When should I upgrade (or not upgrade) Java?

Question: I'm pretty familliar with .NET and know that patches and upgrades are mutually exclusive to framework versions (1.x) and (2.x / 3.x) and (4.x).  This segregation makes it easy to understand the dependencies.
What logic or segregation applies to applying Java upgrades?  When should I do it, or when should I not?
Answer: As Always the answer is 'It Depends'.
If you are a consumer and the patch is security related do it now.
If you are an enterprise and you are running an application server and the patch details do not mention a security vulnerability that you are likely to hit (User running malicious JNLP application) you can hold off. If the 'patch' is adding new functionality such as Java 1.6.0 Update 10 (Update N) then you can maybe hold off.
In general updates to a certain Java version (1.4.2, 5, 6, 7) should be API stable and ok to update, but depending on what your application does to java you may need to test or hold off.
For instance recently Oracle changed some metadata about the HotSpot VM in a patch which caused the Eclipse IDE to fail.
99 times out of a 100 the Java patches should be API stable and have non-breaking changes.
Answer: Many well-known versions of applications that require a specific java version usually include that version of java binaries with their application, and launching it is some variation of  <-lots -of -switches>.
In the above case, upgrading the general/system-wide/default java usually has no impact on the application with it's own java binaries.  On the other hand, you may also be unaware that the application-specific version of java (with a known vulnerability) exists when you update the system default java, unless you are actually measuring and reporting on it using a software inventory application.
Answer: Minor updates are usually bug fixes and security updates, so they should always be applied. This is especially a concern with any Java VMs that communicate with the outside world (web services and clients). Major updates (1.5 to 1.6, 1.6 to 1.7) are generally backward-compatible with earlier versions. This is something that Java has been really reliable for since its inception.
Forward-compatibility is usually the main concern, and the applications or platforms (e.g., Eclipse, Tomcat) that depend on new Java features (e.g., Java 5 generics, Java 6 annotations, Java 8 lambda expressions) will generally drive the decision for major platform upgrades in our shop. As one example, you may find Java 6 clients suddenly unable to access some HTTPS web sites since the last few months due to response to the logjam SSL vulnerability, which has prompted many web administrators to upgrade their SSL certificates to 2048 bit keys, a key size that Java 6 does not support, but one that Java 7 and 8 do support.
In the past, there has generally been a window of three to five years where two or three different major Java versions are in general use, until some critical feature such as those listed above prompts a shift toward a newer version.
Our development environment is still targeting Java 6 where needed (for older OS X clients), Java 7 for new development, and Java 8 for our server environment. Basically, we want a stable production environment based on Java 8 before we start relying on Java 8 features in our development environment. The backward compatibility of Java gives us a long time to make this transition.
For Java 6, I believe the lack of 1024DH support is the nail in the coffin.


Replacing chords with riffs

Question: I'm kind of unsure as to where I can look for help regarding this but I've become very interested in the guitar playing of Jack white and Dan Auerbach. Both seem to have this amazing playing style that in some cases replaces the need for chords, instead using riffs and licks etc, but still keeping up a nice chord progression. My confusion in trying to learn this is how you can follow a chord progression using only notes or riffs? Apologies in advance for I'm sure to be a very amateurish question. Any help is highly appreciated! I'd love to improve in this space.
Answer: The simple answer is: play the notes in the chord as a riff. As the underlying chord changes, change the notes that need to be changed. You can do this by holding down a chord shape and arpeggiating the chord(check out "Simple Man" by Lynyrd Skynyrd) or you can move your fingers in a scale like fashion(The intro riff of "Pride and Joy" by SRV has a good example of a riff going from I to IV). Jack and Dan are both blues players, so the pentatonic scale plays a role here. Instead of strictly using chord shapes, you can switch between pentatonic scales based on the root of the chord you want.
Sometimes they play in this riff/lick style because it is necessary to keep the song interesting. A blues may not have many changes, so playing a riff can make four bars of the same chord sound interesting.
Let's take "Thickfreakness" by Dan Auerbach. The intro is a solo all in Am pentatonic. The riff here begins at the verse and spells out an A power chord:
e-----------------------|
B-----------------------|
G---2----2----2---------|
D---2----2----2---------|
A-0----0----0---0-------|
E-----------------0-3-4-|

The end of that riff is a bass walk-up back to the root E-G-G#-A (The A starts on the beginning of the next bar). Having a part that mimics the bass is good in blues because often times a guitar player may play unaccompanied.
When he plays the riff again, instead of ending with a bass walkup, he does an Am pentatonic run downward to create contrasting motion:
e--------------------------|
B--------------------------|
G---2----2----2--2p0-------|
D---2----2----2------2p0---|
A-0----0----0------------3-|
E--------------------------|

So even though the underlying chord hasn't changed at all(you could argue the short G# is part of an E7), we have things happening that catch the ear of the listener.
My recommendation is if you want to practice this, do so with songs without many chords or songs that sit on one chord for a while.
Answer: If you take a deep view of the matter, you end up with the idea that "chord" and "riff" - or "chord" and "melody" - are just the "vertical" and "horizontal" aspects of harmony.
To keeps things simple we can say "harmony" is combining tones in a pleasing or artful way. Those tones can be combined literally by playing multiple tones simultaneously, or played in succession. So, for example, using a simple E major chord, we can play the chord either vertically or horizontally...

The first way, the vertical way, is the way most people think of harmony. They think of harmony literally as playing chords. But the second way, the horizontal way, is also working with chords and harmony, although you might want to think of it as implied chords and harmony. But to make the point clear, if you played some thing like this...

...it will be heard harmonically as chords E A E.
When you break up chords and play them in that kind of linear, horizontal fashion, it is technically called arpeggiation.
A very important aspect of harmony and horizontal lines is "filling in" the spaces between the tones of the chord. If, for example, I stick notes in between the notes of the arpeggiated E chord, I get this...

