Computing the Bayesian Estimator with Jeffreys prior for the Gamma distribution

Question: Question:
Let $X_1, · · · , X_n$ be a random sample from $Gamma(1, θ)$. The population mean is $θ$. Assume that the Jeffreys prior is used.

Find the generalized Bayesian estimator of θ under the SEL (squared error loss).

Find the Bayesian estimator (rule) of θ under loss $L(θ, a) = (a/θ − 1)^2$

Solution:
My attempt:
Since The Jeffreys prior is the square of the Fisher information of $θ$:
$p(θ)=\frac{\sqrt(1)}{θ}$.
Then using Bayes' rule we have,
$$\begin{align*}p(θ|x)&\propto \dfrac{θ^1}{\Gamma (1)}x^{1-1}e^{-xθ}\cdot\dfrac{\sqrt{1}}{θ} \\ &\propto θ^{1-1} e^{-xθ} \\ &\propto \dfrac{x^1\,θ^{1-1}}{\Gamma(1)}\,e^{-xθ}\end{align*}$$
which shows the posterior is a Gamma $\mathcal{G}(1,x)$ distribution.
Now how can I proceed further to compute the Bayesian estimator, and generalized Bayesian estimator under the stated loss functions?
Comment: Have you written the posterior loss? attempted to minimise it? Please show more details about your work on this question. And add `self-study` as a tag.
Answer: In order to find a Bayesian Estimator for a loss function, we need to minimize the posterior expected loss $E[loss(\theta, \hat{\theta})|x]$, i.e., solve the optimization problem $\underset{\hat{\theta}}{min}\int\limits_{0}^{\infty}loss(\theta,\hat{\theta})p(\theta|x)d\theta$.
(1) We have to solve the optimization problem $\underset{\hat{\theta}}{min}\int\limits_{0}^{\infty}(\theta-\hat{\theta})^2p(\theta|x)d\theta$, for SEL  $loss(\hat{\theta}, \theta)=(\theta-\hat{\theta})^2$.
First we need to compute the full posterior, given
the likelihood $L(\theta|x)=p(x|\theta)=\prod\limits_{i=1}^{n}\dfrac{1}{\Gamma(1)\theta}e^{-x_i/\theta}=\dfrac{1}{\theta^n}e^{-n\sum\limits_{i=1}^{n}x_i/{\theta}}=\dfrac{e^{-n^2\bar{x}/\theta}}{\theta^n}$, where $\bar{x}=\dfrac{\sum\limits_{i=1}^{n}x_i}{n}$
The Fisher Information $I(\theta)=-E[l^{\prime\prime}(\theta)]=-E\left[-2\dfrac{n\sum\limits_{i=1}^{n}{x_i}}{\theta^3}+\dfrac{n}{\theta^2}\right]=\dfrac{n(2n-1)}{\theta^2}$,  with $E[X_i]=\theta$,
where we have the loglikelihood $l=-\dfrac{n\sum\limits_{i=1}^{n}{x_i}}{\theta}-n.ln(\theta)$
Hence. the prior $p(\theta)=\dfrac{\sqrt{n(2n-1)}}{\theta}$ (Jeffrey's prior: the square root of the Fisher information $I(\theta)$)
$\therefore p(x)$
$=\int\limits_{0}^{\infty}p(x|\theta)p(\theta)d\theta=\sqrt{n(2n-1)}\int\limits_{0}^{\infty}\dfrac{e^{-n^2\bar{x}/\theta}}{\theta^{n+1}}d\theta$
$=\dfrac{\sqrt{n(2n-1)}}{(n^2\bar{x})^n}\int\limits_{0}^{\infty}e^{-y}y^{n-1}dy$, with substitution $y=\dfrac{n^2\bar{x}}{\theta}$
$\implies p(x)=\dfrac{\Gamma(n)\sqrt{n(2n-1)}}{(n^2\bar{x})^n}$
By Bayes theorem, the posterior $p(\theta|x)=\dfrac{p(x|\theta)p(\theta)}{p(x)}=\dfrac{(n^2\bar{x})^ne^{-n^2\bar{x}/\theta}}{\Gamma(n)\theta^{n+1}}$
At minimum, we have $\dfrac{\partial}{\partial \hat{\theta}}\int\limits_{0}^{\infty}(\theta-\hat{\theta})^2p(\theta|x)d\theta=\int\limits_{0}^{\infty}-2(\theta-\hat{\theta})p(\theta|x)d\theta=0$
$\implies \hat{\theta}_{SEL}=\int\limits_{0}^{\infty}\theta p(\theta|x)d\theta=\int\limits_{0}^{\infty}\dfrac{(n^2\bar{x}/\theta)^ne^{-n^2\bar{x}/\theta}}{\Gamma(n)}d\theta=\dfrac{n^2\bar{x}}{\Gamma(n)}\int\limits_{0}^{\infty}e^{-y}y^{n-2}dy=n^2\bar{x}\dfrac{\Gamma(n-1)}{\Gamma(n)}$
$\implies \hat{\theta}_{SEL}=\dfrac{n^2\bar{x}}{n-1}$, since $\Gamma(n)=(n-1)\Gamma(n-1)$
Please double-check the above calculation, in case I have done a calculation mistake somehwhere (I have a feeling that I may have an extra $n$ in the Bayesian estimator) please point it out.
We can follow the exactly same steps to compute the Bayesian estimator for (2), with a different loss function $loss(\hat{\theta},\theta)=(\hat{\theta}/\theta-1)^2$.
Comment: Did you compute here  generalized Bayesian or only  Bayesian estimator?
Comment: It's Bayesian estimator... But as per https://en.wikipedia.org/wiki/Bayes_estimator, when the prior is improper, it's called generalized Bayesian estimator, here we have Jeffrey's improper prior.


R Lag Two Variables

Question: DATA = data.frame(STUDENT = c(1,1,1,1,1,1,2,2,2,2,2, 3,3,3),
                  YEAR = c(2000, 2000, 2000, 2001, 2001, 2001, 2000, 2000, 2001, 2001, 2001, 2001, 2001, 2001),
                  TRIMESTER= c(1,2,3,1,2,3,2,3,1,2,3,1,2,3),
                  SCORE = c(5,7,8,9,10,3,4,6,3,1,2,3,6, 9),
                  WANT = c(NA,NA,NA,4,3,-5,NA,NA,NA,-3,-4,NA,NA,NA))

I have DATA and wish to create 'WANT' which is calculate by:
For each STUDENT, find the SCORE where (YEAR = YEAR +1, TRIMESTER = TRIMESTER) and get the difference.
EX: SCORE(STUDENT = 1, TRIMESTER = 1, YEAR = 2001) - SCORE(STUDENT = 1, TRIMESTER = 1, YEAR = 2000)

Answer: Does this do what you want?
library(tidyverse)

DATA = data.frame(STUDENT = c(1,1,1,1,1,1,2,2,2,2,2, 3,3,3),
                  YEAR = c(2000, 2000, 2000, 2001, 2001, 2001, 2000, 2000, 2001, 2001, 2001, 2001, 2001, 2001),
                  TRIMESTER= c(1,2,3,1,2,3,2,3,1,2,3,1,2,3),
                  SCORE = c(5,7,8,9,10,3,4,6,3,1,2,3,6, 9),
                  WANT = c(NA,NA,NA,4,3,-5,NA,NA,NA,-3,-4,NA,NA,NA))

DATA <- as_tibble(DATA)

DATA %>%
    group_by(STUDENT, TRIMESTER) %>%
    mutate(LAST = lag(SCORE),
           DIFF = SCORE - LAST)
#> # A tibble: 14 x 7
#> # Groups:   STUDENT, TRIMESTER [9]
#>    STUDENT  YEAR TRIMESTER SCORE  WANT  LAST  DIFF
#>      <dbl> <dbl>     <dbl> <dbl> <dbl> <dbl> <dbl>
#>  1       1  2000         1     5    NA    NA    NA
#>  2       1  2000         2     7    NA    NA    NA
#>  3       1  2000         3     8    NA    NA    NA
#>  4       1  2001         1     9     4     5     4
#>  5       1  2001         2    10     3     7     3
#>  6       1  2001         3     3    -5     8    -5
#>  7       2  2000         2     4    NA    NA    NA
#>  8       2  2000         3     6    NA    NA    NA
#>  9       2  2001         1     3    NA    NA    NA
#> 10       2  2001         2     1    -3     4    -3
#> 11       2  2001         3     2    -4     6    -4
#> 12       3  2001         1     3    NA    NA    NA
#> 13       3  2001         2     6    NA    NA    NA
#> 14       3  2001         3     9    NA    NA    NA

Created on 2022-11-23 with reprex v2.0.2
Answer: Your data
DATA = data.frame(STUDENT = c(1,1,1,1,1,1,2,2,2,2,2, 3,3,3),
                  YEAR = c(2000, 2000, 2000, 2001, 2001, 2001, 2000, 2000, 2001, 2001, 2001, 2001, 2001, 2001),
                  TRIMESTER= c(1,2,3,1,2,3,2,3,1,2,3,1,2,3),
                  SCORE = c(5,7,8,9,10,3,4,6,3,1,2,3,6, 9))

using merge
DATA=merge(
  DATA,
  cbind(
    DATA[,c("STUDENT","TRIMESTER")],
    DATA[,"YEAR",drop=F]+1,
    "MATCH"=DATA[,"SCORE"]
  ),
  by=c("STUDENT","YEAR","TRIMESTER"),
  all.x=T
)
DATA$WANT=DATA$SCORE-DATA$MATCH

result
   STUDENT YEAR TRIMESTER SCORE MATCH WANT
1        1 2000         1     5    NA   NA
2        1 2000         2     7    NA   NA
3        1 2000         3     8    NA   NA
4        1 2001         1     9     5    4
5        1 2001         2    10     7    3
6        1 2001         3     3     8   -5
7        2 2000         2     4    NA   NA
8        2 2000         3     6    NA   NA
9        2 2001         1     3    NA   NA
10       2 2001         2     1     4   -3
11       2 2001         3     2     6   -4
12       3 2001         1     3    NA   NA
13       3 2001         2     6    NA   NA
14       3 2001         3     9    NA   NA

R Lag Two Variables


Set column value to the value of the next row if a condition is true for pandas

Question: I have a pandas dataframe where I want to overwrite the value of another column with the value in the next row, if a condition is true for a different column.  For example, my data looks like this:

col1
col2

30
False

40
True

50
False

And I want the value in col1 where where col2 == True to be set to the value in col1 of the row following, like so:

col1
col2

30
False

50
True

50
False

I've tried df.loc[df.col2 == True, 'col1'] = df.col1.shift(), which doesn't work.  I suspect this has to do with the shift() function but I'm not sure how to overcome this without resorting to some kind of custom apply function.
Comment: add a `peroids=-1` argument in `shift()`
Answer: You should give shift(-1) if you want the next row.
import pandas as pd
df = pd.DataFrame({'col1':[30,40,50],
                   'col2':[False,True,False]})
print (df)
df.loc[df['col2'],'col1'] = df['col1'].shift(-1)
print (df)

Here's the output:
Before:
   col1   col2
0    30  False
1    40   True
2    50  False

After:
   col1   col2
0  30.0  False
1  50.0   True
2  50.0  False


Slope calculation misunderstanding for linear function

Question: In my Math book I'm solving a case where this is the situation:
"The demand curve for good X is linear. At a price (p) of 300 the demand is 600 units. At a price of 680 the demand is 220 units. Also the supply curve for good X is linear. If the price is 400 then the supply equals 200 units, whereas for a price of 800 the supply will be 1000 units."
I'm asked to formulate the system of equations.
For the demand function I did:
SLOPEqd = delta y / delta x = -1 (delta y 680-300, delta x 220-600)
Which I could use and verify by the coordinates and I got the formula Demand(x) = -x + 900)
If I do the same for the supply function I end up wrong:
SLOPEqs = delta y / delta x = 0.5 (delta y 800-400, delta x 1000-200)
If I try to verify this for the first supply point (800, 1000) I would get:
Supply(x) = 0,5x + 600 but this is incorrect for the second point (400, 200). In the answers I found the slope for the supply function should be 2 instead of 0,5. Why is this? I think I'm overlooking something super obvious, but please enlighten me.
(sorry, I haven't figured out how to write the equations as fancy as I see them in other questions)
Comment: My recommendation is that always in this kinds of graph questions, to take some paper and sketch the graph :) Then you would have immediately seen what the problem is.
Answer: You have your $x$ and $y$ co-ordinates the wrong way round. Supply is your $y$ co-ordinate (dependent variable) and Price is you $x$ co-ordinate (independent variable) so you should have
$\Delta y = 1000 - 200 = 800$
$\Delta x = 800 - 400 = 400$
$\text{Slope } = \frac{\Delta y}{\Delta x} = \frac{800}{400} = 2$
$\text{Supply } = 2 \times \text{Price } - 600$
You had your $x$ and $y$ co-ordinates the wrong way round in your Demand calculation as well, but since the slope there is $-1$ whichever way  round you have the co-ordinates, this did not matter.
Answer: For supply you have computed the following:

SLOPEqs = delta y / delta x = 0.5 (delta y 800-400, delta x 1000-200)
If I try to verify this for the first supply point (800, 1000) I would get:
Supply(x) = 0,5x + 600

Presumably, this is because you think the point $(x,y) = (800,1000)$ should lie on the graph of this function.
Now look carefully. In one place you have $\Delta y = 800 - 400,$
in another you have $x = 800.$ But the $800$ comes from the exact same given quantity (a price on the supply curve) in both places. So is it a value of $x$ or a value of $y$?
If you decide prices should be $x$ in both places, then you'll have
$\Delta x = 800 - 400 = 400,$
$\Delta y = 1000 - 200 = 800,$ and slope $\Delta y/ \Delta x = 2.$
Then when you try $(x,y) = (800,1000)$ you'll get
$$ S(x) = y = 2x - 600. $$
On the other hand, if you say price should be $y$ in both places, you'll still have the slope $0.5,$ but now you're trying to fit a function to the point
$(x,y) = (1000,800),$ from which you get
$$ y = 0.5x + 300 = 0.5 S(y) + 300. $$
As noted in another answer, the conventions of economics are confusing in the regard that they tend to plot the supply and demand curves with quantity on the horizontal axis and price on the vertical axis,
yet the supply and demand functions give quantity as a function of price.
My recommendation to minimize the confusion about this is:
Never use $x$ or $y$ to denote a price or quantity (of supply or demand).
Always use $P$ for price and $Q$ for quantity (possibly with subscripts) when you are naming variables.
Comment: I completely forgot to thank you for your help. Thanks! +1
Comment: Oh, good, I'm glad to know it was helpful!
Answer: I suspect that this is because of the strange (to me) way these things are defined.
According to the Demand curve and Supply curve Wikipedia pages, these are conventionally plotted with price $P$ on the vertical (i.e. $y$) axis, and quantity $Q$ on the horizontal (i.e. $x$) axis, which is exactly what you have used to calculate your slopes.
However the demand function and the supply function are conventionally written in the form $Q=$ function of $P$, so the plots are actually plots of the inverse demand function and the inverse supply function. If that is what is being asked for, your slopes need to be converted into their inverses.
Comment: I completely forgot to thank you for your help. Thanks! +1


How to do songwriting starting from the lyrics, if I don't play any instrument?

Question: I usually write new songs starting with a free backtrack. Then I imagine which words and melodies can go with it and in that way it's pretty easy to write a new song. Finally I can sing them at open mics.
However, now I started writing some beautiful lyrics for which I don't have any music yet. I would like to add the music, but I don't play any instruments myself.
What's the best way to transform my lyrics into music by myself, without the support of other musicians?
Comment: The obvious answer seems to be... you'll have to become a musician!
Comment: I struggle to understand the question. If you're not a musician and you don't want to work with one then putting your lyrics to music seems a strange ambition.
Answer: There are various software packages that let you create chords (harmony) and apply drum tracks (rhythm).  Some are free - depending on the level of sophistication you want.
If you look at common song structures (verse, chorus, bridge), and have good lyrics and phrasing, you can experiment with adding the above.
Just look up common chord progressions (e.g. I IV V).  As you experiment, you will learn which chord progressions provide the harmony and feelings you want behind your lyrics.
If you sing the lyrics - your voice is the melody.  Everything can become more sophisticated as you add other instruments and musicians, but you can start with something very simple.
These are all the pieces you need, in order of priority:  melody (lyrics), rhythm, harmony.
Comment: The OP says they aren't a musician. How is telling them about `I IV V` going to help?
Comment: Yes, they can look it up, but what they find won't be meaningful to them. The OP's purpose isn't _music appreciation_ it's composing. "...without investing the rigor of learning to play..." Except for a few unusual people, this approach won't work.
Comment: Understanding I IV V is very simple, and takes only a bit of theory.  Playing a musical instrument requires hundreds or thousands of hours of investment.  The OP is asking how to bypass that huge investment and understand/create musical ideas.
Comment: OP writes they can sing. Obviously they are a musician already. Perhaps they need to expand their theory knowledge. Perhaps they can use some software or hardware tools to produce music. Perhaps they can try to learn to play an instrument. Maybe they can collaborate with an instrumentalist? There are many ways. I don't see anything incorrect in this answer.
Answer: Try this: get any song, rewrite the lyrics using the same melody (parody), turn off the song and create a new melody. Or sing it with the same melody. That's similar how Yesterday (Beatles) was born. The original lyrics was about Scrambled Eggs
I like using Randomizer for faster songwriting.
Random Music Generators https://random-music-generators.herokuapp.com/melody
Melody creator: I recommend this app
https://play.google.com/store/apps/details?id=com.dmbmobileapps.musicgen
Melody Engineer Lite: https://play.google.com/store/apps/details?id=com.gyokovsolutions.melodyengineerlite
Guitar Engineer Lite: https://play.google.com/store/apps/details?id=com.gyokovsolutions.guitarengineerlite
Linear Drum Patterns Generator: https://play.google.com/store/apps/details?id=com.vk.patterngenerator
Composer: https://play.google.com/store/apps/details?id=com.jpglomot.composer2
WolframTones (Tons of scales and modes): https://tones.wolfram.com/generate/GlPZHFM1w5S2cZKaBOAsPRIoXIg3MyHmXagJauuvpoSWL
Answer:
...but I don't play any instruments myself. What's the best way to transform my lyrics into music by myself, without the support of other musicians?

It seems like your question is straight forward, but there are some details left out.
You said "other musicians." Other than who? Do you mean yourself as a musician? You said you don't play an instrument. Can you sing? Do you plan to become a musician for the sake of setting your lyrics to music on your own?
If you want to compose chords for your songs, the typical instruments to use are piano or guitar. Learning to "comp" some chords to support your singing isn't too difficult. It depends on your motivation, but you could get up to speed with comping at a basic level on either instrument in 1 year.
If you don't want to bother with piano or guitar, I think you still need to be able to sing. At a minimum you need to be able to make a melody for your words and you could do that alone by singing.
If you only sing the melody, you could use various apps to add accompaniment, the bass, drums, chords, etc. There are impressive apps available. Some can even automatically harmonize from only a vocal part. You might find digital tools to fit your need.
In the end, if you cannot find a way to set your lyrics to music on your own, just remember this: you can always call yourself a lyricist. You would be in good company with Ira Gershwin, Hammerstein, Taupin, and many others.
Answer: I would suggest that the easiest way for you to compose music to your lyrics would be to get an electric keyboard that has built-in rhythms and single finger chord ability. There are many models available in different price ranges that can do this.
If your verses don't match a specific rhythm that the keyboard contains you could use the basic metronome function to keep the beat steady.
The single finger chords basically play a full chord for each key you hit. You would then play some of the keys, listening to the chord and trying out your lyrics against the chords. Experimenting with changing the chord at different times during your verses will let you develop what changes you think sounds best. With enough repetition you can settle in on chord changes and what melody you want.
Many of the keyboards have a recording function, allowing you to save your creation. Once you have a progression figured out, the keyboard layout is simple enough to figure out what chord names you ended up playing, and some of the keyboards are USB enabled and able to export a chart for you.
You could even use the keyboard live this way for your open mic adventures, and working with the chord changes can open you up to starting to learn the music theory behind what you are doing, and how to start creating the chords on the keyboard yourself to expand the range of sounds and tones available to you to compose with.
Answer: The best way it to start learning to play an instrument. If you still what to focus more on the lyrics and signing then you can use Arcade by Output. They have 30 days free trial and after that is $10 / month. Their platform has a bunch of loops, instruments that you can use with a mouse click. Arcade by Output website


Como pegar um array de uma tabela e buscar em outra tabela em Ionic e AngularJS

Question: Tenho um campo numa tabela com um array de números:
2;3;7;8;9;10;11;15;1

Cada número destes corresponde a um ID de uma outra tabela. Preciso listar os itens desta outra tabela de acordo com o array. Não estou conseguindo chegar a uma lógica favorável.
Alguma solução?
Comment: Não ficou muito claro para mim quando você diz "outra tabela". Esses dados estão em um array, array de objetos? Se sim, poderia usar o filter.
Comment: @Ramos esse array de números é separado com ; mesmo?
Comment: Alguma das resposta lhe foi útil? Não esqueça de escolher uma e marcar o ✅ para que possa ser utilizada caso alguém tenha uma dúvida similar!
Answer: Fiz um plunker para tentar exemplificar. Veja se é isso que você precisa.
Comment: Olá Danilo, acho que o que ele quer é o contrário, ele quer pegar tudo referente ao primeiro array
Comment: Opa, boa tarde. Nesse caso ele pode alterar a condição.
Comment: @DaniloSilva Seu exemplo foi perfeito. Mas olha no Plunk que fiz a respeito do que estou tentando fazer. Tem alguma coisa muito errada no meu código: https://plnkr.co/edit/Ovg4WHLTdNeOM9Eeae8c?p=preview
Comment: @DaniloSilva Tentei também:  for (var i = 0; i < $scope.array2.length; i++){
                   if ( $scope.array1.indexOf(parseInt($scope.array2[i].categoria_comida_cod_categoria_com)) >= 0 ){

                    $scope.array3.push($scope.array2[i]);

                     }

                 }
Comment: Mas mesmo resultado.
Comment: @Ramos, Haviam algumas inconsistência no seu código. Veja o código [link]http://plnkr.co/edit/2q1dYUsIscHXiv6dbBMR?p=preview com a correção. Agora é só fazer a lógica conforme a sua necessidade.
Comment: Pessoal, muito obrigado! :))))


How to Focus on Input Field after Navigation

Question: How to focus on input field after navigating back from a child page?
Child Page
onNavigateBtnClick: function() {
    var oHistory = History.getInstance();
    var sPreviousHash = oHistory.getPreviousHash();
    if (sPreviousHash !== undefined) {
        history.go(-1);
    } else {
        var bReplace = true;
        this.getRouter().navTo("HomePage", {}, bReplace);
    }
},

