CORS with 3scale

Question: We're trying to setup a 3scale platform over OpenShift to manage API access between a REST service and a JavaScript web application. Authentication shall be managed with the user-key placed in a HTTP header.
The two applications are reachable on different URLs:
JS web application:     http://siteA.example.com
REST API application:   http://siteB.example.com

so we are using CORS to implement cross-origin resources on the webapp. This is introducing several OPTIONS pre-flight requests sent by the browser without the user-key header, thus receiving an HTTP 403 error from 3scale.
Is there a way to avoid this behaviour?
Answer: If you can't handle it at the application level then you can do a nginx if statement to handle it.
location / {
    if ($request_method = OPTIONS ) {
        add_header Access-Control-Allow-Origin "http://example.com";
        add_header Access-Control-Allow-Methods "GET, OPTIONS";
        add_header Access-Control-Allow-Headers "Authorization";
        add_header Access-Control-Allow-Credentials "true";
        ...
        add_header Content-Length 0;
        add_header Content-Type text/plain;
        return 200;
    }
    ...
}

Via http://blog.rogeriopvl.com/archives/nginx-and-the-http-options-method/
Comment: Good day! Possible to get the content of the blog / you remember or know how to route with condition? - https://stackoverflow.com/questions/77145997/is-it-possible-to-route-api-with-condition-in-3scale I have asked same kind of question
Answer: I had the same issue in 3scale when using the AWS AMI and was able to solve it by adding the app_key and app_id to the allowed headers for an options request.
In testing the request worked in postman but would not work via Chrome. In my case when a browser issued the preflight options check it resulted in rejection because the app_key and app_id header are not allowed by the CORS defaults.
Adding support for those headers can be achieved by adding an entry for them to the end of the 'Access-Control-Allow-Headers' header. I made this configuration a separate file named cors.conf:
#### CORS ####
  if ($request_method = 'OPTIONS') {
    add_header 'Access-Control-Allow-Origin' '*';
    add_header 'Access-Control-Allow-Credentials' 'true';
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
    add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,app_id,app_key';
    add_header 'Access-Control-Max-Age' 1728000;
    add_header 'Content-Type' 'text/plain charset=UTF-8';
    add_header 'Content-Length' 0;
    return 204;
  }
#### CORS END ####

