Switch Visual Studio 2010 License keys

Question: I have used one license key and want to switch my configuration to use another key.
I tried to launched the uninstall wizard from "Add/Remove Programs" in the Windows Control Panel. When I reinstalled, the license still work.
How can I modify my Visual Studio 2010 installation to use another key, and possibly without uninstalling and reinstalling?
Sorry for not clarifying it at the beginning. Actually, a valid key is not available to me for now. Is there a way to remove the original license completely and use VS as a trial version for days.
Comment: Not the sort of thing I'd admit to on a public forum.
Comment: Are you intending to use another license key? **Your question didn't actually state that.**
Comment: @p.campbell Yes, of course. I am intending to use it legally.
Answer: Change the serial number after Visual Studio 2010 installation

Go to Control Panel -> Programs and Features, locate and highlight Microsoft Visual Studio 2010 Ultimate/Premium/Professional installation, and click on Uninstall/Change button.
Upgrade Visual Studio 2010 Product Key for Activation
A Visual Studio setup maintenance screen should be shown. After clicking Next button, an option to enter a valid serial number to upgrade product license is available.
Enter the upgrade key accordingly, and click on Activate button. No re-installation required.
Comment: Unfortunately this options does not come up when VS2010 was installed through MSDN download... no option for updating product key in Uninstall/Change
Answer: There is a way to edit the product key in a file called Setup.SDB. It should be located in
\Program Files (x86)\Microsoft Visual Studio 10.0\Microsoft Visual Studio 2010 Professional - ENU\Setup.SDB
Edit this file in a notepad and search for Product key. You can then update the product key.
I actually repaired the installation after this change just to make sure everything was working. This was tested on VS2008 and VS2010

Switch Visual Studio 2010 License keys


PHP Sessions Variables on second Page

Question: Good day.I am trying to use session variables but can not seem to get it to work.
I attach my scripts.I do start the session in both
the first script Test.php looks like this
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>

<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";

?>

and the second script test1.php looks like this
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>

<?php
echo "Favorite color is " . $_SESSION["favcolor"] . ".
";

echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>

when i run the first one,i get the message that the variables was set.But when i run the second script,it do not show the variables.It is just blank.
i realy would appreciate any help
Comment: what is `var_dump($_SESSION)` result?
Comment: in test.php   it shows                                              Session variables are set.array(2) { ["favcolor"]=> string(5) "green" ["favanimal"]=> string(3) "cat" }
Comment: and in test1.php                                                                 NULL Favorite color is .
Favorite animal is .
Answer: The php code works fine for me. It must be something in your environment settings. You may want to check .ini file settings, or browser settings to make sure that it the browser is storing and sending the session id cookie with each request. Without that cookie, the server won't know which session to start.
Try running a file with phpinfo() and search through all the settings under session. That might point you in the direction of a .ini file issue. You can also open your browser dev tools and look at the application tab for your site. There should be a cookie stored for your site that correlates to the session name, probably PHPSESSID.
Comment: It does show PHPSESSID,but i can not find any .ini file .Is the variables saved in the session.save_path? In the session.save_path /usr/home/****/.tmp,           that folder is empty
Comment: i found the php.ini file. How do i get to that folder?
Comment: /etc/php/8.0/fpm/php.ini

PHP Sessions Variables on second Page


Problem proving a multivariable limit using sandwich theorem

Question: I am asked to prove that the following limit exists:
$$\displaystyle \lim_{(x,y) \to (0,0)} \frac{x^2+y^2-x^2y^2}{x^2+y^2} =1 $$
I am able to deduce that the limit exists and equals 1 by trying a few values. I tried to prove using the sandwich theorem, however, it seems to be wrong:
$$\displaystyle 0<\frac{1}{x^2+y^2}\leq1$$
$$\displaystyle 0<\frac{x^2+y^2-x^2y^2}{x^2+y^2}\leq x^2+y^2-x^2y^2$$
$$\displaystyle \lim_{(x,y) \to (0,0)} x^2+y^2-x^2y^2 = 0 $$
$$\displaystyle \lim_{(x,y) \to (0,0)} \frac{x^2+y^2-x^2y^2}{x^2+y^2} = 0 $$
Can anyone help me to find the right proof and tell me how did I use sandwich theorem wrong?
thanks!
Comment: That is because $\frac 1{x^2+y^2}$ could be greater than $1$.
Comment: Take $x = y = 0.5$.
Comment: all you need is $2|xy| \leq x^2 + y^2 $  so $4x^2 y^2 \leq .....$
Comment: develop $(|x|-|y|)^2\ge 0$
Comment: Not sure if it is just my brain is stuck or somehow, would u mind telling me how is that possible?
Comment: Oh right. I was just thinking about integers. So how should I prove this?
Comment: How did you come up with this?
Comment: Okay, thanks a lot. I am just not really good at coming up with a particular inequality to prove a limit.
Comment: @YanZhuang  if you are replying to a specific comment, you should put an @ sign and the beginning of that username. I think you meant me....  You should be seeing a little red flag in the upper right of the screen  (at least if you are using a web browser). I had left this question, I got no flag, I just happened to return, which I sometimes do sometimes don't
Comment: @WillJagy Okay thanks for the reminder :)
Answer: HINT
If $(x,y)\neq(0,0)$, one has that
\begin{align*}
0 < y^{2} \leq x^{2} + y^{2} \Longleftrightarrow 0 < \frac{y^{2}}{x^{2}+y^{2}} \leq 1 \Longleftrightarrow 0 < \frac{x^{2}y^{2}}{x^{2} + y^{2}} \leq x^{2}
\end{align*}
Can you take it from here?
Comment: Yes everything's good now. Thanks a lot for the hint
Comment: You are welcome!


Hidden Markov Models with two emissions per state

Question: I have a problem formulated in terms of hidden markov models. A simplified version is discussed here. I have a system that transitions between two discrete hidden states (states 1, 2). The transition probabilities between these states are known, and are shown in the figure below:

Moreover, I have two instruments (I1 and I2) independently observing the system, trying to classify the system as being in state 1 or 2 at each time interval. The observations by the instruments are made at discrete time intervals (say, every hour). Instrument I1 is more dependable than I2. However, data from I1 is not available at all time intervals.
The dependability of the instruments is also estimated independently, with values such as
P(S1 | I1=1) = 0.9
P(S2 | I1=1) = 0.1
P(S1 | I1=2) = 0.8
P(S2 | I1=2) = 0.2
..etc, for instrument 2 too...

where P(S1 | I1=1) is the probability that the actual state was '1' given that data from instrument 1 estimated it to be '1'.
Now, I have observations (and estimated states) from both the instruments for a given time period:
Time_period I1   I2
1            1     1
2            NA    2
3            2     2
4            1     2
5            1     1
6            NA    2
7            NA    2
8            1     2
9            1     1

where I1 is the state inferred from the observation of instrument 1 and I2 is the state inferred from the observation of instrument 2, and NA means that the observation was not available. Also, I have initial values of what the states were. Given these and the transition probabilities, I would like to get the posterior probability of the two states. That is, something like this (below):
Time_period  I1   I2   pp_1     pp_2
1            1     1   0.92     0.08
2            NA    2   0.85     0.15
3            2     2   0.20     0.80
4            1     2   0.70     0.30
5            1     1   0.90     0.10
6            NA    2   0.95     0.05
7            NA    2   0.93     0.07
8            1     2   0.90     0.10
9            1     1   0.95     0.05

where pp_1 is the posterior probability that the actual state was state 1 and pp_2 is the probability that the actual state was state 2.
I know that this post talked about a similar problem. But I am not sure if I can use the msm package, as I have a discrete time situation. I would like to code this in R; which R package is best for this? Can someone please guide me, maybe with a few lines of relevant code?
Answer: I think I have an answer to this at this point. The first step is to assign probabilistic values for each state at each time step, given just the observations. For example, for the first time step, both I1 and I2 had estimated the state as '1'. Now, given what we know about the accuracy of these instruments, what is the probability that the state was actually '1'? This is the problem of combining multiple pieces of evidence. For a good example, see here: (see formula (5) for the final formula). For the time periods when an instrument output is missing, we use the probability estimated from just one instrument.
Thus, we calculate this kind of table by combining the evidence from both the sensors. So, we may have something like:
Time_period I1   I2      (prior) probability of state 1    (prior) probability of state 2
1            1     1         0.88                               0.12
2            NA    2         0.20                               0.80
3            2     2         0.07                               0.93
4            1     2        ...etc...
5            1     1
6            NA    2
7            NA    2
8            1     2
9            1     1

NOTE! The probability numbers shown in the above table are just illustrations, and NOT actual calculations!
Again, if BOTH instrument outputs are missing for some time step, we can use a 'best guess' estimate (say, probabilities of 0.5 for both state1 & state2).
The second part (and again, I am not sure of this part!) is that you use a method known as 'HMM smoothing', as described in 'Machine Learning: A Probablistic Perspective' by Kevin Murphy (2012).
In that textbook, chapter 17 is 'Markov and hidden markov models'. In 17.4.1, the 'smoothing' problem is explained. The problem I have described maps well into such a smoothing problem. In 17.4.3, the forwards-backwards algorithm is presented as a way to solve the smoothing problem.
Hope this helps someone!
Answer: To use msm, you would have to assume an underlying continuous-time model, and find transition intensities in continuous time which are equivalent to the transition probabilities of 0.7 and 0.9 in discrete time.  This may or may not be possible.  The intensity matrix Q is the matrix logarithm of the probability matrix P - I don't have experience with matrix logs, but I think there's a risk they would have multiple/nonexistent solutions.   So I'd advise you find software which fits the discrete time model that you want.  Afraid I haven't used any of the R packages for discrete time HMMs so can't advise any further.
Comment: @user7831861 https://cran.r-project.org/web/packages/HiddenMarkov/HiddenMarkov.pdf
Thought it could help..
Comment: Thanks so much Chris for the comments! Yes, I will try to find a discrete time modelling package as you suggested.


How to include two resources in Page.Resources?

Question: In WPF, this used to work fine:
<Page.Resources>
    <ResourceDictionary Source="resources/Styles.xaml" />
</Page.Resources>

but adding a converter (see below) causes an error on the 2nd resource (Style.xaml): Each dictionary entry must have an associated key.
<Page.Resources>
    <local:MySizeConverter x:Key="sizeConverter"/>
    <ResourceDictionary Source="resources/Styles.xaml" />
</Page.Resources>

