Expression for variation in the fourth moment of standard normal vs. sample size

Question: Question:
What is the expression for the variation in the fourth (not-centralized) moment as a function of sample size for the standard normal distribution and is there a proper analytic/symbolic way to derive it?
Details:
When I use random number generator to create samples from a standard normal distribution, then I compute the mean, and I do this many times per sample-level, I can create a plot like the following:

My textbooks told me that the relationship between the variation and the sample size was:
$$ Err \propto \frac{1}{\sqrt{n}}$$
where $Err$ is the standard deviation of the estimate and $n$ is the sample size.
When I plug it into this, I get a visual confirmation.

When I plug into a linear fit I get the following summary:
<code>> summary(est)

Call:
lm(formula = s2 ~ I(sqrt(1/n)))

Residuals:
       Min         1Q     Median         3Q        Max
-0.0097079 -0.0004087  0.0000041  0.0004380  0.0093119

Coefficients:
               Estimate Std. Error  t value Pr(>|t|)
(Intercept)  -2.633e-04  5.312e-05   -4.957  8.4e-07 ***
I(sqrt(1/n))  1.005e+00  7.212e-04 1393.680  < 2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.0009955 on 994 degrees of freedom
Multiple R-squared:  0.9995,    Adjusted R-squared:  0.9995
F-statistic: 1.942e+06 on 1 and 994 DF,  p-value: < 2.2e-16
</code>
The R-squared of 99.95% is an indicator of a pretty good fit.
What is the expression for the variation in the fourth (not-centralized) moment as a function of sample size for the standard normal distribution?
The plot of the variation in fourth moment versus sample size looks like this:

When I plot Error versus square root of inverse sample count, I do not get a straight line.

I could wire a stack of transformations on "n" into "glmulti" (link) but that can be a lot of work for little return.
Some "hacking" in algebra gives me a fair error expression, but I have no way of telling if it is local to my data, or more globally valid.
Here is my source code:
<code>set.seed(5) #for reproducibility

n <- seq(from=5,to=1000,by = 1)

#number of iterations at each sample size
N <- 3000

#predeclare
store1 <- matrix(0, nrow=length(n),ncol=N)
store2 <- matrix(0, nrow=length(n),ncol=N)
mymean <- numeric()
mymom<- numeric()

nn <- matrix(0, nrow=length(n),ncol=N)

#for each sample size
for(i in 1:length(n)){

     #repeat the measure "N" times
     for (j in 1:N){

          #store so we can separate it out later
          nn[i,j] <- n[i]

          #take sample
          y <- rnorm(n = nn[i,j],mean = 0,sd = 1)

          #compute moment
          mymean <- mean(y)
          mymom <- mean( (y-mean(y))^4)

          #store
          store1[i,j] <- mymean
          store2[i,j] <- mymom
     }
}

##compute variation

#predeclare
s1 <- numeric()
s2 <- numeric()

s3 <- numeric()
s4 <- numeric()

#loop
for (i in 1:length(n)){

     #find elements which have a particular sample size
     idx <- which(nn==n[i],arr.ind=T)

     #compute statistics of first moment (aka mean)
     s1[i] <- mean(store1[idx])
     s2[i] <- sd(store1[idx])

     #compute statistics of fourth moment (not centered
     s3[i] <- mean(store2[idx])
     s4[i] <- sd(store2[idx])

}

#make figures

plot(n, s2,xlab="Sample count",ylab="Error in mean")
lines(lowess(x=n,y=s2,f=0.01),col="Red",lwd=2)
grid()

plot(sqrt(1/n), s2,xlab="SQRT inverse Sample count",ylab="Error in mean")
lines(lowess(x=sqrt(1/n),y=s2,f=0.01),col="Red",lwd=2)
grid()

plot(n, s4,xlab="Sample count",ylab="Error in fourth moment")
lines(lowess(x=n,y=s4,f=0.005),col="Red",lwd=2)
grid()

plot(sqrt(1/n), s4,xlab="SQRT inverse Sample count",ylab="Error in fourth moment",
     xlim=c(0,0.2),ylim=c(0,2))
lines(lowess(x=sqrt(1/n),y=s4,f=0.02),col="Red",lwd=2)
grid()

#fit to models
est <- lm(s2~I(sqrt(1/n)))
summary(est)

est2 <- lm(s2~I(sqrt(1/n))+I((1/n)^(1/4)) )
summary(est2)
</code>
Answer: What you are doing is basically correct, the small deviations you observe in the last plot is due to the large sample variation of empirical fourth moments.
Here is the algebra for the standard normal case. I am using formulas for moments from https://en.wikipedia.org/wiki/Normal_distribution#Moments
Let $X_1, \dotsc, X_n$ be iid observations from a standard normal distribution. The fourth empirical moment (about zero) is given by
$$\DeclareMathOperator{\E}{\mathbb{E}}  \frac{1}{n} \sum_i X_i^4. $$Its expected value can be calculated:
$$
 \E \left\{ \frac1{n} \sum_i X_i^4 \right\}= 3
$$
and its variance:
$$\DeclareMathOperator{\Var}{\mathbb{Var}}
 \Var\left\{ \frac1{n} \sum_i X_i^4 \right\} = \left(\frac1{n}\right)^2\sum_i \Var X_i^4= \frac{96}{n}
$$
and some details of the last calculation here:
$$
 \Var X_i^4 = \\ \E \left( X_i^4 -\E X_i^4 \right)^2 = \\ \E \left( X_i^4-3\right)^2 = \\ \E X_i^8 - 2\cdot 3 \E X_i^4 + 9 = \\ \sigma^8\cdot 105 -6 \cdot 3 + 9= 96
$$


Brezis (Variational Formulation for Boundary Value Problems)

Question: Brezis considers the inhomogeneous Dirichlet problem,
\begin{align}
-\Delta u+u=f\quad &\text{in }\Omega,\\
u=g\quad &\text{on }\partial\Omega,
\end{align}
where $f$ is given on $\Omega$ and $g$ is given on $\partial\Omega$. In order to build up to the proposition which proves a unique weak solution exists for this problem Brezis first wishes to construct a closed convex set in $H^{1}(\Omega)$. He does this as follows:
Suppose that there exists a function $\tilde{g}\in H^{1}(\Omega)\cap C(\overline{\Omega})$ such that $\tilde{g}=g$ on $\partial\Omega$. and consider the set,
\begin{align}
K=\{v\in H^{1}(\Omega)\,|\,v-\tilde{g}\in H^{1}_{0}(\Omega)\}.
\end{align}
It follows from Theorem 9.17 that $K$ is independent of the choice of $\tilde{g}$ and depends only on $g$.
Where I require assistance: Theorem 9.17 states,
Theorem 9.17: Suppose $\Omega$ is of class $C^{1}$. Let,
\begin{align}
u\in W^{1,\,p}(\Omega)\cap C(\overline{\Omega})\quad\text{with }1\leq p<\infty.
\end{align}
Then the following properties are equivalent:
\begin{align}
\text{(i)}&\,u=0\text{ on }\partial\Omega,\\
\text{(ii)}&\, u\in W^{1,\,p}_{0}(\Omega).
\end{align}
The way I see this working is that to show that $v-\tilde{g}\in H^{1}_{0}(\Omega)$ we can show that $v-\tilde{g}=0$ on $\partial\Omega$ and property (ii) from Theorem 9.17 follows (since the proof of (i)$\implies$(ii) does not require any assumptions on the smoothness of $\Omega$). Then from earlier we have $v=\tilde{g}=g$ on $\partial\Omega$, and so we drop the dependence on $\tilde{g}$. However, we do not know that $v-\tilde{g}\in H^{1}(\Omega)\cap C(\overline{\Omega})$ so how are we reaching this conclusion?
Showing $K$ is convex:
Suppose $u,v\in K$. Consider $t\in\mathbb{R}$, then,
\begin{align}
tv+(1-t)u=t(v-u)+u.
\end{align}
Take $\tilde{g}$ as before, then
\begin{align}
t(v-u)+u-\tilde{g}=t(v-\tilde{g})-t(u-\tilde{g})+(u-\tilde{g})\in H_{0}^{1}(\Omega),
\end{align}
since $H^{1}_{0}(\Omega)$ is a linear space. Hence $tv+(1-t)u\in K$ for $t\in [0,1]$.
Comment: Just be clear, you are asking  why $K$ is independent of the choice of $\tilde{g}$?
Comment: That is correct.
Comment: OK. I guess the problem in your argument is that you want to apply Thm 9.17 to $v-\tilde{g}$, which is not a continuous function and Thm 9.17 therefore not applicable. But you only need to apply Thm 9.17 to the difference of two continuous extensions (see my answer below, hope it helps).
Comment: You probably should ask the Extra Question as a new question. It doesn't really have anything to do with the first one. The comment you quote from Brezis is definitely not sufficient to understand why a weak solution is a classical solution when the data is sufficiently smooth. Most textbooks have a whole chapter devoted to this question (regularity).
Comment: Yes, I have created a new question for this now.
Answer: To show that $K$ is independent of the choice of extension $\tilde{g}$, consider another extension $\hat{g}\in H^1(\Omega)\cap C(\overline{\Omega})$ with $\hat{g}=g$ on $\partial\Omega$. Put
$$
\hat{K}:=\{v \in H^1(\Omega)\ |\ v-\hat{g}\in H^1_0(\Omega) \}.
$$
We have to verify that $K=\hat{K}$.
To this end consider $v\in K$. Then $v-\tilde{g}\in H^1_0(\Omega)$. From Theorem 9.17 we deduce that also $\hat{g}-\tilde{g}\in H^1_0(\Omega)$.
Since $H^1_0(\Omega)$ is a linear space, we obtain
$$
v-\hat{g} = v- \tilde{g} + (\tilde{g}-\hat{g}) \in H^1_0(\Omega).
$$
Consequently, $v\in\hat{K}$. We conclude $K\subset\hat{K}$. The opposite inclusion follows by a similar argument, and we thus obtain $K=\hat{K}$.
Comment: While what you have here is fine, does it really show the dependence of $K$ on $g$? I believe the dependence on $g$ Brezis talks about is that for every $v\in K$ $v=g$ on $\partial\Omega$, however this does not come across, at least for me, from your argument.
Comment: Just to be absolutely clear: $K$ depends on $g$. However, $g$ does not appear explicitly in the definition of $K$, but only implicitly via the extension $\tilde{g}$. Since such an extension is not unique, it is only natural to ask whether a different extension might yield a different set $K$. This is what is typically behind the phrase "$K$ is independent of the choice of $\tilde{g}$".
Comment: The question "is $v=g$ on $\partial\Omega$ for every $v\in K$" from your comment above is an entirely different question. In order to answer it, you first have to define what the value/meaning of $v$ is on the boundary $\partial\Omega$, which is by no means trivial since you only know $v\in H^1(\Omega)$. For this pupose you need the notion of the _trace_ of $v$. It seems to me, however, that Brezis is trying to avoid introducing this notion (it is complicated).
Comment: OK. I think I see what is going on now.
Comment: One extra question regarding $K$. Brezis mentions it is nonempty, is this just because $\tilde{g}\in K$ always? (I should mention for this example $\Omega$ is an open bounded set in $\mathbb{R}^{N}$).
Comment: That is correct, $\tilde{g}\in K$ so $K$ is non-empty.
Comment: Is it possible to check my convexity argument I have edited into the original post? Thank you for your help, I really appreciate it. Also you mentioned texts on regularity in another comment, could recommend a text for a beginner? To give you some idea, all this reading I am doing is in preparation for a PhD which commences soon. Thank you.
Comment: Your convexity argument is fine. Concerning regularity, the book by Evans "Partial Differential Equations" is popular (elliptic regularity in Chapter 6.3). It is generally a very good book also on the level of PhD students. Good luck!