The cors.conf was then included under any "location /" block in nginx.conf:
...
location / {
include /opt/openresty/nginx/conf/cors.conf;
  set $provider_key null;
  set $cached_key null;
...

Once this change was made my browser was able to successfully make requests.
The CORS on Nginx document was used as a baseline and I noted that only the OPTIONS section needed to be modified to get the desired results.
Answer: When the environment variable APICAST_PATH_ROUTING is set to true, and APIcast is exposing multiple Services, if the CORS Policy is not enabled for all the Services, the preflight OPTIONS request will receive a 403 (Forbidden) response.
Set the CORS policy on all the services/apis within your 3scale.
More info from RedHat:
https://issues.jboss.org/browse/THREESCALE-3063
Answer: 3scale gateway now supports out-of-the-box CORS policy definition. More information here: https://access.redhat.com/documentation/en-us/red_hat_3scale_api_management/2.8/html/administering_the_api_gateway/apicast_policies#cors
Comment: This is a borderline [link-only answer](//meta.stackexchange.com/q/8231/371810). You should expand your answer to include as much information here, and use the link only for reference.

CORS with 3scale


incrementar evento depois de um determinado tempo

Question: Estou fazendo uma aplicação que simula um marcador de ponto, e precisaria que ele incremente a próxima marcação somente depois de 5 minutos, fiz alguns testes com setTimeout, mas não cheguei no que precisava.
A aplicação faz as marcações, mas não tem o temporizador de tempo(5 minutos).
js:
    var qtd = document.getElementById("dataTime");

function getTime(){

  var data = new Date();
  var full_time = data.getHours() + ":" + data.getMinutes() + ":" + data.getSeconds();

  var dataCompleta = full_time;

  while (qtd < 4){
   document.getElementById("horaMarcada").insertAdjacentHTML('beforeend', ''+ dataCompleta +' ');
   qtd++;
   return false;
  }
}

html:
<button onclick="getTime()">Marcar</button>

Comment: não seria melhor vc guardar a hora no banco de dados e ir verificando a diferença com o *setTimeout*? assim ficaria mais confiável e mais seguro para sua aplicação.
Comment: a principio pretendo guardar as marcações com localStorage
Comment: Vc quer 3 marcações ou 4?
Comment: 4 marcações, a primeira no ato e as outras 3 somente depois de 5 minutos, se a pessoa clicar antes de 5 minutos vou apresentar uma mensagem dizendo que somente depois de 5 minutos
Comment: obs: e as outras 3, cada uma somente depois de 5 minutos
Answer: É preciso alterar o  para  porque estão sendo criados elementos com o mesmo id, o que já é errado.
Com class você consegue contar a quantidade de elementos em tempo real, dispensando a auto-incrementação com qtd++.
Ao clicar no botão, o atributo onclick muda para um alert, e após 5 minutos, volta ao normal.
Você pode colocar tudo dentro da função na ordem abaixo:

function getTime(){

   document.querySelector("button").setAttribute("onclick","alert('Aguarde 5 minutos!')");

   var data = new Date();
   var full_time = data.getHours() + ":" + data.getMinutes() + ":" + data.getSeconds();
   var dataCompleta = full_time;

   document.getElementById("horaMarcada").insertAdjacentHTML('beforeend', ''+ dataCompleta +' ');
   var qtd = document.getElementsByClassName("dataTime").length;

   if(qtd < 4){
      setTimeout(function(){
         document.querySelector("button").setAttribute("onclick","getTime()");
      }, 300000);
   }else{
      document.querySelector("button").disabled = true;
      console.log("fim");
   }
}
<button onclick="getTime()">Marcar</button>

Comment: Dvd, fiz um teste numa arquivo apartado, mas não esta rolando o temporizador
Comment: ta fazendo o loop, mas não faz a pausa de 5 minutos para a próxima marcação, mudei para 300000
Comment: dvd, estou usando igual, criei um JSFiddle http://jsfiddle.net/josecarlosdw/0ndv7hpp/
Comment: dvd, veja meu resultado https://imgur.com/ZObAdNs
Comment: @josecarlos Agora acho que foi. Abs!
Comment: dvd, exatamente isso, muito obrigado! abs
Comment: @josecarlos não deixe de marcar a resposta como certa. Abs!
Comment: Marcado, meu caro. abs!


Is double Q-learning redundant when using target networks?

Question: Generally speaking, the purpose behind target networks is to reduce the impact of current changes on the model. i.e. if I performed action a and got some reward r, I want to reduce the impact of this specific tuple on the model.
When using double-q learning, I keep a different model for action choosing and reward estimation, also to make the model more robust.
But, and here is my question, generally speaking, both of those methods delays some samples to gain robustness, in slightly different scheme, and as I see it they are solving the same problem. So are they redundant?
Answer: No, double Q-learning is not redundant, since that is not the main motivation for double Q-learning. The abstract of the paper says

In particular, we first show that the recent DQN algorithm, which
  combines Q-learning with a deep neural network, suffers from
  substantial overestimations in some games in the Atari 2600 domain.

And then

We propose a specific adaptation to the DQN algorithm and show that
  the resulting algorithm not only reduces the observed overestimations,
  as hypothesized, but that this also leads to much better performance
  on several games.

So a side-effect of DDQN is to mitigate the "moving target" problem, which the target network also solves. However, that is not the main point. The main point is to reduce over-optimism


What's the mathematical/physical reason this equation is true?

Question: $$-\sum_i \frac{dx_i}{dt} \frac{\partial V(\{x\})}{\partial x_i} = - \frac{dV}{dt}$$
where $x_i$ is the coordinate of a configuration space and $V({x})$ is the potential energy function. I have only started learning multivariable calculus and don't understand why this is true.
Comment: It is the chain rule.
Answer: This expression is nothing more than the chain rule written for multiple variables. Namely, if I have some function $f$ that is a function of many variables, I can express,
\begin{gather*}
\frac{d f}{d y} = \sum_j \frac{\partial f}{\partial x_j} \frac{\partial x_j}{\partial y}
\end{gather*}
Where the sum runs over all of the variables that $f$ depends on. The only difference is the names of the variables and functions and the fact that there is a negative sign multiplied on both sides. Also make sure that you are being careful with total and partial derivatives.
Comment: oh but the book I got this from did multiply the total derivative of x_i with respect to t with the partial derivative of potential energy with respect to x_i. I think having the total derivative of x_i(the velocity) is important because it is required to show the conservation of energy in a system. Is the equation false if the total derivative of x_i with t is used?
Comment: That would mean the $x_j$ are just functions of $t$, which is perfectly possible. I just wanted to point out that care with partial and total derivatives is necessary!
Answer:
What's the mathematical/physical reason this equation is true?...
$$-\sum_i \frac{dx_i}{dt} \frac{\partial V(\{x\})}{\partial x_i} = - \frac{dV}{dt}$$

Consider $V=V(a, b)$ to be a function of just two arguments. The generalization from 2 to $N$ is straightforward.
Now, let each argument $a$ and $b$ be evaluated at a point that depends on time, $x_1(t)$ and $x_2(t)$, respectively.
Physicists, somewhat confusingly, often use the same symbol for two different functions. For example, a physicist might write $V(t)$ to mean the function that results if $V(a, b)$ is evaluated at $V(x_1(t), x_2(t))$. Clearly, the function $V(t)$ can not be the same function as $V(a,b)$. To avoid this potential confusion, I'll write
$$
\tilde V(t) \equiv V(x_1(t), x_2(t))\;.
$$
Now, let $\tilde V(t)$ be evaluated at $t_0+\delta t$, where $\delta t$ is "small." (Meaning we can neglect all but the first order change with respect to $\delta t$.)
$$
\tilde V(t_0 + \delta t) = V(x_1(t+\delta t), x_2(t+\delta t))\tag{A}\;.
$$
The LHS of Eq. (A), to first order in $\delta t$, is:
$$
\tilde V(t_0) + \delta t\left.\frac{d\tilde V}{dt}\right|_{t_0}
$$
The RHS of Eq. (A), to first order in $\delta t$, is:
$$
V(x_1(t_0), x_2(t_0))
+ \delta t\left.\frac{dx_1}{dt}\right|_{t_0}\left.\frac{\partial V}{\partial a}\right|_{(a,b)=(x_1(t_0),x_2(t_0))}
+ \delta t\left.\frac{dx_2}{dt}\right|_{t_0}\left.\frac{\partial V}{\partial b}\right|_{(a,b)=(x_1(t_0),x_2(t_0))}\;.
$$
The first order changes in $\delta t$ are equal on both sides of the equation, so we see:
$$
\left.\frac{d\tilde V}{dt}\right|_{t_0}
=
\left.\frac{dx_1}{dt}\right|_{t_0}\left.\frac{\partial V}{\partial a}\right|_{(a,b)=(x_1(t_0),x_2(t_0))}
+\left.\frac{dx_2}{dt}\right|_{t_0}\left.\frac{\partial V}{\partial b}\right|_{(a,b)=(x_1(t_0),x_2(t_0))}\;.
$$
Or, reverting to a more condensed notation, writing $t$ instead of $t_0$, and using the symbol $V$ in place of $\tilde V$, we have:
$$
\frac{dV}{dt}
=
\frac{dx_1}{dt}\frac{\partial V}{\partial x_1}
+
\frac{dx_2}{dt}\frac{\partial V}{\partial x_2}\;.
$$
Comment: Thank you for the bit about physicists using the same symbol $V$ for two different functions.  I believe this a source of confusion for a great many students.


SQL para comparar horas e minutos uando Timestamp no PostgreSql

Question: Estou tentando comparar 2 campos timestamp, que possuem datas diferentes, ignorando as datas e utilizando apenas a hora/minuto de modo simultâneo, para saber, dentro de um mesmo dia qual deles é maior.
EX: '2000-10-10 10:00:22' > '2000-02-02 11:00:10'
Neste caso seria ignorado as datas sendo comparado apenas '10:00' > '11:00' retornando FALSO.
Tentei usar EXTRACT() mas não encontrei algo do tipo "time"
O SQL seria algo nesse estilo (Se o time existisse):
SELECT * FROM "Tabela" WHERE EXTRACT(TIME FROM "Coluna_1") > EXTRACT(TIME FROM "Coluna_2")

Comment: `SELECT * FROM "Tabela" WHERE "Coluna_1"::time > "Coluna_2"::time` funciona?
Comment: Obrigado pela diga, não conhecia este modo. Queria algo que eliminasse os centésimos, mas esse deve funcionar.
Answer: Pode aplicar um cast da data para time para comparar apenas as horas/minutos, basta usar :: seguido do tipo.
SELECT * FROM "Tabela" WHERE "Coluna_1"::time > "Coluna_2"::time

Exemplo - sql fiddle
Answer: Sua abordagem está correta, exceto pelo uso de time. Uma alternativa é fazer o CAST to campo de TIMESTAMP para TIME, permitindo a comparação somente da hora do campo. A utilização do CAST neste caso, além de funcionar, mantém a compatibilidade com outros SGBDs (que possuam a diretiva TIME, obviamente):
SELECT * FROM TABELA WHERE CAST(Coluna_1 AS TIME) > CAST(Coluna_2 AS TIME)

Exemplo
Comment: Esta alternativa não funcionou, pelo menos no PostgreSQL não. Aparentemente ele não permite um cast da coluna timestamp para um time. Retirando o time ele fornece o epoch do timestamp, incluindo a data.
Comment: Desculpe pelo descuido. Editei a resposta. Obrigado.


Java Drools Object Assignment With a Colon?

Question: I'm learning Java and Drools so that i can edit an existing codebase, I've encountered some syntax i believe is simply assigning a variable/object but i'm uncertain and i'd appreciate some clarity and insight before i incorrectly apply and rely on it.
RULE "Rule1"

    WHEN
        result : Result()
        policy : Policy()

    THEN
        logger.info("Running Rule1");
        retract(result);
END

It's the "xxx : xxx()" bit i'm uncertain about..
i try searching, but i end up with static declaration etc
is it the same as "xxx = new xxx();" or "xxx : xxx();" ?
My previous coding experience is with PHP and C#, thanks.
Comment: This is a basic topic which is explained in the Drools manual you need to study before you try to understand any code. Also, understanding (at least) basic Java is essential *before* you touch anything in the codebase. - And, no, neither a variable binding (`xxx: ...`) nor a pattern (`... Xyz()`) is a "static declaration".
Comment: I appreciate there is a "right way to do it" but i'm in a position where i have to do this work without any knowledge transfer and i'm up against a time limit.  I understand enough to build and run the environment, but there are just a couple of language nuances i need help with as working backwards is not as simple as working forwards.

the static declaration comment was because when i search for this, i get responses talking about the double colon or ternary.

i'm asking for help, not a lecture thanks
Comment: Do you want me to copy-paste the text from the manual?
Comment: At your suggestion, i tried skimming the manual myself to find what you were on about, but i didn't have much luck.
If you would be so kind, i'd be very appreciative.
Answer: A pattern element is the most important Conditional Element. It can potentially match on each fact that is inserted in the working memory.
A pattern contains of zero or more constraints and has an optional pattern binding.
[patternBinding :] pattern type ( [ constraints ] )
In its simplest form, with no constraints, a pattern matches against a fact of the given type. In the following case the type is Person, which means that the pattern will match against all Person objects in the Working Memory:
Person()

For referring to the matched object, use a pattern binding variable such as $p. (The '$' is not mandatory, just a convention.)
$p: Person()

A property can be bound to a variable:
Person( $firstAge : age ) // binding

Just note that "binding" isn't "assigning"; a "binding variable" isn't a "variable" as it is known in C# or PHP.


Bijective and holomorphic function $\Omega=\{z: |\arg(z)|<\pi/3\}$

Question: I have to construct a bijective and holomorphic function from $\Omega=\{z: |\arg(z)|<\frac{\pi}3\}$ to $D(0,1)$.
I think a possible function is $f(z)=\frac{z^{3/2}-1}{z^{3/2}+1}$. I'm right?
My question is: Is it possible to construct a function satisfying the conditions above that also satisfies that $f(1)=0$ and $f(2)=\frac12$? Thank you!
Answer:
I think a possible function is $f(z)=\frac{z^{3/2}-1}{z^{3/2}+1}$. I'm right?

That is correct. $\Omega$ is mapped to the right half-plane and then to the unit disk.

Is it possible to construct a function satisfying the conditions above that also satisfies that $f(1)=0$ and $f(2)=\frac12$?

Your $f$ already satisfies $f(1)=0$, but $f(2)= \frac{2^{3/2}-1}{2^{3/2}+1} \approx 0.478$. Now use that two conformal mappings $f_1,f_2$ from  $\Omega$ to the unit disk with $f_j(1) = 0$ can only differ by a rotation with a factor of absolute value one.
Comment: Applying Schwarz Lemma, I know that $f:D\to D$ bijective and holomorphic with $f(0)=0$ is necessarily $f(z)=cz$ with $|c|=1$, but I don't know how to extend this to $f:\Omega \to D$ with $f(1)=0$
Comment: Maybe I can reason in the following way: Let $f$, $g$ two confromal mappings from $\Omega$ to $D$. The function $F=f\circ g^{-1}$ is in the conditions of the Schwarz Lemma. So I have $f(g^{-1}(\omega))=c\omega$ for $z\in D$ with $|c|=1$. So I conclude that $f(z)=c g(z)$ for $z\in \Omega$
Comment: @JN_2605: If $f_1, f_2: \Omega \to \Bbb D$ are two such mappings then consider $f_2 \circ f_1^{-1}: \Bbb D \to \Bbb D$.
Comment: Thank you very much, I was just writing that!


What exactly is an $R$-module?

Question: From Wikipedia:
"If $R$ is commutative, then left $R$-modules are the same as right $R$-modules and are simply called $R$-modules."
The definition of left $R$-module: $M$ is a left $R$-module if $M$ is an abelian group and $R$ a ring acting on $M$ such that
(i) $r(m_1 + m_2) = rm_1 + rm_2$
(ii) $(r_1 + r_2 ) m = r_1 m + r_2 m$
(iii) $1m = m$
(iv) $r_1 (r_2m) = (r_1 r_2) m$
I don't understand what commutativity of $R$ has to do with the module being left and right. If $R$ is commutative it means that $r_1 r_2 = r_2 r_1$. Now how does it follow from that that $rm = mr$? $M$ is not a subset of $R$, it could be anything so how does commutativity of $R$ make elements of $M$ and $R$ commute, too?
Comment: If you assume a left R module is also a right R module then you will need commutativity of R in order for the last property to hold
Comment: @AlexBecker: That's somewhat non-trivial to make precise, as the two objects live in different categories. It would be easier to say that the two categories are isomorphic.
Comment: I believe that any left $R$-module over a commutative ring is isomorphic to a right $R$-module, and vise-versa.
Answer: The definition of right $R$ module is similar except that elements of $R$ are written on the right, and the axioms become
(i) $(m_1 + m_2)r = m_1r + m_2r$
(ii) $m(r_1 + r_2 )  = mr_1  + mr_2 $
(iii) $m1 = m$
(iv) $(mr_1) r_2 = m(r_1 r_2)$
If $R$ is a commutative ring and $M$ is a left $R$ module, then we can define a right $R$ module $M'$ that is the same abelian group as $M$ and with essentially the same action, but with the elements of $R$ acting on the right: namely, if $rm$ is the result of $r\in R$ acting on $m\in M$, then we define the action of $R$ on $M'$ by $mr = rm$.  (That is, it is not a question of whether it is "true" that $mr=rm$; rather, we define it to be so.)  It can then be verified that $M'$ satisfies the axioms, and there is nothing lost going from $M$ to $M'$ or vice versa.  Commutativity is needed for axiom (iv).  That is what is meant on Wikipedia.
However, one should be careful.  If $M$ is a left $R$ module, then $M$, as an abelian group, might be given a right $R$ module action that is not obtained from the left action in this way, even if $R$ is commutative. Therefore in some contexts, where more than one action is being considered, it can be useful to designate left and right modules even of commutative rings.
Answer: Given a ring $R$, the opposite $R^{op}$ is the ring with the same underlying group, but with multiplication defined by $(a,b)\mapsto ba$.
Now a right $R$-module can be defined as a left $R^{op}$-module.
Clearly $R$ is commutative if and only if $R=R^{op}$; in this case left and right $R$-modules are 'the same'.
[Edit: my answer adds nothing new to Jonas' answer, but I think the term opposite ring deserves to be mentioned in this thread.]
Answer: What Wikipedia wants to say:
If $R$ is a commutative ring and $M$ a right $R$-module, the law $r\cdot m:=mr$ defines a left $R$-module structure on $M$.
So all assertions about right $R$-modules can be turned very easily into assertions about left $R$-modules by writing multiplication on the left. Hence we lose nothing if we study only left $R$-modules.
Make sure you understand that this is generally not the case if $R$ is not commutative.
Answer: For a right module, the multiplication is usually written with the scalar on the right, and axiom (iv) becomes $(mr_1)r_2=m(r_1r_2)$. If you were to write the product with the scalar on the left, axiom (iv) would become quite inconvenient: $r_1(r_2m)=(r_2r_1)m$. But of course, if $R$ is commutative, this doesn't matter.

What exactly is an $R$-module?


Liszt Transcendental Étude No.1 (Prelude): tension-ful chord progression in bar 9, 10, 11

Question: I am trying to digest the Liszt Transcendental Étude No.1 (Prelude) chord progression in bar 9, 10, 11 with the full of tensions.
Three related sub-questions.

In both the Zoltán Gárdonyi (1906–1986) and István Szelényi (1904–1972) imslp version recommended by Aron

and the other older imslp version IMSLP55010-PMLP02567 "Liszt_Musikalische_Werke_2_Band_2_35_Transcendental Étude",

the A4 marked in the RED color in the bar 9 --- should the A4-flat match with the top voice A5-flat as an octave? Are these typos or ...?

From Bar 9, 10, to Bar 11, we see that there are a series of nine chord progressions. How should I understand Liszt's purposes and arrangement here?

I see that

the octave along the top and bottom voices of the right-hand go as:

(previous E) to E -> F -> A-flat -> D-flat -> F-sharp -> B -> E -> A -> F

the octave along the top and bottom voices of the left-hand go as:

(previous C) to B-flat -> A-flat -> G-flat -> F -> E -> D-sharp -> D -> C-sharp -> D

How about the middle voices of the series of nine chord progressions?

Does Liszt arrange that with clear motivations or logics in mind?
Answer: 1. Missing flat symbol?
The flat is already present in the previous chord. Since accidentals persist for the remainder of the measure, there's no need to repeat the symbol except as a courtesy accidental.
2. Chord progression
Note: Lots of enharmonic spellings.
As shown in the image below:

The area in the red box is a cadence in Db major (CTo - I - V - I).
The note heads in cyan comprise a sequence of ascending fourths.
The bass line comprises a descending Db major scale (red note heads) with some chromatic interpolations (blue note heads).

The overall progression is a cadence in Db major (red box) overlapping with a circle of fifths progression (Ab7/Gb through Dm).
3. Inner voices

In the right hand, all of the chords within the circle of fifths progression are in root position.
In the left hand, the notes are kept in close position. This means that while the upper-inner voice can proceed in thirds/sixths with the top/bottom voices, the lower-inner voice must alternate between thirds and fourths.

Liszt Transcendental Étude No.1 (Prelude): tension-ful chord progression in bar 9, 10, 11


AUX Output is audible on main mix

Question: My band uses a very simple in-ear-monitoring set-up in the practice room where we are taking advantage of the 4 AUX channels on the huge audio mixer there.
We do use cheap headphone amps which cannot boost the incoming signal of the aux outputs enough, so we have to crank the aux output knobs all the way to max.
But then it seems that the click is audible on the main mix as well, though it is only to be audible on the in-ears.
How is this 'signal spillover' possible? Might it be how the audio mixers are constructed? We are wondering if it could happen on better mixers at concert venues as well, then we would have to change our set-up, which would cost time and money.
Comment: When you're hearing the click in the mains, is it fairly quiet or is it about as loud as the click in the auxes? Also, cheap headphone amps are good enough for monitoring and not that hard to come by. You really shouldn't crank levels inside a mixer if you can avoid it, and you shouldn't plug headphones straight into aux outputs. If the auxes are balanced then you are really messing things up.
Comment: Are you saying that the click on the main mix comes and goes when you move the aux output knobs? Presumably you can check that out with no input from your instruments and mikes all disconnected. A mixer shouldn't have any *unintended* spill between channels - you need to systematically check out *why* the click is getting to the wrong place. Connect just one thing at a time and play with the faders, till you find it.
Comment: I will check it again on thursday when we practice the next time but as I recall I tried that already. And it seems to only occur when the AUXs are maxed out.
Comment: The click is very quiet but audible during quiet passages. Also we checked already for the headphones being accidentally recorded by a mic. Not the case.
Answer: With all respect to Alephzero's comment, pretty much all mixers have what you might call "spillover" between adjacent channels and among different busses. It's critical to not have any coupling between inputs and outputs (channels and busses) because that causes in the box feedback.
You can't make electronics with zero coupling, and when you crank a channel or bus level you are creating a huge disparity in power and the resulting EM fields. Pretty much no circuit in audio is designed to work at the outer limits of its settings.
Somehow I didn't notice that you are already using headphone amps. I'm a little worried about how loud you might be making those amps if they can't get the headphone level of in-ears high enough on their own. Ideally the aux master level controls should be set of around unity gain.
Your next step should be to check the kind of output and nominal output level for the aux sends and then the kind of input and nominal input level for the headphone amps. The best combination would be that they are both TRS balanced line level. The auxes are almost certainly mono TRS balanced, so if the headphone amps are stereo TRS and you're using a TRS cable to connect the two, that's a major configuration error that is probably causing your problem.
Comment: Thank you for your effort! That it is impossible to build electronics with zero coupling is a very interesting and valuable piece of information for me. You might be right with checking back on the initial connection between AUX and mic-amp. I will do that on thursday and will let you guys know how it turned out. I will edit the question to include additional information I will gain through this then. Thank you!

AUX Output is audible on main mix


Use RD Gateway to direct users to certain term server?

Question: Is it possible to configure RD Gateway to, depending on a users group, point them to one term server or another? Just trying to make it work on the domain right now.
Answer: RD gateway is designed to allow you to go to an internal machine from an outside network (ie..Internet for example).  For example, connect to your desktop at the office from home wihtout exposing your desktop to the internet.
If you wanted to do this, you would simply specify which server you wanted them to connect to in the RDP client as well as specifiying the gateway.  Maybe point them to a CNAME that you can change in DNS so you can move them around if you want to.  something like  rdp1.domain.com CNAME to TS1.domain.com.  This way if you ever want to move them around later, you could.  If you don't have a ton of users, you could add a CNAME entry for each user and let DNS move them around for you when they login.  Keep in mind, you will probably have some certificate issues to overcome if the machine names don't match.  Not sure if RDP supports using subject alternate names in certs.
There is probably a much better way to do this as the above solution would be complicated to admin. A clustering solution might be easier, but probably not cheaper.
I can clarify more if needed, just ask away.
Comment: We currently have our 2003 terminal servers doing basic load balancing, they are not enterprise edition so the problem we run into is they can have 1 session but if they go to make another one theres still a chance they get on a different server. So for some of our users I need to make them user one server or the other. From what I initially saw of RD Gateway I thought it could do this but I was mistaken. Still looking for other possibilities.
Comment: RD Gateway will let you specify the internal machine you want to connect to and it will always connect to that.  But if you are trying to give yourself a way to bounce those users to the second server if the first fails, then you'd need a more complicated solution.  Some firewalls use a MOD of the IP to figure out which load balanced server to send the user to.  (Sonicwall does it this way).  So the user always connects to the same machine in the load balanced pool unless their IP changes or the server they were using goes offline.


looking for views gallery module compatible with lightbox module

Question: I would like to achieve a behaviour like this:
At the bottom of the screen there are thumbnails. Above them is a big image styled for 800x600 which changes after clicking a thumbnail. When the user clicks on the big image, then an overlay with lightbox opens and the image is not 800x600 but full size, scaled to screen. There are working Next and Previous buttons on the lightbox (not necessarily linked to the underlying thumbnails gallery).
How to achieve it? I am interested in a solution working either out of the box or having  clear tweak instructions. Any gallery module and any lightbox will do, as long as they are compatible and have next/previous buttons working.
So far I tested Views Galleriffic and Lightbox2 and Colorbox, using patch from here and I managed to open the big image in original size using lightbox2 and colorbox. However, Previous and Next buttons are not working in either case.
Answer: Have you tried Views Slideshow with Views Slideshow Xtra?
Here are some more details about these modules (quotes included are from their project pages):

Views Slideshow:

... can be used to create a slideshow of any content (not just images) that can appear in a View. Powered by jQuery, it is heavily customizable: you may choose slideshow settings for each View you create.

Views Slideshow Xtra:

... is an enhancement module for Views Slideshow, providing the ability to create overlays for a Views Slideshow. HTML elements are placed in  overlays, with overlay visibility controlled by toggling the CSS display property, so that overlays are displayed with their corresponding slide. Animation of the overlay displays is also supported.
Comment: Thanks, I used just views_slideshow. Because I have also Lightbox2 installed, it shows as a field formatter for the big image, so I don't have to use the xtra. And lightbox prev/next are just working here...


Qt in VS2010 - Can't use the Objects create by the Designer

Question: I'm using Qt with Visual Studio 2010 but I have a doubt.
Whenever I use the Qt Designer to create a GUI, when compiling in Visual I have no access to the Objects auto created by the designer, like the buttons, listboxes etc...
What should I do in order to use them ?
My point is, I can't create events, slots, signals, etc, cause it seems this objects do not exist in my main.cpp and my mainclass.cpp.
Thanks guys !
I'm using VS 2010 with QT 4.8.0.
#include <QListWidget.h>
#include <stdio.h>
#include <string.h>
#include "ui_ratagbc.h"

class dasm: QObject
{
    Q_OBJECT
public:
    dasm(void);
    ~dasm(void);
    int DAsm(FILE *,int);
private:
    Ui::RataGBCClass *ui;
};

Answer: To access the GUI in your code, include the result from running the uic tool.  Create a class, and have as a member variable an instance of the class that uic generated, it is in the Ui namespace.
#include "ui_MyGUI.h" //automatically generated by uic tool

class MyClass : public QDialog //or whatever type of GUI you made
    {
    Q_OBJECT //this macro flags your class for the moc tool
    //other variables and functions
    Ui::MyGUI ui;
    };

You get access through this 'ui' object:
ui.label->setText("New label text set in source file");
In your constructor, call ui.setupUi(this)
Note the Q_OBJECT macro - if you're defining signals and slots or stuff like that, you need the Q_OBJECT there to flag the class for the moc tool to recognize it.
Edit to answer followup question in comments:
It sounds like what you want to do is use the signal/slot system.  In your class definition, include the following:
class MyClass
{
//other stuff
public slots:
void customSlot(){/* your actions here */}
//other stuff
};

Then someplace else, commonly in the constructor or an initialization function, inclue this line:
connect(ui.button, SIGNAL(clicked()), this, SLOT(customSlot()));

The moc tool handles the bulk of the setup.  Your custom slot will then be triggered when the button is clicked.
Comment: Thanks man, it really worked. I have one last doubt. For example, if I want to create an event, for example, when clicking a button, what should I do ? I mean, I know how to do that, I just want to know where should I place the codes, like the slots and signals. Thanks !
Comment: Edited above to answer the follow-up
Comment: You can also use automatic slot connections for that. I use this method almost always for uis I create in the designer. See here: http://qtway.blogspot.com/2010/08/automatic-connections-using-qt-signals.html
Comment: Hey guys, thanks for the tips ! But now I'm getting the following error when I try to use the slots keyword: moc_eventos.obj : error LNK2019: unresolved external symbol "public: void __thiscall eventos::teste(void)" (?teste@eventos@@QAEXXZ) referenced in function "private: static void __cdecl eventos::qt_static_metacall(class QObject *,enum QMetaObject::Call,int,void * *)" (?qt_static_metacall@eventos@@CAXPAVQObject@@W4Call@QMetaObject@@HPAPAX@Z)
Comment: It sounds like you didn't include the moc_Filename.cpp file (the output of the `moc` tool) in your project.
Comment: No, I can see the file there. When doing the nmake process, I got a few errors. Does that have something to do with it ? How should I proceed now ? Thanks !
Comment: Can you post the relevant parts of your code (in an edit or something)?
Comment: I have edit my code. I'm getting this error: 1>dasm.obj : error LNK2019: unresolved external symbol "public: int __thiscall dasm::DAsm(struct _iobuf *,int)" (?DAsm@dasm@@QAEHPAU_iobuf@@H@Z) referenced in function "public: __thiscall dasm::dasm(void)" (??0dasm@@QAE@XZ)
1>C:\Users\Magaly\Documents\Visual Studio 2010\Projects\RataGBC\\RataGBC.exe : fatal error LNK1120: 1 unresolved externals
Comment: In your .cpp file, are you providing the body of the `int DAsm(FILE*,int)` function?  Can you post it?


Jam tracks / low volume computer

Question: I am looking to bring more volume to the jam tracks that I am running off my computer. I have 2 amps, I thought maybe of using one of them as a speaker or are there other ways to make this happen?
Comment: What kind of amps are they?
Comment: A Fender Mustang GT is the one I thought about using. The other is an older Crate amp.
Answer: Out of the headphone port on computer into input on amp. Start with all volumes down, gradually increase. Probably minijack to standard 1/4" jack.

Jam tracks / low volume computer


Can a POE switch power devices if a non-POE hub or switch sits between the source and device?

Question: I want to buy a single POE source and distribute it with cheap network hubs that do not have POE. Will this work?
Answer: No. POE will only be supplied to devices that are directly connected to the POE switch, and only by request.
The standard by which this works is described here: http://en.wikipedia.org/wiki/Power_over_Ethernet#Standard_implementation
Comment: Patch panels are different though?
Answer: That won't work -- PoE doesn't carry through additional switches/hubs -- the last switch before the device has to be the PoE switch.  You can safely plug non-PoE devices (such as other switches) into PoE ports, though.
Answer: No. First, I hope there are no more hubs out there and switches must be POE-capable.
Comment: No, plugging a non-POE hub into a POE hub will not destroy it. The POE protocol will only supply power to the devices that request it.
Comment: FYI, we do this all the time - we have several switches in our office after the POE switch. No damage is done to them, and no POE gets through them.
Comment: Just to confirm, it is likely plugging a POE hub into a non-POE hub might destroy it?
Comment: I am not sure about that, but anyway, a non-POE *switch* is not capable of distributing power, so there is no reason in risking damage to your equipment.


How to find current screen/route in nested Tab.Navigator

Question: I have a custom TabBar for a Tab.Navigator that needs to have a different action when one of the tabs is selected based on what the current route is in the Stack Navigator component for that tab.
How can I inspect the currently displayed Stack.Screen inside of this custom TabBar? Trying to use the getRoute hook only shows me the parent screen that hosts that Tab.Navigator.
<Tab.Navigator tabBar={(props) => <BottomTabBar {...props} />}>
      <Tab.Screen
        name="Home"
        component={HomeStack}
        initialParams={{showSuccess: route.params?.showSuccess}}
      />
      <Tab.Screen name="Alternate" component={AlternateScreen} />
    </Tab.Navigator>

I can't pass the value in using tabBarOptions as I don't know what the selected route would be when the tab bar is created.
Comment: I ended up keeping track of the current screen outside the scope of the navigator, but will leave this open in case someone has a better solution.
Comment: That seems like a good solution to me. You can add it as an answer.
Answer: I ended up keeping track of the current screen outside the scope of the navigator as the built in Tab Navigator did not keep a reference to nested screens in a Stack Navigator like I was hoping it would.
Only needing to determine a difference between two screens, my crude hack was to have a current screen reference in a context hook and update that value in a useEffect hook when the relevant screen was mounted.
In whatever your provider is, have a currentScreen const like this:
const currentScreen = useRef('Closet');

Then, in your screens, destructure that value from the provider in the useContext hook:
const { currentScreen } = useContext(MyContext);

Then, in the same screen update that currentScreen value in a useEffect hook:
useEffect(() => {
    currentScreen.current = 'NewScreen';
}, []);

Comment: Can you add some of the relevant code to make the answer more concrete?
Comment: Code added to the answer above
Answer: just figured this out for ReactNavigation v6+
i use:
const Tab = createMaterialTopTabNavigator();

and then:
<Tab.Navigator
   initialRouteName={'Tab-All'}
   screenOptions={screenOptions}
   screenListeners={{state: (e) => { currentTabIndex.current = e.data.state.index }}}
   initialLayout={{width, height}}
>
... // your screens go here
</Tab.Navigator>

CurrentTabIndex is just variable created by useRef
So as you might figure Tab.Navigator inherits some Navigator properties.


Problema ao puxar lista do servidor no Android

Question: Opa galera, estou puxando uma lista do servidor e populando um RecyclerView com essa lista. Porém quando a lista estiver vazia, quero que apareça uma mensagem do tipo: "Ainda não existem itens cadastrados para esse produto". Mas não um Toast, e sim uma mensagem fixa num TextView. Alguém pode me ajudar?
Valeu
public class ProductAdminActivity extends AppCompatActivity {

public static final String APP_NAME = "PanApp";
public static final String URL = "https://panapp-backend.appspot.com/_ah/api";
private RecyclerView rvProductAdmin;
private Button btnNewProduct;
private Long bakeryId;
private Bundle params;
private TextView txtAnswer;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //getLayoutInflater().inflate(R.layout.activity_product_admin, frameLayout);
    setContentView(R.layout.activity_product_admin);
    setTitle("Meus Produtos");

    Intent it = getIntent();
    params = it.getExtras();
    if (params != null) {
        bakeryId = params.getLong("bakeryId");
    }

    txtAnswer = (TextView) findViewById(R.id.textAnswer);
    rvProductAdmin = (RecyclerView) findViewById(R.id.product_list_admin);
    btnNewProduct = (Button) findViewById(R.id.btn_new_product);
    btnNewProduct.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            params.putLong("bakeryId", bakeryId);
            Intent intentFormProduct = new Intent(ProductAdminActivity.this, FormProductActivity.class);
            intentFormProduct.putExtras(params);
            startActivity(intentFormProduct);
        }
    });
    new ProductListAsyncTask(this).execute();
}

