VB.NET How to check if username and password textboxes are not empty?

Question: is there a way to check two textboxes (username, password) to have text? I'd like to check that before connect buttons gets enabled.
i tried to use two if-statements like
if not user.text = "" then
buttonlogin.enabled = true
end if

if not password.text = "" then
buttonlogin.enabled = true
end if

but the button gets enabled if one of them gets text instead of both.
Comment: The following may be of interest: [String.IsNullOrEmpty](https://learn.microsoft.com/en-us/dotnet/api/system.string.isnullorempty?view=net-8.0)
Comment: Set the computer aside, get a pen and paper, then read through your code and write down what happens in each step of your code.
Answer: Do it like this:
ButtonLogin.Enabled = Not (String.IsNullOrWhitespace(User.Text) OrElse String.IsNullOrWhiteSpace(Password.Text))

This does four things not yet shown in other answers:

Assigns the boolean expression result directly to the button's  .Enabled property, as a single line of code... no If/Else conditional expressions needed.
Uses the correct IsNullOrWhitespace() method to check the textbox values. Other answers (except one) would allow me to click the button just by putting a space or tab character (or similar) into the textbox. Even the answer with .Trim() may leave certain whitespace behind (vertical tab is one example, along with certain other unicode characters). Not that IsNullOrWhitespace() is perfect, but it performs a little better and correctly captures intent.
Uses DeMorgan's Law to factor out the negation (we only need one Not operation)
Uses a proper short-circuiting logical boolean operator (OrElse, in this case). The other answers use the older VB operators, which are actually bitwise operators rather than true logical operators. Among other things, the bitwise operators do not short circuit and can sometimes be a little odd... better to use the real logical operators most of the time.
Answer: Maybe like this.
    If String.IsNullOrWhiteSpace(user.Text) Or String.IsNullOrWhiteSpace(password.Text) Then
    MessageBox.Show("Please fill in both textboxes.", "Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Warning)
Else
    ' Both textboxes have content.
    ' Your code logic here...
End If

Answer: If not user.text = "" And not password.text = ""  Then

    buttonlogin.enabled = true

Else

    buttonlogin.enabled = false
End If

Comment: Thank you for contributing to the Stack Overflow community. This may be a correct answer, but it'd be really useful to provide additional explanation of your code so developers can understand your reasoning. This is especially useful for new developers who aren't as familiar with the syntax or struggling to understand the concepts. **Would you kindly [edit] your answer to include additional details for the benefit of the community?**
Answer: Try
if string.IsNullOrEmpty(strings.trim(user.text)) then
     buttonlogin.enable = false
else
     buttonlogin.enable = true
end if

and same for password.


Show that $\mathbb Z_p \oplus \mathbb Z_p \oplus \mathbb Z_p$ is not generated by two elements

Question:
Show that group $A = \mathbb Z_p \oplus \mathbb Z_p \oplus \mathbb Z_p$  is not generated by two elements. ($p$ is prime.)

any help or hint will be appreciated.
Comment: Hint: let $a,b$ be any two elements. They have order at most $p$. How large can the subgroup generated by them be?
Comment: Note: the fact that two elements of order $p$ cannot generate a group of order greater than $p^2$ depends on the fact that the group is abelian, which is obvious from the structure, but is not explicit in the proofs (which also work within abelian contexts). To see this note that the symmetric group on three elements of order $6$ is generated by any pair of elements of order $2$ and the alternating group on four elements of order $12$ can be generated by a pair of elements of order $3$. This comment is to highlight that abelian methods may fail in non-abelian contexts.
Comment: The group $A$ is not isomorphic to $G=Z_{p^2} \times Z_p$, since $G$ has elements of order $p^2$, but $A$ doesn't.
Comment: BTW, can you prove $\mathbb{R}^3$ has no spanning set of size two? (As a real vector space, not as an additive group.)
Comment: deleted the mistake . thanks
Answer: This hint is in the comments, but let's say $x,y$ are two elements in $\mathbb{Z}_p\oplus\mathbb{Z}_p\oplus\mathbb{Z}_p$. The subgroup generated by them is given by all elements of the form
$$ax+by$$
where $a,b\in\mathbb{Z}$ (written multiplicatively this is more obvious as it becomes $x^ay^b$). There are $p$ distinct possibilities for $a$ and $p$ distinct possibilities for $b$ (since $x$ and $y$ have order $p$). How many elements does this generate? If it's less than $p^3$ then two elements cannot generate the whole group.
Answer: You're wrong for the isomorphisms.
Hint:
$\mathbb Z_p\oplus\mathbb Z_p\oplus\mathbb Z_p$ is a $\mathbb Z_p$-vector space. What is its dimension?
Comment: This feels more like a rewording of the problem than a solution...
Comment: @gpgpgp: More  simply if $2$ elements generate the group, they generate it as a vector space, hence the dimension would be at most $2$.
Comment: The invariant basis number is non-trivial but it remains a basic fact about finite dimensional vector spaces. One cannot always reinvent the wheel. That said, the combinatorial argument  is a fine argument.
Comment: 3 dimensions . so can I say that (1,0,0) , (0,1,0) , (0,0,1) will always be in the groups and I can't make them from any two elements because ill always have one of the three elements to be 1 or 0 not both?
Comment: I didn't intend to give a solution, but a hint. The problem comes down to a problem of *vectors spaces*, not groups. This observation gives new tools to solve the problem.
Comment: that it has 2 dimensions. got it thanks
Comment: I understand your intent. My point is that this approach leverages the non-trivial fact that all bases of a vector space have the same cardinality. So if *any* given pair of linearly independent vectors don't span a space, then none will. My issue with this is that it doesn't generalise to other examples as nicely: maybe because they aren't vector spaces (but still free modules), or maybe because finding an explicit pair of linearly independent elements and proving that they don't span the whole space requires a non-negligible amount of work.
Comment: @Bernard I don't think it's reinventing the wheel in this case, as for a course at this level prior knowledge of linear algebra is not always assumed.


Analyzing Tschaikowsky's Morgengebet

Question:
if you see at the 5th measure from the photo,
there is a question mark.
How did that F#7/A# came out all of a sudden ?
Was it possible because at the measure before there is a bass movement moving down from B ? so that makes it a half step movement ?
or is it just possible that Secondary Dominants could come out of nowhere all of a sudden ?
Answer: Yes, It's possible that secondary dominants can come out of the blue all of a sudden. While the chromatic bassline definitely supports those harmonies, I don't think it's necessary in order for those chords to be used.
In this case, the F#(7)/A# starts off a long chain of secondary dominants, so it sounds even stranger. Such long chains of secondary dominants aren't unheard of, though: see the ragtime progression for more details.
Comment: Ups, I wrote this answer 5 hours ago and was interrupted to send. Now I'm afraid my answer doesn't give any new information but exactly the same as Dekkadeci's.
Comment: What do you mean by "  I don't think it's necessary in order for those chords to be used. " ?
Comment: @HyunYooPark - I mean that I don't think a chromatic bassline is necessary in order to kick off a secondary dominant chain like in the example.
Answer:
or is it just possible that Secondary Dominants could come out of nowhere all of a sudden ?

Yes, secondary dominants have this properties.
And mind the chord progression: measure 4 - 8, this is an entire cadence of secondary dominants following the circle of fifths. This progression is quite usual in all epoques and styles of music.
Comment: what do you mean by "And mind the chord progression: measure 4 -" ?
Comment: sorry, as I had no internet the second part of my answer has been deleted. I will edit.

Analyzing Tschaikowsky's Morgengebet


ICC Agreement with Repeated Measures

Question: I've got measurements from two different types of sites, lets call them "Source" and "Sensor", with a proportion measure for each ranging from 0 to 1, like so:
Source, Sensor
0.25, 0.34
0.05, 0.72
0.38, 0.26

There's some interest in finding out if Sensor could be used as a proxy for Source, as Source is much more difficult to collect samples in. The two measurements are paired, so it makes sense to me to just use an ICC agreement statistic.
Here's the rub: In addition to multiple samples of each type of site, there's potentially multiple visits to the actual sites. So for example, the data actually looks like:
SourceID, Source, Sensor
A, 0.25, 0.34
A, 0.17, 0.28
A, 0.19, 0.45
B, 0.06, 0.72
C, 0.38, 0.26
D, 0.89, 0.97
D, 0.73, 0.85
E, 0.17, 0.19

I'd like to leverage those multiple visits, but of course now all the observations aren't independent, and there are some repeated measures. Is there a way to handle ICC with repeated measures?
Comment: If I understand ICC correctly you could get a high value even if one was systematically higher than the other by a small amount compared to the differences between pairs. Does that matter to you in your application as you say you want to use one as a surrogate for the other?
Comment: @mdewey A problem with some exploration, but provisionally, there are still applications where it would be useful even if one was systematically higher.
Answer: You can do this using the tools from generalizability theory. You can think of these as extensions of the ICC that allow for multiple sources of variation (e.g., source of measurement and repeated measures).
Brennan, R. L. (2001). Generalizability Theory. New York: Springer-Verlag.
Cronbach, L.J., Nageswari, R., & Gleser, G.C. (1963). Theory of generalizability: A liberation of reliability theory. The British Journal of Statistical Psychology, 16, 137-163.
Shavelson, R.J., & Webb, N.M. (1991). Generalizability Theory: A Primer. Thousand Oaks, CA: Sage.

ICC Agreement with Repeated Measures


Why there exists an element $ y\in G\setminus L $ such that $ K/L_{G} = (\langle y \rangle L_{G})/L_{G} $?

Question: Let $ G $ is finite supersoluble group. Then $ G $ has a chief series. Let $ L $ be a subgroup of $ G $ and $ K/L_{G} $ a chief factor of $ G $ where $ L_{G} $ is the core of $ L $ in $ G $. Since $ G $ is supersoluble, $ K/L_{G} $ is a cyclic group with prime order. Clearly, $ K $ is not contained in $ L $. Why there exists an element $ y\in G\setminus L $ such that $ K/L_{G} = (\langle y \rangle L_{G})/L_{G} $?
Answer: Since $G$ is supersoluble, its chief factor is $1$ dimensional. So $|G|=|L_G||K/L_G|$. Since $|K/L_G|=p$, $K/L_G$ is generated by $yL_G$, $y\in G, y\notin L$, for otherwise $K/L_G=L_G$.
Comment: What is mean of dimensional?
Comment: Normally there are many chief factors which form a vector with a dimension. Supersoluble means there is one chief factor. So its dimension is 1.
Comment: But $ K/L_{G} = L_{G} $ don't result $ K/L_{G} = (\langle y \rangle L_{G})/L_{G} $
Comment: Can you explain?
Comment: $K/L_G$ cyclic implies $\exists y \in K$ with $\langle y \rangle L_G/L_G=K/L_G$. Then $y \in L \Rightarrow K \le L$ which is false, so $y \not\in L$.
Comment: @Derek Holt, good explanation. Also $K/L_G\ne L_G$ for $K/L_G$ is quotient group.


minimum point of gamma function and clarification of leibniz

Question: Firstly I have seen that the $\Gamma$ function clearly has a minimum point at about $(1.462,0.886)$ and that this cannot be completely calculated using calculus, as shown below:
$$\Gamma(z)=\int_{0}^{\infty}t^{z-1}e^{-t}dt$$
and since the simplified Liebniz integral rule states that:
$$\frac{d}{dx}\int_{a}^{b}{f(x,t)}dt=\int_{a}^{b}{\frac{\partial}{\partial_{x}}f(x,t)dt}$$
so if we rewrite the gamma function as:
$$\Gamma(z)=\int_{0}^{\infty}{e^{(z-1)\ln(t)}\,e^{-t}}\,dt$$
then we can deduce that:
$$\Gamma'(z)=\int_{0}^{\infty}{\ln(t)\,t^{z-1}\,e^{-t}}\,dt$$
and since we want to find the minimum point we can let $\Gamma'(z)=0$
In addition to this, since it is a minimum point, we know that the second differential is greater than zero, so: $\Gamma''(z)>0$
However, after this point I have got stuck on how people have got from this result to a numerical answer, my only thought was:
$$\frac{d}{dt}\Gamma'(z)=[\ln(t)\,t^{z-1}\,e^{-t}]_{0}^{\infty}$$
so maybe:
$$\lim_{t\to\infty}[\ln(t)\,t^{z-1}\,e^{-t}]-\lim_{t\to0}[\ln(t)\,t^{z-1}\,e^{-t}]=0$$
But I am not sure if this is correct and how this would help find a solution.
Comment: For a numerical answer you can simply compute the positive zero of the digamma function.
Answer: As far as I remember, Ramanujan wrote (I cannot find it again)
$$\psi(x)\sim \log \left(x-\frac{1}{2}\right)$$ which is a very good approximation as soon as $x > 4$.
So, the zero of $\psi(x)$ is "close" to $\frac 3 2$ (using any numerical method, it is $1.46163$). Using the approximation, the minimum would be $$\approx\Gamma \left(\frac{3}{2}\right)=\frac{\sqrt{\pi }}{2}\approx 0.886227$$ while the numerical value would be $\approx 0.885603$.


Como fazer um programa calcular a área de diversos objetos separadamente utilizando os valores dados pelo usuário (scanner)

Question: Sou novo aqui e novo na programação, acredito que a melhor forma de firmar os conceitos e aprender é na prática.
Por isso tentei fazer alguns programinhas básicos no Eclipse (também uso Intellij) e a princípio deu certo, quis usar o Scanner do java para poder inserir valores mas no último programa que fui fazer não consegui fazer certo e estou nisso a horas...
Acredito que seja bem simples, o programa consiste em calcular a área de objetos (triângulo e trapézio eu inseri, apenas para testar) com o valor dado pelo usuário por exemplo:

A fórmula da área de um triângulo é A = (b*h)/2 sendo b = base e h = altura.
  Os valores de b e h quem vai dar é o usuário no console e assim o programa vai calcular e retornar o valor da área (A) de acordo com o objeto geométrico escolhido.

Mas o problema não está na resolução da conta, nesta parte está tudo certinho.
O problema está na hora de fazer o usuário escolher qual objeto geométrico (triângulo ou trapézio) ele quer saber a área para o programa calcular e executar somente o bloco de código daquele objeto, ignorando o outro já que ele não foi escolhido.
O meu programa pede o valor dos dois e independente do que eu faça ele não executa só um deles, pode ser variados erros que cometi e como leigo nesse assunto peço ajuda para resolver, seja por um código totalmente novo ou reaproveitando o meu.
Segue abaixo o código:
package course;
import java.util.Scanner;
public class UtilizandoScanner1 {
public static void main(String[] args) {
    /*Descubra a área do que o usuário passar
     * Trapézio: A = ((B + b)/2) * h
     * B = Base maior, b = base menor, h = altura
     *
     * Triângulo: A = (B*h)/2
     * B = Base, h = altura
     */

    System.out.println("Bem-vindo ao calculador de área!");
    System.out.println("Informe qual objeto quer calcular: ");

    Scanner input = new Scanner(System.in);

    boolean trapézio = true, triângulo = true;

    if(trapézio){
        Double B,b,h,A;
        //coletando os valores do usuário
        System.out.println("Informe o valor de B = base maior: ");
        B = input.nextDouble();
        System.out.println("Informe o valor de b = base menor: ");
        b = input.nextDouble();
        System.out.println("Informe o valor de h = altura");
        h = input.nextDouble();
        //calculando
        A = ((B + b)/2)*h;
        System.out.println("O valor dado é B: "+B+" b: "+b+" h: "+h);
        System.out.println("A área do trapézio é: "+A);
        input.close();
    }
    if(triângulo){
        Double B,h,A;
        //coletando valores do usuário
        System.out.println("Informe o valor de B = base: ");
        B = input.nextDouble();
        System.out.println("Informe o valor de h = altura: ");
        h = input.nextDouble();
        //calculando
        A = (B*h)/2;
        System.out.println("O valor dado é B: "+B+" h: "+h);
        System.out.println("A área do triângulo é: "+A);
        input.close();
    }

}

}
Comment: Bom, declarei booleanos para que quando o usuário digitar no console um objeto geométrico ele passe a ser verdadeiro e seja executado o bloco de código dele, e o restante dos objetos geométricos sejam falsos, não executando nenhum, mas não tô conseguindo passar isso na prática, sinto que falta alguma coisa, no código agora eu coloquei os ''if'' = true, quando coloquei falso nos dois o console não deixou eu digitar nada, sendo assim conclui que preciso arrumar um jeito dele considerar false todos menos o que foi digitado no console
Comment: Você pode fazer uma espécie de menu de opções para o usuário, pedindo que ele digite 1- para triângulo, 2 para quadrado etc. Usando um `if`, vai avaliar qual a opção que ele escolheu e, então, chamar o método de acordo para aquela forma geométrica (você pode construir um para cada forma). Dentro de cada método, você pode pedir para o usuário os parâmetros que você necessita para aquela determinada forma (raio para o círculo, lado para o quadrado etc.). É uma forma bem básica de se fazer, há melhores, mas para começar está bem ok.
Comment: Fiz algumas alterações, consegue dar uma olhada ?
Comment: Você definiu booleanos, mas falta pensar como você vai associar o que o usuário digitou e esses booleanos para executar o bloco de código que lhe interessa. Pense primeiro, "execute" o passo a passo do seu programa na cabeça e só então codifique. Programar é passar 90% pensando na solução do problema e 10% atualmente digitando.
Comment: Sim, compreendo que o exercício mental é essencial, mas estou nele a umas 5 horas kkkk, sério, já refiz muita coisa, fiz de novo, tentei fazer um orientado a classes e um main principal (não sei se seria assim que define) mas tá complicado.
Comment: Esqueça orientação a objetos por enquanto. Você tem questões mais básicas que isso para resolver (algo normal para um iniciante) antes. Por exemplo, explicar a si mesmo por que faz determinada coisa. Você declarou booleanos, mas não sabe o que quer fazer com eles. Que tal inicializá-los com `false` e só atribuir `true` para o booleano que representa a forma geométrica que o usuário escolheu? Claro que para isso você precisa primeiro avaliar o que o usuário escreveu para então saber qual booleano modificar, correto?
Comment: Não deixa você digitar porque você na prática não oferece nenhuma chance para o usuário digitar algo fora do `if`, apenas quando o código cai em algum dos blocos dentro dele. Logo, se as variáveis são inicializadas com `false`, nenhum bloco será executado e você não terá mesmo como digitar nada. Conclui-se então que você deve oferecer uma chance a ele antes de tudo. Após ele digitar, você vai ter que pegar o que ele digitou e comparar: se ele digitou X, então devo setar o booleano X para true, se ele digitou Y, então Y deve ser true etc.
Comment: Você também concluiu que, se deixar as variáveis como `true`, seu código sempre executará todos os blocos, certo? É por isso que elas devem iniciar como `false` e só uma ser `true` por vez.
Comment: Mas independente do que eu faça ele sempre começa a executar o código pelo primeiro '' if '' e se eu por exemplo deixo trapézio como falso e triângulo como verdadeiro ele trava no trapézio e não consigo fazer ele ''pular'' esta etapa, falta algo que não adicionei no código para quando aparecer no console " Informe qual objeto quer calcular: "e eu digitar ''triângulo'' ele automaticamente pule o trapézio, ou me falta conhecimento ou estou fazendo algo errado.
Answer:     public static void main(String[] args) {
        /*Descubra a área do que o usuário passar
         * Trapézio: A = ((B + b)/2) * h
         * B = Base maior, b = base menor, h = altura
         *
         * Triângulo: A = (B*h)/2
         * B = Base, h = altura
         */

        boolean trapezio = false, triangulo = false;

        System.out.println("Bem-vindo ao calculador de área!");
        System.out.println("Informe qual objeto quer calcular: ");

        Scanner input = new Scanner(System.in);

        String escolhaDoUsuario = new String();
        escolhaDoUsuario = input.next();

        if(escolhaDoUsuario.equals("trapezio")) {
            trapezio = true;
        } else if(escolhaDoUsuario.equals("triangulo")) {
            triangulo = true;
        }

        if(trapezio){
            Double B,b,h,A;
            //coletando os valores do usuário
            System.out.println("Informe o valor de B = base maior: ");
            B = input.nextDouble();
            System.out.println("Informe o valor de b = base menor: ");
            b = input.nextDouble();
            System.out.println("Informe o valor de h = altura");
            h = input.nextDouble();
            //calculando
            A = ((B + b)/2)*h;
            System.out.println("O valor dado é B: "+B+" b: "+b+" h: "+h);
            System.out.println("A área do trapézio é: "+A);
            input.close();
        }
        if(triangulo){
            Double B,h,A;
            //coletando valores do usuário
            System.out.println("Informe o valor de B = base: ");
            B = input.nextDouble();
            System.out.println("Informe o valor de h = altura: ");
            h = input.nextDouble();
            //calculando
            A = (B*h)/2;
            System.out.println("O valor dado é B: "+B+" h: "+h);
            System.out.println("A área do triângulo é: "+A);
            input.close();
        }
    }

Esta é uma implementação bem ingênua, mas a ideia era apenas finalizá-la usando a lógica que você desenvolveu. Uma "versão 2.0" poderia ter várias melhorias:

E se o usuário digitar "TRIANGULO"?
Usar métodos em vez de blocos de código.
E se o usuário digitar uma forma geométrica não prevista pelo programa? E se ele não digitar nada?
Perguntar ao usuário se ele deseja calcular outra figura em vez de o programa simplesmente sair após executar uma vez.
Usar apenas uma estrutura de if.
Eliminar os booleanos.

A lista poderia ser ainda maior. Fica por você estudar estruturas de repetição como while, estruturas de fluxo como o switch, investigar o método equals() que utilizei etc.
Comment: Sei que aqui está escrito para evitar um "obrigado", mas obrigado, hoje foi o primeiro dia que usei o stackoverflow e não achei que seria respondido dentro do que eu pedi, enfim, irei fazer sim um "2.0" e adicionar informações, valeu!.


How do I use an `onRequest` Firebase Function from the Emulator?

Question: I have a firebase function that is fired as a return_url from an external api... use goes to the external site, does stuff, and then a return_url is used to send data back to my app.
It is a Firebase Function onRequest. The deployed url to the function is something like https://us-central1-<project-id>.cloudfunctions.net/<function name>

What url would I use for the same function when I'm using the local emulators and how would I find that on my own?
Where's the documentation for Firebase Functions with the Emulator?
Comment: Some services offer testing tools e.g. Stripe CLI can trigger test webhooks for localhost. Or [NGROK](https://ngrok.com/) is pretty useful too.
Answer: As stated in the official Firebase documentation:

Used as arguments for onRequest(), the Request object gives you access to the properties of the HTTP request.

And from the official documentation for the Cloud Functions emulator:

The Firebase CLI includes a Cloud Functions emulator which can emulate the following function types:

HTTPS functions

Therefore, onRequest event is supported and should be used as normal for both the code deployed to Firebase and the code running in the local emulator.
Also, the documentation shows how the local URL is formed as follows:
https://localhost:5001/my-project/us-central1/helloWorld

Instrument your app for HTTPS functions emulation
Each HTTPS function in your code will be served from the local emulator using the following URL format:
http://$HOST:$PORT/$PROJECT/$REGION/$NAME
For example, a simple  helloWorld  function with the default host port and region would be served at:
https://localhost:5001/my-project/us-central1/helloWorld

Also, as shown in this tutorial, when you start the emulator, in the CLI you can view the local URL for each emulator (Firestore, functions, etc.) and its UI if it applies.

...
✔  functions[helloWorld]: http function initialized
(http://localhost:5001/my-project/us-central1/helloWorld).

┌─────────────────────────────────────────────────────────────┐
│ ✔  All emulators ready! It is now safe to connect your app. │
│ i  View Emulator UI at http://localhost:4001                │
└─────────────────────────────────────────────────────────────┘

┌───────────┬────────────────┬─────────────────────────────────┐
│ Emulator  │ Host:Port      │ View in Emulator UI             │
├───────────┼────────────────┼─────────────────────────────────┤
│ Functions │ localhost:5001 │ http://localhost:4001/functions │
└───────────┴────────────────┴─────────────────────────────────┘
  Emulator Hub running at localhost:4400
  Other reserved ports: 4500
...


How to avoid MFC application 's icon is stacked?

Question: I have created a new project by copying an existing project. I want this newly created project to be recognized as another project. In the case of the registry, I was able to change some settings to make it recognized as another program. However, it is impossible to avoid the phenomenon of overlapping icons on the taskbar as if the same program was running. What value do I need to modify to be recognized as a different program?
Please give me piece of advices.
Comment: Don't manually modify the registry. Not only is that dangerous, it only works on your local computer. You need to change the code. Modify all places where the AppWizard inserted strings that are meant to be unique to your application. Make them unique to the application.
Comment: Maybe change the `AppTitle` string? The .exe name? Also take o look into the registry entry `[HKEY_CLASSES_ROOT\Applications\AppName.exe]`, `FriendlyAppName` key. Related documentation: https://learn.microsoft.com/en-us/windows/win32/shell/app-registration?redirectedfrom=MSDN#applications
Comment: Perhaps is this you are searching for? https://stackoverflow.com/a/60975488/383779
Comment: Also remember to check if InitInstance called SetRegistryKey and if so, adjust the key name.
Answer: I figured out how to recognize the uniqueness of MFC apps. Generally, when a project is created through the MFC wizard, a function called SetAppID is called in the class inheriting CWinAppEx to define the uniqueness of the app. If you give an appropriate eigenvalue to that part, it will be recognized as another program. Thanks to everyone who helped in the comments above.
Comment: _"eigenvalue"_ ? Are you shure this is the correct word?


How to access aerospike-client-rest /v3/api-docs

Question: I tried to run aerospike-client-rest in Docker.
following the steps from this github link

docker build -t aerospike-client-rest .
docker run -itd --rm -p 8080:8080 --name AS_Rest1 -e aerospike_restclient_hostname=172.17.0.3 aerospike-client-rest

Was able to access the following:

http://localhost:8080/v1/cluster
http://localhost:8080/swagger-ui.html
http://localhost:8080/v2/api-docs

But not http://localhost:8080/v3/api-docs
Answer: The latest version is available on Docker Hub.
https://hub.docker.com/r/aerospike/aerospike-client-rest/tags
Answer: Which version of Aerospike REST Client are you using?
Open API 3 support was added in version 1.10.0 (latest is 1.10.4).
Anything prior to that uses the Swagger 2 documentation which explains why you are able to access http://localhost:8080/v2/api-docs instead of http://localhost:8080/v3/api-docs.
Comment: latest on this dockerhub link https://hub.docker.com/r/aerospike/aerospike-client-rest
Comment: Thanks for raising this issue, we will upload the latest version of Aerospike REST Client to dockerhub.


Need help on learning java frameworks quickly

Question: I wrote a piece of java code using threads, JDBC, Java Mail API etc. without using any of the frameworks (read Spring). I am frankly not too comfortable learning them first (lots of terminologies to remember!) and use them. So, please suggest me some ways to refine my existing code incorporating few of these framework concepts applicable to the aforementioned things without having to learn a lot about them. Is there any quick way to learn some vital framework concepts and use it.. sounds certainly foolish, but still looking for somebody's experiences :)
Answer: If you aren't interested in frameworks, your code should at least use interfaces and layering that's appropriate.  Your app will be well-layered if you have interfaces for services and repositories whether you use a framework or not.
You should have a front controller servlet that accepts all requests.
You should bind and validate all requests prior to processing in the service tier.
The services should be completely separate from your web tier.  If you can't unbolt the web UI and have the rest of the stuff work, you're doing it wrong.
Answer: for your simple stuff i dont really see a value add of using framework. u could replace the thread handling with the Java 5 Executors though. And if you want IoC/dependency injection then look into Google Guice
Comment: Guice is just as much a framework as Spring is.  I don't see what makes it more acceptable.
Comment: Guice is just for dependency injection and extremely lightweight. Spring on the other hand is (after years of development) a monster.
Answer: I am not one of those people that can read a book and understand (although, I certainly wish I was that type).  I have to learn by doing so I suggest installing an IDE that supports the framework you want to learn and do the tutorials or build something that you can use personally.  Couple that with some books/internet for reference and guidance.  Good luck!


Talend HiveDB connection needs cloudera SerDe

Question: I'm trying to connect Talend Open studio to Hive.
In Hive i have table with custom defined fields(from cloudera-twitter-example).
Open studio find table without problems, but if I try to Retrieve Schema i get such error:

And in talend log i get:
<code>!ENTRY org.talend.platform.logging 4 0 2015-09-21 10:49:12.375
!MESSAGE 2015-09-21 10:49:12,372 ERROR org.talend.commons.exception.CommonExceptionHandler  - java.lang.reflect.InvocationTargetException

!STACK 0
java.sql.SQLException: java.lang.reflect.InvocationTargetException
    at org.talend.metadata.managment.hive.EmbeddedHiveDataBaseMetadata.getColumns(EmbeddedHiveDataBaseMetadata.java:401)
    at org.talend.core.model.metadata.builder.database.manager.ExtractManager.getColumnsResultSet(ExtractManager.java:844)
    at org.talend.core.model.metadata.builder.database.manager.ExtractManager.extractColumns(ExtractManager.java:641)
    at org.talend.core.model.metadata.builder.database.manager.ExtractManager.returnMetadataColumnsFormTable(ExtractManager.java:521)
    at org.talend.core.model.metadata.builder.database.ExtractMetaDataFromDataBase.returnMetadataColumnsFormTable(ExtractMetaDataFromDataBase.java:224)
    at org.talend.repository.ui.wizards.metadata.table.database.DatabaseTableForm.pressRetreiveSchemaButton(DatabaseTableForm.java:1150)
    at org.talend.repository.ui.wizards.metadata.table.database.DatabaseTableForm.access$13(DatabaseTableForm.java:1121)
    at org.talend.repository.ui.wizards.metadata.table.database.DatabaseTableForm$4.widgetSelected(DatabaseTableForm.java:795)
    at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:248)
    at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
    at org.eclipse.swt.widgets.Display.sendEvent(Display.java:4454)
    at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1388)
    at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:3799)
    at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3409)
    at org.eclipse.jface.window.Window.runEventLoop(Window.java:832)
    at org.eclipse.jface.window.Window.open(Window.java:808)
    at org.talend.repository.metadata.ui.actions.metadata.AbstractCreateTableAction.handleWizard(AbstractCreateTableAction.java:139)
    at org.talend.repository.metadata.ui.actions.metadata.AbstractCreateTableAction$1$1.run(AbstractCreateTableAction.java:1088)
    at org.talend.repository.RepositoryWorkUnit.executeRun(RepositoryWorkUnit.java:93)
    at org.talend.core.repository.model.AbstractRepositoryFactory.executeRepositoryWorkUnit(AbstractRepositoryFactory.java:256)
    at org.talend.repository.localprovider.model.LocalRepositoryFactory.executeRepositoryWorkUnit(LocalRepositoryFactory.java:3227)
    at org.talend.core.repository.model.ProxyRepositoryFactory.executeRepositoryWorkUnit(ProxyRepositoryFactory.java:1996)
    at org.talend.repository.metadata.ui.actions.metadata.AbstractCreateTableAction$1.runInUIThread(AbstractCreateTableAction.java:1110)
    at org.eclipse.ui.progress.UIJob$1.run(UIJob.java:97)
    at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java:35)
    at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java:136)
    at org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java:3774)
    at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3412)
    at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$9.run(PartRenderingEngine.java:1151)
    at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332)
    at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1032)
    at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:148)
    at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:636)
    at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332)
    at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:579)
    at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:150)
    at org.talend.rcp.intro.Application.start(Application.java:183)
    at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:380)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:235)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:648)
    at org.eclipse.equinox.launcher.Main.basicRun(Main.java:603)
    at org.eclipse.equinox.launcher.Main.run(Main.java:1465)
    at org.eclipse.equinox.launcher.Main.main(Main.java:1438)
Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.talend.metadata.managment.hive.EmbeddedHiveDataBaseMetadata.getColumns(EmbeddedHiveDataBaseMetadata.java:370)
    ... 49 more
