Access a local variable from the template in the controller in Angular2

Question: I am writing a component where I need access to the <audio controls> native element. I am doing it like this now by getting it in ngOnInit() by using ElementRef like this this.elementRef.nativeElement.querySelector("audio");
While it works I think it is very unelegant and Angular2 also warns of the risks when using ElementRef..
Is there really no simpler way?
Can I mark it as a local variable with <audio controls #player> and somehow access the native element through this.player or something similar from the controller?
import {Component, OnInit, ElementRef, Input} from 'angular2/core';

@Component({
    selector: 'audio-preview',
    template: `
        <audio controls>
            <source [src]="src" type="audio/mpeg">
            Your browser does not support the audio element.
        </audio>
    `
})

export class AudioPreview implements OnInit {

    @Input() src: string;

    constructor(public elementRef: ElementRef) {}

    ngOnInit() {
        var audioElement = this.getAudioElement();
        audioElement.setAttribute('src', this.src);
    }

    getAudioElement() : HTMLAudioElement {
        return this.elementRef.nativeElement.querySelector("audio");
    }
}

Answer:
Use @ViewChild to access some element in the view.
Use [attr.src] to creating binding to 'src' attribute of an element.
Use Renderer if for some reason you need to change the DOM imperatively.

See this plunk.
import {Component, Input, ViewChild, Renderer} from 'angular2/core';

@Component({
  selector: 'audio-preview',
  template: `
    <audio controls #player [attr.src]="src">
      <source [src]="src" type="audio/mpeg">
      Your browser does not support the audio element.
    </audio>
    `
})
export class AudioPreview {
  @Input() src: string;
  @ViewChild('player') player;

  constructor(public renderer: Renderer) {}

  ngAfterViewInit() {
    console.log(this.player);

    // Another way to set attribute value to element
    // this.renderer.setElementAttribute(this.player, 'src', this.src);
  }
}