private class ProductListAsyncTask extends AsyncTask<Void, Void, CollectionResponseProduct> {
    ProductAdminActivity context;
    private ProgressDialog pd;

    public ProductListAsyncTask(ProductAdminActivity context) {
        this.context = context;
    }

    protected void onPreExecute(){
        super.onPreExecute();
        pd = new ProgressDialog(context);
        pd.setMessage("Listando Produtos...");
        pd.show();
    }

    protected CollectionResponseProduct doInBackground(Void... unused) {
        CollectionResponseProduct collectionResponseProduct = null;
        try {
            ProductApi.Builder builder = new ProductApi.Builder(AndroidHttp.newCompatibleTransport(),
                    new AndroidJsonFactory(), null).setRootUrl(URL);
            builder.setApplicationName(APP_NAME);
            ProductApi service =  builder.build();
            collectionResponseProduct = service.list().execute();
        } catch (Exception e) {
            Log.d("Erro", e.getMessage(), e);
        }
        return collectionResponseProduct;
    }

    @TargetApi(Build.VERSION_CODES.KITKAT)
    protected void onPostExecute(CollectionResponseProduct collectionResponseProduct) {
        pd.dismiss();
        if(collectionResponseProduct.size() > 0){
            List<Product> list = new ArrayList<>();
            List<Product> _list = collectionResponseProduct.getItems();
            for (Product productAux : _list) {
                Product product = new Product();
                product.setProductName(productAux.getProductName());
                product.setProductPrice(productAux.getProductPrice());
                product.setType(productAux.getType());
                product.setBakeryId(productAux.getBakeryId());
                product.setProductImage(productAux.getProductImage());
                if(Objects.equals(bakeryId, product.getBakeryId())){
                    list.add(product);
                }
            }
            rvProductAdmin.setLayoutManager(new LinearLayoutManager(ProductAdminActivity.this));
            rvProductAdmin.setAdapter(new ProductAdapter(list));
        } else {
            txtAnswer.setText("Não existem produtos cadastrados!");
        }
    }
}

}
Adapter:
public class ProductAdapter extends RecyclerView.Adapter<ProductViewHolder> {

private final List<Product> products;

public ProductAdapter(List<Product> products) {
    this.products = products;
}

@Override
public ProductViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
    final LayoutInflater layoutInflater = LayoutInflater.from(viewGroup.getContext());
    final View v = layoutInflater.inflate(R.layout.card_product, viewGroup, false);
    //final View v = layoutInflater.inflate(R.layout.item_product, viewGroup, false);
    return new ProductViewHolder(v);
}

