How to show $\sum\limits_{j=1}^\infty(\sum\limits_{i=1}^\infty v_i a_{ij})^2$ is convergent?

Question: Assuming
\begin{align}
&\sum\limits_{i=1}^\infty v_i^2 <\infty  \\
&\sum\limits_{j=1}^\infty  a_{ij}^2 <\infty    ~~~~~~\forall i\ge 1  \\
&\sum\limits_{i=1}^\infty  a_{ij}^2 <\infty    ~~~~~~\forall j\ge 1
\end{align}
then how to show
$$
\sum\limits_{j=1}^\infty(\sum\limits_{i=1}^\infty v_i a_{ij})^2
$$
is convergent?    I can get the convergence of
$$
\sum\limits_{i=1}^\infty v_i a_{ij}~~~~~~\forall j\ge 1
$$
But, I still  suspect it is not right, although I   fail to find counter-example after spending an afternoon.  Therefore, I asked here.  Thanks for any help.
Answer: This is not true. Let $a_{ij}=j$ if $i =j$ and $0$ is $i \neq j$. Let $v_j=\frac 1  j$ . Then $\sum_i v_ia_{ij}=1$ and $\sum_j (\sum_i v_ia_{ij})^{2}=\infty$.
Comment: Thanks your answer. I really feel bad, even though I had a hunch it was wrong.  Thanks again.


Font awesome not working with tooltip

Question: I would like a tooltip pop up from bootstrap 4 to display when the font awesome icon is clicked. Button nothing is occurring. My code is as follows:

would I need to make a javascript function?
EDIT:
I have the following scripts:

Comment: Possible duplicate of [Bootstrap tooltips not working](http://stackoverflow.com/questions/9446318/bootstrap-tooltips-not-working)
Comment: Did you load Bootstrap's JavaScript file?
Comment: yes it is right before the closing body tag
Answer: Tooltip is an "opt-in" component so you have to call .tooltip() on the elements that you want to have tooltips.

$("[data-toggle='tooltip']").tooltip();
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

Comment: for some reason it works here but when I add it to my code it won't work
Comment: no I checked in the console but nothing I am just going to rewrite another page and test it further. I do see I am using a different version of bootstrap but even by putting the latest one no effect.

Font awesome not working with tooltip


Get nodes by content type when type key is not in root of nodes array

Question: I am trying to get all nodes by content type. When the key is in the root of nodes array, like [type] I can easily retrieve it by, for example:
$nodes = node_load_multiple(array(), array('type' => 'page'));

But how do I do it when the key is not in the root, like:
    [title] => Test 1
    [status] => 1
    [comment] => 0
    [promote] => 0
    [sticky] => 0
    [nid] => 24
    [type] => page
    ...
    [field_worktype] => Array
            (
                [und] => Array
                    (
                        [0] => Array
                            (
                                [value] => some_value
                            )

                    )

            )
   ...

So, in the above example, how do I get nodes which [field_worktype][und][0][value] equals "some_value"?
Answer: With an EntityFieldQuery:
$query = new \EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->propertyCondition('type', 'page')
  ->fieldCondition('field_worktype', 'value', 'foo');

$result = $query->execute();
if (!empty($result['node'])) {
  $nodes = node_load_multiple(array_keys($result['node']));
}

As an aside, the method in your OP (using the $conditions array) is deprecated in favour of EntityFieldQuery anyway, which can perform the same filters.
Comment: I saw elsewhere it was deprecated, so it seems I was lucky to be in need for something not achievable by node_load_multiple anyway :)


HTML phone drop down inconsistency

Question: So I have code to create a drop down that is used for my website aimed at mobile users. However it works on one page but not another.
What other code could be interfering for this problem to occur?
It works here:

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>
                Fortune Filly

                        Memberships

                        About

                        Contact

                        Login

But not here:

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>
                Fortune Filly

                        Home

                        Account Details

                        Logout

I will add that on the page that it isn't working I am getting the error: session_start() Cannot send session cache limiter - headers already sent
Here is the rest of the code for the page which doesn't work:
<?php
include 'connect.php';
session_start();
ob_start();
if(!isset($_SESSION['username']))
{
    header("location:http://www.fortunefilly.com/loginTemplate.php");
}
else
{
    $username =$_SESSION['username'];
    $check = $mysqli->query("SELECT id FROM users WHERE username = '$username'");
    $row = $check->fetch_assoc();
    $id = $row['id'];
}
?>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Fortune Filly</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="css/freelancer.css" rel="stylesheet">

    <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href="http://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">
    <link href="http://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic" rel="stylesheet" type="text/css">

                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                        Toggle navigation

                    </button>
                    Fortune Filly

                            Home

                            Account Details

                            Logout

Welcome <?php echo $username;?>

To gain access to the members section and receive daily horse racing tips from our professionals Click here

                    <?php
                    $check = $mysqli->query("SELECT is_member FROM users WHERE username = '$username'");
                    $row = $check->fetch_assoc();
                    $isMember = $row['is_member'];
                    if ($isMember == 0){
                    echo'<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post" target="_top">
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="CTKLZLJZBA4P4">

<input type="hidden" name="on0" value="">

<select name="os0">
    <option value="Weekly">Weekly : £5.00 GBP - weekly</option>
    <option value="Monthly">Monthly : £15.00 GBP - monthly</option>
    <option value="Yearly">Yearly : £60.00 GBP - yearly</option>
</select>

<input type="hidden" name="custom" value="$id">
<input type="hidden" name="currency_code" value="GBP">
<input type="image" src="https://www.sandbox.paypal.com/en_US/GB/i/btn/btn_subscribeCC_LG.gif" border="0" name="submit" alt="PayPal – The safer, easier way to pay online.">

</form>

                    ';
                    // echo '<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post" target="_top">
                    // <input type="hidden" name="cmd" value="_s-xclick">
                    // <input type="hidden" name="custom" value="$id">
                    // <input type="hidden" name="hosted_button_id" value="H4K679J6Y5T7C">
                    // <input type="image" src="https://www.paypalobjects.com/en_US/GB/i/btn/btn_subscribeCC_LG.gif" border="0" name="submit" alt="PayPal – The safer, easier way to pay online.">
                    //
                    // </form>';
                    }
                    ?>

Comment: what code? and what dropdown? The html is kinda useless without the related JS/CSS.
Comment: Surely you wouldn't need to see it if it works for one? @MarcB
Comment: They both work fine for me. First: http://www.bootply.com/render/ZIoghuCYUx Second: http://www.bootply.com/render/zuqucHeXGV
Comment: @APAD1 So is there something which could possibly be interfering?
Comment: I don't know, but what you've posted works fine, so if there is an issue, it's in code that you haven't posted.
Comment: @APAD1 I uploaded the rest of the html file, in the edit
Comment: Adding an answer based on what I see.
Answer: Alright, so based on the latest code you posted, I believe this is your issue. On the login page, there is a bit of jQuery at the bottom of the page:
$(document).ready(function() {
    LoginModalController.initialize();
});

However, it seems like jQuery is either not loading properly or it's being loaded after the function is fired because I'm getting:
Uncaught ReferenceError: $ is not defined

