EXCLUIR linha específica de uma tabela com PHP e AJAX

Question: Olá! Estou com o seguinte problema:
Uma agenda de contatos que, uma das opções existentes é a de EXCLUIR um contato.
É exibia uma TABELA com os contatos, ao clicar em 'pesquisar'.
Em cada linha da tabela existe um botão "Excluir". Entretanto, quando eu clico neste botão, é excluído somente a primeira linha da tabela e não a linha que eu escolhi deletar.
Segue abaixo o exemplo:
Código em php para pesquisar um contato:
if (isset($_GET["txtnome"]))
{
    $nome = $_GET["txtnome"];

    // Conexao com o banco de dados
    $host = "127.0.0.1";
    $port = "5432";
    $db = "agenda";
    $user = "postgres";
    $pass = "postgres";

    $conexao = new PDO("pgsql:host=$host;dbname=$db;user=$user;password=$pass") or die("Erro na conexão!");

    // Verifica se a variável está vazia
    if (empty($nome)) {
        $sql = "SELECT * FROM contato";
    } else {
        $nome .= "%";
        $sql = "SELECT * FROM contato WHERE nome like '$nome'";
    }
    sleep(1);
    $result = $conexao->query($sql) or die("Erro na consulta!");
    $contact = $result->fetchAll();

    // Verifica se a consulta retornou linhas
    if (!empty($contact)) {
        // Atribui o código HTML para montar uma tabela
        $tabela =
        "

                            NOME
                            TELEFONE
                            CELULAR
                            EMAIL
                            ID
                            OPÇÃO

";
        $return = "$tabela";

        // Captura os dados da consulta e insere na tabela HTML

        foreach ($contact as $row) {
            $return.= "" . utf8_encode($row["nome"]) . "	";
            $return.= "" . utf8_encode($row["telefone"]) . "	";
            $return.= "" . utf8_encode($row["celular"]) . "	";
            $return.= "" . utf8_encode($row["email"]) . "	";
            $return.= "" . utf8_encode($row["id"]) . "	";
            $return.= "" . "<input type='button' class='btn btn-danger btn-sm' value='Excluir' onclick='excluir();'/>" . "	";
            $return.= "
";
        }
        echo $return.="

";
    } else {
        // Se a consulta não retornar nenhum valor, exibe mensagem para o usuário
        echo "Não foram encontrados registros!";
    }
}

Função JavaScript para excluir a linha da tabela:
function excluir(){

    swal({
      title: 'Tem certeza que deseja excluir este contato?',
      text: "Você não poderá reverter isso!",
      type: 'warning',
      showCancelButton: true,
      confirmButtonColor: '#3085d6',
      cancelButtonColor: '#d33',
      confirmButtonText: 'Sim, exclua!'
    }).then((result) => {
      if (result.value) {

        var elemento = document.getElementById("deletar").innerHTML;
        document.getElementById("deletar").value = elemento;

        var id = document.getElementById("deletar").value;
        var resultado = document.getElementById("result");

        var xmlreq = CriaRequest();

        xmlreq.open("GET", "contato.php?deletar=" + id, true);

        // Atribui uma função para ser executada sempre que houver uma mudança de ado
        xmlreq.onreadystatechange = function(){

        // Verifica se foi concluído com sucesso e a conexão fechada (readyState=4)
        if (xmlreq.readyState == 4) {
            // Verifica se o arquivo foi encontrado com sucesso
            if (xmlreq.status == 200) {
                resultado.innerHTML = xmlreq.responseText;
                document.getElementById("hidden").style.display = "none";
                swal(
                  'Deleted!',
                  'Your file has been deleted.',
                  'success'
                )

            }else{
                resultado.innerHTML = "Erro: " + xmlreq.statusText;
            }
        }
    };
    xmlreq.send(null);
      } //if do result.value
    }) //swal principal
} //funcao excluir

Código em php para excluir o contato do DB:
if (isset($_GET["deletar"])) {

    $id = $_GET["deletar"];

    // Conexao com o banco de dados
     $host = "127.0.0.1";
     $port = "5432";
     $db = "agenda";
     $user = "postgres";
     $pass = "postgres";

     $conexao = new PDO("pgsql:host=$host;dbname=$db;user=$user;password=$pass") or die("Erro na conexão!");

     $result = $conexao->prepare("DELETE FROM contato WHERE id = :deletar");
     $result->bindValue(':deletar', $id);

     sleep(1);

     if (!($result->execute())) {
         echo "Erro ao excluir contato :(";
     }
}

Answer:
Entretanto, quando eu clico neste botão, é excluído somente a primeira linha da tabela e não a linha que eu escolhi deletar.

Sua página está tendo vários elementos com o mesmo id. Sendo assim, sua função excluir() vai pegar o id do primeiro elemento encontrado.
1) Corrigir a parte que "passa" o id a ser deletado. Repare os comentários.
foreach ($contact as $row) {

    // ...

    // Por estar dentro de um foreach, vários elementos receberão o mesmo id "deletar"...
    // $return.= "" . utf8_encode($row["id"]) . "	";
    $return.= "" . utf8_encode($row["id"]) . "	";
    // Então, vamos passar o ID como parâmetro para a função excluir()! Veja:
    $return.= "" . "<input type='button' class='btn btn-danger btn-sm' value='Excluir' onclick='excluir(".utf8_encode($row["id"]).");'/>" . "	";
    $return.= "
";
}

2) Corrigir a função excluir():
function excluir(id){ // Agora vai recebe o ID como parâmetro

    // ...

        // Comentar aqui pra não sobrescrever a variável id:
        //var id = document.getElementById("deletar").value;

    // ...

}

Agora deve funcionar... Repare que o restante do código permanece o mesmo. Só postei a parte que interessa corrigir...
Comment: Muito obrigado, cara! Deu certo aqui


reverse proxy and load balance server architecture

Question: While creating a load balanced and reverse proxy based architecture, how would the two be placed?
Is this the correct architecture?
First LB server, then proxy: - When client hits a URL, it is basically a load balancer, which has multiple reverse proxy servers sitting behind it. It calls a reverse proxy server, which in turn gathers data from multiple servers and afulfills the request
Is there a possibility of First proxy server then LB server?
Or am I totally missing the plot?
Answer: As Jesper mentioned, you need more details.
What is the role of the reverse proxy in this situation?  Is the goal performance, high availability or both?
Some load balancers do URL filtering, so if the proxy is just routing traffic (not caching), then you may not need a proxy at all.
How much of the traffic can be cached?  Where are your bottlenecks?
Lately, I've been using this stack with good results for a PHP based application:
HAProxy --> Varnish --> Nginx --> PHP-FPM --> MySQL/NFS server

What we found is about 70% of all requests can be served from the Varnish cache.  We considered putting Varnish out front but a single Varnish server cannot handle the load.  So we would need to load balance anyway.
This creates a single point of failure at the LB level, but our client is fine with it as we can spin up a new instance in about 5 minutes.  They are willing to risk 5-10 minute outage rather than have a more complicated infrastructure with dual HA-Proxy servers.
Each usage case varies and only through testing can you find the best solution that fits the budget.
Comment: What is the role of Nginx is this case? Ssl? And what can it do that haproxy that is in the front cant do? Thank you!
Comment: +1 As mentioned I do not have enough points to vote you up, thanks for the tips..you guys rock!
Answer: Here's what I generally do.
Have 2 varnish servers out front with a shared IP via keepalive in case one dies. as my reverse proxy.
Behind it (or on the same server) sit haproxy doing the load balancing.
Varnish also supports load balancing to backends but you don't get the nice stats or control as you do with haproxy. If you go with a hardware load balancer.. chances are that would be up front first since that might also be your firewall.
In the end.. it really depends on how you want to lay it out.
Comment: +1 I cannot vote you up since I dont have enough rep, but thanks for the tips! I will take a look at haproxy
Answer: It depends on your more detailed and specific needs, so it's not really possible to answer based on the info you have given. Both your suggestions are valid and good solutions in certain cases.
As always ... profile your live production load, and benchmark the appliances/the software you're working with for proxying and load balancing.
In general:

If you need SSL, then much will depend on whether the LB or proxy handles SSL best. Generally, you'd want to handle SSL on the edge of your network, i.e. on the first server(s).
If you need multiple proxy servers to handle the load, that would push towards LB --> proxie(s)  -->  LB  --> App Servers (or using crude DNS Round Robin to coarsely distribute load to multiple proxies).
If you need consistent hashing in front of your proxies, then that would push towards LB --> proxie(s)  -->  LB  --> App Servers and a load balancer which supports consistent hashing.
If a single proxy can handle your load, then proxy -->  LB  --> App Servers is simplest. Some proxies, like Varnish, even have a basic load balancer built in.

Willy Tarreau, author of the excellent HAProxy, has written a nice article about common front end load balancing / SSL offload / proxying architectures.


How can I add numbers to array simply using unshift()?

Question: How can I add numbers to an array upside down using 'unshift()'??
I'd like to get an array = {2018, 2017, 2016, 2015, ... , 1999}.
because '2018' is this year and '1999' is the debut year of a singer I like.
And that's why I'm starting with '1999' which is array[0].
Here is my code using 'push()'. I think it's too long and stupid. I believe there is something I can't come up with. Thank you.