Parent Page
onAfterRendering: function() {
    jQuery.sap.delayedCall(500, this, function() {
        this.getView().byId("InputField").focus();
    });
},

Problem

When the nav back button is clicked first time, the onAfterRendering hook is called.
If I do some action on child page then click on the nav back button, the onAfterRendering method would not be called.
Comment: Does this answer your question? [How to Set Initial Focus in a View?](https://stackoverflow.com/questions/36376599/how-to-set-initial-focus-in-a-view)
Answer: Three steps to solve this:
Update your <App> tag of the view to have  autoFocus="false". This will prevent UI5 from autofocusing the first input of the view.
In your controller's onInit, attach a method to the route that will fire when the view is navigated to, like this:
onInit: function(){
    var router = sap.ui.core.UIComponent.getRouterFor(this);

    router.getRoute("routeTargetName").attachPatternMatched(this.onNavTo, this);
}

Declare the onNavTo method in your controller that will set the focus of your input:
onNavTo: function(route){
    this.byId("MyInputField").focus();
}

Now whenever you use your router to navTo("routeTargetName"), the onNavTo method will fire, which will set focus on the field.


How to find child-parent tree from sql table

Question: I have a table child where I have below structure:
id  child_name  parent_id   parent_name
1   vikas        2           sunny
2   john         3           seema
3   ajay         4           delhi
4   josh         4           main

I am trying to find child to parent till parent_name matches to main, then I will stop. I need single query sql if it is possible.
I tried this but it is giving me only one level.
SELECT ChildUserType.child_name,
       ChildUserType.parent_name,
       ParentUserType.id,
      ParentUserType.parent_id
FROM groups AS ChildUserType
  LEFT JOIN groups AS ParentUserType
         ON ChildUserType.id = ParentUserType.parent_id
where ChildUserType.id='1';

Comment: Can you please show what you have tried so far? At SO, we would like to help out on technical problems or the like, we cannot provide code from scratch. Please read our [how to ask guide](http://stackoverflow.com/help/how-to-ask) for more details
Comment: i m editing this with my answer.
Comment: i am trying to pass where id = 1,then trying to find all child where id=1.
Comment: Which DBMS are you using? [Modern DBMS](http://modern-sql.com/slides) support recursive queries
Comment: i am using mysql .
Comment: You can't do this in a single SQL statement with the limited features of MySQL - it doesn't support recursive queries. You need to process this data in your application in a loop or change your database design (or upgrade to Postgres). For MySQL solutions see here: http://stackoverflow.com/questions/tagged/mysql+hierarchical-data
Comment: can u help me with this sql if possible;
Answer: You can try this :
CREATE PROCEDURE find_ancestry(IN id_init int)
 BEGIN
 DECLARE child_id int;
 DECLARE prev_id int;
 SET prev_id = id_init;
 SET child_id=0;
 SELECT parent_id into child_id
 FROM groups WHERE id=id_init ;
 create TEMPORARY  table IF NOT EXISTS temp_table as (select * from groups where 1=0);
 truncate table temp_table;
 WHILE child_id <> 0 DO
   insert into temp_table select * from groups WHERE id=prev_id;
   SET prev_id = child_id;
   SET child_id=0;
   SELECT parent_id into child_id
   FROM groups WHERE id=prev_id;
 END WHILE;
 select * from temp_table;
 END //


Appending data with unequal data frame dimensions

Question: What is the best way to append data using matching column names from two different data frames with differing dimensions?
Scenario:
Df1 = 350(rows)x2778(columns)
Df2 = 321x2910
Df1 has <2778 columns with the exact same name as <2910 columns in Df2.
-It could be 500 columns in each data frame as an example that have equivalent names
What I want to do:
Append data from df2 to df1 where the column names match.
E.x.: df1's data is present in matching column and has df2's data appended to the end of the column, put underneath it so to say.
If the col names don't match, the data frame that lacks the matching name should have the name attached as a new column with NA's filling the missing space.
E.x.: df1 doesn't have a column df2 has, so the column is added while maintaining order of processing.
I've tried to do this using Pandas in Python but got Index duplication errors (probably the columns). I'm looking at R now but I want to know if anyone has a simple solution.
Thanks!
Comment: Please provide sample code and data.
Comment: Concat should do the trick. `new_df=pd.concat([df1, df2])`
Comment: It will be ever so much easier to help you with your specific question if you can find a way to share some fake example data that demonstrates the general structure of your two data frames (a couple rows and columns may be enough) and what output you expect. This sounds like `rbind` or `dplyr::bind_rows` might do it.
Comment: Please provide enough code so others can better understand or reproduce the problem.
Answer: Check out merge() from base r or bind_rows() from dplyr.
Comment: dplyr::bind_rows() did it!


Add class to column in a table

Question: I have a table in a form such as the 'user_admin_account' form. In one of the TD's I want to add a class, how do I do this the most convenient way?
This is what I currently have, it doesn't seem to work
$row = array(
  'title' => array(
    'data' => array(
      '#title' => $name . ' ' . $surname,
      '#attributes' => array(
        'class' => array(
          'myClass',
        ),
      ),
    ),
  ),
  'date' => date('Y-m-d', $account->created),
  'name' => $name . ' ' . $surname,
);

Answer: The variables for theme_table() are structured differently to a standard render array, so you need to format your array slightly differently:
$row = array(
  'title' => array(
    'data' => $name . ' ' . $surname,
    'class' => array('myClass')
  ),
  'date' => date('Y-m-d', $account->created),
  'name' => $name . ' ' . $surname,
);

The above produces:

      1970-01-01

The first and last column are only empty as my test environment doesn't have the same variables defined as in your code.
Comment: This looks ok, but it means hardcoding field names. It makes the code depend on the fields and views configuration. Are you aware of any solution that allows to configure the column class in the UI ?
Answer: The documentation for theme_table() describes what the function is expecting in $variables['rows'], and it says:

rows: An array of table rows. Every row is an array of cells, or an associative array with the following keys:

"data": an array of cells
Any HTML attributes, such as "class", to apply to the table row.
"no_striping": a boolean indicating that the row should receive no 'even / odd' styling. Defaults to FALSE.

The example present in that page is the following one:
$rows = array(
  // Simple row
    array('Cell 1', 'Cell 2', 'Cell 3'),
    // Row with attributes on the row and some of its cells.
    array(
      'data' => array('Cell 1', array('data' => 'Cell 2', 'colspan' => 2)), 'class' => array('funky'))
    );

In that example, "funky" is the CSS class applied to the second row, which contains two cells; the second cell takes the room of two cells (because the 'colspan' => 2 part).

Add class to column in a table


Two sets of fingerings printed for one same bar?

Question: 2nd movement of Beethoven's sonata Op. 49, No. 2. Bar 7. One edition seems to show two sets of fingering numbers: 4-3-2, and 4-4-2? What does it mean?
Answer: It means that either is a possibility, and you can choose whichever best fits your technique and musical intention.
Comment: Schenker, the editor of this edition, was a famous music theorist and editor.  He really went to town on the fingerings in his edition of the Beethoven sonatas.  Strangely, although he provides two choices here, he doesn't provide the one I would automatically use - 4 3 1 (and then land on the G with 2).
Comment: @seamurmurs You're correct that editorial fingerings are just suggestions and there are alternatives. In this case, I can only make an educated guess: sliding finger four from C# to C-natural is a bit unusual, especially in Beethoven, so it's possible the editor felt it should be explicitly mentioned.
Comment: @seamurmurs The Schenker edition is one of the standards — and very distinctive looking. You can find it on [IMSLP](https://imslp.org/wiki/Piano_Sonata_No.20%2C_Op.49_No.2_(Beethoven%2C_Ludwig_van)).
Comment: @cruthers - you got me there. Why put 2 over onto G? It's moving the whole hand in the wrong direction, considering what comes next.
Comment: @Tim it's all personal preference, but I also find cruthers's suggestion natural. I just find the hand-shape with 4 on C#, 3 on C, 1 on A more comfortable than the one with 2 on A instead. Different if there were an octave's leap up on the next quaver, but I don't feel an issue about moving the hand in the wrong direction when the next note is just a third above and there's a whole beat's rest in between....
Comment: @Tim: Agree with JamesMartin - just feels more comfortable for some reason.  I played it a couple of times.  3 2 1 and then 2 on G also feels good.  The cross to G doesn't feel like a big hand move.  I then found myself transferring the G from 2 to 1, even though that's completely unnecessary because I'm lifting my hand a bit for the rest anyway.  It's unconscious, would have never guessed that I would do it.  Maybe it's a habit - when I know the next note is higher, and I have time, I transfer to maximize options.  You might play the following three Bs with 4 3 2.
Comment: Thanks, Aaron. I thought if this was the case, wouldn't most of the scores and bars of any given work also have alternatives? Somehow for this particular bar the editor felt the need to show two choices?
Comment: @cruthers Thanks, good to know. I can't find the editor's name.
Comment: @Aaron Thanks. As I look a bit ahead, "sliding finger four from C# to C-natural" seems to make sense for Bar 19.
Comment: Just to point out another option, for a while I fingered that 431 and then 1 on G, purposely using the same finger on successive notes to force myself to articulate the slur.
Answer: Your example and a few others showing multiple sets of fingerings.
Your example...

...shows fingering alternatives.
Sometimes you see this in technique manuals...

...in that example the "German, English, French" labels help show the stacked up numbers are rows of alternate fingerings.
Also, multiple sets can be shows not so much as alternate fingers, but to give the meaning more of you should be able to do this movement with all digit combinations...

Fairly common is fingerings above and below notes on a single staff...

...in that example, the RH and LH markings make clear the two sets of numbers are for right hand and left hand instead of taking up more page space with a grand staff. That's really about simplifying the printed page.
Stacked fingering numbers are also used for chords or playing double notes in one hand...
Comment: I remember the (confusing) days when *fingers* were numbered 1234, and thumb was +. So 1 was index finger.
Comment: I new a pianist who told me that long ago - I think he meant Renaissance and Baroque - the thumb wasn't used on keyboard. He said is was considered _vulgar_! Not sure how historically true that is, but the 1-4 fingering from old seems to match up with the idea.
Comment: Perhaps, then, thumb should have been x, but + seems the right one.
Answer: Clearly, they're options. The idea of using the same finger to play a black key and the adjacent white key either up or down, is one technique that piano players have developed and particularly here, where the two notes are marked as slurred, it's an easy option. Not necessarily a necessity, as there's enough fingers left using even the top fingering, to land on G with the thumb, especially when the next note is only up by a third.
Answer: A typical convention for multiple sets of fingerings is that the upper fingering is the musically preferable version while the lower version is more accessible.  Now my experience is from playing the violin where this quite commonly corresponds to the top version assigning phrases better to the different strings while the bottom version tends to focus on using "simpler" positions (according to the order in which learners tend to acquire and utilise positions and their changes).
I don't know whether there are similar semi-objective measures of difficulty vs musicality on the piano or whether there is not really a similar division and this is just an offer of alternatives, possibly related to hand size.
Answer: Interestingly, in Beethoven sonatas, the alternative fingerings are often his own suggestions.
I used the Henle edition when I was studying them, and they put italic numbers for Beethoven's suggestions. I don't remember whether your example is one of Beethoven's suggestions, but I suspect that it is.
Like Beethoven's pedal markings, his fingering suggestions have to be taken with a grain of salt, because his piano was very different from the ones we have at present. The notes don't last as long (so some long pedal markings get muddy on a modern piano), and the action is lighter, so some fingerings won't work well on a modern piano.
Comment: @seamurmurs That is the sort of fingering that I often have noticed in what I know to be his suggestions, so I suspect it is. Although "preference" is perhaps too strong a word in the sense of whether he expected others to use it, his suggestions give some insight into how he wants things to be articulated, so it's a good idea to experiment with them.
Comment: Thanks for the interesting info! In this particular case, I have since found that alternative fingering (sliding finger 4 from C# to C) works pretty well--it fits the hand shape better. I hope it's Beethoven's preference :) .


Extract private key from Domino keyring

Question: I'm trying to use a multipurpose certificate on an infrastucture that contains a Domino 7 server.
To accomplish this, I tried:

Generate a CSR outside of Domino: I'm able to use the produced certificate everywhere but not on Domino because it requires to generate a keyring and the correspondent CSR
Generate the keyring and the CSR in Domino: everithing (services) work well in Domino, but I'm not able to extract the private key to use the certificate for other purposes

For the attempt 2. I found that someone used a tool named IKEYMAN from IBM; it's been quite difficult to find a download for IKEYMAN.
IKEYMAN can open a Domino keyring and export it to KDB format or in a .class; I was not able to use any of the formats IKEYMAN exports to extract the private key. Someone on Lotus forums says that he did the trick, but I'm missing something: in the keyring I was not able to find any private keys.
My question is: can I extract the private key from a Domino keyring? In the case of the need to use a tool, where exactly can I find this tool?
Comment: I haven't foun an answer... I ended up with the 'certificate copy' function provided by the CA supplier: different copies of the same certificate produced from different CSRs. I agree for the move to SF.
Answer: Here is the link to IBM's public Download site.. Hope it helps
ftp://ftp.software.ibm.com/software/lotus/tools/Domino/gsk5-ikeyman.zip
If the above link doesn't work, try this:
https://ftpmirror.your.org/pub/misc/ftp.software.ibm.com/software/lotus/tools/Domino/gsk5-ikeyman.zip
Comment: For me IKEYMAN does not start. When I run _runikeyman.bat_ from command prompt it just shows the path etc and returns to "C:\Program Files\IBM\GSK5>". Nothing is launched. I've tried many instructions including this one http://www-10.lotus.com/ldd/nd85forum.nsf/5/d8153f5591411ed185257d2f00765653 but the result is always the same. I've tried it on 3 PCs and one server (Win 10, 7 and 2003). Any ideas?
Answer: IBM support helped me on this one.

Download the new key ring tool and save the appropriate version to program directory of your Notes client.
kyrtool show keys -k <path to keyring file>

Extract private key from Domino keyring


Cannot get my tic-tac-toe game to run correctly in python

Question: I did a code-along for a tic-tac-toe game written in python. I have followed the steps exactly but I think the game was written specifically for a Jupyter notebook because it is not working properly for me in a real python interpreter (I wrote out all the code in VS code). It randomly assigns which player will go first, which it's supposed to, but that player's marker is not assigned correctly and the other player never gets to move. Additionally, the player that does move, whenever they choose a spot on the top row (indexes 7-9), it is an automatic win.
This is in Python 3. I have tried to debug but the code is syntactically valid so I cannot pinpoint the logical issues with it.
def display_board(board):  # Board setup
  print('\n'*100)
  print(board[7] + '|' + board[8] + '|' + board[9])
  print(board[4] + '|' + board[5] + '|' + board[6])
  print(board[1] + '|' + board[2] + '|' + board[3])

def player_input():  # Player assignment - use while loop to keep asking until a valid character is entered

    marker = ''
    while marker != 'X' and marker != 'O':
        marker = input('Player1: Choose X or O: ').upper()

    if marker == 'X':
        return ('X','O')
    else:
        return ('O','X')

def place_marker(board, marker, position):   # Allows player to place their marker at specific board index

    board[position] = marker

def win_check(board, mark):  # Check all rows, columns, diagonals for sharing the same marker to check for a winner
    return ((board[1] and board[2] and board[3] == mark) or   # Rows
    (board[4] and board[5] and board[6] == mark) or
    (board[7] and board[8] and board[9] == mark) or
    (board[1] and board[4] and board[7] == mark) or   # Columns
    (board[2] and board[5] and board[8] == mark) or
    (board[3] and board[6] and board[9] == mark) or
    (board[1] and board[5] and board[9] == mark) or   # Diagonals
    (board[3] and board[5] and board[7] == mark))

import random

def choose_first():  # Randomize who goes first

    flip = random.randint(0,1)
    if flip == 0:
        return 'Player 1'
    else:
        return 'Player 2'

def space_check(board, position):   # Check to see if a space on the board is still available
   return board[position] == ' '

def full_board_check(board):  # Checks to see if board is full resulting in a draw
    for i in range(1,10):
        if space_check(board,i):  # If there is free space, board is NOT full
            return False
    return True

def player_choice(board):  # Asks for the player's next move choice
    position = 0

    while position not in [1,2,3,4,5,6,7,8,9] or not space_check(board, position):
        position = int(input('Choose a position: (1-9): '))

    return position

def replay():   # Asks if the players want to play again
    choice = input("Play again? Enter Yes or No: ")
    return choice == 'Yes'

# Logic to run the game
# While loop needed to keep running the game
# Need to break out of the while loop on replay()

print ('Welcome to TIC TAC TOE')

while True:
    # Game Setup (Board, Players, Player turns)
    the_board = [' ']*10
    player1_marker,player2_marker = player_input()

    turn = choose_first()
    print(turn + ' will go first')

    play_game = input('Ready to play? y or n: ')
    if play_game == 'y':
        game_on = True
    else: game_on = False

    # Game Play
    while game_on:
        if turn == 'Player1':
            # Show the board
            display_board(the_board)
            # Choose a place to move
            position = player_choice(the_board)
            # Place the marker on the position
            place_marker(the_board,player1_marker,position)

            # Check if they won
            if win_check(the_board,player1_marker):
                display_board(the_board)
                print('PLAYER 1 HAS WON!')
                game_on = False
            else:
                if full_board_check(the_board):  # Check for tie
                    display_board(the_board)
                    print("TIE GAME!")
                    game_on = False
                else:
                    turn = 'Player 2'

        else:
            # Show the board
            display_board(the_board)
            # Choose a place to move
            position = player_choice(the_board)
            # Place the marker on the position
            place_marker(the_board,player2_marker,position)

            # Check if they won
            if win_check(the_board,player2_marker):
                display_board(the_board)
                print('PLAYER 2 HAS WON!')
                game_on = False
            else:
                if full_board_check(the_board):
                    display_board(the_board)
                    print("TIE GAME!")
                    game_on = False
                else:
                    turn = 'Player 1'

    if not replay():
        break

I want the game to go back and forth between each player with the correct markers assigned to them and I cannot figure out why this isn't happening as it looks correct to me.
Comment: For what it does you code is too complex. Try using simple 2d matrix for board. I am sure once you simplify things a bit you will spot the issue, for someone that didn't write the code it will be harder.
Answer: Your issue with it not changing turns is due to a typo: you set turn = 'Player 1', but then check if turn == 'Player1' (no space). Your other error with instant wins is due to the section with comparisons like (board[1] and board[2] and board[3] == mark). This does not work, as board[1] and board[2] are converted to boolean True (since they are ' ' not ''). You need to use (board[1] == mark and board[2] == mark and board[3] == mark), or more concisely all(board[i] == mark for i in (1,2,3)).
Comment: Ah, I had a feeling there were spacing issues causing troubles I just couldnt figure out where. And that for loop is alot more concise, thanks!
Answer: The reason the turn was not going properly to "Player 1" is because you had a space missing in the check for that player. You also are not properly checking for when a player wins, which is why you are having that weird top row behavior. You need to check every position, not just the last one. I also added a check on user input to make sure that what the user enters is a number and it does not crash if not.
I totally do not understand why you basically print your board upside down but I left that as is.
Try this:
import random

def display_board(board):  # Board setup
  print('\n'*100)
  print(board[7] + '|' + board[8] + '|' + board[9])
  print(board[4] + '|' + board[5] + '|' + board[6])
  print(board[1] + '|' + board[2] + '|' + board[3])

def player_input():  # Player assignment - use while loop to keep asking until a valid character is entered

    marker = ''
    while marker != 'X' and marker != 'O':
        marker = input('Player1: Choose X or O: ').upper()

    if marker == 'X':
        return ('X','O')
    else:
        return ('O','X')

def place_marker(board, marker, position):   # Allows player to place their marker at specific board index

    board[position] = marker

def win_check(board, mark):  # Check all rows, columns, diagonals for sharing the same marker to check for a winner
    return ((board[1] == mark and board[2] == mark and board[3] == mark) or   # Rows
    (board[4] == mark and board[5] == mark and board[6] == mark) or
    (board[7] == mark and board[8] == mark and board[9] == mark) or
    (board[1] == mark and board[4] == mark and board[7] == mark) or   # Columns
    (board[2] == mark and board[5] == mark and board[8] == mark) or
    (board[3] == mark and board[6] == mark and board[9] == mark) or
    (board[1] == mark and board[5] == mark and board[9] == mark) or   # Diagonals
    (board[3] == mark and board[5] == mark and board[7] == mark))

def choose_first():  # Randomize who goes first
    flip = random.randint(0,1)
    if flip == 0:
        return 'Player 1'
    else:
        return 'Player 2'

def space_check(board, position):   # Check to see if a space on the board is still available
   return board[position] == ' '

def full_board_check(board):  # Checks to see if board is full resulting in a draw
    for i in range(1,10):
        if space_check(board,i):  # If there is free space, board is NOT full
            return False
    return True

def player_choice(board):  # Asks for the player's next move choice
    position = 0

    while position not in [1,2,3,4,5,6,7,8,9] or not space_check(board, position):
        try:
            position = int(input('Choose a position: (1-9): '))
        except:
            print("Please enter a valid number.")

    return position

def replay():   # Asks if the players want to play again
    choice = input("Play again? Enter Yes or No: ")
    return choice == 'Yes'

# Logic to run the game
# While loop needed to keep running the game
# Need to break out of the while loop on replay()

print ('Welcome to TIC TAC TOE')

while True:
    # Game Setup (Board, Players, Player turns)
    the_board = [' ']*10
    player1_marker,player2_marker = player_input()

    turn = choose_first()
    print(turn + ' will go first')

    play_game = input('Ready to play? y or n: ')
    if play_game == 'y':
        game_on = True
    else: game_on = False

    # Game Play
    while game_on:
        if turn == 'Player 1':
            # Show the board
            display_board(the_board)
            # Choose a place to move
            position = player_choice(the_board)
            # Place the marker on the position
            place_marker(the_board,player1_marker,position)

            # Check if they won
            if win_check(the_board,player1_marker):
                display_board(the_board)
                print('PLAYER 1 HAS WON!')
                game_on = False
            else:
                if full_board_check(the_board):  # Check for tie
                    display_board(the_board)
                    print("TIE GAME!")
                    game_on = False
                else:
                    turn = 'Player 2'

        else:
            # Show the board
            display_board(the_board)
            # Choose a place to move
            position = player_choice(the_board)
            # Place the marker on the position
            place_marker(the_board,player2_marker,position)

            # Check if they won
            if win_check(the_board,player2_marker):
                display_board(the_board)
                print('PLAYER 2 HAS WON!')
                game_on = False
            else:
                if full_board_check(the_board):
                    display_board(the_board)
                    print("TIE GAME!")
                    game_on = False
                else:
                    turn = 'Player 1'

    if not replay():
        break

Comment: Wow, I thought I was simplifying things by not including the "==mark" after every index and I had a feeling there was a spacing issue somewhere. Thanks for the help! And as for why my board is printed "upsided down" it just so that it resembles a numpad on keyboard so people playing can use it as a better reference.
Comment: @alex_a I see. Well, if your problem was resolved then please mark my answer as correct!


HibernateSearch - Modify the StandardTokenizerFactory to concatenate all words

Question: I'm using the StandardTokenizerFactory as my @TokenizerDef in my Hibernate class. I would like to keep the way the StandardTokenizerFactory tokenizes words but add another rule to create a token by concatenating (specfically removes all spaces) all the words in a field.
What is the easiest way or any alternatives methods to achieve what I want?
Answer: I think what you need is another token filter (factory) in your filter chain. Have you had a look at ShingleFilterFactory? It does something very similar and the token separator can be configured. Not sure whether it can be the empty string as well. If nothing else you can write your own ConcatenatingFilterFactory based on ShingleFilterFactory.


how to uncompress a folder with with extension gzip

Question: I'm having a problem with a folder with an extension .gz in the client side which contains xml files in it. I have to download the folder into local directory then i need to extract the folder.
I was able to download the .gz folder into local, but I'm unable to extract the folder.
I tried using the
ZipArchive::extractto($targetfolder);

But it is not accepting the .gz.
When i search through stack overflow i found only answers for .gz files not for .gz folders.
Comment: What is it a `gz` folder? `gz` is a file format. Is it just a folder that was named `something.gz`?
Comment: did you try right clicking on it and clicking "extract"?
Comment: Yes it is named with the file.xml.gz
Comment: when i extracted the folder by right clicking on it a file with the name file.xml extracted into the folder file.xml
Answer: Try using PHP's built-in gzfile() function.
This will uncompress the file in 4kB chunks:
function uncompress($srcName, $dstName) {
    $sfp = gzopen($srcName, "rb");
    $fp = fopen($dstName, "w");

    while ($string = gzread($sfp, 4096)) {
        fwrite($fp, $string, strlen($string));
    }
    gzclose($sfp);
    fclose($fp);
}

Comment: Hi -- I'm just curious if what I suggested above worked for you.
Answer: The documentation for ZipArchive doesn't say anything about being able to open gz format files (zip and gz are not the same). You may need to use Zlib to decompress your gz file, and if it's a tar.gz or tgz file, you'll also need something to untar the file.
This question and this newer question discuss how to extract a tar.gz file in PHP.


Variance Estimator Change if we know Population Mean? (Normal dist. example)

Question: For a normal distribution $N(\mu, \sigma^2)$ a commonly used unbiased and consistent estimator of variance is
$$\hat \sigma^2=\frac{\sum_ix_i^2 + n(\bar x)^2}{n-1}=\frac{\sum_i(x_i-\bar x)^2}{n-1}$$
However, suppose we know the population (true) mean, should the estimator be adjusted to reflect that, meaning should my estimator instead be:
$$\hat \sigma^2=\frac{\sum_ix_i^2 + n(\mu)^2}{n-1}=\frac{\sum_i(x_i-\mu)^2}{n-1}$$
?
Answer: Your estimated variance in the case where the population mean $\mu$ is known, has
the wrong denominator (if it is to be unbiased). The correct denominator of the unbiased estimate $\hat{\sigma^2}$ of $\sigma^2$ is especially easy to verify in the case of normal data.
To begin, $Z_i = \frac{X_i -\mu}{\sigma} \sim \mathsf{Norm}(0,1).$
So, $Q_i = Z_i^2 = \frac{(X_i - \mu)^2}{\sigma^2} \sim \mathsf{Chisq}(\nu=1)$
and $Q = \sum_{i=1}^n Z_i^2 = \sum_{i=1}^n \frac{(X_i - \mu)^2}{\sigma^2}
\sim \mathsf{Chisq}(\nu = n),$ which has $E(Q) = n.$
Thus (upon multiplying by $\sigma^2/n)$ we have $V =\hat{\sigma^2} = \frac{1}{n}\sum_{i=1}^n (X_i - \mu)^2$ has
$E\left(\hat{\sigma^2}\right) = \sigma^2.$
In the (most common) case where data are normal and $\mu$ is unknown (estimated by $\bar X),$ the relationship
$\frac{(n-1)S^2}{\sigma^2} \sim \mathsf{Chisq}(n-1),$
where $S^2 = \frac{1}{n-1}\sum_{i=1}^n(X_i-\bar X)^2,$ is important
for making confidence intervals for $\sigma^2$ and testing hypotheses about $\sigma^2.$
Similarly, when data are normal and $\mu$ is known , the relationship
$\frac{nV}{\sigma^2} \sim \mathsf{Chisq}(n)$
is important
for making confidence intervals for $\sigma^2$ and testing hypotheses about $\sigma^2.$
Comment: But then this means that the use of the true parameter $$\mu$$ has led to a minor reduction in estimator variance (practically no difference if n is very large)
Comment: Knowing $\mu$ is useful information, and additional  information often reduces variance. Somewhat similarly, if $\sigma$ is known and $\mu$ is not, then a z confidence interval is used to estimate $\mu.$ However, if $\sigma^2$ is also unknown and estimated by $S^2,$ then the (wider) t confidence interval is used for $\mu.$


templatefield or button column

Question: I see a lot of code samples that use template fields for say a button column. However, asp has a ButtonField in gridview columns. What is the difference, if any, between quickly throwing a buttonfield column in a gridview over configuring a templatefield column?
Answer: Any pre-built column will be easier to use, and be automatically data bound.  A templatefield can contain anything, buttons, 10 different buttons, another gridview, etc etc.  So it can be whatever you want, but you need to deal with all the controls inside manually.  If you are just looking for a column with one button, stick to the buttonfield control.

templatefield or button column


Deleting CoreData store on OS X?

Question: I'm playing around with CoreData in a Mac OS X application. After changing an entity i got the following error:

The managed object model version used to open the persistent store is incompatible with the one that was used to create the persistent store.

All answers i've found for this issue suggest implementing versioning/migration into the app, but I'm not interested in saving my data. Isn't there a less complicated solution for that? Like deleting the stock file or something like that? And if yes, where is this file located?
Thanks.
Answer: If you don't want the data, then yes, you can simply delete the old file and create a new one. If your data is document based, then the document itself should be deleted. If you use a single store for the whole application (not document based), then you should look in the code that creates the store object to find the location. The template places the creation code in the application delegate, and the default location for the store is in ${HOME}/Library/Application Support/${APP_NAME}/.
Comment: hmm my applicaiton doesn't seem to be here. anywhere else i could look?
Comment: If your application is in development mode, it will use your bundle identifier e.g ${HOME}/Library/Application Support/com.yourcompany.yourproduct/
Comment: @binnyb You need to find the code which creates the store. It will create the path where it stores the file.
Comment: I found it. it was in the root (/Library/Application Support) directory not home
Answer: On OS X 10.7 Lion when the app is sandboxed, it is stored in:
~/Library/Containers/com.yourcompany.yourAppName/

Answer: I found that for Mac OS X 10.8 / Xcode 4.6 the data is stored in the derived data folder of under
Users/*username*/Library/Developer/Xcode/DerivedData/*app name*-*random string*/Build/Products/Debug/*app name*.sqlite

The easiest way to delete this data is to go to the organiser, select project tab and click "Delete..." button by derived data.
Answer: Alternatively, For OSX, use the Nsfilemanager to delete the file by using the url defined in the lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator{...}
In this var persistentStoreCoordinator a url will be defined that is designed to be used by the persistentStoreCoordinator. You can just use the url defined there to delete the old store. Insert the below code. Run the project and the file will be deleted. Then delete the code to allow objects to be stored again and not delete the data every time.
here is what I found in the lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("CocoaAppCD.storedata")

here is what i put immediately underneath it.
do{
    try NSFileManager.defaultManager().removeItemAtURL(url)
} catch{
    print("could not delete file")
}

then i clicked run. It ran once then i delete the code i just made so that the data would not be deleted every time
Answer: In macOS Big Sur (11.4), local NSPersistentCloudKitContainer Core Data storage can be found at:

~/Library/Containers/yourAppName/Data/CloudKit/
Answer: On Mac OS X 10.11.4 with Xcode 7.3 cleaning the fixed the problem for me:
Product > Clean or Shift⌘K
Answer: Try to run the app in a simulator of another device that you haven't used before and see if it helps you (i.e. iPhone SE instead of iPhone 7). If it does, then removing the corrupted folders should help. Open Terminal and run the following commands:
sudo rm -rf ~/Library/Developer/CoreSimulator/Devices

to remove the simulators' data that might be corrupted,
sudo rm -rf ~/Library/Developer/XCode/DerivedData/

to remove your app's data.
Hope that helps!

Deleting CoreData store on OS X?


If the characteristic polynomials of $A$ and $B$ are equal, why are the corresponding coefficients of $\lambda^{n-1}$ equal?

Question:
Theorem: Similar matrices have the same trace.
Proof: Let $A$ and $B$ be similar matrices. Then there is $P$, such that $B = P^{-1}AP$. Given that we have similar matrices then we also have the same characteristic polynomial, i.e $\phi(A, \lambda) = \phi(B, \lambda)$. Then the coefficients of $\lambda^{n-1}$ in $\phi(A, \lambda)$ is equal to the coefficient of $\lambda^{n-1}$ in $\phi(B, \lambda)$.

Please, can someone explain the last line? I do not understand which are the coefficients of $\lambda^{n-1}$ we are talking about.
Thank-you :)
Answer: The statement is that the polynomials $\phi(A, \lambda)$ and $\phi(B, \lambda)$ are equal. Two polynomials are equal if and only if all of their coefficients are equal. As $\phi(A, \lambda)$ and $\phi(B, \lambda)$ are polynomials in $\lambda$, they both have a coefficient of $\lambda^{n-1}$. As $\phi(A, \lambda)$ and $\phi(B, \lambda)$ are equal, these coefficients are equal.
More symbolically, if $\phi(A, \lambda) = \lambda^n + a_{n-1}\lambda^{n-1} + \dots + a_1\lambda + a_0$ and $\phi(B, \lambda) = \lambda^n + b_{n-1}\lambda^{n-1} + \dots + b_1\lambda + b_0$, then the equality $\phi(A, \lambda) = \phi(B, \lambda)$ implies $a_i = b_i$ for $i = 0, \dots, n - 1$; in particular, $a_{n-1} = b_{n-1}$.


How to spread these cards evenly

Question: Codepen.io - full code

Jimmy Eat World

Although I'm using Bootstrap I can't spread these cards horizontally, and they keep shrinking (originally squared shape). What's wrong here?
Comment: Links to code pen must be accompanied by the code in the question itself - please use the snippet button and create a [mcve]
Answer: In the codepen you have a width of 150px set. You need to remove this to allow for a full width container.
All columns need to be contained in a row.
I have removed the width from the style, and added a row class to the card-container div. See here:
https://codepen.io/anon/pen/MXVGVE

 // Columns must be contained within a row class

Jimmy Eat World

    Card 2...

    Card 3...

Comment: Thank you very much, but in my actual code they are all layered. How to help it?
https://scontent-frt3-2.xx.fbcdn.net/v/t1.15752-9/35896200_1729589803744794_7795307368123727872_n.png?_nc_cat=0&oh=ed820d62445c7847cbcad5db96b6d05f&oe=5BAD9F70
Comment: What do you mean? Can you give an example?
Comment: I'd like to have three cards in a row, but it's displaying like they all three are on a one place in the center.
Comment: Hmm. It displays correctly in the codepen. Stacking would be to do with the `position` styles. Try removing them and see if that works. Are you using the exact css in the original codepen? Is it possible it is being overridden by styles elsewhere in your script?
Comment: Yeah, that was the position! Thank you again!
Answer: YOU CAN NOT SET col-.. without wrap it row div
Set width: 100%; instead width: 150px; to .card-container
and add row to card-container

.card-container {
    cursor: pointer;
    height: 150px;
    perspective: 600;
    position: relative;
    width: 100%;
  }
  .card {
    height: 100%;
    position: absolute;
    transform-style: preserve-3d;
    transition: all 1s ease-in-out;
    width: 100%;
  }
  .card:hover {
    transform: rotateY(180deg);
  }
  .card .side {
    backface-visibility: hidden;
    border-radius: 6px;
    height: 100%;
    position: absolute;
    overflow: hidden;
    width: 100%;
  }
  .card .back {
    background: #eaeaed;
    color: #0087cc;
    line-height: 150px;
    text-align: center;
    transform: rotateY(180deg);
  }
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

                Choose your hero membership

Jimmy Eat World

Jimmy Eat World

Jimmy Eat World

Comment: tell for more help

How to spread these cards evenly


menu-mini panels: removing anchor tag from menu item

Question: I've used the menu-minipanel module to set-up some mega menus. The main menu items are set (using the module UI) to show a minipanel with my various menu blocks/nodes.
However I don't want the 1st level menu items themselves to point anywhere, and since I've used the Menu Minipanel option to allow for a click to reveal the minipanel I was forced to use the Special Menu Items module to generate a "#" as an href.
However the problem I'm having now is that when the user clicks on the menu items to open the megamenu, the '#' href takes them to the top of the page.
Can anyone suggest any options here?
Here's the site I'm working on presently as reference.
Answer: You can use some jquery here, by capturing click event of this menu item, and returning false.
<code>$("<selector>").click(function(){
   return false;
});
</code>
Or try this
<code>$("<selector>").click(function(e){
   e.preventDefault();
});
</code>


How to capture what parameters are passed to stored procedure inside ssis package runtime

Question: I have a scenario where my client informed me that their sql server agent jobs fail sometimes. On investigation, we found that the sql agent job calls an ssis package, which internally calls an SP with parameters (?,?,?), and the error is being generated in TSQL inside SP as per the error message.
I want to capture the parameters to test SP execution in a new query window, manually. We do not have an SSDT tool in the client environment with which to debug the SSIS package to identify parameters, however we have imported the ssis package in SSMS.
Is there any way I can capture the parameter passed at runtime to SP via the ssis package in SSMS?
Comment: then maybe, try adding a log for the incoming parameters inside the sp before you start further processing, then you can track the parameter from that table
Comment: do you have the permission to alter the sp at clients database ?
Comment: Yes @JayasuryaSatheesh we can edit SPs
Answer: You can turn on sql server profiler and capture the queries being run againt the database when SSIS package is executed, there you can see what parameters being passed in.
Answer: Modify your sp to capture the parameters before doing further processing. Like this :
<code>    CREATE TABLE dbo.ProcParameters
    (
     SeqNo int identity(1,1),
    ProcNm VARCHAR(255),
    Param1 nvarchar(255),
    Param2 nvarchar(255),
ExecResult NVARCHAR(MAX),
    ExecTime DATETIME DEFAULT(GETDATE())
    )

    create procedure MyProc
    (
     @Param1 nvarchar(255),
    @Param2 nvarchar(255)
    )
    as
    begin
declare @Id int,@ExecResult NVARCHAR(MAX)

     insert into ProcParameters
    (
     ProcNm ,Param1 ,Param2
    )
    VALUES('MyProc',@Param1 ,@Param2)

select @id = @@identity
begin try
    /*

    Your Code goes here

    */
SET @ExecResult ='Success'

   end try
 BEGIN CATCH
select @ExecResult = ERROR_MESSAGE()
END CATCH

UPDATE ProcParameters
SET ExecResult = @ExecResult WHERE SeqNo = @id

    end
</code>
Now, each time the proc is being executed, the values will be stored in the table ProcParameters and you can get it from there. Also, the result of each execution can be found in the column ExecResult.
Answer: This one is easy as you can write code in the SP which you want to debug :
<code>  1- Create a table for variable capture
  2- in procedure just give insert statement like

 Insert into dbo.VariableLog values (@param1 , @param2 )
</code>


Harmonic Analysis of Chopin's etude op.10 no 5

Question:
In the circled part, what is the harmony?
Is the E-flat a non-chord tone or is this just some weird chord? (I've only learnt basic harmony.)
Answer: I would view that E♭ as a non-chord tone above a V7 (D♭) chord.
More specifically, I would view this as a passing tone between the F in m. 3 and the D♭ in m. 4. This means that the entirety of mm. 3–4 is best understood as a V7 chord. The E♭ on beat 2 of m. 3 is just a passing tone from the F right before it, and Chopin repeats this passing-tone E♭ on the second eighth note of m. 4 before resolving it to the chord-tone D♭.
And if you're really interested, this E♭–D♭ motion is actually a little conceptual motive throughout the entire piece. (As a couple little examples: look at the first three chords and the cadence right before the coda!) Perhaps Chopin did this intentionally, perhaps it was a byproduct of this being a heavily pentatonic piece (hence the nickname "Black Keys," which themselves create a pentatonic collection), perhaps it's just a part of nineteenth-century compositional practice, or perhaps it's a little bit of all three.
In any event, be prepared to find more of these little E♭–D♭ patterns in this piece!


Avoid calling a non-virtual method in a unit test

Question: I'm tasked with writing some tests to one of our codebases.
Now I have this class:
```
<code>public class A
{
  public void method_1()
  {
    this.method_2();
    // Do something
  }

  public void method_2()
  {
     Environment.CurrentDirectory = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
     // Do something
  }
}
</code>
```
Now I'm trying to write a test for method_1 without invoking method_2 and getting NullReferenceException.
[TestClass]
public class MyTestClass
{

  [TestMethod]
  public void MyTestMethod()
  {
    // Ignore the call: Assembly.GetEntryAssembly() because it returns null>

    new A().method_1();
  }

Any suggestion?
EDIT:
I'm not allowed to change the code.
Comment: Wouldn't it be easier to mock / shim Assembly?
Comment: One proper way to do it you would be to extract the part that is file-system dependent, create an interface for it, and inject in class A as dependency, in constructor. Then, in the tests, you can safely inject a Mock that will just do nothing, or simulate results (or errors) from filesystem.
Comment: Does the method_1() or method_2() changes the object state (ex. some field or property you can observe) ?
Comment: @Pac0 Unfortunately, I can't change the code. I guess the use of mocking is necessary, I just don't how to implement it in this case without virtual methods.
Answer: Without the possibility to override/mock the logic inside method_2 there is not much you can do.
If it is your own codebase I suggest to move the call to Assembly.GetEntryAssembly().Location to some helper method which you can override for the tests.
Answer: Assuming you cannot change anything to the code, you can use MS Fakes to mock out static methods like DateTime.Now. Should also work on Assembly.GetEntryAssembly().

I'm not a big fan of MS Fakes though, had a few too many problems with it in the past. If you can make a small change to the code, you can make the method_2 virtual and do something like this:
public class MyTestA : A
{
  public override void method_2()
  {
    //Do nothing
  }
}

You can then write your tests against MyTestA.
Of course, putting the code in method 2 in a new class/interface and mock that as a dummy interface is an even cleaner solution.


Fully Qualified Domain Name of VPS

Question: I'm really confused by FQDN.
So there is this file on my debian machine /etc/hosts.
What exactly goes in there?
Say my VPS is located at ipadress: 18.104.22.168
And i have a couple of domains all pointing to this ip adress. Let's say:
domainA.com, domainB.com, domainC.com
Those 3 domains do each server another purpose and are correctly configured with Nginx to point to the correct data say: websiteA, websiteB, websiteC
I have one mail server running on my VPS working and all. Yet somehow i think my /etc/hosts file is not configured correctly as all the mail goes into my spam folder even while i have an SSL certificate for all 3 domains and subdomains.
How would one configure his /etc/hosts file?
And should virtual hosts/users help me sending mails from different domains?
For now my /etc/hosts file looks like this:
127.0.0.1    localhost           SomeAlias
22.214.171.124  domainA.com         SomeAlias
126.96.36.199  mail.domainA.com    SomeAlias
18.104.22.168  domainB.com         SomeAlias
22.214.171.124  domainC.com         SomeAlias

Answer: A FQDN is just a format for representing a dns record, like it's the entire dns record without any shorthand or assumptions about what domain the machine is part of. Anyway, it's traditional to stick the hostname of your machine in the /etc/hosts file. You don't have to, but it prevents the machine from having to DNS lookup it's own name all the time, so it makes sense. So as far as your hostname goes, you can just go with whatever your host gave you, or you can set it to something yourself. You should have your ISP/Provider set the reverse DNS for your hostname, since a lot of mail servers won't accept mail from servers that have a mixup between their rdns, dns, and their hostname.
TL;DR: The /etc/hosts file just hardcodes ip addresses. A FQDN is just a full dns record. You're wondering about setting a valid hostname. You can actually use any of your domains, or mail.yourdomains.com or whatever you want really.

Fully Qualified Domain Name of VPS


Show that PTIME and PSPACE is closed under Klenee star

Question: how to show that PSPACE and PTIME are closed under Kleene star ?  I can only show that NP is closed, but it is easy because we can use non-determinism to guess partition of word. In these two cases I don't have idea how to attack it.
Edit
Using @sdcvvc's hint.
Is obvious that when we build this graph the task is solved - it is because of the fact in linear time we check if there exists path from $1$ to $|w|$ where $w$ is input word.
So, how to build this graph in polynomial time and space ?
This building will be polynomial, lets consider position $i+1$, where for $1,2,3..,i$ . To build graph for $i+1$ we must (in pesimistic case) launch Turing machine for $L$ on words: $w[1,i+1], w[2,i+1],..,w[i,i+1]$. It consumes $(i+1)\cdot f(n)$ where $f(n)$ is polynomial. We can see that it is polynomial time and space.
Comment: Please [do not post the same question on multiple sites](https://meta.stackexchange.com/q/64068). Each community should have an honest shot at answering without anybody's time being wasted.
Comment: I'm voting to close this question as off-topic because it has been cross-posted to [cs.se] where it has been answered: [Show that PTIME and PSPACE is closed under Klenee star](https://cs.stackexchange.com/q/71895).
Answer: Hint: Consider a graph $G$ where vertices are positions in the word, and there is an edge $i \to j$ if the subword $w[i..j-1]$ is in $L$. Show that this graph can be computed in $PTIME$ (or $PSPACE$). Can you make a connection between this graph and Kleene star $L^{\ast}$?
Comment: Did you mean dynamic algorithm ?
Comment: What do you mean by dynamic algorithm?
Comment: Ok, let me rethink your hint again
Comment: I edited my first post and tried to exploit your hint, try to check it, please
Comment: Yes, it's correct.
Comment: Simply, edges in this graph may be : $n + (n-1) + ... + 1 ~ n^2$. And $n^2\times$ runtime of MT. So polynomial. Yeah?
Comment: Yes, ${n \choose 2}$ edges, therefore $O(n^2) \times$ runtime of the Turing machine.


How to append "%" symbol?

Question: I have a stored procedure which is returning a integer value, but at the time of print I want to print "%" symbol.

declare @avg int
exec example @avg output
select @avg

It is giving only number like 80. But I want 80%
Answer: It doesn't seem correct to try to solve this by modifying your Stored Procedure. Isn't there any way in which you can add the % symbol in the UI or when you are formatting whatever is supposed to be printed?
You can Cast or Convert an INT value into a VARCHAR using e.g. CAST(@avg as VARCHAR) and thereby making it legal to perform string concatenation using the + operator. This will of course also impact the return type of your sproc.
Answer: Well, since @avg is declared as int, you have to cast it before appending a character.
SELECT cast(@avg as varchar(5)) + '%'

Answer: Convert to string while printing
declare @avg int
set @avg = 80

select Convert(varchar(5),@avg) + '%'

or

print Convert(varchar(5),@avg) + '%'

I hope this help to u...
Answer: declare @avg int
exec example @avg output
select cast(@avg as nvarchar(10))  + '%'

How to append “%” symbol?


How to iterate over a List containing array of strings

Question: I am reading csv file with openCSV reader. There is a method readAll which gives List as the result.
List<String[]> myEntries = reader.readAll();

I want to get the each string from it. I tried this, but doesn't worked out.
Iterator itr = myEntries.iterator();
while(itr.hasNext()) {
    Object element = itr.next();
    for(String temp:element)
       System.out.println(temp);
}

It's giving me an error saying, foreach cannot be applied to type Object. How to get the strings from it?
Comment: Why is `element` an `Object` instead of a `String[]`?
Comment: Type casting is not used properly in your code.
Answer: If a way to solve it is not important for you, I suggest using foreach statements:
for(String[] a : myEntries)
    for(String s : a)
        // do what you want to

Otherwise, you should write like
Iterator<String[]> iterator = myEntries.iterator();
while(itr.hasNext())
    for(String temp : itr.next())
        // Don't worry, itr.next() will be created only one time
        // for an each iteration (while)
        System.out.println(temp);

, that looks not pretty and may have difficulty in reading.
Comment: The second one is not working, it says Foreach is not applicable on type object
Comment: @LokeshS, don't use a raw type of iterator, I corrected
Answer: The list elements are of type String[]. Use this in the declaration:
Iterator<String[]> itr = myEntries.iterator();

...

String[] element = itr.next();

Comment: No, it's not working saying Required: Java.lang.String[] Found: Java.lang.Object. I am surprised.... I expected required: object, but found: String[]
Comment: Yes, the iterator needs to be correctly typed as well. See update
Answer: Try Following code,
for (String[] element : myEntries) {
    for (String temp : element)
        System.out.println(temp);

}

Answer: reader.readAll().forEach(stringArray -> {
   for(String element : stringArray){
      System.out.println(element);
   }
});

Answer: The simplest way is to use a foreach loop, just like you did for the array:
for (String[] entry : myEntries) {
    for (String temp : element) {
        System.out.println(temp);
    }
}

If you really need an Iterator, then don't use a raw type:
for (Iterator<String[]> it = myEntries.iterator(); it.hasNext();) {
    String[] entry = it.next();
    for (String temp : entry) {
         System.out.println(temp);
    }
}

You should always use curly braces around blocks, even if your block has a single instruction. That makes the code more readable, more maintainable, and helps avoiding many bugs.
Answer: If you prefer Java 8, its every more declarative.
myEntries.forEach(entries ->
    Arrays.stream(entries).forEach(entry -> System.out.println(entry)));


An enemy aircraft can be shot down by each of three anti-aircraft guns with probabilities 0.2,0.3,0.4

Question: An enemy aircraft can be shot down by each of three anti-aircraft guns with probabilities $0.2,0.3,0.4$

what is the probability that the aircraft will be shot down with the simultaneous firing of all guns?
What is the probability that it will be shown down with repeated firing if the first one unsuccessful?
the anti-aircraft guns were successful in the first simultaneous firing .what is the likelihood that the third gun was successful was shot down by the third gun if it is known that only one of the guns hit the target?
what is the probability that it was shot down by the third gun if it is known that only of the two guns hit the target?

my try

$0.9$
$1-(0.8*0.7*0.6)$
idk
$(1/2)*0.4$
Comment: "...if it is known that only of the guns hit the target" Do you mean  "...if it is known that only **one** of the guns hit the target"? Please clarify.
Comment: yes I just edit question ty
Answer: Assuming prob. of hits be each gun independent of others.
1) $.664$ = (1 - prob all miss).
2) $1$ - if they keep on firing eventually there will be a hit.
3) $0.495575221238938018$ = (prob hit by 3 and other two miss)/(prob exactly one hit).
4) $0.808510638297872271$ = (prob hit by 3 and one other)/(prob exactly two hit).
Comment: Clarify question - "mean with number"?
Comment: (3) 3 hit and others miss P=.224, exactly one hit P=.224+.144+.084=.452.  (4) 3 and one other hit P=.096+.056=.152, exactly two hit P=.152+.036=.188.
Comment: 3 and 4   (prob hit by 3 and other two miss)/(prob exactly one hit) what is mean with number ?
Comment: thanks for answer but I need to know " (prob hit by 3 and other two miss) equal what ?"
Comment: and also other parameters in 3 and 4
Comment: how u got this number in answer 4 " .036 "
Comment: .036 is the probability that 3 misses and the other two hit $.2\times .3\times .6$
Answer: The aircraft will be shot down if at least one of the anti-aircraft guns hits the enemy aircraft. The probability is equal to 1 minus the probability that no anti-aircraft gun hits the enemy aircraft: $1-(1-0.2)\cdot (1-0.3)\cdot (1-0.4)=1-0.8\cdot 0.7\cdot 0.6=66.4\%$. So your answer for $2.$ is the answer for $1.$
Second question:
I assume that two shots are made. The aircraft is not hit by the first shot of the three guns but by the second shot by at least one of the 3 guns. The probability is
$(1-0.2)\cdot (1-0.3)\cdot (1-0.4)\cdot (1-(1-0.2)\cdot (1-0.3)\cdot (1-0.4))$
$1-(1-0.2)\cdot (1-0.3)\cdot (1-0.4)$: This is the probability that at least one of the 3 guns hit the aircraft.
Third question:
Suppose we denote the event that the aircraft is hit by gun i as  $h_i$. The converse event is denoted by $\overline h_i$
The 3 events  for only one of the guns hit the target are:
\begin{aligned}
\\  h_1 \overline h_2 \overline h_3
 \\  \overline h_1  h_2 \overline h_3
\\ \overline h_1 \overline h_2  h_3
\end{aligned}
Now we identifiy the event that the third gun was successful. This is $\overline h_1 \overline h_2  h_3$
Thus the asked probability is $$\frac{P(\overline h_1 \overline h_2  h_3)}{P(h_1 \overline h_2 \overline h_3)+P(\overline h_1  h_2 \overline h_3)+P(\overline h_1 \overline h_2  h_3)}=\frac{0.8*0.7*0.4}{0.2*0.7*0.6+0.8*0.3*0.6+0.8*0.7*0.4}=$$
$=0.495575\approx 49.56\%$
Fourth question:
Same procedure as in $3$.
\begin{aligned}
\\  h_1  h_2 \overline h_3
 \\  h_1 \overline h_2  h_3
\\ \overline h_1  h_2  h_3
\end{aligned}
$$ \frac{P(h_1 \overline h_2  h_3)+P(\overline h_1  h_2  h_3)}{P(h_1  h_2 \overline h_3)+P(h_1 \overline h_2  h_3)+P(\overline h_1  h_2  h_3)}=\frac{0.2*0.7*0.4+0.8*0.3*0.4}{0.2*0.3*0.6+0.2*0.7*0.4+0.8*0.3*0.4}\approx 80.85\%$$
Comment: wow thank you very much for your explain
Comment: You´re welcome. Have a look to the answer of the second question. Is it comprehensible? I assume that no hit at the first shot and *at least* one hit at the second shot.
Comment: the second line in your answer belongs to the first line
Comment: (1−0.2)⋅(1−0.3)⋅(1−0.4): Prob that the aircraft is not hit by anyone of the three guns. And prob. that at least one gun hit is 1 minus the prob. that no of the guns hit:(1−(1−0.2)⋅(1−0.3)⋅(1−0.4)
Comment: ok thanks very much, your genius
Comment: @predactor  I hope it is all clear now.
Comment: yes it is clear , and i am now understand all answer
Comment: I am pleased about that.
Comment: i am trying to understand it but I am confused
Comment: (1−0.2)⋅(1−0.3)⋅(1−0.4)⋅(1−(1−0.2)⋅(1−0.3)⋅(1−0.4))

1−(1−0.2)⋅(1−0.3)⋅(1−0.4)


Jenkins / groove - Dynamic stage showing all stages as failed

Question: Im readind a shell script file /tmp/cmd_list.sh with groove script and creating a dynamic stage to build.
The content of /tmp/cmd_list.sh is:

ls
pwd
aaaaaa
who

Only "aaaaaa" mut fail to execute (exit code 127).
My problem is, all stages are marked as failed, but when i see the log, comands such as "ls", "pwd" and "who" work fine fine and return code is 0.
I tried to foce stage status for box, but without sucess ...
My Groove script (Jenkinsfile):
import hudson.model.Result

node('master') {

    stage ('\u27A1 Checkout'){
        sh "echo 'checkout ok'"
    }

    def BUILD_LIST = readFile('/tmp/cmd_list.sh').split()
    for (CMDRUN in BUILD_LIST) {

        def status;

        try {
            node{
                stage(CMDRUN) {

                    println "Building ..."

                    status = sh(returnStatus: true, script: CMDRUN )
                    println "---> EX CODE: "+ status

                    if(status == 0){
                        currentBuild.result = 'SUCCESS'
                        currentBuild.rawBuild.@result = hudson.model.Result.SUCCESS
                    }
                    else{
                        currentBuild.result = 'UNSTABLE'
                        currentBuild.rawBuild.@result = hudson.model.Result.UNSTABLE
                    }

                    def e2e = build job:CMDRUN, propagate: false

                }
            }
        }
        catch (e) {
            println "===> " + e
            currentBuild.result = 'UNSTABLE'

            println "++++> EX CODE: "+ status

            if(status == 0){
                println "++++> NEW STATUS: "+ status
                currentBuild.rawBuild.@result = hudson.model.Result.SUCCESS
                currentBuild.result = 'SUCCESS'
            }
            else{
                println "++++> NEW STATUS: "+ status
                currentBuild.rawBuild.@result = hudson.model.Result.UNSTABLE
            }

        }

    }

}

And the result is:

Anyone can help me to show right status?
Thank you!
Answer: I changed my script and now work as expected!
new code:
node('master') {

    def build_ok = true

    stage ('\u27A1 Checkout'){
        sh "echo 'checkout ok'"
    }

    def BUILD_LIST = readFile('/tmp/cmd_list.sh').split()
    for (CMDRUN in BUILD_LIST) {

        try {
            stage(CMDRUN) {

                println "Building ..."
                sh CMDRUN

            }

        }
        catch (e) { build_ok = false }

    }

    if(build_ok) { currentBuild.result = "SUCCESS" }
    else { currentBuild.result = "FAILURE" }

}

expected Result
Answer: Small improvement on waldir's answer
node('master') {

    def build_ok = true

    stage ('\u27A1 Checkout'){
        sh "echo 'checkout ok'"
    }

    def BUILD_LIST = readFile('/tmp/cmd_list.sh').split()
    for (CMDRUN in BUILD_LIST) {

        catchError(buildResult: 'SUCCESS', stageResult: 'FAILURE') {
            stage(CMDRUN) {

                println "Building ..."
                sh CMDRUN

            }

        }

    }

    if(build_ok) { currentBuild.result = "SUCCESS" }
    else { currentBuild.result = "FAILURE" }

}


Failed tls handshake. Does not contain any IP SANs

Question: I'm trying to set up logstash forwarder, but I have issues with making a proper secure channel. Trying to configure this with two ubuntu (server 14.04) machines running in virtualbox. They are 100% clean (not touched hosts file or installed any other packages other than the required java, ngix, elastisearch, etc, for logstash)
I do not believe this is a logstash issue, but improper handling of certificates or something not set correct either on the logstash ubuntu or forwarder machine.
I generated the keys:
sudo openssl req -x509 -batch -nodes -newkey rsa:2048 -keyout private/logstash-forwarder.key -out certs/logstash-forwarder.crt

My input conf on logstash server:
input {
  lumberjack {
    port => 5000
    type => "logs"
    ssl_certificate => "/etc/pki/tls/certs/logstash-forwarder.crt"
    ssl_key => "/etc/pki/tls/private/logstash-forwarder.key"
  }
}

Keys were copied to forwarder host, which has the following config.
{
  "network": {
    "servers": [ "192.168.2.107:5000" ],
    "timeout": 15,
    "ssl ca": "/etc/pki/tls/certs/logstash-forwarder.crt"
    "ssl key": "/etc/pki/tls/certs/logstash-forwarder.key"
  },
  "files": [
    {
      "paths": [
        "/var/log/syslog",
        "/var/log/auth.log"
       ],
      "fields": { "type": "syslog" }
    }
   ]
}

With logstash server running, I 'sudo service logstash-forwarder start' on the forwarder machine, giving me the following repeated error:
Jul  9 05:06:21 ubuntu logstash-forwarder[1374]: 2014/07/09 05:06:21.589762 Connecting to [192.168.2.107]:5000 (192.168.2.107)
Jul  9 05:06:21 ubuntu logstash-forwarder[1374]: 2014/07/09 05:06:21.595105 Failed to tls handshake with 192.168.2.107 x509: cannot validate certificate for 192.168.2.107 because it doesn't contain any IP SANs
Jul  9 05:06:22 ubuntu logstash-forwarder[1374]: 2014/07/09 05:06:22.595971 Connecting to [192.168.2.107]:5000 (192.168.2.107)
Jul  9 05:06:22 ubuntu logstash-forwarder[1374]: 2014/07/09 05:06:22.602024 Failed to tls handshake with 192.168.2.107 x509: cannot validate certificate for 192.168.2.107 because it doesn't contain any IP SANs

As I mentioned earlier, I do not believe this is a logstash issue, but certificate/machine config issue. Problem is, I can't seem to solve it. Hopefully some clever minds here can help me out?
Thanks
Comment: If similar to docker login, it should work using the hostname instead of ip.
Answer:
... Failed to tls handshake with 192.168.2.107 x509: cannot validate certificate for 192.168.2.107 because it doesn't contain any IP SANs

SSL needs identification of the peer, otherwise your connection might be against a man-in-the-middle which decrypts + sniffs/modifies the data and then forwards them encrypted again to the real target. Identification is done with x509 certificates which need to be validated against a trusted CA and which need to identify the target you want to connect to.
Usually the target is given as a hostname and this is checked against the subject and subject alternative names of the certificate. In this case your target is a IP. The validate the certifcate successfully the IP must be given n the certificate inside the subject alternative names section, but not as an DNS entry (e.g. hostname) but instead as IP.
So what you need to is:

Edit your /etc/ssl/openssl.cnf on the logstash host - add subjectAltName = IP:192.168.2.107 in [v3_ca]  section.
Recreate the certificate
Copy the cert and key to both hosts

PS Consider adding -days 365 or more to the certificate creation commandline as the default certificate validity is just 30 days and you probably do not want to recreate it every month..
Comment: Really the same issue or another error message (like unknown CA or similar)? Please post the essential part of the certificate, e.g.  `openssl x509 -text` from the certificate installed on the server. Please check also with `openssl s_client` that the server returns the expected certificate and use `-CApath` with s_client to check that the trust chain can be verified against the configured CA.
Comment: Thanks for the quick reply.

I generated a new certificate on the server. A quick inspect gives me the following:
Issuer: C=AU, ST=Some-State, O=Internet Widgits Pty Ltd, CN=192.168.2.107

Where 2.107 is the logstash server ip. I then copy the crt and key over to the other machine (forwarder) and apply  it to the configuration. Does this sound correct to you? Cause it's still whining about the same thing...:P
Comment: Please ignore my comment above. I have now edited /etc/ssl/openssl.cnf and added subjectAltName=IP:192.168.2.107

Created a new cert with:
'sudo openssl req -x509 -nodes -newkey rsa:2048 -keyout private/logstash-forwarder.key -out certs/logstash-forwarder.crt'

Copied them over and applied config and restart (on both boxes). Unfortunately still the same issue. Having a hard time googling similar cases on this, so hopefully you are able to guide me to the correct path? :)
Comment: I managed to get it to work. I put subjectAltName in the wrong section. Working method:  Basically I edited openssl.cnf, in section  [v3_ca] I added 'subjectAltName = IP:192.168.2.107'. Produced new certificate and added to server + client. Thanks for your help! :)
Answer: There is a script for creating proper certs for lumberjack that was mentioned on a logstash github ticket: SSL handshake fails because IP SANs are missing
Download the file:
curl -O https://raw.githubusercontent.com/driskell/log-courier/1.x/src/lc-tlscert/lc-tlscert.go
...build it:
go build lc-tlscert.go

..and run:
./lc-tlscert
Specify the Common Name for the certificate. The common name
can be anything, but is usually set to the server's primary
DNS name. Even if you plan to connect via IP address you
should specify the DNS name here.

Common name: you_domain_or_whatever

The next step is to add any additional DNS names and IP
addresses that clients may use to connect to the server. If
you plan to connect to the server via IP address and not DNS
then you must specify those IP addresses here.
When you are finished, just press enter.

DNS or IP address 1: 172.17.42.1 (th ip address to trust)
DNS or IP address 2:

How long should the certificate be valid for? A year (365
days) is usual but requires the certificate to be regenerated
within a year or the certificate will cease working.

Number of days: 3650
Common name: what_ever
DNS SANs:
    None
IP SANs:
    172.17.42.1

The certificate can now be generated
Press any key to begin generating the self-signed certificate.

Successfully generated certificate
    Certificate: selfsigned.crt
    Private Key: selfsigned.key

Copy and paste the following into your Log Courier
configuration, adjusting paths as necessary:
    "transport": "tls",
    "ssl ca":    "path/to/selfsigned.crt",

Copy and paste the following into your LogStash configuration,
adjusting paths as necessary:
    ssl_certificate => "path/to/selfsigned.crt",
    ssl_key         => "path/to/selfsigned.key",

Comment: This saved me a lot of time today...albeit for gitlab-runner. Thank you!
Answer: I had a real issue with this.  I'm not using logstash, I was simply trying to get IP SANs to work with docker tls.  I would create the certificate as described in the docker article on https (https://docs.docker.com/articles/https/),  then when I would connect from a docker client:
docker --tlsverify  -H tcp://127.0.0.1:2376 version

I would get this error :
...
FATA[0000] An error occurred trying to connect: Get https://127.0.0.1:2376/v1.16/version: \
x509: cannot validate certificate for 127.0.0.1 because it doesn't contain any IP SANs

which was driving me crazy.  I admit, I stumble around in all things openssl, so, everybody might already know what I discovered.  The subjectAltName example here (and every where else) shows updating the openssl.cnf file.  I couldn't get that to work.  I did a locate on the openssl.cnf, copy it to a local directory, then made the changes to it.  When I examined the cert it did not contain the extension:
openssl x509 -noout -text -in server-cert.pem

The command being used to create that cert is here (from the docker article):
openssl x509 -req -days 365 -in server.csr -CA ca.pem -CAkey ca-key.pem \
    -CAcreateserial -out server-cert.pem

You can't add a -config openssl.cnf line to this command, it is not valid.  Nor can you copy the openssl.cnf file to the current directory, modify it, and hope to get it to work that way.  A few lines later I noticed that the 'client' cert uses an -extfile extfile.cnf. So, I tried this:
echo subjectAltName = IP:127.0.0.1 > extfile.cnf
openssl x509 -req -days 365 -in server.csr -CA ca.pem -CAkey ca-key.pem -CAcreateserial \
   -out server-cert.pem -extfile extfile.cnf

and that fixed it.  So, for whatever reason my version of openssl wasn't allowing me to modify the openssl.cnf file, but, I could specify the subjectAltName like this.  Works great!
You can specify any number of IP addresses, like IP:127.0.0.1,IP:127.0.1.1 (non localhost as well).
Comment: Ah-Ha!

Thank you, I am doing the same thing as you with docker and hit this issue. I will try your suggestions now.
Answer: As of OpenSSL 1.1.1, providing subjectAltName directly on command line becomes much easier, with the introduction of the -addext flag to openssl req
Example:
export HOST="my.host"
export IP="127.0.0.1"
openssl req -newkey rsa:4096 -nodes -keyout ${HOST}.key -x509 -days 365 -out ${HOST}.crt -addext 'subjectAltName = IP:${IP}' -subj '/C=US/ST=CA/L=SanFrancisco/O=MyCompany/OU=RND/CN=${HOST}/'

Inspired by link
Answer: Please see @Steffen Ullrich's solution above for the quick fix.
There is also an issue/a discussing about it in the logstash-forwarder project's github. See it (soon, as currently work on it is in progress) for an easier solution.


How do I debug A block ajax issue on a custom theme?

Question: I'm receiving and ERROR " An error occurred while attempting to process /views/ajax?_wrapper_format=drupal_ajax: ajax.$form.ajaxSubmit is not a function" when clicking on link in views block on exposed form using the taxonomy terms and better exposed filters.
I have tried already attach the views.ajax library to the exposed filter form. it not sorted the issue. Js aggregation also turned off.
I'm using Bootstrap Bario theme as a base and switching to it gives me same error. Core themes works fine.
How do i debug this issue or even possible solution for it?
Answer: I have discovered the issue:
In custom theme I have library which had dependency of jQuery which wasn't core library (that how i got html js css template from the themeforest) I have deleted it and as a dependancy set the core/jQuery in my theme.libraries.yml file. this is solved my issue. This might be helpful to anyone experiencing such an issue and as a step to debug same issue just check that libraries are dependant on core/jquery library


Show number of pages views

Question: I am new to Drupal, so I want to know how do I echo number of views of a page ? or of a category ?
Comment: You're going to have to break this down a bit more I'm afraid!  It's a bit of a broad request :)
Answer: If you go your modules admin screen (/admin/modules), you'll see there's a module called Statistics that actually comes with core Drupal.  Make sure you enable it on this screen if it isn't enabled already.
This will print out page views at the bottom of your pages, but you have to make sure you visit the permissions screen to give anonymous users (if that's what you're trying to do) the ability to see that.  After the module has been enabled, you'll see the following set of permissions for your site(/admin/people/permissions):

Administer statistics
View content access statistics
View content hits

You'd just need to check the last one for whomever you want to be able to see the page views!
You can find additional information about this module on your own site's help pages: /admin/help/statistics
Comment: Sidenote: the Statistics module is a nightmare for performance, and should not be used on high-traffic sites.
Comment: What do you use for displaying page hits, Yuriy?  I use Google Analytics (the module), but that, of course, won't display the page hits on the page itself.  Let us know if you have alternatives...
Comment: There are some alternatives, but none which are quite as easy to use as the default Statistics module. You could use awstats to process Apache's logfiles, or store the visit data in a fast external system like memcache or redis and then write the numbers to Drupal's database during cron runs.

Show number of pages views