It also looks like you're not loading bootstrap.min.js on the login page which, I believe, is required for the nav dropdown(not entirely sure though as I've never used that feature of Bootstrap).
UPDATE: OP was calling the login.js file in the header and footer, the one being called in the header was causing a reference error as it was firing before jQuery was loaded.
Comment: You have confused me far more than I originally was :O
Comment: Surely it wouldn't be anything to do with the jquery or javascript as the homepage is proof it works
Comment: It's definitely an issue with the jQuery or Javascript, the reason it's working on the homepage is because you have it coded one way on the homepage and a completely different way on the login page. I would recommend making a single header and a single footer. Then load `jQuery`, `Bootstrap` and `FontAwesome` in the header file and include that file on your other pages. It will be much cleaner and easier to maintain. Currently you're loading a local version of jQuery 1.11.1 on the homepage and then on the login page you're loading a remote CDN version of jQuery 2.1.3, which doesn't make sense.
Comment: I used a template for the homepage and a seperate one for the login page so all the jQuery and javascript is pretty much over my head at the moment, I'm unsure how to implement what you just commented
Comment: Alright, I see the exact problem now. On the login page, you are loading the file `login.js` twice. Once in the header and the other one in the footer, but jQuery is only being loaded in the footer. So basically the `$(document).ready` function from the header `login.js` is firing before jQuery is loading, which prevents any Javascript on the page from work. Clean up your code and it will work.
Comment: So should i get rid of the one in the header?
Comment: or should I put the jQuery in the header?
Comment: Get rid of the `login.js` in the header and it might work. However, as I said before, you might also need to load `bootstrap.min.js` on that page(it's not currently). Also, I would still recommend cleaning up your code because you're bound to run into more problems if you don't.
Comment: Okay, so adding the bootstrap.min.js at the bottom of the code did the trick. You are a beautiful human being!

HTML phone drop down inconsistency


Uso de variáveis globais e variáveis de classe no Delphi

Question: Eu tenho algumas dúvidas quanto ao uso de variáveis globais e variáveis de classe usando class var no Delphi.
Declarando variáveis de classe com class var.
unit Unit1;

interface

type
  TClass = class
  public
    class var _Object: TObjectList<Integer>
  end;

implementation
end.

Declarando variáveis globais
unit Unit1;

interface

var
  _Object: TObjectList<Integer>

implementation
end.

Pergunta:
Como o compilador aloca memória para essas declarações?
Qual forma de uso é a mais indicada para ser utilizada?
Comment: Depende da intenção.  Se é uma variável de suporte à classe ou a todas as instâncias dessa classe (ou subclasses), deve ser uma `class var`.  Se tiver interesse fora do âmbito da classe e esse interesse for partilhado e único, talvez deva ser uma `var` global, embora prefira sempre que possível usar um campo de um objecto singleton, para agrupar campos/propriedades de forma lógica.  E esse objecto sim estar numa variável global ou ser acessível/instanciável através de outro objecto global.
Comment: Em geral acho que é melhor minimizar o uso de variáveis globais e tender a colocar as outras variáveis nas classes.
Answer: O processo de alocação de memória de uma variável de classe usando o class var é o mesmo que uma variável global.
A unica diferença é que a variável declarada como class var vai ter um escopo de classe.
https://stackoverflow.com/questions/21986202/use-of-variables-global-and-variables-of-class-in-delphi
Comment: Você pode marcar sua própria resposta como aceita.
Answer: Após a separação da CodeGear da Borland a equipe responsável pelo Delphi procurou modernizar a linguagem. Neste sentido, adicionou construções de linguagem que visam permitir melhores práticas de programação, notadamente dando à aplicação um modelo mais orientado a objetos.
As variáveis de classe públicas e globais são relativamente similares, no sentido de que terão apenas uma instância, mas as variáveis de classe têm a vantagem de estar definidas dentro do escopo da classe, o que evita eventuais colisões de nomes em diferentes units ou mesmo dentro da mesma unit.
Por este último motivo eu recomendo o uso de variáveis de classe.
Answer: Em qualquer ambiente de desenvolvimento que forneça facilidades de escopo para as variáveis de forma que você possa criar membros na Classe (Java, Delphi, C#, etc.) use sempre estas funcionalidades em vez de variáveis globais ou de classe pois estas variáveis vão criar acoplamento excessivo no seu código dificultando a manutenção. O Design Pattern Singleton permite que se crie algo melhor que simplesmente usar Variáveis globais mas também deve ser evitado.
Answer: Só para incrementar o que já foi falado.
Eu já vi duas variáveis globais em unit´s diferentes mas com o mesmo nome. Eram do tipo de uma classe. Ao instanciá-la na unit1, era instanciada a da unit2. Na hora de destruir, era então destruida a da unit1. Resultado: "Access Violation".
Como era praticamente impossível mudar a cultura do pessoal em relação ao var Global, eu instrui a declararem dentro do escopo de implementation na unit, em vez da interface. Isso fez ela não ficar visível para as outras units, resolvendo temporariamente o problema.
Answer: A linguagem de programação por traz do Delphi é o Object Pascal cuja origem está no Pascal estruturado, isto é, não orientado a objeto. Por este motivo existe na sintaxe suporte a variáveis globais. Mas num programa Orientado a Objetos não é uma boa prática usar variáveis globais.
Se mesmo assim desejar usar variáveis globais tenha em mente as seguintes regras:
1- Variáveis globais não estão relacionadas a nenhuma classe.
2- Elas são declaradas na seção INTERFACE da unit e quando usadas é boa prática seguir a sintaxe UnitNome.VariavelNome. Exemplo: UnitPessoa.QtdePopulacao := 1234;
3- Elas podem ser referidas em todas os códigos de programas, procedure, function e métodos que usam a unit na qual a variável está definida;
4- Elas podem ser inicializadas ou finalizadas nas seções INITIALIZATION E FINALIZATION da unit na qual está declarada.
Variáveis estáticas das classes "Class Var" seguem as seguintes regras:
1- São declaradas na definição da classe e seu valor é compartilhado por todas as instâncias da classe.
2- Métodos de classe podem fazer referência a elas;
Minha sugestão final:
1- Use variável global quando ela for armazenar informações relacionadas a Unit na qual está declarada, e não específicas de uma determinada classe desta unit;
2- Nos demais casos, use variável de classe que é mais elegante, mais elucidativa, e segue o que é definido como boa prática de OO.
Answer: Quando você declara uma variável no VAR na unit esta variável é estática e fica visível em qualquer local que importar a unit em questão.
Resumindo: Se unit1 tiver uma variável varDaUnit1 e unit2 uses unit1, unit2 pode acessar varDaUnit1 como se ela fizesse parte de unit2. Qualquer alteração em seu valor será refletido para outras units que utilizam unit1.
Ao declarar uma variável no public da classe ela é uma variável dinâmica, que é criada e destruída junto com a classe. A acesso a variáveis no public é via classe, por exemplo:
classe1.varDaClasseDecalradaNoPublic;

Quando trabalhava com Delphi a empresa onde eu trabalhava traçou um conjunto de regras quanto ao uso do var, desencorajando seu uso. A única situação onde vejo que o uso do var seja plausível seria caso precise de uma variável global compartilhada em várias telas do sistema, ex.: Usuário logado.


Debian Security Repos missing an OpenSSL Package

Question: I tried to build a Docker image and found that an OpenSSL related package is missing and apt is unable to correct the issue. This results in the image being unable to build. It seems like this is an issue with the Debian security repo. Thoughts?
Docker File: https://git.ulayer.net/snippets/44/raw
Error Output: https://git.ulayer.net/snippets/43/raw
Answer: The downloaded package lists are outdated. Your system knows about openssl version  1.1.1d-0+deb10u1, however recently 1.1.1d-0+deb10u2 was released which supercedes the old version.
You need you update the lists; even though your docker file has apt-get update, the output shows Using cache which is not useful in this case. Of course it's using a cached image in this case, not the cached apt info (although the cached image contains apt info).
It's probably easiest to combine the two steps apt-get update and apt-get install ...:
RUN apt-get update && apt-get install -y openvpn git netcat ca-certificates inetutils-ping curl wget dnsutils postgresql-client mariadb-client libssl-dev libxml2-dev libyaml-dev libgmp-dev libreadline-dev libz-dev libsqlite3-dev libpq-dev libmariadb-dev pkg-config libpcre3-dev libevent-dev build-essential sudo iptables htop procps apt-utils --fix-missing

This will prevent an image with outdated (or mismatched, if you prefer that term) apt data being cached.
Comment: I did not think about the image caching. Thank you for pointing this out :)


Como provar que a solução do algoritmo é ótima?

Question: Preciso argumentar que a solução encontrada após a execução do Algoritmo Guloso de Prim é ótima. Mas não sei como, alguém poderia ajudar?
Answer: O algoritmo de Prim serve para encontrar a árvore geradora mínima de um grafo, ou seja, uma árvore com o menor peso possível de suas arestas. Fonte: Wikipedia
Ele começa com qualquer nó arbitrário do grafo e coloca na árvore A. Em cada passo seguinte insere a aresta de menor peso que possui exatamente um vértice dentro da árvore A e outro fora de A, repetindo até todos nós serem adicionados.
A forma mais fácil de provar é por contradição. Mas para isso você tem que usar a propriedade do ciclo: "Para qualquer ciclo C do grafo, se o peso de uma aresta [e] do ciclo for maior do que de todas as outras arestas do ciclo, então [e] não pertence à árvore geradora mínima".

Assuma que aresta [e] pertence à árvore geradora mínima T;
Mostre que existe outra árvore geradora T' com custo menor que não utiliza [e];
Conclua que aresta [e] não pode pertencer à árvore geradora mínima T (contradição).

Outra forma de provar é por indução. A hipótese é que a cada iteração do algoritmo, a árvore A é um sub-grafo da árvore geradora mínima T.

Isso é trivial no primeiro passo, pois a árvore A possui apenas um nó e nenhuma aresta, e obviamente este nó precisa estar em T.
Agora suponha que em algum passo nós temos A (subgrafo de T) e o algoritmo de Prim diz para incluir a aresta [e]. Precisamos provar que A U [e] também é uma subárvore de alguma T. Se [e] pertence a T então isso é verdadeiro, pois por indução A é uma subárvore de T e [e] pertence a T, logo A U [e] é uma subárvore de T.
Agora suponha que [e] não pertence a T. Considere o que acontece quando adicionamos [e] à T. Isso cria um ciclo. Como [e] tem um vértice em A e um vértice fora de A (pois o algoritmo adicionou), tem que existir um aresta [e'] neste ciclo que possui exatamente um vértice em A. O algoritmo podia ter adicionado [e'], mas resolveu inserir [e], o que significa que o peso(e) <= peso (e'). Então se adicionamos [e] na árvore T e removemos [e'] nós acabamos com uma nova árvore T' cujo peso é <= ao peso de T e que contém [e]. Isso mantém a indução, e prova o teorema.


Problem on calculating conditional expectation by law of total expectation

Question:
Let $X$ be a standard normal distribution and let
$$ Y= \begin{cases}X-1 & , X\le 0 \\
    X &, X>0 \end{cases}$$
Find mean and variance of $Y$.

MY working
$$E(Y)=E(X-1\mid X\le 0)P(X\le 0)+E(X\mid X>0)P(X>0)$$
Now $E(Y)$ is $-\frac12$.
For variance
$$E((X-1)^2\mid X\le 0)P(X\le 0) +E(X^2\mid X>0)$$
But am unable to calculate $-2E(X\mid X\le 0)$
help!
Comment: Please format your mathematics using LaTeX.
Comment: MathJax tutorial: https://math.meta.stackexchange.com/q/5020/321264.
Answer: Since this is self-study (please tag and research!) I won't give you the answer, but the simple formula you are missing is the law of total variance:
$$\text{var}(X) = E(\text{var}(X|W)) + \text{var}(E(X|W))$$
Comment: Yes got it  thanks


glDrawElements extremally slow on Android ( HTC Wildfire )

Question: I'm testing OpenGL performance on an Android phone ( HTC Wildfire to be exact ), and I came across a strange thing - when I try to draw a textured indexed rectangle the size of the screen ( 320 x 480 ), I can get a framerate up to 40 fps!!! - and that's only when I use a 32x32 texture.
If I increase the texture size to 256x256, the performance drops down to 35 frames.
My question is - how is it possible for all those Android games to run smoothly and still be so full of cool graphics.
Answer: There are a bunch of different ways to eek performance out of your device.

Make sure you aren't doing blending, or drawing that you don't need and from experience a lot of the lower end HTC devices (eg the desire) are fill rate limited.
Use triangle strips instead of triangles.
Use draw elements and cache your calls eg load your vertex buffer and call draw multiple times for a frame.

But most importantly use the DDMS with method profiling to determine where your bottle necks actually are they may be places you don't expect them eg logging, gc, slow operation in a loop. You will be able to see how much of the time is due to rendering and how much for other operations. (look for GLImpl.glDrawElements)
My biggest ones were with GC kicking in too often (5 times per second and causing my fps to be very sluggish), something you will see with mem allocations often in places you won't even think of. Eg if you are concatenating a string to a float with the + operator or using traditional java get() functions everywhere or (worst) collections, these create a large number of objects that can trigger GC.
Also if you have expensive operations separate them out into a separate thread.
Also I am assuming you are creating your texture once and using the same index each time. I have seen some tutorials which create the texture every time a frame is rendered.
With extensive use of the DDMS I was able to take fps from 12 to 50 on the HTC Desire for a busy scene.
Hope that gets you going in the right direction :)
Comment: Like I mentioned, I'm testing the performance - so I'm using just one texture thats loaded and bound to the device only once, and then I'm just drawing two indexed triangles using GL10.GL_TRIANGLES call - nothing more. The thing is that those two triangles cover up the whole screen. So what worries me is that simply bit belting a texture the size of a screen to the back buffer COSTS THAT MUCH
Comment: Hi Paksas I'm currently using several dozen 128x128 textures with AI, collision detection and a bunch of other things going on and I'm able to achieve 40 - 50 fps on the HTC desire. 80% of my rendering time is currently spent drawing the menu and debug information and that is after heavily optimizing out all GC operations out with custom string handlers (My DrawNumber function takes 31% alone). If you post your code we can take a look at it but I would still highly recommend using the Method profiler and allocation tracker to see if your application is waiting anywhere before rendering.
Comment: Actually to compare the devices directly, run Smartbench 2011 free from the android store, and compare values. The desire gets 1134 for cpu and 546 for graphics. Thats should give us a relative scale between the devices.
Answer: In my own experience, they don't on devices like the wildfire.


Conditional probability involving 3 people shooting a target

Question: Suppose that $3$ people will shoot at a target, and that each will hit it with probability $0.9$, independently of whether or not any of the others hit the target. If Gary is one of the $3$ shooters, what is the probability that Gary will hit the target given that at least one of the three shooters will hit it?
Attempted Solution:
P(Gary hits | $1$ hit) = $1\over3$
P(Gary hits | $2$ hit) = $2\over3$
P(Gary hits | $3$ hit) = $3\over3$
P($1$ hit) = $3\choose1$$(.9)(.1^2) = .027$
P($2$ hit) = $3\choose2$$(.9^2)(.1) = .243$
P($3$ hit) = $3\choose3$$(.9^3) = .729$
Then P(Gary hits | $\geq 1$ hit) = $1\over{3}$$(.027)$+$2\over3$$(.243)$+$3\over3$$(.729)$ = $.9$
Is this a valid solution?
Comment: The unconditional probability that Gary hits is $0.9$.  The conditional probability given that someone hits it should be higher.  So I think your solution is incorrect.
Comment: Yeah I was worried about that. I think it should be slightly higher than $0.9$ since you're guaranteed that it's not the case that everyone misses their shot.
Answer: The probability that Gary hits and at least one hits is 0.9, since if Gary hits he counts as one of those who hit. The probability that at least one hits is the complement of the probability that nobody hits: $1-(1-0.9)^3=0.999$. Thus the probability that Gary hits given that at least one hits is
$$0.9/0.999=100/111=0.900900\dots$$
Answer: According to the total probability rule,
P(Gary hits)=1\over{3}(.027)+2\over{3}(.243)+3\over{3}(.729)=.9.
P(Gary hits|\geq 1 hit)=P("Gary hits" intersect "\geq 1 hit")/P(\geq 1 hit)=.9/.999=100/111


