Calcular Valor das colunas SQL

Question: Tenho duas tabelas BMV_PEDIDO e BMV_PEDIDOITEM e gostaria da soma total do valor dos pedidos feitos em determinada data. Atualmente faço isso pedido por pedito, ou seja, replico esse código 70x.
Gostaria que minha consulta retornasse todos.
Segue o script atual:
SELECT p.ST_FRETE, SUM(i.NR_QTDE * i.VL_UNITARIO * i.NR_TAXACONVERSAO)
FROM BMV_PEDIDOITEM i
INNER JOIN BMV_PEDIDO p ON p.ID_PEDIDO = i.ID_PEDIDO
WHERE p.ID_PEDIDO IN (45752)
GROUP BY p.ST_FRETE

Comment: p.ID_PEDIDO in( 45752) ? é quando você tiver 1000 pedidos vai repetir 1000 vezes o mesmo código?
Comment: @JuniorTorres: Além da "soma total do valor dos pedidos feitos em determinada data", necessita também que os pedidos da data sejam listados? Ou somente o valor total, sem linhas de detalhe?
Answer: Acredito que seja isso:
select
 p.ST_FRETE,
 SUM(i.NR_QTDE * i.VL_UNITARIO * i.NR_TAXACONVERSAO) as valortotal
from BMV_PEDIDOITEM i
inner join BMV_PEDIDO p on p.ID_PEDIDO = i.ID_PEDIDO
--where p.ID_PEDIDO in( 45752)
where p.datapedido between '2016-01-01' and '2016-03-31'
group by p.ST_FRETE

Comment: Você tem o seu pedido e seus itens do pedido e quando você faz o "inner join" você está trazendo os itens de um pedido especifico, e somando os totais, se você não informar o id do pedido ele vai calcular de todos os pedidos.
Comment: Não amigo, isso ele me retorna a soma de todos.
Gostaria da soma de cada pedido;
Comment: Conforme você descreve acima, você quer a soma total do valor dos pedidos feitos em determinada data. Nesse caso essa query que o @itasouza escreveu resolveria, Agora se você quer por pedido ai precisa acrescentar o número do pedido na cláusula WHERE.
Answer:
gostaria da soma total do valor dos pedidos feitos em determinada data

Nesse caso não é necessário o uso da cláusula GROUP BY. Eis sugestão de código:
-- código #2
SELECT sum(I.NR_QTDE * I.VL_UNITARIO * I.NR_TAXACONVERSAO) as totalPEDIDO
  from BMV_PEDIDOITEM as I
       inner join BMV_PEDIDO as P on P.ID_PEDIDO = I.ID_PEDIDO
  where P.colunadatapedido = ...

Mas se o objetivo for obter a soma pedido a pedido, me parece que falta o código do pedido no resultado.
-- código #1
SELECT P.ID_PEDIDO,
       sum(I.NR_QTDE * I.VL_UNITARIO * I.NR_TAXACONVERSAO) as soma_ITENS_PEDIDO
  from BMV_PEDIDOITEM as I
       inner join BMV_PEDIDO as P on P.ID_PEDIDO = I.ID_PEDIDO
  where P.colunadatapedido = ...
  group by P.ID_PEDIDO;

Calcular Valor das colunas SQL


Proof of $\triangledown(\top,\top)$ in modal logic

Question: My textbook has this definition in it (actually, the textbook gives a definition for a modal language with arbitrary modal operators, but i believe the simple language with a single binary operator is enough to demonstrate what i want); a set of formulas $\Lambda$ is a normal modal logic iff all of the following is true:

All propositional tautologies belong to $\Lambda$,
If $\phi \in \Lambda$ and $\phi\rightarrow\psi \in \Lambda$, then $\psi \in \Lambda$,
If $\sigma$ is a map from propositional letters to formulas, and $\phi \in \Lambda$, then $\phi^\sigma \in \Lambda$, where $\phi^\sigma$ is $\phi$ with its propositional letters substituted as per defined by $\sigma$ (in other words, $\Lambda$ is closed for the uniform substituion operation),
$\triangledown(p,r)\rightarrow(\triangledown(p\rightarrow q,r)\rightarrow \triangledown(q,r))\in \Lambda$ and $\triangledown(r,p)\rightarrow(\triangledown(r,p\rightarrow q)\rightarrow \triangledown(r,q))\in \Lambda$ (these are the analogs of the K axiom for the binary modal operator),
$\triangle(p,q)\leftrightarrow\neg\triangledown(\neg p,\neg q) \in \Lambda$ (this is the analog of the Dual axiom),
If $\phi \in \Lambda$ then $\triangledown(\phi,\bot) \in \Lambda$ and $\triangledown(\bot,\phi) \in \Lambda$ (the analogs for the generalization rule),

(where $p,q$ and $r$ are distinct propositional letters)
The modal language in question is what you'd expect; given a set of propositional letters, modal formulas are either a propositional letter, or $\bot$, or $\phi \lor \psi$, or $\neg\phi$, or $\triangle(\phi,\psi)$, where $\phi$ and $\psi$ are modal formulas. Other symbols are the usual definitions ($\phi\rightarrow\psi$ is $\neg\phi\lor\psi$, $\triangledown(\phi,\psi)$ is $\neg\triangle(\neg\phi, \neg\psi)$, $\top$ is $\neg\bot$ and so on).
Now, as an easy semantic argument shows, $\triangledown(\top,\top)$ is valid (or, more precisely, it is valid on the class of all Kripke frames). We would expect it to be the case that $\triangledown(\top,\top)\in\Lambda$, for all normal modal logics $\Lambda$.
Is that actually the case?
(I actually suspect it isn't! It feels that, since you can't use the K-like axioms to change both variables at once, and the generalization-like rules always add $\bot$, you're kinda stuck with $\bot$ on one side of the $\triangledown$ formulas.)
Comment: I am not familiar with this 'bivariate' sort of modal logic, but perhaps the problem is with the definition of the 'empty frame', if you textbook allows such a thing?
Comment: @Myself: It doesn't allow for empty frames (or rather, for frames with an empty domain), no. But i fail to see how would it be related. This formula is like the simpler $\Box(\top)$, which is just outright valid. A formula like $\Box(\bot)$, however, would only be valid on a frame with an empty relation, yes, and so would its counterpart $\triangledown(\bot,\bot)$, but this is $\top$ we're talking about.
Comment: Ok, I was only guessing to rule out the obvious :) Actually I have never heard of this extension of 'standard' modal logic. Is there an online resource that explains the semantics briefly?
Comment: @Myself: I cannot seem to find one. The textbook i'm using is partially avaliable on Google; fortunately, it happens to include the two pages that define the semantics for this kind of modal logic: Page 11 (http://books.google.com.br/books?id=gFEidNVDWVoC&lpg=PP1&hl=pt-BR&pg=PA11#v=onepage&q&f=false) defines the language (with definitions 1.11 and 12), whereas page 20 (http://books.google.com.br/books?id=gFEidNVDWVoC&lpg=PP1&hl=pt-BR&pg=PA20#v=onepage&q&f=false) defines the semantics (definition 1.23).
Answer: No, it isn't.
The basic idea of the proof is this: We can define an alternative interpretation for the logic such that the logic is correct with respect to said interpretation, but $\triangledown(\top, \top)$ isn't valid in the interpretation, therefore implying that $\triangledown(\top, \top)$ can't be an theorem of the logic.
We'll restrict ourselves to the minimal normal modal logic $K_2$. We need the following alternative characterization of it:
For all modal formulas $\phi$, $\psi$ and $\rho$, we have that

All propositional tautologies (and the result of any uniform substitution applied to them, in other words, any of their instances, including those containing modal formulas) belong to $K_2$
If $\phi \in K_2$ and $\phi\rightarrow\psi \in K_2$, then $\psi \in K_2$,
$\triangledown(\phi,\rho)\rightarrow(\triangledown(\phi\rightarrow \psi,\rho)\rightarrow \triangledown(\psi,\rho))\in K_2$ and $\triangledown(\rho,\phi)\rightarrow(\triangledown(\rho,\phi\rightarrow \psi)\rightarrow \triangledown(\rho,\psi))\in K_2$,
$\triangle(\phi,\psi)\leftrightarrow\neg\triangledown(\neg \phi,\neg \psi) \in K_2$,
If $\phi \in K_2$ then $\triangledown(\phi,\bot) \in K_2$ and $\triangledown(\bot,\phi) \in K_2$,

