Caixa de Seleção não carrega dados retornados no JSON

Question: Estou com problema para carregar uma caixa de seleção (<select>) usando C# MVC com Json. O método retorna a lista completa com objetos, mas não carrega na caixa de seleção.
Meu Controller:
public ActionResult SelecionarRepresentante()
{
    var lista = Dao.SelecionarRepresentante().ToList();
    return Json(new { lista }, JsonRequestBehavior.AllowGet);
}

Meu Model:
public List<Representante> SelecionarRepresentante()
{
    string consulta = @" SELECT
                            A3_COD,
                            A3_NOME
                        FROM
                            SA3010 SA3
                        WHERE
                            SA3.D_E_L_E_T_ = ''
                            AND A3_SUPER = ''
                            AND A3_COD IN
                                (SELECT DISTINCT A1_VEND FROM SA1010 )
                        ORDER BY
                            A3_NOME";

    using (var conn = new SqlConnection(conexaoProtheus))
    {
        var cmd = new SqlCommand(consulta, conn);
        List<Representante> dados = new List<Representante>();
        Representante p = null;
        try
        {
            conn.Open();
            using (var reader = cmd.ExecuteReader(CommandBehavior.CloseConnection))
            {
                while (reader.Read())
                {
                    p = new Representante();
                    p.codigoRepresentante = reader["A3_COD"].ToString();
                    p.nome = reader["A3_NOME"].ToString();

                    dados.Add(p);
                }
            }
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
        finally
        {
            conn.Close();
        }
        return dados;
    }
}

Meu Javascript:
$(document).ready(function () {
        $.ajax({
            type: "get",
            url:'/Gerenciamento/UsuarioExterno/SelecionarRepresentante',
            data: { representante: $("#representante").val() },
            dataType: 'json',
            contentType: "application/json; charset=utf-8",
            success: function (obj) {
                console.log(obj);
                if (obj != null) {
                    var data = obj.data;
                    var selectbox = $('#representante');
                    selectbox.find('option').remove();
                    $.each(data, function (i, d) {
                       $('<option>').val(d.codigoRepresentante).text(d.nome).appendTo(selectbox);
                    });
                }
            }
        });
});

Minha View:

Usuário Externo Cadastro

    @using (Html.BeginForm("Salvar", "UsuarioExterno", FormMethod.Post, new { Area = "Gerenciamento" }))
    {

    <fieldset class="grupo">

            Codigo Representante:

                <select class="form-control" name="representante" id="representante"></select>

            Empresa:

                <select class="form-control" name="empresa" id="empresa"></select>

    </fieldset>

Comment: Já viu se retorna algum erro no console?
Comment: não retorna erro.
e ainda retorna a lista do objeto
Comment: Coloca esse `console.log(obj);` dentro do IF e veja se imprime
Comment: dentro do if e dentro do  $.each ele retorna a lista do objeto. Mas o d.codigoRepresentante não imprime
Comment: lista:[{"codigoRepresentante":"000041","nome":"A E FILHO E ESTEVES REPRESENTACAO COMERCIAL LTDA ME"},{"codigoRepresentante":"000018","nome":"A. M. LUZ REPRESENTACOES COMERCIAIS LTDA"},
Comment: O `nome` imprime?
Comment: Coloca `console.log(selectbox.length);` logo após `var selectbox = $('#representante');`... tem que retornar `1` no console.
Comment: $.ajax({
        url: "/Gerenciamento/UsuarioExterno/SelecionarRepresentante",
        success: function (data) {
            $("#representante").empty();
            $("#representante").append('Selecione...');
            $.each(data, function (i, element) {
                $("#representante").append('' + element.nome + '');
            });
        }
    });
Comment: Se solucionou tá blz.
Comment: valeu amigo. Abraços
Answer: Revolvi modificando. Ficou assim...
$(document).ready(function () {
    $.ajax({
        url: "/Gerenciamento/UsuarioExterno/SelecionarRepresentante",
        success: function (data) {
            $("#representante").empty();
            $("#representante").append('<option value>Selecione...</option>');
            $.each(data, function (i, element) {
                $("#representante").append('<option value="' + element.codigoRepresentante + '">' + element.nome + '</option>');
            });
        }
    });
});


Hadamard (entrywise) product in the Magma computer algebra system

Question: Is it possible to efficiently compute the Hadamard product (= entrywise product) of 2 matrices in MAGMA? I can't find anything in the documentation.
The best thing I can come up with is computing it directly with 2 nested for loops, but this is really slow.
Comment: Maybe [this](https://en.wikipedia.org/wiki/Hadamard_product_(matrices)#In_programming_languages) can help you, i.e. you can search for an "array multiplication" command in Magma.
Comment: I did, but I couldn't find such a command :(
Answer: How big are the matrices? And what field? If you write your own function, I would imagine it's pretty efficient.
<code>function HadProduct(A,B)
 return Matrix([[A[i,j]*B[i,j] : j in [1..Ncols(A)]] : i in [1..Ncols(A)]]);
end function;
</code>


How to offset the center of a Google maps (API v3) in pixels?

Question: I was wondering if it is possible to offset the center of a map in Google maps api v3. I would like to control this offset in pixels, since by lat and lng seems wrong and very difficult to predict.
I just need to place a marker, and then offset the center by 250px so I can place some other content in the middle of the map.
Hope someone can help!
Answer: Found this question when researching and thought I should provide an answer:
function map_recenter(latlng,offsetx,offsety) {
    var point1 = map.getProjection().fromLatLngToPoint(
        (latlng instanceof google.maps.LatLng) ? latlng : map.getCenter()
    );
    var point2 = new google.maps.Point(
        ( (typeof(offsetx) == 'number' ? offsetx : 0) / Math.pow(2, map.getZoom()) ) || 0,
        ( (typeof(offsety) == 'number' ? offsety : 0) / Math.pow(2, map.getZoom()) ) || 0
    );
    map.setCenter(map.getProjection().fromPointToLatLng(new google.maps.Point(
        point1.x - point2.x,
        point1.y + point2.y
    )));
}

If your Google maps variable isn't map use the following call function reference:
function map_recenter(map,latlng,offsetx,offsety) { ...

Comment: This function should be called after projection_changed event has fired otherwise map.getProjection() call would throw a js error. google.maps.event.addListenerOnce(map,"projection_changed", function() {
   map_recenter(...);
 });
Comment: I'm using it on onMarkerClick(). When I click over a Mark works perfect, but if I fire the Mark (from code) with google.maps.event.trigger(thisMark, 'click'); don't work... but no matters (I can live with that)... It's the best solution to do offset. Thanks!!!
Comment: Beautiful and elegant solution.
Comment: if I use Math.pow(2, this.map.getCameraZoom() the displacement is very small, why?
Comment: This works well, but is there a way to modify it to use panTo instead of setCenter? Would be nice if it transitioned rather than jumped.
Answer: Refer to this question: How to offset the center of a Google maps (API v3) in pixels?
This is a modification of an answer I provided here.
google.maps.Map.prototype.setCenterWithOffset= function(latlng, offsetX, offsetY) {
    var map = this;
    var ov = new google.maps.OverlayView();
    ov.onAdd = function() {
        var proj = this.getProjection();
        var aPoint = proj.fromLatLngToContainerPixel(latlng);
        aPoint.x = aPoint.x+offsetX;
        aPoint.y = aPoint.y+offsetY;
        map.setCenter(proj.fromContainerPixelToLatLng(aPoint));
    };
    ov.draw = function() {};
    ov.setMap(this);
};

You can then just use it like so:
var latlng = new google.maps.LatLng(-34.397, 150.644);
var map = new google.maps.Map(document.getElementById("map_canvas"), {
    zoom: 8,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    center: latlng
});

map.setCenterWithOffset(latlng, 0, 250);

Here is a working example.
Comment: Im currently using an iFrame to load my map on page, it comes with a nice white background box of information about the point of interest, is this achievable with the projection method?
Answer: there's also the panBy method of the map object... you can offset by a specified number of pixels.  However, you'll get a smooth transition animation, which may not be what you wanted.  I'm looking for the same thing myself, will let you know what I find.
Comment: yep, `map.panBy(0,-10)` to move it up per 10px
Comment: this should be the answer, much simpler than the others
Answer: Have a look at the MapCanvasProjection object - http://code.google.com/apis/maps/documentation/javascript/reference.html#MapCanvasProjection
You can get the map center latLng (map.getCenter()) then convert that to the container pixel coordinates with fromContainerPixeltoLatLng()
Comment: Is it possible to do this without rendering the map and then redrawing it, i.e. without the user seeing a jump?
Answer: Example for latitude offset to pan a bit lower (on a negative lat, idk if positive lat will give the same result)
map.setZoom(15);
let latV = e.latLng.lat()+0.0135;
let lngV = e.latLng.lng();
map.panTo({lat: latV, lng: lngV});


Como extrair informações de um cabeçalho HTTP com Python?

Question: Sabemos que, no protocolo HTTP, o fim do cabeçalho é indicado por "\r\n\r\n". Exemplo:

Pode ser que, por alguma razão, o cliente não envie o "\r\n\r\n" ao servidor (pode ser um ataque, por exempo):

Suponha que eu tenha uma captura de tráfego de rede no formato PCAP chamado dump.pcap. Posso lê-lo com o seguinte código Python:
import pyshark

pkts = pyshark.FileCapture('dump.pcap')

Eu gostaria de ler o arquivo dump.pcap (código acima) e depois disso, contar quantos pacotes têm o \r\n\r\n e quantos pacotes não tem o \r\n\r\n
É possível realizar isso em Python? Como eu poderia fazer?
Comment: Uma requisição sem a linha em branco não é uma requisição válida, acredito eu. O servidor manterá a conexão aguardando o resto dos cabeçalhos ou corpo da mensagem e finalizar com timeout se não recebê-los. Se mesmo assim esses dados são capturados no seu arquivo, você deverá fazer a busca pela primeira linha da mensagem para reconhecer onde outra mensagem se inicia.
Comment: Você definiu bem o problema, mas não mostrou nada em termos de tentativa de resolução, fora carregar o arquivo (sequer leu um pacote). Minha sugestão é que você continue lendo a documentação do pyshark e tentando resolver até chegar ao problema que está contido na sua pergunta, e depois coloque o código aqui.
Comment: @Anderson Carlos Woss: exatamente! é um ataque sloworis (negação de serviço). Não entendi muito bem como fazer? teria como ajudar?
Comment: Eu tentaria montar a sequência dos pacotes TCP para conseguir as requisições HTTP completas. Depois disso, avaliar se tem as quebras de linha necessárias depois do último campo de Header HTTP e a próxima requisição HTTP. É fácil identificar o começo das requisições, pois elas todas iniciam com um verbo HTTP (GET, POST, HEAD, PATCH, ...), seguido de um path (`/xampp/`, como no seu exemplo).
Comment: @Bruno Coimbra : Poderia, por gentileza,mostrar um código Python? Não faço ideia de como fazer.
Answer: Bom dia amigo,
Seu problema resumidamente é que você deseja contar quantos ocorrências desse padrão teve em suas mensagens, uma forma de você fazer essa verificação é utilizando REGEX.
Suponha que seus cabeçalhos possam ser convertidos em string e cada string sendo colocado como um item de uma lista, você terá que percorrer a lista procurando a ocorrência do quebra de linha. No caso com são 4 caracteres de new line(\r\n\r\n) basta verificar essa ocorrência.
import re

x = len(re.findall("[\s{4}]+", txt)) #qualquer ocorrencia dos 4 caracters
y = len(re.findall("[\s{4}]+", txt)) #ocorrencias apenas no final da string

A varável x terá a quantidade de ocorrências dos 4 caracteres seguidos em qualquer posição, e a variável y contará apenas no final da string.


Which sensor for rotating android phone?

Question: Imagine you are pointing at the TV. You have your phone gripped in your hand. Now, rotate your wrist.
Which sensor would I need to manage to detect such a movement?
Gyroscope?
Orientation?
Accelerometer?
Answer: The sensors TYPE_MAGNETIC_FIELD and TYPE_ACCELEROMETER are fine to detect that (as TYPE_ORIENTATION is now deprecated).
You will need:
a few matrix:
private float[] mValuesMagnet      = new float[3];
private float[] mValuesAccel       = new float[3];
private float[] mValuesOrientation = new float[3];

private float[] mRotationMatrix    = new float[9];

a listener to catch the values the sensors send (this will be an argument of SensorManager.registerListener() that you will have to call to setup your sensors):
private final SensorEventListener mEventListener = new SensorEventListener() {
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
    }

    public void onSensorChanged(SensorEvent event) {
        // Handle the events for which we registered
        switch (event.sensor.getType()) {
            case Sensor.TYPE_ACCELEROMETER:
                System.arraycopy(event.values, 0, mValuesAccel, 0, 3);
                break;

            case Sensor.TYPE_MAGNETIC_FIELD:
                System.arraycopy(event.values, 0, mValuesMagnet, 0, 3);
                break;
    }
};

And you'll need to compute the azimuth, pitch, and roll:
    SensorManager.getRotationMatrix(mRotationMatrix, null, mValuesAccel, mValuesMagnet);
    SensorManager.getOrientation(mRotationMatrix, mValuesOrientation);

mValuesOrientation is then filled with:

mValuesOrientation[0]: azimuth, rotation around the Z axis.
mValuesOrientation[1]: pitch, rotation around the X axis.
mValuesOrientation[2]: roll, rotation around the Y axis.

Check the documentation of getOrientation() to know how the axis are defined. You may need to use SensorManager.remapCoordinateSystem() to redefine these axis.
Comment: When I do this, the pitch never goes to 180°. It starts at 0° (flat, facing the sky), then goes to 90° when the phone is facing me, then goes back to 90° when it faces the floor. Is that an expected behavior? How do I know if the device is staring the sky or the floor then?
Answer: It depends on what you want to detect, if you want to detect that the phone has been moved in a rotation then accelerometer is probably your best bet.
If you want to detect that the phone is now rotated then Orientation.
Answer: The gyroscope is for detecting rotations if you don't care about your position relative to the Earth.


Erro ao conectar com o banco de dados firebird

Question: Estou tentando criar uma aplicação web e quero utilizar java e html.
Bom depois de tudo configurado e pronto para um pequeno teste de conexao o seguinte erro ocorre:
Fev 09, 2016 1:28:02 PM org.apache.catalina.core.StandardWrapperValve invoke
GRAVE: Servlet.service() for servlet [jsp] in context with path [/TesteTemplateImport] threw exception [java.lang.NullPointerException] with root cause
java.lang.NullPointerException
at org.apache.jsp.main_jsp._jspService(main_jsp.java:190)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:438)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:673)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1526)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1482)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)

Sou iniciante e nunca criei uma aplicação web, segue abaixo meu algoritmo para conexao com o banco:
package teste;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class Conexao {

static final String JDBC_DRIVER = "org.firebirdsql.jdbc.FBDriver";
static final String DB_URL = "jdbc:firebirdsql:192.168.1.225/3050:D:/Dados/Suporte/Sisplan/Base/Belfast.GDB?sql_dialect=3";

static final String USER = "SYSDBA";
static final String PASS = "masterkey";

public static Connection getConexao() throws SQLException {

    try {
        Class.forName(JDBC_DRIVER);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }

    return DriverManager.getConnection(DB_URL, USER, PASS);

   }

}

Tem um pequeno detalhe que acredito que devo mencionar, esse erro ocorre não no momento em que eu faço o start do servidor. Ele inicia a aplicação rodando no eclipse, vou até o navegador web digito o endereço do servidor, ele abre a pagina porem quando executo um select ai sim o log do erro aparece.
Este é meu código dentro da pagina html:
<%@ page import="teste.Conexao" %>
<%@ page import="teste.UsuarioDao" %>
<%@ page import="teste.Usuario" %>

<%

UsuarioDao udao = new UsuarioDao();

Usuario usuario = (Usuario) udao.buscar("12345678");

out.print(usuario.getNome());
%>

Aqui esta meu select:
public Usuario buscar(String rg) {
    conectar();

    String sql = "SELECT nome FROM ENTIDADE_001 WHERE CODCLI = " + rg;

    try {
        ResultSet rs = st.executeQuery(sql);

        while (rs.next()) {
            String rG = rs.getString("rg");
            String nome = rs.getString("nome");

            pessoa = new Usuario(rG, nome);
        }

    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        desconectar();
    }

    return pessoa;
}

E sim. Já adicionei o .jar correto com a mesma versão do meu jdk e minha variavel de ambiente HAVA_HOME nao tem espaços em branco e esta apontando corretamente para pasta da minha jdk.
Comment: Você faz `Conexao.getConexao();` na sua página, porém não faz uso (pelo menos com os códigos que postou) desse elemento. Outra dúvida que eu tenho é sobre a instanciação do elemento `pessoa`, que é retornado no método `buscar`. Caso nenhum usuário seja encontrado, qual o retorno para a página?
Comment: Verdade amigo, nem percebi. Mas esse codigo eu copiei de uma aba que estava usando para alteração e testes. Passou despercebido. Mas em fim o metodo getConexao() é chamado dentro do metodo conectar(). E o retorno para a pagina é apenas o nome do usuario impresso entre textos prontos aqui do template. Coisa simples apenas para testar a conexao.
Comment: Modifiquei o algoritmo para tirar qualquer duvida. Afinal pode ser uma coisa banal que esta ocasionando tanta dor de cabeça pra um dia.
Comment: Você já verificou se o "rg" que está sendo passado como parâmetro do método `buscar` está, de fato, com o valor que você está enviando?
Comment: Acabei de testar aqui amigo, passando o numero de um rg existente na minha tabela funcionou. Porem eu preciso buscar esse valor através de um form da minha pagina de login. Eu tentei request.getParameter("passoword"); dentro do escopo da tag <% %> . Porem é obvio que estou fazendo isso errado ja que funcionou agora com o rg setado diretamente no metodo buscar(). Algum post pra me ajudar sobre isso?
Answer: Veja se esse material lhe ajuda a encontrar o "caminho das pedras".
Neste exemplo é criado um esquema de autenticação bem elaborado. Você não precisa se prender aos pormenores que o autor trata, basta focar no que você está de fato precisando.
Creio que a análise das listagens 10 e 13 lhe serão de grande ajuda no entendimento da interação entre a página JSP e o back-end da aplicação.
Comment: Perfeito, acho que é exatamente isso que eu preciso. Muito obrigado.


Are Piano Stickers for Keys good or bad?

Question: Is it good to use Piano Stickers for Keys w/ Complete Printed Notes to memorize the notes on the sheet and their correspondence to piano keys? Does it work? Or is it better not to do that?
The main point of the question is mapping between notes on the score sheet and the keys. A, B, C,... are just like a bridge to me.
Comment: This would be like looking at the computer keyboard as you type. Who would do that?! ;)
Comment: @LightnessRacesinOrbit, after several months you can do that. But in the beginning, you can't. The question is, is that better to use a keyboard without any letter for typing?? I'm not sure if we can easily apply computer keyboard to piano.
Comment: I'll just say what everyone else will say - NO DON'T DO THAT.  Stickers should never touch a piano, even digitial.  It's a terrible crutch.  I suspect you don't got a piano teacher if you're thinking about this.  That's job one in learning piano.
Comment: @Tim A piano has many more than 12 keys.
Comment: @LightnessRacesinOrbit - missing the point somewhat. On a qwerty board, there's twice what I said - each has minimum two uses! On a piano, after one octave, the next up or down has exactly the same named notes. I.e. in between each pair of black keys there is a D. Nothing else - same everywhere. Not a good comparison.
Comment: @LightnessRacesinOrbit - on a qwery board (azerty in France), there's around **50 different** keys. A far cry from the **12** different a piano has. Touch typing has been around for years - still don't know why kids in school aren't taught it - but it's hardly a comparison.
Comment: @Tim: I really think you're taking my comment too seriously. Regardless, once you've figured out that each octave is the same, and that an octave may be identified by a repeating pattern of black/white spacing, you don't need stickers on the keys any more .. which _is_ the point somewhat.
Comment: @LightnessRacesinOrbit - I really did think you were serious! 'You don't need stickers *anyway*', rather than *any more*...
Comment: I've found that even if I'm not actively looking at computer keyboard, touch typing on a keyboard that has keycaps for a different layout is still confusing. Blank keycaps are mentally easier. Similarly, 10th fret marker on ukulele is more confusing than no fret markers at all.
Answer: I cannot find any research on the topic, only various anecdotes from different teachers. There are some common threads:

A downside reported by some teachers is that the labels can become a crutch that students have a hard time learning to play without.
Actual letter-name labels (e.g., "A", "B", etc.) are not widely believed (by teachers) to help in learning to read music.
Instead of letter names, colors, shapes, and other graphical symbols are what teachers who advocate labels prefer. Such teachers often have special books of easy to read sheet music with matching color codes or shapes.
Instead of labels, teachers who like labeling in general seem to often prefer a card that goes up at the top of the keys and is lined up before playing. That way the card can easily be moved to other pianos or removed when no longer helpful.
Young children, under 8 years old or so, are believed to have the most to gain from labels. Most teachers don't seem to even try labels with older students.

It seems like if you're over age 8 or so, your brain is more capable of using the pattern of white and black keys along with sheet music mnemonics (e.g., FACE and Every Good Boy Deserves Fudge) to learn the note names and read music into the piano.
On a personal note, to me learning note names is not actually very helpful when reading, playing, and sight-reading. Ideally, a shape on the page would be associated in the mind with the motion of the hand, and at least for a while with a specific key on the keyboard that would be visually verified. It's better to go right from that shape means that key than to be thinking that shape is a C and C means that key. Note names are more useful for talking about music and analyzing it, but not when playing.
Comment: @JohnDoe Eager Girls Buy Diamonds First. Early Grackles Beat Dose Falcons. Eyeball Gunk Besets Drowsy Ferrets. Ey Guys Blowup Dat Football! Easy Greasy Breezy Darned Freezy.
Comment: Labelling just middle C is also an idea. The student can learn to recognize the black and white pattern by seeing where the pattern begins and ends.
Comment: Edit: Every Good Boy *Does Fine*.
Answer: Do not bother! there is a pattern to the keys - look at the two black keys, left white  is C, right is E. Look at the three black keys, left white is F, right is B. There are four of the seven notes, al clearly marked with no marks!
Looking for, for example, a marked letter C? Why bother, it's always the left of the two blacks! If it said C, carrot, cucumber, concubine, it's still in that same place, and will always be C.
EDIT: I wonder if we've missed a point. The OP asks about 'complete Printed Notes', which could mean a picture of the 5 lines, with an appropriate dot (note) on a line or space. Not seen that, but initially it's not a bad idea.
Comment: This doesn't exactly answer the question, which seems to be whether letter stickers help or hurt or have no effect.
Comment: @ToddWilcox - it's unequivocal. Do not bother  basically translates as ... well, you work it out. Do you really expect me to say yes, no, don't know? Mark it down again, if it helps the cause...
Comment: It's clear you see them as not **necessary**, but to me that's different from whether they are helpful or hurtful. John Doe's answer at least implies that he believes they will hurt in the long run.
Comment: Incidentally, I find that thinking of key signatures in terms of the black/white key pattern is also more useful than thinking of them in terms of letter notes and then having to translate that to position.  Sharps get added left to right within each chunk, starting with the chunk of 3 and alternating.  Flats alternate the same way, but get added right to left.
Comment: @supercat - what a great way to think of sharps and flats!
Comment: @Tim: Incidentally, another way of thinking about them is to imagine a keyboard where white keys are spaced 12mm apart at the front (84mm/octave), and all key levers are spaced 7mm apart at the back (also 84mm/octave).  If one places a comb with 12mm tooth spacing on the back of the keyboard, the set of key levers it hits will represent a key signature.
Answer: I wouldn't. It might help in the short run, but in the long run you want as few crutches as possible when learning a new instrument. In fact, you should be working towards seldom, if ever, even looking at the keys, at least for simpler songs.
Answer: Many answers already make good points.  I don't think there's only one answer to this -- it depends on the context and particularly the student.  I think if a student seems to be able to make good progress initially without the labels, it's perhaps better to avoid them.  But...
A few points that haven't been highlighted so far:

Students with no pre-existing knowledge of music notation will probably benefit more from having note names labeled somehow.  The combination of trying to learn to decode basic music notation at the same time as learning the piano keyboard can be a bit overwhelming.  For those who already can read music, there's less of an initial cognitive load -- just learning the placement of notes on the keyboard.
Younger kids in particular may enjoy the "matching game" of being able to match a key to a note, particularly if an initial book has note names as part of the notation.  This is more likely to lead beginners to experiment and try out pieces in a book, even if they are not part of an official "lesson."  A lot of the difficulty with young children is keeping them interested and not frustrated, so anything that allows them to learn things, play around, or try out stuff by themselves is potentially a good thing.
The frustration problem is also an issue with older learners, particularly those are trying to self-teach.  New piano students are already trying to learn how to make their hands move, how to strike the keys properly, etc.  And on top of that, they are trying to decode music notation and learn the location of keys.  For some people, having note labels more readily available can alleviate at least some of that frustration initially.  Particularly for the self-taught, creating a new habit and learning an instrument by oneself is already a big commitment.  Finding ways to make it easier to get started can be helpful.  Without a teacher there to correct you, it can be harder to verify you're hitting the right notes in the first place.

Also, I'm not sure I agree with those who deemphasize letter names for notes (or who would substitute colors or shapes, except perhaps for very young children who don't know letters yet fluently).  The theory seems to be that one should make a direct connection between the visual location of the note on the page and the physical location on the keyboard; the note name is secondary.
But I think that can be its own sort of "crutch."  We have a name for music notation that shows one how to physically arrange one's fingers on an instrument -- it's called tablature.  There used to be tablature for keyboard instruments, as well as various other instruments, though nowadays it's mostly seen for guitar.  The standard staff music notation we use is meant to be a somewhat universal system (at least for Western music), which can be helpful for any instrument and music in general.  Part of that is associating the abstract names (i.e., letters) with particular notes.
I've seen way too many sophomore (even junior) music majors in college who still needed to write down note letter names next to notes to be able to read music properly, even though they've played an instrument or sung for over a decade.  (I've even seen said students have to draw a picture of a keyboard on a page to decode what notes were which, before they could identify a chord or something.)  Avoiding letter names can create its own problems in the long run, assuming the student ever wants to talk about music with anyone else, learn any music theory, or understand music written for anything other than piano.  If one wants to use shapes or colors, I think that's fine if combined with letter names in the shape or color so students will eventually make the letter-name connections.  If you're going to use a crutch, why not make it a useful and educational crutch?
I also agree with all of those who note that labeled can also be a crutch that can take a while to wean a student off of.  But sometimes one needs a crutch to get over the initial difficulty.  (Think of how many young piano students quit after a year or three, many because they simply have difficulty decoding music notation and matching it to the keyboard.)  There's no single answer for which is better in the long-run -- I think the needs and personality of the individual student should factor in.
Answer: I wouldn't bother with it. When I was in the 5th grade I could read music and translate that to my fingers on the violin but I really couldn't name the notes. I was good for a beginner, best in the class before having to drop out because my parents couldn't keep up on the instrument rental fees. Now I'm 41 and trying to teach myself the piano and I believe I'm over thinking this myself. I too was looking for the answer to the original question and I think I've found my answer, to concentrate matching the notes to the keys and follow up with naming each note later. It's a daunting task trying to do both and it's taking the fun out of it.
Answer:
Piano Stickers for Keys w/ Complete Printed Notes

I would not do that. Printing sheet music that's small enough to fit on the key would make it unrecognizable when playing. Your fingers would also cover them up and you'd have to take the time out to move your fingers, get close and identify the note, then look up at the page to double check. It's quite a lot of steps.
If you really think you need to label the keys (which there's no shame in doing) I would go the harp route. That is, on most harps with nylon strings (whether a concert or lever harp) all the C notes are marked in red by dyeing the string, while all the F notes are marked with either blue or black dye. Using some red/blue electrical tape you can mark the ends of the C and F keys which would give you a good base to go by to find every other key, and since they're so bold in color it won't be hard to see them. Then you could have a special scale sheet that emphasizes these notes, highlighting them in red/blue. Eventually you shouldn't need them and electrical tape is very easy to remove and clean the residue.


Is there a way to overload extraction operator, inside a class and not as a friend of class?

Question: I am trying to overload << operator, so that when I use my class object in std::cout, it prints out the data members which is supposed to get printed.
I know I have to define a friend functions signature inside of a class, and then outside of the class I define two friend functions doing the job, but I want to hand over the class, and don't want the user to do literally anything and I want the class take care of everything.
How can I achieve such a thing in C++?
Comment: See this answer about how to define the friend inside the class http://stackoverflow.com/a/2077010/597607
Comment: Why would this even matter? I mean, since it doesn't matter (I think), this question is useless (and thus warrants downvotes). If it matters, it helps to know why it matters, because then, instead of trying to solve the problem in an impossible way, one can try to actually solve it some other way.
Comment: @R.MartinhoFernandes I think it's a good question, basically he wants to achieve what ADL does in its unintuitive way. The problem being somewhat obscure, it's hard to formulate well.
Comment: I honestly can't read that in this question. If that's the case, I still think the OP needs to make that clear.
Comment: Specifically, I think he's creating a header-only library and wants to eliminate the `.cpp` component which he considers to be "the user." Which could also be achieved by defining the friend as stated but making it `inline`… however my answer is better :v)
Comment: @Potatoswatter : yes thats exactly what i was after :) but i am happy i learned about ADL :)
Answer: C++ is designed to allow non-member functions to do things that would require a member function in other languages. A friend function is very similar to a member function, in that it can be defined within a class scope. Also (and this can be confusing) if you declare a friend function only within a class scope, it can only be accessed by passing an object of that class to it.
struct printme {
    friend std::ostream &operator<< ( std::ostream &os, printme const & )
        { return os << "hello"; }

    friend void named_friend( printme const & ) {}
};

std::cout << printme(); // OK
named_friend( printme() ); // OK
void (*fn_ptr) = named_friend; /* function not found
           it can only be found by association with printme */