Proving the Probability Integral Transformation Theorem using MGF

Question:
Prove the probability-integral transformation, i.e., if $F_X$ is
continuous, then $F_X(x)\overset{d}{=}\mathsf{Unif}(0,1)$, by finding
the mgf of the random variable $Y=F_X(X)$ where $X$ is absolutely
continuous and has cdf $F_X$.

This is easy to show by noting that
$$\mathsf P\left(F_X(X)\geq x\right)= \mathsf P\left(X\geq F_X^{-1}(x)\right) = 1-F_X\left(F_X^{-1}(x)\right)=1-x\tag{1}$$
but I'm having trouble showing this by mgf. Since the mgf of a $\mathsf{Unif}(0,1)$ random variable is given by $\frac{e^t-1}{t}$ then we need to show that
$$M_Y(t)=\int_{-\infty}^{\infty} e^{tY} f_Y(y)dy = \frac{e^t-1}{t}$$
The only way I can think about showing this is by noting that
$$\begin{align*}
M_Y(t)
&=\int_{-\infty}^{\infty} e^{ty} f_Y(y)dy\\\\
&= \int_{-\infty}^{\infty} e^{ty} dF_Y(y)\\\\
&= \int_{0}^{1} e^{ty} dy\\\\
&=\frac{e^t-1}{t}
\end{align*}$$
but this requires the knowledge that $F_Y(y)=y$ which is already sufficient to showing that $Y\sim\mathsf{Unif}(0,1)$. Is there a way to show this without making use of (1)?
Answer: Your idea is the correct one, but you need to take a slightly different route to get to the end.
To be rigorous, we ought to be working with the characteristic function (cf) of $Y=F_X(X),$ which (unlike the mgf) always exists and determines the distribution.  (If you don't like this, simply erase all occurrences of "$i$" in the following.)
Let's just plug stuff into the definition of the cf, which begins these equalities.
$$\begin{aligned}
E\left[\exp(it\,Y)\right] &= E\left[\exp\left(it\,F_X(X)\right)\right] & \text{definition of } Y\\
&= \int_{\mathbb{R}} \exp\left(it\, F_X(x)\right)\,\mathrm{d}F_X(x)& \text{expectation formula} \\
&= \int_0^1 \exp(it\,y)\,\mathrm{d}y & \text{formal substitution }y=F_X(x)\\
&= \frac{e^{it}-1}{it}.
\end{aligned}$$
This derivation only required knowing that

$F_X$ is the cdf of a continuous variable (if you use the Lebesgue-Stieltjes integral) or at least differentiable (if you use the Lebesgue integral) and

$F_X:\mathbb{R}\to[0,1]$ is a one-to-one function.

No assumptions about $F_Y$ were made (or harmed) in the derivation of this result.
Comment: "No assumptions about $F_Y$ were made (or harmed) in the derivation of this result." Nice!
Comment: By [the LOTUS,](https://stats.stackexchange.com/search?q=lotus) the expectation of a function $g(X)$ is $$E[g(X)] = \int_{\mathbb{R}} g(x)\,\mathrm{d}F_X(x).$$Apply this to the function $g(x)=\exp(itF_X(x)).$
Comment: Thanks! The only thing I don't understand is where $d F_X(x)$ comes from. Why is it not $d F_Y(y)$?


What is the anticommutator of the interior product and codifferential (adjoint of exterior derivative)?

Question: What is $\eta=i_X \delta + \delta i_X$ acting on differential forms? Here $\delta$ is the usual Hodge adjoint of the exterior derivative and $i_X$ is contraction of a form with the vector field $X$. Clearly $\eta=0$ trivially on 0-forms and 1-forms, but does this hold for forms of arbitrary degree?
Comment: I think you mean "adjoint" rather than "Hodge dual" in the second sentence?
Answer: Clifford algebra might make this manipulation easier: its geometric product of vectors (or forms) is associative like the wedge product, but still has the metrical terms needed for the codifferential.
In clifford notation, we have,
$$\eta(\alpha) = X \rfloor (\nabla \rfloor \alpha) + \nabla \rfloor (X \rfloor \alpha)$$
You can see here that the contraction operator $\rfloor$ plays a similar role in relating $\nabla \rfloor$ to $\delta$ as it does in relating $X \rfloor$ to $i_X$.
Now we can use associativity of the geometric product to our advantage, considering the grade $k-2$ terms of a general product:
$$\langle \nabla (X \alpha) \rangle_{k-2} = (\nabla \wedge X) \rfloor \alpha - (X \wedge \nabla) \rfloor \alpha = \nabla \rfloor (X \rfloor \alpha)$$
Expand the $(X \wedge \nabla) \rfloor \alpha$ term as
$$\langle X \nabla \alpha \rangle_{k-2} = (X \wedge \nabla) \rfloor \alpha = X\rfloor (\nabla \rfloor \alpha)$$
So we can conclude that the anticommutator is
$$\eta(\alpha) = (\nabla \wedge X) \rfloor \alpha$$
Hm, I'm not familiar with how this should be denoted in pure differential forms.  $\nabla \wedge X$ ought to be something like $dX$, but since $X$ isn't a form (it's a vector field), that's a little weird.  Similarly, $(\nabla \wedge X) \rfloor \alpha$ ought to read like an interior product into $\alpha$, but with 2-vector (or a 2-form, or a mixed 1-vector/1-form) into $\alpha$.
Comment: I don't know much geometric algebra and so struggle to see how this argument makes sense. Even if $\nabla \wedge X$ is to be viewed as a 1-form and $\alpha$ as a $k$-form how is $\nabla \wedge X \rfloor \alpha$ supposed to be a $(k-2)$-form?
Comment: $\nabla \wedge X$ is grade-2.
Comment: $\delta$ is metric-dependent, so it shouldn't be expected that $\eta$ could be expressed with $d$ and $\iota$, which are metric-independent.
Answer: You can easily verify that
$$\nabla_Y \iota_X \omega = \iota_X \nabla_Y \omega + \iota_{\nabla_YX} \omega$$
for vector fields $X$ and $Y$. For the codifferential, we have the formula
$$\delta = - \sum_{j=1}^n \iota_{e_j} \nabla_{e_j} \omega$$
which holds for any orthonormal frame $e_1, \dots, e_n$. Hence
$$\delta \iota_X \omega = - \sum_{j=1}^n \iota_{e_j} \nabla_{e_j}\iota_X \omega = - \sum_{j=1}^n \iota_{e_i}\bigl(\iota_X \nabla_{e_i}\omega + \iota_{\nabla_{e_i}X} \omega \bigr) = \sum_{j=1}^n \iota_X \iota_{e_i} \nabla_{e_i}\omega - \sum_{j=1}^n\iota_{e_i}\iota_{\nabla_{e_i}X} \omega$$
where we used that $\iota_X \iota_Y = -\iota_Y \iota_X$ for all vector fields $X$ and $Y$. This can be written as
$$\delta \iota_X \omega + \iota_X \delta \omega = -\iota_{\nabla \wedge X} \omega$$
where
$$\nabla \wedge X := e_i \wedge \nabla_{e_i} X$$
is an anti-symmetric bi-vector.


Problem with assembly statements in gcc

Question: I encountered a piece of assembly code in a C program I was trying to run in FreeBSD 64-bit.
<code>void  *curbrk;
__asm__ __volatile__(
        "movl .curbrk, %%eax;"
        "movl %%eax, %0"
            : "=r" (curbrk)
            :: "%eax"
    );
</code>
I get an error like "mov missing suffix or operand".(The above code follows AT&T syntax) What determines the syntax i should use for the code - The compiler (gcc follows AT&T syntax) or the processor (I'm working on an Intel Processor). Is the problem due to the fact that the code is in AT&T syntax or is there anything else I'm missing?
Answer: If you have a 64-bit GCC, the above code will not complete unless you use the -m32 switch to output 32-bit object code, because the 64-bit pointer value will not fit into the 32-bit EAX register.  Either use -m32 to generate 32-bit output, or use rax inplace of eax and change the movl's to mov (without 'l')
Comment: @Pascal: You can use both `mov` and `movq`: `mov` instructs the assembler to "guess" the target data size, whereas `movq` states that we are talking about 64-bit values. For instance, `mov 0, foo` will not compile, because the assembler does not know the size of the variable `foo`, whereas `mov 0, %%rax` will be implicitly understood as a `movq` because `%rax` is a 64-bit register. Note that GCC does not understand any of the above: with inline assembly, GCC just dumps the string into the generated assembly (after replacing the `%`-things): the _assembler_ deals with it.
Comment: Do you know the rationale for picking `mov` instead of `movq` in GCC's inline assembly syntax for amd64 instructions?

Problem with assembly statements in gcc


Piano scales: Why bother with hands together?

Question: During my first ten years studying classical piano, the scales that I played were hands together, parallel.  But the only literature that actually has scales in both hands, for more than one bar per page, is quite advanced and non-solo: Brahms piano trios, Beethoven piano concertos, and maybe some simpler Mendelssohn piano duets.  But nothing that a kid would play in a recital.
If the point of drilling things like scales is to prepare the student for the solo keyboard literature from Bach through Liszt, then why not one hand at a time, as scales actually occur?  Learning one hand at a time has many advantages, which I won't belabor.
On the other, ahem, hand, if the more important goal is hand independence, then why not drill right hand C major in triplets against left hand F sharp minor in sixteenths starting five notes late?  Or at least against an Alberti bass, as in the Mozart sonatas?
Answer: There are a few reasons that I found these technical drills helpful as a piano player:

They help practice playing the hands together clearly and cleanly. Young piano players often play both hands "together," but the articulations between the hands are not actually in sync. As such, the result is one of constant flam and grace-note relationships between the two hands. Playing scales (or any technique) with both hands together (especially in octaves) makes it very clear to the performer when the hands are and are not exactly together.
They practice balance between the hands. Young piano players often inadvertently play one hand more loudly than the other. Practicing scales with both hands together helps teach the young performer about balance. Similarly, it gives them an opportunity to practice bringing one hand out above another if they so desire.
Lastly, the practical reason: it saves time. Why waste time playing hands apart when you can do both hands at once? Of course you can only play one hand if you're focusing on some particular technical aspect, but otherwise, there's too much music in the world and not enough time; do your scales with both hands together and get to music more quickly!
Comment: Another nice little exercise is playing with both hands, but not together, instead, l,r,l,r,l,r, going up scales note by note, if that makes sense. Helps timing and independence.
Comment: Another advantage is that it's relatively obvious what it *should* sound like when done right.  You mention the grace-note relationships between the hands.  You could easily come up with other drills which help with this, but it wouldn't be quite as obvious when done properly.
Comment: Efficiency is the answer!
Answer: It's true that not a lot of music has parallel scales for extended runs. But a lot of methods involve playing things that never show up in real music, so that's entirely normal. The point of these exercises isn't to practice something that you will use directly in real music, but to develop a skill more generally.

On the other, ahem, hand, if the more important goal is hand independence, then why not drill right hand C major in triplets against left hand F sharp minor in sixteenths starting five notes late?

"Hand independence" is a bit of a misnomer. The goal isn't to have two hands that can do two completely different things, the goal is to be able to use both hands to achieve one idea, even if their contributions are different. With scales, you're using different fingers in each hand at the same time, and crosses happen at different times. Very different activities that need to be coordinated precisely. As Richard points out, scales in octaves make it painfully clear when there's imperfect timing.
Comment: I agree. "Hand independence" isn't really a thing. It's really about finger independence.  And that happens in both hands at the same time.  Again, the finger crossing while playing scales (and arpeggios) hands together gives opportunity to practice some of that.
Answer: One hand will teach the other. Plain and simple.  There are ergonomic movements that are required for effortless playing.  If you have it in one hand, playing the hands together will train the weaker hand.  Did I say "hand?"  I meant ARM.
Comment: This sounds mystical.  Can you give a concrete example of what you mean?  ("If, say, E flat minor ascending is easier in the right hand, then I should improve the left hand by playing hands together, rather than left hand alone.")
Comment: Ha!  Oscar Peterson said in a Jazziz article that it was "mystical" and I, too, laughed. So did many others. However, I have since learned that there are proper ways to move and many improper ways to move. Let's see how much I can squeeze in here. With all 5 fingers TOGETHER wave bye bye. Now abduct them and wave. Feel the tension? You don't want that in your playing. It is two muscles pulling 1 bone in 2 directions. That is what causes tension, weakness, cramps and sloppy playing cuz your hand is being pulled in multi directions. When 1 hand learns not to abduct, your BRAIN
Comment: will make the other hand do it too. It is not mystical, it is symmetry, BUT each motion is reversed. EX 2: Without abducting your thumb, use gravity and lower it down on a key. You did not use your finger but gravity and arm weight. Now use your pronator to rotate the thumb into a key, again, you did not use your thumb's abductor. Now from the shoulder forward poke a key. Again, no thumb muscle used. Combine all three and your thumb is effortless. Oscar called it "living thumb." Find a Feldenkrais PIANO BASED teacher to learn other movements. Keep in mind all your bad habits are hardwired
Comment: into your brain and it can take years to undo them. That is why your first teacher before you ever touch a keyboard had better be the right one.  That is why some of us are merely mediocre while others are virtuoso.
Comment: These comments riff on many themes, but they don't address the original question.  If the posted answer actually advises the avoidance of simultaneously contracting an opposed pair of flexor and extensor muscles, then it doesn't address the question either.


html textual link hover background image

Question: There is a background inside the div. Then I would write a list of links, which then pass over the background image, but it not seems to work.
If the link is located above the background mage, hovering the mouse on that, I do not get the underline of the text as for all other links that are not above the image background.
This is my code:

    My link here

Sorry for my English, the concept is really easy to understand but hard to explain ... I hope to be able to explain.
Thanks to all, Danilo

Edit:
I found the error ... if you do not use "absolute" propriety in both div, z-index non work.
Thanks for the suggestions! ;-)
Comment: Try to post an example on [JsFiddle](http://jsfiddle.net/) - it will be easier to understand what you are trying to do!
Comment: Please post your own answer and accept it, so that the question will be made closed. It might also earn you a few upvotes.
Answer: Hard to understand, but I'll try:
1) If you have a link above the div with background, try with a different value of z-index on the link or setting a paddin on the link, so the div goes down and you'll see the underline.
2) If you want to have a list over the image background, insert it IN the div with background.
Comment: sorry, it was "setting a padding-bottom" on the link: with this property the div with background will goes down and you will see the underline.
Comment: I am in the first case. With the z-index does not work. What does "setting at paddin"?
Answer: I found the error ... if you do not use "absolute" propriety in both div, z-index non work.
Thanks for the suggestions! ;-)


Is it possible to get all the eigenclasses in Ruby?

Question: Getting a list of all modules is easy in Ruby:
ObjectSpace.each_object(Module).to_a

However, is it possible to get a list of all eigenclasses (also known as singleton classes or metaclasses)? Or are eigenclasses invisible?
I tried
str = "foo"
my_metaclass = class << str; self; end
my_metaclass.class == Class # my_metaclass' class is Class
ObjectSpace.each_object(Class).include?(my_metaclass) # false
ObjectSpace.each_object.include?(my_metaclass) # still false
# Just to show each_object works
ObjectSpace.each_object(Class).include?(String) # true

I'm trying to get eigenclasses because I'm wanting to list all the methods that are defined within a script. I could look for all the instance methods defined by modules and classes, and then look for singleton methods of modules and classes (or of all objects, if I want to chew up CPU), but that seems a little hackish.
Comment: Did you end up finding an answer to this? nice question ;)
Comment: I couldn't find a way to do this without calling each_object on each class.  One thing I did notice though was that ObjectSpace.count_objects() :T_CLASS count increments with each eigenclass created.  So it may be possible to do this in C land?
Comment: @DanHealy: What do you mean by `each_object` on each class? As in `classes = ObjectSpace.each_object(Class).to_a; objects = classes.map{|klass| ObjectSpace.each_object(klass).to_a}.flatten`?
Comment: I was basically referring to the method you suggested in your question: iterating over all objects.
Comment: woohoo! I love this question.
Comment: You must be doing something seriously meta. =P
Comment: @thomasfedb: I'm working on something where, if there's a method_missing that doesn't get handled, it says something like ":foo isn't implemented in YourFirstClass, but it's implemented in YourOtherClass". I need to put it on github soon.
Answer: If you mean objects that have singleton methods, this should work.
eigens = []
ObjectSpace.each_object do |object|
  eigens << object unless object.singleton_methods.empty?