and no other formula belongs to $K_2$.
At this point, we should prove that $K_2$ is indeed a normal modal logic, or more precisely, we should prove that $K_2$ is closed for uniform substitution, as the rest follows trivially. Note that the notion of "belonging to $K_2$" has a natural inductive structure; do an induction on that, and the proof for closure under uniform substituition follows.
Next, let's define the alternative interpretation. First, define an A-Kripke frame to be a tuple of $(W,R_a,R_b)$, where $W$ is a set, and $R_a,R_b$ are binary relations over $W$ (that is, $R_a,R_b \subseteq W\times W$). An A-Kripke model is a tuple $(F,V)$, where $F$ is an A-Kripke frame, and $V$ is a valuation function, a function from propositional letters to sets of elements of W (that is, $V : \Phi \rightarrow P(W)$, where $\Phi$ is the set of propositional letters, and $P(W)$ is the set of all subsets of $W$).
Next, we define the A-satisfaction relation $\Vdash^A$, a relation between A-Kripke models, elements of W, and modal formulas. Let $w,v\in W$, $M=((W,R_a,R_b),V)$ be an A-Kripke model, and $\phi, \psi$ be modal formulas. We have:
$$
M,w \Vdash^A p \textrm{ iff } w \in V(p)
$$
$$
M,w \Vdash^A \phi\lor\psi \textrm{ iff } M,w \Vdash^A \phi \textrm{ or } M,w \Vdash^A \psi
$$
$$
M,w \Vdash^A \neg\psi \textrm{ iff } M,w \Vdash^A \psi \textrm{ isn't the case (that is, $M,w \nVdash^A \psi$) }
$$
$$
M,w \Vdash^A \triangledown(\phi, \psi),\textrm{ with }\phi\neq\bot\textrm{ and }\psi\neq\bot, \textrm{ or } \phi=\psi=\bot,\textrm{ is never the case}
$$
$$
M,w \Vdash^A \triangledown(\bot, \psi),\textrm{ with }\psi\neq\bot, \textrm{ iff for all worlds } v\in W \textrm{ such that } R_awv, \textrm{ we have } M,v \Vdash^A \psi
$$
$$
M,w \Vdash^A \triangledown(\phi, \bot),\textrm{ with }\phi\neq\bot, \textrm{ iff for all worlds } v\in W \textrm{ such that } R_bwv, \textrm{ we have } M,v \Vdash^A \phi
$$
All other formulas can be defined in terms of those mentioned above; in particular, $\top$ is defined as $\neg\bot$, and $\triangle(\phi,\psi)$ is defined by duality, as $\neg\triangledown(\neg\phi,\neg\psi)$. So this gives us the satisfability of $\triangledown(\top, \top)$ in this interpretation as impossible, since $\top\neq\bot$.
Then all that remains is establishing the main correctness result; we'll prove that, for all modal formulas $\phi$, if $\vdash_{K_2}\phi$ (that is, $\phi\in K_2$), then for all A-Kripke models $M$ and its worlds $w$, $M,w\Vdash^A \phi$, or in more usual notation, simply $\Vdash^A \phi$ (this means: $\phi$ is a valid formula). From there, we can reason counterpositively - if $\triangledown(\top, \top)$ is not valid (in fact it is not even satisfiable!), then it can't possibly belong to $K_2$, and so doesn't belong to all modal logics; which clearly means our definition of modal logic is bogus.
We must once again reason inductively on the structure of $K_2$; this time, let's not skip the proof (at least, not the basic structure!). Let $\phi\in K_2$ be a modal formula. Then our original hypothesis, $\vdash_{K_2}\phi$ gets divided into 5 cases, the 5 possibilities we listed as justification for a formula to belong to $K_2$ (and we have to prove $\Vdash^A \phi$ in all of them):

$\phi$ is an instance of a propositional tautology. Our satisfaction relation agrees completely with the usual definitions for the propositional conectives; it must be the case that $\phi$ is valid.
$\phi$ can be derived from modus ponens, that is, there exist $\psi\in K_2$ and $\psi\rightarrow\phi\in K_2$. In this case, the inductive hypothesis tells us that $\Vdash^A \psi$ and $\Vdash^A \psi\rightarrow\phi$. Again, our satifaction relation behaves as usual regarding propositional conectives, so we do have $\Vdash^A \phi$.
$\phi$ is one of the $K$ axioms. Then consider $\phi=\triangledown(\eta,\rho)\rightarrow(\triangledown(\eta\rightarrow \psi,\rho)\rightarrow \triangledown(\psi,\rho))$ (we'll leave the other possibility for the reader, as it is rather similar to this one). We're trying to establish $\Vdash^A \triangledown(\eta,\rho)\rightarrow(\triangledown(\eta\rightarrow \psi,\rho)\rightarrow \triangledown(\psi,\rho))$. Then consider an A-Kripke model $M=(W,R_a,R_b,V)$, and $w\in W$. Next, suppose $M,w\Vdash^A \triangledown(\eta,\rho)$ and $M,w\Vdash^A \triangledown(\eta\rightarrow \psi,\rho)$. If with those hypotheses we prove $M,w\Vdash^A \triangledown(\psi,\rho)$, then we'll have proven what we wanted. Now, do observe that $\rho$ must be $\bot$, for if it were not, then we'd have  $M,w\Vdash^A \triangledown(\eta\rightarrow \psi,\rho)$ and both subformulas would be different from $\bot$, a situation defined as impossible. Also note that, since $\rho=\bot$ then $\eta\neq\bot$, for if not then we'd have an impossible situation arising from $M,w\Vdash^A \triangledown(\eta,\rho)$ and $\eta=\rho=\bot$.  Then consider a $v$ such that $R_bwv$. By our hypotheses and observations, we have $M,w\Vdash^A \triangledown(\eta,\bot)$ and $M,w\Vdash^A \triangledown(\eta\rightarrow \psi,\bot)$, with $\eta\neq\bot$. Then, by definition of the satisfaction relation, it must be the case that $M,v\Vdash^A \eta$, and $M,v\Vdash^A \eta\rightarrow\psi$. As our satisfaction relation is propositionally sound, we have $M,v\Vdash^A \psi$, and since we made no stipulation over $v$ other than $R_bwv$, we conclude that $M,w\Vdash^A \triangledown(\psi,\bot)$, which, since $\rho=\bot$, is what we wanted to conclude.
$\phi$ is one of the duality axioms. This is trivial, since $\triangle$ is defined in terms of $\triangledown$ exactly as postulated by the axiom.
$\phi$ was obtained from an application of a generalization rule. Let's handle one of them, again leaving the second one for the reader. So we have $\phi=\triangledown(\psi,\bot)$, and $\psi \in K_2$. This time, our inductive hypothesis is simply $\Vdash^A \psi$. But then we have that, for any world in any A-Kripke model, $\psi$ is satisfied there; in particular, we have that in any A-Kripke model $M=(W,R_a,R_b,V)$, for any pair of worlds $w,v$ such that $R_bwv$, $M,v\Vdash^A \psi$, and by the definition of $\Vdash^A$, $M,w\Vdash^A \triangledown(\psi,\bot)$, or simply, $M,v\Vdash^A \phi$. As this was proven for any model and world, we get $\Vdash^A \phi$.

Therefore, $K_2$ is correct with respect to $\Vdash^A$, and as we've reasoned before, we now know that $\triangledown(\top,\top)\notin K_2$, thus proving that $\triangledown(\top,\top)$ doesn't actually belong to all modal logics as defined in this question (and by the textbook). Since $\triangledown(\top,\top)$ is indeed a validity in the usual semantics, the given definition of modal logic is incomplete, in the proper logical sense of the word.
(As a final note, it is rather trivial to fix this definition. One simple way to go at is is by replacing the $\bot$ in the generalization rule with arbitrary formulas $\psi_1,...,\psi_n$, for each $\bot$ in the modal operator, though i'm not sure if this is the best one. Also, another development would be finding an actually complete semantics for this flawed definition of modal logic (or proving that there can't be one!); if someone has a link to that i'd be grateful.)
Answer: So I think that $\triangledown(\top,\top)$ does follow for all normal logics in the sense you have defined. The following would be a proof in any extension of the logic you have given.
A $\vdash\top$ by 1
B $\vdash\triangledown(\top,\bot)$ by 6
C $\vdash\triangledown(\top,\bot)\to(\triangledown(\top,\bot\to\top)\to\triangledown(\top,\top))$ by 4 and 3
D $\vdash\top\to\bot$ by 1
E $\vdash \triangledown(\top,\bot\to\top)$ by 6
Now apply MP twice to C. I think that would work unless I have misunderstood something.
Comment: You did misunderstand. Your step D does not follow.   $\top\rightarrow\bot$ is not a propositional tautology, quite the contrary in fact. As a rule of thumb, keep in mind that $\phi\rightarrow\bot$ is equivalent to $\neg\phi$. And of course, $\neg\top$ is the same as $\bot$, which is anything but a tautology.


How do I align these links inside inline-blocks to the top?

Question: I'm having a little CSS problem with a list of thumbnails. Here's an example:
http://jsfiddle.net/22hs8/
The problem is that when the link is too long to fit in the 150px block it will push the image down. By using inline-block on the list elements instead of a float I could get the images to line up properly, but now I want to have the links at the same height as well.
One thing I tried is making the links itself a block (or surrounding it by a div) and giving that a height, but that would mean they are always the same height even if none of the links uses two rules. Also, if a link is so long it uses three lines the same problem would occur.
In short: how do I align the links to the top of the list items, without breaking the image alignment?
Answer: To address one issue, you can add vertical-align:top; to the
 tag in order to align the content to the top of the element, but unfortunately, I don't believe there's a way to resolve the issue entirely without also implementing one of the following methods:

Placing all of the  tags in a separate
Specifying a height on the  tags
Using javascript to equalize heights

Options
1. Separate Div
By moving the anchor tags into a separate div, they could be given the same width as the images and floated or displayed inline accordingly, but your markup becomes less semantic when you separate the anchor from the content (and may also be programmatically more complex if these are being dynamically generated).
2. Specifying a Height
This option can be thrown out almost immediately because, as you've stated, the anchor lengths can fluctuate to multiple lines. You could specify the height the the largest know line length, but then you'll ultimately end up with unnecessary white space with groups of short links.
3. JavaScript (jQuery)
While It would be ideal to resolve this issue without the requirement of JavaScript, I think it may be the only option that would allow you to preserve the semantics of your markup, and also apply an equal height to each of the anchor tags.

Recommended Solution
I would recommend setting a default height on the anchors of the largest known line length, then applying a bit of jQuery to normalize the heights of the anchors. This way, if the JavaScript parsing fails or JavaScript is disabled, the user still sees a uniform layout (albeit with potentially more whitespace), and with JavaScript active the heights are normalized.

Apply vertical-align:top; to the

Define default height for non-js users
Equalize heights using jQuery:
(function(){
    $.fn.equalizeHeights = function(){
        return this.height( Math.max.apply(this, $(this).map(function(i,e){ return $(e).height() }).get() ))
    }
    $(function(){ $('li a').equalizeHeights(); });
})();

Example: http://jsfiddle.net/Eg7hy/
Comment: Good answer. Unfortunately the first solution is not really semantically correct, but I do feel it is one of the cleanest solutions code-wise. I might just do that.
The fixed height problem I already dismissed in my question. I thought about the JavaScript solution as well, but I don't feel comfortable having to resort to that for such a minor layout issue.  Thanks for the in-depth answer though. I will discuss this with the guy responsible for the requirements and see which of the answers would fit our website best :)
Comment: Requirements have changed, which allowed me to solve it in a slightly different way. This answer was still the best imo.
Answer: How is this:
http://jsfiddle.net/22hs8/3/
Comment: If the title ends up being three lines or longer, it runs over the image.
Comment: Is the title height totally dynamic?
Comment: This is one of the solutions I mentioned in my question. The problem is that it's not dynamic enough. If I can be sure links would never exceed two rules I might just use this after all, but at the moment I can't.
Answer: So you're saying that you want the links to not push the content down? I don't see that as being possible unless you don't allow your content to stretch at all. It's natural flow of a page for something above content to force the content down after it if it needs more space.
Have you thought about chopping off the text after a certain number of characters, with a '...' and providing the full text through a title, and providing the full text through a popup (since I assume you're creating some kind of photo gallery)?
Comment: I thought of that, but I'm not sure if the requirements allow it. I got pretty far using text-overflow: ellipsis (just needs a little extra firefox hack), but these decisions are not up to me (just an HTML codemonkey :P). Might be a good solution though.
Comment: Coding for an employer I take it? It's always good to show them what could possibly happen if they don't take your suggestion and provide examples of other websites that use what you're talking to them about. You can also use PHP to cut off the text after a certain point and tack on the ellipsis. I'm pretty sure other programming languages do this as well.
Answer: The first answer that came to mind was:
"just use a table, it makes this really easy, and works everywhere"
Live Demo

However, I would probably get down voted into oblivion if I posted an answer only containing a
 tag version, so here's a version using CSS display: table and friends:
Live Demo
Of course, that won't work in IE7 because that browser doesn't support display: table.
I can't think of a way to do this using code closer to your original and display: inline-block, which would also support an arbitrary number of lines. I'd love to see a better way to do this.
HTML:

Some text

Some more text (too long)

Some text

Some text (seriously too long) text text text text text text text text text text text text text

image

image

image

image

(you could change some of those div tags into ul and li if you wanted to)
CSS:
#container {
    display: table
}
.row {
    display: table-row;
    text-align: center
}
.cell {
    display: table-cell;
    width: 150px
}
.image {
    width: 150px;
    height: 150px;
    background: grey
}

Comment: Ugh, why would I go through all that trouble if I could just use a table... Oh yeah, because it's completely unsemantic HTML. Using nested divs to simulate a table is like the worst solution ever.
Comment: @Stephan Muller: Example: http://jsfiddle.net/eL5tT/2/ - Certainly nicer than using Javascript unless it's exceptionally important to you that the link and image be in the same element (I can't see why it would be). If IE7 support is vital to you, you could perhaps serve Javascript to fix it through an IE conditional comment.
Comment: @Myles Gray: Appreciated. It did irritate me at the time that I got a downvote for what I thought was a useful idea.
Comment: I have used your above technique to other questions's answers and not received down-vote, you just can't please some people... I felt it was an injustice for a good solution as well as the time and effort put into this.
Answer: Add vertical-align:top; to the images.
Comment: You can add vertical-align to images to align the text near them.
Comment: For example, look at this and try to remove the vertical-align: http://jsfiddle.net/M4vRE/


jquery para clicar e fazer aparecer/desaparecer divs diferentes

Question: Preciso fazer com que ao clicar no item do menu, uma div linkada a esse item apareça na tela, se eu clicar em outro item do menu, a div anterior desaparece e a nova div apareça... na foto abaixo da pra ter uma ideia do que preciso:
Quando eu clicar em GOLEIROS por exemplo, vai desaparecer a div que contem as imagens da DEFESA e vai aparecer a div com as imagens dos goleiros.
Comment: Estilo um `navbar`, um menu ?
Answer: Vi que você colocou a tag jQuery, porém esse resultado é bastante parecido usando somente CSS:

#time { width: 100%; height: 150px;
  overflow: hidden; text-align: center;
  background-color: #005500; }

.jogadores { width: 100%; height: 150px; }

.jogadores h3{ color: #FFF; }

#menu { width: 100%; text-align: center;
  background-color: #004500; }

#menu ul{ margin: 0; }

#menu li { display: inline-block; padding: 10px; }

#menu a { text-decoration: none; color: #FFF; }

Goleiros

Defesa

Laterais

Goleiros

Defesa

Laterais

A ideia neste código foi colocar a div dos jogadores com o mesmo
  tamanho da div que elas estão dentro, o overflow: hidden é para
  que exiba uma div de cada vez e que só exiba a outra div quando
  clicar no link do menu que está apontando para o id de cada uma.

O restante é contigo.
Comment: Perfeito! Funcionou certinho
Answer: Pelo o que eu entendi o código abaixo pode resolver seu problema, claro que você deverá mudar algumas coisinhas, mas a essência é essa. Espero ter ajudado.
HTML
<button onclick="showataque()">Ataque</button>

ATAQUE

<button onclick="showdefesa()">Defesa</button>

DEFESA

CSS
#ataque {
display: none;
width: 100%;
padding: 50px 0;
text-align: center;
background-color: lightblue;
margin-top:20px;
}
#defesa {
display: none;
width: 100%;
padding: 50px 0;
text-align: center;
background-color: lightblue;
margin-top:20px;
}

JavaScript
function showataque() {
   var x = document.getElementById('ataque');
      if (x.style.display === 'none') {
          x.style.display = 'block';
      } else {
          x.style.display = 'none';
      }
}

function showdefesa() {
   var y = document.getElementById('defesa');
      if (y.style.display === 'none') {
          y.style.display = 'block';
      } else {
          y.style.display = 'none';
      }
}

Answer: Veja esse exemplo, acredito que seja mais ou menos isso que você quer!

function mostraDiv(caller) {
        if (caller.id === 'goleiros') {
            $("#divGoleiros").attr("style", "display: block");
            $("#divDefesa").attr("style", "display: none");
            $("#divLaterais").attr("style", "display: none");
            $("#divVolantes").attr("style", "display: none");
        } else if (caller.id === 'defesa') {
            $("#divGoleiros").attr("style", "display: none");
            $("#divDefesa").attr("style", "display: block");
            $("#divLaterais").attr("style", "display: none");
            $("#divVolantes").attr("style", "display: none");
        } else if (caller.id === 'laterais') {
            $("#divGoleiros").attr("style", "display: none");
            $("#divDefesa").attr("style", "display: none");
            $("#divLaterais").attr("style", "display: block");
            $("#divVolantes").attr("style", "display: none");
        } else if (caller.id === 'volantes') {
            $("#divGoleiros").attr("style", "display: none");
            $("#divDefesa").attr("style", "display: none");
            $("#divLaterais").attr("style", "display: none");
            $("#divVolantes").attr("style", "display: block");
        }
    }
img {
    height: 240px;
}

.navbar {
        overflow: hidden;
        background-color: #333;
        position: fixed;
        bottom: 0;
        width: 100%;
    }

    .navbar a {
        float: left;
        display: block;
        color: #f2f2f2;
        text-align: center;
        padding: 14px 16px;
        text-decoration: none;
        font-size: 17px;
    }

    .dropbtn {
        background-color: #4CAF50;
        color: white;
        padding: 16px;
        font-size: 16px;
        border: none;
        cursor: pointer;
    }

    .dropbtn:hover, .dropbtn:focus {
        background-color: #3e8e41;
    }

    .dropdown {
        position: relative;
        display: inline-block;
    }

    .dropdown-content {
        display: none;
        position: absolute;
        background-color: #f9f9f9;
        min-width: 160px;
        overflow: auto;
        box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
        z-index: 1;
    }

    .dropdown-content a {
        color: black;
        padding: 12px 16px;
        text-decoration: none;
        display: block;
    }

    a {cursor: pointer;}
    .navbar a:hover, .dropdown:hover .dropbtn {
        background-color: red;
    }

    .show {display:block;}

    GOLEIROS
    DEFESA
    LATERAIS
    VOLANTES

Coloquei a imagem que tu forneceu (sem editar) só para você ter uma noção de como ficaria.
Referências:

W3Schools - How TO - Clickable Dropdown
W3Schools - How TO - Fixed Menu
Comment: então você precisa fazer uma chamada para cada div, ele só fez defesa, basta pegar o código, copiar e colar e criar todas as outras
Comment: Quase isso... seu código está funcionando quando eu clico no item DEFESA a DivDefesa aparece...mas eu preciso que quando eu clicar nos outros itens do menu, a DIV correspondente aquele menu apareca e as outras divs fiquem ocultas...
Comment: @Clayton, é exatamente conforme o flourigh falou, eu só coloquei um exemplo de como você deve prosseguir! Você não quer o código pronto né ?


How can I create a Nullable Optional Numeric (integer/double) parameter in VB.NET?

Question: How can I create a nullable numeric optional parameter in VB.NET?
Answer: EDIT: this should be possible in VB.NET 10 according to this blog post. If you're using it then you could have:
Public Sub DoSomething(Optional ByVal someInteger As Integer? = Nothing)
    Console.WriteLine("Result: {0} - {1}", someInteger.HasValue, someInteger)
End Sub

' use it
DoSomething(Nothing)
DoSomething(20)

For versions other than VB.NET 10:
Your request is not possible. You should either use an optional parameter, or a nullable. This signature is invalid:
Public Sub DoSomething(Optional ByVal someInteger As Nullable(Of Integer) _
                        = Nothing)

You would get this compile error: "Optional parameters cannot have structure types."
If you're using a nullable then set it to Nothing if you don't want to pass it a value. Choose between these options:
Public Sub DoSomething(ByVal someInteger As Nullable(Of Integer))
    Console.WriteLine("Result: {0} - {1}", someInteger.HasValue, someInteger)
End Sub

or
Public Sub DoSomething(Optional ByVal someInteger As Integer = 42)
    Console.WriteLine("Result: {0}", someInteger)
End Sub

Answer: You can't, so you'll have to make do with an overload instead:
Public Sub Method()
  Method(Nothing) ' or Method(45), depending on what you wanted default to be
End Sub

Public Sub Method(value as Nullable(Of Integer))
  ' Do stuff...
End Sub

Answer: You can also use an object:
Public Sub DoSomething(Optional ByVal someInteger As Object = Nothing)
If someInteger IsNot Nothing Then
  ... Convert.ToInt32(someInteger)
End If

End Sub
Answer: I figure it out in VS2012 version like
Private _LodgingItemId As Integer?

Public Property LodgingItemId() As Integer?
        Get
            Return _LodgingItemId
        End Get
        Set(ByVal Value As Integer?)
            _LodgingItemId = Value
        End Set
    End Property

Public Sub New(ByVal lodgingItem As LodgingItem, user As String)
        Me._LodgingItem = lodgingItem
        If (lodgingItem.LodgingItemId.HasValue) Then
            LoadLodgingItemStatus(lodgingItem.LodgingItemId)
        Else
            LoadLodgingItemStatus()
        End If
        Me._UpdatedBy = user
    End Sub

Private Sub LoadLodgingItemStatus(Optional ByVal lodgingItemId As Integer? = Nothing)
    ''''statement
End Sub


Advice on how to keep learning while away from a piano

Question: Last year, at 35, I started learning to play the piano from absolute beginner level by attending private classes once per week.
The teacher mixed practice with music theory and learning Solfeggio (I'm meaning sight reading the notes from a music sheet).
Currently, and for work reasons, I spend 5 days a week overseas and I can't play the piano at all while I'm there as I don't have a permanent residence where I'd put a cheap digital piano.
My question is whether you have ideas or advice on how I could still use some time while I'm abroad to keep learning more about music theory and other useful knowledge that I could later apply to the piano in the future. Furthermore from not forgetting the knowledge I already had.
I accept any idea: books, software, websites, mobile apps, ...
If it helps, I'm from Europe so I'm learning with what I believe is called Fixed-Do.
Answer: I don't know if this could help but when I shifted to the guitar as a primary instrument but still wanted a piano-layout to work on harmony, I got a MIDI controller keyboard that pretty much worked for me out of the box. Granted, it is not great for building technique, but having a portable MIDI keyboard like the CME X-key which you could carry around in a standard laptop case could help practice when you're on the move or away from a real piano. I use Sampletank 3 with my controller and am very satisfied with the sound.
You could work on understanding the sounds of diatonic chords in all 12 major scales, play simple melodies with chords and transpose them to different keys, or even work on something easy and rewarding like learning the blues scale. This is not a substitute for practice on a real piano, but this is the least I can think of considering your situation.
Happy playing!
Comment: I use a 49 key Roland A-49 and it pretty much works fine for me but it does take me quite a long time to move to a fully weighted keyboard after weeks of only playing on soft keys. You could check out videos of Jordan Rudess going crazy on an X-key so it's certainly not impossible to learn a considerable amount from playing on it.
Comment: Thanks, I had no idea that there were MIDI keyboards as small as this one. Are the keys similar in size to a real piano?
Comment: I actually went for a 37 key controller, as I can leave it in the office during the weekend, so I didn't need it to be extra portable. But semiprime you gave me the idea!
Answer: Sight-singing or a miniature keyboard might help you to continue to practise sight-reading.  Theory books and exercises will definitely help with theory, but specific resource recommendations are out-of-scope here.  If you are working towards taking a music conservatory exam or anything like that, it would probably make sense to work through their books or at least look into the topics in their syllabus.
As far as actual playing goes I don't think you have too many options.  You could use a grip strength exercise tool to help maintain finger strength, though.
Comment: Thanks. No, no conservatory or exam. I want to fulfill a long-time desire, to be able to play the songs I like from the music sheet. Of course my aim to achieve that is not in short term but more in 5-10 years, if I can keep improving on it. In any case, if you would have any theory resource in mind, don't hesitate to mention.


How to sort projects alphabetically by name in PyDev Package Explorer in Eclipse?

Question: In addition is there any universal way of doing this which works for other types of projects (in other perspectives) as well?
Comment: I don't know about PyDev but in the standard Eclipse Package Explorer, projects are _only_ sorted by name.
Comment: I was looking for something similar, to see the package content sorted alphabetically instead of the order from inside the file. It's really hard to navigate through big modules without sorting.
Answer: I was experiencing this (very annoying) problem, and I found a post by somebody on SourceForge having the same problem  who said he discovered that if he added the project's root folder to its PYTHONPATH, it cleared up the problem. So I looked at my mis-alphabetized project's PYTHONPATH and saw that it already included the root folder in addition to the src folder. So just on a whim, I removed the root folder from PYTHONPATH. (I really should not have had it there anyway.) And although that was the opposite of what he said fixed his problem, it fixed my problem. Go figure.
Comment: This is the answer, way to go!
Answer: The following worked for me:

Add the project root to the projects PYTHONPATH
Right click on project > Close Project
Right click on project > Open Project

The problem projects then magically appeared in the right order.
Answer: As Matt already stated, the default and only behaviour of the Eclipse Navigator, which can be used in any perspective, is to sort the projects by name. My Eclipse version (3.6.2) gives me the option to sort resources by type but this applies to leafs of the tree (files) only.
But your question was about PyDevs navigator so I looked at the PyDev Package Explorer. I didn't find an option to change the sorting of projects. My current installed version is 2.7.1.x and as I can remember the same applies to 2.6.0.x.
So your question can't be answered directly because there is no way to change the sorting of projects without putting your hands on the source code of the plug-ins or extending the navigators (if a corresponding extension point exists).
Comment: Navigator is superseded by Project Explorer
Comment: @Piotr you're right but the Project Explorer has no option to change the sorting too. But even now after opening that view I discovered/recognized that the projects in my current workspace are not really sorted alphabetically. `My_Project_VV` is listed before `My_Project_SW` and the same order is displayed by the PyDev Package explorer. The C/C++ Projects view shows the same order as the Navigator (after disabling the filter of none C elements). I had a short look at the sources of PyDev but didn't find an obvious reason. May be this is a bug of PyDev or the CommonNavigator framework.
Answer: My solution to the problem was to go to the ViewMenu icon in the PyDevPackageExplorer and choose Select Working Set. In the Select Working Set window I left the selection as No Working Sets and clicked OK. This appears to have refreshed the alphabetical order as everything is sorted correctly now.


Is $\langle \overline{x}-\alpha, \overline{y}-\beta\rangle$ a principal ideal of $\mathbb{C}[x,y]/\langle x^3-y^2\rangle$?

Question: I'm trying to understand better  the maximal ideals of $\mathbb{C}[x,y]/\langle x^3-y^2\rangle$ and if I did well they are of this form $\langle \overline{x}-\alpha, \overline{y}-\beta\rangle$ and I'd like to know if they are principal, but I'm really stuck with this.
Thanks for any help
Answer: We will show for example that $\langle \bar x - 1, \bar y - 1 \rangle$ is not principal.
To see this, note that $$\mathbb{C}[x,y] / \langle x^3 - y^2 \rangle \simeq \mathbb{C}[t^2, t^3]$$ via an isomorphism where $\bar x \mapsto t^2, \bar y \mapsto t^3$.  Here, we can also view $\mathbb{C}[t^2, t^3]$ as the set of $p \in \mathbb{C}[t]$ such that the coefficient of $t^1$ is 0.  Now, suppose to the contrary that $\langle \bar x - 1, \bar y - 1 \rangle$ were a principal ideal; then $\langle t^2 - 1, t^3 - 1 \rangle$ would have to be a principal ideal of $\mathbb{C}[t^2, t^3]$.  Suppose the generator is $p(t)$.  Then since $t^2 - 1$ is a multiple of $p$, we would have to have $p$ of the form $\lambda, \lambda(t-1), \lambda(t+1)$, or $\lambda(t^2-1)$ for some $\lambda \in \mathbb{C}^*$.  Out of these forms, $\lambda(t-1)$ and $\lambda(t+1)$ are not in $\mathbb{C}[t^2, t^3]$; and $\lambda$ would generate the unit ideal giving a contradiction since $\langle t^2 - 1, t^3 - 1 \rangle$ is not the unit ideal.
We are left with the only possibility being that $p(t) = \lambda(t^2-1)$.  However, then $t^3-1$ is not a multiple of $p$ (even in the larger ring $\mathbb{C}[t]$), giving a contradiction in this case as well.
Comment: Thanks. It is so helpful


Area under ROC curve for random forest

Question: Does the area under ROC curve depends on which class is defined as default positive class by the random forest model?
I am using caret package in R to train and validate a random forest model.
library("ROCR")
library(caret)
rfmodel=train(x,y,method="rf",trainControl=ctrl,
 ntree=500,tuneGrid=data.frame(mtry=c(2,3,4)))
print(rfmodel)
predict.rf=predict(rfmodel,testdata,type="prob")

Now predict.rf has two columns representing probability for class 0 and class 1 respectively, which of this column should be used to calculate area under ROC curve.
In current case, By default the tpr is defined by taking class 0 as the positive class. As I understand The ROC curve is a plot between tpr and fpr. Does the ROC curve and AUC change if I define the positive class as 1 and accordingly tpr and fpr will be swapped?
Answer: Yes, but it is not relevant in practice, except some very rare cases when class order is somewhat not equivalent to the model (like in one-class SVM).
Exchanging class order simply changes AUROC from $a$ to $1-a$, so anyway your model makes so much sense as AUROC is far from .5. This way it is basically safe to report $1-a$ when $a<.5$, and many AUROC implementations will do this automatically.

Area under ROC curve for random forest


Can we pass a Url path and a file name to FileOutputStream in java

Question: Sir I am new in java i Want to write a file on URL path is there is any possible way to write a file on URL path give me some tips
Comment: refer to some good java file handling tutorial
Comment: It lacks information.
Comment: What protocol do you want to use to transfer the data? FileOutputStream won't work, you have to use a way that uses a specific protocol (HTTP PUT, FTP etc.)
Comment: Do you mean file name by "file"?
Answer: No you can not pass URL path and FileName both as a parameter to FileOutputStream.
However you can write a to a file by reading from a specified URL using the below code:
 try{
            URL url = new URL("http://docs.oracle.com/javase/7/docs/api/java/io/FileOutputStream.html");
            String path = "D://StackOverflow/";
            InputStream ins = url.openStream();
            OutputStream ous = new FileOutputStream(path);
            final byte[] b = new byte[2048];
            int length;

                while ((length = ins.read(b)) != -1) {
                       ous.write(b, 0, length);
                 }

                   ins.close();
                   ous.close();
        } catch(Exception e){
            e.printStackTrace();
        }

And could you please explain what you are actually trying to achieve by passing URL and fileName to FileOutPutStream?
Answer: File file = new File(url.getPath());
FileOutputStream fileOutputStream = new FileOutputStream(file);

This actually works for simple cases, like for file:/path/to/abc (which is actually a malformed file URL since it's missing //) or file:///path/to/abc (the correct file URL syntax.) However, this fails to work when the path contains URL-unsafe characters, such as file:///c:/Documents%20and%20Settings/..., because "%20" ends up in file name, which is wrong.
We've been told that java.net.URI is added in JDK1.5 to replace the broken URL class, so why don't we try that?
File file = new File(url.toURI());
FileOutputStream fileOutputStream = new FileOutputStream(file);

This nicely converts %20 to a space (and all the other escaped characters.) The problem solved? Nope. URI is very draconian, and it fails to handle URLs like file:///c:/Documents and Settings/. This URL is broken as far as RFCs are concerned, but the reality is that java.net.URL accepts it happily, so you often end up seeing this. I'm sure many have done new URL("file://"+fileName); — those are the code that creates this URL.
So the current version I have is to combine both:
    File file;
    try {
      file = new File(url.toURI());
    } catch(URISyntaxException e) {
      file = new File(url.getPath());
    }
   FileOutputStream fileOutputStream = new FileOutputStream(file);

Answer: yeap, it should be possible - you can use constructor new FileOutputStream(new File(new URI())). Read more about java.net.URI class.


Using frequency data to populate dataframe in R

Question: I am trying to model an existing meta-analysis to examine alternative hypotheses (e.g., doing a random-effects analysis), as well as re-sampling techniques.  There are over 2,000 subjects, but the data is fairly simple:  a binary outcome, success or failure, linked with a score (0-10) on a structured assessment.  I have the frequencies of success or failure for each score, nested within each study.  I am looking for a easier way to create the dataset rather than keying it in, or using the rep function multiple times.
I would like each row to look something like this:
Study_ID, Test_Result[0-10], Outcome[0 or 1]
For example, let's say I just had two studies and two test levels (1 or 2):  study 1 has 35 successes, and 85 failures for score of "1";  for a score of "2," 46 successes and 83 failures.  In study 2, for a score of "1"  there are 78 successes, 246 failures; for a score of "2," 45 successes and 96 failures.
Using just the frequencies provided, how could I most easily create a data frame with the several hundred lines of data?
Comment: Welcome to SO, please provide a `dput(head(your_data, 10))` in order to let us see what your data looks like and (if possible) a desired output.
Answer: This might work, the only thing that should need to be modified to add more studies is the studies list.
## Your specifications
## Put the lengths of each grouping/study in a list so it's easy to work with
studies <- list(
    study1 = c(35, 85, 46, 83),
    study2 = c(78, 246, 45, 96))
score <- rep(1:2, each=2) # 1 1 2 2
type <- rep(0:1, len=4)   # 0 1 0 1

## Repeat score/type by counts of each grouping/study
res <- lapply(studies, function(study)
    data.frame(
        score=rep(score, study),
        type=rep(type, study)
    ))

## Combine into data.frame
dat <- data.frame(study=rep(seq_along(studies), times=sapply(studies, sum)),
                  as.list(do.call(rbind, res)))
head(dat)
#   study score type
# 1     1     1    0
# 2     1     1    0
# 3     1     1    0
# 4     1     1    0
# 5     1     1    0
# 6     1     1    0

## Check counts
with(dat, table(type, score, study))
# , , study = 1
#
#     score
# type   1   2
#    0  35  46
#    1  85  83
#
# , , study = 2
#
#     score
# type   1   2
#    0  78  45
#    1 246  96


Modal And Input Type FILE ANGULAR

Question: i work for a personal project (a social network). Users can create, modify et delete Post and they can comment each post
I work on Angular
I have a post-list component which display posts.
I create a fonction to open a modal to display a Form to create a post
    displayForm() {
    const dialogConfig = new MatDialogConfig();
    dialogConfig.disableClose = false;
    dialogConfig.autoFocus = true;
    dialogConfig.width = "600px";
    dialogConfig.maxWidth = "80%";
    this.dialog.open(FormPostComponent, dialogConfig);
}

On the Html of FormPostComponent i have an input type File if the user want to upload an image

    Ou choisir une image
    <input
        #fileinput
        type="file"
        class="input-file"
        id="file"
        formControlName="file"
        (change)="addFile($event)"
    />

The problem is i can't have access to the file, the file seems to be retrieved by another input behind the modal.
I find a solution with set in my modalCompononent : encapsulation : ViewEncapsulation.ShadowDom but i don't think it's the solution because ShadowDom is not supported with all the browsers
@Component({
selector: "app-form-post",
templateUrl: "./form-post.component.html",
styleUrls: ["./form-post.component.scss"],
encapsulation: ViewEncapsulation.ShadowDom,

})
the path of the input change
Thanks
Answer: It's nested in the target element property.
addFile(event: any) {
    const files: File[] = event.target.files;
}

This is cleaner. Pass on the input element directly:
<input #fileinput
(change)="addFile(this.fileinput)"
...

and retrieve it:
addFile(input: HTMLInputElement) {
    const files: FileList | null = input.files;
}

Comment: I think it may need `event.target.files[0]` to grab the first file available! not sure though

Modal And Input Type FILE ANGULAR


Gerar e apagar linhas de uma tabela com JQuery

Question: Fiz uma função que gera linhas em uma tabela mas não estou conseguindo apaga-las.
Alguém poderia me dizer como eu consigo adicionar e remover toda vez que eu clicar nos botões?
Função que gera as linhas
var i = 0;

$('#addRow').click(function(){
    // GERA UMA PROXIMA LINHA
    $('
'+
        '	'+
        ''+periodo[i]+'	'+
        '<input type="text" class="form-control" style="width:150px;">	'+
        '	'+
        '	'+
        '	'+
    '
').appendTo('tbody');

    i++;

    // PARA O BOTAO QUANDO CHEGAR NO 12
    if(i == 12){
        $('#addRow').prop("disabled", true);
    }
    return false;

});

Função que remove as linhas
$('#delRow').click(function(){

    $('t_row'+i).remove();

    i--;

    return false;
});

Botões HTML

    <button class="btn btn-primary" id="addRow" >Adicionar linha</button>

    <button class="btn btn-danger" id="delRow">Apagar linha</button>

Tabela HTML

                Meses
                Periodo
                Demanda(Y)
                X
                X2
                X*Y

                ...
                ...
                ...
                ...
                ...
                ...

Comment: Onde você define o `i` do `$('#delRow').click`? Imagino que ele esteja fazendo o seguinte `$('t_rowundefined').remove()`
Comment: Esta como global. Acabei me esquecendo de mostra-la.
Comment: Coloca a tabela com algum dado, por favor.
Comment: Carlos falta o # em `$('t_row'+i).remove(); `, deveria ser `$('#t_row'+i).remove();`
Answer: Existem dois problemas no seu script. O primeiro é que o i está sendo decrementado depois de remover a linha, logo ele vai tentar decrementar uma linha que ainda não foi criada. O segundo é que você colocou $('t_row'+i).remove();, logo não está se referindo a nenhum elemento, para acessar o id, faltou o #. Segue exemplo com o script corrigido:

var i = 0;

$('#addRow').click(function(){
    // GERA UMA PROXIMA LINHA
    $('
'+
        '	'+
        'teste'+i+'	'+
        '<input type="text" class="form-control" style="width:150px;">	'+
        '	'+
        '	'+
        '	'+
    '
').appendTo('tbody');
    i++;
    // PARA O BOTAO QUANDO CHEGAR NO 12
    if(i == 12){
        $('#addRow').prop("disabled", true);
    }
    return false;
});

$('#delRow').click(function(){
    i--;
    $('#t_row'+i).remove();
});

    <button class="btn btn-primary" id="addRow" >Adicionar linha</button>

    <button class="btn btn-danger" id="delRow">Apagar linha</button>

Outro problema é que você não colocou um ponto de parada no decremento, o que pode fazer o i ficar negativo e isso criar mais do que 12 linhas, já que ele iria de -n até 12.


JAVA Google App Engine, JDO select specific data and do summ on all (like excel)

Question: I am new to GAE and my skill level in JAVA is novice to intermediate somehow..
So I need help on retriving a specific filed that is an integer from JDO, and on that do the sum all, like in excel where you select all numbers and do auto sum. Hope is clear what I wont.
This is my JDO query where i select all field and all data from my datastore using jdo:
<code>PersistenceManager pm = PMF.get().getPersistenceManager();
List<JDO> greetings = (List<JDO>) pm.newQuery(JDO.class).execute();
</code>
How do I do to select a field from my class that is called "Cost" and make a sum off all the values tha are stored inside?
Lets say:
Type           Cost
Food           30
Drink          20
Drink          10
...            ...
And I wont the sum of all the costs? How can I make it?
Please help me!!! And thank you!!
Answer: The answer mentioning aggregation in the database, stored procedures and PL-SQL in the context of App Engine is not very helpful, as these are features which are currently not available in the App Engine datastore.
I would advise to check the JAVA code of this example: http://code.google.com/intl/de-DE/appengine/articles/sharding_counters.html
I believe getCount() may point you in the right direction.
Answer: If it is a small dataset do the calculation in java and optionally store it in a cache and separate datastore entry.
For calculating it on many entries I would go for a map and reduce method to do calculation initially.
Check out http://code.google.com/p/appengine-mapreduce/
http://gbayer.com/big-data/mapreduce-analytics-on-google-appengine/ lists a few other alternatives, like the sharding method described by T. Abilo


Drupal 7: Display latest articles by an author with bio

Question: I have a content type called "Author" and have an author field on other content types which has a reference to the "Author" CT. (e.g. News Article having an author field)
The "Author" CT has these fields:

Title (Author Name)
Image
Bio

I'm using Panels on Drupal to create pages and I want to display Author pages like /author/author-name with Views, Panels, etc to display the Author name as Title of the page, author image and bio on top and the latest nodes by that author below all that bio.
I've created a view called Author with a contextual filter Content: Author but I'm unsure about how to use this on a Panel.
How do I go around this process to embrace panel pages and views to create author pages?
Answer: If you create a views panel pane (available as a views display mode) and place that with panels, then you can accept arguments from the panels context when editing the view. The display will have panels argument options controls that other display modes do not offer.
Comment: I understand that I can just drop the view pane in a panel but if a node (like News article) has a an author field displayed on the node (e.g. This news article is by "Author Name") and if someone clicks on that "Author Name" link to open the author node, how will it be displayed? I want to have that author node to display that panel page I create. And how do I add the bio and image on that panel? I mean, which view?
Comment: This sounds like several different questions.
Comment: Sorry for the confusion. Ok, I've figured something out now. I created a panel variant with a selection rule as node type being viewed (=author) and the URL pattern for an author is /author/author-name so when I open an author node it picks up that panel variant. I've then created a view displaying all nodes (except author nodes) with a contextual filter Content: Author so that I can display all the articles from an author.  Now my only question is this: When I drop this view on that panel variant then the articles are not displayed on /author/author-name. Is the contextual filter correct?
Comment: OK, I've figured it out. The contextual filter is Content: Author only but with "Provide default value" set to "Content ID from URL". *feels stupid*. Thanks for your help, Beth. :)
Answer: OK, so here's what I did.
I created a panel page with a selection rule as Node Type = Author.
I changed the URL pattern (pathauto) for Author content type as author/[node:title]
Then I created a view with a content pane called Author Archives with a Contextual Filter set to Content: Author and set the option WHEN THE FILTER VALUE IS NOT AVAILABLE to Provide default value: Content ID from URL. This view then looks for the author ID in the URL and then displays all the content posted by that Author.
I then dropped that view pane on the panel page that I created before with other page elements like node being viewed: Title for Page title as Author name, node being viewed: Image as the author image and node being viewed: Body as the Author Bio.
After saving this panel, when you go to any author node (/author/author-name) -- you'll see an author archive with Author name, image, bio and all the latest articles from the view.


remote host can't send mail using sendmail in ubuntu

Question: I have followed the below steps to configure sendmail

apt-get install sendmail
add the below content in /etc/mail/auth/client-info
 AuthInfo:<gworks.yyy> "U:<email@example.com>" "I:<firstname.lastname@example.com>" "P:<xxxxxxx>"

sudo bash -c "cd /etc/mail/auth/ && makemap hash client-info < client-info"
add the below lines in /etc/mail/sendmail.mc before MAILER_DEFINITIONS
define(SMART_HOST', <gworks.yyy>)dnl
define(confAUTH_MECHANISMS', EXTERNAL GSSAPI DIGEST-MD5 CRAM-MD5 LOGIN PLAIN')dnl
FEATURE(authinfo', `hash /etc/mail/auth/client-info')dnl
sudo bash -c "cd /etc/mail/ && m4 sendmail.mc > sendmail.cf"
service sendmail restart

Test with telnet command
telnet command from remote host throws error Relaying denied
root@e5eae2c464a7:/var/www/public# telnet 10.1.2.3 25
Trying 10.1.2.3...
Connected to 10.1.2.3.
Escape character is '^]'.
220 cthree.gworks.yyy ESMTP Sendmail 8.15.2/8.15.2/Debian-3; Tue, 11 Oct 2016 06:45:28 GMT; (No UCE/UBE) logging access from: development.internet(OK)-development.internet [10.1.2.4]
helo server
250 cthree.gworks.mobi Hello development.internet [10.1.2.4], pleased to meet you
mail from: firstname.lastname@example.com
250 2.1.0 firstname.lastname@example.com... Sender ok
rcpt to: firstname.lastname@example.com
550 5.7.1 firstname.lastname@example.com... Relaying denied

what I did wrong here why it is not get send mail from remote host?
Answer: Sendmail by default refuses relaying (accepting messages from external hosts to external email addresses).
You may allow relaying based on sending host IP address or after SMTP AUTHentication.
To allow relaying based on sending host IPv4 address use one of the following entries in access file (access file requires compilation using makemap):
# relay if connection from 10.1.2.4
connect:10.1.2.4  RELAY
# relay if connection from 10.2.0.0/24
connect:10.2.0    RELAY
# relay if connection from 10.3.0.0/16
connect:10.3      RELAY

WARNING:  IMHO relaying based only on IP address without any additional checks is fit as permanent solution only for small nets/sites.  Spammers and hackers make it unfit for bigger nets.


How to stop loop,when it find the correct answer?

Question: I'm trying to make a projectile calculator, so it really need to change the way to calculate again & again until it is done.
but now i'm facing with a problem..again :(
var Height = Number(document.getElementById("Height").value);
var Velocity = Number(document.getElementById("Velocity").value);
var Range = Number(document.getElementById("Range").value);
var First = ((((Math.SQRT2 * Velocity) + (Math.sqrt(19.6) * Velocity * Height)) * Math.cos(0.785398163)) / 9.8);
document.getElementById("First").innerHTML = First;
if(First < Range)
    document.getElementById("show").innerHTML = "Need more velocity to success on this range";
    else
    {
    for(var i = -1.570796327; [>>>****HELP****<<<] ; i+0.000000001)
    {
    ((((Velocity * Math.sin(i)) + Math.sqrt(Velocity * Math.sin(i) * Velocity * Math.sin(i) - 19.6 * Height))) / 9.8) * Velocity * Math.cos(i))
    }
    }

ALL of this code is make for finding a correct angle for projectile shooting, and I use "i" for angle

Please look on [**HELP**] that's the problem...I want to stop this loop after my calculation is equal to "Range" but I really have no idea to do that :(
After I got the correct "i" how can i print it to show the answer?

or anyways to make this code better or faster calculation?
Ty for every help :)
Comment: use `break` statement, will "jumps out" of a loop.
Answer: You could use break to exit the loop if you reached the expected value/range. You may also check if your result is near your range within +/- a value because you probably won't get the exact same values as you defined for Range.
for(var i = -1.570796327; i < MaxValue ; i+0.000000001)
{
   result = ((((Velocity * Math.sin(i)) + Math.sqrt(Velocity * Math.sin(i) * Velocity * Math.sin(i) - 19.6 * Height))) / 9.8) * Velocity * Math.cos(i));
   if(result >= Range) break;
}

Comment: In this case it might be a bit safer to do `if(result >= Range)` or do an epsilon check as you suggest
Comment: then after it break how can I use "i" for next calculation? any suggestion? thank you
Comment: Just use it for your next calculation. You will have the value at that point you exited the for loop.
Answer: Use this where you want to break
if "condition fullfilled inside for-loop"
 return false;

To print it why not use:
console.log(i);

Answer: In jquery and js, if you are using loops (for, while, $.each) than return true will be equal to continue in PHP, and return false will be equal to break. Since you are using simple for loop, than there is enough to use return false to break this loop.
Comment: If they're equivalent, why not just use `break`? It's more obvious what the code is doing in that case
Comment: [Yes there is](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/break). Please do your research
Comment: Because there is no `break` in js, thats why.


android: How to increase long press time for listview items in android?

Question: I have a custom listview, in which items are scroll horizontal. I want to perform single touch and longpress for items for 5 sec for listview items. How to do this. How can i increase longpress time interval for listview items to 5 sec.
Answer: This replicates onLongPress more accurately because it does not wait for the user to lift their finger before executing. Was written specifically for ViewPager, but should be able to apply similar logic.
// long press duration in milliseconds
public static final int LONG_PRESS_DURATION = 2000;

private boolean mIsTouching = false;

@Override
public boolean onTouchEvent(MotionEvent event) {

    if (event.getAction() == event.ACTION_DOWN) {
        mIsTouching = true;
    } else if (event.getAction() == event.ACTION_UP) {
        mIsTouching = false;
    }

    return super.onTouchEvent(event);
}

@Override
public void onLongPress(MotionEvent event) {

    // subtracts the system set timeout since that time has already occured at this point
    int duration = LONG_PRESS_DURATION - getLongPressTimeout();

    Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            if (mIsTouching) {
                do something...
            }
        }
    }, duration > 0 ? duration : 0);
}

Comment: Where's the `onLongPress(MotionEvent)` method? I can't find it in `ViewPager`. Do you mean the `onLongClick(View view)` in `View.OnLongClickListener`?
Comment: Thanks. Worked for me, although I had to remove the getLongPressTimeout() from your solution.
Comment: This can be done more simply by starting the postDelayed in `onTouchEvent`/ACTION_DOWN. There, it is not necessary to subtract getLongPressTimeout.  Do not need `onLongPress`.
Answer: Here is my implementation: (You don't need to release to shot the action)
Handler longTouchHandler= new Handler();
static final int longduration=10000;//10000ms press duration
@Override
public boolean onTouchEvent(MotionEvent event) {
    if (event.getAction() == event.ACTION_DOWN) {
        longTouchHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                Log.w("Longpress","longpressed");
            }
        }, longduration);
        return true;
    }
    else if (event.getAction() == event.ACTION_UP) {
        longTouchHandler.removeCallbacksAndMessages(null);
        Log.w("Longpress","cancelled");
    }

    return super.onTouchEvent(event);
}

Answer: You can setOnItemLongClickListener, then you can set the view you touch a OnTouchListener, you can record the time when ACTION_DOWN and the time ACTION_UP, so you can calculate if the time is more than 5 sec between ACTION_DOWN and ACTION_UP.
Comment: IMO that would be an unnatural usecase because we usually wait for the popup or any changes before we release the finger, the user does not typically count `188.8.131.52.5` then release.
Comment: To clarify Enzokie's comment: if you wait for ACTION_UP to calculate the time, user has no way of knowing when they have held it long enough. Instead, the action should be triggered on a delay after ACTION_DOWN, if the finger is still touching. See Denver's answer.
Answer: You cant change the delay. It is hardwired in the android framework. I also came across same problem days ago.
You can use setOnTouchListener for it manually.
Example :
private long then;
private int longClickDur= 5000; //5 seconds

//you can use any view you want
ImageView imageView = (ImageView) findViewById(R.id.longclick_view);
imageView.setOnTouchListener(new OnTouchListener() {
      @Override
      public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
          then = (long) System.currentTimeMillis();
        } else if (event.getAction() == MotionEvent.ACTION_UP) {
          if ((System.currentTimeMillis() - then) > longClickDuration) {
            /* Long click behaviour will go here*/
            Toast.makeText(context, "yay, long click", Toast.LENGTH.SHORT);
            return false;
          } else {
            /* LONG CLICK FAILED*/
            Toast.makeText(context, "TRY AGAIN", Toast.LENGTH.SHORT);
            return false;
          }
        }
        return true;
      }
    });

Comment: I did the same thing, but in that case, horizontal scrolling of listview not happening....
Comment: This has the same problem that Enzokie mentioned on juemuren's answer:  this does not give USER any feedback as to when they have held the touch long enough. See Denver's answer for better approach.
Comment: this is long click, not long press


jquery result not loaded into pdf when using dompdf

Question: I'm developing a reporting application and i use dompdf for create pdf report.
I want to load chart to the pdf result, but it have no result. but when i view in browser it show my expected result, but when i save to pdf it didn't loaded the chart..
this is my function created
function pdf_create($html, $filename, $paper, $orientation, $stream=TRUE)
        {
            require_once("dompdf/dompdf_config.inc.php");
            spl_autoload_register('DOMPDF_autoload');

            $dompdf = new DOMPDF();
            $dompdf->set_paper($paper,$orientation);
            $dompdf->load_html($html);
            $dompdf->render();
            if ($stream) {
            $dompdf->stream($filename.".pdf");
            } else {
            $CI =& get_instance();
            $CI->load->helper("file");
            write_file($filename, $dompdf->output());
            }
        }

Comment: Are you saying your HTML content relies on jQuery? If so dompdf won't work for you. There are few server-based PDF rendering classes that support browser-oriented JavaScript. Your best bet is [wkhtmltopdf](http://code.google.com/p/wkhtmltopdf/).
Comment: @BrianS Actually I have success to load all content of a web page using dompdf, but i have 1 page that using jquery to show the graphics. I just have problem for this page.
Comment: dompdf can handle all standard HTML, but not anything related to browser JavaScript (jQuery included). If there's a way to capture the graphic from the web browser and in image format then you could send that back to the server. Otherwise you'll have to look for another PDF library or another graphics library (a PHP-based one would work).
Comment: @BrianS, or maybe it will be easier if i just print out the page right.,?
Comment: That's always an option if it meets your needs.
Answer: Use MPDF. It is very good for creating Pdf file  from html content.
http://www.mpdf1.com/mpdf/index.php
Comment: mPDF does not support browser-oriented JavaScript. Few server-based PDF generating classes do.


How to check if there are multiple

Question: Is there a way of checking using if () statement if there are multiple   in a string?
For example this is checking for one
if ($value == " ")

$value is from foreach loop, so I need somehow using RegEx (I guess) check if there are   (there could be lots of them).
Comment: The code you gave doesn't check if `$value` contains ` ` it checks that `$value` is the same as ` `.
Comment: In other words you want to check if a string contains at least 2 ` `?
Comment: If there are only ' ' and it doesn't matter how many there are of them
Comment: You can split given string by " " and can check count >= 1 as well.
Answer: You can use substr_count:
if (substr_count($value, ' ') > 1)  {
    ....
}

UPDATE : Response to OP's comment (How to check if in this string are ONLY   without any other character?? ). Alternative that use str_replace.
if ($value != '' && str_replace(' ', '', $value) == '') {
    ...
}

Comment: @AigarsCibuļskis, See punund's answer.
Comment: But! How to check if in this string are ONLY   without any other character??
Comment: @AigarsCibuļskis, I updated the answer with the alternative that use `str_replace`. Check it out.
Answer: As you asked for regexp:
if (preg_match('/^( ){2,}$/', $value)) { ... }

This will match if and only if the string is composed of two or more  s.
Comment: @AigarsCibuļskis, You can change `{2,}` to `{1,}` or `+`.
Comment: and if string contains 1+   I need to change 2 to 1 of course, yes?
Comment: in this case it's simpler: `/^( )+$/`
Comment: It should, I tested it.  Check your inputs.
Answer: <?php if (!empty($value));  ?>

or You can use substr_count:
if (substr_count($value, ' ') > 1)  {
    ....
}

Answer: Try this,
if (substr_count($value, ' ') > 1)  {
    $new_str = str_replace(" ", '', $value); //if you want to replace
}

How to check if there are multiple


Hard probability problem: How to calculate the the probability of having selected only < 70% of all marbles in a bag, given the following draw rules?

Question: Imagine I have 100 marbles in a bag. Each marble is uniquely labeled. I want to draw 9 marbles out of that bag all at once. I call this a selection. Once I have draw 9 marbles, I put them back. I make 50 such selections (in other words I draw 9 marbles and put them back 50 times).
I need to know the probability of selecting no more than 70% of all marbles during this process. In my mind, this probability as a percentage should be 100% - the probability of selecting 70% or more of the marbles.
Comment: This is a straightforward variant of the generalized Coupon Collector problem answered at https://stats.stackexchange.com/questions/101255/.  Another closely related variant appears at https://stats.stackexchange.com/questions/208756/.
Answer: Let's solve this generalized Coupon Collector's problem generally, drawing $m=9$ out of $n=100$ balls for $r=50$ times.
If $E(i;r)$ is the event that exactly $i$ distinct balls have been seen after $r$ draws, then--conditional on this--the chance in the next draw of obtaining $k$ balls that haven't yet been seen is found by counting what proportion of the $\binom{n}{m}$ possible samples consist of $m-k$ balls that have been seen and $k$ balls that have yet to be seen.  Any such sample is comprised of an $m-k$-subset of the $i$ balls that have been seen together with a $k$-subset of the $n-i$ unseen balls, whence
$$\Pr(k\mid E(i;r)) = \frac{\binom{i}{m-k}\binom{n-i}{k}}{\binom{n}{m}}.$$
By summing over the possible values $i=0, 1, \ldots, n$, each multiplied by $\Pr(E(i;r))$, we obtain the chance of having seen exactly $k$ distinct balls in $r+1$ draws.
This update rule, which begins by observing that $m$ distinct balls will be obtained in the first draw, is a simple calculation requiring at most $(m+1)(n+1)$ fast calculations for each successive draw, and thereby requires at most $O((r-1)(m+1)(n+1))$ effort and only $O(n)$ storage.
Here are the probability distributions for $r=50$ draws along with some milestones along the way.

We can track the chance of observing $70$ or fewer distinct balls along the way.  It rapidly drops from $1$ down to almost $0$, so it's best to plot its logarithm:

After $50$ draws this chance is only $3.162808\times 10^{-51}$, in accord with your intuition.
Comment: Sometimes when I see you guys explain these probability problems, it seems like magic. Thank you very much for both the explanation and the reference.


Why is fetch_assoc() not returning a value?

Question: For the life of me I can't figure out why fetch_assoc() is returning false here:
$username = $_POST['username'];
print("Username is " . $username . "
");

//Create query
$query = ("SELECT * FROM users WHERE username = '" . $username . "'");
print($query . "
");

//Run query
if (!$result = $db2 -> query($query)) {
    print("Query failed!");
}

if (!$user = new LG_User($result))
    print("Failed to create user!
");

while($row = $result -> fetch_assoc()) {
    $rows[] = $row;
}
var_dump($rows);
print("User is " . $user -> first_name . "
");

The query is successful and the new user object is created, because the last line of code is printing $user->first_name correctly. I'm using the very same block of code to populate the $rows array on another page and it is working. What am I doing wrong here? If I try to use
while($row = mysqli_fetch_assoc($result)) {
    $rows[] = $row;
}
instead of
while($row = $result -> fetch_assoc()) {
    $rows[] = $row;
}
it still doesn't work. What am I missing here?
Comment: new LG_User($result) ? var_dump($result) ?
Answer: You haven't shown the code for the LG_User constructor, but if it's filling in $user from the database, it must be calling a fetch function itself. So when it returns, all the rows of the result have been fetched, and there's nothing left for your loop to read.
You can go back to the beginning of the result set with the data_seek method.
if (!$user = new LG_User($result))
    print("Failed to create user!
");
$result->data_seek(0);
while($row = $result -> fetch_assoc()) {
    $rows[] = $row;
}
var_dump($rows);

Comment: That's it! You're my hero -- I'm embarrassed to say how long I've been sitting at this console trying to debug this issues. Thank you!


Keras single hidden layer model outputting different results given same input?

Question: I'm trying to train a binary classifier with Keras. This is my model:
model = Sequential()
model.add(Dense(DENSE_DIM, activation='relu', input_shape=(data_shape[1:])))
#model.add(Dropout(0.3))
model.add(Dense(target_len, activation='softmax'))
model.summary()

adam = Adam(lr=learning_rate)
model.compile(loss='binary_crossentropy', optimizer=adam, metrics=['binary_accuracy'])

I train the model with the following line:
 model.fit(train, train_target, epochs=num_epochs, batch_size=batch_size, class_weight=weights, validation_data=(dev,dev_target))

I've removed the dropout from the hidden layer to the output layer and I have already checked the input and it is the same every time I run the model. Still I am getting slightly different accuracy and f1 measures:
TrainsetLen:(1231, 865) #EPOCH: (50, 'bert', 0.001, 64) AVG: 0.7047619047619048 F1: 0.693599566738888
TrainsetLen:(1231, 865) #EPOCH: (50, 'bert', 0.001, 64) AVG: 0.7180952380952381 F1: 0.7101035060334213

This is how I compute them:
fold_acc = accuracy_score(test_target, test_preds)
fold_f1 = f1_score(test_target, test_preds, average='macro')
print("Test Accuracy on fold "+str(fold)+": ",fold_acc)
print("Test F1 on fold "+str(fold)+": ",fold_f1)
avg_acc += fold_acc/num_folds
avg_f1 += fold_f1/num_folds

the order of the folds is also the same. Shouldn't I be getting consistent results? What can be causing inconsistency on my model?
Thanks for your time and attention,
Lucas.
Answer:
The model initialization is random. Each update depends on the current position, which depends on the previous position and so to the initialization. Using well-tuned gradient descent on a strongly convex problem should remove this, but neural networks are not convex and gradient descent is hard to tune.
Minibatch-based training is stochastic, because different minibatches are passed to the model. This is because minibatches are constructed by sampling without replacement within each epoch. Different minibatches imply different model predictions, which implies different losses and different gradients. So the updates for 1 epoch applied to the same data set can still be different, because at each step, the direction of the update will probably be different.

If you need repeatable output for each call to fit, you'll need to take some additional steps. The documentation explains how to do this.
Comment: Thanks for your answer. Is there a way that I can pass a seed for the random initialization of the model? I need to benchmark and test some different setups on the same model and the comparison becomes irrelevant when the model is not consistent.
Comment: Whenever I have questions about how to use software, I find it helpful to read the documentation. https://keras.io/getting_started/faq/#how-can-i-obtain-reproducible-results-using-keras-during-development


How to remove Midori from Elementary OS 0.2?

Question: Sometime ago I met Elementary OS and loved it, but it isn't stable yet.
Midori is the default browser of Elementary. If you go to "Applications" you can find and open Midori, but when you go to the Software Center you can't find it.
I want to delete Midori because I prefer Chromium, but as I can't find it in the Software Center, how I can remove it?
Answer: How to remove Midori browser from Elementary OS 0.2?
I don't know why you want remove Midori, but if you have this issue and really want remove Midori from your Elementary, you can follow these instructions:

Open your Software Center
In the search, type: "midori-granite"
Just click in "Remove" button of this item.

Well done, your Midore browser was removed from Elementary!
Comment: Q (by you) "... I want delete Midori because I prefer Chromium ..." A (by you) "... I don't know why you want remove Midori ...".  Split personality, or just a copypaste from some FAQ section?
Comment: It just struck me as a pretty odd way of writing stuff.  Now, please have a look [at the FAQ](http://stackoverflow.com/help/on-topic), I think this question should probably migrate to [superuser](http://superuser.com/) and voted to perform this migration automatically.
Comment: hahaha, well, I just tried to show how a user would ask, and then as a user answer.
Comment: (I wrote the Q and A, I don't find it in any faq section).
Answer: You can easily remove midori from Freya by typing this command in your terminal:
<code>sudo apt-get remove midori-granite
</code>
Cheers
Comment: The best answer every geek would love ... short and sweet.. It did the job right and Midori is gone..!!


Banco de dados não mostra os dados inseridos pelo usuário

Question: Bom dia, estou tentando fazer um sistema de notícias, porém o banco de dados não recebe os dados do php. Gostaria de saber como resolver isso.

    <meta charset="utf-8">
    <title>Inserir Notícia</title>

    <?php

        $host = "localhost";
        $user = "root";
        $pass = "";
        $banco = "sistemanoticias";
        $conexao = @mysql_connect($host, $user, $pass) or die(mysql_error());
        mysql_select_db($banco) or die (mysql_error());

    ?>

    <?php

        $titulo = $_POST['titulo'];
        $campo = $_POST['campo'];

        $sql = mysql_query("INSERT INTO noticias(titulo, campo) VALUES('$titulo, $campo)");
        echo "Notícia inserida com sucesso";
    ?>

    Retornar para o Início

Comment: `VALUES('$titulo, $campo)` problemas com aspas...
Comment: Já considerou o uso do ```PDO``` no lugar do ```mysql```? Os benefícios são enormes.
Comment: Utilize `mysqli_*` ou `PDO` invés de `mysql_*`, porque a mesma se encontra DEPRECATED.
Comment: eu arrumei esse erro, porém ainda continua não enviando.
Comment: Aparece algum erro na tela? Já tentou usar `error_reporting(1);` ?
Answer: Os campos de texto deve estar entre aspas simples cada um, sempre adicione mysql_error() para pegar a mensagem de erro do banco.
$titulo = mysql_real_escape_string($_POST['titulo']);
$campo = mysql_real_escape_string($_POST['campo']);
$sql = "INSERT INTO noticias(titulo, campo) VALUES('$titulo', '$campo')";
$result = mysql_query($sql) or die(mysql_error());

Leitura recomendada:
Por que não devemos usar funções do tipo mysql_*?
MySQLi vs PDO - qual o mais recomendado para usar?
Por que dizem que utilizar @ arroba pra suprimir erros é uma má prática?


do i need to build a vm to use a vpn

Question: I want to connect to a custom VPN in google cloud platform, and even potentially route that vpn traffic to a different vpn in a separate region using google cloud services. However, I'm assuming I need to route this traffic through multiple VM instances, thus causing me to purchase more cloud space and build multiple VM instances. Is there a way to use cloud services to access a small partition of their services to build a console that is dedicated to routing my traffic to a VPN in the cloud? I want to build a VPN in a way other than building a VM in the cloud and then creating and connecting a VPN through that VM. Thanks so much.
Answer: Given GCP has a cloud VPN product, no you don't need to run your own to get onto their network.

do i need to build a vm to use a vpn


select() and poll() in Linux

Question: So, I have been reading about select and poll man pages, but unfortunately, I am still confused about some things. It would nice if someone can answer the following questions for me:

What happens when a file in opened in non-blocking mode? (O_NONBLOCK flag is set)
When there is data is the buffer, read() blocks or returns what?
And what happens when there isn't any data in the buffer to read?
Answer:
What happens when a file in opened in non-blocking mode? (O_NONBLOCK flag is set)

I/O operations don't block and instead return an error code that indicates they would have blocked.

When there is data is the buffer, read() blocks or returns what?

When there is data in the buffer, read returns it.

And what happens when there isn't any data in the buffer to read?

If the socket is blocking, it blocks until some data can be returned. If the socket is non-blocking, it returns an error code that indicates that it would have blocked had the socket been blocking.
By the way, one important caution with select and poll -- they should almost never be used with blocking sockets. When you get a read or write hit from select or poll, that means a hypothetical, canonical operation performed at some time in-between when you called the function and when it returned would not have blocked. These are status-reporting functions and do not provide future guarantees. If you are writing a program that must never block, it must set all its sockets non-blocking.
Answer:
What happens when a file in opened in non-blocking mode? (O_NONBLOCK
  flag is set)

If the file can't be opened immediately, open() returns an error instead of blocking, open() may block only with FIFOs.
If the open() is successful, all IO operations will be non-blocking. It means, if the IO operations can't be completed immediately, it would be performed partially or it fails with an error (EAGAIN or EWOULDBLOCK).

When there is data is the buffer, read() blocks or returns what?

The difference between blocking and non-blocking read() occurs when there is no data to read. Therefore, when there is data in the buffer, non-blocking read() returns it.

And what happens when there isn't any data in the buffer to read?

If there is no data, non-blocking read() returns with EAGAIN error.

select() and poll() in Linux


"Reverse Hölder" type inequality on a dense subset?

Question: I want to know if the following is possible.
Fix some measure space  $(X,\mu)$. Take any $f\in L^1$. Recall that $L^1 \cap L^2$ is dense in $L^1$, i.e. for every $\varepsilon > 0$ there is some $g\in L^1 \cap L^2 $ such that $\Vert f - g \Vert_1 < \varepsilon$.  If $\mu(X)<\infty$ we can bound the $L^1$ norm of $g$ in terms of the $L^2 $ norm, like so: $\Vert g \Vert_1 \leq \mu(X)^{1/2} \Vert g \Vert_2$; this is an immediate consequence of Hölder's inequality.
I want to know when you can get a similar bound in the other direction, that is, that there exists some $C$ such that $\Vert g \Vert_2 \leq C \Vert g \Vert_1$. More specifically, (under what circumstances) can we show that there exists some constant $C$ (possibly depending on $\Vert f \Vert_1 $ and $\varepsilon$) such that there exists some some $g\in L^1 \cap L^2 $ such that $\Vert f - g \Vert_1 < \varepsilon$ and $\Vert g \Vert_2 \leq C \Vert g \Vert_1$? (In other words, can we show a reversal of the usual interpolation inequality on a dense subset?)
Answer: A "reverse Hölder inequality" exists in the literature. It is studied in the theory of "weights". Essentially a weight $w$ is a positive function for which the measure $w(x) dx$ have the same boudedness properties with respect to some classes of singular integral operators. Look into [D: Theorem 7.4].
The only difference between the condition that you demand and the $A_p$ conditions imposed in weighted theory is that they tend to be "open". I.e. you can have a reverse Hölder inequality for your exponent plus some (potentially small) $\epsilon >0$.
[D]: Duoandikoetxea, Javier, Fourier analysis. Transl. from the Spanish and revised by David Cruz-Uribe, Graduate Studies in Mathematics. 29. Providence, RI: American Mathematical Society (AMS). xviii, 222 p. (2001). ZBL0969.42001.
Comment: Very cool! Thanks for the reference, I'll have a look.
Comment: Okay, so I am looking at Duoandikoetxea's book, and this looks related but maybe is not 100% what I'm looking for. For one thing the underlying setting is $\mathbb{R}^d$ rather than an arbitrary measure space, I guess because the Calderón-Zygmund decomposition is used. Also it's not exactly obvious to me how $w$ being in $A_p$ relates to being in $L_p$.


TypeError in React, passing props

Question: I am getting "TypeError: undefined is not an object (evaluating 'this.props.tracks.map')" in the browser, although app compiles successfully.
I checked with console.log that both SearchResults and TrackList receive props (console.log prints all elements of array within map() method) so I do not understand why the object is undefined.
Code is presented below:
File App.js
import React from 'react';
import SearchResults from '../SearchResults/SearchResults.js'

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      searchResults: [{name: '1'}, {name: '2'}]
    }
  }

  render() {
    return (

            <SearchResults searchResults={this.state.searchResults} />

    )
  }
}

export default App;

File SearchResults.js
import React from 'react';
import TrackList from '../TrackList/TrackList.js'

class SearchResults extends React.Component {
    render() {
        return (

                <TrackList tracks={this.props.searchResults}/>

        )
    }
}

export default SearchResults;

File TrackList.js
import React from 'react';
import Track from '../Track/Track.js'

class TrackList extends React.Component {
    render() {
        return (

                {
                    this.props.tracks.map(track => {
                        return <Track track={track}/>
                    })
                }

        )
    }
}

export default TrackList;

Update
I also added error from the browser:
Comment: It's an issue with the way you've defined `searchResults` . The higher order function `map` is used for an array.
Comment: I tried the code live and couldn't reproduce the error... maybe you need rebuild/hot-reload your dev app?
Comment: Yeah, I've been poring over this and I can't find any overt discrepancies. Can you post a working codesandbox that repros your issue, would make debugging a bit easier.
Comment: I copied+pasted this onto my computer and didn't find any errors
Comment: @DrewReese I uploaded all files to the codesandbox - https://codesandbox.io/embed/old-star-rmwgo?fontsize=14&hidenavigation=1&theme=dark
Comment: I also attached error's screenshot to the post
Answer: Not exactly sure why this is happening, but when console logging this.props.tracks in Tracklist it is the defined, passed array from SearchResults then becomes undefined, thus causing the error you see.
QUICK FIX Use Guard Pattern
class TrackList extends React.Component {
  render() {
    const { tracks } = this.props;
    console.log(tracks); // two logs, first (2)[{...}, {...}], then undefined
    return (

        {
          tracks && tracks.map((track, index) => { // Use a guard here to handle undefined tracks prop
            return <Track key={index} track={track} />
          })
        }

    )
  }
}

In the above snippet you can simply place a guard on the tracks prop to defend against undefined values for the mapping. The more important question though is why this is occurring since the prop is never undefined here in SearchResult:
class SearchResults extends React.Component {
  render() {
    console.log('SearchResults', this.props.searchResults); // defined, only see 1 log entry
    return (

Results

        <TrackList tracks={this.props.searchResults} />

    )
  }
}

FURTHER INVESTIGATION
I looked over the rest of your code and found that App is rendering PlayList, and PlayList also renders a TrackList but this time passes no tracks!
class Playlist extends React.Component {
  render() {
    return (

        <input defaultValue={'New Playlist'} />
        <TrackList /> // tracks becomes undefined here
        <button className="Playlist-save">SAVE TO SPOTIFY</button>

    )
  }
}

SOLUTION Define Props/DefaultProps
At this point I would recommend using the react prop-types package to define your component's props and provide default values in some cases. Your TrackList component becomes:
import React from 'react';
import PropTypes from 'prop-types'; // import proptypes
import Track from '../Track/Track.js'
import './TrackList.css'

const propTypes = {
  tracks: PropTypes.array // If you make this required (i.e. PropTypes.array.isRequired) then you'll get a react warning about missing props
};

const defaultProps = {
  tracks: [], // if tracks props is unspecified this value is used
};

class TrackList extends React.Component {
  render() {
    const { tracks } = this.props;
    console.log(tracks);
    return (

        {
          tracks.map((track, index) => { // no longer need guard
            return <Track key={index} track={track} />
          })
        }

    )
  }
}

TrackList.propTypes = propTypes;

TrackList.defaultProps = defaultProps;

export default TrackList;

Comment: React components define their API, i.e. their props. `TrackList` defines what props need to be passed to it to function, regardless of what parent component is rendering it. If it needs a `tracks` prop to be an array, then anything rendering `TrackList` needs to pass an array to its `tracks` prop, else that prop ends up being `undefined` if it isn't defined a default value.
Comment: Thank you for help! Could you pls briefly explain why we need to pass the same props to TrackList from both SearchResults and PlayList? I used different set of data for both files and tried to use different names for props (i.e. tracks and superTracks) but nothing worked until I assigned the same prop name for both SearchResults and PlayList (prop tracks) to pass to TrackList.

TypeError in React, passing props


What's the difference between a property with a private setter and a property with no setter?

Question: If I want a read-only property, I write it like:
public int MyProperty { get { //Code goes here } }

However, the Microsoft example (and a few other examples I've seen) are written like:
public int MyProperty { get; private set; }

Is there any difference between these two, and should I start writing properties like this?
Comment: Yeah, in the second case, the class it belongs to can set its value.
Comment: [`understanding private setters`](http://stackoverflow.com/questions/3847832/understanding-private-setters)
Answer: As you can see in your second sample, you can leave out the implementation for a property. .NET will then automatically create a local variable for the property and implement simple getting and setting.
public int MyProperty { get; private set; }

is actually equivalent to
private int _myProperty;

public int MyProperty {
    get { return _myProperty; }
    private set { _myProperty = value; }
}

Writing
public int MyProperty { get; }

does not work at all, as automatic properties need to implement a getter and a setter, while
public int MyProperty { get; private set; }

leaves you with a property that may return any int, but can only be changed within the current class.
public int MyProperty { get { ... } }

creates a read-only property.
Question is: what do you need? If you already have a member variable that's used within your class and you only want to return the current value using a property, you're perfectly fine with
public int MyProperty { get { return ...; }}

However, if you want a read-only property, which you need to set within your code (but not from other classes) without explicitly declaring a member variable, you have to go with the private set approach.
Comment: `public int MyProperty { get; }` does not leave you with any kind of property; that's illegal.
Comment: `public int MyProperty { get; }` is legal as of C#6
Comment: It can only be set in the constructor.

https://msdn.microsoft.com/en-AU/library/bb384054.aspx
Comment: @EricLippert You're right. I changed my answer to account for this.
Comment: And what would it return if it can never be set?
Answer: With private setter you can only assign property value inside of instance when property is without setter you can't set its value anywhere.
Answer: If you don't use an explicit member assignment in the property, you'll have to declare a private set at least in order to be able to set a value to this property. Otherwise, you'll get a warning at compile-time saying that your property cannot be assigned.
If you use an explicit member, you'll be able to assign a value to this member directly, without needing to add a private set:
private int member ;

public int MyProperty {
    get { return member; }
}

// ...

member = 2;
int anotherVariable = MyProperty; // anotherVariable == 2

Comment: In your example, the use of a private setter to me doesn't actually make sense at all. If I have a private member I can change, why would I have a private setter then? The only reason would be if setting the property did some more than just change the private member.
Comment: @ThorstenDittmar You're right. Deleted the private set for clarity. Thanks for pointing that out.
Answer: public int MyProperty
{
  get
  {
    // Your own logic, like lazy loading
    return _myProperty ?? (_myProperty = GetMyProperty());
  }
}

A property with only a getter is very useful if you need your own logic behind the access of that property, in particular when you need the property to be lazy loaded.
public int MyProperty { get; private set; }

A property with a private setter is useful if you need the property not te be changed from the outside, but still maintained from within the class.
In both cases, you can have a backing data field for the actual value, but in the former, you'll have to maintain that yourself, and in the latter, it is maintained for you by the generated code.
Answer: There is a difference when you access the object with reflection.
public class Foo
{
    public string Bar { get; private set; }
}

// .....
    internal static void Main()
    {

        Foo foo = new Foo();
        foo.GetType().GetProperty("Bar").SetValue(foo, "private?", null);
        Console.WriteLine(foo.Bar);
    }


How do you prove the follwing $|\sqrt[n]{x}-\sqrt[n]{y}| \le \sqrt[n]{|x-y|}$

Question: how do you prove this inequality?
$|\sqrt[n]{x}-\sqrt[n]{y}| \le \sqrt[n]{|x-y|}$
At first glance I thought the triangle inequality would be useful but it's not form what I see. If I raise everything to the power of n I get the following: Possibility 1 (n uneven) : $|x + ... -y| \le |x-y|$ I guess I would have to prove that ... $\le$ 0 but I don't know how to do that.
Possibility 2 (n even) : $|x + ... +y| \le |x-y|$ Same as above but now I have to prove that ... $\le$ -y.
Am I even on the right track here? Any help would be appreciated. Thanks in advance.
Comment: Is $n$ a natural number?
Answer: Let $x\geq y$.
Thus, we need to probe that
$$\left(\sqrt[n]x-\sqrt[n]y\right)^n\leq x-y$$ or
$$\left(\sqrt[n]x-\sqrt[n]y+\sqrt[n]y\right)^n\geq\left(\sqrt[n]x-\sqrt[n]y\right)^n+\left(\sqrt[n]y\right)^n,$$ which is obvious for natural $n$.
Comment: Thanks. It was the absolute value that irritated me here. Getting rid of it makes the problem a whole lot easier.
Comment: You are welcome!
Answer: From the use of the $\sqrt[n]{\phantom{x}}$ sign, we are clearly* meant to assume that $x \geqslant 0$ and $y \geqslant 0$. If $x \geqslant y$, then $\sqrt[n]{x} \geqslant \sqrt[n]{y}$. If $x \leqslant y$, then $\sqrt[n]{x} \leqslant \sqrt[n]{y}$. By interchanging the roles of $x$ and $y$, if necessary, we can assume that $x \geqslant y$.
We now have to prove that $\sqrt[n]{x} - \sqrt[n]{y} \leqslant \sqrt[n]{x - y}$.
As both sides are non-negative, we needn't (yet!) worry whether $n$ is odd or even, we can raise everything to the power of $n$ as you suggested, and the inequality to be proved is equivalent to $\left(\sqrt[n]{x} - \sqrt[n]{y}\right)^n \leqslant x - y$.
It's easier to see what's going on if we change notation. Write $u = \sqrt[n]{x}$, $v = \sqrt[n]{y}$. We now have to prove that $(u - v)^n \leqslant u^n - v^n$ (where it is known that $u \geqslant v \geqslant 0$).
You might still think that now we have to worry about the parity of $n$. But we don't, and the reason is already shown in Michael Rozenberg's answer; so I'll stop here, just where his answer gets going.

*I was a little hasty there. If $n$ is odd, we could have either $x < 0$ or $y < 0$, or both. But then the stated proposition is false, in general. For example, if $n = 3$, $x = 1$, and $y = -1$, it states that $|1 - (-1)| \leqslant \sqrt[3]{|1 - (-1)|}$, i.e. $2 \leqslant \sqrt[3]{2}$, which is false. So we must indeed assume that $x \geqslant 0$ and $y \geqslant 0$.
Answer: hint
If $x\le y,$ it is true.
Assume $x>y=x\cos(t)$ with $0<t<\frac \pi2$.
After simplifying, we have to prove that
$$\Bigl(1-\cos^{\frac1n}(t)\Bigr)^n\le 1-\cos(t)$$