Caused by: java.lang.RuntimeException: MetaException(message:java.lang.ClassNotFoundException Class com.cloudera.hive.serde.JSONSerDe not found)
    at org.apache.hadoop.hive.ql.metadata.Table.getDeserializerFromMetaStore(Table.java:276)
    at org.apache.hadoop.hive.ql.metadata.Table.getDeserializer(Table.java:256)
    at org.apache.hadoop.hive.ql.metadata.Table.getCols(Table.java:595)
    at org.apache.hadoop.hive.ql.metadata.Table.getAllCols(Table.java:612)
    ... 54 more
Caused by: MetaException(message:java.lang.ClassNotFoundException Class com.cloudera.hive.serde.JSONSerDe not found)
    at org.apache.hadoop.hive.metastore.MetaStoreUtils.getDeserializer(MetaStoreUtils.java:385)
    at org.apache.hadoop.hive.ql.metadata.Table.getDeserializerFromMetaStore(Table.java:274)
    ... 57 more
</code>
Most important message is
<code>Caused by: java.lang.RuntimeException: MetaException(message:java.lang.ClassNotFoundException Class com.cloudera.hive.serde.JSONSerDe not found)
at org.apache.hadoop.hive.ql.metadata.Table.getDeserializerFromMetaStore(Table.java:276)
at org.apache.hadoop.hive.ql.metadata.Table.getDeserializer(Table.java:256)
at org.apache.hadoop.hive.ql.metadata.Table.getCols(Table.java:595)
at org.apache.hadoop.hive.ql.metadata.Table.getAllCols(Table.java:612)
... 54 more
Caused by: MetaException(message:java.lang.ClassNotFoundException Class com.cloudera.hive.serde.JSONSerDe not found)
at org.apache.hadoop.hive.metastore.MetaStoreUtils.getDeserializer(MetaStoreUtils.java:385)
at org.apache.hadoop.hive.ql.metadata.Table.getDeserializerFromMetaStore(Table.java:274)
... 57 more
</code>
This message shows that Talend Open Studio for big data cannot find SerDe.
But I placed hive-serede on all hadoop cluster knots and Informatica PowerCenter can get schema information from hive.
Also when i use Hive CLI on knots or Hue to run queries over HIve it works without any problems and extra configurations like
ADD JAR
How can i make Talend Open studio working with my Hive  tables?