end

If not, could you clarify?  I used this discussion as a reference:
http://www.ruby-forum.com/topic/77046
Comment: The main disadvantage of this approach is that iterating through each object seems inefficient.
Comment: It is. :-)  Is this something you need to do frequently in your program? I'm keen to see what you're up to, if you're able to share.
Answer: I doubt this is what you want, but it should return all eigenclasses:
eigens = ObjectSpace.each_object.collect { |obj| class << obj; self; end }

That will indeed assign an array of all the eigenclasses to the variable eigens. The thing is, Ruby implementations likely don't actually create an eigenclass unless there is a need for it, and this code (I believe) will actually create the eigen classes even for the objects where one wasn't needed.
If finding a better way is important, I'd tweet the question to one of the implementors of any of the Ruby implementations (@yukihiro_matz, @evanphx, @headius to name a few that come to mind). If anybody would know, they would.
Answer: As of MRI 1.9, eigenclass enumeration does NOT seem to be supported. As a (semi-)consequence, there is no 100%-reliable way to iterate over all methods. The best approximation for an overall method enumerator is as follows
methods = []

ObjectSpace.each_object { |x|
  if x.kind_of?(Module)
    methods += x.public_instance_methods(false) +
               x.protected_instance_methods(false) +
               x.private_instance_methods(false)
  end
  methods +=   x.singleton_methods(false)
}

However, this code will NOT enumerate

private methods owned by 1st eigenclasses,
methods owned by 2nd, 3rd, ... eigenclasses.


Sort two lists in python?

Question: I am counting some occurrences of words in a text, and I have two lists : the first contains the words, the second contains the occurrences.
So at the end of the analysis I have something like
listWords : ["go", "make", "do", "some", "lot"]
listOccurrences: [2, 4, 8, 1, 5]

And I want to sort those two lists following listOccurrences DESC, so I would have :
listWords : ["do", "lot", "make", "go", "some"]
listOccurrences: [8, 5, 4, 2, 1]