execute method with task scheduler wrapper library

Question: i have a simple job class and i want to execute it continuously.I've done little search and i found Microsoft.Win32.Task-scheduler library. but i can't found out how to execute one my class method with it.
I'm new in C# programing so accept my apologies if it is a silly question. and if there is better way in order to develops a task scheduler application i really apprenticed to let me know.
this is my job class:
class Job
{
    private int counter = 0;
    public override string GetName()
    {
        return this.GetType().Name;
    }
    public override void DoJob()
    {
        //do a job
        counter++;
    }
    public override bool IsRepeatable()
    {
        return true;
    }
    public override int GetRepetitionIntervalTime()
    {
        return 1000;
    }
}

Answer: I would recommend using  Quartz.net for this kind of work:
It works similarly to your code, and you can create multiple job classes that implement the IJob interface.


Regex para capturar bloco de texto

Question: Preciso extrair blocos de texto que estão dentro de #regions:
<code>#region VARIAVEIS GLOBAIS
string aux1 = "teste";
string aux2 = "teste2";
...
#endregion
</code>
O retorno seria:
<code>string aux1 = "teste";
string aux2 = "teste2";
...
</code>
Como faço isso com RegEx?
Lembrando que cada region apresenta um nome diferente.
Answer: Não sou desenvolvedor C# mas esta expressão regular resolve esse problema, você precisa ver como ficaria no seu código:
<code>(?<=#region VARIAVEIS GLOBAIS).*?(?=#endregion)
</code>
Exemplo: https://regex101.com/r/wF5pE9/1

Regex para capturar bloco de texto


Can I deploy my Content on drupal using scripts?

Question: If suppose I have a drupal application in Github and I have automated drupal installation using chef. Now I want to deploy that application content such that i can see it on my content page.
I am unable to put php and drupal tags due to reputation.
Comment: you can create nodes programmatically (like blog posts or basic pages). Is that what you're asking for?
Answer: If you would like to automate your deploys of content, just like you automate your code deploys, you'll probably want to look into the migrate module.  This model is best for sites where the content is managed by a content-generation team; it is less applicable for sites that have a lot of user-generated content.  This is a viable model that some people use, though, and is a very compelling workflow if your use-case supports it. One good extant site that uses this technique and has a public GitHub repository is Gizra's Negawatt.


jQuery mask plugin para CPF

Question: Gostaria de saber o que estou fazendo errado. Estou utilizando esse plugin https://github.com/igorescobar/jQuery-Mask-Plugin para tentar aplicar uma máscara de CPF (preciso que seja através do CDN) porém quando insiro os dados no campo, nada acontece. Segue meu head onde importo os CDNS:
!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

Função javascript:

Meu campo de CPF:

     CPF
     <INPUT type="text" name="paramCpf" id="paramCpf" value="">

Comment: Você está importando o jQuery ? não o plugin de máscara, o jQuery mesmo, são coisas diferentes
Answer: Duas coisas, veja se vc esta importanto o JQUERY também, essas 2 libs que vc ta importanto é só pra mask, todos os plugins de jquery pedem a importação do Jquery também.
Segunda coisa, de um F12 (Caso seja chrome) e vá em "Network" e veja se realmente esta com status 200 os itens que vc importou.
Segue a cdn do jquery pra vc testar

Comment: Era isso mesmo amigo, comecei a mexer com jQuery a pouco tempo e tinha esquecido desse detalhe! Obrigado pela resposta rápida e objetiva!

jQuery mask plugin para CPF


What is the best way to play audio through the VScode API?

Question: Basically the title. I have tried play-sound, which of course does not work. I have tried creating child processes, as such:
require('child_process').exec('python music.py', (err, stdout) => {
            console.log('result', err, stdout)
      })

but as the CWD of debug vscode window is the actual directory of MS VS Code (created when downloading vscode), it can never find my python script. I also can't use any getCWD() methods, as again, the CWD is not where the actual source files for the extension are.
Any input helps, and I know there are extensions to play audio, this is a special use case.
Comment: If the python file is located under the extension path (packed inside the extension), you can get the extension path with `context.extensionPath`.
Answer: You can get it with ExtensionContext.extensionPath.
ExtensionContext can usually be received as context at activate().
For example, for ./scripts/x.py, you can get the path you want by
vscode.Uri.joinPath(context.extensionUri, "scripts", "x.py").fsPath()

extension context doc
https://code.visualstudio.com/api/references/vscode-api#ExtensionContext
uri doc
https://code.visualstudio.com/api/references/vscode-api#Uri
Note:
If saving the mp3 to a file is not a pain for you, using the audio playback extension is the easiest option.
https://marketplace.visualstudio.com/items?itemName=sukumo28.wav-preview


How to make my flutter app read upadated json file instead of old json file?

Question: I made a app where I have to first read local json file and updated some content of it inside app and save that file and without closing the app I want to display the changes by reading updated json file.
I am able to read my json file, save changes in that file but when I try to see my changes without closing the app by reading that json file, it always show my previous data. But if I close my app and open it again It show read new updated file.
How can I show changes by reading updated json file without closing the app??
This is my code:
First I read json file inside initstate:
Future<void> readJson() async {
final String response =
    await rootBundle.loadString('jsonfile/primary_values.json');

final data = jsonDecode(response);

var values = PrimaryValueJson.fromJson(data);
setState(() {
  if (primaryKey == 'Doctor SSN :') {
    widget.primaryIndex = values.doc_ssn;
    widget.primaryValue = 'DC0${widget.primaryIndex}';
    print(widget.primaryValue);
    print('this is readjson');
  }
});

}
@override
  void initState() {
    super.initState();
    print("I am doctor init screen");
    readJson();
  }

And then I increment Doc.ssn by 1 and write it by clicking a button. Function associated with that button is:
_writeJson() async {
    print("this is 1st line writejson: ${widget.primaryIndex}");
    String response =
        await rootBundle.loadString('jsonfile/primary_values.json');
    File path = File('jsonfile/primary_values.json');

    var data = jsonDecode(response);
    var values = PrimaryValueJson.fromJson(data);
    final PrimaryValueJson doctor = PrimaryValueJson(
      doc_ssn: values.doc_ssn + 1,
      phar_id: values.phar_id,
      ssn: values.ssn,
    );
    final update = doctor.toJson();
    path.writeAsStringSync(json.encode(update));
    print('this is writejson:${doctor.doc_ssn}');

    nameController.text = '';
    specialityController.text = '';
    experienceController.text = '';
    widget.primaryIndex = doctor.doc_ssn;
    widget.primaryValue = 'DC0${doctor.doc_ssn}';
  }

  Future<void> insertRecord(context) async {
    count = count + 1;

    if (nameController.text == '' ||
        specialityController.text == '' ||
        experienceController.text == '') {
      print("Please fill all fields");
    } else {
      try {
        String uri = "http://localhost/hospital_MS_api/insert_doctor.php";

        var res = await http.post(Uri.parse(uri), body: {
          "Doc_SSN": widget.primaryValue,
          "name": nameController.text,
          "speciality": specialityController.text,
          "experience": experienceController.text,
        });
        setState(() {
          _writeJson();
        });

        var response = jsonDecode(res.body);
        if (response["success"] == "true") {
          print("Record Inserted");
        } else {
          print("Record not inserted");
        }
      } catch (e) {
        print(e);
      }
    }
  }

Answer: Assets are read-only. After writing an asset file to a file, read also from that file.
File path = File('jsonfile/primary_values.json');
...
path.writeAsStringSync(json.encode(update));
...
var data = jsonDecode(path.readAsBytesSync());


Assign line number to one of the fields based on the no. of fields in each row

Question: I need to manipulate one of my data files using awk command like this. How can I accomplish this using awk? Any inputs would be appreciated. Thank you.
1) Get the no. of fields for each row.
   (a) If the count_of_fields = 'x' then assign a value to nth field in each row.

Input :-
1,x,A,B
2,A,B,C
3,x,C,D
4,D,E,F,G
5,x,E,F

**
Output
** :-
1,1,A,B
2,A,B,C
3,3,C,D
4,D,E,F,G
5,5,E,F

x- is the 2nd column where I would like to assign NR when NF=4
n - This is the 2nd column.

Comment: For example, I could post a solution that's just `awk '{sub(/x/,NR)}1' file` and when run against your posted sample input it would produce your posted expected output. Its completely the wrong solution of course so what value did your sample input/output add? None. It's always easy to make changes you want and much harder to avoid changing things you don't want changed so when creating sample input/output really put some effort into coming up with the cases you think will be hard to get right, at least include cases that cover your most basic requirements.
Comment: Please make the example clearer, what are `x` and `n` in the the input ? Also what have you tried up to now ?
Comment: THINK about the sample input/output you provided. You seem to have a requirement to ONLY do something when a field is x and NF is 4 so why would you only post sample input where every time a field is x NF **is always** 4? As written someone could write a solution that completely ignores your requirement to only change x when NF is 4 and test it against your posted sample input and it would produce your expected output. Also you **always** have x in the field you WANT changed so we could ignore that requirement too. That's a terrible example, not even close to covering your use cases!
Answer: Try the following:
awk -v count=4 -v ndx=2 'BEGIN { FS=OFS="," } NF==count { $ndx = NR } 1' file

If the 2nd field should only be replaced if its original value is x (to be consistent with your sample output):
awk -v count=4 -v ndx=2 'BEGIN { FS=OFS="," } NF==count && $ndx=="x" { $ndx = NR } 1' file

-v count=4 -v ndx=2
passes the desired field count as awk variable count to the awk script, and the index of the target field as variable ndx.
BEGIN { FS=OFS="," }
executed only once, before the rest of the script, sets both the input field separator (FS) and the output field separator to , so that awk breaks the input into fields by commas, and also uses commas as separators when rebuilding the line after changing a field value. Thanks, Ed Morton.
NF==count
is a pattern that tests the field count (NF) against the count variable and executes the following action ({...}) only if the values are equal.
{ $ndx = NR }
assigns the current (1-based) row index (NR) to the field with index ndx, effectively rebuilding the input line with the new field value.
1
is a common shorthand to simply print the (potentially modified) input line. (1 is effectively equivalent to { print }: pattern 1 invariably evaluates to true, and since it has no associated action, the default action kicks in, which is to simply print the line.)
Answer: Your question is not entirely clear.
In awk, the built-in variables NF and NR denote the number of fields in each line and the record/line number, respectively.
To get the desired output from the given input, I would do the following:
awk 'BEGIN{OFS=FS=","}$2=="x"{$2=NR}1' test.txt