Hadoop: CDH 5.4.3
Talend Open studio 6.0.1
Hive  1.1.0+cdh5.4.3+151
Answer: I solved this issue. By default Talend Open Studio is trying to work with Hive metastore directly.
So called embedded connection. (Metastore port is 9093)
But in connection setting i saw port 10000 that pointed me to Hiveserver2(Thrift).
After switching to standalone connection in began working.


MCollective with RabbitMQ stops responding

Question: Using MCollective (2.2.3) with RabbitMQ (3.1.5) on RedHat 6.5, MCollective stops responding after a first successful ping.
When I restart RabbitMQ, it works again.
root@rabbitmqserver# /etc/init.d/rabbitmq-server restart
Restarting rabbitmq-server: SUCCESS
rabbitmq-server.
root@rabbitmqserver# rabbitmqctl list_consumers -p /mcollective  |  grep directed
amq.gen-1amX9Z9w6jBKNP7IQrMfjg  <firstname.lastname@example.com>  Q_/exchange/mcollective_directed/srv114 false
amq.gen-dxFvTuxvQZOU0d1e7XuJJg  <email@example.com>  Q_/exchange/mcollective_directed/srv98  false
amq.gen-lwttnRCCTON9hgPg7X2zZw  <firstname.lastname@example.com> Q_/exchange/mcollective_directed/srv99  false
amq.gen-pG4o5csOGcam9mxvIQvQ7g  <firstname.lastname@example.com>  Q_/exchange/mcollective_directed/srv57  false
amq.gen-xtRFm6aAoeV2mDO9dTAyyA  <firstname.lastname@example.com>  Q_/exchange/mcollective_directed/srv115 false