...I used white note heads for the "in between" notes to make it easier to see that the black note heads are the tones of the E major chord (E G# B.) The technical name for those in between notes is non-chord tones (NCT.) There are many kinds of NCTs. In this example they are called passing tones.
So, in that example we can see there is both the first five tones of the E major scale, but also and arpeggiation of the E major chord with two passing notes. The point bears repeating: those five notes that most would regard as part of only a scale also function harmonically as a manifestation of a chord.
Now let's look at a real music example of those ideas in action...

...in that riff all the notes except two are tones from an E7 chord (E G# B D♮.) The G♮ and F♯ can both be regarded as neighbor or auxiliary tones, which mean to take one step away from a chord tone and then go back. Technically the G♮ is an "incomplete" neighbor, but it works the same way, or call it a passing tone if you like.
But notice that the F♯, which I call an auxiliary tone, is not literally a move immediately from the E and immediately stepping back to the E, there are other notes in between. This kind of thing happens where harmony is regarded in a horizontal way. We can think of those E and F♯ notes as persisting in memory.
Just like we took a chord of simultaneous tones and broke it up by arpeggiation into a horizontal line, we can work in the reverse and take a horizontal line and reduce it to the implied chord. To show how the F♯ is acting like an auxiliary to E we can reduce the riff to this...

Back to your question...

...replaces the need for chords, instead using riffs and licks etc, but still keeping up a nice chord progression. My confusion in trying to learn this is how you can follow a chord progression using only notes or riffs?

emphasize arpeggiating the chord tones
fill in between the chord tones with non-chord tones
use tones from the blues scale, or relative to the chord use flat thirds, flat fifths, and flat sevenths, for a bluesy feel
don't worry about using a small range, many riffs dwell around three adjacent tones for a while
in terms of pitch, your basic material is just chord and scale tones, which is generic, think of rhythm as a primary way to give riffs a unique character
in terms of direction, your basic material is up and down, which is also generic, so use some jumps in the riff to give them a unique shape, for example instead of E G♯ B G♯ E you can try E B G♯ E B

Replacing chords with riffs


How do interpret statistically NULL SVM Output

Question: I am using LibSVM (3.18) as an implementation of SVM. But every time when I'm predicting the result, it's giving zero.
I am following these instructions:

I have CSV file (+50K lines), Most of data in column (target) is zeros, the other values are between 1-10.
I convert csv file to libsvm data by selecting this column as label.
When I Scale Data, I use these parameters
$ svm-scale -l 0 -u 1 data.cv>scaled.data
As I have a huge file, I use Subset.py.
When I finish all the steps and apply predict. I got good result of accuracy.
$svm-predict scaled_data.csv model.train data.predicted
Accuracy = 94.28%

but the file I get (data.predicted) contains only zeros.
What does this mean statistically ?
Is it tricky to predict this kind of data ? Is there any way to solve this problem ?
Comment: Assuming the positive label is `+1` you should do `svm-train -w+1 100 -c 0.03125 -g 0.0078125 -v 5 -q`. Note that you might need to optimize `c` again.
Comment: Perfect! One more thing, by mentioning -c, i run grid.py on small data that extracted using subset. how accurate is subset in this case ? I mean, if we get small data, we might find only zeros in this data as we have a lot of negative points
Comment: If you have no instances of the positive class in a subset you cannot learn anything. libsvm will complain when this happens.
Comment: grid.py is taking a long time (+24 hours) when i apply on the whole file, that's why I used subset to accelerate the process
Answer: You probably have very few positives compared to negatives. This is called an imbalanced setting. In this case, predicting everything as negative will yield high accuracy even though it is useless.
If you indeed have an imbalanced data set, you can improve your models by assigning a higher misclassification to positive instances during training. In libsvm you can do this using the <code>-w</code> flag.
A good heuristic to assign class weights is to use the following equation:
$$C_{pos} \times n_{pos} = C_{neg} \times n_{neg}.$$
Ex.: if you have 1 positive and 100 negatives, $C_{pos}$ should be $100 C_{neg}$.
Comment: Thanks ! That's very very useful. at which step should I do this ? (I mean: when I scale, predict or cross-validate data ..)
Comment: You can assign misclassification penalties per class while training models using `svm-train`.
Comment: "I don't lack data, but the phenomena I am doing a study about is rare", I am doing statistics now about the data I have; 98% of the data is zero. Is it accurate to use the factor this way.
Comment: I couldn't found "-w" flag, but I found "-wi weight" : set the parameter C of class i to weight*C, for C-SVC (default 1)
Comment: @user3378649 that is the flag you need. Replace `i` by the label of the positive class.
Comment: Can you please check the update. Is this what you mentioned ?
Comment: I've worked on your approach, I got some results but it's not sufficient. (10-50 out of 20k). Should I augment the coefficient again. Or should I think about another approach to tackle this problem ?


A kind of Lebesgue differentiation theorem for general sets

Question: Let $\Omega$ be a bounded domain. I have a function $f_n\colon \Omega \to \mathbb{R}$ such that $f_n \to f$ in $L^2(\Omega)$ and $f \leq 0$ a.e. Let $g_n \in L^2(\Omega)$ be uniformly bounded in $n$.
Define $A_n := \{ x : f_n(x) \geq \frac 1n\}$. So in the limit, $A_n$ should tend to the empty set.
Can I say that
$$n\int_{A_n} g_n(x) \to 0$$
I guess not, but what if I have a rate of convergence for $A_n$ or something like that?
as $n \to \infty$?
Answer: $n\int_{A_n} g_n \to 0$ for every uniformly bounded sequence $\{g_n\}$ iff $n \mu \{x: f_n(x) \geq \frac 1 n\} \to 0$. [In one direction take $g_n=1$ for all $n$ to prove this].


jQuery star rating system with a value for every star

Question: I am having a problem with my jQuery code, I would like every star to have a Value.
So star one is 1/5, star two is 2/5 and so on.
(Value="1/5")
I use PHP to send the results of but it uses Values.
The plan is to use this star rating system in forms.
I have put the code in to jsFiddle. Link: http://jsfiddle.net/trickedgaming/2Q5cw/

$(document).ready(function () {
    $('#example-1').ratings(10).bind('ratingchanged', function (event, data) {
        $('#example-rating-1').text(data.rating);
    });

    $('#stars').ratings(5).bind('ratingchanged', function (event, data) {
        $('#example-rating-2').text(data.rating);
    });
});

The rest of the code is in on the jsFiddle page.
Comment: Hi, I use Ajax tolkit and never had problems: http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/Rating/Rating.aspx
Answer: You're missing the #example-rating-... elements that you're attempting to access.
Add:
<input type="text" name="rating" value="" id="example-rating-2" />

And change text() to val():
$('#example-rating-2').val(data.rating);

You should see the value change when the stars are clicked. Make the input type hidden when you're done testing...
Comment: Yes that seems to work, but it wont send it to the email
PHP:

    $stars = $_POST['stars'];

    $formcontent="
    Stars: $stars";
Comment: It's in `$_POST['rating']`. Change the input name to `stars` if you want it in `$_POST['stars']`


How to find CDF of $Y=|X|\wedge 2$ with $X\sim Laplace(\lambda)$

Question: Given $X$ a bilateral exponential with density $f_X(x)=\frac{1}{2}e^{-|x|}, \forall x\in \mathbb{R}$ and $\lambda=1$, i have to find CDF of $Y=|X|\wedge 2$.
I know that $Y$ is not a monotonic function, so i can't apply the law of transformation of random variables.
I know that the support of $Y$ is $[0,2]$, so i can write $F_Y(y)=\left\{\begin{matrix}
0 & if & y<0\\
? & if & 0\leq y\leq 2\\
1 & if &y>2
\end{matrix}\right.$
Then:
$F_y(y)=P(Y\leq y)=P(|X|\wedge 2\leq y)=...$
How can I continue?
Comment: Remember $\lvert X\rvert\wedge 2=\min(\lvert X\rvert,2)$, so this is $\leq y$ when $\lvert X\rvert\leq y$ (since $y\leq 2$).
Answer: You are doing this for $0\leq y\leq 2$ so $|X|\wedge2\leq y$ is the same statement as $|X|\leq y$.
That means that you can continue with:$$\cdots=P(|X|\leq y)=\cdots$$
Comment: Thanks for your answer, again! So: $P(|X|\wedge 2\leq y)=P(|X|\leq y)=P(-y\leq |X|\leq y)=\int_{-y}^{y}f_X(x)dx=\int_{-y}^{0}f_X(x)dx+\int_{0}^{y}f_X(x)dx=(\frac{1}{2}-\frac{1}{2}e^{-y})+(-\frac{1}{2}e^{-y}-\frac{1}{2})=-e^{-y}$.         But solution says that $F_Y(y)=\left\{\begin{matrix}
0 & if & y\leq 0\\
1-e^{-y} & if & 02
\end{matrix}\right.$ Where I wrong?
Comment: I've bisected $|x|=\left\{\begin{matrix}x & for & x\geq0\\ -x & for & x< 0\end{matrix}\right.$. So I obtain $\int_{-y}^{0}\frac{1}{2}e^{-|x|}dx=\int_{-y}^{0}\frac{1}{2}e^{x}dx=\frac{1}{2}[e^x]_{-y}^0=\frac{1}{2}-\frac{1}{2}e^{-y}$ and $\int_{0}^{y}\frac{1}{2}e^{-|x|}dx=\int_{0}^{y}\frac{1}{2}e^{-x}dx=\frac{1}{2}[-e^x]_{0}^y=-\frac{1}{2}e^{-y}-\frac{1}{2}$.
Comment: You forgot a minus sign in e-power in last line: $\int_0^y\frac12e^{-x}dx=\frac12[-e^{-x}]^y_0=\frac12(1-e^{-y})$
Comment: Sure, I was wrong to transcribe. I edit!


What is the typical size of feature matrix for xgboost

Question: In other words, I have a binary classification problem with million samples and around 1000 features. I am trying to understand wheather I should subsample the dataset and add a feature selection step (and approximately how many features I should retain)
Comment: If you feel it too slow, maybe you can try Lightgbm. Similar model to xgboost, but can be like 10 times faster
Comment: with a million samples, 1000 features is fine. No need for feature selection, since xgboost kind of takes care of that in the boosting framework.
Comment: Isn't 1000 features too much for tree based learning?  It takes a long time currently to train ...
Answer: The typical number of features is the number of features that you think are relevant. No more, no less.
It might be possible to tabulate the number of features used in every XGBoost model, and compute descriptive statistics of that data, but this is folly -- there's also an average telephone number, but no one's suggesting that you should call it.
People derive features and estimate models to solve particular problems. What does oncology have to do with the price of tea?


Why is my host not receiving packets sent across tun0?

Question: I have a tun0 interface set up which allows packets to be sent as such:
HOST (aaaa::1) ----> tun0 ----> SLIP ----> Router (aaaa::200:0:0:1)
The router receives the packets, and can send back a webpage (it has a small webserver on it), which I can then see in a browser on the host, and in wireshark:
3205    2129.960625056  aaaa::1 aaaa::200:0:0:1 TCP 80  49192 → 80 [SYN] Seq=0 Win=28800 Len=0 MSS=1440 SACK_PERM=1 TSval=579845 TSecr=0 WS=128
3206    2129.977020758  aaaa::200:0:0:1 aaaa::1 TCP 64  80 → 49192 [SYN, ACK] Seq=0 Ack=1 Win=48 Len=0 MSS=48
3207    2129.977056613  aaaa::1 aaaa::200:0:0:1 TCP 60  49192 → 80 [ACK] Seq=1 Ack=1 Win=28800 Len=0

HOWEVER, when I try to do the following:
Router (aaaa::200:0:0:1) ----> SLIP ----> tun0 ----> HOST (aaaa::1)
The host doesn't receive the packets (UDP).  I have wireshark set up to capture on tun0, and I can see that the packets make it to the interface...
2164    454.682603267   aaaa::200:0:0:1 aaaa::1 UDP 73  8765 → 5678  Len=25

However, when I use netcat to monitor [aaaa::1]:5678, I can't see any packets arriving.
I'm fairly convinced this is something to do with how the routes and forwarding have been set up on the tun interface, but I don't know enough about it to figure this out.
Here is the output when the tunslip interface is set up:
slip connected to ``127.0.0.1:60001''
opened tun device ``/dev/tun0''
ifconfig tun0 inet `hostname` mtu 1500 up
ifconfig tun0 add aaaa::1/64
ifconfig tun0 add fe80::0:0:0:1/64
ifconfig tun0

tun0      Link encap:UNSPEC  HWaddr 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00
          inet addr:127.0.1.1  P-t-P:127.0.1.1  Mask:255.255.255.255
          inet6 addr: fe80::1/64 Scope:Link
          inet6 addr: aaaa::1/64 Scope:Global
          UP POINTOPOINT RUNNING NOARP MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:500
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)

And this is the output from ip route show table local:
broadcast 127.0.0.0 dev lo  proto kernel  scope link  src 127.0.0.1
local 127.0.0.0/8 dev lo  proto kernel  scope host  src 127.0.0.1
local 127.0.0.1 dev lo  proto kernel  scope host  src 127.0.0.1
local 127.0.1.1 dev tun0  proto kernel  scope host  src 127.0.1.1
broadcast 127.255.255.255 dev lo  proto kernel  scope link  src 127.0.0.1
broadcast 172.23.0.0 dev wlx0013ef1b001c  proto kernel  scope link  src 172.23.251.64
local 172.23.251.64 dev wlx0013ef1b001c  proto kernel  scope host  src 172.23.251.64
broadcast 172.23.255.255 dev wlx0013ef1b001c  proto kernel  scope link  src 172.23.251.64

Answer: So this is fairly embarrassing, but I had forgotten I had configured a firewall on my host machine, which meant all incoming connections were blocked. Turned off the firewall and everything works as it should.


Criação de índice na tabela

Question: Tenho uma tabela que tem 140 campos. Dessa tabela 45 itens são importantes numa consulta. Toda vez que usuário seleciona um item como verdadeiro, meu script monta o SQL de acordo com o solicitado. Nesse caso, devo criar 45 índices na tabela ou não? Os dados estão hoje com char(1) que pode ser S ou N. Mas posso mudar para int do tipo 1 ou O. O que vocês me sugerem? O banco é Mysql.
Comment: 140 campos? Não serão campos a mais para uma tabela só?
Comment: Posso dividir mas vou necessitar desses 45 campos numa tabela. Todos campos são passíveis de consulta
Comment: Quantos registos tem a tabela?
Comment: Ainda estou fazendo a modelagem e fazendo alguns testes de performance e fiquei pensando nesses campos que sempre vou consultar, mas o problema é a quantidade de índices. A tabela pode ter N registros.
Comment: Se a tabela tiver poucos registo (na ordem das centenas) pouco ganha em ter índices. A minha abordagem e começar sempre sem índices. Só quando começo a notar algum lentidão e que os crio e sempre verifico se melhora. Veja esta [resposta](http://pt.stackoverflow.com/a/38388/2541) onde tem algumas considerações acerca disso.
Comment: Qual melhor em desempenho. Um campo var(1) ou int para um índice?
Answer: Sugiro normalizar esta tabela e nas tabelas que surgirem criar os índices somente para os campos que serão usados como condição nas consultas.
Comment: A tabela já esta normalizada. O que posso fazer e dividir pra outra tabela com esses campos chaves. Mas mesmo assim o cliente vai ter a possibilidade de definir quais itens deseja pesquisar. Ele pode definir apenas 1 assim como os 45.
Answer: A sua questão só surge porque a tabela tem 45 colunas que podem ser usadas para limitar a consulta.
Se o problema são essas colunas vamos nos livrar delas.
Se as 45 colunas só podem ter dois valores: "V"|"F" ou 0|1, porquê não tratá-las como bits?
Seguindo esta abordagem as 45 colunas podem ser transformadas em apenas uma.
Cada uma passa a ser representada como um bit numa coluna BIGINT UNSIGNED.
Não sei qual é a linguagem que usa na aplicação que irá tratar os dados das consultas, o código seguinte está em C# mas pode facilmente ser traduzido para qualquer linguagem que permita fazer operações lógicas.
As 45 colunas passarão a existir apenas no programa e serão representadas por outras tantas variáveis do tipo bool.
Para facilitar a explicação cada uma dessas variáveis terá o nome de 'colunaX' onde X representa a posição do bit que lhe é atribuída no BIGINT:
bool coluna0;
bool coluna1;
bool coluna2;
...
...
..
bool coluna44;

Vamos definir dois métodos auxiliares para manipular os bits.
1 - Retorna o valor passado com o bit ON na posição indicada por pos
private ulong TurnBitOn(ulong value, int pos)
{
    return (value | pos);
}

2 - Retorna true se a posição pos em value está ON
private bool IsBitOn(ulong value, int pos)
{
    return (value & (1 << pos)) != 0;
}

Esses dois métodos servirão para:
1 - Calcular o valor a gravar na tabela de acordo com as opções selecionadas:
private ulong GetOptions()
{
    ulong options = 0UL;
    if(coluna0)TurnBitOn(options,0);
    if(coluna1)TurnBitOn(options,1);
    if(coluna2)TurnBitOn(options,2);
    ...
    ...
    if(coluna44)TurnBitOn(options,44);
    return options;
}

2 - "Setar" a variáveis de acordo com o valor que está na tabela:
private SetOptions(ulong options)
{
    coluna0 = IsBitOn(options, 0);
    coluna1 = IsBitOn(options, 1);
    coluna2 = IsBitOn(options, 2);
    ....
    ....
    coluna44 = IsBitOn(options, 44);
}

Com esta abordagem as consultas são feitas apenas sobre uma coluna e, se necessário, à criação de apenas um índice.
Notas:
Os métodos GetOptions() e SetOptions(ulong flags) são apenas um exemplo de implementação.
Caso não seja possível usar valores inteiros de 64 bits, divida as 45 colunas em dois grupos e associe cada grupo a uma coluna na tabela.
Comment: Interessante esse método. Estava pensando em algo pra unir todos. Vou tentar implementar. Só tenho uma dúvida, a posição vai ficar tipo assim 01011100 ...etc. Na tabela eu vou gravar sempre as 45 posições ou só as selecionadas. E como fica na busca SQL? Terei que buscar os resultados com outras condições e salvar na memória. Depois aplicar o conceito num loop e filtrar. Isso?

Criação de índice na tabela


How to set uWSGI loglevel?

Question: I managed to setup uWSGI logging into a file by setting logto = /path/to/logfile. The problem is that logging every single request causes the log file to grow too fast. How can I increase the logging level so that only errors are logged?
Answer: You can use the disable-logging option as shown here.
You might want to also ensure log-4xx and log-5xx are enabled so that you can still see errors.
More info in the docs.

How to set uWSGI loglevel?


What happened to "allow application to interact with desktop" checkbox in cluster manager for server 2008?

Question: The cluster managing software for managing clusters on a windows server 2005 cluster had a checkbox for "allow application to interact with desktop" when creating a generic application resource. This appears to be gone in the management software for server 2008 clusters. Does anyone know where this option, if it still exists, is?
Answer: This option was removed in Server 2008 as a security enhancement. This is because the application runs as the cluster service account which has elevated privileges.
Even in 2003 clusters, the security best practice was to not have this checked.
Comment: Ok, so how does one go about managing permissions on private message queues on a clustered server?

What happened to “allow application to interact with desktop” checkbox in cluster manager for server 2008?


Is it possible to override existing html tags?

Question: So, I tend to write my documents in markdown and I recently discovered that I could create abbreviations in markdown. This is great, but I had already created my own version of the abbreviation tag as I didn't like the way the standard tag looked when rendered. Is there a best practice to overriding existing tags?
The below text is to explain what I am trying to achieve in equivalence to. I cannot modify the markdown parser itself as I host my site on Github pages. For those who want to know how I have my own HTML tag, I use Polymer to create these tags.

Markdown Text:
 Markdown converts text to HTML.

*[HTML]: HyperText Markup Language

Converted Code:

Markdown converts text to HTML.

I want it converted to:

Markdown converts text to <short-text abbr="HTML">HyperText Markup Language</short-text>.

Comment: Have you considered using CSS to make it look the way you want?
Comment: You could use JavaScript.  In particular you could use the jQuery library and call the document.Ready function to manipulate the DOM.
Comment: @NiettheDarkAbsol I have in the past when I created the tag, however, I [lose a lot of control over how my tag functions](https://stackoverflow.com/questions/1682714/can-an-abbr-tags-title-be-styled).
Answer: If it's all simple text, and you're doing this to all abbr tabs, you can simply build a new element and replace the old one.
With jQuery (for simplicity):
jQuery("abbr").each(function() {
    var title = jQuery(this).attr("title");
    var text = jQuery(this).text();
    var $new = jQuery("<short-text></short-text>").attr("abbr", text).html(title);
    jQuery(this).replaceWith($new);
});

Answer: After the page is loaded and the Markdown is parsed, try something like this (supported in ES5, nothing external required for supporting browsers):
document.querySelectorAll('abbr').forEach(function(el) {
  var newEl = document.createElement('shortText');
  newEl.setAttribute('abbr', el.innerHTML);
  newEl.innerHTML = el.getAttribute('title');
  el.parentNode.replaceChild(newEl, el);
});


Wordpress FAQ Schema Markup Not Showing

Question: There are 2 examples on Google Search Central.
I don't know much about javascript or JSON-LD so I have put the second code (Micro Data) on the bottom of my Wordpress template file (HTML).

    Frequently Asked Questions(FAQ)

What is the return policy?

        Most unopened items in new condition and returned within 90 days will receive a refund or exchange. Some items have a modified return policy noted on the receipt or packing slip. Items that are opened or damaged or do not have a receipt may be denied a refund or exchange. Items purchased online or in-store may be returned to any store.

Online purchases may be returned via a major parcel carrier.  Click here  to initiate a return.

How long does it take to process a refund?

        We will reimburse you for returned items in the same way you paid for them. For example, any amounts deducted from a gift card will be credited back to a gift card. For returns by mail, once we receive your return, we will process it within 4–5 business days. It may take up to 7 days after we process the return to reflect in your account, depending on your financial institution's processing time.

What is the policy for late/non-delivery of items ordered online?

      Our local teams work diligently to make sure that your order arrives on time, within our normal delivery hours of 9AM to 8PM in the recipient's time zone. During  busy holiday periods like Christmas, Valentine's and Mother's Day, we may extend our delivery hours before 9AM and after 8PM to ensure that all gifts are delivered on time. If for any reason your gift does not arrive on time, our dedicated Customer Service agents will do everything they can to help successfully resolve your issue.

Click here to complete the form with your order-related question(s).

When will my credit card be charged?

      We'll attempt to securely charge your credit card at the point of purchase online. If there's a problem, you'll be notified on the spot and prompted to use another card. Once we receive verification of sufficient funds, your payment will be completed and transferred securely to us. Your account will be charged in 24 to 48 hours.

Will I be charged sales tax for online orders?

      Local and State sales tax will be collected if your recipient's mailing address is in:

Arizona

California

Colorado

However, when I checked my post url in Rich Results Test, it said there was no FAQ markup detected. Of course, the  tags and contents showed up 'cause they are HTML. As far as I know, JavaScript doesn't show contents visually to readers. Then, should I use both codes (JSON-LD + Micro Data) inside of my template file? Also, if it is needed, can I put JavaSript codes bottom of my template file? Sadly, there isn't much explanation how to use the code. Here is JSON-LD code from Google Search Central.

    <title>Example Site - Frequently Asked Questions(FAQ)</title>

Answer: Sorry for asking myself and answering myself haha. It worked! If you want to use FAQ schema markup, you need to write your own schema codes based on the Google Search Central examples and put the codes into your template file. You can also put JavaScript codes below the HTML codes.  I hope someone who has similar question would be helped and save his/her time!

Wordpress FAQ Schema Markup Not Showing


How to make a php curl / POST processing url?

Question: What I'm trying to ask is a url on which any one can POST variables on to it. How can I create a PHP page which can accept variables sent via post, sent either through curl or by form post or whatever.
Can I just accept variables sent via post just by using
$_POST['varible']

so that If someone post a 'variable' to my url,will I be able to get it
Comment: that's how it works. just set up a simple php test file with a form and you can test sending variables over GET/POST
Comment: if the client uses curl to post,will this solution works?
Comment: If client's use curl, they have to specify the curl_setopt($ch,CURLOPT_POSTFIELDS, $poststring);
Comment: At my end,I just have to use $_POST[''] to accept those variables even if client uses curl or any POST methods right
Answer: <?php
if (isset($_POST['submit'])) { //Check if the submit button is pressed.
    $field1 = $_POST['field1']; //Take the post data of "field1" from the form.
    $field2 = $_POST['field2']; //Take the post data of "field2" from the form.
    echo "$field1 $field2"; //Echo the fields.
}
?>
<form method="post">
<input type="text" name="field1" placeholder="Field 1">

<input type="text" name="field2" placeholder="Field 2">

<input type="submit" name="submit" value="Send Data">
</form>

Comment: I just not only asking about the form.What if if curl is used.How will I get the values?Is it the same as how we do for form?
Answer: Yes you can accept the value using $_POST.form datas which are posted to a php is recieved using what you said


Displaying other webpage using cURL request

Question: I want to display other webpages on the website using cURL. I am not working with iframes because they do not work in a lot of cases.
I can make the pages to display using cURL using the following code.
    $result=query("SELECT url FROM links WHERE l_id='$linkId'");

$url =$result[0]["url"];
$ch = curl_init();

// set a single option...
// ... or an array of options
curl_setopt_array(
    $ch, array(
    CURLOPT_URL => $url,
    CURLOPT_RETURNTRANSFER => true

));

// execute
$output = curl_exec($ch);

But in most of the url's sometime the css file or other images do not load.
I get a 403 forbidden error. What can i do to make these errors go away in most of the cases.
I am opening a host of URL's. Again don't want to open it in a iframe. Or is there another method I could use.
Comment: You're trying to scrape the content from web sites and they're sending you messages saying they don't want you to do that. Take the hint.
Comment: I tried your code with your backlino.com URL and I got the website rather than a 403 error. It could be that you're IP has been blacklisted for too many attempts
Comment: @JamieBicknell how do u do that from user's website?
Comment: Guys first of all i am developing a authentic service, i want to enable users to annotate the article once i get it back, so if you have any other suggestion regarding how i can do this let me know. @JamieBicknell . I get the website but some images are missing, You can see the console, some elements are missing, and all of them have absolute paths.
Comment: I never implied anything, just provided an example as to why you'd be receiving 403's
Answer: they have used related path for css and images. So you could add domain URL with  the image url.
Example,

 Like this.
 <img src="<?php echo $url;?>/img1.jpg">

Comment: Thanks selvan for the reply but the images for which i am getting a 403 error already have a absolute path http://backlinko.com/wp-content/uploads/2014/09/viral-marketing-case-study-image.png
Answer: The website in your example appears to have a HTACCESS rule to prevent hotlinking, this is done by the website checking the referrer.
You can add a CURL option to spoof the referrer like so:
curl_setopt($ch, CURLOPT_REFERER, 'http://backlinko.com/');

Comment: I tried this solution but still get a lot of 403 errors for images in the wpcontent folder. Can i make any other changed to my cURL request
Comment: Can you give specific examples? I've tried the example image URL you've provided in the other comment and it's working. I can only assume my original comment is the most likely and that your IP has been blacklisted for too many requests.
Comment: I cant be blacklisted, I have made not more than 20 requests on this URL. And without the cURL the page opens perfectly. Here are some of the errors i am getting in my console for example, http://backlinko.com/wp-content/themes/backlinko/library/images/backlinko.png ,  http://backlinko.com/wp-content/uploads/2014/09/viral-marketing-case-study-image.png . Your console has no errors?
Comment: Have you tried setting the user agent to a generic browser like Chrome?
Comment: You may not be blacklisted, but you could be getting rate limited. The reason I suspect this is the case is because I have no trouble in fetching all of your example URLs via my console's CURL and PHP's CURL. So the only difference between my requests and your requests are the IP address.
Comment: Yes i have set the user agent to a generic browser, can you share the cURL request you are using
Comment: It's exactly the same as your code example in your question.


Paypal Refund Rest Api v2 - Authorization failed due to insufficient permissions

Question: I am able to successfully execute below APIs
<code>/v2/checkout/orders
/v2/checkout/orders/{order_id}/authorize
/v2/checkout/orders/{order_id}/capture
</code>
Why am I getting the "NOT_AUTHORIZED" response while executing PayPal refund as described here? -  https://developer.paypal.com/docs/api/payments/v2/#captures_refund
POST request
<code>https://api.sandbox.paypal.com/v2/payments/captures/<Capture ID I got from capture request>/refund
</code>
Response
<code>    {
    "name": "NOT_AUTHORIZED",
    "message": "Authorization failed due to insufficient permissions.",
    "debug_id": "6c6xxxxx6c",
    "details": [
        {
            "issue": "PERMISSION_DENIED",
            "field": "capture_id",
            "value": "XXXXXXXXX",
            "description": "You do not have permission to access or perform operations on this resource.",
            "location": "path"
        }
    ],
    "links": [
        {
            "href": "https://developer.paypal.com/docs/api/v2/payments/#NOT_AUTHORIZED",
            "rel": "information_link"
        }
    ]
}
</code>
Comment: Sumeet, are you still facing the problem? As long as you make the call with the client_id + secret_id combination (just as you made the capture call); you should not face this issue. If you are still facing this issue; please revert back with the paypal-debug-id and we will take a look.
Comment: @TriniGeorge By default client ID doesn't have refund permission. I raised a ticket to technical support and they gave permission to my client ID and now it works.
Answer: You have to contact the PayPal support to add permission for your existing ClientId and Client secret (which works fine for PayPal V1 APIs) for V2 Refunds and Cancel request and there is no other way you can set the permission for same.
If you need to avoid this then Just create new ClientId and Client secret from PayPal accounts and it will work fine with PayPal V2 APIs.
Comment: Unfortunately this does not help. Only way seems to contact the support.
Comment: This helped me, I just needed to create new API keys..... :(
Comment: I did not manage to find this documented anywhere having spent a day trying to debug this issue. Creating a new key set worked. Thank you !
Answer: Creating a new application with a new set of client ID and secret worked for me.
Comment: it solve my problem. my problem is  https://api-m.sandbox.paypal.com/v1/shipping/trackers   Authorization failed due to insufficient permissions


How do I change order of completion rules in checkout?

Question: How do I change the order in which completion rules fire?
There is a default Completition reaction rule. I wanted to add a second rule which executes some custom PHP but it's never executed.
I see no way to change the weight as in other rules. I also tried adding what I need as an action in that default rule, but it also doesn't seem to fire.
This is the reaction rule that fires on order completion.
{ "rules_completion" : {
    "LABEL" : "completion",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "php", "rules", "commerce_checkout" ],
    "ON" : [ "commerce_checkout_complete" ],
    "DO" : [
      { "php_eval" : { "code" : "jch_send_quote()" } },
      { "commerce_checkout_complete" : { "commerce_order" : [ "commerce_order" ] } }
    ]
  }

This is the code for jch_send_quote() which doesn't seem to fire.
function jch_send_quote(){
    global $user;
    watchdog('dev', 'jch_send_quote running here');
    drupal_set_message($user->uid);
        die('jch_send_quote running here')
}

What am I missing?
Comment: Added Rule and php to question. Any ideas?
Comment: This really doesn't seem to have anything to do with the Rules module. If the commerce_checkout_complete event is not firing, that's a problem with Commerce or with your expectations. Commerce defines that event and decides when to fire it. You can test this event by using a rule which just has that event and a "Show a message on the site" action - if you don't see this message on the site when you expect that means the event is not firing, and you need to investigate what circumstances that event is supposed to fire to determine what you should expect here.
Answer: You should be able to edit the rule and set it's weight:

Screenshot, showing reaction rule with weight of "2"
Lastly, your rule should still fire, even with a different weight. If it's not firing, it's probably an issue with that rule itself.
Comment: The weight should save and be non-zero if set as such. If that's not the case, something else is broken there. In regards to debug, you could try watchdog. e.g `watchdog('dev', 'code running here');` then check in admin > reports > recent log entries
Comment: First, I can change the Weight inside the Reaction Rule edit form, but when I save and return to the Rules View, every Rule appears with a Weight of 0... at least those in 'Completion' for Commerce. Second, I -thought- that all the Reaction Rules should fire. I simply added a die() message and it never 'dies' or displays. Is there a fool-proof way to see if/when my code is firing? I'm on a shared host without Devel. Thanks again.  ---JC
Comment: Thanks. I tried watchdog() and nothing is appearing in the recent log entries. Any other ideas on what could be going on?
Comment: You would need to post your code / rule and relevant conf there, else is just guesswork.
Comment: I added code and rule above. Although I think now this is a conceptual issue. The completion rule is -never- firing... which I don't understand. Can you recommend a tutorial or doc which explains this process?


Is there a way to capture all FormClosed event in C# within an application automatically?

Question: I would like to centralize code handler for all FormClosed Event, is there a way to be notified automatically by all forms that are closing ?
Answer: Subclass Form and in the constructor hook up some function to the FormClosed event of itself? Something like the following:
public class MyForm : Form
{
    public MyForm(FormClosedEventHandler handler) : base()
    {
        this.FormClosed += handler;
    }
}

And then just use MyForm instead of Form as your baseclass for all your forms.
EDIT: If you've got some static function somewhere that you want to use as a handler for all FormClosed events, then you can of course use:
    public MyForm() : base()
    {
        this.FormClosed += Program.MyFormClosedHandler;
    }

But this is a little bad (hard to test, see dependency injection), and you can use constructor chaining to achieve the same thing anyway.
Comment: Hello good solution, I don't know why it works for me when I create a simple example but it doesn't seem to work on my real world app, will have to investigate why.
Comment: Have you changed all the forms in app to use `MyForm` or whatever you called it insteaed of `Form`?
Answer: subscribe your event handler after you instantiate the form. i.e. use +=
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace Craft
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            var f = new Form2();
            f.FormClosing += ClosingMonitorer;
            f.Show();

            var g = new Form3();
            g.FormClosing += ClosingMonitorer;
            g.Show();
        }

        void ClosingMonitorer(object sender, FormClosingEventArgs e)
        {
            MessageBox.Show((sender as Form).Text + " is closing");
        }

    }
}

[EDIT: or you can use extension methods to simplify the event subscription process]
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace Craft
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            var f = new Form2();
            f.Show(ClosingMonitorer);

            var g = new Form3();
            g.Show(ClosingMonitorer);

        }

        void ClosingMonitorer(object sender, FormClosingEventArgs e)
        {
            MessageBox.Show((sender as Form).Text + " is closing");
        }

    }

    public static class Helper
    {
        public static void Show(this Form f, FormClosingEventHandler feh)
        {
            f.FormClosing += feh;
            f.Show();
        }
    }
}