This replaces each x in the second column by the line number:
1,1,A,B
2,A,B,C
3,3,C,D
4,D,E,F,G
5,5,E,F

Update: If you want to replace the 2nd column's content by NR if the number of fields equals 4:
awk 'BEGIN{OFS=FS=","}NF==4{$2=NR}1' test.txt

Output:
1,1,A,B
2,2,B,C
3,3,C,D
4,D,E,F,G
5,5,E,F


Is this head voice/mixed voice?

Question: I have been a curious student of singing for a long time on my own now.
Basically scoured the Internet videos/forums, etc and practiced on songs that I like to cover.
The way I sing has consistently change with every new information/tip I discover from said media, I used to always(I'm pretty sure) pull chase only. Now the thing is I'm not sure if I have actually found my mixed or head voice yet. I no longer feel easily fatigued/tired much when singing the way I do today, but my tone is not something I'm a fan of. I'm hoping you guys can point me in the right direction. Like what I'm doing wrong,etc.
This is a cover of a 3 Days Grace song, Lost in You. In the Bridge section, I sing in what I myself call a mixed voice, though I'm not sure what it really is.
It just doesn't sound like my pure chest voice, which is why I call it mixed because it also doesn't sound like the pure operatic head voice, but then again, tone sounds quite disconnected to me. I'd like to improve on that part.
https://www.dropbox.com/s/uy8695n4g9abfnj/Lost%20in%20You.mp3?dl=0
Answer: This may be a duplicate, in fact there are quite a few posts on this site about trying to sing head voice/falsetto. Consider seeing the other post and the good tips that are there.
From personal experience, I will say that the best learning mechanism for this is time. The other post gives technical descriptions of the voice mechanisms and explains that the voice needs to mature to help falsetto develop.
I developed an ok falsetto from singing a lot of rock and roll music, not that you should imitate other singers as much as you should hear how falsetto generally sounds and attempt it in your voice, not as an imitation of theirs.
Just a friendly reminder, singing too high can damage your voice. Don't strain out high notes, sing what is comfortable. If you want to improve your upper range hoot like an owl very high.
Answer: I applaud the work you've been doing.  Making music is one of the things that keep us human!
I would suggest that you start to work with a teacher.  There are so many things a teacher can help you discover.  Learning to sing without a teacher is kind of like learning a foreign language just from a dictionary, without any interaction or conversation with other people in the target language.
The various parts of a singer's range that you have read about make sense in a trained voice, a voice that is doing things right.  They don't necessarily make sense in an untrained voice; and even in a trained voice, one would need to hear the full range in order to describe the voice, say where its break points currently are, and make targeted suggestions for the particular singer.
You have lots of talent and interest in music.  To channel the talent and interest optimally, you would need the help of an experienced vocal teacher.
Answer: One does not "discover" mixed voice.  Mixed voice replaces the flip from chest voice to falsetto with a controlled transition.
Head voice is basically the chest-falsetto see-saw still on the chest voice side, just with most of the weight taken off.  It doesn't forego the flip but diminuishes its strength, and it takes overall strain off.  That's something you can develop gradually.  "pure operatic head voice" sounds like you are just throwing words around.  You should not try planning an exercise regimen based on words.
It makes more sense to work with a teacher for developing your voice, assuming that your aim is developing your voice rather than your terminology.

Is this head voice/mixed voice?


Embed NavigationController in Container View

Question: I am trying to embed a Navigation Controller in a Container View using the Storyboard.  I add my Container View to my scene, delete the View Controller that it is automatically generated, and control-drag from the Container View to my Navigation Controller, creating a segue.
When I run the app in the simulator and transition to the scene containing the Container View, I get this exception:
2018-04-28 15:22:40.278627-0400 Woofr[8977:18656423] *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key containerView.'
If I run it as a test with just the original automatically generated View Controller in place, it works.  If I control-drag from the Container View to the Navigation Controller without deleting the automatically generated View Controller, the segue is replaced in the Storyboard, but I get the same exception when I run the app.
ETA full stack trace:
2018-04-28 15:44:22.748243-0400 Woofr[15437:18687945] *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<UIStoryboardShowSegueTemplate 0x6040004756c0> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key containerView.'
*** First throw call stack:
(
    0   CoreFoundation                      0x00000001078521e6 __exceptionPreprocess + 294
    1   libobjc.A.dylib                     0x000000010699a031 objc_exception_throw + 48
    2   CoreFoundation                      0x00000001078520b9 -[NSException raise] + 9
    3   Foundation                          0x00000001063bbb47 -[NSObject(NSKeyValueCoding) setValue:forKey:] + 292
    4   UIKit                               0x0000000108cc2d56 -[UIRuntimeOutletConnection connect] + 109
    5   CoreFoundation                      0x00000001077f4e8d -[NSArray makeObjectsPerformSelector:] + 317
    6   UIKit                               0x0000000108cc1700 -[UINib instantiateWithOwner:options:] + 1856
    7   UIKit                               0x00000001089dc137 -[UIViewController _loadViewFromNibNamed:bundle:] + 383
    8   UIKit                               0x00000001089dca64 -[UIViewController loadView] + 177
    9   UIKit                               0x00000001089dcd81 -[UIViewController loadViewIfRequired] + 175
    10  UIKit                               0x00000001089dd5d4 -[UIViewController view] + 27
    11  UIKit                               0x0000000108a0ec6e -[UINavigationController _startCustomTransition:] + 945
    12  UIKit                               0x0000000108a255e2 -[UINavigationController _startDeferredTransitionIfNeeded:] + 714
    13  UIKit                               0x0000000108a268cc -[UINavigationController __viewWillLayoutSubviews] + 150
    14  UIKit                               0x0000000108c7ebd7 -[UILayoutContainerView layoutSubviews] + 231
    15  UIKit                               0x0000000108908808 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 1515
    16  QuartzCore                          0x00000001045d161a -[CALayer layoutSublayers] + 177
    17  QuartzCore                          0x00000001045d582b _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 395
    18  QuartzCore                          0x000000010455c29f _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 343
    19  QuartzCore                          0x0000000104589940 _ZN2CA11Transaction6commitEv + 568
    20  UIKit                               0x000000010883334f _UIApplicationFlushRunLoopCATransactionIfTooLate + 167
    21  UIKit                               0x0000000109198532 __handleEventQueueInternal + 6875
    22  CoreFoundation                      0x00000001077f4bb1 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
    23  CoreFoundation                      0x00000001077d94af __CFRunLoopDoSources0 + 271
    24  CoreFoundation                      0x00000001077d8a6f __CFRunLoopRun + 1263
    25  CoreFoundation                      0x00000001077d830b CFRunLoopRunSpecific + 635
    26  GraphicsServices                    0x000000010cb86a73 GSEventRunModal + 62
    27  UIKit                               0x00000001088390b7 UIApplicationMain + 159
    28  Woofr                               0x0000000100d34427 main + 55
    29  libdyld.dylib                       0x000000010b050955 start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException

ETA Settings Scene screen shot:
Answer: In the ViewController class which contains the containerView, make sure to add IBOutlet for it
@IBOutlet var containerView: UIView!

When you drag a ContainerView into a view and give it constraints, it creates a ViewController with a segue from that ContainerView.
Embed this destination ViewController in a NavigationController from
Editor -> Embed In -> Navigation Controller
Comment: That was it, thank you!  It's not possible to embed a Navigation Controller directly into a Container View.  You have to add a segue to the first View Controller from the Container View then embed that VC in a Navigation Controller.
Comment: I control-dragged to add that but got the same exception.
Comment: value coding-compliant for the key containerView ??? or another view ?? post the new error
Comment: I don't understand your question, but I edited the question to include the full stack trace.
Comment: can you show a photo of storyboard ? with expanded views content
Comment: I added a screen shot of the Settings Scene.  There are a lot of scenes in the app -- in this case the only segues are back to the Log In screen and to the Navigation Controller.  The Navigation Controller is a standard container for a Table View that segues to a detail page for the items in the Table View.
Comment: make the segue from the the yellow icon of the setttingsVC not from a view inside it
Comment: How will that display the Navigation Controller inside the Container View?  All the examples I've seen say to drag from the Container View to the View Controller.
Comment: How can I embed the ContainerView with NavigationController programmatically? any idea?


How to post data to ASP site using php curl

Question: I need to post data to ASP site using php curl from my website.
The ASP site is http://www.hotfrog.com.au/AddYourBusinessSingle.aspx
For this point I approached like below

Crawled the webpage html source from that website using PHP curl to maintain cookies & sessions
From that source asp hidden variable values extracted
Prepared post string with required form fields
And posted that data to target ASP site url using PHP curl but response is that page form information without entry details and even its not shows validation messages from curl response for non entry fields.
For this process maintained same values for CURLOPT_USERAGENT, CURLOPT_COOKIEJAR, CURLOPT_COOKIEFILE

The ASP site required form fields like this below
ctl00$contentSection$CompanyDetailsControl$txtBusinessName
ctl00$contentSection$CompanyDetailsControl$txtSuburb
are them to be posted directly or there any encode needed for these field names before posting to target site by PHP curl
Can anyone have solution for this solution or any other approaches for ASP sites by php curl?
Answer: use
function get_headers_from_curl_response($headerContent) {

    $headers = [];

    // Split the string on every "double" new line.
    $arrRequests = explode("\r\n\r\n", $headerContent);

    // Loop of response headers. The "count() -1" is to
    //avoid an empty row for the extra line break before the body of the esponse.
    for ($index = 0; $index < count($arrRequests) - 1; $index++) {

        foreach (explode("\r\n", $arrRequests[$index]) as $i => $line) {
            if ($i === 0) {
                $headers[$index]['http_code'] = $line;
            }
            else {
                list ($key, $value) = explode(': ', $line);
                $headers[$index][$key] = $value;
            }
        }
    }

    return $headers;
}

function regexExtract($text, $regex, $regs, $nthValue) {
    if (preg_match($regex, $text, $regs)) {
        $result = $regs[$nthValue];
    }
    else {
        $result = "";
    }

    return $result;
}

$regexViewstate = '/__VIEWSTATE\" value=\"(.*)\"/i';
$regexEventVal   = '/__EVENTVALIDATION\" value=\"(.*)\"/i';

$ch = curl_init("__YOUR__URL__HERE__");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookies.txt');

$response = curl_exec($ch);
curl_close($ch);

$viewstate = regexExtract($response, $regexViewstate, $regs, 1);
$eventval  = regexExtract($response, $regexEventVal, $regs, 1);

$params = [
    '__EVENTTARGET'       => '',
    '__EVENTARGUMENT'     => '',
    '__VIEWSTATE'         => $viewstate,
    '__EVENTVALIDATION'   => $eventval,
    'ctl00%24txtUsername' => 'xxx',
    'ctl00%24txtPassword' => 'xxx',
    'ctl00$ImgLogin.x'    => '0',
    'ctl00$ImgLogin.y'    => '0',];

$ch2 = curl_init("http://gsc.klub-modul.dk/cms/ShowContentPage.aspx?ContentPageID=1");
curl_setopt($ch2, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch2, CURLOPT_HEADER, 1);
curl_setopt($ch2, CURLOPT_POST, true);
curl_setopt($ch2, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch2, CURLOPT_POSTFIELDS, http_build_query($params));
curl_setopt($ch2, CURLOPT_COOKIE, 'cookies.txt');
curl_setopt($ch2, CURLOPT_COOKIEJAR, 'cookies2.txt');

$response2 = curl_exec($ch2);
curl_close($ch2);

foreach (get_headers_from_curl_response($response2) as $value) {
    foreach ($value as $key => $value2) {
        echo $key.": ".$value2."
";
    }
}


Java - Can't use ResultSet after connection close

Question: I have a problem with closing a connection to MySQL.
I'm getting the error:

java.sql.SQLException: Operation not allowed after ResultSet closed

My code:
public static ResultSet sqlquery (String query)
{
 ResultSet rs=null;
 Connection connection=null;
 Statement st=null;
 try{
     Class.forName("com.mysql.jdbc.Driver");
     connection = DriverManager.getConnection("databaseadress","username","password");
     st = connection.createStatement();
     rs = st.executeQuery(query);

    }catch(SQLException e){System.out.println("SQL error: " + e);}
      catch(Exception e){System.out.println("Error: " + e);}
       finally {
       try{
          if(rs != null) rs.close();
          if(st!= null) st.close();
          if(connection != null)  connection.close();
  }catch(SQLException e){System.out.println("SQL error : " + e);}

    }
     return rs;
}

Comment: I'm no database expert, but it seems to me that you don't want to close your connection until you're done with the ResultSet. So what happens when you change your code to reflect this? Why not extract the data from your ResultSet within the method, and return an ArrayList of whatever objects you wish to create with your data, and then return this list from the method?
Comment: You closed the ResultSet, so everything is deleted. Why you want to use it? Extract the data before you close it and return the data
Comment: Which line of code is the exception occurring on?  Are you sure it's one that you've shown here?
Comment: It appears he's returning the `ResultSet` object and getting the exception later in code not shown here.
Comment: @JimGarrison Yes, I know that.  I was hoping that by examining the stack trace, he'd figure that out.
Comment: Yes, I use function sqlquerry in other part of the code.
It worked without connection closed, but I've realized that it's not a good idea ;)
Answer: JDBC doesn't bring back all the results of a query in a ResultSet, because there may be too many of them to fetch them all eagerly. Instead it gives you something you can use to retrieve the results, but which goes away when the connection closes. So when you pass it back from your method after closing the database connection, nothing else can use it.
What you can do instead is to have this method use the resultSet to populate an object or a collection of objects, and pass that populated object back.
If you change your code to pass in a rowMapper (that takes a resultSet and passes back an object populated with the current row in the resultset), and use that to populate a container object that you pass back, then you'll have something as reusable as what what you've written, but which actually works because it doesn't depend on having the connection held open after the call is finished.
Here's your example code rewritten to use the rowmapper, get rid of some unnecessary exception-catching, and fix a bug that will prevent the connection from getting closed in some cases:
public static List<T> sqlquery (String query, RowMapper<T> rowMapper) throws SQLException
{
    Connection connection=null;
    Statement st=null;
    ResultSet rs=null;
    // don't need Class.forName anymore with type4 driver
    connection = DriverManager.getConnection("databaseadress","username","password");
    st = connection.createStatement();
    rs = st.executeQuery(query);
    List<T> list = new ArrayList<T>();
    while (rs.next()) {
        list.add(rowMapper.mapRow(rs));
    }
    // don't let exception thrown on close of
    // statement or resultset prevent the
    // connection from getting closed
    if(rs != null)
        try {rs.close()} catch (SQLException e){log.info(e);}
    if(st!= null)
        try {st.close()} catch (SQLException e){log.info(e);}
    if(connection != null)
        try {connection.close()} catch (SQLException e){log.info(e);}
    return list;
}

If you don't catch each exception thrown on close individually, as shown above, you risk failing to close the connection if either the statement or the resultSet throw an exception on close.
This is similar to what spring-jdbc does, it defines a RowMapper as:
public interface RowMapper<T> {
    T mapRow(ResultSet, int rowNum) throws SQLException;
}

The next step is going to be parameterizing your queries so you don't have to
surround parameter values in quotes or worry about sql injection. See this answer for an example of how spring-jdbc handles this. The long term answer here is, it would be better to adopt spring-jdbc or something similar to it than to reinvent it piecemeal.
Comment: Thanks, for explanation how  ResultSet is handled
Answer: This is the way JDBC works.  In your code you closed the ResultSet and the Connection, after which the ResultSet is no longer usable.  If you want it to be usable you must leave it (and the Connection) open.
However, if you return the ResultSet, you should refactor your code so the calling method provides the Connection.
Comment: Thanks, it would be probably the best way :)
Answer: RowSetFactory factory = RowSetProvider.newFactory();
CachedRowSet rowset = factory.createCachedRowSet();
rowset.populate(ResultSet data)