Is there any way I can do this ? Or do you know any other way more "natural" than two lists ? (Like a single "list" where every occurrence is referenced by a word)
Comment: One way is using [zip](https://docs.python.org/dev/library/functions.html?highlight=zip#zip). You may also want to use an [OrderedDict](https://docs.python.org/dev/library/collections.html#collections.OrderedDict).
Answer: >>> listWords = ["go", "make", "do", "some", "lot"]
>>> listOccurrences = [2, 4, 8, 1, 5]
>>> listTmp = zip(listOccurrences, listWords)
>>> listTmp
[(2, 'go'), (4, 'make'), (8, 'do'), (1, 'some'), (5, 'lot')]
>>> listTmp.sort(reverse=True)
>>> listTmp
[(8, 'do'), (5, 'lot'), (4, 'make'), (2, 'go'), (1, 'some')]
>>> zip(*listTmp)
[(8, 5, 4, 2, 1), ('do', 'lot', 'make', 'go', 'some')]
>>> listOccurrences, listWord = zip(*listTmp)

Note that the obvious data type for a key:values pairs (here : word:count) is a dict. FWIW you may want to have a look at collections.Counter.
Edit : For the sake of completeness: you can also use the builtin sorted() function instead of list.sort() if you want to cram all this in a single line statement (which might not be such a good idea wrt/ readability but that's another story):
>>> listWords = ["go", "make", "do", "some", "lot"]
>>> listOccurrences = [2, 4, 8, 1, 5]
>>> listOccurrences, listWords = zip(*sorted(zip(listOccurrences, listWords), reverse=True))
>>> listWords
('do', 'lot', 'make', 'go', 'some')
>>> listOccurrences
(8, 5, 4, 2, 1)

Answer: Another way of doing this to have your data in a dictionary. As you are counting occurrence of word therefore listwords will have unique words and use can use it as dictionary key. You can use python sorted method to sort the keys and values in same order.
listWords = ["go", "make", "do", "some", "lot"]

listOccurrences = [2, 4, 8, 1, 5]

dict = {}

i=0

while(len(listWords) > i):

    dict[listWords[i]] = listOccurrences[i];

    i = i + 1

print sorted(dict, key=dict.get, reverse=True)

print sorted(dict.values(), reverse=True)

Answer: I'd use a Counter. Here's the pointless one-liner :)
from collections import Counter

listWords, listOccurences = map(list, zip(*Counter(dict(zip(listWords, listOccurrences))).most_common()))

And as readable code you should use:
from collections import Counter

listWords = ["go", "make", "do", "some", "lot"]
listOccurrences = [2, 4, 8, 1, 5]

counter = Counter(dict(zip(listWords, listOccurrences)))

print(str(counter))
# Counter({'do': 8, 'lot': 5, 'make': 4, 'go': 2, 'some': 1})

# Want lists again?

listWords, listOccurences = map(list, zip(*counter.most_common()))

print(listWords)
# ['do', 'lot', 'make', 'go', 'some']

print(listOccurrences)
# [8, 5, 4, 2, 1]

Neat conversion back to lists provided thanks to Jon Clements.
Also, you might want to use a Counter to collect the frequency data in the first place (from here):
import collections

c = collections.Counter()
with open('/home/me/my_big_file_o_words') as f:
    for line in f:
        c.update(line.rstrip().lower())

print('Words ordered by most common:')
for letter, count in c.most_common():
    print(letter + ": " + count)

Finally: it's considered stylish to use underscores in variable names in Python, not camelCase. Maybe change to list_words and list_occurrences? :)
Answer: One-liner:
[listWords[i] for i, k in sorted(enumerate(listOccurrences), key=itemgetter(1), reverse=True)]

i.e.:
In [62]: from operator import itemgetter
In [63]: listWords = ["go", "make", "do", "some", "lot"]
In [64]: listOccurrences = [2, 4, 8, 1, 5]
In [65]: [listWords[i] for i, k in sorted(enumerate(listOccurrences), key=itemgetter(1), reverse=True)]
Out[65]: ['do', 'lot', 'make', 'go', 'some']

Comment: shorter one-liner: `list(zip(*sorted(zip(listOccurrences,listWords),reverse=True))[1])`

Sort two lists in python?


Making Blur Specific Area in CameraView with Swift?

Question: i have a side project that contains this screen below link. It is important that i want to create this screen in camera view, not in the picture.
I am thinking about dealing with Metal for this. how can i write this code, any suggestions will be appreciated. Thank you.
https://gofile.io/?c=Wan0H9
Comment: This question is a bit broad. Have you looked at Apple's [AVCamFilter](https://developer.apple.com/documentation/avfoundation/cameras_and_media_capture/avcamfilter_applying_filters_to_a_capture_stream?language=objc) sample? It shows how to apply Core Image filters to a live camera feed. From there, it's just a matter of selecting the right filter chain (`CIMaskedVariableBlur` looks like a good choice here) to get the desired effect.
Comment: I think the impulse to keep everything on the GPU and leverage Metal is a good one. I think you may in fact need to use Metal to efficiently capture and display the video content. I just also happen to think that there are good existing high-level facilities (Core Image and MetalPerformanceShaders) that can make the tasks of filtering and compositing a bit easier.
Answer: Not sure if this is going to work but if I were you I would create 4 different views (with semi transparent blur effect) as shown in the image below.

Hope it helps!
Comment: Good idea but how can i implement this idea in code with Metal? it is the hardest part.
Answer: there are 2 steps:
(i) first get complete blurred image from basic
<code>CIFilter *filter = [CIFilter filterWithName:@"CIGaussianBlur"];
</code>
(ii) With UIGraphicsContext, you can set blurred image as background image then crop original image and put over blurred image.
Then you can get resulted image from context.
Thats it.
Comment: thank you for your answer but i want to use it in live camera view, not image. Any suggestion?
Comment: yes, there is third party GpuimageView that support blur on camera with control on frame : (Y)


postfix, spam assassin, swiftmailer

Question: Linux webserver, running a local postfix mail server, PHP web systems on apache. Postfix is configured to pass emails to spampd for spam checking but local networks are exempted:
smtp       inet  n       -       y       -       20      smtpd
-o smtpd_proxy_filter=127.0.0.1:10025
-o smtpd_client_connection_count_limit=10 127.0.0.1:10026 inet n  -       n       -        -      smtpd
    -o smtpd_authorized_xforward_hosts=127.0.0.0/8
    -o smtpd_client_restrictions=
    -o smtpd_helo_restrictions=
    -o smtpd_sender_restrictions=
    -o smtpd_recipient_restrictions=permit_mynetworks,reject
    -o smtpd_data_restrictions=
    -o mynetworks=127.0.0.0/8
    -o receive_override_options=no_unknown_recipient_checks

This works for all our websystems except the newest, which is running Yii2 and Swiftmailer.  Emails from this system are being passed to spampd unnecessarily and this is slowing response times dramatically.
Here is a typical mail log showing the problem:
Sep 17 10:37:33 ip-172-31-12-147 postfix/smtpd[28970]: connect from localhost[127.0.0.1]
Sep 17 10:37:33 ip-172-31-12-147 postfix/smtpd[28990]: NOQUEUE: client=localhost[127.0.0.1]
Sep 17 10:37:33 ip-172-31-12-147 postfix/smtpd[28970]: E3526409A9: client=localhost[127.0.0.1], orig_client=localhost[127.0.0.1]
Sep 17 10:37:33 ip-172-31-12-147 spampd[23514]: processing message <email@example.com> for <***@cbdweb.net>
Sep 17 10:37:39 ip-172-31-12-147 spampd[23514]: clean message <firstname.lastname@example.com> (-102.90/5.00) from <***@cbdweb.net> for <***@cbdweb.net> in 5.14s, 1250 bytes.
Sep 17 10:37:39 ip-172-31-12-147 postfix/cleanup[28971]: E3526409A9: message-id=<firstname.lastname@example.com>
Sep 17 10:37:39 ip-172-31-12-147 postfix/qmgr[20013]: E3526409A9: from=<***@cbdweb.net>, size=1753, nrcpt=1 (queue active)
Sep 17 10:37:39 ip-172-31-12-147 postfix/smtpd[28990]: proxy-accept: END-OF-MESSAGE: 250 2.0.0 Ok: queued as E3526409A9; from=<***@cbdweb.net> to=<***@cbdweb.net> proto=ESMTP helo=<alpinebookings.cbdweb.net>
Sep 17 10:37:39 ip-172-31-12-147 postfix/smtpd[28970]: disconnect from localhost[127.0.0.1] ehlo=1 xforward=1 mail=1 rcpt=1 data=1 quit=1 commands=6
Sep 17 10:37:39 ip-172-31-12-147 postfix/smtpd[28990]: disconnect from localhost[127.0.0.1] ehlo=1 mail=2 rcpt=2 data=2 quit=1 commands=8
Sep 17 10:37:39 ip-172-31-12-147 postfix/smtp[28983]: E3526409A9: to=<***@cbdweb.net>, relay=ip-172-31-11-15.ap-southeast-2.compute.internal[172.31.11.15]:25, delay=5.2, delays=5.2/0/0.01/0, dsn=2.0.0, status=sent (250 Message accepted for delivery)
Sep 17 10:37:39 ip-172-31-12-147 postfix/qmgr[20013]: E3526409A9: removed

Compare to email sent by a wordpress site on the same server:
Sep 17 11:00:04 ip-172-31-12-147 postfix/pickup[27803]: 33917409AA: uid=33 from=<apache>
Sep 17 11:00:04 ip-172-31-12-147 postfix/cleanup[30456]: 33917409AA: message-id=<email@example.com>
Sep 17 11:00:04 ip-172-31-12-147 postfix/qmgr[20013]: 33917409AA: from=<***@cbdweb.net>, size=847, nrcpt=1 (queue active)
Sep 17 11:00:24 ip-172-31-12-147 postfix/smtp[30458]: 33917409AA: to=<***@***.com>, relay=mx1.***.com.au[220.127.116.11]:25, delay=20, delays=0.05/0/0.08/20, dsn=2.0.0, status=sent (250 Ok: queued as 2F3701100075)
Sep 17 11:00:24 ip-172-31-12-147 postfix/qmgr[20013]: 33917409AA: removed

The Yii2 configuration of the mailer is:
'mailer' => [
        'class' => 'yii\swiftmailer\Mailer',
        // send all mails to a file by default. You have to set
        // 'useFileTransport' to false and configure a transport
        // for the mailer to send real emails.
        'useFileTransport' => false,
        'transport' => [
            'class' => 'Swift_SmtpTransport',
            'host' => $params['level'] === 'DEV' ? '***.cbdweb.net' : '127.0.0.1',
            'port' => '25'
        ],
    ],

Comment: Your WordPress installation is dropping mail directly into the local mail spool by calling the sendmail command. But your swiftmailer code is connecting via SMTP (over the network). It could be configured to also use sendmail as its transport; see [so] for help on writing the necessary PHP code to do that. There is nothing in your Postfix configuration that exempts this mail from being passed to SpamAssassin, and it's not clear why you think that there is. Can you clarify this?
Comment: Thanks your answer is spot on.  If you would like to make it the answer I will mark it as correct.
The Yii2 configuration to use is
'mailer' => [
            'class' => 'yii\swiftmailer\Mailer',
            'useFileTransport' => false,
            'transport' => [
                    'class' => 'Swift_SendmailTransport'
                ]
            )
        ],
This uses a default value for the sendmail command which worked for me on Ubuntu, I suspect this is equivalent to 'command'=>'/usr/sbin/sendmail -bs' but Yii2 doesn't provide any documentation on this.
Comment: I'll ask a separate question on how to stop postfix from sending mail to spampd when the connecting server is localhost. I'd like to compare this config with using sendmail directly, because at the moment bounces aren't going to the return-path address, they are going to the webserver admin. I wonder if using SMTP would fix this.
Comment: Follow up question is at https://serverfault.com/questions/984531/how-to-stop-postfix-from-forwarding-mail-to-spampd-when-connection-is-from-local
Answer: Instead of using sendmail, it is possible to avoid the milter (mail filter) problem by using the SMTP port that postfix listens on for output from the milter.  This is fully explained in my answer to the follow-up question at How to stop postfix from forwarding mail to spampd when connection is from localhost

postfix, spam assassin, swiftmailer


How to return an item (if it exists) preferably over another?

Question: I'm working on a system and I need a query to return preferably a client's cellphone number, but if they didn't insert one, return their home number.
Here's how the tables look like (they can't be changed):
CREATE TABLE Clients
(
    id_client int PRIMARY KEY, /* client's id */
    nm_client varchar(200), /* client's name */
    zipcode int
);

CREATE TABLE PhoneType
(
    cd_phoneType int PRIMARY KEY, /* 1 for landline 2 for cellphone */
    nm_phoneType varchar(60) /* "Landline" if the above is 1 or "Cellphone" if 2*/
);

CREATE TABLE Phones
(
    cd_phone int PRIMARY KEY,
    cd_phoneType int, /* 1 for landline 2 for cellphone */
    nu_phone VARCHAR(20), /* phone number */
    id_client INT, /* client's id */
    FOREIGN KEY (cd_phoneType) REFERENCES PhoneType(cd_phoneType)
    FOREIGN KEY (id_client) REFERENCES Clients(id_client)
);

Basically, if cd_phoneType = 2 for a client, it should return his cellphone number, otherwise return his other number. How do I do this in SQL syntax?
Here's the initial code I made:
SELECT nm_client, nm_phoneType, nu_phone
FROM Clients
JOIN Phones ON Clients.id_client = Phones.id_client
JOIN PhoneType ON PhoneType.cd_phoneType = Phones.cd_phoneType;

Comment: How many clients are you selecting at any one time?
Answer: First, let's turn the data from "2 rows with one phone number each per client" into "one row of 2 phone number columns per client"
SELECT
  nm_client,
  MAX(CASE WHEN nm_phoneType = 1 THEN nu_phone END) as landline,
  MAX(CASE WHEN nm_phoneType = 2 THEN nu_phone END) as mobile
FROM Clients
JOIN Phones
ON Clients.id_client = Phones.id_client
GROUP BY nm_client

When you see how this works, now you can use COALESCE, a function that works through the argument list from left to right and returns the first non null argument it finds:
SELECT
  nm_client,
  COALESCE(
    MAX(CASE WHEN nm_phoneType = 2 THEN nu_phone END),
    MAX(CASE WHEN nm_phoneType = 1 THEN nu_phone END)
  ) as pref_num
FROM Clients
JOIN Phones
ON Clients.id_client = Phones.id_client
GROUP BY nm_client

--
If you're only ever selecting one client at a time a shortcut can be achieved by TOP ORDER BY:
SELECT TOP 1
  nm_client,
  nu_phone
FROM Clients
JOIN Phones
ON Clients.id_client = Phones.id_client
WHERE clients.id_client = 1234
ORDER BY nm_phonetype DESC --prefer 2 over 1

