AJAX response keep increasing without loop issue

Question: I am doing promote and demote system. Result will update and show immediately once user click on the button. The function is working properly. But I figured out, if I keep pressing the promote / demote button. The loading time will keep increasing. So I try to check the Console by using Firebug and I found out this problem regarding to AJAX response.
The response keep on increasing once I press the button.
I will attach the screenshot.

From the image, you can see the AJAX response when I click the button for first time and second time.

This is the result when AJAX response when I click for third time. The number will keep increasing until my browser crash.
I will attach my Javascript code here.
Feel free to correct my bad coding. I'm will appreciate it.
This is the displayTable function which include some extra click event function.
function displayTable() {

$('#tableContent').empty();

$.post(base_url + "index.php/resident_detail_controller/selectAllUser", {}, function(data) {

    $('#tableContent').html(
            "<input type='hidden' id='totalRows' value='" + data.result.length + "' />" +
            "
" +
            "
" +
            "
" +
            "#	" +
            "Email	" +
            "Full Name	" +
            "Contact Number	" +
            "Status	" +
            "Action	" +
            "
" +
            "
" +
            "
");

    if (data.status === 'Success') {

        for (var j = 0; j < data.result.length; j++) {

            if (data.result[j].Category === "N") {
                $('tbody').append(
                        "
" +
                        "" + j + "	" +
                        "<input type='hidden' id='email" + (j + 1) + "' value='" + data.result[j].Email + "' />" + data.result[j].Email + "	" +
                        "" + data.result[j].FullName + "<input type='hidden' id='fullName" + (j + 1) + "' value='" + data.result[j].FullName + "'/>	" +
                        "" + data.result[j].ContactNo + "	" +
                        "" + data.result[j].Category + "	" +
                        "" +
                        "<button type='button' id='btnPromote" + (j + 1) + "' class='btn btn-sm btn-primary btnPromote' value='" + (j + 1) + "'>Promote</button>" +
                        "" +
                        "	" +
                        "
");
            } else {
                $('tbody').append(
                        "
" +
                        "" + j + "	" +
                        "<input type='hidden' id='email" + (j + 1) + "' value='" + data.result[j].Email + "' />" + data.result[j].Email + "	" +
                        "" + data.result[j].FullName + "<input type='hidden' id='fullName" + (j + 1) + "' value='" + data.result[j].FullName + "'/>	" +
                        "" + data.result[j].ContactNo + "	" +
                        "" + data.result[j].Category + "	" +
                        "" +
                        "<button type='button' id='btnDemote" + (j + 1) + "' class='btn btn-sm btn-info btnDemote' value='" + (j + 1) + "'>Demote</button>" +
                        "" +
                        "	" +
                        "
");
            }
        }

        $(document).on("click", ".btnPromote", function(event) {

            //var index = $(this).attr('value');
            var index = String(event.target.value);

            var email = $('#email' + index).val();
            var username = $('#fullName' + index).val();
            $.post(base_url + 'index.php/resident_detail_controller/promoteUser', {email: email}, function(data) {

                if (data.status === 'Success') {
                    notif({
                        msg: 'You had successfully promoted ' + username + '',
                        type: 'success'
                    });

                    $('#tableContent').empty();
                    displayTable();
                } else {
                    notif({
                        msg: 'You fail to promote ' + username + '',
                        type: 'error'
                    });
                }

            }, 'JSON');
        });

        $(document).on("click", ".btnDemote", function(event) {

            var index = String(event.target.value);

            var email = $('#email' + index).val();
            var username = $('#fullName' + index).val();
            $.post(base_url + 'index.php/resident_detail_controller/demoteUser', {email: email}, function(data) {

                if (data.status === 'Success') {
                    notif({
                        msg: 'You had successfully promoted ' + username + '',
                        type: 'success'
                    });

                    $('#tableContent').empty();
                    displayTable();
                } else {
                    notif({
                        msg: 'You fail to promote ' + username + '',
                        type: 'error'
                    });
                }

            }, 'JSON');
        });

        $('#tableContent').append("

");
    }
}, "JSON");

This is the code when user click on the Promote / Demote button.
$('document').ready(function() {

$('.btnPromote').click(function(event) {

    //var index = $(this).attr('value');
    var index = String(event.target.value);
    var email = $('#email' + index).val();
    var username = $('#fullName' + index).val();
    $.post(base_url + 'index.php/resident_detail_controller/promoteUser', {email: email}, function(data) {

        if (data.status === 'Success') {
            notif({
                msg: 'You had successfully promoted ' + username + '',
                type: 'success'
            });

            $('#tableContent').empty();
            displayTable();
        } else {
            notif({
                msg: 'You fail to promote ' + username + '',
                type: 'error'
            });
        }

    }, 'JSON');
});

$('.btnDemote').click(function(event) {

    //var index = $(this).attr('value');
    var index = String(event.target.value);
    var email = $('#email' + index).val();
    var username = $('#fullName' + index).val();
    $.post(base_url + 'index.php/resident_detail_controller/demoteUser', {email: email}, function(data) {

        if (data.status === 'Success') {
            notif({
                msg: 'You had successfully promoted ' + username + '',
                type: 'success'
            });
            $('#tableContent').empty();
            displayTable();
        } else {
            notif({
                msg: 'You fail to promote ' + username + '',
                type: 'error'
            });
        }

    }, 'JSON');
}
);

});
Comment: Every time you call `displayTable()`, you're binding another set of click handlers to all the buttons. So when you click on the button, it runs all the handlers that you've bound. You should normally only bind event handlers at the top level, not inside other event handlers.
Comment: @Barmar, what should I do to overcome this issue?

Is that mean if can try not to use
$(document).on("click", ".btnDemote", function(event)?
Comment: You should put that in the `$(document).ready()` handler, not in `displayTable()`.
Answer: Remove the .on("click") bindings from displayTable(), and replace the .click() bindings in your document ready handler with them.
You also don't need to append '
</table'. When you append elements to the DOM, you're adding whole elements, not bits of HTML strings. So when you append the
, the
 is part of that element, and it's already in there.
I also recommend using $("#tableContent").on("click", ".btnPromote", ...). You should delegate the handler from the closest enclosing static element. Delegation works by binding a handler to the element you apply it to, and it has to check whether the target matches the selector; this way you don't run the handler unnecessarily.
function displayTable() {

    $('#tableContent').empty();

    $.post(base_url + "index.php/resident_detail_controller/selectAllUser", {}, function(data) {

        $('#tableContent').html(
            "<input type='hidden' id='totalRows' value='" + data.result.length + "' />" +
                "
" +
                "
" +
                "
" +
                "#	" +
                "Email	" +
                "Full Name	" +
                "Contact Number	" +
                "Status	" +
                "Action	" +
                "
" +
                "
" +
                "
");

        if (data.status === 'Success') {

            for (var j = 0; j < data.result.length; j++) {

                if (data.result[j].Category === "N") {
                    $('tbody').append(
                        "
" +
                            "" + j + "	" +
                            "<input type='hidden' id='email" + (j + 1) + "' value='" + data.result[j].Email + "' />" + data.result[j].Email + "	" +
                            "" + data.result[j].FullName + "<input type='hidden' id='fullName" + (j + 1) + "' value='" + data.result[j].FullName + "'/>	" +
                            "" + data.result[j].ContactNo + "	" +
                            "" + data.result[j].Category + "	" +
                            "" +
                            "<button type='button' id='btnPromote" + (j + 1) + "' class='btn btn-sm btn-primary btnPromote' value='" + (j + 1) + "'>Promote</button>" +
                            "" +
                            "	" +
                            "
");
                } else {
                    $('tbody').append(
                        "
" +
                            "" + j + "	" +
                            "<input type='hidden' id='email" + (j + 1) + "' value='" + data.result[j].Email + "' />" + data.result[j].Email + "	" +
                            "" + data.result[j].FullName + "<input type='hidden' id='fullName" + (j + 1) + "' value='" + data.result[j].FullName + "'/>	" +
                            "" + data.result[j].ContactNo + "	" +
                            "" + data.result[j].Category + "	" +
                            "" +
                            "<button type='button' id='btnDemote" + (j + 1) + "' class='btn btn-sm btn-info btnDemote' value='" + (j + 1) + "'>Demote</button>" +
                            "" +
                            "	" +
                            "
");
                }
            }
        }
    }, "JSON");
}

$(document).ready(function() {
    $("#tableContent").on("click", ".btnPromote", function(event) {

        //var index = $(this).attr('value');
        var index = String(event.target.value);

        var email = $('#email' + index).val();
        var username = $('#fullName' + index).val();
        $.post(base_url + 'index.php/resident_detail_controller/promoteUser', {email: email}, function(data) {

            if (data.status === 'Success') {
                notif({
                    msg: 'You had successfully promoted ' + username + '',
                    type: 'success'
                });

                $('#tableContent').empty();
                displayTable();
            } else {
                notif({
                    msg: 'You fail to promote ' + username + '',
                    type: 'error'
                });
            }

        }, 'JSON');
    });

    $("#tableContent").on("click", ".btnDemote", function(event) {

        var index = String(event.target.value);

        var email = $('#email' + index).val();
        var username = $('#fullName' + index).val();
        $.post(base_url + 'index.php/resident_detail_controller/demoteUser', {email: email}, function(data) {

            if (data.status === 'Success') {
                notif({
                    msg: 'You had successfully promoted ' + username + '',
                    type: 'success'
                });

                $('#tableContent').empty();
                displayTable();
            } else {
                notif({
                    msg: 'You fail to promote ' + username + '',
                    type: 'error'
                });
            }

        }, 'JSON');
    });
});

Comment: Thank you for your help. I appreciated it very much!
Answer: It looks to me like you're adding a new event handler with these two lines:
$(document).on("click", ".btnDemote", function(event) {

$(document).on("click", ".btnDemote", function(event) {

for every time you do this operation.  Over time, these will pile up and every click will call than event handler a whole bunch of times causing you to do N ajax calls for every click (where N continually grows).
Because these are attached to the document object, these event handlers should be set up ONCE at initialization time and never installed again.
Comment: What can I do to overcome this issue?
Sorry, I'm quite new to this.
Comment: Move the installation of those event handlers outside of the `displayTable()` function to someplace that they are only done once when your page is first loaded.
Comment: I will vote this answer once I had enough reputation. Thanks!!


Chamar outra tela em tkinter

Question: Estou tentando criar uma tela principal com dois botões para chamar as telas "Estoque e "Clientes", porém ao invés de fechar e abrir, ele adiciona na mesma tela.
<code>from clientes import Clientes
from tkinter import *

class Application:
    def __init__(self, master=None):

        self.fonte = ("Verdana", "8")
        root.iconbitmap('ico.ico')
        root.title("Cadastro de clientes: ")
        root.geometry("300x300")
        self.container1 = Frame(master)
        self.container1["pady"] = 10
        self.container1.pack()
        self.container2 = Frame(master)
        self.container2["padx"] = 20
        self.container2["pady"] = 5
        self.container2.pack()

        self.titulo = Label(self.container1, text="Informe os dados :")
        self.titulo["font"] = ("Calibri", "9", "bold")
        self.titulo.pack()

        self.btnCliente = Button(self.container2, text="Clientes", command=lambda: self.Clientes(),
                                 font=self.fonte, width=10)
        self.btnCliente.pack(side=RIGHT)

        self.btnEstoque = Button(self.container2, text="Estoque", command=lambda: self.Estoque(),
                                 font=self.fonte, width=10)
        self.btnEstoque.pack(side=RIGHT)

    def Clientes(self, master=None):
        self.fonte = ("Verdana", "8")
        root.iconbitmap('ico.ico')
        root.title("Cadastro de clientes: ")
        root.geometry("300x300")
        self.container1 = Frame(master)
        self.container1["pady"] = 10
        self.container1.pack()
        self.container2 = Frame(master)
        self.container2["padx"] = 20
        self.container2["pady"] = 5
        self.container2.pack()
        self.container3 = Frame(master)
        self.container3["padx"] = 20
        self.container3["pady"] = 5
        self.container3.pack()
        self.container4 = Frame(master)
        self.container4["padx"] = 20
        self.container4["pady"] = 5
        self.container4.pack()
        self.container5 = Frame(master)
        self.container5["padx"] = 20
        self.container5["pady"] = 5
        self.container5.pack()
        self.container6 = Frame(master)
        self.container6["padx"] = 20
        self.container6["pady"] = 5
        self.container6.pack()
        self.container7 = Frame(master)
        self.container7["padx"] = 20
        self.container7["pady"] = 5
        self.container7.pack()
        self.container8 = Frame(master)
        self.container8["padx"] = 20
        self.container8["pady"] = 10
        self.container8.pack()
        self.container9 = Frame(master)
        self.container9["pady"] = 15
        self.container9.pack()

        self.titulo = Label(self.container1, text="Informe os dados :")
        self.titulo["font"] = ("Calibri", "9", "bold")
        self.titulo.pack()

        self.txtcpf = Label(self.container2,
                            text="Cpf:", font=self.fonte, width=10)
        self.txtcpf.pack(side=LEFT)

        self.txtcpf = Entry(self.container2)
        self.txtcpf["width"] = 15
        self.txtcpf["font"] = self.fonte

        self.txtcpf.pack(side=LEFT)

        self.btnBuscar = Button(self.container2, text="Buscar",
                                font=self.fonte, width=10)
        self.btnBuscar["command"] = self.buscarCliente
        self.btnBuscar.pack(side=RIGHT)

        self.lblnome = Label(self.container3, text="Nome:",
                             font=self.fonte, width=10)
        self.lblnome.pack(side=LEFT)

        self.txtnome = Entry(self.container3)
        self.txtnome["width"] = 25
        self.txtnome["font"] = self.fonte
        self.txtnome.pack(side=LEFT)

        self.lbltel = Label(self.container5, text="Telefone: ",
                            font=self.fonte, width=10)
        self.lbltel.pack(side=LEFT)

        self.txttel = Entry(self.container5)
        self.txttel["width"] = 25
        self.txttel["font"] = self.fonte
        self.txttel.pack(side=LEFT)

        self.btnInsert = Button(self.container8, text="Inserir",
                                font=self.fonte, width=10)
        self.btnInsert["command"] = self.inserirCliente
        self.btnInsert.pack(side=RIGHT)

        self.btnAlterar = Button(self.container8, text="Alterar",
                                 font=self.fonte, width=12)
        self.btnAlterar["command"] = self.alterarCliente
        self.btnAlterar.pack(side=LEFT)

        self.btnExcluir = Button(self.container8, text="Excluir",
                                 font=self.fonte, width=12)
        self.btnExcluir["command"] = self.excluirCliente
        self.btnExcluir.pack(side=LEFT)

        self.lblmsg = Label(self.container9, text="")
        self.lblmsg["font"] = ("Verdana", "9", "italic")
        self.lblmsg.pack()

    def inserirCliente(self):
        cli = Clientes()

        cli.cpf = self.txtcpf.get()
        cli.nome = self.txtnome.get()
        cli.telefone = self.txttel.get()

        self.lblmsg["text"] = cli.insertCliente()

        self.txtcpf.delete(0, END)
        self.txtnome.delete(0, END)
        self.txttel.delete(0, END)

    def alterarCliente(self):
        cli = Clientes()

        cli.cpf = self.txtcpf.get()
        cli.nome = self.txtnome.get()
        cli.telefone = self.txttel.get()

        self.lblmsg["text"] = cli.updateCliente()

        self.txtcpf.delete(0, END)
        self.txtnome.delete(0, END)
        self.txttel.delete(0, END)

    def excluirCliente(self):
        cli = Clientes()

        cli.cpf = self.txtcpf.get()

        self.lblmsg["text"] = cli.deleteCliente()

        self.txtcpf.delete(0, END)
        self.txtnome.delete(0, END)
        self.txttel.delete(0, END)

    def buscarCliente(self):
        cli = Clientes()

        cpf = self.txtcpf.get()

        self.lblmsg["text"] = cli.selectCliente(cpf)

        self.txtcpf.delete(0, END)
        self.txtcpf.insert(INSERT, cli.cpf)

        self.txtnome.delete(0, END)
        self.txtnome.insert(INSERT, cli.nome)

        self.txttel.delete(0, END)
        self.txttel.insert(INSERT, cli.telefone)

    def Estoque(self, master2=None):
        self.fonte = ("Verdana", "8")
        root.iconbitmap('ico.ico')
        root.title("Cadastro de clientes: ")
        root.geometry("300x300")

        self.container1 = Frame(master2)
        self.container1["pady"] = 10
        self.container1.pack()
        self.container2 = Frame(master2)
        self.container2["padx"] = 20
        self.container2["pady"] = 5
        self.container2.pack()
        self.container3 = Frame(master2)
        self.container3["padx"] = 20
        self.container3["pady"] = 5
        self.container3.pack()
        self.container4 = Frame(master2)
        self.container4["padx"] = 20
        self.container4["pady"] = 5
        self.container4.pack()
        self.container5 = Frame(master2)
        self.container5["padx"] = 20
        self.container5["pady"] = 5
        self.container5.pack()
        self.container6 = Frame(master2)
        self.container6["padx"] = 20
        self.container6["pady"] = 5
        self.container6.pack()
        self.container7 = Frame(master2)
        self.container7["padx"] = 20
        self.container7["pady"] = 5
        self.container7.pack()
        self.container8 = Frame(master2)
        self.container8["padx"] = 20
        self.container8["pady"] = 10
        self.container8.pack()
        self.container9 = Frame(master2)
        self.container9["pady"] = 15
        self.container9.pack()

        self.titulo = Label(self.container1, text="Informe os dados :")
        self.titulo["font"] = ("Calibri", "9", "bold")
        self.titulo.pack()

        self.txtcdbarra = Label(self.container2,
                                text="cod barra:", font=self.fonte, width=10)
        self.txtcdbarra.pack(side=LEFT)

        self.txtcdbarra = Entry(self.container2)
        self.txtcdbarra["width"] = 15
        self.txtcdbarra["font"] = self.fonte

        self.txtcdbarra.pack(side=LEFT)

        self.btnBuscar = Button(self.container2, text="Buscar",
                                font=self.fonte, width=10)
        self.btnBuscar["command"] = self.buscarProd
        self.btnBuscar.pack(side=RIGHT)

        self.lblnome = Label(self.container3, text="Nome:",
                             font=self.fonte, width=10)
        self.lblnome.pack(side=LEFT)

        self.txtnome = Entry(self.container3)
        self.txtnome["width"] = 25
        self.txtnome["font"] = self.fonte
        self.txtnome.pack(side=LEFT)

        self.lblval = Label(self.container5, text="Valor:",
                            font=self.fonte, width=10)
        self.lblval.pack(side=LEFT)

        self.txtval = Entry(self.container5)
        self.txtval["width"] = 25
        self.txtval["font"] = self.fonte
        self.txtval.pack(side=LEFT)

        self.lbqtd = Label(self.container6, text="Quantidade:",
                           font=self.fonte, width=10)
        self.lbqtd.pack(side=LEFT)

        self.txtqtd = Entry(self.container6)
        self.txtqtd["width"] = 25
        self.txtqtd["font"] = self.fonte
        self.txtqtd.pack(side=LEFT)

        self.btnInsert = Button(self.container8, text="Inserir",
                                font=self.fonte, width=10)
        self.btnInsert["command"] = self.inserirProd
        self.btnInsert.pack(side=RIGHT)

        self.btnAlterar = Button(self.container8, text="Alterar",
                                 font=self.fonte, width=12)
        self.btnAlterar["command"] = self.alterarProd
        self.btnAlterar.pack(side=LEFT)

        self.btnExcluir = Button(self.container8, text="Excluir",
                                 font=self.fonte, width=12)
        self.btnExcluir["command"] = self.excluirProd
        self.btnExcluir.pack(side=LEFT)

        self.lblmsg = Label(self.container9, text="")
        self.lblmsg["font"] = ("Verdana", "9", "italic")
        self.lblmsg.pack()

    def inserirProd(self):
        prod = Produtos()

        prod.cdbarra = self.txtcdbarra.get()
        prod.nome = self.txtnome.get()
        prod.valor = self.txtval.get()
        prod.quantidade = self.txtqtd.get()

        self.lblmsg["text"] = prod.insertProd()

        self.txtcdbarra.delete(0, END)
        self.txtnome.delete(0, END)
        self.txtval.delete(0, END)
        self.txtqtd.delete(0, END)

    def alterarProd(self):
        prod = Produtos()

        prod.cdbarra = self.txtcdbarra.get()
        prod.nome = self.txtnome.get()
        prod.valor = self.txtval.get()
        prod.quantidade = self.txtqtd.get()

        self.lblmsg["text"] = prod.updateProd()

        self.txtcdbarra.delete(0, END)
        self.txtnome.delete(0, END)
        self.txtval.delete(0, END)
        self.txtqtd.delete(0, END)

    def excluirProd(self):
        prod = Produtos()

        prod.cdbarra = self.txtcdbarra.get()

        self.lblmsg["text"] = prod.deleteProd()

        self.txtcdbarra.delete(0, END)
        self.txtnome.delete(0, END)
        self.txtval.delete(0, END)
        self.txtqtd.delete(0, END)

    def buscarProd(self):
        prod = Produtos()

        cdbarra = self.txtcdbarra.get()

        self.lblmsg["text"] = prod.selectProd(cdbarra)

        self.txtcdbarra.delete(0, END)
        self.txtcdbarra.insert(INSERT, prod.cdbarra)

        self.txtnome.delete(0, END)
        self.txtnome.insert(INSERT, prod.nome)

        self.txtval.delete(0, END)
        self.txtval.insert(INSERT, prod.valor)

        self.txtqtd.delete(0, END)
        self.txtqtd.insert(INSERT, prod.quantidade)

root = Tk()
Application(root)
root.mainloop()```
</code>
Answer: Já existe um outro tópico que responde a essa mesma pergunta vá até: Transição de telas - Tkinter

Chamar outra tela em tkinter


Twitter Bootstrap - nav bar issues in internet explorer

Question: I am using Twitter Bootstrap in my rails app.  My navbar looks perfect in Firefox / Chrome / Safari (tested chrome on both a Mac & PC). In Internet Explorer, it looks ugly! Wrong colours & everything.
Any help you can provide would be appreciated. I can post whatever code would help.
Update
Here is all of the CSS where I override anything from bootstrap (brought into my app via sass-rails gem). Hopefully it pushes us in the right direction.
Note: Where I have color:#F8F8F8; below, I used to have #333. This is just one iteration of me trying to fix it.  I've even tried changing the background color to #333334 as I think that my precompiler was changing #333333 to #333 (don't know for sure though)
/*  Styling */

.navbar, .navbar-inner, .navbar-fixed-top, .container, #tabs .nav {
  border:none;
  background-image:none;
}

.navbar {

  font-size:14px;
  text-shadow:none;
  -webkit-box-shadow: none;
  -moz-box-shadow: none;
  box-shadow: none;

  .nav {
    float:right;
  }

  .brand {
    margin-left:30px;
    color:#333334;
    font-family: Georgia, serif
  }

  .navbar-inner {
      background-color: #F8F8F8;
      border-bottom-color: #E0E0E0;
      border-bottom-style: solid;
      border-bottom-width: 1px;
      color: #333334;
  }

}

.navbar .nav > li > a {
  text-shadow:none;
  color:#555555;
  background-color: transparent;
  cursor:pointer;

  &:hover {
    color:#E6E6E6;
  }
}

.navbar .nav .active > a, .navbar .nav .active > a:hover {
  background-color: transparent;
  color: #555555;
}

.navbar .nav .inactive > a:hover {
  color:#999999;
}

.navbar .nav > li > a.sign-in {
  color:#555555;
  padding-top:4px;
  padding-bottom:4px;
  margin-top:5px;
  margin-left:30px;
}

.navbar .nav > li > a.sign-in:hover {

  background-position: 0 0px;

}

.navbar .nav > li > a.active-button {
  background-color: #E6E6E6;
  background-image: none;
  border:1px solid #cccccc;
  border-radius:4px;
  box-shadow: none;
  cursor: pointer;
  opacity: 0.6499999761581421;
  outline-color: #555555;
  outline-style: none;
  outline-width: 0px;
  text-decoration: none;
  text-shadow: none;
  padding-top:4px;
  padding-bottom:4px;
  margin-top:5px;
}

I have also tried the following (in an attempt to explicitly override anything to do with gradients from Bootstrap):
body {
  color:#333334;
}

.navbar-inner {
  background-image: -moz-linear-gradient(top, #F8F8F8, #F8F8F8);
  background-image: -ms-linear-gradient(top, #F8F8F8, #F8F8F8);
  background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#F8F8F8), to(#F8F8F8));
  background-image: -webkit-linear-gradient(top, #F8F8F8, #F8F8F8);
  background-image: -o-linear-gradient(top, #F8F8F8, #F8F8F8);
  background-image: linear-gradient(top, #F8F8F8, #F8F8F8);
}

.btn-navbar {
  background-image: -moz-linear-gradient(top, #F8F8F8, #F8F8F8);
  background-image: -ms-linear-gradient(top, #F8F8F8, #F8F8F8);
  background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#F8F8F8), to(#F8F8F8));
  background-image: -webkit-linear-gradient(top, #F8F8F8, #F8F8F8);
  background-image: -o-linear-gradient(top, #F8F8F8, #F8F8F8);
  background-image: linear-gradient(top, #F8F8F8, #F8F8F8);
}

Yet another update
Fiddling around with the internet explorer developer tools leads me to believe the issue is this:
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#FF333333',endColorstr='#F2222222', GradientType=0)

What is this?  Do I need it?  (Why does it not use the same gradients as firefox/chrome?)  It comes from Bootstrap... I can try to override the colours in there because for whatever reason IE is interpreting FF333333 as that dark blue.
Comment: Try `filter:none` on your navbar (totally forgot about that), IE uses a separate syntax to generate gradients. `background-image` is still not supported by IE9 to create gradients.
Comment: What file in bootstrap has the offending line 'filter:progid...'?
Comment: post some code so we can take a look.
Comment: Will throw up a bunch of relevant CSS... hope that helps!
Comment: @AndresIlich any thoughts?  Still struggling!
Comment: We need more info work with, the css you postd is not enough.
Comment: So frustrating that something so small takes so long to fix! Thanks so much for your help.  Going to post an answer with the exact code I used to over-write the filter, but a HUGE rate-up for you!
Comment: I have identical code as yours, but I get the blue bar in production and a correct one in development.  I think the minification is confusing IE.
Comment: I got this problem when I used stylebootstrap.info, which is a great tool other than it caused the problem you describe below in your solution.
Answer: Turns out I was able to fix this by over-riding the default filter code generated by Bootstrap.  Big thanks for Nathan and Andres!  To override the code I had posted above, I added the following :
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#F8F8F8', endColorstr='#F8F8F8', GradientType=0)

Hope this saves some pain for somebody....
Comment: You helped me save a ton of pain. Apparently I had the line:
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#'ffffff, endColorstr='#'e5e5e5, GradientType=0);, where the ' quotes only enclosed the '#' sign and not the whole color. Changing it to, for example '#ffffff' made it work.
Comment: I was still experiencing this with Bootstrap 2.1.0 using dotless, and it turns out the problem was dotless.  Since that's been updated to 220.127.116.11 the problem has gone away (dotless is formatting the colours in filters correctly for IE)
Comment: I think there is a slightly better answer here: http://stackoverflow.com/questions/14088485/replace-background-in-twitter-bootstrap-navbar-for-ie
Answer: Andres Ilich commented on the OP:

"Try filter:none on your navbar (totally forgot about that), IE uses a
  separate syntax to generate gradients. background-image is still not
  supported by IE9 to create gradients."

After developing very painful forehead from smacking it numerous times on the desk, this is exactly what fixed the issue for me. Thanks Andres.
Comment: I really think they should have made the default CSS a little less involved. For a framework that's supposed to help speed up web development, they sure make it a pain to style. Is that minor gradient really so important to the default style that they need to add so much complexity to the customization of the primary navigation?
Comment: THANK YOU, you saved me a lot of time!
Answer: This happened to me too. But I found out that in CSS gradients, IE (even 9) doesn't seem to except just 3-character HEX codes. So you need to change the hex codes  to 3-character instead if they aren't already (such as #CCC to #CCCCCC) so it'll work correctly in IE (only for the IE gradient CSS, not all of them).
If you could post your CSS I could see if there are any other problems. But, my problem was that #CCC was being interpreted as dark blue in IE.
Comment: @brandon - have you tried setting it to black and white temporarily to see if that works? Also is the CSS that you posted all for the header or is there more? If so please post that as well.
Comment: Thanks for getting back to me.  I'll give that a shot!
Comment: Unfortunately still can't get it to work (managed to get it to go somewhat black...) Will post some code.
Comment: @Brandon That's weird. Mine was all blue and ugly looking like yours (actually it looked exactly like yours) but I changed it to the longer version and it worked. How does it look in IE now?
Comment: unfortunately its still terrible looking... will post an updated capture.  Any other thoughts?
Comment: I just used -ms-filter: etc etc (vendor prefixes) and this solved the issue
Answer: From what i can tell you're using a solid color for your background in the top navbar, so you're only adding a background-color but not removing the background-image as well, so try to reset that too like so:
  .navbar-inner {
      background-color: #F8F8F8;
      background-image:none;
      border-bottom-color: #E0E0E0;
      border-bottom-style: solid;
      border-bottom-width: 1px;
      color: #333334;
  }

Answer: This is much more simple:
.dropdown-menu>li>a:hover,
.dropdown-menu>li>a:focus,
.dropdown-submenu:hover>a,
.dropdown-submenu:focus>a,
.dropdown-menu>li.active>a
{
   filter: none;
}

Answer: Internet Explorer is quite good at messing things up what I normally do is use a separate style sheet to fix up explore without messing up the rest of my site. Paste this line of code in your web pages:

and modify the css to make look better on explorer, and the good part is other browsers will ignore this style sheet.


Allowing custom CSS

Question: I want to allow my users to insert their custom CSS into their websites.
The custom CSS file will be served to the customers website only. I will host the CSS myself and I'm thinking of serving it through a PHP script and doing the filtering there.

What should I pay attention to while doing this?
I should filter things, what exactly should not be included in the CSS file?

Thank you
Comment: There are a few things to concern yourself with.  One of which is that you can simply hide all of your elements on the page and replace them with some giant graphic that you probably don't want to see.  Is that an issue for you?  Other issues may arise depending on how you are including the user-supplied CSS, and what it's purpose is.  Then you also have the potential exploit of services that perform actions for GET requests, but you may not care about that.
Comment: The user supplied CSS will only be visible on his part. I think people may try to upload all kinds of malicious things including PHP and/or JS code. So what should I pay attention to?
Comment: As I said, you need to provide more detail.  Are you hosting this CSS?  Depending on how you include it, you might not have to do anything.  Show us what you are doing.
Comment: I can see close votes but no information why it has been close-voted.
Answer: I implemented this sometime ago. My approach was to create a seperate php/css document. Create a html/php page with a form on it with inputs for the user to input their styling options. Post this to the css/php script and then use the variables from the post accordingly. You would need to escape all post requests for security.
Put this within your html document
<link rel='stylesheet' type='text/css' href='css/style.php' />

Create a php/css document like so
<?php
    header("Content-type: text/css; charset: UTF-8");

   $brandColor = "#990000";
   $linkColor = "#555555";
   $CDNURL = "http://cdn.blahblah.net";
?>

#header {
   background: url("<?php echo $CDNURL; ?>/images/header-bg.png") no-repeat;
}
a {
  color: <?php echo $linkColor; ?>;
}
ul#main-nav li a {
  color: <?php echo $linkColor; ?>;
}

Comment: @Vector, Agreed, I'm just adding notes with the hope that someone doesn't blindly copy/paste what you have without knowing what they're doing.
Comment: Hmm yes. They could modify the colours but not the style at all. Yes seems interesting :) Thank you!
Comment: They could modify style/color etc, which ever you choose. they could rewrite your entire CSS if you let them.
Comment: As implemented here, someone could modify whatever they wanted in your CSS, include external CSS, etc.  Your line about "you would need to escape all post requests for security" should not be taken lightly.  Better in this case to actually validate the values you accept.
Comment: @Brad You would only apply the post request variables to elements that you specify within your script. Also you would run checks using regex on all entries to ensure they meet your requirements, plus escaping. This is just a basic example. When i posted it i assumed some knowledge of the developer.

Allowing custom CSS


Prove, if $\delta>0$, then $\lim_{n\to\infty}\int_{\delta<|s|<a}K_n(s)ds=0$

Question: Prove, if $\delta>0$, then $\lim_{n\to\infty}\int_{\delta<|s|<a}K_n(s)ds=0$ if
$$K_n(s)=
\begin{cases}
&n, |s|<1/2n\\
&0, |s|>1/2n
\end{cases}
$$
This shouldn't be too difficult, but I'm struggling somewhat. If I just set up the problem, then we have
$$\int_{-1/2n}^{-\delta}n ds+\int_{\delta}^{1/2n}n ds=1-2n\delta$$
and clearly taking the limit does not give us the desired result. Where am I going wrong? Thanks!
Comment: Your calculation of the integral is valid only if $\delta <\frac  1 {2n}$. If  $\delta >\frac  1 {2n}$ you will get $0$ instead of $1-2n\delta$
Answer: Hint: If $n >\frac 1 {2\delta}$ then the set $\{s: \delta <|s|<a\}\cap \{s:|s|<\frac 1 {2n}\}$ is the empty set.
Comment: This makes sense. Thank you. However, in your comment, you mentioned if $\delta>\frac{1}{2n}$, we get 0. I get your reasoning with the set, but if we just set up the case $\delta>\frac{1}{2n}$ in a similar fashion to the integral in the OP, then we just get $2n\delta-1$. Can't we show that the integral actually goes to zero instead of considering the set?
Comment: You cannot write $\int_{2<x<1} f(x)dx=-\int_1^{2}f(x)dx$.  $\int_{2<x<1} f(x)dx=0$ because you are integrating $f$ over the empty set.  $\int_{2<x<1} f(x)dx$ is not the same as $\int_2^{1}f(x)dx$. @William


Maximal Cohen-Macaulay modules of full support, over non-artinian local Cohen-Macaulay rings, are faithful?

Question: Let $(R,\mathfrak m)$ be a local Cohen-Macaulay ring of positive dimension. Let $M$ be a finitely generated maximal Cohen-Macaulay module i.e. $\operatorname{depth} M=\dim R$.
If $\operatorname{Supp}(M)=\operatorname{Spec}(R)$, then is it true that $M$ is faithful?
My thoughts: Since $\operatorname{Supp}(M)=\operatorname{Spec}(R)$, so the radical of the annihilator ann$_R(M)$ is exactly the nilradical of $R$, so every element in the annihilator of $M$ is nilpotent. We would be done if $R$ were reduced, but that's not necessarily the case.
Please help.
Answer: Let $R=K[X,Y]/(X^2Y)$ and $M=R/(xy)$. Then $M$ is MCM, $\operatorname{Ann}_R(M)=(xy)$, and $\operatorname{Supp}(M)=\operatorname{Spec}(R)$ since every prime ideal of $R$ contains $x$ or $y$.
Comment: As a note, one can also take any proper cyclic module over an Artinian local ring; examples abound.
Comment: I just noticed that you want $R$ local. Then localize at $(x,y)$ or replace $K[X,Y]$ by $K[[X,Y]]$.


Is it possible to set "global" shared attributes for all devices?

Question: I am doing a study about the ThingsBoard features and I'm working on a particular scenario:
I have several devices (thousands) and I want to advertise them when a new firmware is available. To do so, I want to modify, through the dashboard, all the shared attributes named "fwVersion" (linked to the devices) with the new FW version.
Is it possible to do it globally with one specific widget for instance? (Of course, I don't want to manually modify the shared attribute for each device)
Thank you for your time and help.
Answer: You could try setting up an alias which is populated via a device query so it contains all the devices you're interested in. Then use that alias as the input to an update shared attribute widget.
Note I have not tried this, but I noticed dashboard aliases can be populated from queries and are always used as the inputs to widgets.
Comment: The accepted solution is not working since it does not let you read/write data if configured with multiple entities. Any other ideas?


Use cosine rule to determine the length of a side of a triangle. Cannot replicate textbook solution

Question: Given a triangle of lengths $4$, $5$ and $x$, where the sides of length $4$ and $5$ meet at an angle of $60^{\circ}$, I must calculate the length of side $x$.

The cosine rule is: $$a^2 = b^2 + c^2 - 2bc\cos(\alpha)$$
So, applying to my problem:
$$\begin{align}
a^2&=b^2+c^2-2bc\cos(\alpha) \\
x^2&=4^2+5^2-2(4)(5)(\cos(60^{\circ})) \\
x^2&=16+25-40\cos(60^{\circ}) \\
x^2&=41-40\cos(60^{\circ}) \\
x^2&=41-40(0.9524) \\
x^2&=41-38.1 \\
x^2&=2.9 \\
x&=\sqrt{2.9}
\end{align}$$
The textbook solution says I should arrive at $x = \sqrt{21}$, not $x=\sqrt{2.9}$. The textbook does not provide working to the solution, only the final answer.
Where did I go wrong?
Comment: $\cos 60°=0.5$, you need to study the unit circle
Answer: Hint: $\cos(60^o)=0.5$ maybe you mixed radians ($60^o=1/3\pi$) with degrees on your calculator?
Comment: @DougFir: In Google calculator, click "Rad" in the left top corner, that will switch it to degrees.
Comment: Oh. I used Google Calculator in my browser: https://www.google.com/search?q=online+calculator, I typed the COS button then 60. Thanks for letting me know. Are you able to get 0.5 with Googles online calculator somehow?
Comment: Hm. I just openned R application too and typed cos(60) which gave me the same result as Google calculator
Comment: @Vasya thank you, that allowed me to replicate the result 0.5.
Comment: @DougFir $\cos 60\text{rad}\approx -0.9524$, so there's a sign issue too. A negative cosine is obtained for obtuse angles.


Logic Pro X: keyboard shortcut to move the playhead to the begining of selected region

Question: Is there a keyboard shortcut to move the play-head to the beginning of the selected region?
When I try to edit the shortcuts, I don't find anything similar.
Comment: Ctrl-End goes to END of selected region
Answer: For US Keyboard layout, it's Control-Home.

If you want to play selected region(s), it's Shift-SpaceBar
Answer: The accepted answer is spot on - just wanted to add one important thing...
If you're using a laptop - ctrl-home is produced by pressing ctrl-fn and the left arrow key.
Comment: yes, that was part of the problem :)
Answer: Go to navigate, then scroll down to play button options then click on play from selected region, and this feature will always be enabled


Non-Uniform Spherical Distributions

Question: Suppose $X_i\overset{\text{iid}}{\sim} N(0,1)$, and define the random vector $\mathbf{X}=(X_1,\ldots,X_n)$. Then the normalized vector $\mathbf{Z}:=\frac{\mathbf{X}}{\|\mathbf{X}\|_2}$ is uniformly distributed on the sphere $\mathbb{S}^{n-1}$. Several properties of the distribution of $\mathbf{Z}$ are known, e.g.,

All odd moments are $\mathbf{0}\in\mathbb{R}^{n}$
Cross-term/second moments: $\mathbb{E}[Z_iZ_j]=n^{-1}\mathbb{1}(i=j)$

(More properties of higher order moments are listed in Chapter 9 of Mardia and Jupp's Directional Statistics textbook.)
My question is: what happens if we define $X_i\overset{\text{ind}}{\sim}N(0,\sigma_i^2)$, more generally? One could rely on symmetry arguments to show that Property 1 above still holds for the normalized vector $\mathbf{Z}$, but is there a straightforward way to obtain second and higher order moments of $\mathbf{Z}$? I am most keen to be pointed to any references or techniques (recurrences or recursions perhaps?) for deriving these quantities. Thanks in advance!
Comment: A similar spherical distribution (but not the same because of a different construction method without projection) is the [Von Mises-Fisher distribution](https://en.m.wikipedia.org/wiki/Von_Mises%E2%80%93Fisher_distribution).
Comment: Shouldn't the expectation of $Z_iZ_j$ be zero as well for $i\neq j$ because of symmetry? Maybe you refere to the expectation of the absolute value?
Comment: I was asking for the way that you want to generalize the distributions. But I see now that the generalisation are just to change the variance?
Comment: Thanks for the comments @SextusEmpiricus. Yes I am aware of the Von Mises-Fisher distribution. Also, you are right re: Property 2 for $i\neq j$; I have that covered by the indicator function.
Comment: I am looking for a generalization to a collection of independent but not necessarily identically distributed zero-mean Gaussians.
Comment: I see. To be more specific, I'm interested in the second moments. But I suspect the way to derive the second moment might reveal general techniques that allow one to work up to higher moments. Thus I phrased my question more broadly.
Comment: The moments of $X$ are found by multiplying the moments of $Z$ by suitable products of powers of the $\sigma_i$ because *all you are doing is changing the units of measurement of the $Z_i.$*  That looks so trivial that I am led to wonder whether you have something more complicated in mind where you refer to "higher order moments of $Z.$"
Answer: In two dimensions, the second moments $E[Z_i^2]$ have a simple formula, which implies that those moments are proportional to the standard deviations of the variables.
Suppose $X_i$ and $X_j$ have standard deviations $s$ and $t$. By considering these as dilations of two standard normals,
$$(X_i,X_j)\sim (Rs\cos\theta,Rt\sin\theta)$$
where $\theta$ is uniformly distributed on $[0,2\pi]$, and the distribution of $R$ is half-normal but irrelevant. By substituting $u=(t \tan\theta)/s$, and then integrating with the method of partial fractions,
$$Z_i^2=\frac{(Rs\cos\theta)^2}{(Rs\cos\theta)^2 + (Rt\sin\theta)^2}$$
\begin{align}
E[Z_i^2] &= \frac{1}{2\pi}\int_0^{2\pi}\!
\frac{s^2\cos^2\theta}{s^2\cos^2\theta + t^2\sin^2\theta}\,d\theta\\
&=\frac{2}{2\pi}\int_{-\infty}^\infty \frac{1}{1+u^2}\frac{(t/s)\,du}{(t/s)^2+u^2}\\
&=\frac{s}{s+t}
\end{align}
Similarly $E[Z_j^2]=t/(s+t)$. In the special case mentioned in the post of identical standard deviations, this gives the expected value of $1/2$.
Comment: This argument makes sense. Thanks! I will see if there is a way to generalize, and post an update if I find something.

Non-Uniform Spherical Distributions


Why my Polynomial model has this spike?

Question: How can I explain the spike in my Poly model after using the polynomial 3rd degree?
My dataset consist of the X variables external facctores (x1,x2...xk) and Y which is a target variable. For a polynomial I am not using interactions. I am using only the degrees. So i have x1, x12, x12 and so on for all values which might have a degrees.

 Meanwhile OLS is quite ok

And here is my OLS regression output
Comment: The spike is the least of your problems. This model is grossly overfit: you use far too many variables for the limited number of observations you have. There are many indications that conditions needed to apply OLS reliably don't hold (look, in particular, at the kurtosis of the residuals).
Comment: Have you looked at the huge condition number?  What you have posted is a useless model due to the overfitting and multicollinearity, unless your sole objective is to describe your data.
Comment: There are lots of polynomials. Can you explain which polynomial basis you used? How is the OLS model computed? It's clearly not a single line in the space of the $x$ axis of the plot.
Comment: Sure I will edit the question
Comment: @whuber thank you for observation. But anyways my data is not normaly distributed so the kurtosis is not preoccupying me. I have checked the main assumptions of OLS which are multicollenearity, endegen. and autocorrelation of residuals are all ok.
Answer: The answer is simple. Look at your "polynomial" model output. Find the coefficient that is orders of magnitude higher than the others. This is where the model is so finely adjusted, that there is a single observation for one or more cofficients uniquely determine its value. Consider yourself lucky that the observation you have overfit is obviously visible in the plot - and consider further it's probably happening in a few other places.
The best solution is just to fit a smarter model. I don't know anything about your problem, but it's curious that you have adjusters such as "8marzo" i.e. the 8th of March. One wonders why you effectively delete the observation by adjusting for it specially.
But in cases such as this, analysts have often advocated for a ridge (L2 penalty) regression to reduce the high variance of coefficients in overadjusted prediction models.
You might liken it to the following example in OLS:
<code>set.seed(123)
x <- sort(rnorm(100))
i <- 1:100 == 100 ## indicator for 100th observation
y <- rnorm(100, x) ## no relation to i at all

fit <- lm(y ~ x + i)

plot(x, y)
lines(x, predict(fit))
</code>
Comment: How can you tell which coefficients are large when you know nothing about the values of the underlying variables??
Comment: True, one assumes they are standardized in a sensible way, and if they are not, then they can be without impacting the inference/analysis/observed issue here.
Comment: @AdamO I really liked your answer however I didn't quite get the points of overfitting and fine adjustment. Could you please explain in a simpler way? Thank you
Comment: @AdamO btw i have used also LAsso and Ridge models. They have set some of my variables to 0. Variables set to 0 are constant, and 2 other dummy variables
Comment: @Amirgiano the issue seems to stem from a lack of experience in analysis - which is ok. Even in the polynomial setting, you can attempt to add variables one after the other - or remove them in a similar fashion - to gain insight into your model. It's tedious and every bit worthwhile.
Comment: Given the large range of the coefficient estimates, the assumption of standardization is not tenable.
Comment: @AdamO so you mean there is a variable which has a huge coefficent which is actually makes that spike. The only way to find it is a backward selection technique. Correct?
Comment: Perhaps the simplest way to identify a variable contributing to an anomaly is to identify the record or records exhibiting that anomaly and inspect the values of all variables in those records.  That's quick and easy.
Comment: Indeed I did something similar. I was thinking that one variable might to that. I used it as a mediator. I have regressed the media variables' total with that variable and used the regression predictions as a new variable. Then my polynomial model had 0.38 of the RMSE

Why my Polynomial model has this spike?


binary numbers: strange differences between + and |

Question: I'm trying to manipulating binary numbers with c. I found a strange thing with the minimum code below. Can anyone tell me what is the difference between "+" and "|" here? Thank you!
char next_byte1 = 0b11111111;
char next_byte2 = 0b11110101;
short a = (next_byte1 << 8) | next_byte2;
short b = (next_byte1 << 8) + next_byte2;
printf("a vs b is %d ~ %d.\n", a, b);

It showed: a vs b is -11 ~ -267, which is 0b11111111 11110101 and 0b11111110 11110101. I'm very confused with this result.
Answer: The problem you are seeing is because next_byte2 is sign-extended to a full int before doing the bitwise operation and thus is "corrupting" the high byte.
When doing bit manipulation it's better to use unsigned types (that is actually what unsigned are to be used for). Plain char types can be (and normally are) signed types and thus are better avoided for these uses.
Comment: @AleksanderBobiński: Actually in C99 it's not undefined behavior but either there is an implementation-defined result or an implementation-defined signal is raised. This means that things like the crazy back-in-time propagation of UB that modern g++ likes so much is not allowed.
Comment: Also the compiler warns about an overflow from int to char when defining next_byte1 and next_byte2. There is UB in this example.
Comment: It is worth to mention that `char` is not necessarily signed type (it is implementation defined). Probably the OPs compiler defines `char` as signed type.
Answer:
You should never use char for binary/bitwise arithmetic, because it has implementation-defined signedness and might be negative. In general, use stdint.h over the default C types.
In case char is signed, then the value inside it ends up converted to -1 in two's complement during the variable initialization. This happens to next_byte1 and next_byte2 both.
Whenever you use a small integer type inside an expression, it is usually promoted to signed int. So your -1 (0xFF) gets changed to -1 (0xFFFFFFF) before you left shift.
Left shifting a negative operand is undefined behavior, meaning that any kind of bugs may rain all over your program. This happens in this case, so no results are guaranteed.
Apparently in your case, the undefined behavior manifested itself as you ending up with a large negative number with the binary representation 0xFFFFFF00.
The difference between | and + is that the latter cares about sign, so in case of + you end up adding negative numbers together, but in case of | the binary representations are simply OR:ed together.

You can fix the program in the following way:
#include <stdio.h>
#include <stdint.h>

int main(void)
{
  uint8_t next_byte1 = 0xFF;
  uint8_t next_byte2 = 0xF5;
  uint16_t a = (next_byte1 << 8) | next_byte2;
  uint16_t b = (next_byte1 << 8) + next_byte2;
  printf("a vs b is %d ~ %d.\n", a, b);
}

And now | and + work identically, as intended.
Answer: Both answers should resolve your problem. I just want to add clarity around '|' and '+' operators.

'|' is the bitwise inclusive OR operator

'+' is the addition operator, which translates into inclusive OR
operator with CARRY propagation for multi-bit numbers.

They are not the same operator and one should not expect the same result in general, although for some cases they might lead to the same result like in your example.


Deriving Cartesian Coordinates from Cylindrical Coordinates

Question:
The ans given was:

$x = r \cos (\alpha)$
$y = h$
$z = -r \sin(\alpha)$

Could somebody explain to me how to arrive at the formula?
I'm probably confused with the axes because usually, the $Z$ axis was given as the depth or "height" for cylindrical coordinates. Even when the axes rotates, shouldn't the formula be

$x = r \cos(\alpha)$
$y = r \sin(\alpha)$
$z = z$

Sorry if this qns seems elementary. I'm really confused with 3D coordinates
Answer: The important facts of cylindrical coordinates are:

You need an axis to determine height,
The other two coordinates will be given as distance from the origin and rotation around the other planes.

Therefore, height ("depth") doesn't have to be $z$. Here is how I would go about it:
The picture suggests you use the $y$ axis as height, therefore $y=h$. We need to a point in the $xz$ plane in polar coordinates. From the picture you can see that the vector has a positive $x$ component and a negative $z$ component, hence we perform $x = r \cos (\alpha)$ and $z = - r \sin (\alpha)$.
Comment: Thanks a lot for the clear explanation! It really help to clear the doubts I had regarding 3D coordinate systems.


extracting numbers or changing them directly using perl

Question: $harddisk = `wmic logicaldisk get size,caption`;

contains the following. What i want to do is extract the numbers, or change them directly
Total Hard disk capacity:
Caption  Size
C:       480737488896
D:       19157479424
E:
F:

would it be possible to perhaps get them using a foreach+
foreach($harddisk =~ m/\d+/g){
    push(@hdd, noideawhattoputhere;
}
or is it perhaps possible to use math in a regex? here i'd want to divide $1 by 1024.
$harddisk =~ s/(\d+)/$1/g;

thanks in advance!
Answer: $harddisk =~ s|\d+|$&/1024|ge;

The e modifier means to treat the substitution as an expression to evaluate.


How to do validation date_end in odoo

Question: I have two model in my calendar_holidays that is date_start and date_end, I plan to do validation for date_end "date_end must greater than date_start"
below is my code odoo python code
date_start = fields.Date(string='Date start', required=True,index=True)
date_end = fields.Date(string 'Date End', constrains="_check_holidays")

@api.multi
@api.constrains('date_start','date_end')
def _check_holidays(self):
  if self.date_start < self.date_end:
     raise ValidationError('Date end must greater than start date')

Any things I do wrong, actually I feel weird for my code, thanks.
Answer: You are checking wring condition, I have just update IF condition else everything seems fine.
@api.multi
@api.constrains('date_start','date_end')
def _check_holidays(self):
  if self.date_start > self.date_end:
     raise ValidationError('Date end must greater than start date')

How to do validation date_end in odoo


Having trouble passing data between client and server in eclipse: nosuchelementexception

Question: I've a bank account program where users can add, withdraw money and view account details. I'm trying to send this data back and forth between the client and the server. I'm getting a connection but I'm not able to send data back and forth. I've gotten a nosuchelementexception for every line where I use my Scanner object for getting values from the server :
Scanner sScan = new Scanner(s.getInputStream());
Is it the right way for passing data back and forth?
Here's the client:
import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class Main {
    public static void main(String args[])  {
        {
            String user_name=null,type,temp;
            type = null;
            int balance=0,tmp=0,temp1=0;
            int withdraw=0,currentBal=0;
            int randNumber = 0;
randNumber = (int)((Math.random() * 9000)+1000);

            create_account user = new create_account("user",0,"savings");

                Scanner in = new Scanner(System.in);
                Scanner strng=new Scanner(System.in);
                try{
                    //new socket for communicatio
                Socket s = new Socket("127.0.0.1", 3000);
                //scanner for accepting data from serve
                Scanner sScan = new Scanner(s.getInputStream());
                //new printstream for passing values to server
                PrintStream p = new PrintStream(s.getOutputStream());
                 System.out.println("Connected");

                int userChoice;
                boolean quit = false;
                 System.out.println("Welcome to UNCC Banking, please select from the menu");

                do {
                    //present menu
                      System.out.println("1. Deposit money");
                      System.out.println("2. Withdraw money");
                      System.out.println("3. Check balance");
                      System.out.println("4. Display Account Details");
                      System.out.println("0. to quit: \n");
                      System.out.print("Enter Your Choice : ");
                      //send userChoice to Server?
                      userChoice = in.nextInt();

                      //p.println(userChoice);
                      //get number from server?
                     // temp1 = sScan.nextInt();
                      switch (userChoice) {

                    case 1: // deposit

                        //p.println(tmp);
                       //temp1 = sScan.nextInt();
                     System.out.print("Enter Amount Of Money : ");
                     //balance=in.nextInt();
                     p.println(balance);
                     temp1 = sScan.nextInt();
                     user.Acc_Balance=balance;
                     System.out.println("\t Successfully Deposited.");

                       break;

                      case 2: // withdraw money

                                 if(user.Acc_Balance==0)
                                 System.out.print("Your Account is Empty.");

                                 else{
                                 System.out.print("Enter Amout Of Money : ");
                                 //withdraw=in.nextInt();
                                 p.println(withdraw);
                                 temp1=sScan.nextInt();

                                 if(withdraw>user.Acc_Balance){
                                 System.out.print("Please enter Valid Amout of Money : ");
                                 //withdraw=in.nextInt();
                                 p.println(withdraw);
                                 temp1=sScan.nextInt();

                                 }
                                 else
                                 currentBal= user.withdraw(withdraw);

                                 System.out.println("Your Current Balance : "+currentBal);
                                 p.println(currentBal);
                                 }

                            break;

                      case 4: // check balance

                                 System.out.println("Your Current Balance : "+user.Acc_Balance);
                                 p.println(user.Acc_Balance);

                          break;

                      case 5: // display account info

                                 user.display_details();

                          break;
                      case 0:
                            quit = true;
                            break;
                      default:
                            System.out.println("Invalid Choice.");
                            break;
                      }
                      System.out.println("\n");
                } while (!quit);
                System.out.println("Thank you for visiting UNCC Banking");

         }

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

}

Here's the server:
import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

class BankAccount  {
    String name,acc_type;

    int Acc_Balance;

    BankAccount(){

    }

        BankAccount(String n,int b,String a_t) {

            try{
                 ServerSocket s1 = new ServerSocket(3000);
                 Socket s2 = s1.accept();
                 Scanner sc=new Scanner(s2.getInputStream());
                 PrintStream p = new PrintStream(s2.getOutputStream());

                 System.out.println("Connected");

        name=n;
           p.println(name);
           name = sc.nextLine();
           Acc_Balance=b;
         p.println(Acc_Balance);
         Acc_Balance = sc.nextInt();
           acc_type=a_t;
           p.println(name);
           name = sc.nextLine();
            }
            catch(Exception e)
            {

            }
        }
        public static void main(String[] args)
        {

        }

} // end class

class create_account extends BankAccount {

    create_account (String n,int b,String a_t){

        name=n;
        // name = sc.nextLine();
       //  p.println(name);

         Acc_Balance=b;
        // Acc_Balance=sc.nextInt();
     //    p.println(Acc_Balance);
         acc_type=a_t;
    }
    create_account(){
        super();
    }

    void insert(String n,String a_t){
        name=n;

        acc_type=a_t;
        Acc_Balance=0;
    }

    void display_details(){
        /*
        try{
             ServerSocket s1 = new ServerSocket(1342);
             Socket s2 = s1.accept();
             Scanner sc=new Scanner(s2.getInputStream());
             PrintStream p = new PrintStream(s2.getOutputStream());
             */
                         System.out.println("Depositor Name :" +name);

             System.out.println("Account Balance : "+Acc_Balance);
            // p.println(Acc_Balance);
             System.out.println("Account Type : "+acc_type);
            // p.println(acc_type);

    }

        //deposit money
        void deposit(int money){
                Acc_Balance=money;
        }
        //withdraw money
        int withdraw(int withd){
                Acc_Balance=Acc_Balance-withd;
                return Acc_Balance;
        }

}

Answer: First of all, when you run a server it waits for client to connect Socket s2 = s1.accept().
The first thing after that, you're trying to get a name from a client name = sc.nextLine().
As I see from the client code, you are never passing a name to the server. Try to refactor your code to have the same order of writing and reading. Which means, if you're waiting for a name on the server side, the first thing you need to do on the client side  is p.println(name).
Comment: Okay I actually don't need the name or anything in that constructor sorry for the confusion, I just need to pass the account balance,money withdrawn, and money deposited, but that's happening in different methods in the server, so it's like I'd have to make a server for each method, how could I do this with just one server?


Como fazer gráfico dinâmico baseado em registros do banco de dados

Question: O meu sistema tem uma página com uma tabela que mostra cada registro do banco com um botão para abrir um modal.

Gostaria que dentro desse modal tivesse um gráfico que comparasse a quantidade de ações previstas com a quantidade de ações realizadas mês a mês.
Porém, como eu só tenho um botão que se repete de acordo com a quantidade de registros dentro de um while, eu não sei como fazer pra esse botão entender qual é o ID do registro e gerar um gráfico dinamicamente pra ele.
O código:

Resultados

                    <?php
                            //Conexão e consulta ao Mysql
                            $lnk = mysqli_connect('localhost','root','') or die(mysql_error());
                            mysqli_select_db($lnk,'banco') or die(mysql_error());
                            $qry = mysqli_query($lnk, "select * from gptw");

                            //Pegando os nomes dos campos
                            $num_fields = mysqli_num_fields($qry);//Obtém o número de campos do resultado

                            for($i = 0;$i<$num_fields; $i++){//Pega o nome dos campos
                                $fields[] = mysqli_fetch_field_direct($qry,$i)->name;
                            }

                            //Montando o cabeçalho da tabela
                            $table = '

';

                            for($i = 0;$i < $num_fields; $i++){
                                $table .= ''.$fields[$i].'	';
                            }

                            //Montando o corpo da tabela
                            $table .= '
';
                            while($r = mysqli_fetch_array($qry)){
                                $table .= '
';
                                for($i = 0;$i < $num_fields; $i++){
                                    $table .= ''.$r[$fields[$i]].'	';
                                }

                                // ADICIONANDO BOTÃO DE EDIÇÃO
                                $table .= '<form action="edicao-gptw.php" method="post">';
                                $table .= '<input type="hidden" name="ID" value="'.$r['ID'].'">';
                                $table .= '<input type="hidden" name="JAN PREV" value="'.$r['JAN PREV'].'">';
                                $table .= '<input type="hidden" name="JAN REAL" value="'.$r['JAN REAL'].'">';
                                $table .= '<input type="hidden" name="FEV PREV" value="'.$r['FEV PREV'].'">';
                                $table .= '<input type="hidden" name="FEV REAL" value="'.$r['FEV REAL'].'">';
                                $table .= '<input type="hidden" name="MAR PREV" value="'.$r['MAR PREV'].'">';
                                $table .= '<input type="hidden" name="MAR REAL" value="'.$r['MAR REAL'].'">';
                                $table .= '<input type="hidden" name="ABR PREV" value="'.$r['ABR PREV'].'">';
                                $table .= '<input type="hidden" name="ABR REAL" value="'.$r['ABR REAL'].'">';
                                $table .= '<input type="hidden" name="MAI PREV" value="'.$r['MAI PREV'].'">';
                                $table .= '<input type="hidden" name="MAI REAL" value="'.$r['MAI REAL'].'">';
                                $table .= '<input type="hidden" name="JUN PREV" value="'.$r['JUN PREV'].'">';
                                $table .= '<input type="hidden" name="JUN REAL" value="'.$r['JUN REAL'].'">';
                                $table .= '<input type="hidden" name="JUL PREV" value="'.$r['JUL PREV'].'">';
                                $table .= '<input type="hidden" name="JUL REAL" value="'.$r['JUL REAL'].'">';
                                $table .= '<input type="hidden" name="AGO PREV" value="'.$r['AGO PREV'].'">';
                                $table .= '<input type="hidden" name="AGO REAL" value="'.$r['AGO REAL'].'">';
                                $table .= '<input type="hidden" name="SET PREV" value="'.$r['SET PREV'].'">';
                                $table .= '<input type="hidden" name="SET REAL" value="'.$r['SET REAL'].'">';
                                $table .= '<input type="hidden" name="OUT PREV" value="'.$r['OUT PREV'].'">';
                                $table .= '<input type="hidden" name="OUT REAL" value="'.$r['OUT REAL'].'">';
                                $table .= '<input type="hidden" name="NOV PREV" value="'.$r['NOV PREV'].'">';
                                $table .= '<input type="hidden" name="NOV REAL" value="'.$r['NOV REAL'].'">';
                                $table .= '<input type="hidden" name="DEZ PREV" value="'.$r['DEZ PREV'].'">';
                                $table .= '<input type="hidden" name="DEZ REAL" value="'.$r['DEZ REAL'].'">';
                                $table .= '<button class="btn btn-primary"> Editar </button>'; //
                                $table .= '</form>	';

                                // ADICIONANDO MODAL PARA GRÁFICO
                                $table .= '<form action="graf-gptw.php" method="post">';
                                $table .= '<input type="hidden" name="ID" value="'.$r['ID'].'">';
                                $table .= '<input type="hidden" name="JAN PREV" value="'.$r['JAN PREV'].'">';
                                $table .= '<input type="hidden" name="JAN REAL" value="'.$r['JAN REAL'].'">';
                                $table .= '<input type="hidden" name="FEV PREV" value="'.$r['FEV PREV'].'">';
                                $table .= '<input type="hidden" name="FEV REAL" value="'.$r['FEV REAL'].'">';
                                $table .= '<input type="hidden" name="MAR PREV" value="'.$r['MAR PREV'].'">';
                                $table .= '<input type="hidden" name="MAR REAL" value="'.$r['MAR REAL'].'">';
                                $table .= '<input type="hidden" name="ABR PREV" value="'.$r['ABR PREV'].'">';
                                $table .= '<input type="hidden" name="ABR REAL" value="'.$r['ABR REAL'].'">';
                                $table .= '<input type="hidden" name="MAI PREV" value="'.$r['MAI PREV'].'">';
                                $table .= '<input type="hidden" name="MAI REAL" value="'.$r['MAI REAL'].'">';
                                $table .= '<input type="hidden" name="JUN PREV" value="'.$r['JUN PREV'].'">';
                                $table .= '<input type="hidden" name="JUN REAL" value="'.$r['JUN REAL'].'">';
                                $table .= '<input type="hidden" name="JUL PREV" value="'.$r['JUL PREV'].'">';
                                $table .= '<input type="hidden" name="JUL REAL" value="'.$r['JUL REAL'].'">';
                                $table .= '<input type="hidden" name="AGO PREV" value="'.$r['AGO PREV'].'">';
                                $table .= '<input type="hidden" name="AGO REAL" value="'.$r['AGO REAL'].'">';
                                $table .= '<input type="hidden" name="SET PREV" value="'.$r['SET PREV'].'">';
                                $table .= '<input type="hidden" name="SET REAL" value="'.$r['SET REAL'].'">';
                                $table .= '<input type="hidden" name="OUT PREV" value="'.$r['OUT PREV'].'">';
                                $table .= '<input type="hidden" name="OUT REAL" value="'.$r['OUT REAL'].'">';
                                $table .= '<input type="hidden" name="NOV PREV" value="'.$r['NOV PREV'].'">';
                                $table .= '<input type="hidden" name="NOV REAL" value="'.$r['NOV REAL'].'">';
                                $table .= '<input type="hidden" name="DEZ PREV" value="'.$r['DEZ PREV'].'">';
                                $table .= '<input type="hidden" name="DEZ REAL" value="'.$r['DEZ REAL'].'">';
                                $table .= '
                                            <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
                                              Gráfico
                                            </button>

Gráfico

                                                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                                      ×
                                                    </button>

                                                    Aqui entra o gráfico.

                                                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>

'; //
                                $table .= '</form>	';

                            }

                            //Finalizando a tabela
                            $table .= '

';

                            //Imprimindo a tabela
                            echo '
';
                            echo $table;
                    ?>

Eu até sei fazer um gráfico para cada registro do banco de dados em php e highharts, mas não sei fazer um gráfico só que se se adapta dependendo do registro que tenha sido clicado.
Alguém tem algum exemplo pra me dar um norte?
Answer: Olá, você já ouviu falar no C3? É uma biblioteca js de gráficos que é muito bonita e fácil de usar.
http://c3js.org/
Talvez possa te ajudar! Abraços
Comment: Então, eu uso o Highcharts pra gráficos em JS, eu só não sei como eu vou fazer ele dinamicamente se adequando ao registro clicado.


Understanding Policy Iteration and Value Iteration

Question: I have read an answer there but still cannot capture the ideas behind it.
In Sutton's book, section Value Iteration, it is said that

In fact, the policy evaluation step of policy iteration can be truncated in several ways without losing the convergence guarantees of policy iteration. One important special case is when policy evaluation is stopped after just one sweep (one backup of each state). This algorithm is called value iteration.

When I look at the algorithm (in the same link above), since we loop until the error threshold $\Delta < \theta$, we must "sweep" through the state space multiple times. Could someone explain the idea that "policy evaluation is stopped after just one sweep" above?
Also, in the section Generalized Policy Iteration,

In value iteration, for example, only a single iteration of policy evaluation is performed in between each policy improvement.

In the value iteration algorithm: we compute all possible $q(s,a)$ <- policy evaluation, then assign the maximum $q(s,a)$ to $V(s)$ based on action $a$ <- policy improvement, then store the error $\Delta$. In general, we have sequence:

compute all $q(s,a)$: policy evaluation
choose $a$ that maximizes $q(s,a)$ and assign it to $V(s)$: policy improvement
update error term $\Delta$
compute all $q(s',a)$: policy evaluation
choose $a$ that maximizes $q(s',a)$ and assign it to $V(s')$: policy improvement
update error term $\Delta$
...

Then between each policy improvement, we have one iteration of policy evaluation. Is this the correct way to understand the above claim from the book?
Answer: Though as you stated in the value iteration algo we loop until the error threshold $\Delta < \theta$ we must sweep through the state space multiple times, the single sweep (one backup of each state) mentioned in your reference simply means that one line in the referenced algo which is $v \leftarrow V(s)$. Thus in value iteration the updated value at every iteration step of any state is not that state's value function, but some intermediate value of an iterative process which theoretically converges to that state's value function eventually.
On the other hand, in each evaluation step of the policy iteration algo we do multiple sweeps to arrive at each state's value function via another iterative process within one policy evaluation and improvement cycle, which obviously involves more computation steps than value iteration. So in practice you could use value iteration or truncated policy iteration to stop earlier before arriving at each state's true value function in a theoretically potentially infinite iterative process.
Finally you could separate value update for your sequence of each state from policy improvement in your referenced algo's while-until loop since it's implemented in an elementwise fashion, and yes between each policy improvement we have one iteration (sweep) of policy evaluation for each state.


How i can pass the completion handler to another function swift ios

Question: I'm working on the firebase chat app and here is the first function insertConversation2 and this function creating a node of conversation array that contains all the data about chat.
Now I want when user sending the message and code goes to success block, and at this point, I want to create another node of messages through function and pass the first function
completion handler to the second function (finishCreatingConversation) completion handler but the issue is that it's not working fine and not creating the second node. See the firebase screenshot conversation node is creating but message-id not creating please check the code thanks.
First function
func insertConversation2(with otherUserEmail: String,name:String,message:Message,completion:@escaping(Bool) -> Void){

    let dformatter = DateFormatter()
    dformatter.dateFormat = "dd/MM/yyy HH:mm"
    let dateToString = dformatter.string(from: Date())
    guard let email = UserDefaults.standard.value(forKey: "useremail") as? String else {
    return}
    var getSafeEmail = getUserEmail(currentEmail: email)

    database.child("\(getSafeEmail)").observeSingleEvent(of: .value) { (snapshot) in
        //if user is not preens to go to false block else go to furhter
        guard var userNode = snapshot.value as? [String:Any] else {
            completion(false)
            print("user not found in insert time in networking manager")
            return
        }

    var messageData = ""

    switch message.kind{

    case .text(let messageText):
        messageData = messageText
        default:break
    }

let conversationId = "conversation_\(message.messageId)"

    let newConversation:[String:Any] = [
        "id":conversationId,
        "other_user_email": otherUserEmail,
        "name":name,
        "latest_message":[
            "date":dateToString,
            "message":messageData,
            "is_read":false
        ]
    ]

        if var userConversation = userNode["conversation"] as? [[String:Any]]{
            //conversation array is exiten append the conversation data
            userConversation.append(newConversation)
            userNode["conversation"] = userConversation
            database.child("\(getSafeEmail)").setValue(userNode) { (error, ref) in
                guard error != nil else {return}

               self.finishCreatingConversation(conversationId: conversationId, message: message, completion: completion)
               //completion(true)
            }
        }
        else{

            userNode["conversation"] = [
                newConversation
            ]
            database.child("\(getSafeEmail)").setValue(userNode) { (error, ref) in
                guard error != nil else {return}
                self.finishCreatingConversation(conversationId: conversationId, message: message, completion: completion) //second not working fine
               //completion(true) //passing a refrence of completion in above function of insert method
            }
        }
    }

}

Second function
func finishCreatingConversation(conversationId:String,message:Message,completion:@escaping(Bool) -> Void){
      var messageData = ""
    switch message.kind{

    case .text(let messageText):
        messageData = messageText
    }
    let dformatter = DateFormatter()
    dformatter.dateFormat = "dd/MM/yyy HH:mm"
    let dateToString = dformatter.string(from: Date())

    guard let email = UserDefaults.standard.value(forKey: "useremail") as? String else {
    return}
    //var getUserEmail = getUserEmail(currentEmail: email)
    let getUserEmailData = getUserEmail(currentEmail: email)
    let collectionMessge: [String:Any] = [
        "id":message.messageId,
        "type":message.kind.messageKindString,
        "content":messageData,
        "date": dateToString,
        "sender_email":getUserEmailData,
        "is_read":false

    ]

    database.child("\(conversationId)").setValue(collectionMessge) { (error, ref) in
        guard error != nil else {return}
        completion(true)
    }
}

Firebase Image:
Answer: Replace
self.finishCreatingConversation(conversationId: conversationId, message: message, completion: completion)

with
self.finishCreatingConversation(conversationId: conversationId, message: message) { res in
     completion(res)
}

Comment: Same result It's not working not creating the message id node but creating the conversation node
Comment: add breakpoints every where to track your code execution also print error inside `database.child("\(conversationId)").setV` may be it's a permission one
Comment: the issue on first function insertConversation2() the last else block   database.child("\(getSafeEmail)").setValue(userNode) { (error, ref) in the error is nil and not reaching on secondfunction and execution is terminating but in firebase it creating the node of conversation


I would like to know few things about chord progression

Question: I would like to know few things about chord progression:-
(I-IV-V)
(I-III-IV-V)
(I-II-V-I)
(I-IV-II-V-I)
(I-VI-II-V-I)
(I-III-VI-II-V-I)
These are some of the popular chord progressions.

What is the logic behind these chord progressions?? why I IV V?? is it because of circle of fifth ?? or some sort interval?  How did the musicians came up with this?
How are these chord progression played in a song? is Chord I played first then IV and V -and the same pattern continues?? or these chords can be played randomly??

I am completely new to music, and was wondering how all this stuff works, though I know how to construct triad and seventh chords. I also know that in a major scale I IV V are Major chords, II III VI are Minors and VII is a diminished.
I'll be happy if someone could explain me all this, I tried finding it on the internet, but it was all in vain.
Thanks for your time
Comment: 1. They sound good. 2. You can play chords in any order you like, but generally when someone specifies a progression they mean in-order.
Answer: The chords of the major scale are I ii iii IV V vi viio (Upper case = Major; Lower case = minor; Lower case with o = diminished).
Each one of those chords has a certain tension - ranging from none (I) to very tense (viio). That tension depends on the notes of the chord (how many notes it shares with the I chord and whether or not it has a leading tone):

I consists of 1-3-5, and is the most stable chord.
ii consists of 2-4-6: No notes in common with I, doesn't have a
leading tone.
iii consists of 3-5-7: 2 notes in common with I, has a leading
tone.
IV consists of 1-4-6: 1 note in common with I, doesn't have a
leading tone.
V consists of 2-5-7: 1 note in common with I, has a leading tone.
vi consists of 1-3-6: 2 notes in common with I, doesn't have a
leading tone.
viio consists of 2-4-7: No notes in common with I, has a leading
tone.

There are also differences based on which notes are in the chord, as 1 is more stable than 5, 3 and 5 want to move to 1 but are stable, 2 and 7 want to move to 1 and are unstable, 4 wants to move to 3, and 6 wants to move to 5, but those differences are subtle, so we won't discuss them - just be aware that they are a thing.
We could also categorize those chords into 3 different groups based on their tension: Tonic (stable), Subdominant (some tension, doesn't have a real strong sense of resolution when resolved) and Dominant (tense, has a strong sense of resolution when resolved. I iii and vi are T, ii and IV are SD and V and viio are D.
In functional harmony, T can move to SD or D, SD can move to T or D, and D can move to T. So in all of those progressions, we can see that kind of movement:

I-IV-V = T-SD-D
I-iii-IV-V = T-T-SD-D
I-ii-V-I = T-SD-D-T
I-IV-ii-V-I = T-SD-SD-D-T
I-vi-ii-V-I = T-T-SD-D-T
I-iii-vi-ii-V-I = T-T-T-SD-D-T

And for your other question - There isn't a rule about how long a chord should last, it can last a beat, half a beat, 4 beats and so on... But mostly when talking about pop songs which are usually going to be in 4/4, it will probably last 4 beats (a measure).
Comment: So a chord starts on a T then SD, then D and finally T. Some websites talk about Supertonic, Mediant, submediant, subtonic, where are all these?? Do they exist in the real world or they are just theoretical concepts.
Comment: Those are just names for the actual degrees (Supertonic=ii, mediant=iii...). You will never use these names, and they are only relevant when talking about diatonic chord progressions. Those are purely theoretical names. T, SD and D, however, are terms for describing a chord's tension, and can be heard (however there is more of a spectrum instead of just three groups).
Comment: T->SD,D. SD->T,D. D->T. Because of the concept of tension and release in music. D doesn't go to SD because it wouldn't sound as good as moving to T (however, that isn't an unbreakable rule - just regarding functional harmony).
Comment: @dudwhuknowstheory - in every 12 bar blues I've ever played, V goes to IV (bars 9, 10).
Comment: My answer regards functional harmony, and 12 bar blues is modal - not diatonic, or functional. Also, I said that is not a rule, but more of a guideline telling us about moving tension and release. So the 12 bar blues is simply irrelevant (and is about the circle of fifths - the closer two chords of the same type are on the circle of fifths - in the case of the 12 bar blues in A: A, D and E, and are all dominant seventh chords - the "better" they will sound).
Comment: Will the chord quality remain same irrespective of what chords and scales are i.e. T=1st & D= 5th. Will this also hold true ( T->SD,D. SD->T,D. D->T.) for minor scales?? I also found when we add a seventh to a 5th chord it becomes a dominant chord in a ( Major scale, Melodic minor and Harmonic minor scale) and in a minor scale it becomes (min 7th chord) - this further adds tension to the existing 5th chord, is it true that 7th adds tension?? So if we add chords from other scales, that should create more tension?is it possible?if yes then how?Can we identify a scale from a chord?
Comment: Based on the way of analyzing chords I've given, we see that v has 1 note in common with the tonic chord, and doesn't have a leading tone - but its individual notes give it a higher tension than the IV who also has 1 note in common and no tonic chord. That is why people usually make the V major in a minor context - because it is more tense and more pulling than the minor version. The 7th of a V7 chord adds even more tension because it is another note that isn't a scale degree, and every note in that chord (apart from the root) wants to move to a stable degree.
Answer: By listening to many pieces, you will understand that while any chord can and does follow and precede any othe chord in a diatonic piece, certain tried and tested patterns occur time and time again. Check out '12 bar blues' as a format that never seems to fail!
You asked about I IV V. Put simply, I is the home chord, analogy - where a journey starts. A very common, because it sounds acceptable to us, change is up a fourth. So a chord that can follow I is IV. Now, we're about as far from I as is possible. How to get back? Use the fourths trick again, and this time, the jump is a fourth from V to I. We're home again. That's a very short journey, but it's taken us from home, back again, in a natural sounding way.
Any of the diatonic chords will fit anywhere, but some do sound more like they're meant. Take the jazz 'ii>V>I. That again uses the moving a fourth. In C, ii is Dm, up a 4th to G, up another to C. So, so common. It also works with non-diatonic chords. In C, play a bar of E (maj), up 4 to A, up 4 to D, you can see where it's going to end!
Use your ears, and try any diatonic chord followed by another. You'll very soon hear what sounds good and not so good. The 'rules' are based on these premises. Incidentally, Roman capitals usually represent major chords (with a maj 3), while lower case show minors. The dim is lower case as it has that m3 also.


How do I make translatable views?

Question: I want to have the front page view with my own title, but if I add it, it is shown for all the languages.
Is it possible to have a different title for each enabled language?
Answer: Enable the module "Configuration Translation" and then you get a tab "Translate view":
<code>/admin/structure/views/view/[view]/translate
</code>
where you can add translations and edit the translated view.
The title is in:
Displays -> Master Display Settings -> [View] Default Display Options -> Display title

How do I make translatable views?


Abertura de Modal usando links diferentes para uma mesma linha da tabela

Question: Tenho a seguinte tabela:

         Produto
         Cliente

           Banana
           José da Silva

Como deu para perceber, na tabela possuo 2 links na mesma linha, um link deve mostrar através de um modal os dados do produto e o outro mostra os dados do cliente.
Para mostrar o modal do produto eu usei o seguinte script Jquery:
$(document).on("click","#tabela td a",function(e){
    e.preventDefault()
    var idproduto= $(this).parent().attr("id");
    $('.modal-body').load('dados_produto.php?id='+idproduto);
});

Até ai tudo funciona perfeitamente, o meu problema é: como fazer para criar uma nova interação com Jquery para o link do cliente abrir um modal para exibir o arquivo 'dados_cliente.php?id=+idcliente'?
Comment: [Nesse link](https://pt.stackoverflow.com/questions/38744/enviar-informa%C3%A7%C3%B5es-do-link-para-uma-modal?rq=1) contém uma resposta bem semelhante para o que você precisa.
Comment: Nossa... Não consegui fazer funfar através do post recomendado
Answer: Consegui resolver da seguinte forma:
No link de produtos, o id vai com um nome que indica a coluna referente a informação e concatento com um separador '-' mais o valor do id onde o usuário clicou, ficando assim:
'cliente-1' ou 'produto-5'
No Jquery eu dou um split e separo o campo que identifica o a posição na tabela e o valor do id clicado.
$(document).on("click","#tabela td a",function(e){
    e.preventDefault()
    var linkClicadoComId = $(this).parent().attr("id").split('-');
    var tipo = linkClicadoComId[0];
    var id = linkClicadoComId[1];

    if(tipo == 'produto'){
        $('.modal-body').load('dados_produto.php?id='+id);
    }
    if(tipo == 'cliente'){
        $('.modal-body').load('dados_cliente.php?id='+id);
    }
});

Ficou fera, quem quiser tá ai a resolução.


MsMpEng.exe high CPU usage on Windows Server 2012

Question: We have a Windows Server 2012 installation that we use as an internal web server. Most HTTP requests are very slow on this machine (about 15 seconds for a simple ASP.NET WebAPI request). We noticed that during a request, the process MsMpEng.exe's CPU usage is going to 50-90%.
MsMpEng.exe is Microsoft's Anti-Malware executable, included in Windows Defender, Forefront and Security Essentials. However, none of those products is installed on our server.
Where can we configure the Anti-Malware component of Windows Server 2012?
Comment: start -> type defender. Any luck with that?
Comment: Nope, there isn't any Defender entry there.. If I enter `Defender` and press `Enter`, Windows Search shows `No results found for your search`
Answer: We analyzed the problem with Sysinternals ProcessMonitor, where we saw that MsMpEng.exe consumes much CPU time analyzing the log files of our web application (written by NLog).
Since we could not find a GUI to exclude the log files from MsMpEng.exe's real-time monitoring, we added it using regedit.exe.
The solution was to create a DWORD entry at
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows Defender\Exclusions\Paths`

where the key of the entry is set to the full path of our log files (C:\inetpub\wwwroot\webapp\logs), and leaving the DWORD value at 0x00000000.
Comment: How did you manage to find which files "MsMpEng.exe" is trying to scan? I'd like to make exclusions as well :(
Comment: This is an old answer and we already got UI for this: Start menu --> Virus & thread protection --> Manage settings -> Add or remote exclusions. Also it is possible to provide exclusions with policy editor.
Comment: Nice answer, and I forgot about the powerful Sysinternals tools. I edited your answer to add the official link.
Comment: @RomanR. I can't find Start menu --> Virus & thread protection --> Manage settings -> Add or remote exclusions on my windows 2012. Are you sure?
Answer: You might find it under Endpoint Protection or System Center Endpoint Protection, there you can set excluded filetypes and such under settings.


How to delete multiple hdfs directories starting with some word in Apache Spark

Question: I have persisted object files in spark streaming using dstream.saveAsObjectFiles("/temObj") method it shows multiple files in hdfs.
temObj-1506338844000
temObj-1506338848000
temObj-1506338852000
temObj-1506338856000
temObj-1506338860000

I want to delete all temObj files after reading all. What is the bet way to do it in spark. I tried
val hdfs = org.apache.hadoop.fs.FileSystem.get(new java.net.URI("hdfs://localhost:9000"), hadoopConf)
hdfs.delete(new org.apache.hadoop.fs.Path(Path), true)

But it only can delete ane folder at a time
Comment: Is it possible to use wildcards `*` in the path when deleting?
Comment: I tried it but it dosen't work
Answer: Unfortunately, delete doesn't support globs.
You can use globStatus and iterate over the files/directories one by one and delete them.
val hdfs = FileSystem.get(sc.hadoopConfiguration)

val deletePaths = hdfs.globStatus(new Path("/tempObj-*") ).map(_.getPath)

deletePaths.foreach{ path => hdfs.delete(path, true) }

Alternatively, you can use sys.process to execute shell commands
import scala.sys.process._

"hdfs dfs -rm -r /tempObj*" !

Comment: Thank you very much. It works for me but your last line need modification fs to hdfs


Finding the polynomial when given a divisor and the remainder

Question: Find a polynomial $p(x)\in \mathbb{Z}/5\mathbb{Z}[x]$ such that, when we divide $p(x)$ by $x+1$ we obtain a remainder of $1$, and when we divide $p(x)$ by $2x-1$ we obtain a remainder of $2$.  Explain how you found that polynomial.
Comment: This appears to be an application of the Chinese Remainder Theorem I believe.
Comment: You know that value of $p(x)$ at $x=-1=4$ as well as at $x=1/2=3$.  What does Lagrange interpolation tell you?
Comment: @Jyrki Lagrange is overkill since here the solution is obvious - see my answer.
Answer: The problem can be rephrased as: Find some $p(x)$ such that the following system of congruences is satisfied:
$$p(x) \equiv 1 \textrm{ mod }(x+1)$$
$$p(x) \equiv 2 \textrm{ mod }(2x-1)$$
The Chinese Remainder Theorem gives us a way to find solutions to a system of congruences like this.  When we want:
$$p(x) \equiv a_1 \textrm{ mod }q_1(x)$$
$$p(x) \equiv a_2 \textrm{ mod }q_2(x)$$
$$...$$
$$p(x) \equiv a_n \textrm{ mod }q_n(x)$$
The following equation gives a solution:
$$p(x) = a_1 \cdot m_1(x) \cdot y_1 + a_2 \cdot m_2(x) \cdot y_2 + ... + a_n \cdot m_n(x) \cdot y_n $$
Where $$m_i(x) = \frac{q_1(x) \cdot q_2(x) \cdot ... \cdot q_n(x)}{q_i(x)}$$.
and $y_i$ is the inverse of $m_i(x)$ mod $q_i(x)$.
When we only have two congruences to satisfy, this becomes much more simple to state:
$$p(x) = a_1 \cdot q_2(x) \cdot y_1 + a_2 \cdot q_1(x) \cdot y_2$$
We know the following: $$a_1 = 1$$ $$a_2 = 2$$ $$q_1(x) = x+1$$ $$q_2(x) = 2x-1$$
All that remains is to find the inverses ($y_1$ and $y_2$).  To do this we can use the Euclidean Algorithm:
$$2x-1 = 2(x+1) - 3$$
$$3 = 2(x+1) - (2x-1)$$
Multiplying by 2 and reducing mod 5 we get:
$$1 = 4(x+1) +3(2x-1)$$
So we can see that $y_1 = 3$ and $y_2 = 4$
Putting this all together we have:
$$p(x) = 1 \cdot (2x-1) \cdot 3 + 2 \cdot (x+1) \cdot 4$$
$$p(x) = 6x-3 + 8x+8$$
$$p(x) = 14x + 5$$
And then reducing mod 5 we have:
$$p(x) = 4x$$
It is easy to check that this polynomial leaves the desired remainders when divided by the given polynomials.
Comment: According to your answer  $p(-1) \neq 1$ where as in the question it is give $ p(-1) = 1$
Comment: @Akshaj Bansal We are working in $\mathbb{Z}/5\mathbb{Z}[x]$, so $p(-1)=-4=1$.
Answer: Hint$\ \bmod 5\!:\ \begin{align} p(1)\,\equiv\, -1\\[.2em] \smash[b]{p(\underbrace{1/2}_{\textstyle -2})}\,\equiv\, 2\\ \end{align}\ $ has $\,\ \bbox[5px,border:1px solid #c00]{p(x) \equiv -x}\,$  as an obvious solution.
$\phantom{.}$
Comment: *Generally* we can use [CRT / Lagrange / mod distributivity](https://math.stackexchange.com/a/2021696/242) $\ \ \ $