outputFileNameMapping and exclude problem with maven-assembly-plugin (3.1.0)

Question: I have a multi-module maven project with two separate "main" projects (projectA and projectB) from which I would like to build a zip file (incl. all dependencies).
One of the dependencies "subProjectC" I would like to exclude. This is the relevant portion of assembly.xml:
<code><moduleSets>
    <moduleSet>
        <!-- Enable access to all projects in the current multimodule build! -->
        <useAllReactorProjects>true</useAllReactorProjects>

        <includes>
            <include>${project.groupId}:projectA</include>
            <include>${project.groupId}:projectB</include>
        </includes>
        <excludes>
            <exclude>${project.groupId}:subProjectC</exclude>
        </excludes>
        <binaries>
            <outputFileNameMapping>${module.artifactId}.${module.extension}</outputFileNameMapping>
            <outputDirectory>project-root/lib</outputDirectory>
            <unpack>false</unpack>
        </binaries>
    </moduleSet>
</moduleSets>
</code>
subProjectC turns up in the zip file nevertheless.
Also, all dependencies show up with their full version, e.g. projectA-0.0.1-SNAPSHOT.jar, although the outputFileNameMapping should have prevented this...
What am I doing wrong?
Answer: Ok, it seems "outputFileNameMapping" only affects those artifacts that are specified in the "includes" list...


Number of regions formed by translations of a hyperplane arrangement

Question: Let $\mathcal{A}$ be a hyperplane arrangement (a collection of hyperplanes) in $\mathbb{R}^d$. The number of regions $r(\mathcal{A})$ determined by $\mathcal{A}$ is defined as the number of connected components of $$\mathbb{R}^d\setminus\bigcup_{h\in\mathcal{A}}h.$$ It is well known and easy to see that $r(\mathcal{A})\le |\mathcal{A}|^d.$
Now, let $\mathcal{A}_1,\ldots,\mathcal{A}_M$ be translates of $\mathcal{A}$, that is, if $\mathcal{A} = \{h_1,\ldots, h_n\}$, then $\mathcal{A}_m = \{h_1^m,\ldots, h_n^m\}$, where $h_i^m$ and $h_i$ are parallel. Obviously, as before, $r(\bigcup A_m)\le (M|\mathcal{A}|)^d.$ I'm wondering if something stronger can be said here by exploiting the fact that the arrangement consists of translations of a smaller arrangement. For example, no two hyperplanes from $\{h_i^1,\ldots, h_i^M\}$ can contribute to the same region, for each $i$ (since they are translates of one another). Most work in this area starts by assuming the arrangement is in general position, so I'd appreciate any help here!
Comment: Presumably we know at least that the $\mathcal A_m$ are disjoint? That is $\left|\bigcup_{m=1}^M \mathcal A_m\right|=M|\mathcal A|?$
Comment: A simple example has $|\mathcal A|=2$ and $d=2.$ Then $r(\mathcal A)=4$ (in most cases) and $$r\left(\bigcup \mathcal A_m\right)=(m+1)^2$$ which is certainly  lower than $(2m)^2.$
Comment: Well I want a worst case bound, so yes, I'm assuming they are disjoint. I don't understand where you are getting $(m+1)^2$ from, are you just illustrating that you can do a lot better when they are not disjoint?
Comment: I just drew a picture to get $(M+1)^2.$ Not related to the disjoint question. Should have been $(M+1)^2$ rather than $(m+1)^2.$
Answer: If $d=1$, then worst-case answer is $M|A|+1$, so no improvement here.
If $d=2$, then you get the bound $\frac{|A|M(|A|M+1)}{2}-|A|\frac{(M-1)M}{2}$, so if you want to view $|A|$ as fixed and have $M \to \infty$, this yields an improvement of $\frac{|A|^2M^2}{2}$ to $\frac{(|A|^2-|A|)M^2}{2}$ roughly.
The way you get that $d=2$ bound is simply by going through the proof that $r(A) \le \frac{|A|(|A|+1)}{2}+1$ (which is obtained by starting with $r(1) = 2$ and then noting $r(m+1) \le r(m)+m$, which follows from the creation of at most $m$ new regions when you "add" the $(m+1)^{st}$ line). Indeed, you start with $r(A) \le \frac{|A|(|A|+1)}{2}+1$ and note that when you add $h_1^2$, you create new regions only possibly by intersecting with $h_2^1,\dots,h_n^1$ (not with $h_1^1$), and when you add $h_2^2$, you intersect with $h_1^1,h_3^1,\dots,h_n^1$ but not with $h_2^1$. Etc until you add $h_n^2$. Then $h_3^1$ misses $h_1^1,h_2^1$. Etc. etc.
I assume the same argument gives an improvement for $d \ge 3$ when $|A|$ is fixed and $M \to \infty$.
The argument given is tight, at least for $d=2$, in that the addition of $h_j^m$ will create new regions via intersection with $h_i^{m'}$ for $m' < m$ and $i \not = j$, provided $h_1,\dots,h_n$ start off in general position, so you can't get a better improvement than the bound obtained above. [It's probably tight for $d \ge 3$; I just can't visualize].


Cleaning table tennis rubbers

Question: I just bought a new table tennis paddle and I've bought a new cleaner, but I forgot to purchase one of those sponges.
Is there any problem with using a plain microfiber cloth to clean my table tennis paddle to remove dust?
What are some acceptable clothes or sponges I could use to clean a table tennis paddle?
Answer: I find anything that doesn't leave fibres on the rubber works. I often just use a paper towel.
Answer: As long as you don't damage the surface or leave fibres or dirt on the rubber, any soft material should be okay. In general you don't even need a special cleaner. Water is enough to get rid of dust. From time to time an additional drop of dishwashing liquid helps to keep fat/grease away from your racket surfaces. But the cleaner can be stored easier in your sports bag. :-)

Cleaning table tennis rubbers


Why does my delegate aiming to get data to update one form from another form comes up blank? c#

Question: Apologies for the explaining, This is my first time coding C#.
So my goal is to display  the inputs in a  label  in the Forms Load  event. Here is my code so far
<code>public  DelegateText DelFirstName;

public FrmConfirm()
        {
            InitializeComponent();
            DelFirstName = new DelegateText(sic.GetFirstName);
}

private void FrmConfirm_Load(object sender, EventArgs e)
        {
            lblFirstName.Text = DelFirstName(sic.FirstName);
}
</code>
When I run it, it only shows a blank label. There are no syntax errors showing. I do not understand
Answer: Well you are assigning an object as a string. You should probably do lblFirstName.Text = sic.FirstName; (given that sic.FirstName is a non-empty string).
Comment: I tried that as well but it yielded the same results.


Problemas com o CSS do Bootstrap no DOMPDF

Question: Estou utilizando o DOMPDF para imprimir um CV que pega os dados através de $_GET da URL.
Quando eu "imprimo" o arquivo na tela, apenas o HTML, consigo obter exatamente o que preciso, porém, quando eu tento rodar o DOMPDFcom o CSS em outro local, ele não gera, gera apenas uma tela em branco...
Como eu consigo fazer o DOMPDF entender esta folha de estilos?
Tentei também adicionar o CSS inline, porém, ele não reconhece coisas como o float por exemplo...
Alguém consegue me dar uma ajuda em relação a utilização do CSS externo com o DOMPDF? É obrigatório que eu utilize ele, não posso usar outra coisa como o html2pdf por exemplo.
Segue o meu código:

<?php
error_reporting(E_ALL);
$var1 = "";
$var2 = "";
$var3 = "";
$var5 = "";
$var6 = "";
$var7 = "";
require_once 'dompdf/autoload.inc.php';

include('../conexao.php');

$cpf = $_GET['cpf'];

$result_nome = mysqli_query($conexao, "SELECT * FROM profissionais WHERE cpf='$cpf'");
    while($dados = mysqli_fetch_object($result_nome)) {
        global $nome;
        $nome = $dados->nome;
        $var1 .= '

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

foto.'">

'.$dados->nome.'

'.$dados->profissao.'

'.$dados->cidade.' - '.$dados->estado.'

'.$dados->telefone.'

'.$dados->email.'

Apresentação

'.$dados->apresentacao.'

        ';
    }
    $var1 .= '

Formação Academica

';
         $var1;
    $result_formacao = mysqli_query($conexao, "SELECT * FROM formacaoacademica WHERE cpf='$cpf'");
    while($formacao = mysqli_fetch_object($result_formacao)) {
        $var2 .= '

'.$formacao->escola.'

'.$formacao->curso.'

'.$formacao->anoinicio.' - '.$formacao->anotermino.'

        ';
    }
     $var2;
     $var3 .= '

Licenças e certificados

';
    $result_certificados = mysqli_query($conexao, "SELECT * FROM certificadosprofi WHERE cpf='$cpf'");
    while($certificado = mysqli_fetch_object($result_certificados)) {
        $var5 .= '

'.$certificado->curso.'

'.$certificado->escola.'

'.implode('/', array_reverse(explode('-', $certificado->data))).'

        ';
    }
     $var5;
     $var6 .= '

Experiência Profissional

';
    $result_experiencia = mysqli_query($conexao, "SELECT * FROM experienciaprofissional WHERE cpf='$cpf'");
    while($experiencia = mysqli_fetch_object($result_experiencia)) {
        $var7 .= '

'.$experiencia->empresa.'

'.$experiencia->funcao.'

'.implode('/', array_reverse(explode('-', $experiencia->admissao))).' - '.implode('/', array_reverse(explode('-', $experiencia->demissao))).'

'.$experiencia->localidade.'

'.$experiencia->responsabilidade.'

        ';
    }
     $var7;

$encoding = mb_internal_encoding();
//$encoding = mb_internal_encoding();

$content = $var1 . $var2 . $var3 . $var5 . $var6 . $var7;

use Dompdf\Dompdf;

$dompdf = new DOMPDF();

//$dompdf->set_base_path("public_html/css/");

// Carrega seu HTML
$dompdf->load_html($content);

//Renderizar o html
$dompdf->render();

//Exibir a página
$dompdf->stream(
    $nome."cv.pdf",
    array(
        "Attachment" => false //Para realizar o download somente alterar para true
    )
);

?>

Comment: Isso é sintoma de erro no código. Já debugou isso no log? Tem alguma coisa que não está deixando a biblioteca renderizar a saída do PHP.
Answer: Acho que você precisa informar o caminho do css para o Dompdf
tipo se o boostrap estiver externamente, como CND do bootstrap, precisa ativar no domPdf
$options->set('isRemoteEnabled', TRUE);

se estiver em local, precisa informar onde, com set_base_path():
$dompdf->set_base_path("caminho/pasta-com-bootstrap");

tipo com esse exemplo automático:
$dompdf->set_base_path(realpath(dirname(__FILE__).'pasta-com-bootstrap/'));

Answer: Por que não utilizar uma URL absoluta, como a do próprio repositório do Bootstrap? Meu primeiro palpite é que talvez, o DOMPDF não esteja localizando o caminho relativo ../css/bootstrap.css.
Outra coisa importante é que você envolva todo o seu conteúdo que está em body em uma div com a classe container ou container-fluid, como é requisitado pelo Bootstrap.
Certifique-se de que todos os requisitos do DOMPDF estão sendo atendidos no seu servidor (local/produção). E ative todas as mensagens de erro/warnings do PHP, para saber se o DOMPDF está fazendo algum output.
Comment: Olá Macário,

Todos os requisitos são preenchidos, quando mando "printar" o conteúdo, ele consegue montar tudo da forma correta, mas quando mando ele gerar o PDF, ele não está conseguindo gerar. Ele gera apenas uma página em branco.
Comment: Você conseguiu obter alguma informação dos logs do Apache? Pode ser que encontre algo por lá.


How to print the paragraph field translation value in twig template