@Override
public void onBindViewHolder(ProductViewHolder productViewHolder, int i) {
    productViewHolder.tvProductName.setText(products.get(i).getProductName());
    productViewHolder.tvPrice.setText(products.get(i).getProductPrice().toString());
    productViewHolder.tvCategory.setText(products.get(i).getType());
    //productViewHolder.tvItensSale.setText(products.get(i).getItensSale());

    String strBase64 = products.get(i).getProductImage();
    byte[] imgBytes = Base64.decode(strBase64, Base64.DEFAULT);
    Bitmap bitmap = BitmapFactory.decodeByteArray(imgBytes, 0, imgBytes.length);

    productViewHolder.ivProduct.setImageBitmap(bitmap);
}

@Override
public int getItemCount() {
    return products.size();
}
}

Exception:
FATAL EXCEPTION: main
                                                                  Process: com.gregmachado.panapp, PID: 8730
                                                                  java.lang.NullPointerException: Attempt to invoke interface method 'java.util.Iterator java.util.List.iterator()' on a null object reference
                                                                      at com.gregmachado.panapp.activity.ProductAdminActivity$ProductListAsyncTask.onPostExecute(ProductAdminActivity.java:106)
                                                                      at com.gregmachado.panapp.activity.ProductAdminActivity$ProductListAsyncTask.onPostExecute(ProductAdminActivity.java:70)
                                                                      at android.os.AsyncTask.finish(AsyncTask.java:651)
                                                                      at android.os.AsyncTask.-wrap1(AsyncTask.java)
                                                                      at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
                                                                      at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                      at android.os.Looper.loop(Looper.java:148)
                                                                      at android.app.ActivityThread.main(ActivityThread.java:5443)
                                                                      at java.lang.reflect.Method.invoke(Native Method)
                                                                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
                                                                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)

Comment: Se você colocar seu código aqui, eu te ajudarei!
Comment: Coloquei o código, aquele Toast ali não tá funcionando, não sei se tem a ver com o ColletionResponse, primeira vez que trabalho com esse tipo de lista.
Answer: Você vai fazer o seguinte, na sua activity_product_admin.xml crie um TextView
<TextView
        android:id="@+id/textResposta"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Resposta"
        android:textStyle="bold"
        android:textColor="#ff00ff"
       />

Na sua classe ProductAdminActivity você vai instanciar seu TextView, primeiro declarando uma variável do tipo TextView e depois fazer a ligação com o .xml.
private TextView textReposta;

Dentro do seu onCreate você faz desta forma:
textResposta= (TextView) findViewById(R.id.textResposta);

Aí resta somente substitui seu Toast por o seguinte código:
textResposta.setText("Não existem produtos cadastrados!");

Só isso! Abraços! Boa Sorte!
Comment: ai esta. Também achei que era só isso, mas dispara um Exception. Editei lá e coloquei.
Comment: @GrégoriMachado ajuda ai irmão. Qndo você comentar, já atualiza seu código ou coloque ai senão fica difícil saber o que você está errando.
Comment: respondi e fui atualizar o código.
Comment: @GrégoriMachado tá atualizado não.
Comment: Ué, coloquei o exception no fim do código.
java.lang.NullPointerException: Attempt to invoke interface method 'java.util.Iterator java.util.List.iterator()' on a null object reference
Comment: De qualquer forma. Pensei aqui e fiz várias tentativas. Consegui resolver. Vou postar a solução.
Comment: @GrégoriMachado brother, é pra atualizar seu código com as alterações que eu inseri.
Comment: Atualizei também agora
Answer: Solução:
protected CollectionResponseProduct doInBackground(Void... unused) {
        CollectionResponseProduct collectionResponseProduct = null;
        ProductApi.Builder builder = new ProductApi.Builder(AndroidHttp.newCompatibleTransport(),
                new AndroidJsonFactory(), null).setRootUrl(URL);
        builder.setApplicationName(APP_NAME);
        ProductApi service =  builder.build();
        try {
            collectionResponseProduct = service.list().execute();
        } catch (Exception e) {
            Log.d("Erro", e.getMessage(), e);
        }
        return collectionResponseProduct;
    }

    @TargetApi(Build.VERSION_CODES.KITKAT)
    protected void onPostExecute(CollectionResponseProduct collectionResponseProduct) {
        pd.dismiss();
        List<Product> list = new ArrayList<>();
        List<Product> _list = collectionResponseProduct.getItems(); // fiz o get pro List antes
        if(_list == null){ // e fiz o teste aqui no List ao invés do Collection Response
            txtAnswer.setText("Não existem produtos cadastrados!");
        } else {
            for (Product productAux : _list) {
                Product product = new Product();
                product.setProductName(productAux.getProductName());
                product.setProductPrice(productAux.getProductPrice());
                product.setType(productAux.getType());
                product.setBakeryId(productAux.getBakeryId());
                product.setProductImage(productAux.getProductImage());
                if(Objects.equals(bakeryId, product.getBakeryId())){
                    list.add(product);
                }
            }
            rvProductAdmin.setLayoutManager(new LinearLayoutManager(ProductAdminActivity.this));
            rvProductAdmin.setAdapter(new ProductAdapter(list));
        }
    }

Comment: Você sabe que não ganha nenhum mérito respondendo sua própria pergunta né?! É muito melhor você dar os créditos para quem te ajuda, porque você acaba ganhando também com isso. Abraços
Comment: cara não me leva a mal. Eu não to nem ai pros créditos. Ao contrário de você. Desde o primeiro comentário você respondeu com o ar de superioridade. Tudo que tu disse pra eu fazer, eu já tinha feito.
Se eu soubesse tudo de programação não estaria pedindo ajuda. Mas creio que não exista alguém que saiba tudo de programação né.