Comment: Thank you very much. It should only return one client at a time, so the last one works pretty well. Thank you for the input about the Coalesce command as well, I didn't know about it.
Comment: Awesome. If you ever want to do a report of all people and their preferred contact, the top one is the one to use. To mark an answer as accepted, click the faint grey tick under the number/updown arrows so it turns green. Welcome to the site! May it long be a useful resource for you
Answer: Use APPLY:
SELECT c.nm_client, c.nm_phoneType, p.nu_phone
FROM Clients c OUTER APPLY
     (SELECT TOP (1) p.*
      FROM Phones p
      WHERE c.id_client = p.id_client
      ORDER BY (CASE WHEN p.cd_phoneType = 2 THEN 1 ELSE 2 END)
     );

You can also phrase this as a correlated subquery (because you want only one column and one row in the matched table).
Comment: That's another insteresting way of doing it. Thanks!
Comment: Quick q Gordon; did you do your order by like that rather than "order by desc" because of potential extensions if there were 3+ types that weren't necessarily numerically ordered (e.g. Prefer 2,1,3 in that order) ?
Comment: @CaiusJard . . . The OP does not specify that there are only two phone types, only that number 2 should be first.
Comment: Interesting; I parsed his post differently (he only ever talks about/defines two types of phone in e.g. the comments of the DDL or the opening sentence). One for future readers of these respective techniques to note
Comment: @PHTessmer . . . Is there a reason you no longer prefer this solution?


$\frac{\sin(\pi x)}{\pi x}$ is differentiable in $0$

Question: Define a function $g:\mathbb{R}\rightarrow\mathbb{R}$ by $g(x)=\frac{\sin(\pi x)}{\pi x}$  if $x\neq0$ and $g(x)=1$ if $x=0$. I want to show that $g$ is two times differentiable and i want to compute $g'(0)$ and $g''(0)$. Can someone help me with this? Can you do something with L'Hospital? since both functions are differentiable? Or do you have to do something more basically? Thanks a lot.
Comment: What do you know about power series? Do you know the Taylor/MacLaurin series of $\sin$?
Comment: Welcome to MSE! Since you are new, I wanted to let you know a few things about the site. In order to get the best possible answers, it is helpful if you say in what context you encountered the problem, and what your thoughts on it are; this will prevent people from telling you things you already know, and help them give their answers at the right level.
Comment: You can't use l'Hospital rule as it requires differentiability, and you don't know yet if the function actually is differentiable. You would better use the differentiability definition: the function has a derivative in $x=0$ [iff](http://en.wikipedia.org/wiki/If_and_only_if)...? Try it and show your progress.
Answer: It's better to consider
$$
G(x)=\begin{cases}
\dfrac{\sin x}{x} & \text{if $x\ne0$}\\[6px]
1 & \text{if $x=0$}
\end{cases}
$$
because $g(x)=G(\pi x)$ and $g$ is (twice) differentiable if and only if $G$ is.
The function $G$ is continuous at $0$, by a well known limit. The derivative, for $x\ne0$, is
$$
G'(x)=\frac{x\cos x-\sin x}{x^2}
$$
and
$$
\lim_{x\to0}G'(x)=
\lim_{x\to0}\frac{x(1-\frac{1}{2}x^2+o(x^2))-x+\frac{1}{6}x^3+o(x^3)}{x^2}=0
$$
Thus $G$ is differentiable at $0$, by l'Hôpital. Consequently, $g'(0)=\pi G'(0)=0$.
Can you compute the second derivative and argue similarly?

There's an alternative way, with Taylor expansion:
$$
\sin(\pi x)=\pi x-\frac{\pi^3 x^3}{3!}+o(x^3)
$$
so
$$
g(x)=1-\frac{\pi^2 x^2}{6}+o(x^2)
$$
so (in a neighborhood of $0$),
$$
g'(x)=-\frac{\pi^2 x}{3}+o(x)
$$
and
$$
g''(x)=-\frac{\pi^2}{3}+o(1)
$$
so $g''(0)=-\pi^2/3$.
Comment: I think the second derivative in $0$ is equal to $-\pi^2/3$. Is this correct?
Comment: @SonyaWatkins Yes; I added an alternative way.
Answer: At zero, the function is continuous and you can use the bilateral definition of the first derivative,
$$\lim_{h\to0}\frac{f(h)-f(-h)}{2h}.$$
As the function is even, the limit is $0$.
Then,
$$f''(0)=\lim_{h\to0}\frac{f(h)-2f(0)+f(-h)}{h^2}=2\lim_{h\to 0}\frac{\sin(\pi h)-\pi h}{\pi h^3}=-2\lim_{h\to 0}\frac{\pi^2\sin(\pi h)}{6\pi h}=-\frac{\pi^2}3,$$
applying L'Hospital twice.


save checked checkbox php

Question: I need your help please to get something working.
I've a kind of a link parser which put the links in an array and displays them with a checkbox at the beggining of every link.
I've separated all the work into multiple files :

Form.php which contains only the HTML form.
Confing.php contains the necessary lines to connect to database.
New.php contains the source
and checkbox.php to save checked links in database.

Now, what I want is to be able to save only checked links in the database, but instead it saves everything.
Here's the code (in New.php) to add a checkbox to every link of the array :
// $r is the array

for($i=0;$i<sizeof($r);$i++)
{
    echo "<input type='checkbox' name='recup[]' value='".$r[$i]."'>".$r[$i]."
";
}
$_SESSION[sup] =

At the end of this file, an action to start checkbox.php :
<form action="checkbox.php" method="post">
<input type='submit' name='Submit' value='Submit'>

The file chekbox.php :
<?php
include("config.php");
if($_POST["Submit"]=="Submit")
    {
        for ($i=0; $i<sizeof($r);$i++)
        {
            $query="INSERT INTO ub0oi_newcraw_liens(id,url,description) VALUE(NULL,'$r[$i]','Lien')";
            mysql_query($query) or die ('Error updating database');
            echo "Record is inserted.";
        }
    }
?>

I Only want to save the checked value, please help me.
Answer: you did not catch checkbox post value:
try this code:
<?php
include("config.php");
if(isset($_POST["Submit"]))
    {
       $r=$_POST['recup'];   // you forget to add this line
        for ($i=0; $i<sizeof($r);$i++)
        {
            $query="INSERT INTO ub0oi_newcraw_liens(id,url,description) VALUE(NULL,'$r[$i]','Lien')";
            mysql_query($query) or die ('Error updating database');
            echo "Record is inserted.";
        }
    }
?>

save checked checkbox php


Restarting webmin firewall/iptables

Question: I'm trying to figure out how can I restart iptables setup made from webmin.
When created the firewall rules, webmin saved everything into iptables.up.rules.
I used the iptables to DROP as default action, and ACCEPT traffic only from certain IP addresses using NAT, because Filtering was making connection really slow.
One of the IPs was my office IP. After resetting the modem/router at the office, our IP changed, and now I can't access webmin.
I have SSH access via other server, which is also at the ACCEPT list, and has static IP.
So I'm trying to modify iptables.up.rules, and change the old office IP to the new one, but nothing happens.
trying:
user@serv:/# iptables -L
Chain INPUT (policy ACCEPT)
target     prot opt source               destination

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination
user@serv:/#

no rules / NAT.
can't restart iptables, nothing happens when restarting webmin, tried
user@serv:/# modprobe -r iptable_nat
FATAL: Module iptable_nat is in use.

any ideas how to resolve without rebooting?
thanx.
Answer: ok finally success!
after modifying /etc/iptables.up.rules, needed to:
iptables-restore /etc/iptables.up.rules

Comment: Good to know, nice one.
Answer: I'm presuming you just want to enable access for your new office ip to and from the firewall so you can then connect from the office ip via webmin? Webmin listens on port 10000 by default afaik.
iptables rule to the firewall
iptables -I INPUT -p tcp -m tcp --dport 10000 -s x.x.x.x -j ACCEPT
iptables rule from the firewall
iptables -I OUTPUT -p tcp -m tcp --sport 10000 -d x.x.x.x -j ACCEPT
where x.x.x.x is your office ip.
Then run iptables-save from the cli.
I'm not sure if you'll have to restart iptables, I doubt it but if you do -
service iptables restart
Comment: service iptables not existing.
for the ACCEPT rules from the iptables, I've already tried even to ACCEPT any connection, not just for 10000 port, but the webmin settings are overriding any iptables rule I insert from cli.
Comment: Can you flush all your rules? iptables -F, which should leave your default rule actions. I'm not familiar with webmin but it just seems to be a web interface for managing a *nix box so restarting it will have no effect on your iptable rules.
Comment: Tried iptables -F, no good. And if there are no rules under iptables -L, so you can't flush them.
The thing is that the rules in webmin config file "iptables.up.rules" override anything I do manually.
Comment: The only other thing then would be to clear the iptables.up.rules file with "cat /dev/null > iptables.up.rules". I've never used webmin so I'm not familiar with how it constructs the firewall rules.
Comment: not working. I've already tried to remove the file completley, not working either.

Restarting webmin firewall/iptables


Apache on debian don't redirect http to https correctly

Question: Debian 11
config file: /etc/apache2/sites-enabled/000-default.conf
<VirtualHost *:80>
    RewriteEngine On
    RewriteCond %{HTTPS} off
    RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
    ServerName zabbix.example.ru

</VirtualHost>
<VirtualHost *:443>
    ServerName zabbix.example.ru
    DocumentRoot "/usr/share/zabbix/"
</VirtualHost>

If I open in brouser zabbix.example.ru it will be open by https. But if I open manualy http://zabbix.example.ru it doesn't redirect to https
The same setting (as I understand) perfectly forks for me on FreeBSD, but it looks like on Debian I should make something other
/usr/sbin/apachectl -S
VirtualHost configuration:
*:80                   zabbix.lasil.ru (/etc/apache2/sites-enabled/000-default.conf:1)
*:443                  zabbix.lasil.ru (/etc/apache2/sites-enabled/000-default.conf:9)
ServerRoot: "/etc/apache2"
Main DocumentRoot: "/var/www/html"
Main ErrorLog: "/var/log/apache2/error.log"
Mutex watchdog-callback: using_defaults
Mutex rewrite-map: using_defaults
Mutex ssl-stapling-refresh: using_defaults
Mutex ssl-stapling: using_defaults
Mutex proxy: using_defaults
Mutex ssl-cache: using_defaults
Mutex default: dir="/var/run/apache2/" mechanism=default
Mutex mpm-accept: using_defaults
PidFile: "/var/run/apache2/apache2.pid"
Define: DUMP_VHOSTS
Define: DUMP_RUN_CFG
User: name="www-data" id=33
Group: name="www-data" id=33

UPD: I was a little wrong about problem. Not only there is no redirect, but such an error is also issued
Bad Request
Your browser sent a request that this server could not understand.
Reason: You're speaking plain HTTP to an SSL-enabled server port.
Instead use the HTTPS scheme to access this URL, please.
Apache/2.4.54 (Debian) Server at zabbix.example.ru Port 80