Although this subtle rule is odd at first, it reflects the idea that nonmember functions can also be encapsulated by the class.
For more info, read up on argument-dependent lookup (ADL).
Answer: we usually uses << in the following way:
cout<<myobject;

if you make operator<<() a member function of your class you have to use the following syntax
to call operator<<()
myobject<<cout;

do you want it that way? if its ok for you , you can make it a member function .
if you want it like
cout<<myobject

- you have to make operator<<() a friend function of your class
Comment: Please, observe the preview as you create your post… and press the `{}` button to quote source code.
Answer: Here is an example:
#include <iostream>
#include <string>

using namespace std;

class A {
public:
    string pr() { return "Hi, I'm class A"; }
};

ostream &operator << (ostream &o, const A &a) {
    o << a.pr();
    return o;
}

int main() {
    A a;

    cout << a << endl;

    return 0;
}

However, from my experience, don't do that. Oveloading is academically nice, but it makes it diffult to search your application for its implementation, and even comprehend that << has been overloaded. I always use something of the form cout << myobject.tostring()
Comment: thank you very much :)
i recently tried to use boost , and in meantime , i saw alot of this overloading , which made my life really easy , specially when using boost::serialize , then i thought to myself , why wouldnt i do this myself and make my like easier ? :)
and yes you are right , i have never thought about this issue . I'll have this in mind for sure :)
again Thank you sir :)


Overwrite Not Working

Question: I've seen other threads on here touching upon the issue I'm having, but none of them either apply to my problem or provide a solution, so I thought I'd post a new thread.
Basically, I'm creating a script that runs weekly and updates a shapefile (technically, it updates the 8 files associated with a shapefile, including the CPG) by converting a feature class to a shapefile. Currently I have it set to delete the existing files and then re-export them, but I'd rather have them be overwritten. For whatever reason, I can't get it to overwrite; it just creates the same files with "_1" appended to the end. Where am I going wrong? Thanks!
import arcpy, os
from arcpy import env
import time
import smtplib

arcpy.env.overwriteOutput = True

connStr = "D:\Jobs\BSA-GIS-Shapefiles\Connections\GIS_Enterprise.sde"
outWrkSpc = "\\\gis\gisdata\BSA_Shapes"

inputParcels = "GISEnterprise.EOWNER.CParcel"
inputParcelAnnoAddr = "GISEnterprise.EOWNER.cParcel_Anno_Address"
inputPlats = "GISEnterprise.EOWNER.cPlat"

shpParcels =  "CParcel.shp"
shpParcelAnnoAddr =  "cParcel_Anno_Address.shp"
shpPlats =  "cPlat.shp"

env.workspace = outWrkSpc

try:
    arcpy.Delete_management(shpParcels)
    arcpy.Delete_management(shpParcelAnnoAddr)
    arcpy.Delete_management(shpPlats)

    arcpy.FeatureClassToShapefile_conversion(os.path.join(connStr,
    inputParcels),outWrkSpc)
    arcpy.FeatureClassToShapefile_conversion(os.path.join(connStr
    ,inputParcelAnnoAddr), outWrkSpc)
    arcpy.FeatureClassToShapefile_conversion(os.path.join(connStr
    ,inputPlats), outWrkSpc)

I know those last lines shouldn't be split; they aren't in my code, I was just having trouble formatting in the post.
Comment: Please be aware that there is a [gis.se] Stack Exchange.
Answer: Instead of using FeatureClassToShapefile, I would use CopyFeatures, so you can explicitly specifiy the output's name (not just the output workspace) and it will be overwritten:
arcpy.CopyFeatures_management(os.path.join(connStr, inputParcels), os.path.join(outWrkSpc, shpParcels))

Feature Class to Feature Class is another perfectly suitable here too.
Both will accept shapefiles as input and/or output.
As stated in the help page for Feature Class To Shapefile (which is supposed to be used to process multiple input shapefiles in one step):

If the output shapefile already exists in the Output Folder, a number
  will be appended to the end to make the shapefile name unique (for
  example, rivers_1.shp).
Comment: I'm trying to export a GDB feature class to a shapefile not inside a GDB; won't the copy features try to copy as a GDB feature class?
Comment: I'm also just curious as to what I'm doing wrong with the overwrite process. I may need it for a future problem.
Comment: So using the Feature Class to Feature Class operation will allow overwriting files, but the Feature Class to Shapefile operation will not? Is that the gist of what you're saying?

Overwrite Not Working


Population studies - interpreting confidence intervals, should they even be included?