E se o problema é crédito, eu marco a tua resposta como solução.
Comment: De boa! Cada um tem seu pensamento e eu respeito o seu! Abraços


Como imprimir um valor double com zero a esquerda em java?

Question: Gostaria de imprimir um valor de um Array do tipo double em Java, exemplo:

8,00  <- gostaria que a saída fosse 08,00.

Como posso fazer isso?
public class Main
{
    public static void main(String[] args) {

        double[] exemplo = {24.00, 8.00, 16.00, 14.00, 10.00};

        for (int l = 0; l < 5; l++){

            System.out.printf("%.2f \t| \n", exemplo[l]);
        }

    }
}

Comment: Isto responde à sua pergunta? [Preencher string com zeros a esquerda](https://pt.stackoverflow.com/questions/38652/preencher-string-com-zeros-a-esquerda)
Answer: Uma maneira de resolver o problema é utilizando a classe NumberFormat.
NumberFormat é a classe base abstrata para todos os formatos de número.
Esta classe fornece uma maneira padrão para formatar e fazer o parse de números.
Esta classe também fornece métodos para determinar quais localidades têm certos padrões de formatação de números e quais os nomes dessas localidades.
Desta forma como deseja formatar um número decimal, devemos utilizar a classe concreta DecimalFormat que é uma subclasse de NumberFormat.
Ao analisar a documentação da classe DecimalFormat vemos que existe um padrão de caracteres especiais que devemos "montar" para gerar a formatação do número de maneira desejada. Estes caracteres especiais devem ser passados no construtor da classe DecimalFormat.

Símbolo
Tipo
Significado

0
número
Dígito

#
número
Dígito, omite o zero

.
número
Separador decimal

*Estou representando apenas os valores que usei na resposta, para mais opções veja o javadoc da classe DecimalFormat.
Segue um exemplo:
 double[] exemplo = {24.00, 8.00, 16.00, 14.00, 10.00};
 NumberFormat nf = new DecimalFormat("00.00");
 for (int l = 0; l < 5; l++){
     System.out.println(nf.format(exemplo[l]));
 }

Assim deve ter o resultado esperado.
Caso queira também é possível "formatar" o separador decimal (trocar ponto por vírgula, por exemplo), para isto será necessário utilizar a classe DecimalFormatSymbols
Esta classe representa o conjunto de símbolos (como o separador decimal, o separador de agrupamento e assim por diante) necessários na classe DecimalFormat para formatar números.
Um caso de uso interessante seria para personalizar uma formatação.
Segue um exemplo:
 DecimalFormatSymbols dfs = new DecimalFormatSymbols(Locale.getDefault());
 dfs.setDecimalSeparator(',');

 double[] exemplo = {24.00, 8.00, 16.00, 14.00, 10.00};
 NumberFormat  nf = new DecimalFormat("00.00", dfs);
 for (int l = 0; l < 5; l++){
     System.out.println(nf.format(exemplo[l]));
 }

No exemplo acima seria mais simples usar um locale que já possui a vírgula como separador decimal.
DecimalFormatSymbols dfs = new DecimalFormatSymbols(new Locale("pt", "BR"));

Desta forma você não fica dependendo do locale default (que pode inclusive ser mudado por qualquer aplicação rodando na mesma JVM (visto que este é um recurso compartilhado), ou seja, é algo que vc não controla). Até porque, se o locale default for algum outro, ele pode ter outras configurações diferentes, como o separador de milhares (tudo bem que nesse caso não está sendo usado, mas é melhor já usar o locale correto do que usar o default e sair mudando tudo)
Uma lista de locales que a linguagem Java possui suporte pode ser vista aqui.
Também é possível fazer uma formatação de valores monetários utilizando a moeda, segue um exemplo:
NumberFormat nf = NumberFormat.getCurrencyInstance(new Locale("pt", "BR"));
nf.setMinimumIntegerDigits(2);
System.out.println(nf.format(24.00));
//R$ 24,00

Desta forme ele já vai formatar como moeda ( que já inclui o "R$"). Mudando os locales vai mudar também a apresentação.
Comment: O mais simples é usar um *locale* que já possui a vírgula como separador decimal: `new DecimalFormatSymbols(new Locale("pt", "BR"))` - assim você não fica dependendo do *locale default* (que pode inclusive ser mudado por qualquer aplicação rodando na mesma JVM, ou seja, é algo que vc não controla). Até porque, se o *locale default* for algum outro, ele pode ter outras configurações diferentes, como o separador de milhares (tudo bem que nesse caso não está sendo usado, mas é melhor já usar o *locale* correto do que usar o *default* e sair mudando tudo)
Comment: Outra opção é criar o formatador com o locale correto (fica "feio" mas enfim): `NumberFormat nf = NumberFormat.getNumberInstance(new Locale("pt", "BR")); ((DecimalFormat) nf).applyPattern("00.00");` - sem isso, cai no mesmo problema: ele vai usar o separador decimal do *locale default*, que nem sempre pode ser o correto (faça `Locale.setDefault(Locale.US);` no início do programa e veja que agora ele usa o ponto e não a vírgula). Por fim, se for para mostrar o "R$", pode usar `nf = NumberFormat.getCurrencyInstance(new Locale("pt", "BR")); nf.setMinimumIntegerDigits(2);` que já inclui o "R$"
Comment: Sem problemas, pode adicionar :-)
Comment: @hkotsubo eu vou adicionar essas ressalvas na resposta, tem problema?
Answer: Use o método:
public PrintStream format(String format, Object... args)
O método PrintStream.format() escreve uma string formatada na saída da stream
utilizando como parâmetros:

format- Uma string de formato, conforme descrito em Sintaxe da string de formato.
args- Argumentos referenciados pelos especificadores de formato na string de formato.

class Main {
  public static void main(String[] args) {
     double[] exemplo = {24.00, 8.00, 16.00, 14.00, 10.00};

     for (int l = 0; l < 5; l++){
        System.out.format("%05.2f \t| \n", exemplo[l]);
     }
  }
}

Saída:
24.00   |
08.00   |
16.00   |
14.00   |
10.00   |

Teste o código no Repl.it
No caso o especificador de formato %05.2f significa:

05 - Ao menos cinco caracteres serão impressos e os caracteres faltantes serão completados com zeros a esquerda.
.2 - O valor será restrito a precisão de duas casas decimais.
f  - O resultado será formatado como número decimal.
Comment: Vale lembrar que o separador decimal será o do *locale default* que estiver configurado na JVM, que nem sempre pode ser a vírgula. Se quiser forçar um separador específico, pode passar o *locale* para `format`, assim: `System.out.format(new Locale("pt", "BR"), "%05.2f \t| \n", exemplo[l])`


@ContentChildren is not being populated when parent render items using ng-content

Question: I have three components: Panel, PanelGroup (ul) and PanelItem (li):
Panel:
@Component({
selector: "panel",
directives: [PanelGroup,PanelItem],
template: `
  <panel-group>
    <ng-content select="panel-item"></ng-content>
  </panel-group>
`})

export default class Panel {}

PanelGroup:
@Component({
selector: "panel-group",
directives: [forwardRef(() => PanelItem)],
template: `

    <ng-content></ng-content>

`
})

export default class PanelGroup {
  @ContentChildren(forwardRef(() => PanelItem)) items;

  //I need to access children here and modify them eventually:
  ngAfterContentInit() {
    console.log(this.items.toArray()); //the array is always empty
  }
}

PanelItem:
@Component({
selector: "panel-item",
directives: [forwardRef(() => PanelGroup)],
template: `

        {{title}}

    <panel-group>
        <ng-content select="panel-item"></ng-content>
    </panel-group>

`
})

export default class PanelItem {
  @Input() title = 'SomeTitle';
}

As seen in the above example I try to get the content children inside the PanelGroup component, however the collection is always empty. Also tried to add selector to the 'ng-content' inside it - in this case the children are never rendered which is bit weird.
Am I missing something?
Here is plunk:

demo
Comment: Looks like a bug to me.
Comment: Created issue https://github.com/angular/angular/issues/8937
Answer: Use descendants: true:
@ContentChildren(forwardRef(() => PanelItem), {descendants: true}) items;

See also angular 2 / typescript : get hold of an element in the template
Comment: Well this saved my bacon
Comment: I have tried to modify the existing demo and it does not work. Could you check again ?
Comment: @javaLearner can you please create a reproduction in http://stackblitz.com?
Comment: As you can see, items.length is still 0. I wonder if I miss something?
Comment: Why did you use such an old Angular version? http://stackblitz.com/ would make this much easier. Just click Angular and you get a fully set up project.
Comment: Because the panel component is the one they are projected to http://plnkr.co/edit/pfKONBv13GhIt8cpP7LU?p=preview
Comment: I'm having the same issue with Angular 12. I'm using forward ref, descendants:true and I'm checking in ngAfterContent init the list is empty.
Answer: I am having a similar issue but it seems this one can also be solved by removing the select option from the panel-item. I assume since select='panel-item' is looking for only  content but there is a Nested Object as content. If you remove the restriction (in the plunk example) it shows it.


Problema com pk que não existe ainda

Question: Eu tenho a seguinte urls:
# urls.py
url(r'^proposal/(?P<pk>\d+)/$', ProposalDetail.as_view(), name='proposal_detail'),
url(r'^contract/(?P<pk>\d+)/$', ContractDetail.as_view(), name='contract_detail'),
url(r'^proposal/edit/contract/$', 'create_contract', name='create_contract_url'),

Significa que existe eu tenho /proposal/1/,
mas no meu exemplo eu não terei /contract/3/ ainda,
ou seja, /contract/3/ é um contrato que não existe ainda,
e quando existir terá um pk que pode ser diferente de proposal.
# views.py
class ProposalDetail(DetailView):
    template_name = 'core/proposal/proposal_detail.html'
    model = Proposal

Para o contract existir eu irei executar a função a seguir...
def create_contract(request, pk):
    if request.user.is_authenticated:
        proposal = Proposal.objects.get(pk=pk)
        if proposal.status != 'co':
            return HttpResponse('O status do orçamento deve ser concluido.')
        else:
            contractor = proposal.work.customer
            obj = Contract(
                proposal=proposal,
                contractor=contractor
            )
            obj.save()
            proposal.status = 'a'
            proposal.save()
    return redirect('/contract/%d' % obj.id)

... a partir deste botão.
# proposal_detail.html
<form class="navbar-form navbar-right" action="." method="get">
     Criar Contrato
</form>

O problema é que não estou conseguindo controlar os pk da forma correta.
Pergunta: Como eu faço para melhorar este código de modo a informar o pk de proposal na função create_contract
e redirecionar a página para /contract/3, sendo que 3 será um novo pk de contract, mas ele não existe ainda?
Answer: Supondo que Contract possua uma ForeignKey de Proposal, você pode atribuir o valor no ato do salvamento, por exemplo:
#models
class Contract(models.Model):
    proposal = models.ForeignKey('Proposal', blank=True)

#views:
def create_contract(request, pk):
    proposal = Proposal.objects.get(pk=pk)
    form = ContractForm(request.POST or None)
    if request.METHOD == 'POST':
        if form.is_valid():
            obj = form.save(commit=False)
            obj.proposal = proposal
            obj.save()
            return redirect('/contract/%d' % obj.id)

    return render(request, "seu_template.html", {'form':form, 'proposal':proposal})

Lembrando que não é muito sugestivo você utilizar o pk da url para duas coisas, no template você passou o id de proposal na url:
{% url 'create_contract_url' proposal.id %}"

E no redirect da sua view, você está retornando o id do contrato criado:
return redirect('/contract/%d' % obj.id)