/* now you can close you connection and prepare statement*/
Answer: Once the connection is closed you can no longer use any of the resources (statements, prepared statements, result sets), all of them are automatically closed. So you need to do all of your processing while the resources are open.
Try filling and returning a DTO, this way you can have the data you need without keeping a connection alive.


Computing the Laplace transform of $\tan(pt)$

Question: I've been  thinking of using  complex number approach , what's your view guys ?.
Comment: The singularities will make this quite challenging. My guess is you'll have to appeal to the residue theorem.
Comment: Oh.OK...can you throw more light please , am not really familiar with the residue  Theorem , though av  heard of it  & seen video tutorials on it....ain't they other  approach ?.
Comment: The Laplace transform of $f(t) = \tan(pt)$ doesn't exist. That's one of the reasons equations like $y'' + y = \tan x$ are interesting and challenging.
Comment: ^ but  the solution to the   D.E you put up there could easily  be determined by variation of parameters , maybe because The use of Laplace ..to solve D.E,s works suitably for IVPs ,
Comment: I think you have to calculate the integral in the sense of principal value, to get a Laplace transform of  $\tan(p t)$, and even then, it won't be that easy. I would not be surprised if the result involves some special function.
Answer: Since:
$$ \cos(x)=\prod_{n\geq 0}\left(1-\frac{4x^2}{(2n+1)^2\pi^2}\right)\tag{1} $$
by considering the logarithmic derivative of both sides we have:
$$ \tan(x) = \sum_{n\geq 0}\frac{8x}{(2n+1)^2\pi^2-4x^2}=\sum_{n\geq 0}\left(\frac{-1}{x-\frac{2n+1}{2}\pi}+\frac{-1}{x+\frac{2n+1}{2}\pi}\right)\tag{2}$$
so $\tan(x)$ does not have a Laplace transform, but, at least formally, has a nice inverse Laplace transform:
$$\mathcal{L}^{-1}(\tan(x))=-2\sum_{n\geq 0}\cosh\left(\frac{2n+1}{2}\pi s\right).\tag{3} $$
For practical purposes, we may consider partial sums for the RHS of $(2)$ or the RHS of $(3)$.
Comment: But what does this even mean?  You have a clear divergent series that represents an input (causal) signal. A partial sum does not represent the LT or the ILT in this case.  Maybe you had something more specific in mind?
Answer: Using CAS like Mathematica we have:
$$\mathcal{L}_t[\tan (p t)](s)=-\frac{i}{s}+\frac{\Phi \left(-1,1,1-\frac{i s}{2 p}\right)}{p}$$
where:
$\Phi \left(-1,1,1-\frac{i s}{2 p}\right)$ is HurwitzLerchPhi function
Using:
$$\tan (x)=-i+\sum _{k=1}^{\infty } -2 i (-1)^k e^{-2 i k x}$$
we have:
$$\mathcal{L}_t[\tan (p t)](s)=\sum _{k=1}^{\infty } \mathcal{L}_t\left[-i-2 i (-1)^k e^{-2 i k p t}\right](s)=-\frac{i}{s}-\sum
   _{k=1}^{\infty } \frac{2 i (-1)^k}{2 i k p+s}=-\frac{i}{s}+\frac{\Phi \left(-1,1,1-\frac{i s}{2 p}\right)}{p}$$
Comment: Also another identity: $\mathcal{L}_t[\tan (p t)](s)=\Re\left(\frac{\psi \left(\frac{i s}{4 p}\right)}{2 p}-\frac{\psi \left(\frac{1}{2}+\frac{i s}{4
   p}\right)}{2 p}\right)=\Im\left(\frac{i \psi \left(\frac{i s}{4 p}\right)}{2 p}-\frac{i \psi \left(\frac{1}{2}+\frac{i s}{4
   p}\right)}{2 p}\right)$ where: $\psi \left(\frac{i s}{4 p}\right)$ is PolyGamma function.


Printable Templates for Views using Print Module

Question: Any views related report can be printed using the Print module when enabled. This can be achieved by simply using /print/views-url. It uses the standard print.tpl.php.
I do not want the print version of views output to display the exposed filter. At the same time, I would not want to modify the default print.tpl.php.
Is there a way to use alternative print templates for views in the same line as for content types: print[--html|--mail|--pdf][--node--node-type].tpl.php
Thanks.
Answer: I faced a similar issue quite a while back and below is how I solved it:

Create another display of the same view (clone page)
Choose 'Remember last selection' in the Views exposed filters' settings in the original page view
In the cloned page view, set 'Expose form in a block' to 'Yes'
Use the regular 'print/view-url' wherever you want but remember that 'view-url' in this case is the path of the cloned page view.

Hope this helps,
Regards,
Supriya Rajgopal
Comment: This may help https://www.drupal.org/node/2037097


Basic Question: how does feed-forward neural network solve regression?

Question: This is a fairly basic question but I can't seem to find an answer on the net (perhaps I'm searching the wrong things).
Regression is trying to predict continuous outputs. Since a neural network uses a clamping function (typically giving a value between 0 and 1) before the output.. if the output can only be between 0 and 1, how can a neural network learn a regression function?
Thanks in advance
Answer: The usual solution is to provide an output layer which uses a linear neuron rather than the traditional sigmoid or tanh. This achieves the necessary infinite range from a finite range. A linear neuron simply outputs a linear combination of its inputs, usually with an added bias parameter for a constant term. The weights in the linear function and the bias are learnt by the network during training.
Comment: The linear output unit can only output the weighted sum of the layer before it. Say all weights were 1 and the outputs to the layer before this linear unit were $z_i$. In this case, the maximum value of $z_i$ is one, therefore the output unit has an upper bound of $n$ where $n$ is the number of units in the second to last layer. I don't see the network could output numbers greater than $n$.
Answer: The input is usually normalized to a value between 0 to 1. After feeding it into the neural network the output will also be between 0 to 1. After which it is denormalized. The neural net works by finding the underlying relationship between the input and output mathetically. Think of it as a linear equation. However it is an approximate solution.