Comment: For your update, your Virtual Host for port 443 does not have an SSL certificate configured. Therefore it is speaking HTTP and not HTTPS.
Comment: Port 80 does not have HTTPS enabled. If it was enabled, the error message would be different.
Comment: @MrWhite - Oops,  I read the port numbers backwards. How is SSL enabled on port 80? The VirtualHost does not show that configuration.
Comment: Or, they have seemingly enabled SSL on port 80?! @JohnHanley
Comment: @JohnHanley "You're speaking plain HTTP to an SSL-enabled server port." - Only HTTP (port 80) requests get this message (server rejects the request and the redirect does not happen). HTTPS (port 443) requests appear to be working just fine (there is a valid SSL cert).
Answer: You want a permanent, unconditional redirect. Simply don't use mod_rewrite:
<VirtualHost *:80>
    ServerName zabbix.example.ru
    Redirect permanent / https://zabbix.example.ru/
</VirtualHost>

Comment: I still got error. By the way I see I didn't mention an important thing, please see question update
Comment: Have you included *ALL* of your `/etc/apache2/sites-enabled/000-default.conf` in the question?
Answer: Thank's to all.
After reading comments I understand that site configuration (where was enabled SSL) (that was in /etc/apache2/conf-enabled/ folder) wasn't limited to any VirtualHost, so it was enabled to all server, not only to port 443
I moved it to VirtualHost on port 433 and problem was solved
Comment: Apache doesn't are about *where* the *file* is located. It cares about in what type of config it's located. Apache has different sections with different scopes, e.g. vhost, directory, serverwide etc.
Answer: In my case, I had to disable 000-default site.
# a2dissite 000-default
# systemctl reload apache2

Cheers!


How to change user info with a rule when Points are granted to user (using userpoints module)?

Question: I need to create a rule to change info of a user when this user is granted with points using the http://drupal.org/project/userpoints module.
I need the rule to have a condition and action like:
if total points of the user are greater than 1000 --> then set the field passed to 1
The field passed is a field that I added at admin/config/people/accounts/fields
My problem is that I can't load the Total points of the user in the conditions of the rule
I already have the userpoints_contrib module enabled.
Comment: I think that was added recently in dev: http://drupal.org/node/1109992
Answer: I think that was added recently in dev: drupal.org/node/1109992
Answer: In the condition of your rule add Execute custom PHP code.
Then add the following code to get total userpoints and check condition:
$current_points = userpoints_get_current_points($userpoints_transaction->uid, 'all');
if ($current_points >= 1000) {
  return true;
}

For more information about userpoints_get_current_points refer to this page
Answer: Apart from what's mentioned in the previous answers, there is also the Rules Action "Load user points of a user", whereas you can ask for either a specific category, or for all categories together. This Rules Action provides a Rules variable (for which you can specify its name and description) which contains the amount of user points for the requested category. You can then use this variable in subsequent Rules Actions.
If you then want to use that variable within a Rules Condition, you have 2 ways of doing so:

Include the condition in a Rules Component, whereas you trigger the execution of that Rules Component via a Rules Action following the "Load user points of a user" (and passing the variable containing the amount of user points as a variable for the Rules Component).
Use the Conditional Rules module, so that you can specify Rules Conditions within Rules Actions.

Here is a basic example that displays a message about the current total user points for a user (change the Rules Event to any Rules Event that you want):
{ "rules_display_userpoints_after_updating_content" : {
    "LABEL" : "Display userpoints after updating content",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "userpoints_rules", "rules" ],
    "ON" : { "userpoints_event_points_awarded_after" : [] },
    "DO" : [
      { "userpoints_rules_get_current_points" : {
          "USING" : { "user" : [ "site:current-user" ], "tid" : "all" },
          "PROVIDE" : { "loaded_points" : { "total_points" : "Number of points in all categories together" } }
        }
      },
      { "drupal_message" : { "message" : "You now have [total-points:value] points" } }
    ]
  }
}

Use the Rules UI to import the above rule in your own site if you want.


Bootstrap Grid Html - Problema com botão collapse

Question: Olá, criei uma grid de 3 colunas com o bootstrap e inseri dois botões collapse em cada coluna. O problema é que em qualquer botão collapse que eu clico, ele só abre em uma coluna, sempre na primeira coluna. Eu quero clicar no botão collapse da coluna 2 e abrir o conteúdo dele na 2, mas abre sempre no mesmo.

 <!DOCTYPE html>

 <title>Unlock</title>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
  <link rel="stylesheet" type="text/css" href="style.css">
  <link rel="stylesheet" href="maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">

    Hello, world!!!

 Voltar

      First, but unordered

ola

  Unlock all

Well done!

Aww yeah, you successfully read this important alert message. This example text is going to run a bit longer so that you can see how spacing within an alert works with this kind of content.

Whenever you need to, be sure to use margin utilities to keep things nice and tidy.

    Link with href

  <button class="btn btn-primary" type="button" data-toggle="collapse" data-target="#collapseExample" aria-expanded="false" aria-controls="collapseExample">
    Button with data-target
  </button>

    Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident.

<button type="button" class="btn btn-secondary" data-container="body" data-toggle="popover" data-placement="top" data-content="Vivamus sagittis lacus vel augue laoreet rutrum faucibus.">
  Popover on top
</button>

      Second, but last

ola

  Unlock all

Well done!

Aww yeah, you successfully read this important alert message. This example text is going to run a bit longer so that you can see how spacing within an alert works with this kind of content.

Whenever you need to, be sure to use margin utilities to keep things nice and tidy.

    Link with href

  <button class="btn btn-primary" type="button" data-toggle="collapse" data-target="#collapseExample" aria-expanded="false" aria-controls="collapseExample">
    Button with data-target
  </button>

    Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident.

<button type="button" class="btn btn-secondary" data-container="body" data-toggle="popover" data-placement="top" data-content="Vivamus sagittis lacus vel augue laoreet rutrum faucibus.">
  Popover on top
</button>

      Third, but firsts

ola

  Unlock all

Well done!

Aww yeah, you successfully read this important alert message. This example text is going to run a bit longer so that you can see how spacing within an alert works with this kind of content.

Whenever you need to, be sure to use margin utilities to keep things nice and tidy.

    Link with href

  <button class="btn btn-primary" type="button" data-toggle="collapse" data-target="#collapseExample" aria-expanded="false" aria-controls="collapseExample">
    Button with data-target
  </button>

    Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident.

<button type="button" class="btn btn-secondary" data-container="body" data-toggle="popover" data-placement="top" data-content="Vivamus sagittis lacus vel augue laoreet rutrum faucibus.">
  Popover on top
</button>

Answer: Você está usando o mesmo id para as três colunas, o target da primeira tem q ser um id apenas da primeira, e assim por diante.


My navlink is not working in react.js but after reloading it works

Question: Developing a react.js app. Used nav link at navbar. The router is also defined but it doesn't go anywhere. after reloading it works. If Job Post is clicked on Navbar it doesn't work but in the URL it's http://localhost:3000/jobPost and after reloading it is routed.
App package.json is
"react": "^18.2.0",
"react-bootstrap": "^2.5.0",
"react-dom": "^18.2.0",
"react-hook-form": "^7.34.0",
"react-router-dom": "^5.3.0",

import Navbar from 'react-bootstrap/Navbar';
import NavDropdown from 'react-bootstrap/NavDropdown';
import Offcanvas from 'react-bootstrap/Offcanvas';
import { Link } from 'react-router-dom';

Home
job Post
<NavDropdown title="Dropdown" id={`offcanvasNavbarDropdown-expand-${expand}`}>
<NavDropdown.Item href="#action3">Action</NavDropdown.Item>
... ... ...
<NavDropdown.Divider />

In App.js
<Route exact path="/">
      <Home></Home>
</Route>

<Route path="/home">
        <Home></Home>
</Route>

<Route path="/jobPost">
        <JobPost></JobPost>
</Route>

Need some help.
Answer: import Nav from 'react-bootstrap/Nav';
add this line,hope it will work
Comment: Added now  ```import Nav from 'react-bootstrap/Nav';``` but  same result. It works only after reloading.
Comment: use react-router-dom@v6, it works well in my project
Comment: It's still not working yet[Installed react-router-dom@v6].
Comment: OP is using RRDv5, so the fact you are using v6 and works differently is completely irrelevant.
Comment: It works:: in App.js ```

} />
      } />``` and in Navbar.js ``` Post Job``` Thanks all.


