Movimento diagonal unity 5

Question: sou iniciante no unity 5, estou tentando criar um jogo 2d, onde quero colocar movimentos diagonais após colisões, atualmente conseguir que meu objeto após colisão seja jogado para cima, mais não consigo de forma alguma fazer um movimento diagonal, minha matriz tem uma escala eixo y(0,6)e(0,-6) eixo x(6,0) e (-6,0), estou trabalhando com 2 objetos um retângulo e um circulo, o circulo fica dentro do retângulo, quando o circulo bate nas paredes do retângulo acontece a colisão e ação. Se alguém puder me ajuda fica grato.
Não tenho nenhum código para diagonal, somente para o pulo para cima.
Código:
using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour
    {
    public Vector2 jump = new Vector2(0,300);
    private Rigidbody2D rb;
    private Transform tmf;
// Use this for initialization
void Start ()
    {
    rb = GetComponent<Rigidbody2D>();
   // tmf = GetComponent<Transform>();

    }

// Update is called once per frame
void Update ()
    {
    clik();
    }

//Dectando colisão de objetos e adicionando ação.
void OnCollisionEnter2D(Collision2D coll)
    {
    if (coll.gameObject.tag == "piso")
        {

            jump.y += 100;
            rb.velocity = Vector2.zero;
            rb.AddForce(jump);

    }
}

//Destruir objeto ao clickar
  void clik()
    {
    if (Input.GetMouseButtonDown(1))
        {
        Destroy(tmf);
        }
    }

}

Answer: Voce está zerando a velocidade com este comando : rb.velocity = Vector2.zero; isto deixa sem condições de ir pra frente ou pra tras .
use  rb.velocity = new Vector2(direcao * speed, rbPlayer.velocity.y);
direcao= 1  Vai pra frente
direcao= -1 Vai pra trás
speed tem que ser maior que zero (0).
Comment: Desculpe  aí, não prestei atenção na data da postagem.
Answer: Voce deve adicionar um valor para o jump.x tambem.
Ele esta com o valor 0 então o objeto só vai se mover em y e voce quer q ele se move em X tb.
Answer: Você não consegue realizar o movimento na diagonal, pois você não esta adicionando valores nas direções da diagonal, ou seja nas direções X e Y juntas, você esta apenas adicionando em Y com o trecho jump.y += 100;, o que falta agora é adicionar valores também em X desta maneira jump.x += 100 ou ainda
/*...*/
{
jump = new vector2(jump.x+100,jump.y+100);
rb.AddForce(jump);
}
/*...*/

Answer: using UnityEngine;
using System.Collections;
public class PlayerControl : MonoBehaviour
{
[HideInInspector]
public bool facingRight = true;         // Para determinar de que forma o jogador está enfrentando.
[HideInInspector]
public bool jump = false;               // Condição para saber se o jogador deve pular.
public float moveForce = 365f;          // Quantidade de força adicionada para mover o jogador para a esquerda e para a direita.
public float maxSpeed = 5f;             // O mais rápido que o jogador pode viajar no eixo x.
public AudioClip[] jumpClips;           // Conjunto de clipes para quando o jogador salta.
public float jumpForce = 1000f;         // Quantidade de força adicionada quando o jogador salta.
public AudioClip[] taunts;              // Conjunto de clipes para quando o jogador se toca.
public float tauntProbability = 50f;    // Possa uma provocação.
public float tauntDelay = 1f;           // Atrasar para quando a provocação deve acontecer.

private int tauntIndex;                 // O índice da matriz de provocações indicando a provocação mais recente.
private Transform groundCheck;          // Uma marcação de posição onde verificar se o jogador está aterrado.
private bool grounded = false;          // Independentemente de o jogador estar ou não ligado.
private Animator anim;                  // Referência ao componente do animador do jogador.

void Awake()
{
    // Configurando referências.
    groundCheck = transform.Find("groundCheck");
    anim = GetComponent<Animator>();
}

void Update()
{
    //O jogador está aterrado se um linecast na posição groundcheck atinja qualquer coisa na camada terrestre.
    grounded = Physics2D.Linecast(transform.position, groundCheck.position, 1 << LayerMask.NameToLayer("Ground"));

    // Se o botão de salto for pressionado e o jogador estiver aterrado, o jogador deve pular.
    if (Input.GetButtonDown("Jump") && grounded)
        jump = true;
}

void FixedUpdate ()
{
    // Cache a entrada horizontal.
    float h = Input.GetAxis("Horizontal");

    // O parâmetro Speed animator é definido como o valor absoluto da entrada horizontal.
    anim.SetFloat("Speed", Mathf.Abs(h));

    // Se o jogador estiver mudando de direção (h tem um sinal diferente para velocity.x) ou ainda não alcançou o MaxSpeed ...
    if (h * GetComponent<Rigidbody2D>().velocity.x < maxSpeed)
        //  ... adicione uma força ao jogador.
        GetComponent<Rigidbody2D>().AddForce(Vector2.right * h * moveForce);

    // Se a velocidade horizontal do jogador for maior do que o maxSpeed ...
    if (Mathf.Abs(GetComponent<Rigidbody2D>().velocity.x) > maxSpeed)
        // ... ajuste a velocidade do jogador para o maxSpeed no eixo x.
        GetComponent<Rigidbody2D>().velocity = new Vector2(Mathf.Sign(GetComponent<Rigidbody2D>().velocity.x) * maxSpeed, GetComponent<Rigidbody2D>().velocity.y);

    // Se a entrada estiver movendo o jogador para a direita e o jogador estiver virado para a esquerda ...
    if (h > 0 && !facingRight)
        // ... flip the player.
        Flip();
    // Caso contrário, se a entrada estiver movendo o jogador para a esquerda e o jogador estiver virado para a direita ...
    else if (h < 0 && facingRight)
        // ... vire o jogador.
        Flip();

    // If the player should jump...
    if(jump)
    {
        // Set the Jump animator trigger parameter.
        anim.SetTrigger("Jump");

        // Play a random jump audio clip.
        int i = Random.Range(0, jumpClips.Length);
        AudioSource.PlayClipAtPoint(jumpClips[i], transform.position);

        // Add a vertical force to the player.
        GetComponent<Rigidbody2D>().AddForce(new Vector2(0f, jumpForce));

        // Make sure the player can't jump again until the jump conditions from Update are satisfied.
        jump = false;
    }
}

void Flip ()
{
    // Switch the way the player is labelled as facing.
    facingRight = !facingRight;

    // Multiply the player's x local scale by -1.
    Vector3 theScale = transform.localScale;
    theScale.x *= -1;
    transform.localScale = theScale;
}

public IEnumerator Taunt()
{
    // Check the random chance of taunting.
    float tauntChance = Random.Range(0f, 100f);
    if(tauntChance > tauntProbability)
    {
        // Wait for tauntDelay number of seconds.
        yield return new WaitForSeconds(tauntDelay);

        // If there is no clip currently playing.
        if(!GetComponent<AudioSource>().isPlaying)
        {
            // Choose a random, but different taunt.
            tauntIndex = TauntRandom();

            // Play the new taunt.
            GetComponent<AudioSource>().clip = taunts[tauntIndex];
            GetComponent<AudioSource>().Play();
        }
    }
}

int TauntRandom()
{
    // Choose a random index of the taunts array.
    int i = Random.Range(0, taunts.Length);

    // If it's the same as the previous taunt...
    if(i == tauntIndex)
        // ... try another random taunt.
        return TauntRandom();
    else
        // Otherwise return this index.
        return i;
}

}
Comment: Qual é a dúvida?

Movimento diagonal unity 5


Show two plots of different natures in same figure with Matplotlib

Question: I'm trying to plot two different plots (one is a simple figure generated by a matrix with a color scale) and the other is a graph with x and y axes from a group of points that represents an skeleton. The matrix color scale is associated with the skeleton graph. It must be shown n times in a loop, at each time that the canvas is closed, then next plot shows.
But I'm only being capable of showing each figure at once, for example,let's say that I must have 43 canvas each one with a graph and a color scale matrix side by  side, instead I'm getting 86 plots, one from the dots graph, the next for the scale matrix, and so on.
The code is below, and so the pictures of each plot. I'm using gridspec to generate the graph, and a simple imgplot to generate the color scale matrix.
from pylab import *
from matplotlib import gridspec
import numpy as np
import sys
import math
import matplotlib.pyplot as plt

movimento = np.loadtxt("file01.txt")
qtd_posturas = int(len(movimento)/20)

c = 0
lista = []
for i in range(qtd_posturas):
lista.append(movimento[(i*20):((i+1)*20),:3])

matrixCoord = np.array(lista)

matrixDistance= np.zeros((qtd_posturas,20,20))
for k in range(qtd_posturas):
    for i in range(len(matrixDistance[0])):
        for j in range(len(matrixDistance[0])):
        matrixDistance[k,i,j] = np.linalg.norm(matrixCoord[k,i,:] -         matrixCoord[k,j,:])

num_plots = qtd_posturas
z = 0
for m in range(num_plots):
  img = matrixDistance[m]
  imgplot = plt.imshow(img)
  imgplot.set_cmap('PuBu')
  plt.colorbar()
  plt.show()
  z += 20
  esqueleto = movimento[:z,:2]
  x = esqueleto[:,0]
  y = -esqueleto[:,1]
  gs = gridspec.GridSpec(1, 2, width_ratios=[3, 1])
  plt.figure()
  plt.subplot(gs[1])
  plt.scatter(x,y, s=50)
  plt.title('Esqueleto')
  plt.show()

Images:
Comment: In the `for` loop you create a new figure at each iteration via `plt.figure()`. Why would you do that? That takes you to a new figure and so you'll twice as many as iterations. Also when looking at the plots, the axes scales don't match so you'll have trouble fitting them on the same axis. Either you need to create new axes or rescale one of them to fit on the existing axis.
Comment: That's what I'm having problems with, I don't know how to reconfigure it properly.
Comment: You don't plot the `imshow` image in the figure with subplots...
Answer: You need to create the figure with subplots at the start of the loop, then plot the graphs in the respective subplots:
for m in range(num_plots):
    gs = gridspec.GridSpec(1, 2, width_ratios=[3, 1])  # create figure at start of loop

    img = matrixDistance[m]
    plt.subplot(gs[0])  # first subplot
    imgplot = plt.imshow(img)
    imgplot.set_cmap('PuBu')
    plt.colorbar()

    z += 20
    esqueleto = movimento[:z,:2]
    x = esqueleto[:,0]
    y = -esqueleto[:,1]
    plt.subplot(gs[1])  # second subplot
    plt.scatter(x,y, s=50)
    plt.title('Esqueleto')
    plt.show()


Not able to retrieve correct file contents using commitID

Question: I'm using the following code to retrieve the file from JGIT repo:
public class JGitPrintContent3
{
    public static void main(String[] args) throws Exception
    {
        File gitWorkDir = new File("D:/jboss/server/repo/Repository/");
        Git git = Git.open(gitWorkDir);
        Repository repo = git.getRepository();

        ObjectId lastCommitId = repo.resolve("b35fd0300270e6ba4d9238a1ab328b25a627885a");//userFile.sql

        System.out.println("Points to : " + lastCommitId.name());

        RevWalk revWalk = new RevWalk(repo);
        RevCommit commit = revWalk.parseCommit(lastCommitId);
        revWalk.markStart(commit);

        RevTree tree = commit.getTree();
        TreeWalk treeWalk = new TreeWalk(repo);
        treeWalk.addTree(tree);
        treeWalk.setRecursive(true);
        treeWalk.setFilter(PathFilter.create("userFile.sql"));

        ObjectId objectId = treeWalk.getObjectId(0);
        System.out.println(" objectId : " + objectId );
        ObjectLoader loader = repo.open(objectId);

        File targetFile = new File("C:\\temp\\gittest\\target2\\" + "userFile.sql");
        OutputStream out = new FileOutputStream(targetFile);
        loader.copyTo(out);
        out.flush();
        out.close();

        System.out.println("Done");
    }
}