Holding violin bow without pinky

Question: For classical violin: Is holding the bow without using the small finger of the right hand considered defective technique, or does it not matter?
I've realized that I bow without my pinky, and usually it is not even in contact with the bow.  In fact, even if I try I can't easily keep my pinky on the bow as I draw it down towards the tip.
Here is my bowing hand:

And here is my default grip on the bow:

Am I doing something obviously wrong?  Is this considered bad form?
Comment: My pinky size is essentially the same as yours and my pinky is usually in contact with the bow. I spread my fingers wider than you have them to be able to control the pressure with more torque/moment. Also when I down-bow all the way to the tip, I pretty much have to lift my pinky off the bow slightly. I'm only commenting because I have never had my grip validated by anyone, so I could be doing it wrong.
Answer: If you intend to use the bow over its full length, you'll need the pinky to counterbalance the index finger action when playing close to the frog.  Try playing notes in piano at full bow length on every string and switching direction as inconspicuously as possible on the far ends.  Having the pinky involved in the balance definitely helps.  Your picture of your default grip on the bow actually has it placed pretty well already. I'd slide it slightly farther from the ring finger on the bow stick but that's about it.  Most of the time you don't do a lot with it, just keeping it lightly lodged where it can seamlessly engage when necessary.  If you start placing it only then, the seamlessness is gone.
Comment: Good explanation: In fact my pinky naturally comes back in contact as I bow towards the frog.
Answer: Your pinky is only redundant because your ring and middle finger are not doing their job.
Balancing the bow happens mostly between the fingers with largest leverage, namely index finger and pinky.  Controlling bow tilt happens in the grip triangle of thumb, middle and ring finger.  To have control in all directions, middle and ring finger need to actually reach around the bow stick, with the bow stick being near the first finger joint of those fingers.
You should be able to move the and rotate the bow in all directions (including tilt) even without it touching the violin (try "air bowing" a constant small distance above the string).  If your ring and middle finger are as detached as in your picture, the bow is close to slipping out of control.
Once your ring finger comes around further, the pinky will be less redundant.
Answer: The bow hold varies slightly between the various "schools" of teaching.
My Moscow Conservatory trained instructor preferred her students to have the weight of the hand constant and even on the first finger, between the first two knuckles, and the rest of the hand as completely relaxed as possible. With this style, depending on your pinky length, the pinky may leave the stick at tip position, and help with balance and rotation at the frog position.
I have looked into other styles, and one of the common themes I have seen is that the technique should allow for the least use of muscle in the lower part of the hand so as to give the wrist the most flexibility possible.
In teaching, I have found that when students press with the pinky or third finger, it activates the thumb muscle which contributes to the locking up of the wrist through tendon action, so I actively discourage the use of the back fingers as much as possible while they are learning.
Answer: I've heard that the pinky (when on the bow) is used for balancing the bow and used in stuff like spiccato, but personally, I've never really encountered anything that definitely requires the pinky on the bow. For example, when I play spiccato, my pinky occasionally falls off my bow - no biggie, I just put it back on again when I can.
Of course, it's recommended, but not mandatory or as important as the other fingers in my opinion.
I would instead comment this instead due to the lack of sources/validation in my answer like Todd Wilcox has but I haven't the reputation yet, sorry.
Answer: You'll need to train your pinky's muscles to hold your bow, it'll come to use when you want to play at the tip. A good exercise would be holding your bow horizontally and lifting it with your pinky. It'll give you better control over your bow.
Anyway, you'd also benefit from lowering your middle and ring finger a towards the frog, so you have a better grip, especially if you want to play loud and fat.
Answer: (Note that I am not a professional)
In my grip different fingers seem to rotate the bow in different directions.

Pitch: little finger and index finger (with some other fingers keeping the axis of rotation stable)
Yaw: thumb and index finger or ring finger
Roll: thumb and middle finger

So perhaps you could check that you are able to perform all these rotations with your grip?
(Maybe you should also be able to lift the bow slightly using just the fingers (no wrist or arm motion) like moving them to some kind of L shape ? Not sure)

Holding violin bow without pinky


Android ProgressDialog não aparece

Question: Estou tentando mostrar um ProgressDialog no processo de download de um ficheiro binário, contudo este não aparece, e não obtenho qualquer erro também.
Resumidamente explicarei a maneira como tenho o código estruturado
Na minha MainActivity defino um botão para obter esse ficheiro... Ao clicarmos no botão cujo nome é botao_getbscan, aparece-nos um AlertDialog, com uma série de parâmetros para o utilizador definir, de forma a construir uma string que representa o URL para fazer o download do ficheiro binário. Após a definição desses parâmetros o utilizador carrega no botão ok do AlertDialog e este desaparece, começando a fazer o download, como podem ver de seguida:
botao_getbscan = (Button)findViewById(R.id.button4);
botao_getbscan.setOnClickListener(new View.OnClickListener() {
@Override
        public void onClick(View arg0) {

            // Se houver internet avança...
            if (isNetworkAvailable()) {
                // Construção de um dialog para introduzir os valores de contrução do b-scan
                LayoutInflater li = LayoutInflater.from(mContext);
                View dialog_view = li.inflate(R.layout.getbscan_dialog,null);
                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(mContext);
                alertDialogBuilder.setView(dialog_view);

                // Define o titulo e a mensagem do dialog
                //(...)

                // Define os botões do dialog
                alertDialogBuilder
                        .setCancelable(false)
                        .setPositiveButton("OK",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {

                                       //Definição de uma série de parâmetros para construir uma string com o "GET" pretendido...
                                       final String fullstring = "http://...................................;

                                       // Inicia o download e armazena na memória interna...
                                       boolean succed = StartDownload(fullstring);

                                })
                        .setNegativeButton("Cancel",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(
                                            DialogInterface dialog, int id) {
                                        dialog.cancel();
                                    }
                                });

                // Cria e mostra o alert dialog
                AlertDialog alertDialog = alertDialogBuilder.create();
                alertDialog.show();
            }
            else {
                AlertDialog.Builder saveDialog = new AlertDialog.Builder(MainActivity.this);
                saveDialog.setTitle("No Internet Connection Detected");
                saveDialog.setMessage("A connection to the internet is required to retrieve B-Scan. Please check your connection settings and try again.");
                saveDialog.setNeutralButton("OK",
                        new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog,int id) {
                        dialog.dismiss();
                    }
                });
                saveDialog.show();
            }
        }
    });//End of Get B-Scan Button

O método StartDownload consiste no seguinte:
public boolean StartDownload(String string){
    BitmapDownloaderTask object = new BitmapDownloaderTask(MainActivity.this);
    object.execute(string);
    try {
        byteArray = object.get();
        return true;
    } catch (Exception e) {
        Log.e("saveToInternalStorage()", e.getMessage());
        return false;
    }
} // End of StartDownload

Em seguida tenho a minha AsyncTask num ficheiro diferente ao qual chamei BitmapDownloaderTask.java, que basicamente define a minha classe BitmapDownloaderTask que estende uma AsyncTask. É aqui que defino o progress dialog, que gostaria que aparece-se após clicar no botão OK do meu AlertDialog, visto que após isso inicia-se de imediato o processo de Download.. Contudo o progress dialog não aparece e também não obtenho qualquer erro. Tenho então o seguinte:
class BitmapDownloaderTask extends AsyncTask<String, Void, byte[]> {

private ProgressDialog dialog;
private Context context;
private byte[] byteArray;

//--------------------CONSTRUCTOR--------------------------------//
public BitmapDownloaderTask(Context context) {
    this.context = context;
    this.byteArray = null;
    dialog = new ProgressDialog(context);
}

//--------------PRE EXECUTE--------------------------------------//
@Override
protected void onPreExecute() {
    super.onPreExecute();

    dialog.setMessage("Loading...");
    dialog.show();
}

//--------------BACKGROUND---------------------------------------//
@Override
// Actual download method, run in the task thread
protected byte[] doInBackground(String... params) {

    // params comes from the execute() call: params[0] is the url.
    return downloadBitmap(params[0]);
}

//--------------POST EXECUTE-------------------------------------//
@Override
// Once the image is downloaded
protected void onPostExecute(byte[] byteArray) {
    super.onPostExecute(byteArray);
    dialog.dismiss();
    if(byteArray != null){
        //pDialog.dismiss();
    }else{
        //pDialog.dismiss();
        Toast.makeText(this.context,"B-scan doens't exist, or there was a connection problem!", Toast.LENGTH_SHORT).show();
    }
}

static byte[] downloadBitmap(String url) {
// ......................
}

Obrigado!
Comment: Você implementou algo no método `downloadBitmap()`?
Comment: @ramaral Sim implementei, é um simples metodo de download a partir de um url utilizando HttpEntity HttpResponse e InputStream...
Answer: A razão de isso acontecer deve-se à chamado do método get() da classe AsyncTask no método StartDownload().
public boolean StartDownload(String string){
    BitmapDownloaderTask object = new BitmapDownloaderTask(MainActivity.this);
    object.execute(string);
    try {
        byteArray = object.get();
        return true;
    } catch (Exception e) {
        Log.e("saveToInternalStorage()", e.getMessage());
        return false;
    }
} // End of StartDownload

Esse método bloqueia a UIThread enquanto o AsyncTask é executado.
O método dialog.show(); é chamado no onPreExecute() mas como a UIThread está bloqueada o Dialog não pode ser apresentado.
Na altura em que a UIThread é desbloqueada, já o método onPosExecute() foi chamado e a linha dialog.dismiss() executada.
Não faz sentido usar uma AsyncTask e depois ficar à espera que ela termine dentro da UIThread.
Tire a chamada ao método get() e faça o tratamento do resultado do Download dentro do método onPostExecute(); ou, dentro dele, chame um método da Activity que o faça.
Implementação da BitmapDownloaderTask.
Como BitmapDownloaderTask reside num ficheiro próprio, teremos que passar, no construtor, a classe que contém o método que irá tratar o resultado.
Para que ela possa ser usada com qualquer Activity além da MainActivity, declaramos uma interface que deverá ser implementada por ela(Activity).
class BitmapDownloaderTask extends AsyncTask<String, Void, byte[]> {

    // Interface a ser implementada pela classe consumidora
    public interface OnDownloadFinishedListener{
        public void onDownloadFinished(byte[] resultado);
    }

    private ProgressDialog dialog;
    private Context context;
    private OnDownloadFinishedListener listener;
    private byte[] byteArray;

    //--------------------CONSTRUCTOR--------------------------------//
    public BitmapDownloaderTask(Activity activity) {

        this.context = activity;

        //Verifica se a Activity passada implementa a interface
        if(activity instanceof OnDownloadFinishedListener){
            this.listener = (OnDownloadFinishedListener)activity;
        }
        else{
            throw new ClassCastException(activity.toString()
                      + " must implement OnDownloadFinishedListener");
        }
        this.byteArray = null;
        dialog = new ProgressDialog(context);
    }