Is there a way to disallow the node/* path for anonymous users?

Question: The reason of my question is that I have built a one-page website, but if people who knows a bit of drupal patterns wants to try to request the site by editing the url with a path like domain.tld/node/12 (for ex.), they will be redirected to the clean url and it will work, but this behavior is not intended and the theming customized in a way which is not made for direct requests on nodes.
Apart from the one-page, all the other content is in views and blocks, with a few colorbox links to open one content type in detail.
What I want to do is find a way to disallow node/* requests in path, just to "keep some control" of the way anonymous users visit the site (and potentially test it).
I have tested internal nodes which gives a partial answer, but it disallows all node's requests in colorbox.
I tried path rules but same issue as internal nodes.
Any idea to help me?
Comment: If you will use any of them and narrow down your question to *only* colorbox part, I'll retract my "close as duplicate" vote. For now, main part of your question seems already answered to me. Maybe whole of it.
Comment: thanks for the links, I'll look into it. But I am not sure it answers the "colorbox issue".
Comment: I need to test a few of the options suggested in the links you have pointed. It is possible that the answer will be in one of them. Then I would know and maybe change my question if none of them works. Thanks for follow-up on the comment.
Answer: You can give permission to particular node using hook_permission().
<code>function your_module_name_permission() {
  return array(
    'access your modulename module' => array(
      'title' => t('Access your modulename module'),
      'description' => t('Allows access to your modulename module'),
      'restrict access' => TRUE
    ),
  );
}
</code>
and then go to permission section under people menu. and uncheck above created permission for anonymous user.
Answer: I believe the Taxonomy Access Control or Taxonomy Access Control Lite is what you need. You can set the access control for user roles based on taxonomy categories. Here are the features.

Automatically controls access to nodes(based on their taxonomy terms)
Configuration page for each user role.
Three node access permission types: View, Update, Delete.
Two term access types: View tag, Add tag.

Here are the steps you need

Create a Vocabulary in Taxonomy, and named something like "Access
Permission". Then add "Member" term.
Add a "Term reference" field on a Content type with that Vocabulary
you just created. Make sure the Required field is NOT checked, so
you can use the default None value.
Go to "Configuration > People > Taxonomy access control" and add
that "Member" term to anonymous user. Set the View, Update and
Delete to "D", then Save all.

This way, anonymous user will not be able to view any node with "Member" term. You may also want to set the Default 403 to the login page, so whoever try to access "Member" term page will require to login. You can change the default 403 in "Configuration > System > Site information".


Why am I getting a 'fatal: SASL library initialization'

Question: If I turn on smtp_sasl_auth_enable=yes <- yes
I get this set of warnings and a fatal for SASL.
I can not see why it's also looking for cyrus - which is not compiled in.
postfix/smtp[87056]: warning: unsupported SASL client implementation: cyrus
Apr 20 13:29:52 zeus.quantum-radio.net postfix/smtp[87056]: fatal: SASL library initialization
Apr 20 13:29:53 zeus.quantum-radio.net postfix/master[86038]: warning: process /usr/libexec/postfix/smtp pid 87056 exit status 1
Apr 20 13:29:53 zeus.quantum-radio.net postfix/master[86038]: warning: /usr/libexec/postfix/smtp: bad command startup -- throttling

My configs are like this:
smtpd_use_tls=yes
smtpd_tls_cert_file=/System/Library/OpenSSL/certs/testServer.crt
smtpd_tls_key_file=/System/Library/OpenSSL/private/testServer.key
tls_random_source=dev:/dev/urandom

smtpd_sasl_auth_enable=yes
smtpd_sasl_type=dovecot
smtpd_sasl_path=private/auth
smtpd_recipient_restrictions=check_sender_access  hash:/usr/local/cutedge/postfix/etc/access, check_client_access hash:/usr/local/cutedge/postfix/etc/access, permit_mynetworks, permit_sasl_authenticated, reject_unauth_destination, check_recipient_access hash:/usr/local/cutedge/postfix/etc/access
broken_sasl_auth_clients=yes

smtp_sasl_auth_enable=no
smtp_sasl_password_maps=hash:/usr/local/cutedge/postfix/etc/sasl_passwd
smtp_sasl_security_options=noplaintext,noanonymous
smtp_use_tls=yes

smtpd_helo_required=yes

Comment: yes, I know. It was yes - generated error - I changed it to no - error gone.
Comment: did you realize that there is also the line `smtp_sasl_auth_enable=no` in your config? What you changed, was `smtpd_sasl_auth_enable=yes`, which is not what you say in your question
Answer: Postfix does not implement SASL itself, but instead uses existing implementations as building blocks. Currently postfix only support two SASL implementation, Cyrus SASL and Dovecot SASL.

Cyrus SASL provide SASL framework for both Postfix SMTP server smtpd  and SMTP client smtp
Current implementation of Dovecot SASL does not provide client functionality.

So, that's clear enough why postfix smtp throws error about missing cyrus SASL implementation. It's because Postfix SMTP client only using Cyrus SASL implementation to get working.

The obvious solution is compile postfix with both SASL implementation: Cyrus SASL and Dovecot SASL. To check if they are both compiled to postfix use, postconf command
postconf -a

Comment: Thanks, I have Dovecot - not Cyrus. I don't need client - smtp, so didn't compile it in. So I probably also need to turn off smtp_use_tls=yes
Comment: Good... That's will turn off the error.
Comment: I now have Postfix-3.1+Dovecot+Cyrus+Mysql+Pche compiled in and running - with Dovecot still the master. It seems to be working, mail is flowing - but now still getting "no worthy mechs found" in syslog. See other thread.


How to award User Points after checkout using Rules?

Question: I'm trying to award some User Points to users who select a certain plan during his checkout process.
Here is the explanation of my website functionality.

When a user register with a role, the user will get access to the website with certain functionality.
Some users will be having permission to create new nodes.
During the node creation, the user needs to select a plan (I'm using Commerce Node Checkout module to add product as plan).
Based on the user's selection, the user will be redirected to the checkout page.
After completion of the checkout process, the user will receive some User Points. For this I have created a rule, but it is not working as expected.

Here is the export of my rule:
{ "rules_per_day" : {
    "LABEL" : "Per day",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "per day" ],
    "REQUIRES" : [ "commerce_order", "userpoints_rules", "commerce_checkout" ],
    "ON" : { "commerce_checkout_complete" : [] },
    "IF" : [
      { "commerce_order_contains_product" : {
          "commerce_order" : [ "site:current-cart-order" ],
          "product_id" : "day_4dxivfX2oFRAqQH-Ij6VBFnBheZBRIo744cF46KKPSI",
          "operator" : "=",
          "value" : "1"
        }
      }
    ],
    "DO" : [
      { "userpoints_action_grant_points" : {
          "user" : [ "site:current-user" ],
          "points" : "50",
          "tid" : "0",
          "entity" : [ "commerce-order" ],
          "description" : "You have received  the points for selected plan.",
          "operation" : "Insert",
          "display" : 1,
          "moderate" : "approved"
        }
      }
    ]
  }
}

The Rules Condition checks whether the order contains a specific product withe the product id n.
I don't understand what I did wrong or what I have missed in this rule. Any suggestions to make this rule work?
Comment: The condition checks whether the order contains a specific product withe the product id `n`.
Comment: @Pierre.Vriens, Thanks for the answer. The specified reasons in your answers are correct. I had posted this question almost 2 years ago and I really don't remember on which project I've faced this issue and the cause.
Answer: In order for your Rules Condition to be satisfied, ALL these criteria must be true:

Order contains the product whereas the SKU of that product must be "day_4dxivfX2oFRAqQH-Ij6VBFnBheZBRIo744cF46KKPSI".
The quantity of the specified product on the order must be "= 1".

Since the user does not seem to receive the userpoints, it must be because of either of these reasons:

Reason 1: your Rules Condition is not satisfied. Assuming that there is no typo in the SKU value, it could be because the quantity is NOT "= 1".
As a quick check to find out if this is what is causing your issue, simply do a test in which you (temporary) change this rules condition to the opposite, by using the "negate" checkbox for that Rules Condition. If in that scenario the userpoints are granted, you can be sure that the quantity is indeed NOT "= 1" (even though you may think/expect that to be the case ...).
Reason 2: your Rules Condition is OK, but your Rules Action for some unknown reason does not actually grant the points to the user.
As a quick check to find out if this is what is causing your issue, just add another Rules Action (before the one you have already) to simply "Display a message" (which you find within "System"). All the message should be is something like "Rules Action triggered". If in that scenario such message is actually shown, you can be sure that the cause of your problem is something related to your Rules Action (to grant points) that is not working as you think/expect it to work.

If none of the above helps, then it's time for Rules debugging, as detailed in "How to debug a rule that doesn't want to fire?".


Error: Control reaches end of non-void function. Cant find where to fix the error

Question: I cannot find the error, the error is located with the function (calculation findCalculations).
This is where the code seems to be having the problems.
START
calculation findCalculations(float A[][5], int rows) {
    {
        double sum = 0;
        for (int x = 0; x < rows; x++) {
            cout << endl;
            for (int y = 0; y < 5; y++) {
                sum = sum + A[x][y];

            }
        }
        cout << "Average graylevel: " << sum << endl;

        double min = 0;
        for (int x = 0; x < rows; x++) {
            for (int y = 0; y < 5; y++) {
                if (A[x][y] < min) {
                    min = A[x][y];
                }
            }
        }
        cout << "Min graylevel: " << min << endl;
        int graylevel = 0;

        for (int x = 0; x < rows; x++) {
            for (int y = 0; y < 5; y++) {
                if (A[x][y] >= .75) {
                    graylevel = A[x][y];
                }
            }
            cout << "Number of bright pixels: " << graylevel << endl;
        }
        bool bright = true;
        bool dark = false;
        for (int x = 0; x < rows; x++) {
            for (int y = 0; y < 5; y++) {
                if (A[x][y] < .5) {
                    bright = A[x][y];
                }
                if (A[x][y] >= .5) {
                    dark = A[x][y];
                }
            }
            if (dark < bright) {
                cout << "Image has more bright pixels: yes" << endl;

            } else if (dark == bright) {
                cout << "Image has more bright pixels: they have the same" << endl;
            } else {
                cout << "Image has more bright pixels: no" << endl;
            }
        }
    }
}

STOP
If anyone could possibly help me out to figure out what is going wrong that would mean a lot thanks.
Comment: Also, searching for `Control reaches end of non-void function` here on Stack Overflow returns 505 hits. Please use the search function before you ask (and consider looking at the duplicate suggestions that popped up when you wrote the question in the first place).
Comment: Since the return type of the function isn't `void`you need to return a `calculation`object from it, or declare the funtion `void` - meaning it doesn't return anything.
Comment: possible duplicate of [I keep Getting Control reaches end of non-void function. What am I doing wrong?](http://stackoverflow.com/questions/2562545/i-keep-getting-control-reaches-end-of-non-void-function-what-am-i-doing-wrong)
Answer: You are telling the compiler in the function signature
calculation findCalculations(float A[][5], int rows)

that the function is returning a calculation object. But you have no return statement in your function that actually does that. You are just outputting stuff via cout. If you don't actually need to return anything from the function, you should change the function signature to
void findCalculations(float A[][5], int rows)

indicating this to the compiler. If the code calling this function actually expects calculation objects, you will have to create and return them at some in the function via a return statement.
Comment: Even though im using a structure for this?
Comment: @jayden How could anyone know that you're using a struct? And it does not matter; you either have to return an object of the `calculation`type, or declare the function void.
Comment: What do you mean, you are "using a structure". For what? Do you mean the return type "calculation" is a structure? Even if it was just an int, you would have to return one. Where do you think the program should get the information from to build the return value? I think you have a conceptual problem, but I don't really know how to help you solve it.


$y'(x)=\sin(x+y(x))$, with $y(\frac{-\pi}2)=0$ - stuck at placing the initial condition at the general result $y(x)$

Question: I have the ODE $y'(x)=\sin(x+y(x))$, with the initial condition $y(\frac{-\pi}2)=0$.
I solved the general ODE by writing $t=x+y$ and then solving the equation $x=\int \frac{dt}{\sin t+1}$, getting $$x=\frac{-2}{\tan(\frac{x+y}{2})+1}+c$$
But when I try to plug in the initial condition $(-\frac{\pi}2,0)$ to find c, I get $0$ in the numerator.
How do I continue from here?
Answer: If you divide by a term that can assume the value zero, you should always check that you do not lose a solution that way. Considering the initial conditions, the equation $1+\sin t=0$ has the solution $t=-\frac\pi2$ and thus
$$
y(x)=-x-\frac\pi2
$$
which is indeed a solution of the IVP complementing the family of solutions of the ODE found by the separation approach.


Command Prompt: Why do I get "cannot find the path specified" when I move a folder (with contents) from the desktop to a new directory?

Question: move C:\%USERNAME%\Desktop\TZClock C:\%USERNAME%\Start Menu\Programs\TZClock

I keep getting system cannot find the path specified. But I can navigate to it.
Does MOVE only work on files?
Comment: You'll also get this error if the destination *parent* directory does not exist. So if the `C:\%USERNAME%\Start Menu\Programs` folder does not exist, you won't be able to move the `TZClock` folder into it.
Answer: Under Windows XP, it would be thus:
move "c:\documents and settings\%USERNAME%\desktop\TZClock" "C:\documents and settings\%USERNAME%\Start Menu\Programs\TZClock"

On Windows 7, it is the following (though I'm not in a position to test this right now):
move "c:\users\%USERNAME%\desktop\TZClock" "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\TZClock"

Comment: Thanks for the insight on how to do it on XP. I intend to make a version for it too. Im on Win7.
Comment: Are you sure you didn't mean to use `%USERPROFILE%` and only write code once rather than per OS?
Comment: Oh, I see, the `Start Menu` isn't under `%APPDATA%\Microsoft\Windows` on XP. Anyway, you probably want to use `%APPDATA%\Microsoft\Windows\Start Menu` rather than the user-global `%PROGRAMDATA%` directory.
Answer: If you want to move more than one directory using wildcard, you can use FOR /D command.
Type this in command-line (don't forget to replace _source_dirs_ and _destination_dir_ with your directories):
FOR /D %p IN ("_source_dirs_*") DO MOVE %p _destination_dir_

Answer: Got It! My syntax was wrong: the space was blocking the command from running. Also, I did not have User specified in the path.
After changes:
move C:\Users\%USERNAME%\Desktop\TZClock C:\Users\%USERNAME%\"Start Menu"\Programs\

Command Prompt: Why do I get “cannot find the path specified” when I move a folder (with contents) from the desktop to a new directory?