É interessante que você se refira a uma coisa só em sua url, caso você queira os dois pk's, passe os dois pk's na url.
Se todo contrato se referir a um proposal, fica mais intuitivo que sua url de contrato seja dessa maneira:
url(r'^(?P<proposal_id>\d+)/contract/new/$', ContractCreate.as_view(), name='contract_create'),
url(r'^(?P<proposal_id>\d+)/contract/(?P<pk>\d+)/$', ContractUpdate.as_view(), name='contract_edit'),
url(r'^(?P<proposal_id>\d+)/contract/(?P<pk>\d+)/$', ContractDetail.as_view(), name='contract_detail'),

Respeitando a ideia do CreateView, UpdateView e DetailView, o sistema ficará muito mais legível.
https://docs.djangoproject.com/en/1.8/ref/class-based-views/flattened-index/#createview
Comment: Sim, mas não estou usando formulário, é apenas um botão que eu clico e executa a função.
Mas vc entendeu o que preciso sobre o id que não existe ainda do contrato?
Eu sei que baguncei um pouco os ids, mas eu preciso usar o pk de proposal apenas para me referenciar na hora de criar o novo contrato. E depois o redirect é para entrar no contrato novo, quando o pk dele existir.
Comment: Eu entendi, mas mesmo assim você pode utilizar as urls da forma que sugeri. Tanto no UpdateView quanto no DetailView, o default do django utiliza o "pk" para renderizar as informações de um objeto que já existe. Você pode utilizar a nomenclatura "proposal_id", no futuro isso até ajudará em manutenção de código. Na sua view ficaria def create_contract(request, proposal_id):
Fica mais intuitivo se você trabalhar dessa maneira.
Comment: Agora entendi. Obrigado.
Answer: Resolvido.
@login_required
def create_contract(request, proposal_id):
    if request.user.is_authenticated:
        proposal = Proposal.objects.get(pk=proposal_id)
        if proposal.status != 'co':
            return HttpResponse('O status do orçamento deve ser concluido.')
        else:
            contractor = proposal.work.customer
            contract = Contract(
                proposal=proposal,
                contractor=contractor
            )
            contract.save()
            proposal.status = 'a'
            proposal.save()
    return redirect('/contract/%d' % contract.id)

Problema com pk que não existe ainda


Symmetrical matrix determinant

Question: Is it true that every symmetrical matrix has a determinant non-zero?
If so how can I prove it?
Note: A symmetrical matrix that is not zero. (thanks to the commenter that pointed it out)
Comment: What about $A = \begin{bmatrix} 1 & 1\\ 1 & 1 \end{bmatrix}$? Or in general (for size $n\times n$ with $n\ge 2$), a matrix with all entries $1$.
Comment: Isn't the zero matrix symmetric?
Comment: Right, that is nonzero
Comment: Then take a diagonal matrix which has one zero on the diagonal and all entries outside of the main diagonal are zero. It is symmetric but its determinant is still zero. For example Diag[$1,0$].
Answer: No it is not. Consider the diagonal matrix with all values on the diagonal non-zero except one which is $0$. Its determinant is clearly $0$. The fact that it is symmetric only gives you that the eigenvalues are real. However it is enough for one eigenvalue to be $0$ for you to get a $0$ determinant. However if all rows/columns are linearly independent (the matrix is full rank) then the determinant is not $0$.
Answer: For a counterexample take any row with all zeros,  and fill in the rest of the matrix any way at all as long as it's symmetric and not the zero matrix.
Expanding along the zero row gives zero determinant.

Symmetrical matrix determinant


Perplexity calculation with neural nets

Question: I am having troubles understanding which formula to use to calculate perplexity of a neural language model. Various places online on the forums people suggest using 2^(cross-entropy) measure, which is what suggested also in this paper https://link.springer.com/chapter/10.1007/978-3-642-24809-2_15
Alternatively, I have just found out a more complex approach to perplexity calculation (https://arxiv.org/abs/1703.08864), which is  with hidden state being fed into max-entropy classifier , optimized with respect to the sequence
negative log likelihood . The paper compares perplexities to the SRILM toolkit, which produces similar results and gives more confidence in their approach to perplexity calculation.
I believe the second formula is similar to that of PPL = exp(NLL) as in (https://dp.readthedocs.io/en/latest/languagemodeltutorial/index.html)
The question is, why would I choose one formula over another? I suppose there are arguments out there that Log Loss and Cross Entropy are similar (https://jamesmccaffrey.wordpress.com/2016/09/25/log-loss-and-cross-entropy-are-almost-the-same/), but they produce very different perplexity results in language modelling from my experience.
Comment: We support math formatting using MathJax. More information: https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference
Answer: Negative log-likelihood and negative likelihood both have minima in the same location because the logarithm is a monotonic injective transformation. In terms of optimization, they are the same. In terms of numerics, one generally prefers to avoid exponentiation since this can cause overflow errors.
Note that we can use algebra to re-arrange from one expression to the other.
$$
\begin{align}
PPL &= \exp\left(-\frac{1}{N}\sum_{i=1}^N\sum_{t=1}^T \log\left(P_\Theta(w_t | h)\right) \right) \\
N \log(PPL) &= - \sum_{i=1}^N\sum_{t=1}^T \log\left(P_\Theta(w_t | h)\right)
\end{align}
$$
One reason to prefer one presentation over another is if you're reporting results and convention prefers reporting in one format or another in your subject.

Perplexity calculation with neural nets


Orbits of a 4x4 checkerboard

Question: Suppose we have a $4\times4$ checkerboard with 16 squares. Let $S$ be the set of all colorings with 8 black and 8 white colors. Note: colorings are considered the same if they map to each other using rotations and reflections.
Let $G=\{ e, A,B,C,D,90^\circ,180^\circ,270^\circ\}$ be the group of symmetries where $A$ and $B$ are vertical and horizontal reflections, $C$ and $D$ are diagonal reflections, and $90^\circ,180^\circ,270^\circ$ are the rotations. Let $S^g$ be the set of elements fixed by an element $g\in S$. Then:
$$|S^e|=\binom{16}{8}$$
$A$ and $B$ reflect halves, so each side must have 4 black squares (and 4 white):
$$|S^A|=|S^B|=\binom{8}{4}$$
Since $90^\circ$ and $270^\circ$ project to all 4 quadrants, we get
$$|S^{90^\circ}|=|S^{270^\circ}|=\binom{4}{2}$$
Similarly, $180^\circ$ exchanges halves:
$$|S^{180^\circ}|=\binom{8}{4}$$
For $C$ and $D$, there are either 2 or 4 black squares along the diagonal. Otherwise, we would reach a contradiction as an odd number of black squares must be split evenly into two halves. Case 1: 2 black squares on diagonal. In this case, we have 6 squares left which are split into 3 per half (out of 6 available squares), so we have $\binom{6}{3}$. But there are $\binom{4}{2}$ different ways of arranging the black squares on the diagonal. Thus, for Case 1 we have
$\binom{6}{3}\binom{4}{2}$.
For Case 2 (4 black squares on diagonal), each side has 6 total squares and 2 black squares, which is $\binom{6}{2}$. Combining the cases, we get:
$$|S^C|=|S^D|=\binom{6}{3}\binom{4}{2}+\binom{6}{2}$$
By Burnside's Lemma, the number of orbits $|S/G|$ is given by
$$|S/G|=\frac{1}{|G|}\sum_{g\in G}|S^g|=\frac{1}{8}\left[\binom{16}{8}+3\binom{8}{4}+2\binom{4}{2}+ 2\left[\binom{6}{3}\binom{4}{2}+\binom{6}{2}\right] \right]$$
But this cannot be right, because I put it in Wolfram Alpha and got 1670.25. Obviously, we expect an integer. Where did I go wrong?
Answer:
For C and D, there are either 2 or 4 black squares along the diagonal.

Or 0. I got 1674 orbits with this correction.
Comment: Oh I overlooked that. Thanks.

Orbits of a 4x4 checkerboard


Does $2 \log(-1) = 0$?

Question: It occurred to me, following the rule of logarithms, that $a\log(b)=\log(b^a)$
Thus $2 \log(-1) = \log((-1)^2) = \log(1) = 0$
Comment: the equality holds $iff b>0$
Comment: And for $\ln(i)$?
Comment: Please remember that you can choose an aswer among the given if the OP is solved, more details here https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work
Answer: In complex analysis the answer is no.  You do not have $\ln(a^b)=b\ln(a)$, it simply isn't an identity when we move beyond positive real arguments.
Things are different, however, in $p$-adics.  Select base 2 and consider the Maclaurin series
$\ln(1+x)=x-\frac{x^2}{2}+\frac{x^3}{3}-\frac{x^4}{4}...$
Plug in $x=-2$ and convert all terms to $2$-adics; the series converges $2$-adically ... to $...000000 = 0$!  We indeed have $2\ln(-1)=2×0=0$ in $2$-adics.
It's an example of how $p$-adics logarithms differ from what we are used to seeing in real or complex analysis.  In the case of $2$-adics, if we want to have the one-to-one and "inverse of exponential" properties that often make logarithms useful we have to limit the domain to arguments $\equiv 1 \bmod 4$.
Answer: The rule of logarithms (for reals) you mention can be valid when both $\log$ arguments, $b$ and $b^a$, are positive. This is not the case here.
If you think further, your equality would mean that, dividing by $2$, $\log -1$ is equal to $0$, which is not valid.
Answer: As far as I know you can assign as input to any lnx function only numbers greater than 0, meaning that the following must happen: x>0. This is very obvious, cause there cannot exist a number such that when it is raised to the e to be equal to -1. So this 2ln(-1) cannot be defined. The same happens to any function of the form logax.
Comment: Welcome to MSE! Unfortunately, this answer misses the fact that the logarithm *does* have an extension to negative numbers, using the *complex* exponential. So $2 \ln(-1)$ **can** be defined, but it's not zero for other reasons.
Comment: Than you very much. I didn't know that!
Comment: @user296602 I saw the other answers above and thought that I was right

Does $2 \log(-1) = 0$?


PHPUnit error call to undefined method on mock

Question: I am getting Error: Call to undefined method Mock_SimpleInterface_8a93e777::mymethod() when I call the mymethod() on the Simple class mock.
class PlaygroundTest extends \PHPUnit_Framework_TestCase
{
    public function testMock()
    {
        $class     = $this->getMockBuilder('\Playground\Simple')->getMock();

        $class->mymethod();
    }
}

The Simple class implementation
namespace Playground;

class Simple
{

    public function mymethod()
    {
        print "Hey!";
    }
}

According to PHPUnit docs (https://phpunit.de/manual/5.1/en/test-doubles.html), it states that "By default, all methods of the original class are replaced with a dummy implementation that just returns null (without calling the original method)."
Shouldn't I be able to call mymethod() and get a null return value? I want to avoid to specify all class methods. PHPUnit should be clever enough to know which methods can be called on the mock or not.
Is this a bug? I'm using PHPUnit 5.1.4
Comment: You are right. It is not a bug, I used this plenty of times. There has to be a different reason. You are assigning the mock to `$class` but calling `mymethod()` on `$interface`. Is it really like this or a mistake in your question?
Comment: It's a mistake from copying my code into stackoverflow. It really has been called on $class in the actual code. (I did tests on mocking an interface too, that's where I mistakenly copied my code). I will edit.
Comment: So I just copy&pasted your code, as I could not see any error. And I can tell you: There is none. I am getting no errors at all: `OK (1 test, 0 assertions)
` is the result. The problem has to be elsehwere. Do you have a call stack, with which you could verify where the call is actually coming from?
Comment: Also: Which PHP version do you use?
Comment: It was on PHP7. But according to the docs, PHPUnit 5 is compatible with PHP 7 though. I'll check more in details on monday for the call stack.
Comment: My test was also on PHP7.0.2, and with the same PHPUnit version, so... I can really not reconstruct this :(
Answer: Your assumptions are correct, so you have an error somewhere else or did not show the real code.
The mock class name Mock_SimpleInterface_8a93e777 suggests that you don't actually mock \Playground\Simple but rather \Playground\SimpleInterface, which probably does not contain mymethod()
Comment: Yeah, I tried also with an interface. I think I mixed code on stackoverflow from my test with a class and the one with the interface (both the same result though).
Comment: Then check if maybe a different version of the class is autoloaded .


Best CMS to handle short snippets of text?

Question: I have to install a CMS to manage a set of mathematical problems, i.e., our main content will be short (~3 lines) snippets of text. We need the ability to add comments and categories/tags, possibly with a powerful search function combining different constraints on the categories.
A crucial ability is the possibility to combine the results of a search in the same page to produce a (printable) problem sheet: not many CMS's seem to be able to do so, and it is difficult for me to test every one for this specific function. Do you guys know of a CMS that is capable to return formatted search result in this fashion?
Thanks in advance!
Answer: I would look into Drupal.  As it can support all of this quite easily.  Drupal is a bit of a mix between CMS and web framework.  It has a bit of a learning curve but it's very flexible and once mastered can be leveraged to solve almost any use case.
Just add a new content type "problem" or whatever you want to call it.  You can use Content Construction Kit to add additional custom fields that you wish to capture.
The Comment module is part of core...so just enable it and allow comments on this content type.
Taxonomy is also part of core so enable it and use it for tagging.  There are many additional taxonomy modules that add some features and help manage these.
Search is in Core.
Views can be used to generate a problem sheet.
That should get you going in the right direction but Drupal is a big subject and there are a ton of modules available.
Comment: Also, if you're working with Math, the Drutex Drupal module makes it dead simple to have very nicely-rendered equasions in your content.
Answer: Any CMS shall do. But I love http://textpattern.org, for syntax highlighter and snippets use SyntaxHighlighter (http://alexgorbatchev.com/wiki/SyntaxHighlighter). It's a javascripts! So, Any CMS shall do.


Como bloquear a lista de sugestões de um input text?

Question: Estou querendo bloquear aquela lista de sugestões que aparece quando digita alguma coisa num campo text, alguém sabe como faz?
Answer: Os campos input possuem uma propriedade "autocomplete", você pode desativar para eliminar este comportamento
<code><input type="email" id="email" name="email" autocomplete="off">
</code>
Mais informações:
https://www.w3schools.com/tags/att_input_autocomplete.asp
Comment: Obrigado @Bins, resolveu perfeitamente aqui.


Problema com menu em css

Question: Galera montei um menu em css que esta funcionado muito bem, o problema que que ao colocar o cursor do mouse em cima de letra do menu ele muda, parece que altera suas bordas.
Alguém pode me ajudar a solucionar isso?
Segue o código:

.aside-menu {
  z-index: 1000;
  position: fixed;
  height: 100%;
  top: 40px;
  bottom: 0px;
  left: 0px;
  width: 35px;
  background: #F1F1F1;
}

#cssmenu ul,
#cssmenu ul li,
#cssmenu ul ul {
    list-style: none;
    margin: 0;
    padding: 0;
}
#cssmenu ul li.hover,
#cssmenu ul li:hover {
    position: relative;
    cursor: default;
}
#cssmenu a {
    background-color: #F1F1F1;
    color: #484848;
    display: block;
    text-decoration: none;
    padding-top: 15px;
    padding-left: 10px;
}
#cssmenu ul {
    border-right: 2px solid #0fa1e0;
    list-style: none;
}
#cssmenu > ul > li:hover:after {
    content: '';
    display: block;
    width: 0;
    height: 0;
    position: absolute;
    right: 0;
    top: 50%;
    border-top: 10px solid transparent;
    border-bottom: 10px solid transparent;
    border-right: 10px solid #0fa1e0;
    margin-top: -4px;
}
#cssmenu .has-sub:hover > ul {
    display: block;
}
#cssmenu .has-sub ul {
    display: none;
    position: absolute;
    width: 150px;
    top: 5px;
    left: 100%;
}
#cssmenu .has-sub ul li a {
    background: #0fa1e0;
    filter: none;
    display: block;
    line-height: 120%;
    padding: 10px;
    color: #ffffff;
}
#cssmenu .has-sub ul li:hover a {
    background: #0c82b5;
}
#cssmenu .has-sub .has-sub:hover > ul {
    display: block;
}
#cssmenu .has-sub .has-sub ul {
    display: none;
    position: absolute;
    left: 100%;
    top: 0;
}
#cssmenu .has-sub .has-sub ul li a:hover {
    background: #09638a;
}