    //--------------PRE EXECUTE--------------------------------------//
    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        dialog.setMessage("Loading...");
        dialog.show();
    }

    //--------------BACKGROUND---------------------------------------//
    @Override
    // Actual download method, run in the task thread
    protected byte[] doInBackground(String... params) {

        // params comes from the execute() call: params[0] is the url.
        return downloadBitmap(params[0]);
    }

    //--------------POST EXECUTE-------------------------------------//
    @Override
    // Once the image is downloaded
    protected void onPostExecute(byte[] byteArray) {

        dialog.dismiss();

        //Se houver um resultado
        //Chammos o método da interface(Activity)
        if(byteArray != null){
            listener.onDownloadFinished(byteArray);
        }else{
            Toast.makeText(this.context,"B-scan doens't exist, or there was a connection problem!", Toast.LENGTH_SHORT).show();
        }
    }

    static byte[] downloadBitmap(String url) {
        // ......................
    }
}

Faça a MainActivity implementar a interface:
public class MainActivity extends ActionBarActivity implements OnDownloadFinishedListener{

    ..........
    ..........
    ..........
    ..........
    @Override
    public void onDownloadFinished(byte[] resultado) {

        //Faça aqui o tratamento do resultado
    }
}

O método StartDownload() será assim:
public void StartDownload(String string){
    BitmapDownloaderTask object = new BitmapDownloaderTask(this);
    object.execute(string);

} // End of StartDownload

Nota: O método passa a retornar nada
Comment: A classe *BitmapDownloaderTask* é declarada na *Activity* ou está num ficheiro próprio?
Comment: Editei a resposta.
Comment: Eu percebi o que você disse, mas o método StartDownload apenas chama a AsyncTask, e depois com o object.get() eu obtenho o array de bytes que representa o resultado do download efectuado na async task... nao vejo como fazer isso de outra maneira... eu preciso desse array de bytes na minha MainActivity...  poderia explicar-me como fazer isso no onPostExecute()?
Comment: está num ficheiro próprio... ficheiro esse que contem a classe BitmapDownloaderTask que extende a AsyncTask, e contém ainda o método  static byte[] downloadBitmap(String url) que é responsável por efectuar o download do array de bytes. Obrigado!
Comment: Muito Obrigado! Consegui implementar a tua solução, grande ajuda mesmo :D
Answer: Seu código está certo, verifique se ele esta passando por esse trecho:
    //--------------PRE EXECUTE--------------------------------------//
    @Override
    protected void onPreExecute() {
       super.onPreExecute();

       dialog.setMessage("Loading...");
       dialog.show();
    }

