Evaluate $\int_{y=-\infty}^1\int_{x=0}^\infty 4xy\sqrt{x^2+y^2}\mathrm dx\mathrm dy$

Question: Evaluate $$\int_{y=-\infty}^1\int_{x=0}^\infty 4xy\sqrt{x^2+y^2}\mathrm dx\mathrm dy$$
I tried to solve this for hours without any success. I tried substitution method of $u = x^2+y^2$ but doesn't seem to work.
Here is my attempt:

$$\int_{-\infty}^1\int_0^\infty (16x^2y^2)^{\frac{1}{2}}(x^2 + y^2)^\frac{1}{2} \; \mathrm{d}x \mathrm{d}{y} = \int_{-\infty}^1 \int_0^\infty (16x^3y^2 + 16x^2 y^3)^{\frac{1}{2}} \; \mathrm{d}x\mathrm{d}{y}.$$
Let
\begin{align}
u &= 16x^3 y^2 + 16x^2 y^3 \\
\mathrm{d}u &= (48x^2y^2 + 32xy^3) \; \mathrm{d}{x} \\
\mathrm{d}u &= 16xy^2(3x + 2y) \; \mathrm{d}{x} \\
\mathrm{d}u &= 4xy(12xy + 8y^2) \; \mathrm{d}{x} \\
4xy \; \mathrm{d}{x} &= \frac{\mathrm{d}{u}}{12xy + 8y^2}.
\end{align}
$$\int_{-\infty}^1 \int_0^\infty 4xy \sqrt{x^2 + y^2} \; \mathrm{d}x \mathrm{d}y = \int_{-\infty}^1 \int_0^\infty \frac{\mathrm{d}u}{(12xy + 8y^2)}.$$

Attaching image for reference