But unfortunately it is retrieving the file contents of earlier retrieved (commit Id) contents.
I would be most thankful for your help.
Thank you.
~Shyam */
Comment: See http://stackoverflow.com/a/14856330/305973
Answer: You have hard-coded the commit in your code, so you'll always get that value.
ObjectId lastCommitId = repo.resolve("b35fd0300270e6ba4d9238a1ab328b25a627885a");//userFile.sql

If you want to base it on the current branch then use repo.resolve("HEAD")
Also note that your RevCommit is unnecessary here; if you want to get the current tree instead, use repo.resolve("HEAD^{tree}") instead.
Comment: Thank you so much for you reply AlBlue. ...Actually i am trying to retrieve the content of the commitId "b35fd0300270e6ba4d9238a1ab328b25a627885a" Object.  But id does not work properly and fetching earlier commitId contents for previous commitId of the same file name Object in the repository.


Full system backup on a remote server with Borg

Question: I'm trying to do a full system backup on my remote server. I want to use Borg for this process because it has deduplication so it only copies files that are different and thus doesn't use as much space as a regular backup. Currently I'm using the command that follows:
sudo borg create --stats --progress --one-file-system --compression lz4 backup::Monday /run/media/archie/server/{bin,boot,etc,home,lib,lib64,opt,root,run,sbin,srv,tmp,usr}

This doesn't look like an optimal solution so how can I make it better? Or is there any other tool with deduplication for this job?
Comment: What is the problem you are having?
Comment: It looks messy and I don't think this is an optimal solution.
Comment: Huh? Where is the messy bit? Where is the not optimal bit?
Comment: {bin,boot,etc,home,lib,lib64...} bit is quite messy and if there were to be other files added this script won't back them up.
Answer: I've solved the problem with this script:
borg create --stats --progress --compress lz4 --one-file-system \
    --exclude $SERVER/dev \
    --exclude $SERVER/mnt \
    --exclude $SERVER/proc \
    --exclude $SERVER/run \
    --exclude $SERVER/swapfile \
    --exclude $SERVER/tmp \
    --exclude $SERVER/sys \
    --exclude $SERVER/lost+found \
    $BACKUP::$DAY $SERVER


An application of Rouché's theorem

Question: i need help to proof the next:
Let $f$ be analytic at $D$ minus a finite numbers of interior points where $f$ has poles. Show that if $0<|f(z)|<1$ over $\partial D$, then the number of poles of $f$ in $D$ is equal to the number of roots of the equation $f(z)=1$ in $D$.
I have tried to prove it using Rouché's theorem, but i cannot conclude anything , I would appreciate your help.
Comment: write $1-f=g/h$ with $g,h$ analytic in the (closed) unit disc (in a minimal way so $g,h$ do not share zeroes) and then $0< |1-g/h| <1$ on the boundary so $g,h$ have the same number of zeroes (counted with multiplicity) in the unit disc; the zeroes of $g$ are the solutions of $1-f=0$ and the zeroes of $h$ are the poles of $f$
Answer: HINT: Use the argument principle for $g(z)=1-f(z)$. What is the image of $\partial D$ under $g$?

An application of Rouché's theorem


WordPress uploads pointing to test server

Question: I just took over an older developer and I been trying to make changes to a WordPress page but I just noticed that the uploads are pointing to his test server, so instead of being
http://mywebsite.com/wp-content/uploads/2011/10/sampleimage.jpg
all the images and uploads are
http://172.20.201.879/wp-content/uploads/2011/10/sampleimage.jpg
What can i change from the back end so it points towards the correct place. The content is there is just the wrong path.
Another question is, can I find out which server was he using? I been trying to update but the server information he gave me is completely wrong.
Comment: If you have access to your db via phpmyadmin or similar, you can run this code `UPDATE \`wp_posts\` SET \`guid\` = REPLACE(\`guid\`, '172.20.201.879' , 'mywebsite.com');` to replace the website address.
Comment: did you try changing the site address in settings -> general ?
Comment: That won't change links in db
Comment: @Eugen I ran the query and it worked, the problem is that the page still is looking for the images at `http://172.20.201.879/...` and not at `http://mywebsite.com/`
Comment: Nevermind I had to change the code in the theme but now finally go it to work, but god knows I have many changes to it.
Answer: I would suggest this: https://interconnectit.com/products/search-and-replace-for-wordpress-databases/
Find the old url's: 172.20.201.879/
Replace with: mywebsite.com/
EDIT
The reason to use this tool over manual database edits is because of how Wordpress likes to store data in serialized strings. If you edit a serialized string, without changing the additional size delimiter, you will have a corrupt string.
Answer: From @Eugen:
If you have access to your db via phpmyadmin or similar, you can run this code UPDATE wp_posts SET guid = REPLACE(guid, '172.20.201.879' , 'mywebsite.com'); to replace the website address.


Get Claims from Extended UserClaim Table in Web Api using Microsoft Identity

Question: i am working on ASP.Net 5 , web api project and using Microsoft Identity and jwt token based for my security management . I have already extended the user claim table and add a new row of isSelected to this table . I need to know , how can i just get the claims that has the isSelected == true from the table , is there any way that i can use the _signinManager services for this task? I can do like this for normal situation :
var claims = await _signinManager.ClaimsFactory.CreateAsync(user)

and get the ClaimPrincipals , but this will return all the claims whether the isSelected is true or false .
Thank you!
Answer: Some behaviors require customization. Like in your case, you want the default configuration to filter list of data based on a particular column name (isSelected) and only return the filtered list. The best way to approach this using a customized UserManager or SignInManager and create a method that will do just what you're asking for.
Here's an idea:
Create a method called IList<UserClaim> GetUserClaimsBasedOnSelection(bool isSelected, User user). All that this method should do is use the underlying Claims retrieving method and just filter that list to only return the selected claims. That's it. And then after you just register your configured SignInManager inside Program.cs or startup.cs by adding this service to your AddIdentity service configuration .AddSignInManager<YourSignInManager>()


Overlap Probability of Empirical Distributions

Question: I have a load versus capacity problem, and I'm trying to determine the likelihood of failure. Here's a simple example of what I mean.
I have load and capacity discrete pdfs that were determined through a series of computer calculations that analyzed different input values (Monte Carlo simulations to address uncertainties). The figures below are a simplified version of the output:

As you can see, there is some amount of overlap between the two. I am trying to determine the probability that the system will fail (i.e., the load with exceed the capacity).
Is this as simple as integrating the overlapping area of the empirical cdfs and multiplying, or am I looking for something more complicated, like a Bhattacharyya coefficient?
Answer: Unfortunately, I don't think you can really answer this question accurately without knowing a bit more about what drives load and capacity variability.
Consider the case of load and capacity in the electrical grid.  In the middle of the day in the summertime, as businesses have all their lights turned on and everybody is running their air conditioning, the load (the number of megawatts that people are demanding) soars.  On the other hand, at 3:00 a.m. on generally any day of the year, as almost everyone is asleep, load falls.  In spite of this fluctuating load problem, in developed countries at least, you almost never see a situation where load exceeds capacity (which would manifest as either a brownout or a rolling blackout).  Why is this?
It's because in the electrical grid, load and capacity are tightly correlated over time.  Engineers deliberately start up and shut down power plants, or subsections of power plants, in anticipation of time-varying changes in demand.
If your systems behaves in a similar way, it's not enough to simply calculate the overlap between the two overall accumulated static distributions.  Instead, you need to Monte Carlo both factors simultaneously, and look for individual instances (i.e., individual "rolls" of the Monte Carlo dice) where load exceeds capacity.  This is because, if the random factors in the Monte Carlo lead to correlated variability in both the load and capacity (or for that matter, anti-correlated variability as well) the probability of system failure will be different than just a simple pdf overlap calculation would suggest.
Comment: Ah, O.K., I see.  Then in that case, I think it is just the overlap in probabilities that you will want.  Since you're already doing a numerical simulation anyway, you can simulate this part easily as well, by simply taking random draws from each of the sample distributions that you have pictured, and counting the relative frequency (over many experiments) with which load exceeds capacity.
Comment: Thanks stachyra, I understand your comments. However, I think in my case the variables that effect the load are independent of those that influence capacity. I'm actually looking at a power plant, so your comments are well taken, but the problem is a little different. The load (plant temperature) is determined by environmental effects, but the capacity of a material to withstand that temperature is a product of uncertainties related to manufacturing. So uncertainties exist related to both the load and capacity, but they are not correlated.
Comment: Thanks again, let me see if I understand correctly. Rather than trying to asses the overlap failure probability from the final empirical distributions, I can take a load simulation output and compare it to a capacity simulation output directly. If I repeat this many times (which I'm already doing to develop the distributions), it should approach the actual failure probability with a large enough sample size ("actual" within the confines of my model). That makes sense.
Comment: Yes, I believe the procedure that you have outlined should estimate the failure probability correctly.


Passar valor de uma página para input de outra

Question: eu tenho uma página html onde o usuário digita o email e eu realizo a verificação. Caso aquele email não esteja no banco de dados, é um novo usuário e portanto, redireciono para a página de cadastro.
Na página de cadastro quero que o campo email venha já com o email digitado na página anterior. Como faço?
página 1

página 2

    $( document ).ready(function() {
           $("#id_email").val("firstname.lastname@example.com");
 });

Comment: Manda por sessão ou querystring.
Comment: A ideia é mandar por sessão mesmo, mas não sei como fazer, estou aprendendo
Comment: Que linguagem está utilizando?
Comment: Python usando Django
Comment: Não sei nem uma linha de Python. Sorry!
Answer: Você poderia tentar da seguinte forma.

<input type="hidden" name="volposition" value="{{ request.REQUEST.email }}">

Levando em conta que você faz na action o post pra enviar a outra pagina.
Answer: Você pode usar sessionStorage, dessa forma o navegador vai salvar uma sessão com seus dados e você pode recuperar em qualquer pagina.
Pagina 1
<input type="text" id="email">

Pagina 2
<input type="text" id="RecuperaEmail">

Ou pode fazer isso com jQuery
Pagina 1
<input type="text" id="email">

Pagina 2
<input type="text" id="RecuperaEmail">

Comment: Obrigada Rafael, consegui resolver!


Ionic 4 getUserMedia NotAllowed in ionic-webview

Question: This happens in android build of ionic app.
I am using a iframe to test the getUserMedia.
The demo page of webrtc gives me "GetUserMedia : Not Allowed Error".
I have given all permissions in AndroidManifest.xml, but still couldn't access the camera. is there anything else needs to be done, for getting camera access for external website?
home.html
<ion-content class= 'padding has-subheader'>

</ion-content>

config.xml
<plugin name="cordova-plugin-statusbar" spec="2.4.2" />
<plugin name="cordova-plugin-device" spec="2.0.2" />
<plugin name="cordova-plugin-splashscreen" spec="5.0.2" />
<plugin name="cordova-plugin-ionic-webview" spec="^2.0.0" />
<plugin name="cordova-plugin-ionic-keyboard" spec="^2.0.5" />
<plugin name="cordova-plugin-camera" spec="^4.0.3" />
<plugin name="android-camera-permission" spec="^1.0.0" />
<plugin name="cordova-plugin-media" spec="^5.0.2" />
<plugin name="cordova-opentok-android-permissions" spec="^1.0.1" />
<plugin name="cordova.plugins.diagnostic" spec="^4.0.10" />
<plugin name="cordova-plugin-android-permissions" spec="^1.0.0" />
<plugin name="cordova-plugin-media-capture" spec="^3.0.2" />
<plugin name="cordova-plugin-compat" spec="^1.2.0" />
<plugin name="cordova-plugin-whitelist" spec="^1.3.3" />
<engine name="android" spec="7.0.0" />

Comment: Please see below. Primarily the iframe permissions allow="camera" and the CORS headers.
Comment: Possible duplicate of [Does getUserMedia works in ionic-webview in Android app?](https://stackoverflow.com/questions/52557767/does-getusermedia-works-in-ionic-webview-in-android-app)
Answer: Flagged as a duplicate of: Does getUserMedia works in ionic-webview in Android app?
Nevertheless I have copied and pasted my answer below

Update - 19/11/2020
WKWebView can use getUserMedia in iOS 14.3 beta 1.

https://bugs.webkit.org/show_bug.cgi?id=208667
https://bugs.chromium.org/p/chromium/issues/detail?id=752458

Update - 04/11/2018 - Working Ionic example
As promised I had a crack at this today. To answer your question now in full: Yes you can access getUserMedia inside of ionic on Android.
See my GitHub project here for a working example and for screenshots.
See this feature branch here which successfully tests getUserMedia inside of an iframe
Steps involved:

Install Ionic
ionic start getUserMedia blank
cd getUserMedia
ionic cordova plugin add cordova-plugin-android-permissions
npm install --save @ionic-native/android-permissions
npm install webrtc-adapter --save
link to adapter in angular.json scripts (link)
Add AndroidPermissions to app.module.ts provider (link)
Create camera access code in home.component.ts (link)
Add android manifiest permissions to config.xml and AndroidManifest.xml (link, if the config doesn't copy go to platforms/android/app/src/AndroidManifest.xml)
ionic cordova platform add android
ionic cordova build android
ionic cordova run android

You can also see alternative versions of this for React Native, native Android and Cordova.
As of this update support for iOS is still a no due to Apple security restrictions on WKWebView and UIWebView.
Iframes: To make sure getUserMedia works inside of them make sure you:

CORS of the embedded site need to have the allowed access origin header
enable security permissions to access the camera and microphone

Please read the following for more info on iframe features:

https://www.chromestatus.com/feature/5023919287304192
https://bugs.webkit.org/show_bug.cgi?id=167430
https://dev.chromium.org/Home/chromium-security/deprecating-permissions-in-cross-origin-iframes
https://bugzilla.mozilla.org/show_bug.cgi?id=1389198
https://github.com/instructure/canvas-lms/issues/1219

Yes, it theoretically can work. See my example below on how to do it in Android. For iOS this isn't currently possible due to the limitations of WKWebView.  I have linked to a StackOverFlow question below on how people are achieving this on Cordova which Ionic is based off.
The core main steps which need to be achieved to get getUserMedia working on Android regardless of framework are:

Make sure your app is Android API 21 and above
Add permissions to Manifest (link to file)
Make sure you use getUserMedia adapter for API compatibility
Make sure you add webrtc to the Android project gradle file (link to file)
Override Chrome WebView permissions to grand access (link to file example, line 106)
On app start ask user for permission to access the camera.

The issue you are specifically facing is 4. or 5. It looks like the project gets you that far. The permission error is most likely down to the Chrome WebView your app is using doesn't override the permission, and/or it is and the user hasn't manually enabled the permission.
Thus within the Ionic framework you need to extend its Browser to get access to the override onRequestPermissionsResult. To do this you need to make a Cordova plugin and then create the Ionic bindings.
More reading about this for similar frameworks can be found here:

Why CordovaWebViewClient not working in Cordova 6 anymore
https://github.com/marcusbelcher/rn-getUserMedia-test
https://github.com/marcusbelcher/android-getUserMedia-test
Cordova version of this question: NotReadableError: Could not start source
Progressive Web App: Error Accessing navigator.mediaDevices.getUserMedia?
Comment: @Moritz Done! I tried before and apparently I wasn't ranked high enough ;)
Comment: Ahh, checkout https://github.com/marcusbelcher/android-getUserMedia-test
Comment: If you have your own app you need to handle the permissions for your app to gain access to the camera, mic, and chrome permission callbacks. If you are in someone else's app e.g. Facebook you need to ask them to handle this. if this is in another browser it may be down to browser or emulation compatibility.

If the above doesn't help I  will need more info here to assist. Feel free to drop me a DM.
Comment: Tried multiple times but keep getting: `Browser API navigator.mediaDevices.getUserMedia not available`
Comment: @askar have you included the WebRTC adapter (https://www.npmjs.com/package/webrtc-adapter)? Have you checked for Browser compatibility ( https://caniuse.com/?search=mediaDevices)?
Comment: thank you for a quick response. yeah I included `webrtc-adapter`.  also if I run via browser on the phone it is working.  as soon as I run natively via `Android studio` on my Pixel4 I get that error.


Disable Undefined Property error in PHP Devsense extension on VSCode

Question: I just added the PHP extension by Devsense to my VSCode and now it's lighting up like a Christmas tree. I want to disable the Intellisense option for unknown/undefined properties.
Here is the issue
and the error message
Undefined property: MY_Model::$load PHP(PHP0416)
And a link to the post where they talk about adding it
I saw some options for Intelliphense where you could set "intelephense.diagnostics.undefinedProperties": false
in the vscode settings.json, but I couldn't find anything that would work for this extension.
The fix described here in the 3rd post to add the property in a comment does work, but is not feasible in the codebases I am working in. I need something more like the second post, where I can just disable the check altogether
Answer: 1 - Open Settings.json :  ctrl + shift + P  and type 'settings.json'
2 - Select 'Open User Settings (JSON)
3 - At the end of file, add this code:
"php.problems.exclude" : {
  "/" : [416],
  "vendor/" : true,
}

Answer: I found the answer to my own question. Leaving it here because It took me way too long.
You just have to exclude the error code, in this case error code 0416


create jquery infinite animation not using recursion?

Question: How to use jquery to create infinite animation,
BUT NOT using recursion way?
The recursion solution I found: jQuery .animate() callback infinite loop
The problem of using recursion is:
while animating, the browser tab of currrent page will take MORE and MORE memory.
Comment: did you actually verify that it takes up more and more memory
Comment: Why not using CSS animation?
Comment: Please show the code you are using.
Comment: @Foon I opened my page in chrome an using chrome task manager to check it (shift + esc), the memory of that page keep increasing per sec.
Comment: @charlietfl I was using the same pattern following: http://stackoverflow.com/questions/6461945/jquery-animate-callback-infinite-loop
Comment: @A.Wolff Nice Suggestion. I knew CSS animation, just looking for a jquery  way. Curiosity ^_^
Comment: @Littlee we shouldn't have to go to other links to see the code you are using
Comment: The code used, from the linked question, may look recursive but it is not actually *stack-based* recursive. See my answer below. If you have a memory leak it will be down to something else going on. Don't be fooled into changing a very simple animation pattern into something more complicated.
Answer: You have actually made a mistake in assuming that the code is "recursive". It is not recursive. Your comment that "the browser tab of current page will take MORE and MORE memory." is not because of any recursion in that code. If you have a memory leak per second (as per your comments), then the problem lays elsewhere.
The instances of the code actually run sequentially and not via nested stack calls (i.e. linear and not recursive).
Using the most basic example you linked to:
function start() {
    $('#element').animate({}, 5000, 'linear', start);
}
start();

here is what actually happens:

A function called start is defined and then called once
Inside start, an animation operation is started, then start immediately exits!
The animate just adds information to a single animation queue for the element, then returns.
The animation queue is processed step by step by a separate process (single timer etc).
When the queued entry has met its expected end state, it calls the callback - The global start function stored in the queued entry.
That simple adds another entry on the animation queue and exits.

Basically the code looks recursive, but as the operations are async, via a queue, it is not recursive. I don't know if there is an official name for these, so I just call them chained callbacks.
Comment: [I've heard](http://stackoverflow.com/a/29456618/1048572) the term "pseudo-recursion" for it. Basically, it *is* recursion, but a call-stack optimised one (like tail calls).
Comment: @Bergi: Call me old-school, but that does not meet my definition of recursion (code actually calling itself). In this instance a separate process is working through the queue.
Comment: Oh, I'm coming from a functional programming background, where you don't care about "calls" at all and more about structure. It definitely is a recursive approach :-)
Comment: @Bergi: Fair enough. His question implied concerns about "growing memory usage", which implied stack-based recursion, rather than the problem being recursive in nature, hence my answer.
Comment: @TrueBlueAussie regardless of what theories you have,  the code you provide here causes the memory usage to quickly increase for that tab.  My solution above is a little better, but still eats memory.
Comment: @NotoriousPet0: the code was for description only from the other answer and not intended as a code solution at all. As I stated any memory leak will be down to other issues and it is those that need to be addressed.
Comment: Yeah but your defending that code saying its not going to cause a problem, and it does.  so you are wrong.   its ok some people cant admit that and will make excuses til time ends.   I tested this on bare code base, just this an djquery.   and on js fiddle,  both have same speed of memory increase.
Comment: @NotoriousPet0: feel free to provide the test code to which you refer. I do not need to defend this answer as it is technically correct. Any memory issues are a side-effect of other issues (to be determined) and not the assumed stack-based "recursion". That is my one and only point: further investigation is required to identify the actual problem.
Comment: No, it's not.  You can check the other tabs and see there is no leak.  You can run one tab with the code, and one tab without the code.  If memory is leaking, you can be sure it's the code.  Are you even a developer?  This is basic.   See my answer for test code.
Comment: @Notorious Pet0: While you provide alternatives, your answer does not explain why the original code is leaking. Sorry your answer was accepted but not up-voted, but I really do not have more time to waste when I was purely explaining the misunderstanding the OP had about recursion in this instance. FYI SO profiles have a little link to give further information about those you wish to insult. Probably worth a check to avoid further embarrassment :)
Answer: UPDATED WITH TEST RESULTS
Conclusion...   All methods burn up the same amount of memory and it eventually gets released, doesn't keep building forever so not really an issue.
Example 1
This is the code the OP originally had a problem with memory usage increasing in Chrome.
(function($){
    $(function(){  //document.ready

        function start() {
                $('#animate').animate({'margin-left':'150px'}, 1000, function () {
                    $(this).animate({'margin-left':'50px'}, 1000, 'linear', start);
                });
        }
        start();

    });
})(jQuery);

Example 2
Current solution including a callback as requested by Bergi to avoid potential "drifting" in setinterval.
(function($){

    $(function(){  //document.ready

    });

    (function customSwipe(element) {
        element
            .animate({"margin-left" : "150px"}, 1000)
            .animate({"margin-left" : "50px"}, 1000, function(){
                setTimeout(function(){
                    customSwipe(element);
                }, 2000);
            });
    })($('#animate'));

})(jQuery);

Example 3
Original Answer I gave, using setInterval()
(function($){
    $(function(){  //document.ready

            setInterval(function(){
                    $("#animate").animate({'margin-left':'150px'},1000);
                    $("#animate").animate({'margin-left':'50px'},1000);
            },2000);

    });
})(jQuery);

Skeleton w/ Jquery
Empty page w/ only the #animate element
(function($){
    $(function(){  //document.ready

    });
})(jQuery);

DATA AFTER TAB OPEN FOR 10 MINUTES
CODE            STARTING    ENDED
Example 1       14.300k     19.996k
Example 2       14.300k     20.020k
Example 3       14.300k     20.344k
Skeleton w/ jQuery  14.300k     15.868k

Interesting that the code that did nothing still increased usage slightly.   These values go up and down as memory is used and released.  Another thing would be to use the "purge memory" button in task manager to see how much of that used memory is garbage waiting to be collected.
DATA AFTER 25 MINUTES
Example 1       14.300k     18.640k
Example 2       14.300k     18.724k
Example 3       14.300k     18.876k
Skeleton w/ jQuery  14.300k     15.868k

Conclusion...   All methods burn up the same amount of memory and it eventually gets released, doesn't keep building forever so not really an issue.
So just using the most solid, sound code would be the best option,  Example 2 would be my choice.
UPDATED USING CALLBACK
Have you tried using setTimeout with $.animate()?
(function($){
    (function customSwipe(element) {
        element
            .animate({'margin-left':'150px'}, 1000)
            .animate({'margin-left':'50px'}, 1000, function(){
                setTimeout(function(){
                    customSwipe(element);
                }, 2000);
            });
    })($('#animate'));

    $(function(){  //document.ready

    });

})(jQuery);

Remove the setTimeout() if you don't need it to delay between animations.
JSFIDDLE of the above code working...
You might also want to look into this for more intricate animations.
http://api.jquery.com/jquery.fx.interval/
Conclusion...   All methods burn up the same amount of memory and it eventually gets released, doesn't keep building forever so not really an issue.
What you are seeing in the Chrome TM is every time it fires the animation,  that much memory is requested and the OS "commits" that memory to chrome for the operation.   Once the operation is completed, the memory is still committed.  At some point Chromes garbage collector comes along and releases that memory and your usage stats will drop back down.  So you will see the memory going up and down if you watch it long enough.
You can put --purge-memory-button at the end of your Chrome command line to have a Purge Memory button available in Chrome TM.   This might help you to see how much memory is actually waiting to be released.
Hope this answer helps you and maybe some others.
Comment: this is not really a useful answer. `setInterval` may drift, and when it does get a bit faster than the actual animation you really start filling up memory. To know when the animation has finished, use callbacks, that's what they are for.
Comment: @bergi do I really deserve a downvote for that?   I didn't get an upvote from the OP in the first place.  Plus OP marked it correct.  Meaning it worked for them, so the "*Possibility*" of drifting, which is remote,  doesn't affect his implementation.  Please remove downvote.  Thanks.
Comment: If you went around downvoting everyone who had a solution with an obscure possiblity of some rare failure happening, then you'd be downvoting all day, but hey, maybe that's what you do.  I personally have better things to do than hate on people trying to help others.
Comment: Yes, I think it deserves a downvote because I consider it a bad practise (And it's not only drifting, but also readability and maintainability, what if someone changes `1000` to `1500` but misses to adjust `2000`?). It doesn't matter whether OP upvoted or not, or whether he accepted it. I'm not hating around, and my votes are not personal. It's just when I come across a good answer, I upvote it, and when I come across a bad answer I downvote and comment what is wrong/could be improved from my pov.
Comment: @Littlee I updated this answer with a better solution.
Comment: Thanks, yes. Though the `setTimeout` isn't really needed any more for what OP wanted to do.
Comment: @bergi, he did ask for one not using recursion, which is probably why i didn't use the callback.  Do you know if this will keep increasing used memory in the browser tab (as OP describes) the way I have set it up now ?
Comment: Uh, `setTimeout` still has a callback… And passing a callback directly to `animate` is recursive neither, see TrueBlueAussie's excellent answer.
Comment: @bergi,  i meant on the code you didn't like.  which is probably still the best solution for the OP.  The code above continues to increase memory usage in chrome task manager.


Java String Scanner nextline input string not as expected

Question: I have a simple program run in the console which accepts inputs, creates objects based on these and saves those objects into a list. If however a "x" is entered, the function stops.
public static void input(List<Things> slist) {
    String strA = new java.util.Scanner(System.in).nextLine();
    if(!xcheck(strA) {return;}
    Things s = new Things(strA);
    slist.add(s);
}

public static boolean xcheck(String xStr){
if(xStr == "x"){
        return false;
    } else {
        return true;
    }
}

The problem is that the function xcheck never returns false. It does recognise that the input string contains "x" (xStr.contains("x")), but it doesn't seem to think that the input is only "x", even though when ouptutting the string into the console, it definately only outputs the "x" without anything else and the length of the String is 1.
Comment: What does this have to do with C++?
Comment: possible duplicate of [How do I compare strings in Java?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java)
Answer: Strings are comared with equals not ==.
Try:
public static boolean xcheck(String xStr){
if("x".equals(xStr)){
        return false;
    } else {
        return true;
    }
}

Comment: It may not even be worth the time to answer these; it's all explained pretty well in http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java.
Answer: Use xStr.equals("x") instead of xStr == "x".


Factorize $x^4 + 4x^2 +1$ over $\mathbb{F}_{29}$

Question: How do I factorize $x^4 + 4x^2 +1$ over $\mathbb{F}_{29}$?
I checked that the discriminant $D = 16 -4 = 12$ is not a square ($12^{14} = -1 \mod 29$) so this polynomial has no roots. Therefore it's either irreducible or is a product of two polynomials of degree $2$.
In theory I can find all irreducible polynomials of degree $2$ but $29$ is too big to do it by hand so what do I do?
Comment: Write it as a product $(x^2+ax+b)(x^2+cx+d)$ and compare the coefficients. There is a solution to the resulting equations: $a=20$, $b=-1$, $c=9$, $d=-1$.
Comment: A tip for a quicker solution: The polynomial $f(x)=x^4+4x^2+1$ has only even degree terms, so $f(-x)=f(x)$. So if $f(x)=g(x)h(x)$ is a factorization, $f(x)=g(-x)h(-x)$ is another. But factorization into irreducibles is unique. So either $g(x)=g(-x)$ (a case your discriminant calculation ruled out, do you see why), or $h(x)=g(-x)$ (looking for quadratic factors $g,h$). So you only need to consider factorizations of the form (building on Dietrich's comment):
$$f(x)=(x^2+ax+b)(x^2-ax+b).$$
Only two unknowns now.
Comment: `Factor[x^4 + 4*x^2 + 1, Modulus -> 29]` Mathematica code shows the result is $\left(x^2+9 x+28\right) \left(x^2+20 x+28\right)$
Comment: (cont'd) Admittedly the symmetry between the factors also follows easily from just expanding their product. Not relevant this time, but the case $g(-x)=g(x)$ would make you look for a factorization like $f(x)=(x^2+a)(x^2+b)$. This trick has recurred many times on the site already, searching for them may not be straight forward, but hopefully not too taxing either.
Comment: In his answer (+1) Mike uses automagically the consequences of the even/odd symmetry in relating the coefficients of the linear terms of the two factors, but could have saved one step by using it for the constant terms also even though he arrived at that conclusions rather speedily :-)
Answer: All operations below in this post are done in the field $\mathbb{F}_{29}$.
Write $x^4+4x^2+1 = (x^2+bx+c)(x^2-bx+d)$. [why can $x^4+4x^2+1$ be written this way]. Then doing out the multiplication yields
$$c-b^2+d=4$$
$$bc-bd = 0$$
$$cd = 1.$$
Now the equations $cd = 1$ and $c-b^2+d = 4$ together yields $b \not = 0$ [why is that] and thus the equation $c = d$. Thus plugging these into the above yields:
$$2c-b^2 = 4$$
$$c = d$$
$$c^2 = 1.$$
Now, one can check that $-2$ is not a square in $\mathbb{F}_{29}$ so the equation $2c-b^2 = 4$ has no integral solution where $c = 1$. However, for $c = d = -1$ the equation $-b^2 = 6$ has the solution $b = 9$. So to conclude, plugging in $b=9$ and $c=d=-1$:
$$x^4+4x^2+1 = (x^2+bx+c)(x^2-bx+d) = (x^2+9x-1)(x^2-9x-1).$$


form_set_error not working in node form validation

Question: I'm frustrated right now. This very reduced module code shows the problem:
<?php

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ('pic_node_form' == $form_id && !path_is_admin(current_path()) ) {
    $form['#validate'][] = '_mymodule_pic_add_form_validate';
  }
}

function _mymodule_pic_add_form_validate($form, &$form_state) {
  form_set_error(null, t('Keep calm bro'));
  // die("foo");
}

function mymodule_node_validate($node, $form, &$form_state) {
  form_set_error(null, 'test');
  // die("bar");
}

pic_node_form is the node add form for the content type pic. That form is exposed (hence && !path_is_admin(current_path())). There is an image upload field involved.
The form_set_error doesnt do anything and nodes keep getting submitted. The die() functions actually work when I remove the //, so the functions do get invoked.
The form itself is placed via block:
function _mymodule_get_block_content($delta) {
  if ('pic_add_form' == $delta) {
    global $user;
    module_load_include('inc', 'node', 'node.pages');
    $node = (object) array(
      'uid' => $user->uid,
      'name' => (isset($user->name) ? $user->name : ''),
      'type' => 'pic',
      'language' => LANGUAGE_NONE,
    );
    $form = drupal_get_form('pic_node_form', $node);
    $form_rendered = drupal_render($form);
    $markup .= $form_rendered;

    return $markup;
  }
}

Any ideas what I am doing wrong?
Comment: I guess that you have to set the `$name` (first) argument of the [form_set_error](https://api.drupal.org/api/drupal/includes!form.inc/function/form_set_error/7) function to a field name instead to `null`.
Comment: @mchar post your comment as an answer
Answer: If you check the source of form_set_error(), you will see that if you don't supply the name of the form element for which you are setting the error, error messages will not be set.
As long as the first argument is NULL, form will be submitted. Your code was being executed, but it didn't stop the submission.
What you need to do is to pass the name of the field for which you want the error to show. This goes as the first argument for form_set_error().
Example:
form_set_error('YOUR_FIELD_NAME', t('Your message'));

Comment: i feel so dumb right now :) still, I dont think this is nicely solved by Drupal
Answer: I guess that you have to set the $name (first) argument of the form_set_error function to a field name instead to null.


JQuery .click not working as I expected

Question: I have a question about the .click function in Jquery. I have this code:
for (var i = 0; i < 5; i++) {
    var divTest = $('

');
    divTest.text("My Div " + i);
    divTest.click(function() {
        alert("Alert: Div " + i);
    });
    $('#myTest').append(divTest);
}

I expected to add five divs to the "myTest" element and for each div the onclick function would show an alert with the corresponding div number.
The divs were added properly, but when I click on the divs I always get the alert with the text: "Alert: Div 5". Why? What I have to change to generate the behavior that I'm expecting?
Here is my jsFiddle: http://jsfiddle.net/BKFGm/2/
Answer: In this case you should use closure:
(function(i) {
    divTest.click(function() {
        alert("Div: " + i);
    });
})(i);

DEMO: http://jsfiddle.net/BKFGm/4/

Another option is to pass i in the eventData map:
divTest.click({ i: i }, function(e) {
    alert("Div: " + e.data.i);
});

DEMO: http://jsfiddle.net/BKFGm/11/
Comment: Note that you're creating a new function object for each iteration, which may cause performance issues when there is a large number of iterations. A declared function would provide better performance in that case.
Comment: OH I see. I didn´t know this term. Thanks for your time! I'll accept as soon as possible.
Comment: @FabrícioMatté Agreed with your first note. Maybe `eventData` is a good alternative for such cases.
Answer: Once again, a classic case of closures. i keeps getting incremented, whereas you want to anchor it in the click event. Try this:
for( i=0; i<5; i++) {
  (function(i) {
    // your code that depends on `i` here
  })(i);
}

Comment: OH I see. I didn´t know this term. Thanks for your time! Its working now =D
Answer: This is a scope issue. Also, it's a very commonly asked question here.
The simple fix:
for(var i = 0; i < 5; i++){
     var divTest = $('

')
         divTest .text("My Div " + i);

    (function(index){
        divTest .click(function () {
             alert("Div: " + index);
                    });
    })(i);

        $('#myTest').append(divTest);
}

Answer: When the Alert happens, the variable i is already set to 5.
Answer: .click works in a different scope than your cycle and it is undefined when your click handler is executed, unless you have an other i variable on the global scope.
Answer: You can also try this
$(function() {
    for(var i = 0; i < 5; i++){
        var divTest = $('
', {
            'text':"My Div " + i,
            'click':(function(i){
                return function(){
                    alert("Div: " + i);
                }
            })(i)
        });
        $('#myTest').append(divTest);
    }
});

DEMO.

JQuery .click not working as I expected


C# 8 non nullable references and implicit usage

Question: In Resharper and Rider, there is the Jetbrains.Annotations attributes which can be applied to types and fields that are used implicitly.
e.g. if you define a data contract/DTO of some sort, you can decorate that with [UsedImplicitly] and Resharper will know to not flag this field as not used.
But, in C# 8. if you use the Nullable Ref Types feature.
Any non nullable field of such type will be flagged as "Never initialized" if you don't explicitly set those fields to non null values.
Is there some way to tell the C#8 compiler that "hey, ignore this, just trust me on this one" ?
e.g.
Assume we have a request message such as this, maybe it is passed to an ASP.NET endpoint or similar.
class LoginRequest
{
    public string UserName {get; set;}
}

The compiler will complain that UserName is never initialized, which it isn't because it is initialized by a web client. e.g. a SPA app.
What is the correct way to suppress such warning?
Comment: This post would be clearer with a code example.
Comment: You can suppress warning as suggested by visual studio
Comment: Does this help: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/null-forgiving
Answer: You can use #nullable disable in the context.
Answer: You can initialize it with a null value that is marked as being non-null:
public string UserName { get; set; } = null!;

This seems strange at first but is a pretty straightforward way of declaring that something may technically be null for a short time, but is known not to be when actually used.


How to add new content using a content type added after taxonomy access control was installed?

Question: I have added some content types to Drupal to store some custom content.
Then I installed the Taxonomy Access Control module to manage the access rights. At this point everything was working perfectly and easily.
Then I added a new content type but when I try to "add a new content", this content type doesn't appear in the list of content types.
Is this because of the Taxonomy Access Control module? Do I have to re install it?
Note: I also flushed the cache and performed "rebuild permissions". It appears in the admin/content type filter. but if i add content, no trace of it.
Comment: and you  try this with the user 1 (uid=1)?
Comment: Yes. I used the user 1 and with others with rights to create content.
Comment: Are you sure the new content type got created? Does it show up in `/admin/content` [Type filter](http://i.stack.imgur.com/V8FvR.jpg)?
Comment: Did you try flushing the cache?
Comment: What i did : - flush the cache and rebuild permissions. It appears in the admin/content type filter (i didn't look à this before) but if i add content, no trace of it.
Answer: Have a look at the Community documentation of the Taxonomy Access Control module. Especially what it says about the Global default (within Global and vocabulary defaults), i.e:

The global default, at the top of the form, determines the grants the role receives for untagged nodes (including nodes with terms that are not in controlled vocabularies). Keep in mind that access is denied by default, so if you want TAC to grant a role access to untagged nodes, set the global default to allow for that grant and role.

See what happens if you adapt this default. If the issue persists, then you may want to perform TAC troubelshooting, possibly even Troubleshooting with Devel.
Comment: Thank you. For the first point, i have already read this documentation (I may have understood it the wrong way though). My problem is that I have two other custom content types that work perfectly (so i don't think the TAC module is misconfigured). The only difference with the new one (as far as i believe) is that the TAC module was installed **after** these two were created but **before** the last one was. So i'll have a look at the troubleshooting pages and maybe try to uninstall the TAC and re-install it...
Comment: @Jice Just an extra check: all for your content types do have a term reference field, right? Because for a content type without such field, how would TAC know if it should yes or no grant access. Sorry of this is a stupid extra check, but one never knows ... and I bet that, in the end, it's going to turn out some config option missing somewhere (+ debugging = the art of trying to eliminate all possible causes ...). Curious to hear how it will turn out ... if you ever find it.
Comment: There is no stupid extra check ;-). Thank you for your help. I'm rather new to Drupal and I may have forgotten some stupid thing. But in this case, there is a term reference field. But this term reference points a new taxonomy (created after the TAC module installation). Another thing is that the label of this field is Tag which is the same as another filed in another content type. Machine names are different but label are identical.
Comment: @Jice I don't expect (hope!) that using the same labels would cause any issues. Not sure if it would help, but I would try to eliminate the possibility that your issue might have to do with the fact that that taxonomy is "new" (created after TAC was installed). This by (again) disable / uninstall  / enable TAC.
Comment: I'll try this but it will take some time as i have to reinstall it on my dev machine.
Comment: I disabled TAC module and desinstall it and the new content type still doesn't appear. So it doesn't seem to be linked with TAC.
Comment: I assume you also performed a "clear cache", and "rebuild permissions", if it doesn't help, it doesn't hurt either ... If that's the case, you've made a major progress in debugging: TAC has nothing to do with your issue, right?
Comment: In a way yes, TAC is innocent. But i still don't understand. Thank you for your help anyway.


Why $\psi$-invariance implies eigenbasis exists

Question:
Let $\varphi,\psi$ be endomorphisms on a finite-dimensional vector space over a field $K$ such that $\varphi\circ\psi=\psi\circ\varphi$. Assume $V$ has a basis of eigenvectors of $\psi$ and a basis of eigenvectors of $\varphi$. Prove that $V$ has a basis consisting of vectors that are eigenvectors of both $\varphi$ and $\psi$.

My work so far:
Let $\lambda_1,\ldots,\lambda_n$ be the distinct eigenvalues of $\varphi$. For each $\lambda_i$, let $c_{i,1},\ldots,c_{i,m_i}$ be the eigenvectors of $\varphi$ corresponding to $\lambda_i$. By assumption, $\varphi$ is diagonalizable, so we can write
$$
V\cong V_1\oplus\cdots\oplus V_n
$$
where each $V_i=\text{eig}(\varphi,\lambda_i)$. Using the fact that $\varphi$ and $\psi$ commute, it is easy to show that for all $v_i\in V_i$, $\psi(v_i)$ is an eigenvector of $\varphi$ corresponding to $\lambda_i$, so $\psi(v_i)\in V_i$. Apparently, I need this fact in order to show that since $\psi$ is also diagonalizable by assumption, we can find a basis $\{d_{i,1},\ldots,d_{i,m_i}\}$ for each $V_i$ consisting of eigenvectors of $\psi$. From here it follows that each $d_{i,j}$ is an eigenvector of $\varphi$, since $\varphi(d_{i,j})=\lambda_id_{i,j}$ ($\varphi$ acts as multiplication by $\lambda_i$ on $V_i$).
My question: I know that $\psi$ being diagonalizable implies I can decompose $V$ into eigenspaces corresponding to $\psi$, but how do I know I can find a basis of eigenvectors of $\psi$ for each $V_i$? Like I said before, I believe this comes from the fact that $\psi(V_i)\subset V_i$, but I am not sure. Any ideas?
Answer: Let's suppose that $\phi,\psi$ commute and let's prove that exists a common basis of eigenvectors.
Let $\lambda_{1},\cdots,\lambda_{k}$ di eigenvectors of $\phi$ and $E(\lambda_{i},\phi)$ the relative eigenspaces. Since $\phi \circ \psi = \psi \circ \phi$ we get that $\psi(E(\lambda_{i},\phi)) \subseteq E(\lambda_{i},\phi) \hspace{0.1cm} i = 1,\cdots k $. Infact, $\forall x \in E(\lambda_{i},\phi)$ we have
$$\phi(\psi(x)) = \psi(\phi(x)) = \phi(\lambda_{i}x) = \lambda_{i}(\phi(x))$$
So $\psi(x) \in E(\lambda_{i},\phi)$.
Beeing $\phi$ diagonalizable we have that
$$V = E(\lambda_{1},\phi) \oplus \cdots \oplus E(\lambda_{k},\phi)$$
Let $w$ an eigenvector for $\psi$ with eigenvalue $\mu$. Thanks to the decomposition we can write $w$ in a unique way $w = x_{1}+\cdots +x_{k}$,$x_{i} \in E(\lambda_{i},\phi)$ so
$$\mu w = \mu x_{1}+\cdots +\mu x_{k}$$
But $\mu w = \psi(w)$ so we have also
$$\psi(w) = \psi(x_{1})+\cdots +\psi(x_{k})$$
With $\psi(x_{i}) \in E(\lambda_{i},\phi)$ thanks to the invariance dicussed above. Since the decomposition to the space in eigenspaces is unique, it must follow that
$$\psi(x_{1}) = \mu x_{1},\cdots \psi(x_{k}) = \mu x_{k} $$
And the $x_{i}$ not all equals to the null vector (since $w$ is an eigenvector). But if you look at the $x_{i}$ you'll notice that they are exactly eigenvectors in common for $\phi,\psi$ since $x_{i} \in E(\lambda_{i},\phi)$ and $\psi(x_{i}) = \mu x_{i}$.
If you apply the same argument of this proof starting from a basis $w_{1},\cdots,w_{n}$ of eigenvectors for $\psi$ given by hyphtesis, we get a set of at least $n$ coommon eigenvectors which generates $V$ because $w_{i}$ are wrote as a linear combination of those, hence they generate; and you can just simply extract a basis from them.
Answer: This is actually really simple, my friend and I just figured it out. Since $\psi$ is diagonalizable, and each $V_i$ is $\psi$-invariant, it is actually  a known theorem that $\psi$ restricted to each $V_i$ is also diagonalizable. The result follows. For the proof of this theorem, see here.


Given two basis, find the transformation matrix from one to another

Question: I have these two basis of $M^R_{2x2}$:
$C= (\begin{pmatrix}1 & 0 \\  0 & 0\end{pmatrix}, \begin{pmatrix}0 & 1 \\  0 & 0\end{pmatrix}, \begin{pmatrix}0 & 0 \\  1 & 0\end{pmatrix}, \begin{pmatrix}0 & 0 \\  0 & 1\end{pmatrix}  )$
$B= (\begin{pmatrix}1 & 1 \\  0 & 0\end{pmatrix}, \begin{pmatrix}0 & 1 \\  1 & 0\end{pmatrix}, \begin{pmatrix}0 & 0 \\  1 & 1\end{pmatrix}, \begin{pmatrix}0 & 0 \\  0 & 1\end{pmatrix}  )$
And I need to find:
$$M_C^B, M_B^C$$
Now, I'm pretty now sure what is the process of finding the transformation matrix from one vector to another.
Can someone please help me understand it?
Comment: Try constructing the basis elements of $B$ using linear combinations of elements in $C$.
Answer: Consider the coefficient vector
$$
\begin{pmatrix}1 & 0 & 0 & 0\end{pmatrix},
$$
in $B$, i.e., 1 times the first element of $B$, plus 0 times the second, and so on. That represents the matrix
$$
\begin{pmatrix}1 & 1 \\  0 & 0\end{pmatrix},
$$
right?
That's easily expressed in the $C$ basis as $1$ times the first element plus one times the second, i.e., in vector form, it's
$$
\begin{pmatrix}1 \\ 1 \\  0 \\ 0\end{pmatrix}.
$$
So to find $M^B_C$, you need a $4 \times 4$ matrix that sends
$$
\begin{pmatrix}1 \\ 0 \\ 0 \\ 0\end{pmatrix} \to \begin{pmatrix}1 \\ 1 \\  0 \\ 0\end{pmatrix}.
$$
That means that the first column of $M^B_C$ must be
$$
\begin{pmatrix}1 \\ 1 \\  0 \\ 0\end{pmatrix}.
$$
Repeat with the other three items in the $B$ basis to find the other three columns.
Going the other way might seem harder, but it's not much harder; alternatively, you can invert the matrix $M^B_C$ to get $M^C_B$, but since I'm rotten at matrix inversion, I'd probably get that wrong. :)
Answer: Hint:
Let $C_1,C_2,C_3,C_4$ be the elements of the canonical basis $C$, than you can represent any matrix $X$ in $M(2,\mathbb{R})$ as a linear combination
$$
X=x_1C_1+x_2C_2+x_3C_3+x_4C_4
$$
that is a vector of components $(x_1,x_2,x_3,x_4)^T$ with respect to the basis $C$.
For the elements of the new basis $B$ you have:
 $$
B_1=C_1+C_2=(1,1,0,0)^T \quad B_2=C_2+C_3=(0,1,1,0)^T
$$
$$
B_3=C_3+C_4=(0,0,1,1)^T \quad B_4=C_4=(0,0,0,1)^T
$$
So the matrix:
$$
M=
\begin{bmatrix}
1&0&0&0\\
1&1&0&0\\
0&1&1&0\\
0&0&1&1
\end{bmatrix}
$$
 and its inverse $M^{-1}$ represent the transformations between the basis $B$ and $C$.


What is the "contract" for EventSubscriberInterface functions?

Question: The EventSubscriberInterface can be used to listen for events, and getSubscribedEvents is used to announce which events an implementation would like to subscribe to.
The getSubscribedEvents must return an array which holds the type of events an implementation would like to subscribe to, as well as the function which is to be invoked when an event triggers.
  public static function getSubscribedEvents() {
    return [
      KernelEvents::REQUEST => [
        ['redirectToLoginPage'],
      ]
    ];
  }

The documentation is very sparse on the function :

The method name to call (priority defaults to 0)

By looking at other implementations, I see that the function may return TRUE, FALSE and even implementations of Response. An example implementation could thus look like this :
public function redirectToLoginPage(GetResponseEvent $event) {
  $random = rand(0,2);
  switch($random) {
    case 0:
      return TRUE;
    case 1:
      return FALSE;
    case 2:
     $response = new RedirectResponse('/user/login', 301);
     $event->setResponse($response);
     return TRUE;
  }
}

What is the "contract" for the function which subscribes to events? Specifically, what is the impact of returning TRUE and/or FALSE from this function?
Answer: The contract is the event class itself. In case of GetResponseEvent (deprecated by the way and will be replaced by RequestEvent in future Drupal releases) you can set a response, this will stop the propagation of this event and the kernel will return the response as an answer to the request.
From where do you have the example code, I'm not sure what case 0/1 is trying to do? In the Symfony default dispatcher the return value is ignored.
Comment: Yes, just return. The event dispatcher polls all event listeners until one stops propagation, which for this specific event is possible by setting a response.
Comment: the example code is something I made up, based on a project I work on. The randomness is just something i added here in an attempt to explain the three types of return values I've seen returned from the callback function. That project returns TRUE and FALSE from the callback function. However, I could not figure out what TRUE and FALSE in this context signalled. Should the function either set a response on the passed event, or just return (with no return value)?


Expected number of cards in the stack?

Question: Suppose we have a deck of cards, ordered $[$$1$$,52$] (using e.g. the bridge ordering).
Shuffle the cards (uniformly at random).
Turn over the top card, it has value $v_0$.
We will turn over cards one by one and place them either on the stack or in the discard.
The stack starts off empty.
Let $v_t$ be the value of the top card in the stack (or $\infty$ when the stack is empty).
Now we begin turning over additional cards. For each card $i$ with value $v_i$,
if $v_0 < v_i < v_t$ then we place card $i$ on the top of the stack, so that now $v_t = v_i$. Otherwise, we place card $i$ in the discard.
After turning over $k$ cards, what is the expected number of cards in the stack?
Comment: This is related to longest increasing/decreasing subsequence in a permutation, but I don't think it's the same. For example, if the first card in the stack has value $v_0 + 1$, then the size of the stack will be 1, even if the discard pile has a decreasing subsequence of length $k-1$.
Answer: In a circle with $53$ cards, choose one dummy card uniformly at random and number the remaining cards beginning at that position, say, clockwise. Then draw from the numbered cards as you described. The condition for putting the card $v_i$ on the stack is fulfilled if and only if the card is the clockwise neighbour of the first card $v_0$ among all the cards drawn up to that point (including the dummy card), and by symmetry the probability for that is $1/(i+1)$. Thus the expected number of cards on the stack after turning over $k$ cards (in addition to the first card) is
$$\sum_{i=1}^k\frac1{i+1}=\sum_{j=2}^{k+1}\frac1j=H_{k+1}-1\;,$$
where $H_k$ is the $k$-th harmonic number. Note that the probability of each card to be counted as a record low is exactly the same as it is in the standard case without special treatment of the first card; the result in that case would be $H_{k+1}$, and $1$ is subtracted from that because the first card doesn't count as a record low.
Comment: "condition for putting the card vi on the stack is fulfilled if and only if the card is the clockwise neighbour of the first card v0 among all the cards drawn up to that point (including the dummy card)" This seems to ignore the threshold. A card that's just counter-clockwise of the dummy card will be the first clockwise neighbor, however, it shouldn't be put in the stack.
Comment: @Joe: I don't understand "A card that's just counter-clockwise of the dummy card will be the first clockwise neighbor" -- of what? Do you mean the clockwise neighbour of the first card $v_0$? If so, why would that be? A card that's just counter-clockwise of the dummy card is the  highest card; it should be put on the stack if and only if it's the clockwise neighbour of the first card $v_0$, as in any other case; I don't see how the case where it's just counter-clockwise of the dummy card is any different than other cases.
Comment: Maybe I don't understand your answer. Where are the cards that are less than $v_0$ in the clockwise order?
Comment: @Joe: I'm not sure I understand that question; I suspect that there's some deeper misunderstanding that we haven't identified yet. The cards are numbered clockwise, beginning at the position of the dummy card, so the cards that are less than $v_0$ are the ones that lie between the dummy card and $v_0$ (going clockwise).
Comment: I thought you were calling $v_0$ the dummy card. I think I see what you were saying.
Comment: @Joe: In my first draft of the answer I only called it "the first card"; then I noticed that that could be misunderstood to refer to the dummy card, so I added "$v_0$" to clarify that. I usually stick to the notation used in the question to keep things clear; if there had been some cogent reason to deviate from your notation, I would have explicitly announced that I was deviating from it.
Answer:
I think $v_0$ never changes, so you are sort of restricted to cards bigger that $v_0$ right at the start
If $v_0$ is 0 (which I realize it is not) , you  put a new card on the stack if it is a record low, and by symmetry the probability that the $j^{th}$ you turn over is a record low is $\frac 1 j$, so the expected number of cards after you've turned over n cards is like $log(n)$.
when $v_0$ isn't 0, this argument more or less works, but the card you turn over has to be $ > v_0$, and a new low among all other cards $> v_0$.  This involves conditioning on the number of such cards , which I think is hypergeometric, and something can be ground out.
If you only want to know how many cards after you've gone through the whole deck, then conditional on $v_0$ it's like $log(53 - v_0)$
Comment: (2) is well known. (3) is the crux, but the above is too sketchy. I agree that the number of cards $> v_0$ is hypergeometric.
Comment: Let $L$ be the number of record lows, and let $D$ be the number of cards $> v_0$. Then $E[L] = E[E[L|D]] = \sum E[L|D]p(D)$, where $p(D)$ is hypergeometric. I was really hoping for something more elegant than that... something that could be given in closed form.
Answer: I use an approach similar to mike one, but obtaining a closed formula.
First solve a simpler problem, you have $v_0=0$ and $n$ cards, the expected number of record low, as stated by mike, is $\sum_{i=1}^{n} 1/i$.
Now increasing $v0$, we can just discard all the cards below $v_0$, so we can solve the subproblem with $v_0=0$ and $n=N-v_0$.
Doing the summation for each $v_0$: $$\sum_{j=1}^N \frac{1}{N}\sum_{i=1}^{N-j}\frac{1}{i}=\frac{1}{N}\sum_{i=1}^N\frac{N-i}{i}=\frac{1}{N}\sum_{i=1}^N(\frac{N}{i}-1)=\sum_{i=1}^N\frac{1}{i}-1$$
For $N=52$, the solution is $\simeq3.538$.
EDIT: I've see now that i've forgot that we are interested in the expectation after $k$ cards, we should do the summation only the first $k-1$ terms.
$$\mathbb{E}(k,N)=\frac{1}{N}\sum_{i=1}^{k-1}(\frac{N}{i}-1)=\sum_{i=1}^{k-1}\frac{1}{i}-\frac{k-1}{N}$$
Comment: I don't see any reason why that sum should give the right result if you truncate it at $k-1$. That would seem to assume that the $i$-th term in the sum is the expected value for the $(i+1)$-th card drawn, but that's clearly not the case, e.g. for $i=2$.
Comment: That works if you turn over *all* the cards in the deck. What if you only turn over $k$?
Comment: @Joe: I've forgot to consider $k$, I've added this part.
Comment: For that to work, do you need to assume that the number of record lows and the number $> v_0$ are independent? $E[X,Y] = E[X]\cdot E[Y]$ only when $X$ and $Y$ are independent.

Expected number of cards in the stack?


Covariance of order statistics

Question: I'm a researcher in social science and I have encountered the following math formulation of a problem in my field. Note that I'm relatively new to stack exchange and I have already posted this on math.stackexchange as well as mathoverflow, before being asked to post it here. Please let me know if I should delete the double post from the sites (otherwise I will definitely update all sites when I receive an answer). Thank you!
Let $x_1,x_2,...,x_n,x_{n+1}$ be $n+1$ i.i.d. random variable with non-negative support and strictly positive probability mass around zero. Let $$z_k\equiv \min\{x_1,...,x_k\}.$$
In simulations, I find $Cov(z_{n+1},z_n)$ to be very close to $Var(z_{n+1})$ and very different from $Var(z_{n})$, as long as $n>>1$. I have tried this for many distributions (with non-negative support): $Cov(z_{n+1},z_n) / Var(z_{n+1}) \approx 1$ and the approximation gets better as $n$ increases, even for small $n$ such as $n=5$. On the other hand, $Cov(z_{n+1},z_n)/Var(z_n)$ is very far from 1.
How can I formalize this? That is, I'm looking for some kind of bounds on how the approximation improves with $n$. Of course, as $n\to\infty$, $Var(z_n)=Var(z_{n+1})$, so I'm looking for results either for $n$ finite, or an asymptotic result that takes $n$ to $\infty$ on $m\equiv floor(c\cdot n)$ for constant $c>1$ such that $Cov(z_n,z_m)$ is closer to $Var(z_m)$ than $Var(z_n)$.
Note that the approximation only works for X with non-negative support and has a positive probability mass in a neighborhood around zero. I believe that from results in extreme value theory, such distributions have exponential distribution in the limit. I don't know if this is important.
Comment: If you wanted to analyze a specific example, taking the $x_i$ to be uniform might be convenient; the $z_i$ will then be $\beta$ distributions, which, among other things, have closed-form variances.  If you're interested in the phenomenon across distributions more broadly, you may find the [Fisher-Tippett-Gnedenko Theorem](https://en.wikipedia.org/wiki/Fisher%E2%80%93Tippett%E2%80%93Gnedenko_theorem) relevant
Comment: Hi Bill, thanks for the response. Yes, I did derive the closed form solution for uniform, and verified my conjecture. I will check out the FTG theorem you cited. Thanks a lot. Just a quick question, before I dive into it: do you think (gut-feeling or otherwise) a more general result is possible, using FTG theorem, or are you citing it simply because my question is related to extreme value distributions? Thanks again.
Comment: Sorry, forgot to tag you - @BillBradley . Thanks again!
Comment: @wolfies answer is very nice, but to formalize it, one might want a general tool for characterizing the distribution of the gap between the first and second order statistics.  The FTG at least lets you characterize the first order statistic across distributions quite broadly, so I was hoping it might be the right tool to apply.  That's the extent of my "gut-feeling" :)
Answer:
Let $(X_1,\dots,X_n,X_{n+1})$ denote a random sample of size $(n+1)$ drawn on $X$, and let $$Z_n = \min\{X_1,...,X_n\} \quad \text{and} \quad Z_{n+1} = \min\{X_1,...,X_n,X_{n+1}\}$$

By including the extra $X_{n+1}$ term, there are only 2 possibilities:

EITHER CASE A $\rightarrow$ with probability $\frac{n}{n+1}$

$\quad \quad \text{The extra term } X_{n+1}$ does NOT change the sample minimum i.e. $z_{n+1} = z_n$. Then:
$$\text{Cov}(Z_n, Z_{n+1})\big|_\text{Case A} \; = \; \text{Cov}(Z_{n+1}, Z_{n+1}) \; = \; \text{Var}(Z_{n+1})$$
Since Event A occurs with probability $\frac{n}{n+1}$, this immediately explains why your observed unconditional covariance $\text{Cov}(Z_n, Z_{n+1})$ is well approximated by $\text{Var}(Z_{n+1})$, as $n$ increases.

OR CASE B $\rightarrow$ with probability $\frac{1}{n+1}$

$\quad \quad \text{The extra term } X_{n+1}$ DOES change the sample minimum i.e. $Z_{n+1} < Z_n$. Then $Z_{n+1}$ and $Z_n$ must be the $1^{\text{st}}$ and $2^{\text{nd}}$ order statistics from a sample of size $n+1$ i.e.
$$\text{Cov}(Z_n, Z_{n+1})\big|_\text{Case B} \; = \; \text{Cov}\big(X_{(1)}, X_{(2)}\big) \text{ in a sample of size: } n+1$$

In summary:
\begin{align*}\displaystyle  \text{Cov}(Z_n, Z_{n+1}) \; &= \frac{n}{n+1}\text{Cov}(Z_n, Z_{n+1})\big|_\text{Case A} \quad  + \quad  \frac{1}{n+1}\text{Cov}(Z_n, Z_{n+1})\big|_\text{Case B} \\
&= \frac{n}{n+1} \text{Var}(Z_{n+1})   \quad  + \quad  \frac{1}{n+1}  \text{Cov}\big(X_{(1)}, X_{(2)}\big)_{\text{sample size } = n+1} \\ &
\end{align*}
This makes it easy to see why the result is similar to  $\text{Var}(Z_{n+1})$: because Case A dominates with probability $\frac{n}{n+1}$

Example and Check: Uniform Parent
In the case of $X \sim \text{Uniform}(0,1)$ parent:

Case A:  $\text{Var}(Z_{n+1}) = \text{Var}(X_{(1)})_{\text{sample size } = n+1} = \frac{n+1}{(n+2)^2 (n+3)}$
Case B: $\text{Cov}\big(X_{(1)}, X_{(2)}\big)_{\text{sample size } = n+1} = \frac{n}{(n+2)^2 (n+3)}$
Then: $\text{Cov}(Z_n, Z_{n+1})  = \frac{n}{(n+1) (n+2) (n+3)}$

The following diagram compares:

this exact theoretical solution for $\text{Cov}(Z_n, Z_{n+1})$, as $n$ increases from 1 to 30  $\rightarrow$ the red curve
to a Monte Carlo calculation of $\text{Cov}(Z_n, Z_{n+1})$  $\rightarrow$  the blue dots

Looks fine.

The following diagram compares the exact theoretical solution for $\text{Cov}(Z_n, Z_{n+1})$, $\text{Var}(Z_n)$ and $\text{Var}(Z_{n+1})$:  as the OP reports, by the time $n = 5$, $\text{Cov}(Z_n, Z_{n+1})$ is well approximated by $\text{Var}(Z_{n+1})$:
Comment: Will need to give some thought to the 'correctness' of the $\frac{n}{n+1}$ bits, in non-Uniform cases. Time for bed ... back later :)
Comment: Hi wolfies, thanks a lot for typing this up. I have two small follow-up / clarification questions.

1) Your analysis for $Cov(Z_n,Z_{n+1}) \approx V(Z_{n+1})$ is compelling. Do you think it's possible to have a formal analysis to show that $Cov(Z_n, Z_{n+1})$ is closer to $V(Z_{n+1})$ than $V(Z_n)$, whatever "closer" means?

2) I understand that as we take $n$ to infinity, then $V(Z_n)=V(Z_{n+1})$. Do you think a similar result would hold asymptotically, i.e. let $m=floor(1.1*n)$, then can we have $Cov(Z_n,Z_m)\approx V(Z_m)$ and $Cov(Z_n,Z_m)\not\approx V(Z_n)$?

Thanks  a lot!
Comment: Actually, your arguments in case A applies similarly to $V(Z_n)$, that is, with probability $\frac{n}{n+1}$, $Z_n=Z_{n+1}$ and $V(Z_n)=V(Z_{n+1})$. Hence I do not think the answer explains why $Cov(Z_n,Z_{n+1})\approx V(Z_{n+1} \not\approx V(Z_n)$.
Comment: user341296 wrote: ///////  "Under case A: $Z_n = Z_{n+1}$ so $Var(Z_n) = Var(Z_{n+1})$ ////////////  No - that does not follow ... and it is the crux of the issue. Under Case A, $Var(Z_{n+1})$ denotes the variance of the sample min in a sample of size $n+1$. $Var(Z_{n})$ denotes  the variance of the sample min in a sample of size $n$: even though $z_{n+1} = z_n$, the variance of the two variables is different.
Comment: Apologize for my rusty stats background, I don't immediately understand your comment about $V(Z_n)\neq V(Z_{n+1})$ yet but I'll think about it more. On the other hand, the approximation only works for X with non-negative support and has a positive probability mass in a neighborhood around zero. If you try simulation with normal distribution, you'll see that the approximation doesn't hold. I *think* your case A applies to those distributions as well, hence I still think I'm missing something...
Comment: I tried working out your argument more carefully, but I still don't see how the argument doesn't work for $Var(Z_n)$. In particular, could you write out mathematically how do you get $\left. Cov(Z_n,Z_{n+1})\right| _{CaseA}=Cov(Z_{n+1},Z_{n+1})$? I tried writing out definitions of covariance formally with integrals but I couldn't get it. I am confused about what's random and whats not...
Comment: It's been a while :) Could you get back to this and help me understand why Var(z_n+1)\neq Var(z_n) even in case A?
Answer: This seems to imply that Var(zn)/Var(zn+1) if far from 1 as well. If zi is really the minimum of a sample of size i, then for standard computable examples, like the exponential distribution, the ratio of variances is close to 1 for n reasonably large, for example ((n+1)/n)^2 for the exponential. Perhaps you're simulating the second smallest order statistic?
Comment: Hi kjetil, thanks for you answer. I understand that as $n$ grows to infinity, then $Var(Z_n) / Var(Z_{n+1})$ goes to 1. However, please see the second plot in the answer provided by @wolfies . Red curve is much closer to green than purple - that's what I'm trying to explain.

Covariance of order statistics


Does this chord function as a 13 chord?

Question: In Debussy's La Fille aux Cheveux de Lin, there is this passage:

(Debussy: Préludes Livre I, No. 8, bar 24)
The piece is in Gb major.
This first chord is probably a I chord. But since it has that extra Eb, does it mean it's a I13 chord, despite the fact it has no other notes from that extension? Or is it just a normal I chord with some decoration?
The other option is that it's vi7b chord. Is this more likely?
Comment: Why can't is just be a 6th chord?  There is no dominant 7th which would be the signature of 13.
Comment: This isn't a sixth / thirteenth chord.
Answer: Every single chord in this measure is an Ebm7, in various inversions and voicings.
Comment: Gb maj 6 = Eb min 7.
Comment: @ggcg, it is not possible to understand the function of this chord without the surrounding music.
Comment: I interpreted the OP as asking about the chord itself.
Comment: So did I, and the more standard interpretation would be Ebm7.
Comment: They are quite the same, just inversions of each other,  But okay.
Comment: I'm not sure whose answer to accept. Imo, this seems like the more likely one.
Answer: A 13th chord usually has a dom 7 in it.  Without that you will not hear the typical 13th chord sound.  It is however a maj 6 chord {1, 3, 5, 6}.  Sometimes the 5th is omitted but doesn't need to be if the voicing avoids a maj 2nd, e.g. {5, 1, 3, 6}.

Does this chord function as a 13 chord?


csv_amino acid composition_columnwise

Question: Sample file:
Column 10: A|Y|E|A
Column 11: W|I|Q|Q

How do I calculate amino acid composition (percentage) specific to each column?
for ex: composition of A in column 10 is 50%, E is 25% and Y is 25%.
Biopython provides modules to calculate amino acid composition of entire file in fasta format
from Bio import SeqIO
from Bio.SeqUtils.ProtParam import ProteinAnalysis

for record in SeqIO.parse('output_translation3.fasta', 'fasta'):
    X = ProteinAnalysis(str(record.seq))
    print('\n Results for record: {}'.format(record.id))
    print(X.count_amino_acids()['G'])
    print(X.count_amino_acids()['A'])
    print(X.count_amino_acids()['L'])
    print(X.count_amino_acids()['M'])

Comment: Yes, you are write about biopython module but your input file is not a fasta format.
Answer: from collections import Counter
import re

with open("input.txt") as f:
    for line in f:
        line=line.strip()
        [col,sep,seq] = re.split(r'(: )', line)
        aa = re.split(r'[|]', seq)
        aa_counts = Counter(aa)
        aa_length=len(aa)
        print(col)
        for k,v in aa_counts.items():
            print("  ", k, v/aa_length)

Gives:
Column 10
   A 0.5
   Y 0.25
   E 0.25
Column 11
   W 0.25
   I 0.25
   Q 0.5

csv_amino acid composition_columnwise


Where to set Project Path in Sonar?

Question: I am trying to set up Sonar with Maven Project. I haven't set path of the project anywhere. Please tell in  which file I have to set the path?
[INFO] Scanning for projects...
[INFO]
[INFO]------------------------------------------------------------------------
[INFO] Building Maven Stub Project (No POM) 1
[INFO]------------------------------------------------------------------------
[INFO]------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO]------------------------------------------------------------------------
[INFO] Total time: 0.188 s
[INFO] Finished at: 2015-05-18T11:27:53+05:30
[INFO] Final Memory: 5M/15M
[INFO]------------------------------------------------------------------------
Answer: Did you have a look on the documentation? http://docs.sonarqube.org/display/SONAR/Analyzing+with+Maven

Where to set Project Path in Sonar?


Responsabilidades da View

Question: Por toda a internet, encontro postagens alertando sobre a responsabilidade da View que unicamente deveria zelar por seu nome e exibir o conteúdo.
Apesar de entender que o MVC se baseia exatamente na distribuição de funções e separação da aplicação por camadas, gostaria de entender os agravantes de utilizar a View para executar algumas funções simples, tais como condicionais.
Utilizando a View deste modo, existe alguma perda de desempenho ou vulnerabilidade de segurança?
Por exemplo, em uma das minhas aplicações eu recebo valores trafegados da URL (id) via um ActionLink e faço uma verificação no mesmo para uma exibição condicional de conteúdo. Essa seria uma má pratica?
Answer: De forma alguma seria má prática o trabalho da View é exatamente esse, exibir os dados e esses tipos de validações, que são mais do que normais, são necessárias.
Quanto a questão de segurança não, pois a página é escrita de uma vez só pelo Response e não fornece acesso algum ao usuário.
Answer: Utilizar for, foreach, if, switch, etc. são práticas normais em ASP.NET em suas Views. Não há perca de desempenho e a parte de segurança não é afetada, o que o usuário de internet tem como resultado em seu navegador é somente só HTML.
Existe claro o fator senso, eu por exemplo, coloco a maioria das codificações no Controller e subo para as Views somente o necessário. Exemplo, se eu mando um @model sendo uma Lista de algum objeto (IEnumerable, IList, List, ICollection, etc.) eu sou obrigada a fazer um for ou foreach para mostrar os dados e isso é bem normal em aplicações ASP.NET MVC.
Resumindo, a maior parte da programação faça no Controller e nas Views só faça códigos triviais, como um for, um if, ou seja, o básico.
Comment: E quanto a Where em listas? O certo é não existir isso em View, né?
Comment: Isso @DiegoZanardo não é boa prática, já mande a informação final e na Views coisas básicas!

Responsabilidades da View


Can Imaj7(#5) resolve to I?

Question: I am reconsidering the chord progression of a song I wrote. The problem is that the chord progression both begins and ends on a C chord; the first bar and the last two bars (out of sixteen bars) are C chords. As you can tell, the key is also C. This causes the transition between the ending of one iteration and the beginning of the next iteration, to sound fairly dull.
For the record, the last four bars of the chord progression are Am | G | C | C.
While experimenting with those last two bars a bit, I came up with the Cmaj7(#5) chord, which in my opinion sounds quite good. The G# can resolve to the C chord's G, and the B can resolve to the C chord's C.
However, I read everywhere that this chord normally resolves to an F chord. Does this mean that it cannot resolve to a C, and that it would be a far fetched option in my particular situation? Or are my own findings with this chord correct after all?
Answer: Cmaj7#5 to C doesn't sound far fetched at all. In the end, if something sounds good - use it! But, if something sounds good, there will usually be an explanation for why it works...
In this case, Cmaj7#5 is a chord containing chromatic tension, that "wants" to resolve to something simpler. In particular, the two chromatic alterations to the chord (B, the maj7 and G#, the #5) can resolve by half-step to pitches within your home key, C Major:

with Cmaj7#5 to C: the G# resolves downwards to G, the 5th of the C chord; the B resolves upwards to C, the root of the C chord.
with Cmaj7#5 to F: the B resolves upwards again to C, the 5th of the F chord; the G# resolves upwards to A, the 3rd of the F chord; the E, which is the 3rd of the Cmaj7#5 chord, also resolves upwards, to F the root of the F chord.

From this, it is easy to see why a resolution to F may seem stronger: Cmaj7#5 to F is essentially all the pitches of an E chord moving up by half-step to an F chord, over a C bass (which may or may not move to the root of the F chord). But, of course, this leaves you on chord IV, if you are in C Major; although the chromatic chord may have been resolved, this won't feel like a resolution to your whole song or chord sequence. For this to happen, you need to resolve to a C chord, as you suggest. However, if this chord sequence occurs within the song (if it is repeated, for instance), you may want to resolve to a chord other than C; this will propel the music forward, as the music won't feel as though it has come to rest.
If you were going to use this chord (Cmaj7#5) at a point other than your song's ending, it could resolve by half-step to other chords in the key of C Major, for instance:

In fact, the first of these (Cmaj7#5 - Am) could essentially use the E chord "within" the first chord, to create a V - I cadence into the relative minor, A Minor. Whether this feels like an actual modulation would depend upon whether you stay long in A Minor...
(It is worth pointing out, that this kind of voice-leading works well in popular music, but would break rules in more strict forms of harmony/counterpoint - before somebody jumps on my parallel fifths!)
Finally, if you were using a dominant 7th chord, rather than a major 7th chord, this certainly would want to resolve to a chord with it's root a fourth higher. For instance C7#5 would certainly want to move to an F chord. There are two related reasons for this: the Bb in the C7#5 chord wants to resolve downwards to the A in the F chord; this is essentially a dominant chord, wanting to resolve using a perfect cadence.
Comment: No problem! Would be good to see the rest of the chord sequence; I've been trying to guess what they might be, to see how your Cmaj7#5 might fit…! In the end, I reckon the Cmaj7#5 almost sounds like a chromatic "decoration" of the C chord, as it is between two other C chords...
Comment: Nice answer! This is essentially what I was trying to say too, but you put a bit more depth into it.
Answer: It's certainly possible for these notes to resolve to the I. Only, I'd argue what you have there is not so much Imaj7(♯5) as Imaj7(♭6)... and immediately it makes sense. For that chord is basically just V♭9 plus a I pedal bass note. If you ignore the pedal and add an F, since you omit the G note it's simply the standard diminished seventh dominant chord.
Comment: @RolandBouman: you certainly can't just ignore any non-chord tone, least so if it's in the bass. But pedal points are a special case, they aren't really considered part of the harmony at all but rather "reminder of what tonic we eventually want to end up in". Then, there's not actually an f in G♭9, but if set so clearly as a dominant the seventh would be somewhat implied. As for the G itself, that's not in fact present in the diminished-seventh chord – since the bass has a pedal point the fifth-movement is out as a resolving effect anyway, so it's mainly the third b that resolves to the tonic.
Comment: I have some trouble following your line of thought and I would be grateful if you could elaborate. The OP's chord is c-e-g#-b, you argue it should be c-e-a flat-b. I understand and agree. I can see how that could be called Imaj7(b6). I do not understand how you can argue that that is about the same as "Vb9 with I pedal bass". Vb9 would be g-b-d-f-ab. With "I pedal bass" I assume you mean c, but then we would have a chord of g that does not contain a g, and has an added 4th as bass note. You then argue we should "ignore the pedal".
Comment: I'm just saying, it seems very strange to "ignore" such an unusual (fourth) non-chord tone, especially if it is in the bass.
Comment: Thanks for the explanation. I guess we need to see the actual voice leading to know more.
Comment: Or rather a V13b9 (emphasizing the 6). Very common in jazz standards.
Answer: When in doubt, refer to the first rule of composition: If it sounds cool, it's right.
However, there's also a sound theoretical basis for what you're doing here. The common V–IV–I–I blues turnaround has the same problem as your song when leading back into another I chord, and the solution is similar. In blues, you usually substitute in a V chord at the end of a verse, creating an imperfect cadence that resolves to the I at the start of the next phrase. But it's perfectly reasonable to use a lesser tension and release here, because you're really just trying to liven up a dull spot in the harmony. Your vi–V–I–I+7 cadence accomplishes that well.
Comment: Hm, I got a different impression, that he was substituting a tension for the final chord the way you do in a blues turnaround (which is the theoretical analogue I'm referring to).
Comment: -that I-V is an imperfect cadence. The perfect (V-I) would come at the very end of the piece.
Comment: Thanks for the feedback! Now that I am fully awake I checked my facts and you are right. Fixed the post.
Comment: IIUC the OP has vi-V-I+7#5-I, not vi–V–I–I+7? You argue that "there's a sound theoretical basis for what you're doing here" - can you point me to some sources where this is described?
Answer:
While experimenting with those last two bars a bit, I came up with the Cmaj7(#5) chord, which in my opinion sounds quite good. The G# can resolve to the C chord's G, and the B can resolve to the C chord's C.

An alternative interpetation is that your chord is actually a (enharmonically equivalent) Ab9(#5) chord (omitted 7th).
There is a "rule" that says that alterations resolve in the direction of the alteration. So if it would be raised g, then the tendency would be to keep rising and resolve to a; this is certainly possible as demonstrated by Bob Broadley.
Since in your case the altered note resolves to g, it makes more sense to see it as a lowered a, which can then keep falling down to g.
Comment: Good point RB; I decided not to "worry" about the enharmonic spelling of G#-G, but you're absolutely right...
Comment: Bob, thanks. In retrospect, the interpretation as a chord of Ab has a problem as well. IIUC the preceding chord is G, which does not contain an a. So where is the ab coming from? If it is approached from g then g# would make more sense, except that it resolves again to g.

I tried it out for a bit myself on guitar, and personally I have some issues to make the altered chord go to C in a convincing way. In the context of the preceding Am and G, I keep hearing the "Cmaj7(#5) as a dominant of Am (E major with added c) with a tendency to resolve to Am.
Comment: Yes, I hear it most strongly as, basically an E chord, wanting to go to A minor, too. But, I guess, sometimes those quirky, unexpected uses of harmony are what make a pop song (or a piece of "classical" music, too!) I hope Lee posts the whole chord sequence, as I'm intrigued to see how it works. I reckon at present, the Cmaj7#5 functions as a decoration of the preceding and following C chords (using both upper and lower auxiliary notes?)
Comment: Bob, agreed :) Curious too about the entire chord scheme. Als curious about the voicing. @Lee White can you share?

Can Imaj7(#5) resolve to I?


iPhone: how to stop Record Automated tests in Instruments

Question: I wrote some scripts for automation testing, then I put them in .js file. And using Instruments, I start them by taping on Record button. What I want to know, is there any way to stop recording in script ? Because, if my Test1 fail, I don't want Test2 to be run. Thanks...
Answer: If you record with xctrace you can capture the pid of the xctrace process and terminate it later:
<code># Start recording
xcrun xctrace record \
    --device <device> \
    --attach <pid|name> \
    --template <path|name> \
    --time-limit 5m \
    --no-prompt \
    --output recording.trace \
    >> trace.log \
    &
    2>&1 \

xctracePID=$!
</code>
Stop recording:
<code># Send Interupt signal (Ctrl-C)
kill -INT $xctracePID 2>/dev/null

# Wait for recording to be saved to disk
wait $xctracePID 2>/dev/null
</code>