Answer: There isn't an easy way that I am aware of, but if you want to learn some new techniques you could do it with aspect-oriented programming.
Comment: Why is this a comment on your own answer and not mine? As for needing to handle this case, let the original author say if this is a concern for him. If it is, then you start to dig into message loop filters which will handle your case. But it's a little overkill if you don't need to handle every single little form like common dialogs and message boxes.
Comment: Extending the Form object won't help you with Forms which are not part of your application (OpenFileDialog for instance)


Action depend select option value selected?

Question: I need to change color of select box and its row depending on selected value of select box. Like i have tried there is 3 select box and 3 option selected on each combo.
How can i make color change on each option  selected on each select box?

.row {
  padding: 10px 20px;
  background: purple;
}

select {
  width: 100px;
  height: 40px;
  background: #eee;
  border: 1px solid #333;
}

    <select id="impSelect">
      <option value="primary" selected>Primary</option>
      <option value="secondary">Secondary</option>
      <option value="optional">Optional</option>
    </select>

    <select id="impSelect">
      <option value="primary">Primary</option>
      <option value="secondary" selected>Secondary</option>
      <option value="optional">Optional</option>
    </select>

    <select id="impSelect">
      <option value="primary">Primary</option>
      <option value="secondary">Secondary</option>
      <option value="optional" selected>Optional</option>
    </select>