user@mco-client$ mco ping

srv114                        time=66.49 ms
srv57                         time=69.34 ms

---- ping statistics ----
2 replies max: 69.34 min: 66.49 avg: 67.91
user@mco-client$  mco ping

---- ping statistics ----
No responses received

root@rabbitmqserver# rabbitmqctl list_consumers -p /mcollective  |  grep directed
amq.gen-1amX9Z9w6jBKNP7IQrMfjg  <email@example.com>  Q_/exchange/mcollective_directed/srv114 false
amq.gen-dxFvTuxvQZOU0d1e7XuJJg  <firstname.lastname@example.com>  Q_/exchange/mcollective_directed/srv98  false
amq.gen-lwttnRCCTON9hgPg7X2zZw  <firstname.lastname@example.com> Q_/exchange/mcollective_directed/srv99  false
amq.gen-pG4o5csOGcam9mxvIQvQ7g  <email@example.com>  Q_/exchange/mcollective_directed/srv57  false
amq.gen-xtRFm6aAoeV2mDO9dTAyyA  <email@example.com>  Q_/exchange/mcollective_directed/srv115 false

If I try using another command (such as package), it fails right after the discovery (after restarting RabbitMQ that is):
user@mco-client$ mco package status bash
Do you really want to operate on packages unfiltered? (y/n): y

 | [ >                                                             ] 0 / 2
[... stalled ...]

