<commit_before>"use strict";

function soma(numeroA, numeroB) {
    return numeroA + numeroB;
}
function subtrair(numeroA, numeroB) {
    return numeroA - numeroB;
}
function multiplicar(numeroA, numeroB) {
    return numeroA * numeroB;
}
function dividir(numeroA, numeroB) {
    if(numeroA == 0 || numeroB == 0){
        return "Ops, ZERO ??";
    }
    return numeroA / numeroB;
}

function validarCampoNaN($campo){
    if(isNaN($campo.value)){
        $campo.value = "";
        $campo.placeholder = "Digite um numero";
        return 0;
    }else{
        return Number(campoB.value)
    };
}

function ativarBotao($botao,$metodo) {
    $botao.addEventListener("click", function () {
        var numeroA = validarCampoNaN(campoA),
            numeroB = validarCampoNaN(campoB);

        document.getElementById("resultado").innerHTML = $metodo(numeroA, numeroB);
    });

}

window.onload = function () {
    var botaoSOMAR = document.getElementById("somar"),
        botaoSUBTRAIR = document.getElementById("subtrair"),
        botaoMULTIPLICAR = document.getElementById("multiplicar"),
        botaoDIVIDIR = document.getElementById("dividir");

    var campoA = document.getElementById("campoA"),
        campoB = document.getElementById("campoB");

    ativarBotao(botaoSOMAR,soma);
    ativarBotao(botaoSUBTRAIR,subtrair);
    ativarBotao(botaoMULTIPLICAR,multiplicar);
    ativarBotao(botaoDIVIDIR,dividir);
};

<commit_msg>Exercicio para a turma COMENTAR e interpretar o codigo, DESCREVER ALGO facilita a memorização, lembrem!<commit_after>"use strict";
// Função som.a...
function soma(numeroA, numeroB) {
    return numeroA + numeroB;
}
// Função som.a...
function subtrair(numeroA, numeroB) {
    return numeroA - numeroB;
}
// Função som.a...
function multiplicar(numeroA, numeroB) {
    return numeroA * numeroB;
}
// Função som.a...
function dividir(numeroA, numeroB) {
    if(numeroB == 0){
        return "Ops, ZERO ??";
    }
    return numeroA / numeroB;
}
/*
    @name: adhakdjahsjkd,
    @parametros: dajhdadhjas,adha
    @description:
        1. se ov aasdhaskdja
        2. ajkdhkadhkasjd
            2.1 akdshakdhkajs
*/
function validarCampoNaN($campo){
    if(isNaN($campo.value)){
        $campo.value = "";
        $campo.placeholder = "Digite um numero";
        return 0;
    }else{
        return Number($campo.value)
    };
}

function ativarBotao($botao,$metodo) {
    $botao.addEventListener("click", function () {
        console.log(campoA,campoB);
        var numeroA = validarCampoNaN(campoA),
            numeroB = validarCampoNaN(campoB);

        document.getElementById("resultado").innerHTML = $metodo(numeroA, numeroB);
    });

}
window.onload = function () {
    var botaoSOMAR = document.getElementById("somar"),
        botaoSUBTRAIR = document.getElementById("subtrair"),
        botaoMULTIPLICAR = document.getElementById("multiplicar"),
        botaoDIVIDIR = document.getElementById("dividir");

    var campoA = document.getElementById("campoA"),
        campoB = document.getElementById("campoB");

    ativarBotao(botaoSOMAR,soma);
    ativarBotao(botaoSUBTRAIR,subtrair);
    ativarBotao(botaoMULTIPLICAR,multiplicar);
    ativarBotao(botaoDIVIDIR,dividir);

};

<|endoftext|>


<commit_before>/*jslint devel: true*/
/*global perfis */

// variables
var project, beam, mk, concrete, steel;
var tsd, as, bw, fcd;
var betax23, betax34, epc, eps, epyd, fyd, Es, fck, fyk, fckForm, fykForm;
var d, h, cob, diamEstForm, diamLongForm, diamEst, diamLong;
var a, b, c, delta, deltaR, x1, x2;
var x, mk, md;
var x2lim, x3lim, dominio, dl;
var gamac, gamaf, gamas, s;
var situationD, situationLN;
var dlc, xd, m1d, m2d, tlsd, asl, as1, as2, ast, situationS, result;
var astcalc, asccalc, ncamC, ncamT;

var nBarras, nBarrasC, nBarrasT;
var arranjos = [];

var bitola = [
    {
        "diametro": 5.0,
        "area": 0.196349540849362
    },
    {
        "diametro": 6.3,
        "area": 0.311724531052447
    },
    {
        "diametro": 8.0,
        "area": 0.502654824574367
    },
    {
        "diametro": 10.0,
        "area": 0.785398163397448
    },
    {
        "diametro": 12.5,
        "area": 1.22718463030851
    },
    {
        "diametro": 16.0,
        "area": 2.01061929829747
    },
    {
        "diametro": 20.0,
        "area": 3.80132711084365
    },
    {
        "diametro": 25.0,
        "area": 4.90873852123405
    },
    {
        "diametro": 32.0,
        "area": 8.04247719318987
    },
    {
        "diametro": 40.0,
        "area": 12.5663706143592
    }

];

var steelProp = [
    {
        "steelType": "CA25",
        "fy": 250,
        "fu": 217.4,
        "E": 21000
    },
    {
        "steelType": "CA50",
        "fy": 500,
        "fu": 434.8,
        "E": 21000
    },
    {
        "steelType": "CA60",
        "fy": 600,
        "fu": 521.7,
        "E": 21000
    }
];

var concreteProp = [
    {
        "concType": "C20",
        "fckProp": 200
    },
    {
        "concType": "C25",
        "fckProp": 250
    },
    {
        "concType": "C30",
        "fckProp": 300
    },
    {
        "concType": "C35",
        "fckProp": 350
    },

    {
        "concType": "C40",
        "fckProp": 400
    },
    {
        "concType": "C45",
        "fckProp": 450
    },
    {
        "concType": "C50",
        "fckProp": 500
    }

];

function processFormDC() {
    "use strict";
    var i, j, k, w;

    /* Clean suggestion array */
    arranjos = [];

    // Getting values from HTML form inputs
    project = document.formDC.projectDC.value;
    /* if (project === "") {
        alert("Por favor preencha o campo Projeto.");
        console.log("Por favor preencha o campo Projeto.");
        return false;
    } */
    if (project === "") {
        project = "Exemplo 1";
    }

    beam = document.formDC.beamDC.value;
    /* if (beam === "") {
        alert("Por favor preencha o campo Viga.");
        console.log("Por favor preencha o campo Viga.");
        return false;
    } */
    if (beam === "") {
        beam = "V1";
    }

    h = Number(document.formDC.hDC.value);
    if (document.formDC.hDC.value === "" || isNaN(h)) {
        alert("Por favor preencha o campo Altura da Viga com números.");
        console.log("Por favor preencha o campo Altura da Viga.");
        return false;
    }

    bw = Number(document.formDC.bwDC.value);
    if (document.formDC.bwDC.value === "" || isNaN(bw)) {
        alert("Por favor preencha o campo Largura da Viga com números.");
        console.log("Por favor preencha o campo Largura da Viga.");
        return false;
    }

    ncamT = Number(document.formDC.layerTCC.value);
    if (document.formDC.layerTCC.value === "" || isNaN(bw)) {
        alert("Por favor preencha o campo Nº de camadas tracionadas com números.");
        console.log("Por favor preencha o Nº de camadas tracionadas.");
        return false;
    }

    nBarrasT = Number(document.formDC.barsTCC.value);
    if (document.formDC.barsTCC.value === "" || isNaN(bw)) {
        alert("Por favor preencha o campo Nº de barras com números.");
        console.log("Por favor preencha o Nº de barras.");
        return false;
    }

    ncamC = Number(document.formDC.layerCCC.value);
    if (document.formDC.layerCCC.value === "" || isNaN(bw)) {
        alert("Por favor preencha o campo Nº de camadas comprimidas com números.");
        console.log("Por favor preencha o Nº de camadas comprimidas.");
        return false;
    }

    nBarrasC = Number(document.formDC.barsCCC.value);
    if (document.formDC.barsCCC.value === "" || isNaN(bw)) {
        alert("Por favor preencha o campo Nº de barras com números.");
        console.log("Por favor preencha o Nº de barras.");
        return false;
    }

    mk = Number(document.formDC.mDC.value);
    if (document.formDC.mDC.value === "" || isNaN(mk)) {
        alert("Por favor preencha o campo Momento com números.");
        console.log("Por favor preencha o campo Momento.");
        return false;
    }

    concrete = concreteProp[(document.formDC.concreteDC.value)].concType;
    steel = steelProp[(document.formDC.steelDC.value)].steelType;
    diamLongForm = bitola[Number(document.formDC.longDC.value)].diametro;
    diamEstForm = bitola[Number(document.formDC.estDC.value)].diametro;
    gamac = Number(document.formDC.gamacDC.value);
    gamaf = Number(document.formDC.gamafDC.value);
    gamas = Number(document.formDC.gamasDC.value);
    s = Number(document.formDC.sDC.value);
    cob = Number(document.formDC.cobDC.value);
    dl = Number(document.formDC.dlDC.value);
    dlc = Number(document.formDC.dlcDC.value);

    // Getting bitolaLong properties
    i = Number(document.getElementById("bitolaLongT").value);
    w = Number(document.getElementById("bitolaLongC").value);

        // Getting concrete properties
    j = Number(document.getElementById("concrete").value);

    fckForm = concreteProp[j].fckProp;

    // Getting steel properties
    k = Number(document.getElementById("steel").value);

    fykForm = steelProp[k].fy;
    Es = steelProp[k].E;

    // Converting Units
    fyk = fykForm / 10;
    fck = fckForm / 100;
    diamEst = diamEstForm / 10;
    diamLong = diamLongForm / 10;

    // Calculating parameters
    fcd = fck / gamac;
    fyd = fyk / gamas;
    tsd = fyd;
    epc = 3.5;
    eps = 10.0;

    //CÁLCULO DO MOMENTO FLETOR MAJORADO
    md = mk * gamaf;

    //CÁLCULO DA ALTURA ÚTIL (d)
    d = h - dl;

    //CÁLCULO DOS LIMITES DOS DOMÍNIOS 2 E 3
    //DOMÍNIO 2
    betax23 = epc / (epc + eps);

    //DOMÍNIO 3
    epyd = (fyd / Es) * 1000;
    betax34 = epc / (epc + epyd);

    //CÁLCULO DA POSIÇÃO DA LINHA NEUTRA (x)
    //md = 0.68*bw*x*fcd*(d-0.4*x);
    //(0.4*x^2)+(d*x)+(md/(0.68*bw*fcd))=0

    a = 0.4;
    b = -1 * d;
    c = md / (0.68 * bw * fcd);
    delta = Math.pow(b, 2) - ((4 * a) * c);

    if (delta > 0) {
	    deltaR = Math.sqrt(delta);
	    x1 = ((-b +  deltaR)  / (2 * a));
	    x2 = ((-b -  deltaR)  / (2 * a));
    } else {
        x1 = ("Sem raiz");
		x2 = ("Sem raiz");
    }

    if (x1 > h) {
        x = x2;
    } else {
        x = x1;
    }

    //VERIFICAÇÃO DO DOMÍNIO DA VIGA

    x2lim = betax23 * d;
    x3lim = betax34 * d;

    if (x > x2lim && x < x3lim) {
        dominio = "Domínio 3";
        situationD = "Aprovado";
    } else if (x < x2lim) {
        dominio = "Domínio 2";
        situationD = "Aprovado";
    } else if (x > x3lim) {
        dominio = "Domínio 4";
        situationD = "Reprovado";
    } else {
        dominio = "Error";
    }

    //VERIFICAÇÃO DA RELAÇÃO x/d

    if (x / d <= 0.45) {
        situationLN = "Aprovada";
    } else {
        situationLN = "Reprovada";
    }

    //CÁLCULO DA ÁREA DE AÇO

    if (situationD === "Aprovado" && situationLN === "Aprovada") {
        situationS = "Simples";
	    as = md / (tsd * (d - 0.4 * x));
        alert(as);

    } else {
        situationS = "Dupla";

        //Cálculo da nova posição da LN
        xd = 0.45 * d;

        //Cálculo de M1d
        m1d = 0.68 * bw * xd * fcd * (d - 0.4 * xd);

        //Cálculo de M2d
        m2d = md - m1d;

        //Encontrar valor de tlsd na tabela (!!!!)
        tlsd = 43.5;

        //Encontrar área de aço comprimida A's
        asl = m2d / (tlsd * (d - dlc));

        //Encontrar área de aço tracionada As
        as1 = m1d / (tsd * (d - 0.4 * xd));
        as2 = m2d / (tsd * (d - dlc));
        ast = as1 + as2;

        //Calcular Área de Aço Utilizada na Viga em Verificação
        astcalc = nBarrasT * ncamT * bitola[i].area;
        asccalc = nBarrasC * ncamC * bitola[w].area;
        if (astcalc >= ast && asccalc >= asl) {
            result = "A viga resiste ao momento cortante solicitado";
            alert(result);
        } else {result = "A viga não resiste ao momento cortante solicitado";
                alert(result);
               }

        //result = "Área de aço comprimida = " + asl + "cm². Área de aço tracionada = " + ast + "cm².";
        //alert(result);

        //Arranjos
        if (situationS === "Simples") {
            for (i = 0; i < arranjos.length; i += 1) { //Log of approved
                console.log(arranjos[i]);
                nBarras = as / (bitola[i].area);
            }
        } else {
            for (i = 0; i < arranjos.length; i += 1) { //Log of approved
                console.log(arranjos[i]);
                nBarrasC = asl / (bitola[i].area);
                nBarrasT = ast / (bitola[i].area);
            }
        }

        arranjos.push({    // saves to a list of approved sections
            "bitola": bitola[i],
            "area": bitola[i].area,
            "nº de barras": nBarras

        });

    }

}

  /*
    document.getElementById("botaoRelatorio").href = "reportCS.html?test=" + JSON.stringify(resultado);
} */