Question: I work with administrative ('routinely collected') data in situations where the data capture the entire population, e.g. hospital records, prison records, etc. When reporting statistics the question of interpreting confidence intervals has come up with colleagues and reviewers, and I'm trying to work out a coherent position. I've had a look at a related question (Why don't we calculate the average of an entire given population instead of computing confidence interval to estimate the population mean?) but it doesn't touch on the question of measurement error.
In one sense, a confidence interval is a measure of uncertainty about our sampling process, so when the population is known, we could simply report the various statistics we use, and declare any difference as statistically significant (questions of practical significance, minimal clinical differences, etc. notwithstanding).
In another sense, there is still uncertainty in the data collection process, e.g. measures being rounded to the nearest number, which the confidence interval can stand in for. I feel this is a separate issue since it's to do with uncertainty with measuring/recording rather than sampling, but reviewers/colleagues seem to be happy to accept this interpretation of the confidence interval.
Pragmatically, the confidence intervals in these scenarios are usually incredibly small, so including them, or not, and interpreting them as including measurement uncertainty, or not, has little bearing on the conclusions we draw from data.
Overall, I'm just confused about whether confidence intervals are appropriate when dealing with known/entire/captive populations, and whether or not the concept of measurement uncertainty applies in this case or not. I don't have a strong statistics background and would appreciate any thoughts and/or references!
Comment: My thought: confidence intervals only apply when you've randomly sampled a portion of all the data. When you have actual measurements of the entire population you're interested in, confidence intervals wouldn't apply, but measurement intervals might. For example, if you have temperature data from thermometers known to have a normally distributed error, that would be your "confidence interval". In this case, unless you know the measurement techniques themselves are flawed, since the data is whole numbers, there are no confidence intervals.
Comment: @barrycarter I think this summarises my position as well, but I'm still wondering if the (sampling-related) confidence interval is a valid proxy for measurement error in this case or not... especially since there isn't really any systematic consideration given to measurement error, we just assume it's there, and that we can include it using the CIs we compute anyway.
Answer: A case where confidence intervals might still be useful is when the population statistic is considered as a random variable.
For instance the number of students that enrolled into a school. You can count them precisely, or at least without much error and with no errors due to random sampling. But those figures for the population might be interpreted as a sample from a hypothetical larger population. For instance the school board might wonder whether the numbers of students are following an increasing trend. For such a question one needs to regard the random nature of such figures, even when they relate to an entire population.
Comment: So in this case, when I work with, say, the entirety of the population admitted to hospital in a particular year, they can be considered as a sample of the population admitted to hospital over time? (since the factors that lead to someone being admitted in a particular year can be considered random, I suppose)


PHP stopped working after I upgraded

Question: Windows install with Apache. I'm not using WAMP.
I just upgraded from 5.2.3 to 5.3.0. After I installed it (msi) I restarted the server but php isn't working. I looked at the httpd file and noticed that the php loadmodule is not there anymore. Can someone offer a hand?
Answer: I have the follow in my httpd.conf file.
<code>LoadModule php5_module "c:/wamp2/bin/php/php5.3.0/php5apache2_2.dll"
</code>
(this is for wampserver install)
Just change the path to where you installed php and you should be good.
Comment: It looks like the fix is to download the VC9 threaded version. I downloaded the non-threaded version so we'll see how that goes. :/
Comment: Hey Samuel, I'll give this a try now and be right back. Thanks!
Comment: Samuel, I just searched the entire hard drive and don't have that dll anywhere.
Comment: look in c:\Program Files\PHP for php5.dll I think that is the file you need.
Comment: Hey Samuel, I tried using that file too but nothing. I just found a bug report on the PHP site regarding that file accidentally being excluded from the MSI.
Comment: Yep.. That works great. All I needed to do was download the threaded version. Thanks for all the help Samuel!

PHP stopped working after I upgraded


Hyperlinks affecting how validation is added

Question: I noticed that if I add hyperlinks to table column before validation list on another column it will affect how validation list is added.
For example:
RangeTarget(c, r).Hyperlinks.Add Anchor:=RangeTarget(c, r), Address:=hyperlink, TextToDisplay:="Link"

And another:
RangeTarget(c, r).Validation.Add Type:=xlValidateList, Formula1:=celldata

If I don't add hyperlinks, celldata can be separated by ',' and if I add hyperlinks celldata can be separated with ';' being my local separator for excel.
Can someone retry this and confirm please.
The actual code is this:
RngTarget(2 + i, mvaln).Hyperlinks.Add Anchor:=RngTarget(2 + i, mvaln), Address:=rsrows(j, i), TextToDisplay:="Link"
RngTarget(2 + i, mvaln).Validation.Add Type:=xlValidateList, Formula1:=rsrows(j, i)

I assume it affects RngTarget range, if I use it for both. I assume if I redefined RngTarget inbetween I could then separate items with ','. So I guess there is some hidden locale for range that is being changed after adding hyperlink.
EDIT:
Ok I reduced the problem to this.
If I add .ClearHyperlinks on RngTarget(2 + i, mvaln) before adding validation list, it will apparently separate list by "," character instead of ";".
Answer: So basically if someone knows if this is a bug...
I run this on a table (after selecting 2 columns):
Sub test()
    Selection.ClearHyperlinks
    Selection.Validation.Delete
    Selection.Columns(2).Validation.Add Type:=xlValidateList, Formula1:="a, b, c, d, e"
End Sub
Sub test2()
    Selection.ClearHyperlinks
    Selection.Validation.Delete
    Selection.Columns(1).Hyperlinks.Add Anchor:=Selection.Columns(1), Address:="no address", TextToDisplay:="Link"
    Selection.Columns(2).Validation.Add Type:=xlValidateList, Formula1:="a, b, c, d, e"
End Sub

Test1 will list dropdown items correctly while test2 will not. For test2 I'd have to use ";" delimiter.

Adding hyperlinks to the column after adding the validation doesn't affect this. Also this is bugged not just on tables but also on range.


Change div to visible after initial load?

Question: I have an issue where a div is loaded before the javascript, which displays the text, and after the javascript is loaded it will display it differently (autoscrolling). To prevent this I tried adding visibility: hidden; to the div #vs, and then add the following code to the jQuery document.getElementById("vs").style.visibility= "visible";
This solves the problem, but after 3 seconds it will disappear, and after 3 seconds it will reappear, and it keeps going like this. How do I prevent this?
jQuery(document).ready(function($) {
  function autoRefresh() {
    $.ajax({
      success: function(data) {
        // Find div id #vs
        var result = $('
').append(data).find('div#vs').html();
        $('div#vs').html(result);

        document.getElementById("vs").style.visibility= "visible";
        // If div id #vs takes up more than 85% of inner height, add class .vscroll
        if (document.getElementById('vs').clientHeight > window.innerHeight * 0.85)
          $('div#vs').addClass('vscroll');
        // If div id #vs takes up less than 85% of inner height, remove class .vscroll
        if (document.getElementById('vs').clientHeight < window.innerHeight * 0.85)
          $('div#vs').removeClass('vscroll');
      }
    });
  }
  autoRefresh();
  // Refresh at page load and every 3000 milliseconds / 3 seconds
  var auto_refresh = setInterval(autoRefresh, 3000);
})

Comment: Well you are refreshing the page every 3 seconds, which probably explains it. Why do you need to do that?
Comment: I need to refresh the div #vs every 3 seconds to check for changes, without refreshing the whole page. This part works well, just not together with the latest addition, and I don't know how to solve it.
Comment: Is there a reason you aren't really using XHR to retrieve data from a **URL**? Also, you should use jQuery's `.load()` method. It was designed to remove all this pain.
Comment: I'm sorry, I don't understand how to change to this?
Comment: Where does `data` come from and what does it contain in the `success` handler? As written, you are not retrieving any data from anywhere.
Comment: I really don't know, I got help with that part! What can I remove?
Answer: I am not a JQuery expert, but I think it's because you are using getElementById() instead of a JQuery selector.
I think you need to do this:
$('div#vs').attr('style','visibility: visible');
Forgive me if the JQuery code isn't perfect, I haven't tried to run it
Comment: Works perfectly! Thank you very much!


17 Week Coin Flip Contest - Calculate Probability/Odds For Each Individual To Have The Winning Count Of "Heads"

Question: I'm new to statistics, like WAY new. So green, in fact, I'm scarcely pushing (0,1,0) in the RGB color model.
I'm presently the recordkeeper for our office's 17-week "Coin flip pool". As of right now, 7 weeks have passed and we are in our 8th week, and, therefore, there are 9 weeks remaining. Each contestant has amassed a certain number of points gained by essentially flipping 3 coins a week and for each "head" result, they get 1 point - if they get 3 "heads" in a week, that's 3 points. Current accumulated scores across all 23 contestants ranges from 7 to 15, so each has their own weekly average of success.
One contestant recently asked what his odds of winning were. This obviously necessitates knowing his current score, his current performance, the current score of the other contestants, the average weekly performance of other contestants, and, possibly, the average potential score of 3-coin-flips-resulting-in-heads-a-week.
I've searched and searched and found only betting odds calculators and basic explanations of what the probability of the result of any single series might be, but I don't know enough about this subject nor what keywords to use to possibly narrow down my results to find the right answer.
I can provide a whole spreadsheet's worth of data (if I don't readily know how to share it within Stack Exchange).
As I know next to nothing about this subject, would someone kindly nudge me in the right direction? Especially if this ends up being far to complicated a topic for a Stack Exchange question.
Thank you for your time!
Edit (20181027T08:45-05:00):
Additional clarification that might make this simpler (or not, statistics is not my forte after all): Knowing the absolute chance of winning at the end of Week 17 is not necessary, only a projection based on current performance (maybe that's the same thing?).
Some sample data (actual data from my spreadsheet)

Person      Score   Performance Week 1  Week 2  Week 3  Week 4  Week 5  Week 6  Week 7  Week 8
Alpha       2       0.250       2       0       0       0       0       0       0       0
Bravo       10      1.250       2       0       0       2       1       3       2       0
Charlie     12      1.500       3       1       0       2       2       1       3       0
Delta       8       0.875       0       1       1       1       2       1       0       1
Echo        11      1.375       2       0       2       1       1       2       3       0
Foxtrot     13      1.625       1       2       2       2       2       1       3       0
Golf        9       1.125       2       1       1       1       1       1       2       0
Hotel       12      1.500       2       1       1       0       2       3       3       0
India       8       1.000       1       1       0       1       2       1       2       0
Juliett     9       1.125       2       1       1       0       1       2       2       0
Kilo        9       1.125       2       1       0       2       2       0       2       0
Lima        11      1.375       2       1       2       1       1       2       2       0
Mike        15      1.875       1       1       2       3       2       3       3       0
November    9       1.125       2       0       2       1       1       1       2       0
Oscar       12      1.500       1       2       0       2       2       2       3       0
Papa        10      1.250       1       2       1       1       0       2       3       0
Quebec      11      1.375       2       1       2       1       1       1       3       0
Romeo       7       0.875       1       1       1       0       1       1       2       0
Sierra      11      1.375       2       1       2       3       2       0       1       0
Tango       8       1.000       2       2       0       1       1       1       1       0
Uniform     8       1.000       1       1       0       2       0       0       3       1
Victor      11      1.375       2       2       1       1       1       2       1       1
Whiskey     10      1.250       2       0       3       1       1       2       1       0
X-ray       9       1.000       0       1       2       1       1       1       2       0

Score: total "heads" so far
Performance": average heads (score / 8 at present)
Week #: total "heads" results that week
Edit (20181027T09:52-05:00):
For commentors (commentators?) asking why Week 8 has so few successes: Week 8 is "in progress" and ends Tuesday morning. One coin-flip is performed Thursday, Sunday, and Monday so probability will change as each day's flip occurs. American sports fanatics might start to see where this is headed.
Edit (20181027T14:37-05:00):
As Martijn Weterings and I have discussed in the talk section, this is indeed not exactly a coin-flipping contest. Under my prospective simplification is it the NFL Regular season: 17 games for which there are two outcomes (and their inverse): Team A wins or loses (for which Team B loses or wins). We are using a variant that adjusts the underdog team's score by a positive amount (a handicap, if you will). Based on last year's pool statistics with the inclusion of a handicap the odds of either team winning after score adjustment is 1:1 (50%, yes?) - more accurately 45.824% by averaging the averages on last season's sheet.
This is why I described this problem as a coin-flipping contest. While true betting odds compute all manner of variables, that work has been done for us and for simplification, just went with "the handicap makes it so each team has an equal shot at winning the game". This handicap variant helps immensely because a good majority of our players don't follow the sport at all and would get squarely defeated week after week by those that do. The handicap is an equalizer of sorts.
More accurately each contestant selects three "coins" from a pool of 16 and if any of those "coins" lands as "heads" they get a point - from 0 to 3 points per week. We are presently in Week 8 and as of this writing, only 2 coins have been flipped (the Thursday night game and the Saturday morning game). Which is why the probability can change with time as not all 16 results occur simultaneously. However, for the sake of simplicity (and again I know next to nothing about statistics to say "simplicity" repeatedly) probability of every participant will update as more of these contests are completed.
I apologize for not realizing the true reality was less simple than "contestant flips 3 coins" and more "there is a pool of coins from which each contestant 'bets' will be heads".
Comment: Are these really 'coin flips' ie. can we safely assume the probability of heads is always $0.5$ and no skill involved? If yes, this is a probability problem (where I think simplifications are available and you don't need to go through $28^{23}$ cases...)  If no, this is also a statistics problem of how to model the skills (in which case more information might be needed about the nature of the competition)  What's the difference between 'performance' and 'score'?
Comment: 9 weeks mean 0-27 heads available for each contestant. For 2 contestants, I can generate 28 x 28 probabilities and get who will win. For 3 contestants, it seems still doable. But for 23 contestants, I know how to do it, but it seem too hard even we have high speed computer.
Comment: I was (very likely, wrongly) approaching it as: player's current points + (player's average points * weeks remaining) = estimated final score. Estimated final score "modified by"  = "probability" that player will have 1 point more than the current leader, or if player is the leader, 1 point more than 2nd place.

The method you outlined is certainly the right way to do it, but the variable space is REALLY large. Can a probability be estimated at the end of each week as with my attempt?
Comment: No, their true nature is not coin flips, but for the sake of simplicity and for the sake of this calculation I'm treating them as such. Absolute precision is not a necessity and high accuracy isn't necessarily a requirement either. A simple "you've got a good shot (75%)", "you've got a fair shot (50%)", or "you're the long shot (1%)" will suffice. Performance = average "heads" per week, score is total "heads" since the start of the contest.
Comment: But if we assume the shots are coin flips, "performance" matters only through past score. If we assume coin flips, "the average potential score of 3-coin-flips-resulting-in-heads-a-week"  is by definition $1.5$. If answerers are supposed to assume coin flips, this should be explicitly mentioned in the question
Comment: I apologize if I've not made it obvious or not explicitly stated any part of the question; maybe I thought it was inferred by the nature of the contest. I have based my attempts both on the simple average of 1.5 for 3 coins and the weekly success history of each player. Neither necessarily feels right - like I've done the calculation the correct way using the correct parameters. Does the approach change depending on which basis is employed? I have a feeling we might get tagged for "extended discussion" and get moved to the talk section. :)
Comment: What's going on with Alpha and Yankee? Why has week 8 so little amount of successes?
Comment: @MartijnWeterings Sorry, Yankee should have been excluded from that sample. It was originally an unoccupied slot on my sheet reserved for a future participant. Ooor.. he hit that "mythical" streak in an RNG where he got 24 "tail" results in a row. I'll take that one out of the sample data. For that matter, Alpha effectively stopped participating after Week 1, but COULD come back if they wanted to which would make their chances of winning REALLY long at this stage.
Comment: @MartijnWeterings Addendum: Week 8 is still in progress. Maybe this is all important information to have put in the question??
Comment: How do you explain the increase of weekly total successes per week, from week 2 to 7? Is it coincidence or do the 'coins change' over time?
Comment: How do you define 'winning' (is it the most heads after the 17 weeks?).
Comment: @MartijnWeterings I'm starting to think I've inadvertently left a whole lot of basic information out of my question. Yes, the winning condition is the most "heads" results at the end of Week 17. As for increase of total successes? I'm not sure I follow. TTH, THT, and HTT are all treated the same - contestant gains 1 point for that week.THH, HHT, and HTH, therefore, are 2 points.
Comment: @JW-OP take the sum of the values in the columns. It is increasing (only week 1 is different). You can also count the number of 0s, 1s, 2s, and 3s and they show a pattern that changes gradually.
Comment: I see it now. Week 7 (last week) was an especially good week for 18 contestants - each getting two or three points.The weekly averages are still about as expected, yes?
Comment: So you say that the increase in heads is all coincidence (this is of course possible, I just noticed a trend)? Another issue, aside from differences between weeks, is whether the individuals are to be assumed to have different probabilities in the "coin flip".
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/84989/discussion-between-jw-op-and-martijn-weterings).
Comment: To choose three winners out of a pool of 17 games with 17 winners and 17 losers, is a case of drawing *without* replacement, and should be modeled with a [Hypergeometric distribution](https://en.wikipedia.org/wiki/Hypergeometric_distribution) instead of a binomial distribution. But beyond that small detail the principle of Whuber's answer should work out the same (you get smaller variance because the cases with 0 and 3 heads become less probable, and the probability for the leader to win should rise somewhat). My answer becomes more complicated because there are no standard GLM(M) for this.
Answer: A relatively simple formula can be obtained, requiring only readily-computed sums and products.  The computational effort is proportional to the number of players, times the number of distinct scores they exhibit so far, times the number of remaining rounds, times the number of flips per round.

Let's establish notation:

Let $x=(x_1, x_2, \ldots, x_{23})$ be the current scores.
Let $n=17 - 7 = 10$ be the number of rounds to go.
Let the number of flips remaining during those rounds be $m = 3*n = 30.$
Let the coin have probability $p=1/2$ of coming heads.

There are $m+1$ possible scores for player $j$ at the end, given by $x_j+Z_j$ where $Z_j\in\{0,1,\ldots, m\}.$  The chances for $Z_j$ follow a Binomial$(m,p)$ distribution.
Suppose player $j$ ends up with score $x_j+z$ with probability $q$ (which we can readily compute).  In this case the chance this player wins outright is the chance that every other player's final score is less than $x_j+z.$  That, too, is readily computed from the Binomial distribution, because the scores of each player are independent, causing the individual chances to multiply.
To be clear,

Let $F$ be the cumulative distribution function for the Binomial$(m,p)$ distribution.
Let $f$ be the probability function, $$f(z) = \binom{m}{z}p^z (1-p)^{m-z}.$$

Thus, for each player $j$ and any possible number $z,$ $\Pr(Z_j \le z) = F(z).$ In particular note that $$\Pr(Z_j \lt z) = F(z-1).$$
Finally, let $\mathcal{W}_j$ be the event "Player $j$ wins outright" and $\mathcal{T}_j$ be the event "Player $j$ ties for the win."  From the foregoing and the axioms of probability it is immediate that

$$\Pr(\mathcal{W}_j \mid Z_j=z) = \prod_{i\ne j} F(x_j - z - x_i - 1)$$

and

$$\Pr(\mathcal{T}_j \mid Z_j=z) = \prod_{i\ne j} F(x_j - z - x_i) - \Pr(\mathcal{W}_j \mid Z_j=z).$$

We obtain the chances of wins and ties by summing over all the possible outcomes $Z_j,$

$$\Pr(\mathcal{W}_j) = \sum_{z=0}^m f(z) \Pr(\mathcal{W}_j\mid Z_j=z)$$

(and likewise for the ties).
For the $24$ players listed in the question, this calculation produces the following chances of wins and ties (with the nine unique scores given at the top):
    2     7      8      9     10     11     12     13     15
Win 0 4e-04 0.0014 0.0041 0.0106 0.0248 0.0529 0.1038 0.3251
Tie 0 1e-03 0.0026 0.0064 0.0136 0.0259 0.0446 0.0692 0.1215

(Despite the presentation of results by distinct scores, do not forget that the answers depend on how many players currently have each score.)

One can also simulate the game to estimate the chances.  This is perfectly straightforward; the details appear in the code at the end.
In a simulation of 10,000 independent continuations, the outcomes were these:
    2     7      8      9     10     11     12     13     15
Win 0 5e-04 0.0015 0.0041 0.0095 0.0261 0.0544 0.1018 0.3282
Tie 0 1e-03 0.0026 0.0063 0.0120 0.0250 0.0391 0.0660 0.1150

The agreement is good, suggesting the original calculations are correct.
It may be worth remarking that (a) the sum of winning chances cannot exceed $1$ and indeed will never equal $1$ whenever there is any chance of a tie; and (b) the sum of all winning chances plus tieing chances will never be less than $1$ and will always exceed $1$ whenever there is a chance of any three-way (or more-way) tie.
A better solution would be to weight ties inversely by how many people are in each tie, assuming if the game is tied at the end, winning will be equally distributed among all those tied with the best score.  This solution can be obtained using the same techniques, but is combinatorially more involved (it requires applying an inclusion-exclusion approach).

Because such calculations likely need to be repeated after each round, here to help with that is the R code.  It is not efficiently written, because it makes repeated calls to compute $F$ (with pbinom) and $f$ (with dbinom).  These calls can all be made once and stored in arrays, thereby speeding up the calculation.  This will not change the asymptotic behavior of the algorithm and would be useful only for large numbers of players or games with many coin flips to go.
#
# Inputs.
#
x <- c(2,10,12,8,11,13,9,12,8,9,9,11,15,9,12,10,11,7,11,8,8,11,10,9) # Current scores
n <- 17 - 7            # Number of rounds left
n.flip <- 3            # Flips per round
p <- 1/2               # Chance of success per flip
#
# Derived quantities.
#
n.players <- length(x)        # Number of players
m <- n.flip * n               # Number of flips to go
z <- 0:m                      # Possible outcomes for any player
prob <- dbinom(z, n.flips, p) # Their chances
#
# Compute individual chances of wins and ties.
#
scores <- sort(unique(x))
chances <- sapply(scores, function(score) {
  j <- min(which(x == score))
  y1 <- sapply(0:m, function(k) {
    exp(sum(pbinom(x[j] + k - x[(1:n.players)[-j]], m, p, log.p=TRUE)))
  })
  y <- sapply(0:n.flips, function(k) {
    exp(sum(pbinom(x[j] + k-1 - x[(1:n.players)[-j]], m, p, log.p=TRUE)))
  })
  c(Win=sum(prob * y), Tie=sum(prob * (y1-y)))
})
#
# Check with a simulation.  It will do a few thousand iterations per second.
#
set.seed(17)
sim <- replicate(1e4, {
  Z <- rbinom(n.players, m, p) # The future results
  final <- x + Z               # The final scores
  scores <- table(final)       # The unique final scores
  k <- length(scores)
  if (scores[k]==1) {
    Win <- final == max(final) # Tally who wins
    Tie <- rep(0, n.players)
  } else {
    Tie <- final == max(final) # Tally who ties
    Win <- rep(0, n.players)
  }
  rbind(Win, Tie)
})
sim <- apply(sim, 1:2, mean)   # Average over the iterations
#
# Display the results.
#
colnames(chances) <- paste(scores)
scores <- sort(unique(x))

sim <- sapply(scores, function(score) sim[, min(which(x==score))])
colnames(sim) <- paste(sort(unique(x)))

print(round(sim, 4))
print(round(chances, 4))

Comment: Your computational algorithm at end seems too explicit to be pseudocode, but it is not one I recognize. I can interpret it's function fairly well (programmer by trade), but the origin of the function "dbinom" and "pbinom" elude me. Might I inquire what language this is?
Comment: Ahh, I see now. 'Tis `R`. I thought that was another statistical term. Thank you for laying that out.
Comment: Does the above change much if a Tie and a Win can technically be considered a win for the sake of the normal point-scoring contest? If one or more players tie for 1st place, they would then be sub-ranked (tiebroken) via other player statistics like quality of record (number of 3-, 2-, and 1-point weeks).
Comment: It doesn't change at all: because my definitions of "tie" and "win" are mutually exclusive, you can simply add the chances for each person.  But note that the sum of these chances over all players exceeds 1.0: these are *individual probabilities* and not a probability distribution over the players.
Comment: Next, and possibly final point of clarification, with potential visceral reaction: Because I haven't yet built an actual computer application to drive these computations, where the above `R` code can be replicated - using this answer can the probability of a Win be computed within Microsoft Excel? Perhaps this is a new Stack Exchange question? Would it help/be appropriate to determine only any single individual's chance of beating the contest leader?
Comment: If you must use Excel, program the function in VBA.  You can even use Excel packages that connect to `R` if you like.  Please note that a given individual's chance of beating the current contest leader is only loosely related to their chance of actually winning, even assuming everybody is flipping the same coin.  A win means you beat *everybody,* not just the person who's currently ahead, and therefore will almost always have noticeably smaller chances than just beating the current leader.
Comment: Thank you very much. Your explanation has been most insightful. I was hoping to avoid macros, just because I don't know why - VBA, maybe. But if it's the best too, it's the best tool.
Comment: One more follow up, if I may: The `R` code above, when placed into this [online R compiler](https://rextester.com/l/r_online_compiler) shows Win/Tie at 0 for all rows/columns. I'm afraid I don't know enough about R to debug it.
Answer: modelling
You can model this as a binomial regression model where the odds/probability are functions of the player and the time (you add the time since there seems to be a time effect).
There are several ways to do this. That is the tricky part and you could first investigate what model would be best. But say you use a logistic model. Then the linear part can be modeled as a polynomial function where you choose the order based on whichever has the highest penalized log likelihood (e.g. aic).
Also, for better predictions you need to treat the effects for the players as some random variable (you could use a mixed model). In this way you get a shrinkage effect (say, you incorporate regression to the mean) which will lead to better predictions.
predicting
Given the model you can predict new values. This is a bit difficult since you modeled the function that defines a probability for a heads/tails, and not the heads/tails themselves. You could do, to obtain distributions of outcomes at week 17 for each participant:

monte carlo simulations
some computational solution of the integral (for every week you need to calculate all possible values for the probability, which is a continuous variable but you could discretize this, and for each of these probabilities you need to solve the probabilities for a particular outcome in number of heads)
Possibly you may evaluate the functions analytically (I doubt it however, you will get some Poisson binomial distribution with annoyingly many terms and those terms themselves are also distributed according to the error of your model instead of constant )
Or you could find some approximation to the outcome.

Based on the distributions for each individual (and assuming the outcomes for the individuals are independent) you can compute the probability that an individual is gonna win by summing over all outcomes of an individual; summing the probability for that outcome multiplied by the probabilities that the others are not gonna have an equal or higher outcome.
Comment: The final paragraph of this post sketches how to obtain an answer.  It's unclear how relevant the other remarks are about models or regression, because this does not appear to be a statistical problem: it is purely a computational exercise in probability.
Comment: @whuber, the other remarks are relevant because underlying this is not the standard coin flipping with *known* and with *constant* probabilities. Or at least, it does not appear as such to me, overdispersion (and strong correlation between the score and the individual) and change in time indicate that the problem is *not* like a static fair coin flip (assumption "Let the coin have probability p=1/2 of coming heads)". The OP simplified the question and wishes an answer of the simplified problem, but if you ask further you get to the fact that it is actually a football pool and not coinflips.
Comment: Thank you.  It is annoying that the nature of a question can change so fundamentally, especially after answers have been offered.
Comment: Technically the question did not change (and it is a bit ambiguous what a 'coin flip contest' means, it is not explicitly stated that the probabilities are 50%, I initially thought that this was literally a coin flipping contest where people try, with some technique, to flip heads) But it is a bit of an XYproblem, although the knowledge about the 32.5% probability of a win for the current leader (with 15 points) is very useful. I imagine that his probabilities are somewhat higher since he may also be 'better' and have a higher probability to "flip H", also the p will rise in time away from 0.5


BottomNavigationBar using Nativescript is not working

Question: I am beginner to Nativescript, I am trying to use BottomNavigationBar in my project. Below steps i have followed.
Step 1: npm i nativescript-bottom-navigation -> executed on my project path
Step 2: added the icons(As for testing purpose i have added only one image 'ic_home' and i only used that icon for all items) for android & iOS in your App_Resources directory.
Step 3: As guided in this link added html file and typescript codes
But I am getting below error while trying to run app. Please help me to come out from this rid.
==================
An uncaught Exception occurred on "main" thread.
com.tns.NativeScriptException:
Calling js method onCreateView failed
TypeError: AHBottomNavigation is not a constructor
File: "file:///data/data/org.nativescript.bottomsheet/files/app/tns_modules/nativescript-bottom-navigation/bottom-navigation.js, line: 22, column: 26
==================
Answer: Why not use the nativescript Tab View? https://docs.nativescript.org/angular/code-samples/ui/tab-view
I'm guessing you want to put the tabs at the bottom on android platform? well in the latest version of nativescript (4.0) you can now have the option to put the tab at the bottom on android by setting androidTabsPosition="bottom" see this link for example: https://docs.nativescript.org/angular/code-samples/ui/tab-view#tabs-position
Comment: I have found a couple issues with TabView for android.  Do you know if you can disable horizontal scrolling of tabs when you have like 5+ tabs?  Also, I found that when using position bottom, the tabs float up to top of keyboard when it is displayed.
Comment: yeah, there are confirmed issues with the current tab implementation for iOS/Android. But there's an ongoing plan to create a new tab implementation, you can check track it here https://github.com/NativeScript/NativeScript/tree/tabs-redesign .

But on my side I created a custom tab using `StackLayout` or `GridLayout`.


Deduce P(h|h or w) from P(h), P(w), P(h and w) and P(h or w)

Question: Life expectancy tables for a given couple predict that the husband has a 60% chance of surviving 10 years and his wife has a 80% chance of surviving 10 years.
1.) Find the probability that both survive 10 years.
2.) Find the probability that ONLY ONE of the couple will survive 10 years.
3.) Given that only one survives after 10 years, what is the probability that it is the husband?
My solution:
1.) P(Husband and Wife survive) = 0.48
2.) P(only one of them survive) = 0.92
3.) P(Husband survives given that husband or Wife survives) = 0.65
Edit: Wrote the whole problem.
Comment: Applying the definition P(h|h or w)=P(h and (h or w))/P(h or w)=P(h)/P(h or w), perhaps?
Comment: Note that if you were only given P(h) and P(w) and "deduced" from these the values of P(h and w) and P(h or w) given in your post, then this deduction is wrong and there is no way to compute P(h|h or w).
Comment: Was it given that h and w are independent? If not, where do you get P(h and w)? More info needed.
Answer: There is this formula:
$$P(A|B)=\frac{P(A\cap B)}{P(B)}$$
which here means:
$$P(h|h\ or\ w)=\frac{P(h\ and\ (h\ or \ w))}{P(h\ or\ w)}=\frac{P(h)}{P(h\ or\ w)}=\frac{0.6}{0.92}$$
Answer:
Consider
$$(A\ and \ B) \equiv (A \cap B)$$
and
$$(A\ or \ B) \equiv (A \cup B)$$
This is Conditional Probability
$$P(A|B) = \frac{P(A\ and \ B)}{P(B)}$$
And This is always true that  $$h \subset (h\ or\ w)$$ so
$$P\Big((h)\ and\ (h\ or\ w)\Big) = P(h)$$
This means if $A$ be a subset of $B$ then Intersection of $A$, $B$ is $A$.
Solution
$$
\begin{align}
P(h|h\ or\ w) &= \frac{P\Big((h)\ and\ (h\ or\ w)\Big)}{P(h\ or\ w)}\\
\\
&= \frac{P(h)}{P(h\ or\ w)}\\
\\
&=\frac{0.6}{0.92}\\
\\
& \simeq 0.65
\end{align}
$$