EDITS
Original Post asked integrate: 4xy sqrt(x^2+y^2) where 0<x, y<1, and added this image. .
Later edits misread 0<x,y<1 as if 0<x<1and 0<y<1
Comment: @RobertShore that was the integral in the linked image.
Comment: @RobertShore What new limits of integration? If you check the edit history, the OP originally posted a linked image, which gave the limits of integration in the newest version. It wasn't changed.
Comment: These new limits of integration can't be right.  The integral obviously diverges.  The problem was originally written asking for the integral over the unit square (in the first quadrant), and I think that's what was intended.
Comment: The original image for reference - https://i.stack.imgur.com/m4Gyt.gif
Comment: The original post (which didn't use MathJax) also stated the limits of integration as $0 \leq x, y \leq 1$.
Comment: ...yes, so what's the issue, exactly?
Comment: Oh I see, you're interpreting **both** $x,y$ as being in $[0,1]$. I assumed it was just a list of conditions, i.e. $0 < x$ and $y < 1$. Plus the integral included with the OP at the time actually reflected this latter interpretation.
Comment: That was my edit.  Not certain that's what the OP intended, but based on the math I think it's likely.  Need clarification from the OP.
Answer: With constant $y$ the substitution $u=x^2+y^2$ implies $$\int_0^1\sqrt{x^2+y^2}xdx=\frac{1}{2}\int_{y^2}^{1+y^2}u^{1/2}du=\frac{1}{3}[u^{3/2}]_{y^2}^{1+y^2}=\frac{(1+y^2)^{3/2}-y^3}{3}.$$Now we apply the integration operator $4\int_0^1 dy\,y$, giving$$\frac{4}{3}\int_0^1[y(1+y^2)^{3/2}-y^4]dy=\frac{4}{15}[(1+y^2)^{5/2}-y^5]_0^1=\frac{4}{15}(2^{5/2}-2)\approx 0.975.$$
Comment: how did you change the upper and lower limit from 0 to 1, to y^2 to 1+y^2, I understand the rest of the solution. Thank you
Comment: @Nawa From $u=x^2+y^2$.
Answer: You want to do this a piece at a time.  First compute the inner integral with respect to $y$ (considering $x$ to be a constant for the moment).  Do you see how to do that via the obvious $u$-substitution that you've already considered?
Once you have computed that integral (which will result in some expression that's a function of $x$), compute the outer integral with respect to $x$.
Let us know if you're still stuck.
Comment: Still Stuck, :(
Comment: If I could upload an image as a comment I would have shown you how many pages I practiced trying to solve it....
Comment: Please clarify the intended limits of integration and edit your posts to show some of your work.
Comment: Here is my attempt
Comment: Try $u = x^2+y^2$ and don't move anything inside the radical.
Comment: I tried with u substitution but end up with wrong answer, I am pretty sure I did something wrong on this. Please let me know if you can. Answer is supposed to be 0.975
Comment: Please double check your limits of integration.  I'm pretty sure the improper integral written above diverges.
Comment: I double and triple checked, that's the correct limit. This problem is directly from the Probability and Statistics for Engineers and Scientists Ninth edition by Walpole
Comment: The integrand is an odd function in $y$ so you can change the $y$ limits to $- \infty$ and $-1$ (the integral from $-1$ to $1$ will always be $0$) but I don't see how that helps you.  I don't usually encourage this, but maybe it's a good idea for you to post a picture of the problem directly from the book.  Because those limits of integration can't possibly be right.  If the result converges (and I'm pretty sure it doesn't), it *has* to be negative because the integrand is negative whenever $y \leq -1$.
Comment: @ Robert Shore My assumption was wrong on the upper limit and lower limit, I changed the question accordingly. I know how to do the integration but I just need to understand the u substitution method to solve the sqrt.  Thanks
Answer: You first integrate with respect to $x$ while treating $y$ as a constant. Then, you integrate the result of that with respect to $y$:
$$
\int_{0}^{1}\int_{0}^{1} 4xy\sqrt{x^2+y^2}\,dx\,dy=
\int_{0}^{1}\left(\frac{4}{2}y\int_{0}^{1}\sqrt{x^2+y^2}\frac{d}{dx}(x^2+y^2)\,dx\right)\,dy=
\int_{0}^{1}\left(2y\int_{0}^{1}\sqrt{x^2+y^2}\,d(x^2+y^2)\right)\,dy=\\
\int_{0}^{1}\left(2y\frac{2\sqrt{(x^2+y^2)^3}}{3}\bigg|_{0}^{1}\right)\,dy=
\int_{0}^{1}\left[2y\left(\frac{2\sqrt{(1^2+y^2)^3}}{3}-\frac{2\sqrt{(0^2+y^2)^3}}{3}\right)\right]\,dy=\\
\frac{4}{3}\int_{0}^{1}\left(y\sqrt{(1+y^2)^3}-y^4\right)\,dy=\\
\frac{4}{3}\int_{0}^{1}y\sqrt{(1+y^2)^3}\,dy-\frac{4}{3}\int_{0}^{1}y^4\,dy=\\
\frac{4/3}{2}\int_{0}^{1}\sqrt{(1+y^2)^3}\frac{d}{dy}(1+y^2)\,dy-\frac{4}{3}\frac{y^5}{5}\bigg|_{0}^{1}=\\
\frac{2}{3}\int_{0}^{1}(1+y^2)^{3/2}\,d(1+y^2)-\frac{4}{3}\left(\frac{1^5}{5}-\frac{0^5}{5}\right)=\\
\frac{2}{3}\frac{2(1+y^2)^{5/2}}{5}\bigg|_{0}^{1}-\frac{4}{15}=\\
\frac{2}{3}\left(\frac{2(1+1^2)^{5/2}}{5}-\frac{2(1+0^2)^{5/2}}{5}\right)-\frac{4}{15}=\\
\frac{2}{3}\left(\frac{2\sqrt{2^5}}{5}-\frac{2}{5}\right)-\frac{4}{15}=\\
\frac{4(4\sqrt{2}-1)}{15}-\frac{4}{15}=\frac{16\sqrt{2}-4-4}{15}=\frac{16(\sqrt{2}-8)}{15}=\frac{8(2\sqrt{2}-1)}{15}.
$$
Wolfram Alpha check.
Answer: Hint:
Don't switch to polar coordinates. Notice that
$$\frac d{dx}(x^2+y^2)^a=2ax(x^2+y^2)^{a-1}$$
and
$$\frac d{dy}\frac d{dx}2ax(x^2+y^2)^{a-1}=4a(a-1)xy(x^2+y^2)^{a-2}.$$
Answer: Using polar coordinates, the integrand is
$$4\rho^2\cos\theta\sin\theta\,\rho\,\rho\,d\rho\,d\theta.$$
By symmetry, we can integrate twice in the triangle between $\theta=0,\theta=\dfrac\pi4$ and $\rho\cos\theta=1$ (or $\rho=\dfrac1{\cos\theta}$).
After integration on $\rho$,
$$8\cos\theta\sin\theta\ \left.\frac{4\rho^5}{5}\right|_0^{1/\cos\theta}=\frac{32}5\frac{\sin\theta}{\cos^4\theta}.$$
Then
$$\int_0^{\pi/4}\frac{\sin\theta}{\cos^4\theta}\,d\theta=\int_0^{1/\sqrt2}\frac{dt}{(1-t^2)^2}\,d\theta.$$
This integral is soluble by decomposition in simple fractions.


SDL2 program write only part of string

Question: I have a code with a function TextOut that writes one char on the window every time with some delay. All was in normal but my program writes only part of string to the window. However sometimes program writes the whole text.
This function create wchar from char
char* cts(char c)
{
    char *ptr = (char*)malloc(2 * sizeof(char));
    ptr[0] = c;
    ptr[1] = '\0';
    return ptr;
}

void TextOut(SDL_Renderer *ren, TTF_Font *f)
{
    SDL_Surface *sur;
    SDL_Texture *tex;
    static SDL_Rect rect;
    static int32_t x;

   //Checking if string is end
    if (OUT_STRING[x] == '\0') return;

    //Get a wide char from string
    char *temp = cts(OUT_STRING[x]);

    //Get the size of font
    TTF_SizeText(f, temp, &rect.w, &rect.h);

    sur = TTF_RenderText_Blended(f, temp, color)

    free(temp);

    tex = SDL_CreateTextureFromSurface(ren, sur);
    SDL_RenderCopy(ren, tex, NULL, &rect);
    SDL_RenderPresent(ren);
    rect.x += rect.w;
    x++;
    SDL_FreeSurface(sur);
    SDL_Delay(50);
}

int main(int argc, char* argv[])
{

    /*

    Initialization of Window, Renderer, Font and other things

    */

    OUT_STRING = "We are waiting";

    while (!quit)
    {
        while (SDL_PollEvent(&e) != 0)
        {
            TextOut(renderer, font);
            if (e.type == SDL_QUIT) quit = true;
        }
    }
    return 0;
}

Comment: I realized that the program still outputs the required text but after a certain amount of the main cycle pass.
Answer: The problem you describe is due to your event loop - you're calling your render function there. When your window is shown, several events are generated (SDL_WINDOWEVENT_EXPOSED, etc.), so your render function called severnal times, but not enough for your "whole" text. When more events arrives (mouse move, keypressed, window manipulations, ...) - you can see more. If that is undesired behaviour - you should use event loop for what it is, events handling, e.g.:
while (!quit)
{
    while (SDL_PollEvent(&e) != 0)
    {
        if (e.type == SDL_QUIT) quit = true;
    }
    TextOut(renderer, font);
}

It is questionable how you're going to continue drawing after all characters are shown, or why you need malloc (you don't).
Comment: Problem is solwed. Thank you for help!
Answer: For me, the whole text appeared invariably so I haven't been able to test if these improvements will solve your problem or not, but they are definitely issues with your code.
You should free the memory allocated by the malloc inside cts, for example you can do it like this:
char* temp = cts(OUT_STRING[x]);
TTF_SizeText(f, temp, &rect.w, &rect.h);
free(temp);

When checking if an exit event has happened, don't use assignment instead of comparison. The correct way to do this is:
if (e.type == SDL_QUIT) quit = true;

When checking if you have reached the end of the char array, don't use NULL. Do it like this instead:
if (OUT_STRING[x] == '\0') return;

Comment: You're welcome. There is no such thing as a stupid mistake, as long as you learn from it ;)
Comment: If you want to get your already working code checked, please don't post it here, but on [codereview](https://codereview.stackexchange.com/).

SDL2 program write only part of string


Comando Java para somar coluna em tabela

Question: Preciso do código em Java no Android para fazer a soma da coluna de uma determinada tabela SQLite.
Sei que o comando é "Select sum(coluna) from tabela", mas o que preciso saber é como escrever isso em Java para conseguir recuperar esse valor da soma.
Como a coluna se trata de números, algum comando que me retorne um valor inteiro que eu possa estar utilizando em outros lugares.
Desde já agradeço.
Comment: E a tag Javascript?
Answer: Aparentemente você precisa acessar uma coluna da tabela, mas não consigo dizer exatamente que tipo de componente está utilizando, sendo assim, a minha melhor sugestão é utilizar o EntityManager da JPA.
Comece criando uma classe que abrirá a conexão ao banco, como no exemplo abaixo.
private static ConnectionFactory instance;
private final EntityManagerFactory factory;

private ConnectionFactory() {
    factory = Persistence.createEntityManagerFactory("nome da persistence unit"));
}

private EntityManager getEntityManager() {
    return factory.createEntityManager();
}

public static EntityManager getConnection() {
    if (instance == null) {
        instance = new ConnectionFactory();
    }

    return instance.getEntityManager();
}

Após isso, crie uma classe Entidade, que será a responsável por receber os dados recuperados da tabela por uma outra classe que acessa o banco, exemplo: "SomaDAO".
E finalmente crie a classe de acesso a dados e utilize uma Query para recuperar os dados da coluna da tabela que você deseja realizar a soma.
public Integer soma() {
    EntityManager em = getEntityManager();
    em.getTransaction().begin();

    Query q = em.createQuery("SELECT sum(coluna) from tabela");

    Integer soma = (Integer) q.getSingleResult();

    em.getTransaction().commit();
    em.close();

    return soma;
}

EDIT 1
Aqui o código para um comando SELECT no banco SQLite que pode ser utilizado em sistemas Android. Vide esta questão: Android SQLite SELECT
SQLiteDatabase db = this.getReadableDatabase();
    Cursor c = db.rawQuery("SELECT sum(column1) FROM table ", null);
    if(c.moveToFirst()){
        do{
           //Recuperando valores
           int column1 = c.getInt(0);

    //Fazendo algo com os valores

        }while(c.moveToNext());
    }
    c.close();
    db.close();

Comment: Amigo, obrigado pela resposta. Mais não funciona o query no meu projeto java. Ele é para plataforma android, e os comandos sqlite acredito q sejam diferentes.
Comment: Adicionado parte de código que funciona no SQLite na resposta.


Wrong usage of OpenGL?

Question: I wrote a small particle system in Java with the LWJGL.
So therefore I am using openGL.
Now I read, that changing a texture is very slow. So I make sure, that I only change a texture which is used for a bunch of particles and then draw all these particles.
Still my FPS drop from about 8000 to 4000 although there are only 60 particles at the same time drawn.
I know that the problem is the rendering, because when I just update particles but do not draw them, then I have no drop in FPS.
It would be great if someone could tell me what is wrong with my OpenGL code.
This is the particle emitter which manages the particles:
public void render() {
//Initialize....
GL11.glMatrixMode(GL11.GL_MODELVIEW);
BloodParticle.PARTICLE_TEXTURE.bind();

for(Integer index : this.getBlockedParticles()){
    this.getParticles()[index].render();
}

GL11.glDisable(GL11.GL_TEXTURE_2D);
}

This is the render method of a single particle:
public void render() {
if(!this.isAlive()){
    return;
}

// Store matrix
GL11.glPushMatrix();

// Set to particle's position and scale
GL11.glTranslatef(this.getPosition().getX(), this.getPosition().getY(), 0);
GL11.glScalef(3.5f, 3.5f, 1.0f);

// Set the current alpha.
GL11.glColor4f(1.0f, 1.0f, 1.0f, this.getAlphaFade());

//Draw the texture on a quad.
GL11.glBegin(GL11.GL_QUADS);
{
    GL11.glTexCoord2f(0, 0);
    GL11.glVertex2f(-PARTICLE_TEXTURE.getImageWidth()/2.0f,
            -PARTICLE_TEXTURE.getImageHeight()/2.0f);

    GL11.glTexCoord2f(0, 1);
    GL11.glVertex2f(-PARTICLE_TEXTURE.getImageWidth()/2.0f,
            PARTICLE_TEXTURE.getImageHeight()/2.0f);

    GL11.glTexCoord2f(1, 1);
    GL11.glVertex2f(PARTICLE_TEXTURE.getImageWidth()/2.0f,
            PARTICLE_TEXTURE.getImageHeight()/2.0f);

    GL11.glTexCoord2f(1, 0);
    GL11.glVertex2f(PARTICLE_TEXTURE.getImageWidth()/2.0f,
            -PARTICLE_TEXTURE.getImageHeight()/2.0f);

}
GL11.glEnd();

//Get the matrix again.
GL11.glPopMatrix();
}

I know that 4000 FPS are much more than enough. But I am just scared about this drop to half the FPS and with only one emitter in the game currently.
I know that this will become a problem with a fixed FPS of 60 and more than 3 emitter.
Comment: "*But I am just scared about this drop to half the FPS and with only one emitter in the game currently.*" A drop from 8000 FPS to 4000 represents 0.125 ***milli*** seconds of time difference. It's not a problem. Measuring by framerate isn't helpful; always measure by *time*.
Answer: State changes have nothing to do with your performance problem.
This has:

//Draw the texture on a quad.
GL11.glBegin(GL11.GL_QUADS);
{
    GL11.glTexCoord2f(0, 0);
    GL11.glVertex2f(-PARTICLE_TEXTURE.getImageWidth()/2.0f,
            -PARTICLE_TEXTURE.getImageHeight()/2.0f);

    GL11.glTexCoord2f(0, 1);
    GL11.glVertex2f(-PARTICLE_TEXTURE.getImageWidth()/2.0f,
            PARTICLE_TEXTURE.getImageHeight()/2.0f);

    GL11.glTexCoord2f(1, 1);
    GL11.glVertex2f(PARTICLE_TEXTURE.getImageWidth()/2.0f,
            PARTICLE_TEXTURE.getImageHeight()/2.0f);

    GL11.glTexCoord2f(1, 0);
    GL11.glVertex2f(PARTICLE_TEXTURE.getImageWidth()/2.0f,
            -PARTICLE_TEXTURE.getImageHeight()/2.0f);

}
GL11.glEnd();

Think about it: Each and every particle causes 8 calls into OpenGL. At several thousand particles this is a huge overhead. Even worse, you're not even batching several quads into a single glBegin/*glEnd* block.
Here's how to improve performance: Don't use glBegin/glVertex/glEnd aka the immediate mode
Use Vertex Arrays!

Wrong usage of OpenGL?


Async Await conversion

Question: Hoping to elicit some ideas on the converted api load func.  Somehow, it works, it's my first try.
I'm asking because I'd like to know if the error catch, from the do-catch, covers all the response stuff I removed.
import SwiftUI
import Foundation

struct ContentView: View {
    @State private var food: Food = Food(id: 0, uid: "", dish: "", description: "", ingredient: "", measurement: "")

    var body: some View {
        display
            .lineLimit(10)
            .task {
                do {
                    try await getRandomFood()
                } catch {
                    print("Error", error)
                }
            }
    }

    // my converted 1st attempt, I wrote this from getRandomFood2() below
    func getRandomFood() async throws {
        let url = URL(string: "https://random-data-api.com/api/food/random_food")!

        do {
            let (data, _) = try await URLSession.shared.data(from: url, delegate: nil)
            let food = try JSONDecoder().decode(Food.self, from: data)
            self.food = food
        } catch {
            throw error
        }
    }

    // original func do-catch-ified above
    func getRandomFood2() async throws {
        guard let url = URL(string: "https://random-data-api.com/api/food/random_food") else { fatalError("Missing URL") }
        let urlRequest = URLRequest(url: url)
        let (data, response) = try await URLSession.shared.data(for: urlRequest)

        guard (response as? HTTPURLResponse)?.statusCode == 200 else { fatalError("Error while fetching data") }
        let decodedFood = try JSONDecoder().decode(Food.self, from: data)
        food = decodedFood
        // print("Async decodedFood", decodedFood)
    }

    var display: some View {
        /* ...    */
   }
}

Comment: FWIW, there is no value to a `do`-`try`-`catch` if the only thing you do in the `catch` clause is to `throw error`. In your other example (w/o the `do`-`try`-`catch`) is fine. In fact, that additional validation of `statusCode` is prudent. But, then again, (a) it is not just 200 that is success, but any code b/w 200…299; and (b) you should not crash the app with `fatalError` just because the server did not report success, but rather just `throw` an appropriate error. E.g., https://gist.github.com/robertmryan/109550d14c73fc2226f6a77f53f022cf.
Answer: Creating the URL with this string literal cannot fail, it can be forced unwrapped.
And rather than aborting the code with an fatal error throw an URLError
func getRandomFood2() async throws {
    let url = URL(string: "https://random-data-api.com/api/food/random_food")!
    let (data, response) = try await URLSession.shared.data(from: url)

    guard (response as? HTTPURLResponse)?.statusCode == 200 else { throw URLError(.badServerResponse) }
    food = try JSONDecoder().decode(Food.self, from: data)
}

Comment: I modified getRandomFood2(), and came up with getRandomFood() above.  Is there any difference between a URL error using the do-catch, and the getRandomFood2() version.  Say if the URL disappears, or becomes broken.  Pardon for not understanding.  But I am eliciting commentary for getRandomFood(), which I wrote.  Is getRandomFood() any good?
Comment: As I said this specific URL string cannot fail. If the URL *disappears* you get a server error, the URL is still valid. And the explicit `do - catch` block is redundant. `getRandomFood()` is fine without the `do - catch` block

Async Await conversion


Matching URLs containing a string pattern and save the url in a new column in a R dataframe

Question: I have a dataset containing multiple urls as a string in one column 'urls'
urls <- "https://www.linkedin.com/xx/xxx-xx-xxx/ https//domain.io https://medium.com/@xxxxx"
id <- 1

df <- cbind(data.frame(urls), data.frame(id))

I now want to extract the complete domain matching "linkedin.com" and store it in a new column df$linkedin. And do the same for domain matching "medium.com" and store it in a new column df$medium. So the result would be basically
df$linkedin
"https://www.linkedin.com/xx/xxx-xx-xxx/"

df$medium
"https://medium.com/@xxxxx"

Somehow I have today a bad hair day and don't see an elegant solution. Would be awesome if you can help out me here :)
Answer: I'll make this a little more interesting by making it two rows:
df2 <- structure(list(urls = c("https://www.linkedin.com/xx/xxx-xx-xxx/ https//domain.io https://medium.com/@xxxxx", "https://www.linkedin.com/yy/yyy-yy-yyy/ https//domain.io https://medium.com/@yyyyy"), id = c(1, 1)), row.names = c(NA, -2L), class = "data.frame")
df2
#                                                                                urls id
# 1 https://www.linkedin.com/xx/xxx-xx-xxx/ https//domain.io https://medium.com/@xxxxx  1
# 2 https://www.linkedin.com/yy/yyy-yy-yyy/ https//domain.io https://medium.com/@yyyyy  1

base R
baseurls <- c("linkedin", "medium")
newcols <- lapply(setNames(nm = baseurls), function(U) unlist(regmatches(df2$urls, gregexpr(paste0("http[^ ]*", U, "[^ ]*"), df2$urls))))
newcols
# $linkedin
# [1] "https://www.linkedin.com/xx/xxx-xx-xxx/" "https://www.linkedin.com/yy/yyy-yy-yyy/"
# $medium
# [1] "https://medium.com/@xxxxx" "https://medium.com/@yyyyy"
cbind(df2, data.frame(newcols))
#                                                                                urls id                                linkedin                    medium
# 1 https://www.linkedin.com/xx/xxx-xx-xxx/ https//domain.io https://medium.com/@xxxxx  1 https://www.linkedin.com/xx/xxx-xx-xxx/ https://medium.com/@xxxxx
# 2 https://www.linkedin.com/yy/yyy-yy-yyy/ https//domain.io https://medium.com/@yyyyy  1 https://www.linkedin.com/yy/yyy-yy-yyy/ https://medium.com/@yyyyy

tidyverse
## baseurls <- ...
library(dplyr)
library(stringr) # str_extract
library(purrr)   # map_dfc
map_dfc(setNames(nm = baseurls), ~ str_extract(df2$urls, paste0("http[^ ]*", .x, "[^ ]*"))) %>%
  bind_cols(df2, .)
#                                                                                urls id                                linkedin                    medium
# 1 https://www.linkedin.com/xx/xxx-xx-xxx/ https//domain.io https://medium.com/@xxxxx  1 https://www.linkedin.com/xx/xxx-xx-xxx/ https://medium.com/@xxxxx
# 2 https://www.linkedin.com/yy/yyy-yy-yyy/ https//domain.io https://medium.com/@yyyyy  1 https://www.linkedin.com/yy/yyy-yy-yyy/ https://medium.com/@yyyyy


Term for relationship of set overlap without containment?

Question: What is the term for the relationship between two sets that share at least one common element, but neither set is a proper or improper subset of the other?
$$
A?B=_{def}\exists x \exists y \exists z ((x \in A) \wedge (x \notin B) \wedge (y \notin A) \wedge (y \in B) \wedge (z \in A) \wedge (z \in B))
$$
Comment: "Two sets neither of which is a subset of the other" is not good enough?
Comment: Nonempty intersection.
Comment: @AsafKaragila Two non-empty non-overlapping sets fulfill that.
Comment: @user4894 A set and it's subset fulfill that.  As do identical sets.
Answer: One idea to name the relation of two sets is to borrow concepts from logic gates. In your case we have:
$$
\begin{array}{c|cc}
\lor  & a\notin A & a\in A \\
\hline
b\notin B & 0 & 1 \\
b\in B & 1 & 1
\end{array}
$$
where a 1 indicates the intersection is non-empty and 0 implies the intersection is empty, so we could say $A \lor B$.
Comment: Sorry if I was unclear, but I'm looking for terminology, not definition.  Also, I think my question leaves the absolute complement of (A union B) undefined, rather than necessarily empty.  I edited the question for clarity.
Comment: in which case you are looking at $X$, the whole universe


SCCM Wireless Adapter driver version info

Question: iam working on SCCM Dashboard to get all wireless devices on whole SCCM, so iam running this query
<code>    select count(name0),Name0 from v_GS_NETWORK_ADAPTER where
v_GS_NETWORK_ADAPTER.Description0 like '%Wireless%'
group by Name0
</code>
after running this query i do get wireless adapter list like this

my question is iam making pie chart to show this.. but i need Wifi driver Versions so  that i can show in drill down report for each model, so from where can i get Driver versions of Each model?
Comment: SCCM doesn't inventory information about drivers afaik so you would have to expand the whole inventory. It is possible (described e.g. at: https://docs.microsoft.com/en-us/archive/blogs/configmgr_geek_speak/inventorying-and-reporting-network-adapter-driver-details-and-how-to-report-only-the-wireless-type-with-bonus-mini-primer-on-sql-report-builder-in-configuration-manager-2012) but not trivial. Alternative way could be to use the information about installed software if the driver is in addprograms but the relations would probably have to be hardcoded because those drivers names are arbitrary.
Comment: neways we raised called with MS.. only option is to Add PNP driver data once you add PNP driver view builts up.
Answer: neways we raised called with MS.. only option is to Add PNP driver data once you add PNP driver view builts up.
we need to class to Default settings in client setting of SCCM


Generate nested HTML code based on the array

Question: I have the following array:
[0] => [
  'parent_id' => null,
  'id' => 1,
  'count' => 0
  'children' => [
    [0] => [
      'parent_id' => 1,
      'id' => 11,
      'count' => count11
    ]
    [0] => [
      'parent_id' => 1,
      'id' => 12,
      'count' => count12
    ]
  ]
],
[1] => [
  'parent_id' => null,
  'id' => 2,
  'count' => 0,
  'children' => [
    [0] => [
      'parent_id' => 2,
      'id' => 21,
      'count' => 0,
      'children' => [
        [0] => [
          'parent_id' => 21,
          'id' => 211,
          'count' => count211
        ]
      ]
    ]
  ]
]

And I have to create a nested HTML list out of this according to the following pattern:

All categories (count)

    Category 1 (count1)

        Category 11 (count11)

        Category 12 (count12)

    Category 2 (count2)

        Category 21 (count21)

            Category 211 (count211)

The problem is, the count value exists only in leaves, so parents would have to sum all values of their children. Another problem is that I need a header here (all categories), but it doesn't exist in the array.
How can I do this?
I have been trying to come up with some solutions, but none works.
public function generateHTML($arr, $html, $depth = 0)
{
  if($depth == 0)
  {
    $html = '

All categories
';
  }
  foreach($arr as $key => $value)
  {
    $html .= '

';
    $this->generateHTML($arr, $html, $depth++);
    $html .= '

';
  }
  if($depth == 0)
  {
    $html = '
';
  }
}

I have completely no idea how could this look like.
Comment: can you provide me your array in PHP to do some test ?
Answer:
Blockquote Here is exactly working code as per your requirement.

<?php

class test{

    public function getTree($arr){
        $html = '
';
        foreach($arr as $k=>$v){
            $html .= '
'.$v['count'].'';

            if(isset($v['children'])){
                if(is_array($v['children'])){
                    $html .= $this->getTree($v['children']);
                }
            }
            $html .= '
';
        }
        return $html .= '
';
    }
}

$arr = array(
array(
    'parent_id' => null,
    'id' => 1,
    'count' => 'count1',
    'children' => array(
        array(
            'parent_id' => 1,
            'id' => 11,
            'count' => 'count11'
        ),
        array(
            'parent_id' => 1,
            'id' => 12,
            'count' => 'count12'
        )
    )
),
array(
    'parent_id' => null,
    'id' => 2,
    'count' => 'count2',
    'children' => array(
        array(
            'parent_id' => 1,
            'id' => 21,
            'count' => 'count21',
            'children' => array(
                array(
                    'parent_id' => 21,
                    'id' => 211,
                    'count' => 'count211'
                )
            )
        )
    )
)
);

$obj = new test();
echo $obj->getTree($arr);

?>


Replicating linear trend with ANOVA from paper

Question: This is the paper I am trying to replicate: https://link.springer.com/article/10.3758/s13428-011-0172-y
The authors propose a within-subject design in which they manipulate the numerical distance of their stimuli into 5 levels of the condition Distance.
To check that RT increases with Distance, the authors first perform a One Way Anova on their 8 subjects. By this, they assign a p-value to the main effect of Distance (see Table 2 from the paper).
Then they calculate the Sum of Squares (SS) of Linear and the SS Participants x Linear, used to calculate F and the partial eta-squared of the linear trend.
I managed to replicate these data until SS Participants x Linear. Do you have an idea on how to do calculate this specific SS.
I put the code I used here with the dataset and the steps I performed:
import numpy as np
import pandas as pd

#recreating the dataframe
array1 = np.array([[1, 489.33, 'Cond1'],[1, 454.82, 'Cond2'],
       [1, 425.07, 'Cond3'],
       [1, 450.1, 'Cond4'],
       [1, 395.0, 'Cond5'],
       [2, 412.83, 'Cond1'],
       [2, 398.87, 'Cond2'],
       [2, 408.87, 'Cond3'],
       [2, 390.5, 'Cond4'],
       [2, 375.7, 'Cond5'],
       [3, 489.23, 'Cond1'],
       [3, 458.98, 'Cond2'],
       [3, 423.73, 'Cond3'],
       [3, 410.25, 'Cond4'],
       [3, 397.0, 'Cond5'],
       [4, 549.21, 'Cond1'],
       [4, 472.07, 'Cond2'],
       [4, 451.57, 'Cond3'],
       [4, 431.05, 'Cond4'],
       [4, 419.7, 'Cond5'],
       [5, 459.64, 'Cond1'],
       [5, 428.1, 'Cond2'],
       [5, 403.1, 'Cond3'],
       [5, 393.53, 'Cond4'],
       [5, 372.2, 'Cond5'],
       [6, 467.09, 'Cond1'],
       [6, 438.6, 'Cond2'],
       [6, 393.33, 'Cond3'],
       [6, 367.6, 'Cond4'],
       [6, 417.9, 'Cond5'],
       [7, 424.22, 'Cond1'],
       [7, 381.28, 'Cond2'],
       [7, 388.97, 'Cond3'],
       [7, 385.84, 'Cond4'],
       [7, 362.8, 'Cond5'],
       [8, 377.05, 'Cond1'],
       [8, 351.67, 'Cond2'],
       [8, 346.2, 'Cond3'],
       [8, 339.7, 'Cond4'],
       [8, 343.6, 'Cond5']])

#convert the array into a dataframe
dataset = pd.DataFrame({'Subj': array1[:, 0], 'RT': array1[:, 1], 'Cond': array1[:, 2]})
dataset["RT"] = pd.to_numeric(dataset["RT"])

subjects = 8 #subjects from the paper

#calculate One-Way Anova
df_ANOVA = dataset.rm_anova(dv='RT', within='Cond', subject='Subj', detailed=True)
df_means = dataset.groupby(["Cond"])['RT'].agg(['mean', 'std']) #means + SD

# Calculate SSlinear
# #use the values calculated from df_means and fit it to -2 -1 0 1 2
fit = (-2*458.57500) + (-1*423.04875) + 0 + 396.07125*1 + (2*385.48750)
model = ((-2)**2)+((1)**2)+((0)**2)+((1)**2)+((2)**2)
trend = (fit*fit*subjects)/model

They define SS Participants x Linear as "the sum of the squares due to the interaction between participants and the linear component of distance".
Answer: I am not so familiar with pinguoin, but you can get the results using statsmodels. The first model with participant x distance:
import statsmodels.api as sm
from statsmodels.formula.api import ols

lmfit = ols('RT ~ C(Cond)+C(Subj)',data=dataset).fit()
sm.stats.anova_lm(lmfit)

            df        sum_sq      mean_sq         F        PR(>F)
C(Cond)    4.0  26253.981825  6563.495456  19.96224  7.184050e-08
C(Subj)    7.0  43533.297190  6219.042456  18.91462  4.623600e-09
Residual  28.0   9206.274935   328.795533       NaN           NaN

We just convert the Cond to numeric. you can do it like -2 to 2 or 1 to 5:
dataset['Cond_L'] = pd.to_numeric(dataset['Cond'].str.replace("Cond",""))

lmfit = ols('RT ~ Cond_L*C(Subj)',data=dataset).fit()
sm.stats.anova_lm(lmfit)
                  df        sum_sq       mean_sq          F        PR(>F)
C(Subj)          7.0  43533.297190   6219.042456  20.388095  1.166856e-08
Cond_L           1.0  23985.430605  23985.430605  78.632241  4.867599e-09
Cond_L:C(Subj)   7.0   4154.033515    593.433359   1.945472  1.060743e-01
Residual        24.0   7320.792640    305.033027        NaN           NaN


Loop overdub bar

Question: I have a question about loop overdubbing:
Let's say I record with my looper a simple 2-bar melody or whatever, like:

then, using the same pedal to overdub it, I record something that is one bar long like:

what will happen? I mean,will the first 2 bars (first recording) play and at the beginning of each bar,the second recording will play?
Or will it just play at the first of the first bar and then the 3rd etc.. ?
Comment: Simple thing to do is try it !! It can always be deleted, and you'll have your answer either way.
Answer: Most simple loop pedals don't know about bars - it's just a sound sample of a length you set.
Typically:

You start recording by tapping a pedal
You play your instrument
You mark the end of the loop by tapping the pedal. The length of the loop is now set.
The loop keeps playing, over and over.
When you overdub, you add sounds to the loop

More advanced loopers with more complicated interfaces allow you to have multiple loops of different lengths. For example with the iOS app "Loopy", you can have several independent loops, with lengths that are whole-number multiples of the base loop, or even completely unsynchronised.
Answer: Say your first bar is 4 seconds long, so the first recording then becomes 8 secs. The overdub is only 4 secs long, so will only replay alongside the first 4 secs. (1st bar).The second bar remains as original.
They are great fun, and a good tool to have.Make your own backing track in a few minutes, add bass, whatever, and play lead along to yourself.Scrub any mistakes immediately. If you can afford it, go for a twin pedal model, which will give the opportunity to replay different mixes. There's also a quite expensive multi-pedal model.
Comment: I didn't understand the `The second bar remains as original.` part.

I was thinking of buying the Ditto Looper from TC electronic
Comment: The second bar will just play as is, unless you overdub something during the second bar's time.This site is not for recommending gear, however, I do like my Boss RC-30.
Answer: You need a multitrack looper with multi-sync feature (whatever the name).
I know three of them :
- Boomerang III
- Pigtronix Infinity Looper
- Boss RC300 (just guess, for the price...)
In this looper, you can define the shorter loop (n bars) then, let say the second track is defined as 3x as long as the first track, play the longer loop on 3n bars. The 2 tracks will be synchronized.

Loop overdub bar


Find limit of sequence $(x_n)$

Question: Find limit of sequence $(x_n)$:
$$x_1 = a >0$$
$$x_{n+1} = \frac{n}{2n-1}\frac{x_n^2+2}{x_n}, n \in Z^+$$
I think I can prove $(x_n)$ is low bounded (which is obvious that $x_n>0$) and decreasing sequence. Then I can calculate the limit of sequence is $\sqrt{2}$
All my attempts to prove it's a decreasing sequence have been unsuccessful.
My attemps: Try to prove $x_{n+1}-x_{n} <0$ from a number $N_0$ large enough. It lead to I have to prove $x_n \ge \sqrt{\frac{2n}{n-1}}$ and I stuck.
Does anyone have an idea?
Comment: Please edit your post to include your attempts
Comment: It is more difficult than expected, but I think that I have got it.
Comment: @Jnote, look at my answer now, I have corrected it.
Comment: My idea has failed, not because it's not working but because it's as difficult to execute as the winning argument. I'm dropping it and voting up the accepted answer.
Comment: @AnneBauval thank u, I edited it
Comment: I saw $\Rightarrow$ +1
Comment: @SarveshRavichandranIyer yeahh, Can u write it down? Thank u so much, this exe takes me the whole night
Comment: I have already corrected my answer. Please, remove the downvotes.
Answer: For all $n\ge 1$ is
$$
 x_{n+1} = \frac{2n}{2n-1} \cdot \frac 12 \left( x_n + \frac{2}{x_n} \right) \ge \frac{2n}{2n-1}\sqrt 2 \,,
$$ using the inequality between the arithmetic and the geometric mean. So we have
$$
 x_n^2 \ge 2 \left( \frac{2n-2}{2n-3}\right)^2
$$
for $n \ge 2$. It follows that for $n\ge 2$,
$$
x_{n+1} = \frac{n}{2n-1}\frac{x_n^2+2}{x_n}
 \le \frac{n}{2n-1} \frac{x_n^2 + \left( \frac{2n-3}{2n-2}\right)^2x_n^2}{x_n} = a_n x_n
$$
with
$$
a_n := \frac{n}{2n-1} \left( 1+ \left( \frac{2n-3}{2n-2}\right)^2\right)
= \frac{8 n^3 - 20n^2+13n}{8n^2-20n^2+16n - 4} < 1 \, .
$$
This shows that $(x_n)_{n \ge 2}$ is decreasing. It is also bounded below (by zero) and therefore convergent. Now you can take the limit in the recurrence relation and show that the limit is $\sqrt 2$.
Comment: I think in 6th line: $x_{n+1} = \frac{n}{2n-1}\frac{x_n^2+2}{x_n}$ and $\frac{n}{2n-1} \le \frac{2}{3}$ so $x_{n+1} = \frac{2}{3}\frac{x_n^2+2}{x_n} \le \frac{4}{3}x_n$.
Comment: @Jnote: There was indeed an error, the estimate were too rough. I have updated the answer, hopefully it is correct now!
Answer: A recursion shows that the $x_n$ for $n \ge 2$ are well-defined and bounded below by $\sqrt{2}$, since $x^2+2-2\sqrt{x} = (x-\sqrt{2})^2$ is always positive. Set $y_n = x_n-\sqrt{2}$. Then for $n \ge 2$,
\begin{eqnarray*}
y_{n+1}
&=& \frac{n(x_n^2+2)-\sqrt{2}(2n-1)x_n}{(2n-1)x_n} \\
&=& \frac{n(x_n-\sqrt{2})^2+\sqrt{2}x_n}{(2n-1)x_n} \\
&=& \frac{ny_n^2}{(2n-1)x_n} + \frac{\sqrt{2}}{2n-1} \\
&\le& \frac{n}{2n-1}y_n+ \frac{\sqrt{2}}{2n-1},
\end{eqnarray*} since $y_n \le x_n$.
For $n \ge 2$, $n/(2n-1) \le 2/3$, so
$$y_{n+1} \le \frac{2}{3}y_n+\frac{1}{3}z_n, \text{ where } z_n = \frac{3\sqrt{2}}{2n-1}$$
Given $\epsilon>0$, one can find an integer $N$ such that for every $n \ge N$, $z_n \le\epsilon$ so $$y_{n+1}-\epsilon \le \frac{2}{3}(y_n-\epsilon),$$
so by recursion
$$y_n-\epsilon \le \Big(\frac{2}{3}\Big)^{n-N}(y_N-\epsilon).$$
As a result, $\limsup_{n \to +\infty} y_n \le \epsilon$. Since this is true for every $\epsilon>0$, we get the desired conclusion.
Comment: Thank you. I corrected the typo.
Comment: Wow, thank u so much. I think in 6th line have small mistake, for $n\ge 2, \frac{n}{2n-1} \le \frac{2}{3}$ (all below is still correct). Thank u so much again
Answer: We will prove that
$\sqrt2<x_{n+1}<x_n\;\;$ for any $\;n\in\Bbb N\;\land\;n\geqslant2\;.\quad\color{blue}{(*)}$
For any $\;n\in\Bbb N\;$ it results that
$\begin{align}x_{n+1}&=\dfrac n{2n-1}\!\cdot\!\dfrac{x_n^2+2}{x_n}=\dfrac n{2n-1}\!\cdot\!\dfrac{\left(x_n-\sqrt2\right)^2+2\sqrt2x_n}{x_n}\geqslant\\&\geqslant\dfrac{2\sqrt2\,n}{2n-1}>\sqrt2\;.\end{align}$
In particular we get the first inequality of $\,(*)\,$ and we also obtain that
$x_n\geqslant\dfrac{2\sqrt2\,(n-1)}{2n-3}\;\;$ for any $\;n\in\Bbb N\;\land\;n\geqslant2\;.\quad\color{blue}{(1)}$
Moreover, for any $\;n\in\Bbb N\;\land\;n\geqslant2\;,\;$ it results that
$2n-(n-1)x_n^2\underset{\color{brown}{(1)}}{\leqslant\;}2n-\dfrac{8(n-1)^3}{(2n-3)^2}=\dfrac{-6n+8}{(2n-3)^2}<0\,.\;\;\color{blue}{(2)}$
For any $\;n\in\Bbb N\;\land\;n\geqslant2\;,\;$ it also results that
$\begin{align}x_{n+1}&=\dfrac n{2n-1}\!\cdot\!\dfrac{x_n^2+2}{x_n}=\dfrac{\big[(2n-1)-(n-1)\big]x_n^2+2n}{(2n-1)x_n}=\\&=\dfrac{2n-(n-1)x_n^2+(2n-1)x_n^2}{(2n-1)x_n}\underset{\color{brown}{(2)}}{<}x_n\;.\end{align}$
So we have proved the inequalities $\,(*)\,$, consequently the sequence $(x_n)$ is bounded and eventually decreasing, therefore there exists $\lim\limits_{n\to\infty}x_n=l\in\Bbb R^+\,.$
Moreover ,
$l=\lim\limits_{n\to\infty}x_{n+1}=\lim\limits_{n\to\infty}\left(\dfrac n{2n-1}\!\cdot\!\dfrac{x_n^2+2}{x_n}\right)=\dfrac{l^2+2}{2l}\;,$
hence ,
$l=\dfrac{l^2+2}{2l}\quad,$
$2l^2=l^2+2\quad,$
$l^2=2\quad,$
$l=\sqrt2\,.$
It means that $\;\lim\limits_{n\to\infty}x_n=\sqrt2\,.$
Comment: You first have to show that the series is bounded above.
Comment: You are right, I am going to correct my answer.
Comment: I have the same idea but I can't prove that the sequence is monotonic. Can you give me some hint
Comment: I have already corrected my answer. Please, take off the downvotes.
Comment: @Fix, I have already corrected my answer.
Comment: @Angelo: I noticed your update only after fixing my solution. It seems that we had similar ideas now. +1 from me!
Answer: In general, you are given $x_{n+1} = f_n(x_n)$.  You wanted to show $f_n(x)-x \leq 0$ for all $x \geq \sqrt{2}$, but that's not true.
However, what you have shown is that $(x_n)$ can only move away from $\sqrt{2}$ when it's very close to $\sqrt{2}$.  If we ignore for a moment whether it's even possible for $x_n$ to get that close, the question this would raise for me is "how large can the move away from $\sqrt{2}$ even be?"  More precisely, what is the maximum of $f_n(x) - x$ on $\sqrt{2} \leq x \leq \sqrt{2n/(n-1)}$.
Answering this is a simple question of optimization (at least by derivatives if not algebra).  After a bit, we find that maximum is $\sqrt{2}/(2n-1)$ (at $x=\sqrt{2}$), which goes to zero in the limit.
And that would finish it.  You know that outside a diminishing neighborhood of $\sqrt{2}$, the sequence is always decreasing, and if it even were possible to increase, the maximum increase diminishes to $0$.

Find limit of sequence $(x_n)$


Reading strumming patterns for sheet music

Question: Ok I am not sure how close or far off I am here and IF I am explaining this correctly...
When reading sheet music is strumming a down stroke a single note line, and a UD strum when you see both notes attached? I can figure out IF in 4/8/16's BUT cannot quite catch onto the strum patters used, IF I could figure it out in sheet music I can of course figure the pattern out.
Comment: Basically I am semi struggling on "I Won't Back down", in 16's, the E is 4 beats, the D is 3 and the G/C are 9 beats.... I'd assume it was DUDU (E) - DDU (D) - DUDUDUDUD (G/C depending which part of the song...) ... Just doesn't sound right and it's at 114bpm..
Answer: The rhythm shown is a fairly commonly used one, and often takes a bit of getting into.
Simple way to consider most strum patterns in 4/4 is that the 4 main beats (1,2,3,4) are downstrums. This of course means that the hand needs to go in the opposite direction in between, for the '&' part. You could strum all 8 down/up strums, and that would fill each bar.
Taking this principle, you're actually missing the strings on some of the movements down or up. 1 (&)  2 & (3) & 4 (&).
Comment: I get down and up strokes when coming to down on 1,2,3,4 and up on the &'s, simple there for 8 patterns, I also get the "1 e & a" on 16ths, I can easily strum them to basic patterns and switching out on counts.

Where I struggle is picking up always hearing a pattern like Petty's I Won't Back down, where he switches up his strum patter, the E is different than the D (only 3 strokes DDU),
Comment: it SOUNDS like when he switches to the G he is upstroking the chord but when I do it up or down it just doesn't quite seem right...

The figure I attached was not the song I am looking to play, just wondering IF I got the concept of the theory right on IF I am understanding the diagram correctly, IF SO I can find the sheet music for the song I want and figure out on my own the pattern I am slighting missing on the G/C chords
Comment: Right now, it sounds like a standard 8 in the bar, with nothing syncopated, and the rhythm in question isn't relevant.
Comment: I figured it out, definitely 16th, when coming off the dsus2 or D (Can be played either I guess), it's DDU switch to the G or C depending which bar you're on with an Up, BUT NO hesitations on the switch like he does when going to the E and D chords. That slight pause on the first two switches throws it off on the 3rd switch, no pause, sounds perfect.

Thanks though for trying to help! I went to YouTube and found Marty Music doing a tutorial on it, slowed it to .5 speed and watched how he did it... What I was missing
Comment: @BruceNadeau - Whatever the song, strum patterns generally involve the strum hand going down, up, down, up, sometimes catching strings, sometimes missing, but the relentless down up takes precedence. Not keen on Marty - there's lots of open string strumming between chords; sloppy playing, but kind of gets away with it in keys like G, with lots of open strings anyway. I stopped watching his videos after he stated that the U.S. national anthem was in Lydian mode! - It certainly isn't!
Comment: @Bruce Nadeau - I've just had a listen to Tom Petty, and it seems like they're *all* downstrokes anyway, muted strings. So to emulate that, you'll need to double up, and only hit on downs, missing the occasional one. Straight eights, in the trade!


How to get eigenvectors from eigenvalues

Question: I'm not seeing where the eigenvectors are in terms of eigenvalues in the paper that came out recently named "Eigenvectors from Eigenvalues" by the neutrino physicists and Terence Tao:
https://arxiv.org/pdf/1908.03795.pdf
I'm guessing that with as fundamentally groundbreaking as this paper is, some people on here have read it.  Please let me know if you know where in the paper the eigenvectors are in terms of eigenvalues.
Edit:  To be more specific, I saw the norm squared part, but how do you narrow it down to the actual value of each element of each eigenvector. For any reals, you can just act the transformation on the at most the finite $2^n$ possibilities (unless it has infinite dimensions as can be the case in particle physics), where n is the dimension of the vector. But, what about when the values that the norm square is being taken of are complex?
Also, if you can address infinite dimensions, that would be appreciated.  Meaning, is there a way to get the elements without testing each combination?
Comment: I am personally a big fan of formula $7$. When you think about it, it makes sense if $A$ is hermitian and diagonal, with distinct eigenvalues. It also provides a geometric interpretation of the adjugate of a hermitian matrix with exactly one of the eigenvalues being $0$, as a kind of orthogonal projection onto the kernel, times $s_{n-1}$ of the set of eigenvalues (which is nonzero in this case).
Comment: Could you be more specific? -- E.g., corollary 3 is certainly far from groundbreaking
Comment: I read it yesterday. Lemma $2$ is the main theorem, although I would definitely recommend reading both proofs, as the second proof contains a "more complete" formula (formula $7$ in the paper). That formula also enables one to recover the phases of the eigenvector elements (up to a global phase factor for each eigenvector).
Comment: Lemma 2 gives the norm of the Eigenvector elements in terms of Eigenvalues and Eigenvalues of adjugate matrices. It essentially seems of no practical use for computation of the Eigenvectors.
Comment: Right – it gives the norms of the components of the eigenvectors, not the exact values of those components.
Comment: Agree with @YvesDaoust and the authors states clearly "Discussion. The form of Lemma 2 with the norm squared of the elements of the eigenvectors is expected in that any determination of the eigenvectors from the eigenvalues is insensitive to the phases since one can multiply any eigenvector by a phase eiθ while leaving A, Mj, and the eigenvalues unchanged."
Comment: There seems to be various ways to generalize formula $7$. One way is to consider a complex diagonalizable matrix with distinct eigenvalues. I think there should be a similar formula in that case. Also, instead of considering $n-1$ by $n-1$ minors, one may consider $n-k$ by $n-k$ minors, which would have applications to Grassmannians rather than projective spaces, so to speak. I like this work.
Answer: By formula $7$ in that paper, they prove that
$$ \operatorname{adj}(\lambda_i I_n - A) = \prod_{k\neq i} (\lambda_i - \lambda_k) \operatorname{proj}_{v_i}, $$
where $\operatorname{proj}_{v_i}$ is the orthogonal projection from $\mathbb{C}^n$ onto the complex line $\mathbb{C}v_i$. So assuming $\lambda_i$ to be different from $\lambda_k$, for $k \neq i$, which would be the case for instance if all the eigenvalues are distinct, then this implies that the image of the left-hand side is $\mathbb{C}v_i$. So taking any non-zero column from the left-hand side and normalizing would give you the eigenvector $v_i$, the latter being determined up to a phase factor.
I must admit that, while this does recover the eigenvector $v_i$ (up to a phase factor), it involves not only knowing the eigenvalue $\lambda_i$, but also computing the adjugate on the left-hand side.
This is one way to answer your question. Another way is that one does recover the modulus squared of any element of each eigenvector by knowing not only the eigenvalues of $A$, but also the eigenvalues of each matrix $A_i$, for $1 \leq i \leq n$, where $A_i$ is the $n-1$ by $n-1$ matrix obtained from $A$ by deleting the $i$-th row and $i$-th column from it. Lemma $2$ in that paper does just that, and is (I suppose) the reason for the title of that article.
Answer: Let me give an example to show how to derive the eigenvectors from eigenvalues. To be specific, we derive the "norm square of coefficients of eigenvectors from eigenvalues" (link).
Suppose the matrix A is a diagonal matrix A = diag(1, 2, 3). The eigenvalues for A is 1, 2, and 3. That means $\lambda_1 (A) = 1$, $\lambda_2 (A) = 2$ and $\lambda_3 (A) = 3$.
To find the eigenvector $v_1$ of the first eigenvalue $\lambda_1 (A)$, we need to know the exact values of $v_{1,1}$, $v_{1,2}$ and $v_{1,3}$.
Now use the Lemma2 from the arxiv paper [https://arxiv.org/pdf/1908.03795.pdf].
To solve $v_{1,1}$,  $ v_{1,1}^2 (1 - 2) (1 - 3) = (1 - 2) (1 - 3)$, and you know $v_{1,1} = 1$ or $v_{1,1} = -1$. Note, the $(1-2) (1-3)$ on  the left is $( \lambda_1 (A) - \lambda_2 (A) ) \cdot ( \lambda_1 (A) - \lambda_3 (A) )$, and the $(1-2) (1-3)$ on  the right is $( \lambda_1 (A) - \lambda_{k=1} (M_1) ) \cdot ( \lambda_1 (A) - \lambda_{k=2} (M_1) )$ where $M_1$ is $A$ after deleting the $1$st row and column.
To solve $v_{1,2}$,  $ v_{1,2}^2 (1 - 2) (1 - 3) = (1 - 1) (1 - 3) = 0$, and you know $v_{1,2} = 0$.
To solve $v_{1,3}$, $ v_{1,3}^2 (1 - 2) (1 - 3) = (1 - 1) (1 - 2) = 0$, and you know $v_{1,3} = 0$.
Comment: Thanks for the detailed example!  I saw the norm squared part, but how do you narrow it down to the actual value.  Between 1 and -1, or any reals, you can just act the transformation on the at most finite $2^n$ possibilities (unless it has infinite dimensions as can be the case in particle physics), where n is the dimension of the vector.  But, what about when the values that the norm square is being taken of are complex?
Comment: The diagonal case that you are considering here is a bit trivial because here the matrix and the matrix of eigenvalues coincide. You don't need the result of the paper in this case
Comment: @lcv you're right. I provided a toy example here.
Comment: @user3146, my understanding is that you cannot determine 1 or -1, as this paper is to calculate the "norm square of coefficients of eigenvectors from eigenvalues".


causal impact - adding multiple control groups

Question: I want to run an analysis using causal impact tool. I have one test group but multiple control groups. Can I use multiple control groups all together in one model? Eg: Y = test and A,B,C as control all together as multivariate in this tool? Any suggestions?
Thanks
Comment: What is the difference among your controls? How can they all be controls?
Comment: In causal statistics, causation is usually discussed relative to another potential situation. The effect of a drug is not well defined; one must estimate the effect of the drug relative to placebo or the effect of the drug relative to no treatment. Could you separately estimate effects relative to each of your control levels?
Answer: Yes, absolutely. CausalImpact constructs a counterfactual to the observed post-intervention outcomes using a combination of all the control time series you enter. So in practice you almost always want at least a few control time series. Keep in mind that the model assumes all of these to be unaffected by the treatment.
The package documentation has more details:

To illustrate how the package works, we create a simple toy dataset.
  It consists of a response variable y and a predictor x1. Note that in
  practice, we'd strive for including many more predictor variables and
  let the model choose an appropriate subset. [...]

And further below:

Analyses may easily contain tens or hundreds of potential predictors
  (i.e., columns in the data function argument). Which of these were
  informative? We can plot the posterior probability of each predictor
  being included in the model using:
plot(impact$model$bsts.model, "coefficients")


Rejection probability given true $\mu$, for a hypothesis test of normal distribution $\sim N(\mu, 1)$

Question: I am testing the hypothesis: $H_0: \mu \leq 1$ against $H_1: \mu>1$. I've found the UMP test, which rejects the null hypothesis based on $ \bar{x}$:
reject when $$\bar{x} \geq \left(\dfrac{1.65}{\sqrt{n}}\right)+1.$$
I'm at a loss to find rejection probability given true $\mu$. At first I thought that it would be based on the CDF of the normal distribution (denote $F_{\mu}$ as CDF associated with $\sim N(\mu,1)$:
$$R(\mu) = 1-F_{\mu}\left(\dfrac{1.65}{\sqrt{n}} + 1 \right).$$
However, this is clearly incorrect since it is based on the CDF of drawing only one observation (i.e., $n=1$).

How do I solve this? Maybe there is a CDF that takes $n$ into account in some way?
Comment: I might be wrong about this, but couldn't you do $P($reject$ H_0 \vert \mu = \mu_{\ast}) = P($reject$ H_0 \vert \mu_{\ast} \leq 1) +  P($reject $H_0 \vert \mu_{\ast} > 1)$, where $\mu_{\ast}$ is the true mean.
Answer: I assume that the level of the test is $\alpha = 0.05$, hence the critical value for a one-sided test is $$z_\alpha^* = \Phi^{-1}(0.95) \approx 1.64485.$$  Then the rejection region as stated is correct.
The probability of rejecting $H_0$ given $\mu$ is therefore
$$\Pr\left[\bar x \ge \frac{z_\alpha^*}{\sqrt{n}} + 1 \,\Bigl| \,\mu\right],$$ and since $\bar x$ is now normally distributed with mean $\mu$ and variance $1/n$, we compute this probability with the usual standardization technique:
$$\begin{align}
\Pr\left[\bar x \ge \frac{z_\alpha^*}{\sqrt{n}} + 1 \,\Bigl| \,\mu\right]
&= \Pr\left[\frac{\bar x - \mu}{\sqrt{1/n}} \ge \frac{1}{\sqrt{1/n}}\left( \frac{z_\alpha^*}{\sqrt{n}} + 1 - \mu \right) \, \Bigl| \, \mu \right] \\
&= \Pr\left[Z \ge z_\alpha^* + (1-\mu)\sqrt{n}\right] \\
&= \Phi\left((\mu-1)\sqrt{n} - z_{\alpha}^*\right),
\end{align}$$
where $\Phi$ is the standard normal CDF.  Notice how once we standardized and wrote $Z$, we can drop the conditional statement, since that step is valid precisely when the conditional assumption is true (i.e., $(\bar x - \mu)\sqrt{n}$ is standard normal, given that $\mu$ is the true mean).
So for instance, for a sample size of $n = 16$ and $\alpha = 0.05$, for a true mean of $\mu = 2$, the rejection probability will be approximately $$\Phi\left((2-1)\sqrt{16} - 1.64485\right) = \Phi(2.35515) \approx 0.990742.$$  Our formula makes intuitive sense:  The larger $\mu$ is, the larger the quantity $(\mu - 1)\sqrt{n} - z_\alpha^*$ and thus the more likely we are to reject $H_0$; similarly, the larger the sample size, the more precision we have for the sample mean reflecting the true value $\mu$, so if $\mu < 1$, increasing $n$ makes the rejection probability smaller, and if $\mu > 1$, increasing $n$ makes the rejection probability larger.  Finally $z_\alpha^*$, being fixed for a given level $\alpha$, is a constant chosen such that when $\mu = 1$, the rejection probability is equal to the Type I error.


Setting null hypothesis for Binomial test

Question: I have a question for setting null hypothesis in binomial test.
More specifically, is there any way to assume chance level when it is unknown?
For example, let's say that I have a slightly bent coin. So chance for getting Heads or tails is not equal. Instead, it's more likely that it will give us tail.
To find out the probability, I tossed the coin 100 times, and got P(getting tail) = 68%
Then I bent it even more, and I wanted to check if it had any effect on the probability.
So I threw it 10 times and got tails 9 times (90%).
Is it correct to use one sample binomial test to check if 9 out of 10 (90%) is significantly different using 68% as expected probability?
I'm not sure if it's okay because it "assumes" that chance level is 68% based on experience of throwing the coin 100 times, instead of mathematical calculation.
Thanks for reading.
Answer: No, it is not correct.  In this example you have two samples so you should be using a two-sample hypothesis test.  There are a few different two-sample binomial tests available, so you will need to choose one.
Comment: Thanks for the comment. It helped me a a lot.
Answer:
Is it correct to use one sample binomial test to check if 9 out of 10 (90%) is significantly different using 68% as expected probability?

I don't think this is correct because you would assume that 68% was measured without uncertainty. Intuitively, 68% obtained from 10000 flips is "better", more certain than 68% from just 100 flips.
In your case you could use Fisher test for the null hypothesis that 68/100 and 9/10 can originate from the same coin. In R:
mat <- matrix(c(68, 9, 100-68, 10-9), nrow= 2)
mat
     [,1] [,2]
[1,]   68   32
[2,]    9    1

fisher.test(mat)

    Fisher's Exact Test for Count Data

data:  mat
p-value = 0.2765
alternative hypothesis: true odds ratio is not equal to 1
95 percent confidence interval:
 0.005230503 1.851113305
sample estimates:
odds ratio
 0.2384069
```

Comment: Thanks for the reply. Would there be any chance for using measured data as expected value if the observation number increased? My actual data can't be tested using Fisher Exact Test nor Mcnemar Test,  because it is partially paired.
Comment: @RoasClack I'm not sure I can answer your comment without more detail - perhaps edit the question to better explain your situation. E.g., what do you mean by *partially paired*?
Comment: You can see that from my previous question here: https://stats.stackexchange.com/questions/572561/how-to-test-if-watching-a-advertisement-only-1-time-is-enough-to-change-ones-pr?noredirect=1#comment1056520_572561 Thanks for the kind answer.
Answer: No, you treat the result from your sample of 100 ($\hat{p}=68/100$) as a sample statistic not a population proportion. If you repeated that trial of $100$ before the second bending, you would be very likely not to get $68$ on the second attempt; you'd see $65$ or $74$ or $70$ or $63$, or some other number, and a third trial would be likely different again from the first two.
Which is to say $0.68$ is just a noisy estimate of the true proportion. You should not ignore that uncertainty, treating it as if it were the true proportion.
Comment: Thanks for the comment. I see that even though 100 seems relatively large compared to throwing just 10 times, it's still an sample.
Comment: Going from 10 to 100 trials. you'd only reduce the standard error to about 32% of what it was -- not an especially dramatic reduction. People often underestimate quite how large a sample it would take to reasonably treat the sample proportion as known exactly. Much easier to just calculate it as what it is and not worry.
Comment: Can I ask you another question? What if I predict the population proportion not by sampling, but by using mathematical models like linear regression? More specific question is posted here in case you're interested:  https://stats.stackexchange.com/questions/573019/binomial-test-with-chance-level-prediction
Comment: I'll look. I don't promise that I will have time to answer.
Comment: Thank you so much


Gerar um PDF a partir de uma Div HTML

Question: Boa Noite pessoal...
Gostaria de saber oque posso usar para gerar um Pdf a partir de uma div selecionada.
Poderia ser em Jquery,VB,Vb net Ou Javascript.
Poderiam me ajudar ?
Answer: Cara eu faco da seguinte forma.
eu pego o elemento (id ou class) e coloco o evento de (CTRL + P) que abre a opcao de imprimir a pagina ou salvar como pdf.
ou
Vc vai ter que pegar o elemento e transformar em um canvas.
-> Como exportar uma DIV HTML para PDF rederizando o CSS?
http://cdn.rawgit.com/MrRio/jsPDF/master/dist/jspdf.min.js
http://html2canvas.hertzen.com/build/html2canvas.js

Gerar um PDF a partir de uma Div HTML


javascript JSON object to JSF back bean

Question: I know this is going to sound a bit weird, but here is the case... I have a JSF form which in the bottom load an "image viewer", implemented purely with javascript:
...

...

and the javascript code to load the image editor (OpenLayers):
...
function setImageEditorHeight(){
    imageEditorID = $(".imageEditorImagePanel")[0].id;
    ....
}
...
function initialiseMap(){
    ...
    map = new OpenLayers.Map(imageEditorID, options);
    ...
    imageLayer = new OpenLayers.Layer.TMS(imgURL, "", {
        url : '',
        serviceVersion : '.',
        layername : '.',
        alpha : true,
        type : 'png',
        getURL : overlay_getTileURL,
        transitionEffect: 'resize'
    });
    map.addLayer(imageLayer);

    var vlayer = new OpenLayers.Layer.Vector("Editable");
    map.addLayer(vlayer);
    //add controls for drawing shaped on the map like:
    var drawPointControl = new OpenLayers.Control.DrawFeatureOpt(vlayer, OpenLayers.Handler.Point,
            {title:'Draw a point', text: 'Point','displayClass':'olControlDrawFeaturePoint'});
    ...
    //add a save button to store shapes as geoJSON object
    var save = new OpenLayers.Control.Button({
        title: 'Save', text: 'Save',
        trigger: function(){
        var GEOJSON_PARSER = new OpenLayers.Format.GeoJSON();
        var vectorLayerAsJson = GEOJSON_PARSER.write(vlayer.features);
        alert(vectorLayerAsJson);
        //i want something similar
        //just for demonstrating, instead of URL i would like a way to post JSON object to bean
        jQuery.ajax({
            type: 'POST',
            url: '/ajax/add',
            dataType: 'json',
            data: {"vLayerAsJson": vectorLayerAsJson}
         });
    }, 'displayClass': "olControlSaveFeatures"
    });
    ...
    panel.addControls([hand, zoomToDrawControl, drawPointControl, drawPathControl, drawPolygonControl, drawRegularPolygonControl,
        new OpenLayers.Control.ZoomToMaxExtent({title:"Zoom to the max extent", text: "World"}), modifyFeatureControl, deleteFeatureControl, save]);
    ...
    map.addControl(panel);
    ...

Finally when i press the javascript "Save" button, i would like to submit somehow in my backing bean this JSON object ... In particular i would like to call a bean method in order to process JSON object and store it as XML.
Any ideas?
Answer: You can't do that via jQuery. That's why jsf provides the <f:ajax> tag, you can set it in the submit button action. JSF is kind of different from "classic" web development, in JSF you think more on events and desktop-like development.
Comment: Omar thanks for responding. I am aware about JSF. The problem is that my Image Viewer (google map like) is totally built on javascript and that shapes on the image are drawn dynamically. How can i submit the JSON string representing them back to my bean?
Comment: When you perform an ajax action in jsf you can "update" an entire container such divs. That said, you could update the ImageViewer container after the ajax action completion. The thing with JSF is to use in a higher level the web, with advantages and disadvantages of it.
Comment: Other way is to keep your jQuery code and use a Servlet that provides a JSON as response.
Answer: You could also have your button call a Rest service which passes the info along to where it needs to be. The Javascript just needs to call it using the onclick event of the button. Jax-rs allows you to set the consumes annotation to JSON. I actually use this approach quite often. Its really easy to create the Rest service with your JSF web app project.
This answer might also be of help pass array from javascript to back bean

javascript JSON object to JSF back bean


Read, manipulate and save text file

Question: All,
I'm trying to read text files that are being downloaded every 20 min in to a certain folder, check it, manipulate it and move it to another location for further processing. Basically, I want to check each file that comes in, check if a string contains a "0.00" value and if so, delete that particular string. There are two strings per file.
I managed to manipulate a file with a given name, but now I need to do the same for files with variable names (there is a timestamp included in the title). One file will need to be processed at a time.
This is what I got so far:
import os

path = r"C:\Users\r1.0"
dir = os.listdir(path)

def remove_line(line, stop):
    return any([word in line for word in stop])

stop = ["0.00"]
for file in dir:
    if file.lower().endswith('.txt'):
        with open(file, "r") as f:
            lines = f.readlines()

        with open(file, "w") as f:
            for line in lines:
                if not remove_line(line, stop):
                    f.write(line)

What works are the def-function and the two "with open..." codes. What am I doing wrong here?
Also, can I write a file to another directory using the open() function?
Thanks in advance!
Comment: can you post the error you are getting ?
Comment: The code runs and I don't get an error. It just doesn't change the file like I want to. The line with "0.00" values in it is not deleted. The code just adds a space between every character.
Answer: Your code looks mostly fine. I don't think your list comprehension method does remove the string though. You can write to a different folder with Open(). This should do the trick for you:
import os

path = r"C:\Users\r1.0"
dir = os.listdir(path)

stop = ["0.00"]
for file in dir:
    if file.lower().endswith('.txt'):
        with open(file, "r") as f:
            lines = f.readlines()
        # put the new file in a different location
        newfile = os path.join("New", "directory", file)
        with open(newfile, "w") as f:
            for line in lines:
                if stop in line: #check if we need to modify lime
                      #modify line here
                      #this will remove stop from the line
                      line.replace(stop, "")
                # Regardless of whether the line has changed, we need to write it out.
                f.write(line)

Read, manipulate and save text file


How to prove the spectrum of the Laplace operator?

Question: How can I prove that the spectrum of the Laplace operator $$\Delta: H^2(\mathbb{R}^N)\subset L^2(\mathbb{R}^N)\rightarrow L^2(\mathbb{R}^N)$$ is $\sigma(\Delta)=[-\infty,0]$?
Comment: Ok, I'll write an answer in a while. If you are in a hurry you can look here: http://www.mat.univie.ac.at/~gerald/ftp/book-schroe/
Comment: Fourier transform
Comment: Could you be more detailed please?
Answer: We determine the resolvent set of $(\Delta, H^2(\mathbb{R}^n))$. By definition, the complex number $\lambda$ belongs to the resolvent set if and only if the following equation (named resolvent equation)
$$\tag{1}\Delta f -\lambda f = g$$
has a unique solution $f\in H^2$ for any fixed $g\in L^2$. The spectrum is the complementary of the resolvent set and its elements are called spectral values.
[EDIT: Summary. Here's two different approaches. The first uses the Fourier transform. The second computes explicitly a set of (generalized) eigenfunctions.]

Method 1. Taking the Fourier transform termwise we see that (1) is equivalent to
$$(-\lvert\xi\rvert^2 - \lambda)\hat{f}=\hat{g}, $$
which has the unique formal solution
$$\tag{2}\hat{f}=-\frac{\hat{g}}{\lambda+ \lvert\xi\rvert^2}.$$
Equation (2) determines a solution $f\in H^2$ of the resolvent equation (1) if and only if $f\in H^2$, that is
$$\tag{3}\begin{array}{ccc}
\lambda \text{ is in the resolvent set }&\iff&
(1+\lvert\xi\rvert^2 )\hat{f} = -\frac{1+\lvert\xi\rvert^2}{\lambda+ \lvert\xi\rvert^2}\hat{g}\in L^2.\end{array}$$
When $\lambda\notin (-\infty, 0]$ the function $\frac{1+\lvert\xi\rvert^2}{\lambda + \lvert\xi\rvert^2}$ is bounded, so condition (3) is satisfied. Therefore $\lambda$ belongs to the resolvent set.
On the other hand, when $\lambda\in (-\infty, 0]$, the function $\frac{1+\lvert\xi\rvert^2}{\lambda + \lvert\xi\rvert^2}$ has a singularity at $\lvert \xi \rvert= -\sqrt{\lambda}$. If $\lambda \ne 0$ then we write
$$
\frac{1+\lvert \xi\rvert^2}{\lambda +\lvert \xi\rvert^2}=\frac{1+\lvert \xi\rvert^2}{\sqrt{-\lambda}+\lvert \xi\rvert}\frac{1}{\sqrt{-\lambda}-\lvert \xi\rvert}.$$
We take a function $\hat{g}$ that is equal to $\lvert\sqrt{-\lambda}-\lvert\xi\rvert^2\rvert^{-\frac{N-1}{2}}$ in a neighborhood of the annulus $\lvert\xi\rvert=\sqrt{-\lambda}$ and vanishes elsewhere. This function is in $L^2$ but its product against $\frac{1+\lvert\xi\rvert^2}{\lambda +\lvert\xi\rvert^2}$ is not, because of the strong singularity around $\lvert\xi\rvert=\sqrt{-\lambda}$. Therefore condition (3) is not satisfied and $\lambda$ is not in the resolvent. The proof that $\lambda=0$ is not in the resolvent is completely analogous. (Alternatively, one can recall that the spectrum is always a closed set, so if the open half-line $(-\infty, 0)$ is contained in the spectrum, the value $\{0\}$ must be in the spectrum as well).

Method 2 (Added in response to Neal's comment below). Here's an alternative computation of the spectrum that determines a system of approximate eigenfunctions (in Weyl's sense).
Definition. Let $(A, D(A))$ be a closed operator on a Hilbert space $H$. We say that $f_k\in D(A)$ is a sequence of approximate eigenfunctions of $A$ relative to $\lambda\in \mathbb{C}$ if the following two conditions are satisfied:

The sequence is normalized, meaning that $\lVert f_k\rVert =1$ for all indices $k$.
It holds that: $\lVert Af_k-\lambda f_k\rVert \to 0$ as $k\to \infty$.
If $\lambda$ admits a sequence of approximate eigenfunctions then it is a spectral value. The converse holds if $\lambda$ is on the boundary of the spectrum. (For more information see Teschl, Mathematical methods in quantum mechanics, Lemma 2.16 pag.76).

In the case at hand the eigenfunction equation
$$
  \Delta f-\lambda f=0
$$
is formally solved by the plane wave profiles $e^{i\sqrt{-\lambda}\xi_0\cdot x}$, where $\xi_0$ is a unit vector. However, those profiles have not a finite $L^2$ norm. To circumvent this difficulty we fix a smooth bump function $\Phi$, normalized so that $\lVert \Phi\rVert_2=1$, and we define
 \begin{align*}
 f^0_k(x)&=\frac{1}{k^{N/2}}\Phi\left(\frac{x}{k}\right);  \\
 f^{\lambda}_k(x)&=e^{i\sqrt{-\lambda}\xi_0\cdot x} f^0_k(x).
 \end{align*}
 Here $\xi_0\in \mathbb{S}^{N-1}$ is arbitrarily chosen.
Claim. For any fixed $\lambda\in (-\infty, 0]$ the sequence $f^\lambda_k$ consists of approximate eigenfunctions of $(\Delta, H^2)$ relative to the spectral value $\lambda$.
Proof. We consider the case $\lambda=0$ first. It is obvious that the sequence $f^0_k$ belongs to $H^2$ and that it is normalized. We have
 \begin{equation*}
\lVert \Delta f^0_k\rVert_2=\frac{1}{k^2}\left\lVert \frac{1}{k^{N/2}} \Delta\Phi\left(\frac{x}{k}\right) \right\rVert_2 =\frac{C}{k^2}\to 0.
 \end{equation*}
 So $f^0_k$ is a sequence of approximate eigenfunctions. We note also that
 \begin{equation*}
\left\lVert \nabla f^0_k\right\rVert_2=\frac{1}{k}\left\lVert \frac{1}{k^{N/2}} \nabla\Phi\left(\frac{x}{k}\right) \right\rVert_2\to 0;
 \end{equation*}
this will be useful later. Now we consider the sequence $f^\lambda_k$ for a $\lambda\in (-\infty, 0)$. It is again obvious that $f^\lambda_k$ is normalized and that it belongs to $H^2$. Using the Leibniz formula for the Laplacian (that is, $\Delta(fg)=\Delta f g + 2 \nabla f\cdot\nabla g + f \Delta g$), we compute
 \begin{equation*}
 \begin{split}
 \lVert \Delta f^\lambda_k -\lambda f^\lambda_k \rVert_2 &=\left\lVert 2\nabla \left( e^{i\sqrt{-\lambda} \xi_0\cdot x}\right)\cdot \nabla f^0_k + e^{i\sqrt{-\lambda}\xi_0\cdot x} \Delta f^0_k \right\rVert_2 \\
 &\le2\sqrt{-\lambda}\lVert \xi_0\cdot \nabla f^0_k\rVert_2 + \lVert \Delta f^0_k\rVert_2 \\
 &\le 2\sqrt{-\lambda} \lVert \nabla f^0_k\rVert_2 +\lVert \Delta f^0_k\rVert_2 \to 0.
 \end{split}
 \end{equation*}
 This proves our claim.
Comment: Actually, the "eigenfunctions" of $\Delta$ are the plane wave profiles $f_\lambda(x)=e^{i\sqrt{-\lambda}\xi_0\cdot x}$, where $\xi_0\in\mathbb{R}^n$ is a unit vector. At Fourier side those correspond roughly to Dirac deltas concentrated at the point $\sqrt{-\lambda} \xi_0$. So a sequence $f_k\in H^2$ such that $\hat{f}_k$ is a bump function that concentrates more and more at $\sqrt{-\lambda} \xi_0$ should do the trick here. I have not checked the details though
Comment: Quite clear! Thank you for the alternative approach. It looks like the Fourier transform of your argument should be what you sketched in your comment.
Comment: Do you know of any constructive proofs, e.g., constructing a sequence of $\psi_k\in H^2(\mathbb{R}^n)$ satisfying Weyl's criterion?
Comment: Thank you! That makes perfect sense.
Comment: I am adding a commentary to this answer to account for your observation.
Comment: @Neal: I edited my post. Contrarily to what I wrote in the previous comment, I did not use any Fourier analysis to construct the approximate eigenfunctions. I hope that it is a bit clearer this way.
Comment: @Neal: Indeed, the Fourier transform of $\frac{1}{k^{N/2}}\Phi\left( \frac{x}{k}\right) e^{i \sqrt{-\lambda} \xi_0\cdot x}$ is $k^{N/2}\hat{\Phi}(k(\xi-\sqrt{-\lambda}\xi_0))$, which concentrates on the point $\sqrt{-\lambda}\xi_0$. What was not clear from my previous comment was that the exponent of $k$ has got to be $N/2$.
Comment: @GiuseppeNegro what happens if I consider $\Delta:C^\infty_0(\mathbb R^n)\subset L^2(\mathbb R^n)\longrightarrow L^2(\mathbb R^n)$. Does the spectrum change?
Comment: @PtF: One usually speaks of the spectrum of the *closure* of an operator, if it's closable and not closed. Taking $C^\infty_0$ as the domain of the Laplacian, we obtain a closable operator whose closure is precisely the Laplacian on $H^2$.
Answer: You can also prove that the operator is sectorial. Recall that an operator is sectorial if
there exists $a\in \mathbb{R}$, $\phi\in (0, \frac{\pi}{2})$ and $M>0$ such that the spectrum contain the sector
$S=\{ \lambda\in \mathbb{C}; \phi\leq |arg(\lambda-a)|\leq \pi; \pi\neq a \}$
and $|(\lambda I-A)^{-1}|\leq \frac{M}{|\lambda-a|}$, for each $\lambda\in S$.
You can see that, if the operator is sectorial, then the spectrum contain $(-\infty, a)$. You can find in Dlotko's book that, if an operator is symmetric and bounded below, then its sectorial and you win that a must be positive by this result.


Relatório de produtividade via git

Question: Como faço para tirar um relatório de produtividade de cada usuário no git( pode ser um programa). Por exemplo: linhas de código inseridas ou alteradas.
Comment: Linha de código serve entre outras coisas pra medir ineficiência. Geralmente quanto pior o programador, mais linha ele usa para fazer as mesmas coisas.
Comment: Primeiro, não seria um relatório de produtividade e sim de atuação...
Answer: Tem alguns projetos open source que fazem isso:

http://gitstats.sourceforge.net/
https://repo.or.cz/w/git-stats.git
https://github.com/ejwa/gitinspector

Relatório de produtividade via git


How to get the list of nodes edited by an specific user?

Question: I need to be able to see all the nodes that have been edited by an user and be able to download that info, I've been searching for a module but I can't find one.
On the log messages report I can see that info but I can't download it and also it only shows the data for the last month.
Comment: This is for Drupal 8?
Comment: Yes, sorry, Drupal 8!
Answer: You can also use Views to export that data for you, here are the rough steps,

Create a Page view which shows content.
Select the fields you want to see for the node like nid, title, author, etc.
Add Author as a filter and expose this field so that you can provide user id or username via the exposed filter form.
Save the view.
The page view should now work on the URL you provided in step 1. Here once you provide a username or user id (depending on which field you exposed) the content should get filtered.
Add a module like views_data_export, which allows you to export the list in a file.

These are very rough steps but you can play around with it to get it working, let me know if you need exact steps.
Comment: The node author is not always the revision author, I think that you are missing something in your solution.
Comment: Hello, thanks for your help, it's working perfectly. Is it possible tot find the field for the user who made the last revision?
Answer: This is how i ll get all nid of revision of an user :

All node revision are store in the node_revision table.

<code>  $connection = \Drupal::database();
  $query = $connection->query("SELECT DISTINCT(nid) FROM node_revision where revision_uid = 1");
  $result = $query->fetchAll();
  //devel module
  kint($result);
</code>
node_revision aren't entity so the only way you have is to do a manuel query.

And if you need to filter by content type :

<code>      $connection = \Drupal::database();
      $query = $connection->query("
      SELECT DISTINCT(node_revision.nid)
      FROM node_revision
      LEFT JOIN node ON node_revision.nid = node.nid
      WHERE node_revision.revision_uid = 1 and node.type='page'"

);
      $result = $query->fetchAll();
      //devel module
      kint($result);
</code>
In this table you can get the revision_log field too.
Then you can use entityManager for load all your node :
<code> \Drupal::entityManager()->getStorage('node')->loadMultiple($nids);
</code>
you need to build your $nids array with the query result.
You can load all revision too by node id.
Answer: For Drupal 8 with the following code you can get the nids that have been edited by the user:
<code>// List of modified nodes.
$modified_nodes = [];
// The user id.
$uid = 5;
//Load all the nodes.
$nodes = \Drupal\node\Entity\Node::loadMultiple();
foreach($nodes as $node) {
// Getting the revisions for each node.
$vids = \Drupal::entityManager()->getStorage('node')->revisionIds($node);
foreach ($vids as $vid) {
  // Loading revision.
  if ($revision = node_revision_load($vid)) {
    // Checking the uid and the owner.
    if($revision->getRevisionAuthor()->id() == $uid) {
      $modified_nodes[] = $node->id();
      break;
       }
    }
  }
}
// To use dpm you need the devel module.
dpm($modified_nodes);
</code>
Comment: @Patty if my answer helps you consider to check it as accepted to help other users to find the correct way, if you don't know how to do it take the tour https://drupal.stackexchange.com/tour
Comment: for me this code is not good. it work but you loop on all node ?! i ll try to answer tomorow, but with entityQuery first you ll get nid with a query condition.
Comment: It will be great if it can loop through all the nodes of a certain content type
Comment: its possible with entityQuery, i ll post an example tomorow, its night for me right now.


How to split a list into a list of sublists that contain duplicate values in Python?

Question: I have a list of lists of information about tides at certain times each day. It looks kinda like this:
tideData = [
['Thursday 4 January',11.58,0.38],
['Thursday 4 January',16.95,0.73],
['Friday 5 January',6.48,0.83],
['Friday 5 January',12.42,0.33],
['Saturday 6 January',0.5,0.02],
['Saturday 6 January',7.18,0.85],
...
['Friday 2 February',23.52,0.04]
]

I would like to split this list into sublists containing the same dates. In the case above, the list would become:
tideData = [
[['Thursday 4 January',11.58,0.38],
['Thursday 4 January',16.95,0.73]],
[['Friday 5 January',6.48,0.83],
['Friday 5 January',12.42,0.33],
['Friday 5 January',17.92,0.75]],
[['Saturday 6 January',0.5,0.02],
['Saturday 6 January',7.18,0.85]],
...
['Friday 2 February',23.52,0.04]]
]

Now, this wouldn't be a problem if there was an equal number of each date. However, the dates sometimes appear twice and sometimes appear three times. As such, I'd like to be able to sort them into sublists based on repeat dates. How would I go about this?
Comment: Have you tried something? Did you write a piece of algorithm? Did you write a piece of python? If yes, what blocks you? If no, do it :) Show that you tried, and we'll help you, it seems like basic python to me.
Comment: Possibly duplicate of [Python: how to group similar lists together in a list of lists?](https://stackoverflow.com/questions/30987825/python-how-to-group-similar-lists-together-in-a-list-of-lists)
Answer: I think you want to use groupby from the itertools package
from itertools import groupby

tideData = [
['Thursday 4 January',11.58,0.38],
['Thursday 4 January',16.95,0.73],
['Friday 5 January',6.48,0.83],
['Friday 5 January',12.42,0.33],
['Saturday 6 January',0.5,0.02],
['Saturday 6 January',7.18,0.85],
['Friday 2 February',23.52,0.04]
]

If you data is not sorted, you can use:
tideData = sorted(tideData, key=lambda x: x[0])

before using the following:
[list(g) for _,g in groupby(tideData, key=lambda x: x[0])]
# returns:
[[['Thursday 4 January', 11.58, 0.38], ['Thursday 4 January', 16.95, 0.73]],
 [['Friday 5 January', 6.48, 0.83], ['Friday 5 January', 12.42, 0.33]],
 [['Saturday 6 January', 0.5, 0.02], ['Saturday 6 January', 7.18, 0.85]],
 [['Friday 2 February', 23.52, 0.04]]]

Comment: This is my favored approach as it is guaranteed to be stable **(as long as** `tideData` **is already sorted by date)**
Comment: Note that the optional argument `key=lambda x: x[0]` in `tideData = sorted(tideData, key=lambda x: x[0])` is only needed if you want to preserve the order of the data for each day. Otherwise, you can just sort without providing a key. Tuples are sorted in lexicographical order, which gives the highest priority to `x[0]` already.
Comment: @DeepSpace Also note that python sort is a stable sort.
Answer: You can use collections.defaultdict for an O(n) solution.
In Python 3.7, you will have the added benefit that the order of values will match the order in the input. This works in Python 3.6, but is considered an implementation detail.
from collections import defaultdict

d = defaultdict(list)

for item in tideData:
    d[item[0]].append(item)

res = list(d.values())

Result:
[[['Thursday 4 January', 11.58, 0.38], ['Thursday 4 January', 16.95, 0.73]],
 [['Friday 5 January', 6.48, 0.83], ['Friday 5 January', 12.42, 0.33]],
 [['Saturday 6 January', 0.5, 0.02], ['Saturday 6 January', 7.18, 0.85]],
 [['Friday 2 February', 23.52, 0.04]]]

For those interested in performance difference between O(n) and O(n log n) solutions:
from collections import defaultdict
from itertools import groupby
from operator import itemgetter

tideData = [
['Thursday 4 January',11.58,0.38],
['Thursday 4 January',16.95,0.73],
['Friday 5 January',6.48,0.83],
['Friday 5 January',12.42,0.33],
['Saturday 6 January',0.5,0.02],
['Saturday 6 January',7.18,0.85],
['Friday 2 February',23.52,0.04]
]

tideData = tideData * 10000

def jp(tideData):
    d = defaultdict(list)
    for item in tideData:
        d[item[0]].append(item)
    return list(d.values())

def grp(tideData):
    grouper = groupby(sorted(tideData, key=itemgetter(0)), key=itemgetter(0))
    return [list(g) for _, g in grouper]

%timeit jp(tideData)   # 5.63 ms per loop
%timeit grp(tideData)  # 9.87 ms per loop

Comment: "In Python 3.6, you have the added benefit that the order of values will match the order in the input." The Python docs say that this should not be relied on as it is an implementation detail and may not hold true forever.
Comment: @DeepSpace, Guido has confirmed 3.7 will maintain order! So your quote may be overridden.
Comment: The `sort+groupby` approach incurs a `n log(n)` cost because of the sort, not because of the groupby. But you actually forgot to sort in the code.
Answer: Here is simple approach without any import :
groub_by={}
for i,j in enumerate(tideData):
    if j[0] not in groub_by:
        groub_by[j[0]]=[j]
    else:
        groub_by[j[0]].append(j)
print(groub_by.values())

output:
[[['Thursday 4 January', 11.58, 0.38], ['Thursday 4 January', 16.95, 0.73]], [['Saturday 6 January', 0.5, 0.02], ['Saturday 6 January', 7.18, 0.85]], [['Friday 5 January', 6.48, 0.83], ['Friday 5 January', 12.42, 0.33]], [['Friday 2 February', 23.52, 0.04]]]


Does the $form['element']['#disabled'] = TRUE guarantee that the user cannot edit the field or is it just a UI setting

Question: I have a form element like this:
$form['title'] = array(
  '#type' => 'textfield',
  '#title' => t('Subject'),
  '#default_value' => $node->title,
  '#size' => 60,
  '#maxlength' => 128,
  '#disabled' => TRUE,

);

Does this make the field 100% non-editable by the user or is it still possible to set a value for this field using manual form submission using jQuery / Postman to the action URL?
Answer: If you disable field in backend, the field value won't be actually changed even if you change it in HTML or by JS.
You can test it:
 - disable element in form alter
 - open element in Chrome inspector (or other) and remove disabled attribute
 - change value in field and save the form
 - changed value will not be saved


Is the MLE of an exponential distribution complete and sufficient?

Question: I've just prove that the MLE of an exponential distribution is:
$$
   \hat \theta = \frac{n}{\sum x_i}
$$
So I'm trying to show that $\hat \theta $ is complete and sufficient.
For sufficiency I've tried to apply the Fisher–Neyman factorization theorem but I can't find the function $g_\theta(T(x))$ which makes me suspect that it might not be sufficient.
For completeness I know I have to prove that $E_\theta[g(\hat \theta)] = 0$ $\forall \theta \iff g(\theta) = 0 $ $ \forall \theta $ but the sum in $\hat \theta$ is really annoying.
Any hints or suggestions?
This is not homework. I'm studying by my own.
Answer: The density for a sample from the exponential distribution is $f(\textbf x; \theta)=\theta^ne^{-\theta\sum_i x_i}$. From the Fisher-Neyman factorization theorem, $\sum_i x_i$ is a sufficient statistic for $\theta$. There is a fact that any one-to-one transformation of a sufficient statistic is also sufficient. So $\frac n{\sum_i x_i}$ is sufficient as well. The exponential distribution is from the exponential family of distributions. For one-dimensional exponential families, if the parameter space contains an open interval in $\mathbb R$, then the sufficient statistic is complete. Here $\theta\in(0,\infty)$, an open set, so the statistic is complete. So the MLE is a complete, sufficient statistic.
Here is how you would prove completeness directly from the definition. $T(x)=\sum_i x_i$ is gamma-distributed so it has density $f(t)=\frac{\theta^n}{\Gamma(n)}t^{n-1}e^{-\theta t}$, and so $E(g(T))=\int_0^\infty g(t)t^{n-1}e^{-\theta t}dt$. This is called a Laplace transform and it equals zero only if $g(t)t^{n-1}=0$, so $g(t)=0$. Thus, the sufficient statistic is complete.
Comment: The exponential distribution is NOT distributed as an exponential family if the location parameter is unknown.


Which are the differences between the typical nylon strings, and the newer fluorocarbon (or "carbon") strings?

Question: We all know the traditional nylon strings for the classical guitar, which in turn replaced the even more traditional gut strings.
Lately, more and more string manufacturers are introducing products that feature carbon strings for some specific strings in the set, or all the strings in the set. Daddario, Savarez, Hannaback, La Bella, RC, Thomastik; seems that everyone is looking to offer options made of fluorocarbon.
What's the difference?
Comment: The evolution of materials for stringed instruments is driven by performance of the product and the subsequent demand for it. The answer would lie in the consistency of tone dependent upon varying tension. Somewhere there should be engineering documentation that relates frequency, amplitude, and material.
Comment: @FrancisPhillips That's what I'm looking for! How do the carbon strings affect tone, durability, intonation, and other dynamics, in contrast to nylon.
Comment: There are two answers. 1)Try them and see if you like the tone;  2) sometimes things are manufactured for quality and sometimes for price.
Answer: Fluorocarbon have a harder, more direct response and feel, and less of a "singing" tone. In some sense, switching from nylon to FC has a similar effect as switching to a longer scale length. For an electric-guitar analogy: it feels like switching from a Les Paul to a Strat (though obviously the difference is not so extreme).
Most of that difference is just due to the higher tension, which you could also get with simply heavier nylon strings – but those still feel softer and kind of sweeter because they're also thicker, unlike FC. Thick strings can have problems with tone clarity and intonation, so if you want a more powerful sound without sacrificing that then FC can be a good choice. The downside is a somewhat less expressive, less malleable character.
Comment: Indeed, vibrato is one of the things that's easier on nylon than FC. "Brightness" – I wouldn't say there's much difference there. "Singing" – I don't mean sustain per se but tone development. In fact, FC have probably a bit _more_ sustain, but it's a more plain, "flat" sound, whereas nylon has more of a sweet harp-like trickle in each note. ...I don't know much water that description really holds, objectively, it's more of a subtle difference in feel.
Comment: By less malleability you mean that it's harder to do stuff like vibrato? And what about tone, is there an important difference in brightness?
Comment: And by singing, you mean less sustain (faster decay)?


Python - determine if a word contains a question mark within it

Question: Sometimes character encoding goes wrong, and instead of "It's", you end up with "It?s".
Using Python, can anyone advise on an expression/function which will allow me to determine these instances of a string containing "?", but not at the end of the word?
"Is This It? Nope, that's fine" = False
"It?s This" = True
Comment: Wouldn't you be better off noticing the decoding failure directly?
Comment: @Chris: why do you think encoding errors can only happen in the middle of words?
Answer: s = "Is This It? Nope, that's fine"

'?' in s[:-1].replace('? ','')

Comment: Looks like it?s been fixed.
Answer: Sounds like a job for regex to me:
import re
re.match(r'\w+?\?\w+?',"Is This It? Nope, that's fine") ##Returns a 'match object' which evaluates to True
re.match(r'\w+?\?\w+?',"It?s This") ##Returns None which evaluates to False

Then if you want to replace it:
re.sub(r'(\w+?)\?(\w+?)',r'\1\2',"It?s This") ##Returns "Its This"

The regular expression: '\w+?\?\w+?'
matches one or more word characters: '\w+?'
followed by an actual question mark(escaped): '\?'
followed again by one or more word characters: '\w+?'
this ensures the question mark is in fact in the middle of a word.
As for replacing the question mark,adding parentheses in your expression like so: '(\w+?)\?(\w+?)' creates 2 capture groups which you can then reference as group number one and group number 2 in your desired output like so: '\1\2' omitting the question mark.


Prove not general convergence of integral

Question: I am looking for an example of two distribution such that their product is not a distribution. I'm using $f=\frac{1}{\sqrt{|x|}}$ which gives the distribution $\int_{-\infty}^{+\infty}\frac{\varphi(t)}{\sqrt{|t|}}dt$, then $f^2$ gives the "distribution" $\int_{-\infty}^{+\infty}\frac{\varphi(t)}{|t|}dt$.
I think the fact that $f$ is regular integrable gives the convergence of $f=\frac{1}{\sqrt{|x|}}$, but I am not completely sure how to show that $\int_{-\infty}^{+\infty}\frac{\varphi(t)}{|t|}dt$ doesn't converge. Can I simple set $\varphi$ to be the identity?, in which case it follows immediatly from the non ocnvergence of $\frac{1}{x}$
Comment: @AndrewTindall: I  think *distribution* in this context means *generalized function* in the sense of https://en.wikipedia.org/wiki/Distribution_(mathematics) , and not *probability distribution*.
Comment: It looks like you're right. deleted
Answer: Take $\varphi\in C_{0}^{\infty}$ to be $1$ around a neighbourhood of $0$ then $\displaystyle\int_{-\infty}^{\infty}\dfrac{\varphi(t)}{|t|}dt$ does not converge. It is a standard construction such $\varphi$ must exist.


How to get Drush to use alternative php.ini

Question: I'm trying to get Drush up and running on my webserver via SSH. I'm new to working with SSH so hopefully someone can help me work this out. When checking Drush's status it mentions that the disable_functions are not empty.
So I copied the webservers php.ini to the .drush file but it still uses the php.ini from the webserver and not from my .drush folder.
I tried finding a solution online but can't get this to work. A couple of thigs I tried are:

Using a drush.ini file. If I add this I is found by drush and shown in my drush status. But it doesn't solve the disable_functions problem. It also shows the webserver php.ini file. So it's the php.ini first and then the drush.ini.
I added export PHP_INI="/path/to/.drush/php.ini" to my .bashrc file and when I run echo PHP_INI it shows the right path but it doesn't solve my problem. I also did the source ~/.bashrc to reload the .bashrc. But this didn't help.

This is the complete drush status:
<code>The following restricted PHP modes have non-empty values:            [error]
disable_functions. This configuration is incompatible with drush.
Please check your configuration settings in
/opt/alt/php56/etc/php.ini or in your drush.ini file; see
examples/example.drush.ini for details.
exec() has been disabled for security reasons preflight.inc:380      [warning]
exec() has been disabled for security reasons preflight.inc:425        [warning]
exec() has been disabled for security reasons preflight.inc:380        [warning]
exec() has been disabled for security reasons preflight.inc:380        [warning]
 PHP configuration      :  /opt/alt/php56/etc/php.ini
 PHP OS                 :  Linux
 Drush script           :  /home/bin/drush
 Drush version          :  8.0.3
 Drush temp directory   :  /tmp
 Drush configuration    :
 Drush alias files      :
</code>
Hopefully someone can help me getting this Drush installation to work.
Thanks in advance.
Zeb
Answer: Looks like you are using the Drush Phar, which does not support php.ini selection.  You must either:

Configure your webserver php-cli php.ini correctly (may not be an option if /opt/alt/php56/etc/php.ini is not writable)

or -

Install Drush via Composer per the installation instructions
Comment: Thanks! I didn't try the Composer option because my host told me it wasn't possible. But your answer made me try it any ways and it worked! Drush runs perfectly without error. I'm only coping with a _"Command pm-enable needs a higher bootstrap level to run - you will need to invoke drush from a more functional Drupal environment to run
this command."_ problem. So time to figure this new problem out.
Comment: You just need to be sure that (a) you are correctly identifying your Drupal site to Drush (e.g. via correct 'root' and 'uri' parameters in your site alias), and the user that Drush is running as has permission to access the database credentials specified in your settings.php file. There is quite a bit of discussion on those topics here; you should do fine.


How to solve : $\,8^x=6x$

Question: I am stuck on the following problem which one of my friends gave me:

Solve : $\,8^x=6x$.

MY ATTEMPTS:
We see that $$8^x=6x \implies 2^{3x}=6x.$$ Now I am not sure how to proceed further. Taking logarithm on both sides of the equation does not help much. Clearly, $x=\frac 1 3$ satisfies the given equation but I am not sure how to get it.
Can someone help? Thanks and regards to all.
Comment: Well, the Lambert-W function might help here: http://en.wikipedia.org/wiki/Lambert_W_function#Example_1 ?
Comment: I tried to solve this without using derivatives only to get frustrated. Oh well.
Answer: For simplicity let $3x=u$ so you are really looking at $2^u = 2u$. One is exponential, the other is linear and given the nature of their derivatives, they intersect at most twice. In this case, they intersect twice: at $u=1$ and $u=2$. These are the only solutions. So for your original question that means $x = 1/3$ or $x=2/3$.
Comment: @learner The function $2^u$ has a strictly positive second derivative. Which means it will get steeper and steeper. It can intersect a linear function twice: once being less steep, and once being steeper. After that, $2^u$ will never "slow down" enough to intersect $2u$ again.
Answer: In general, problems like this do not have closed-form solutions.  Taking the logarithm of this equation; you get:
$$
x\log 8 = \log x + \log 6
$$
Generalize this to
$$
ax + b\log x + c = 0
$$
If this had a solution algebraic in $a, b, c: x = A(a, b, c)$, then
$$
\begin{align}
aA + b\log A + c &= 0 \\
\log A &= -\frac{a}{b}A -\frac{c}{b} = B(a, b, c)\\
A(a, b, c) &= e^{B(a, b, c)}
\end{align}
$$
where both $A$ and $B$ are non-constant and algebraic in $a, b, c$.  That is impossible.
I originally said that $\log x$ would be algebraic, and that isn't quite right.
This problem was devised for effect.  We'll look backward here by seeing what happens if you substitute $y=3x$.
$$
\begin{align}
8^x &= 6x  \\
2^{3x} &=2 \cdot 3x\\
2^y &= 2y
\end{align}
$$
Now, we consider the coincidence that $2^2 = 2\cdot2$ and $2^1 = 2\cdot 1$.  So, $y=2$ and $y=1$ are solutions, and so $x=\frac23$ and $x=\frac13$ are solutions.  But for general constants, you can't hope to guess at a solution. You will be in the realm of numerical approximation.
Not understanding how to solve this problem is not a sign of a lack of skill. The problem is too contrived.
Comment: Thanks @Eric for the nice and detailed explanation. +1 from me.
Comment: Upvoted for that last sentence.
Comment: Nice solution Eric Jablow....
Answer: Hint: How many different roots can this equation have?
Comment: Infinitely many, if you allow complex roots.
Comment: I know what you want to get at with your hint, but right now you are just rephrasing the question. Try to clarify, or else it's in trouble.
Comment: Right now the question is answered, so there is no need in hints. :-)
Answer: $8^x=6x\implies e^{x\log 8}=6x\implies -xe^{-x\log8}\log8=-\dfrac{\log8}6$
Recall the Lambert W-function is defined as the inverse of $ze^z$ in $\Bbb C$, so if we let $t=-x\log8$, then $te^t=-\dfrac{\log8}6\implies t=W(-\dfrac{\log8}6)$
Hence, $x=-\dfrac{W(\dfrac{\log8}6)}{\log8}$.

How to solve : $\,8^x=6x$