/*
    Cria um objeto bitola
*/
function criarBitola(nomeBitola, linhaBitola) {
    "use strict";
    var opcao = document.createElement("OPTION"),
        texto = document.createTextNode(nomeBitola);
    opcao.value = linhaBitola;
    opcao.appendChild(texto);
    return opcao;
}

var bitolaLista1 = document.getElementById("bitolaLongT"),
    bitolaLista2 = document.getElementById("bitolaEst"),
    acoLista = document.getElementById("steel"),
    concretoLista = document.getElementById("concrete"),
    i;

for (i = 0; i < bitola.length; i += 1) {
    bitolaLista1.appendChild(criarBitola(bitola[i].diametro, i));
}

for (i = 0; i < bitola.length; i += 1) {
    bitolaLista2.appendChild(criarBitola(bitola[i].diametro, i));
}

var bitolaLista3 = document.getElementById("bitolaLongC"),
    acoLista = document.getElementById("steel"),
    concretoLista = document.getElementById("concrete"),
    w;

for (w = 0; w < bitola.length; w += 1) {
    bitolaLista3.appendChild(criarBitola(bitola[w].diametro, w));
}

function criarAco(nomeAco, linhaAco) {
    "use strict";
    var opcao = document.createElement("OPTION"),
        texto = document.createTextNode(nomeAco);
    opcao.value = linhaAco;
    opcao.appendChild(texto);
    return opcao;
}

for (i = 0; i < steelProp.length; i += 1) {
    acoLista.appendChild(criarAco(steelProp[i].steelType, i));
}

function criarConcreto(nomeConcreto, linhaConcreto) {
    "use strict";
    var opcao = document.createElement("OPTION"),
        texto = document.createTextNode(nomeConcreto);
    opcao.value = linhaConcreto;
    opcao.appendChild(texto);
    return opcao;
}

for (i = 0; i < concreteProp.length; i += 1) {
    concretoLista.appendChild(criarConcreto(concreteProp[i].concType, i));
}
<commit_msg>Update scriptCC-Dupla.js<commit_after>/*jslint devel: true*/
/*global perfis */

// variables
var project, beam, mk, concrete, steel;
var tsd, as, bw, fcd;
var betax23, betax34, epc, eps, epyd, fyd, Es, fck, fyk, fckForm, fykForm;
var d, h, cob, diamEstForm, diamLongForm, diamEst, diamLong;
var a, b, c, delta, deltaR, x1, x2;
var x, mk, md;
var x2lim, x3lim, dominio, dl;
var gamac, gamaf, gamas, s;
var situationD, situationLN;
var dlc, xd, m1d, m2d, tlsd, asl, as1, as2, ast, situationS, result;
var astcalc, asccalc, ncamC, ncamT;

var nBarras, nBarrasC, nBarrasT;
var arranjos = [];

var bitola = [
    {
        "diametro": 5.0,
        "area": 0.196349540849362
    },
    {
        "diametro": 6.3,
        "area": 0.311724531052447
    },
    {
        "diametro": 8.0,
        "area": 0.502654824574367
    },
    {
        "diametro": 10.0,
        "area": 0.785398163397448
    },
    {
        "diametro": 12.5,
        "area": 1.22718463030851
    },
    {
        "diametro": 16.0,
        "area": 2.01061929829747
    },
    {
        "diametro": 20.0,
        "area": 3.80132711084365
    },
    {
        "diametro": 25.0,
        "area": 4.90873852123405
    },
    {
        "diametro": 32.0,
        "area": 8.04247719318987
    },
    {
        "diametro": 40.0,
        "area": 12.5663706143592
    }

];

var steelProp = [
    {
        "steelType": "CA25",
        "fy": 250,
        "fu": 217.4,
        "E": 21000
    },
    {
        "steelType": "CA50",
        "fy": 500,
        "fu": 434.8,
        "E": 21000
    },
    {
        "steelType": "CA60",
        "fy": 600,
        "fu": 521.7,
        "E": 21000
    }
];

var concreteProp = [
    {
        "concType": "C20",
        "fckProp": 200
    },
    {
        "concType": "C25",
        "fckProp": 250
    },
    {
        "concType": "C30",
        "fckProp": 300
    },
    {
        "concType": "C35",
        "fckProp": 350
    },

    {
        "concType": "C40",
        "fckProp": 400
    },
    {
        "concType": "C45",
        "fckProp": 450
    },
    {
        "concType": "C50",
        "fckProp": 500
    }

];

function processFormDC() {
    "use strict";
    var i, j, k, w;

    /* Clean suggestion array */
    arranjos = [];

    // Getting values from HTML form inputs
    project = document.formCC.projectCC.value;
    /* if (project === "") {
        alert("Por favor preencha o campo Projeto.");
        console.log("Por favor preencha o campo Projeto.");
        return false;
    } */
    if (project === "") {
        project = "Exemplo 1";
    }

    beam = document.formDC.beamCC.value;
    /* if (beam === "") {
        alert("Por favor preencha o campo Viga.");
        console.log("Por favor preencha o campo Viga.");
        return false;
    } */
    if (beam === "") {
        beam = "V1";
    }

    h = Number(document.formDC.hCC.value);
    if (document.formCC.hCC.value === "" || isNaN(h)) {
        alert("Por favor preencha o campo Altura da Viga com números.");
        console.log("Por favor preencha o campo Altura da Viga.");
        return false;
    }

    bw = Number(document.formCC.bwCC.value);
    if (document.formDC.bwDC.value === "" || isNaN(bw)) {
        alert("Por favor preencha o campo Largura da Viga com números.");
        console.log("Por favor preencha o campo Largura da Viga.");
        return false;
    }

    ncamT = Number(document.formCC.layerTCC.value);
    if (document.formCC.layerTCC.value === "" || isNaN(bw)) {
        alert("Por favor preencha o campo Nº de camadas tracionadas com números.");
        console.log("Por favor preencha o Nº de camadas tracionadas.");
        return false;
    }

    nBarrasT = Number(document.formCC.barsTCC.value);
    if (document.formCC.barsTCC.value === "" || isNaN(bw)) {
        alert("Por favor preencha o campo Nº de barras com números.");
        console.log("Por favor preencha o Nº de barras.");
        return false;
    }

    ncamC = Number(document.formCC.layerCCC.value);
    if (document.formCC.layerCCC.value === "" || isNaN(bw)) {
        alert("Por favor preencha o campo Nº de camadas comprimidas com números.");
        console.log("Por favor preencha o Nº de camadas comprimidas.");
        return false;
    }

    nBarrasC = Number(document.formCC.barsCCC.value);
    if (document.formCC.barsCCC.value === "" || isNaN(bw)) {
        alert("Por favor preencha o campo Nº de barras com números.");
        console.log("Por favor preencha o Nº de barras.");
        return false;
    }

    mk = Number(document.formCC.mCC.value);
    if (document.formCC.mCC.value === "" || isNaN(mk)) {
        alert("Por favor preencha o campo Momento com números.");
        console.log("Por favor preencha o campo Momento.");
        return false;
    }

    concrete = concreteProp[(document.formCC.concreteCC.value)].concType;
    steel = steelProp[(document.formCC.steelCC.value)].steelType;
    diamLongForm = bitola[Number(document.formCC.longCC.value)].diametro;
    diamEstForm = bitola[Number(document.formCC.estCC.value)].diametro;
    gamac = Number(document.formCC.gamacCC.value);
    gamaf = Number(document.formCC.gamafCC.value);
    gamas = Number(document.formCC.gamasCC.value);
    s = Number(document.formCC.sCC.value);
    cob = Number(document.formCC.cobCC.value);
    dl = Number(document.formCC.dlCC.value);
    dlc = Number(document.formCC.dlcCC.value);

    // Getting bitolaLong properties
    i = Number(document.getElementById("bitolaLongT").value);
    w = Number(document.getElementById("bitolaLongC").value);

        // Getting concrete properties
    j = Number(document.getElementById("concrete").value);

    fckForm = concreteProp[j].fckProp;

    // Getting steel properties
    k = Number(document.getElementById("steel").value);

    fykForm = steelProp[k].fy;
    Es = steelProp[k].E;

    // Converting Units
    fyk = fykForm / 10;
    fck = fckForm / 100;
    diamEst = diamEstForm / 10;
    diamLong = diamLongForm / 10;

    // Calculating parameters
    fcd = fck / gamac;
    fyd = fyk / gamas;
    tsd = fyd;
    epc = 3.5;
    eps = 10.0;

    //CÁLCULO DO MOMENTO FLETOR MAJORADO
    md = mk * gamaf;

    //CÁLCULO DA ALTURA ÚTIL (d)
    d = h - dl;

    //CÁLCULO DOS LIMITES DOS DOMÍNIOS 2 E 3
    //DOMÍNIO 2
    betax23 = epc / (epc + eps);

    //DOMÍNIO 3
    epyd = (fyd / Es) * 1000;
    betax34 = epc / (epc + epyd);

    //CÁLCULO DA POSIÇÃO DA LINHA NEUTRA (x)
    //md = 0.68*bw*x*fcd*(d-0.4*x);
    //(0.4*x^2)+(d*x)+(md/(0.68*bw*fcd))=0

    a = 0.4;
    b = -1 * d;
    c = md / (0.68 * bw * fcd);
    delta = Math.pow(b, 2) - ((4 * a) * c);

    if (delta > 0) {
	    deltaR = Math.sqrt(delta);
	    x1 = ((-b +  deltaR)  / (2 * a));
	    x2 = ((-b -  deltaR)  / (2 * a));
    } else {
        x1 = ("Sem raiz");
		x2 = ("Sem raiz");
    }

    if (x1 > h) {
        x = x2;
    } else {
        x = x1;
    }

    //VERIFICAÇÃO DO DOMÍNIO DA VIGA

    x2lim = betax23 * d;
    x3lim = betax34 * d;

    if (x > x2lim && x < x3lim) {
        dominio = "Domínio 3";
        situationD = "Aprovado";
    } else if (x < x2lim) {
        dominio = "Domínio 2";
        situationD = "Aprovado";
    } else if (x > x3lim) {
        dominio = "Domínio 4";
        situationD = "Reprovado";
    } else {
        dominio = "Error";
    }

    //VERIFICAÇÃO DA RELAÇÃO x/d

    if (x / d <= 0.45) {
        situationLN = "Aprovada";
    } else {
        situationLN = "Reprovada";
    }

    //CÁLCULO DA ÁREA DE AÇO

    if (situationD === "Aprovado" && situationLN === "Aprovada") {
        situationS = "Simples";
	    as = md / (tsd * (d - 0.4 * x));
        alert(as);

    } else {
        situationS = "Dupla";

        //Cálculo da nova posição da LN
        xd = 0.45 * d;

        //Cálculo de M1d
        m1d = 0.68 * bw * xd * fcd * (d - 0.4 * xd);

        //Cálculo de M2d
        m2d = md - m1d;

        //Encontrar valor de tlsd na tabela (!!!!)
        tlsd = 43.5;

        //Encontrar área de aço comprimida A's
        asl = m2d / (tlsd * (d - dlc));

        //Encontrar área de aço tracionada As
        as1 = m1d / (tsd * (d - 0.4 * xd));
        as2 = m2d / (tsd * (d - dlc));
        ast = as1 + as2;

        //Calcular Área de Aço Utilizada na Viga em Verificação
        astcalc = nBarrasT * ncamT * bitola[i].area;
        asccalc = nBarrasC * ncamC * bitola[w].area;
        if (astcalc >= ast && asccalc >= asl) {
            result = "A viga resiste ao momento cortante solicitado";
            alert(result);
        } else {result = "A viga não resiste ao momento cortante solicitado";
                alert(result);
               }

        //result = "Área de aço comprimida = " + asl + "cm². Área de aço tracionada = " + ast + "cm².";
        //alert(result);

        //Arranjos
        if (situationS === "Simples") {
            for (i = 0; i < arranjos.length; i += 1) { //Log of approved
                console.log(arranjos[i]);
                nBarras = as / (bitola[i].area);
            }
        } else {
            for (i = 0; i < arranjos.length; i += 1) { //Log of approved
                console.log(arranjos[i]);
                nBarrasC = asl / (bitola[i].area);
                nBarrasT = ast / (bitola[i].area);
            }
        }

        arranjos.push({    // saves to a list of approved sections
            "bitola": bitola[i],
            "area": bitola[i].area,
            "nº de barras": nBarras

        });

    }

}

  /*
    document.getElementById("botaoRelatorio").href = "reportCS.html?test=" + JSON.stringify(resultado);
} */