Question: I am trying to access the nested paragraph field inside my twig template.
<code>{% for items in item['#paragraph'].get_aw_title_details%}
  {{ item.entity.field_award.value }}
{% endfor %}
</code>
When I am using this syntax it is always returning the English content. Translation content is not visible for me. For chinese also it is giving the english content
Answer: Normally it's a better idea to process (or even better let Drupal process) the field values in PHP.
If there is no other way you can use Twig Tweak and its newly added entity translation filter:
<code>{% set entity = item.entity|translation %}
{{ entity.field_award.value }}
</code>
See https://git.drupalcode.org/project/twig_tweak/-/blob/3.x/docs/cheat-sheet.md#entity-translation


Prove that if $f$ is continuous and differentiable on $\mathbb{R}$ and has three roots, then its derivative $f′$ has at least two roots.

Question: I know that we are supposed to use Mean Value THeorem for this question. So from the theorem, if $f$ is continuous on an interval $[a,b]$ and has two roots, this means that there is a point $c\in [a,b]$ where $f'(x)=0.$ But is this logic correct for $3$ roots?
I am not sure if I understand how to construct a proof here.
Answer: If $f$ is differentiable and $f(x_1) = f(x_2) = f(x_3) = 0$ with $x_1 < x_2 < x_3$ then you can apply the mean-value theorem (or Rolle's theorem) to both intervals $[x_1,x_2]$ and $[x_2, x_3]$.  It follows that $f'$ has a root in each of the open intervals $(x_1, x_2)$ and $(x_2, x_3)$. That makes (at least) two roots of the derivative.
In the same way you can show that if  $f$ has $n$ distinct roots then $f'$ has (at least) $n-1$ distinct roots.
(And if the second derivative exists, then $f''$ has at least $n-2$ roots, you get the idea?)
Comment: yes, thank you so much!


Sum of 3 vectors is $\vec 0$

Question: So i have this problem:  $|\vec{a}| = 5$, $|\vec{b}| = 6$,$|\vec{c}| = 7$ and $\vec{a}$+$\vec{b}$+$\vec{c}$=0. Calculate the sum $\vec{a}$·$\vec{b}$+$\vec{b}$·$\vec{c}$+$\vec{c}$·$\vec{a}$.
I have no clue how to go about this, any help would be appreciated (hopefully the problem makes sense, i'm translating things directly, so if something isn't adding up (hehe), please do let me know, thanks.
Comment: how are they unit if their respective lengths are $5$, $6$, and $7$?
Comment: What have you tried?
Comment: Where did the title come from?
Comment: @paperskilltrees This is not a puzzle. It is a straight forward vector algebra problem.
Comment: Such a cute little question! Is there a suitable tag? I would label it "puzzle", but the tag's description made me wonder if there is a better one.
Comment: Without fancy ideas, you know $c=-a-b$ and you know $\lvert c\rvert$, therefore you know $a\cdot b$. Then the requested quantity is a polynomial in $a\cdot b$, $\lvert a\rvert$ and $\lvert b\rvert$.
Comment: @JohnDouma You can solve this problem using a straightforward computation, or you can make use of a nice algebraic observation made in [emacs...'s answer](https://math.stackexchange.com/a/4469913/774351). I believe that another commenter implicitly referred to it as a "fancy idea". I find this a characteristic of many puzzles. Probably we understand and use the word "puzzle" in slightly different ways.
Answer: Hint: square $\vec a+ \vec b+ \vec c$

$0=(\vec a+\vec b+\vec c)^2 = \vec a^2+\vec b^2+\vec c^2+2(\vec a \cdot \vec b+\vec b \cdot \vec c+\vec a \cdot \vec c) \;\;\;\; \\ = 5^2+6^2+7^2 + 2(\vec a \cdot \vec b+\vec b \cdot \vec c+\vec a \cdot \vec c) $
Answer: @emacs-drives-me-nuts' solution is the correct one. Here's a fun, incorrect solution:
From $a + b + c = 0$, we have $a + b = -c$, $a + c = -b$, $b + c = -a$
Whence (the dot product commutes),
$$
\color{red}{ab + ac + bc} =\\
ab + c \cdot (a + b) =\\
ac + b \cdot (a + c) =\\
bc + a \cdot (b + c) =\\
\color{green}{ab - 49} =\\
\color{blue}{ac - 36} =\\
\color{orange}{bc - 25}
$$
Using this,
$$
\color{red}{ab + ac + bc} = ab + ab - 13 + ab - 24 = \color{green}{3ab - 37}\\
\color{red}{ab + ac + bc} = ac + 13 + ac + ac - 11 = \color{blue}{3ac + 2}\\
\color{red}{ab + ac + bc} = bc + 24 + bc + 11 + bc = \color{orange}{3bc + 35}
$$
Whence, finally, putting both of these together,
$$
\color{green}{2ab = -12}\\
\color{blue}{2ac = -38}\\
\color{orange}{2bc = -60}
$$
and
$$
\color{red}{ab + ac + bc} = - \dfrac{\color{green}{12} + \color{blue}{38} + \color{orange}{60}} {2} = -55
$$
Comment: Actually, come to think of it, this solution does tell you more.
Comment: Why "incorrect"?
Comment: The only possibly wrong thing I can see is the notation $ab$ instead of $\vec a\cdot\vec b$.
Comment: Incorrect, because there's a much shorter (and better) answer. The proof is otherwise correct.
Comment: And I'll actually disagree that there's anything wrong with writing $ab$ in place of $\vec {a} \cdot \vec{b}$. :-)
Answer: In geometric terms, these three vectors form the lengths of a triangle with sides 5, 6, and 7.  (Their sum is zero because traveling the three sides in order gets you back to where you started.)
From the Law of Cosines, the three angles of a triangle with known sides are given by:
$$\cos(\alpha) = \frac{b^2 + c^2 - a^2}{2bc}$$
$$\cos(\beta) = \frac{a^2 + c^2 - b^2}{2ac}$$
$$\cos(\gamma) = \frac{a^2 + b^2 - c^2}{2ab}$$
But the dot product has the property that $\vec{x} \cdot \vec{y} = |\vec{x}|  |\vec{y}| \cos(\theta)$, where $\theta$ is the angle between the vectors.  Thus,
$$\vec{a} \cdot \vec{b} + \vec{b} \cdot \vec{c} + \vec{c} \cdot \vec{a}$$
$$=ab \cos(\gamma) + bc \cos(\alpha) + ca\cos(\beta)$$
$$=\frac{1}{2}(a^2 + b^2 - c^2) + \frac{1}{2}(b^2+c^2-a^2) + \frac{1}{2}(a^2 + c^2 - b^2)$$
$$= \frac{a^2 + b^2 + c^2}{2}$$
Comment: $\vec a\cdot\vec b=ab\cos(\pi-\gamma)=-ab\cos\gamma$

Sum of 3 vectors is $\vec 0$


Preventing a player from playing a specific position via suspension

Question: In Major League Baseball, any player can play any position. This seems to be the main reason a Pitcher is suspended with the same standard suspension as a position player. This despite a pitcher's suspension not being as likely to affect the team as perhaps a position player's suspension would.
Has Major League Baseball ever prevented a player from playing a specific position via suspension?
Answer: Actually, starting pitchers are typically not suspended the same as position players.  Starting pitchers, in recent years, have been suspended based on the number of pitchers in their rotation, which these days is typically five.
Thus, if MLB decides that a starting pitcher should be suspended for an amount of time that equals one game for a position player, then that pitcher is typically suspended for five days.
For example, on May 7, 2012, Cole Hamels hit Bryce Harper with a pitch and, after the game, Hamels admitted that he hit Harper on purpose.
MLB doesn't want to encourage such behavior, of course, so the next day, Hamels was suspended for five days, which, in this case, actually covers six games.
The point here is that MLB is preventing Hamels from making his next start.
Furthermore, Philadelphia is stuck playing a man short for the five days of Hamels' suspension, though that's not as dire as it seems since Hamels would rarely be used in games where he isn't the starting pitcher.  However, in the game that he would have started, the Phillies will be starting a pitcher that may normally work out of the bullpen.
Comment: Thank you for your answer. Though the conversation on Cole Hamels is very interesting and could be looked at from many angles, I would still like to know if MLB has ever suspended a player from playing a specific position. :–)
Comment: As for the one day suspension for position players I should have stated that I would not dismiss that Major League Baseball likely has issued such a suspension, but it does not seem to be the stance MLB takes in regards to what seems to be its standard.
Comment: Though, I do agree that the suspension does hurt the team as they are then one player short in regards to their roster, I do not agree that this actually affects Philadelphia in any other way. In most cases, Hamels would be pushed back a day and still not be forced to miss his scheduled start. However, with a scheduled off-day on Thursday for the Phillies, their staff would have been pushed back a day anyway, thus negating any effect the suspension would have had on Hamels.
Comment: Without appeal, he will simply go on about his business as if nothing ever occurred. Also in the this particular case a returning ace in Cliff Lee was already scheduled to return from the DL. So at least in this case it does not seem that Major League Baseball utilized the suspension in a way that would have actually equalled the effects of say even a 1 game suspension to a position player. (NOTE: I do not know if 1 day suspensions are even handed down to position players)
Answer: As far as I am aware, there is no provision in the CBA or official rules that allows for a player to be banned from playing a specific position. It's either they are suspended, or they aren't.


Theming views fields with twig

Question: I have a search results view from Search API where I need to use the excerpt that highlights the keywords being searched. In this instance, that prevents me from using a view mode output as the result.
In this instance, I have a view set up to output title, URI, date modified and search excerpt. I have a decent bit of theming to do around the form and results, but I can't seem to figure out how to view both the template suggestions for each view field, or just theme it manually in the given template views-view--unformatted--search--results.html.twig.
I also tried {{ kint(row) }} and even when viewing on its own page, basically locked up my browser.
So for instance, for the title, I need the markup to be:
Foo Exam
For consistency reasons, I would like to control it from twig templates instead of attempt to do it in the views admin (setting label field etc settings).
Answer: You're probably looking for
views-view-fields--[view-name]--[machine-name].html.twig
views-view-fields--search--results.html.twig
In your view click on your title field and uncheck Link to the content.
then your template file
{{ fields.title.content }}

Not really sure if you really want # as href. I think you want to link to content. So add Path as a field.
{{ fields.title.content|striptags }}

Note: You'll probably want to use |striptags if you do not strip the markup from the views UI. Unless you do not mind having <divs> wrapping your title text.
then {{ fields.field_machine_name.content }} each of the rest of your fields that you want to output.

Important: Make sure TWIG DEBUG is off, as it tends to screw up templates in Views.
Comment: Yeah the # is just from the prototype.
Comment: How do I find out what the machine name would be for just the node title? `title` by itself does not work.
Comment: In content type Manage Display, there is a [Machine Name column](https://www.drupal.org/files/field-ui-machine-name.png), you can check there. But... the machine name should be `title`, unless you somehow changed it... Oh also check that you're not hiding this field from display in the Views UI.
Comment: Yes. Also, fields.path.content doesn't work. This data is coming out of Search API + Search API Solr.
Comment: @Kevin interesting, if you do a Rewrite Results on your title field throught the Views Field UI, for available replacement patterns what do you get?
Comment: It just says `{{ title }}`. I just printed the excerpt as `{{ fields.search_result_excerpt.content }}`.
Comment: So are you saying that twig level overrides per field is not possible in views?
Comment: @Kevin, I guess you could use views-view-field--title--[view-name].html.twig
Comment: @Kevin nvm because you need access to the `path` field along with your `title`. That's why we are not using it here.
Comment: @Kevin do you have Twig Debug on? that tends to screw up templates in views. Turn it off and flush cache if you do.

Theming views fields with twig


Forwarding mail to alias in Postfix

Question: Currently I have setup Slicehost as my relayhost for mail. Postfix is my MTA.
This is how I have configured forwarding:
virtual_alias_maps = hash:/etc/postfix/virtual
my virtual file has:
email@example.com firstname.lastname@example.com
But the mail is being forwarded as spam.
In case I send mail directly from email@example.com to email@example.com it appears in the inbox,but the forwarding results in the mail ending in spam.
What could be the problem?
Answer: At first guess, I'd say that joschi is on the right track...what's your $myorigin?
Or, perhaps the output of postconf -n?
Comment: +1, always post "postconf -n" when troubleshooting postfix.
Answer: Your problem could be caused by SPF or similar mechanisms. When your MTA forwards the mails to GMail, the SPF records of the original sender's domain do not match your domain and thus GMail thinks it is spam. The proper solution to this (given SPF is really the problem) would be using SRS.
See the SPF FAQ on forwarding for details. You can also check the SPF records of the incoming mail's domain using the SPF Record Testing Tools.
Answer: You can look into raw headers at GMail (top right menu -> Show original).
Usually there is a line or two, explaining why Google thinks your message is SPAM, if the problem is in the SPF.
Answer: You need to use SRS (Sender Rewriting Scheme) to avoid forwarded E-Mails classified as SPAM.
Here's a tutorial on how to setup SRS with postfix on Ubuntu: http://www.ameir.net/blog/archives/71-installing-srs-extensions-on-postfix-ubuntudebian.html
Summarized:

Install pfixtools
Set up the secret file and whitelisted addresses
Add pfixtools to the postfix configuration

Forwarding mail to alias in Postfix


Sql utilizando left join

Question: Tenho as seguintes tabelas:
TB_ESTOQUE
|PRODUTO|QT_DISPONIVEL|COD_FILIAL|
|0856322|      5      |    41    |
|0856351|      2      |    41    |
|0856322|      9      |    114   |
|0856720|      3      |    20    |

TB_FILIAL
|COD_FILIAL|COD_LOCALADM|
|    41    |    114     |
|    128   |    114     |
|    133   |    114     |
|    10    |    156     |
|    56    |     12     |

Resultado desejado:
|COD_FILIAL|  ESTOQUE_FILIAL  |
|    41    |     41 - 2       |
|    128   |128 - SEM ESTOQUE |
|    133   |133 - SEM ESTOQUE |

Estou tentando fazer o SQL dessa forma:
SELECT
F.COD_FILIAL,
CASE WHEN E.QT_DISPONIVEL IS NULL THEN
  F.COD_FILIAL || ' - ' || 'SEM ESTOQUE'
ELSE F.COD_FILIAL || ' - ' || E.QT_DISPONIVEL
END AS ESTOQUE_FILIAL
FROM
TB_FILIAL F
LEFT JOIN TB_ESTOQUE E
ON E.COD_FILIAL = F.COD_FILIAL AND  E.COD_PRODUTO = 0856351 AND
F.COD_LOCALADM = 114
ORDER BY
E.COD_FILIAL

O SQL esta me retornando todos os registros da tabela TB_ESTOQUE. Ignorando o comando
"F.COD_LOCALADM = 114"

Comment: Retire o F.COD_LOCALADM = 114 do LEFT JOIN com a tabela TB_ESTOQUE e coloque num WHERE logo abaixo.
Answer: O ON no LEFT JOIN funciona para as chaves que você quer manter no seu JOIN, para adicionar condições você precisa de um WHERE, como em:
SELECT
F.COD_FILIAL,
CASE WHEN E.QT_DISPONIVEL IS NULL THEN
F.COD_FILIAL || ' - ' || 'SEM ESTOQUE'
ELSE F.COD_FILIAL || ' - ' || E.QT_DISPONIVEL
END AS ESTOQUE_FILIAL
FROM
TB_FILIAL F
LEFT JOIN TB_ESTOQUE E
ON E.COD_FILIAL = F.COD_FILIAL
WHERE E.COD_PRODUTO = 0856351 AND
F.COD_LOCALADM = 114
ORDER BY
E.COD_FILIAL

Sql utilizando left join


Problem in showing that a sequence is a Cauchy sequence on a space with the integral metric.

Question: I'm having difficulty following what is going on and understanding parts in the following example. It is quite similar to an example I posted before (Changing of the limits of integration with the integral metric.), but then, I haven't seen many examples of these problems before.
Given the sequence of functions for $n\ge2$,
$$f_n(x)=\begin{cases}
0  & \text{for $0\le x\le\frac12-\frac1n$} \\
n(x-\frac12)+1 & \text{for $\frac12-\frac1n\lt x\lt\frac12$} \\
1 &\text{for $x\ge\frac12$}
\end{cases}$$
in the space of continuous functions on the interval $[0,1]$, $C([0,1])$, with the integral metric $d_{int}$,
$$d_{int}(f,g)=\int_0^1 |f(x)-g(x)| \,dx\\$$
In moving to show that this is a Cauchy sequence we consider $d_{int}(f_n,f_m)$ with $n\ge m$:
$$d_{int}(f_n,f_m)=\int_0^1 |f_n(x)-f_m(x)| \,dx\\$$
$$=\int_{1/2-1/m}^{1/2} f_m(x) \,dx-\int_{1/2-1/n}^{1/2} f_n(x) \,dx\\$$
$$=\frac12\left(\frac1m-\frac1n\right)$$
Here are the points I am struggling with:

How is it that one can get rid of the modulus sign whilst still maintaining equality throughout the consideration? All tricks for dealing with the modulus that I have seen so far deal with the inequalities $"\ge"$. What could I use that doesn't involve such inequalities?
How is it that I get the final result from the second part of the consideration (i.e. from the statement at the second equals sign)? This is one of the things that I tried so far, although I am sure I have missed something very minuscule and rudimentary:

$$\int_{1/2-1/n}^{1/2} f_m(x) \,dx-\int_{1/2-1/n}^{1/2} f_n(x) \,dx\\$$
$$=f_m(1/2)-f_m(1/2-1/m)-(f_n(1/2)-f_n(1/2-1/n))$$
$$=1-0-(1-0)$$
$$=0$$
Comment: when you split into two integrals, the lower bound of the first should be 1/2-1/m, not 1/2-1/n ... or it is even more complicated than that but this is a hint. The comment below by @zhw is even better, using a suitable estimate to avoid exact messy computation
Comment: $\int_0^1|f_m-f_n| = \int_{1/2-1/m}^{1/2}|f_m-f_n| \le (1/m)\cdot 1 = 1/m.$
Answer: The absolute value of $|a|$ is $a $ or $-a $, depending on whether  $a $ is nonegative or not.
In your case, the condition $n\geq m $ implies $f_m (t)\geq f_n (t) $, so $$|f_n (t)-f_m (t)|=-(f_n (t)-f_m (t))=f_m(t)-f_n (t). $$
For your second question, when you calculate your integrals you are forgetting the antiderivatives.


Erro ao fazer requisição Ajax

Question: Quando tento fazer um requisição ajax usando o comando $.post do jQuery aparece um erro no netWork do chrome alguém sabe o que pode ser esse erro

Código: estou usando o framework codeigniter
$.post('/pages/entradaprodutos/carregar_notasfiscais',{
        codigo:$("#fornecedores").val()
        },function(resposta){
                console.log(resposta)
         });

Comment: Isso não é um erro, é um aviso... Pode compartilhar a chamada Ajax para analisarmos?
Comment: Pronto, editei a pergunta...
Comment: Qual a response?
Answer: Pelo que pesquisei, isso pode ser causado por algo que está interceptando o seu request, e enviando um request vazio.
Possivelmente um bloqueador de propagandas (como o AdBlock), como indicado nesta resposta do SOEN:
https://stackoverflow.com/a/21179105/195417
Sugestão: tenta instalar o fiddler para ver como está ficando o request sendo feito, pois deve haver algo interceptando o request... depois de fazer isso, tente verificar em outros navegadores, e ver como os requests ficam em cada um dos navegadores... assim poderá isolar o problema cada vez mais.
EDIT Mais sugestões baseadas no SOEN:

Iniciar o chrome com --disable-extensions na linha de comando (https://stackoverflow.com/a/21400449/195417)
Verificar se o request não está sendo feito a outro domínio
Recurso está sendo carregado do cache do browser (https://stackoverflow.com/a/21272049/195417)... e.g. por falta de conectividade ao servidor, o browser pega um recurso do cache, sem atualmente fazer o request.
Comment: @SilvioAndorinha Sem a possibilidade de reproduzir o problema, só posso ajudar com a pesquisa... editei a resposta... se não for nada disso, ai quando você resolver, por favor poste a solução como uma resposta, de forma a ajudar outros que passem pelo mesmo problema.
Comment: putz, que coincidência kkkk
Comment: Mas eu não tenho nenhuma extensão chamada AdBlock no meu navegador
Comment: e também esse erro só da de vez em quando.. talvez pode ser algum processo que está sendo rodado no navegador porque o erro só da de vez em quando
Comment: @PauloRoberto , sim eu já tinha visto a pergunta do soen mas não resolveu me problema aí eu peguei a imagem deles para não precisar mostrar minha url mas a final o erro é mesmo
Comment: @MiguelAngelo OK, pode deixar.
Answer: Obs: Há uma pergunta extremamente parecida com a sua aqui, a imagem é idêntica.
Resposta Traduzida do SOEN
O recurso poderia estar sendo bloqueado por uma extensão (AdBlock, etc..)
A mensagem está aí porque a requisição para resgatar este recurso, nunca foi feita, por isso os headers sendo apresentados não são reais.
Referência(resposta no SOEN)
Comment: Sim eu já vi está pergunta mas eu não tenho nenhuma extensão AdBlock instalada no meu browser
Comment: há e sim eu já tinha visto a pergunta do soen mas não resolveu me problema aí eu peguei a imagem deles para não precisar mostrar minha url mas a final o erro é mesmo
Comment: nos comentários da resposta eu achei o seguinte: "Tente digitar `chrome://net-internals`, executar seu código, depois volte a tela do `chrome://net-internals` e use o campo de texto para procurar o evento relacionado à sua requisição (partes da url), então clique no evento e veja se as informações te ajudam.

Erro ao fazer requisição Ajax


Create nested paragraphs programmatically

Question: Similar to the question here but for D8. I've managed to create the child paragraphs but failing to generate the parent paragraphs and attaching the child to them.
$questions = [];

foreach($data['questions'] as $question) {
    $answers = [];
    foreach($question['answers'] as $answer) {
        $correct = $answer['field_correct'] === 'Yes' ? 1 : 0;

        $answers[] = Paragraph::create([
            'type' => 'quiz_answers',
            'field_answer' => $answer['field_answer'],
            'field_correct' => $correct,
        ])->save();
    }

    $questions[] = Paragraph::create([
        'type' => 'quiz_question',
        'field_question' => $question['field_question'],
        'field_answers' => $answers,
    ])->save();
}

$new_submission = Node::create([
    'type' => 'quiz_submissions',
    'title' => 'Quiz Submission',
    'field_quiz' => $data['quizID'],
    'field_question_submission' => $questions,
]);

Comment: Does this answer your question? [Programmatically append multiple paragraphs to entity reference field on node](https://drupal.stackexchange.com/questions/236544/programmatically-append-multiple-paragraphs-to-entity-reference-field-on-node)
Comment: @Hudri thanks, that does help. But my issue is with the child paragraphs. I have an unlimited question paragraph and within it an unlimited answers paragraph. I can create either one but failing to do rest because of the 'unlimited' param.
Answer: save() returns the status of the save operation, not the entity. And you probably don't need to save the paragraphs, saving the node should save new paragraphs automatically.
So you can try this version:
$questions = [];

foreach($data['questions'] as $question) {
    $answers = [];
    foreach($question['answers'] as $answer) {
        $correct = $answer['field_correct'] === 'Yes' ? 1 : 0;

        $answers[] = Paragraph::create([
            'type' => 'quiz_answers',
            'field_answer' => $answer['field_answer'],
            'field_correct' => $correct,
        ]);
    }

    $questions[] = Paragraph::create([
        'type' => 'quiz_question',
        'field_question' => $question['field_question'],
        'field_answers' => $answers,
    ]);
}

$new_submission = Node::create([
    'type' => 'quiz_submissions',
    'title' => 'Quiz Submission',
    'field_quiz' => $data['quizID'],
    'field_question_submission' => $questions,
]);
$new_submission->save();

Comment: Indeed, didn't need to save them. Works perfectly fine now.
Comment: Very cool, that we can save paragraphs along with nodes, and no need to set $paragraph->id() as referenced value. Thanks
Comment: I wonder, can we pass raw arrays instead of creating the paragraph objects? If we do, will the paragraph objects be created automatically?


copy image over image in Content body?

Question: I want to overlay an image over another in the Content body. How do I achieve this? I do not know much about coding or themeing.
Could someone guide me please?
Thanks
Comment: Where are these images coming from? Are they both Image fields? You will probably need to edit the `node.tpl.php` in your theme and add some custom CSS (see http://stackoverflow.com/questions/48474/how-do-i-position-one-image-on-top-of-another-in-html).
Comment: No, they are not image fields, I'm inserting the images in the body field using Wysiwyg editor. Thank you for the Link, I'll try that.
Answer: You can add your own CSS classes to the images via the WYSIWYG editor. The code provided on https://stackoverflow.com/questions/48474/how-do-i-position-one-image-on-top-of-another-in-html should do what you are looking for:
.parent {
  position: relative;
  top: 0;
  left: 0;
}
.image1 {
  position: relative;
  top: 0;
  left: 0;
}
.image2 {
  position: absolute;
  top: 30px;
  left: 70px;
}

copy image over image in Content body?


YAML error : end of the stream or a document separator is expected

Question: I'm getting the following error in a yaml file
Error : end of the stream or a document separator is expected at line 2, column 11:
apiVersion: v1
^
Line : undefined  undefined
This is the entire contents of the file
<<EOT
apiVersion: v1
clusters:
    - cluster:
    server: https://3F46DDD9022BD149B88DA7ED4AFB2B30.gr7.eu-west-1.eks.amazonaws.com
    certificate-authority-data: LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSUN5RENDQWJDZ0F3SUJBZ0lCQURBTkJna3Foa2lHOXcwQkFRc0ZBREFWTVJNd0VRWURWUVFERXdwcmRXSmwKY201bGRHVnpNQjR>  name: kubernetes
  contexts:
    - context:
    cluster: kubernetes
    user: aws
  name: aws
current-context: aws
kind: Config
preferences: {}
users:
- name: aws
  user:
    exec:
      apiVersion: client.authentication.k8s.io/v1alpha1
      command: aws-iam-authenticator
      args:
        - "token"
        - "-i"
        - "terraform-eks-demo"

EOT

I've been googling this for hours but I'm getting nowhere tried . I've tried every YAML linter I can find, can anybody point me in the right direction? I am new to this, if that wasn't obvious
Answer: You need to remove <<EOT and EOT. You probably copied them from some code that injected YAML into a command line utility via a heredoc but they should not part of the YAML content.
What happens is that when the YAML processor sees <<EOT (which parses as part of a YAML scalar because < is not a special character) and then a new line. A multiline scalar at root level must be the single root node of a document. When the second line is read, the YAML processor sees a : which is not allowed here. At this point, both lines have been read as multiline scalar, and a multiline scalar cannot be used as mapping key. Therefore, the processor complains that after the single root node of the YAML document, the document must end, but instead you try to start a mapping.
Answer: I think you should keep a space before 'v1' at line2.
Answer: In my particular case, I was entering URL in address-bar like this, localhost:{port}/Swagger/index.html, but it should be as like as in our launchSettings.json(if is mentioned there) or like localhost:{port}/swagger. It resolved my problem.
Thank you.


Help with a Probability Proof

Question: How do I prove the following:
Show that if $A$, $B$ and $C$ are three events such that
$P(A \cap B \cap C) \neq 0$ and $P(C | A \cap B)$ = $P(C|B)$,
then $P(A| B \cap C) = P(A | B)$.
Here is my attempt
$P(C|A \cap B) = { {P(A \cap B \cap C)} \over {P(A \cap B)}} = P(C|B) = {{P(C \cap B)} \over {P(B)}}$
Now, I do not know what to do. I am hoping somebody can help me. This is not a homework problem.
Bob
Comment: You know that $${ {P(A \cap B \cap C)} \over {P(A \cap B)}}  = {{P(C \cap B)} \over {P(B)}}$$ and you want to show that $${ {P(A \cap B \cap C)} \over {P(B \cap C)}}  = {{P(A \cap B)} \over {P(B)}}.$$ Well...
Answer: Since $P(A\cap B)>0$ by hypothesis, one can do the following:
$$P(A | B\cap C)=\frac{P(A\cap B\cap C)}{P(B\cap C)}\frac{P(A\cap B)}{P(A\cap B)}=$$
$$=\frac{P(A\cap B\cap C)}{P(A\cap B)}\frac{P(A\cap B)}{P(B\cap C)}=$$
$$=P(C | A\cap B)\frac{P(A\cap B)}{P(B\cap C)}.$$
Now, from hypothesis againg:
$$P(C | A\cap B)=P(C | B)=\frac{P(C\cap B)}{P(B)}.$$
That is,
$$P(A | B\cap C)=\frac{P(C\cap B)}{P(B)}\frac{P(A\cap B)}{P(B\cap C)}=$$
$$=\frac{P(A\cap B)}{P(B)}=P(A | B).$$
Answer: Hint.  Write the equation $P(A\mid B\cap C)=P(A\mid B)$ in terms of quotients of probabilities.  Then compare it carefully with the equation you have already written down in your question.  A little simple algebra is all that is needed.
Answer: You are very close, you just need to do a little rearrangement.
From where you're up to:
$$
\begin{eqnarray}\frac{P(A\cap B \cap C)}{P(A \cap B)} & = &\frac{P(C \cap B)}{P(B)}\\
\Rightarrow P(A\cap B \cap C)\cdot P(B) & = & P(C \cap B)\cdot P(A \cap B)\\
\Rightarrow \frac{P(B)}{P(A\cap B)} & = & \frac{P(C\cap B)}{P(A\cap B \cap C)}\\
\Rightarrow \frac{1}{P(A\mid B)} & = & \frac{1}{P(A\mid B \cap C)}\\
\Rightarrow P(A\mid B) & = & P(A\mid B \cap C)
\end{eqnarray}
$$

Help with a Probability Proof


If $\sum\limits_{t=1}^{\infty}R_t$ is finite with $R_t\geq 0$, does $\lim_{t\rightarrow \infty}R_t=0$?

Question: This question arises from my study of economic models with an infinite time horizon in which production is constrained by a finite initial stock of a non-renewable resource.
Given $\sum\limits_{t=1}^{\infty}R_t = S$ where $S$ is finite and $R_t\geq 0\,\forall t$, can it be inferred that $\lim_{t\rightarrow \infty}R_t=0$, and if so how can this be proved?
My thoughts: From the definition of a limit and given $R_t\geq 0$, we require that for any $\epsilon >0$, there exists $k \in \mathbf{N}$ such that $R_t<\epsilon\, \forall t>k$.  If $R_t$ decreases monotonically it seems obvious that this must hold.  However, the fact that the sum is finite does not require $R_t$ to decrease monotonically.  It could be that $R_t=0$ for most $t$ and is positive only for occasional $t$ at widely spaced intervals.  In that case the result doesn't seem obvious.
Comment: If a series is convergent its terms must tend to $0$.
Comment: To be fair, this is true only if you are summing with a Cauchy method. If you were to use Cesaro criterion to sum, this result wouldn't hold.
Comment: This fact (without the redundant assumption $R_t \ge 0$) should be in every beginning calculus textbook.  Congratulations if you discovered it without ever taking such a course!
Comment: @DavideTrono In the application I am interested in, $R_t$ is the quantity of a resource used in period $t$.  Is there any reason why the Cauchy method - which to me seems much more natural than the Cesaro method - should not be used to obtain the sum to infinity?
Comment: @AdamBailey I don't think so. But if one day you will end up with a similar concept (infinite sum of resources) which, by any unluck, diverges, then maybe using stronger methods than Cauchys one could be useful.
Answer: $S_N:= \sum^N R_k$ converges, so is a Cauchy sequence, so $|\sum_{k=1}^{n+1}R_k-\sum_{k=1}^{n}R_k|= |R_{n+1}|$   becomes arbitrarily small.
This also
shows that the assumption $R_k\ge 0$ can be omitted.


Creating commerce iframe payment

Question: I need to create an iframe to my payment provider that will do the actual payment in the checkout process of Drupal commerce.
In this iframe the user will actually insert his credit card details.
What is the best way to accomplish this?
I need this (of course) to interact with the commerce checkout process.
Comment: Did you get a solution for this?
Comment: Nope...
Still looking for some help on this topic
Comment: I might have found a solution. Let me test it further then provide an answer.
Answer: I did create a Commerce payment gateway with an almost similar challenge. You can have a look at the Commerce Pesapal module code.
A brief description would be;

Register a Commerce payment method.
Create settings for your payment method if any.
Implement hook_menu()and create at least three pages. One to hold the iframe, one to hold the callback from the payment gateway and another that will hold the form used to pass values to the iframe.
The second page can also be used to pass a message to the user.
On the redirect form you will not use a 'Submit' button because we need to pass the values to an internal URL. Instead you will do something like this.
$form['#action'] = $base_path.'Path To Your Iframe';
$form['actions'] = array('#type' => 'actions');
$form['actions']['submit'] = array(
 '#type' => 'submit',
 '#value' => 'Pay',
);

On the iframe page you can get all the variables rom your redirect from using $_GET.

The rest of the details I believe will depend on the gateway provider from that point on.
Answer: Quite an old question, but if anyone still faces this issue, here are few example payment method modules apparently implementing iframe integration:

Commerce Sagepay
PayPal Payments Advanced / Payflow Link
Commerce Payment Novalnet
Commerce Paypoint (Advanced)

Creating commerce iframe payment


SyntaxError:" identifier starts immediately after numeric literal"

Question: I'm getting that error being reported in firebug:
data = data + "&network=" + rowdata.network + "&10xx=" + rowdata.10xx;

can anyone help me how to fix this error.
Comment: error being reported due to `rowdata.10xx`. This is not a valid JS.
Answer: rowdata.10xx is invalid JS. Dot notation access of properties uses identifiers and identifiers cannot start with a number. Either use a different property name:
rowdata.x10xx

or use square bracket notation, which lets you use strings instead of identifiers:
rowdata['10xx']


ILogger does not log to Application Insights when using Azure Function V2 Durable functions

Question: Can someone, please explain how to force ILogger to actually log something into Application insights when using Azure Function V2 (.net Core)?
We have Application Insights configured and it shows live telementry and unhandled exceptions. What we are trying to make work is to force Application insights to store logs we create via the default ILogger.
No matter what kind of logLevel we are using (Information, Warning, Error, Critical) - nothing gets stored in Application insights.
I have also tried creating 500 log messages in the hopes that it might push it to application insights as a batch.
Am I missing something obvious here? Can someone suggest how to use the default ILogger so that it passes something to the Application Insights associated with the Azure function App V2 (.net core)?
host.json
{
  "version": "2.0",
  "functionTimeout": "00:10:00",
  "extensions": {
    "durableTask": {
      "maxConcurrentActivityFunctions": 4,
      "maxConcurrentOrchestratorFunctions": 1
    }
  },
  "logging": {
    "fileLoggingMode": "debugOnly",
    "logLevel": {
      "default": "Information"
    },
    "applicationInsights": {
      "samplingSettings": {
        "isEnabled": true,
        "maxTelemetryItemsPerSecond": 5
      }
    }
  }
}

Azure Function V2, TimerTrigger, DurableOrchestrationClient:
[FunctionName("MainTriggerEntry")]
public static async Task RunMainTriggerEntry([TimerTrigger("%CRON_EXPRESSION%", RunOnStartup = false)]TimerInfo timer,
[OrchestrationClient]DurableOrchestrationClient starter, ILogger log)
{
    log.LogInformation("[Information] Message!");
    log.LogError("[Error]. Something occured");
    log.LogCritical("[Critical] Critical issue");
    for (var i = 0; i < 500; i++)
    {
        log.LogWarning($"[Warning] Logging to Application insights. {i}");
    }

    // We don't want more than one orchestrator running at the same time:
    var orchestrationStatus = await starter.GetStatusAsync(OrchestratorInstanceGuid);
    if (orchestrationStatus == null || !orchestrationStatus.IsBusy())
    {
        var instanceId = await starter.StartNewAsync(OrchestratorFunctionName, OrchestratorInstanceGuid, null);
        log.LogInformation($"Triggering {OrchestratorFunctionName} function with an ID '{instanceId}'.");
    }
    else
    {
        log.LogInformation($"{OrchestratorFunctionName} function with an ID '{OrchestratorInstanceGuid}' is already running.");
    }
}

Nothing shows up in Application insights that we logged. But Failures show up as they should:

This shows that ILogger saves something on disk:

More info:

Nuget package Microsoft.NET.SDK.Functions v1.0.26
Azure function v2 is connected to the Apllication insights via APPINSIGHTS_INSTRUMENTATIONKEY
Application insights shows live telemetry and Exceptions
Application insights shows some data, but not from ILogger
Comment: Peter, that's it. You are right. I see all my logs when I go to the Search menu on the left. Thank you very much. Do you want to create an answer so that I can accept it? I can do it otherwise.
Comment: See my answer :-)
Answer: The activity log is not the place you want to look for your logs. The logs written using Ilogger are stored as Traces in application insights. You can query them using the Search menu item (the option directly above the Availability menu item in your 2nd screenshot)
The activity log will show you events regarding the application insights resource itself, not the data it contains.


How do I assign a class to all table cells containing a particular string?

Question: I am working on a project for a company I just started working for and have hit a roadblock with this data visualizer I have been assigned to create. I am pulling in information from a MySQL database using PHP and embedding the data into an HTML-CSS table.
Four particular columns of this table will always contain one of the following strings: 'red', 'green', 'yellow' and 'grey'. I am trying to write a script in PHP that looks for all table cells containing the string 'green', for example, and assigns that table cell a class called 'green_circle'. My plan is to then put a green circle (a .png, most likely) in all cells with that class. I hope to do this so the information is more efficiently visible. I want to do this for each of those four colors.
Here is what the table-body looks like:

                            <?php
                                while ($row6 = mysql_fetch_assoc($orl_error)) {
                                    echo '

                                            '.$row6["project"].'
                                            '.$row6["participant"].'
                                            '.$row6["reel"].'
                                            '.$row6["machine"].'
                                            '.$row6["qc_gsr"].'
                                            '.$row6["qc_hr"].'
                                            '.$row6["qc_acz"].'
                                            '.$row6["qc_bre"].'

 ';
                                    }
                                ?>

The strings 'green', 'yellow', 'red', and 'grey' are always found in the 4 cells with names beginning with 'qc_', so qc_gsr, qc_hr, qc_acz, qc_bre. The other 4 columns never contain any of the color strings. I hope the information I have provided is clear enough for someone to figure out this problem I have been having.
Answer: Try something like this:
<?php
$keys = array('qc_gsr', 'qc_hr', 'qc_acz', 'qc_bre');
while ($row6 = mysql_fetch_assoc($orl_error)) {
    echo '

        '.$row6["project"].'
        '.$row6["participant"].'
        '.$row6["reel"].'
        '.$row6["machine"].'	';
        foreach($keys AS $key){
            echo ''.$row6[$key].'	';
        }
    echo '
 ';
    }
?>

Comment: Thanks for your answer Jessica, I am kind of a rookie developer so a more thorough answer would be even more appreciated. If, rather than inserting the key name of the column, I want to insert a circle with the color of the string that is contained in that cell, what would I want to do?
Comment: Would javascript be more useful for this task?
Comment: Then just have PHP generate the HTML needed for an image. Assuming you've already created your 4 images.
Comment: I have, can you run me through how I might do that if the image to replace the string 'green' is say green_circle.png
Comment: echo '`';`
Comment: But then you don't even need the class part. You talked about CSS classes, I assumed you'd made the class use the image already.
Comment: Jessica, wow! The simplest solution of all was to save the image files so that they started with the string! this is why I love programming! Thanks so much
Answer: This is not an easy task, to say the least, but I think you can accomplish it with a little good array based iteration, and the use of the array_keys, implode, and preg_match functions.  Basically, the goal is to make an associative array that links the keywords as the key, and the desired classes as the values.  I then join them to make a regular expression of the form #\b(key1|key2|key3)\b#i, which will search the string for any of the keywords.  Using the $matches argument for  preg_match, I get the actual matched text, and use the strtolower function to convert it to lower case, and the $classes array to convert it to the desired class.

    <?php
        $keys = array('project'
            , 'participant'
            , 'reel'
            , 'machine'
            , 'qc_gsr'
            , 'qc_hr'
            , 'qc_acz'
            , 'qc_bre'
        );
        $classes = array('yellow' => 'yellow_square'
            , 'green' => 'green_circle'
        );
        $class_keys = '#\b(' . implode('|', array_keys($classes)) . ')\b#i';
        while ($row6 = mysql_fetch_assoc($orl_error)) {
            echo '
';
                foreach($keys as $key){
                    $class = '';
                    if(preg_match($class_keys, $row6[$key], $match)){
                        $class = $classes[strtolower($matches[0])];
                    }
                    echo "".$row6[$key].'	';
                }
            echo '
 ';
         }
     ?>

I did make a few assumptions, for the sake of brevity:

I assumed that your qc_ fields would only contain one of the necessary keywords.
I assumed that the necessary keywords were on there own (i.e. that you wouldn't want `yellowbellied' to match)

I did not assume an order to your existing $row6 array.  Though there's likely some order that is implied by the select statement, which would eliminate the $keys variable, and allow you to change foreach($keys as $key) to foreach ($row6 as $key => $value), and you can thereafter change any $row6[$key] to just value.
EDIT:  To insert the img tag directly, do something more like this:

    <?php
        $keys = array('project'
            , 'participant'
            , 'reel'
            , 'machine'
            , 'qc_gsr'
            , 'qc_hr'
            , 'qc_acz'
            , 'qc_bre'
        );
        $images = array('yellow' => '/path/to/yellow_square.png'
            , 'green' => '/path/to/green_circle.png'
        );
        $image_keys = '#\b(' . implode('|', array_keys($images)) . ')\b#i';
        while ($row6 = mysql_fetch_assoc($orl_error)) {
            echo '
';
                foreach($keys as $key){
                    echo '';
                    if(preg_match($image_keys, $row6[$key], $match)){
                        echo ' ';
                    }
                    echo $row6[$key].'	';
                }
            echo '
 ';
         }
     ?>

Comment: now if my image file is called green_circle.png for the green string replacement, how might I proceed. qc_ fields DO only contain one of the keywords, and the keywords are on their own
Comment: @user2479631  That's not really what you asked in your question.  But I'll humor you.  You can either do it through php directly, or through css3 with the `before` pseudo-element.  If you want to do it with css3, I think it's outside the scope of this problem. I'll update with new PHP shortly.


How can see always selected tableView row? (iPhone)

Question: I have i problem with tableView selected row. When i select the row it selected, but when i back in the previous navigation controller the row deselected. Can i do that iPhone remember what row was selected and when i push controller it remember selected row and can it be blue?
Answer: The way objects ordinarily 'remember' things is by storing them in instance variables. So the simple way to keep track of the selected row would be add an instance variable and property of type NSIndexPath * to the list controller. Then you could use the property to store the indexPath passed to the table view controller's -tableView:didSelectRowAtIndexPath: method.
Then your list controller can override the inherited -viewWillAppear: method to send a message to the table view to re-select the row, as follows:
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    // Good idea to reload the table view's cells
    // in case the underlying data was changed by
    // another view controller.
    [[self tableView] reloadData];

    // Assuming you added a selectedIndexPath property
    // to your list controller...
    //
    if ([self selectedIndexPath] != nil)
    {
        // Select the row. Note that you need to be sure
        // that the table view is scrolled so that the
        // selected row is visible.
        [[self tableView] selectRowAtIndexPath:[self selectedIndexPath]
                                      animated:NO
                                scrollPosition:UITableViewScrollPositionMiddle];
        // Get rid of the saved selection
        [self setSelectedIndexPath:nil];
    }
}

Answer: I suggest maintaining state in the iPhone by saving the selected row index to a file (info.plist? properties.plist). Then when you return to that view, get the selected row back from the file and change the selected row index.
Comment: How can i save selected row index in a file?
Comment: http://stackoverflow.com/questions/905542/how-to-write-data-in-plist

alternatively if you are new to iPhone development look into Titanium Appcelerator, which makes iPhone development much easier by allowing you to develop iPhone apps in Javascript.
Comment: Your app should never write to Info.plist. A better place to store application state (as opposed to user data) is in the defaults system (see the NSUserDefaults Class Reference).

http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSUserDefaults_Class/Reference/Reference.html


ForEach com lambda que retorna a soma dos itens iterados

Question: Estou tentando iterar sobre uma List chamada produtos de objetos chamados Produto, usando o forEach, para obter a soma dos valores desses produtos usando a função lambda do forEach. Mas não encontro a sintaxe correta pra fazer isso.
Vejam como está meu código:
    private double getValorVenda(){
       double valor=0;

        produtos.forEach(produto -> {
            produto.getValor(Venda.class);
        });
        return valor;
    }
}

Alguma ideia?
Answer: Por que não usar um for simples?
private double getValorVenda() {
    double valor = 0.0;
    for (Produto produto : produtos) {
        valor += produto.getValor(Venda.class);
    }
    return valor;
}

O método forEach serve para "fazer algo" com cada elemento da lista, tanto que ele recebe como parâmetro um Consumer (uma operação que faz algo com o elemento e não retorna nada).
Se você tentar fazer o mesmo algoritmo acima com forEach, o código não compila:
produtos.forEach(p -> {
    valor += p.getValor(Venda.class);
});

Esse código dá um erro de compilação:

local variables referenced from a lambda expression must be final or effectively final

Isso acontece porque variáveis declaradas fora de um lambda só podem ser usadas dentro dele se forem final. Mas se eu declará-la como final:
final double valor = 0.0;

Aí eu não posso modificá-la, e o código dá outro erro:

cannot assign a value to final variable valor

Enfim, se você quer sumarizar resultados, um loop tradicional já resolve.

Mas se quiser, também pode usar streams, uma alternativa é fazer assim:
double valor = produtos
    // cria o stream
    .stream()
    // obtém os valores das vendas de todos os produtos
    .mapToDouble(produto -> produto.getValor(Venda.class))
    // soma tudo
    .sum();

Com isso, valor terá a soma dos valores, ou zero caso a lista de produtos seja vazia.
Só lembrando que streams são legais, mas têm o seu custo e geralmente serão mais lentas que um loop tradicional, e temos que balancear a clareza do código e outros benefícios que as streams trazem (vai da opinião de cada um) versus a velocidade. Claro que para casos simples como esse talvez nem faça tanta diferença, mas é algo a se considerar sempre.
Comment: Faz todo sentido. Desculpe a demora, deixei isso de lado por algumas semanas.
Answer: Lucas.
Não sei se o forEach é uma boa opção pra somar valor, e também nem consegui fazer usando ele.
O que eu normalmente uso é retornar uma stream, usar um map pra pegar os valores e um reduce depois, pra somar tudo:
double valor = lista.stream().map(x -> x.getValor()).reduce((x,y) -> x + y).orElse(0.0);

Como eu não sou nenhum conhecedor do Java 8, provavelmente deve ter jeitos mais eficientes.
Answer: Usando um foreach simples:
  private double getValorVenda() {
    double valor = 0.0;
    for (Produto produto : produtos) {
      valor += produto.getValor(Venda.class);
    }
    return valor;
  }

Ou usando expressão lambda:
  private double getValorVenda(){
    final double[] valor= {0};

    produtos.forEach(produto -> valor[0] += produto.getValor(Venda.class));
    return valor[0];
  }


Can you strum a bass guitar?

Question: I always had the idea that you can strum a bass guitar. An idea I got from watching Mark Hoppus play. Recently the bass teacher I know told me that you mostly play lead lines with a bass. I'm not sure what to believe.
The bass intro from the song 'carousel' always gave me the idea you could strum a bass.
Comment: Pretty much anything with strings can be strummed
Comment: *Heartbreaker* by Led Zeppelin and everything by Ned's Atomic Dustbin seem to indicate that strumming on bass is definitely a thing that is done by some. That said, playing single root notes and playing "lead lines" are not the same thing, from my point of view.
Comment: You can certainly strum; even us cellists do now and then.   Or you could run the back of a saw blade across the strings, or the chuck of a power drill :-) , all of which one crazy rocker or another has done at some point.
Comment: There's no contradiction anyway. "Mostly" doesn't mean "always".
Comment: Just in case you hadn't seen this lot, they **all** have bass guitars: https://www.youtube.com/watch?v=9Ky8rfTJlY4
Comment: Just had to check the dictionary again. 'Strum' = twang strings (especially carelessly or unskilfully). Had to smile...    Playing lead lines is not usually in a bassist's remit. Neither is usually playing runs.
Answer: Pretty much every string instrument can be strummed.  The Blink 182 example you provided shows an electric bass guitar being strummed. Here is an example where Charlie Haden strums on double bass:

(the strumming part starts at 3:26)
Answer: 1) Lemmy of the band Motorhead strums power chords all the time.
Here is Lemmy demonstrating his technique

2) There is a more elaborate technique for strumming on bass guitar which involves several fingers of the right hand, rather than a pick. The technique is called rasgueado, which is a technique taken from flamenco guitar.
The technique has been utilized by master jazz bass guitarists including Victor Wooten and Anthony Jackson. Chris Wolstenholme of Muse uses a similar technique in "Panic Station," visible here:
Answer: This is not a standalone answer, Todd & Shev have covered strumming - but as for lead lines, they too are possible.
The idea that a bassist must simply play along to what the rest of the band are doing I think is neatly put aside by this band.
Before Royal Blood came along, if anyone had told me that you could make a 'proper' rock band with just a drummer & bassist, I'd have been mildly amused but unlikely to take them seriously.