However, adding a key to the 2nd line (e.g. <ResourceDictionary x:Key="myStyleDict" Source="resources/Styles.xaml" /> causes the following error in code behind
The name 'aTextBlockUsedToWork' does not exist in the current context

where aTextBlockUsedToWork could be successfully accessed in code behind before adding the key. Note that the converter works fine if I comment out the style resource. How can I have both of the resources working?
Answer: You need to use MergedDictionaries to import another dictionary file, like this:
<Page.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="resources/Styles.xaml" />
        </ResourceDictionary.MergedDictionaries>
        <local:MySizeConverter x:Key="sizeConverter"/>
    </ResourceDictionary>
</Page.Resources>

Comment: Here are two: `http://blogs.msdn.com/b/wpfsldesigner/archive/2010/06/03/creating-and-consuming-resource-dictionaries-in-wpf-and-silverlight.aspx` & `http://www.codeproject.com/Articles/35346/Using-a-Resource-Dictionary-in-WPF`
Comment: thanks! do you know any good tutorials on using ResourceDictionary and good practice to group/"modulize" resources (such as Styles, DatasTemplates, etc.)? I am new to this and all the examples I saw seem to suggest one can define and use Resources anywhere. just wondering if there is some good practice to follow. thanks again!


passando valor webapi para select html em angular 2

Question: eu tenho uma função em typescript que recebe um valor json da minha webapi, e preciso passar esse resultado para um select em html...
Service:
teste: teste[];
public getNomes(type: string, formGroup: FormGroup) {
    let params: HttpParams = undefined;
    params = new HttpParams().set('type', type);
    switch (type) {
        case "teste":
            params = params.set('cod', formGroup.controls['codigoCliente'].value);
            this.retornaNomeApi(API + '/Pesquisa/SelectPesquisa', params).subscribe(nome => {this.teste = nome.result});
    }
}

HTML:
 <select class="form-control" name="pedido">
        <option selected>Selecione...</option>
        <option *ngFor="let testes of teste">{{testes.cod}} - {{testes.nome}}</option>
      </select>

agradeço desde já :D
Answer: Acredito que a melhor forma de fazer isso seria criando um reactive form.
Você poderia fazer da seguinte forma.
No HTML você poderia criar o form com um formGroup deste modo.
<form [formGroup]="form">`
     <select class="form-control" formGroupName="pedido">
        <option selected>Selecione...</option>
        <option *ngFor="let testes of teste">{{testes.cod}}
          {{testes.nome}}</option>
   </select>
</form>

No typescript você precisaria injetar a dependência de formBuilder e criar um FormGroup com o nome definido no [formGroup] do Html.
constructor(private fb:FormBuilder){
}
form: FormGroup;

E adicionar a instância de seu form dentro do método ngOnInit().
ngOnInit(){
 this.form = this.fb.group({
    pedido: ''
 })
}

No recebimento dos dados da sua WebAPI poderia adicionar o dado ao select da seguinte forma:
this.testes = res;

Aproveita e dá uma olhada na documentação dos reactive forms https://angular.io/guide/reactive-forms
Comment: cara, eu tentei dessa forma, porém continua sem receber nenhum retorno
Comment: Desculpa pela obviedade, mas há de fato o retorno dos dados da API?
Comment: sim, eu consigo ver o retorno da api no sources do navegador
Comment: Bruno, adiciona no HTML acima do form esse código

{{ form.value | json }} e vê se ele mostra o valor de pedido como vazio.
Comment: ele mostra vazio.
Comment: adiciona this.form.controls['pedido'].setValue(this.testes[0], { onlySelf: true });
dentro do subscribe da requisição. Teoricamente ele tem que definir a posição 0 do teu array como padrão do teu select


How many digits in this base?

Question: The problem is to derive a formula for determining number of digits a  given decimal number could have in a given base.
For example: The decimal number 100006 can be represented by  17,11,9,8,7,6,8 digits in bases 2,3,4,5,6,7,8 respectively.
Well the formula I derived so far is like this : (log10(num) /log10(base)) + 1.
in C/C++ I used this formula to compute the above given results.
long long int size = ((double)log10(num) / (double)log10(base)) + 1.0;
But sadly the formula is not giving correct answer is some cases,like these :
Number 8 in  base 2 : 1,0,0,0
Number of digits: 4
Formula returned: 3

Number 64 in  base 2 : 1,0,0,0,0,0,0
Number of digits: 7
Formula returned: 6

Number 64 in  base 4 : 1,0,0,0
Number of digits: 4
Formula returned: 3

Number 125 in  base 5 : 1,0,0,0
Number of digits: 4
Formula returned: 3

Number 128 in  base 2 : 1,0,0,0,0,0,0,0
Number of digits: 8
Formula returned: 7

Number 216 in  base 6 : 1,0,0,0
Number of digits: 4
Formula returned: 3

Number 243 in  base 3 : 1,0,0,0,0,0
Number of digits: 6
Formula returned: 5

Number 343 in  base 7 : 1,0,0,0
Number of digits: 4
Formula returned: 3

So the error is by 1 digit.I just want somebody to help me to correct the formula so that it work for every possible cases.
Edit : As per the input specification I have to deal with cases like 10000000000, i.e 10^10,I don't think log10() in either C/C++ can handle such cases ? So any other procedure/formula for this problem will be highly appreciated.
Comment: yeah, but unable to figure out the required modification.
Comment: `int size = static_cast((log10((double)num) / log10((double)base)) + 1.000001);`
Comment: This isn't my homework + the formula tag is necessary so rolling back !
Comment: It looks like you're having an off by one issue on the edge cases.
Comment: I used to do this in school on my calculator; I forget the formula I used back then but when I was taught the `log()` function I was, like, wow this is much simpler!
Answer: There are fast floating operations in your compiler settings. You need precise floation operations. The thing is that log10(8)/log10(2) is always 3 in math. But may be your result is 2.99999, for expample. It is bad. You must add small additive, but not 0.5. It should be about .00001 or something like that.
Almost true formula:
int size = static_cast<int>((log10((double)num) / log10((double)base)) + 1.00000001);

Really true solution
You should check the result of your formula. Compexity is O(log log n) or O(log result)!
int fast_power(int base, int s)
{
    int res = 1;
    while (s) {
        if (s%2) {
            res*=base;
            s--;
        } else {
            s/=2;
            base*=base;
        }
    }
    return res;
}

int digits_size(int n, int base)
{
    int s = int(log10(1.0*n)/log10(1.0*base)) + 1;
    return fast_power(base, s) > n ? s : s+1;
}

This check is better than Brute-force test with base multiplications.
Comment: +1,I haven't checked your solution using a compiler but I think it will work fine.I liked your approach.Although I am aware of the exponentiation at O(logn) but not aware of it's use here, So thanks :)
Comment: I am accepting your solution as it solved both problems, before edit and after edit.
Comment: Thanks, but what if num = 10000000000l ? I think log10() can't handle such cases, any other solution ?
Answer: Either of the following will work:
>>> from math import *
>>> def digits(n, b=10):
...     return int(1 + floor(log(n, b))) if n else 1
...
>>> def digits(n, b=10):
...     return int(ceil(log(n + 1, b))) if n else 1
...

The first version is explained at mathpath.org. In the second version the + 1 is necessary to yield the correct answer for any number n that is the smallest number with d digits in base b. That is, those numbers which are written 10...0 in base b. Observe that input 0 must be treated as a special case.
Decimal examples:
>>> digits(1)
1
>>> digits(9)
1
>>> digits(10)
2
>>> digits(99)
2
>>> digits(100)
3

Binary:
>>> digits(1, 2)
1
>>> digits(2, 2)
2
>>> digits(3, 2)
2
>>> digits(4, 2)
3
>>> digits(1027, 2)
11

Edit: The OP states that the log solution may not work for large inputs. I don't know about that, but if so, the following code should not break down, because it uses integer arithmetic only (this time in C):
unsigned int
digits(unsigned long long n, unsigned long long b)
{
  unsigned int d = 0;
  while (d++, n /= b);
  return d;
}

This code will probably be less efficient. And yes, it was written for maximum obscurity points. It simply uses the observation that every number has at least one digit, and that every divison by b which does not yield 0 implies the existence of an additional digit. A more readable version is the following:
unsigned int
digits(unsigned long long n, unsigned long long b)
{
  unsigned int d = 1;
  while (n /= b) {
    d++;
  }
  return d;
}

Comment: Python automatically switches to arbitrary-precision arithmetic; `log` will always be correct. But `floor` and `ceil` are not: on my computer at least, printing out digits(n) for the first 20 powers of 10 shows mistakes. (Two 3s in the first version and two 15s in the second.)

For the C version: why the trickery in the for loop with comma-separated statements and an empty body? You could move one of them out and improve clarity. Or, if clarity is not the goal, it would be shorter to write: "while(n/=b) d++;"  :-)
Comment: I haven't dissected your second solution entirely but just a rough look, seems to me that you are just computing the entire base representation of the number,that's isn't much efficient :)
Comment: This fails at larger numbers-- digits(1027, 2) for me, but it's probably implementation-dependent.
Comment: @Beta: interesting. Here `digits(1027, 2)` yields `11`, which is correct (can be tested with e.g. `len('{0:b}'.format(1027))`).
Comment: What is the precision of your log function?
Comment: @Beta: in Python `log` appears to accept arbitrarily large numbers (well, I just punched in a lot of digits and it kept working).
Comment: But how many digits does it return? I don't know a thing about Python, but I'll just bet we can find two numbers, b^p and (b^p)-1, that have the same log as far as Python is concerned.
Comment: @Beta: I cannot answer your question, but if you are right that such numbers exist, then the second solution is clearly to be preferred (since it relies solely on integer arithmetic).
Comment: @ShreevatsaR: thanks, updated the answer with more obscurity ;). @Debanjan: you are right. When in doubt, just time both solutions. Regardless, you may have to choose between speed and accuracy...
Answer: Number of digits of a numeral in a given base
Answer: Since your formula is correct (I just tried it), I would think that it's a rounding error in your division, causing the number to be just slightly less than the integer value it should be. So when you truncate to an integer, you lose 1. Try adding an additional 0.5 to your final value (so that truncating is actually a round operation).
Comment: If you would just add another 0.5, you'll get different answers in other border cases:
Number 15 in  base 2 : 1,1,1,1
(log10(15) / log10(2)) + 1.5 = 5.407.., so the answer would be 5, not 4.
Comment: The correct formula is `floor(log10(num)/log10(base)+1.0)`. However, with rounding errors in your initial division, that formula doesn't necessarily work in practice. So you need to round if and only if you're within a certain epsilon of an integer, and then floor, as some divisions will correctly leave you with a non-integer answer.
Comment: Do you mean this : `size = ((((double)log10(num) / (double)log10(base))) + 1.0)+ 0.5;` ? well then it will not work.
Comment: @kigurai : `size = ceil((log10(num) / log10(base)) + 1.0);` won't work !!
Comment: @debanjan, yes I noticed that it does not work for n=7 and base=2.
Comment: @catchmeifyoutry: Then that implies his formula is actually incorrect. Oops.
Comment: @kigurai: `ceil((log(num)/log(base))+1)` doesn't work on number 15 in base 2, as catchmeifyoutry pointed out. The floor is correct (and is given implicitly in the truncation to integer), but there is a rounding error. However, it is not safe to ALWAYS round. Only round within a safe epsilon, though I don't know what that would be here.
Answer: What you want is ceiling ( = smallest integer not greater than) logb (n+1), rather than what you're calculating right now, floor(1+logb(n)).
You might try:
int digits = (int) ceil( log((double)(n+1)) / log((double)base) );

Comment: Of course, this breaks down if n<=1.  Presumably you could handle n=0,1 as special cases, if you wanted to be thorough.
Comment: This is not enough, as it will still yield `2` for `n = 100` and `base = 10`.
Comment: It does **not work** if there are fast floating operations in the setting of the compiler and n=7, base=2. `log10(8)/log10(2)` is about `3` (`2.9999` or `3.000001`). and ceil(3.00001) may be 4 sometimes.
Answer: Using your formula,
log(8)/log(2) + 1 = 4

the problem is in the precision of the logarithm calculation. Using
ceil(log(n+1)/log(b))

ought to resolve that problem. This isn't quite the same as
ceil(log(n)/log(b))

because this gives the answer 3 for n=8 b=2, nor is it the same as
log(n+1)/log(b) + 1

because this gives the answer 4 for n=7 b=2 (when calculated to full precision).
I actually get some curious resulting implementing and compiling the first form with g++:
double n = double(atoi(argv[1]));
double b = double(atoi(argv[2]));
int i = int(std::log(n)/std::log(b) + 1.0);

fails (IE gives the answer 3), while,
double v = std::log(n)/std::log(b) + 1.0;
int i = int(v);

succeeds (gives the answer 4). Looking at it some more I think a third form
ceil(log(n+0.5)/log(b))

would be more stable, because it avoids the "critical" case when n (or n+1 for the second form) is an integer power of b (for integer values of n).
Comment: What's the precision of your log function?
Comment: I was using a JavaScript calculator which gives the right answer for the first form, I assume that the reason sixlettervariables gets the wrong answer is because of a problem representing the final results. In particular log(8)/log(2) is exactly 3 (2^3 = 8), so log(8)/log(2)+1 has the expected value of 4.
Answer: As others have pointed out, you have rounding error, but the proposed solutions simply move the danger zone or make it smaller, they don't eliminate it. If your numbers are integers then you can verify -- using integer arithmetic -- that one power of the base is less than or equal to your number, and the next is above it (the first power is the number of digits). But if you use floating point arithmetic anywhere in the chain then you will be vulnerable to error (unless your base is a power of two, and maybe even then).
EDIT:
Here is crude but effective solution in integer arithmetic. If your integer classes can hold numbers as big as base*number, this will give the correct answer.

  size = 0, k = 1;
  while(k<=num)
    {
      k *= base;
      size += 1;
    }
Answer: It may be beneficial to wrap a rounding function (e.g. + 0.5) into your code somewhere: it's quite likely that the division is producing (e.g.) 2.99989787, to which 1.0 is added, giving 3.99989787 and when that's converted to an int, it gives 3.
Answer: Looks like the formula is right to me:
Number 8 in  base 2 : 1,0,0,0
Number of digits: 4
Formula returned: 3

log10(8) = 0.903089
log10(2) = 0.301029

Division => 3

+1 => 4

So it's definitely just a rounding error.
Answer: Floating point rounding issues.
log10(216) / log10(6) =  2.9999999999999996

But you cannot add 0.5 as suggested, because it would not work for the following
log10(1295) = log10(6) = 3.9995691928566091   //    5, 5, 5, 5
log10(1296) = log10(6) = 4.0                  // 1, 0, 0, 0, 0

Maybe using the log(value, base) function would avoid these rounding errors.
Answer: I think that the only way to get the rounding error eliminated without producing other errors is to use or implement integer logarithms.
Answer: Here is a solution in bash:
% digits() { echo $1 $2  opq | dc | sed 's/ .//g;s/.//' | wc -c; }

% digits 10000000000 42
7

Answer: static int numInBase(int num, int theBase)
{
   if(num == 0) return 0;
   if (num == theBase) return 1;
   return 1 + numInBase(num/theBase,theBase);
}

How many digits in this base?


Is there a difference between DictionarySectionHandler and NameValueSectionHandler?

Question: In .NET, we can create custom configuration sections using the <configSections> element, like so:
<configuration>
  <configSections>

  </configSections>
  <dictionarySample>
    <add key="key1"
         value="value1"/>
  </dictionarySample>
  <nameValueSample>
    <add key="key2"
         value="value2" />
  </nameValueSample>
</configuration>

Above, I am defining two sections. One of type DictionarySectionHandler, and another of type NameValueSectionHandler.
As far as I can tell, these two Handlers are used in exactly the same way and result in identical configuration sections.
So, is there a difference, or can I use them interchangeably?
Answer: TL;DR NameValueSectionHandler is fine for string->string pairs in simple situations, but if you need your configuration to be efficient (particularly if you're going to be using remove repeatedly), use DictionarySectionHandler.

I dug into the source of these two classes (NameValue, Dictionary), and found very little difference in implementation.
There are two things worth noting, though:

As the names of the handlers hint at, the primary difference is in the collections they use: DictionarySectionHandler stores its key/value pairs in a Hashtable, whereas NameValueSectionHandler uses a NameValueCollection.
In the DictionarySectionHandler, the value is not required and will default to an empty string if it is not provided, but NameValueSectionHandler requires the value.

As far as the differences between Hashtable and NameValueCollection, NameValueCollection can have duplicate keys, but Hashtable cannot. Additionally, Hashtable is pretty significantly more efficient in its implementation.
This article on the MSDN Blog has some good information about Hashtable and NameValueCollection.
To summarize their findings, Hashtable is...

2.6x more efficient on lookup.
8.5x more efficient on add.
an order of magnitude more efficient on remove.

They wrap up the article with some helpful information on when to use NameValueCollection:

So you may be wondering when you'd want to use NameValueCollection. NameValueCollection only accepts keys and values that are Strings, so this is a very specialized collection. It's useful in a situation in which you either need to associate multiple values with a key, or to do hash-based lookups as well as lookup by index (and hopefully not perform too many removes).
However, if you need to store string key/value pairs and you don't need to perform index-based lookups or associate multiple values with a key, you may prefer to use the generic Dictionary class. This has the same asymptotic behavior as Hashtable in all cases and furthermore avoids any costs due to boxing.


Has there been a project to apply machine learning to generation of indices for books?

Question: Generating an index for a textbook is a tedious task. Can one automate it with machine learning? Are there any references to previous attempts in the literature to do this?
Comment: I have not seen this idea before, but it sounds like it'd be interesting. Do it!
Comment: C.f. http://tex.stackexchange.com/questions/856/is-there-an-automatic-process-to-create-index-creation
Answer: To add on to the answer by @denis-tarasov, I would refer you to this amazing article by the Guardian.
Take a look at this passage:

One of the things that's commonly imagined is that indexing is, in the age of Google, something that can be outsourced to a computer algorithm. Dead wrong. A concordance – essentially, an alphabetical list of all the words in a book with page references – can be done by a computer. But an index, to be useful, needs to be done by a human. In a book about the Middle East, say, an entry that said: "Syria 2, 3, 5, 6, 7, 10, 23, 25, 26, 27 … " would be no use at all.

Indeed, the main argument is that keyword/keyphrase extraction cannot replace the human element of wittiness, critical thinking, and engagement with the reader of a book.
Comment: I agree that AI can't yet match human level of insight. However, example of "Syria 2, 3, 5, 6, 7, 10, 23, 25, 26, 27 …" is to naive. No modern (or even good 15 years old) keyword extraction method can make such a mistake. Even simple Inverse Document Frequency weighting over pages/paragraphs will probably be enough to avoid  it.
Answer: I think this problem is very similar to keywords/keyphrases extraction problem. Keywords extraction is well studied task (see for example this paper for review). Possible approaches include  heuristics, supervised machine learning (with a number of special feautures like TD/IDF, position in the sentence and other) and  language models. Powerful keywords/keyphrases extraction tools exist, thus one can try them first, and see if they do job well.


Definir uma variável de sessão clicando em um link

Question: Tenho uma lista dropdown, que permite escolher o ano que será utilizado na pesquisa da base de dados. Gostaria que o utilizador ao seleccionar uma dessas datas,  defini-se uma variável de sessão com o valor do ano, e assim ser possível utilizar essa variável em futuras pesquisas à base de dados.

       2016

2015

2017

Se possível que não muda-se de página, mas se for obrigatório não será, para mim, impeditivo a sua utilização.
Comment: Esse dropdown é do bootstrap.
Answer: Alterando um pouquinho sua estrutura para:

    2016

2015

2017

Um script em javascript usando jQuery para executar a sessão de forma invisível.

Arquivo externo com a função para alterar a sessão:
alterarSessaoDoAno.php
<?php
    session_start();
    // aqui você personaliza o nome da sessão de acordo com o que já tem (se tiver).
    $_SESSION['ano'] = $_POST['ano'];
    header('Content-Type: application/json');
    echo json_encode(array('status' => true));
?>

É isso! Dessa forma, no clique da opção do ano, de forma invisível ao usuário e sem piscar a página, ele vai alterar a sessão do ano.
Comment: Quando tento ver o valor de `value` ele dá undefined: `var value = $(this).data("ano");
                alert(value);` Deveria dar o ano que seleccionei, Correcto?
Comment: Tente trocar `$("#alterar-ano li")` por `$("#alterar-ano [data-ano]")` e tente ver o resultado do `alert`.


Setting executable file permissions with automake

Question: I'm trying to figure out how to have automake change the file permissions on a newly generated executable automatically.  Essentially, I want it to perform a 'chmod' every time it creates the executable, but I can't find anything that allows me to specify arbitrary shell commands after compilation.  Any suggestions?
Thanks a lot,
Kyle
Answer: If you use the standard variables such as bin_PROGRAMS and bin_SCRIPTS, the installed files should be made executable automatically.  For other uses you could use a hook target such as install-exec-hook or install-data-hook.  This is described in the documentation and in the autobook.


How does $1/e^{(1/\infty)}$ equal $1$?

Question: My professor had us solve an improper integral, the problem or work I did correctly, however, when I got to the final part of the answer, I got $1/e^{1/\infty} - 1/e$.
My professor got this as well, but when she put the actual value, she put $1 - 1/e$.
I thought that $e^{(-1/\infty)}$ equals zero, because anything over infinity equals zero. Am I wrong? Why does it equal 1?
Comment: $1/e^{1/\infty}$ doesn't mean anything.
Comment: $\frac{1}{\infty}=0$ (assuming you have this definition) but $e^0=1$.
Answer: First of all, $\frac{1}{x^{1/\infty}}$ doesn't equal anything because $\infty$ is not a number.
However, $\lim_{x\to\infty} \frac{1}{e^{1/x}}=\frac{1}{e^0}=1$
Comment: This is such an important answer. Students need to remember that $\infty$ is not a number and shouldn't just be substituted in.
Answer: HINT
Note that $(1)$ $\lim_{x\to \infty }1/x=0$, $(2)$ $e^0=1$, and $(3)$ the exponential function is continuous.
Answer: The bit that reads (-1/inf) is equivalent to zero. So now doing the exponential you have exp(0), which of course is 1.

How does $1/e^{(1/\infty)}$ equal $1$?


Using Riemann integrals to find limits

Question: Evaluate $$\lim_{n\to\infty}\frac{\sum_{k=1}^n\sqrt{k}}{\sum_{k=1}^n\sqrt{n+k}}$$
I can't seem to remove the $\frac{1}{n}$ term in order to use the riemann integral any help?
Comment: Two different sums, one in numerator and the other one un denominator? That's weird...are you sure that's right? Also, shouldn't it be $\;n^2+k^2\;$ or something like that inside the denominator's square root?
Answer: Hint:
Let me introduce some terms $$\lim_{n\to\infty}\frac{\sum_{k=1}^n\sqrt{k}}{\sum_{k=1}^n\sqrt{n+k}} = \lim_{n \to \infty}\frac{\frac1n\sum_{k=1}^n\sqrt{\frac{k}{n}}}{\frac1n\sum_{k=1}^n\sqrt{\frac{n+k}{n}}}  $$
Comment: $$\ldots = \frac{\int_0^1\sqrt{x}\,dx}{\int_1^2\sqrt{x}\,dx}=\frac{2\sqrt{2}+1}{7}.$$
Comment: Oh so are we supposed to calculate two riemann integrals in this case
Comment: That is my first intuition when I first look at the question.

Using Riemann integrals to find limits


low gain pre-amp does not cause distortion. But hi-gain pre-amp does. Is this a guitar wiring issue?

Question: I have a yamaha THR5 which models a low-gain preamp('CRUNCH') and a hi-gain preamp('BRIT-HI').
For some reason Brit-Hi works just fine, but Crunch doesn't sound any different from clean(except louder).
My wiring diagram is a standard one from SD(HSS):
https://www.seymourduncan.com/wiring-diagrams?meta_params=guitar-options,3-pickups,neck-s,middle-s,bridge-h,1-volume,1-tone
Does this behavior imply my guitar's output is too low to get any effects from the low-gain preamps? Or is there some other issues?
Comment: Usually "low gain" means little to no distortion, and "hi gain" means a medium amount to a lot of distortion. Seems like the amp is working as intended.
Comment: Maybe you're not running the amplifier louder enough for breakup to occur?
Comment: IIRC, one of the ways to cause distortion is to have your "input volume" higher than your "output volume" - so a low-gain preamp might not be creating a higher input volume, where the high-gain preamp *is* creating the higher input volume.  Don't know if this helps with your question, but I thought it might be interesting.
Answer: The THR tries (supposedly) to model all-tube amps. In such an amp, distortion is produced at (at least) two different spots: in the preamp and in the power stage.

Preamp overdrive is mostly used for long-sustain lead sounds. This requires very high gain in the first stage, but not necessarily very high volume.
Poweramp overdrive is an inevitable side-effect of making an amp loud - basically, of reaching its power limits. This is a more dynamic distortion, good for rhythm parts.

The "crunch" model of the amp probably focuses on the power stage, i.e. the preamp doesn't have so much gain that it really distorts by itself, it merely makes the signal really loud so it can then overdrive the power stage. But that will only actually happen if you also turn the volume way up, since the volume control sits between preamp and power stage.
With real tube amps, in particular full stacks, this is often a bit of a problem: the amps only sound good if played brutally loud, i.e. so loud that nobody else in the band can hear anything. With the THR5, don't know... but apparently that has gain, volume and additionally master controls. For a crunchy sound you'll want to turn gain medium to high, volume pretty high, and only the master down again if necessary.
Note that it's a hallmark of a tube amp to give you a good warm overdrive without sounding very obviously distorted. This is unlike analogue transistor amps, which tend to sound pretty nasty already in crunch setting.
Answer: I don't have enough info to answer this question comprehensively but here is my experience.
Gain is something tha can be seen as a type of volume or distortion maker but it isn't. Gain is the effect that makes and instrument more sensitive to minor things. Gain increases sensitivity, not distortion or loudness. The reason why people may think that distortion of sound is due to gain is the fact that a lot of guitar amps can't take the sensitivity of the gain and this produces distortion, or the guitar amp is designed to give out a more distorted sound when sensitivity in increased. Note pre amps are those things that are made to amplify your guitar before the speaker or amp. They are initially made for those low output instruments to amplify the sound. This is why the CRUNCH amp is simply louder. If the effects on the CRUNCH preamp don't work for your guitar I would say the preamp is the problem, not the guitar. If you are wanting a higher output from your guitar then I would say that you have to put an onboard preamp on it or change the pickups to a higher output type.
In a low gain situation (CRUNCH), rubbing the pick against a guitar string should cause little or no sound. This is why low gain is usually used in a situation where a clean strumming or picking sound is needed. It can also be used to make notes clearer.
In a high gain situation (BRIT-HIGH), you should clearly be able to hear a pick rubbing against the strings. The guitar has just been made more sensitive. This is useful in situations such as pinch harmonics where the sound of the harmonic is very low and the sensitivity needs to be increased, to hear that harmonic. Volume can sometimes increase the sound of a pinch harmonic but it also increases the sound of the pick rubbing on the string making the pinch harmonic sound sloppy.
In my experience I would say that there is nothing wrong with your guitar. Just a misunderstanding. If the crunch preamp effects don't work for your guitar then the preamp is probably broken. Give both of the preamps a test with different guitars and see what happens, this may give you more information on the problem.
Good luck. :)


Differences between linear and canonical discriminant analyses (LDA and CDA)

Question: I'm using R to try and compare the results of variable chemical compositions, following on from an article I've read.  In it, the authors used CDA to do something very similar to what I want to do, but I've been told by another researcher (without much of an explanation) that LDA would be better suited.  I could go into the specifics of why supervised learning is the avenue chosen, etc. but I won't post that unless someone asks.
After doing some background reading (which hasn't really cleared up the difference between the two), I figured I'd try to explore this myself and compare the results.  The primary difference between my data and that in this article is that instead of just using the compositions, I've created 3 new variables (S-, F- and V-) for the CDA that are functions of the original compositional data (see code below).
However, when I run the two analyses I get EXACTLY the same results - identical plots.  This doesn't seem possible, but I can't find an error in my coding.
My two questions are:

Is it possible for LDA and CDA to return the exact same result?
What are the practical differences between LDA and CDA?

Data:
library(MASS)
library(candisc)
library(ggplot2)

al2o3<-runif(20,5,10)
sio2<-runif(20,10,30)
feo<-runif(20,40,60)
country<-c(rep("England",6), rep("Scotland",6), rep("Wales",4), rep("France",4))
df<-data.frame(country,al2o3,sio2,feo)

LDA:
lda <- lda(country ~ feo+sio2+al2o3, data=df)
plda <- predict(object = lda, newdata = df)
dataset = data.frame(country = df[,"country"], lda = plda$x)
ggplot(dataset) + geom_point(aes(lda.LD1, lda.LD2, colour = country))

CDA:
fvalue<-(df$also3/df$sio2)
svalue<-((2.39*df$feo)/(df$al2o3+df$sio2))
vvalue<-(df$sio2/df$feo)

mod <- lm(cbind(feo,sio2,al2o3) ~ country, data=df)
can2 <- candiscList(mod)
mod2 <- lm(cbind(fvalue,svalue,vvalue) ~ country, data=df)
can3 <- candiscList(mod2)
ggplot(can2$country$scores, aes(x=Can1,y=Can2)) + geom_point(aes(color=country))

Comment: Why are you surprised? That's just two names for the same thing.
Comment: What introductory book does the "CDA" name come from?
Comment: Thanks for the response amoeba - that's kind of the sneaking suspicion I've had... but then why do the two names exist?  Do you know of any citation that the two techniques are identical?  The introductory books I've looked through haven't said as much.  I think I'd need some kind of reasoning to justify why I call it LDA v.s. CDA for my research.
Comment: It's from this particular article - looking at it again, it actually says "canonical linear discriminant analysis, or CDA".  So if the two are the same, then I must have gotten mixed up by not seeing the acronym LDA.  Then the presence of the `candisc` function made me even more confused.  Thanks - repost your comment as an answer and I'll accept it!
Comment: I can't be sure what those authors of that article call canonical DA, but modern LDA _is_ canonical LDA (see footnote to [my answer](http://stats.stackexchange.com/a/190821/3277) for example) because the latent roots of $W^{-1}B$ matrix are called "canonical".
Answer: These are two names for the same thing.
Linear discriminant analysis (LDA) is called a lot of different names. I have seen

canonical discriminant analysis
canonical linear discriminant analysis
descriptive discriminant analysis (see What is "Descriptive Discriminant Analysis"?)
Fisher's discriminant analysis

and possibly some others. I suspect different names might be used in different applied fields. In machine learning, "linear discriminant analysis" is by far the most standard term and "LDA" is a standard abbreviation.

The reason for the term "canonical" is probably that LDA can be understood as a special case of canonical correlation analysis (CCA). Specifically, the "dimensionality reduction part" of LDA is equivalent to doing CCA between the data matrix $\mathbf X$ and the group indicator matrix $\mathbf G$. The indicator matrix $\mathbf G$ is a matrix with $n$ rows and $k$ columns with $G_{ij}=1$ if $i$-th data point belongs to class $j$ and zero otherwise. [Footnote: this $\mathbf G$ should not be centered.]
This fact is not at all obvious and has a proof, which this margin is too narrow to contain.
Comment: I've updated [one of my answers](http://stats.stackexchange.com/a/169483/3277) to highlight the matter and how I find it. Please share your thoughts if you've got any.
Comment: `n rows and k columns with...` k-1 columns?
Comment: @ttnphns No, I really meant $k$ columns. I am certain that CCA will give LDA result in this case. Of course the $k$ columns are linearly dependent and any one of them can be dropped to make $G$ full rank; I think that after one of the columns is dropped, CCA will still give the same result, but I am not 100% sure at the moment. Can you confirm that?
Comment: I don't know how it will give any result at all. The implementation which I [know well](http://stats.stackexchange.com/a/77309/3277) uses Cholesky function which won't allow singularity of any of the two correlation matrices. Besides, if even linear regression (standard algorithm) won't tolerate singularity, why multivariate regression (such as CCA) should allow it?
Comment: @ttnphns Oh, yes. Thanks for bringing it up. I figured out what's going on. The CCA should be applied between $X$ and $G$ (where $G$ has all $k$ columns as I wrote), but without centering $G$. Without centering it is full rank and can be inverted (or one can use Cholesky) without a problem. By the way, CCA-LDA correspondence works because $(G^\top G)^{-1} G^\top X$ will be a matrix filled with class means, so one quickly gets to the between-class scatter matrix via the CCA formulas. For this it is important that $G$ remains non-centered, in its original zeros-and-ones form. Does it make sense?
Comment: @ttnphns I think what you wrote there is correct (by the way, this answer of yours as well as another related one that you now edited too, both have my enthusiastic +1s). For me, non-centering the indicator matrix $G$ and including all $k$ columns is more convenient (and not "less convenient") because it makes the algebra easier, at least in the derivations that I know. Perhaps there are some alternative derivations that would be easier with $k-1$ centered columns. And it might very well be that the latter approach is more convenient in practice. Thanks for this exchange, it was useful.


Minimum distance between curves

Question: We define $$f: \mathbb{R} \to \mathbb{R^3}, f(x)=\begin{pmatrix}
cos(\pi \cdot x) \\
sin(\pi\cdot x) \\
1-x^2
\end{pmatrix}$$
Problem: Calculate the minimum distance to the point of orign
My ideas:
The distance is definded by:
$$d(x)=\sqrt{|(cos(π⋅x)-0)^2|+|(sin(π⋅x)-0)^2|+|((1-x^2)-0)^2}|$$
$$d(x)=\sqrt{|(cos(π⋅x))^2|+|(sin(π⋅x))^2|+|(1-x^2)^2}|$$
The minimum distance is the extrema of the first derivation, so I have to calculate $$d'(x)=0$$
As solution I get x=-1 or x=0 or x=1 (Wolfram Alpha)
But I'm not actually sure absout the solution and I don't know how to solve it without calculator.
Thanks in advance!
Comment: You can drop the square root.
Comment: ...and the moduli.
Answer: You're on the right track, you can minimize distance squared though. Try minimizing
$$
d^2(x)=f(x)=(\cos\pi x)^2+(\sin \pi x)^2+(1-x^2)^2=1+(1-x^2)^2
$$
Then we have, for a minimum
$$
f'(x)=-4x(1-x^2)=x^3-x=0\implies x=0,x=\pm1
$$
and
$$
f''(x)=12x^2-4
$$
Meaning we have a maximum at $x=0$ and minima at $x=\pm 1$
Comment: Thanks but I don't understand why $$(cosπx)^2+(sinπx)^2=1$$
Comment: That's a trig identity for sine and cosine
Comment: Do you know exactly which idendity it is?
Comment: I thought about the Set of pythagoras $$cos(x)^2+sin(x)^2=1$$, Right?
Comment: That's the one!
Answer: A geometric rather than an analytical approach would be the following:
The x and y values of the curve describe a circular motion (as the free variable $t$ increases, not the substition $x \rightarrow t$ here), projected on the x-y-plane, this is a circle around $(0,0)$.
All the points on a circle around the origin have the same distance to the origin in the x-y-plane. Hence, only the z-component $1-t^2$ is of imprortance to the distance. As a function of $t$, the z-component is a parabola which is closest to $0$ (in fact, equal to $0$) at the points $t=\pm1$.
Answer: You can continue, knowing that place where maximum of its square occurs is also the same.
$$ d^2(x) = y (x) = 1 + (1-x^2)^2 = 2 - 2 x^2 + x^4 $$
Derivative =0,
$$ 4x = 4 x^3,\ \quad x(1-x)(1+x) = 0 $$
gives WA result. Next derivative finds where max/min occur for above cubic.

Minimum distance between curves


The differences between date time zone handling

Question: There are several options for time zone handling, Site's time zone, Date's time, User's time zone, UTC and no time zone conversion. What are the differences between them?
One case would be a television broadcast where everybody in the world would experience simultaneously. Would User's time zone be correct to use? If the broadcaster put 8:00pm while living in New York someone in California would experience this at 5:00pm.
Or, the case, a poetry slam is happening in New York City and anybody who wants to experience it will have to physically be there at 8:00pm meaning it might be happening at 5:00pm in California but that doesn't matter to the person in California. What matters is that they are at the place at 8:00pm in New York so the time shouldn't change no matter where the user is or what time in their timezone the poetry slam is going on.
Answer: The Date module's documentation page describes the difference between the 5 options fairly well.
From that page:
There are 5 different options for field Time zone handling:

Site's time zone - When entering data into the field, the data entered is assumed to be in the site's time zone. When the data is saved to the database, it is converted to UTC. When retrieved from the database, the data is converted to the Site's time zone for annonymous users or the User's time zone for logged in users when User-configurable time zones is enabled.
Date's time zone - With this option enabled, the date field adds a select box to explicitly specify the time zone for the date entered. When the date is saved to the database, it is not converted & the time zone information is saved with the date. When retrieved from the database, no conversion is performed and the date is displayed exactly as entered.
User's time zone - When entering data into the field, the data entered is assumed to be in the user's time zone. When the data is saved to the database, it is converted to UTC. When retrieved from the database, the data is converted to the Site's time zone for annonymous users or the User's time zone for logged in users when User-configurable time zones is enabled.
UTC - When entering data into the field, the data entered is assumed to be in UTC time zone. When the data is saved to the database, it is converted to UTC (e.g. no conversion necessary). When retrieved from the database, the data is converted to the Site's time zone for annonymous users or the User's time zone for logged in users when User-configurable time zones is enabled.
No time zone conversion - The date entered is not converted when saved to the database. When retrieved from the database, the data is NOT converted and is displayed exactly as entered.


Page Inspector in ASP.NET MVC not working

Question: I am trying to open razor view templates in Page Inspector mode and those are not shown. What I get instead is the error The resource cannot be found.
My path to open the View Page is View/Admin/Login.cshtml
Earlier I have used the controller with the name AdminController but now I am using the controller with a different name. What I have done is divide the AdminController into multiple controllers in order to ease out things. I have one named LoginController.
When I run the project all views are working fine, but not in page inspector mode.
How can this page inspector problem  be resolved?
Comment: When you moved logic to another controller, did you also move the view to matching folder name. For example if your action method Login has logic such as return View(), it would first look for the folder named same as controller and then towards share etc. So you would have to move the view to folder named login, or return view like this return View("~/Views/YourArea/YourController/YourView.aspx");
Answer: Check following place of your code:
webconfig
    <appSettings>
      <add key="loginUrl" value="[ControllerName]/[LoginActionName]" /> ...

if it is still render wrong, then add following to system.web in web config too(if you use Form Authenticate):
<authentication mode="Forms">
      <forms loginUrl="[ControllerName]/[LoginActionName]" timeout="2880" />
    </authentication>


Show that $\frac{X}{X+Y}\sim Beta(\alpha,\beta)$

Question:
Let IG denote Inverse-Gamma distribution
  Inverse-Gamma.
  If $X\sim IG(\alpha,1)$ and $Y\sim IG(\beta,1)$. Show that
  $\frac{X}{X+Y}\sim Beta(\alpha,\beta)$

I tried with jacobian transformation taking
$Z=\frac{X}{X+Y}$ and $W=Y$ then $$X=\frac{WZ}{1-Z};Y=W$$
$$\frac{\partial(z,w)}{\partial(x,y)}=\frac{1}{(1-z)^2}$$
$$f_{z,w}(z,w)=f_x(\frac{wz}{1-z})f_y(w)(1-z)^2$$
$$f_{z,w}(z,w)=\frac{1}{\Gamma{(a)}}(\frac{wz}{1-z})^{-\alpha-1}e^{-\frac{(1-z)}{wz}}\frac{1}{\Gamma{(\beta)}}w^{-\beta-1}e^{-\frac{1}{w}}(1-z)^2$$
but I'm stuck, in some place I read that $\frac{X}{X+Y}$ is a type 3 Beta distribution, but I can't show that.
Comment: Your result is a joint density for $z$ and $w$, but you need marginal density for $z$ only. So if you integrate your $f_{z,w}(z,w)$ by $w$ from 0 to $\infty$ and use property of beta function that $B(\alpha, \beta) = \frac{\Gamma(\alpha)\Gamma(\beta)}{\Gamma(\alpha+\beta)}$ you'll obtain exactly the same Beta distribution as you want. Note that you don't have to calculate the integral from scratch because expression under it can be seen as inverse gamma distribution.
Comment: And yes, $(1 - z)^2$ should be $(1 - z)^{-2}$ (you could see it yourself because otherwise $f_{z,w}(z,w)$ has wrong dimension.
Comment: Looks like that should be $\frac{X}{X+Y}\sim Beta(\beta,\alpha)$
Answer: Here is my solution from first principles:
$$P\left(z' \leq z\ \left|\ z' = \frac{x}{x+y},\ x \sim X,\ y \sim Y\right. \right) = P\left(\frac{x}{x+y} \leq z\right) = $$
$$ \int dP_{X}(x) \int dP_{Y}(y)\ I\left[
\frac{x}{x+y} \leq z\right] =
 \iint dx\ dy \ f_{X}(x)\ f_{Y}(y)\ \theta\left(y \frac{z} {1-z} - x\right),$$
where $\theta(x)$ is a Heaviside Step function.
Differentiating $P(z)$ by $z$ one can obtain that
$$f_{Z}(z) = \frac{d}{dz} P(z' < z) =
\int dx\ f_{X}(x) \int dy\ f_{Y}(y)\ \delta\left(y \frac{z} {1-z} - x\right) \frac{y}{(1-z)^2},$$
where $\delta(x)$ is a Dirac Delta function. So integrating over $x$ one could see that
$$f_{Z}(z) = \int dy \ f_{Y}(y)\ f_X\left(y \frac{z}{1-z}\right) \frac{y}{(1-z)^2} =$$
$$\frac{1}{\Gamma(\alpha)\Gamma(\beta)} (1-z)^{-2} \int dy\
y^{-\beta -1}e^{-\frac{1}{y}}\cdot y^{-\alpha - 1} z^{-\alpha -1} (1-z)^{\alpha+1} e^{-\frac{1-z}{yz}},$$
and after simplification and integration by $y$
$$f_{Z}(z) = \frac{\Gamma(\alpha + \beta)}{\Gamma(\alpha)\Gamma(\beta)} (1-z)^{\alpha-1} z^{\beta - 1}$$ which is probability density of beta  distribution $Beta(\beta, \alpha).$
P.S. You can avoid using of Step/Delta functions by specifying precise limits of the inner integral, but I find that way less handy.


How to upload/insert images in content from module?

Question: <code>  $article = entity_create('node', array(
    'type' => 'article',
    'title' => generate_demo_content('lorem_ipsum_title'),
    'body' => array(
      'value' => generate_an_article(),
      'format' => 'full_html',
    ),
    // how attach here, a file or an image?
  ));
  $article->save();
</code>
I create an article from a .module file, and I would like know if I can link an image/file object to my article?
By example if I have an image inside /modules/my_module_name/images/img.jpg, how I can insert this image inside my article object from my .module file please?
Thanks.
Answer: I have tried the below code with node_save method but not with entity_create way. Check if it works.
<code>$dir = 'public://';
if (file_prepare_directory($dir, FILE_CREATE_DIRECTORY)) {
  $file = file_save_upload('image', array(), $dir, FILE_EXISTS_RENAME);
  $file->status = FILE_STATUS_PERMANENT;
  file_save($file);
  $attachment = array(
    'fid' => $file->fid,
    'display' => 1,
    'description' => $file->name,
    'title' => $values->tooltip
  );
}

$article = entity_create('node', array(
  'type' => 'article',
  'title' => generate_demo_content('lorem_ipsum_title'),
  'body' => array(
    'value' => generate_an_article(),
    'format' => 'full_html',
  ),
  'field_attachment' => $attachment, //may need to change here
));
</code>


What does it mean that "point estimation resulted in $\hat{\mu} = 12.5 \pm 1.0$"?

Question: I'm trying to figure out what the following statement means:

As a result of point estimation of the mean value of a certain quantity, the value $$\hat{\mu} = 12.5 \pm 1.0 \ [u]$$ was obtained. Assume $n=36$ measurements, each with the same precision.

I know that for a iid normal sample, the sample mean $\hat{\mu} \equiv \bar{X}$ (which is a random variable) has a $N(\mu, \sigma^2/n)$ distribution. Likewise, the sample variance $\hat{\sigma}^2 \equiv s^2$ is such that $(n-1) s^2/\sigma^2$ has a $\chi^2 _{n-1}$ distribution.
I'm confused because I thought "point estimation" referred to specifying one number, in this case $12.5$. So I'm not sure what the $1.0$ in this case - is it $s/ \sqrt{n}$, the standard error of the mean (which is the estimate for the standard deviation of the random variable $\bar{X}$ )? What is the convention used here?
Additionally, I have another identical problem except it's about the variance:

As a result of point estimation of the variance of a certain quantity, the value $$\hat{\sigma} = 12.3 \pm 4.1 \ [u^2]$$ was obtained. Assume $n=36$ measurements, each with the same precision.

In this case, does the $\pm$ part refer to the estimate of the standard deviation of the random variable $s^2$, obtained from the $\chi^2$ distribution, which is $ s^2 \sqrt{2/n-1} $ ?
Comment: It isn't nonstandard, either.  It's a little idiosyncratic.  It's also ambiguous, because the meaning of the numbers after the "$\pm$" isn't clear: would those be standard errors or confidence limits (and if they are the latter, with what confidence level)?  The ambiguity might be resolved within the context; for instance, maybe your textbook has previously explained what these numbers mean.  That's why you need to go back to it and why we can only guess.
Comment: Can you provide the reference for the statements?
Comment: @Thomas Unfortunately there isn't any, it's just a problem from a problem set
Comment: You ought to consult the underlying authority, then: either the teacher or the textbook.
Comment: @whuber So I take it this isn't a standard way of writing things?
Comment: @whuber It's definitely not the confidence interval because the question is to calculate that (make an interval estimation at 0.95). Unfortunately there isn't any explanation provided for the notation anywhere that I can find.
Answer: From the prologue of Lehmann and Casella's Theory of Point Estimation:

Point estimation is one of the most common forms of statistical
  inference. One measures a physical quantity in order to estimate its
  value; surveys are conducted to estimate the proportion of voters
  favoring a candidate or viewers watching a television program;
  agricultural experiments are carried out to estimate the effect of a
  new fertilizer, and the clinical experiments to estimate the improved
  life expectancy or cure rate resulting from a medical treatment....

I take a "point estimate" to mean a very general sense of "things you estimate with statistics": unifying the concepts of means, proportions, rates, counts, hazards, differences, ratios, etc. as well as their respective methods: maximum likelihood, method of moments, regression, estimating equations, minimax, root finding algorithms, and so on.
This would seem to imply that that terminology is really only endemic to statistical theory and pedagogy. It would be totally out of place in the context of actually reporting statistics: you know the thing you estimated, why not tell us what it is?
The notation $\mu$ is highly suggestive of the population mean whose estimate $\hat{\mu}$ is usually the sample (arithmetic) mean and has a standard error estimated by the sample standard deviation divided by the root of the sample size. Confusingly, I have seen written $\hat{\mu} \pm \text{SE}$ as well as $\hat{\mu} \pm 1.96 \times \text{SE}$ in lieu of reporting an actual confidence interval, the former only really being appropriate if there is no set level of confidence or if it is in fact 66% and the latter only if the confidence is 95%. So alas, all I can definitively say is that the notation is ambiguous.


Erro Assertion failure: "(!"SetThreadContext failed")" in ..\win32src\thread32.cpp at line 434

Question: Estou compilando meu projeto C++ no CodeGear 2009 da Embarcadero, e quando começo a debugar meu programa esta mensagem aparece:

bds.exe - bordbk120N.dll
  Assertion failure: "(!"SetThreadContext failed")" in ..\win32src\thread32.cpp at line 434
  Continue execution?

Imagem:

Alguém poderia me ajudar a entender o porque deste erro e como solucionar?
Answer: Consegui resolver o problema, pesquisando um pouco mais na internet descobri que a .dll bordbk120N.dll possui um bug quando a mesma é executada na plataforma Win7 x64 para esta versão 2009 e anteriores. Para correção deste problema, deve-se alterar um trecho do bordbk120N.dll. Segue abaixo os passos para correção deste bug:
Tome cuidado! Não há garantias! Eu não sou responsável por arquivos perdidos, etc.! Faça cópia de backup antes de prosseguir!
Passos para resolução:
1 - Feche o Delphi ou o C++ Builder
2 - Localize a biblioteca bordbk120N.dll (C:\Program Files (x86)\CodeGear\RAD Studio\6.0\bin)
3 - Faça uma cópia de backup
4 - Verifique que o passo 3 foi efetuado corretamente
5 - Abra o arquivo bordbk120N.dll em um editor Hexadecimal (o UltraEdit funciona suficientemente bem)
6 - Procure pela sequência "01 00 48 74 47 80 3D"
7 - Garanta que essa sequência aparece no arquivo uma única vez
8 - Altere o valor "74" por "EB"
9 - Salve o arquivo
10 - Reinicie o Delphi ou o C++ Builder. O erro não deve mais ocorrer.
Estas informações foram extraídas (em tradução livre) do link abaixo:
http://www.monien.net/delphi-2009-windows-7-64-bit-debugger-crash-workaround/comment-page-3/#comment-7588
Comment: Eu tomei a liberdade de traduzir os passos para Português (pra facilitar a possíveis leitores futuros). :)


A Haar measure via the Lebesgue measure on $\Bbb R^d$

Question: $\newcommand{\d}{\mathrm{d}}$
This the Exercise 3, Chapter 11 of the Gerald B. Folland book Real Analysis:

Let $G$ be a locally compact group that is homeomorphic to an open subset $U$ of $\Bbb R^d$ in such a way that, if we identify $G$ with $U$, left translation is an affine map -- that is, $xy=A_x(y)+b_x$ where $A_x$ is a linear transformation of $\Bbb R^d$ and $b_x\in\Bbb R^d$. Then $|\det A_x|^{-1}\d x$ is a left Haar measure on $G$, where $\d x$ denotes Lebesgue measure on $\Bbb R^d$.

Let me know if I understand this.
What the problem gives us is $G$ a locally compact group, an open set $U\subseteq\Bbb R^d$, and a bijection $\varphi:G\to U$ such that $\varphi$ and $\varphi^{-1}$ are both continuous and satisfy that given $u\in G$ there is a linear operator $A_{\varphi(u)}:\Bbb R^d\to \Bbb R^d$ and $b_{\varphi(u)}\in\Bbb R^d$ so that $$\varphi(uv)=A_{\varphi(u)}(\varphi(v))+b_{\varphi(u)}.$$

Is this right

If it is, define $f:\Bbb R^d\to\Bbb [0,\infty[$ given by $$f(x)=|\det A_x|^{-1}\quad\text{i.e.}\quad f(x)=|\det A_{\varphi(\varphi^{-1}(x))}|^{-1}.$$

Is the problem asking if the measure $\mu$ in $G$ given by $$\mu(E)=\int_{\varphi(E)}f(x)\d x$$ is a left Haar measure?

This reminds me the formula $$\int_E f(y)\d y=|\det T|\int_{T^{-1} E} f(Tx)\d x,$$
but I don't know what  can I do.
Any advice in how to interpret the problem or on how to proceed is very appreciated.
Comment: As to why such a $\phi$ exists: That's an assumption, part of the "Let ..."; no reason is given or required.
Comment: @martini $\mu$ is a Haar measure if is a nonzero Radon measure that satisfies that for all $x\in G$ and $E\subseteq G$, $\mu(xE)=\mu(E)$
Comment: @joriki okay ${}{}$
Comment: What do you have to check for $\mu$ to be a Haar measure? ...
Comment: What of these condition did you manage to check?
Comment: @martini First I want to know if the way I read the problem is correct. Is it?
Answer: The notation $xy=A_xy+b_x$ is quite confusing indeed.  It appears on the left hand side, that $x,y\in G$; however, on the right hand side, it would appear that $y\in\mathbb{R}^d$. Your introduction of the homeomorphism, $\varphi:G\mapsto U\subset\mathbb{R}^d$, is the right thing to do.

Is this right

Yes, that is a restatement of part of the hypothesis with the homeomorphism given explicitly by $\varphi$. Since $\varphi$ is a homeomorphism, we could simply write
$$
\varphi(uv)=A_u\varphi(v)+b_u
$$

Is the problem asking if the measure $\mu$ in $G$ given by $$\mu(E)=\int_{\varphi(E)}f(x)\mathrm{d} x$$ is a left Haar measure?

Since $f(x)$ is meaningless for $x\not\in U$, I would define $f:U\mapsto[0,\infty)$ by
$$
f(\varphi(u))=|\det A_u|^{-1}
$$
and then define $\mu$ as you do above:
$$
\begin{align}
\mu(E)
&=\int_{\varphi(E)}f(x)\,\mathrm{d}x
\end{align}
$$
Now note that
$$
\begin{align}
\varphi(uvw)
&=\color{#C00000}{A_{uv}}\varphi(w)+\color{#00A000}{b_{uv}}\\
&=A_u\varphi(vw)+b_u\\
&=A_u(A_v\varphi(w)+b_v)+b_u\\
&=\color{#C00000}{A_uA_v}\varphi(w)+\color{#00A000}{A_ub_v+b_u}
\end{align}
$$
Therefore, we get $A_{uv}=A_uA_v$. Thus, we get
$$
\begin{align}
f(\varphi(uv))
&=|\det(A_{uv})|^{-1}\\
&=|\det(A_uA_v)|^{-1}\\
&=|\det(A_u)\det(A_v)|^{-1}\\
&=f(\varphi(u))f(\varphi(v))
\end{align}
$$
At this point, to show the translation invariance,
$$
\begin{align}
\mu(uE)
&=\int_{\varphi(uE)}f(x)\,\mathrm{d}x\\
&=\int_{\varphi(E)}\color{#C00000}{f(\varphi(u\varphi^{-1}(x)))}\,\color{#00A000}{\mathrm{d}(A_{u}x+b_{u^{-1}})}\\
&=\int_{\varphi(E)}\color{#C00000}{f(\varphi(u))f(x)}\color{#00A000}{|\det A_{u}|\,\mathrm{d}x}\\
&=\int_{\varphi(E)}|\det A_{u}|^{-1}f(x)|\det A_{u}|\,\mathrm{d}x\\
&=\int_{\varphi(E)}f(x)\,\mathrm{d}x\\
&=\mu(E)
\end{align}
$$
Comment: This is great! thanks for your answer.


My images are not being displayed in a row

Question: In a section of my code I made a row-grid for a part that displays images but when I went to insert and look at the website its not displaying in a row format but in a column and im not sure why. I thought the problem came from it being col-sm-6 but i changed it to col-sm-12 and its still not displaying it. Any reasons why?

.site-main .project-area {
  padding: 4rem 0;
}

.site-main .project-area .button-group button {
  background: transparent;
  border: none;
  font: normal 500 16px/130px var(--lato);
  text-transform: uppercase;
}

.site-main .project-area .button-group button+button {
  padding-left: 3rem;
}

.site-main .project-area .grid .our-project>title h4 {
  font: normal 700 25px/12px var(--lato);
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

 Recent Projects

 Quality Work

      <button type="button" class="active">All</button>
      <button type="button" data-filter=".cars">Cars</button>
      <button type="button" data-filter=".character">Characters</button>
      <button type="button">Food</button>
      <button type="button">Activities</button>

minimul design

            Latest, Popular

video game character

            popular, Portfolio

minimul design

            Latest, Popular

minimul design

            Latest, Popular

Comment: I don't recall a BS classed called row-grid
Answer: Changing the class row-grid to row makes it work. I don't think Bootstrap has a class called row-grid.
If you are trying to fit all the div elements into one row, just replace the col-lg-4 col-md-6 col-sm-6 and the col-lg-4 col-md-6 col-sm-12 with col
Comment: thank you so much. im learning bootstrap.
Comment: Glad I could help


The module react-native-image-picker in iOS always requires microphone permissions although I don't select video, only camera

Question: I'm using react-native-image-picker (to take photos / to select photos) to upload them to my server. It works perfectly.
To do this I use an ImagePicker. The problem comes when I notice that in iOS, if I want to use it, the module requires me the microphone permissions.
I've looked in the documents because it should happen and they say that if you want to make videos you have to have the microphone permissions. It seems consistent, the problem is that I only use the camera to take only pictures, no video.
This is my code:
<code>var ImagePicker = require('react-native-image-picker');
var options = {
  title: 'Adjuntar Imagenes',
  takePhotoButtonTitle: 'Hacer foto',
  chooseFromLibraryButtonTitle: 'Elegir foto',
  cancelButtonTitle: "Cancelar",
  mediaType: 'photo',
  storageOptions: {
    skipBackup: true,
    path: 'images'
  }
};

ImagePicker.showImagePicker(options, (response) => {

  if (response.didCancel) {
    console.log('User cancelled image picker');
  }
  else if (response.error) {
    console.log('ImagePicker Error: ', response.error);
  }
  else {
      var fileNamePlanB = response.uri;
      fileNamePlanB =  fileNamePlanB.split('/')[fileNamePlanB.split('/').length-1]
      console.log(fileNamePlanB.split('/')[fileNamePlanB.split('/').length-1]);
      var dataOBJ = {uri: response.uri, name: (response.fileName != null? response.fileName : fileNamePlanB ), type: response.type};
      this.uploadImage(dataOBJ, this.dameRistraSubject(data));
    }
});
</code>
So, I'm doing something wrong that requires microphone permission? Always open the camera to still make a picture.
Answer: Finally I found the mistake. It has no relationship with the react-native-image-picker module. I was receiving authorizations from another wrong source.


Can I make a linear congruential generator with a lognormal distribution?

Question: One of my class tasks is to make a simulation. I've gathered the data and done distribution fitting to it and the result of the distribution is log-normal. I have the code to generate random numbers in Java using a linear congruential generator, so can I somehow convert them to a log-normal distribution with parameters mu and sigma?
Comment: Sure - convert uniforms to the corresponding normal by any of the standard methods (Polar method, Box-Muller, inverse transform, ziggurat, etc etc) - and then exponentiate.
Comment: unclear: do you have to run a simulation or analyse data?
Comment: i analyze a set of the data and make simulation based on it.
Comment: and in which part i set the parameter for the distribution, because the lognormal dist in my case must follow specific mu and sigma
Comment: The mu and sigma are set when you transform to normality. Since this is for a class, you need to add the `self-study` tag and edit your question to follow the guidelines at its [tag wiki](http://stats.stackexchange.com/tags/self-study/info), including explaining what you understand, outlining what attempts you made to solve your problem and identifying the *specific* help you need.
Answer: You should be able to use your random number generator to get a random uniform $U \sim \mathcal{U}(0, 1)$ (just a random number between zero and one, the default for many random number generators).  Then you can use the Box-Muller transform to get a random normal $X \sim \mathcal{N}(0, 1)$.  This involves generating two random uniforms $U_1$ and $U_2$ and then forming the variables:
$$\sqrt{-2 \log(U_1)} \cos(2 \pi U_2)$$
and
$$\sqrt{-2 \log(U_1)} \sin(2 \pi U_2)$$
Both of these resulting random variables are normally distributed with mean $0$ and standard deviation $1$.
Finally, take one of your standard normals $X$. The transformation $e^{\mu + \sigma X}$ is the log-normal you're after.
Here's a quick implementation of this in R, plus a histogram to show it working its magic:
<code>mu <- 0; sigma <- 1
u1 <- runif(50000); u2 <- runif(50000)
n <- sqrt(-2 * log(u1)) * cos(2 * pi * u2)
e <- exp(mu + sigma * n)
hist(e[e < 4], breaks=100)
</code>
Comment: @MatthewDrury This looks like a good answer to the question. Unfortunately it also looks like you've completed (at least part of) the OP's homework for them, which isn't consistent with our policy. The idea is to give hints and guidance on anything which is effectively routine bookwork (as might be set for.homework, even when it isn't homework).
Comment: and where do i set my own parameters for lognormal (mu and sigma)?
Comment: In the exponentiation step $e^{\mu + \sigma X}$.
Comment: @Glen_b  I see that you are correct.  I almost certainly did not read the introduction carefully enough, and the "one of my class tasks is to make a simulation" went through my head like noise.  I'll be more careful in the future, thank you for the heads up.


Copy div's append showing code how to fix it

Question: I using code to copy div's content using the code below :
<code> <textarea cols="100" rows="10" id="output"></textarea>
 <input type="submit" onClick="javascript:copyText();" value="Copy">

 function copyText(){
 var output = document.getElementById("container").innerHTML;
 document.getElementById("output").value = output;
 }
</code>
The problem is my div's in in list from append function. when i click copy the result will show the code. I want exact value showing in div's.
The full code in a fiddle
Answer: Change innerHtml to InnerText property
<code>var output = document.getElementById("container").innerText;
</code>
InnerHtml returns the html content of the element whereas innerText return the text(value)
See the updated Fiddle


Normal form and bifurcation

Question: Question:
Consider the discrete map
$$x_{n+1} = \mu \sin (\pi x_n) \qquad \qquad x \in [0,1]$$
where $\mu \in [0,1]$ is a parameter.

Find the value of $\mu$ for which a bifurcation occurs at the point $x=0$
State the normal form at the bifurcation and identify the type of bifurcation.

Attempt:
Let $f(x) = \mu \sin (\pi x)$.
For the first part, I computed
$$|f'(0)| = 1 \implies |\mu \pi| = 1 \implies \mu = \frac 1\pi$$
so a bifurcation occurs at $\mu = 1/\pi$. Is this correct?
For the second part, I let $\mu^* = \mu - 1/\pi$ so that a bifurcation occurs at $\mu^* = 0$ for $x=0$. Moreover, Taylor expanding about $x_n=0$ we get
$$x_{n+1} = (\pi\mu^*- 1)x_n - \frac{\pi^2(\pi\mu^*- 1)}{6}x_n^3 + \mathcal O\big(x_n^5 \big)$$
Is this correct? I don't recognise this type of bifurcation though? Looks like a pitchfork but it isn't? (Pitchfork is supposed to be $\, x_{n+1} \sim rx_n - x_n^3 \,$ I think?)
Any hints would be much appreciated. Thanks!
Answer: You get an equivalent iteration using $y_n=\sqrt{\frac{1+πμ^∗}6}πx_n$ where
$$
y_{n+1}=(1+πμ^∗)y_n-y_n^3+O(y_n^3)
$$
which has the desired normal form.

Normal form and bifurcation


why is my electric guitar rattling after being hit

Question: I accidenally hit the end of my guitar against the wall (stupid, i know) and now it's making a rattling noise. Any ideas why that is and how to fix it?
I haven't tried anything yet as I don't know what the problem is and I don't want to do any more damage.
edit: The rattling's coming from the top part (just under the part where you tune it) and it sounds like it's coming from inside it. Nothing looks like it's moving when it shouldn't. The make is Westwood but I'm not sure what the model is
Comment: You may have broken the truss-rod. See Player's somewhat terse answer.... if it's expensive, repair it, if cheap then bin it ..or keep it til the neck bends too far to use. Either way, you will need to strip it to find what it is.
Comment: Is it possible to tell where the rattling is coming from? What kinds of movements make it rattle? Does it sound like some small thing rattling around inside or does it feel like the whole guitar rattles? Doesn't any part of it seem to move that shouldn't be moving? Also, what kind of guitar is? (the make an model)
Comment: The rattling's coming from the top part (just under the part where you tune it) and it sounds like it's coming from inside it. Nothing looks like it's moving when it shouldn't. The make is Westwood but I'm not sure what the model is
Comment: Are all the strings in tune? It sounds like it could either be the truss rod or a tuning machine. If you haven't worked on guitars before you should take it to a shop and see what their estimate is for fixing it.
Answer: I'm guessing you mean that the rattling is coming from the head stock (where the tuning machines are).  Depending on what type of guitar it is, slotted head stock like a classical guitar, or steel string, there may be a small cover plate screwed in just behind the nut (the bit the strings rest on near the tuning machines).
If there is one, you can un-screw it and check inside to see if the truss rod nut is moving around, or if there is something that knocked loose in there.
You should also check the tuning machines themselves. Some machines have a nut that screws down on each machine which can come loose and cause rattling. Some of the inexpensive tuners have a metal cover plate that screws over the gears which can also come loose and rattle.
If you don't find anything obvious, then as the comments say, it may be your truss rod has come loose or broken. A trip to your Guitar tech or Luthier can tell you if the instrument needs and/or is worth repairing.
Answer: I agree with Alphonso.
First remove the truss rod cover to see if the truss rod has been broken.
(If it is, then the broken upper half may well rattle out when you upend the guitar.)


How to find the density of $Y=g(X)$ in this case?

Question: I have a vector $X=(1,X_2,X_3)$, where $(X_2,X_3)$ is a random vector in $\mathbb{R}^2$. Now consider $Y=g(X)=X/\|X\|$. What is a density function of $Y$  with respect to the uniform spherical measure, if I know the density of $(X_2,X_3)$?
The change of variables formula tells us that if $X=(X_1,\dots,X_n)$ has a density $f_X$ and $g:\mathbb{R}^n\to\mathbb{R}^n$ is continuously differentiable and injective, then $Y=g(X)$ has a density
$$f_Y(y)=\begin{cases}
  f_X(g^{-1}(y))|\det J_{g^{-1}}| & \text{ if $y$ is in the range of $g$} \\
  0 & \text{ otherwise }
\end{cases}
$$
The transformation $g:\mathbb{R}^2\to\mathbb{R}^3$,
$(x_2,x_3)\mapsto\left(\frac{1}{\sqrt{1+x_2^2+x_3^2}},\frac{x_2}{\sqrt{1+x_2^2+x_3^2}},\frac{x_3}{\sqrt{1+x_2^2+x_3^2}}\right)
$ is injective with inverse $$g^{-1}:(y_1,y_2,y_3)\mapsto \left(\frac{y_2}{y_1},\frac{y_3}{y_1}\right).$$
But now, I see some difficulties with the standard change of variables formula. First, $g^{-1}$ is a transformation between $\mathbb{R}^3$ and $\mathbb{R}^2$. The Jacobian is a $3\times 2$ matrix, which is not square.
Is there still a way to find a density of $Y$ with respect to the uniform spherical measure?
Comment: Just remove the first function $1/\sqrt{1 + x_2^2 + x_3^2}$.  Then you'll have a $2\times2$ matrix.
Comment: You can't. The three _random_ variables in $Y$ are not _jointly_ continuous and as such do not enjoy a joint density function $f_{Y_1,Y_2,Y_3}(y_1,y_1,y_3)$.  On a smaller scale, note that $W$ and $Z=W^2$ are two real random variables that do not possess a joint density because all the probability mass lies on the curve $z=w^2$ in the $w$-$z$ plane and the _density_ (measured in mass per unit _area_) of the probability mass at points on this curve is unbounded.
Comment: @Dilip Sarwate: I forgot to mention, that I'm interested in the joint density with respect to the uniform spherical measure.
Comment: @muaddib: Could you help me with some intuition why am I allowed to do this, please?
Comment: @Aad - I don't understand your addition to the problem: "What is a density function of Y with respect to the uniform spherical measure"
Comment: The original distribution is in $\mathbb{R}^2$. After normalization we have a distribution of $Y$ on the half-sphere, so there is no density with respect to the Lebesgue measure in $\mathbb{R}^3$ as pointed out by Dilip Sarwate. The density should be considered with respect to the spherical measure, which gives area, to any subset of the half-sphere and 1 to the whole $\mathbb{S}^2$.
Answer: You asked for an explanation of why you can restrict to two variables:
As you have found, when given two input random variables $X_2, X_3$ you need two output random variables $Y_2, Y_3$ to use the change of random variables formula.  Here
$$Y_2 = \frac{X_2}{1 + X_2^2 + X_3^2} \,\,\,\,\,\,\, Y_3 = \frac{X_2}{1 + X_2^2 + X_3^2}$$
I'll use your wording to show how this compares to your partial solution:
The transformation $g:\mathbb{R}^2\to\mathbb{R}^2$,
$(x_2,x_3)\mapsto\left(\frac{x_2}{\sqrt{1+x_2^2+x_3^2}},\frac{x_3}{\sqrt{1+x_2^2+x_3^2}}\right)$.  i.e. $(Y_2, Y_3) = g(X_2, X_3)$.  After computing the Jacobian of $g$ we see that is never $0$, hence the function is injective.  Now we can apply the change of random variables formula.


Routing to different networks but same IPs and subnet

Question: My issue is like this:
From our network, we have to connect to different client networks and their internal LAN is not defined by us. Every client is connected through separate IPSEC GRE tunnel on CISCO devices. now consider below scenario:
Client A having an internal IP address scheme of 192.168.1.0/24 and Client B also having the same. I have to route the packets from our Linux server --> our internal F/W --> our Router --> Respective Tunnels. (Suppose, both Clients having machines with same IP address 192.168.1.100)
Now, How can I route the packets from my internal LAN to respective clients? is there any changes I have to make in My network?
(Hope the question is clear to you, I'm not a hard core network engineer :))
Comment: An ipv4 solution is described here, but it requires basic networking knowledge: http://serverfault.com/questions/548888/connecting-to-a-remote-server-through-openvpn-when-local-network-subnet-conflict/557030#557030
Answer: Approaches to consider:

If you are routing to specific systems on their network, then you can route individual hosts, or subnets such as 192.0.2.55, 192.0.2.0/26. 188.8.131.52/28.  This will break if you need to route to the same address on both networks.   Setting this up over geographically spread networks requires configuring routing on multiple routers.
For incoming connections you can use SNAT from there systems to your.  You will need NAT each client separately.
Outgoing connections you can use a different subnet for one or both clients and use DNAT to correct the addresses.  If you need DNS, you will need to create a local zone using the local addresses for the clients servers.
If only certain protocols need to be handled, you may be able to use proxy the connections

When connecting to clients networks, you should firewall their networks.  At a minimum you will need to ensure their networks don't interconnect.  This applies even if their addresses don't overlap.  Routing rules will need to be across your network.
IPv6 addressing avoids this problem.  Each device which can connect off of the LAN will have a unique Internet address.  IPv6 private network addresses have been deprecated.  NAT is not required except to connect to IPv4 addresses.  Routing is much simpler.
Answer: Well, start learning basics of networking and realize it can not be done.
YOu can not route to IP on the same subnet. This is like saying you want to use the same phone number like your neighbot but people should be calling only you. MAKES NO SENSE.
If you address machine 192.168.1.55 - how is the router supposed to magically know which if your clients you want to talk to? EPIC FAIL.
So, whoever decided on 192.168.1.0 on BOTH sides - everyone had no clue how networking works and should have asked a professional.
THAT SAID: I have a similar situation and my solution was to IGNORE the IP(4) addresses and add a coordinated IPv6 network on top on both sides. Result is that the machines are addressable.
Comment: Thank you @TomTom, for your reply. This is actually a fictious question. But we have to anticipate for it. Well, I understand routing to same IP/same subnet cannot be done. The issue here is that we have no role in defining their networks and both of them  are geographically distant. Now considering this, how we can re-configure/re-design our network without very less disturbance to the client networks? Can you please elaborate me about "coordinated IPv6 network"?


How should I throw an exception if Some(null) is called?

Question: I've done Some(Option(null).get) but it looks a little strange.

Updated with sample. I can't compile check that the text is not null.
object Code {
  def main(args: Array[String]): Unit = {
    println(computeSomething("good"))
    println(computeSomething(null))
    def computeSomething(text: String): Option[String] =
      Some(Option(text).get).map("not null text was [" + _ + "]")
  }
}
//System.out:
//
//Some(not null text was [good])
//Exception in thread "main" java.util.NoSuchElementException: None.get
//  at scala.None$.get(Option.scala:347)
//  at scala.None$.get(Option.scala:345)
//  at Code$.computeSomething$1(ZipInputLocation.scala:13)
//  at Code$.main(ZipInputLocation.scala:11)
//  at Code.main(ZipInputLocation.scala)

Updated with a second sample.
object Code {
  def main(args: Array[String]): Unit = {
    println(computeSomething("good"))
    println(computeSomething(null))
    def computeSomething(text: String): String = {
      require text != null
      //or
      //if(text == null)
      //  throw new RuntimeException("You broke the contract")
      "not null text was [" + text + "]"
    }
  }
}
//System.out:
//
//not null text was [good]
//Exception in thread "main" RuntimeException:
//  at Code$.computeSomething$1(ZipInputLocation.scala:13)
//  at Code$.main(ZipInputLocation.scala:11)
//  at Code.main(ZipInputLocation.scala)

Comment: Using `.get` is unsafe/discouraged, using `Some(..)` with a not-pure value also.
Comment: Can you post an example ?
Comment: What is it you are trying to do? Do you want to throw an exception if `null` is passed? Are you looking for how to deal with `null` idiomatically in _Scala_? In _Scala_ programs, you should never use `null`, nor should you throw exceptions (which violates _referential transparency_). If you have to interact with _Java_ programs that might pass `null` to your code, it's better to wrap such values in `Option` - as per my answer below - since that's a better way of dealing with an undefined value (which is typically the meaning of `null` in _Java_). But please clarify your intention...
Comment: BTW, your second example doesn't even mention `Some(null)`, so how does it relate to your original question?
Comment: It happened that my code needed an Option. In case this adds one unnecessary layer of confusion to the question I removed it.
Answer: Don't use Option.get. Instead, use the Option.apply and map on that, since it will return None for null values:
def computeSomething(text: String): Option[String] =
  Option(text).map("not null text was [" + _ + "]")

Even better, if you want to disallow someone to compile code explicitly passing Some(null) at compile time, use a tool like WartMover, which has a specific rule for it that generates a compile time warning.
Comment: The OP wants to throw exception on `null`. I agree this is probably a bad design, but your answer does not address this and the code just behaves differently.
Comment: @Suma The fact that OP wants to throw doesn't mean I think it's the right choice, and doesn't force me to directly address it in my answer. If he doesn't like my choice of an answer he's free to choose not to accept it.
Comment: In my case receiving null as a parameter to computeSomething is a bug at the caller site. I was thinking that such cases are best handled by throwing an exception.
Answer: If I understand you correctly, you want Some(null) to throw an exception, instead of storing null as a value, correct?
Unfortunately, that's not going to happen. The only option you have is to put the creation of the Some instance inside a function and check for null explicitly. For example:

def wrapSome(s: String): Some[String] = {
  if(s eq null) throw new NullPointerException("Can't have null string!")
  Some(s)
}

Probably not what you wanted to hear, and not particularly useful either...
Alternatively, you could wrap the value in an Option (resulting in None, if the value is null), instead of in Some (which results in Some(null) if the value is null), and then call .get: None.get throws a NoSuchElementException. Indeed, this is exactly what you're doing in your example. (Is there a reason why you want to wrap the value explicitly with Some when that will happen automatically to non-null values wrapped in Option?)
One of the primary objectives of Option is to protect against null values.  Clearly, it would depend upon what you're trying to achieve, but functional programing discourages both null values and throwing of exceptions. If you're coming from Java, this can seem very strange, at first.
A more functional approach would be something like this:
// Return None if s is null; otherwise, Some(s). Both are Option[String] values.
def computeSomething(s: String): Option[String] = Option(s)

// Use this function to create an optional string.
val os = computeSomething(x) // x is some string. Could be null.

// Provide a default value if wrapped value is null (i.e. if os is None).
val a = os.getOrElse("some default value") // a is a string, never null.

// Do something with the value if it's not null; do nothing otherwise.
os.foreach(doSomething) // Calls doSomething(x), but only if x wasn't null/os isn't None.

// Process the string to something else. If os is None, result is None too.
val len = os.map(_.length) // Returns an Option[Int], None or Some(length of x)

// etc.

There's a whole host of idioms for using Option values like this, none of which involve throwing exceptions. If you could tell us more about what you're trying to do, I'll show you the Scala/functional way of doing it.
In the meantime, here's a reworked version of your program using this idiom with the fold method:
object Code
extends App { // No need for main function! ;-)

  println(computeSomething("good"))
  println(computeSomething(null))

  def computeSomething(text: String): String =
  Option(text).fold("text was null")(t => s"not null text was [$t]")
}

// System.out:
// not null text was [good]
// text was null


swift 4 - Parsing json to struct (codable), but with an extra variable which is not from json

Question: I am currently getting all the data I want from my json, but I want to add extra variable which is not from the json.
struct LoanUser: Codable {
let name: String
let use: String
let location: Location
let loan_amount: Int
let image: Image
var favorite: Bool = false

}
The     var favorite: bool = false is not a json string. This is the extra variable I want added
Answer: You have to specify coding keys by yourself and do not include favorite
struct LoanUser: Codable {
    let name: String
    let use: String
    let location: Location
    let loan_amount: Int
    let image: Image
    var favorite: Bool = false

    enum CodingKeys: String, CodingKey {
        case name, use, location, loan_amount, image
    }
}


What is the reference for the General Chernoff inequality in Wikipedia?

Question: Where is the reference mentioned in the Wikipedia article for the General Chernoff inequality? I cannot find it.
Comment: I don't understand - I don't see anything referenced, except for a link to the Chernoff Bound. Are you looking for a reference for Chernoff?
Comment: I'm looking for a reference to the form of general Chernoff inequality in my link, which I'm using. Somehow none of other references of Chernoff I find gives the same form.
Comment: Did you see this previous post here?: http://math.stackexchange.com/q/20550/9003
Answer: If you mean that there is no direct link to a reference in the section of the entry you linked, you're correct.  There are no links to any relevant references provided that support or pertain to that section, in that particular entry.
However, there is a link, in the given entry, to another Wikipedia entry: the Chernoff Bound (a separate entry), where the Chernoff inequality/bound is discussed and developed in greater detail, and many references are provided in this entry (one reference is even a paper authored by Chernoff).
Indeed, when I used the expression "Chernoff Inequality" in the search field of Wikipedia, it took me directly to the entry whose link I've provided.
Added: If you're looking for a particular form of the inequality, try googling "Chernoff's Inequality"...when I did so, I came up with a lot of "hits": lecture notes, discussions, etc., which may provide you with more information and/or references. P.S. Is this the form of the inequality in which you're interested in? It's from your linked entry.
       ?
That formulation can be found in this document: p. 27, Section 2.2 pdf,
and perhaps these lecture notes, too, are helpful.
If you are referring to a different formulation, please include that in your question. I guess I'm not clear as to the inequality (that is, the specific form, or variation) you're using. Perhaps adding to your question some context as to what it is you need it for/and why in this form only, its significance to your work etc?
Do keep us posted if you have any further clarification of your question, and/or if you find what you are looking for!  Good luck.
Comment: But Chernoff bound there takes a different form from the general Chernoff inequality mentioned in my link, which is what I'm using and trying to find reference to.


how compile kernel and disable root access?

Question: is it possible to restrict system to have only one root privilege access?
only user "lala" and "root" have root access ?
im looking for a solution to prevent hacker who hacked system to add new account on system
Comment: @Nimafire please don't edit a 6 year old question in a way that completely changes it, even if it is your own. It would be better to ask a new question instead.
Comment: You should look for solutions to prevent the hacking in the first place. If someone is already in, adding user accounts is least of your concerns.
Answer: You must restore a compromised system from a known good backup. Very rarely can you  be sure administrator level exploits are completely removed. See the canonical question on compromised servers.
Part of the prevention of compromise is through mandatory access controls such as SELinux. That restricts services to what they actually need.
And, develop intrusion detection. The addition of users can be detected through changed files detection, or log file analysis.

Edit: To answer your specific question, classic privilege management means any uid 0 is all powerful. This user does not have to be named 'root', and there could be multiple in /etc/passwd.
In practice, security controls means not granting the ability to run arbitrary commands as root. Maybe adding more robust mandatory access control like SELinux. Plus auditing what happens to find any suspicious activity. Read  comprehensive hardening documentation such as the RHEL security guide.
Comment: mmm im thinking to set restrict with kernel to prevent any extra root privilege/
Comment: Like I said, mandatory access controls. Look at the policy in a distribution that ships with SELinux. Actually, read hardening manuals in general to have a better concept of multiple layers of defense.
Comment: ive to disable selinux coz of some reason. i hope someone working on kernel and know the solution, i think its possible to restrict root privilege from kernel
Comment: You do not need a Linux security module to restrict root effectively. Run your services as not root. Do not allow root login. Audit privilege escalation like sudo. Audit user creation. If you can run SELinux, that provides a "sandbox" that greatly isolates what a given context can do.
Comment: mm this is for new system not hacked server, before attach server to internet im looking for kernel solution for block add root user
Comment: As I said, SELinux. Really, start with the basics and read hardening guides like the RHEL one I linked in my edit.
Comment: Wow, a year and a half has passed and that server still isn't finished?
Comment: i cant find any clear document about this on selinux. can you update me how?
Comment: Clear documentation about *what*? It's not a five minute fix that you configure; it's a process. And selinux is *complex*, as is any MAC system.