Comment: @skovmand [attr.src] create binding to the attribute of an element, using [`setAttribute()`](https://developer.mozilla.org/en/docs/Web/API/Element/setAttribute) method of DOM (`element.setAttribute('src', src)`). `[src]` creates binding to  the property of an element (just set it by `element.src = src`)
Comment: I found it... eventually.  The [source code for ViewChild](https://github.com/angular/angular/blob/2.0.0-beta.0/modules/angular2/src/core/metadata.ts#L1147-L1147) says "Supports the same querying parameters as QueryMetadata, except `descendants`."  The [QueryMetadata API doc](https://angular.io/docs/ts/latest/api/core/QueryMetadata-class.html) explains the different selectors supported.
Comment: @MarkRajcok Actually I don't read some "secret" special books or articles about angular2. Almost all things about angular2 I've learnt from the source codes and their tests. For example [here](https://github.com/angular/angular/blob/9e44dd85ada181b11be869841da2c157b095ee07/modules/angular2/test/core/linker/query_integration_spec.ts#L341) are the tests for `@Query('something')`.
Comment: Thanks!! I just tried it, and `````` seems to work the same as `````` ... What's the difference?
Comment: I have to ask... where did you learn about using `#player` in the template, and then being able to get a reference to it using `ViewChild('player')`?  (I need to start reading whatever you're reading, because I can't find this kind of info in the Angular docs.  The [ViewChild API page](https://angular.io/docs/ts/latest/api/core/ViewChild-var.html) doesn't explain this.)


How to prove $\min(\delta a_k)\le\delta S\le \max(\delta a_k)$?

Question: We have sum of exact numbers: $$S=a_1+a_2+a_3+\cdots+a_n$$
And sum of their corresponding approximate numbers:
$$S_0=a_{0_1}+a_{0_2}+a_{0_3}+\cdots +a_{0_n}$$
Our lecturer wrote the following inequality without any proof: $$\min(\delta a_k)\le\delta S\le \max(\delta a_k)$$
Where $\delta_{a_k}$ is relative error of $a_k$.
I am very curious to know why this inequality works.
I know $\delta S=\cfrac{\Delta a_1}{|S|}+\cfrac{\Delta a_2}{|S|}+\cfrac{\Delta a_3}{|S|}+\cdots+\cfrac{\Delta a_n}{|S|}\quad\quad,\quad \delta a_k=\cfrac{\Delta a_k}{|a_k|}$ If I'm not mistaking
Therefor :
$$\min(\cfrac{\Delta a_k}{|a_k|})\le\ \cfrac{\Delta a_1}{|S|}+\cfrac{\Delta a_2}{|S|}+\cfrac{\Delta a_3}{|S|}+\cdots+\cfrac{\Delta a_n}{|S|}\le \max(\cfrac{\Delta a_k}{|a_k|})$$
But no idea comes to my mind how to prove this inequality works.
Answer: For simplicity, denote $m=\min \left(\frac{\Delta a_k}{|a_k|}\right)$ and $M=\max \left(\frac{\Delta a_k}{|a_k|}\right).$
Then for each $k$ $$m \cdot|a_k|\le \frac{\Delta a_k}{|a_k|}|a_k|\le M\cdot {|a_k|} \tag 1$$
Rewrite
$$\ \cfrac{\Delta a_1}{|S|}+\cfrac{\Delta a_2}{|S|}+\cfrac{\Delta a_3}{|S|}+\cdots+\cfrac{\Delta a_n}{|S|}=\color{blue}{\frac{1}{|S|}\left(\frac{\Delta a_1}{|a_1|}|a_1|+\dots +\frac{\Delta a_n}{|a_n|}|a_n|\right)}.$$
With the use of $(1)$ we get
$$\frac{1}{|S|}\left(m|a_1|+\dots + m|a_n|\right)\le \color{blue}{\frac{1}{|S|}\left(\frac{\Delta a_1}{|a_1|}|a_1|+\dots +\frac{\Delta a_n}{|a_n|}|a_n|\right)}\le \frac{1}{|S|}\left(M|a_1|+\dots + M|a_n|\right)$$
Left inequality (that you want to prove) is true as $|S|\le|a_1|+\dots + |a_n|,$ the right one holds provided $a_k$ have equal signs.
Comment: @soheil The blue part in the last inequality is equal to $\delta S$ as shown by the equation above, and if $a_1,\ldots,a_n\geq 0$, then $|S| = |a_1|+\ldots+|a_n|$.
Comment: I don't understand last why last inequality works. and how it prove $\min(\delta a_k)\le\delta S\le \max(\delta a_k)$ ?
Comment: @soheil Looks like the last inequality is a direct consequence of $(1)$.
Comment: @Surb I got it. but I don't understand how we prove $\min(\delta a_k)\le\delta S\le \max(\delta a_k)$ from last inequality
Comment: Got it. Thank you !


How is mlb.com's ">.500" record calculated?

Question: On Major League Baseball's Standings page, one of the fields is headed <code>>.500</code>: "Record against >.500 teams".
Is this the record in games against teams whose record was above .500 when the game was played, or games against teams whose record is above .500 now?
Answer: Current record, not at the time of the game.
For example, the White Sox are "6-9" against .500 teams; that includes 4-4 against CLE, 2-2 against BOS, and 0-3 against NYY.  However, the KC Royals were over .500 for several of their games, the Mariners even were over .500 for the first game they played, etc.; while CLE, BOS, and NYY were all over .500 for all of the games they played against the White Sox.


Why should an outer measure give 0 on an empty set?

Question: A standard definition of outer measure on a set $X$ is a function
$$\rho:2^X\to[0,\infty]$$
satisfying the following properties:

$\rho(\varnothing)=0$
$A\subseteq B\implies\rho(A)\leq\rho(B)$
$\rho(\cup_{n=1}^\infty A_n)\leq\sum_{n=1}^\infty\rho(A_n)$

A subset $E\subseteq X$ is then said to be $\rho$-measurable if
$$\rho(A)=\rho(A\cap E)+\rho(A\cap E^c)$$
for all $A\subseteq X$.
My question is: Why is the first condition necessary? As far as I can see, none of  the important properties of outer measure and measurable set seems to require this condition.
Comment: Not my area of expertise, but unless I am mistaken, $\rho(\emptyset)>0$ would imply that there are no measurable sets at all (choose $A=E$ in the definition).
Comment: If $\rho(\emptyset) >0$ then, for any measurable set, we would have $$\rho(\emptyset)=\rho(A\cap \emptyset)+\rho(A\cap \emptyset^c)= \rho(\emptyset) +  \rho(A) \tag{1}$$ Since , $\emptyset \subseteq A$, we have $0 < \rho(\emptyset) \leq \rho(A)$. So, the only way to satisfy $(1)$ is having $$\rho(\emptyset)= \infty$$ and so, for all $A\subseteq X$, $$\rho(A) = \infty$$ In this case, all sets will be measurable. Such $\rho$ is OK, but not very useful.
Comment: If $\rho(\emptyset) > 0$, then there will be no measurable set, **unless** $\rho$ is identically $+\infty$ (in this case, all sets will be measurable).
Answer: Unless I am mistaken, for any measurable non empty set we would have
$\rho(A) = \rho(A \bigcap \emptyset) + \rho(A \bigcap X) = \rho(\emptyset) + \rho(A)$, so $\rho(\emptyset)$ must be $0$ if a measurable set $A$ exists
Comment: If $\rho(\emptyset) > 0$, then there will be no measurable set, **unless** $\rho$ is identically $+\infty$ (in this case, all sets will be measurable).


Is it possible not to use utf8mb4 as encoding?

Question: Due to an old version of libmysqlclient, we are stuck and can't deploy a completed site to our server.  The client does not support utf8mb4.  We have the datacenter who manages the server looking into the issue, but is there a way to make Drupal use the regular utf8 character set without hacking core?
Answer: MySQL (and libmysqlclient) have a minimum version requirement of 5.5.3 for Drupal 8 (see https://www.drupal.org/node/2558615, https://www.drupal.org/node/2473301, etc).
It's not often that requirements are applied arbitrarily, so there will almost certainly be something in MySQL >=5.5.3 that core/vendor code requires.
As such, I would have to assume that no, it's not possible to change this without hacking core. Maybe not even with hacking core, as vendor supplied code may rely on it.
Comment: Thanks.  In this case we were able to switch from libmysqlclient to mysqlnd for the driver.  MySQL was up to date and did support the UTF8mb4 charset, but the driver did not.  I did check, and it is possible to remove the core checks in the installer, but I figure that's an awful large gamble to take.


Java, pass-by-value, reference variables

Question: I have a problem with understanding the "pass-by-value" action of Java in the following example:
public class Numbers {

    static int[] s_ccc = {7};
    static int[] t_ccc = {7};

    public static void calculate(int[] b, int[] c) {

        System.out.println("s_ccc[0] = " + s_ccc[0]); // 7
        System.out.println("t_ccc[0] = " + t_ccc[0]); // 7

        b[0] = b[0] + 9;
        System.out.println("\nb[0] = " + b[0]); // 16

        c = b;
        System.out.println("c[0] = " + c[0] + "\n"); // 16
    }

    public static void main(String[] args) {

        calculate(s_ccc, t_ccc);

        System.out.println("s_ccc[0] = " + s_ccc[0]);  // 16
        System.out.println("t_ccc[0] = " + t_ccc[0]);  // 7
    }
}

I know that because s_ccc is a reference variable, when I give it to the method calculate() and I make some changes to its elements in the method, the changes remain even after I leave the method. I think that the same should be with t_ccc. It is again
a reference variable, I give it to the method calculate(), and in the method I change the referece to t_ccc to be that of s_ccc. Now t_ccc should be a reference variable pointing to an array, which has one element of type int equals to 16.  But when the method calculate() is left, it seems that t_ccc points its old object. Why is this happening? Shouldn't the change remain for it, too? It is a reference variable after all.
Regards
Comment: Did you mean calculate(s_ccc, t_ccc) instead of calculate(s_ccc, s_ccc) ?
Comment: Yes, exactly! I do mean calculate(s_ccc, t_ccc). I am sorry.
Comment: @gemm: Could you amend your post please?
Answer: There's an extended discussion of how Java passes variables at an earlier question "Is Java pass by reference?". Java really passes object references by value.
In your code, the references for the arrays (which are objects) are passed into calculate(). These references are passed by value, which means that any changes to the values of b and c are visible only within the method (they are really just a copy of s_ccc and t_ccc). That's why t_ccc in main() was never affected.
To reinforce this concept, some programmers declare the method parameters as final variables:
public static void calculate(final int[] b, final int[] c)

Now, the compiler won't even allow you to change the values of b or c. Of course, the downside of this is that you can no longer manipulate them conveniently within your method.
Answer: Here's a simple way to understand it.
Java always passes copies of arguments. If the argument is a primitive type (e.g. an integer), then the called method gets a copy of the primitive value. If the argument is a reference type, then the called method gets a copy of the reference (not a copy of the thing referred to).
When your main method begins, each of s_ccc and t_ccc refers to a distinct array.
This is the situation, where parentheses indicate variables and square brackets indicate the actual array structures:
(s_ccc) ---> [7]
(t_ccc) ---> [7]

Assuming that you meant calculate(s_ccc, t_ccc), then at the beginning of the calculate method:
(s_ccc) ---> [7]  <---(b)
(t_ccc) ---> [7]  <---(c)

Locals b and c are copies of globals s_ccc and t_ccc respectively.
Still within calculcate, after b[0] = b[0] + 9 has completed:
(s_ccc) ---> [16] <---(b)
(t_ccc) ---> [7]  <---(c)

The zero (only) position in the array referred to by b has been modified.
The assignment c = b within calculate produces this situation:
(s_ccc) ---> [16] <---(b)
               ^------(c)
(t_ccc) ---> [7]

The local reference variable c, now contains the same reference as b. That has no effect on the global reference variable t_ccc, which still refers to the same array as before.
When calculate exits, its local variables (on the right-hand side of the diagrams) disappear. The global variables (on the left-hand side) were not used in calculate, so they are unaffected. The final situation is:
(s_ccc) ---> [16]
(t_ccc) ---> [7]

Neither c_ccc nor t_ccc were changed; each still refers to the same array as before calculate. Calling calculate changed the content of the array referenced by s_ccc, using a copied reference to that array (in b).
Local variable c started as a copy of t_ccc and was manipulated within calculate, but that changed neither t_ccc itself nor it's referenced data.
Answer: The method receives variables by value. Those values can't be changed (as far as the caller of the method sees), but the values contained within them can (if it's an object, or as in this case, an array).
So when you change the value b[0] inside the array, the change can be seen outside the method. However the line
c = b;

will change the value of c inside the method, but that change will not be seen outside the method, since the value of c was passed by value.
Answer: The line calculate(s_ccc, s_ccc); indicates you're not actually doing anything to t_ccc.
However, should this line have read calculate(s_ccc, t_ccc); than the effect remains the same.
This is due to the fact that you're assigning a new value to c here: c = b;
When assigning a new value to a reference argument the reference is lost.
This is the difference between altering a by reference variable and assigning a new value.
Answer: On entry to calculate(), b points at s_ccc and c points at t_ccc.  Altering b[0] will therefore change s_ccc, as you've seen.
However, the assignment
c = b;

only points c at the same object b is pointing at, namely s_ccc. It does not copy the contents of what b points to to what c points to.  As a result, t_ccc is unchanged.  If you added the following line to the end of calculate():
c[0] = c[0] + 5;

s_ccc[0] would be 21.


Batch para localizar uma subpasta, mover todos os arquivos para um nível acima e deletar a pasta

Question: Tenho esta estrutura:
<code>    ..
    ..\FolderA\FolderX\File1.txt
    ..\FolderB\FolderX\File2.txt
    ..\FolderC\FolderD\FolderE\FolderX\File3.txt
</code>
Eu preciso de um batch que localize todas as pastas "FolderX" nos subdiretórios e mova todos os arquivos para um nível acima e delete a pasta "FolderX"
<code>    ..
    ..\FolderA\File1.txt
    ..\FolderB\File2.txt
    ..\FolderC\FolderD\FolderE\File3.txt
</code>
Como programar o batch? Eu tentei este código, mas está incompleto, pois não localiza as pastas.
<code>    @Echo Off
    Set _Source=%~dp0
    Set _FindDir=FolderX
    Set _Path=%_Source%\%_FindDir%
    If Exist "%_Path%" (
    Move /-Y "%_Path%\*.*" "%_Source%"
    For /F "Tokens=* Delims=" %%I In ('Dir /AD /B "%_Path%"') Do Move "%_Path%\%%I" "%_Source%"
    RD /S /Q "%_Path%"
    )
</code>
Answer: Resolvido com o seguinte código:
<code>    @echo off & setlocal enabledelayedexpansion
    for /d /r %~dp0 %%a in (*) do (
    if /i "%%~nxa"=="FolderX" (
    set "folderpath=%%a" (
    move /y !folderpath!\* !folderpath:~,-8!
    rmdir !folderpath!
    )
    )
    )
</code>


Bootstrap 4 image grid alignment

Question: So I am creating an image grid using bootstrap 4.All the grid is included in the class "showcase".There are 2 landscape photos on the first row, and 3 portrait photos in the 2nd row.The problem is, I want the portrait photos to be aligned with the landscape photos.1 to the left, 1 in the center, and 1 to the right.I want them to have the same margin so it looks nice.
I tried googling and setting margins on my own.I tried using "row-sm-4" and stuff like that.

It should show all the photos by the same left and right margins.
Answer: If I fully understand what you mean then I think what you need to do is put the images into the correct amount of columns. For example:
Your 2 landscape images need to go into two columns with a span of 6.
Your 4 portrait images need to into 3 columns with a span of 4.
This should look something like this:

Let me know how it goes! You also won't need the floats
Comment: You understood correctly.The thing is that for the right hand side, it worked.But the distance from the center photo to the left photo is bigger than the distance from the center photo to the right photo, which makes it so it doesnt fix for the left hand side.
Comment: In that case add text-center to the div that you want to center. That should fix it for you!
Comment: wow it worked.At first, it didn't do anything because I didn't use the col-4 layout.I used css for it.Then I copied your code, which made it how I said above.When I said text-align center, it didnt do anything, but I just had to remove the css.Thank you! Tried to fix this for hours.
Comment: Glad I could help!

Bootstrap 4 image grid alignment


How to display iPhone free memory ? and how to free iPhone memory?

Question: How to display iPhone free memory in a UILabel ?
and I would like to ask, how to free up memory using iPhone SDK?
FYI, I'm using iPhone SDK 3.1.2 with xcode 3.2.1 (Mac OS X Snow Leopard).
Answer: There is no direct access to this information in the SDK, and apps are not allowed to mess around with the OS the way you're suggesting. You're in your own little box; Apple expects you to stay there. When you ask questions that include "the system," you are probably outside of your box.
That said, there are some tricks you can use. You can allocate increasingly-large blocks of memory until you receive -didReceiveMemoryWarning. At that point, release your allocated memory. That will give you a rough idea of how much memory the OS will allow you to have. That's not the same as how much the OS has of course. Tripping -didReceiveMemoryWarning will also cause the OS to do some housekeeping of its own, so this is pretty much the most effective programmatic way you have to free up memory.
The most effective non-programmatic way to free up memory is to ask the user to reboot. For applications that require substantial memory (generally games), this approach is not unheard of.
SBSettings requires jailbreaking and is outside of the SDK.
Comment: It is not documented and is difficult to determine because the OS's own use of memory is always fluctuating. It is completely possible for you to receive a memory warning, do nothing, and everything be fine because the OS freed memory on its own. Due to memory fragmentation, it's also possible to allocate more memory using small blocks than large ones, so the issues can be complicated.
Comment: Thank you for your answer. I would like to ask a bit further, at which level, iPhone will see the memory is low? say 10% memory remaining?
Answer: It is possible to determine the amount of free memory on an iPhone using the mach api.  See this related question: Available memory for iPhone OS app
Answer: You can free up memory by calling "release" on objects you've allocated after you're done with them.  See http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/MemoryMgmt/MemoryMgmt.html
Comment: Is there any way to free up the memory of whole iPhone system, instead of a class itself? I notice that an app called SBSettings can do the job, but I don't know how they achieve it.


How to solve using random variables

Question: Eighteen balls are placed at random in seven boxes that are labeled $B_1 , . . . , B_7$ .
Find the probability that boxes with labels $B_1 , B_2$ and $B_3$ all together contain six
balls.
I solved the problem using generation functions.
A: no of cases 6 balls can be placed in 3 boxes.

coefficient of $x^6$ in
  $(1+x+x^2+\dots)(1+x+x^2+\dots)(1+x+x^2+\dots)$
coefficient of $x^6$ in $(1-x)^{-3}$ equals to $\binom{8}{6}$ = 28

B: no of cases 12 balls can be placed in 4 boxes.

same way we can get $N(B)=\binom{15}{3}=420$

C: no of cases 18 balls can be placed in 7 boxes.

we can get $\binom{24}{18}$

final answer of question will be$\frac{N(A)N(B)}{N(C)}$
I want do same problem using random variables but I am not getting how to solve using random variables.
Answer: We need to make a probability model of the situation. Assume that balls are placed one at a time, with all boxes equally likely, and that the placements are independent.
Call a placement of a  particular ball a success if the ball ends up in $B_1$, $B_2$, or $B_3$. The probability of success is $\dfrac{3}{7}$.
We want the probability of exactly $6$ successes in $18$ trials. This is a straight binomial distribution problem. The required probability is
$$\binom{18}{6}\left(\frac{3}{7}\right)^6 \left(\frac{4}{7}\right)^{12}.$$
Remark: We get a different answer if we assume instead that all $7$-tuples $(x_1,\dots,x_7)$ such that $x_1+\cdots+x_7=18$ are equally likely. But that assumption, unless explicitly specified in the problem, is not a reasonable one.
Comment: answers are different because you assumed balls to be same and I have assumed balls are different???
Comment: The balls are different, each has an identity label. It makes no difference. The assumptions about how the balls are placed in the boxes are given at the beginning of the answer. If that is also the model you have in mind, then no answer numerically different from the binomial one is correct.
Comment: I am confused What are the differences in answers ??(using generating function I have assumed that balls are Identical)
Comment: You have assumed that the $\binom{24}{18}$ ways of placing balls in boxes are equally likely. For the model I described, that is false. Everybody in Box 1 is much less likely than a more even distribution.
Comment: In  model I described, balls are Identical and boxes are different. In model you described, balls are different and boxes are also different.Is it correct ???
Comment: Identical or different balls is not relevant. What matters is the process of placing balls in boxes. To make an analogy, boxes are labelled Boy, Girl. Balls are births. You are in essence assuming that $(2,0)$, $(1,1)$, and $(0,2)$ are equally likely. They are not.
Comment: Maybe this will help, maybe not. Suppose the balls are indistinguishable. Before you start tossing the balls into boxes, I put ID numbers on them in secret ink. Will this change the probability that exactly $6$ balls end up in $B_1,B_2,B_3$ combined?
Comment: let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/8120/discussion-between-stranger001-and-andre-nicolas)
Comment: Why (2,0) , (1,1) and (0,2) are not equally likely??because of order B,G and G,B..
Comment: Sorry, I avoid chat, had negative experiences. The posted answer is correct. There is no other reasonable interpretation of the wording. And yes, the probability of one of each, under the usual assumptions, is $1/2$, not $1/3$.

How to solve using random variables


XP Clients to Sync with Server 2008 Domain

Question: I have around 200 XP users and one DC and one ADC.
I want to sync xp machine with DC or ADC. On DC i have given NTP server source(it is a unix server)
Currently in XP registry the NTP source is times.windows.com which i want to be my DC IP
Please tell what are the steps on server side and clients.
Comment: What exactly is an ADC and how is it different than a DC?
Comment: You still haven't answered my question. What exactly is an ADC and how is it different than a DC?
Comment: Are your XP clients joined to the domain? If so they should already be synchronising with the PDC emulator of your domain. What's the output of `w32tm /query /configuration` on one of your XP clients?
Comment: @ChrisMcKeown Not exactly true. All other DCs sync time from the DC holding the PDC Emulator role. All member servers and client computers sync from the DC that is their logon server.
Comment: @MDMarra absolutely correct, my bad!
Comment: the command /query is unknown
Comment: DC stands Domain Controller and ADC Additional Domain Controller. Normally ADC is created as a backup if DC fail's
Comment: That's not correct. There's no such thing as a backup DC or ADC. They're all multi master peers.
Answer: Unless you've changed it, the default behavior is for domain-joined computers to sync time from the DC that they used as a logon server. You don't have to configure anything special for this to happen.
Your DCs will sync time from the DC holding the PDC Emulator role. If you want your DCs to sync from an external time source, you should only modify the DC that holds this role. The other DCs will automatically sync from it.
Comment: NTP uses port 123. Make sure that is open through your firewall. Also, is it really that hard to type out words like `waiting` and `event viewer`? This is a site for professionals, not a text message.
Comment: i just started one machine and i looked at eventvwr and it was successfully sync'g with my DC but at another machine which i rebooted was not showing any w32 msg......and one more thing in eventvwr w32 msg show that it will try for NTP server after 15 mintues but that was not true...m still w8ing but its is not sync'g and no msg also in eventvwr...   There is a firwall so how do i check there is no issue from firewall
Comment: sorry for text message...the machine which is getting syncing with DC on that i tried to telnet that port but it didn't work..


Modifying Piano & Guitar Techniques For Arthritis

Question: I'm almost 40, and I've played the piano for 35 years. I still play almost daily. I've been playing the guitar off and on for about 30 years, although at a lower level of proficiency than the piano.
I started getting arthritis in my hands about 8 years ago, which has resulted in my thumb rotating inward, and ulnar deviation at the wrist, so that instead of my middle finger aligning with my forearm my thumb does. I've somewhat compensated for this at the piano, but I've lost thumb dexterity and often get cramps and pain in my forearms from the misalignment; the impact on my guitar-playing has been much worse, to the point that I almost can't play at all.
Has anyone else experiencing this had success with technique modifications or anything else to mitigate the problem?
Comment: What type of arthritis?  Osteoarthritis, rheumatoid arthritis, ...?  [I can only offer OA advice.]
Comment: @Theodore As far as I know, just OA.
Comment: Poss dupe - 'what are the limitations for a guitarist with arthritis in his hands?'
Comment: https://music.stackexchange.com/q/24505/16897
Comment: My arthritis is beginning to limit how long I can play guitar uninterrupted.  I am hoping to find some type of therapeutic solution to mitigate the pain and inflammation.
Answer: The arm really needs to be aligned behind each finger which requires constant adjustments while playing.  Do you play "quietly" from the flexors or from your shoulder and elbow?  Improper technique can exacerbate other disorders and I am a firm believer that proper technique can promote healing. I would suggest finding a Taubman teacher and never ever again play your old repertoire since its improper movement is already hardwired into your brain. In fact, none of us should play our early repertoire unless we take a bit of time to re-learn those works with our newer movement. That is what unravels our technique or gives us "bad days" because the old technique tries to resurface and the old strains we once got used to are no longer supported by muscles we don't need or use anymore. In your case, I wonder if an improper technique combined with the arthritis is causing the arthritic deformity. I would contact Edna Golandsky in NYC and see if she has a student/teacher in your area.  I know three of them and like anything else, some are better teachers, detectives and problem solvers than others. All want your money.  One of my teachers, Stanley Hummel, he had arthritis in his fingers and all of them were deformed at the phalanges but he overcompensated with his elbow and shoulder and you'd never know by listening to him that his fingers were all gnarled.  Good luck.


React forwardRef uncaught syntaxError

Question: I create react forwardref. but show one error. i use vite, typescript. here my code:
import * as React from 'react'

interface PageProps {
    number: number;
    children: React.ReactNode
}

const PageComponent = React.forwardRef<HTMLDivElement, PageProps>((props, ref) => {
    return (

Page header - {props.number}

{props.children}

{props.number + 1}

    );
});

export default PageComponent;

show this error:

PageComponent.tsx?t=1711471952502:17 Uncaught SyntaxError: Identifier
'React' has already been declared (at
PageComponent.tsx?t=1711471952502:17:92)
Answer: The error you're encountering suggests that there might be a conflict in how you're importing React. This issue can arise when you have multiple import statements for React in different files.
Here's how you can modify your code to avoid the conflict:
import { forwardRef, ReactNode } from 'react';

interface PageProps {
    number: number;
    children: ReactNode;
}

const PageComponent = forwardRef<HTMLDivElement, PageProps>((props, ref) => {
    return (

Page header - {props.number}

{props.children}

{props.number + 1}

    );
});

export default PageComponent;

In above suggestion,forwardRef and ReactNode are imported directly from the react package, and React is not imported since it's not explicitly used within the component. Kindly revert if this resolves the conflict you're encountering.

React forwardRef uncaught syntaxError


Is a GMM-HMM equivalent to a no-mixture HMM enriched with more states?

Question: I'm trying to model sequence data that has 5 hidden states. Observation data conditional to each state is gaussian except for one state for which mixture of 2 gaussians seems more appropriate. Unfortunately, the R package that I'm using (depmix) does not seem to support (without extending the package) a GMM as a possible response distribution. So I was considering the possibility of adding a 6th state so I could interpret one of this enriched set of states as a state for which observation distribution is the first gaussian in my above mixture and another one as a state for which observation distribution is the second gaussian.
Am I wrong thinking that the two approaches are equivalent?
Answer: It is not exactly equivalent: the 6-state HMM can model everything the GMM-HMM can, but not the other way around.
Suppose you start with the GMM-HMM, with $s_5$ being the GMM state, and turn it into the 6-state HMM with states $s_6$ and $s_7$ instead of $s_5$.
Let $p_6$ and $p_7$ be the prior probabilities of the two components of the GMM (that are then transformed into states $s_6$ and $s_7$).
For every transition from a state $s_i$ to $s_5$ in the GMM-HMM (with probability $t$), create two transition probabilities in the 6-state HMM:

$s_i$ to $s_6$ with probability $t \cdot p_6$
$s_i$ to $s_7$ with probability $t \cdot p_7$

For every transition from $s_5$ to a state $s_i$ in the GMM-HMM (with probability $t$), create two transition probabilities, respectively from $s_6$ and $s_7$, going to $s_i$, both with the same probability $t$.
If I am not mistaken, the resulting 6-state HMM is equivalent to the GMM-HMM.
However, the other way around doesn't always work. Imagine you are starting the the 6-state HMM.
Suppose that the transition probabilities for $s_i \rightarrow s_6$ and $s_i \rightarrow s_7$ are not equal do not have the same ratio as $s_j \rightarrow s_6$ and $s_j \rightarrow s_7$ (EDIT). You could not carry this information into the GMM-HMM.
In short, the 6-state HMM should be able to represent everything the GMM-HMM can, and more.
Comment: I'm not sure that last "suppose" is correct.  What if the mixture probabilities are, say, 0.3 and 0.7?  Wouldn't that imply that the transition probabilities into $s_6$ and $s_7$ weren't equal?
Comment: On the other hand, there is an implication of the GMM that $p_{i,6}/p_{i,7} = p_{j,6}/p_{j,7}$ for all $i,j$, well except the zero transition probabilities of course, which doesn't have to be enforced by the 6-state HMM model, so your fundamental point is correct.
Comment: @jbowman you are correct, I've changed it.
Comment: @VincentB.Lortie so should we conclude that in this case the mixture is better because it's a more parcimonious model?
Comment: First, I would look into how well both fit the data. If the GMM-HMM is really sufficient to model the data, then it should perform comparably to the 6-state HMM, or even better if the 6-state HMM overfits. Then, I suppose you could make a case that the GMM-HMM has fewer parameters than the HMM.
Comment: There's a chance the 6-state HMM will perform better, however, in which case it might be the better option.

Personally, and this is just a matter of taste, I like the 6-state HMM better. I find it less convoluted to add a state to a regular HMM with gaussian states than to turn one of the states into a GMM. Also, it is supported by more software packages.
Answer: No you are not wrong thinking that.
If $Y \mid X_1 \sim \alpha f_1(y) + (1-\alpha)f_2(y)$, then you can also let $X_2 \sim \text{Bernoulli}(\alpha)$ independently and say
$$
Y \mid X_1, X_2 = 1 \sim f_1(y)
$$
and
$$
Y \mid X_1, X_2 = 0 \sim f_2(y).
$$
This is because
$$
f_{Y|X_1}(y \mid x_1) =  \sum_{i=1}^2f_{Y|X_1,X_2}(y \mid x_1, x_2) f(x_2) = \alpha f_1(y) + (1-\alpha)f_2(y).
$$
Keep in mind the sequence through time $\{X_2^t\}_t$ is iid, and so the Markov structure is overkill (but still perfectly fine).
Comment: could you clarify what do you mean by "Markov structure is overkill"?
Comment: @Patrick I mean iid random sample data are less complicated to analyze than a Markov chain because each element does not rely on the chain's past.  If you wanted to think of $\{X_{2}^t\}$ as a two-state Markov chain, then its transition matrix would have columns with all the same elements.


Open next month if selectable date falls in the next month

Question: I have jQuery calendar. I have to make it so that only Monday or Tuesday etc are selectable depending on other variables. Now if today is 27 of April 2012 and the selectable days are Thursday with mindate set as 27th of April 2012 or the current date, The default month will still be April even if there are no selectable dates there.
How can I make it so that in those case the default month is the month which has selectable days in it.
I hope the figure will be helpful!
Answer: You could use a custom function to set the defaultDate/minDate.  Here I have an array that defines valid days of the week. If the current date is not one, it move forward until it finds one.  You could customize something like this for your particular use:
var validDays = [0, 1, 1, 0, 0, 1, 0];

function firstDate() {
    var valDate = new Date();
    valDate.setDate(valDate.getDate() + 14);
    var day = valDate.getDay();
    var i = 0;
    while (validDays[day] != 1 && i < 7) {
        valDate.setDate(valDate.getDate() + 1);
        day = valDate.getDay();
        i++;
    }
    return valDate;
}

function validDate(date) {
    if (validDays[date.getDay()] == 1) {
        return [true, ""];
    } else {
        return [false, ""]
    }
}

$(function() {
    $("#datepicker").datepicker({
        beforeShowDay: validDate,
        minDate: firstDate(),
        defaultDate: firstDate()
    });
});

Demo: http://jsfiddle.net/jtbowden/LgLr9/1/
Comment: Thanks it works, but I have already set the min date as +14 days. in this case what do I have to change to make it work
Comment: You need to add `valDate.setDate(valDate.getDate() + 14);` after the first line of `firstDate()`.  Edited above.


Appropriate use of education tag

Question: Our site has a tag education:
https://economics.stackexchange.com/questions/tagged/education
and another for education-economics:
https://economics.stackexchange.com/questions/tagged/education-economics
What is the communities view on the how these tags should be used:

Tag use should be consistent. education is sometimes used to tag questions about those interested in learning economics (e.g. What prerequisite courses do I need in order to specialize in Mechanism/Market design theory?) But it is also sometimes used to take questions about the economics of education (Have there been attempts to measure the value of specific taught skills?).
education-economics only seems to be used for the second kind of question, but is not used very often.

It seems like this needs some tidying up. Are there any suggestions about how to handle this?
Comment: Im in favor of getting rid of the education tag, It seems redundant and unclear.The self study tag or educational economics tag are more specific.
Comment: @EconJohn Good point, I had overlooked the self-study tag.
Answer: One suggestion would be the following:

Stadardise around the use of education-economics for questions about the economics of education.
Since some people will inevitably use education to ask questions about the economics of education, we should create a tag-synonym that maps education into education-economics.
Create a new tag (e.g. learning-economics) for questions about becoming educated in economics (although many such questions might belong on Academia.SE, which raises the question of whether we need such a tag at all).

We can create tag wikis to make the appropriate use clearer.
Answer: One suggestion would be the following:

Stadardise around the use of education-economics for questions about the economics of education.
Since education is used mainly for questions about learning economics, we should adopt the convention that this tag is reserved only for such questions (and never for questions about the economics of education).

We can create tag wikis to make the appropriate use clearer.
Comment: If this is implemented education should also map to self-study.

Appropriate use of education tag


simple triangle won't draw in opengl 4.3

Question: I'm trying my hand at opengl programming, loaded up a default example in codeblocks, and after doing a whole lot of function pointer loading, I got myself an opengl 4.3 context in a window which can be cleared with a certain color(YES!), so I went ahead and try to render a triangle...well its not working, not sure where I went wrong I've been around the dark corners of google and my debugger to see if VBO and shader creation went wrong...no luck
here's relevent gl code:
GLuint IndiceArray[3] = {
0, 1, 2
};

const float vertexPositions[] = {
    0.75f, 0.75f,
    0.75f, -0.75f,
    -0.75f, -0.75f,
};

const float vertexColors[] = {
    1.0f, 0.0f, 0.0f, 1.0f,
    0.0f, 1.0f, 0.0f, 1.0f,
    0.0f, 0.0f, 1.0f, 1.0f,
};

//Prepare GPU program
vertexID = glCreateShader( GL_VERTEX_SHADER );
fragmentID = glCreateShader( GL_FRAGMENT_SHADER );

glShaderSource(vertexID, 1, &vsSource, NULL) ;
glShaderSource(fragmentID, 1, &fsSource, NULL) ;

glCompileShader( vertexID );
glCompileShader( fragmentID );

programID = glCreateProgram();
glAttachShader( programID, vertexID );
glAttachShader( programID, fragmentID );
glLinkProgram( programID );
glUseProgram( programID );

//Send to OpenGL
glGenBuffers(3, vertexAttribBufferID);

glBindBuffer( GL_ARRAY_BUFFER, vertexAttribBufferID[0] );
glBufferData( GL_ARRAY_BUFFER, sizeof(vertexPositions), vertexPositions, GL_STATIC_DRAW );

glBindBuffer( GL_ARRAY_BUFFER, vertexAttribBufferID[1] );
glBufferData( GL_ARRAY_BUFFER, sizeof(vertexColors), vertexColors, GL_STATIC_DRAW );

glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, vertexAttribBufferID[2] );
glBufferData( GL_ELEMENT_ARRAY_BUFFER, sizeof(IndiceArray), IndiceArray, GL_STATIC_DRAW );

colorAttribID = glGetAttribLocation( programID, "colorIn" );
positionAttribID = glGetAttribLocation( programID, "vertexPos" );

/* program main loop */
while (!bQuit)
{
    /* check for messages */
    if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
    {
        /* handle or dispatch messages */
        if (msg.message == WM_QUIT)
        {
            bQuit = TRUE;
        }
        else
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
    }
    else
    {
        /* OpenGL animation code goes here */

        glClearColor(1.0f, 0.0f, 0.0f, 0.0f);
        glClear(GL_COLOR_BUFFER_BIT);
        //Render!!
        glBindBuffer( GL_ARRAY_BUFFER, vertexAttribBufferID[0] );
        glEnableVertexAttribArray( positionAttribID );
        glVertexAttribPointer( positionAttribID, 2, GL_FLOAT, GL_FALSE, 0, 0 );

        glBindBuffer( GL_ARRAY_BUFFER, vertexAttribBufferID[1] );
        glEnableVertexAttribArray( colorAttribID );
        glVertexAttribPointer( colorAttribID, 4, GL_FLOAT, GL_FALSE, 0, 0 );

        glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, vertexAttribBufferID[2] );

        glDrawElements( GL_TRIANGLES, 3, GL_UNSIGNED_INT, 0 );
        glDisableVertexAttribArray( colorAttribID );
        glDisableVertexAttribArray( positionAttribID );

        SwapBuffers(hDC);
        Sleep (1);
    }

And shaders :
const char vertexShader[] =
"#version 150 core\n"

"in vec2 vertexPos;\n"
"in vec4 colorIn;\n"
"smooth out vec4 outColor;\n"

"void main()\n"
"{\n"
"   gl_Position = vec4(vertexPos, 0.0f, 1.0f);\n"
"   outColor = colorIn;\n"
"}";

const char fragShader[] =
"#version 150 core\n"

"smooth in vec4 inColor;\n"
"out vec4 f_color;\n"

"void main()\n"
"{\n"
"   f_color = inColor;\n"
"}";

Needless to say, I would be ever thankful for any help, might save me from being frustrated from OpenGL!!!
edit: I only see the cleared background in case you're wondering...
Answer: OK, figured it out: apparently data that you pass between shaders must have the same name as variables on both sides, so my code should be:
const char vertexShader[] =
"#version 150 core\n"

"in vec2 vertexPos;\n"
"in vec4 colorIn;\n"
"smooth out vec4 outColor;\n"

"void main()\n"
"{\n"
"   gl_Position = vec4(vertexPos, 0.0f, 1.0f);\n"
"   outColor = colorIn;\n"
"}";

const char fragShader[] =
"#version 150 core\n"

"smooth in vec4 outColor;\n"
"out vec4 f_color;\n"

"void main()\n"
"{\n"
"   f_color = inColor;\n"
"}";


Is Drupal Commons right for me?

Question: I'm reading a lot, searching, asking questions. Measuring thrice before cutting once.
Now it seems to be a straight choice between a pre-built Drupal Commons and roll-your-own based on core-Drupal plus some modules.
I absolutely require a wiki, which doesn't seem to be in the standard distro, no easily addable as a single module.
I won't mention standard stuff like forums, but will say that I want a "social networking site" for ex-pat foreign workers in another country.
It would be nice to have some form of Goups of fiends & colleagues and to provide sharing permissions at that level of granularity (e.g, world read, group right/ group read only, etc); joint calendars,  access to blogs, maybe chat rooms or even one form per Group; maybe a photo album, although I suppose they can just refer to their Flikr.
Maybe profiles with some extra stuff like IM, phone #, etc,  where the user can control who gets to read it.
(Plus anything more that you can suggest for such a community, of course)
It looks to me like I would be best to start with Drupal Commons – do you agree?
The only thing is that when I go to download it, it says
6.x-2.0 tar.gz (17.4 MB) 2011-Aug-26 Version 2.0 is a major upgrade
Which seems to imply that it is based on Drupal 6, not Drupal 7. Is that correct? Is it a show-stopper for me? Or can I just install it and upgrade everything?
Sorry if I don't sound too knowledgeable; I am still not a Drupal user, just a dabbler on my local PC.
Thanks in advance for any help.
Answer: I would recommend starting with Drupal Commons as a base. It comes with a lot of prebuilt configuration that's very nice, like the fb-style walls for groups and for users. You get all the standard things you mentioned except for forums, but that comes with Drupal core, or you could go for a more advanced solution. You can disable any features you don't want in a per group basis. Commons already comes with a nodes as profiles solutions, so you just need to add the fields you want to the profile node. For chats you will also need an additional module, there are several, maybe this will help get started.
To answer your question more directly, yes Drupal Commons is right for you. It will save you a lot of configuration time, and you can see some best practices in configuration from what they did. Remember to back up your db often and don't be afraid to modify everything to suit your needs, you will learn a lot that way. As long as you have a a backup you can always revert.
Comment: +1 sounds great!! Thanks VERY much for the help. One quick question before I award you the answer. As I said, it looks like Commons is based on Drupal 6. Am I wrong? Should I worry? Can I simply apgrade?
Comment: Drupal Commons is Drupal 6 right now. I used to use Drupal Commons 1.0 and the upgrade to 1.0 (both Drupal 6) was seamless. I imagine that the upgrade from Commons 2.0 to Commons 3.0 (possibly D7) will most likely be supported to. Not all the modules used in Commons have a D7 version yet, check out the chart (http://commons.acquia.com/wiki/migration-status-drupal-commons-modules). Check out this comment (http://commons.acquia.com/blog/commons-20-announcement-backgrounder#comment-20836) to get an idea about when Commons in D7 will be out.

Is Drupal Commons right for me?


What happens if a referee gets injured and there is no replacement available?

Question: I understand that the fourth official is there to come on if the main referee gets injured, but what happens if even the substitute is injured . Is the match forfeited ?
Also, has there been any similar scenario in a real match?
Comment: For an example, in a recent Australia vs Brazil women's international friendly, the appointed referee was injured on the way to the match. A local, suitably qualified referee who was there simply to watch the game took on the referee role instead - she had to borrow football boots from a player, and a whistle and cards from the assistant referees (hence why she was running around the field with white boots instead of black).
Comment: What do the regulations for the competition say? In all likelihood (one of) the (senior) assistant(s) will take over and the sideline will be either empty or covered by another official where possible or a volunteer where not.
Comment: @Nij , I reckon my question assumes a pretty far fetched scenario, however i want to know if **absolutely** no replacement for a referee is available, Do they stop the match there and continue from the same point some other day or totally forfeit or something else?
Comment: You're asking about a match *with a fourth official*. This isn't farfetched, it's outright not ever going to happen, that no kind of replacement is available.
Comment: Whoever is around and willing, if you go down enough to a certain level that is. :D
Comment: It's very unlikely that no-one will take over. On higher level games, one of the other officials will take over as per Law 6 (in the accepted answer). In lower level games without ARs / 4th officials, an official from one of the teams will probably take over to get the match completed. If no-one is willing or able, the match is abandoned (not forfeited).
Comment: I've left these as comments btw, as I have no source on any of this so it would not make a good answer.
Answer: For what it's worth, your first sentence is not necessarily true. Law 6 states:

Competition rules must state clearly who replaces a match official who is unable to start or continue and any associated changes. In particular, it must be clear whether, if the referee is unable to start or continue, the fourth official or the senior assistant referee or senior additional assistant referee takes over.

i.e. it's not necessarily the fourth official who replaces the referee if they become injured. That paragraph pretty much indicates the answer to your question as well: it's covered by the competition rules. You follow whatever procedures are listed in the competition rules, and after that it becomes a "do the best you can, report what happened to the organising body for the competition and let them sort it out" - as happens with any other situation which isn't covered by the rules.


How do I figure out the fundamental frequency of a sound from its frequency spectrum?

Question: I really want to know the fundamental frequency (hertz) of every sound I play in my DAW. All I have is an oscilloscope. I can see the waveform of a sound, I can see all the frequencies the sound is at on the spectrum analyzer, but I can't get the fundamental frequency of the sound.
Is it possible to figure that out just by looking at the frequency spectrum? It is definitely not always obvious, especially with inharmonic sounds or any sound that is really complex! Is there some way to find it no matter what?
Also, is there a vst that actually does what I'm looking for? Like, give you the fundamental frequency in hertz upon hearing the sound?
Answer: To answer your last question first, tuners pretty much do this. So a tuner VST may help. I have not tried it, especially on inharmonic sounds.
Here's a definition (Wikipedia):

The fundamental frequency, often referred to simply as the fundamental, is defined as the lowest frequency of a periodic waveform. [...] In terms of a superposition of sinusoids (e.g. Fourier series), the fundamental frequency is the lowest frequency sinusoidal in the sum.

So, in general, you want to take the Fourier transform of the sound, and find the lowest peak. Spectrum analysers do the transform bit (ignoring some complexity around bin sizes), so I guess you could just look for the peak. You'll have to distinguish it from the noise floor, or any other artifacts, of course.
As E.P. notes in the comments, this won't work for an arbitrary waveform. Specifically, if it's not periodic, the concept of a fundamental frequency doesn't really make sense any more. Even if it is periodic, there's the concept of the missing fundamental. The Wikipedia article mentions that this is intentionally used in music to imply lower bass frequencies that are not otherwise reproducible. In these cases, you're probably going to have to do some more analysis of the specific waveform. I'm not aware of an algorithm that can perform this automatically.
You could probably build a tuner using this technique, but I'm not sure if "real" ones are actually implemented this way. A very cursory Google revealed that there are other techniques which do not require an FFT, which are probably more attractive to your average guitar tuner.
This Stack Overflow answer may be of interest: https://stackoverflow.com/questions/435533/detecting-the-fundamental-frequency
Comment: It's important to note that the lowest peak may not coincide with the fundamental frequency (which might not be populated) - so, for instance, f(t) = cos(2wt) + cos(3wt) is periodic, but the fundamental ( at frequency w/6) carries no amplitude, and this [can still be detected by the brain](https://en.wikipedia.org/wiki/Missing_fundamental). And, similarly, for an arbitrary waveform, there is no guarantee that it will be periodic and that you can even define a fundamental. Probably neither is a problem in the OP's case, but important to keep in mind.
Comment: Just dropping by to say a certain physicist (and musician) agrees with every part of this answer.   I'll just emphasize that waveforms in general do not have, or need to have, a fundamental.  Consider, e.g., 3 different instruments playing three different notes simultaneously.


Is constructing the target variable manually a form of data leakage?

Question: Let's say, I have a data table with numerical features A, B, C. I do not have the target variable but I extract the target variable Y from the features A, B, and C. like so:
<code>If A < 0.1*sum(A,B,C) and B < 0.1*sum(A,B,C) and C < 0.1*sum(A,B,C) then Y=1 else Y=0
</code>
Now I have features A, B, C and target variable Y for which I train model to predict Y. Is this data leakage? Is there anything wrong with this method?
Comment: Where did that formula come from? Did you come up with the formula after looking at the data?
Answer: It is not data leakage. But it has another issue. Namely - the relationship between your variables and the target is deterministic and known to you, so what will you gain by training a model?
In this particular case if you get a new observation with new variables A, B, and C you can know the target outcome of this new observation by applying your formula. Any model that is trained on this data can fail to predict the Y correctly and hence can only do worse.
And in general, one of the requirements for applying "machine learning" is that features and the outcome shouldn't have a deterministic derivable relationship. For example this is why no one trains models in order to predict the odds of winning in games like roulette, where each outcome can be calculated perfectly using probability.
Comment: thank you for your answer, got an idea.
Answer: No, this is not data leakage. It's actually dataset generation (a mockup target variable) and it's typically done to test if a model can capture the underlying a user-defined relationship, which I assume it is also your aim to do so.


Difference between dependent and correlated variables

Question: I read that correlated variables are always dependent but dependent variables may be uncorrelated. Can anyone please correct me if I am wrong? And also explain me intuitively the difference between correlation and dependence in variables with an example? I will be very thankful
Comment: Thank you @kjetilbhalvorsen, but I am looking for more of an intuitive explanation. If you have checked the link that you have mentioned here, it does a very good job but, apologies, I couldn't derive an intuitive explanation from it. Please help if you can elaborate more on the answer
Comment: There are more intuitive explanations at some of the other duplicates. See also some of the discussions in answers and some comments in posts under "Related" in the sidebar
Answer: Suppose that X ranges from -2 to +2.  Suppose that Y = X^2.
Now the correlation will be close to 0 (how close depends on how noisy the data are) but the dependence will be strong.


array as value in hash in ruby

Question: I want to have a hash whose key is a string and the value is an array. I tried it the following way:
h = Hash.new([]) # => {}
h["one"]         # => []
h["two"]         # => []
h["one"].push 1  # => [1]
h["one"]         # => [1]
h["two"]         # => [1] //why did it assign it to h["two"] also??

What is the correct way to do it?
Comment: That is the correct way to do it.
Comment: possible duplicate of [Can't use an array as default values for Ruby Hash?](http://stackoverflow.com/questions/5488853/cant-use-an-array-as-default-values-for-ruby-hash)
Answer: You get this behavior because [] that you passed into new method isn't copied but referenced in all unset hash keys. So h['one'] references the same object as h['two']. So if you modify object referenced by h['one'] (using push method), h['two'] will also be modified.
The correct way to set default value which will be initialized for every single hash key is to use block:
h = Hash.new { |hash, key| hash[key] = [] }

Answer: I usually do it like this:
h = Hash.new { |h,k| h[k] = [] }
h['one']
h
# => { 'one' => [] }
h['two'] << 12
h
# => { 'one' => [], 'two' => [12] }

Which is more verbose and (IMO) reads nicer.

array as value in hash in ruby


How many possible monograms are there?

Question: The question is simple. A couple want to name their baby in such a way that his initials are in alphabetical order, with no repetition.The monogram is of the form ABC, where A is the initial of his first name, B his second name and C his last name.
My reasoning is simple. I realised that it's equivalent to picking up $3$ elements from a list of $26$ elements. We don't have to worry about counting if they're in alphabetical order because every $3$ tuple chosen like this will have one and only one alphabetical order. In other words, there is a one to one correspondence in between the number of ways of choosing $3$elements and the number of ways of arranging these $3$ elements in alphabetical order.
My answer is $$\binom{26}{3}$$
However, it is wrong. What is the mistake here ?
Edit : I left out the name of the couple because I didn't think it mattered. Their name was Mr. And Mrs. Zeta. Now, I see why the answer makes sense. The baby shares the parents last name and the remaining two alphabets can be chosen in $\binom{25}{2}$ ways, each of which correspond with only one alphabetical arrangement since they are all different combinations.
Comment: The answer is indeed $\binom{26}{3}$. Clearly described reasoning.
Comment: Why do you claim it is wrong?
Comment: The book gives the answer as $\binom{25}{2}$
Answer: Depends.  What's the couple's last name?  (Or are you saying the child will not share the parents' last name?)
Comment: Wow. That was brilliant. Their last name was Zeta, but I didn't think it mattered until you said it.
Comment: Now, I see why it is $\binom{25}{2}$.

How many possible monograms are there?


Automatic NN Architecture Configuration

Question: I have to implement 3 Neural Networks, an MLP, an RNN and an LSTM, for a "Future Location Prediction" problem and it's the first time I am in touch with NNs.
I would like to ask whether there is a way to automatically find the best configuration for their parametres, aca number of layers, number of nodes in each layer, dropout, activation and loss functions, as well as optimiser.
If there is no such solution, would you suggest a better way than blind trying?
Thanks in advance!!
Answer: The two most common methods are Grid Search and Random Search. For both of these you specify a set or a range of hyperparameter values and then iteratively try combinations of hyperparameters to find the best combination. For a grid search, a set of values is provided for each hyperparameter to be tuned and each combination is tried systematically. For a random search, the values are selected randomly and tried, until a stopping condition is met. Typically, cross-validation is used to test the various hyperparameter combinations.
If you're using Python, there are several packages that can help you do this. If you search for "hyperparameter tuning python" you will find plenty of information on these packages and how to use them. To get started, have a look at Jason Brownlee's Machine Learning Mastery blog:

Hyperparameter Optimization With Random Search and Grid Search
How to Grid Search Hyperparameters for Deep Learning Models in Python With Keras
Comment: Do be aware though that searching over model architectures and any hyper-parameter that may be involved is a bit of a recipe for over-fitting the model selection criterion and the model that is selected by the procedure may be worse than the model you started with in extreme cases.  For "shallow" neural networks, I would recommend using either pruning or growing methods rather than architecture selection, or just use a large network and regularisation (although that is not a panacea).

Automatic NN Architecture Configuration


disable audio on remote desktop

Question: I am running a Windows 2008 server that has remote users connecting to it via terminal services.
I have group policies in place for each organization that connects.
Is there a way, through group policies, to disable audio on a remote desktop connection?
Thanks!
Comment: Do you want to disable it for everyone connecting to the system?  Or individual users?
Comment: Everyone within that policy, if possible.
Comment: **You didn't answer my question**.  There is a policy, but it is a **per-computer policy** and it applies to the terminal server, completely disabling audio.  So I guess that is what you want, because it will affect everyone within that policy right?
Comment: Yes that is what I'm wanting
Comment: http://technet.microsoft.com/en-us/library/ee791794(v=ws.10).aspx
Comment: ty! I'll check it out now.
Comment: That is what I'm looking for! If you post this as your answer I'll accept it.
Answer: The group policy that controls device and resource connection is under.

Computer Configuration\Policies\Administrative Templates\Windows Components\Remote Desktop Services\Remote Desktop Session Host\Device and Resource Redirection.

These settings are per-computer.
See http://technet.microsoft.com/en-us/library/ee791794(v=ws.10).aspx for full details.

disable audio on remote desktop


Why does the neck of a bass get wider?

Question: I've noticed in many basses (not sure if this happens in all of them), the top of the neck starts at a certain width and towards the bottom, it is wider. Here is an example:

This happens to my double bass as well. What is the reason for this?
Comment: Possibly for the same reason guitar fingerboards and fingerboards on instruments from the strings section all get wider towards the bridge. What is that reason? I really don't know. If forced to guess... I still draw a blank. On guitar it is common to play chords closer to the nut and single notes closer to the bridge, but it's the only one of all those instruments that would likely have that reason. Why do the strings on all of them get spaced futher apart towards the bridge? Maybe it's string spacing driving the fingerboard flare.
Answer: In a nutshell: different hands have different requirements.
Your left hand (assuming you are right-handed) has to comfortably reach around the neck to fret the notes. Since the indispensible lowest-string notes (the ones you cannot play on a higher string) are in the lowest position, you want the neck to be reasonably narrow near the headstock. Also, any single-finger double-stops - or barres - are going to be much easier to play if the strings are close together.
Your right hand will want some space between strings, in order to cleanly articulate notes using a variety of techniques without the other strings getting in the way - for example slap bass. A further consideration, as far as bass guitars with more than four strings are concerned, is keeping the same general string spacing at the bridge as a four-string, allowing for a similar playing experience.
How can we satisfy these contrary requirements? Make the neck narrower at the headstock and wider at the body. The left hand is happy, because it doesn't have to reach that far and the right hand is happy, because it has space to do its work without hitting adjacent strings. A neck that widens towards the body end is a standard design that can be found on most stringed instruments with a neck, as Todd Wilcox points out. The width of the neck at the body end is not such a big issue, because the crucial notes are on the highest strings and thus easy to reach regardless of neck-width, while the hard-to-reach notes on the lower strings can be played in lower positions.
Comment: Can we extend this to explain other stringed instruments having the same fingerboard shape? Clearly the same applies to guitar. I suppose both arco and pizzicato playing on instruments from the strings section benefit from wider spacing near the bridge. I think there's a case to be made for increased spacing being needed to keep strings from colliding when played open.
Answer: The same question for strings in general is discussed here. Here are a few good quotes from that discussion:

The truth is that you want strength at the heel of the neck, you want slimness where your fingers need to go the most, and you don't want a baseball bat for your neck

and

Then there is the matter of the amplitude of a vibrating string. As you get closer to the 12th fret (midpoint of the string), you need to be sure that the strings are sufficiently far apart that they don't interfere with each other.

and my personal favorite:

A tapered neck will ensure more even levels of stress within the neck. A parallel neck will have higher relative stress levels nearer the body than near the nut. Since the relation betweeen stress and strain is constant, a tapered neck will deform more uniformly along its length under the load from the strings; a parallel neck would tend to bend from the heel. So the amount of taper will affect the shape the neck deforms to under the string load.

The last one implies that the taper of the neck affects how the neck relief  (the bow of the neck to keep the strings from buzzing on the frets) is distributed. That combined with the truss rod channel shape allows the luthier to design for a fairly particular relief profile.
It does look like the best answer is probably "all of the above", and by "all" I mean to include Faza's answer regarding playability.
Comment: Good point about the mechanics of - essentially - stretching a string on a stick. :)

Why does the neck of a bass get wider?


Left and Right Continuity of a Line that contains at least one Asymptote

Question: I've been slowly learning about function continuity, lately, and believe I understand how to find if a function is continuous at a given number.  I am confused, however, about left-continuity and right-continuity of a function when the function is something like (Graph 1):
$$f(x)=\frac{1}{x^2}$$
I understand that:
$$ \lim_{x \to 0}\frac{1}{x^2} = \infty $$
so I know that the limit does not exist... which, in turn, lets me know that this equation's line is not completely continuous.
Though the line is not continuous, is there any way for there to be left-continuity or right-continuity with a function like this?  (At what point on the graphed line would I even be able to decide where to start to check for left-continuity or right-continuity, if each graphed line goes on indefinitely toward 0?)
Graph 1:
Answer: Your function is not continuous from either side.  Consider $f(x)=\begin {cases} 0& x\le 0\\\frac 1x& x \gt 0 \end {cases}$  It is nicely continuous if you approach $0$ from the left, but not from the right.
Comment: @summea:  that is correct, but it doesn't take that.  $f(x)=x$ for $x \ne 0$ is not continuous at zero, just because the point is missing.  An asymptote is another way to have the point missing.
Comment: @summea:  that is correct.  Whether it is horizontal or not doesn't matter, but having the point at $0$ connect with the stuff to the left does.
Comment: Thanks for your answer; so... am I correct in thinking that a function is not continuous (either from the right or from the left) if there is an asymptote involved *(like in Graph 1 in the question above...)*?
Comment: Also, about the example in your answer: is the "nicely continuous if you approach 0 from the left" part referring to the $f(x)=\begin {cases} 0& x\le 0\\ \end {cases}$ (horizontal line) part?
Answer: Function is not continious if a. $$\lim_{x\to x_0}f(x)$$ is infinite or b. $$\lim_{x\to x_0^+}f(x)\neq \lim_{x\to x_0^-}f(x)$$. In the function $f(x)=\frac{1}{x^2}$ , $\lim_{x\to x_0^+}f(x)= \lim_{x\to x_0^-}f(x)$ but $\lim_{x\to x_0}f(x)=\infty$. Hence, this function is not continious in the point $x_0=0$ but at any other point in $\mathbb{R}$ it is contiious. e.g take $x_0=1$: you know that $g(x)=x^2$ is continious so $\lim_{x\to 1}f(x)=1$, which means, $\lim_{x\to 1}f(x)=\lim_{x\to 1}\frac{1}{x^2}=1=f(1)$ (the limit in the point equal to the value of the function in this point).
If you still have questions, let's do another example of function:$h(x)=\frac{1}{sinx}$. if you check my chriterions for points you will discover that function is continious at every point expet $x_0=\pi k$ (reason b). How do you in which point to check ? I recommand check where $g=\frac{1}{f}$ or $log(f)$ or any other frequent functions for which x's the picture is not defined.


Migrate Paragraphs from CSV

Question: I am migrating Paragraphs from CSV file. I have Paragraph called Text with two fields -> title and body.
The problem is that I would like to also migrate translations for them, which currently don't know how to achieve. Tried with the migration_lookup plugin and translations: true option, but receive error for duplicate primary key ids.
What is the way to do this?
Comment: Is this for Drupal 8?
Answer: A simple solution could be the content import module that allows you to import among other things paragraph content from CSV I believe and you can specify language for each field.  Give it a try
Comment: Sadly, not yet, see issue "Add support for importing Paragraphs references" at https://www.drupal.org/project/contentimport/issues/3001880
Answer: You will need two migrations. One for the paragraphs in the default language and one for the translations. Make sure the migration for the translation include the language code as a key.
And this post looks useful, https://evolvingweb.ca/blog/migrate-translations-csv-json-or-xml-drupal-8. As do all the links here,
 How to migrate multilingual content from CSV to Drupal 8?
Comment: I tried that approach, but the problem is that the migration doesn't create translation for the default language, but creates new paragraph records.

Migrate Paragraphs from CSV


"No compatible targets were found" eclipse adt plugin error

Question: I don't understand...
In my office I installed Eclipse + Android SDK (API 16) + ADT plugin to develop my own app. When I installed it on my Galaxy Tab and Galaxy Nexus nothing happened and it worked fine. But when I installed all of this on my laptop in my house and imported the eclipse project to installed it again on my devices ADT says that message: "No compatible targets were found". Despite it's the same project, i didn't change a thing and the software is the same...
What can be causing this issue? Any ideas?
I have a meeting this wednesday to start selling the app and it would be great if someone could answer me before that day!! xD
Thanks!!
Comment: Have tried to add SDK path to the eclipse preferences?
Answer: Are the ADB drivers for the phone working/installed on the laptop?
if your using windows check the device manager.
Answer: It sounds like you don't have the proper version of the SDK installed on your Eclipse.  You need to make sure you have used the 'SDK Manager' to install the proper Android version, that your build is compiling to what you expect (this is set in the AndroidManifest.xml), and that your emulator or device is targeting the version of the OS you are expecting.
My quess is you don't have the proper Android SDK downloaded.
Comment: I don't think so... because I downloaded SDK number 16 and 17 in my office and in my laptop... and in AndroidManifest I put minSDKVersion = 9 and targetSDKVersion = 15... it worked in my office but not at home... I think, as pvyParts said, it's about the drivers of the devices...


Inconsistent dates in Python, Mule?

Question: In a nutshell: How can I get a reliable date out of Python code that needs to run both in a normal Python interpreter and within Mule (specifically, MuleSoft Anypoint Studio, which is supposed to interpret it as Jython)?
Verbose mode: As part of a Mule ESB project, I am running a few Python scripts to generate data files. These generated files are stored on the local disk, and from there picked up by a Mule flow that pushes their content to a database connection (if this seems roundabout, there are other sources that may also store these types of files in the same file system location, and I'll push their content to the database, too).
Here's an extract:
from datetime import datetime as dt
...
this_date = dt.today()
if (this_date.year<1900): this_date.year += 1900 # Mule has a weird offset...?
...
print(str(date.year))
...

Now, with that comment, you can see I'm already having trouble. When I run the code in Python, I get 2015 as year; but when I run the same code through Mule (which I presume is using a Jython interpreter), the year becomes 115 so I add 1900.
This worked fine a month ago (over a course of many days). Today I found out that (when running through Mule) the "today()" method in the script returns not "2015-11-12" but rather "2015-10-05". Tomorrow, I will see how this date changes.
Now I'm stumped as to how I can get a reliable date out of this -- ideally it should work in both Python and Jython, but if I have to choose, Jython is the key thing.
Update: Nope. The new code works when run as Python from my text editor, but when interpreted by Mule, I get:
javax.script.ScriptException:
AttributeError: 'java.sql.Timestamp' object has no attribute 'replace'
in

Inconsistent dates in Python, Mule?


Name this collection

Question: This question is language-agnostic (although it assumes one that is both procedural and OO).
I'm having trouble finding if there is a standard name for a collection with the following behavior:
-Fixed-capacity of N elements, maintaining insertion order.
-Elements are added to the 'Tail'
-Whenever an item is added, the head of the collection is returned (FIFO), although not necessarily removed.
-If the collection now contains more than N elements, the Head is removed - otherwise it remains in the collection (now having advanced one step further towards its ultimate removal).
I often use this structure to keep a running count - i.e. the frame length of the past N frames, so as to provide  'moving window' across which I can average, sum, etc.
Comment: If no name is discovered, I'd like to suggest that it be called "Frank".
Comment: Though, if I had to implement something of the sort, I'd call it a "SlidingWindowQueue" or a "FixedLengthQueue".
Comment: How can I add and remove elements from a Collection with a fixed length?
Comment: I typically reference it as a RunningList (or MovingAverage, if the implementation's purpose is to provide the average over the window), but Frank does have a certain ring to it.
Comment: Since it has a fixed capacity and you can not overflow it then I would name it a NonOverflowableQueue
Comment: Frank is a great data structure name.  It's short, honest, and to the point. :)
Comment: @M. Reif I meant 'fixed capacity' - thanks! Edited.
Answer: Sounds very similar to a circular buffer to me; with the exception that you are probably under-defining or over constraining the add / remove behavior.
Note that there are two "views" of a circular buffer.  One is the layout view, which has a section of memory being written to with "head" and "tail" indexes and a bit of logic to "wrap" around when the tail is "before" the head.  The other is a "logical" view where you have a queue that's not exposing how it is being laid out, but definately has a limited number of slots which it can "grow to".
Within the context of doing computation, there is a very long standing project that I love (although the cli interface is a bit foreign if you're not use to such things).  It's called the RoundRobinDatabase, where each databases stores exactly N copies of a single value (providing graphs, averages, etc).  It adjusts the next bin based on a number of parameters, but most often it advances bins based on time.  It's often the tool behind a large number of network throughput graphs, and it has configurable bin collision resolution, etc.
In general, algorithims that are sensitive to the last "some number" of entries are often called "sliding box" algorithms, but that's focusing on the algorithm and not on the data structure :)
Comment: Yup, also called a "ring buffer" (the name I know it by) or "circular queue" or probably several other names.
Comment: @T.J.Crowder I've heard it called a ring buffer too.  Probably another one of the "multiple names for the same thing" issues that crop up in some of the early data structure terminology.  Kind of like "map" and "dictionary" (and I'm pretty happy that barely anyone refers to maps as dictionaries any more)
Comment: Any known difference (other than the names!) between a ring buffer / circular queue / circular linked list?
Comment: @EdwinBuck Sliding Box algorithm, indeed, although my use cases tend to be much simpler (running averages, mins, maxes... 'integrating' mouse movement over several frames, etc)
Comment: @bfishman There are no real differences.  Hardware implementations tended to call them ring buffers, people who were more concerned with the ordering aspects as opposed to the buffering aspects favored queue over buffer.  In short, all the implementations are more or less conceptually the same, but the names come from different areas of development / different common naming practices in different languages / different countries / etc.
Comment: Great response, thank you. I think ring buffer / circular queue is *slightly* closer to what I'm trying to describe (although implementation wasn't indicated in my question), especially because my collection is typically backed by an Array, not a Linked List.
Comment: @bfishman I found a link for the source code of frameCounter. You can take a look at it. I added it in my solution.
Answer: The programming riddle sounds like a circular linked list to me.
Well, all these description fits, doesn't it?
• Fixed-capacity of N elements, maintaining insertion order.
• Elements are added to the 'Tail'
• Whenever an item is added, the head of the collection is returned (FIFO), although not necessarily removed.

This link with source codes for counting frames probably helps too: frameCounter
Comment: Very close, thank you for your answer. From the question, which didn't discuss implementation in detail, your answer is just as good as the selected answer, circular buffer / queue. But since I'm backing it by an array, not a linked list (you had no way of knowing this), I selected the other answer for their better mind-reading powers.
Comment: This might be it - doing a bit more research on it!
Comment: Lists in general support insertion and removal from any position.  Circular linked lists were fun optimizations of regular linked lists because you didn't have to check if the next pointer was null.  Instead you checked if the next pointer was the same as the head pointer (which you had to store anyway to have a "handle" to the list.  It removed one constant from the code, and made the nesting of if statements a bit cleaner.  That said, they were very much used as lists (insert / remove at any position) (and with care any list can be used as a queue).

Name this collection


django-plotly-dash div size too small and wont change

Question: Using Django-plotly-dash module and dash app is rendering in a very small window. is there something specific other than typical css that i can do to render this full page?
I have tried updating style of the specific div as well as updating the style in the entire page.
...
{% extends 'base_page.html' %}
{% block content %}

{%load plotly_dash%}

        {% plotly_app name="SimpleExample" %}

{% endblock %}
...

Expecting div to be full page however it is only rendering a very small window
Comment: i ended up finding my answer. i simplely needed to add ratio=1.00 i believe by default ratio is set to .2 which only shows the div in a window 20% the size of the actual dash app.
"{% plotly_app name="NFLDATA" ratio=1 %}"
Answer: I ran into the same problem, couldn't find where the template tag gets its style. One thing you cant try is adding a ratio argument
{% plotly_app name="SimpleExample" ratio=1 %}

EDIT:
I didn't see your comment there before.
You could also try using
{% plotly_direct name="SimpleExample" %}

This template tag allows the direct insertion of html into a template, instead of embedding it in an iframe. You will need the {% plotly_header %} and {% plotly_footer %} tags too, and not to forget the middleware should be added in settings.py
MIDDLEWARE = [

               'django_plotly_dash.middleware.BaseMiddleware',

             ]

This link is helpful: https://django-plotly-dash.readthedocs.io/en/latest/template_tags.html
Answer: I ran into the same problem with the intention of displaying a full-width graph. I have found the only satisfying option was to use {% plotly_app_bootstrap %} in a combination with css to format the classes iframe, and dash-graph, respectively outside and inside the iframe. This solution relies on setting the aspect-ratio and width attributes.
Solution
Example file structure:
AmazingDjangoProject
└───AamazingDjangoApp
    │   AmazingDashApp.py
    │   ...
    │
    └───static
    │   └───AmazingDjangoApp
    │       │   inner.css
    │       │   outer.css
    │
    └───templates
        │   base.html

In base.html

{% load static %} and include the outer.css stylesheet
{% load plotly_dash %}, {% plotly_header %}, and {% plotly_footer %}
{% plotly_app_bootstrap name="AnAmazingAppName" %}

{% load static %}
{% load plotly_dash %}

<!doctype html>

        <link rel="stylesheet" href="{% static 'AmazingDashApp/outer.css' %}">
        {% plotly_header %}

        {% plotly_app_bootstrap name="AnAmazingAppName" %}

    {% plotly_footer %}

In the outer.css set the iframe, that is included by django-plotly-dash, to have 100% width (of its parent), and the desired aspect ratio:
iframe {
    width: 100%;
    aspect-ratio: 16 / 9;
}

Load the inner.css in the Dash app AmazingDashApp.py:
from django_plotly_dash import DjangoDash

app = DjangoDash(
    name='AnAmazingAppName',
    external_stylesheets=["/static/AmazingDjangoApp/inner.css"],
)
app.layout = ...

In the inner.css set the aspect ratio of the Dash app´s container, and optionally configure the body (of the document inside the iframe):
.dash-graph {
    aspect-ratio: 16 / 9;
}
body {
    margin: 0;
}

Preliminary setup
The static folder(s) need to be registered according to the Django doc. Django needs to be configured for bootstrap according to the django-plotly-dash doc.
Answer: After fighting with this same problem for entirely too long, I finally realized that the problem was that the template itself wasn't including the bootstrap css, meaning none of the settings that should be getting applied for the embed-responsive style applied around the django-plotly-dash iframe.  The .css files all get included properly within the iframe so the applciation itself was working just fine, but nothing was telling the iframe what size to be so it was running in a tiny little window on a big blank screen.
Starting from the instructions from Bootstrap's 'getting started' page I did some quick tests and found that I could get it working properly just by adding a header block to my template that explicitly included the bootstrap css:

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

  <link rel="stylesheet" href="/static/rest_framework/css/bootstrap.min.css" >

Since none of the examples I've seen do anything special to include anything I had assumed it was baked in - I don't know if this is an actual issue for django-plotly-dash, something wrong with my setup, or just my inexperience with modern web development, but hopefully this helps someone down the road.


Number of strings

Question: There are $2^{10} =1024$ possible $10$ -letters strings in which each letter is either an $A$ or a $B$. Find the number of such strings that do not have more than $3$ adjacent letters that are identical.
Comment: Find the number of all the permutations and subtract those that have a sequence of 4 or more adjacent letter. The challenge, when subtracting, is not to count the four or more sequences multiple times. E.g. don't count $BAAAABBBBA$ as 2 strings of more than 3 adjacent letters.
Answer: Let $f(n)$ be the number of strings of length $n$ that begin with A and do not have $4$ or more consecutive  occurrences of the same letter (good strings).  Then the answer to our problem is $2f(10)$.
The second letter could be a B. There are $f(n-1)$ such good strings.
The second letter could be an A, and the next a B. There are $f(n-2)$ such good strings.
The second and third letter could be an A, and the next a B. There are $f(n-3)$ such good strings.
So for $n\gt 3$ we have $f(n)=f(n-1)+f(n-2)+f(n-3)$. It is easy to see that $f(1)=1$, $f(2)=2$, and $f(3)=4$. Now we can use the "tribonacci" recurrence to climb to $10$.
Answer: Any allowed string can be seen as a sequence of blocks made of $A$ or $B$ only, whose length is between $1$ and $3$. For instance:
$$ ABBABABBBA \longrightarrow (A)(BB)(A)(B)(A)(BBB)(A)$$
can be associated with the identity: $10=1+2+1+1+1+3+1$. Hence we just have to count in how many ways we can write $10$ as a sum of integers between $1$ and $3$, then multiply such number by two (since we may start with an $A$ or a $B$). So we have that the number of allowed strings is given by twice a tribonacci number:
$$ 2\cdot[x^{10}]\left(\frac{1}{1-(x+x^2+x^3)}\right)=2\cdot 274=\color{red}{548}. $$

Number of strings


Why is variational Bayesian mixture model an alternative to MCMC? What are the similarities?

Question: Why do people say that a variational Bayesian mixture model could be an alternative to MCMC for clustering? For example see the details here: https://en.wikipedia.org/wiki/Variational_Bayesian_method.
What is the purpose of the Markov Chain in MCMC? Does it correspond to the beta / Dirichlet distribution in variational Bayesian method? Do I make sense of the probability model described in Markov Chain?
Answer: The variational Bayes approach to a Bayesian mixture model, as described in detail in the Wikipedia page, is producing a pseudo-posterior distribution on the parameters of the mixture model, including the latent variables $\mathbf{Z}$, by imposing a certain dependence structure (or graphical model) and estimating the hyperparameters of this model by a maximising algorithm akin to the EM algorithm.

Note: variational Bayes is a form of (empirical) Bayesian inference, which simplifies the true posterior into a distribution
  with more independence assumptions. In the current example, the
  construction of the  variational Bayes approximation relies on an
  optimisation algorithm that is close to EM, usually employed for
  maximum likelihood estimation.

Reproducing the equations from that Wikipedia page we have that
$$q(\mathbf{Z},\mathbf{\pi},\mathbf{\mu},\mathbf{\Lambda}) = q(\mathbf{Z})q(\mathbf{\pi},\mathbf{\mu},\mathbf{\Lambda})$$
means that $\mathbf{Z}$ is given as independent from $(\mathbf{\pi},\mathbf{\mu},\mathbf{\Lambda})$ in the variational Bayes approximation, which is not true for the exact posterior distribution, proportional to $p(\mathbf{X},\mathbf{Z},\mathbf{\pi},\mathbf{\mu},\mathbf{\Lambda})$. When solving the VB equation
$$q^*(\mathbf{Z}) = \mathbb{E}_{\mathbf{\pi},\mathbf{\mu},\mathbf{\Lambda}}[\ln p(\mathbf{X},\mathbf{Z},\mathbf{\pi},\mathbf{\mu},\mathbf{\Lambda})] + \text{constant} $$
the variational Bayes version of the posterior on the latent variables is of the Multinomial kind
$$q^*(\mathbf{Z}) = \prod_{n=1}^N \prod_{k=1}^K r_{nk}^{z_{nk}}$$
Similarly, the variational Bayes approximation makes the assumption that the posterior on the parameters factorises as
$$q(\mathbf{\pi},\mathbf{\mu},\mathbf{\Lambda})=q(\mathbf{\pi}) \prod_{k=1}^K q(\mathbf{\mu}_k,\mathbf{\Lambda}_k)$$
and the conjugate nature of the prior implies that the variational Bayes posterior is also from the conjugate family. (This is a generic result for variational Bayes approximations in exponential families.)
There is no connection with MCMC, but rather EM, as well-described in the Wikipedia page: the reason is that the variational Bayes posterior is made of standard distributions, thus does not require simulation, but has hyperparameters, like the $r_{kn}$ above that need derivation by an optimisation program, hence the call to an EM-like algorithm. The only weak similarity is that both MCMC and EM are iterative, but the number of iterations in EM is determined by convergence to the optimum, while the number of iterations in MCMC is unlimited. Furthermore, MCMC operates on the parameter space, while EM operates on the hyperparameter space.
Comment: Several points: (1) VB produces an approximate posterior distribution (2) EM is used for the hyperparameters only (3) MCMC is used to sample from the exact posterior distribution and (4) sample size is not connected with the use of VB versus MCMC.
Comment: Xi'an, thanks for explaining. Can I say like this? variational Bayes finds the full posterior distribution using EM over parameters and hyper-parameters. Whereas MCMC takes a more direct approach by sampling. Besides, I am sensing that MCMC would be the more appropriate method to used when sample size (observation) is limited. Does it make sense?
Comment: I have two last questions. 1) What is the thing that are iteratively optimized using EM-like method in VB? Is it the hyperparameters (such as weight concentration) in posterior probability distribution? 2) What is the advantage of VB over simple EM? In what circumstance do we have to apply VB instead of EM?
Comment: (1) EM is used to find the (hyper)parameters of the pseudo-posterior distribution on the parameters of the model, based on the data; this is a type of empirical Bayes approach (2) VB produces a whole distribution on the .parameters, while EM only produces the maximum likelihood estimator.


svg are not seen on iphone

Question: I have a problem with my code, I have an animation of an SVG, and it shows on all devices except iPhones.
I can't find solutions. here is the code of the SVG

  <svg viewBox="-85 -85 170 170" xmlns="http://www.w3.org/2000/svg">
        <defs>
            <filter id="blur">
               <feGaussianBlur stdDeviation="4.8" />
            </filter>
            <linearGradient id="gradient" x1="0%" y1="0%" x2="100%" y2="100%">
                <stop offset="10%" stop-color="#9DB6F2" />
                <stop offset="70%" stop-color="#FF5321" />
                <stop offset="20%" stop-color="#FF2E00" />
            </linearGradient>
        </defs>
        <path fill="url(#gradient)" style="opacity: 1;" filter="url(#blur)">
            <animate attributeName="d" dur="20000ms" repeatCount="indefinite"
                         values="M46.8,-53.3C55.6,-48.4,54.1,-28.9,52.8,-12.8C51.5,3.3,50.4,15.8,43.8,23.4C37.2,31,25.2,33.7,11.7,43.5C-1.7,53.2,-16.7,70.1,-28.8,69.8C-40.8,69.4,-49.9,51.7,-56.8,35.1C-63.7,18.4,-68.4,2.8,-67.8,-13.9C-67.2,-30.5,-61.2,-48.2,-49,-52.4C-36.8,-56.7,-18.4,-47.5,0.3,-47.9C19,-48.3,38,-58.1,46.8,-53.3Z;
 M38.9,-46.9C53,-34.5,69,-24.7,67.4,-14.7C65.8,-4.7,46.7,5.6,36.9,20C27,34.3,26.5,52.7,19.6,56.2C12.8,59.7,-0.3,48.3,-11.3,40.3C-22.3,32.3,-31.1,27.7,-34.4,20.5C-37.7,13.4,-35.5,3.8,-38.3,-11.3C-41.1,-26.5,-48.9,-47,-43.4,-61C-37.8,-75,-18.9,-82.3,-3.3,-78.4C12.4,-74.5,24.7,-59.3,38.9,-46.9Z;

                                                    M25.6,-33.4C38.3,-19.9,57.2,-16.7,65.6,-6.1C74.1,4.6,72.1,22.5,62.9,34.2C53.6,45.8,37.1,51.1,19.7,59.9C2.4,68.7,-15.7,80.9,-24.3,74.4C-32.9,68,-32,43,-36.8,25.6C-41.7,8.2,-52.5,-1.5,-50.6,-8.3C-48.7,-15.2,-34.1,-19.3,-23.6,-33.2C-13.1,-47,-6.5,-70.7,0,-70.7C6.5,-70.7,13,-46.9,25.6,-33.4Z;

                                                    M36.1,-40.2C51.4,-30.3,71.5,-23.2,71.4,-14C71.3,-4.8,51.1,6.5,37.5,13.8C23.9,21.1,17,24.4,6.9,35C-3.2,45.7,-16.5,63.7,-23.2,62C-30,60.3,-30.2,38.9,-33.3,23.9C-36.4,8.9,-42.4,0.2,-46.9,-14.2C-51.4,-28.5,-54.5,-48.6,-46.4,-59.7C-38.4,-70.9,-19.2,-73.2,-4.4,-68C10.4,-62.8,20.9,-50.1,36.1,-40.2Z;

                                                    M35.5,-41.2C48.2,-31.7,62.1,-22.5,70.7,-7.5C79.3,7.6,82.5,28.5,73.4,40.6C64.3,52.6,42.9,55.7,26.4,53.4C10,51,-1.4,43.2,-11.9,37.3C-22.3,31.5,-31.7,27.6,-36.2,20.6C-40.7,13.5,-40.2,3.2,-38.7,-7.1C-37.3,-17.5,-34.7,-27.9,-28.1,-38.5C-21.5,-49,-10.7,-59.7,0.3,-60.1C11.4,-60.5,22.8,-50.7,35.5,-41.2Z;

                                                    M34.2,-37.4C48.6,-28.8,67.2,-22,69.5,-11.9C71.8,-1.7,57.7,11.7,46.2,22.1C34.8,32.5,26,40,15.8,44C5.5,47.9,-6.2,48.5,-17.9,45.7C-29.6,42.9,-41.3,36.7,-54.5,25.7C-67.8,14.7,-82.6,-1.3,-79.2,-12.8C-75.8,-24.4,-54.2,-31.6,-37.9,-39.8C-21.7,-48.1,-10.8,-57.4,-0.4,-56.9C10,-56.3,19.9,-46,34.2,-37.4Z;

                                                    M46.8,-53.3C55.6,-48.4,54.1,-28.9,52.8,-12.8C51.5,3.3,50.4,15.8,43.8,23.4C37.2,31,25.2,33.7,11.7,43.5C-1.7,53.2,-16.7,70.1,-28.8,69.8C-40.8,69.4,-49.9,51.7,-56.8,35.1C-63.7,18.4,-68.4,2.8,-67.8,-13.9C-67.2,-30.5,-61.2,-48.2,-49,-52.4C-36.8,-56.7,-18.4,-47.5,0.3,-47.9C19,-48.3,38,-58.1,46.8,-53.3Z;
                                                    ">
            </animate>
        </path>
     </svg>

Answer: All you did was add one too many ; to the values attribute. If you remove the last one it should work.

  <svg viewBox="-85 -85 170 170" xmlns="http://www.w3.org/2000/svg">
        <defs>
            <filter id="blur">
               <feGaussianBlur stdDeviation="4.8" />
            </filter>
            <linearGradient id="gradient" x1="0%" y1="0%" x2="100%" y2="100%">
                <stop offset="10%" stop-color="#9DB6F2" />
                <stop offset="70%" stop-color="#FF5321" />
                <stop offset="20%" stop-color="#FF2E00" />
            </linearGradient>
        </defs>
        <path fill="url(#gradient)" style="opacity: 1;" filter="url(#blur)">
            <animate attributeName="d" dur="20000ms" repeatCount="indefinite"
                         values="M46.8,-53.3C55.6,-48.4,54.1,-28.9,52.8,-12.8C51.5,3.3,50.4,15.8,43.8,23.4C37.2,31,25.2,33.7,11.7,43.5C-1.7,53.2,-16.7,70.1,-28.8,69.8C-40.8,69.4,-49.9,51.7,-56.8,35.1C-63.7,18.4,-68.4,2.8,-67.8,-13.9C-67.2,-30.5,-61.2,-48.2,-49,-52.4C-36.8,-56.7,-18.4,-47.5,0.3,-47.9C19,-48.3,38,-58.1,46.8,-53.3Z;
 M38.9,-46.9C53,-34.5,69,-24.7,67.4,-14.7C65.8,-4.7,46.7,5.6,36.9,20C27,34.3,26.5,52.7,19.6,56.2C12.8,59.7,-0.3,48.3,-11.3,40.3C-22.3,32.3,-31.1,27.7,-34.4,20.5C-37.7,13.4,-35.5,3.8,-38.3,-11.3C-41.1,-26.5,-48.9,-47,-43.4,-61C-37.8,-75,-18.9,-82.3,-3.3,-78.4C12.4,-74.5,24.7,-59.3,38.9,-46.9Z;

                                                    M25.6,-33.4C38.3,-19.9,57.2,-16.7,65.6,-6.1C74.1,4.6,72.1,22.5,62.9,34.2C53.6,45.8,37.1,51.1,19.7,59.9C2.4,68.7,-15.7,80.9,-24.3,74.4C-32.9,68,-32,43,-36.8,25.6C-41.7,8.2,-52.5,-1.5,-50.6,-8.3C-48.7,-15.2,-34.1,-19.3,-23.6,-33.2C-13.1,-47,-6.5,-70.7,0,-70.7C6.5,-70.7,13,-46.9,25.6,-33.4Z;

                                                    M36.1,-40.2C51.4,-30.3,71.5,-23.2,71.4,-14C71.3,-4.8,51.1,6.5,37.5,13.8C23.9,21.1,17,24.4,6.9,35C-3.2,45.7,-16.5,63.7,-23.2,62C-30,60.3,-30.2,38.9,-33.3,23.9C-36.4,8.9,-42.4,0.2,-46.9,-14.2C-51.4,-28.5,-54.5,-48.6,-46.4,-59.7C-38.4,-70.9,-19.2,-73.2,-4.4,-68C10.4,-62.8,20.9,-50.1,36.1,-40.2Z;

                                                    M35.5,-41.2C48.2,-31.7,62.1,-22.5,70.7,-7.5C79.3,7.6,82.5,28.5,73.4,40.6C64.3,52.6,42.9,55.7,26.4,53.4C10,51,-1.4,43.2,-11.9,37.3C-22.3,31.5,-31.7,27.6,-36.2,20.6C-40.7,13.5,-40.2,3.2,-38.7,-7.1C-37.3,-17.5,-34.7,-27.9,-28.1,-38.5C-21.5,-49,-10.7,-59.7,0.3,-60.1C11.4,-60.5,22.8,-50.7,35.5,-41.2Z;

                                                    M34.2,-37.4C48.6,-28.8,67.2,-22,69.5,-11.9C71.8,-1.7,57.7,11.7,46.2,22.1C34.8,32.5,26,40,15.8,44C5.5,47.9,-6.2,48.5,-17.9,45.7C-29.6,42.9,-41.3,36.7,-54.5,25.7C-67.8,14.7,-82.6,-1.3,-79.2,-12.8C-75.8,-24.4,-54.2,-31.6,-37.9,-39.8C-21.7,-48.1,-10.8,-57.4,-0.4,-56.9C10,-56.3,19.9,-46,34.2,-37.4Z;

                                                    M46.8,-53.3C55.6,-48.4,54.1,-28.9,52.8,-12.8C51.5,3.3,50.4,15.8,43.8,23.4C37.2,31,25.2,33.7,11.7,43.5C-1.7,53.2,-16.7,70.1,-28.8,69.8C-40.8,69.4,-49.9,51.7,-56.8,35.1C-63.7,18.4,-68.4,2.8,-67.8,-13.9C-67.2,-30.5,-61.2,-48.2,-49,-52.4C-36.8,-56.7,-18.4,-47.5,0.3,-47.9C19,-48.3,38,-58.1,46.8,-53.3Z">
            </animate>
        </path>
     </svg>

Comment: A thousand thanks!! it worked

svg are not seen on iphone