Comment: If your code works and you want to improve it, this question is not really suited for this site. I suggest you go to [Code Review SE](https://codereview.stackexchange.com/)
Comment: If you want to create an array of numbers listing all numbers between two numbers, you'll have to create a loop. `unshift()` can't just guess the numbers to fill.
Comment: @Zenoo that's true, but with unshift there would be no reverse.
Comment: @Federico klez Culloca Actually, it works. I just wanted to make it shorter and better. 'Code Review SE' is a web site for practicing?
Comment: Nope, it's a website to have your code reviewed by other developer who will give you suggestions on how to improve it.
Comment: Oh, I see. really nice for me to know that. thank you so much.
Answer: Something like this?

var years = [1999];
var i = 0;
var n = new Date().getFullYear() - years[i];
while (i < n) {
  years.unshift(years[0]+1);
  i++;
}
console.log(years);

This adds the next year to the beginning of the array with unshift() like you wanted. This removes the need to reverse the array like you did.
Noteworthy here is that we always unshift the value of years[0]+1 since the the array is reversed making the largest number always at index 0.
Comment: You don't really need the counter, you could set n as the current year and do it while (years[0] < n).
Comment: Thanks for the answer. it's helpful :)
Comment: @maraca yeah, indeed.
Answer: Why do you even need an array at all?

var currentYear = new Date().getFullYear();
for (var year = currentYear; year >= 1999; year--){
  document.write('
'+year+'
');
}
Answer: If I modify your code to generate years in array. That should be like this with initial year i.e debutYear

this.years = function(debutYear) {
            var currentYear = new Date().getFullYear(), years = [];
            while ( debutYear <= currentYear ) {
                    years.push(debutYear++);
            }
            return years.reverse();
    }

console.log(years(1999));
Comment: This will require `return years.reverse()` to fully meet the OP's requirement.
Comment: Edited as per your suggestions. Thnx :)


Examples of two different maximal atlases given the abstract manifold

Question: I am very confused by the notion of the maximal atlas.
Given some separable metrizable $C^r$  manifold $\mathcal{M}$, from what I read from the internet and the book, there might be more than one maximal atlases covering it, i.e. they are not compatible with one another, and they have different $C^r$ structures.
Can anyone give me some clear explicit example(s)? (Due to the definition of maximal atlases, of course, you just need to provide non-compatible beginning atlases rather than the maximal ones).
I would really appreciate it.

Here's the definition of compatibility from the material I read:
Suppose we have two coordinate patches in $M$, $F_i:U_i\rightarrow V_i\subset \mathbb{R}^n$, i=1,2. The coordinate patches are $C^r$-compatible (where $r\in \mathbb{N}$ or $r=\infty$) if

Either $U_1\cap U_2= \emptyset$,
or if $U_1\cap U_2 \neq \emptyset$ but $F_{12}:=F_1\circ F_2^{-1}: F_2(U_1\cap U_2)\leftrightarrow F_1(U_1\cap U_2)$ is a bijection of $C^r(F_2(U_1\cap U_2);\mathbb{R}^n)$ and
$F_{21}:=F_2\circ F_1^{-1}: F_1(U_1\cap U_2)\leftrightarrow F_2(U_1\cap U_2)$ is a bijection of $C^r(F_1(U_1\cap U_2);\mathbb{R}^n)$
Answer: Consider the real line with a single coordinate patch given by $F_1: x\mapsto |x|^{t-1}x$ where $t$ is any real number $> 1$. You can verify that $F_1$ is a homeomorphism whose inverse is not differentiable at $0$. It is incompatible with the usual differential structure given by the coordinate $F_2: x \mapsto x$, because at the point $0$ the map $F_2 \circ F_1^{-1}$ is not differentiable. This shows that there are at least uncountably many smooth structures on the real line; you can generalise the method to generate uncountably many smooth structures from any given smooth manifold.
Comment: You can even make it slightly wilder: Choose $F_1$ such that it isn't differentiable, just continuous. Then $F_1\circ F_2^{-1}$ certainly isn't differentiable.
Comment: Almost - you would need $F_1$ to be a homeomorphism for it to qualify as a chart.
Comment: Okay... So if I am understanding this example correctly, both (particularly the first one) will lead to a $C^\infty$ atlas, because $F_1\circ F_1^{-1}=$Identity, which is of $C^\infty$, that correct?  Actually, what I am trying to ask is that do you mean "smooth" by $C^\infty$?
Comment: Yes by smooth I mean $C ^ \infty$. And yes both $(\mathbb{R},F_1)$ and $(\mathbb{R},F_2)$ are atlases for the real line.


How can I translate Olivero default search string?

Question: In the default theme for Drupal 9 (Olivero) I have the following string in my search box field:

Search by keyword or phrase.

I have tried to change it by going to admin/config/regional/translate (and searching search) and also admin/config/regional/config-translation but nowhere have I found where to change it.
How to change Olivero default search string?
Comment: I don't fully understand where you are stuck, whether with translation itself or with this string in particular.
Answer: It is a translatable string so translation tools should work.
Alternatively you could alter the search_block_form or search_form form (you did not specify which), and change $form['keys']['#attributes']['placeholder'] or $form['basic']['keys']['#attributes']['placeholder'], respectively.
Comment: I don't know to which translation tool you referred. About using a hook, as a non PHP programmer I prefer not to touch the PHP. I think I'll use JavaScript in the end...
Answer: There is nothing special about this string.  Here are the exact steps to translate it.

Ensure the Search and Interface Translation modules are enabled at /admin/modules.
Ensure the search block is set to be shown at /admin/structure/block.
Visit a page with the search block.  If you never visit a page with the search block, the string will not be generated and will thus not be available for translation.
Go to /admin/config/regional/translate and search for "Search by" (case sensitive).  The string will appear for translation.

Again, this process is the same for all strings. The most important point is that you need to view the string once as a user for it to be made available for translation.
Comment: Thanks, I actually made a search on the phrase `search` alone but it didn't yield the right result because `Search by` is case sensitive here.


Finite Calculus on undefinded values -- Concrete Mathematics

Question: I have been reading Concrete Mathematics by Donald Knuth.  Upon reading chapter 2 on page 29, I came across the following sum : $H_n=1+\frac{1}{2}+\frac{1}{3}+...+\frac{1}{n}=$$\sum_{k=1}^n \frac{1}{k}$.
From this I deduce that $H_n$ is defined for any integer $\geq 1$.
However, on page 56, we have the following:
$\sum_{}^{} xH_x \delta x = \frac{x^{\underline2}}{2}H_x - \frac{x^{\underline2}}{4} + C$ and that $\sum_{0}^{n-1} kH_k = \sum_{0}^{n} xH_x \delta x =\frac{n^{\underline2}}{2}(H_n - \frac{1}{2})$.
That is, $\frac{x^{\underline2}}{2}H_x - \frac{x^{\underline2}}{4} + C \bigg|_{0}^{n} = \frac{n^{\underline2}}{2}(H_n - \frac{1}{2})$.
But this last line requires us to compute $(\frac{n^{\underline2}}{2}H_n - \frac{n^{\underline2}}{4} + C) - (\frac{0^{\underline2}}{2}H_0 - \frac{0^{\underline2}}{4} + C)$. But $H_0$ is not defined.  So how can we correctly compute this last line?
Comment: One can even [define](https://en.wikipedia.org/wiki/Harmonic_number#Special_values_for_fractional_arguments) $H_n$ for $0\le n\le 1$, and from there for other fractional values for $n$.
Comment: I don't think I am good enough at mathematics yet to understand what is happening in this link. But thank you.
Answer: Actually, there is a natural way to define $H_0$ according to the definition of $H_n$.  A summation like $\sum_{k=1}^0 \frac{1}{k}$ makes sense: you are adding up $\frac{1}{k}$ for all values of $k$ such that $1\leq k\leq 0$.  There are no such values of $k$, so you are adding up no numbers.  When you add up no numbers, you get $0$, so $H_0=0$.
Comment: No, it has nothing to do with that.  We never need to consider $\frac{1}{0}$, because $k=0$ does not satisfy $1\leq k\leq 0$.
Comment: Just to make sure, we are allowed to say that $H_0 = 0$ because $\frac{1}{0}$ is undefined?
Comment: Thank you for reminding me that mathematics is a literal art.


how can i export IntOrString from dhall kubernetes

Question: i want to import : IntOrString from dhall kubernetes,
https://github.com/dhall-lang/dhall-kubernetes/blob/master/1.19/types/io.k8s.apimachinery.pkg.util.intstr.IntOrString.dhall;
but i don't know how to import it?,
i have this code :
let kubernetes =
      https://raw.githubusercontent.com/dhall-lang/dhall-kubernetes/master/package.dhall
let Prelude =https://prelude.dhall-lang.org/package.dhall

Answer: You can either import it directly:
let IntOrString = https://raw.githubusercontent.com/dhall-lang/dhall-kubernetes/master/1.19/types/io.k8s.apimachinery.pkg.util.intstr.IntOrString.dhall

…

… or access it as a field of the kubernetes package:
let kubernetes =
      https://raw.githubusercontent.com/dhall-lang/dhall-kubernetes/master/package.dhall

in  kubernetes.IntOrString


Bottle framework caches my template even in debug mode

Question: There's a similar question on here, but the answers are over 2 years old and I can't get it to work.  If I'm missing something - please let me know.
Bottle.py caching templates despite being in debug mode
Whenever the browser points to 0.0.0.0:8080/16boxes, I need to prevent caching.  The Bottle docs say when in Debug mode, caching is disabled, but that isn't the case for me unfortunately.
Here is my hello.py code in question:
@route('/16boxes')
def send_static():
    response.set_header('Cache-control', 'no-cache, must-revalidate')
    return template (resource_path('16boxes.html'), globalVar0 = globalVar0)
run(host='0.0.0.0', port=8080, debug=True)

I open up terminal and run:  python hello.py
It doesn't cache when I run it on my Mac/Chrome - but when I use Windows and Internet Explorer - it uses a cached version.  How can I prevent this?
In my 16boxes.html, I even have the following in my :
<meta http-equiv="Cache-control" content="no-cache, no-store, must-revalidate">
<meta http-equiv="Expires" content="0" />
<meta http-equiv="Pragma" content="no-cache">

Comment: Does your application reload when you change files?
Comment: No, only when I clear my cache in my browser.
Answer: Your problem is that your JavaScript onload event doesn't fire when the page loads as a result of browser caching, jQuery's ready event was created for just this sort of issue.
Comment: Yes!  Using Jquery ready instead of load was the fix!  Edit your answer and I'll accept!
Comment: When I type "app = bottle.app()" I get "NameError: name 'bottle' is not defined.
Comment: add `import bottle` before that line
Comment: It's funny because I always had "from bottle import...stuff" so I assumed it was imported but I guess not!  Adding import bottle allowed bottle.app() to work - but still when I run it, it's loading a cached version of my HTML file.
Comment: The thing is - when my HTML page loads, I have a javascript function on my body tag -   I need this javascript function to fire for everything to work properly.  So it seems that when a cached version is loaded, that function never gets started.
Comment: Can you use jQuery? it will handle that for you with it's [ready event](http://api.jquery.com/ready/#fn) function


Hypothesis for differentiating under the integral

Question: I've been trying to understand when it is allowed to move a derivative inside the integral, especifically the requirements on the derivative of the function being integrated.
$$\frac{d}{dx}\int_a^bf(x,y)dy=\int_a^b\frac{\partial}{\partial x}f(x,y)dy$$
In some sources I find that it just requires that $\frac{\partial}{\partial x}f(x,y)$ be continuous in some neighbourhood while in others it is also required that there exists a function $g(y)$ such that $|\frac{\partial}{\partial x}f(x,y)|<g(y)$.
Can someone please explain to me if/when the second hypothesisis not necessary?
Comment: See [Leibniz integral rule](https://en.wikipedia.org/wiki/Leibniz_integral_rule)
Answer: The Dominated Convergence Theorem can be used to explain the second hypothesis. Let $f_n(x,y) = n(f(x+1/n,y)-f(x,y))$ which converges to the derivative $\partial_x f(x,y)$. If there exists a function $g(y)$ such that $|\partial_x f(x,y)|\leq g(x,y)$ and $g(x,y)$ is integrable in $y$, then the derivative (which is just a limit) can be interchanged with the integral. Usually it's easier to deduce a function $g(y)$ instead.
So if for each $x$, $\partial_x f(x,y)$ is continuous in a neighborhood of $y\in [a,b]$ that should suffice since you can just bound it by $g(x,y)$ being a constant function that's large enough.
Comment: Thank you. So just to clarify, the second hypothesis becomes necessary only  if you have a inproper integral, where you can't necessarily bound the derivative with a large enough function?


Survivor Function vs. Hazard Function

Question: I'm attempting to understand what the survivor and hazard functions describe under a non-traditional context. I have data comprising distances between successive points on a line ($1D$ vector):

Traditionally in my field, such data is fitted with a gamma-distribution in an attempt to describe the distribution of the points. For example, such data may yield a best-fit (MLE) gamma of $\alpha = 3.5$, $\beta = 450$. In plotting this distribution as a survivor function, I obtain:

And as a hazard function:

Under this context, what is each plot describing? It was my understanding that the hazard function could be understood as describing the probability of finding another point when a point already exists at $x(0)$ i.e. the further away from a pre-existing point you go, the higher the chance is that you will encounter another point. However, I am not entirely sure if this is correct.
With regards to the survivor function, I'm struggling to translate the typical descriptions of it (regarding time, populations etc.) into a more applicable understanding.
Any help would be greatly appreciated.
Answer: The theory about survival analysis usually regards time to event data, but I would say that the concepts can be transferred here without loss of generality.
You usually have (referring to the wiki article: wiki )
$S(t) = P(T>t)$ = survival function, which is basically the probability that the event has not happened yet at time t, where the event could be the death of a patient or the malfunction of some machinery and T is the random variable describing it.
$h(t) = lim_{dt \to 0} \frac{P(t \leq T<t+dt)}{dt*S(t)} = - \frac{S'(t)}{S(t)}$ is the hazard function and from wiki Suppose that an item has survived for a time t and we desire the probability that it will not survive for an additional time dt: this is the hazard function/rate.
You usually assume that $T_i$ time of death of patient i, is independent from $T_j$ time of death of patient j, for any $j \neq i$.
So i would Say that you could define a set of independent R.V. $X_i$ = distance where I occur in point i, measured from i-1 with $i=1,..,n$, where $n$ = number of points (not considering the first one).Being independent means that the distance between point $i$ and $j$ does not depend on the distances between any other 2 points.
Given this assumptions I'd say:
$D(x)=P(X>x)$ is your 'survival function'.
$h(x) = -\frac{D'(x)}{D(x)}$ is your hazard rate/function.

Survivor Function vs. Hazard Function


Computing the product $xy$

Question:
$$\dfrac{|x|}{2}=y$$
$$|y|-x=4$$

Compute $xy$

Here I would have been able to solve this question in such case there was only one unknown. I, however, cannot solve this type of questions when there are more than one unknown so let me at least share my thoughts with you.
$$|x| = 2y \implies  \dfrac{1}{2}|x| = y $$
Plugging into the second equation and we get that
$$\biggr |\dfrac{1}{2}|x|\biggr |-x = 4 $$
This is where I'm stuck.
Regards
Answer: Since $y=|x|/2$ you know $y\ge 0,$ so in the second equation $|y|$ can be replaced by simply $y.$
Answer: Hint: Since $$y=|x|/2\implies y\geq 0\implies |y|=y$$
so $$|x|= 2(x+4)\implies ...$$
Answer: $$y=|x|/2\implies y\geq 0\implies |y|=y$$
Also
$$|x|=2y, |y|-x=y-x=4$$
If $x$ is positive, then
$$x=2y$$
$$y-x=y-2y=-y=4\implies y=-4$$
which  contradicts the claim that $$y \geq 0$$
So $x\le0$, and
$$x=-2y$$
$$y-x=y-(-2y)=3y=4\implies y=4/3$$
$$x=-2y=-8/3$$
$$xy=-32/9$$

Computing the product $xy$


Django mass email - get single recipient address in every email template

Question: I'm sending email in Django:
...
recipient_list = ['firstname.lastname@example.com', 'email@example.com',]

mail = EmailMessage('Subject', 'content body', [email@example.com], recipient_list)
mail.send()

In the template I'm rendering I would like to extract single recipient like this.
template.html
...
This message was sent at {{ datetime_sent }} to address {{ recipient_address }}.

I don't want to pass recipient_list in every email in case of mass email, but rather a single recipient address. Is this possible?
Answer: You won't be able to customise this sort of information sending the same email to more than one recipient. What you will want is to use Django's mass mail function, see here:
https://docs.djangoproject.com/en/4.0/topics/email/#send-mass-mail
You can access the recipient as {{ mail.to }} in your template


Integral domain in a commutative ring.

Question: So I have a question where I'm not sure what assumptions I can make.
Here are the conclusions and information about the problem from previous parts of the question that I've completed.
$R$ is a commutative ring with unit. $R = (R,+_R,0_R,*_R,1_R) $
Let the set $S:= R\times R$ and give it the following two operations.

$(a_1,b_1)+_S(a_2,b_2) := (a_1 +_R a_2, b_1 +_R b_2)$.
$(a_1,b_1)*_S (a_2,b_2):= (a_1 *_R a_2, a_1 *_R b_2 +_R a_2 *_R b_1)$.

I've proven that:

$*_S$ is associative.
$S$ with the two operators is a commutative ring.

Where I'm having trouble is in this:

Let $(0,b)\in S$. Compute $(0,b)^2$. Is S an integral domain?

Am I correct in thinking that $(0,b)^2 = (0,b)*_S(0,b)$
I tried expanding this into:
$$(0,b)*_S (0,b)=(0*_R0,0*_Rb+_R0*_Rb)$$
$$=(0*_R0,b*_R(0+_R0)).$$
I'm confused if $(0*_R0=0)$ and $(0+_R0=0)$ since it's $0$ and not $0_R$.
What would be the way forward from here?
Also how can I use this to show if $S$ is an integral domain?
I'm new to abstract algebra so any help is appreciated.
Comment: They just write $0$ rather than $0_B$ because there is no other zero it could be in tje context and it gets tedious to have so many subscripts everywhere. Once you do the computation, the answer to whether this is an integral (!) domain should be clear from the definition.
Comment: No, those are elements of different rings so they are not equal. And you cannot use the multiplication from one ring on the elements of the other.
Comment: @TobiasKildetoft Don't you mean $0_S$ or $0_R$?
Comment: Right, sorry. Misread the symbol.
Comment: So would $0_S$ and $0_R$ be the same then such that $0_S *_R 0_S = 0_S$
Comment: @TobiasKildetoft So if they meant $0_S$ how would I do the computation? I also just noticed that since $S:=R \times R$ would that mean the two identities are similar? Trying to research a bit on direct product of rings to check this.
Comment: Actually I think I misunderstood, I think it should be $0_R$ they are referring to since in $(a,b)$ the $a$ comes from the first ring in the direct product and the $b$ comes from the second which in this case are the same. I'll see how I get on with that.
Answer: So the solution I got with the help of @TobiasKildetoft in the comments was that when they stated $(0,b)$ they meant $(0_R,b)$ for simplicity.
This means the computation becomes trivial and I find
$$(0_R,b)^2 = (0_R,0_R)$$
The definition of integral domain states there are no non-zero zero divisors.
Thus since $(0,b)$ is a non-zero element in $S$ and $(0,b)(0,b) = 0$, then S cannot be an integral domain.

Integral domain in a commutative ring.


sendmail user unknown - debian lenny

Question: My php's mail() function just stopped working a short while ago. It's started returning FALSE.
I am not much of a sysadmin so please forgive my ignorance.
I set my php.ini send_path option to: "sendmail_path = /usr/sbin/sendmail -t -i" and restarted apache.
Then, I learned how to test sendmail like so:

sudo /usr/sbin/sendmail -bv email@example.com
  email@example.com... deliverable: mailer esmtp, host example.com., user email@example.com

The example email is a real mail box.
I have also seen unknown user messages in the mail log.
Can anyone please help me debug this?
Comment: sendmail is a binary provided by all SMTP servers available for Linux systems. So you have to make sure that you are running [sendmail](http://www.sendmail.org) (the mail server) or [exim](http://www.exim.org) which also provides a sendmail binary. My guess is that you are running Exim, for it is installed by default on Debian systems.
Comment: The "user unknown" error message could indicate an SMTP email config problem.  Telnet to your mail server on port 25 and attempt to send to the problem email account.  You should get a specific SMTP error code.  Please update your question with the error.
Answer: It would help if you tell which mailer system you are using so you can see if the messages are stalled in the queue. Is it really sendmail, postfix, qmail, exit, what?
Meanwhile, if you want try a replacement function for the mail() function, you may want to try the smtp_mail() function which is a wrapper to use this PHP MIME e-mail message class. It takes the same parameters as mail but uses a SMTP server that you can configure to route the message.

sendmail user unknown - debian lenny


Maximum Log-Likelihood Estimation interpretation results

Question: I have fitted four distributions to a sample using MLE.
The following code (example) was used to calculate the MLE in python:
from scipy.optimize import minimize
from math import exp, log

def distr(d, a):
    result = (d/a**2)*exp(-d/a)
    return result

def log_L(a, diameters):
    result = -sum(log(distr(d, a)) for d in diameters)
    return result

res = minimize(log_L, [1], args=diameters)

Which returns an output such as:
     fun: 737.6689924048228
hess_inv: array([[  5.68951613e-06]])
     jac: array([[ -1.52587891e-05]])
 message: Desired error not necessarily achieved due zo precision loss.
    nfev: 164
     nit: 7
    njev: 51
  status: 2
 success: False
       x: array([ 0.37047972])

As far as I understand it, the value "fun" of my result of the optimize.minimize function returns the actual optimized max. log-likelihood. Subsequently the values i got for "fun" for my 4 distributions:
function1 = 580.05
function2 = 1293.68
function3 = 689.63
function4 = 737.67

I'm pretty confident, that the algorithm for the MLE is correct, since I also calculated the MLE for function 4 analytically and it resulted in the identical fitted parameter.
This may now sound like a stupid question, but do I have to take the smallest or the greatest value as my best fit? I suppose its the smallest value since I minimized my log-likelihood, but I'm not completely sure.
And on the other hand, when I then want to calculate the Akaike Information Criterion (AIC), computed in the following way:
AIC = 2*k - 2* "fun"
where k is the number of parameters and "fun" is the max. log-likelihood calculated above, would I take the greatest value as my best option?
I'd appreciate any answer you could give me very much!
Answer: Your question is a little confusing because you interchangeably talk about maximum likelihood estimation, and "minimizing the log-likelihood". The estimate that maximizes the likelihood also maximizes the log-likelihood. However, it so happens that many standard optimization algorithms by default want to minimize the function you give them. So to maximize the log-likelihood with such an algorithm, the solution is to pass it the negative of the log-likelihood. This also seems to be what you're doing in your code. This means that those "fun" values you're getting from your minimizing functions are not log-likelihoods, but negative log-likelihoods. Thus lower values are indeed "better" because they reflect higher likelihoods.
The formula for the AIC is:
$$
AIC = 2k - 2\ln(\hat{L})
$$
where $\hat{L}$ is the maximum likelihood for your model. Your "fun" value corresponds to $-\ln(\hat{L})$, not $\ln(\hat{L})$. So the way you're currently computing the AIC is wrong. It should be, in your notation: AIC = 2*k + 2*"fun", i.e. '+' instead of '-' (because "fun" is already the negative log-likelihood). Note that lower AIC values are better.
Comment: Thank you very much for your answer! Please excuse the confusion, but I just wanted to be correct by pointing out, that I minimized the log-likelihood and not the likelihood itself (which is of course (I think) everytime the case, since it makes the computation easier). But apparently I made things more complicated when I tried to be accurate ;). So, thank you once again very much for the clarification not only regarding the returned values of the minimization function but also regarding the AIC!


Integração AngularJS e Django forms para gravar dados

Question: Como vocês estão tratando a integração frameworks em JavaScript com os forms do Django?
Cenário de exemplo
Forms  de endereços aonde o existe um campo telefone (Muitos-para-UM), que no template ele é representado por um elemento adicionado dinamicamente, conforme a necessidade.
Estou usando o AngularJS para fazer isso, porém como gosto muito dos forms do Django, estou tentando fazer um Frankenstein, usando o AngularJS somente aonde necessário e recuperando os valores da submissão pelo objeto request do Django (exemplo: request.POST.getlist('telefones')).
No entanto, acho que isso não é uma boa prática, e é nesse momento que preciso de ajuda.
Comment: Não sei de onde exatamente surgiu a ideia de que você está criando um Frankenstein ao juntar Django com AngularJS, pois as duas tecnologias são integráveis: http://django-angular.readthedocs.org/en/latest/integration.html
Comment: @IvanFerrer o Frankstein está na maneira como ele está integrando os dois.
Comment: Então @IvanFerrer é exatamente como o Pablo Palácios falou, como testes esta tentando utilizar  o forms do Django e AngularJS ao mesmo tempo, "pedaço de um, pedaço do outro" no mesmo template.
Answer: Como você disse, isso é uma má ideia. Como sua pergunta é muito ampla, vou me restringir em responder apenas a questão do formulário.
O Django possui formsets que é uma funcionalidade que te permite submeter vários forms de um mesmo tipo de uma só vez.
Os formsets funcionam de forma bastante similar aos forms tradicionais e, nas views, você pode passar request.POST para uma instância dele que ele saberá como processá-lo.
Fiz um pequeno exemplo utilizando formsets para models, que funciona de forma análoga ao ModelForm:
models.py
class Pessoa(models.model):
    nome = models.CharField(max_length=255)

forms.py
from django.forms.models import modelformset_factory
from .models import Pessoa

PessoaFormSet = modelformset_factory(Pessoa, fields(('nome',))

Há várias maneiras de criar formsets, essa que apresentei é apenas um jeito breve. No entanto, é possível criar um formulário normal e passá-lo como parâmetro para a função que gera o formset. Dê uma olhada na documentação quanto a isso (links no fim da resposta).
views.py
from django.shortcuts import render, redirect
from .forms import PessoaFormSet
from .models import Pessoa

def adicionar_nomes(request):
    formset = PessoaFormSet(queryset=Pessoa.objects.none())
    if request.method == 'POST':
        formset = PessoaFormSet(request.POST)
        if formset.is_valid():
            formset.save()
            return redirect('/')
    return render(request, 'adicionar_nomes.html', {'formset': formset})

A única observação aqui é o parâmetro queryset passado para o formset. Por padrão, o django passa todos os objetos da classe determinada no modelsformset_factory, o que não é interessante caso você esteja criando um formulário para adicionar novos objetos.
adicionar_nomes.html
<form method="post">
    {% csrf_token %}
    {% verbatim %}

    {% endverbatim %}
    <button type="submit">Salvar</button>
</form>

Por fim, adicione sua mágica no template. Como o AngularJS utiliza tags com a mesma sintaxe dos templates do Django, para utilizá-las sem que o Django as processe antes da resposta ser enviada, coloque-as dentro do bloco verbatim.
Enfim, vale a pena dar uma boa lida na documentação do Django sobre formsets. O que apresentei aqui foi apenas uma pequena parte, mas o suficiente para evitar a criação de franksteins e o processamento direto do request.POST.
Documentações úteis do Django para sua questão
Formsets (em inglês)
Formsets para models (em inglês)
Tag de template verbatim (em inglês)
Comment: acho que é exatamente isso que estou buscando. Uma dúvida; no meu template eu continuo utilizando as tags do AngularJS e a do Django ? Isso não continuaria um Franksteins ? Um exemplo, no caso das mensagens de erros eu não continuaria ter que tratar individualmente para o Django e para o AngularJS ? Ou o Formsets ira empacotar tudo no final ?
Comment: O uso da tag verbatim foi criada justamente para permitir esse tipo de integração. Dê uma olhada na documentação sobre essa tag (adicionei na questão) tendo em vista que ela te permite criar blocos dentro dela mesmo, facilitando a integração.


Possible ways to fire HTTP requests involving various methods

Question: I'm interested in knowing various ways I can fire HTTP requests involving different Methods
Ex. HTTP request involving GET method can be fired in following ways

type URL in browser and hit enter
click a hyper link
submit a HTML form without specifying method attribute
submit a HTML form with method attribute "GET"

Only way of firing HTTP request involving POST method is to submit a HTML form with method attribute "POST"
I've already experimented on GET & POST using Java Servlets and am curious to test HEAD, PUT, DELETE, TRACE, OPTIONS using Java Servlets
Waiting for suggestions from Java/HTML/HTTP Gurus
FYI, I'm using Apache Tomcat 7.0.47 for experimenting all this stuff
Thanks in advance
Comment: Browsers usually don't send requests other than POST and GET, but some Javascirpt libraries can. If you are curious about REST, you shall consider clients other than browsers, consider that REST is a paradigm shift from HTTP based RPCs.
Comment: Hi Amir, is there no other way to send request other than GET/POST from a browser using simple HTML?

Thanks for reminding, we can use AJAX to send various methods.. But I'm just a beginner and want to simulate this using HTML, to start with
Comment: @JavaHopper No, [HTML currently does not support any requests other than GET and POST.](http://programmers.stackexchange.com/questions/114156/why-there-are-no-put-and-delete-methods-in-html-forms)
Comment: By the way, if you want to implement a RESTful webservice, don't reinvent the wheel! Use JAX-RS or similart things.
Comment: Thanks Sotirios for the link and Amir for your webservice example.
Answer: HTTP is a standard protocol. It has a standard request and response format. It is sent over TCP. You have HTTP servers listening on some port to respond to requests and HTTP clients sending those requests.
At the most basic level, an HTTP client can use a Socket and a SocketOutputStream to send the HTTP request. Take a look at this example. You simply write bytes (from the serialized request String) to the socket output stream. The HTTP server parses the bytes and if it is in the right format, dispatches some handler to handle the request.
There are a lot of Java libraries out there that simplify the task for you. For example, Java's HttpUrlConnection or Apache's HTTP Components.
On the client side, sending a HEAD, PUT, DELETE, TRACE, OPTIONS request is no different than a GET or POST, except in what the request line and body of the request might contain.
On the server side, implemented with Servlets, you simply make your class extend HttpServlet and implement the various doXxx() methods.
Comment: I tried submitting below form to send HEAD

....

I still see in Fiddler(HTTP Proxy/Debugging Tool) a GET being fired, rather than HEAD

Any specific reason?

Theoretically, I know that HEAD is only to get the response header info.. But it displays the output of service(ServletRequest, ServletResponse) method present in my servlet
Comment: @JavaHopper The entry point of all `Servlet` classes is the `service` method. If your class doesn't extend `HttpServlet` you will have to implement your own dispatching routines for handling the different http methods.
Comment: Sotirios, Digging a bit further, I wrote a class extending HttpServlet and I've overridden doHead(HttpServletRequest, HttpServletResponse) method..

And still I was getting "HTTP Status 405 - HTTP method GET is not supported by this URL"

Going by your earlier link, and looking at the fiddler trace, browser (IE-10) is sending GET request for methods other than POST..

May be my research can continue on this at time when I start exploring advanced technologies such as AJAX/Web Services
Comment: @JavaHopper As stated in the comments to your question, HTML doesn't support other methods, only GET and POST. You can use a different http client to test your servlet.


Differentiation Involving Determinant.

Question: I have to compute the following differentiation :
$$\frac{\partial}{\partial\sigma^2}\det[\mathbf X_{p\times n}'(\sigma^2 \mathbf I_{n}+\mathbf Z_{n\times q}\mathbf G_{q\times q}\mathbf Z_{q\times n}')^{-1}\mathbf X_{n\times p}],$$
where $\sigma^2$ is a scalar, $\det$ denotes determinant, $\mathbf I_{n}$ is a $n\times n$ identity matrix. Note that, $\mathbf X$, $\mathbf Z$, and $\mathbf G$ do NOT involve $\sigma^2$.
How can I do that?
Answer: We assume that $p\leq n$ and $rank(X)=p$.
Let $U=X^T(\sigma^2 \mathbf I_{n}+\mathbf Z_{n\times q}\mathbf G_{q\times q}\mathbf Z_{q\times n}^T)^{-1}X$ and $f(\sigma^2)=\det(U)$.
Then $\dfrac{\partial f}{\partial\sigma^2}=tr(\dfrac{\partial U}{\partial\sigma^2}adj(U))$ where
$\dfrac{\partial U}{\partial\sigma^2}=-X^T(\sigma^2 \mathbf I_{n}+\mathbf Z_{n\times q}\mathbf G_{q\times q}\mathbf Z_{q\times n}^T)^{-2}X$.

Differentiation Involving Determinant.


Impossible to have a triangle where trisectors of an angle trisect the opposite side

Question:
Prove that there cannot exist a triangle in which the trisectors of an angle also trisect the opposite side by using proportions.

Attempt
I have started the proof by way of contradiction.
Suppose we have a triangle $\Delta BAC$ with trisectors $AD$ and $A$E so that $D$ and $E$ are points lying in side $BC$. I also supposed that $D$ and $E$ trisect $BC$ such that $BD=DE=EC$. I then looked at triangle $BAE$ and observed that $AD$ bisects $\angle BAE$ and that point $D$ is the midpoint of $BE$ therefore $BD$ is both a median and an angle bisector.
From this I get stuck and do not know how to apply proportions. I know we proceed similarly when looking at $\Delta DAC$.
Answer: It is enough to show (through the sine theorem, for instance) that in the following configuration the red segments are longer than the blue ones:
Answer: You have a $\triangle{ABC}$. Let us say that side $BC$ is trisected by points $D, E$ such as $BD=DE=EC$. Note that $A_{\triangle{ACE}}=A_{\triangle{AED}}=A_{\triangle{ADB}}$ (equal bases, same height). Using area of a triangle formula this leads to $AC=AD$, $AE=AB$. But then $AE$ is a median and height of  $\triangle{ACD}$ and $AD$ is a median and height of  $\triangle{AED}$. We have two perpediculars from one point $A$ to side $BC$ that go to two distinct points. This is impossible.


Coordinates of small boxes

Question: I have the screen for different users like this:

In each screen there are small boxes each for a user. I have calculated width and height of each small box for different number users.
But now I am not getting how to get the coordinates of the boxes(top left point of the box).
The coordinate system starts from top-left of the screen that is the top left of the screen has coordinates as (0,0)
Can someone please help me out in this.
Sorry, my image is not displaying. I think it is because I dont have enought reps
Comment: Sorry, my image is not displaying. I think it is because I dont have enought reps.
Comment: Actually, I realised now that the number of smaller screens is not always a square number. What is the rule for how many smaller screens there are, as a function of $n_{\text{users}}$ ?
Comment: @MattiP. Why we need a rule for that?
Comment: Ah, so you want to calculate the coordinates, knowing the width and height of each smaller screen (instead of the number of users)?
Comment: I believe that you can calculate it yourself :) What are the coordinates of the top-left corner of user number 1? Well, $(0,0)$ of course. How about user number 2 ? Etc etc ...
Comment: @MattiP. I have still doubts like for user 3 the x coordinate is again 0 when number of small boxes are 3 or 4. But when number of boxes are from 5 to 9 then x coordinate of user 3 is (width of small screen) * 2
Answer: Let's assume that we know the dimensions of the large screen (width $W$, height $H$) and how many smaller screens there are in each direction (for example, for two users, we have a $2 \times 1$-grid). Let the number of screens in the $x$-direction be $n$ and the number of screens in the $y$-direction be $m$. So these are all the numbers that we know in the beginning.
The next step is to realize that the coordinates of the top-left corner of each of the smaller screens are multiples of $\frac{W}{n}$ and $\frac{H}{m}$. In other words, there are integers $a$ and $b$ so that the coordinates for each of these points is of the form
$$
(x,y) = \left(a\cdot \frac{W}{n} ,~ b\cdot \frac{H}{m}\right)
$$
The next question is, what are these multipliers $a$ and $b$ ? We can take a test case and just see if we see a pattern. Let's assume that we have eight users and then $n=m=3$. Then, for each of the users (we start numerating the user number $u$ from 0, so the "first" user has $u=0$), the multipliers are the following:

First user: $u= 0 \Rightarrow (a,b)= (0,0)$
$u= 1 \Rightarrow (1,0)$
$u= 2 \Rightarrow (2,0)$
$u= 3 \Rightarrow (0,1)$
$u= 4 \Rightarrow (1,1)$
$u= 5 \Rightarrow (2,1)$
$u= 6 \Rightarrow (0,2)$
$u= 7 \Rightarrow (1,2)$

Can you see the pattern here? It's really easy to see that, for the "$u+1$":th user,
$$
\begin{cases}
a = u \mod n \\
b = \lfloor \frac{u}{n} \rfloor
\end{cases}
$$
Here, $\text{mod}$ refers to taking the remainder in division, and $\lfloor ... \rfloor$ is the floor function. I think we're done here.

Coordinates of small boxes


Mudar a cor do texto no AlertDialog

Question: Estou criando um aplicativo de Android e gostaria de saber como eu faço para mudar a cor para vermelho da frase "Equação SPI" nesse AlertDialog ?
AlertDialog.Builder dlg = new AlertDialog.Builder(this);
    dlg.setMessage("Equação SPI \n\n"+
        "Calculos:\n\n" +
        "L1 vezes "+D1+" menos a L2.\n " +
        "L1 vezes "+D2+" menos a L3\n\n"+
        "Temos:\n\n"+
        valorA1+"X+"+valorB1+"Y+"+valorC1+"Z="+valorK1+"\n"+
        L2A+"X+"+L2B+"Y+"+L2C+"Z="+L2K+"\n"+
        D3A+"X+"+D3B+"Z+"+D3C+"Z="+D3K+"\n\n"+
        "Por fim L2 vezes "+D3+" menos a L3\n\n"+
        "Equações Escalonadas:\n\n"+
        valorA1+"X+"+valorB1+"Y+"+valorC1+"Z="+valorK1+"\n"+
        L2A+"X+"+L2B+"Y+"+L2C+"Z="+L2K+"\n"+
        L3A+"X+"+L3B+"Z+"+L3C+"Z="+L3K+"\n\n");

dlg.setNeutralButton("ok", null);
dlg.show();

Answer: Não use setMessage use setView e faça toda a formação por XML.
AlertDialog.Builder dlg = new AlertDialog.Builder(this);
dlg.setView(R.layout.um_layout_qualquer ou [view inflada dinamicamente]);

dlg.setNeutralButton("ok", null);
dlg.show();

Mudar a cor do texto no AlertDialog


preg_split não está quebrando as strings no array

Question: Não estou conseguindo utilizar a função preg_split() corretamente.
Estou tentando quebrar uma String num array() via regex mas não está rolando.
$string = "<:termo.9:><:termo.10:><:termo.11:>";
$res = preg_split("/(<:)(nome|termo)(.)(\d+)(:>)/", $string,-1,PREG_SPLIT_DELIM_CAPTURE);

O valor atribuído a $res é:
        Array (
          [0] =>
          [1] => <:
          [2] => termo
          [3] => .
          [4] => 9
          [5] => :>
          [6] =>
          [7] => <:
          [8] => termo
          [9] => .
          [10] => 12
          [11] => :>
          [12] =>
          [13] => <:
          [14] => termo
          [15] => .
          [16] => 10
          [17] => :>
          [18] =>
          [19] => <:
          [20] => termo
          [21] => .
          [22] => 11
          [23] => :>
        )

E na verdade gostaria de:
Array (
           [0] => "<:termo.9:>"
           [1] => "<:termo.10:>"
           [2] => "<:termo.11:>"
       )

Uma solução paliativa seria utilizar a seguinte pattern:
$res = preg_split("/(<:nome\.\d+:>|<:termo\.\d+:>)/", $string,-1,PREG_SPLIT_DELIM_CAPTURE);

E o $res sai:
Array (
          [0] =>
          [1] => <:termo.9:>
          [2] =>
          [3] => <:termo.12:>
          [4] =>
          [5] => <:termo.10:>
          [6] =>
          [7] => <:termo.11:>
          [8] =>
          [9] => <:termo.9:>
          [10] =>
        )

Mas se observar bem, as condições impostas são:
(<:nome\.\d+:>|<:termo\.\d+:>)

E as variações de nomenclaturas que poderei usar pode aumentar, como:

<:nome.2:>, <:text.4:>,<:codigo.5:>,etc

e desta forma o código não estaria "otimizado", digamos assim.
O que pode estar errado na pattern para que seja melhorada?
Comment: Já tentou colocando no 4º parâmetro `preg_split_delim_capture`?
Comment: @WallaceMaxters realmente retornou o `array` quebrando a String, mas quebrou cada condição do `pattern`. Ex: `Array([0]=>"<:",[1]=>"nome",[2]=>"."...etc)`
Comment: É praticamente impossível fazer isso utilizando o `preg_split`, porque, essa função, procura por referências específicas para dividir o código. É praticamente uma versão melhorada do `explode`, se posso assim dizer.
Comment: @Edilson acho que compreendi melhor agora. Talvez a solução que necessito não seja exatamente utilizar `preg_split` .
Answer: O problema não é bem o pattern, a função preg_split, procura pelo padrão para quebrar a string em partes, ou seja é similar ao explode, contudo, nela você pode definir um padrão de explosão que não se limita a mesma sequencia sempre.
Exemplo
$string = "teste_de_explosão-de-string";
$res = preg_split('/_|-/', $string); // vai explodir por '_' e por '-'

No seu caso seria uma captura e não uma explosão, e para isso pode ser usado o preg_match_all.
No seu caso
$string = "<:termo.9:><:termo.10:><:termo.11:>";
preg_match_all("/(<:(nome|termo)\.\d+:>)/", $string, $res);

Para recuperar os valores previamente agrupados, utilize:
foreach($res[1] as $id=>$val){
    $arr[] = $val;
}

print_r($arr);

Obs
Para capturar . literal em REGEX deve se escapar o mesmo \., pois ele representa qualquer coisa.
Comment: Ajudou em Partes o que necessito, pois realmente precisava de um `explode` utilizando uma condição *regex*. Mas a *patter* que instruiu acima melhorou minha situação.
Comment: Ah, o `preg_match_all` faz basicamente isto.
Comment: Faltou testar um pouco mais a função para compreende-la. Acho que é isso! Muito obrigado!
Answer: $foo = "<:termo.9:><:termo.10:><:termo.11:><:nome.2:><:text.4:><:codigo.5:>";

preg_match_all("/<:[a-z]+\.[0-9]+:>/s", $foo, $bar);

print_r($bar);

Retornará:
Array
(
    [0] => Array
        (
            [0] => <:termo.9:>
            [1] => <:termo.10:>
            [2] => <:termo.11:>
            [3] => <:nome.2:>
            [4] => <:text.4:>
            [5] => <:codigo.5:>
        )

)

Comment: Acho que é isso.. rsrs. Thanks!


Validate a BST in Python Leetcode

Question: I was attempting to solve Validate Binary Search Tree in Leetcode.
My approach was to do a inOrder Traversal , and add the data to a list. Now I will try to sort the list and compare with the original list to check if the BST is valid or not.
However while running the code in leet code even though my logic is correct and works properly in Jupiter Notebook, the same logic doesn't seem to work in Leetcode.
My code :
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    def isValidBST(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        if root:
            stk = self.inOrder(root,[])
            old_stk = stk
            print(old_stk)
            stk.sort()
            print(stk)
            for i,j in zip(old_stk,stk):
                if i!= j:
                    print('{} :: {}'.format(i,j))
                    return False
                else:
                     print('{} :: {}'.format(i,j))
        return True

    def inOrder(self,root,trav):

        if root:
            trav = self.inOrder(root.left,trav)
            trav.append(root.val)
            trav = self.inOrder(root.right,trav)
        return trav

STD OP for old_stk and stk:
[1, 5, 3, 4, 6]
[1, 3, 4, 5, 6]
1 :: 1
3 :: 3
4 :: 4
5 :: 5
6 :: 6

It is clear that both the list or not same, I tried using return stk == old_stk and also iterating element by element, but I am getting the wrong output.
Is my logic correct , or can anyone point out where I have gone wrong ?
Thanks !
Answer: The problem lies in the shallow copy of the list, specifically old_stk = stk this line.
With your current implementation, if you print the old_stk after the sort, it should be changed as well.
       if root:
            stk = self.inOrder(root,[])
            old_stk = stk
            print(old_stk)               # [1, 5, 3, 4, 6]
            stk.sort()
            print(stk)                   # [1, 3, 4, 5, 6]
            print(old_stk)               # [1, 3, 4, 5, 6]
            .......
            .......
        return True

So, deep copying the list should generate the correct output for the following input [5,1,4,null,null,3,6].
class Solution(object):

    def isValidBST(self, root):
        if root:
            stk = self.inOrder(root,[])
            old_stk = stk[:]   # Deep copy
            stk.sort()
            for i,j in zip(old_stk, stk):
                if i!= j:
                    return False
        return True

    def inOrder(self, root, trav):
        if root:
            trav = self.inOrder(root.left,trav)
            trav.append(root.val)
            trav = self.inOrder(root.right,trav)
        return trav

With that portion solved, when answering,

Is my logic correct?

Actually still, it is incorrect. For input, [2, 2, 2] will give the wrong value. Checking the left value is always smaller, and the right value is always bigger should fix it. Plenty of solutions are available.

Validate a BST in Python Leetcode


How do I avoid creating hundreds of files.vue

Question: I am building a website with a lot of items.
So the path is like:
example.com/catalog/indoor/fireplace/awesome-one
And currently I am creating hundreds and hundreds of Vue instances:
AwesomeOne.vue
AnotherOne.vue
YetAnotherThing.vue
...
AhundredthThing.vue

And all they have inside is a filtered array and passing a prop to the reusable component which uses data from Vuex storage.
And so I am thinking, is there a way to avoid creating so many Vue files? I kinda sorted the problem with Nuxt.js, but it only automatically generates routes which makes the development slightly easier. But I still have to create a lot of files with nearly identical code inside (it's literally just 3 words difference: the name of the computed property, the filter option and the name of the prop).
I was thinking about some computed property which would assign an URL dynamically, using data from Vuex.state. But I can't put things together.
as requested posting the code:
Catalog.vue
<template>
  <v-main>
    <v-row>
      <v-col
        v-for="category in categories"
        :key="category.i"
      >
        <v-card
          router
          :to="category.link"
        >
          <v-img
            height="250"
            width="250"
            :src="category.img"
          />
          <v-card-title>
            {{ category.name }}
          </v-card-title>
        </v-card>
      </v-col>
    </v-row>
  </v-main>
</template>

CatalogCategories.vue (having 5 of them)
<template>
  <v-sheet>

Изделия для дома

    <v-row>
      <v-col
        v-for="indoorItem in indoorItems"
        :key="indoorItem.i"
      >
        {{ indoorItem.name }}
      </v-col>
    </v-row>
  </v-sheet>
</template>

Banquet.vue (one of the categories, having over 20 of them)
<template>
  <v-sheet>

Банкетки

    <item-view :items="this.banquet" />
  </v-sheet>
</template>

ItemView.Vue (reusable component)
<template>
  <v-sheet>
    <v-row>
      <v-col
        v-for="item in items"
        :key="item.i"
      >
        <v-card
          route
          :to="item.path"
        >
          <v-img
            width="250"
            height="250"
            :src="item.img"
          />
          <v-card-title> {{ item.name }} </v-card-title>
          <v-card-subtitle> Цена: {{ item.price }} грамм конфет му-му </v-card-subtitle>
        </v-card>
      </v-col>
    </v-row>
  </v-sheet>
</template>

IndividualItem.vue (I'll have to create over 100 of them)
<template>
  <v-sheet>
    <v-card>
      <individual-item-view :items="this.obossana" />
      <v-card />
    </v-card>
  </v-sheet>
</template>

IndividualItemView.vue (reusable component)
<template>
  <v-sheet>
    <v-card
      v-for="item in items"
      :key="item.i"
    >
      <v-card-title> {{ item.name }} </v-card-title>

      <expandable-image
        class="image"
        close-on-background-click
        :src="item.img"
      />
      <v-card-subtitle> Цена: {{ item.price }} раз послать тебя ко всем чертям </v-card-subtitle>
      <v-card-text> {{ item.description }} </v-card-text>
    </v-card>
  </v-sheet>
</template>

And little snippet from Vuex store:
 {
        name: "Обоссаная банкетка",
        title: "obossana",
        type: "banquet",
        path: "/catalog/indoor/banquet/obossana",
        price: "215361",
        img:
          "https://b2.3ddd.ru/media/cache/tuk_model_custom_filter_ru/model_images/0000/0000/0079/79546.53239b3804d0a.jpeg",
        description: "blah blah blah",
      },

Answer: You're very close, and there's a few different ways that you can solve this.  I'll show the simplest way IMO, which is to continue to use props and push the hardcoded data you have further and further up the component hierarchy.
I'll use IndividualItem.vue as the example, since it's by far the most obvious how to apply it:
<template>
  <v-sheet>
    <v-card>
      <individual-item-view :items="this.items" />
      <v-card />
    </v-card>
  </v-sheet>
</template>

To use it, all you need to do is the following:
<IndividualItem title="obossana" />

Using props in this manner is what actually allows you to create and use reusable components.  There's also all kinds of different strategies that you can apply for passing props.
For example, rather than passing the title, you could instead pass the items, which would give the user of you IndividualItem component even more control over what items they want to show.
Here's a quick demo of that too:
<template>
  <v-sheet>
    <v-card>
      <individual-item-view :items="this.items" />
      <v-card />
    </v-card>
  </v-sheet>
</template>

Then, the user of the component might do (Note: you could create obossanaItems the exact same way you already do, just in the parent components scope):
<IndividualItem :items="obossanaItems" />

As a final piece of closing advice, which may be the piece that you're missing,  almost all hardcoded data (like title: obossana) should come directly from either your page components, or your API, which is what ultimately allows you to create reusable components.
For example, the page component in charge of rendering pages for example.com/catalog/indoor/fireplace/awesome-one should be in charge of supplying all its child components with the information they need to render the proper data.
This isn't the only method, but it's definitely the easiest to get started with, and it's what I'd recommend instead of creating specific components for each category, sub-category, etc.
As I mentioned at the beginning of this post, you're already very close, you just need to continue abstracting the specific data items to parent components.  There's other features of Vue and Nuxt, like Vuex getters, that can also help to make the specific filtering calls reusable as well, but that's getting into another topic.
Comment: Sorry I was a bit busy learning Nuxt.js. Now I got some time to have a look over here. And I think we've got misunderstanding over here.
I do know how to pass props and create reusable components.
The thing is that I have to actually create all the files: `catalog.vue` which will have `indoor.vue` nested inside, which will have `fireplaces.vue` nested inside(which has reusable `ItemView.vue` nested inside), which will have `awesome-fireplace.vue` nested inside (which has reusable `IndividualItemView.vue` nested inside).
Comment: My problem is that I don't want to create 100x `files.vue` with identical code inside with the only 1 difference as a different prop passed into reusable component inside of them.
`fireplace.vue`: `<IndividualItemView :items="this.awesomeOne"`
And then I'll have to create another file `shelf.vue`: `<IndividualItemView :items="this.rottenShelf"`
And so on, 100 files for catalog with the only 1 difference as a different prop. Is that alright or there's a way I can avoid that and sorta generate views without actually creating files.
Comment: Okay I found what I've been looking for. It called dynamic pages.
https://nuxtjs.org/examples/routing-dynamic-pages/
I hope I can figure out how to apply it :)
Answer: Alright I figured it out.
_view.vue for individual item view:

turned out it was pretty easy. All I had to do is to fetch the hard coded data (I decided to use API because in the future I'll have to add more items and I believe it gonna be easier if I use API) and filter it that the item.title matches the route $route.params.view
Inside the template tag (_view.vue file) I had:
<template>
  <v-main>

API: items

'/catalog/_subcategory/_individualitem/_view.vue' here

params.view: {{ params }}

    <v-card v-for="item in filteredItems" :key="item.i">
      <v-avatar size="200">

      </v-avatar>
      <v-card-title>
        {{ item.name }} and item.title: {{ item.title }}
      </v-card-title>
      <v-card-subtitle>Цена: {{ item.price }} сантиметров</v-card-subtitle>
      <v-card-text> {{ item.description }} </v-card-text>
    </v-card>
  </v-main>
</template>

h1, h2, h3 tags helped me to figure out (by displaying) values of variables.
The file tree is (the root is catalog itself):
├── index.vue
├── _subcategory
│   ├── _individualitem
│   │   └── _view.vue
│   └── _items.vue
└── _type.vue

And a little bit of api.json:
{
    "title": "stremnaya-arka",
    "path": "/catalog/outdoor/arcs/stremnaya-arka",
    "name": "Стрёмная арка",
    "type": "arcs",
}

Might be a bit confusing with the file names, but I hope it is not.
I hope it'll help some other newbie who struggles as much as me ;)


Cumulative probabilities - when to take inverse probability?

Question: Tasked with:

Given EPS is distributed with $\mu = 6$ and $\sigma = 2$, what is the
probability that EPS will be $9.70 or more?

Answer, convert to z-score and input into $F()$:
$$ \frac{9.70-6}{2} = 1.85$$
A z-table gives us $F(1.85) = .9678$ but this is $P(EPS\le9.70)$, we want $P(EPS\gt9.70)$, which is $1-P(EPS\gt9.70)$, or .0322.
However, the following nearly identical question in terms of wording seems to have a totally different interpretation of the probability calculation:

A survey on annual income finds that $\mu = 175,000$ and $\sigma =
> 25,000$. What is the percentage that respondents of the study have
incomes greater than $150,000?

I thought, surely, we'd do the same as above. After all, calculating probability for "9.70 or more" sounds like exactly the same task as finding "greater than 150,000". However, according to my textbook, we do not. We simply use $1-F(-1)=F(1)=.8413.$ Formally:
$$ \frac{150,000-175,00}{25,000}=-1$$
Question
Wouldn't the answer be $1-.8413$ like the initial example? And if I'm wrong on that, then why is the wording is the same but the technique not?
Answer: I think you've missed a minus sign when working something out. Using the same method as your first example,
$$
\frac{150000-175000}{25000} = -1\\
F(-1) = P(inc \leq 150000) = 0.1587\\
P(inc > 150000) = 1 - P(inc \leq 150000) = 1 - 0.1587 = 0.8413
$$
Which is exactly the same as $F(1) = 0.8413$.
It looks like the answer key uses a trick that $F(a) = 1-F(-a)$ to simplify the calculation. But both methods give the same answer.
(Some Z-tables only give values for positive $a$ or for negative $a$, so that's a very useful trick to remember.)


Help on a set proof using propositional logic.

Question: Prove that, if $B \not\subseteq \emptyset$ and $(A \times B) \subseteq (B \times C)$, then $A \subseteq B$.
How would a formal proof of this look like using propositional logic? What relevance does $B$ not being a subset of the empty set have? Is it simply saying $B$ is not an empty set? How would I get rid of the $C$ set in my proof?
Comment: No, A is a subset of B is the correct problem. And I am assuming I don't know what propositional logic is I guess.
Comment: Don't you mean "then $A\subseteq C$"?
Comment: Why are you stressing "using propositional logic" ? Do you know *propositional logic* ?
Comment: "What relevance does B not being a subset of the empty set have? Is it simply saying B is not an empty set?" -- Yes. For all sets $A$, $$A \times \emptyset = \emptyset \times A = \emptyset \subseteq \emptyset$$ holds. In this proposition, $A$ could then be an arbitrary set, and no non-empty could be a subset of the empty set, violating the proposition. Non-emptiness is required.
Answer: $B\nsubseteq\emptyset$ does indeed assert that $B$ is not empty. That is that $B$ contains something.
The importance is that $A\times\emptyset = \emptyset$ and $\emptyset\times C = \emptyset$ for any $A,C$, including those where $A\nsubseteq C$.  So the implication only holds when $B$ is not empty (if at all).
Your proof should use this to begin somewhat like:

Take $B\nsubseteq\emptyset$ and $A\times B\subseteq B\times C$ as premises.
The first premise entails that there is some term $y$ where $y\in B$.
Therefore for any term $x$, where $x\in A$, then there is some $y$ where $\langle x,y\rangle\in A\times B$.
Next, the second premise entails...

And in conclusion

Therefore, for any term $x$ that $x\in A\to x\in B$.
Which is to say $A\subseteq B$, by definition of (improper) subset.

In Fitch Style that is:
$$\def\fitch#1#2{\quad\begin{array}{|l}#1\\\hline#2\end{array}}\fitch{~~1.~B\nsubseteq \emptyset\hspace{20ex}\textsf{Premise}\\~~2.~A\times B\subseteq B\times C\hspace{10.5ex}\textsf{Premise}}{~~3.~\exists y~.y\in B\hspace{16.5ex}1,\subseteq  \textsf{Elimination}\\\fitch{~~4.~[b]~b\in B\hspace{14.5ex}\textsf{Assumption (Witness)}}{\fitch{~~5.~[a]\hspace{17ex}\textsf{Assumption (Arbitrary)}}{\fitch{~~6.~a\in A\hspace{10.5ex}\textsf{Assumption}}{~~7.~a\in A\wedge b\in B\hspace{2.5ex}4,6,\wedge\textsf{Introduction}\\~~8.~\langle a, b\rangle \in A\times B\hspace{2.5ex}7,\times\textsf{Introduction}\\~~\vdots}\\~~\vdots}\\~~\vdots}\\17.~\forall x~.(x\in A\to x\in B)\hspace{6ex}3,4{-}16,\exists\textsf{Elimination}\\18.~A\subseteq B\hspace{20ex}17,\subseteq\textsf{Introduction}}$$


How can I have a URL like www.example.com/about?language=ja to set Japanese for the page?

Question: I've enabled the Locale and Content Translation module but am having trouble understanding how to do something that it seems should be working.
Basically I have a page, we'll say '/about' and it's in English.
I click translate, I have a few languages enabled, so I click to add translation for Japanese. It brings up the interface for making a new page. I change some stuff to Japanese, and set the URL alias to be /about ('about') like the english page.
I've setup my language options to use the "Session" detection method.
The result I'm wanting to achieve, but not getting is to have:
<code>www.example.com/about -- to go to english (this works)
www.example.com/about?language=ja -- to go to the Japanese translation, this does not work, it just loads up the English page.
</code>
It seems like this would be the normal functionality so I feel like I'm missing something here.
Comment: belongs on drupal.
Comment: www.example.com/ja/about ?
Comment: there are 4-5 methods of selecting a language.  That is using the 'URL' option.  I'm referencing the 'Session' option.
Answer: just to be sure:
at admin/config/regional/language/admin_language, enable "Session" Detection method
make sure request/get parameter set to language
make sure you have about page in 'ja' language
try to visit yoursite.com/?language=japanese, it should be translating interface/etc - this way you can check translation is working.
Comment: I don't have any interfaces translated currently (I don't display any standard drupal interfaces to regular users anyway).  I have Session enabled, and there is a 'ja' version of the page, it even gives me a link to the Japanese version at the bottom of the page, but it links directly to the node so something like /node/123?language=ja instead of /about?language=ja.  I setup the URL alias but can't seem to access the japanese page with it by default.
Comment: /node/123?language=ja what this url is displaying? translated node?
try to clear cache at performance page, maybe this will help.
Answer: It seems the Content Translation module is out-dated and was replaced by Entity Translation.  Content Translation doesn't seem to work with the Session Detection method (at least with URL Aliases), but Entity Translation works fine with it.


Send email on ldap creation

Question: I have an LDAP server setup on a server running Debian 7 and I wanted to make it send out an email whenever a new user was created on that LDAP.
I thought a cronjob would be best, but I have no idea how to do a search for recent creations.
Mail doesnt have to be too complex, just something along the lines of
welcome,
your username is: XXXX
you are in group: YYYY

and this will be sent to commonName@domain.com
any ideas/starting points on how to go about this?
Answer: Make this a part of the user creation process, where it belongs.
If you want/must do it in a separate way, I would simply either add a custom schema with a field like WelcomeSent or (ab)use an unused field for this purpose and set it to true if the mail has been sent. You then write a simple cron job searching for user records with this field not set to true, send the mail and update this field. Obviously, you would set this field to true for all existing users in order to avoid confusion when introducing this.
I would not try to do this with a date field (or the update/creation date metadata records), as this is susceptible to race conditions (among other problems).

Send email on ldap creation


Calculating number of items displayed - pagination

Question: This is my first post here and found it through Stack Overflow. I am a web designer but I am currently pulling my hair out over the lack of my mathematical knowledge.
On a site displaying a category, there may be a scenario where a user will put subcategories and products within a parent category.
On these pages (categories) where products are displayed, there is a "showing $N$ to $I$ of $T$ products" message (e.g. "showing 1 to 6 of 10 products").
So I am in a rut about how I am to calculate this to only take into account the products and not the categories.
Here's what I know (variables):

$E =$ the current page number (there can be many pages to split up the view)
$F =$ the amount of products or subcategories allowed on any 1 page
$Y =$ the total amount of subcategories being displayed in this category
$L =$ the total amount of products displayed in this category

Also the subcategories are always displayed first before the products.
If anyone can help me out or give a push in the right direction, it would be much appreciated.
EDIT
as per the solution below, here is the PHP interpritation:
(valiables are in relation to the post and relating comments)
<code>function f( $x, $f, $y, $l ) {
    return ( ( $x * $f ) - $y < 0 ? 0 : ( ( $x * $f ) - $y > $l ? $l : ( $x * $f ) - $y ) );
}

$n = 1 + f($e-1, $f, $y, $l);
$i = f($e, $f, $y, $l);
echo 'Showing ' . $n .' to ' . $i . ' of ' . $l . ' Products';
</code>
Answer: When you don't have categories, the number of pages is $\frac{L}{F}$, rounded up to the next whole number.  So if there are 53 products and you display 8 per page, you will need 7 pages.  On page E, you will have objects (E-1)*F+1 to E*F.If you have categories, does each one start on a new page?  Then you just have the same calculation for each category.  If your 53 objects are in categories of 12,23,5, and 13, you would have 2,3,1, and 2 pages, for a total of 8.  You then have to decide whether the showing N to P of M is within the category or over all products.  Is this what you were after?
Comment: if there are lets say 3 sub cats and 6 prods and each page only allows 6 items per page to be displayed, then 3 cats and 3 prods would be on the first page (showing 1 to 3 of 6 products) and 3 on the next.
Comment: I think I may have sused *N* = ( ( ( *E* * *F* ) - ( *F* - 1 ) ) - *Y* );
Answer: If I understand you correctly, a category can contain two kinds of items: subcategories and products.  Out of those, subcategories are always sorted before products.  On each page, you display (up to) $F$ items, and, for the $E$-th page, you want to know

$N =$ the total number of products displayed on pages $1$ to $E-1$ plus one, and
$I =$ the total number of products displayed on pages $1$ to $E$.

Clearly, there are $E$ times $F$ items (products or subcategories) displayed on the pages $1$ to $E$ (unless this would exceed $L+Y$, in which case that's the upper limit).  Out of those, up to $Y$ will be subcategories, so we're left with $EF-Y$ products (unless $EF<Y$, in which case there will be no products on those pages).
So, let's use $f(X)$ to denote the total number of products displayed on pages $1$ to $X$.  Then
$$f(X) = \begin{cases}
0 & \text{if } XF-Y < 0 \\
L & \text{if } XF-Y > L \\
XF-Y & \text{otherwise}.
\end{cases}$$
Using this rule, we can then easily calculate $N = 1 + f(E-1)$ and $I = f(E)$.
(Ps. Note that, if $Y \ge F$, using this rule the first page would carry a message saying "showing $1$ to $0$ of $L$ products".  You may want to have a separate message for the case $I=0$ if there's any chance that it could occur in practice.)
Comment: this is the most detailed message I have ever recieved on ANY forum... I'm just going to spend a few minutes finding out what the squiggly *f*() means... brb
Comment: think it means function and X being the passing value of total products... hope so
Comment: Yes, the "squiggly $f$" is just the name of a function.  Its argument $X$ is the number of a page; I used $X$ there instead of $E$ to avoid confusion below, where we pass $E-1$ as the argument to $f$ when calculating $N$.
Comment: one more thing (trying to remember what a teacher tried to teach me many moons ago..) does XF mean X*F... sorry if im being a pain
Comment: Yes, $XF$ means $X$ times $F$.  I suppose I could've written it as $X \times F$ or $X \cdot F$, but in mathematics it's common to [denote multiplication just by juxtaposition](http://en.wikipedia.org/wiki/Multiplication#Notation_and_terminology).
Comment: brilliant, thank you very much (added PHP version above for anyone googling
Answer:
Also the subcategories are always displayed first before the products.

The alarm bell wrang after reading that line, it is not a requirement of the problem but just a viewing of the results. More than math looking at Design Patterns will help you.
The mathematical solution of this problem is completely wrong for Web Programming.
First separate your entities i.e. divid your problem to Categories, Products etc., 2nd solve the problem for each group separately, Last display the products and categories in a way that they are not coupled ( i.e. choosing one does not effect what you see in other one).
Lastly try asp.net, there were pre made samples that have already this scenario implemented. This is not a job for a web designer but a programmer. If this is a job for a client you will be way behind by the time it is gonna take to design, implement and test this approach, get a php shopping card close to what you need, then ponder about the math part separately.


"System.NullReferenceException" for Using Session in MVC

Question: In My MVC project, I am using session values like
var empId = Convert.ToInt32(Session["EmpId"].ToString());

I am getting Exception:
"An exception of type 'System.NullReferenceException' occurred in Project.Web.dll but was not handled in user code.
Additional information: Object reference not set to an instance of an object."
Comment: Have you checked Session["EmpId"] for null?
Answer: This error occurs when you call a method on the null object. In your case the value of Session["EmpId"] is NULL.
Which means you are calling NULL.ToString(), which is invaild hence it throws error.
You can avoid the error using null coaleascing operator or simply check null before performing any opearation on it.
Solution:
if(Session["EmpId"] == null)
 //do something
else
 var empId = Convert.ToInt32(Session["EmpId"].ToString());

Alternatively you can check my blog post on it
Comment: I have the same issue but my property definition is like this get
            {
                if (Session["_exportViewModel1"] == null)
                    Session["_exportViewModel1"] = new BG.Indigo.Controls.Utilities.CountrySurveyReportExportVM();
                return (BG.Indigo.Controls.Utilities.CountrySurveyReportExportVM)Session["_exportViewModel1"];
            }
            set
            {
                    Session["_exportViewModel1"] = value;
            }
Answer: Before use first check  is it null or not.
var empId = Session["EmapId"] != null ? Convert.ToInt32(Session["EmapId"]) : 0;

Answer: You have to check null as shown below :-
var empId = Convert.ToInt32((Session["EmpId"] ?? 0).ToString());

A more efficient way to accomplish your requirement :-
int temp = 0;
var empId = int.TryParse( Convert.ToString( Session["EmpId"] ),out temp );


select N-1 records for update

Question: I have a query where I want to update n-1 records from result set. Can this be done without loops?
If my query is like this:
with cte(id, count)
as
(
  select e.id, count(*) as count
  from data
  where id in (multiple values)
  group by id
  having count(*) >1
)

Now I want to update the rows in another table with the resulting id's but only any n-1 rows for each id value from the above query. Something like this:

update top( count-1 or n-1) from data2
inner join cte on data2.id = cte.id
set somecolumn = 'some value'
where id in (select id from cte)

The id column is not unique. There are multiple rows with the same id values in table data 2.
Comment: What does `n` correspond to? You should probably provide sample data and expected results to clarify your requirement.
Comment: the id column. There are multiple rows with similar id's. I only want n-1 of these rows for each id to be modified.
Comment: It's still not entirely clear whether n is the count of ID in table [data], or the count of that ID in table [data2].  One way or another you'll need to use ROW_NUMBER(), but let's be clear exactly what table contains the count of ID that you intend to use as 'n'.  From there, it'll be pretty straightforward.
Comment: Thank you all. Nick is right. I had to use row_number() with partition and that solved the issue.
Answer: This query will do what you want. It uses two CTEs; the first generates the list of eligible id values to update, and the second generates row numbers for id values in data2 which match those in the first CTE. The second CTE is then updated if the row number is greater than 1 (so only n-1 rows get updated):
with cte(id, count) as (
  select id, count(*) as count
  from data
  where id in (2, 3, 4, 6, 7)
  group by id
  having count(*) >1
),
cte2 as (
  select d.id, d.somecolumn,
         row_number() over (partition by d.id order by rand()) as rn
  from data2 d
  join cte on cte.id = d.id
)
update cte2
set somecolumn = 'some value'
where rn > 1

Note I've chosen to order row numbers randomly, you might have some other scheme for deciding which n-1 values you want to update (e.g. ordered by id, or ...).
Answer: Is this what you're looking for? The CTE identifies ALL of the source rows, but the WHEREclause in the UPDATE statement limits the updates to n-1.
WITH cte AS
(
  SELECT
    id,
    ROW_NUMBER() OVER (ORDER BY (SELECT 0)) AS RowNum
  FROM data
)
UPDATE t
 SET t.<whatever> = <whateverElse>
FROM
 otherTable AS t
 JOIN
 cte AS c
  ON t.id = c.id
WHERE
 c.RowNum > 1;

Comment: Thank you. I had to slightly modify your query and that did the trick.
Answer: I believe this would work just fine
;with cte(id, count)
as
(
select e.id, count(*) as count
from data
where id in (multiple values)
group by id
having count(*) >1
)
update data
set soemcolumn = 'some value'
from data join cte on cte.id = data.id
;

select N-1 records for update


JQGrid maintain data on postback

Question: I have a jqgrid which is declared in  user control and referred in web page. Data is loaded on button click event using ajax call. Everything works fine except when  a post-back is triggered on page to do some server processing data vanishes on grid. User as to search again by clicking button to get results back. Is there a way to retain data on a jqgrid when post-back is done.
Answer: It would be way to expensive to try and retain the grid data during a postback.  You shouldn't even try to do that.
Your best option is to use ajax for whatever is initiating the full page postback.

JQGrid maintain data on postback


checking if a postal code matches from a predefined list

Question: I want to create a list of postal codes that are out of range for free shipping. I am not sure if I need an array to do this so I first created a variable:
outlimit_postal = "V0R1A0,X0E0A0,J0M1V0,P0V1B0,X0A0A0,X0C0E0,P0L1A0,J0M1X0,X0C0A0,X0B2A0,P0V1E0,R0B0A0,P0V1G0,S0J0H0,A0K1N0,V0P1B0,R0C0J0,R0B0B0,X0B0C0,X0A0C0,P0V1J0,X0C0B0,G0G1G0,X0A0E0,X0E1L0,X0C0C0,V0N1M0,P0V1N0,X0E0G0,P0T1L0,X0A0G0,S0J0W0,P0L1H0,T0P1B0,X0E0H0,P0V1W0,T0H1R0,G0G1M0,X0B1J0,R0B0M0,R0B0N0,R0B0P0,X0A0J0,X0A0K0,G0G1N0,V0V1A0,X0E0S0,A0P1G0,X0A0L0,J0M1M0,X0A0H0,X0A1H0,R0B0T0,J0M1H0,J0M1N0,J0M1K0,J0M1A0,P0V1Y0,P0L1S0,G0G1S0,P0V3G0,X0A0N0,V0N2B0,P0V1Z0,V0V1C0,V0T1L0,X0B1K0,X0B0E0,J0M1C0,J0M1G0,V0P1J0,G0G1T0,R0B2E0,P0T1Z0,V0V1H0,R0B0V0,X0E1A0,A0P1J0,V0P1L0,P0V3B0,G0G2C0,A0P1L0,A0P1A0,R0B0Z0,X0E0V0,P0V2G0,V0T1P0,P0T2L0,Y0B1N0,V0V1E0,V0N3S0,R0B1C0,X0A0R0,R0B2G0,X0E1N0,P0L2H0,P0V2L0,X0A0S0,P0V3E0,R0B0Z0,G0G2Y0,A0P1N0,R0B1G0,J0M1P0,X0A0B0,J0M1J0,X0E1R0,X0C0G0,R0B1H0,V0P1P0,X0C0H0,X0A0V0,A0P1P0,P0V2P0,X0E0Z0,J0M1S0,P0V1V0,X0A0W0,R0B1K0,V0P1S0,R0B1N0,G0G2R0,R0B1J0,R0B2H0,S0J2R0,V0P1V0,V0N3H0,P0T3B0,V0P1W0,R0B2C0,X0B1B0,J0M1T0,G0G2W0,X0E1Z0,V0J3N0,X0E1C0,X0E0K0,J0M1Y0,S0J2W0,R0B1Z0,V0J3B0,P0V2Y0,P0T3A0,X0E1W0,X0E1P0,X0C0J0,A0K5V0,S0J3C0,P0V2Z0,R0B2B0";

My first issue is I am not sure if I need to create an array or store these in my database as separate rows. Or if I can just keep them in a single variable list to check against like I have.
Anyhow next I want to match the persons postal code to check if they are in the list:
  if ($this->enabled == true)   {

            if (preg_match($order->delivery['postcode'], $outlimit_postal )) {
                $this->enabled = false;

            }

However I got an error:
Warning: preg_match(): Empty regular expression
is my syntax for using preg_match incorrect? does it not return a boolean?
Comment: I would suggest `strpos($postcode, $outlimit_postal) === false ? "no match" : "match"`
Comment: Howdy! Yeah, preg_match is for regular expressions- which you're not using here. Instead, ```explode``` the outlimit_postal string on the comma- which will give you an array of allowed postal codes. Then, use ```in_array``` to check your string against that array. References: http://php.net/manual/en/function.explode.php http://php.net/manual/en/function.in-array.php
Comment: the first param is pattern, `$order->delivery["postcode"]` does not sounds like a pattern
Comment: I'd second Andrew's recommendation- much simpler and would use less memory.
Answer: You can use an array for this, and PHP's in_array():
$outlimit_postal = array("V0R1A0","X0E0A0","J0M1V0");

and
if (in_array($order->delivery['postcode'], $outlimit_postal) )

Comment: Thanks this would work But I like the explode method better as it is lazier
Answer: Consider trying something like this instead of attempting to use preg_match. Preg_match is for matching against a regular expression, which you don't need here.
$outlimit_postal = "V0R1A0,X0E0A0,J0M1V0,P0V1B0,X0A0A0,X0C0E0,P0L1A0,J0M1X0,X0C0A0,X0B2A0,P0V1E0,R0B0A0,P0V1G0,S0J0H0,A0K1N0,V0P1B0,R0C0J0,R0B0B0,X0B0C0,X0A0C0,P0V1J0,X0C0B0,G0G1G0,X0A0E0,X0E1L0,X0C0C0,V0N1M0,P0V1N0,X0E0G0,P0T1L0,X0A0G0,S0J0W0,P0L1H0,T0P1B0,X0E0H0,P0V1W0,T0H1R0,G0G1M0,X0B1J0,R0B0M0,R0B0N0,R0B0P0,X0A0J0,X0A0K0,G0G1N0,V0V1A0,X0E0S0,A0P1G0,X0A0L0,J0M1M0,X0A0H0,X0A1H0,R0B0T0,J0M1H0,J0M1N0,J0M1K0,J0M1A0,P0V1Y0,P0L1S0,G0G1S0,P0V3G0,X0A0N0,V0N2B0,P0V1Z0,V0V1C0,V0T1L0,X0B1K0,X0B0E0,J0M1C0,J0M1G0,V0P1J0,G0G1T0,R0B2E0,P0T1Z0,V0V1H0,R0B0V0,X0E1A0,A0P1J0,V0P1L0,P0V3B0,G0G2C0,A0P1L0,A0P1A0,R0B0Z0,X0E0V0,P0V2G0,V0T1P0,P0T2L0,Y0B1N0,V0V1E0,V0N3S0,R0B1C0,X0A0R0,R0B2G0,X0E1N0,P0L2H0,P0V2L0,X0A0S0,P0V3E0,R0B0Z0,G0G2Y0,A0P1N0,R0B1G0,J0M1P0,X0A0B0,J0M1J0,X0E1R0,X0C0G0,R0B1H0,V0P1P0,X0C0H0,X0A0V0,A0P1P0,P0V2P0,X0E0Z0,J0M1S0,P0V1V0,X0A0W0,R0B1K0,V0P1S0,R0B1N0,G0G2R0,R0B1J0,R0B2H0,S0J2R0,V0P1V0,V0N3H0,P0T3B0,V0P1W0,R0B2C0,X0B1B0,J0M1T0,G0G2W0,X0E1Z0,V0J3N0,X0E1C0,X0E0K0,J0M1Y0,S0J2W0,R0B1Z0,V0J3B0,P0V2Y0,P0T3A0,X0E1W0,X0E1P0,X0C0J0,A0K5V0,S0J3C0,P0V2Z0,R0B2B0";
$allowed_postal_codes = explode(',', $outlimit_postal);

  if ($this->enabled == true)   {

            if (in_array($order->delivery['postcode'], $allowed_postal_codes)) {
                $this->enabled = false;

            }

Answer: Since it is already in a form of string, I would suggest just search the substring in your outlimit_postal string.
E.g.
if (strpos($order->delivery['postcode'], $outlimit_postal) === false) {
    echo "no match in outlimit_postal";
}
else {
    echo "match in outlimit_postal";
}

Answer: Store it as a string but check it as an array..
$outlimit_postal = explode(",", $outlimit_postal);
if(in_array($post_code, $outlimit_postal)) echo "Your post code is in the list";

Answer: Use an array. Make the postal code the array key. Put anything that defines the non-free shipping as the value, i.e. the amount of shipping in absolute or relative terms, or some entire business object being configured to calculate the correct shipping.
$shipping['V0R1A0'] = 1.5; // e.g. as absolute amount

Checking if non-free shipping has to be made:
if (isset($shipping[$postalcode])) {...

Those suggesting solutions with in_array() should be reminded that searching inside an array is slow - that's what array keys are made for.
If you cannot use the value, just add true as a value.


How to include attributes of the MySQL table to hook_schema() schema in drupal 7?

Question: I am creating a table using hook_schema()
I am referring phpMyadmin to create a new table. In the phpMyadmin there is a
column 'Attributes'
which has values as 'unsigned' or  on update CURRENT_TIMESTAMP'
I have a row in a table which is of type 'timestamp' and has attributes 'on
update CURRENT_TIMESTAMP'.
How can I  include this attribute on update CURRENT_TIMESTAMP in the hook_schema() ?
Also there is  a default column in phpMyAdmin how can I add that in hook_schema() ?
the first time I created a hook_module_name.install a table was created as it was specified in the hook_schema()
Then I uninstalled that module but the table was not deleted ?
Now I even removed the .install file cleared the cache , even after this  a table is not created. What can be the solution to this problem.
What I have checked is that it is entering into hook_schema function but the table is not generated at the database. Any hints on this would be appreciated.
Comment: Hello. Please avoid [chameleon questions](http://meta.stackexchange.com/questions/43478/exit-strategies-for-chameleon-questions). I strongly suggest rollback and asking future questions using ["Ask Question"](http://drupal.stackexchange.com/questions/ask) button.
Comment: ok. I am sorry..
Comment: No problem :) Keeping things clear and questions stable makes it easier to find answers, and more encouraging to answer - the only reason I mentioned it was to keep this site and community able and willing to provide what you need. You've read and applied, great. No reason to feel bad about mistakes that got corrected.
Answer: You can't use an ON UPDATE unfortunately - Drupal's schema API doesn't give you that sort of dbms-specific control.
You can use unsigned for unsigned and default for a default value though:
$schema['some_table'] = array(
  'fields' => array(
    'some_field' => array(
      'type' => 'int',
      'not null' => TRUE,
      'unsigned' => TRUE,
      'default' => 0,
    ),
  ),
);

See the Schema API docs for the full list of data types and usage.
Comment: pls check updated question? I am not able to generate or remove a table on enabling or disabling a module
Comment: I'd wager you didn't uninstall the module, and just disabled it. There's an 'uninstall' tab you need to visit once disabling the module (or run `drush pm-uninstall`)


Send to back functionality in HTML5

Question: I'm having the following use case that I want to achieve in HTML
I've two div element with background red and blue. The blue div is added later of which a part overlaped with red div.
I have the option of "send to back" which sends the selected div to back of other div.
If I apply this to blue div and select blue div it should look like below image

Basically I'm trying to minic the functionality of Arrange --> Order --> Send to back of Google Presentation
I did try z-index with no success. I can use background-gradient with the overlaped part of blue div transparent but that will invole some calculations which I want to avoid.
How to acheive this in HTML?
Any help is appreciated.
Note: All div elements are placed with position: absolute
Update: The red div lies above the blue div as its z-index is higher than blue div. When red div is selected it should look like below (with border highlighted).

Now if I select the blue div a part of it that overlapes with red div does not appear (obviously since its z-index is lesser) but I want its border to appear when I select.it.
Comment: [You mean like this](http://jsfiddle.net/3pLzX/)?
Comment: You were right to use `z-index`, but you may want to look into how to use it. http://stackoverflow.com/search?q=z-index+not+working
Comment: @Mr.Alien I regret for not mentioning the details as required. Now I guess you will understand my question as I added more details. By the way thanks for replying.
Comment: @Shubhmay Please check out the demo 3
Comment: @Vucko I've updated the [fiddle](http://jsfiddle.net/3pLzX/6/) but when I click `blue div` I want only its `border` to be `visible` which is overlaped with `red` not entire `blue div`. Please see first image in my question.
Comment: @Shubhmay http://jsfiddle.net/FKDNf/7/
Answer: As you've commented, I guess what you need is this, also, just call a class on a div which you want to stack up.
Final Demo

I am not getting your question quiet well, but I assume you want to bring an element above another when it is clicked, than you can do it this way
Demo
Explanation:
What am doing here is, am simply applying z-index on the div you click using jQuery.
Demo 3 (As you updated your question)

Using border to mark the current selected div
$(".wrap div").click(function(){
    $('.wrap div').removeAttr('style');
    $(this).css({"z-index":"1", "border":"1px solid #000"});
});

Demo 2
Code Reference :
$(".wrap div").click(function(){
  $(this).css("z-index","1");
});

.wrap {
    position: relative;
}

.wrap div {
    position: absolute;
    height: 100px;
    width: 100px;
}

.wrap div:nth-of-type(1) {
    background: #f00;
    left: 10px;
}

.wrap div:nth-of-type(2) {
    background: #0f0;
    left: 80px;
}

Comment: In [Demo2](http://jsfiddle.net/FKDNf/5/) When I click green div I want part of overlaped red and border of green div visible as in first image of my question
Comment: @Shubhmay I contributed a final demo, though am still not clear what exactly you are looking for, thats the reason I've kept all the previous demos in my answer as well, if you want border,than simply add border like http://jsfiddle.net/FKDNf/8/
Comment: Can I share Google presentation demo with you? I guess from that you will get clear idea what I actually need.
Comment: @Shubhmay omg, even my final one is not the thing you wanted? *sigh*, instead of that, try to edit and clear out the question, and am sure we will solve
Comment: [check this example](https://docs.google.com/presentation/d/1wStnObHGUNP0EdY7yzvXe99Vu5yzsCiOdzNRb2HsBQY/edit?usp=sharing) you will get clear idea what I want to achieve.
Comment: @Shubhmay isn't that the same thing I provided you?
Comment: @Shubhmay is this what you want? [fiddle](http://jsfiddle.net/venkateshwar/FKDNf/9/).
Comment: @Mr_Green You did what I actually wanted. Thanks for solving my problem.

Send to back functionality in HTML5