Fitting negative binomial in python

Question: In scipy there is no support for fitting a negative binomial distribution using data
(maybe due to the fact that the negative binomial in scipy is only discrete).
For a normal distribution I would just do:
from scipy.stats import norm
param = norm.fit(samp)

Is there something similar 'ready to use' function in any other library?
Comment: Have you found the solution to this question?
Comment: Please see the answer from @Eran.
statsmodels.discrete.discrete_model.NegativeBinomial
Answer: Statsmodels has discrete.discrete_model.NegativeBinomial.fit(), see here:
https://www.statsmodels.org/dev/generated/statsmodels.discrete.discrete_model.NegativeBinomial.fit.html#statsmodels.discrete.discrete_model.NegativeBinomial.fit
Answer: Not only because it is discrete, also because maximum likelihood fit to negative binomial can be quite involving, especially with an additional location parameter. That would be the reason why .fit() method is not provided for it (and other discrete distributions in Scipy), here is an example:
In [163]:

import scipy.stats as ss
import scipy.optimize as so
In [164]:
#define a likelihood function
def likelihood_f(P, x, neg=1):
    n=np.round(P[0]) #by definition, it should be an integer
    p=P[1]
    loc=np.round(P[2])
    return neg*(np.log(ss.nbinom.pmf(x, n, p, loc))).sum()