Actually i want result like this?
About custom select box i will manage. Its all about adding specific class for different color.
Comment: About custombox i will manage. I just need to add specific class depending on select option selected.
Answer: Keep a color dict and accordingly change color on change of select box. Below is the sample code:

var color = {'primary':'red', 'secondary': 'blue', 'optional':'gray'};

$('.impSelect').click(function(){
$(this).css('background-color', color[$(this).val()]);
});
$('.impSelect').click();
.row {
  padding: 10px 20px;
  background: purple;
}

select {
  width: 100px;
  height: 40px;
  background: #eee;
  border: 1px solid #333;
}

    <select id="impSelect" class="impSelect">
      <option value="primary" selected>Primary</option>
      <option value="secondary">Secondary</option>
      <option value="optional">Optional</option>
    </select>

    <select id="impSelect" class="impSelect">
      <option value="primary">Primary</option>
      <option value="secondary" selected>Secondary</option>
      <option value="optional">Optional</option>
    </select>

    <select id="impSelect" class="impSelect">
      <option value="primary">Primary</option>
      <option value="secondary">Secondary</option>
      <option value="optional" selected>Optional</option>
    </select>

Comment: Its very cool brow... Can we make via adding class on parent? And thanks for helping me out.
Answer: Do the addClass when change the function of the select button.For adding class to the parent .Target the row class using closest() jquery function

$('.row').on('change','select',function(){
$(this).attr('class','').addClass($(this).val()).closest('.row').attr('class','row').addClass($(this).val())
})
$(function(){
$('.row select').each(function(){
$(this).attr('class','').addClass($(this).val()).closest('.row').attr('class','row').addClass($(this).val())
})
})
.row {
  padding: 10px 20px;
  background: purple;
}

select {
  width: 100px;
  height: 40px;
  background: #eee;
  border: 1px solid #333;
}
.primary{
background-color:red;
}
.optional{
background-color:blue;
}
.secondary{
background-color:#aaa;
}

    <select id="impSelect">
      <option value="primary" selected>Primary</option>
      <option value="secondary">Secondary</option>
      <option value="optional">Optional</option>
    </select>

    <select id="impSelect">
      <option value="primary">Primary</option>
      <option value="secondary" selected>Secondary</option>
      <option value="optional">Optional</option>
    </select>

    <select id="impSelect">
      <option value="primary">Primary</option>
      <option value="secondary">Secondary</option>
      <option value="optional" selected>Optional</option>
    </select>

Answer: One of the ways of doing so would be to bind a change event handler to the targeted select elements. In the snippet below I have bound to all select elements, but you can select them through a CSS class or through descendent selectors.
Then, you can define CSS classes to give required styles to the select. In the snippet, I have kept the CSS class names equal to the intended value of the select. Hence adding a class primary to the select would apply red background and white color.
select.primary {
  background-color: red;
  color: white;
}