If you go to the YouTube page, there's a track list with clickable links to listen to bits of each track, for a quick precis of what they do.
Comment: I realise know that I used lead lines incorrectly. Maybe I just meant bassist just usually play runs.
Comment: For sure - I just used it as an example of what can be done with a bit of ingenuity :)
Answer: If it has more than one string it can be strummed.  Keith Emerson has even strummed the harp inside his piano.  I have to say that full strumming a five string may sound a bit funky with that low B, but rock bassists have been strumming for over 40 years.
And as far as "Playing lead lines is not usually in a bassist's remit. Neither is usually playing runs.", all I can say is Tim has obviously never listened to Jack Bruce, Tim Bogert, Busta Cherry Jones, or the host of other rock and jazz bassists that made the bass more than just an accompanist.
Comment: I agree the bass playing I always enjoyed where those that played melodies that went with the guitar player
Answer: Yes you can. As I mentioned in my comment, one member of Ned's Atomic Dustbin pretty much strums the bass through all of every song. He is in the foreground playing in this video:
Answer: For another example If you don't mind Nu-Metal and growling vocals then check out Mudvaynes LD 50 album. Ryan Martinie uses slap, strumming, picking almost any bass playing technique you can think of.
Answer: Les Claypool is another great bassist with a nice strum technique that he uses often... Checkout Groundhog Day by Primus:

Can you strum a bass guitar?


ssh from CL using keyfile from Windows client to Linux server

Question: This sort of thing drives me crazy - hopefully obvious solution(s). Have keys on Win 10 laptop, and on one of my Linux servers. If I use puTTY, where I can explicitly browse to the keyfile on the laptop, works perfectly.
But, not luck at all using ssh from CL with key exchange. And, this is where I'm stuck...
1\ Linux server using a non-standard port (say, 1234). Suppose username on Linux server is bob.
2\ if I use simple password authentication, and not key exchange, then
ssh -p 1234 firstname.lastname@example.com

works perfectly.
3\ but, if I try to ssh from the command line, pointing at the keyfile, no such luck. The user directory on the laptop has a space (say, c:\users\Bob Jones...), which might be part of the problem (or not). The ppk (which I'll call server.ppk) is in c:\users\Bob Jones.ssh
So, in theory, the following should work (again, in theory...)
ssh  -i "C:\Users\Bob Jones/.ssh/server"  firstname.lastname@example.com  -p 1234

But...no luck. The preceding (and the various permutations I've tried) throws errors like:
 Warning: Identity file C:\Users\Bob Jones/.ssh/server' not accessible: No such file or directory.
 email@example.com: Permission denied (publickey,gssapi-keyex,gssapi-with-mic).

So, what obvious thing am I missing? Keyfile is there, and works perfectly using puTTY, where I can uses the GUI to explicitly point at the key. But danged if I can figure out how to get things to work using the CL.
Thanks in advance...
Comment: **OpenSSH doesn't use PPK files.** The PPK format is only used by PuTTY -- and PuTTY pieces like pscp or derivatives like KiTTY and WinSCP or some other things like Java jsch. For the `ssh[.exe]` program (a port of OpenSSH) you must supply a keyfile in OpenSSH format. You can use PuTTYgen to _convert_ from PPK to OpenSSH format(s). _Traditionally_ OpenSSH privatekey files have no extension (like `id_rsa`) (and _publickey_ files have `.pub` or `-cert` if applicable) but you can use any name you like as long as you use the same name in `ssh -i`.
Answer: Does windows understand "C:\Users\Bob Jones/.ssh/server" vs "C:\Users\Bob Jones.ssh\server.ppk"


The .ccp and .h / header files output error 'this declaration has no storage class or type specifier' with implementation of SendInput function

Question: So my problem is I keep getting error
"this declaration has no storage class or type specifier"
"the size of an array must be greater than zero"
" expected a ';' "
I don't know what's wrong. I tried to look online and find no specific solution to my problem other than generic solutions like defining the class for the terms in my .h file but I don't even know where to begin defining 'ZeroMemory' or something like that. You can see in my code, in my Source.cpp, I have commented out the code and did a paste crossover into my .h file. The error presented above appears and it seems it won't compile but its fine compiling if I leave them in my Source.cpp file instead. How do I go about solving this? I'm at my wits end here.
BTW I want them on a separate file which is a .h file.
Source.cpp file
#include <windows.h>
#include <iostream>
#include <conio.h>
#include "Input Buttons.h"

int main()
{
    //INPUT blocks[6], grabs[4];

    /*ZeroMemory(blocks, sizeof(blocks));*/
    /*ZeroMemory(grabs, sizeof(grabs));*/

    //virutal key list website
    //learn.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes

    //Setting up key/mouse input environment

    //a
    //blocks[0].type = INPUT_KEYBOARD;
    //blocks[0].ki.wVk = 0x41; //keyboard button 'a'
    //blocks[0].ki.dwFlags = KEYEVENTF_EXTENDEDKEY; //press down

    //blocks[1].type = INPUT_KEYBOARD;
    //blocks[1].ki.wVk = 0x41;
    //blocks[1].ki.dwFlags = KEYEVENTF_KEYUP; //let go

    //d
    //blocks[2].type = INPUT_KEYBOARD;
    //blocks[2].ki.wVk = 0x44; //keyboard button 'd'
    //blocks[2].ki.dwFlags = KEYEVENTF_EXTENDEDKEY;

    //blocks[3].type = INPUT_KEYBOARD;
    //blocks[3].ki.wVk = 0x44;
    //blocks[3].ki.dwFlags = KEYEVENTF_KEYUP;

    //s
    //blocks[4].type = INPUT_KEYBOARD;
    //blocks[4].ki.wVk = 0x53; //keyboard button 's'
    //blocks[4].ki.dwFlags = KEYEVENTF_EXTENDEDKEY;

    //blocks[5].type = INPUT_KEYBOARD;
    //blocks[5].ki.wVk = 0x53;
    //blocks[5].ki.dwFlags = KEYEVENTF_KEYUP;

    //i
    //grabs[0].type = INPUT_KEYBOARD;
    //grabs[0].ki.wVk = 0x49; //keyboard button 'i'
    //grabs[0].ki.dwFlags = KEYEVENTF_EXTENDEDKEY;

    //grabs[1].type = INPUT_KEYBOARD;
    //grabs[1].ki.wVk = 0x49;
    //grabs[1].ki.dwFlags = KEYEVENTF_KEYUP;

    //k
    //grabs[2].type = INPUT_KEYBOARD;
    //grabs[2].ki.wVk = 0x4B; //keyboard button 'k'
    //grabs[2].ki.dwFlags = KEYEVENTF_EXTENDEDKEY;

    //grabs[3].type = INPUT_KEYBOARD;
    //grabs[3].ki.wVk = 0x4B;
    //grabs[3].ki.dwFlags = KEYEVENTF_KEYUP;

}

Input Buttons.h
#pragma once

using namespace std;

INPUT blocks[6], grabs[4];

ZeroMemory(blocks, sizeof(blocks));
ZeroMemory(grabs, sizeof(grabs));

//a
blocks[0].type = INPUT_KEYBOARD;
blocks[0].ki.wVk = 0x41; //keyboard button 'a'
blocks[0].ki.dwFlags = KEYEVENTF_EXTENDEDKEY; //press down

blocks[1].type = INPUT_KEYBOARD;
blocks[1].ki.wVk = 0x41;
blocks[1].ki.dwFlags = KEYEVENTF_KEYUP; //let go

Error in image form from my perspective
Comment: Do you know what a *function* is? Because everything below the `INPUT blocks[6], grabs[4];` line in your header belongs in a function, and as a matter of course, *not* in a header file unless inlined. I suggest a good book on C++. If you want to gut `main` (coincidentally, a function, albeit a special one), and relocate that code to a different function, so be it, but what you're doing ain't that.
Comment: Does this answer your question? [error: expected declaration specifiers or '...' before string constant](https://stackoverflow.com/questions/19371206/error-expected-declaration-specifiers-or-before-string-constant)
Answer: As it currently is, your header file has "freestanding" execution code.
This is not possible in C++ - C++ is not a scripting language where you can execute code in arbitrary files.
Every executable code needs to be in a function.
So you better declare a function prototype in your Buttons.h with the necessary data types.
Then you create a function in Buttons.cpp where you define the function with the code you want to execute and compile and link it. You can then include Buttons.h and call the function from main()
Buttons.h
#include <conio.h>

void do_stuff();

Buttons.cpp
void do_stuff() {
    INPUT blocks[6];
    INPUT grabs[4];
    //... rest of your code//
}

Source.cpp
#include "Buttons.h" // makes do_stuff() visible in Source.cpp

int main() {
    do_stuff();
}

Comment: Thanks, I actually solved it. Just created 'Buttons.h' and put it into a struct. However I put the 'INPUT' details within the first layer of the struct and then I created a function called 'do_stuff()' and put in the details of the 'INPUT' names inside of the 'do_stuff()' function. Now the problem is, how do I implement 'SendInput'? Cuz now it doesn't work cuz I don't know what to put into the first parameter. I tried 'SendInput(1, playerButtons.grabs, sizeof(INPUT)) and there was no buttons pressed at all. Can you help me on that?


Multiple Landing Pages Under Same Url

Question: I need some suggestions, I am not sure which direction to go to do this, but I need to do 4 different landing pages, with 4 different urls, example http://site.com/landingpage?blue=1, http://site.com/landingpage?blue=2.
Now everything is almost the same on the landing pages except for a banner thats going to be on the front and on 2 of the landing pages the layout will be different. I am using panels for the pages. Should I make 4 different panels for them or can panels allow me to change different elements on certain urls? How would I do that using panels? Or would you suggest a different module?
Any suggestions is appreciated,
Thanks
Answer: a way to do something like you are talking about is creating one panel page with panels variants and showing each one depending on selection rules.

Regards.
Answer: You can use View Mode Page to achieve this. Just create a new view mode per page, which if you want the same display, just clone it for each view mode and apply the styling with CSS for each view mode.

Multiple Landing Pages Under Same Url


Imagem não aparece na view, em ambiente de produção

Question: Tenho o caminho das imagens salvas no banco, e as imagens numa pasta dentro da pasta public (nomeProjecto/public/imagem-post/post_id_2.jpg). em ambiente de desenvolvimento, aparece normalmente na view. Mas em ambiente de produção não aparece, mas o caminho da imagem é salvo no banco.
Outro pormenor é que as imagens que já foram gravadas no banco antes de hospedar o site, aparecem normalmente.
Ajudem-me por favor. Desde já agradeço.
Answer: Se você está utilizando Laravel, você deve utilizar o método de asset() para pegar imagens como mostra na documentação.
https://laravel.com/docs/5.8/filesystem
Verifique também se seu framework está configurado para reconhecer a pasta onde você está salvando suas imagens.
Comment: Como faria esta verificação do framework?
Comment: Coloquei o método asset(), mas continua na mesma, não aparece nada.
Comment: Embora este link possa responder à pergunta, é melhor incluir as partes essenciais da resposta aqui e fornecer o link para referência.  As respostas apenas por link podem ser invalidadas se a página com o link for alterada. - [Da Revisão](/review/low-quality-posts/272951)
Comment: Para verificar a configuração é só ir em `config/filesystems.php`
Por padrão o Laravel usa a pasta `storage/app/public`
Para te ajudar, clica com o botão direito do seu mouse em cima da imagem quebrada, depois em `inspecionar elemento` e veja qual caminho está no seu `src`
Comment: @veroneseComS a resposta é "usar o método `asset()`" e para usar esse e qualquer outro recurso o correto é SEMPRE recorretar à documentação.


Average Diameter of a polyhedron

Question: Define the caliper diameter of a polyhedron as follows:
Let $P_1$ and $P_2$ be two planes both of which are parallel to the x axis such that the perpendicular distance between $P_1$ and $P_2$ is the smallest possible distance allowing the whole of the polyhedron to lie in the region of space between the two planes. Define the perpendicular distance between the two planes as the caliper diameter of the polyhedron.
How do I prove that the average caliper diameter of the polyhedron across all possible rotations is given by this formula:
$$\sum_{e\in E} L_e(\pi - \delta_e)/(4\pi)$$
Where $E$ is the set of all edges of the polyhedron, $L_e$ is the length of edge $e$ and $\delta_e$ is the interior angle where the two faces forming edge $e$ meet (e.g. for a cube the interior angle between two faces is always $\pi/2$).
Comment: What is an average diameter?
Comment: @lisyarus OP probably mean [mean width](https://en.wikipedia.org/wiki/Mean_width). the angular average of the length of projection of an object along all possible directions. See wiki entry for definition.
Comment: @achillehui This makes perfect sense, thank you! (btw, I've read the "mean mean" part several times until I understood this is not a typo)
Comment: @lisyarus Ah sorry - so if the polyhedron was sandwiched tightly between two parallel planes define the calliper distance as the perpendicular distance between these two planes. The average calliper distance over all rotations of the polyhedron would then be what I meant by the average diameter.

Apologies I can see this was not clear. I will update the original post.
Comment: Also posted to MO with no notice to either site, https://mathoverflow.net/questions/306318/average-caliper-diameter-mean-width-of-a-polyhedron
Answer: This answer try to derive the formula from first principle.
For an alternative derivation of the formula using relation between mean-width and integral over mean curvature, see the second half of my answer
to a related question.
Please note that the formula can fail for non-convex polyhedron
(e.g. $[0,1]^3 \setminus [\epsilon,1-\epsilon]^2\times [\epsilon,1]$)
We will assume the polyhedron at hand is a convex one.

Let $\pi_1, \pi_2$ be the projections: $
\;\;\mathbb{R}^3 \ni (x,y,z)
\;\; \overset{\pi_2}{\longmapsto}\;\;
\overset{\in \mathbb{R}^2}{(x,y)}
\;\; \overset{\pi_1}{\longmapsto}\;\;
x \in \mathbb{R}
$
Let $\mu O$ be the length/area/volume for $1/2/3$-dim geometric object $O$ in $\mathbb{R}^3$.
Let $R_3$ be a random rotation uniformly sampled over $SO(3)$.
For any convex polyhedron $P$, let $\;\nu P = \verb/E/_{R_3}[\mu \pi_1\pi_2 R_3 P]\;$ be its average caliper diameter.
Let $E(P)$ be the edges of $P$ and $E'(P) = \{ e \in E(P) : \pi_2 e \subset \partial \pi_2 P \}$. When none of the faces of $P$ is tangent to the $z$-direction, edges in $E'(P)$ will get mapped to edges of $\pi_2 P$. Furthermore, the correspondence will be bijective. In the illustration below, $P$ is a dodecahedron and $\pi_2 P$ is the gray polygon on $xy$-plane.  $E'(P)$ are those red edges on $P$ and under $\pi_2$, they get mapped to the blue edges of $\pi_2 P$.
$\hspace1in$
If one further project these edges down to $x$-axis using $\pi_1$ and sum over their length, one will notice the sum overs those edges in $E'(P)$ whose $\pi_2 e$ is facing upwards or exactly right equals to the caliper diameter of $P$ along $x$-direction.
The same thing happens to the sum over those edges whose $\pi_2 e$ is facing downwards or exactly left. This leads to
$$\mu \pi_1\pi_2 P =
\frac12 \sum_{e \in E'(P)} \mu \pi_1 \pi_2 e
= \frac12 \sum_{e \in E(P)} \verb/1/_{E'(P)}(e) \mu \pi_1 \pi_2 e
$$
where $\displaystyle\;\verb/1/_{E'(P)}(e) = \begin{cases} 1,&  e \in E'(P)\\
0, & \text{ otherwise }\end{cases}\;$
is the indicator function for $e \in E'(P)$.
Replace $P$ by $R_3 P$ and taking expectation value. Notice the probability for $R_3P$ to have any face tangent to $z$-direction is zero, one obtain
$$\nu P = \frac12 \sum_{e\in E(P)} \verb/E/_{R_3}[
\verb/1/_{E'(R_3P)}(R_3e) \mu \pi_1\pi_2 R_3 e
]
$$
For any edge $e$, let $L_e = \mu e$ be its length. Let $t_e$ be a unit vector pointing from one end-point of $e$ to another. Let $n_{e,1}$, $n_{e,2}$ be the outward pointing unit normal vectors for the two faces attached to edge $e$. Let $\psi_e = \pi - \delta_e$ be the angle between $n_{e,1}$ and $n_{e,2}$.
If one pick a unit vector $t$ and look at those $R \in SO(3)$ which make
$t_{Re} = t$. One will notice $n_{Re,1}$ and $n_{Re,2}$
lies on a circle which lives on a plane normal to $t$.
As long as $t$ is not parallel to the $z$-direction, $Re \in E'(RP)$ when the arc between $n_{Re,1}$ and $n_{Re,2}$ cut the $xy$-plane. This leads to
$$\verb/E/_{R_3}[ \verb/1/_{E'(R_3P)}(R_3e) | t_{R_3e} = t ] = \verb/Pr/_{R_3} [ R_3 e \in E'(R_3P) | t_{R_3 e} = t ] = \frac{\psi_e}{\pi} = 1 - \frac{\delta_e}{\pi} \quad $$
Aside from events of probability zero, this conditional expectation is independent of $t$, one find
$$\verb/E/_{R_3}[
\verb/1/_{R_3P}(R_3e) \mu \pi_1\pi_2 R_3 e]
= \left(1 - \frac{\delta_e}{\pi}\right) \verb/E/_{R_3}[ \mu \pi_1\pi_2 R_3 e ]
= \left(1 - \frac{\delta_e}{\pi}\right) \frac{L_e}{2}
$$
As a result,
$$\nu P = \sum_{e \in E(P)} \frac{\pi - \delta_e}{4\pi} L_e$$
Comment: hmm okay... thank you! Do you have any notion of what this sum represents for concave shapes, if not the average calliper diameter?

Average Diameter of a polyhedron


Como posso criar meu próprio protocolo assim como o HTTP?

Question: Veja esse código abaixo. Ele cria um servidor com o Node.js. Mas, se eu alterar o var http para exemplo: var xyz = require ("xyz"), var server = xyz.createserver... dá erro.
var http = require("http");
var server = http.createServer(function(request, response) {
  response.writeHead(200, {"Content-Type": "text/html"});
  response.write("<!DOCTYPE "html">");
  response.write("");
  response.write("");
  response.write("<title>Hello World Page</title>");
  response.write("");
  response.write("");
  response.write("Hello World!");
  response.write("");
  response.write("");
  response.end();
});

server.listen(80);
console.log("Server is listening");

Comment: Talvez porque criar um protocolo é muito além do que apenas renomeá-lo? Quando você usa o `require` você está "chamando um arquivo", é como se você informasse ["vou precisar usar essa biblioteca"](https://github.com/nodejs/node/blob/3954ea9f41b187915c4812ff6f360276bc94028c/doc/api/http.md). Então passa a usar o que ele oferece, que é um conjunto de funções que _alguém_ desenvolveu e você utiliza.  Quando você usa `xyz` ele não existe, portanto você não pode usar. Se você realmente quer criar um novo protocolo acredito que terá um longo caminho para isso.
Comment: @teves-rei A resposta resolveu sua dúvida? Acha que pode aceitá-la? Veja o [tour] se não souber como faz. Isso ajudaria muito indicar que a solução foi útil para você. Também pode votar em qualquer pergunta ou resposta que achar útil no site todo (quando tiver 15 pontos).
Comment: Obrigado por sua resposta. Sou novo no node.js e tals. Ainda preciso saber muita coisa.
Comment: Existem vários níveis e protocolo. Inclusive, existem protocolos sobre protocolos. O próprio TCP/IP (boa barte da nossa internet atual) funciona sobre 5 camadas principais de protocolo: 1. camada física; 2. cama da de enlace/salto (ethernet/ATM); 3. camada de rede (IP); 4. camada de transporte (TCP/UDP); 5. camada de aplicação (HTTP/FTP/SSH etc). Eu particularmente já escrevi alguns protocolos sobre o HTTP (uso HTTP como base) e, também, tive de fazer a engenharia reversa de um protocolo não documentado (lá do trabalho) que funcionava diretamente sobre TCP. Posso responder com isso, se desejar
Comment: Adendo ao meu comentário: quando li o título da pergunta, interpretei como sendo sobre protocolos de maneira genérica, não havia me atentado ao fato de estar ligado com `node.js`.
Answer: Com muito estudo dos fundamentos da computação.
Bom, simplificadamente, escreve em um papel o que deseja que ele faça, quais operações, como é o formato das mensagens, os erros, como lidar com cada situação. Já terá um protocolo.
Depois que especificou precisa implementá-lo.
Mas, não! Se nem os programadores mais experientes ficam criando protocolos a não ser em caso de extrema necessidade, não tente fazer isto em casa, nem com supervisão de adultos :)
Veja: Em que linguagem o HTTP foi escrito?.


Book recomendation for Elliptic-curve cryptography

Question: I have already taken a course on Cryptography, The course focused mainly on the  public-key cryptography based on the algebraic structure of elliptic curves over finite fields. Now, I would like to deepen this topic.
I've been searching for a book in this line, but haven't found many good recomendations.
I would like to find a book that not only explains the theoretical aspect of the Elliptic Curve, but also by means of exercice and examples put into practice the theoretical content.
Any recommendations on what books or what material may be helpful?
Thanks!
Comment: The two canonical recommendations (out of a long list of recommendations) are Koblitz for undergrad-level elliptic-curve cryptography and Silverman for a graduate-level general treatment with a modicum of elementary algebraic geometry (just at the level of, say, Riemann-Roch).
Answer: Here some recommendations from ECC:

Cryptography, An Introduction by Nigel Smart. A great little introduction to all aspects of cryptography. Elliptic curves and ECC are briefly discussed. This is a good first choice for learning about cryptography in general, and ECC in particular.

Cryptography: Theory and Practice by Doug Stinson. This is a very good introduction to all aspects of cryptography, from a relatively mathematical point of view. Elliptic curves are briefly discussed. The book is longer and has more detail than Smart's book. It is an excellent place to start for anyone with a serious interest in learning ECC.

Guide to Elliptic Curve Cryptography by Darrel Hankerson, Alfred Menezes, and Scott Vanstone. This book is written for computer scientists, engineers and security professionals who have some basic knowledge of cryptography. It gives a very thorough and detailed presentation of the implementation aspects of ECC. Many efficient algorithms for point multiplication etc are described. The book does not deeply discuss the mathematics behind ECC. This book is highly recommended for cryptographers who want to implement or use ECC in practice.

Introduction to Modern Cryptography by Katz and Lindell. This is a fine book about theoretical cryptography. It mentions elliptic curves. The focus is on rigorous security proofs, rather than practical cryptosystems. The book is not suitable for beginners in cryptography, but is an excellent text for PhD students in theoretical computer science.

A Course in Number Theory and Cryptography by Neal Koblitz. This is the best "easy" reference for ECC. It contains a nice presentation of the basic ideas. Unfortunately, the book is too elementary to cover many topics which are needed to understand the research literature in ECC. This book is highly recommended for beginners (e.g. undergraduate students in maths or computer science).

An introduction to mathematical cryptography by J. Hoffstein, J. Pipher and J. H. Silverman. This book contains a good introduction to all sorts of public key cryptography, including elliptic curves, at an advanced undergraduate level. It covers most of the main topics in cryptography, and would be a suitable alternative to the books of Smart or Koblitz. This book is recommended for students of mathematics who want an introduction to the subject.

Elliptic Curves in Cryptography by Ian Blake, Gadiel Seroussi and Nigel Smart. This book is useful resource for those readers who have already understood the basic ideas of elliptic curve cryptography. This book discusses many important implementation details, for instance finite field arithmetic and efficient methods for elliptic curve operations. The book also gives a description of the Schoof-Atkin-Elkies point counting algorithm (mainly in the case of characteristic two) and a description of some of the mathematics behind the attacks on the ECDLP.
This book is recommended for researchers in the field.

Elliptic Curves: Number Theory and Cryptography by Lawrence C. Washington. This is a very nice book about the mathematics of elliptic curves. It contains proofs of many of the main theorems needed to understand elliptic curves, but at a slightly more elementary level than, say, Silverman's book. This book would be an excellent next step after the book of Koblitz mentioned above. I recommend this book to all my students and I have not had any serious complaints yet. There is quite a lot of information about cryptographic aspects, including a discussion of the Weil and Tate pairings. This book is highly recommended for those who want to get a deeper understanding of the mathematics behind ECC.

The Arithmetic of Elliptic Curves (2nd Edition) by Joe Silverman.
Every serious researcher on elliptic curves has this book on their shelf. It is an excellent advanced textbook on the topic. The new edition has an additional chapter on algorithms for elliptic curves and cryptography. It is not the place to learn about how ECC is used in the real world, but is a great textbook for a rigorous development of the
theory of elliptic curves.

Advances in Elliptic Curve Cryptography edited by I. Blake, G. Seroussi and N. Smart. This is definitely not an introductory text. Instead it covers recent developments in ECC. The intended reader is someone with a basic knowledge of ECC who wants to learn about the latest research developments without having to read all the papers in the subject. I think it is an excellent book, but I am a contributor so am completely biased. This book is highly recommended for researchers in the field.

The Handbook of elliptic and hyperelliptic curve cryptography edited by H. Cohen and G. Frey. This is an excellent reference for researchers in the field. I increasingly use this book as a reference, and I increasingly find it useful. This book is highly recommended for experts in cryptography.

Algorithmic Cryptanalysis by Antoine Joux. This book is about algorithms in cryptanalysis. The focus is mainly on symmetric cryptography, but it contains many topics of peripheral interest to ECC, as well as some discussion of pairings.

Mathematics of Public Key Cryptography by Steven Galbraith. This is an advanced textbook, mostly about cryptography based on discrete logarithms. I am obviously totally biased, but I think it is pretty good. The book is not yet published, as it is not quite finished, but over half the chapters of the current draft are on the web.
Answer: You could try the following (in no particular order):

Hankerson, Menezes, Vanstone, Guide to Elliptic Curve Cryptography
Blake, Seroussi, Smart, Advances in Elliptic Curve Cryptography
Washington, Elliptic Curves: Number Theory and Cryptography
Husemoller, Elliptic Curves
Ash, Gross, Elliptic Tales: Curves, Counting and Number Theory

Its best to get a look at them in your nearest library or online before settling onto one book.


PHP Open Source eCommerce Software

Question: I hope you are good today, my query is a simple one i am searching for an open source ecommerce solution that can be extended with my own modules etc.
after scouring google there are loads of open source solutions and different websites recommend different solutions.
I trust the community of stack far more than random websites on google, so can you please make recommendations on systems you have previously used and how you found them on an overall.
Thanks in advance.
Answer: For a big application, you could take a look at Magento : it's a robust solution, with both a community and an entreprise version.
Another idea (that might be lighter) might be PrestaShop.

Some might suggest you osCommerce, but it's an old software -- and even if it had much success some years ago, it doesn't really anymore now (I've never used it myself, but some colleagues of mine have worked with it -- and have since switched to Magento).
Comment: thanks for the recommendation i will research both.
Comment: Having used Magento for some work projects I have to say that it is very extensible and customisable once you get your head around the hideous XML templates. Big problem we found with it is that it eats servers for breakfast. Even with full caching enabled it uses a lot of ram and cpu cycles. But it will do everything you could possibly want it to.
Comment: I was going to write exactly the same :). Btw, I am using Magento and I am in love with it. It has a lot of features and it is fully extensible. My vote is for Magento.
Comment: Thanks for your responses *still investigating* :)
Comment: @chapagain @Adam Pointer @Pascal Martin do you have a knowledge base you consult for support on Magneto ? Obviously as you guys have been using far long than i would of had, you should of already established the necessary knowledge bases for the software :)
Comment: In the end i went with Magneto thanks for the advise much appreciated !!!! :)
Comment: I used all of them, in my opinion PrestaShop is just great for small to medium websites!
Answer: i use osCommerce but it is "old software" but i have be with it a long time and know it well. for someone new looking at getting in to it i would look more to PrestaShop. osCommerce still have its good points in there is a lot of info on the web so it is not hard to find a fix when you need one.
The best bet mite be to download some and have a play for yourself :) hope this helps
Answer: I would try www.oscmax.com - it is a osCommerce fork which has all of the functionality most shop owners would need.  There is a new release coming out now (currently Release Candidate going through final testing and bug fixing)
Why oscmax?  It is truely open-source ... no purchasing of extra modules etc.  The 6,000+ modules coded for osCommerce will install into it which gives the average user an almost unlimited ability to tailor the store to their specific needs.
Friendly and active forums and an active development cycle.
I would avoid Magento - it has a very complex code structure (especially the templates) and is very resource hungry (you will need a dedicated server to run it).
PrestaShop and OpenCart are probably the next best but I prefer to use the work already done on the osCommerce community and not having to pay for additonal module (which tend to come with very poor support)
So all in all - I would give www.osCmax.com a go ... test the new v2.5 RC1 not the old version.

PHP Open Source eCommerce Software


Dump Banco de dados

Question: Tem alguma forma de saber se foi ou quando foi realizado um DUMP de um banco de dados?
Comment: Talvez seria interessante realizar backups constantes do DB
Comment: Mas tem como ver que foi realizado um backup?
Comment: Seria interessante saber qual o banco você usa e qual ferramenta de acesso.
Answer: Faça um SELECT na tabela backupset:
SELECT b.database_name AS base,
       CASE b.type
            WHEN 'D' THEN 'Completo'
            WHEN 'L' THEN 'Log'
            WHEN 'I' THEN 'Diferencial'
            ELSE 'Outro'
        END tipo,
        CONVERT(VARCHAR, b.backup_finish_date, 103) + ' ' + CONVERT(VARCHAR, b.backup_finish_date, 108) AS fim
  FROM msdb.dbo.backupset b
 ORDER BY b.database_name, b.backup_finish_date DESC

backupset
Contém uma linha para cada conjunto de backup. Um conjunto de backup contém o backup de uma única operação de backup bem-sucedida.

Dump Banco de dados


How to add item to top menu on android

Question: I want to add a a menu item to the top (Where the class title is). I added the item to menu.xml and also for made an Intent to open a new class after clicking but it does not open my whole app anymore. And when I remove android:onClick:"history" it starts working again with out the menu function of course.
Have a look at the picture please: http://snag.gy/udxXc.jpg
That 'History' is my button that needs to open a new class.  and this is my code:
xml:
<item
        android:id="@+id/history"
        android:showAsAction="always"
        android:title="History"
        android:onClick="history"/>

Java:
public void history(View view){
    Intent historyIntent = new Intent(this, History.class);
    startActivity(historyIntent);
}

Am i doing it correctly? or any better solution?
Comment: You want to add an item to the ActionBar. Have you looked at the documentation? http://developer.android.com/guide/topics/ui/actionbar.html
Answer:
I want to add a a menu item to the top (Where the class title is)

That is called the action bar.

And when I remove android:onClick:"history" it starts working again with out the menu function of course.

I am not aware that android:onClick is valid for <item> elements.

Am i doing it correctly?

Not as far as I am aware.

or any better solution?

Override onOptionsItemSelected() and respond to the item click there.

How to add item to top menu on android


Linear Algebra Practice Midterm Question: vectors in span

Question: Let $u_1, ..., u_m$ be vectors in span$\{v_1,...,v_k\}$; and let $\{v_1,...v_k\}$ be vectors in span$\{w_1,...,w_n\}$. Show that $u_1, ..., u_m$ are vectors in span$\{w_1,...,w_n\}.$
I am not sure how to prove this using appropriate formulas and theorems. Conceptually I understand that if the $u$ vectors are in the span of the $v$ vectors, and if the $v$ vectors are in the span of the $w$ vectors, then the $u$ vectors must be in the span of the $w$ vectors. I just don't know how to properly prove it.
Comment: What does it mean for $u$ to be in the span of $\{v_1,v_2\}$?
Answer: The argument, by itself, is relatively straightforward.
If $u_1,\ldots,u_m$ belong to $span(v_1,\ldots,v_k)$, then each of those vectors can be expressed as some linear combination of the vectors in $\{v_1,\ldots,v_k\}$. Remember, there is an underlying field $\mathbb{F}$ and an underlying vector space $(V,+,\cdot)$ that we need to keep in mind.
Now, since the vectors $\{v_1,\ldots,v_k\}$ belong to $span(w_1,\ldots,w_n)$ each vector in the set $\{v_1,\ldots,v_k\}$ can be expressed as some linear combination of the vectors in $\{w_1,\ldots,w_n\}$. So, it follows (using the algebraic rules on vector spaces) that every vector $u_1,\ldots,u_m$ can be expressed as a linear combination of the vectors $\{w_1,\ldots,w_n\}$. This is exactly what we wanted.
I would say that, for most people, this would be enough. Like, you can definitely formalize the above and I'd say that if you're not too experienced with Mathematics, then you probably should try to formalize it. I just hope that the gist of the argument is clear, though.


ruby on rails console processes in the background

Question: Is there a way to run processes from rails script/console in the background?
I have a onetime lib script that will take two or so days to execute and I want to set this to run in the background.
Something like:
<code>script/console
</code>
Then:
<code>>> load 'script.rb' &
</code>
In the commandline I'd just do:
<code>$ command &
</code>
I did find: http://backgroundrb.rubyforge.org/ but this seemed like overkill for just this onetime task.
I also tried:
<code>$ ruby data_importer2.rb &
</code>
This doesn't import the active record stuff though (error: uninitialized constant ActiveRecord)
Thanks!
Answer: You can do this with the script runner instead of the console:
<code>./script/runner script.rb &
</code>
Answer: You could use script/runner, or if you need to run it again at some point, the easiest way would be to wrap it in a rake task.
Answer: <code>$ script/console
>> fork { load 'script.rb' }
>> Process.detach
>> # ...
</code>