In [165]:
#generate a random variable
X=ss.nbinom.rvs(n=100, p=0.4, loc=0, size=1000)
In [166]:
#The likelihood
likelihood_f([100,0.4,0], X)
Out[166]:
-4400.3696690513316
In [167]:
#A simple fit, the fit is not good and the parameter estimate is way off
result=so.fmin(likelihood_f, [50, 1, 1], args=(X,-1), full_output=True, disp=False)
P1=result[0]
(result[1], result[0])
Out[167]:
(4418.599495886474, array([ 59.61196161,   0.28650831,   1.15141838]))
In [168]:
#Try a different set of start paramters, the fit is still not good and the parameter estimate is still way off
result=so.fmin(likelihood_f, [50, 0.5, 0], args=(X,-1), full_output=True, disp=False)
P1=result[0]
(result[1], result[0])
Out[168]:
(4417.1495981801972,
 array([  6.24809397e+01,   2.91877405e-01,   6.63343536e-04]))
In [169]:
#In this case we need a loop to get it right
result=[]
for i in range(40, 120): #in fact (80, 120) should probably be enough
    _=so.fmin(likelihood_f, [i, 0.5, 0], args=(X,-1), full_output=True, disp=False)
    result.append((_[1], _[0]))
In [170]:
#get the MLE
P2=sorted(result, key=lambda x: x[0])[0][1]
sorted(result, key=lambda x: x[0])[0]
Out[170]:
(4399.780263084549,
 array([  9.37289361e+01,   3.84587087e-01,   3.36856705e-04]))
In [171]:
#Which one is visually better?
plt.hist(X, bins=20, normed=True)
plt.plot(range(260), ss.nbinom.pmf(range(260), np.round(P1[0]), P1[1], np.round(P1[2])), 'g-')
plt.plot(range(260), ss.nbinom.pmf(range(260), np.round(P2[0]), P2[1], np.round(P2[2])), 'r-')
Out[171]:
[<matplotlib.lines.Line2D at 0x109776c10>]

Comment: I realized it is a very ad-hoc solution. The optimization function does  not work always
Answer: I know this thread is quite old, but current readers may want to look at this repo which is made for this purpose: https://github.com/gokceneraslan/fit_nbinom
There's also an implementation here, though part of a larger package: https://github.com/ernstlab/ChromTime/blob/master/optimize.py
Answer: I stumbled across this thread, and found an answer for anyone else wondering.
If you simply need the n, p parameterisation used by scipy.stats.nbinom you can convert the mean and variance estimates:
mu = np.mean(sample)
sigma_sqr = np.var(sample)