Se não estiver passando, ele será executado em background por isso você não consegue ver o load, uma alternativa é você colocar seu Progress Dialog dentro apenas do onClick.
Comment: Se o `dialog.show();`for colocado no `onClick()` onde se coloca o `dialog.dismiss();`?
Comment: @Leonardo Rocha em concreto como como colocava o dialog.show no onClick? criava o objecto na minha MainActivity? é que tenho a asynctask noutro ficheiro e não no ficheiro do onClick que é o da classe MainActivity.  Seria algo como antes de botao_getbscan.setOnClickListener(new View.OnClickListener() criava o objecto to tipo progressdialog e depois dentro do onClick colocaria dialog.show()? e onde ficaria o dialog.dismiss(), como disse o ramaral... Obrigado!
Comment: @Leonardo Rocha Esqueci-me de referir que o programa passa em onPreExecute(), verifiquei através de Logs e fazendo debug...
Comment: Você deve criar p objeto do tipo progressdialog e dentro do onClick colocar o dialog.show(), o dialog,dismiss ficaria no preExecute.

Android ProgressDialog não aparece


OpenVPN connection works but no gateway is assigned

Question: I try to setup OpenVPN on a VPS and I'm able to establish a connection to the server, but the gateway isn't assigned to the client.
Here are my config files:
client config:
client
dev tun
proto udp
remote foo.bar 1194
resolv-retry infinite
nobind
persist-key
persist-tun
ca ca.crt
cert client1.crt
key client1.key
ns-cert-type server
redirect-gateway
comp-lzo
verb 3
pull

server config:
port 1194
proto udp
dev tun
ca easy-rsa/2.0/keys/ca.crt
cert easy-rsa/2.0/keys/server.crt
key easy-rsa/2.0/keys/server.key
dh easy-rsa/2.0/keys/dh2048.pem
server 172.30.90.0 255.255.255.192
ifconfig-pool-persist ipp.txt
push "redirect-gateway def1"
push "dhcp-option DNS 22.214.171.124"
push "dhcp-option DNS 184.108.40.206"
keepalive 10 120
comp-lzo
user nobody
group nobody
persist-key
persist-tun
status openvpn-status.log
log openvpn.log
log-append openvpn.log
verb 3

ifconfig client:
tun0: flags=8851<UP,POINTOPOINT,RUNNING,SIMPLEX,MULTICAST> mtu 1500
inet 172.30.90.6 --> 172.30.90.5 netmask 0xffffffff
open (pid 42823)

iptables rules on the server:
iptables -L
Chain INPUT (policy ACCEPT)
target prot opt source destination
ACCEPT all -- anywhere anywhere state RELATED,ESTABLISHED
ACCEPT icmp -- anywhere anywhere
ACCEPT all -- anywhere anywhere
ACCEPT tcp -- anywhere anywhere state NEW tcp dpt:ssh
ACCEPT udp -- anywhere anywhere state NEW udp dpt:openvpn
REJECT all -- anywhere anywhere reject-with icmp-host-prohibited

Chain FORWARD (policy ACCEPT)
target prot opt source destination
REJECT all -- anywhere anywhere reject-with icmp-host-prohibited

Chain OUTPUT (policy ACCEPT)
target prot opt source destination

I want to route the whole traffic over the VPN. I already added redirect-gateway, so it should work. I really can't see what's wrong here and I hope that you can help me to fix the issue.
Answer: After connecting to the VPN, run the command route -n or netstat -rn on the client and see if the gateway address is assigned.
Check if you've done the following:
On the server:
push gateway to client:
Add this to file: /etc/openvpn/server.conf
push "redirect-gateway def1"

Add this to file: /etc/sysctl.conf
net.ipv4.ip_forward=1

Or issue the following command to set this variable for the current session:
echo 1 > /proc/sys/net/ipv4/ip_forward

Issue the following commands to configure iptables to properly forward traffic through the VPN:
iptables -A FORWARD -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -A FORWARD -s [vpn client subnet] -j ACCEPT
iptables -A FORWARD -j REJECT
iptables -t nat -A POSTROUTING -s [vpn client subnet] -o eth0 -j MASQUERADE

Source
Answer: Try removing:
redirect-gateway

in the client configuration.
You are already pushing the redirect-gateway configuration via the push mechanism of the server and only in that case you are sending it with the correct parameter (def1).
The behavior of redirect-gateway without parameter is openvpn-version-dependent (and you did not specify your specific version) so better be on the safe side.
If this does not help, I see different possible problems.
I suggest the following troubleshoot:

check that you can ping the other side of the tunnel
if yes, try adding manually the default gateway pointing to the remote side of the tunnel and try pinging 184.108.40.206 (to remove a possible problem in the DNS you are pushing through the tunnel)
if that does not work, your problem is likely in the nat configuration (you did not post the result of iptables -L -t nat) or in the forwarding configuration
if that works, but pinging www.google.com does not work your problem is likely in the DNS configuration


Is the Likelihood Ratio test using cluster robust standard errors fixable by Bootstrap (or someting else)?

Question: There is a common agreement about the invalidity of using likelihood ratio tests when computing Maximum Likelihood Estimates (MLE) using clustered corrected standard errors. The main argument is that observations are no longer independent; hence, is it not a proper likelihood. The same argument goes when using weights in the estimation. However, I haven't happened to find any paper discussing said issues or offering corrected asymptotic distributions.
For instance, the official Stata's FAQ offers the following.

The "likelihood" for pweighted or clustered MLEs is not a true likelihood; i.e., it is NOT the distribution of the sample. When there is clustering, individual observations are no longer independent, and the "likelihood" does not reflect this. Where there are pweights, the "likelihood" does not fully account for the "randomness" of the weighted sampling.
The "likelihood" for pweighted or clustered MLEs is used only for the computation of the point estimates and should not be used for variance estimation using standard formulas. Thus the standard likelihood-ratio test should NOT be used after estimating pweighted or clustered MLEs. Instead of likelihood-ratio tests (the lrtest command), Wald tests (the test command) should be used.

They conclude by referring to a possible Bonferroni correction when using Wald tests. However, I am still wondering if the conventional likelihood ratio test is still ''salvable'' by, for example, adjusting the asymptotic distribution or using some sort of Bootstrap procedure. Finally, as far as I understand the problem, the issue is with the asymptotic distribution not being $\chi^{2}$.
Answer: Everything works better when you specify a full model that leads to a full likelihood.  If you have exchangeability, add random effects.  If you have serial correlation, use a serial correlation structure through the use of a Markov model or generalized least squares.  Advantages of full models include

statistical efficiency
better fit
more accurate confidence intervals
ability to handle wildly varying cluster sizes

The cluster bootstrap is an approximate method that can yield disappointing confidence interval coverage and will not handle large clusters or varying cluster sizes well.
Answer: I believe you are correct.  If we could derive the full and complete likelihood with correlated data we could construct a proper likelihood ratio test statistic.  The Wald test can be viewed as an approximation to the likelihood ratio test [1] (both are functions of the parameter estimator) and the Wald test can easily incorporate covariance terms for correlated data.
The standard issue likelihood ratio test statistic is constructed under an independence correlation structure but if the data are correlated the statistic won't follow the usual asymptotic chi-square distribution.    You could absolutely bootstrap the sampling distribution of the standard issue likelihood ratio test statistic to estimate its sampling distribution and standard error, but this is computationally more expensive than the Wald test and may not add much value.


Show that a space X is homeomorphic to the space of multiplicative linear functionals

Question: Let $\mathcal{A}=C(X,\mathbb{R})$ where $X$ is a compact Hausdorff space. Let $\hat{\mathcal{A}}$ be equal to the set of multiplicative linear functionals from $\mathcal{A}$ to $\mathbb{R}$.
STATEMENT: Let $f\in\mathcal{A}$ and let $\hat{f}$ be the function from $\hat{\mathcal{A}}$ to $\mathbb{R}$ defined by $\hat{f}(\phi)=\phi(f)$. Put on $\hat{\mathcal{A}}$ the initial topology from the collection of all the functions $\hat{f}$ for $f\in\mathcal{A}$.  Prove that the map $x\mapsto \phi_x$ is a homeomorphism from $X$ onto $\hat{\mathcal{A}}$.
QUESTION: I have already shown that the given map is bijective and continuous, but I do not know how to show that the map is open. Any hints?
Answer: I'm assuming that $\varphi_x$ is evaluation at $x$. Instead of just giving the argument or a hint, I'll show how I actually worked my way to the argument.
Let $U$ be a non-empty open subset of $X$, and let $\Phi=\{\varphi_x:x\in U\}$; we want to show that $\Phi$ is open. You already know that the map is bijective, so any point of $\Phi$ is $\varphi_x$ for some $x\in U$. Fix $x\in U$; we want to find a finite $\{f_1,\ldots,f_n\}\subseteq\mathscr{A}$ and open sets $V_1,\ldots,V_n$ in $\Bbb R$ such that $\varphi_x\in\bigcap_{k=1}^n(\hat f_k)^{-1}[V_k]\subseteq\Phi$.
Now $\varphi_x\in(\hat f_k)^{-1}[V_k]$ iff $f_k(x)=\varphi_x(f_k)=\hat f_k(\varphi_x)\in V_k$, so we need only take $V_k$ to be an open nbhd of $f_k(x)$ for $k=1,\ldots,n$ in order to ensure that $\varphi_x\in\bigcap_{k=1}^n(\hat f_k)^{-1}[V_k]$.
For $y\in X$ we have $\varphi_y\in(\hat f_k)^{-1}[V_k]$ iff $f_k(y)\in V_k$, so $\bigcap_{k=1}^n(\hat f_k)^{-1}[V_k]\subseteq\Phi$ iff $\bigcap_{k=1}^nf_k^{-1}[V_k]\subseteq U$. Thus, it only remains to show that there are a finite $\{f_1,\ldots,f_n\}\subseteq\mathscr{A}$ and open nbhds $V_k$ of $f_k(x)$ for $k=1,\ldots,n$ such that $\bigcap_{k=1}^nf_k^{-1}[V_k]\subseteq U$.
In fact we require only one function: $X$, being compact Hausdorff, is Tikhonov, so there is an $f\in\mathscr{A}$ such that $f(x)=0$, and $f(x)=1$ for all $y\in X\setminus U$, and I expect that you can finish it off from here.


How to move a ImageButton dynamically?

Question: I'm new to Android
I need to move the ImageButton dynamically, Like when i click the button it needs to be relocated into a new position. Im using AbsoluteLayout.
Answer: Never ever use AbsoluteLayouts. Use animations instead. imageView.startAnimation(ANIMATION); You can find examples from google here and here
Comment: Hey, I was wondering, how can I make the image button move around so that it looks as if it's vibrating? For example, the way Apple apps move when you hold them down to delete them? I have been searching this for a few hours with no luck, I really appreciate your help!

How to move a ImageButton dynamically?


Erro ao trazer Hora e Data

Question: Estou cadastrando no banco de dados MySQL valores como a hora e data.
Código JAVA:
public String getDataPedido() {

    StringBuilder horaSistema = new StringBuilder();

    GregorianCalendar pegarHora = new GregorianCalendar();
    horaSistema.append(pegarHora.get(GregorianCalendar.HOUR_OF_DAY));
    horaSistema.append(":");
    horaSistema.append(pegarHora.get(GregorianCalendar.MINUTE));
    horaSistema.append(":");
    horaSistema.append(pegarHora.get(GregorianCalendar.SECOND));
    return horaSistema.toString();
}

public void setDataPedido(String dataPedido) {
    this.dataPedido = dataPedido;
}

public String getHoraPedido() {
    StringBuilder mesString = new StringBuilder();

    GregorianCalendar pegarMes = new GregorianCalendar();
    mesString.append(pegarMes.get(GregorianCalendar.MONTH));
    mesString.append("/");
    mesString.append(pegarMes.get(GregorianCalendar.DAY_OF_MONTH));
    mesString.append("/");
    mesString.append(pegarMes.get(GregorianCalendar.YEAR));

    return mesString.toString();
}

public void setHoraPedido(String horaPedido) {
    this.horaPedido = horaPedido;
}

Ele insere a hora e data corretamente, mas quando eu dou um SELECT ele não traz a hora registrada no banco e sim a hora atual.
Meu select ficou assim:
public List<ClubeDoDvdPedidoEmprestimo> selicionarPedidosDeEmprestimo(ClubeDoDvdPedidoEmprestimo clube) throws SQLException{
    StringBuilder sql = new StringBuilder();
    sql.append("SELECT codemprestimo, dataemprestimo, horaemprestimo, codigo_socio_solicitou_emprestimo, dvd_codigo, socio_codigo ");
    sql.append("FROM solicitacaoemprestimo ");
    sql.append("WHERE socio_codigo = ? ");
    sql.append("ORDER BY dataemprestimo ASC, horaemprestimo ASC ");

    Connection conexao = FabricaDeConexao.conectar();

    PreparedStatement comando = conexao.prepareStatement(sql.toString());
    comando.setLong(1, clube.getSocio().getCodigo());

    ResultSet resultado = comando.executeQuery();

    List<ClubeDoDvdPedidoEmprestimo> retorno = new ArrayList<>();

    while(resultado.next()){

      final ClubeDoDvdPedidoEmprestimo cdpe = new ClubeDoDvdPedidoEmprestimo();
      cdpe.setCodEmprestimo((resultado.getLong("codemprestimo")));
      cdpe.setDataPedido(resultado.getString("dataemprestimo"));
      cdpe.setHoraPedido(resultado.getString("horaemprestimo"));

      cdpe.setCodigoSocioSolicitouEmprestimo(resultado.getLong("codigo_socio_solicitou_emprestimo"));

      retorno.add(cdpe);
    }
    return retorno;
 }

E assim:
public void listarSocilitacoesEmprestimo(){
    AdicionarSocioVisao e = new AdicionarSocioVisao();
    e.solicitarCodigoUsuario();

    ClubeDoDvdPedidoEmprestimo find = new ClubeDoDvdPedidoEmprestimo();
    find.setSocio(e);

    try {
        SolicitarEmprestimoDAO dsdao = new SolicitarEmprestimoDAO();
        List<ClubeDoDvdPedidoEmprestimo> resultado = dsdao.selicionarPedidosDeEmprestimo(find);
        for(ClubeDoDvdPedidoEmprestimo d: resultado){
            System.out.println("Código Dvd: "+d.getCodEmprestimo());
            System.out.println("Data Pedido: "+d.getDataPedido());
            System.out.println("Hora Pedido: "+d.getHoraPedido());
            System.out.println("Código do sócio solicitou emprestimo: "+d.getCodigoSocioSolicitouEmprestimo());
            System.out.println("");
        }
    } catch (SQLException e1) {
         // TODO Auto-generated catch block
         e1.printStackTrace();
    }
}

Só que a hora está vindo atual ou seja o que eu registrei a dois dias atrás esta vindo com a data e hora atual.
Alguém pode me dar uma mão para resolver esse problema?
Answer: As suas funções getDataPedido e getHoraPedido não usam os campos this.dataPedido e this.horaPedido; portanto, elas não podem retornar o valor que você gravou. Essas funções retornam a hora atual porque o GregorianCalendar funciona usando a hora atual.
De qualquer forma, eu suponho que no futuro você vai precisar calcular os períodos de tempo decorridos entre o empréstimo e a devolução, certo? Neste caso, você deveria estar usando uma classe como a LocalDateTime, e não uma string, para armazenar essas informações: ela já vem com um método minus (pra calcular diferenças temporais).
Comment: Continua trazendo a data atual...
Comment: Pode postar a alteração que você fez nas `get*Pedido`?
Comment: Se você não quer a data atual, você tem que parar de puxar a data atual — a função vai ser simplesmente `public String getDataPedido() { return this.dataPedido; }`.
Comment: Caramba cara, quando eu acho que estou aprendendo eu levo um chute nas canelas... É isso mesmo que você disse, deu certinho... Obrigado...
Comment: Então precisei criar mais dois metodo... esta aqui eles:
Answer: Então precisei criar mais dois métodos, estão aqui eles, agora funcionou:
public String solicitarDataPedido(){
    LocalDateTime pegarData = LocalDateTime.now();
    LocalDate dataAtual = pegarData.toLocalDate();

    return dataPedido = dataAtual.toString();
}

public String solicitarHoraPedido(){
    LocalDateTime pegarData = LocalDateTime.now();
    LocalDate dataAtual = pegarData.toLocalDate();
    return horaPedido = dataAtual.toString();
}

Erro ao trazer Hora e Data


What is the name of this chord? D Eb A

Question: I'm writing a song with some pretty funky chords. I am unsure what to call one of them.
The notes are D Eb and A. D is the root of the chord. It is like a Dsus2, except the 2 is flat. Would that be a Dsusb2? For context, this section of the song is in C minor, and the harmony is alternating between Cm and this chord.
EDIT: After taking a closer look at the piece, I think saying it is in C minor is not specific enough, as it is following the Bb major scale, but the root is C, so I believe that would make it C Dorian. So the chord I am trying to analyze is just the ii chord in the Dorian mode, but with a minor second instead of a minor third.
Comment: Just to confirm, is the A flat or natural?
Comment: How are you actually voicing this, on what instrument?
Comment: @MichaelCurtis it is an A natural.
Comment: @Tim it is a solo piano piece
Answer: If it's alternating between Cm and this harmony, I'd say this is an instance where naming the chord is less important than acknowledging the voice leading:
E♭–––––
G––A––G
C––D––C

Note that the E♭ stays constant while the perfect fifth C–G moves up to D–A and back; I think this, rather than labeling that middle chord, is a better way of conceptualizing this harmony.

Edit: But if you really want to name the chord, I think Dsus♭2 will get the point across well. sus♭2 replaces the chordal third with E♭, while the D tells us to include the D–A perfect fifth.
At least one website uses this nomenclature; here they show you an E♭sus♭2 chord, which is your exact harmony, just transposed up a minor second.
Comment: @MarcksThomas: The answer here is that the question was an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem).  The question written was "What is the name of this chord?", but the real question the OP probably needed answered was "How should I notate/describe/analyse this chord?", and this answer answers that real question.
Comment: See edit; `Dsus♭2` might be the most succinct way of labeling this chord.
Comment: This is so much more straight forward than a strange, rootless inversion like F7/D. It's just an embellished c minor chord.
Comment: I didn't downvote, because I agree this is a useful explanation, perhaps more so than F7/D (though it's hard to say without more context), but it is somewhat of a non-answer. _"What is the name of this chord?"_ - _"Not important."_
Comment: Thanks for pointing out the shifting fifths, that is a useful way for me to think about this.  But thinking of it as some sort of embellished C minor still feels unsatisfactory because you can definitely feel the shift from C minor to the D "minor." It functions as a D minor chord, but it has a minor second instead of a minor third.
Answer: There are a few ways you could think of this, depending how the chord functions in your song.
It could be an Eb dim maj7, which is one of my favorite chords... not very justifiable unless you are working that Eb in the bass. It is very striking when played that way.
You could call it an 0,1,6, a favorite trichord of Anton Webern, one of the big names in serial music.  That's sort of a stretch though.
It could be a Viennese trichord which has dominant function. Does your band wear powdered wigs?
Most likely is that is is operating as a Cm69 chord, which is pretty common, but in your case without the C note.  This interpretation would be more justifiable if your song has a strong sense of C pedal point.  The A and the D operate as neighbor notes in a common tone chord.  This creates a sort of continuous, monolithic sort of progression that feels like a wall of sound shifting restlessly between consonance and dissonance.
Answer: My inclination would be to think of this as a rootless F7/D. Since it has the third and seventh of the F7 it should be functionally equivalent, and alternating with the cmin would give you a funky dorian vamp. This really doesn't fit into traditional harmony so there could multiple interpretations, but the tritone suggests a dominant. Dsusb9 is also a possibility, which some in the jazz community use to imply various phrygian mode derived chord voicing and can subdtitute for a minor ii-V, but I think the argument for the F7/D is stronger.
Answer: Based on your description, this chord almost definitely should be labeled Cmin6 or Cmin6/9 if you want to provide more specificity.
You can probably find this exact chord voicing in either The Jazz Piano Book or The Jazz Theory Book, both by Mark Levin. In solo piano, it's expected that some/most chord voicings will omit the root, particularly in a section of a piece where the chords are not changing quickly or are not changing at all. Playing the root on every note would sound odd and would not allow room for playing the chords with more complex rhythms. In a band setting, it's very intuitive that we shouldn't stipulate the constraint that the harmony must always be played in rhythm with the bass. For example, in a jazz quartet with piano, bass, drums, and saxophone, we wouldn't expect the bassist to play the root note every single time the pianist plays a rootless chord when comping. (If you were to pick up any jazz album put out in 1990 or later that features a piano-bass-drums rhythm section and transcribe the pianist's chords when he/she is comping, I bet at least 50% of those chords are rootless.) In solo piano, both of these functions--bass and harmony--are performed on one instrument instead of being split across two instruments. And just like the band setting, we likewise wouldn't want to constrain the solo pianist by requiring that every chord he/she plays be accompanied by a bass note. So when you look at the D Eb A voicing, what was the most recent bass note played in the bass register? C. That's still the bass note for this D Eb A chord. What you have here is an extremely common progression (Cmin - Cmin6 - Cmin - Cmin6) which switches between the fifth and the natural sixth. It's a really nice sound.
I highly doubt the chord is D sus ♭2. If a sus ♭2 chord exists at all, then it's extremely rare, and I wouldn't expect a song to use such an uncommon/nonexistent chord without also establishing a D in the bass register. (It sounds like the piece does not play a D in the bass register.)
If you don't want to label the chord, you could instead show the voice leading alternates between G and A, as another answer states. But if you're looking for a name with which to label this chord, I would use either Cmin6 or Cmin6/9. It's not going to be the exact 1-3-5-6-9 chord you see on Wikipedia, but it is still a common way to voice Cmin6/9 (i.e., without the 5th or the root).
Comment: The song is for solo piano, and the bass does also alternate between the C and the D. So when the "D chord" is played, there is no C being voiced anywhere. Later on in the song, this bizarre "D chord" we are discussing actually becomes clarified to a D major chord (still with the flat 2 in it however), so I really want to call it some sort of D chord.
Comment: Can you share a recording or a title of the song?
Answer: Consider the main key is Cminor. This means that your scale is C D Eb F G Ab Bb. Placing the chord D Eb A on this means: D is the unchanged root, the Eb is the diatonic second and the A is the usual (although non-diatonic) fifth. Putting this in notation, it is a Dsusb2.
When reading it back it means: take D as root plus the usual pure fifth and add a suspended minor second instead of the thirdto it.
Comment: Although the A is just a perfect fifth above D, not an augmented fifth, no?
Comment: Yes, of course you're right. I should think first and then type. I confused the A being non-diatonic with being a perfect fifth. My bad.
Comment: These things happen, no worries :-) Welcome to Music.SE!
Answer: In context, we might be able to analyse the tensions and resolutions created by those notes.  But there's probably no point in calling it anything, use notation.  There's no virtue in abusing the system of chord symbols to accommodate it.  A chord symbol should be an EASIER way of describing a chord!