b

Product 1

Sub Product

Sub Product

Product 2

Comment: Aqui não aconteceu isso.
Comment: basta colocar o cursor em cima da letra B que ela fica mais clara.
Comment: Não estou vendo isso aqui não. Quando passa o mouse sobre o B aparece o SubMenu.
Comment: tenta dar um zoom na tela
Comment: acabei de perceber que o erro so ocorre com o safari e com IE
Comment: Ufa, ainda bem, uso oculos e ja achei que teria que trocar as lentes de novo porque não tava vendo diferença nenhuma kk
Comment: hahhahahahhahahah
Answer: Sem uma página de exemplo fica um pouco difícil ver seu problema, mas tente tirar as bordas desse trecho do seu css:
#cssmenu > ul > li:hover:after {
    content: '';
    display: block;
    width: 0;
    height: 0;
    position: absolute;
    right: 0;
    top: 50%;
    border-top: 10px solid transparent; /* Remover */
    border-bottom: 10px solid transparent; /* Remover */
    border-right: 10px solid #0fa1e0; /* Remover */
    margin-top: -4px; /* Também pode ser isto */
}

Mas se puder criar uma página de exemplo seria melhor.
Comment: Não deu certo. basta colocar o cursor em cima da letra B que ela fica mais clara. Tenta dar um zoom na tela que vc ve o problema melhor
Comment: acabei de perceber que o erro so ocorre com o safari e com IE
Comment: Se o erro só ocorre nesses navegadores pode ser a formatação própria que eles aplicam aos links. No seu css tente colocar #cssmenu a:hover { color: #484848 !important; } pra ver se resolve.
Comment: não deu certo :/
Comment: Tem algum link pra mim testar no internet explorer, porque essa pagina do stack não da pra abrir nele.
Comment: vou criar e te mando ok

Problema com menu em css


C# datagridview filter on DataGridViewCheckBoxColumn checked or unchecked

Question: The dataset contains a DataGridViewCheckBoxColumn and i whould like to filter the view on 3 possibilities: show all(checkbox checked and unchecked) show only checked and only unchecked
<code> private void listBoxBehandeld_SelectedValueChanged(object sender, EventArgs e)
        {
            string listBoxValue = "Alle";
            listBoxValue = listBoxBehandeld.GetItemText(listBoxBehandeld.SelectedItem);

        switch (listBoxValue)
        {
            case "Alle":
               //Show checked and unchecked

                break;

            case "Ja":
               //show checked

                break;

            case "Nee":
                //show unchecked
                }
                break;
        }
        dataGridView.DataSource = meldingenBindingSource;
</code>
Answer: You will need to enumerate the rows in the grid to filter based on your case selection.
There's an example from
https://social.msdn.microsoft.com/Forums/windows/en-US/74df79a9-87ad-4cec-8502-3a357015558d/how-to-check-the-datagridviewcheckboxcolumn-if-its-checked-?forum=winforms
<code>foreach (DataGridViewRow row in dataGridView.Rows)
{
   //Get the appropriate cell using index, name or whatever and cast to DataGridViewCheckBoxCell
   DataGridViewCheckBoxCell cell = row.Cells[colCheck] as DataGridViewCheckBoxCell;

   //Compare to the true value because Value isn't boolean
   if (cell.Value == cell.TrueValue)
      //The value is true
}
</code>


Qt Quick QML MouseArea autorepeat on press

Question: Hopefully I'm not missing something obvious here.
I am writing an app and have made a zoom in button with an Image and a MouseArea. I need the button to repeat a method call after, say, every second to zoom in while holding the mouse button down. It isn't entirely obvious how to make this repeat. Right now I have:
Rectangle {
    id:zoomInBtn
    Image {
        id: zoomInImg
        anchors.centerIn: parent
        fillMode: Image.PreserveAspectFit
        source: zoomIn.pressed ? ":/img/zoom_in_sel" : ":/img/zoom_in_unsel"
    }
    MouseArea {
        id: zoomIn
        anchors.fill: parent
        onPressed: { cameraController.zoomIn(0.5); }
    }

I have also tried with
onPressAndHold: { cameraController.zoomIn(0.5); }

which does basically the same, although with a small delay as expected, but I need to repeat this action every second while the mouse button is held.
Answer: To perform the task you need you must use a Timer. the timer must remain active while the containsMouse is active. you must also enable triggeredOnStart to run immediately if the timer is activated.
Rectangle {
    id:zoomInBtn
    Image {
        id: zoomInImg
        anchors.centerIn: parent
        fillMode: Image.PreserveAspectFit
        source: zoomIn.pressed ? ":/img/zoom_in_sel" : ":/img/zoom_in_unsel"
    }
    MouseArea {
        id: zoomIn
        anchors.fill: parent
    }

    Timer {
        id: timer
        interval: 1000
        repeat: true
        triggeredOnStart: true
        running: zoomIn.containsMouse
        onTriggered: cameraController.zoomIn(0.5) //task
        }
    }
}

Comment: It is often beneficial to have such repetitive tasks implemented as stand alone functions rather than inside the handlers, and simply invoke the function via a one-liner. Also, if you use a named function, you can connect and disconnect, which can be very useful because unlike property bindings that get replaced on re-binding, signal handlers get stacked together, so the only way to remove previous or "inherited" handlers is to have them as named functions so you can disconnect them. Which is obviously impossible with anonymous expressions.
Comment: You should trigger the timer on started to avoid the initial delay.
Comment: Also, `;`'s in QML are redundant unless you have multiple statements per line
Comment: Finally, I'd save a few lines of code by setting the timer `running: zoomIn.containsPress`, eliminating the need for the pressed and released handlers ;)
Comment: And they just keep on coming, you don't need a `{ }` block for signal handlers if they contain a single expression.
Comment: @dtech Thanks for notifying me of that detail, an elegant way to do what you're committing is to activate the triggeredOnStart property. :P
Comment: @dtech I understand that point, but my idea is that there must be repetitive task, it is only for educational purposes. :P
Comment: @dtech Okay, I understand, you're right, it's just what you recommend in the documentation: http://doc.qt.io/qt-5/qtqml-syntax-signals.html#connecting-signals-to-methods-and-signals
Comment: I'd say that `pressed` is more fitting here than `containsMouse`
Comment: `pressed` will be true even if the cursor moves outside the mouse area, in this regard I'd say `containsPress` is more intuitive in the apparent usage scenario. My first comment featured `containsMouse ` but that was quickly revised to `containsPress`, however since comment changes do not auto-update, eyllanesc ended up taking the advice in its initial and suboptimal form. `containsMouse` will work just fine thou, unless you employ `hoverEnabled`.


How to perform XSLT Transformation with Java extension from within OSGi Bundle

Question: We are in the process of converting existing code to an OSGi environment. In one of our (yet to be) OSGi bundles we have code that perform an XSLT transformation. A piece of the XSLT includes a java extension function to create a unique numeric value. The Java class also resides within the bundle. This is a fragment of the style sheet:
<xsl:template match="m:property">
   <xsl:variable name="uniqueDataStreamName" select="concat(../@id,'/',@name)" />
   <xsl:variable name="uniqueDataStreamId"
       select="java:com.xyz.TransformationUtils.makeDataStreamIdFromUniqueName($uniqueDataStreamName)" />
   <data id="{number($uniqueDataStreamId)}">
   <tag>
      <xsl:value-of select="$uniqueDataStreamName" />
   </tag>
   <current_value>
     <xsl:value-of select="@value" />
  </current_value>