n = mu**2 / (sigma_sqr - mu)
p = mu / sigma_sqr

If you the dispersionparameter you can use a negative binomial regression model from statsmodels with just an interaction term. This will find the dispersionparameter alpha using MLE.
# Data processing
import pandas as pd
import numpy as np

# Analysis models
import statsmodels.formula.api as smf
from scipy.stats import nbinom

def convert_params(mu, alpha):
    """
    Convert mean/dispersion parameterization of a negative binomial to the ones scipy supports

    Parameters
    ----------
    mu : float
       Mean of NB distribution.
    alpha : float
       Overdispersion parameter used for variance calculation.

    See https://en.wikipedia.org/wiki/Negative_binomial_distribution#Alternative_formulations
    """
    var = mu + alpha * mu ** 2
    p = mu / var
    r = mu ** 2 / (var - mu)
    return r, p

# Generate sample data
n = 2
p = 0.9
sample = nbinom.rvs(n=n, p=p, size=10000)

# Estimate parameters
## Mean estimates expectation parameter for negative binomial distribution
mu = np.mean(sample)

## Dispersion parameter from nb model with only interaction term
nbfit = smf.negativebinomial("nbdata ~ 1", data=pd.DataFrame({"nbdata": sample})).fit()

alpha = nbfit.params[1]  # Dispersion parameter

# Convert parameters to n, p parameterization
n_est, p_est = convert_params(mu, alpha)

# Check that estimates are close to the true values:
print("""
                   {:<3}   {:<3}
True parameters:  {:<3}   {:<3}
Estimates      :  {:<3}   {:<3}""".format('n', 'p', n, p,
                                  np.round(n_est, 2), np.round(p_est, 2)))

Comment: It appears that in statsmodels>=0.14.0 the NegativeBinomial model includes method that returns a scipy.stats.nbinom distribution object  without any custom additional code https://www.statsmodels.org/stable/generated/statsmodels.discrete.discrete_model.NegativeBinomial.get_distribution.html#statsmodels.discrete.discrete_model.NegativeBinomial.get_distribution

Fitting negative binomial in python


Codeigniter not generating its log files

Question: I am running codeigniter framework and I've come across a peculiar problem.
Even though I have turned logging 'on', no log files are being generated.
Looking at responses to similar questions on this forum, I did the following:

Created a new folder with 777 permissions and "apache" as the owner
Specified this folder as the logging destination
Set logging threshold as 4

Below are the excerpts from the settings file:
<code>*/
$config['log_threshold'] = 4;
$config['log_path'] = '/logtest/';
/*
</code>
Here are the permissions details of the log directory:
 drwxrwxrwx.   2 apache apache    6  8月 12 09:28 logtest
Even with these settings I'm not seeing any files being generated in the log folder.
Could someone please guide me on how to fix this, or direct me to settings that I should be looking at?
Edit: I'm running version 2.2.0 of CodeIgniter
Thanks,
Comment: Open system/core/Log.php and change the following lines; set the value of: $this->log_path to a writable directory, preferably home directory so that there are no permission issues. If you want to change the filename also, search for the variable $filepath and change the name. Example: $this->log_path = '/log'; touch /log/ restart the webserver.not best the best one
Comment: @Anmol Raghuvanshi: There's no "Log.php" in the system/core folder. I'm running ver 2.2.0 of CodeIgniter.
Comment: i am using CI-3 then you should check on libraries folder
Comment: have a look http://stackoverflow.com/questions/3209807/how-to-do-error-logging-in-codeigniter-php
Comment: I made the changes you suggested to no avail.
No log files are being generated. I have no idea where to look for reasons as to why logfile creation isn't happening.
Answer: Keep in mind that you have set your log_path to the root of your hardisk.
Try:
<code>$config['log_path'] = BASEPATH.'logtest';
</code>


Confidence intervals for non-parametric statistics

Question: I have a positive random variable $X$ (say, price or latency or energy) and I want to be able to say something like

I am 95% confident that $P(X<42)>0.9$ (percentile) or $P(X<22)\ge\frac12$ (median)
I am 97% confident that $EX<17$ (mean)

If I knew that the distribution is, say, Exponential, I could use the confidence interval for $\lambda$. However, I would rather avoid such assumptions.
It seems that I should be able to use the CLT for the Empirical distribution function, so, for $x=42$ I can see that $$\hat{F}_n(42)-F(42)\sim N(0,\frac{F(42)(1-F(42))}n)$$
Am I barking up the wrong tree here?
How do I make the type (1) statement? (2 is optional)
Comment: (1) Is called a *tolerance interval* (or *tolerance limit*), while (2) indeed is a confidence interval.  Nonparametric TLs are usually based on order statistics.  There's not much in the way of good accounts to be found with a Web search, but the Hahn & Meeker handbook, *Statistical Intervals,* explains this and some US government guidance has some good material, too: see https://nepis.epa.gov/Exe/ZyPURL.cgi?Dockey=P10055GQ.TXT for instance. Good nonparametric CLs for the mean are hard to come by: it helps immensely to restrict the possible distribution as much as possible.
Comment: For #1, do you mean that you're looking for confidence intervals for the 0.5 and 0.9 quantiles?
Comment: This can be addressed with a semiparametric model.  See the chapter on ordinal models for continuous Y in [rms](https://hbiostat.org/rms).
Comment: @Dave: yes, upper bounds thereof
Answer: What I am looking for turned out to be either a tolerance interval or a prediction interval.
Comment: There isn't anything in your formulation of the question to suggest you were looking for a prediction interval.


How to obtain contents from a drupal 7 query?

Question: I am trying to perform the below simple query:
$query = db_select('sage.USER', 'USER')
  ->fields('USER', array('USER_ID', 'OFFICE_ID'));
$result = $query->execute();

I would like to then pull out the 'office_id' that is returned by the query, which I have been told can be done with the following:
$office = $result->office_id;

However, when I do 'print_r($office)' or 'echo $office', it would seem the $office string is empty. The database is not empty and contains the appropriate values.
Could someone please how I can pull out the contents of a drupal 7 query?
Answer: execute() returns a resource you can iterate over in a foreach loop, e.g:
foreach ($result as $record) {
  $office_id = $record->office_id;
}

In your case you probably want to use the fetchObject() method to actually retrieve the first record returned from the query:
$result = $query->execute()->fetchObject();
$office = $result->office_id;

Comment: I am trying to do this in a Migrate class. If I do $result->execute()->fetchObject() I will only ever get the first office_id and that will be used for all my records. If I do $result->execute() and loop over the records with foreach, then only the last office_id will be used for all the records...is there a way I can make it so the office_ids are used in sequential order?
Comment: I'm not really familiar with custom Migrate classes, but going off the code in your other question it seems like you need to add a condition to your db query. Is the code for your class very long? It might be worth posting it in a new question so people can offer advice, it gets a bit tricky to debug code in the comments and editing the answer with stuff not relevant to the original question might make this thread lose its focus


Where is the actual content in a TCP segment

Question: When I email something or download a program, or do anything else over a network, where in the segment is the actual content? If I am emailing a 20KB word document, and the maximum data field size in a segment is 1500 bytes, does that mean it takes about 14 segments to mail my document wherever it is going?
I get, I think, the OSI model and I have a decent grasp of the IP protocol. I think I understand the concept of header wrapping of each successive layer in the protocol stack. What I can't get a definitive answer to is where does the actual content go in a TCP segment? Is that the datagram?
Maybe the fact I am asking proves I have no clue...
Many thanks.
Answer: The data comes at offset 160 if no option-headers are present, and further down (multiples of 32) if IP option headers are present. The data portion continues to the end of the packet.  A packet can be variable size due to differing MTu settings along the path, so the exact number of packets a portion of higher-protocol data gets carved into depends.
The 'datagram' is the size of the IP header + data.
You are incorrect in the maximum data field size being 1500b. That's the size of the entire packet including headers. The data-field size is variable based on header length, as I described above.
Comment: So would I be correct in saying the word document in my example gets split up however many times is required and the actual text from that document goes into that data field starting at offset 160 or later? My confusion centers on not being clear on if the 'data'  that get encapsulated at each successive layer are referring to protocol 'data' (PDU's) or the actual stuff people send each other and read. My apologies if I am not making sense. I am trying to understand the practical implementation of all this. Separating the abstraction, if you will.
Comment: @packetloss Since we're talking layer 3 here, it's (in your case) SMTP data in each packet, which is likely the base64 representation of the binary file itself.
Comment: I think that answers my question. Now I think I have more questions...
Answer: The content gets broken up into chunks and put into the "data" portion of the packets.  The offsets for that data section were mentioned in another answer.
This is worth a read:
http://en.wikipedia.org/wiki/TCP_packet#TCP_segment_structure
TCP/IP is pretty complicated; witness:
http://www.tcpipguide.com/free/t_toc.htm
Here's a pretty good representation of the data portion of packets, which I found on http://concept51.co.uk/in_how_networks.html :
Comment: Perhaps this is where I am missing something. The encapsulation that occurs in the diagram you attached is for the PDU's, correct? My apologies for the confusion but isn't this just 'data' for the various protocols? And not the actual text in the word document I am sending in the example? I have read the wikipedia article and sentences like: 'The Option-Kind field indicates the type of option, and is the only field that is not optional' do not shed light on this.
Comment: The data of the 20K word document gets broken up into chunks and each chunk is put into the data portion of a packet - the green portion in the above diagram.   For the packets involved in sending your word document, that green data portion isn't for anything else other than the chunks comprising your word document - the "payload" being transmitted.
Answer: Please see RFC 793 (http://www.ietf.org/rfc/rfc793.txt).
The actual "data" (i.e., your document) is contained in the TCP segment (after the TCP header) of the packet.  The size of the data in the packet is determined by the TCP Maximum Segment Size (MSS).
I suggest downloading a tool like Wireshark (http://www.wireshark.org) and capturing the network traffic as you send your file.  Wireshark will interpret the packets for you (you can even right click on one of the packets which contain data from your file and select 'Follow TCP Stream').
You will also be able to look at each successive packet header which is decoded and explained for you by Wireshark.  That should give you a much better idea as to what's happening when you sent data via TCP.
HTHAL