/*
    Cria um objeto bitola
*/
function criarBitola(nomeBitola, linhaBitola) {
    "use strict";
    var opcao = document.createElement("OPTION"),
        texto = document.createTextNode(nomeBitola);
    opcao.value = linhaBitola;
    opcao.appendChild(texto);
    return opcao;
}

var bitolaLista1 = document.getElementById("bitolaLongT"),
    bitolaLista2 = document.getElementById("bitolaEst"),
    acoLista = document.getElementById("steel"),
    concretoLista = document.getElementById("concrete"),
    i;

for (i = 0; i < bitola.length; i += 1) {
    bitolaLista1.appendChild(criarBitola(bitola[i].diametro, i));
}

for (i = 0; i < bitola.length; i += 1) {
    bitolaLista2.appendChild(criarBitola(bitola[i].diametro, i));
}

var bitolaLista3 = document.getElementById("bitolaLongC"),
    acoLista = document.getElementById("steel"),
    concretoLista = document.getElementById("concrete"),
    w;

for (w = 0; w < bitola.length; w += 1) {
    bitolaLista3.appendChild(criarBitola(bitola[w].diametro, w));
}

function criarAco(nomeAco, linhaAco) {
    "use strict";
    var opcao = document.createElement("OPTION"),
        texto = document.createTextNode(nomeAco);
    opcao.value = linhaAco;
    opcao.appendChild(texto);
    return opcao;
}

for (i = 0; i < steelProp.length; i += 1) {
    acoLista.appendChild(criarAco(steelProp[i].steelType, i));
}

function criarConcreto(nomeConcreto, linhaConcreto) {
    "use strict";
    var opcao = document.createElement("OPTION"),
        texto = document.createTextNode(nomeConcreto);
    opcao.value = linhaConcreto;
    opcao.appendChild(texto);
    return opcao;
}

for (i = 0; i < concreteProp.length; i += 1) {
    concretoLista.appendChild(criarConcreto(concreteProp[i].concType, i));
}
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import gql from 'graphql-tag';
import { Mutation } from 'react-apollo';
import { questionsConnectionQuery } from './ListConnector';

export const newQuestionMutation = gql`
  mutation newQuestionMutation($input: QuestionCreateInput!) {
    createQuestion(input: $input) {
      question {
        id
        type
        wording
        imageUrl
        choices {
          id
          text
        }
      }
    }
  }
`;

// Atualiza o cache do Apollo com a nova questão
const updateApolloStore = (proxy, { data: { createQuestion } }) => {
  try {
    const data = proxy.readQuery({ query: questionsConnectionQuery });
    const questionEdge = {
      cursor: createQuestion.question.id,
      node: createQuestion.question,
    };
    data.questionsConnection.unshift(questionEdge);

    proxy.writeQuery({ query: questionsConnectionQuery, data });
  } catch (error) {
    // Do nothing. Questions were not fetched yet.
  }
};

const CreateConnector = ({ children }) => (
  <Mutation mutation={newQuestionMutation} update={updateApolloStore}>
    {createQuestion => children({ createQuestion })}
  </Mutation>
);

CreateConnector.propTypes = {
  children: PropTypes.func.isRequired,
};

export default CreateConnector;
<commit_msg>Refetch questionsConnectionQuery in CreateConnector<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import gql from 'graphql-tag';
import { Mutation } from 'react-apollo';
import { questionsConnectionQuery } from './ListConnector';

export const newQuestionMutation = gql`
  mutation newQuestionMutation($input: QuestionCreateInput!) {
    createQuestion(input: $input) {
      question {
        id
        type
        wording
        imageUrl
        choices {
          id
          text
        }
      }
    }
  }
`;

const CreateConnector = ({ children }) => (
  <Mutation mutation={newQuestionMutation} refetchQueries={[{ query: questionsConnectionQuery }]}>
    {createQuestion => children({ createQuestion })}
  </Mutation>
);

CreateConnector.propTypes = {
  children: PropTypes.func.isRequired,
};

export default CreateConnector;
<|endoftext|>


<commit_before>define('app/views/machine_manage_keys', [
    'app/models/machine',
    'text!app/templates/machine_manage_keys.html',
    'ember'],
    /**
     *
     * Machine Manage Keys
     *
     * @returns Class
     */
    function(Machine, machine_manage_keys_html) {

        return Ember.View.extend({

            selectedKey: null,

            template: Ember.Handlebars.compile(machine_manage_keys_html),

            init: function() {
                this._super();
            },

            didInsertElement: function() {
                var machine = this.get('controller').get('model'), that=this;
                for (var i=0; i < machine.keys.content.length; i++){
                    machine.keys.content[i].machines.forEach(function(item){
                        machine.keys.content[i].set('probed', null);
                        if (item[1] == machine.id && item[0] == machine.backend.id && item[2] > 0) {
                            machine.keys.content[i].set('probed', true);
                            warn('set probed for key ' + machine.keys.content[i].name);
                        } else if (item[1] == machine.id && item[0] == machine.backend.id && item[2] < 0){
                            machine.keys.content[i].set('probed', false);
                        }
                    });
                }
            },

            associatedKeyClicked: function(key) {
                this.selectedKey = key;
                if (key.priv) {
                    $('#key-action-upload').parent().css('display', 'none');
                    $('#key-action-probe').parent().css('display', 'block');
                } else {
                    $('#key-action-upload').parent().css('display', 'block');
                    $('#key-action-probe').parent().css('display', 'none');
                }
                $('#non-associated-keys').listview('refresh');
                $('#key-actions').popup('option', 'positionTo', '#associated-keys').popup('open');
            },

            associateButtonClicked: function() {
                $('#non-associated-keys').listview('refresh');
                $('#associate-key-dialog').popup('option', 'positionTo', '#associate-key-button').popup('open');
            },

            backClicked: function() {
                $('#manage-keys').panel("close");
            },

            actionRemoveClicked: function() {
                $('#key-actions').popup('close');
                var that = this;
                var machine = that.get('controller').get('model');
                if (machine.keys.content.length == 1 /*&& machine.keys.content[0] == that.selectedKey*/) {
                    Mist.confirmationController.set('title', 'Remove last key?');
                    Mist.confirmationController.set('text', 'WARNING! You are about to remove the last key associated with this machine.\
                                                             You will not be able to login through mist.io. Are you sure you want to do this?');
                    Mist.confirmationController.set('callback', function() {
                        $('#manage-keys .ajax-loader').fadeIn(200);
                        Mist.keysController.disassociateKey(that.selectedKey, machine);
                    });
                    Mist.confirmationController.show();
                } else {
                    $('#manage-keys .ajax-loader').fadeIn(200);
                    Mist.keysController.disassociateKey(that.selectedKey, machine);
                }
            },

            actionUploadClicked: function() {
                if (window.File && window.FileReader && window.FileList) {
                    $("#key-action-upload-key").click();
                } else {
                    alert('The File APIs are not fully supported in this browser.');
                }
            },

            actionProbeClicked: function() {
                $('#key-actions').popup('close');
                this.get('controller').get('model').probe(this.selectedKey.name);
            },

            actionBackClicked: function() {
                $('#key-actions').popup('close');
            },

            uploadInputChanged: function() {
                $('#manage-keys .ajax-loader').fadeIn(200);
                var reader = new FileReader();
                var key = this.selectedKey;
                reader.onloadend = function(evt) {
                    if (evt.target.readyState == FileReader.DONE) {
                        $('#key-actions').popup('close');
                        Mist.keysController.editKey(key.name,
                                                     key.name,
                                                     key.pub,
                                                     evt.target.result);
                    }
               };
               reader.readAsText($('#key-action-upload-key')[0].files[0], 'UTF-8');
            },

            associateKeyClicked: function(key){
                $('#associate-key-dialog').popup('close');
                $('#manage-keys').panel('open');
                $('#manage-keys .ajax-loader').fadeIn(200);
                var machine = this.get('controller').get('model');
                Mist.keysController.associateKey(key.name, machine);
            },

            createKeyClicked: function() {
                $('#associate-key-dialog').popup('close');
                setTimeout(function(){
                        $('#dialog-add-key').popup('open', {transition: 'pop'});
                }, 350);
            },

        });
    }
);
<commit_msg>use for instead of forEach when iterating key associations<commit_after>define('app/views/machine_manage_keys', [
    'app/models/machine',
    'text!app/templates/machine_manage_keys.html',
    'ember'],
    /**
     *
     * Machine Manage Keys
     *
     * @returns Class
     */
    function(Machine, machine_manage_keys_html) {

        return Ember.View.extend({

            selectedKey: null,

            template: Ember.Handlebars.compile(machine_manage_keys_html),

            init: function() {
                this._super();
            },

            didInsertElement: function() {
                var machine = this.get('controller').get('model'), that=this;
                for (var i=0; i < machine.keys.content.length; i++){
                    for (var j=0; j<machine.keys.content[i].machines.length; j++){
                        var item = machine.keys.content[i].machines[j];
                        if (item[1] == machine.id && item[0] == machine.backend.id && item[2] > 0) {
                            machine.keys.content[i].set('probed', true);
                            warn('set probed for key ' + machine.keys.content[i].name);
                        } else if (item[1] == machine.id && item[0] == machine.backend.id && item[2] < 0){
                            machine.keys.content[i].set('probed', false);
                        }
                    }
                }
            },

            associatedKeyClicked: function(key) {
                this.selectedKey = key;
                if (key.priv) {
                    $('#key-action-upload').parent().css('display', 'none');
                    $('#key-action-probe').parent().css('display', 'block');
                } else {
                    $('#key-action-upload').parent().css('display', 'block');
                    $('#key-action-probe').parent().css('display', 'none');
                }
                $('#non-associated-keys').listview('refresh');
                $('#key-actions').popup('option', 'positionTo', '#associated-keys').popup('open');
            },

            associateButtonClicked: function() {
                $('#non-associated-keys').listview('refresh');
                $('#associate-key-dialog').popup('option', 'positionTo', '#associate-key-button').popup('open');
            },

            backClicked: function() {
                $('#manage-keys').panel("close");
            },

            actionRemoveClicked: function() {
                $('#key-actions').popup('close');
                var that = this;
                var machine = that.get('controller').get('model');
                if (machine.keys.content.length == 1 /*&& machine.keys.content[0] == that.selectedKey*/) {
                    Mist.confirmationController.set('title', 'Remove last key?');
                    Mist.confirmationController.set('text', 'WARNING! You are about to remove the last key associated with this machine.\
                                                             You will not be able to login through mist.io. Are you sure you want to do this?');
                    Mist.confirmationController.set('callback', function() {
                        $('#manage-keys .ajax-loader').fadeIn(200);
                        Mist.keysController.disassociateKey(that.selectedKey, machine);
                    });
                    Mist.confirmationController.show();
                } else {
                    $('#manage-keys .ajax-loader').fadeIn(200);
                    Mist.keysController.disassociateKey(that.selectedKey, machine);
                }
            },

            actionUploadClicked: function() {
                if (window.File && window.FileReader && window.FileList) {
                    $("#key-action-upload-key").click();
                } else {
                    alert('The File APIs are not fully supported in this browser.');
                }
            },

            actionProbeClicked: function() {
                $('#key-actions').popup('close');
                this.get('controller').get('model').probe(this.selectedKey.name);
            },

            actionBackClicked: function() {
                $('#key-actions').popup('close');
            },

            uploadInputChanged: function() {
                $('#manage-keys .ajax-loader').fadeIn(200);
                var reader = new FileReader();
                var key = this.selectedKey;
                reader.onloadend = function(evt) {
                    if (evt.target.readyState == FileReader.DONE) {
                        $('#key-actions').popup('close');
                        Mist.keysController.editKey(key.name,
                                                     key.name,
                                                     key.pub,
                                                     evt.target.result);
                    }
               };
               reader.readAsText($('#key-action-upload-key')[0].files[0], 'UTF-8');
            },

            associateKeyClicked: function(key){
                $('#associate-key-dialog').popup('close');
                $('#manage-keys').panel('open');
                $('#manage-keys .ajax-loader').fadeIn(200);
                var machine = this.get('controller').get('model');
                Mist.keysController.associateKey(key.name, machine);
            },

            createKeyClicked: function() {
                $('#associate-key-dialog').popup('close');
                setTimeout(function(){
                        $('#dialog-add-key').popup('open', {transition: 'pop'});
                }, 350);
            },

        });
    }
);
<|endoftext|>