After a while, I start seeing this in my MCollective server logs:
E, [2014-03-18T11:51:01.332969 #24456] ERROR -- : base.rb:29:in `run' Sending registration message failed: Stomp::Error::NoCurrentConnection
E, [2014-03-18T11:55:35.759653 #24456] ERROR -- : agents.rb:138:in `dispatch' Execution of discovery failed: Stomp::Error::NoCurrentConnection
E, [2014-03-18T11:55:35.760040 #24456] ERROR -- : agents.rb:139:in `dispatch' /usr/lib/ruby/gems/1.8/gems/stomp-1.2.2/lib/stomp/connection.rb:331:in `publish'
        /usr/libexec/mcollective/mcollective/connector/rabbitmq.rb:184:in `publish'
        /usr/lib/ruby/site_ruby/1.8/mcollective/message.rb:230:in `publish'
        /usr/lib/ruby/1.8/timeout.rb:67:in `timeout'
        /usr/lib/ruby/site_ruby/1.8/mcollective/message.rb:218:in `publish'
        /usr/lib/ruby/site_ruby/1.8/mcollective/runner.rb:129:in `reply'
        /usr/lib/ruby/site_ruby/1.8/mcollective/runner.rb:83:in `agentmsg'
        /usr/lib/ruby/site_ruby/1.8/mcollective/agents.rb:132:in `dispatch'
        /usr/lib/ruby/1.8/timeout.rb:67:in `timeout'
        /usr/lib/ruby/site_ruby/1.8/mcollective/agents.rb:125:in `dispatch'
        /usr/lib/ruby/site_ruby/1.8/mcollective/agents.rb:121:in `initialize'
        /usr/lib/ruby/site_ruby/1.8/mcollective/agents.rb:121:in `new'
        /usr/lib/ruby/site_ruby/1.8/mcollective/agents.rb:121:in `dispatch'
        /usr/lib/ruby/site_ruby/1.8/mcollective/runner.rb:82:in `agentmsg'
        /usr/lib/ruby/site_ruby/1.8/mcollective/runner.rb:55:in `run'
        /usr/lib/ruby/site_ruby/1.8/mcollective/runner.rb:50:in `loop'
        /usr/lib/ruby/site_ruby/1.8/mcollective/runner.rb:50:in `run'
        /usr/lib/ruby/site_ruby/1.8/mcollective/unix_daemon.rb:30:in `daemonize_runner'
        /usr/lib/ruby/site_ruby/1.8/mcollective/unix_daemon.rb:13:in `daemonize'
        /usr/lib/ruby/site_ruby/1.8/mcollective/unix_daemon.rb:5:in `fork'
        /usr/lib/ruby/site_ruby/1.8/mcollective/unix_daemon.rb:5:in `daemonize'
        /usr/lib/ruby/site_ruby/1.8/mcollective/unix_daemon.rb:20:in `daemonize_runner'
        /usr/sbin/mcollectived:43
E, [2014-03-18T11:56:01.336954 #24456] ERROR -- : base.rb:29:in `run' Sending registration message failed: Stomp::Error::NoCurrentConnection
E, [2014-03-18T12:01:01.343415 #24456] ERROR -- : base.rb:29:in `run' Sending registration message failed: Stomp::Error::NoCurrentConnection
E, [2014-03-18T12:06:01.347218 #24456] ERROR -- : base.rb:29:in `run' Sending registration message failed: Stomp::Error::NoCurrentConnection
E, [2014-03-18T12:11:01.354069 #24456] ERROR -- : base.rb:29:in `run' Sending registration message failed: Stomp::Error::NoCurrentConnection

even though the machine is still listed as a consumer on the RabbitMQ server.
What could be going wrong here?
Answer: RabbitMQ had disk_free_limit set to 1000000000 in rabbit.app. This caused RabbitMQ to drop connections when available disk space in /var was lower than 950MB…


Will the main effect of two binary independent variables change when I enter them in a regression with their interaction term?

Question: If I have two dummy independent variables (both binary, with two levels each) in a regression, then how do I construct the the interaction variable? By coding both variables as (1,0) and multiplying them?
Let's say, I put the two dummy coded IVs and their interaction term in a regression, would the p value associated with the resulting main effects and interaction be the same as the p value obtained for the main effects and interaction in an ANOVA? I know that an ANOVA is supposed to be equivalent to a regression, but in an ANOVA, the main effects will be the same regardless of whether I calculate an interaction. Whereas in the regression, if the interaction term is correlated with the two dummy variables, it can affect the estimate (and resulting p values) of the main effect of the two dummy variables (and the interaction term also).
 Also, in case of interactions, should the dummy variables always be coded as (1,0) or can they also be coded as (1,-1) and then multiplied if I predict a certain type of interaction? Thanks
Answer:
If I have two dummy independent variables (both binary, with two levels each) in a regression, then how do I construct the the interaction variable? By coding both variables as (1,0) and multiplying them?

Yes.  When both are 1, then the interaction is 1, else 0.
As for the second part of your post, there is a lot of unpack there.

...the main effects will be the same regardless of whether I calculate an interaction.

Really?  This is news to me.  ANOVA is a linear model, and so unless the interaction forms an additional orthogonal column to an already orthogonal design matrix, then I don't see a good reason why this would happen.


Can Cisco wlan-controllers (nm-air-wlc6) function like a regular fast-ethernet port?

Question: I have a Cisco router at school that has a wlan-controller.I connected a wlan-controller to another fast-ethernet port on another router and  configured ip addresses. Although they are directly connected they are not able to ping each other.
I want to know if you can configure it to work as a regular ethernet port.
Answer: As per http://www.cisco.com/en/US/docs/ios/12_4/12_4x/12_4xa/boxernm.html , the FE port is not supported, so, no.


Interpreting QQplot

Question: This is a question about how to understand qqplot results. To present the problem, I have a set of 54 measurements from archaeological objects. I calculated both kurtosis and skewness with the Moments package and I plotted the data with ggplot, to assess if they followed a normal distribution.
<code>> library(ggplot2)
> library(moments)

> volume
[1]  39.984  77.280  81.252  98.304 113.520 190.190 440.220 739.500 750.120  35.100  57.960 170.586 225.262 574.308 584.100 609.280 711.360 746.928 186.576
[20]   1.500   1.512   1.890   1.950   5.280   7.200   7.200   9.200   9.280  24.752  39.528  49.880  67.620  73.950 342.000 401.625 468.000 512.818 565.250
[39]  29.040  80.344  68.370  88.830 121.176 128.800 133.200  18.000  69.312  89.880 180.264 265.680 412.720 638.400 680.400 506.000

> volume <- as.data.frame(volume)
> kurtosis(volume)
  volume
2.280249
> skewness(volume)
   volume
0.8915582

> ggplot(volume) + geom_qq(aes(sample=volume)) + stat_qq_line(aes(sample=volume)) + theme_bw() + xlab("Theoretical") + ylab("Sample") + ggtitle("Quantile-Quantile")
</code>

The shape of the curve seems very odd, and I'm not sure how to understand it. Does it simply shows that these are, in fact, samples from two populations? Or maybe I'm trying a calculation that doesn't make sense? I've been looking for similar cases over the internet, but couldn't find any.
Comment: You should always think about what your data *are*, & how they arose & were gathered & measured. Given that your variable is called "volume", I wonder if these are [volumes](https://en.wikipedia.org/wiki/Volume). In addition, there is an obvious floor effect that the values asymptote to 0.  The normal distribution goes to negative infinity, whereas volumes cannot be negative. Thus, if they are volumes, they cannot be normal by definition. Also perhaps of interest is that there may be a ceiling effect. Do you have any thoughts on whether that might be true and why?
Comment: "Measurements of archeological objects" are almost surely positive -- but *pace* @gung, that does not rule out the use of a Normal distribution to model and even describe them.  There's no reason to think that a set of volumes could not be approximately Normally distributed (although, in practice, there are many reasons to suppose their *cube roots* might have a near Normal distribution).  The issue here is that, as you suspect, the distribution is clearly bimodal and perhaps ought to be considered a set of measurements from two populations.
Comment: Hmm, that's intereseting @gvanhavre.  I wonder if it would make more sense to work with the three individual measurements.  Are they just length, width, & height?  What is it that you ultimately want to do with / know about these data?  Often, people think it's important that they be normal, but that unnecessary or even irrelevant.  The floor effect is common, but the ceiling effect is more subtle (& potentially interesting, depending on what you're doing). Transforming to normality would be much more straightforward, if the ceiling effect didn't exist.
Comment: Does this help https://stats.stackexchange.com/questions/111010/interpreting-qqplot-is-there-any-rule-of-thumb-to-decide-for-non-normality?rq=1 ?
Comment: I particularly liked the rule of thumb "I am happy to call a distribution non-normal if I think I can offer a different description that is clearly more appropriate". My curve seems like a very extreme version of those presented in the 24 random sets.
Comment: @gung-ReinstateMonica Indeed they are maximum cuboids from three morphological measurements. In fact my question arose because each of these measurement, separately, follows a more straight normal line. They gave way to this shape once combined. But you're right, of course, about the floor and ceiling effects. After all, they are all, ultimately, objects that have to be manipulated by hand...
Answer: Negatives can be much easier than positives in this territory, and here are two:

In principle and in practice, this distribution is not plausibly normal. The numerical skewness and kurtosis results are less emphatic than the clear graphical asymmetry on your plot and the fact that values must be positive, which constraint is biting hard. A variable that is positively skewed will tend to plot as convex down on a normal quantile plot. (FWIW, quantile plot or quantile-quantile plot is a much wider class than normal quantile plot.)

It's a happy accident if data are close to a brand-name or named distribution, but the fit to any such can often be poor. One reason among several why fits can be disappointing is if any kind of heterogeneity is producing a mixture.

Something like a volume I would expect to be closer to a gamma or lognormal, but my explorations were not especially encouraging. Just to show some results, I played with how far a square root, cube root or logarithmic scale might help.

I see a slight edge to working with a cube root scale.
It's suggestive if not definitive to mention that the cube root of a volume is simple dimensionally, as a length, and that, to a good approximation, the cube root of a gamma distribution is a normal distribution. At the same time, it seems likely that your objects have a minimum volume rather above zero.
All that said, it's interesting if data are close to any named distribution, but contrary to myth normal distribution is an ideal condition (often mis-stated as an assumption) for methods only rarely.
Comment: +1 for emphasizing that seeking Normality is not a good objective.  A Normal probability plot merely uses Normality as a reference point, much as one might use the horizon as a reference point to determine how high or low an object in the field of view might be, without any implication that all objects are *supposed* to be on the horizon.
Comment: How nice there is a good philosophical side in the question and thanks for addressing it. @whuber, that's right, and the horizon example is very clear and clever.

Interpreting QQplot


HP Onboard Software SATA RAID. Knowing which drive failed

Question: On of our HP Proliant DL320 G4's is reporting a failure. It's running Windows 2003 and configured using the built in software SATA Raid.
The array manager shows only one drive attached labelled "Port 1" and so it's in a degraded state.
I have the replacement drive sitting on my desk and I'm all ready to go to the hosting centre to swap it out... My question is... how do I know which drive to pull?
The on board software raid on the HP's does NOT show any lights on the disks and therefore it is not possible to see which one has failed, which one is working or the ability to blink a specific drive.
Is there a simple rule that Port 0 is on the left and Port 1 is on the right?
Answer: There is no simple rule that would be the same on all machines, so you will have to consult your documentation.
Also look for an etched label on the machine's case. These can sometimes be difficult to see clearly even in reasonable lighting conditions so try with a torch.
Still take care though: if the machine doesn't have fixed wiring for each drive bay (which is common in non-hot-swap arrangements) any label or document could be wrong because the controller would not know if you'd plugged SATA data cable 1 into drive bay 3 and so forth...
One extra possible clue: If the array is only using one drive and there is a visible activity LED on each drive (there usually is when drives are front-mounted for hot-swapping), create some IO activity and you should see one drive being active and the other not.
Answer: The DL320 G4 has an Intel 82801FR SATAS controller which provides RAID0/1 via hardware not software. If you've installed the 'Proliant Support Pack' (PSP) you should be able to find the 'Array Configuration Utility' (ACU), fire that up and it will give you lots more information about your array, including details of any failure conditions. If you've not installed it then get the latest PSP from HERE, install it then look for the ACU.
Comment: There are no controllers present when looking with the ACU. However, you can install the HP Storage Manager and that shows the controller "SATA HostRAID (adpahci)". From here is where I know that it is failed and that there is only a drive detected on Port 1. It does not give me the option to "blink" the drive. There was a sticker on the server when purchsed that stated the drive lights will not work when using the embedded sata raid. Hence the problem knowing which drive failed.
Comment: Bay 1 is the left-hand slot when looked at from the front.
Answer: Ok, so I managed to get downtime on the server so I could shut it down and therefore pull the drives safely to see which one was which. On this server (I can't say the same for all) Port 0 is the left bay looking at the front and Port 1 is the right bay.
Answer: If you purchased the iLO option from HP and have hooked it up you can access the iLO (insight Lights Out) and look at the drive information there. You also can use iLO to remote to the machine, reboot it, and then look at the RAID configuration via the RAID utility on post to see what drive is degraded.


Validating `DefaultAzureCredential()` using Python SDK?

Question: What are some example methods for logging and handling exceptions using try/except and DefaultAzureCredential()?
Example:
When DefaultAzureCredential() is used in a Python Azure Function, it generates a few WARNING messages and one of the .get_token methods in the credential chain succeeds.
I want to log which one succeeded and which ones failed.
WARNING:azure.identity._internal.decorators:EnvironmentCredential.get_token failed: EnvironmentCredential authentication unavailable. Environment variables are not fully configured.

WARNING:azure.identity._internal.decorators:ManagedIdentityCredential.get_token failed: ManagedIdentityCredential authentication unavailable, no managed identity endpoint found.

WARNING:azure.identity._internal.decorators:SharedTokenCacheCredential.get_token failed: SharedTokenCacheCredential authentication unavailable. No accounts were found in the cache.

WARNING:azure.identity._internal.decorators:VisualStudioCodeCredential.get_token failed: Failed to get Azure user details from Visual Studio Code.

And then it just succeeds, but there is no message indicating which one succeeded. In this case, running snippets in a .ipynb file in VS Code).
How do I log and handle errors when using DefaultAzureCredential() in production?
Looking for an example of something like:
try:
    credentials = DefaultAzureCredential()
    logging.info(f'<whichever>.get_token succeeded')
except Error1 as e1:
    logging.error(f'EnvironmentCredential.get_token failed: EnvironmentCredential authentication unavailable. Environment variables are not fully configured.', e1)
except Error2 as e2:
    logging.error(f'ManagedIdentityCredential.get_token failed: ManagedIdentityCredential authentication unavailable, no managed identity endpoint found.', e2)
...<etc>

Answer: Just to supplement the accepted answer with some more details, let me add that DefaultAzureCredential does log this information. For example, if you enable INFO-level logging:
import logging
from azure.identity import DefaultAzureCredential

logger = logging.getLogger('azure.identity')
logger.setLevel(logging.INFO)

handler = logging.StreamHandler(stream=sys.stdout)
formatter = logging.Formatter('[%(levelname)s %(name)s] %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)

You'll see log messages like these from DefaultAzureCredential:
[INFO] DefaultAzureCredential - EnvironmentCredential is unavailable
[INFO] DefaultAzureCredential - ManagedIdentityCredential is unavailable
[INFO] DefaultAzureCredential - SharedTokenCacheCredential is unavailable
[INFO] DefaultAzureCredential acquired a token from VisualStudioCodeCredential

You'll see the failed attempts logged only the first time the DefaultAzureCredential instance acquires a token. Once one of its constituent credentials provides a token, it uses that credential exclusively. So this particular DefaultAzureCredential will always authenticate through Visual Studio Code, and in the logs you'll see this message whenever it does so:
[INFO] DefaultAzureCredential acquired a token from VisualStudioCodeCredential

Answer: There are a few ways I might approach this but none are particularly pretty.  At the risk of a naive suggestion, if you want a fine-grained understanding of what worked in sequence, you could take an approach similar to what your example sketched out using the components credentials listed here:
for credential in [EnvironmentCredential, ManagedIdentityCredential, ...]:
  try:
    credentials = credential()
    # Validate credential functionality...
    logging.info('{}.get_token succeeded'.format(credential))
  except Error1 as e1:
    logging.error('{} failed due to {}'.format(credential, e1))

I suggest this because it does not seem like what you want is exposed in an easily accessible manner, looking at the ChainedCredential source here (history is built up but only used in the log message).
More "self-contained" approaches might involve creating a custom wrapper that basically does what ChainedCredential does for DefaultAzureCredential in running the list of get_token calls, but with more ability to export the success history, you could likely hack that off of the code I linked in 2 and do something directly comparable to the DefaultAzureCredential logic, but at the end of the day it's all isomorphisms of the sample above.
Don't hesitate to shout if I've misunderstood some aspect of the question or your requirements/constraints; and as always feel free to reach out if you need to get in touch with us on our github (full disclosure, am a maintainer for some of the other Python Azure SDKs)
Comment: To be clear, my solution basically "works around' needing to consume `DefaultAzureCredential()` explicitly, because I do not see an obvious way to extract the information you need from it; it simply does not persist it, so you'd need to have "your own version" of `DefaultAzureCredential()` which is what I outline above.

Echoing myself to be VERY predantic: I do not see a way that you CAN actually use `DefaultAzureCredential` explicitly with the requirements you have above (to know what succeeded and failed within it)
Comment: Thank you for providing some ideas. I want to make sure I'm not overriding anything that `DefaultAzureCredential()` is doing and am actually *using* `DefaultAzureCredential()`. I don't see it listed in your proposed solution. Where is the actual call to `DefaultAzureCredential()` in your solution?
Comment: Thank you for the clarification. Due to my current level of experience, I'd prefer not to create my own version of `DefaultAzureCredential`. I'll pursue an alternative unless you know a simple Python method to catch all the "Warning" messages that are displayed.


Correct cardinals vs Stable ordinals

Question: I recently learnt about correct and stable cardinals and ordinals.

A cardinal $\kappa$ is called $\Sigma_n$-correct iff $V_\kappa \prec_n V$.

An ordinal $\alpha$ is called $\Sigma_n$-stable iff $L_\alpha \prec_n L$.

Apart from one being a cardinal and the other being an ordinal, is there really any difference between the two?
Answer: To start with, note that stability is a very, well, stable notion: since the $L$-hierarchy is appropriately absolute, if $\alpha$ is $n$-stable in $V$ then $\alpha$ is also $n$-stable in every generic extension $V[G]$. This is very false for correctness (this is a good exercise - think about e.g. starting with $V=L$ and then forcing a failure of $\mathsf{GCH}$ above what $V$ thinks is the smallest $2$-correct cardinal).
So even at a very coarse level - "How much can these notions be affected by forcing?" - we see a fundamental difference. Relatedly, by Tarski's theorem the class of pairs $(\alpha,n)$ such that $\alpha$ is $n$-correct is never (parameter-freely-)definable in $V$, but the class of pairs $(\alpha,n)$ such that $\alpha$ is $n$-stable may be definable in $V$ (if $V$ is very far from $L$ - e.g. if $V\models$ "$0^\sharp$ exists").
Comment: Additionally, $V_\alpha$ must be correct about which ordinals are cardinals (i.e. for $V_\alpha\vDash"\beta\textrm{ is a cardinal}"$, it's necessary that $\beta$ actually is a cardinal), but $L_\alpha$ isn't. That's why we can have things like a countable $\alpha$ where $L_\alpha\vDash\mathsf{ZFC}$, because for some countable $\beta<\alpha$, $L_\alpha\vDash"\beta\textrm{ is a cardinal}"$.
Comment: Great, thanks! I don't really understand forcing however, I just have a vague idea.

Correct cardinals vs Stable ordinals


SQL Syntax for 'If A does not exist in Query Return B, but if A does exist only return A'

Question: I have a query that returns current and future revenue from a GLTable.  There are two posting types I need to return.  If Postingtype A does not exist then return postingtype B if postingtype A exists only return postingtype A. DB is MSSQL 2014.
I have tried several variations of below,
WHERE (EXISTS (SELECT 1 FROM GLAccountPosting WHERE PostingType = 10)
        )
        OR
        NOT EXISTS (SELECT 1 FROM GLAccountPosting WHERE PostingType = 14)

        (;

WHERE
postingtype in (14, 10)
AND
    (StartDateTime > '2019/07/01' AND postingtype = 10)
    OR
     (StartDateTime < '2019/07/01' AND postingtype = 14);

WHERE
    (StartDateTime > '2019/07/01' AND postingtype = 10 ) OR
    (StartDateTime < '2019/07/01' OR postingtype = 14);

Query Below(Truncated as it is very large):
SELECT

prepay.Prepay,
Case When GAP.postingtype = 14 then isnull(sum(GAP.CreditValue),0) ELSE 0 end as CreditTodate,
Case When GAP.postingtype = 14 then prepay.Prepay -  isnull(sum(GAP.CreditValue),0) ELSE prepay.Prepay   end AS Balance,

GAP.PostingType

 FROM
GLAccountPosting AS GAP

    JOIN (SELECT

                        SalesTransactions.BranchID,
                        Departments.DepartmentGUID,
                        SalesTransactions.SalesTransactionGUID,
                        SalesTransactionDetails.SalesTransactionLineGUID,
                        Sum(SalesTransactionDetails.Prepayvalue) AS Prepay

                 FROM
                      intellimanager.dbo.SalesTransactionDetails
                      INNER JOIN  intellimanager.dbo.SalesTransactions ON SalesTransactionDetails.SalesTransactionGUID=SalesTransactions.SalesTransactionGUID
                      INNER JOIN  intellimanager.dbo.SalesTransactionLines ON SalesTransactionDetails.SalesTransactionLineGUID=SalesTransactionLines.SalesTransactionLineGUID
                      INNER JOIN  intellimanager.dbo.Departments on Departments.DepartmentGUID = SalesTransactionDetails.ItemDepartmentGUID
                      left  JOIN  intellimanager.dbo.BookingLinesDetails on BookingLinesDetails.BookinglinesDetailGUID = SalesTransactionDetails.BookinglinesDetailGUID
                      LEFT JOIN  intellimanager.dbo.BookingLines on BookingLines.BookingLineGUID = BookingLinesDetails.BookingLineGUID

                 WHERE
                      (
                            SalesTransactionDetails.AccrualStatus = 1 OR SalesTransactionDetails.AccrualStatus=2 -- 1 = reversed, 2 = deferred
                      ) AND
                        SalesTransactions.PostingDateTime < DateAdd(day,1,'2019/04/27') and
                        SalesTransactionDetails.BranchID IN (SELECT number FROM dbo.InzSplitInt(1)) AND-- selected branch
                        SalesTransactionDetails.AccrualType = 2 AND  --- sessions only
                        SalesTransactionDetails.PrepayValue <> 0 AND
                        isnull(SalesTransactionLines.CreditSalesTransactionLineGUID,0x0) = 0x0  and -- remove credited lines
                        SalesTransactions.status = 1 and -- remove not finalised and cancelled invoices
                        BookingLinesDetails.ItemType = 1 and
                      (BookingLinesDetails.BookingDetailProgress not in (2,4) or
                        (
                            BookingLinesDetails.BookingDetailProgress in (2,4) and SalesTransactionDetails.AccrualStatus <> 1)
                        )
                        and
                        (
                            BookingLinesDetails.CalendarLinkGUID is null or
                            (BookingLinesDetails.CalendarLinkGUID is not null and BookingLinesDetails.StartDateTime >= '2019/01/01'
                            )
                        )

                         -- include all sales tran details that are for bookings in the future
                         -- whether they have been completed or not and whether they have

                        GROUP BY
                            SalesTransactions.BranchID,
                            SalesTransactions.SalesTransactionGUID,
                            SalesTransactionDetails.SalesTransactionLineGUID,
                            Departments.DepartmentGUID,
                            BookingLinesDetails.StartDateTime) As prepay on prepay.SalesTransactionLineGUID = GAP.SalesTransactionLineGUID
                        JOIN salestransactionlines stl on stl.salestransactionlineguid = gap.salestransactionlineguid

                        LEFT JOIN salestransactiondetails sd on sd.SalesTransactiondetailGUID = GAP.SalesTransactiondetailGUID

where
        GAP.ItemType = 1

group by

GAP.GLPostingDescription,
GAP.postingtype,
GAP.FormattedGLAccountCode,
prepay.Prepay,
GAP.PostingType

The results I need are:
Prepaid   Current Future  postingtype
26.90     0.00    26.90   10
215.20  215.20     0.00   14

Each line would potentially have both Postingtype 10 and 14 but I only want to see one at a time.  If both show up for the same transaction it makes the totals inaccurate.
Comment: `select top(1) with ties ... order by row_number() over (partition by order by postingtype)`
Comment: If you want only one row, then use `select top (1)`.
Comment: The report can return over 5000 rows.
Comment: . . " If Postingtype A does not exist then return postingtype B if postingtype A exists only return postingtype A. "  That statement and your sample data suggest that you want only one row.
Comment: Apologies perhaps I misunderstood, I only want one row for each transaction yes.  it has to be either posting type A and if that does not exist in the query then I want Posting type B.
Comment: thank you Serg, but that only gives me type 10 in the query when it should have only type 14.
Comment: `.. order by postingtype DESC` if 14 is top priority over 10
Comment: Thank you so much Serg that worked fantastically,  never heard of syntax with ties.  I have spent weeks on the whole report and this was the last bit.  thanks again.  Not sure how I mark your comment as correct
Comment: @sabbegk, If performance matters, it was actually better to use a CTE with `ROW_NUMBER()` and a `WHERE` on the outermost `SELECT` to filter for the rows wich git a row-number of `1`. Serg's query is very *pretty* and I really like its slickness, but the sorting will be performed twice, quite a drawback with larger sets...
Answer: Is this what you mean?

DECLARE @t TABLE (TransactionID INT)
DECLARE @p TABLE (PostingType CHAR(1), TransactionID INT)

INSERT INTO @t
(TransactionID)
VALUES
(1),
(2),
(3)

INSERT INTO @p
(PostingType, TransactionID)
VALUES
('A', 1),
('B', 1),
('A', 2),
('B', 3)

SELECT t.TransactionID FROM @t t
WHERE
 EXISTS
  (
   SELECT 1 FROM @p p
   PIVOT
   (
   COUNT(p.PostingType)
   FOR p.PostingType IN ([A], [B])
   ) sq
   WHERE
    (
     ([A] = 0 AND [B] > 0) --Postingtype A does not exist then return postingtype B
     OR ([A] > 0 AND [B] = 0) --If postingtype A exists only return postingtype A
    )
    AND sq.TransactionID = t.TransactionID
  )
Comment: Thank you, I did try this, not exactly sure where to put it in my code, My knowledge of using temp tables etc is limited, but I got this error when running: (3 rows affected)
Msg 8152, Level 16, State 14, Line 11
String or binary data would be truncated.
The statement has been terminated.
Comment: This error message "binary data would be truncated" means content is to large for number of allowed characters in column. Perhaps you can post a script that inserts sample data into a #temp table and your current query.


Direct limit and constant are adjoint functors

Question: I have a question. Why $(\varinjlim, | |)$ is an adjoint pair of functors?
Here the definition of constant direct system || is: For any I, fix a module A and set $A_i=A$, all $i\in I$, and $\phi_j^i=1_A$ for all $i\leq j$.
The adjoint pair of functors is an ordered pair (F,G), $F:C\rightarrow D, G:D\rightarrow C$ such that there is a bijection $\tau: Hom_C(FA,C)\rightarrow Hom_D(A,GC) $   which is natural in each variable.
The definition of constant direct system is clear. It is a functor G from C to D, here C is the index set I. But the direct limit seems like consisting of an object and a family of morphisms such that the universal property holds. Then how we regard it as a functor? I guess it might be a functor from a direct system to an object with some morphisms? Then I am confused about how to check the condition of adjoint functors. Thanks for any help!
Answer: By definition, a direct limit of a system $\{B_i\}_{i \in I}$, if it exists, is an object $\varinjlim B_i \in \mathsf{C}$ together with morphisms $f_i : B_i \to \mathcal{B}$, such that for all objects $A \in \mathsf{C}$,
$$\hom_{\mathsf{C}}(\mathcal{B}, A) \cong \hom_{\mathsf{C}^I}(\{B_i\}, |A|) \tag{*}$$
is a bijection, the map being given by
$$(g : \mathcal{B} \to A) \mapsto \{ g_i = g \circ f_i : B_i \to |A|_i = A \}_{i \in I}.$$
You can easily see that this is equivalent to the universal property of the direct limit: it exactly means that for all system of morphisms $g : B_i \to A$ (compatible with the system $\{B_i\}$) there exists a unique morphism $\mathcal{B} \to A$ compatible with the $g_i$. (It's one of these things you need to work out yourself to really understand, so I encourage you to write down the details.)
It can be shown that if for all systems $\{B_i\} \in \mathsf{C}^I$, the direct limit exists, then the constant direct system functor $|-| : \mathsf{C} \to \mathsf{C}^I$ has a left adjoint. It can be denoted $\varinjlim : \mathsf{C}^I \to \mathsf{C}$ and is called the direct limit (or colimit) functor. Since this is a left adjoint, equation $(\text{*})$ holds (with $\mathcal{B} = \varinjlim B_i$), and you see that therefore $\varinjlim B_i$ is a direct limit of the system $\{B_i\}$.
I won't prove that it's a functor, but to get an idea, suppose that you have two systems $\{B_i\}$ and $\{C_i\}$ and a collection of morphisms $h_i : B_i \to C_i$, compatible with the systems. Then you can compose with the "injection" morphisms to get $\tilde{h_i} : B_i \to C_i \to {\varinjlim}_j C_j$, and these maps commute with the maps of the system $\{B_i\}$. So by the universal property you get a map $$\varinjlim h_i : \varinjlim B_i \to \varinjlim C_i.$$
It remains to show that $\varinjlim (h_i \circ g_i) = \varinjlim h_i \circ \varinjlim g_i$, a healthy exercise.
Comment: Thanks! I think I totally understand it. The point is the direct limit is a functor from the category of direct systems(I feel some compatible condition needed) to the category where {$B_i$ } belong to, that is C. The constant direct system functor can be regarded as a functor from C to $C^I$. And $hom_{C^I}({B_i}, A)$ is a family of morphisms that are compatible. Thank you very much!


Deploy large code base to new Salesforce dev org

Question: Currently we have multiple users trying to develope code on same application in salesforce. We have a Product already in place and it already have lots of code. What we are trying to do is find an easy to use mechanism that can be used to deploy our central code base to multiple developer unrelated orgs.
What we have -

SVN Code base where all of code has been stored.
Multiple unrelated dev orgs.
Current Org and code base have lots of Apex, Pages, Email templates, reports, dashboards, Workflow , Profiles, triggers and most of the standard as well as Custom Salesforce functionalities.

What we want to do -
1. A simplified mechanism or way which can be used to deploy all of org to some unrealted dev / partner orgs.
What we have tried -
1. We tried the same using Eclipse and it takes almost 6-7 hours to complete activity and that too has a probability of missing out things due to dependecies among multiple compinents. A very big headache with this approach.
2. Use Ant Migration tool. Using Force.com Migration tool and Ant commands, we tried deploying for first time to unrelated org. But it gave at least 400 -500 errors over command prompt. Not sure how to make this work. Do we have easer way or we need to go ahead and solve each issue one by one.
We dont have provision for Change Sets or Sandbox / Production org as we are creating a package for multiple users.
Please let me know about any other possible ways that can be used to migrate huge code base (standard + Custom SF components) to any unrelated dev org.
Any help would be appreciated.
Thanks,
Kaushik
Answer: When we need to deploy SF project to new org manually (or update current one manually), we usually deploy parts of a project in such sequence:

static res
labels
groups
roles
letterhead
documents
OBJETCS
tabs
apps
email
classes
pages
components
layouts
triggers
workflows
reports
dashbords
homepage layouts
homepage components
profiles
permission sets

This allows us to to avoid mistakes related to dependencies in the components of the project. Also we use some tools for continuous integration (e.g. Jenkins which deploys all  changes (which are commited to repository) to CI org and every night deploys builds on QA org).


Parse XML string using C#

Question: I need to parse a simple XML string using C#
<items>
    <item1 value="value1" />
    <item2 value="value2" />
    <item3 value="value3" />
    <itme4 value="value4" />
    <item5 value="value5" />
    <itme6 value="value6" />
</items>

I'm trying to do it as follow:
    XMLParser XMLParserObj = new XMLParser();
    XmlDocument xmlDoc = new XmlDocument();
    xmlDoc.LoadXml(xmlString);

   string item1 = xmlDoc.Attributes.GetNamedItem("item1").Value;
   string item2 = xmlDoc.Attributes.GetNamedItem("item2").Value;
   string item3 = xmlDoc.Attributes.GetNamedItem("item3").Value;
   string item4 = xmlDoc.Attributes.GetNamedItem("item4").Value;
   string item5 = xmlDoc.Attributes.GetNamedItem("item5").Value;
   string item6 = xmlDoc.Attributes.GetNamedItem("item6").Value;

with no luck
please advise..
Comment: some of your xml items are named `itme` and not `item` as your code has them.
Answer: A possible solution would be to use LINQ2XML:
// retrieve a single element by tag name
private XElement getElement(XDocument xmlDocument, string elementName)
{
    var element = xmlDocument.Descendants("items").Elements().Where (x => x.Name == elementName).FirstOrDefault();
    return element != null ? element : null;
}

// retrieve attribute by name
private string attributeValue(XElement item, string attributeName)
{
    var attribute = item.Attribute(attributeName);
    return attribute != null ? attribute.Value : string.Empty;
}

The two functions can be used like this:
// input for the example
var input = @"<items>
<item1 value=""value1"" />
<item2 value=""value2"" />
<item3 value=""value3"" />
<itme4 value=""value4"" />
<item5 value=""value5"" />
<item6 value=""value6"" />
</items>";

var xml = XDocument.Parse(input);
var element = getElement(xml, "item2");
if (element != null)
{
    Console.WriteLine(attributeValue(element, "value"));
}

The output is:
value2

For a repetative tasks like this it is often advantageous to implement the methods as extensions:
public static class ProjectExtensions
{
    // retrieve a single element by tag name
    public static XElement GetElementByName(this XDocument xmlDocument, string parentElementName, string elementName)
    {
        var element = xmlDocument.Descendants(parentElementName).Elements().Where (x => x.Name == elementName).FirstOrDefault();
        return element != null ? element : null;
    }

    // retrieve attribute by name
    public static string GetAttributeValueByName(this XElement item, string attributeName)
    {
        var attribute = item.Attribute(attributeName);
        return attribute != null ? attribute.Value : string.Empty;
    }
}

The usage is IMO much more easier and cleaner:
var xml = XDocument.Parse(input);
var element = xml.GetElementByName("items", "item2");
if (element != null)
{
    Console.WriteLine(element.GetAttributeValueByName("value"));
}

You can of course (as already suggested) use XPath directly.
Answer: leave all your code the same but change this :
string item1 = xmlDoc.GetElementsByTagName("item1")[0].Attributes[0].Value;

do the same for other items , and you will get the value.
Answer: Assuming you want the value attribute of each of your item elements, you could use Xpath:
        string xmlString = "<items><item1 value=\"value1\" /><item2 value=\"value2\" /><item3 value=\"value3\" /><item4 value=\"value4\" /><item5 value=\"value5\" /><item6 value=\"value6\" /></items>";

        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.LoadXml(xmlString);

        string item1 = xmlDoc.SelectSingleNode("items/item1/@value").InnerText;
        string item2 = xmlDoc.SelectSingleNode("items/item2/@value").InnerText;
        string item3 = xmlDoc.SelectSingleNode("items/item3/@value").InnerText;
        string item4 = xmlDoc.SelectSingleNode("items/item4/@value").InnerText;
        string item5 = xmlDoc.SelectSingleNode("items/item5/@value").InnerText;
        string item6 = xmlDoc.SelectSingleNode("items/item6/@value").InnerText;

Answer: You missunderstand the term 'Attribute', you are trying to catch "item1" and it is actually a Node.
Use this:
string item1 = xmlDoc.SelectSingleNode("//items/item1").Attributes["value"].value;

There are other options, but this will give you the values you are looking for.
Cheers...
Answer: this will get you all those attributes values:
1)Load xml with XDocument.Load() if from a string XDocument.Parse() then do this:
IEnumerable<string> result = from node in xmlDoc.Root.Descendants()
                             select node.Attribute("value").Value;

Parse XML string using C#


Event generation on gridview field click in asp.net using C#

Question: I have view user field in grid view. So, when i click on view user text
,it should generate me popup in which I enter user ID, if userID is correct, only then it will allow to navigate to other page containing that user details.
I am able to navigate to other Url using NavigateUrl, but not able to generate event.
My code is as below:
 protected void grdPage_SelectedIndexChanged(object sender, System.EventArgs e)
    {
        if (grdPage.RowHeaderColumn.Contains("View"))
        {
            Response.Redirect("../Login.aspx?");

        }
    }

Comment: The code I have just populates grid view, I dont think that will be relevant to this, as I am not able to generate event on click of field.
Comment: grdPage_SelectedIndexChanged, this is only event i am able to get when i click on grid field, but I need specific event for particular field in grid view, still i will post my code
Answer: Use OnRowCommand for this purpose.
Comment: Let me do it, will get back to you
Comment: I have edited my my question, hopefully you will get what I am trying to do
Answer: you can use jquery/javascript to open the popup
like this
 <a  href="javascript:;" title="View" onclick="javascript:return openModal(<%#  DataBinder.Eval(Container.DataItem, "userID ")%>);">View


Como alterar uma imagem dinamicamente quando um button é pressionado e guardar o estado dessa imagem

Question: Tenho um problema em que preciso alterar uma imagem de uma imageView quando o Button for pressionado e quando o mesmo for pressionado novamente altere para a imagem que estava anteriormente. Eu até consegui fazer isso através do setBackgroundResource, o problema é quando eu fecho o aplicativo ou saio dessa determinada Activity e volto para ela a imagem volta a ser a que estava no  android:background desde o início.
Alguém pode me ajudar?
Código xml

<Button
    android:id="@+id/buttonLigarDesligar"
    android:padding="10dp"
    android:layout_width="40dp"
    android:layout_height="40dp"
    android:background="@drawable/icone_ligar"/>

<ImageView
    android:id="@+id/imgStatus"
    android:padding="10dp"
    android:background="@drawable/icone_vermelho"
    android:layout_width="40dp"
    android:layout_height="40dp"/>

Código Java

buttonLigarDesligar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int status = 0;

            if (satus == 0){
                imgStatus.setBackgroundResource(R.drawable.ic_on);
                status = 1;
            }else{
                imgStatus.setBackgroundResource(R.drawable.icone_vermelho);
                status = 0;
            }
        }
    });
}

Comment: Você pode guardar essa informação em um banco de dados, ou o ideal no caso seria guardar em um sharedpreferences, se ninguém te responder até amanhã, eu ajudo. Pq agora to fora do pc
Answer: Pode utilizar SharedPreferences pra guardar a informação do usuário para isso faça o seguinte:
Primeiro dentro da sua Activity declare:
private SharedPreferences sharedPreferences;
private boolean statusOff;
public static final String SHARED_PREFERENCES_USER = "user_preferences";
public static final String BUTTON_ON_OFF = "button_on_off";

Dentro do método onCreate acrescente:
    sharedPreferences = this.getSharedPreferences(SHARED_PREFERENCES_USER, Context.MODE_PRIVATE);
    //Caso ainda não tenha sido criada essa preferência o retorno booleano
    //sera true, como destacado embaixo
    statusOff = sharedPreferences.getBoolean(BUTTON_ON_OFF, true);

Deixe o evento de clique do seu botão assim:
buttonLigarDesligar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                SharedPreferences.Editor editor = sharedPreferences.edit();

                if (statusOff) {
                    imgStatus.setBackgroundResource(R.drawable.ic_on);
                    //agora o valor do sharedpreferences é true, ou seja está ligado.
                    editor.putBoolean(BUTTON_ON_OFF, false);
                } else {
                    //caso o sharedpreference for false, então altera o icone pra vermelho e o valor
                    //booleano passa a ser true.
                    imgStatus.setBackgroundResource(R.drawable.icone_vermelho);
                    editor.putBoolean(BUTTON_ON_OFF, true);
                }
                editor.apply();
            }
        });

Dentro da sua Activity reescreva o método onResume da seguinte maneira:
@Override
protected void onResume() {
    super.onResume();
    //Para quando a aplicação, for pausada ou parada, o método onResume checará
    //o status do botão que está salvo e caso ele seja "false" então altera
    //o seu background para o ic_on. Caso statusOff seja "true", não tem necessidade
    //de alteração já que você definiu por padrão no xml "icone_vermelho"
    if (!statusOff) {
        imgStatus.setBackgroundResource(R.drawable.ic_on);
    }
}

Espero ter ajudado.
Comment: Mt obrigado cara, consegui resolver aqui,não sabia da existência do sharedpreferences kkk, sou novo no android, mas de novo obrigado!


Empty sequence when interacting with TimeSpan in a list

Question: So here's the thing. I have the following list:
var Diffusions = new List<SetDiffusion>();

Filled this way:
Diffusions.Add(new SetDiffusion
{
    VideoName = videoName,
    Selected_Dif = ConvertToTimespan(TimeParts[1])
});

VideoName being a string, and Selected_Dif a Timespan.
Now with said list I need to get the closest absolute Timespan and call a method with it and its corresponding VideoName. Now this is my first time messing around with a class list but from what I understand this should work:
UpcomingDif = Diffusions.OfType<TimeSpan>()
                        .OrderBy(t => Math.Abs((t - DateTime.Now.TimeOfDay).Ticks))
                        .First();

I've used it with a previous List<Timespan> without .OfType and it worked fine. But now in the same testing environment, it raises an empty sequence error.
Any idea what's wrong with my code?
Thank you.
LAST EDIT:
Just in case it might help someone, here is my timer initialization (Thanks @Koopakiller):
        var diffusion= Diffusions.OrderBy(t => Math.Abs((t.Selected_Dif - DateTime.Now.TimeOfDay).Ticks)).First();
        TimeLeft = diffusion.Selected_Dif - DateTime.Now.TimeOfDay;

Comment: I presume its due to the `OfType` call which returns an empty sequence? As SetDiffusion is not of type `TimeSpan` ?
Comment: @DanielVarab Yes that was it, I wasn't familiar with `list`
Answer: Diffusions does not contain any TimeSpan that's why OfType does not return any element from the list.
The simpliest way to do your task is to order the elements by there time stamp descending and then take the first.
UpcomingDif = Diffusion.OrderByDescending(t => t.Selected_Dif)
                       .First()

UpcomingDif is now a SetDifusion. If you want only the time span to now, you can access the Selected_Difproperty and subtracting DateTime.Now with it:
var timeSpan = DateTime.Now - UpcomingDif.Selected_Dif;

Comment: Thank you for your answer. However wouldn't proceeding this way result in a negative timespan since `UpcomingDif` is the "earliest" timespan instead of the closest to `DateTime.Now` ?


Proving $[0,1]^{\omega}$ in box topology is not compact

Question: Here is my attempt at proving this, any ideas if it is completely correct?
Let $U^{(0)}=[0,\frac{3}{5}), U^{(1)}=(\frac{2}{5},1]$. Let $x=(x_n)_{n \in \mathbb{N}}$ be an arbitrary sequence of $0's$ and $1's$ in the collection $C$ of all infinite sequences of $0's$ and $1's$. With each sequence $x$ in this collection, associate a sequence of subsets of $[0,1]$ defined by $$U_{nx}= \begin{cases}  U^{(1)}   &\text{ if } x_n=1 \\
          U^{(0)}  & \ \text{if} \ x_n=0\end{cases}$$ Then the collection $S$ of all products of the form $\prod_{n \in \mathbb{N}} U_{nx}$,which are open in $[0,1]^{\omega}$ where $x$ ranges over the set of all binary sequences is an open cover for $[0,1]^{\omega}$ with the box topology.Since for any $k \in \mathbb{N}$ there are at least two elements in $S$ such that the $k$'th factor in the products differ. Now if any element is removed from $S$, one of the infinite sequences $x$ will be removed from $C$, and this sequence will have exactly one coordinate differing from all the other sequences in either a $0$ or $1$ in say the $m$'th slot. So the $m$'th factor in the product of the union of all the elements of this new collection $S'$ will either  be $[0,\frac{3}{5})$ or $(\frac{2}{5},1]$ and hence the collection upon removing the element from $S$ will not cover $[0,1]^{\omega}$. Thus since $S$ is infinite any finite subset of $S$ will certainly not cover the space.
Answer: It's correct but could be stated much more clearly. The key point, which you saw but didn't really state explicitly, is that for each $x\in C$, the set $\prod_nU_{nx}$ is the only member of $S$ that contains $x$. Your argument for this could be much clearer. Clearly $x\in\prod_nU_{nx}$. If $y\in C\setminus\{x\}$, however, there is an index $k$ such that $y_k\ne x_k$. But then $x_k\notin U_{ky}$, so $x\notin\prod_nU_{ny}$.
$S$ is in fact an irreducible open cover of $[0,1]^\omega$: each member of $S$ contains a point that is not in any other member of $S$, so no proper subset of $S$ covers $[0,1]^\omega$.
Note that essentially the same argument can be used to show that the box product $\{0,1\}^\omega$ is not compact (where $\{0,1\}$ has the discrete topology): here you're working directly with $C$ as a box product. Since this space is a closed subset of $[0,1]^\omega$, that is another way to see that $[0,1]^\omega$ cannot be compact: if it were, all of its closed subsets would be compact as well.