So when the value in the select change, you just remove existing classes on it, and apply the new class.

$("select").on("change", function() {
  // Remove the other classes.
  $(this).attr("class","");

  // Add the new class as per the value selected.
  var value = $(this).val();
  $(this).addClass(value);
});

// Apply the colors initially.
$("select").each(function(){
  var value = $(this).val();
  $(this).addClass(value);
});
.row {
  padding: 10px 20px;
  background: purple;
}

select {
  width: 100px;
  height: 40px;
  background: #eee;
  border: 1px solid #333;
}

select.primary {
  background-color: red;
  color: white;
}

select.secondary {
  background-color: purple;
  color: white;
}

select.optional {
  background-color: gray;
}

    <select id="impSelect">
      <option value="primary" selected>Primary</option>
      <option value="secondary">Secondary</option>
      <option value="optional">Optional</option>
    </select>

    <select id="impSelect">
      <option value="primary">Primary</option>
      <option value="secondary" selected>Secondary</option>
      <option value="optional">Optional</option>
    </select>

    <select id="impSelect">
      <option value="primary">Primary</option>
      <option value="secondary">Secondary</option>
      <option value="optional" selected>Optional</option>
    </select>

Answer:
Declare colors in your stylesheet with the same classes as the name of select options. For eg.
.mandatory { background: red; color: white;}
.optional { background: purple; color: white;}
Assign the class on select change using jQuery
$(document).ready(function(){
   $('select').on('change', function(){
      var thisSelect = $(this);
      var optionSelected = thisSelect.find("option:selected");
      var optionName = optionSelected.attr('value');
      thisSelect.removeClass().addClass(optionName);
   });
});
Answer: You can achieve this using javascript (jQuery's) change event on select and use closest() for parent selection, like:
$('select').on('change', function() {
  var value = $(this).find(':selected').text();
  if(value == 'Primary') {
    $(this).parent().closest('.row').addClass('primary');
    $(this).parent().closest('.row').removeClass('secondary optional');
  } else if(value == 'Secondary') {
    $(this).parent().closest('.row').addClass('secondary');
    $(this).parent().closest('.row').removeClass('primary optional');
  } else {
    $(this).parent().closest('.row').addClass('optional');
    $(this).parent().closest('.row').removeClass('primary secondary');
  }
});

Have a look at the working snippet below:

$('select').each(function() {
  var text = $(this).find(':selected').text();
  if(text == 'Primary') {
    $(this).parent().closest('.row').addClass('primary');
    $(this).parent().closest('.row').removeClass('secondary optional');
  } else if (text == 'Secondary') {
    $(this).parent().closest('.row').addClass('secondary');
    $(this).parent().closest('.row').removeClass('primary optional');
  } else {
    $(this).parent().closest('.row').addClass('optional');
    $(this).parent().closest('.row').removeClass('primary secondary');
  }
});

$('body').on('change', 'select', function() {
  var value = $(this).find(':selected').text();
  if(value == 'Primary') {
    $(this).parent().closest('.row').addClass('primary');
    $(this).parent().closest('.row').removeClass('secondary optional');
  } else if(value == 'Secondary') {
    $(this).parent().closest('.row').addClass('secondary');
    $(this).parent().closest('.row').removeClass('primary optional');
  } else {
    $(this).parent().closest('.row').addClass('optional');
    $(this).parent().closest('.row').removeClass('primary secondary');
  }
});

$('#btnAddEmpField').on('click', function(){
 $('.emp-customize-form').append("
\

\
    <select id='impSelect1'>\
      <option value='primary'>Primary</option>\
      <option value='secondary' selected>Secondary</option>\
      <option value='optional'>Optional</option>\
    </select>\

\

");
})

.row {
  padding: 10px 20px;
  background: purple;
}

select {
  width: 100px;
  height: 40px;
  background: #eee;
  border: 1px solid #333;
}

.primary {
  color: white;
  background-color: red;
}

.secondary {
  color: white;
  background-color: green;
}

.optional {
  color: white;
  background-color: blue;
}

      <select id="impSelect1">
        <option value="primary" selected>Primary</option>
        <option value="secondary">Secondary</option>
        <option value="optional">Optional</option>
      </select>

      <select id="impSelect2">
        <option value="primary">Primary</option>
        <option value="secondary" selected>Secondary</option>
        <option value="optional">Optional</option>
      </select>

      <select id="impSelect3">
        <option value="primary">Primary</option>
        <option value="secondary">Secondary</option>
        <option value="optional" selected>Optional</option>
      </select>

add

Hope this helps!
Comment: yea, it helps me a lot..

Thanks bro
Comment: Its my pleasure @Kumar
Comment: yes, it works i need to add row on click on add button too. I have added script for append row on click add button but its not working on appended row. http://jsfiddle.net/7jznjqax/1/
Comment: can you help me bro?
Comment: @Kumar I've updated my code, please have a look or see the updated fiddle - http://jsfiddle.net/7jznjqax/2/ . Please let me know if this works?
Comment: Yes, its working.. Thanks a lot
I accept your answer and thumbs up


Smarter example of biased but consistent estimator?

Question: I am trying to get an intuitive understanding of why there exists biased but consistent estimator.
Suppose $X_i \sim \mathcal{N}(\mu, 1)$. One example I came across is this:
$$W_n(X_1,\cdots,X_n) = \frac{1}{n} \sum_{i=1}^n X_i + \frac{1}{n}$$
I see that $W_n$ is biased due to the $\frac{1}{n}$ term, but is consistent. However, I feel that this example is somewhat "silly" because few people would use $W_n$ to estimate $\mu$.
Do we have any other example of biased but consistent estimator $W_n$, where people are more likely to use it?
Comment: Many commonly-used estimators are biased but consistent, for example, the MLE of the two parameters of the Negative Binomial distribution, or, for that matter, the method-of-moments estimator of same.
Answer: Here's a straightforward one.
Consider a uniform population with unknown upper bound
$$ X \sim U(0, \theta) $$
A simple estimator of $\theta$ is the sample maximum
$$ \hat \theta = \max(x_1, x_2, \ldots, x_n) $$
This is a biased estimator.  With a little math you can show that
$$ E[\hat \theta] = \frac{n}{n+1} \theta $$
Which is a little smaller than $\theta$ itself.
This also shows that the estimator is consistent, since $\frac{n}{n+1} \rightarrow 1$ as $n \rightarrow \infty$.
An natural unbiased estimator of the maximum is twice the sample mean.  You can show that this unbiased estimator has much higher variance than the slightly biased on above.
Comment: Strictly speaking, we would also need the variance of the maximum (and show that it tends to zero) to establish consistency.
Answer: A very commonly used consistent but biased estimator used is that of the estimated standard deviation.
If we are looking at a simple situation in our data is distributed as $x_i \sim N(\mu, \sigma^2)$, then sometimes the MLE estimate of $\sigma$ is used, ie
$\hat \sigma^2 =
\frac{1}{n} \sum_{i = 1}^n (x_i - \bar x)^2$
This is, of course, a biased but consistent estimator of the variance. Some people may try to account for this bias by using
$\hat s^2 =
\frac{1}{n-1} \sum_{i = 1}^n (x_i - \bar x)^2
$
which is now unbiased for $\sigma^2$...but people don't usually look at variances, they usually look at standard deviations! Jensen's inequality will tell us that if $\hat s^2$ is an unbiased estimator of $\sigma^2$ with positive variance, then $E[s] > \sqrt{E[s^2]}$...so even though we had a unbiased estimator for $\sigma^2$, by taking the square root of this estimator, we now have a biased estimator for $\sigma$!
More generally (and stated without proof), it is very common that MLE estimates of variance components will be downwardly biased but consistent. Hopefully, this bias is ignorable; in the example above, we can see that the fix is almost inconsequential for decent sized $n$. However, if the number of parameters estimated becomes very large, it is quite possible that this bias can be especially problematic; this manifests itself as overfitting.


SQL Left Join - menor data maior do que data actual

Question: 3 tabelas: Processo, Evento, Alerta
O objectivo é fazer uma consulta que devolva todos os processos acrescentando as colunas do tipo de evento e data do evento mais recente MAX(DataEvento) e o próximo alerta (menor data maior do que a data actual) e observações do alerta.
SELECT p.id
      ,p.scope
      ,p.entrydate
      ,p.applicant
      ,p.status
      ,MAX(ev.eventdatetime) lastevent
      ,ev.type
      ,ev.eventobs
      ,MIN(al.deadlinedate) nextalert
      ,al.alertobs
  FROM process p
  LEFT JOIN event ev
    ON ev.processid = p.id
  LEFT JOIN alert al
    ON al.eventid = ev.eventid
   AND al.expiredate > getdate()
 GROUP BY p.id
         ,p.scope
         ,p.entrydate
         ,p.applicant
         ,p.status
         ,ev.type
         ,ev.eventobs
         ,al.expiredate
         ,al.alertobs

O código acima repete todos os processos várias vezes, consoante o número de eventos.
    SELECT p.id
      ,p.scope
      ,p.entrydate
      ,p.applicant
      ,p.status
      ,MAX(ev.eventdatetime) lastevent
      ,ev.type
      ,ev.eventobs
      ,MIN(al.deadlinedate) nextalert
      ,al.alertobs
  FROM process p
 INNER JOIN event ev
    ON ev.processid = p.id
 INNER JOIN alert al
    ON al.eventid = ev.eventid
 WHERE ev.processid = p.id
   AND a.expiredate > getdate()
 GROUP BY p.id
         ,p.scope
         ,p.entrydate
         ,p.applicant
         ,p.status
         ,ev.type
         ,ev.eventobs
         ,al.alertobs

Lista apenas um processo, aquele que tem o evento mais recente.
SELECT DISTINCT p.id
               ,p.scope
               ,p.entrydate
               ,p.applicant
               ,p.status
               ,(SELECT TYPE
                      ,MAX(ev.eventdatetime) lastevent
                      ,eventobs
                  FROM event ev
                 WHERE ev.processid = p.id
                 GROUP BY TYPE
                         ,eventobs)
               ,(SELECT MIN(a.expiredate) nextalert
                      ,alertobs
                  FROM event ev
                 INNER JOIN alert a
                    ON ev.eventid = a.eventid
                 WHERE ev.processid = p.id
                   AND a.expire > getdate())
  FROM process p
 ORDER BY p.id ASC

Aqui dá o erro:

Only one expression can be specified in the select list when the
  subquery is not introduced with EXISTS.

O que pretendo é listar todos os processos cada um aparece uma única vez e são apresentados os campos do query, acrescentando a data, tipo e observações do último evento e a data e observações do próximo alerta, exemplo:
1|Registo|21/06/2018|João Sousa|Activo|21/06/2018|Entrada do processo|Observações do evento|26/06/2018|Prazo para resposta

2|Pedido|21/06/2018|Pedro Antunes|Activo|21/06/2018|Entrada do processo|Observações do evento|26/06/2018|Prazo para resposta

Comment: passa a estrutura das tabelas por favor
Comment: As tabelas são maiores na verdade, simplifiquei aqui para colocar a questão...
Comment: olha esse: https://www.db-fiddle.com/f/xzzMqmDGQe6TXFg9LchNqw/0
Comment: Sim, lista correctamente, no entanto trata-se de T-SQL e não tem a questão do alerta. O alerta está associado ao evento e cada evento pode ter 1 ou vários alertas, preciso listar a menor data do alerta maior do que a data actual. Vou tentar adaptar essa solução, creio que estes detalhes causam alguma confusão na sintaxe, quando conseguir coloco aqui
Answer: Só usar SubSelect:
SELECT
    p.Id,
    p.Scope,
    p.EntryDate,
    p.Applicant,
    p.Status,
    (SELECT
         MAX(ev.EventDateTime)
     FROM event ev
     WHERE ev.processId = p.id) as evento_recente,
    (SELECT
         MIN(a.ExpireDate)
     FROM event ev
     INNER JOIN Alert a ON ev.eventid = a.eventId
     WHERE ev.processId = p.id) as proximo_alerta
FROM Process p

Comment: Perfeito, só faltou comparar a data com a data actual nesta linha: (Select MIN(a.ExpireDate) from event ev inner join Alert a on ev.eventid = a.eventId where ev.processId = p.Id and a.ExpireDate > GETDATE()) as proximo_alerta. Obrigado
Comment: Quando tento carregar outras colunas do evento ou do alerta seleccionados dá o seguinte erro: Only one expression can be specified in the select list when the subquery is not introduced with EXISTS. Como posso ultrapassar isso?
Comment: tem que ver sua query, parece erro de sintaxe
Comment: Com left join consigo reunir todas as colunas que pretendo, no entanto, repete o mesmo processo para cada evento em vez de mostrar apenas o último. Modificando o subquery que sugeriu antes para incluir as restantes colunas que pretendo dá o erro que referi. A lógica parece estar correcta, provavelmente é um problema de sintaxe sim, mas estou com dificuldade em resolver apesar de já ter consultado vários exemplos aparentemente semelhantes
Comment: @OMB edite sua pergunta, coloque como está sua query agora e um exemplo dos dados que estão retornando, e um exemplo de como deveriam retornar
Comment: Editado. A solução do subquery que sugeriu antes serve perfeitamente desde que consiga adicionar também o tipo e observações do evento e as observações do alerta, mas não estou a acertar com a sintaxe para o fazer.
Comment: @OMB vc não colocou um exemplo de como os dados estão... mas acho que é só usar o `Distinct` : `SELECT DISTINCT
    p.Id,` ...
Comment: Supondo que há n eventos no processo 1, esse processo é listado n vezes, uma para cada evento. Já tentei usar o Distict, não funciona...
Comment: veja se é o mesmo problema: https://pt.stackoverflow.com/q/308450/69359
Comment: Exacto, o mesmo problema, vou ver se alguma solução serve para mim
Answer: Poderão ser necessários pequenos ajustes pois ainda não testei se as datas carregadas são sempre as correctas, mas nunca será muito diferente da lista que obtenho com o código abaixo:
 SELECT p.id
      ,p.scope
      ,p.entrydate
      ,p.applicant
      ,p.status
      ,ev.type
      ,ev.eventdatetime AS lastevent
      ,ev.eventobs
      ,MIN(al.expiredate) nextalert
      ,al.alertobs
  FROM process p
  LEFT OUTER JOIN event ev
    ON ev.processid = p.id
   AND ev.eventid = (SELECT top(1) eventid
                       FROM event e
                      WHERE e.processid = ev.processid
                      ORDER BY e.eventdatetime DESC)
  LEFT OUTER JOIN alert al
    ON al.processid = p.id
   AND al.alertid =
       (SELECT top(1) alertid
          FROM alert a a.deadlinedate > getdate())
 GROUP BY p.id
         ,p.scope
         ,p.entrydate
         ,p.applicant
         ,p.status
         ,ev.type
         ,ev.eventdatetime
         ,ev.eventobs
         ,al.alertobs

Muito obrigado @Rovann Linhalis pela ajuda preciosa.
Comment: certo, normalmente perguntas com query sem as tabelas e sem registros de amostra ficam um tanto confusas... sempre coloque esses dados e se possível monte um SQLFiddle... ajuda muito...; Por nada, sempre que precisa a comunidade ajuda =]
Comment: Sim, vou lembrar disso para a próxima!


Verificação de senha com bcrypt em session e mysql

Question: Tenho um usuário e senha que estao sendo salvos em uma session, so que a senha esta sendo criptografada pela função bcrypt. Como eu faço para verifica se a senha que está salva na session é igual a senha q está no banco de dados mysql que também esta criptografada?
Comment: Samuel http://chat.stackexchange.com/rooms/22834/verificar-session
Comment: Samuel, apaguei meu comentário por não trazer nada relevante a pergunta... mas sobre bcrypt aqui tem um tutorial sobre o uso dele: http://blog.thiagobelem.net/criptografando-senhas-no-php-usando-bcrypt-blowfish/
Comment: @RafaelWithoeft eu estava seguindo este tutorial, mas la ele não explica como usar ele em session e mysql, pois para verificar se os dois dados são iguals, um dos valores que tem q ser passados para a função, tem q ser a senha sem estar criptografada, e a senha já criptografada que vem do banco de dados. Só que no meu caso, as duas senhas estao criptografadas. Tem alguma maneira de fazer este sistema de login sem usar session?
Comment: Existem várias maneiras, eu particularmente não armazeno senhas em sessão... apenas um id de identificação do usuário normalmente. Aqui tem uma pergunta que envolve essa questão de sessão e login: http://pt.stackoverflow.com/questions/38920/o-que-guardar-em-uma-sess%C3%A3o-de-login você usa bcrypt com salt dinâmico ? O que você pode fazer talvez é: armazenar a sessão no banco (tabela - memory), e em áreas críticas você pede a senha novamente...
Comment: Mas voltando ao foco da sua pergunta, antes de armazenar na sessão você passa a senha novamente por uma função de bcrypt, assim gerando um valor diferente do que pode estar na base certo? Se você comparar o que tem na sessão de valor será diferente da base então... (Pelo menos foi isso que entendi, só estou confirmando essa informação)
Comment: @RafaelWithoeft Isso mesmo, e como as duas senhas, tanto a que está no banco de dados, quanto a que está salvas na session, estão criptografadas em bcrypt, não consigo verificar se as duas são iguais, pois para fazer essa verificação, preciso da senha original sem estar criptografada, mas salvar essas senha em session sem criptografia fica muito inseguro.
Comment: Samuel, ao meu entender está usando um salt fixo certo? O que você pode fazer para não armazenar senhas sem segurança por ai é, gerar um hash, deixar ele na sessão e adicionar ele em uma tabela na base de dados que vai cuidar das sessões (tabela memory), você valida se esse hash existe na base, caso contrário você pede a senha novamente, e para lugares críticos do sistema você pede a confirmação da senha mesmo logado e quando a sessão expirar ou o usuário sair você elimina essa hash da tabela. É uma das maneiras, caso contrário você apenas verifica se existe sessão e deixa o usuário seguir...
Comment: @RafaelWithoeft não, eu estou usando um salt dinâmico. Entendi o método que você falou, mas não entendi como farei para verificar se usuário está logado com a tabela memory. Se não for incomodar, tem como me mostrar um pequeno exemplo dessa verificação em php?
Comment: @RafaelWithoeft muito obrigado, deu para entender agora. Vou fazer desta maneira daqui em diante.
Answer: Nunca, nunca, mas nunca guardes senhas em sessões, por mais segura que as tuas sessões pareçam.
Para verificar uma hash, com o bcrypt, deves simplesmente fornecer a primeira hash(hash existente no banco de dados) e encriptar a senha proveniente do formulário(no teu caso, a hash armazenada na sessão).
<?php
// See the password_hash() example to see where this came from.
// a variavel hash possui o valor da hash no banco de dados
// Imagine que este é o valor
$hash = '$2y$07$BCryptRequires22Chrcte/VlQH0piJtjXl.0t1XkA8pw9dMXTpOq';

// So para relembrar, que guardar senhas na sessão nao é uma boa pratica.
if (password_verify($_SESSION['senha_na_sessao'], $hash)) {
echo 'Password is valid!';
// Usuario autenticado
// Inicializar as sessoes para esse usuario
} else {
echo 'Invalid password.';
// Usuario invalido
// Retorna a pagina de login
}
?>

A função password_verify é exclusiva para o PHP >= 5.5.0
Para versões do PHP inferiores a PHP < 5.5.0 existe esta API que simula estas novas funções.
#Um exemplo:
<?php

//Reset dos valores
$usr = $pwd = "";

// Cadastro
if(isset($_POST["cadastrar"])){
// Neste exemplo, não irei verificar se o usuario digitou algo ou nao
if(isset($_POST["usuario"]) && isset($_POST["senha"])){
    $usr = $_POST["usuario"];
    $pwd = $_POST["senha"];
    // A partir daqui tratamos da senha
    // Encripta-se a senha;
    // esta funcao utiliza o blowfish por predefinicao
    $hash = password_hash($pwd, PASSWORD_DEFAULT);
    if($hash){
        // Insere no banco de dados
        // Um exemplo:
        $query = "INSERT INTO usuarios ('nome','senha') VALUES  ('{$usr}','{$hash}') LIMIT 1";
        if(mysqli_query($conexao_sqli, $query)){
            echo "Cadastrado";
            // redirecciona
        } else {
            echo "Não cadastrado";
            // redirecciona
            exit;
        }
        // Encerra a conexao algures

        }
 }
}

// Login
if(isset($_POST["entrar"])){
// Neste exemplo, não irei verificar se o usuario digitou algo ou nao
if(isset($_POST["usuario"]) && isset($_POST["senha"])){
    $usr = $_POST["usuario"];
    $pwd = $_POST["senha"];
    // A partir daqui tratamos da senha
    // Aqui faz-se a mesma, coisa, mas desta vez utiliza-se
    // a hash do banco de dados
    // O blowfish utiliza apenas os 22 primeiros carateres
    // para criar a hash
    // Uma consulta SQL/funcao que retorna a hash no banco
    // de dados passa este usuario
    // exemplo:
    $query = "SELECT nome, senha FROM usuarios WHERE usuario = '{$usr}'";
    $if(mysqli_query($conexao_sqli, $query)){
        $hash_do_banco_de_dados = mysqli_fetch_assoc($query);
        $hash = password_hash($pwd, $hash_do_banco_de_dados["senha"]);
        if($hash){
            if(password_verify($pwd, $hash)){
                echo "Logado";
                // Sessoes
                // Redirecciona
                exit;
            } else {
                echo "Nao logado";
                // redirecciona
                exit;
            }
        }
    }

 }
}

?>
<?php
if(!isset($_GET['pagina']) && $_GET['pagina'] == 'cadastrar'){
?>
<form method="POST" action="">
    Usuario:

<input type="text" name="usuario" size="30"/>

Senha:

<input type="password" name="senha" size="30"/>

<input type="submit" name="cadastrar" value="Cadastrar"/>
</form>

Clique aqui para Entrar
<?php
} elseif(isset($_GET['pagina']) && $_GET['pagina'] == 'entrar'){
?>
<form method="POST" action="">
    Usuario:

<input type="text" name="usuario" size="30"/>

Senha:

<input type="password" name="senha" size="30"/>

<input type="submit" name="entrar" value="Entrar"/>
</form>

Clique aqui para cadastrar
<?php
} else {
?>
<form method="POST" action="">
    Usuario:

<input type="text" name="usuario" size="30"/>

Senha:

<input type="password" name="senha" size="30"/>

<input type="submit" name="entrar" value="Entrar"/>
</form>

Clique aqui para Cadastrar
<?php>
}
?>

É basicamente isto aí, levei algum tempo a criar isto, porque criei-o à partir do gedit e também porque estou pelo linux num notebook :/, mas não pude executar o exemplo, mas garanto que funciona, bastará que substituas as variaveis de conexao fiticias que eu usei no exemplo.
Comment: Como faria para fazer a verificação por login sem passar a senhas para as session?
Comment: Antes de mais, qual é a tua versão do PHP ?
Comment: A versão do PHP é 5.6.8.
Comment: Demorei algum tempo, mas é basicamente isto que aí esta. Eu tenho um tutorial a falar disto e mostrar de forma detalhada no youtube, mas tive de escrever este, porque de momento estou sem o código-fonte do outro.


Change makefile to work on 'make all' command

Question: So I have completed school project on making a Sudoku program and I have this makefile which works cleanly when i use 'make' command. I just found out that I need it to compile cleanly on 'make all' command. I can't figure out how to set this up though. Any suggestions?
CC = gcc
OBJS = main.o MainAux.o game.o parser.o solver.o
EXEC = sudoku_console
COMP_FLAG = -ansi -Wall -Wextra -Werror -pedantic-errors
GUROBI_COMP = -I/usr/local/lib/gurobi563/include
GUROBI_LIB = -L/usr/local/lib/gurobi563/lib -lgurobi56

$(EXEC): $(OBJS)
    $(CC) $(OBJS) $(GUROBI_LIB) -o $@ -lm
main.o: main.c game.h
    $(CC) $(COMP_FLAG) -c $*.c
game.o: game.c MainAux.h parser.h solver.h game.h
    $(CC) $(COMP_FLAG) -c $*.c
MainAux.o: MainAux.c game.h
    $(CC) $(COMP_FLAG) -c $*.c
parser.o: parser.c MainAux.h
    $(CC) $(COMP_FLAG) -c $*.c
solver.o: solver.c game.h MainAux.h
    $(CC) $(COMP_FLAG) $(GUROBI_COMP) -c $*.c
clean:
    rm -f $(OBJS) $(EXEC)

Answer: Just make a target named all that depends on whatever you want to happen.  So for example:
all: $(EXEC)
.PHONY: all

the .PHONY is good hygiene but not strictly required.
Now when you run make all it finds the all target, sees that in order to update it it must first update the $(EXEC) target, and Bob's your uncle!
Comment: Thank you, this works! I have a question though.
When I change the first target $(EXEC): $(OBJS) to all: ($OBJS) it also seems to work (and of course the executable output name). Is the effect of your proposition and this one any different?
Comment: If you do it your way and you run `make` twice in a row without changing any files, it will still re-link the program the second time (and every other time).  If you do it my way then the second (and subsequent) times it won't do anything because there's nothing to do.


Asp.Net MVC não executa JQuery após chamar Action através de "url:"

Question: Preciso chamar uma Action usando Ajax e até então tudo certo, faço o request da seguinte forma:
confirm: function () {
            $.ajax({
                url: urlToDelete + id,
                success: function () {
                    //window.location = urlToDelete + id; <- forma que funciona porém não considero segura, não consigo usar o Request.IsAjaxRequest() no controller, tornando-o vulnerável.
                }
            });
        },

ele entra na Action, executa tudo perfeitamente e retorna para a minha View. Na view tenho o seguinte trecho:
@if (TempData["Alerta"] != null && !String.IsNullOrEmpty(TempData["Alerta"].ToString()))
{

    TempData["Alerta"] = null;
}

neste trecho, passo para a variável 'msg' o valor do meu TempData, que seria uma mensagem de erro. Eis o problema, executando desta forma (com Ajax) a mensagem de erro não exibe na tela.
Retirando o 'url' e descomentando o trecho 'window.location' ele funciona tudo da mesma forma, porém executa o alerta que eu quero. Acredito que o problema é com o Ajax, que não executa um Jquery ou Javascript após o retorno de uma view que foi feita com ele.
JQuery:
 $(document).ready(function () {
        $.confirm({
            icon: 'fa fa-warning text-warning',
            title: 'Atenção',
            keyboardEnabled: true,
            content: msg,
            confirmButton: 'OK',
            cancelButtonClass: 'hide',
            animation: 'top',
        });

        msg = null;
    });

Answer: Você poderia retornar um JsonResult com sua mensagem, e tratar a mesma no success do seu javascript. Algo tipo:
Action
public ActionResult Delete(long id)
{

    /*Lógica da sua action*/

    //aqui retorna no data sua menssagem
    return new JsonResult() { Data = "Deletado com sucesso", JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}

Javascript
$.ajax({
url: urlToDelete + id,
success: function (data) {
    //Aqui você exibe sua mensagem, pode apendar a um modal ou topo da pagina..

    $.confirm({
        icon: 'fa fa-warning text-warning',
        title: 'Atenção',
        keyboardEnabled: true,
        content: data,
        confirmButton: 'OK',
        cancelButtonClass: 'hide',
        animation: 'top',
    });
  }
});

Comment: Por favor evitem longas discussões nos comentários; a conversa de vocês foi [movida para o chat](http://chat.stackexchange.com/rooms/27079/discussion-on-answer-by-brunno-asp-net-mvc-nao-executa-jquery-apos-chamar-action)


Finding the area of a set

Question: I am trying to find the area of the set $A=\{(x,y) \;|\; (x^2+y^2)^2 \leq x^3+y^3 \}$.
I tried doing it with a polar change of coordinates but I didn't manage to solve the integral that I came up with $\int (cos^3t+sin^3t)^2dt$.
Any ideas how can a handle this problem?
Comment: I think you have the right approach, now you just use trig. identities:  $\sin^3 t+\cos^3 t=(\sin t+\cos t)(1-\sin t \cos t)$ and so forth.
Comment: I think I did it. Thank you very much!
Answer: Write $x^2 + y^2 = r^2(\theta)$ on the left-hand-side and $x = r^3(\theta) \sin (\theta)$ and likewise for $y$ on the right-hand side.  Cancel an $r(\theta)$ to get a cubic.  The solutions are:
$$\left\{\sqrt[3]{\sin ^3(\theta )+\cos ^3(\theta )},-\sqrt[3]{-1} \sqrt[3]{\sin ^3(\theta )+\cos ^3(\theta )},(-1)^{2/3}
   \sqrt[3]{\sin ^3(\theta )+\cos ^3(\theta )}\right\}$$
Now integrate in radial coordinates, being sure to use the proper solutions.
Comment: How to find them? The equation is from fourth power.
Comment: Use computer algebra.  I get the answer directly in *Mathematica*.  Yes... it is long and complicated, but who cares?
Comment: But I want to solve it on a paper with a pen without a PC. Maybe there is an easier way to do this
Answer: Tedious but basic.  $(cos^3(x)+ sin^3(x))^2= cos^6(x)+ 2cos^3(x)sin^3(x)+ sin^6(x)$.
To integrate $2cos^3(x)sin^3(x)dx$, write it as $2cos^2(x)sin^3(x)(cos(x)dx)= 2(1- sin^2(x))sin^3(x)(cos(x)dx)$ and let $u= sin(x)$so that $du= cos(x)dx$ and this becomes $2(1- u^2)u^3du= (2u^3- u^5)du$.
Both $cos^6(x)dx$ and $sin^6(x)dx$ have even powers of sine and cosine so you will want to use the "reduction formulas": $sin^2(x)= \frac{1- cos(2x)}{2}$ and $cos^2(x)= \frac{1+ cos(2x)}{2}$ to get odd powers.

Finding the area of a set


compute $\int_0^1\sqrt{x(1-x)}dx$.

Question: My sister has a following integral to compute
$$\int_0^1\sqrt{x(1-x)}dx.$$
I know how to compute it : doing the substitution $x=\sin^2(u)$ yields
$$\int_0^{\pi/2}2\sin(x)^2\cos^2(x)dx=\frac{1}{2}\int_0^{\pi/2}\sin^2(2x)dx=\frac{1}{4}\int_0^{\pi/2}(1-\cos(4x))dx=\frac{\pi}{8}.$$
So I know how to do it. However, my sister is in high school, and they never saw substitution, so it's impossible that it's what her teacher expect. Is there an other way to compute it with more elementary tools ? I don't see it...
Comment: https://math.stackexchange.com/q/170284/42969
Comment: A possible method to find such a method would be to compute the primitive using any method you know, then derive this primitive until you obtain the original function. Then, by doing the steps backward, you will have found a method that does allow to compute the integral, without using integration by substitution. You could also use integration by parts.
Answer: Notice that $$x(1-x)=\frac14-\left(x-\frac12\right)^2.$$
Sketch the curve
$$y=\sqrt{\frac14-\left(x-\frac12\right)^2},$$
then we find that it is the top half of a circle of radius $\frac12$ centered at the point $(1/2,0)$. By the geometric meaning of the definite integrals, we have
$$ \int_0^1\sqrt{x(1-x)} \,dx=\frac12\cdot (\text{Area of the circle})=\frac12\cdot\pi\cdot\left(\frac12\right)^2=\frac\pi8.$$
Sorry for my poor English. I've added a picture. I hope that it will be much more helpful.
Comment: +1:  perhaps worth saying "Sketch the curve: it is the top half of a circle radius $\frac12$ centred at $(\frac12,0)$" if you are at high school
Comment: https://math.stackexchange.com/a/3865109/42969
Comment: @Henry Thanks for your comments! I've changed some of my words. I'm not good at describing the pictures in my head using English. If you or any other people think that it will be better after editting some more words, please feel free to do so. :)

compute $\int_0^1\sqrt{x(1-x)}dx$.


Map refresh on button click-Javascript

Question: JS:
function initialize() {
  var latLng = new google.maps.LatLng({{location_latitude}}, {{location_longitude}});
  var map = new google.maps.Map(document.getElementById('mapCanvas'), {
    zoom: 8,
    center: latLng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  });

Map is loading at the time of page load.
Apart from that,i need it to refresh the map on a button click,namely "<button>Refresh Map</button>"
How to make the map refresh on clicking Refresh Map button.
Answer: $('button').on('click',initialize);

Map refresh on button click-Javascript


Using ng-repeat to propagate a list containing another ng-repeat list

Question: I'm trying to make an angular list that propagate n objects, and inside the list items, use ng-repeat again to make a horizontal list from a property of the object which is an array
How do I accomplish that?
Here is the object I'm working with so far:

    $scope.profileCompare = {

        You: {
            questionAnswer: [false, true, false, false, false, false],
            questionImportance: [false, true, false]
        },
        Pizza: {
            questionAnswer: [true, false, false, false, false, false],
            questionImportance: [false, false, true]
        },
        Greenie: {
            questionAnswer: [false, false, false, false, true, false],
            questionImportance: [true, false, false]
        }
    }

No real progress on how to reach the questionAnswer property with an ng-repeat to make the horizontal list inside each
 of the first ng-repeat. But I'll update that as we go
Comment: can you post your HTML code?
Comment: There is none because I don't know how to do it. Unless you want to see something basic and derivative in every way
Answer: Your first level isn't an array, it's a dictionary of key value pairs.
You can iterate through the first level using the object syntax, (key, value), and then iterate through the second tier using array syntax; something like the following:

    {{key}}
    {{answer}}

in your case, the value will be an object, with 2 properties, questionAnswer and questionImportance.
The downside of using this syntax is that the order is set by the browser, and may or may not be the same as the order defined in the data set.  If you want to be able to filter, order, etc. the data, you will need to convert the objects to arrays first;  The angular documentation recommends using angular-toArrayFilter for this task.
Comment: I do really want to help you get to a final solution; I wasn't trying to criticize your approach or get you to delete your newest question; I probably came on a bit strong, but I was only trying my best to encourage you to show more of the picture and pick a larger number of tags to get more exposure and better answers.
Answer: If you want to iterate over the first level you will need the following syntax:
ng-repeat="(key, value) in profileCompare"

After that, it's pretty straight forward to iterate over your array properties:
Here's the complete HTML:

{{key}}

Answers

    {{answer}}

Question importance

      {{importance}}

Note the track by $index since you are iterating over booleans, which will most definitely have duplicates.
Here's a plunkr: http://plnkr.co/edit/U20nzazg0O9qnksFIze2?p=preview


magento - change the colour of the footer links text

Question: hoping somebody might be able to help me.
I am currently using a hellothemes theme.
I would like to change the colour of the footer links text. Any ideas on how to?
Also can anyone explain the differences between the CSS's on Boxes.css:

Mage_CSS_B Common Elements
Mage_CSS_E Shop Pages
Mage_CSS_F Overrides
etc...

Regards,
Fiona
Answer: This question is similiar to your other question..
If you use Firebug for Firefox, you can inspect the Footer link text, and see the line of CSS that is deciding the color. It's much easier than trying to guess what each line of CSS is trying to do.


Python lstrip Sometimes Removes Extra Character

Question: I have Python 2.7 code that operates on a list of files.  In part of the code I strip away the directory information.  Today I was surprised to find that code didn't work correctly, when the file names begin with "s".  This sample code demonstrates the problem:
<code>import os

TEST_RESULTS_DIR = ".." + os.sep + "Test Results"

filename = TEST_RESULTS_DIR + os.sep + "p_file.txt"
stripped_filename = filename.lstrip(TEST_RESULTS_DIR + os.sep)
print ("%s : %s") % (filename, stripped_filename)

filename = TEST_RESULTS_DIR + os.sep + "s_file.txt"
stripped_filename = filename.lstrip(TEST_RESULTS_DIR + os.sep)
print ("%s : %s") % (filename, stripped_filename)
</code>
When I run this code, I get this:

..\Test Results\p_file.txt : p_file.txt
..\Test Results\s_file.txt : _file.txt

Does anyone understand why?
Answer: Lstrip doesn't replace a string at the beginning of another string, it strips all characters that match the characters in the string argument from the string it is called on.
For example:
<code>"aaabbbc".lstrip("ba") = "c"
</code>
Your directory has an s in it, so it get's striped, you would see the same result if the file started with a u or an e.
Comment: Thanks, you're right that I was thinking it'd only strip the whole string.
Comment: you need to use re module, re.sub(re.escape(TEST_RESULTS_DIR + os.sep), '', filename)


No action was found on the controller that matches the request from AngularJS and Asp.Net WebApi

Question: My head is fuming. I am learning AnjularJS with Asp.Net Web Api. I have the following AnjularJS controller which has an ajax call to a Web Api service as follows.
CustomerController = function ($http, $scope, $httpParamSerializer) {
    $scope.modelObject = { first: 2, second: 3 };
    $scope.modelObject.sendRequest = function (requestType) {
        var dataTemp = {first:2, second:3 };
        alert( $httpParamSerializer(dataTemp));
        $http({
            method: 'GET',
            url: '/api/bindings/sumnumbers',
            data: $httpParamSerializer(dataTemp),
            headers: { 'Content-Type': 'application/json' }
        }
        ).then(function successCallback(response) {
            $scope.modelObject.result = response.data;
        }, function errorCallback(response) {
            alert(response.data);
            $scope.modelObject.result = response;
        });
    }

And the web api action method is as follows.
    [HttpGet]
    [HttpPost]
    public int SumNumbers(int first, int second)
    {
        return first + second;
    }

I even have a route in the webconfig for web api as follows as was suggested in the tutorial.
        config.Routes.MapHttpRoute(
            name: "Binding Example Route",
            routeTemplate: "api/{controller}/{action}/{first}/{second}"
        );

But I get the following error
{"data":{"Message":"No HTTP resource was found that matches the request URI        'http://localhost:29845/api/bindings/sumnumbers'.","MessageDetail":"No action was found on the controller 'Bindings' that matches the request."},"status":404,"config":{"method":"GET","transformRequest":[null],"transformResponse":[null],"url":"/api/bindings/sumnumbers","data":"first=2&second=3","headers":{"Content-Type":"application/json","Accept":"application/json, text/plain, */*"}},"statusText":"Not Found"}

Can some one please suggest me whats wrong?
Answer: I would recommend using Attribute Routing to make things easier. You could change your WEB API method to this:
[HttpGet]
[Route("api/bindings/sumnumbers/{first}/{second}")]
public int SumNumbers([FromUri] int first, [FromUri] int second)
{
    return first + second;
}

In your Angular JS Controller you need to pass the parameters in the URL:
url: '/api/bindings/sumnumbers/' + first + '/' + second
This should work for you. I would also highly recommend using a tool like Fiddler to test your WEB API methods before trying them out with Angular.
Comment: what if attribute routing is not an option? (i. e: I'm using web api 1.0)
Answer: Just found, instead of
data: $httpParamSerializer(dataTemp),

in the ajax call, you can simply have
params: dataTemp,

Then in such a case you dont need to put a route attribute for the action method, and FromUi attribute for the parameters keithm suggested.


Como exibir número de registros por categoria em PHP e MySql

Question: Tenho uma tabela de imóveis em MySql divididos em 6 categorias.
Quero fazer uma consulta que retorne o número de registros para cada categoria.
A única forma que conheço até agora é fazer uma consulta para cada categoria, mas acho que isso exige muito do servidor.
É possível fazer uma única consulta e depois achar uma forma de mostras os resultados separados por categoria?
Ah, como são apenas 6 categorias fixas, não criei outra tabela só de categorias, dispensando o uso de join.
Comment: SELECT
categoria , COUNT(categoria) AS totalCount
FROM
nome_tabela
GROUP
BY categoria
Answer: Esse simples SELECT utiliza o GROUP BY categoria para agrupar todos os registros com o conteúdo de campo categoria iguais. Nas colunas que trazemos tem a própria categoria e COUNT(categoria) qtde que tem como função contar todas as linhas agrupadas:
SELECT categoria, COUNT(categoria) qtde FROM imoveis
GROUP BY categoria;

Comment: Nossa, tão simples. Valeu pela força.


How to set the Database Host Name during Oracle enterprise manager installation

Question: I'm trying to install Oracle Database for the first time and I'm facing many problem. I, following this guide, but I can't understand what should I set in the form shown in section 14. What is the database hostname? How I determine it?
Answer: It is described right above the section 14's screenshot:

The host name must resolve to the local host or virtual host because
  the host name is used for the local Oracle WebLogic Server as well as
  the Oracle Management Service. Do not provide a remote host or a load
  balancer virtual host in this field. Do not enter an IP address. Do
  not use underscores in the name. Short names are allowed, but you will
  see a warning, so Oracle recommends that you enter a fully qualified
  domain name instead.


Disable or Bypass login of odoo when trying to hit from external application

Question: I am trying to open odoo url from my hosted application but its redirecting to login screen. As user is already logged in to my application logically user should not be redirected to  login screen again...How can I bypass  this security check of odoo???
Thanks In advance
Comment: Possible duplicate of [How to bypass ODOO security rules given by administrator?](https://stackoverflow.com/questions/47193832/how-to-bypass-odoo-security-rules-given-by-administrator)
Answer: From your question, I think what you are trying to achieve is to authenticate your user's odoo session automatically if that user is already authenticated in your non-odoo application. To achieve that, you can implement your application such that, on authentication of a user, your backend will authenticate a session in odoo with corresponding user, and set session_id cookie of user's browser to that authenticated session_id. I guess that may be achievable if both application are served under same domain with reverse proxying using nginx or apache, as other's already commented, there is no way you can totally disable or bypass authentication of odoo itself, as this is a well developed business related software, and that will just defeat it's purpose.
Answer: It is possible to bypass the security of odoo. These changes are required in these two files
`
**server/odoo/http.py**
line number 406 in odoo 12
 def validate_csrf(self, csrf):
        # if not csrf:
        #     return False
        #
        # try:
        #     hm, _, max_ts = str(csrf).rpartition('o')
        # except UnicodeEncodeError:
        #     return False
        #
        # if max_ts:
        #     try:
        #         if int(max_ts) < int(time.time()):
        #             return False
        #     except ValueError:
        #         return False
        #
        # token = self.session.sid
        #
        # msg = '%s%s' % (token, max_ts)
        # secret = self.env['ir.config_parameter'].sudo().get_param('database.secret')
        # assert secret, "CSRF protection requires a configured database secret"
        # hm_expected = hmac.new(secret.encode('ascii'), msg.encode('utf-8'), hashlib.sha1).hexdigest()
        # return consteq(hm, hm_expected)
        return True

def setup_session(self, httprequest):
        explicit_session = True
        # recover or create session
        # session_gc(self.session_store)
        #
        # sid = httprequest.args.get('session_id')
        # explicit_session = True
        # if not sid:
        #     sid =  httprequest.headers.get("X-Openerp-Session-Id")
        # if not sid:
        #     sid = httprequest.cookies.get('session_id')
        #     explicit_session = False
        # if sid is None:
        #     httprequest.session = self.session_store.new()
        # else:
        #     httprequest.session = self.session_store.get(sid)
        httprequest.session = self.session_store.new()
        httprequest.session.uid =2
        httprequest.session.login = 'root'
        httprequest.session.db = 'odoo'
        httprequest.session.sid = '7aa5500f30365aead781465ec08bbb03c3a5024b'
        return explicit_session

line number 1348

def setup_session(self, httprequest):
        explicit_session = True
        # recover or create session
        # session_gc(self.session_store)
        #
        # sid = httprequest.args.get('session_id')
        # explicit_session = True
        # if not sid:
        #     sid =  httprequest.headers.get("X-Openerp-Session-Id")
        # if not sid:
        #     sid = httprequest.cookies.get('session_id')
        #     explicit_session = False
        # if sid is None:
        #     httprequest.session = self.session_store.new()
        # else:
        #     httprequest.session = self.session_store.get(sid)
        httprequest.session = self.session_store.new()
        httprequest.session.uid =2
        httprequest.session.login = 'root'
        httprequest.session.db = 'odoo'
        httprequest.session.sid = '7aa5500f30365aead781465ec08bbb03c3a5024b'
        return explicit_session

**server/odoo/service/security.py**
line number 18
def check_session(session, env):
    # self = env['res.users'].browse(session.uid)
    # expected = self._compute_session_token(session.sid)
    # if expected and odoo.tools.misc.consteq(expected, session.session_token):
    #     return True
    # self._invalidate_session_cache()
return True