What is the name of this chord? D Eb A


How can I ensure that every page within my drupal 6 site loads a specific Javascript file?

Question: I want to include the sites/all/themes/fusion/mapsindeed/js/css3-mediaqueries.js
 file so that mediaqueries will work within Internet Explorer 8 and below, like it already does for other web browsers.
How can I do it?
Answer: Add the URL of the JavaScript file as scripts[] to the theme's info file.


How to translate my drupal site in other language.

Question: My drupal site is in default English language and I have added Spanish and German languages using Internationalization and Locale Modules. When I switch to other language using Language Switcher block placed in header of my site, It translated Drupal Interface like admin menu and other core displays, but does not translate nodes or module pages which I have added. I have used t() function to display page contents or titles and its not translating them using t function.
The code for the page which I have added is as:
function MY_MODULE_menu() {
     $items['fee/per'] = array(
    'title callback' => 'attendance_og_get_title',
    'title arguments' => array('calendar'),
    'description' => t('Shows attendance percentage recorded per day for a group in a calendar.'),
    'page callback' => 'attendance_og_calendar_page',
    'file' => 'fee_management.pages.inc'
  );

    return $items;
}

function attendance_og_get_title($c) {
    return t('!entity_type Attendance Report (Aggregated)',  array('!entity_type' => ucfirst('Some Name ' . $c)));
}

File fee_managemen.pages.inc.
 function attendance_og_calendar_page($entity_type, $etid) {
       return array(
        '#prefix' => '
' .
        t('This view shows the percentage attendance recorded per attendance day in this group. An attendance day is a calendar day in which attendance was taken.') . '
',
        '#markup' => '
' . t('Loading.. I am loading here') . '

',
      );
}

Please help me to get this working.
Answer: As your module is not hosted on drupal.org, the strings it uses are not available on localize.drupal.org, where they can be translated in any language available there.
As such, you need to enable the Locale module, and translate the strings on your site.
With Drupal 7, you visit the page at admin/config/regional/translate/translate, and you get a list of untranslated strings you can translate.

In Drupal 6, a similar page is available on admin/build/translate/search.
Answer: Go to Language and Translation configuration , select the language and check all un translated strings , you will get all the text written in t("here"), then save the translations of each word and string . This is how it will work :)
Thanks


Is 48 polyphony in a digital piano enough for playing most classical music pieces?

Question: I have bought a CASIO CDP-130 digital piano - unfortunately it has only 48 polyphony. I only love classical music and that´s what I want to play. Will it be enough for playing most classical pieces as piano solo?
Comment: The proposed duplicate directly addresses the CDP-130 is [this answer](https://music.stackexchange.com/a/53200/70803), which includes example videos.
Answer: Yes.  A full-range arpeggio flourish with sustain pedal might run out of notes, but I don't think you'll find it a practical limitation.
Incidentally, be wary of polyphony numbers on electric keyboards.  48-polyphony might mean only 24 notes if a layered sound - piano/strings maybe - is selected.  Your CDP-130 can do this.  But I think you can expect 48 notes on a plain piano sound.
I investigated the new range of Casio pianos recently, in a search for something lighter to carry than my Kurzweil PC3X. (You just DON'T take your car to a central London gig any more, I need something I can carry on my back.)    I was most impressed by them, particularly considering Casio's previous reputation for being cheap-and-nasty and the low price.
Comment: St John's Wood is pretty good for parking after 6:30 pm . Did a couple of night shoots out of there last week, base right next to Lords, shoot in Marylebone… though I wouldn't have wanted to walk between the two with a piano on my back ;)) Might be worth a look at a black cab from/to there though, save worrying about getting home on the tube at midnight or after.
Comment: @tetsujin A book, a book!!! ;)


$X\times Y$ is a banach space. What can you say about $X$ and $Y$?

Question: $X\times Y$ denotes the cartesian product of $X$ and $Y$. $X\times Y$ is a Banach space with respect to the norm
$$||(x,y)||:=  (||x||^p + ||y||^p)^{\frac 1p}.$$
What can I say about $X$ and $Y$ where they are normed linear space ? Are they Banach spaces?
Comment: As far as I understand, you assume that $X$ and $Y$ are normed spaces (since you use the notations $\text{Norm}_X$...), and your question is, if $X$ and $Y$ are complete, assuming that $X\times Y$ is complete. That's true, of course, since if $x_i$ and $y_i$ are Cauchy sequences in $X$ and $Y$, then the convergence $(x_i,y_i)\to (x,y)$ in $X\times Y$ means exactly that $x_i\to x$ in $X$ and $y_i\to y$ in $Y$.
Answer: $X$ and $Y$ are isometric to closed subsets of $X\times Y$ via the maps $$x\mapsto (x,0),\qquad y\mapsto (y,0)$$
Draw your conclusion about their completeness.


Merge two pngs via command line tool in windows?

Question: I'm looking for a tool I can use via command line (windows 7) to merge two equally sized pngs.  I'm not having much luck with search so far as most tools I've seen are pretty heavy applications which don't seem to target simple manipulations.
I want to overwrite the bits in the opaque base image with the non-transparent pixels in the overlay image.  I have photoshop CS4 as well, but haven't had much luck in finding the relevant command line arguments.
Answer: ImageMagick has a command line tool called composite which will do what you want. Distributions available for Windows, Mac, Linux etc. I've just tested it with two transparent PNGs and works as expected.
<code>composite foreground.png background.png newimage.png
</code>
Comment: Coincidentally (or maybe it's the only one that rises to the top) I was looking at ImageMagick. I'm in the middle separating my layers and getting everything ready for the trial run.  +1 for verifying, thanks.


AWS Lambda - how to handle errors on asynchronous (AWS S3) triggers?

Question: I have an AWS Lambda function that converts an html document to a pdf document whenever a new document is uploaded to S3. Working great.
Once the pdf has been generated, my application code (which is a traditional server backed web service) needs to send an email to the user with a link to the pdf file. I can think of a few ways to handle this:

Just assume the pdf conversion worked and trigger the email naively
Send a webhook from the lambda function to my application code when the conversion happens
In the background job check for the existence of the pdf before sending the email

In reality all of these will work, but I am curious if there is a suggested 'best practice' for handling AWS lambdas that are triggered asynchronously like this, rather then being directly triggered.
Comment: Step Functions is one approach: https://aws.amazon.com/step-functions/
Comment: Your lambda function could invoke a backend rest api call with file path details once s3 upload is done.
Answer: Take a look at Lambda Dead Letter Queues.
Dead Letter Queues

By default, a failed Lambda function invoked asynchronously is retried
  twice, and then the event is discarded. Using Dead Letter Queues
  (DLQ), you can indicate to Lambda that unprocessed events should be
  sent to an Amazon SQS queue or Amazon SNS topic instead, where you can
  take further action.
You configure a DLQ by specifying a target Amazon Resource Name (ARN)
  on a Lambda function's DeadLetterConfig parameter of an Amazon SNS
  topic or an Amazon SQS queue where you want the event payload
  delivered, as shown in the following code. For more information about
  creating an Amazon SNS topic, see Create an SNS Topic. For more
  information about creating an Amazon SQS queue, see Tutorial: Creating
  an Amazon SQS Queue.