<commit_before><commit_msg>Save post after submit the form<commit_after>Template.add_post.events({
    'submit .add_post_form': function(){
        var title = event.target.title.value;
        var body - event.target.body.value;

        // Insert the post
        Posts.insert({
            title: title,
            body: body
        });

        FlashMessages.sendSucess('Post has been successfully added!');
        Router.go('/admin/posts');

        // Prevent submit
        return false;
    }
});
<|endoftext|>


<commit_before>/* EZ-Emote plugin
 * These are commands that make it easier for people to actually
 * add / remove emotes without having to manaully do so every time
 * By: panpawn (inspired by jd's ez-tc plugin)
 */

var fs = require('fs');
var serialize = require('node-serialize');
var emotes = {};

function loadEmotes() {
	try {
		emotes = serialize.unserialize(fs.readFileSync('config/emotes.json', 'utf8'));
		Object.merge(Core.emoticons, emotes);
	} catch (e) {};
}
setTimeout(function(){loadEmotes();},1000);

function saveEmotes() {
	try {
		fs.writeFileSync('config/emotes.json',serialize.serialize(emotes));
		Object.merge(Core.emoticons, emotes);
	} catch (e) {};
}

exports.commands = {
	emotes: 'ezemote',
	temotes: 'ezemote',
	temote: 'ezemote',
	emote: 'ezemote',
	ec: 'ezemote',
	ezemote: function (target, room, user) {
		if (!target) target = 'help';
		var parts = target.split(',');
		for (var u in parts) parts[u] = parts[u].trim();
		try {
			switch (toId(parts[0])) {
				case 'add':
					if (!this.can('ban')) return this.sendReply("Access denied.")
					if (!(parts[2] || parts[3])) return this.sendReply("Usage: /ezemote add, [emote], [link]");
					var emoteName = parts[1];
					if (Core.emoticons[emoteName]) return this.sendReply("ERROR - the emote: " + emoteName + " already exists.");
					var link = parts.splice(2, parts.length).join(',');
					emotes[emoteName] = Core.emoticons[emoteName] = link;
					saveEmotes();
					this.sendReply("The emote " + emoteName + " has been added.");
					this.logModCommand(user.name + " added the emote " + emoteName);
					Rooms.rooms.staff.add(user.name + " added the emote " + emoteName);
					break;
				case 'rem':
				case 'remove':
				case 'del':
				case 'delete':
					if (!this.can('ban')) return this.sendReply("Access denied.");
					if (!parts[1]) return this.sendReplyBox("/ezemote remove, [emote]");
					var emoteName = parts[1];
					if (!Core.emoticons[emoteName]) return this.sendReplyBox("ERROR - the emote: " + emoteName + " does not exist.");
					delete Core.emoticons[emoteName];
					delete emotes[emoteName];
					saveEmotes();
					this.sendReply("The emote " + emoteName + " was removed.");
					this.logModCommand("The emote " + emoteName + " was removed by " + user.name);
					Rooms.rooms.staff.add("The emote " + emoteName + " was removed by " + user.name);
					break;
				case 'list':
					if (!this.canBroadcast()) return;
					if (this.broadcasting) return this.sendReply("ERROR: This command is too spammy to broadcast.  Use / instead of ! to see it for yourself.");
					var output = "There's a total of " + Object.size(emotes) + " emotes added with this command:
";
					for (var e in emotes) {
						output += e + "
";
					}
					this.sendReplyBox(output);
					break;
				case 'view':
					if (!this.canBroadcast()) return;
					if (!Core.settings.emoteStatus) {
						return this.sendReplyBox("Sorry, chat emotes have been disabled. :(");
					} else {
						var name = Object.keys(Core.emoticons),
						emoticons = [];
						var len = name.length;
						while (len--) {
							emoticons.push((Core.processEmoticons(name[(name.length - 1) - len]) + ' ' + name[(name.length - 1) - len]));
						}
						this.sendReplyBox("List of emoticons (" + Object.size(emotes) + "):

" + emoticons.join(' ').toString());
					}
					break;
				case 'object':
					if (!this.canBroadcast()) return;
					if (this.broadcasting) return this.sendReply("ERROR: This command is too spammy to broadcast.  Use / instead of ! to see it for yourself.");
					this.sendReplyBox("Core.emoticons = " + fs.readFileSync('config/emotes.json','utf8'));
					break;
				case 'status':
					if (!this.can('pban')) return this.sendReply("Access denied.");
					if (!parts[1]) {
						switch (Core.settings.emoteStatus) {
							case true:
								this.sendReply("Chat emotes are currently enabled.");
								break;
							case false:
								this.sendReply("Chat emotes are currently disabled.");
								break;
						}
					} else {
						switch (toId(parts[1])) {
							case 'on':
							case 'enable':
								if (!this.can('pban')) return this.sendReply("Access denied.");
								Core.settings.emoteStatus = true;
								room.add(Tools.escapeHTML(user.name) + ' has enabled chat emotes.');
								this.logModCommand(Tools.escapeHTML(user.name) + ' has enabled chat emotes.');
								break;
							case 'off':
							case 'disable':
								if (!this.can('pban')) return this.sendReply("Access denied.");
								Core.settings.emoteStatus = false;
								room.add(Tools.escapeHTML(user.name) + " has disabled chat emotes.");
								this.logModCommand(Tools.escapeHTML(user.name) + " has disabled chat emotes.");
								break;
							default:
								if (!this.can('pban')) return this.sendReply("Access denied.");
								this.sendReply("Usage: /ezemote status - views the current emote status OR /ezemote status, [off / on] - Turns emotes on / off.  Requires &, ~.");
						}
					}
					break;
				case 'help':
				default:
					if (!this.canBroadcast()) return;
					this.sendReplyBox(
						"EZ-Emote Commands:
" +
						"/ezemote add, [emote], [link] - Adds an emote. Requires @, &, ~.
" +
						"/ezemote remove, [emote] - Removes an emote. Requires @, &, ~.
" +
						"/ezemote status - Views the current status of emotes.  Requires &, ~.
" +
						"/ezemote status, [on / off] - Enables or disables the status of emotes. Requires &, ~.
" +
						"/ezemote list - Shows the emotes that were added with this command.
" +
						"/ezemote view - Shows all of the current emotes with their respected image.
" +
						"/ezemote object - Shows the object of Core.emoticons.
" +
						"/ezemote help - Shows this help command.
"
					);
			}
		} catch (e) {
			console.log("ERROR!  The EZ-Emote script has crashed!");
		}
	}
};
<commit_msg>check if an emote is an image<commit_after>/* EZ-Emote plugin
 * These are commands that make it easier for people to actually
 * add / remove emotes without having to manaully do so every time
 * By: panpawn (inspired by jd's ez-tc plugin)
 */

var fs = require('fs');
var serialize = require('node-serialize');
var emotes = {};

function loadEmotes() {
	try {
		emotes = serialize.unserialize(fs.readFileSync('config/emotes.json', 'utf8'));
		Object.merge(Core.emoticons, emotes);
	} catch (e) {};
}
setTimeout(function(){loadEmotes();},1000);

function saveEmotes() {
	try {
		fs.writeFileSync('config/emotes.json',serialize.serialize(emotes));
		Object.merge(Core.emoticons, emotes);
	} catch (e) {};
}

exports.commands = {
	emotes: 'ezemote',
	temotes: 'ezemote',
	temote: 'ezemote',
	emote: 'ezemote',
	ec: 'ezemote',
	ezemote: function (target, room, user) {
		if (!target) target = 'help';
		var parts = target.split(',');
		for (var u in parts) parts[u] = parts[u].trim();
		try {
			switch (toId(parts[0])) {
				case 'add':
					if (!this.can('ban')) return this.sendReply("Access denied.")
					if (!(parts[2] || parts[3])) return this.sendReply("Usage: /ezemote add, [emote], [link]");
					var emoteName = parts[1];
					if (Core.emoticons[emoteName]) return this.sendReply("ERROR - the emote: " + emoteName + " already exists.");
					var link = parts.splice(2, parts.length).join(',');
					if (link != ".gif" && link != ".png" || link != ".jpg") return this.sendReply("ERROR: the emote you are trying to add must be a gif, png, or jpg.");
					emotes[emoteName] = Core.emoticons[emoteName] = link;
					saveEmotes();
					this.sendReply("The emote " + emoteName + " has been added.");
					this.logModCommand(user.name + " added the emote " + emoteName);
					Rooms.rooms.staff.add(user.name + " added the emote " + emoteName);
					break;
				case 'rem':
				case 'remove':
				case 'del':
				case 'delete':
					if (!this.can('ban')) return this.sendReply("Access denied.");
					if (!parts[1]) return this.sendReplyBox("/ezemote remove, [emote]");
					var emoteName = parts[1];
					if (!Core.emoticons[emoteName]) return this.sendReplyBox("ERROR - the emote: " + emoteName + " does not exist.");
					delete Core.emoticons[emoteName];
					delete emotes[emoteName];
					saveEmotes();
					this.sendReply("The emote " + emoteName + " was removed.");
					this.logModCommand("The emote " + emoteName + " was removed by " + user.name);
					Rooms.rooms.staff.add("The emote " + emoteName + " was removed by " + user.name);
					break;
				case 'list':
					if (!this.canBroadcast()) return;
					if (this.broadcasting) return this.sendReply("ERROR: this command is too spammy to broadcast.  Use / instead of ! to see it for yourself.");
					var output = "There's a total of " + Object.size(emotes) + " emotes added with this command:
";
					for (var e in emotes) {
						output += e + "
";
					}
					this.sendReplyBox(output);
					break;
				case 'view':
					if (!this.canBroadcast()) return;
					if (!Core.settings.emoteStatus) {
						return this.sendReplyBox("Sorry, chat emotes have been disabled. :(");
					} else {
						var name = Object.keys(Core.emoticons),
						emoticons = [];
						var len = name.length;
						while (len--) {
							emoticons.push((Core.processEmoticons(name[(name.length - 1) - len]) + ' ' + name[(name.length - 1) - len]));
						}
						this.sendReplyBox("List of emoticons (" + Object.size(emotes) + "):

" + emoticons.join(' ').toString());
					}
					break;
				case 'object':
					if (!this.canBroadcast()) return;
					if (this.broadcasting) return this.sendReply("ERROR: this command is too spammy to broadcast.  Use / instead of ! to see it for yourself.");
					this.sendReplyBox("Core.emoticons = " + fs.readFileSync('config/emotes.json','utf8'));
					break;
				case 'status':
					if (!this.can('pban')) return this.sendReply("Access denied.");
					if (!parts[1]) {
						switch (Core.settings.emoteStatus) {
							case true:
								this.sendReply("Chat emotes are currently enabled.");
								break;
							case false:
								this.sendReply("Chat emotes are currently disabled.");
								break;
						}
					} else {
						switch (toId(parts[1])) {
							case 'on':
							case 'enable':
								if (!this.can('pban')) return this.sendReply("Access denied.");
								Core.settings.emoteStatus = true;
								room.add(Tools.escapeHTML(user.name) + ' has enabled chat emotes.');
								this.logModCommand(Tools.escapeHTML(user.name) + ' has enabled chat emotes.');
								break;
							case 'off':
							case 'disable':
								if (!this.can('pban')) return this.sendReply("Access denied.");
								Core.settings.emoteStatus = false;
								room.add(Tools.escapeHTML(user.name) + " has disabled chat emotes.");
								this.logModCommand(Tools.escapeHTML(user.name) + " has disabled chat emotes.");
								break;
							default:
								if (!this.can('pban')) return this.sendReply("Access denied.");
								this.sendReply("Usage: /ezemote status - views the current emote status OR /ezemote status, [off / on] - Turns emotes on / off.  Requires &, ~.");
						}
					}
					break;
				case 'help':
				default:
					if (!this.canBroadcast()) return;
					this.sendReplyBox(
						"EZ-Emote Commands:
" +
						"/ezemote add, [emote], [link] - Adds an emote. Requires @, &, ~.
" +
						"/ezemote remove, [emote] - Removes an emote. Requires @, &, ~.
" +
						"/ezemote status - Views the current status of emotes.  Requires &, ~.
" +
						"/ezemote status, [on / off] - Enables or disables the status of emotes. Requires &, ~.
" +
						"/ezemote list - Shows the emotes that were added with this command.
" +
						"/ezemote view - Shows all of the current emotes with their respected image.
" +
						"/ezemote object - Shows the object of Core.emoticons.
" +
						"/ezemote help - Shows this help command.
"
					);
			}
		} catch (e) {
			console.log("ERROR!  The EZ-Emote script has crashed!");
		}
	}
};
<|endoftext|>


<commit_before>/**
 * Gulp test tasks.
 */

'use strict';

var path = require('path'),
  gulp = require('gulp-help')(require('gulp')),
  runSequence = require('run-sequence'),
  conf = require('./conf'),
<% if (browser) { -%>
  Server = require('karma').Server,
<% } -%>
  remapIstanbul = require('remap-istanbul/lib/gulpRemapIstanbul'),
  $ = require('gulp-load-plugins')();

<% if (browser) { -%>
/**
 * Shows the available launchers.
 */
var Launcher = {
  Chrome: 'Chrome',
  PhantomJs: 'PhantomJS'
};

/**
 * Run unit tests with the given options.
 * @param karmaConf Karma file.
 * @param singleRun Flag determine run tests only once.
 * @param launcher Launching browser.
 * @param done Test done callback function.
 */
function runTestsCI (karmaConf,singleRun, launcher, done) {
  Server.start({
    configFile: karmaConf,
    singleRun: singleRun,
    autoWatch: !singleRun,
    browsers: [launcher]
  }, function() {
    done();
  });
}

/**
 * Gulp test task do CI test.
 * Single Run with PhantomJs.
 * @param done - done callback function.
 */
gulp.task('test', function(done) {
  runTestsCI(conf.paths.karmaConf, true, Launcher.PhantomJs, done);
});

/**
 * Gulp development build test task.
 * Single Run with Chrome.
 * @param done - done callback function.
 */
gulp.task('dev-test', function(done) {
  runTestsCI(conf.paths.karmaConf, false, Launcher.Chrome, done);
});

/**
 * Gulp coverage build task.
 * clean tmp -> tmp scripts
 */
gulp.task('coverage-build', function(done){
  runSequence('clean-source-tmp','tmp-scripts',done);
});

/**
 * Gulp coverage test with karma coverage configuration.
 * Single Run with PhantomJs.
 * @param done - done callback function.
 */
gulp.task('coverage-test',['coverage-build'], function(done) {
  runTestsCI(conf.paths.karmaCoverageConf, true, Launcher.PhantomJs, done);
});

/**
 * Gulp coverage task.
 * Cleans temporary created files in sources -> cleans coverage folder -> run coverage test with PhantomJs -> remap istanbul support -> clean temporary generated files.
 * @param done - done callback function.
 */
gulp.task('coverage', 'Run tests and generate coverage', function(done) {
  runSequence('clean-source-tmp','clean-coverage','coverage-test','remap-istanbul','clean-source-tmp',done);
});
<% } else { -%>

/**
 * Gulp pre coverage test with mocha and istanbul configuration.
 */
gulp.task('pre-test', ['coverage-build'], function() {
  return gulp.src(path.join(conf.paths.src, '/**/*.js'))
    .pipe($.istanbul({
      includeUntested: true
    }))
    .pipe($.istanbul.hookRequire());
});

var runTest = function(reporters, done) {
  var mochaError;

  gulp.src(path.join(conf.paths.test, '/**/*.js'))
    .pipe($.plumber())
    .pipe($.mocha({
      reporter: 'spec'
    }))
    .on('error', function (error) {
      mochaError = error;
    })
    .pipe($.istanbul.writeReports({
      dir: conf.paths.coverage,
      reporters: reporters,
      reportOpts: {
        dir: conf.paths.coverage
      }
    }))
    .on('end', function () {
      done(mochaError);
    });
};

/**
 * Gulp coverage test with mocha and istanbul configuration.
 * @param done - done callback function.
 */
gulp.task('coverage-test', ['pre-test'], function(done) {
  runTest(['json', 'text', 'text-summary'], done);
});

/**
 * Gulp summary test with mocha and istanbul configuration.
 * @param done - done callback function.
 */
gulp.task('summary-test', ['pre-test'], function(done) {
  runTest(['text', 'text-summary'], done);
});

/**
 * Gulp coverage task.
 * Cleans temporary created files in sources -> cleans coverage folder -> run coverage test -> remap istanbul support -> clean temporary generated files.
 * @param done - done callback function.
 */
gulp.task('coverage', 'Run tests and generate coverage', function(done) {
  runSequence('clean-source-tmp', 'clean-coverage', 'coverage-test', 'remap-istanbul', 'clean-source-tmp', done);
});

/**
 * Gulp test task.
 * Cleans temporary created files in sources -> run summary test -> clean temporary generated files.
 * @param done - done callback function.
 */
gulp.task('test', 'Run tests and generate coverage', function(done) {
  runSequence('clean-source-tmp', 'summary-test', 'clean-source-tmp', done);
});
<% } -%>

/**
 * Gulp remap istanbul task.
 * RemapIstanbul will access the coverage-final.json and generate reports.
 * Report errors.
 */
gulp.task('remap-istanbul', function () {
  return gulp.src(path.join(conf.paths.coverage, 'coverage-final.json'))
    .pipe(remapIstanbul({
      reports: {
        'html': path.join(conf.paths.coverage, conf.paths.reportDir),
        fail: true
      }
    }))
    .on('error', conf.errorHandler(conf.errors.title.TYPESCRIPT));

});
<commit_msg>Add coverage build task to common area<commit_after>/**
 * Gulp test tasks.
 */

'use strict';

var path = require('path'),
  gulp = require('gulp-help')(require('gulp')),
  runSequence = require('run-sequence'),
  conf = require('./conf'),
<% if (browser) { -%>
  Server = require('karma').Server,
<% } -%>
  remapIstanbul = require('remap-istanbul/lib/gulpRemapIstanbul'),
  $ = require('gulp-load-plugins')();

<% if (browser) { -%>
/**
 * Shows the available launchers.
 */
var Launcher = {
  Chrome: 'Chrome',
  PhantomJs: 'PhantomJS'
};

/**
 * Run unit tests with the given options.
 * @param karmaConf Karma file.
 * @param singleRun Flag determine run tests only once.
 * @param launcher Launching browser.
 * @param done Test done callback function.
 */
function runTestsCI (karmaConf,singleRun, launcher, done) {
  Server.start({
    configFile: karmaConf,
    singleRun: singleRun,
    autoWatch: !singleRun,
    browsers: [launcher]
  }, function() {
    done();
  });
}

/**
 * Gulp test task do CI test.
 * Single Run with PhantomJs.
 * @param done - done callback function.
 */
gulp.task('test', function(done) {
  runTestsCI(conf.paths.karmaConf, true, Launcher.PhantomJs, done);
});

/**
 * Gulp development build test task.
 * Single Run with Chrome.
 * @param done - done callback function.
 */
gulp.task('dev-test', function(done) {
  runTestsCI(conf.paths.karmaConf, false, Launcher.Chrome, done);
});

/**
 * Gulp coverage test with karma coverage configuration.
 * Single Run with PhantomJs.
 * @param done - done callback function.
 */
gulp.task('coverage-test',['coverage-build'], function(done) {
  runTestsCI(conf.paths.karmaCoverageConf, true, Launcher.PhantomJs, done);
});

/**
 * Gulp coverage task.
 * Cleans temporary created files in sources -> cleans coverage folder -> run coverage test with PhantomJs -> remap istanbul support -> clean temporary generated files.
 * @param done - done callback function.
 */
gulp.task('coverage', 'Run tests and generate coverage', function(done) {
  runSequence('clean-source-tmp','clean-coverage','coverage-test','remap-istanbul','clean-source-tmp',done);
});
<% } else { -%>

/**
 * Gulp pre coverage test with mocha and istanbul configuration.
 */
gulp.task('pre-test', ['coverage-build'], function() {
  return gulp.src(path.join(conf.paths.src, '/**/*.js'))
    .pipe($.istanbul({
      includeUntested: true
    }))
    .pipe($.istanbul.hookRequire());
});

var runTest = function(reporters, done) {
  var mochaError;

  gulp.src(path.join(conf.paths.test, '/**/*.js'))
    .pipe($.plumber())
    .pipe($.mocha({
      reporter: 'spec'
    }))
    .on('error', function (error) {
      mochaError = error;
    })
    .pipe($.istanbul.writeReports({
      dir: conf.paths.coverage,
      reporters: reporters,
      reportOpts: {
        dir: conf.paths.coverage
      }
    }))
    .on('end', function () {
      done(mochaError);
    });
};

/**
 * Gulp coverage test with mocha and istanbul configuration.
 * @param done - done callback function.
 */
gulp.task('coverage-test', ['pre-test'], function(done) {
  runTest(['json', 'text', 'text-summary'], done);
});

/**
 * Gulp summary test with mocha and istanbul configuration.
 * @param done - done callback function.
 */
gulp.task('summary-test', ['pre-test'], function(done) {
  runTest(['text', 'text-summary'], done);
});

/**
 * Gulp coverage task.
 * Cleans temporary created files in sources -> cleans coverage folder -> run coverage test -> remap istanbul support -> clean temporary generated files.
 * @param done - done callback function.
 */
gulp.task('coverage', 'Run tests and generate coverage', function(done) {
  runSequence('clean-source-tmp', 'clean-coverage', 'coverage-test', 'remap-istanbul', 'clean-source-tmp', done);
});

/**
 * Gulp test task.
 * Cleans temporary created files in sources -> run summary test -> clean temporary generated files.
 * @param done - done callback function.
 */
gulp.task('test', 'Run tests and generate coverage', function(done) {
  runSequence('clean-source-tmp', 'summary-test', 'clean-source-tmp', done);
});
<% } -%>

/**
 * Gulp coverage build task.
 * clean tmp -> tmp scripts
 */
gulp.task('coverage-build', function(done){
  runSequence('clean-source-tmp','tmp-scripts', done);
});

/**
 * Gulp remap istanbul task.
 * RemapIstanbul will access the coverage-final.json and generate reports.
 * Report errors.
 */
gulp.task('remap-istanbul', function () {
  return gulp.src(path.join(conf.paths.coverage, 'coverage-final.json'))
    .pipe(remapIstanbul({
      reports: {
        'html': path.join(conf.paths.coverage, conf.paths.reportDir),
        fail: true
      }
    }))
    .on('error', conf.errorHandler(conf.errors.title.TYPESCRIPT));

});
<|endoftext|>


<commit_before>function youtubeReplaceAllString(inputString, stringToFind, replaceWithString)
{
  var thisRegExp = new RegExp(stringToFind, 'g');
  return inputString.replace(thisRegExp, replaceWithString);
}

function youtubeAddBlock(videoList)
{
   var title      = 'saved video';
   var videoTitle = document.getElementById('watch-headline-title');
   if(videoTitle != null){
      title = videoTitle.children[0].innerText;
   }

   var html = '
';
   html = html + '
Click on the format to download the video:
';
   html = html + '
';
   var counter = 0;

   for(i in videoList){
      var video = videoList[i];
      if(video.url != '' && video.url.indexOf('http') == 0)
      {
         if(counter != 0) html = html + ' | ';
         if(typeof video.formatObject == 'undefined')
         {
            html = html + 'Unknown Format';
         }
         else{
            html = html + '' + video.formatObject.resolution + 'p ' + video.formatObject.format + '';
         }
         counter++;
      }
   }
   html = html + '
';
   html = html + '
';

   var wpDiv = document.getElementById('watch7-content');
   if(wpDiv != null){
      wpDiv.innerHTML = html + wpDiv.innerHTML;
   }
}

function youtubeGetVideoList()
{
  try{
    var videoFormats = {
        5:  {   itag: 5,    resolution: 224,    format: "FLV"},
        6:  {   itag: 6,    resolution: 270,    format: "FLV"},
        13: {   itag: 13,   resolution: 144,    format: "3GP"},
        17: {   itag: 17,   resolution: 144,    format: "3GP"},
        18: {   itag: 18,   resolution: 360,    format: "MP4"},
        22: {   itag: 22,   resolution: 720,    format: "MP4"},
        34: {   itag: 34,   resolution: 360,    format: "FLV"},
        35: {   itag: 35,   resolution: 480,    format: "FLV"},
        36: {   itag: 36,   resolution: 240,    format: "3GP"},
        37: {   itag: 37,   resolution: 1080,   format: "MP4"},
        38: {   itag: 38,   resolution: 2304,   format: "MP4"},
        43: {   itag: 43,   resolution: 360,    format: "WebM"},
        44: {   itag: 44,   resolution: 480,    format: "WebM"},
        45: {   itag: 45,   resolution: 720,    format: "WebM"},
        46: {   itag: 46,   resolution: 1080,   format: "WebM"},
        82: {   itag: 82,   resolution: 360,    format: "MP4"},
        83: {   itag: 83,   resolution: 240,    format: "MP4"},
        84: {   itag: 84,   resolution: 720,    format: "MP4"},
        85: {   itag: 85,   resolution: 520,    format: "MP4"},
        100:{   itag: 100,  resolution: 360,    format: "WebM"},
        101:{   itag: 101,  resolution: 480,    format: "WebM"},
        102:{   itag: 102,  resolution: 720,    format: "WebM"}
    };

    var videoList     = new Array();
    var encodedStream = ytplayer.config.args.url_encoded_fmt_stream_map;
    var streamInfo    = encodedStream.split(',');

    for(i in streamInfo)
    {
      streamData = streamInfo[i].split('&');
      var youtubeURL  = '';
      var youtubeSIG  = '';
      var youtubeITAG = 0;

      for(y in streamData)
      {
        if(streamData[y].indexOf('itag=') == 0)
        {
           itagData    = streamData[y].split('=');
           youtubeITAG = itagData[1];
        }
        if(streamData[y].indexOf('url=') == 0)
        {
           urlData    = streamData[y].split('=');
           youtubeURL = unescape(urlData[1]);
        }
        if(streamData[y].indexOf('s=') == 0)
        {
           sigData = streamData[y].split('=');
           youtubeSIG = unescape(sigData[1]);
        }
      }

      if(youtubeURL != '' && youtubeITAG != 0)
      {
        if(youtubeURL.indexOf('signature') > 0)
        {
           var video = {formatObject: videoFormats[youtubeITAG], url: youtubeURL};
           videoList.push(video);
        }
        else
        {
           var video = {formatObject: videoFormats[youtubeITAG], url: youtubeURL+'&signature='+youtubeRetrieveSignature(youtubeSIG)};
           videoList.push(video);
        }
      }
    }
    return videoList;
  }
  catch(e){
    var videoList = new Array();
    console.log(e);
    return videoList;
  }
}

function youtubeRetrieveSignature(signature)
{
   a = signature.split("");
   decipherSignature.kR(a, 3);
   decipherSignature.sI(a, 44);
   decipherSignature.kR(a, 1);
   decipherSignature.nV(a, 55);
   decipherSignature.kR(a, 1);
   decipherSignature.nV(a, 34);
   decipherSignature.kR(a, 3);
   decipherSignature.nV(a, 17);
   decipherSignature.kR(a, 3);
   return a.join("")
}

var decipherSignature = {
   sI: function(a, b) {
      var c = a[0];
      a[0] = a[b % a.length];
      a[b] = c
   },
   kR: function(a, b) {
      a.splice(0, b)
   },
   nV: function(a) {
      a.reverse()
   }
};

function youtubeListener(){
    var ext = document.getElementById('download-youtube-chrome-extension');
    if(typeof ytplayer != 'undefined' &&
        typeof ytplayer.config != 'undefined' &&
        ytplayer.config != null &&
        typeof ytplayer.config.args != 'undefined' &&
        typeof ytplayer.config.args.url_encoded_fmt_stream_map != 'undefined' &&
        ext == null){
        youtubeAddBlock(youtubeGetVideoList());
    }
}

if(window.history && history.pushState){
    setInterval("youtubeListener()", 300);
}else{
    youtubeAddBlock(youtubeGetVideoList());
}<commit_msg>Added comment to youtube video downlader javascript file<commit_after>/**
 * Filename: videodownloader.js
 * Purpose : This will parse the decode the video data and will allow users to download
 * Project : Cefal School
 * Author  : beroza@cefalo.com
 * Version : 1.0
 * Copyright (c) 2015 Cefal School
 */

/**
 * Purpose : Replace all instances of input string.
 * @access : public
 * @params : inputString, stringToFind, replaceWithString
 * @return : string;
 */
function youtubeReplaceAllString(inputString, stringToFind, replaceWithString)
{
  var thisRegExp = new RegExp(stringToFind, 'g');
  return inputString.replace(thisRegExp, replaceWithString);
}

/**
 * Purpose : Loop through each video and create the downloadable link (add a block after video).
 * @access : public
 * @params : videoList
 */
function youtubeAddBlock(videoList)
{
   var title      = 'saved video';
   var videoTitle = document.getElementById('watch-headline-title');
   if(videoTitle != null){
      title = videoTitle.children[0].innerText;
   }

   var html = '
';
   html = html + '
Click on the format to download the video:
';
   html = html + '
';
   var counter = 0;

   for(i in videoList){
      var video = videoList[i];
      if(video.url != '' && video.url.indexOf('http') == 0)
      {
         if(counter != 0) html = html + ' | ';
         if(typeof video.formatObject == 'undefined')
         {
            html = html + 'Unknown Format';
         }
         else{
            html = html + '' + video.formatObject.resolution + 'p ' + video.formatObject.format + '';
         }
         counter++;
      }
   }
   html = html + '
';
   html = html + '
';

   var wpDiv = document.getElementById('watch7-content');
   if(wpDiv != null){
      wpDiv.innerHTML = html + wpDiv.innerHTML;
   }
}

/**
 * Purpose : Fetch encoded youtube video data and prepare array of video object.
 * @access : public
 * @params : undefined
 * @return : array of video objects;
 */
function youtubeGetVideoList()
{
  try{
    var videoFormats = {
        5:  {   itag: 5,    resolution: 224,    format: "FLV"},
        6:  {   itag: 6,    resolution: 270,    format: "FLV"},
        13: {   itag: 13,   resolution: 144,    format: "3GP"},
        17: {   itag: 17,   resolution: 144,    format: "3GP"},
        18: {   itag: 18,   resolution: 360,    format: "MP4"},
        22: {   itag: 22,   resolution: 720,    format: "MP4"},
        34: {   itag: 34,   resolution: 360,    format: "FLV"},
        35: {   itag: 35,   resolution: 480,    format: "FLV"},
        36: {   itag: 36,   resolution: 240,    format: "3GP"},
        37: {   itag: 37,   resolution: 1080,   format: "MP4"},
        38: {   itag: 38,   resolution: 2304,   format: "MP4"},
        43: {   itag: 43,   resolution: 360,    format: "WebM"},
        44: {   itag: 44,   resolution: 480,    format: "WebM"},
        45: {   itag: 45,   resolution: 720,    format: "WebM"},
        46: {   itag: 46,   resolution: 1080,   format: "WebM"},
        82: {   itag: 82,   resolution: 360,    format: "MP4"},
        83: {   itag: 83,   resolution: 240,    format: "MP4"},
        84: {   itag: 84,   resolution: 720,    format: "MP4"},
        85: {   itag: 85,   resolution: 520,    format: "MP4"},
        100:{   itag: 100,  resolution: 360,    format: "WebM"},
        101:{   itag: 101,  resolution: 480,    format: "WebM"},
        102:{   itag: 102,  resolution: 720,    format: "WebM"}
    };

    var videoList     = new Array();
    var encodedStream = ytplayer.config.args.url_encoded_fmt_stream_map;
    var streamInfo    = encodedStream.split(',');

    for(i in streamInfo)
    {
      streamData = streamInfo[i].split('&');
      var youtubeURL  = '';
      var youtubeSIG  = '';
      var youtubeITAG = 0;

      for(y in streamData)
      {
        if(streamData[y].indexOf('itag=') == 0)
        {
           itagData    = streamData[y].split('=');
           youtubeITAG = itagData[1];
        }
        if(streamData[y].indexOf('url=') == 0)
        {
           urlData    = streamData[y].split('=');
           youtubeURL = unescape(urlData[1]);
        }
        if(streamData[y].indexOf('s=') == 0)
        {
           sigData = streamData[y].split('=');
           youtubeSIG = unescape(sigData[1]);
        }
      }

      if(youtubeURL != '' && youtubeITAG != 0)
      {
        if(youtubeURL.indexOf('signature') > 0)
        {
           var video = {formatObject: videoFormats[youtubeITAG], url: youtubeURL};
           videoList.push(video);
        }
        else
        {
           var video = {formatObject: videoFormats[youtubeITAG], url: youtubeURL+'&signature='+youtubeRetrieveSignature(youtubeSIG)};
           videoList.push(video);
        }
      }
    }
    return videoList;
  }
  catch(e){
    var videoList = new Array();
    console.log(e);
    return videoList;
  }
}

/**
 * Purpose : Retrieve youtube video signature.
 * @access : public
 * @params : signature
 * @return : decrypted signature;
 */
function youtubeRetrieveSignature(signature)
{
   a = signature.split("");
   decipherSignature.kR(a, 3);
   decipherSignature.sI(a, 44);
   decipherSignature.kR(a, 1);
   decipherSignature.nV(a, 55);
   decipherSignature.kR(a, 1);
   decipherSignature.nV(a, 34);
   decipherSignature.kR(a, 3);
   decipherSignature.nV(a, 17);
   decipherSignature.kR(a, 3);
   return a.join("")
}

var decipherSignature = {
   sI: function(a, b) {
      var c = a[0];
      a[0] = a[b % a.length];
      a[b] = c
   },
   kR: function(a, b) {
      a.splice(0, b)
   },
   nV: function(a) {
      a.reverse()
   }
};

/**
 * Purpose : Protect multiple loading.
 * @access : public
 * @params : undefined
 */
function youtubeListener(){
    var ext = document.getElementById('download-youtube-chrome-extension');
    if(typeof ytplayer != 'undefined' && typeof ytplayer.config != 'undefined' && ytplayer.config != null && typeof ytplayer.config.args != 'undefined' &&
        typeof ytplayer.config.args.url_encoded_fmt_stream_map != 'undefined' && ext == null){
        youtubeAddBlock(youtubeGetVideoList());
    }
}

if(window.history && history.pushState)
{
   setInterval("youtubeListener()", 300);
}
else
{
   youtubeAddBlock(youtubeGetVideoList());
}<|endoftext|>


<commit_before>import { dependencies as Inject, singleton as Singleton } from "needlepoint";
import Db from "mongodb";
import ScheduledTask from "../ScheduledTask";
import Configuration from "../../core/config/Configuration";
import ChatApi from "../../core/api/ChatApi";
import Threads from "../../core/config/Threads";
import Promise from "bluebird";
import until from "async/until";

@Singleton
@Inject(Configuration, Db, ChatApi, Threads)
export default class ThreadHistoryDownloader extends ScheduledTask {
    /**
     * @param {Configuration} config
     * @param {Db} db
     * @param {ChatApi} api
     * @param {Threads} threads
     */
    constructor(config, db, api, threads) {
        super();

        this.config = config;
        this.db = db;
        this.api = api;
        this.threads = threads;
    }

    execute() {
        const threadIds = this.threads.getThreadIds();

        const promises = threadIds.map(id => this.downloadMessagesByThreadId(id));

        return Promise.all(promises);
    }

    downloadMessagesByThreadId(threadId) {
        const dbCollection = this.db.collection(`thread-${threadId}`);

        return Promise
            .all([
                ThreadHistoryDownloader.createUniqueIndexIfNotExists(dbCollection),
                dbCollection.count(),
                this.api.getThreadInfo(threadId).then(info => info.messageCount)
            ])
            .then(([_, dbCount, fbCount]) => ThreadHistoryDownloader.handleMessageCount(dbCount, fbCount, threadId))
            .then(messageCount => this.batchDownloadMessages(messageCount, threadId))
            .then(messages => dbCollection.insertMany(messages, {
                ordered: false // throw everything at the db and see what persists, i.e. don't stop on duplicate keys
            }))
            .catch(ThreadHistoryDownloadCancelledError, err => console.warn(err.message))
            .catch(err => ThreadHistoryDownloader.handleDuplicateKeysError(err, threadId));
    }

    batchDownloadMessages(messageCount, threadId) {
        const msgsPerRequest = Math.min(messageCount, 500);

        let i = 0;
        let lastTimestamp = +Date.now();
        let downloadedMessages = [];

        return new Promise((resolve, reject) => {
            until(
                () => (i * msgsPerRequest) >= messageCount,
                done => {
                    this.api.getThreadHistory(threadId, 0, msgsPerRequest, lastTimestamp).then(messages => {
                        downloadedMessages = messages.concat(downloadedMessages);
                        lastTimestamp = parseInt(messages[0].timestamp) - 1;
                        i++;

                        console.log(`Thread ${threadId}: Downloaded total ${downloadedMessages.length}/${messageCount} messages (got ${messages.length})`);

                        done();
                    }).catch(err => done(err));
                },
                err => {
                    if (err) return reject(err);

                    return resolve(downloadedMessages);
                });
        });
    }

    static handleMessageCount(dbCount, fbCount, threadId) {
        console.log(`Thread ${threadId}: There are ${dbCount} messages in cache, and ${fbCount} reported by Facebook`);

        if (dbCount == fbCount) {
            return Promise.reject(new ThreadHistoryDownloadCancelledError(
                `Thread ${threadId}: Message cache is up-to-date`
            ));
        }

        if (dbCount > fbCount) {
            console.warn(`There are more messages in the cache (${dbCount}) than Facebook reports (${fbCount}). ` +
                `Will download the whole chat history.`);
            return Promise.resolve(fbCount);
        }

        const diff = fbCount - dbCount;
        console.log(`Thread ${threadId}: Message cache is ${diff} messages behind`);

        return Promise.resolve(diff);
    }

    static createUniqueIndexIfNotExists(dbCollection) {
        const msgIdIndexName = "messageID";
        const uniqueMsgIdIndex = {};
        uniqueMsgIdIndex[msgIdIndexName] = 1;

        return dbCollection.indexExists(msgIdIndexName)
            .then(() => Promise.resolve())
            .catch(err => dbCollection.createIndex(uniqueMsgIdIndex, { unique: true }));
    }

    static handleDuplicateKeysError(err, threadId) {
        if (err.code === 11000) {
            return console.warn(`Thread ${threadId}: There were one or more duplicate messages`);
        }

        throw err;
    }
}

class ThreadHistoryDownloadCancelledError extends Error {
    constructor(msg) {
        super(msg);
    }
}<commit_msg>Refactor ThreadHistoryDownloader<commit_after>import { dependencies as Inject, singleton as Singleton } from "needlepoint";
import Db from "mongodb";
import ScheduledTask from "../ScheduledTask";
import Configuration from "../../core/config/Configuration";
import ChatApi from "../../core/api/ChatApi";
import Threads from "../../core/config/Threads";
import Promise from "bluebird";
import until from "async/until";

@Singleton
@Inject(Configuration, Db, ChatApi, Threads)
export default class ThreadHistoryDownloader extends ScheduledTask {
    /**
     * @param {Configuration} config
     * @param {Db} db
     * @param {ChatApi} api
     * @param {Threads} threads
     */
    constructor(config, db, api, threads) {
        super();

        this.config = config;
        this.db = db;
        this.api = api;
        this.threads = threads;

        this.uniqueIndexName = "messageID";
    }

    execute() {
        const threadIds = this.threads.getThreadIds();

        const promises = threadIds.map(id => this.downloadMessagesByThreadId(id));

        return Promise.all(promises);
    }

    downloadMessagesByThreadId(threadId) {
        const dbCollection = this.db.collection(`thread-${threadId}`);

        return Promise
            .all([
                this.createUniqueIndexIfNotExists(dbCollection),
                dbCollection.count(),
                this.api.getThreadInfo(threadId).then(info => info.messageCount)
            ])
            .then(([_, dbCount, fbCount]) => this.handleMessageCount(dbCount, fbCount, threadId))
            .then(messageCount => this.batchDownloadMessages(messageCount, threadId, dbCollection))
            .catch(ThreadHistoryDownloadCancelledError, err => console.warn(err.message))
    }

    batchDownloadMessages(messageCount, threadId, dbCollection) {
        const msgsPerRequest = Math.min(messageCount, 500);

        let i = 0;
        let lastTimestamp = +Date.now();
        let downloadedMessageCount = 0;

        return new Promise((resolve, reject) => {
            until(
                () => (i * msgsPerRequest) >= messageCount,
                done => {
                    return this.api
                        .getThreadHistory(threadId, 0, msgsPerRequest, lastTimestamp)
                        .then(messages => {
                            downloadedMessageCount += messages.length;
                            lastTimestamp = parseInt(messages[0].timestamp) - 1;
                            i++;

                            return this.upsertMany(dbCollection, messages);
                        })
                        .then(({ upsertedCount }) => {
                            console.log(
                                `Thread ${threadId}: ` +
                                `Downloaded total ${downloadedMessageCount}/${messageCount} messages ` +
                                `(${upsertedCount} new)`
                            );

                            return done();
                        })
                        .catch(err => done(err));
                },
                err => {
                    if (err) return reject(err);
                    return resolve();
                });
        });
    }

    handleMessageCount(dbCount, fbCount, threadId) {
        console.log(`Thread ${threadId}: There are ${dbCount} messages in cache, and ${fbCount} reported by Facebook`);

        if (dbCount == fbCount) {
            return Promise.reject(new ThreadHistoryDownloadCancelledError(
                `Thread ${threadId}: Message cache is up-to-date`
            ));
        }

        if (dbCount > fbCount) {
            console.warn(`There are more messages in the cache (${dbCount}) than Facebook reports (${fbCount}). ` +
                `Will download the whole chat history.`);
            return Promise.resolve(fbCount);
        }

        const diff = fbCount - dbCount;
        console.log(`Thread ${threadId}: Message cache is ${diff} messages behind`);

        return Promise.resolve(diff);
    }

    createUniqueIndexIfNotExists(dbCollection) {
        const uniqueMsgIdIndex = {};
        uniqueMsgIdIndex[this.uniqueIndexName] = 1;

        return dbCollection.indexExists(this.uniqueIndexName)
            .then(() => Promise.resolve())
            .catch(err => dbCollection.createIndex(uniqueMsgIdIndex, { unique: true }));
    }

    upsertMany(dbCollection, messages) {
        const getFilter = msg => {
            const filter = {};
            filter[this.uniqueIndexName] = msg[this.uniqueIndexName];
            return filter;
        };

        const operations = messages.map(msg => ({
            updateOne: {
                filter: getFilter(msg),
                update: { $set: msg },
                upsert: true
            }
        }));

        return dbCollection.bulkWrite(operations, { ordered: false });
    }
}

class ThreadHistoryDownloadCancelledError extends Error {
    constructor(msg) {
        super(msg);
    }
}<|endoftext|>


<commit_before>var name = function(user) {
  if(user._id === Meteor.userId()) {
    return "Ik";
  } else {
    return user.name ? user.name : user.emails[0].address;
  }
};

var scrollToBottom = function() {
  // Scroll to bottom and select entry field
  window.scrollTo(0, document.body.scrollHeight);
  d3.select("textarea").node().focus();
};

Template.messagesPage.helpers({
  messages: function() {
    return Messages.find({});
  },

  sender: function() {
    return name(Meteor.users.findOne({_id: this.sender}));
  },

  sender_location: function() {
    return this.sender === Meteor.userId() ? "right" : "left";
  },

  message_id: function() {
    return this._id;
  },

  recipient_names: function() {
    var recipients = Meteor.users.find({"_id": {$in: this.recipients}}).fetch();
    var names = recipients.map(function(recipient) { return name(recipient); });
    return names.length > 0 ? names.join(", ") : "Iedereen";
  },

  selected_users: function() {
    var selectedItems = Session.get("selectedItems");
    if(selectedItems.length === 0) {
      return "Iedereen";
    } else {
      var users = Meteor.users.find({"_id": {$in: selectedItems}}).fetch();
      return users.map(function(user) { return name(user); }).join(", ");
    }
  }
});

Template.messagesPage.events({
  "click .reply_message": function(e) {
    e.preventDefault();

    // Retrieve recipients from selected message
    var messageId = d3.select(e.currentTarget).attr("data-message-id");
    var message = Messages.findOne({ _id: messageId });
    var recipients = message.recipients;

    // Check if message is to selected recipients (instead of all)
    if(recipients.length > 0) {

      // Add sender to recipients and than remove user (user will either be sender or a recipient)
      recipients.splice(0, 0, message.sender);
      recipients = recipients.filter(function(recipient) { return recipient !== Meteor.userId(); });
    }

    // Set recipients as new selected users
    Session.set("selectedItems", recipients);

    // Scroll to bottom to show message entry field and focus field
    scrollToBottom();
  },

  "click .send_message": function(e) {
    e.preventDefault();

    // Create extra message
    var messageProperties = {
      project: this._id,
      content: d3.select("[name=messagecontent]").property("value"),
      recipients: Session.get("selectedItems")
    };
    Meteor.call("messageInsert", messageProperties, function(error, result) {
      if(error) {
        throwError(error.reason);
      }

      // Remove message content
      d3.select("[name=messagecontent]").property("value", "");
    });

    // Scroll to bottom to allow new entry to be given
    scrollToBottom();
  },

  "click .project_title": function(e) {
    e.preventDefault();
    Router.go("projectPage", {_id: this._id});
  }
});

Template.messagesPage.onRendered(function() {
  scrollToBottom();
});
<commit_msg>Fixed issue with names in messages<commit_after>var name = function(user) {
  if(user._id === Meteor.userId()) {
    return "Ik";
  } else {
    if(user.name) {
      return user.name;
    }
    var emailAddress = user.emails[0].address;
    var cleanedName = emailAddress
      .replace(/@.*$/, "")              // Remove @domain.com
      .replace(/\./g, " ")              // Replace . with space
      .replace(/(^.| .)/g, function(match, firstChar) {
        return firstChar.toLocaleUpperCase();
      })
    ;
    return cleanedName;
  }
};

var scrollToBottom = function() {
  // Scroll to bottom and select entry field
  window.scrollTo(0, document.body.scrollHeight);
  d3.select("textarea").node().focus();
};

Template.messagesPage.helpers({
  messages: function() {
    return Messages.find({});
  },

  sender: function() {
    return name(Meteor.users.findOne({_id: this.sender}));
  },

  sender_location: function() {
    return this.sender === Meteor.userId() ? "right" : "left";
  },

  message_id: function() {
    return this._id;
  },

  recipient_names: function() {
    if(!this.recipients) {
      return "Iedereen";
    }
    var recipients = Meteor.users.find({"_id": {$in: this.recipients}}).fetch();
    var names = recipients.map(function(recipient) { return name(recipient); });
    return names.length > 0 ? names.join(", ") : "Iedereen";
  },

  selected_users: function() {
    var selectedItems = Session.get("selectedItems");
    if(selectedItems.length === 0 || selectedItems.length === Session.get("items").length) {
      return "Iedereen";
    } else {
      var users = Meteor.users.find({"_id": {$in: selectedItems}}).fetch();
      return users.map(function(user) { return name(user); }).join(", ");
    }
  }
});

Template.messagesPage.events({
  "click .reply_message": function(e) {
    e.preventDefault();

    // Retrieve recipients from selected message
    var messageId = d3.select(e.currentTarget).attr("data-message-id");
    var message = Messages.findOne({ _id: messageId });
    var recipients = message.recipients;

    // Check if message is to selected recipients (instead of all)
    if(recipients.length > 0) {

      // Add sender to recipients and than remove user (user will either be sender or a recipient)
      recipients.splice(0, 0, message.sender);
      recipients = recipients.filter(function(recipient) { return recipient !== Meteor.userId(); });
    }

    // Set recipients as new selected users
    Session.set("selectedItems", recipients);

    // Scroll to bottom to show message entry field and focus field
    scrollToBottom();
  },

  "click .send_message": function(e) {
    e.preventDefault();

    // Create extra message
    var messageProperties = {
      project: this._id,
      content: d3.select("[name=messagecontent]").property("value"),
      recipients: Session.get("selectedItems")
    };
    Meteor.call("messageInsert", messageProperties, function(error, result) {
      if(error) {
        throwError(error.reason);
      }

      // Remove message content
      d3.select("[name=messagecontent]").property("value", "");
    });

    // Scroll to bottom to allow new entry to be given
    scrollToBottom();
  },

  "click .project_title": function(e) {
    e.preventDefault();
    Router.go("projectPage", {_id: this._id});
  }
});

Template.messagesPage.onRendered(function() {
  scrollToBottom();
});
<|endoftext|>


<commit_before><commit_msg>Update namespace<commit_after><|endoftext|>


<commit_before>'use strict';
const extend = require('deep-extend');
const Base = require('yeoman-generator').Base;

function fixSourceFile(content) {
  // REMOVE /// <reference path="../../tsd.d.ts" />
  content = content.replace(/\/\/\/ <reference path="\.\.\/\.\.\/tsd\.d\.ts" \/>\s/gm, '');
  // FROM ../caleydo_(.*)/main to phovea_$1/src/index
  content = content.replace(/\.\.\/caleydo_(.*)\/main/gm, 'phovea_\$1/src/index');
  // FROM ../caleydo_(.*)/(.*)' to phovea_$1/src/$2'
  content = content.replace(/\.\.\/caleydo_(.*)\/(.*)/gm, 'phovea_\$1/src/\$2');
  // FROM import (.*) = require('(.*)') TO import * as $1 from '$2'
  content = content.replace(/import\s+(.*)\s+=\s+require\('(.*)'\)/gm, 'import * as \$1 from \'\$2\'');

  // FROM /// <amd-dependency path='css!(.*)' /> TO import '$1';
  content = content.replace(/\/\/\/ <amd-dependency path='css!(.*)' \/>/gm, 'import \'\$1.css\';');

  return content;
}

class Generator extends Base {

  writing() {
    this.fs.copy(this.destinationPath('src/*.ts'), this.destinationPath('src/'), {
      process: (contents) => {
        const ori = contents.toString();
        return fixSourceFile(ori);
      }
    });
  }
}

module.exports = Generator;
<commit_msg>use scss instead of css for including style<commit_after>'use strict';
const extend = require('deep-extend');
const Base = require('yeoman-generator').Base;

function fixSourceFile(content) {
  // REMOVE /// <reference path="../../tsd.d.ts" />
  content = content.replace(/\/\/\/ <reference path="\.\.\/\.\.\/tsd\.d\.ts" \/>\s/gm, '');
  // FROM /main to /index
  content = content.replace(/\/main/gm, '/index');
  // FROM ../caleydo_(.*)/(.*)' to phovea_$1/src/$2'
  content = content.replace(/\.\.\/caleydo_(.*)\/(.*)/gm, 'phovea_\$1/src/\$2');
  // FROM import (.*) = require('(.*)') TO import * as $1 from '$2'
  content = content.replace(/import\s+(.*)\s+=\s+require\('(.*)'\)/gm, 'import * as \$1 from \'\$2\'');

  // FROM /// <amd-dependency path='css!(.*)' /> TO import '$1.scss';
  content = content.replace(/\/\/\/ <amd-dependency path='css!(.*)' \/>/gm, 'import \'\$1.scss\';');

  return content;
}

class Generator extends Base {

  writing() {
    this.fs.copy(this.destinationPath('src/*.ts'), this.destinationPath('src/'), {
      process: (contents) => {
        const ori = contents.toString();
        return fixSourceFile(ori);
      }
    });
  }
}

module.exports = Generator;
<|endoftext|>


<commit_before>process.env['NODE_ENV'] = 'production'
const CanvasApi = require('kth-canvas-api')
const inquirer = require('inquirer')
const moment = require('moment')
require('dotenv').config()

const canvasApi = new CanvasApi(process.env.CANVAS_API_URL, process.env.CANVAS_API_KEY)

async function listErrors () {
  try {
    const {numOfDays} = await inquirer.prompt({
      message: 'Hur många dagar bakåt?',
      name: 'numOfDays',
      type: 'number',
      default: 1
    })
    console.log(numOfDays)
    const from = moment().subtract(numOfDays, 'days').utc().toDate().toISOString()

    const allSisImports = await canvasApi.recursePages(`${process.env.CANVAS_API_URL}/accounts/1/sis_imports?created_since=${from}`)
    console.log(JSON.stringify(allSisImports, null, 4))

    const flattenedSisImports = allSisImports.reduce((a, b) => {
      a.push(...b.sis_imports)
      return a
    }, [])

    console.log(flattenedSisImports)
      // const canvasUsers = await canvasApi.recursePages('/accounts/1/sis_imports?created_since=2017-09-13T06:30:10.278Z')
      // const usersWithoutSisId = canvasUsers.filter(u => !u.sis_user_id)
      // console.log(JSON.stringify(usersWithoutSisId, null, 4))
  } catch (e) {
    console.error(e)
  }
}
listErrors()
<commit_msg>filter out warnings<commit_after>process.env['NODE_ENV'] = 'production'
const CanvasApi = require('kth-canvas-api')
const inquirer = require('inquirer')
const moment = require('moment')
require('dotenv').config()

const canvasApi = new CanvasApi(process.env.CANVAS_API_URL, process.env.CANVAS_API_KEY)

async function listErrors () {
  try {
    const {numOfDays} = await inquirer.prompt({
      message: 'Hur många dagar bakåt?',
      name: 'numOfDays',
      type: 'number',
      default: 1
    })
    console.log(numOfDays)
    const from = moment().subtract(numOfDays, 'days').utc().toDate().toISOString()

    const allSisImports = await canvasApi.recursePages(`${process.env.CANVAS_API_URL}/accounts/1/sis_imports?created_since=${from}&per_page=100`)

    const flattenedSisImports = allSisImports
    .reduce((a, b) => a.concat(b.sis_imports), []) // Flatten every page

    const allWarnings = flattenedSisImports
    .map(_import => _import.processing_warnings)
    .filter(warnings => warnings) // filter out nulls and undefineds
    .reduce((a,b)=>a.concat(b),[])  // Flatten every warning from every sis_import

    // console.log(allWarnings)
    const filteredWarnings = allWarnings
    .filter(([fileName,warning])=> !warning.startsWith('Neither course nor section existed'))
    .filter(([fileName,warning])=> !warning.startsWith('An enrollment referenced a non-existent section'))
    console.log(filteredWarnings)
      // const canvasUsers = await canvasApi.recursePages('/accounts/1/sis_imports?created_since=2017-09-13T06:30:10.278Z')
      // const usersWithoutSisId = canvasUsers.filter(u => !u.sis_user_id)
      // console.log(JSON.stringify(usersWithoutSisId, null, 4))
  } catch (e) {
    console.error(e)
  }
}
listErrors()
<|endoftext|>


<commit_before>$(document).ready(function(){
  var user1, user2, currentSession, startTime, endTime, currentInterval, totalTimeWorking, pairingDurationMs, timer;
  var sessions = [];

  $('button.duration-button').on('click', function(event){
    event.preventDefault();
    if($('input.duration').val() !== "" ){
      currentInterval = parseInt($('input.duration').val());
      pairingDurationMs = currentInterval * 60000;
    } else {
      alert("Please Enter A Real Number");
    }
  });

  $('button.start-pairing').on('click', function(){
    var date = new Date();
    startTime = date.getTime();
    currentSession = sessions.push(PairingSession(user1, user2));
    startTimerCount();
  });

  $('.pause_button').on('click', function(){

  })

  function PairingSession(){
    this.drive = user1;
    this.navigate = user2;
    this.timeWorked;
    this.timePaused;
  }

  function startTimerCount(){
    timer = setInterval(function(){
      totalTimeWorking ++;
      currentInterval --;
      updateTimerCountdown();
      checkDuration();
    }, 60000);
  }

  function calculatePauseTime(){
    pause_time = endTime - startTime - totalTimeWorking;
    currentSession.timePaused = pause_time;
  }

  function stopTimer(){
    window.clearInterval(timer);
  }

  function checkDuration(){
    if(currentInterval === 0){
      currentInterval = pairingDurationMs / 60000;
      currentSession.timeWorked = 20;
      alert('Switch it ^');
    }
  }

  function updateTimerCountdown(){
    $('.countdown').val(currentInterval);
  }
});

<commit_msg>Add Total Session Constructor Class<commit_after>$(document).ready(function(){
  var user1, user2, currentSession, startTime, endTime, currentInterval, totalTimeWorking, pairingDurationMs, timer;
  var sessions = [];

  $('button.duration-button').on('click', function(event){
    event.preventDefault();
    if($('input.duration').val() !== "" ){
      currentInterval = parseInt($('input.duration').val());
      pairingDurationMs = currentInterval * 60000;
    } else {
      alert("Please Enter A Real Number");
    }
  });

  $('button.start-pairing').on('click', function(){
    var date = new Date();
    startTime = date.getTime();
    currentSession = sessions.push(PairingSession(user1, user2));
    startTimerCount();
  });

  $('.pause_button').on('click', function(){
    if(timer){
      window.clearInterval(timer);
      timer = null;
    } else {
      startTimerCount();
    }
  });

  function PairingSession(user1, user2){
    this.drive = user1;
    this.navigate = user2;
    this.timeWorked = 0;
    this.timePaused = 0;
  }

  function TotalSessionInfo(activeTime, pauseTime){
    this.totalTime = pauseTime + activeTime;
    this.activeTime = activeTime;
    this.pauseTime = pauseTime;
  }

  function startTimerCount(){
    timer = setInterval(function(){
      totalTimeWorking ++;
      currentInterval --;
      updateTimerCountdown();
      checkDuration();
    }, 60000);
  }

  function calculatePauseTime(){
    pause_time = endTime - startTime - totalTimeWorking;
    currentSession.timePaused = pause_time;
  }

  function stopTimer(){
    window.clearInterval(timer);
  }

  function checkDuration(){
    if(currentInterval === 0){
      currentInterval = pairingDurationMs / 60000;
      currentSession.timeWorked = 20;
      alert('Switch it ^');
    }
  }

  function updateTimerCountdown(){
    $('.countdown').val(currentInterval);
  }
});

<|endoftext|>