</data>

For reference, this is how the transformation is set up and called:
protected Templates createTemplates(Source xsltSource) {
    try {
        TransformerFactory tf = TransformerFactory.newInstance();
        Templates templates = tf.newTemplates(xsltSource);
        return templates;
    } catch (TransformerException e) {
        throw new RuntimeException(e);
    }
}

protected byte[] transform(byte[] input) throws TransformerException {
    ByteArrayOutputStream out = new ByteArrayOutputStream(2048);
    templates.newTransformer().transform(
            new StreamSource(new ByteArrayInputStream(input)),
            new StreamResult(out));
    return out.toByteArray();
}

When run in a non OSGi environemnt, it works. When run in an OSGi framework, it fails because the stylesheet cannot be compiled because the class TransformationUtils cannot be found. I kind of understand that--the class loader loading the jaxp transformer implementation does not see the extension class in our bundle. However, I'm stumped at finding a solution. I've tried using OSGi:fied Xalan and Xerces bundles to no avail.
My question is: How can this be solved? Can it?
Answer: The answer depends on how the XSLT processor looks up the extension class. You might need to read the source code and/or run it through a debugger to find this out.
For example, if the XSLT processor uses the Thread Context ClassLoader (TCCL) then this would normally fail because the TCCL is undefined in OSGi. You can work around this by explicitly setting the TCCL for the duration of the call to the XSLT processor, e.g.:
ClassLoader orig = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(MyClass.class.getClassLoader());
try {
    // invoke XSLT processor
} finally {
    Thread.currentThread.setContextClassLoader(orig);
}

where MyClass is a class from your bundle and has visibility of the extension class.
In the worst case, the processor might look up the extension using its own classloader, i.e. with a simple call to Class.forName(). The best thing to do here is to beat up the developer of the library for being so stupid. After you've done that, you could use a fragment to attach the extension class to the processor bundle... it's a nasty hack but better than some of the other possible nasty hacks.
Comment: One thing to be aware of is that getting and setting the TCCL is a privileged operation, so if you need this to work when Java 2 security is enabled you'll need to setup the permissions.perm file to allow it and you may need some strategically placed calls to doPriv.
Comment: Of course, this works! Just realized I've done it a couple of times for other reasons. Eeerhm, at least I don't have to go and beat someone--besides myself that is! Thanks!


Show that if $a_n(X_n-X) \overset{\mathcal{D}}\to Z$ then $X_n \overset{P}\to X$.

Question:
Let $(a_n)\subseteq \Bbb{R}$ be a sequence such that $a_n \to \infty$. Let $(X_n)$ be a sequence of random variables such that $a_n(X_n-X) \overset{\mathcal{D}}\to Z$ fore some random variables $X$ and $Z$.
Show that $X_n \overset{P}\to X$.

So I have some sort of Idea why should this happen. Since $a_n \to \infty$ for $a_n(X_n - X)$ to have a "finite" limit, say $Z$, then $X_n - X \to 0$ somehow. (The excercise says that the convergence must be in probability.) But Im having a lot of trouble in making this ideas more precise. I've tried with characteristic functions for the convergence in distribution. Got to nothing. Any hint?
Answer: Let $Z_n=a_n(X_n-X)$. We are told that $\frac{1}{a_n}\to 0$ so, in particular, $\frac{1}{a_n}\overset{P}{\to}0$. So by Slutsky's Theorem, $X_n-X=\frac{1}{a_n}\times Z_n\overset{d}{\to}0\times Z=0$. But convergence in distribution to constant is equivalent to convergence in probability to that same constant, so we conclude that $X_n-X\overset{P}{\to}0$.
Answer: $a_n(X_n-X)\stackrel{\mathcal{D}}{\to}Z$ implies that $\mathbb{P}\left(|Z|<\infty\right)=1$ - $Z$ should be a proper random variable.
If the claim would not hold for some $\varepsilon$, then:
$$
\exists\varepsilon>0: \lim_{n\to\infty}\mathbb{P}\left(|X_n-X|>\varepsilon\right)\neq 0\Rightarrow \limsup_{n}\mathbb{P}\left(|X_n-X|>\varepsilon\right)=\delta(\varepsilon)>0
$$
Thus, $\exists\sigma:\mathbb{N}\to\mathbb{N}: \sigma(i)<\sigma(i+1)$ and
$$
\mathbb{P}\left(|X_{\sigma(i)}-X|>\varepsilon\right)=\delta(\varepsilon)\left(1-\frac{1}{i}\right)
$$
Since $a_n\to\infty$, thus $a_{\sigma(n)}\to\infty$ as well. Choose $\theta:\mathbb{N}\to\mathbb{N}: a_{\theta(\sigma(n))}<a_{\theta(\sigma(n+1))}$ (an inscreasing subsequence of $a_{\sigma(n)}$ - this must exist, as $a_n\to\infty$.
$$
\mathbb{P}\left(|a_{\theta(\sigma(n))}||X_{\theta(\sigma(n))}-X|>|a_{\theta(\sigma(n))}|\varepsilon\right)>\delta(\varepsilon)\left(1-\frac{1}{\theta(n)}\right)\geq \delta(\varepsilon)\left(1-\frac{1}{n}\right)
$$
Since $a_n(X_n-X)$ converges to $Z$ in distribution, so does any subsequence of it. Let $Y_n=a_{\theta(\sigma(n))}(X_{\theta(\sigma(n))}-X)$. Then by the previous claim,
$$
F_{Y_n}(-|a_{\theta(\sigma(n))}|\varepsilon)+1-F_{Y_n}(|a_{\theta(\sigma(n))}|\varepsilon)>\delta(\varepsilon)\left(1-\frac{1}{n}\right)\geq\frac{\delta(\varepsilon)}{2}
$$
Since $a_{n}\to \infty$ and $a_{\theta(\sigma(n))}$ is an increasing sequence, $\forall x\in\mathbb{R}\exists N_x\in\mathbb{N}:\forall n>N_x$
$$
|x|<\varepsilon|a_{\theta(\sigma(n))}|\Rightarrow
$$
$$
\forall n>N_0: F_{Y_n}(-|x|)+1-F_{Y_n}(|x|)\geq \frac{\delta(\varepsilon)}{2}
$$
But as $Z$ is a proper random variable, $\lim_{x\to-\infty}F_Z(x)=0$ and $\lim_{x\to\infty}F_Z(x)=1$, and $F$ is a non-decreasing function, thus:
$$\forall \varepsilon'>0:\exists x(\varepsilon')\in\mathbb{R}: \forall x>|x(\varepsilon')|: F(-x)+1-F(x)<\varepsilon'$$
Now choose $\varepsilon'=\frac{\delta(\varepsilon)}{3}$, thus by the convergence in distribution:
$$
\frac{\delta(\varepsilon)}{2}\leq\lim_{n\to\infty}F_{Y_n}(-|x(\delta(\varepsilon)/3)|)+1-F_{Y_n}(|x(\delta(\varepsilon)/3)|)\leq\frac{\delta(\varepsilon)}{3}
$$
Which is a contradiction.


How to determine where the function is continuous and where the function is differentiable with a piecewise function

Question: Working on my AP Calc summer assignment and I am having a hard time understanding how to solve this; I could really use some very dumbed-down help if possible because I don't even know where to start. Here it is...
Determine where the function is continuous and where the function is differentiable.
$$f(x)=\begin{cases}(x+1)^2,& x \leq 0\\
2x+1,& 0< x < 3\\
(4-x)^2,& x \geq 3\end{cases}$$
Thank you in advance for your help!
Comment: Hint: Is it already clear to you that the function is continuous and differentiable everywhere except possibly 0 and 3, and you simply need to find which properties it fulfills at 0 and 3?
Comment: That makes sense but how would I go about doing that? I've never worked with piecewise functions before.
Answer: As is said in the comments, everything is clear except at $0$ and $3$.
To see if it is continuous at $0$, for example, you need to check that the definition of continuity at a point is satisfied at $0$. That is, is it true that $\displaystyle \lim_{x\to 0}f(x) = f(0)$?
For differentiability, you again need to check the definition: Does the limit $\displaystyle \lim_{h \to 0} \frac{f(0+h)-f(0)}{h}$ exist?
Similar checks need to be performed for behavior at $3$.
Comment: @Kaleidoscopic if you find an answer to your question useful, then it is good practice to accept an answer. This will serve to let the community know that your question has been resolved.
Comment: I think I understand this better now, thank you!
Comment: You're welcome, @Kaleidoscopic !


How to turn on block or panel from old site to the new one

Question: I'm fairly new to Drupal. I have an old version of site with a "block" or "panel" or whatever it's called, that displays on a page, and the new version doesn't have it, and I for god's love can't figure out how to turn it on. It would require looking at it directly, because it's just something I can't see in that beautiful user friendly admin dashboard of Drupal.
EDIT: Upon closer examination, it looks like a view with "content" data that is on the old site, but the "content" is missing on new one. Anyone knowing how to deal with that, I would appriciate that a lot.
Comment: Export the view from old site and import in new site.. Are they (Old Site & New Site) using same Major Version of Drupal ?
Comment: Yes, thats great, how do I export it / import it. THere's not export import button there mate.
Comment: Which version of Drupal are you using ? Are you logged in as admin ?
Comment: Hi there mate, yes I am. It's 7.2
Answer: Views out of the box support export / import functionality . You can export any view from any instance to any instance using below steps.. Make sure both the instances are in same Major Drupal version..

Login as administrator
Go to the view you want to export "admin/structure/views"
Edit View
Click on export link in the drop down

Copy content
Go to new site and navigate to "admin/structure/views/import"
Paste copied content and click on Import


Byte order of DEC VAX vs IA-32

Question: A description of the problem follows.  You can skip to the bottom line if you're not interested.

I am working with a data file with this description:

A 109-slice MRI data set of a human head. Complete slices are stored consecutively as a 256 x 256 array. Pixels consist of 2 consecutive bytes making one binary integer. Data taken on the Siemens Magnetom and provided courtesy of Siemens Medical Systems, Inc., Iselin, NJ.

and then:

The data sets were written on a Digital Equipment Corporation (DEC) VAX computer. Each file contains only pixels, stored in row major order with 2-byte integers per pixel. To use the images on machines that have normal byte order (DECs use reverse byte order), you should swap alternate bytes, for example using the 'dd' command in UNIX. A sample command that does this for the 3dknee data set is:

<code>% dd if=3dknee of=3dknee.new conv=swab
</code>
I don't know what the real values are, so I can't judge just by looking if the byte order is correct.
The Bottom line
Is the byte order of a DEC VAX the same as in IA-32, or reversed?
Comment: This question was refreshingly different from all the 'plz send teh codez' questions I've seen today. +1
Answer: According to this page and this page, the VAX and x86 both use little-endian byte order.  So no conversion should be needed.

Byte order of DEC VAX vs IA-32


Is there an FX aggregator pedal that allows A/B/Y for 2 outputs?

Question: I recently bought and set up the Boss ES8 and was very disappointed to realize that even though it has 2 outputs that can be used individually or at the same time, ALL of the effects route to both outputs when activated. You cannot choose which output to send individual effects to. Obviously, I'm dumb for not figuring that out ahead of time, but now I'm wondering if that capability exists at all.
So, does anybody know of a similar programmable patch pedal that will allow you to assign multiple effects pedals to individual patches, but ALSO allows you to designate which outputs the various individual effects are sent to?
Answer: Some of those in/out are stereo, so surely some pedals could be routed left and right. Boss would have to incorporate this because some pedals ( theirs also!) are stereo, and would need routing to two destinations. As I say to myself often, if all else fails, read the instructions...