Como acessar parametro de classe Python

Question: Bom dia amigos,
Estou fazendo uma script para uma GUI com o Tkinter para um projeto de gerador de senha. Criei inicialmente duas classe: uma que cria o container principal (myApp) e outra que cria o primeiro Frame da tela (Frame1). Agora precisa criar uma segundo Frame (Frame2) logo abaixo do top porém preciso acessar um parametro da classe Frame1 dentro da classe Frame2 e não estou conseguindo fazer.
from tkinter import *
from geradorSenha import *

class Frame1(LabelFrame):
    def __init__(self, container):
        super().__init__(container)
        self.config(text="Escolha seu tipo de senha", width=400,
                    height=100)
        self.columnconfigure(0, minsize=400)
        self.grid(row=0, padx=10)

        self.var = IntVar()

        self.Rb1 = Radiobutton(self, text="Somente letras",
                               variable=self.var, value=1)
        self.Rb1.grid(column=0, row=0, sticky=W)

        self.Rb2 = Radiobutton(self, text="Somente números",
                               variable=self.var, value=2)
        self.Rb2.grid(column=0, row=1, sticky=W)

        self.Rb3 = Radiobutton(self, text="Letras mais números",
                               variable=self.var, value=3)
        self.Rb3.grid(column=0, row=2, sticky=W)

        self.Rb4 = Radiobutton(self, text="Letras mais caracteres especiais",
                               variable=self.var, value=4)
        self.Rb4.grid(column=0, row=3, sticky=W)

        self.Rb5 = Radiobutton(self, text="Letras, caracteres especiais e números",
                               variable=self.var, value=5)
        self.Rb5.grid(column=0, row=4, sticky=W)

        self.escolha_button = Button(self, text='Escolha')
        self.escolha_button.grid(column=0, row=5, pady=5)
        self.escolha_button.config(command=self.escolha)

    def escolha(self):
        return self.var.get()

class Frame2(LabelFrame):
    def __init__(self, container):
        super().__init__(container)
        self.config(text="Frame 2", width=200,
                    height=100)
        self.columnconfigure(1, minsize=200)
        self.etiqueta = Label(self, text=Frame1.escolha) #QUERO PEGAR O PARAMETRO DA CLASSE FRAME1 AQUI
        self.etiqueta.grid(column=0, row=1)
        self.grid(row=1)

class myApp(Tk):
    def __init__(self):
        super().__init__()
        self.title("Gerador de Senhas")
        self.geometry("420x400")

myGui = myApp()
frame1 = Frame1(myGui)
frame2 = Frame2(myGui)
myGui.mainloop()

Answer: Você tem duas classes Frame1 e Frame2, se você deseja acessar um parâmetro do Frame1 dentro do Frame2, nesse caso do teu código é necessário passar no momento da criação do Frame2, exemplo:
Primeiro você define que a Classe Frame2 vai receber um novo parâmetro, nesse caso com nome parametro_que_voce_deseja.
class Frame2(LabelFrame):
    def __init__(self, container, parametro_que_voce_deseja):
        super().__init__(container)
        self.parametro_que_voce_deseja = parametro_que_voce_deseja
        # Resto do código aqui

No momento da criação do Frame2, você passa o parametro_que_voce_deseja (do Frame1) para dentro de Frame2.
myGui = myApp()
frame1 = Frame1(myGui)
frame2 = Frame2(myGui, frame1.parametro_que_voce_deseja)
myGui.mainloop()

Como acessar parametro de classe Python


Please explain the bars

Question: I was trying to play a piece of music on my keyboard when I got stuck at this bar no.17 (Please refer to the pic below).
Can someone please explain how do a rest symbol and a whole note appear one upon another? How to play these two bars?
Thanks a lot.
Answer: bar 17: Hold the A down with your pinky for the entire duration of the bar, while playing the melody with your other four fingers (ref. the fingerings on your score)
bar 18: Release your pinky as you play the F# with probably your middle finger. Then jump to a higher position to play the rest.
This is a simple example of two voices in one hand, which is abundant in piano repertoire.
Answer: Think of it as two instruments.  One has the whole note, the other has the rest and the 8ths.
Answer: If you consider the stem directions pointing up for one voice and those pointing down for another voice, you will see it's two voices on one stave. You could show it on two staves like this...

Notating it on one staff basically means play it with one hand unless other markings tell to use two hands.
Now, notice the fingering numbers on the two parts. The 5 above the A means play it with your pinky. While you hold that for four beats you use fingers 1 2 3 - thumb, index, middle - to play the other part, notes D E F#.
So, you sort of split the fingers of your hand into two groups and working them separately. In this case the top group is just 5 and the bottom group is 1 2 3. The fingers could be split up into different groupings depending on the particular passage.
If this is new to you, try looking up "five finger exercises." That's a common keyboard method. You want to find the type that have some fingers stay down while the others move, in one hand. Finger independence is the goal of the practice.
The passage you gave just happens to fit into a five finger position - five adjacent steps of a scale - but this kind of two part texture could happen with larger intervals like a sixth or octave. Starting practice with the smaller five finger position would be normal.

Please explain the bars


Aspherical homology class

Question: I am completely stuck on the following algebraic topology exercise:
Let $X$ and $Y$ be CW complexes and $\alpha \in H_p(X)$, $\beta \in H_q(Y)$, $p, q > 0$, homology classes such that the homology cross product $\alpha \times \beta \neq 0$ in $H_{p+q}(X \times Y).$ Show that $\alpha \times \beta$ is aspherical, i.e. there is no map $\phi \colon S^{p+q} \to X \times Y$ such that $\phi_*[S^{p+q}] = \alpha \times \beta$, where $[S^{p+q}]$ denotes the fundamental class of $S^{p+q}$.
I am quite sure that the Hurewicz theorem will play a prominent rule in the solution, but I just don't see how.
Maybe it could be useful to play around with the definition of the cellular homology of $X$ and $Y$, since it involves maps from disks and spheres to $X$ and $Y$, but again I don't see how this might actually lead to a solution.
(The exercise is taken from the book Stöcker/Zieschang - Algebraische Topologie and is not a homework problem.)
Answer: I don't see how to use Hurewicz's theorem since we don't know anything about lower-dimensional classes.  I would try to use the product structure in cohomology, e.g. if $a$ is a cohomology class dual to $\alpha$ and $b$ is a cohomology class dual to $\beta$ then $a\cup b$ will be a nonzero class.  If it pairs nontrivially with a homology class represented by a sphere $S^{p+q}$ then you can pull back the classes $a$ and $b$ to the sphere and get nontrivial (co)homology classes there that are "forced" on you by the naturality of the cup product, yielding a contradiction.  The technical details may not work out exactly as I stated but I am confident this direction has a better chance of succeeding than Hurewicz.
Comment: Sorry, but I don't understand the details of your solution. I would be very glad, if you could try to give a more in-depth account of your argument.
Comment: The idea is to exhibit a $p+q$-dimensional cohomology class in $X\times Y$ which is a cup product of cohomology classes of dimensions $p$ and $q$.  Since the product structure in cohomology is natural with respect to pullback of maps, the sphere $S^{p+q}$ would also inherit such a product decomposition for the pullback class, which is impossible.

Aspherical homology class


Two Quadratic Equation having real roots

Question: Let $x^2 + 2ax + b = 0$ and $x^2 + 2bx + a = 0$ have real roots $(a,b > 0)$, then minimum possible integral value of ab is___________
My approach is as follow
$T(x)=x^2 + 2ax + b = 0$, hence $4a^2-4b\ge 0$
$U(x)=x^2 + 2bx + a = 0$, hence $4b^2-4a\ge 0$
How do we approach from here
Comment: Alternative approach to the answer of b00n heT.  Since $a,b > 0$, you have that $(ab) > 0 \implies (ab) \geq 1$, since the question calls for an integral value for $(ab)$.  So, all that is necessary is to *manually* check whether $(a=1,b=1)$ satisfies the constraints.
Comment: In fact $a \leq b^2, b \leq a^2$ and multiplying LHS and RHS, $ab \leq a^2b^2 \implies ab \geq 1$ as $ab \ne 0$
Comment: I'm sorry, but not simplifying $4a^2-4b \ge 0$ to $a^2>b$, or at least to $a^2-b \ge 0$ makes you look lazy.
Answer: Notice that the two inequalities can be rewritten as
$$\begin{cases}a^2\geq b\\
b^2\geq a
\end{cases}$$
and since both $a,b>0$ and $\sqrt{\cdot}$ is increasing we can take roots and obtain the inequality
$$a^2\geq b\geq \sqrt{a}$$
Now
$$a^2\geq \sqrt{a}\iff a\geq 1,$$
($a=0$ is excluded by assumtion) and by a simmetric argument for $b$ we get $b\geq 1$.
In conclusion the minimal value for  $a\cdot b$ is for $a=1=b$ and is $1$.
Comment: sorry, it is my misunderstanding
Comment: $\sqrt{\cdot}$ is not always increasing
Comment: What do you mean? Maybe my notation is misleading: I am saying that you can apply the square root to an inequality as it is an increasing function, I am not saying that $\sqrt{f(x)}$ is increasing in general.


Find all solutions to $\frac{a+b}{b} = \frac{a}{a+b}$

Question: I want to find all solutions to $\frac{a+b}{b} = \frac{a}{a+b}$. I have plugged this into a calculator which tells us that if we solve for $a$, without loss of generality, we obtain
$$a = - \frac{b}{2} \pm \frac{\sqrt{3}}{2}i$$
and vice versa. I am not sure how to show this, however. I have tried a couple of different things. For example,
Method 1:
$$\frac{a}{a+b} = \frac{a+b}{b} \implies (a+b)^2=ab \implies a+b = \pm \sqrt{ab}$$
Method 2:
$$\frac{a}{a+b} \cdot \frac{a-b}{a-b}= \frac{a+b}{b} \cdot \frac{a-b}{a-b} \implies \frac{a(a-b)}{a^2-b^2}=\frac{a^2-b^2}{b(a-b)} \implies \big( a^2-b^2 \big)^2 = ab(a-b)^2$$
But so far neither of these methods are shedding any light for me. Any advice? Thanks in advance.
Comment: Assuming $ab \ne 0$ let $x=a/b$ and show it satisfies $x^2+x+1=0$
Answer: To begin with, let us assume that $b\neq 0$ and $a\neq -b$.
Now we can multiply both sides by $b(a+b)$ in order to obtain
\begin{align*}
(a + b)^{2} = ab & \Longleftrightarrow a^{2} + 2ab + b^{2} = ab\\\\
& \Longleftrightarrow a^{2} + ab + b^{2} = 0\\\\
& \Longleftrightarrow \left(a + \frac{b}{2}\right)^{2} + \frac{3b^{2}}{4} = 0\\\\
& \Longleftrightarrow \left(a + \frac{b}{2}\right)^{2} = -\frac{3b^{2}}{4}\\\\
& \Longleftrightarrow a + \frac{b}{2} = \pm\frac{bi\sqrt{3}}{2}\\\\
& \Longleftrightarrow a = -\frac{b \pm bi\sqrt{3}}{2}
\end{align*}
Hopefully this helps !
Comment: It helped a lot! Thank you
Answer: You have $(a+b)^2=ab$ or $a^2+ab+b^2=0$. If $a\ne b$, multiply by $(a-b)$, get $a^3-b^3=0$. So $a=b\omega$ where $\omega$ is one of the cube roots of $1$. The possibility $a=b$ does not work, the other two work.
Answer: $b$ is any non-zero number, $a=b\omega$ where $\omega$ is one of the two non-1 cube roots of $1$.
Comment: Your answer is $a=b \omega$? But then $a^3-b^3 = (b\omega)^3-b^3=b^3-b^3=0$, a contradiction, according to your own answer...


Using Grid to layer items over each other

Question: I am using absolute positioning to layer div one, two, three (and cover main). Would it be possible to achieve the same with CSS grid?

div.main is always displayed
div one, two, three will be shown when needed

Update: Toggle button added for better visualisation

const div = document.querySelector('div.content');
document.querySelector('button').addEventListener('click', () => {
  const on = document.querySelector('.on');
  on?.classList.remove('on');
  (on?.nextElementSibling || div.firstElementChild).classList.add('on');
});
* {
  box-sizing: border-box;
}

button {
  padding: 0.5em;
  margin-bottom: 1em;
 }

.content {
  width: 15em;
  height: 8em;
  position: relative;
  margin: 0;
  padding: 0;
  border: 1px solid #aaa;
}

.main {
  height: 100%;
  background: #eee;
  padding: 0.5em;
}

.one,
.two,
.three {
  display: none;
  margin: 0;
  padding: 2em;
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 3;
}

.one.on,
.two.on,
.three.on {
  display: block;
}

.one {
  background: #fef8;
}

.two {
  background: #fec8;
}

.three {
  background: #cdc8;
}
<button>Toggle</button>

This is main

This is one

This is two

This is three

Answer: Assuming that the div just need to stack on each other, perhaps a simple implement would be setting content a grid of a single cell, and have all the div placed in grid-area: 1/1/1/1.
Example: (with a simple display toggle)

const btn = document.querySelector("button");
const divs = document.querySelectorAll("div > div");

let i = 1;

btn.addEventListener("click", () => {
  if (i === 4) {
    divs.forEach((div) => div.classList.remove("on"));
    i = 1;
    return;
  }
  divs[i - 1].classList.toggle("on");
  divs[i].classList.toggle("on");
  i++;
});
.content {
  width: 15em;
  height: 20em;
  margin: 0;
  padding: 0;
  border: 1px solid blue;
  display: grid;
}

.main {
  border: 1px solid red;
  grid-area: 1/1/1/1;
}

.one,
.two,
.three {
  display: none;
  margin: 0;
  padding: 1em;
  z-index: 3;
  border: 1px solid green;
  grid-area: 1/1/1/1;
}

.one.on,
.two.on,
.three.on {
  display: block;
}

button {
 padding: 6px;
 margin-bottom: 1em;
}

.one {
 background-color: rgba(100, 149, 237, 0.25);
}

.two {
background-color: rgba(34, 139, 34, 0.25);
}

.three {
background-color: rgba(255, 140, 0, 0.25);
}
<button>Toggle</button>

This is main

This is one

This is two.

This is three.


Coefficient dependences of cohomology group of spaces

Question: In Hatcher's textbook, the cohomology groups of spaces are defined by the homology of the cochain complex Hom$_R(C_i(X;R),G)$, dual of the original chain complex $C_i(X;R)$ where $R$ is a principal ideal domain and the abelian group $G$ is an $R$-module.
Clearly, we have two coefficient dependences: $G$ and $R$. However, when we write down the notation of the cohomology group, we use
\begin{eqnarray}
H^i(X;G),
\end{eqnarray}
which does not specify the $R$-dependence. In my understanding, $H^i(X;G)$ is used in the case when $R=\mathbb{Z}$, but, later in Hatcher's book, when the coefficient ring $R$ of cochains is different from $\mathbb{Z}$, the notation $H^i(X;G)$ is still used.
My question is whether this notation will bring about any ambiguity. If so, why not specify explicitly the $R$-ring dependence of the chain complex?
Answer: It makes no difference, since the two versions are naturally isomorphic.  Indeed, the version that goes through $R$ is obtained by applying the functor $\operatorname{Hom}_R(R\otimes -,G)$ to the integral chain complex, and the version that does not go through $R$ is obtained by applying the functor $\operatorname{Hom}_{\mathbb{Z}}(-,G)$ to the integral chain complex.  These two functors are naturally isomorphic.  Very explicitly, in the case of (say) singular homology, in both cases an $n$-cochain is just a function from the set of singular $n$-simplices to $G$, since $C_n(X)$ is the $\mathbb{Z}$-module on the set of singular $n$-simplices and $C_n(X;R)$ is the free $R$-module on the set of singular $n$-simplices.
Comment: Thanks for the clear answer! It means, for a fixed $H^i(X,G)$, we can choose various applicable P.I.D. $R$ to get several splitting of it by the universal coefficient theorem.


DNS Records not found for a website

Question: I am running a dedicated server.
The server is running two sites. This morning one website is not working and I found that there is a problem with the dns settings. I don't know how it happened very suddenly.
The other website is working properly.
nslookup @domainname.com

Server:         22.214.171.124
Address:        220.127.116.11#53

** server can't find @domainname.com: NXDOMAIN

I checked online dns tools and they are reporting errors.
nslookup for another site is also not working
But dig for another site is working properly.
dig @domainname.com

dig: couldn't get address for 'domainname.com': not found

and ping is reporting
ping: unknown host domainname.com

dig SOA sitename.com

; <<>> DiG 9.8.2rc1-RedHat-9.8.2-0.17.rc1.el6_4.6 <<>> SOA sitename.com
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NXDOMAIN, id: 25377
;; flags: qr rd ra; QUERY: 1, ANSWER: 0, AUTHORITY: 1, ADDITIONAL: 0

;; QUESTION SECTION:
;sitename.com.              IN      SOA

;; AUTHORITY SECTION:
co.in.                  879     IN      SOA     a0.cctld.afilias-nst.info. noc.afilias-nst.info. 2008728028 600 900 2592000 86400

;; Query time: 53 msec
;; SERVER: 220.127.116.11#53(22.214.171.124)
;; WHEN: Mon Sep 30 17:36:06 2013
;; MSG SIZE  rcvd: 99

cat /etc/resolv.conf

nameserver 126.96.36.199
nameserver 220.127.116.11

I tried one online website for nslookup.
DNS server handling your query: localhost
 DNS server's address:  127.0.0.1#53

 ** server can't find domain.co.in: NXDOMAIN

domain name : justforfun.co.in
Comment: @user192058 - the details of your question are pretty vague and you don't give much to work with here.  Before the question gets closed as "unclear" it would behoove you to include additional details like the actual domain name in question, any changes made recently to its dns zone, etc.
Comment: Adding your actual domain name here is fine by us.  Doing this helps greatly with DNS questions.  If you don't want to do that, you might want to check the status page or the Twitter feed of your DNS provider.  If that's fine, also check if the domain has expired in the last few days.
Comment: Check in your DNS management if that service is up and running.
Comment: So check your DNS settings using the control panel through your host.
Comment: I don't have any control panel
Comment: If you have registered a domain name, you have a control panel.
Comment: I checked that it has the correct name servers
Comment: What does `dig SOA domainname.com` say?
Comment: What is the domain?
Comment: updated the question
Comment: Domain is not expired. I am not using any DNS Provider. Is it really important to share the domain name?
Comment: @user192058 It's really hard to diagnose DNS problems without knowing the domain name. So yes, if you want help, it is kind of important.
Comment: It definitely can be: see http://serverfault.com/questions/485137/lame-dns-server/485148#485148 for an example of where it was absolutely vital.
Comment: I just added my domain name! Thanks for trying to help me
Comment: I tried to add a new domain to the server which is successfully added and working. But this one, which was working properly, is not working.
Comment: What did you change on September 29th (yesterday) in regards to this domain? It seems what ever that change was, caused your name servers to disappear...
Comment: It is not working today. I tried many things still I cant find the problem. But other sites are working. So I recreated the DNS settings.
Answer: http://info.info/index.php?q=faq/7 The whois on your domain returns Status: Hold which likely means that your nameservers are not configured [properly] at the registrar.
Further Investigation reveals the following:
DNS server handling your query: NS2.FUNNY.ORG.IN
 DNS server's address:  184.108.40.206#53

 Name:  JUSTFORFUN.CO.IN
 Address: 18.104.22.168

NS1.FUNNY.ORG.IN does not resolve to an IP address. This is likely why the registrar placed the domain in hold status and refuses to publish it to the zone. Contact the admin responsible for ns1.funny.org.in or switch to a different DNS provider.

Or at least it didn't appear to be resolving ns1.funny.org.in a minute ago..
Comment: http://who.is/whois/justforfun.co.in - The various online whois lookupp providers respond back with the `Status: Hold` line present. If they don't accept that as evidence of an issue and help (or at least explain why it is not an issue), Have them open up the transfer hold on the domain and threaten to move your registration to a new provider.
Comment: How did you get those details? Where can I check them?
Comment: Whois: `http://www.networksolutions.com/whois/results.jsp?domain=justforfun.co.in` && `dig @ns1.funny.org.in justforfun.co.in`
Comment: I would contact the registrar and ask for assistance. It appears that they have put your domain on hold status for one reason or another.
Comment: which registrar? justforfun.co.in?
Comment: how do I prove them it is in the hold status? I already contacted and explained but they didn't accept it.

DNS Records not found for a website


Pandas not working in AWS GLUE 4.0 version

Question: Pandas not working in AWS GLUE 4.0 version:-
I tried importing pandas in AWS Glue 4.0 but getting following error, pandas is working in AWS Glue 3.0 version but not in 4.0.
ModuleNotFoundError: No module named '_bz2'
Comment: Use glue 3 if you can.
Comment: I am using Delta 2.1.0 version with Spark3.3, and this version is supported by Glue 4.0 only.
Answer: I have also encountered this issue and have contacted AWS support about it. It appears that it is an AWS issue and is happening to anyone who uses it. They are currently working on a fix.


Changes to leaflet Settings not working

Question: I am unable to alter a settings of a leaflet map generated by a view using the method described here in a custom module. https://www.drupal.org/node/1883788
Using the code below in my custom module does not work.
  function MYMODULE_leaflet_map_info_alter(&$map_info) {
      $map_info['esri-world-street-map']['settings']['scrollWheelZoom'] = TRUE;
      $map_info['esri-world-topo-map']['settings']['scrollWheelZoom'] = TRUE;
  }

Where MYMODULE is the name of my module.
Someone else had this same issue and we have been talking trying to solve the issue. https://www.drupal.org/node/2831593
Comment: Did you clear cache?
Comment: Yup. Module had been there for a week. Someone else has this same problem too on the forums.
Comment: Could you update your Question with a link to the forum topic?
Comment: Gee that was embarrassing https://www.drupal.org/node/2831593
Comment: Maybe it is a leaflet.markercluster version issue?
Comment: Maybe. I am using the latest version. Ill try an older one...
Comment: I'm voting to close this question as off-topic because it is crossposted as a bug report in the module's issue queue.  DA is not the place for bug reports; issue queues are the proper place and cross-posts are counter-productive.
Comment: Yes but it has gotten responses here and none on the forum. So it is productive because this bounty has gotten it a response while in the forum it was not seen.
Answer: The code shown in your question can never work: you need, at least, change the function name from "MYMODULE_leaflet_map_info_alter" to the actual name of your module.
PS: debugging is the art of taking away all possible reasons why something doesn't work as expected. This is for sure 1 of the possible reasons ...
Comment: Using MYMODULE or MYTHEME in questions and answers here is pretty standard to make something generic.  It's used hundreds, if not, thousands of times in posts on DA.
Comment: i didn't have enough rep to leave a comment :(
Comment: Since you didn't "object" my edit in any way (yet), I assume you're ok with my edit ...
Comment: I changed the hook name to the module, this is just example code.  This is the issue https://www.drupal.org/node/2831593

Changes to leaflet Settings not working


Function notation (domain "maps to" range) for a parameterized function

Question: I have a function $f(x; a)$. Note that $x \in \mathbb{R}$ and $a \in \mathbb{R}$. For simplicity, let's say the function is $f(x; a) = ax$. For my use case, it is more convenient to think about $f$ as a function of $x$ that is parameterized by $a$ (as opposed to a function of $x$ and $a$).
I'd like to express $f$ using the "maps to" function notation. My question is, is it more appropriate to express it as $f : \mathbb{R} \mapsto \mathbb{R}$ or as $f : \mathbb{R^2} \mapsto \mathbb{R}$? I can't find any examples of this notation for a function that also uses "parameterized by" notation.
My guess is the former, as $f$ is viewed as a function of one variable (that just so happens to be parameterized). However, given discussion in Why do we say function "parameterized by" vs just function of (x,y,z,...)?, there is no mathematical difference between writing $f$ as $f(x; a)$ and $f(x, a)$. However, in the latter case one would surely use the function notation $f : \mathbb{R^2} \mapsto \mathbb{R}$. This is the source of my doubt.
Answer: If you want to consider $a$ as a parameter, then you will write that you are using a family of functions $(f_a)_{a\in \mathbb{R}}$ : each one of them are then defined by $f_a(x) = ax$ (so $f_a:\mathbb{R} \mapsto \mathbb{R}$ for each $a\in \mathbb{R}$).
In the other case (two variables) you will indeed write $f:\mathbb{R}^2 \rightarrow \mathbb{R}, (a,x) \mapsto ax $.
But you cannot write simultaneously $f:\mathbb{R} \mapsto \mathbb{R}$ and $f:\mathbb{R}^2 \mapsto \mathbb{R}$... (the first one is not defined).
I hope it will help a bit.
Comment: Thanks! Ideally, I would like to stick to the $f(x;a)$ notation as well (instead of introducing a family of functions), since that's the standard in my field. I think of parameters as constants once they're chosen, so if $a=10$, then $f(x;10) = 10x$ and that function can be described as $f : \mathbb{R} \mapsto \mathbb{R}$.


Is there a way for my aplication to detect beacons in Powerapps?

Question: I am trying to create an app using Powerapps where I need to interact with beacons ( their brand is Minew).
I want to start with something basic, like get a notification when the beacon is detected. Is it possible? If so, how?
Answer: As @davidgyoung mentioned, the simple answer is no. The most complex answer is it depends on whether the beacon can be exposed to the world (Internet) as a custom connector - there's currently no way to use bluetooth, for example, for communication between PowerApps and the external world.
If the beacon is Internet-connected, then it may be possible to use whatever the beacon is detecting (time, temperature, etc.) as a trigger in the custom connector. Once that is done, then you could create a flow that is started based on that trigger, and the flow can send a push notification to PowerApps (or the flow can store the notification in some data source, and PowerApps can poll for new notifications). You'll also need to manage subscriptions (which apps / users can listen to which notifications from the beacons).
So, this may technically be possible (depending on the capability of the Minew, which I don't know), but it will involve some work to get it done.
Comment: This is helpful info.  The most popular Minew beacon models are simple bluetooth transmitter devices that have no network connectivity, so it certainly would not be possible to get notified of a beacon detection event over a network interface.  What I don't know is whether PowerApps has any ability to provide local native connectors that run exclusively on the device.  If PowerApps provides this ability, then it may in theory be possible to make this happen.  @carosfigueira, can you confirm this either way?
Comment: You're correct. Currently connectors used within PowerApps are hosted in Azure (or hosted on-premises via gateways) but they always go via a network interface. If you really, really, really want to get this scenario working, you could possibly have a separate device that would connect via bluetooth to the Minew, and then broadcast it to the Internet, but at this point (or even before that) I wonder if the complexity is worth it.
Comment: @carlosfigueira the MINEW beacons I am using have a router that recieves their signal and I can access them online. If I build a simple azure web app that connects to it and registers the beacons in my database would that work?
Comment: @MigthyMoron yes, that may work; if you can write the beacon signals to a database, then your app should be able to get that database to poll for data from the beacon.
Answer: It's always hard to authoritatively say something is not possible (somebody can always build a way later and then prove you wrong!) but in years of professional beacon work, I have never heard of anybody using the Powerapps platform to build beacon apps.  While I highly suspect that "no" is the simple answer to this question, I would welcome anyone knowing otherwise to provide another answer.
Comment: Well from what I have been reading I think "no" really is the answer.
Too bad


Is there a map in java?

Question: Is there any standard structure Map<k1,k2>? This means I can get the "value" through the "key" and the "key" through the "value". In other words both values and key are a Set connected to each other.
Comment: Check [this](http://stackoverflow.com/questions/1383797/java-hashmap-how-to-get-key-from-value). There is also an answer which shows how you can do it with the Java standard library.
Answer: The standard library doesn't have one, but for example Guava has the BiMap.

Is there a map in java?


Required modal Bootstrap

Question: Tenho um modal, onde preciso fazer as validações dos campos, porém no modal não consigo colocar o required=required, pois ele não abre o modal.
Como posso proceder, para que na função funcione como required?
Segue as funções que estou utilizando:
Esta é um asterisco, e quando o usuário preenche o campo, muda para um sinal de ok.

$(document).ready(function() {
  $('.input-group input[required], .input-group textarea[required], .input-group select[required]').on('keyup change', function() {
    var $form = $(this).closest('form'),
      $group = $(this).closest('.input-group'),
      $addon = $group.find('.input-group-addon'),
      $icon = $addon.find('span'),
      state = false;

    if (!$group.data('validate')) {
      state = $(this).val() ? true : false;
    } else if ($group.data('validate') == "email") {
      state = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test($(this).val())
    } else if ($group.data('validate') == 'phone') {
      state = /^[(]{0,1}[0-9]{3}[)]{0,1}[-\s\.]{0,1}[0-9]{3}[-\s\.]{0,1}[0-9]{4}$/.test($(this).val())
    } else if ($group.data('validate') == "length") {
      state = $(this).val().length >= $group.data('length') ? true : false;
    } else if ($group.data('validate') == "number") {
      state = !isNaN(parseFloat($(this).val())) && isFinite($(this).val());
    }

    if (state) {
      $addon.removeClass('danger');
      $addon.addClass('success');
      $icon.attr('class', 'glyphicon glyphicon-ok');
    } else {
      $addon.removeClass('success');
      $addon.addClass('danger');
      $icon.attr('class', 'glyphicon glyphicon-asterisk');
    }

    //if ($form.find('.input-group-addon.danger').length == 0) {
    //    $form.find('[type="submit"]').prop('disabled', false);
    //} else {
    //    $form.find('[type="submit"]').prop('disabled', true);
    //}
  });

  $('.input-group input[required], .input-group textarea[required], .input-group select[required]').trigger('change');

});

E esta é pra borda do textbox ficar em vermelho quando clica e e quando digita ela muda de cor:

$(document).ready(function () {

    $('#contact-form').validate({
        rules: {
            txtnome: {
                minlength: 2,
                required: true
            },
            txtHora: {
                required: true
            },
            txtData: {
                required: true
            }
        },
        highlight: function (element) {
            $(element).closest('.control-group').removeClass('success').addClass('error');
        },
        success: function (element) {
            element.text('OK!').addClass('valid')
                .closest('.control-group').removeClass('error').addClass('success');
        }
    });

});

Tentei colocar com o nome do elemento, e colocar required na função, porém não deu certo.
Este é o código do meu modal:

          <button type="button" class="close" data-dismiss="modal">×</button>

                <asp:Label ID="Label78" runat="server" Font-Size="Large" Text="Modal"></asp:Label>

                      ×
                      Atenção!
                      <asp:Label ID="lbAlertAviso" runat="server" Text="Label"></asp:Label>

                  <asp:Label ID="Label18" runat="server" Text="Hora"></asp:Label>

                    <asp:TextBox ID="txtHora" runat="server" class="form-control" onblur="Verifica_Hora(this);"></asp:TextBox>

                  <asp:Label ID="Label250" runat="server" Text="Data"></asp:Label>

                    <asp:TextBox ID="txtData" runat="server" class="form-control" onblur="limparDataInvalida(this);"></asp:TextBox>

                  <asp:Label ID="Label19" runat="server" Text="Observação"></asp:Label>

                  <textarea id="txtObservacao" cols="20" rows="2" runat="server" class="form-control" style="resize: none"></textarea>

              <asp:Button ID="btnGravar" runat="server" CssClass="btn btn-success btn-block" Text="Gravar" OnClick="btnGravar_Click" />

Cheguei nesta função, ela verifica, porém ela só funciona com o alert, quando puxo um css para colocar a borda vermelha sem preenchimento e a borda verde com preenchimento, porém não funciona.

$(document).ready(function () {
            function validateCampo(campoField) {
                if ($("#<%=txtHora.ClientID %>").val() == "") {
                    alert("vazio");
                }
                else { alert("preenchido");}

            }

            $("[id$='txtHora']").on('change', function () {
                validateCampo($(this).val());
                return false;
            })
        });
Comment: Não sei se é o seu caso ou se resolve na sua situação, mas pq vc não usa tipo `` e depois faz uma regra CSS com :valid e :invalid para alternar entre o asterisco e o Ok? Se quiser eu te respondo com um exemplo simples pra vc ver como fica.
Comment: Se puder me ajudar com um exemplo, vou tentar.
Comment: Cara e porque vc está chamando assim ".input-group input[required]"? Não poderia remover esses [required] ?
Comment: porque eu faço isso também nos required, nos campos que são requeridos. Só que no bootstrap, eu preciso fazer a condição sem required, pois toda forma que tento com required, ele não abre o modal, por causa do click do button.
Comment: @hugocsl editei a resposta, mas mesmo assim ainda não consegui fazer da forma que quero.
Answer: Consegui resolver, colocando o required, ao clicar o button, e ao concluir a operação coloco o required como false.

 function openModalIncluir() {
            $('#myModalIncluir').modal('show');
            ($("#<%=txtValorIncluir.ClientID %>").prop('required', true));
            ($("#<%=txtVencimentoIncluir.ClientID %>").prop('required', true));
        }

E aqui eu coloco como falso:

function Campos() {
              ($("#<%=txtValorIncluir.ClientID %>").prop('required', false));
            ($("#<%=txtVencimentoIncluir.ClientID %>").prop('required', false));
          }

Required modal Bootstrap


Approximating the Logit-Normal by Dirichlet

Question: There is a known approximation of the Dirichlet Distribution by a Logit-Normal, as presented in wikipedia.
However, I am interested in the reverse, can I approximate a logit-normal by a Dirichlet?
I.e. Exists an explicit expression for the concentration paramters $\alpha$, given the parameters of the Logit-Normal $\mu, \Sigma$?
Comment: Isn't "approximates" a symmetric relation?  If not, what kind of asymmetry concerns you?
Comment: @whuber KL divergence isn't symmetric
Comment: @Cat That is true.  I had believed it irrelevant to the question, but a close look at the Wikipedia reference shows it was used for the approximation, so you make a very perceptive point.
Comment: Maybe we can ease the problem. Is the KL (forward or reverse does not matter) between Logit-Normals and Dirichlet known? Probably yes, as Aitchinson derived a solution in the wiki link, but his paper is hidden behind a paywall.
Answer: Two approaches: iterative and closed-form Laplace Bridge.
See below.
Iterative Newton-Raphson
Given Logistic Normal $p(x \mid \mu,\Sigma)$ and Dirichlet $q(x \mid \alpha)$, the objective is to minimize the KL divergence $\mathbb{KL}(p \parallel q)$ (see Stanford cs228 note (2023) for the specific choice of KL divergence):
$$
L=\mathbb E_p[-\log \tilde q(x \mid \alpha)] + \log\frac{\prod_{d=1}^D \Gamma(\alpha_d)}{\Gamma(\sum_{d=1}^D \alpha_d)}+C\,,\tag{1}
$$
where $C$ is a irrelevant constant and $\tilde q$ is the unnormalized Dirichlet:
$$
\tilde q(x \mid \alpha) = \prod_{d=1}^D x_d^{\alpha_d-1}\,.
$$
Note here, we extract the normalization constant out of the expectation.
Equation (1) yields:
$$
\mathbb E_p[-\log \tilde q(x \mid \alpha)]
= -\mathbb E_p \left[\sum_{d=1}^D (\alpha_d-1)\log x_d\right]
= -\sum_{d=1}^D (\alpha_d-1) \mathbb E_p[\log x_d]\,,\tag{2}
$$
where $\mathbb E_p[\log x_d]$ can be evaluated using reparameterization trick (Kingma and Welling (2014); Jankowiak and Obermeyer (2018)) followed by Monte Carlo estimate.
Finally, with all the pieces in hand, to optimize Equation (1), while plain old gradient descent may be used, we may adopt instead a linear-time Newton-Raphson method (Ronning (1989); Minka (2000); Blei et al. (2003)), with update rule on $\alpha$:
$$
\alpha := \alpha - H(\alpha)^{-1} g(\alpha)\,.
$$
Here, $g(\alpha)$, the gradient of Equation (1), can be written as:
$$
g_j(\alpha) = \frac{\partial L}{\partial \alpha_j}
= -\mathbb E_p[\log x_j] + \psi(\alpha_j) - \psi(\textstyle\sum\nolimits_{d=1}^D \alpha_d)\,,
$$
whereas $H(\alpha)$, the Hessian, can be written as:
$$
H_{ij}(\alpha) = \frac{\partial^2 L}{\partial\alpha_i\partial\alpha_j}
= \delta_{ij} \psi'(\alpha_i) - \psi'(\textstyle\sum\nolimits_{d=1}^D \alpha_d)\,.
$$
where $\psi(\cdot)$ is the digamma function, $\psi'(\cdot)$ is the trigamma function, and $\delta_{ij}$ is the Kronecker Delta function, which is one iff $i=j$ else zero.
Since the Hessian admits the form $H = \operatorname{diag}(h) + \mathbf 1 z \mathbf 1^\top$, the $H^{-1}g$ can be computed in linear time:
$$
(H^{-1}g)_i = \frac{g_i-c}{h_i}\,,\quad c= \frac{\sum_{d=1}^D g_d/h_d}{z^{-1}+\sum_{d=1}^D h_d^{-1}}\,.
$$
In this spirits, let's attack a 1-D example, where the Dirichlet reduces to Beta distribution.
<code>from matplotlib import pyplot as plt
from scipy import stats
import numpy as np
import torch
from torch.distributions import Normal
from torch import nn
from torch import optim

def logsigmoid(z):
    return -torch.logaddexp(torch.zeros_like(z), -z)

def loss_fn(a, b, mu, sigma):
    eps = Normal(0, 1).sample([1000])
    return (torch.mean(
            - (a - 1) * logsigmoid(mu + sigma * eps)
            - (b - 1) * logsigmoid(-mu - sigma * eps))
            + torch.lgamma(a) + torch.lgamma(b)
            - torch.lgamma(a + b))

def train_SGD(mu, sigma):
    a = nn.Parameter(torch.tensor(1.))
    b = nn.Parameter(torch.tensor(1.))
    optimizer = optim.SGD([a, b], lr=1e-2, momentum=0.9)
    losses = []
    n_epoch = 100
    for _ in range(n_epoch):
        loss = loss_fn(a, b, mu, sigma)
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
        losses.append(loss.item())
    return losses, a.item(), b.item()

def train_NewtonRaphson(mu, sigma):
    a = torch.tensor(1.)
    b = torch.tensor(1.)
    for _ in range(50):
        eps = Normal(0, 1).sample([1000])
        x = mu + sigma * eps
        da, db, dab = torch.digamma(a), torch.digamma(b), torch.digamma(a + b)
        ga = -torch.mean(logsigmoid(x)) + da - dab
        gb = -torch.mean(log1msigmoid(x)) + db - dab
        ha, hb = torch.polygamma(1, a), torch.polygamma(1, b)
        z = -torch.polygamma(1, a + b)
        c = (ga / ha + gb / hb) / (1 / z + 1 / ha + 1 / hb)
        a -= (ga - c) / ha
        b -= (gb - c) / hb
    return a.item(), b.item()

def sigmoid(z):
    return 1 / (1 + np.exp(-z))

def sample(a, b, mu, sigma):
    Betas = stats.beta(a, b).rvs(size=10000)
    LogitNormals = sigmoid(stats.norm(mu, sigma).rvs(size=10000))
    return Betas, LogitNormals

# experiment 1
mu, sigma = torch.tensor(0.), torch.tensor(1.)
# experiment 2
mu, sigma = torch.tensor(1.), torch.tensor(2.)

# either use SGD
_, a, b = train_SGD(mu, sigma)
# or use Newton-Raphson
a, b = train_NewtonRaphson(mu, sigma)

B, LN = sample(a, b, mu, sigma)
fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.hist(B, bins=100, density=True)
ax1.set_title('Beta')
ax2.hist(LN, bins=100, density=True)
ax2.set_title('LogitNormal')
</code>
The SGD typically takes 80 ms, while Newton-Raphson takes 20 ms.
The code produces the following plots, where the left are the solution Beta, and the right are the groundtruth Logit Normal:

Closed-form Laplace Bridge
Hobbhahn et al. (2020) gave the bidirectional approximation formulae, which is different from the wikipedia formula:
Providing Dirichlet parameter $\alpha$, the approximated Logistic Normal parameters are:
$$
\begin{gather}
\mu_j = \log\alpha_j - \frac{1}{D}\sum_{d=1}^D \log\alpha_d\,;\tag{3.1}\\
\Sigma_{jj} = \frac{1}{\alpha_j} \left(1 - \frac{2}{D}\right) + \frac{1}{D^2}\sum_{d=1}^D \frac{1}{\alpha_d}\,;\tag{3.2}\\
\Sigma_{ij} = 0\,\quad(i \ne j)\,.\tag{3.3}\\
\end{gather}
$$
Providing Logistic Normal parameters $\mu$ and $\Sigma$, the approximated Dirichlet parameters are:
$$
\alpha_j = \frac{1}{\Sigma_{jj}} \left(1 - \frac{2}{D} + \frac{e^{\mu_j}}{D^2} \sum_{d=1}^D e^{-\mu_d}\right)\tag{4}\,.
$$
Note, however, that Equations (3.1-3.3,4) does not hold precisely all the time.
In particular, since the parameter space (basically, $\mathbb R^D \times \mathbb R^{D \times D}$) of Logistic Normal is much larger than that of a Dirichlet (basically, $\mathbb R_+^D$), Equation (4) admits good approximation only for certain choice of $\mu$ and $\Sigma$.
The rule of thumb, which probably sounds uninformative, is that, if the $\mu$ and $\Sigma$ can be yielded by some $\alpha$ under Equations (3.1-3.3), then they can be approximated by that $\alpha$.


How to compare predictions from MLE-based regression Vs. predictions from bayesian regression?

Question: Say I have two linear regression models that I want to use for predictions.
Linear regression:
\begin{equation}
\mathbf{y} \sim  \mathcal{N}(\mathbf{X^Tb}, \Sigma_y)
\end{equation}
Bayesian linear regression:
\begin{align}
\mathbf{y | b} &\sim \mathcal{N}(\mathbf{X^Tb}, \Sigma_y) \notag\\
\mathbf{b} &\sim \mathcal{N}(0, \Sigma_b)
\end{align}
Predictions
For the linear regression, I find the coefficients by MLE:
\begin{equation}
\mathbf{b}_{\text{MLE}} =  \mathbf{(X X^T)^{-1} X y}
\end{equation}
The predictions for the the test set are:
\begin{equation}
\mathbf{y_{test}} = \mathbf{X_{test}^T b_\text{MLE}}
\end{equation}
For the bayesian linear regression, I find the predictive posterior:
\begin{equation}
p(\mathbf{y_{test}}  | \mathbf{X_{test}} , \mathbf{y}, \mathbf{b})  =
\int  p(\mathbf{y_{test}}  | \mathbf{X_{test}}, \mathbf{b}) p(\mathbf{b} |\mathbf{y}) \text{d}\mathbf{b}
\end{equation}
(Thought this integral could be analytically derived, I find it by Gibbs sampling since in my actual model the different $b_i$ come from a mixture of gaussians.)
The predictions are plotted here, where for the bayesian prediction I also plotted the variance of every $y$ (computed from the traces of the Gibbs sampler)

Questions

How should I compare the two models? Should I use $R^2$ (and then all the bayesian machinery is for nothing?)
(forgetting about MLE) How to evaluate the performance of the bayesian estimators? I've found a lot about model selection, but what about the accuracy of a single model?
Comment: No, they are not the MAP: If you multiply two distributions (likelihood and prior), MAP is the mode and not the expectation.
Comment: Yeap, Maximum a Posteriori. Maybe I shouldn't call it MAP anyway. It is the mean of the samples of the posterior predictive distribution. And the vertical lines are their variance.
Comment: Well, in this case you should be careful calling your approach 'Bayesian'. Just taking the best guess (MAP) is not Bayesian: for a full Bayesian approach you have to sample from the posterior.
Comment: But I sample from the posterior $p(y_{test} | x_{test}, b)$ indeed, don't I?
Comment: It is not clear from your description of the problem. MAP means that you find the maximum of the product of prior and likelihood. Loosely speaking, if everything you Gaussian, than the red line you are plotting is the mean of the posterior. However, if you have many samples from you posterior: How do you want to apply $R^2$? In a Bayesian framework you have not only one posterior model prediction but a lot.
Comment: mmm let see if I understood it: so the $y_{test}$ points, which are the E[y_test] with respect to the posterior p($w$ | X, y), are not a MAP? I thought it would give the same result than a "traditional" MAP!. In that case I will edit the question.
Comment: What does MAP stand for? Maximum a-posteriori?
Answer:
How should I compare the two models?

Rather than think of these two approaches as two distinct "models", I suggest you look at the ML and MAP results as estimates (or predictions) derived from models that are characterizing randomness/uncertainty (depending on the perspective). Consider this: the ML estimates you are using for the points $\mathbf{y}_\text{test}$ have a sampling distribution, the expectation of which is what you have taken as your prediction for $\mathbf{y}_\text{test}$; this is just $\mathbf{X}_\text{test}^T \mathbf{b}_\text{MLE}$. Observe that you can construct a confidence interval with this estimate/prediction using frequentist theory. This characterization of randomness is analogous to the Bayesian characterization of uncertainty in the posterior predictive. For example, in your posted plot, you could have also given the blue line "error bars" to denote your characterization of randomness as it relates to your estimates of $\mathbf{y}_\text{test}$.
So in that sense, your plot is playing favorites: it did not present the frequentist measure of "variance" in the MLE predictions. It's not as if the Bayesian approach to regression offers substantially useful information that the ML approach does not.

Should I use $R^2$ (and then all the bayesian machinery is for nothing?)

You can use $R^2$ to compare two (point estimate) predictions, which you did for the MLE and MAP predictions. There are pros/cons and caveats to using that particular metric which have been answered in other questions on this site.

(forgetting about MLE) How to evaluate the performance of the bayesian estimators? I've found a lot about model selection, but what about the accuracy of a single model?

You can specify a loss function that has some valuable meaning and then calculate it. For example, for a set of actual values $\{y_i\}_{i=1}^n$ and a set of estimators $\{\hat y_i\}_{i=1}^n$, the root mean square deviation (RMSD; a.k.a. RMSE) is given by
$$
\text{RMSD}(y_{i=1,\dots,n}, \hat y_{i=1,\dots,n}) = \sqrt{\frac{1}{n} \sum_{i=1}^n (y_i - \hat y_i)^2}
$$
and is equivalent to the sample standard deviation of the difference between the estimator and its actual value --- which has a particularly useful meaning.
This approach of evaluating loss functions on estimators rings well with formal Bayesian theory, where the choice of which specific estimator to use can only be determined once a loss function, which we are wanting to minimize, has been specified. For example, the posterior mean estimate is the Bayesian estimator implied when we specify squared error loss. (Although, in practice, we often choose which estimator to use and then justify the loss function implying that estimator as needed..)
Answer:
How should I compare the two models?

Form a Bayesian point of view you do not have two models to compare: MLE is just a single 'best' guess. (Instead of 'MAP' I would you the expectation of the model prediction; because MAP also is only a 'best' guess.)
To compare the two models in a Bayesian framework, you would need their evidences - which is essentially zero for the MLE 'model'.

How to evaluate the performance of the bayesian estimators? I've found a lot about model selection, but what about the accuracy of a single model?

From a Bayesian viewpoint it makes only sense to compare a model if you have alternative competing models. The 'root means square deviation' (RMSD) is a measure I would refrain from using (the only exception being if everything is nice and Gaussian). By definition, the likelihood defines how your model relates to the data. How can you justify to switch to the RMSD to assess the 'quality of your model'?
Of course, you can use the tools mentioned. However, you should not call it Bayesian then.


Assessing the accuracy of a deterministic mathematical model

Question: How can assess the accuracy of the output of a deterministic mathematical model?
For example, a climate model can predict the mean annual temperature (MAT) for a specific location. I can use the model to predict thirty years of MAT in New York City, $T_\text{model}$. Now let's say I have the observed MAT in New York City for the same 30 years, $T_\text{obs}$.
Is there a statistical test for the hypothesis $T_\text{obs}=T_\text{model}$? Can I assess the accuracy of the mathematical model?
Comment: Specifically, is there a way to test this using R statistical software?
Comment: Also, if its not too much trouble, might someone be able to recommend me a p-value to use for the test?
Comment: Do you have an estimate of uncertainty in the model output, or is it a point estimate? If not, I think that the model will, by definition, be wrong. For example, if the model estimates MAT$=20$ and the actual MAT was $20 + x$, where x is a continuous variable, then the model is wrong because $20\neq20+x$
Comment: I hope you don't mind my edits for clarity - Also, I have asked a related follow up question here: http://stats.stackexchange.com/q/30771/2750
Comment: Would someone be able to answer for me why a Chi Square Goodness of Fit test would not be appropriate for assessing how well the model fits the actual data?
Comment: perhaps you could ask about using $\chi^2$GOF as a separate question
Answer: A decent first step might be to compute the correlation between your model's predictions ("data A") and the observed temperatures ("data B"). Correlations range from -1 to +1: 0 indicates no (linear) relationship between the predicted and observed values, while higher values suggest that your model better agrees (up to a scale factor) with the observed data. Correlations can easily be computed in R with the cor function. The cor.test function does some testing of association between two variables.
You should also just plot the data and take a look at it. Your model might not perform equally well under all conditions (e.g., maybe it breaks down around freezing temperatures)
There are more sophisticated things you could try, but I think these are a reasonable first step.
Comment: In this situation, the null hypothesis of interest is not $\rho=0$, as is the default in `cor.test`, but $\rho=1$, which would obviously produce a degenerate distribution.
Comment: I don't see how calculating the correlation coefficient assesses how well the model fits the data. For instance, if when I plot data A and data B together, it could end up that the plot perfectly produces a line y = 0.5x. This would have a correlation coefficient of 1. But it does not mean that the model fits the data well; for example when x = 2000, y = 1000
Comment: @Stask, I'm afraid I don't follow. Wouldn't the null hypothesis be "this model is cannot predict", i.e., rho=0, and the alternative hypothesis "this model captures some info about temperature" i.e., rho>0?
Comment: @Steven That's a valid point. I would argue that a model which perfectly predicts, say, half or twice tomorrow's temperature from other data is still a fantastic model. Since correlation works up to a scale factor, you could just rescale the model's prediction at the end, if you need an actual temperature.
Answer: Your question sounds confusing.  When you say accuracy of the model, are you just referring to how well it predicts or do you mean how well it simulates the behavior of weather in New York City?  I don't think you can assess the latter.  As to the former, I would compute the mean square prediction error. By that I mean use the model to predict the mean annual temperature for each of the 30 years (presumably based on available inputs that the mode needs to get the estimates) and take the average squared difference between it and the actual recorded mean annual temperatures.  This gives you an estimate but not the accuracy of the estimate.  So you may have a standard for the accuracy and you want to test the hypothesis that accuracy is better than a certain level.  Now I can give a somewhat vague description of how to do this.  It is admittedly vague because I do not know what inputs go into the model to make the prediction.  The idea would be to make small perturbations to the input and see how these perturbations affect the accuracy of the prediction.  This would give you a distribution of mean square errors from which you could estimate a p-value for your hypothesis.  All this assumes that you have a sensible way to perturb the inputs that would characterize the sampling variability in the inputs.  The resulting estimates would then provide a representation of the variability of the individual predictions and from that the variability in the estimated means square error of prediction.
Comment: @Steven If you can't vary the inputs to get various estimates of the temperature you have no way to see the distribution of the prediction accuracy.I do not know what you have in mind for the chi square test. You have 30 years of average temperatures and thirty model estimates. I fyou treat these as independent estimates of an unknown target temperature i could see using mean square error as a measure of accuracy but I din't see a chi suqare statistic entering in here. That would mean having some form of a contingency table where you would compare expected counts to observed counts.
Comment: Are you are saying that a P-value requires an estimate of both model and observation uncertainty?
Comment: I vaguely recall a statistical test for this kind of situation- the Chi Square Goodness of Fit test. Do you all think this would be an appropriate test for my situation? I am just looking to assess how well the model fits the observed data. This is what I mean by testing whether or not the model is "accurate"
Comment: @Abe Frist of all a p-value has to refer to an hypothesis test.  it represents the probability that if the null hypotheis is ture that you would obtain an estimate of the size of the observed value or higher.  So you need a test.  I suggested testing that the prediction accuracy (not the model accuracy or the uncertainty in the observed temperatures) is good in the sense that the mean square error is less than some standard A.  Your model and your data give you one estimate of this accuracy.
Comment: To perform a test you need to get a distirbution for the test statistic under that hypothesis that the actual mean square error is A.  Ding repeated peerturbations of the inputs gives a set of estimates of the temperatures and from that a set of mean square errors.  You use that distribution to obtain your p-value.
Comment: Unfortunately I do not have access to the mathematical model, just the output (specifically the 30 year temperatures in New York City). So I cannot manipulate inputs. Why will the Chi Square test not work?
Comment: Is the approach of [Kennedy and O'Hagan 2001, Bayesian calibration of computer models. J. R. Stat. Soc. B](http://www.stat.lsa.umich.edu/pdfs/KA2001.pdf) in line with your suggestion?
Comment: @Abe I think they are dealing with a different situation.  They are talking about calibration which involves inferring unknown parameters based on observed results.  I was think that this problem deals just with the accuracy of the prediction without regard to the model parameters.
Answer: I would suggest two approaches to assessing whether or not a deterministic mathematical model is performing well - neither of which actually involve a statistical test, and which especially do not involve trying to reduce model performance to a p-value.

How well does your model predict parameters? If your model estimates parameters from data, how well does this estimate agree with observed parameters from data other than what you fit the model to?
Does it generate the correct answer when confronted with parameters that result in a known change. For example, if your model is given all the parameters that occur before a heat wave, does it correctly produce said heat wave?

As someone else has suggested, you could also compare the error between your predicted output and the actual output of the system, though this just gives you a number that you're trying to minimize, not actually a statistical estimate. Designing mathematical models to be tested statistically is very hard to do backwards - the elements you need generally need to be discussed in the model design step, just like with studies.
Answer: I recently devised a validation frame for deterministic solar irradiance forecasts. It bases on the insight that outcome and prediction of a perfect forecast must be mathematically exchangeable. It is generally applicable for the forecast of continuous stochastic variables.
See https://doi.org/10.1016/j.renene.2021.08.032


MySQL - backup from binary data - some databases seems to be empty while they were not!

Question: my OS died today, so I have to copy the data onto working machine. I've set up the new environment including MySQL, then copied contents of <code>/var/lib/mysql</code> from an old machine to the new one. Unfortunately, while looking at the results I have noticed that some (yes, only some) databases are completely empty - while the others survived untouched.
The only thing connecting those databases with "lost" tables and records, is the fact they were all created recently, comparing to the survived ones. [by recently I mean half a year or so]
My question is quite obvious now - how should I restore the data correctly?
Thanks in advance
Comment: How did perform your backups?  Without knowing how you performed your backups telling you how to restore, or even if you can restore is pretty difficult.  If you just copying the files without from /var/lib/mysql you may have lost your data.
Answer:
What is your Data Storage Engine (MyISAM, InnoDB)?
How did you perform the backup/restore (scp, cp, tar, rsync ?)
Was fsck run on your old system ? did it notice any issues ?
did you try using mysqldump from the old box ?
Was your OS and data on same partition ?
if you are able to mount the MySQL data partition from the old machine, and have a new instance of MySQL use it, then you could run a mysqlcheck and then do the necessary ?


Display a node form in default theme for admin

Question: I think this question has been asked many times, but I am sorry not to find a working solution. May be I am doing something wrong. I want to display a specific node form in my default custom theme and not in the admin theme when the administrator logs in. However, other node forms should continue to display in the admin theme. Hence the "Use the administration theme when editing or creating content " should be checked.
I have tried the themekey module. I came across that there's something called themekey compatibility by which this can be achieved. But I fail to find an example.
I want the default theme for a specific content type. Also I tried the followings: hook_custom_theme & hook_theme_init as described in How to change the theme for a particular admin page in drupal?
Thanks
Comment: "specific node form" - form for specific node ID? for specific content type? Or what exactly is *specified* in your case?
Comment: Oh, and for *"I also tried using some hooks from my custom modules but without success."* - See our help center. If you want help with code you wrote, please post that code, and describe how it failed.
Comment: I want the default theme for a specific content type. Also i tried the followings:

`hook_custom_theme` & `hook_theme_init` as described in http://drupal.stackexchange.com/questions/97364/how-to-change-the-theme-for-a-particular-admin-page-in-drupal
Hope this clears up a little.
Comment: This site is not a forum - **[edit](http://drupal.stackexchange.com/posts/131286/edit)** new data into question. Don't use comments to create discussion threads.
Answer: There is a hook that you can use to set which pages use the admin theme and which don't.
The hook is hook_admin_paths().
The node module uses this hook to provide the functionaity where you can set node forms to use the admin theme (see node_admin_paths()).
If you wanted to set certain paths to use the admin them (or not use it) you could implement that hook, however if you want to change admin paths that another module has already defined you need to use hook_admin_paths_alter().
In this case the node module defines a wild card path for all node add pages like this <code>'node/add/*' => TRUE</code>
Since you only care about a specific node type you can ignore that and do this:
<code>/**
 * Implements hook_admin_paths().
 */
function MODULENAME_admin_paths() {
  // We have configured the site to use the admin theme for node forms
  // however we want the article content type to use the default theme
  // instead of the admin theme.
  $paths = array(
    'node/add/article' => FALSE,
  );
  return $paths;
}
</code>
As you can see in path_is_admin(), where the check is done to see if the current page is an admin page, for a page to be an admin page it must have a matching path that is TRUE and also not have one that is FALSE.
So by adding this FALSE in for this specific page you are overriding the wildcard node/add/* from the node module.
The problem that you then have is the node edit page (if you also want that to use the same theme as the node add form), because the URL for the node edit page has nothing in it that relates to the content type so you can't override node edit pages based on their type.
You could get the node IDs of all nodes of your specific type and add each individual node edit path however if you have a large number of nodes that is not going to be ideal.
Comment: hook_admin_paths() it worked!


Find all local maximum and minimum points

Question: $F(x)=1$   if the decimal expansion of $x $ contains a $5$; $=0$ otherwise.
According to the answer, $x$ is a local minimum point if its decimal expansion does not contain 5.
If I understand the question correctly, if $x$'s decimal expansion does not contain $5$, $x$ should be $0$ and every number around it should also be $0$ unless $x$ is $.49999\cdots999$ So the correct answer should be either local minimum or both a local minimum and a local maximum
Comment: $F(x)$ is a piecewise function assuming only two values: $F(x)=1$ when the decimal expansion of $x$ contains a 5, and $F(x)=0$ otherwise. Since $F(x)$ does not assume any other value, *every x which does not have 5 in its decimal expansion serves as a local minimum, and every x which does serves as a local maximum.*
Comment: There is a third option. Every x is both a maximum and a minimum no?
Comment: I don't think a value from the domain can simultaneously be a local minimum and maximum. Why would you think it can be both?
Comment: For the situation where x is a horizontal line
Comment: From page 635 answer of calculus:Michael Slovak edition: in all other cases, x is both a local maximum and a local minimum
Comment: I guess you're referring to Spivak's Calculus? I'll look into the exact context and add an answer once I understand your point of confusion.
Comment: @Manan yes, Spivak. Thank you so so much
Answer: As elaborated by you in the comments, I looked up for the exact question and solution provided in Spivak's Calculus, 3rd Edition. Perhaps the way the solution was phrased(for the sake of compactness) confused you. Here's the solution:

$x$ is a local maximum(minimum) point if the decimal expansion contains(does not contain) a 5.

This simply means that for every $x$ containing a 5 in its decimal expansion, the function acquires a local maximum(=1), and for every $x$ not containing a 5, the function acquires a local minimum(=0).
Furthermore, a point cannot serve as a local minimum and maximum simultaneously. I suggest you to go through the Calculus 1 course on Khan Academy.
Comment: @jxhyc I find the solution in 4th edition to be quite baffling. I've always seen Spivak as the gold-standard Calculus textbook so I wouldn't expect an error like this one. I'll pass and upvote the question for now. Maybe an expert can enlighten me as well.
Comment: Very strange. I have the 4th edution and there seesm to be some change.


Show form errors before opening AJAX modal

Question: I have a form that adds a product to the cart.
The form uses AJAX to open a modal when the form is submitted.
I want to show form errors (if any) before the modal opens and avoid opening it if there are errors.
Here's my form submit element:
$form['submit'] = [
  '#type' => 'submit',
  '#value' => $this->t('Submit'),
  '#ajax' => [
    'callback' => '::submitAjaxForm'
  ],
  '#attached' => [
    'library' => ['core/drupal.dialog.ajax'],
  ],
];

My submitAjaxForm:
public function submitAjaxForm(array $form, FormStateInterface $form_state) {
  $response = new AjaxResponse();
  $response->addCommand(new OpenModalDialogCommand(
    $this->t('Product added to cart!'),
    [
      '#theme' => 'some_theme',
    ]
  ));

  return $response;
}

And my submitForm:
public function submitForm(array &$form, FormStateInterface $form_state) {
  // Add product to cart.
}

I have tried by adding this code to the AjaxSubmit but it only shows the error messages once the page has been reloaded.
if ($form_state::hasAnyErrors()) {
  foreach ($form_state->getErrors() as $error) {
    $this->messenger()->addError($error);

    $message = [
      '#theme' => 'status_messages',
      '#message_list' => $this->messenger()->messagesByType(MessengerInterface::TYPE_ERROR),
    ];

    $messages = $this->renderer->render($message);

    $response = new AjaxResponse();
    $response->addCommand(new HtmlCommand('#result-message', $messages));
    $form_state->setRebuild(TRUE);

    return $response;
  }
}

How can I show the errors without having to reload the page?
Answer: I see two things that stand out to me:
1) Setting the '#name' attribute on the submit button. You should never do that. I've learned over the days that there is always a better way to do whatever you're trying to do when setting the #name attribute, and setting it causes some wonkiness. This may be why your form is not rebuilding.
2) You are rendering your status messages in a D7 way. Use this instead:
$messages = ['#type' => 'status_messages'];
$response->addCommand(new PrependCommand('#target-div', \Drupal::service('renderer')->renderRoot($messages)));
It looks weird, because the messages aren't being retrieved, but by setting the #type to status messages, Drupal will handle the retrieval in the background. This is probably why you are seeing some funkiness with the messages.
Comment: I don't set `#name` on the submit button.


MPI matrix multification compile err: undeclared with code

Question: I coded a mpi matrix multification program, which use scanf("%d", &size), designate matrix size, then I defined int matrix[size*size], but when I complied it, it reported that matrix is undeclared. Please tell me why, or what my problem is!
According Ed's suggestion, I changed the matrix definition to if(myid == 0) block, but got the same err! Now I post my code, please help me find out where I made mistakes! thank you!
int size;

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

int myid, numprocs;
int *p;
MPI_Status status;
int i,j,k;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD,&myid);
MPI_Comm_size(MPI_COMM_WORLD, &numprocs);
if(myid == 0)
 {
  scanf("%d", &size);
  int matrix1[size*size];
  int matrix2[size*size];
  int matrix3[size*size];
  int section = size/numprocs;
  int tail = size % numprocs;
  srand((unsigned)time(NULL));
  for( i=0; i<size; i++)
     for( j=0; j<size; j++)
        {
            matrix1[i*size+j]=rand()%9;
            matrix3[i*size+j]= 0;
            matrix2[i*size+j]=rand()%9;
         }
      printf("Matrix1 is: \n");
      for( i=0; i<size; i++)
         {
             for( j=0; j<size; j++)
              {
                  printf("%3d", matrix1[i*size+j]);
              }
             printf("\n");
         }
       printf("\n");
       printf("Matrix2 is: \n");

Comment: how about reformatting your code?
Comment: hehe, I tried, but the layout seems not to work!
BTW, I have sovled the problem! I tried a #define MAX_SIZE 500, then I just use part of the array ^u^
Answer: Reformatted code would be nice...
One problem is that you haven't declared the size variable.  Another problem is that the [size] notation for declaring arrays is only good for sizes that are known at compile time.  You want to use malloc() instead.
Comment: thanks, I think scanf("%d", &size) can work at run time! I've try scanf("%d", &size);
int matrix[size];
successfully on my own computer. but on mpi environment, it sucks! that is where I comfused!
Answer: You don't actually need to define a MAX_SIZE if you use dynamic memory allocation.
#include <stdio.h>
#include <stdlib.h>
...
   scanf("%d", &size);
   int *matrix1 = (int *) malloc(size*size*sizeof(int));
   int *matrix2 = (int *) malloc(size*size*sizeof(int));
   int *matrix3 = (int *) malloc(size*size*sizeof(int));
...


Hardy–Littlewood maximal inequality on measurable sets

Question: The Hardy–Littlewood maximal inequality states that for $d ≥ 1$, $1 < p ≤ ∞$, and $f ∈ L^p(\mathbb{R}^d)$, there is a constant $C_{p,d} > 0$ such that
$$||Mf||_{L^p(\mathbb{R}^d)}\leq C_{p,d}||f||_{L^p(\mathbb{R}^d)},$$
where
$$Mf(x)=\sup_{r>0}{\dfrac{1}{|B(x,r)|}}\int_{B(x,r)}|f(y)|dy.$$
Is it true that $$\Big(\int_A |Mf(x)|^pdx\Big)^{1/p}\leq C_{p,d}\Big(\int_A |f(x)|^pdx\Big)^{1/p} $$
where A is a measurable set?
Comment: I think that you should write out precisely what you want to be true. If you only replace the restriction to $A$ in the first inequality, then it seems  false.
Comment: @H.H.Rugh I wrote what I want to be true.
Answer: No if e.g. $f$ has support outside of $A$ the RHS is zero but the LHS is non-zero if $f$ has non-vanishing integral in ${\Bbb R}^d$ and $A$ has positive measure.
Comment: If $f\in L^p(A)$, if you set $g(x)=f(x)\cdot \boldsymbol 1_A(x)$, then $g\in L^p(\mathbb R^n)$, and has all the hypothesis of the theorem. Therefore, it must be true...
Comment: That's why I asked to make the statement more precise. $f$ was not supposed to have support in $A$.
Comment: What if  $|f|>0$ a.e and $A$ has positive measure?
Comment: Not with a uniform bound without further conditions, since you may get arbitrarily close to the situation I described. If you happen to know something about the ratio of the $L^p(A)$ and $L^p(A^c)$ norm then you are in business (with an obvious estimate) but I can't think of a 'natural' general condition.


taylor expansion for $\frac1{\cos(x)-\sin(x)}$

Question: I am trying to find a closed expression for the taylor series of $\frac1{\cos(x)-\sin(x)}$ in a neighborhood of $x = 0$. One can obtain the coefficients from: $$(a_o+a_1x+a_2x^2+\cdots)(1-x-\frac{x^2}2+\frac{x^3}{3!}+\frac{x^4}{4!}--++\cdots) = 1$$
thus $a_0= 1, a_1=1, a_2 = 3/2$, etc. Is it possible to find a recursive or symbolic law (like $(B+1)^n-B^n = 0$ for bernoulli numbers) for the coefficients $a_n$?
edit: if we let $a_n = b_n/n!$, we can find the following: $$b_n = \binom{n}1b_{n-1}+\binom{n}2b_{n-2}-\binom{n}3b_{n-3}-\binom{n}4b_{n-4}++--\cdots$$ for $n\ge1$, and $b_0 = 1$. Still this is not very appealing.
Comment: I don't know if it might help but $\frac{1}{\cos x-\sin x} =\frac{1}{\sqrt{2}} \sec(x+\pi/4)$ so you're basically looking for the coefficients of the expansion of $\sec$ around $-\pi/4$.
Comment: @ECL. Why around $-\frac \pi 4$ ?
Answer: The coefficients of numerators are
$$\{1,1,3,11,19,361,307,24611,83579,2873041,12193841,512343611,869783713\}$$ and for denominators
$$\{1,1,2,6,8,120,80,5040,13440,362880,1209600,39916800,53222400\}$$ You could find them in $OEIS$ (sequences $A279257$ and $A279258$) but according to the pages, they do not show any particularity.
Edit
If it was around $x=-\frac \pi 4$ (which is not the case)
$$\sec \left(x+\frac{\pi }{4}\right)=\sum_{n=0}^\infty \frac{E_{2 n}}{(2 n)!}\left(x+\frac{\pi }{4}\right)^{2 n}$$ where appear Euler numbers.


How to configure database in Blackberry enterprise server?

Question: I have downloaded Trial - BlackBerry Enterprise Server 4.1 for MDS Applications. Tried to install the same.but unable to configure Database settings.
Am using MS SQL Server
<code>Microsoft SQL Server 2008 (RTM) - 10.0.1600.22 (Intel X86) Jul 9 2008 14:43:34 Copyright (c) 1988-2008 Microsoft Corporation Enterprise Edition on Windows NT 6.0 <X86> (Build 6001: Service Pack 1)
</code>
But while configuration its prompting me an error.
<code>"Your database environment must be Microsoft SQL server 2000 SP3a or later"
</code>
Can anybody help me where am going wrong?
Answer: BES 4.1 is old, and I don't think it supports SQL 2008. BES 5.x should work fine however.
Comment: While the BES components can be installed separately on different machines, they all work together as a whole. A BES MDS connection server does you no good without the other components.
Comment: but all BES 5.x have there prerequisite,like MS Exchange sever,etc. Is it possible to use push service on BES without these Prerequisite,as I think they deal with requirements related to emails,and my requirement is just send a message to push enabled client,I am very new to BB development,so might be going wrong some where,Will be glad if someone correct me. Thanx
Comment: @joeqwetry:Thanx for the Reply.So in that case, I guess 3  option left BES with Exchange server or Novell or Dommino. Can you please suggest me which is better for Push service.I have 32 bit Windows Vista as OS so I guess in that enviorment I will not be able to use Exchange server,Now which is better Novell or Dommion?? Hope for a help


error MSB007 node.js mongoose

Question: i'ms trying to install mongoose on mys nodeJS project and i have this error
C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\Microsoft.Cpp.InvalidPlatform
C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\Microsoft.Cpp.InvalidPlatform
.Targets(23,7): error MSB8007: The Platform for project 'kerberos.vcxproj' is i
.Targets(23,7): error MSB8007: The Platform for project 'bson.vcxproj' is inval
nvalid.  Platform='x64'. You may be seeing this message because you are trying
id.  Platform='x64'. You may be seeing this message because you are trying to b
to build a project without a solution file, and have specified a non-default Pl
uild a project without a solution file, and have specified a non-default Platfo
atform that doesn't exist for this project. [c:\testNodeMongoose\node_modules\m
rm that doesn't exist for this project. [c:\testNodeMongoose\node_modules\mongo
ongoose\node_modules\mongodb\node_modules\kerberos\build\kerberos.vcxproj]
ose\node_modules\mongodb\node_modules\bson\build\bson.vcxproj]

But i had install Python and visual studio 2010 express and Gyp. When i trying to install socket.io i have the same problem...
Answer: VS Express has no x64 build support, so you have a couple of options here:

install the trial edition of the full Visual Studio suite
uninstall 64bit node and use the x86 version
install the Windows SDK

I personally recommend the second (win32 node), since the SDK install is a pain in the back (mostly it fails with no error messages, which "may be" the sign of a "bad" vcredist version), and the full Visual Studio is not that cheap (while the trial is not a permanent solution).
Answer: 32-bit Node reports warnings for bson and kerberos.
I don't understand why is node-gyp even being fired. I thought that native packages come pre-built, with binaries for my OS?
Hmm, I guess I thought wrong.
...
npm http 304 https://registry.npmjs.org/bson/0.2.2
npm http 304 https://registry.npmjs.org/kerberos/0.0.3

> email@example.com install D:\mbo\repos\mean-mbo\node_modules\mongodb\node_modules\kerberos
> (node-gyp rebuild 2> builderror.log) || (exit 0)

D:\mbo\repos\mean-mbo\node_modules\mongodb\node_modules\kerberos>node "C:\Program Files (x86)\nodejs
\node_modules\npm\bin\node-gyp-bin\\..\..\node_modules\node-gyp\bin\node-gyp.js" rebuild

> email@example.com install D:\mbo\repos\mean-mbo\node_modules\mongodb\node_modules\bson
> (node-gyp rebuild 2> builderror.log) || (exit 0)

D:\mbo\repos\mean-mbo\node_modules\mongodb\node_modules\bson>node "C:\Program Files (x86)\nodejs\nod
e_modules\npm\bin\node-gyp-bin\\..\..\node_modules\node-gyp\bin\node-gyp.js" rebuild
  kerberos.cc
  worker.cc
  security_credentials.cc
  security_buffer.cc
  bson.cc
C:\Users\mbo\.node-gyp\0.10.18\deps\v8\include\v8.h(184): warning C4506: no definition for inline
 function 'v8::Persistent<T> v8::Persistent<T>::New(v8::Handle<T>)' [D:\mbo\repos\mean-mbo\node_mod
ules\mongodb\node_modules\kerberos\build\kerberos.vcxproj]
          with
          [
              T=v8::Object
          ]
C:\Users\mbo\.node-gyp\0.10.18\deps\v8\include\v8.h(184): warning C4506: no definition for inline
 function 'v8::Persistent<T> v8::Persistent<T>::New(v8::Handle<T>)' [D:\mbo\repos\mean-mbo\node_mod
ules\mongodb\node_modules\kerberos\build\kerberos.vcxproj]
          with
          [
              T=v8::FunctionTemplate
          ]
C:\Users\mbo\.node-gyp\0.10.18\deps\v8\include\v8.h(179): warning C4506: no definition for inline
 function 'v8::Persistent<T> v8::Persistent<T>::New(v8::Handle<T>)' [D:\mbo\repos\mean-mbo\node_mod
ules\mongodb\node_modules\kerberos\build\kerberos.vcxproj]
          with
          [
              T=v8::Object
          ]
  security_buffer_descriptor.cc
  security_context.cc

Comment: Did you resolved this issue? I have exactly the same problem now. :)
Comment: I didn't want to install *VisualStudio* so I used Ubuntu. The similar thing happens in Ubuntu, but *node-gyp* successfully builds it without any additional installations.
Comment: This helped me get a different error on windows: https://groups.google.com/d/msg/node-mongodb-native/lz3-e1_WZP4/JJETYDDQrMUJ
Answer: Make sure you have all the required software to run node-gyp:

https://github.com/TooTallNate/node-gyp

You can configure version of Visual Studio used by gyp via an environment variable so you can avoid having to set the --msvs_version=2012 property every time you do an npm install.
Examples:

set GYP_MSVS_VERSION=2012 for Visual Studio 2012
set GYP_MSVS_VERSION=2013e (the 'e' stands for 'express edition')

For the full list see
 - https://github.com/joyent/node/blob/v0.10.29/tools/gyp/pylib/gyp/MSVSVersion.py#L209-294
This is still painful for Windows users of NodeJS as it assumes you have a copy of Visual Studio installed and many end users will never have this. So I'm lobbying Joyent to the encourage them to include web sockets as part of CORE node and also to possible ship a GNU gcc compiler as part of NodeJS install so we can permanently fix this problem.
Feel free to add your vote at:

https://github.com/joyent/node/issues/8005#issuecomment-50545326

error MSB007 node.js mongoose


How do I implement a way for the customer to submit a coupon (cart rule) code in PrestaShop 1.6?

Question: I cannot find any ready-made coupon field in the default PrestaShop theme or a controller that takes care of the entire process, but I can find the associated methods in the CartRule class. To avoid having to call the class methods manually one-by-one, is there a controller that takes care of this functionality?
Answer: Field on frontend in shopping-cart.tpl with id discount_name.
On backend ParentOrderController method init handle it.


How to mount the root directory of docker container as a NFS mount point

Question: I'm new to docker, and I'm trying mount the root directory of docker container as a NFS mount point.
for example, I had a NFS mount point test:/home/user/3243, and I'm trying:
docker run -it -v "test:/home/user/3243":/ centos7 /bin/bash

absolutely, it's failed. So I tried this:
mount -t nfs test:/home/user/3243 /mnt/nfs/3243
docker run -it -v /mnt/nfs/3243:/ centos7 /bin/bash

but failed again, so how to do this? Could it be worked out?
Answer: A couple of issues here:

You cannot mount to the root directory of a container. So docker run -v /foo:/ will never work.
With the syntax of your first attempt, -v test:/foo:bar, Docker would see this as wanting to create a "named" volume called "test".

You should be able to first do the NFS mount, then do docker run -v /mnt/nfs/3243:/foo to have the nfs path mounted to /foo.
But again, you can't mount to /.
Comment: Because this would overwrite the entire container fs.
Comment: Thanks for your help! By the way, why cannot mount to the root directory of a container? Is there some documents for this?
Comment: Thanks @cpuguy83! I post my original purpose at [How to run docker container on high available storage like NFS,EBS,flock etc](http://stackoverflow.com/questions/33227359/how-to-run-docker-container-on-high-available-storage-like-nfs-ebs-flock-etc), want to hear from you if possible~
Answer: That is currently discussed (since mid 2014) in issue 4213.
One recent workaround by Jeroen van Bemmel (jbemmel) was:

It appears that NFS functionality depends on the underlying storage driver ( aufs, devicemapper, etc. ), as well as the sharing of file handles between processes ( see blog post "docker: devicemapper fix for "device or resource busy" (EBUSY)") i.e. 'unshare' may have an impact on NFS mounts.
I've moved away from using the 'MOUNTPOINT=/vm/nfs' as I am not sure if that event is even emitted.
Instead I created an upstart file like this:

cat > /etc/init/ecdn.conf << EOF
description "eCDN container"
author "Jeroen van Bemmel"
# mounted MOUNTPOINT=/vm/nfs doesn't seem to work, at least not the first time
start on started docker and virtual-filesystems
stop on starting rc RUNLEVEL=[016]
respawn
script
exec /usr/bin/docker start -a ecdn
end script

pre-stop script
/usr/bin/docker stop ecdn
# dont /usr/bin/docker rm ecdn
end script

EOF

and then create the container like this:

script -c "docker create -it --name='ecdn' --volume /vm:/usr/share/nginx/html/vm:ro image/name"

Comment: Thanks for you answer, I had two important point: use NFS and mount on root directory. I read that issue most aboud NFS mount, do you know how to mount on root directory?


How to read header values in spring batch

Question: Hi currently i have a input xml file. I have to read the xml file and write it to another xml file.I need to have output file should have the same headers as the input file
Input file :
<testFile>
<fileId>string</fileId>
<fileDate>2008-09-29</fileDate>
<fileTime>01:18:33</fileTime>
<sourceSystemId>string</sourceSystemId>
<Delivery>

    <deliveryOrder>
       <consumer>
       </consumer>
       <Data>
       </Datla>
    </deliveryOrder>
<Delivery>
<Delivery>

    <deliveryOrder>
       <consumer>
       </consumer>
       <Data>
       </Datla>
    </deliveryOrder>
<Delivery>
<recordCount>2</recordCount>
 </testFile>

Expected output :
<testFile>
<fileId>string</fileId>
<fileDate>2008-09-29</fileDate>
<fileTime>01:18:33</fileTime>
<sourceSystemId>string</sourceSystemId>
<conusmers>

       <consumer>
       </consumer>
        <consumer>
       </consumer>
        <consumer>
       </consumer>
</consumers>

<recordCount>2</recordCount>
 </testFile>

I am reading rootElement as Deliveryobject. which doesnt have header tags like fileId,FileName,FileTime. How to get headers in output xml file.
Appreciate your help on this.
Comment: Did you find a way to solve this problem? I need to implement something similar. I am thinking if there is any way to store the header data in jobContext, so that it could be accessed in CustomHeaderCallback.
Answer: In your FlatFileItemWriter you can call setHeaderCallback(new StringHeaderWriter("YourHeader"));
Comment: mrkernelpanic , i dont want to compare the headers. I want to have output file headers same as input headers. How the reader/writer should be configured to read and write headers
Comment: Mrkernelpanic, How we are going to pass the values to headerCallback, how we are going to read the header values to pass it to the headercallback.I want to have header values also the same.


Overloading operators in ClearScript

Question: I'm trying to utilize custom operators for arithmetic on custom classes in my application, which is interfaced to with ClearScript. Below is a snippet of my example custom class:
public class Vector3 {
    public float x { get; set; }
    public float y { get; set; }
    public float z { get; set; }

    public Vector3(float x, float y, float z) {
        this.x = x;
        this.y = y;
        this.z = z;
    }

    public static Vector3 operator +(Vector3 a, Vector3 b) {
        return new Vector3(a.x + b.x, a.y + b.y, a.z + b.z);
    }
}

My ClearScript engine is initialized properly, and I can correctly initialize Vector3 objects through Javascript, and modify the properties accordingly.
However, if I initialize 2 Vector3 objects in the Javascript environment, and attempt to use the Javascript addition operator, it ends up evaluating the addition operator as string concatenation, not my custom operator.
Example:
var a = new Vector3(1, 1, 1);
var b = new Vector3(0, 2, -1);

var c = a + b;

print(typeof a); //returns "function" (which is correct)
print(typeof b); //returns "function" (which is also correct)

print(typeof c); //returns "string" (should return function)

The variable c only contains the string ([object HostObject][object HostObject]), instead of the Vector3 object.
How do I let the Javascript engine know to call my custom operator instead of using the default Javascript operators using ClearScript?
Answer: JavaScript's + operator returns the result of numeric addition or string concatenation. You can't overload it. Objects can override valueOf and/or toString to affect operand conversion, but there's no way to override the operation itself.
If you can't call your custom operator directly from JavaScript, try adding a normal method that wraps it:
public Vector3 Add(Vector3 that) { return this + that; }

Then, in JavaScript:
var c = a.Add(b);

It isn't as elegant, but it should work.
Comment: Darn, that's what I thought to be the case but I was hoping there might've been some weird reflection done on ClearScript's side to make my use case possible. I'll use your solution, thanks!

Overloading operators in ClearScript


Long wait for the first request in the time of authorization or registration of Firebase

Question: I use in my application Firebase Database and at the time of the first request for authorization or registration, I wait for a long time for the data.
The first request takes about 5-6 minutes and sometimes more. I suspect that my app caches all the information from the database and did the cancellation of this action by setting a flag in keepSynced NO.
But even this did not help and I had to wait a very long time. All subsequent requests are quickly and data come instantly. Below is the code that I use on the first request.
self.ref = [[FIRDatabase database] reference];
[self.ref keepSynced:NO];

[self.ref observeEventType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot * _Nonnull snapshot) {

    self.fireUser = [TSFireUser initWithSnapshot:snapshot];
    [self configureController];

}];

code model:
TSFireUser *user = [[TSFireUser alloc] init];

NSString *token = [[NSUserDefaults standardUserDefaults] valueForKey:@"token"];
FIRUser *fireUser = [FIRAuth auth].currentUser;
if(token)
{

    NSString *keyUserData = [NSString stringWithFormat:@"dataBase/users/%@/userData", fireUser.uid];
    NSString *keyToParameters = [NSString stringWithFormat:@"dataBase/users/%@", fireUser.uid];
    NSString *keyToPhotos = [NSString stringWithFormat:@"dataBase/users/%@", fireUser.uid];

    FIRDataSnapshot *fireUser = [snapshot childSnapshotForPath:keyUserData];
    FIRDataSnapshot *fireUserParameters = [snapshot childSnapshotForPath:keyToParameters];
    FIRDataSnapshot *fireUserPhotos = [snapshot childSnapshotForPath:keyToPhotos];

    FIRDataSnapshot *userIdent = fireUser.value[@"userID"];
    FIRDataSnapshot *userName = fireUser.value[@"displayName"];
    FIRDataSnapshot *userEmail = fireUser.value[@"email"];
    FIRDataSnapshot *userPhoto = fireUser.value[@"photoURL"];
    FIRDataSnapshot *dateOfBirth = fireUser.value[@"dateOfBirth"];
    FIRDataSnapshot *age = fireUser.value[@"age"];
    FIRDataSnapshot *location = fireUser.value[@"location"];
    FIRDataSnapshot *gender = fireUser.value[@"gender"];
    FIRDataSnapshot *online = fireUser.value[@"online"];
    FIRDataSnapshot *parameters = fireUserParameters.value[@"parameters"];
    FIRDataSnapshot *photos = fireUserPhotos.value[@"photos"];

    user.uid = (NSString *)userIdent;
    user.displayName = (NSString *)userName;
    user.email = (NSString *)userEmail;
    user.photoURL = (NSString *)userPhoto;
    user.dateOfBirth = (NSString *)dateOfBirth;
    user.age = (NSString *)age;
    user.location = (NSString *)location;
    user.gender = (NSString *)gender;
    user.online = (NSString *)online;
    user.parameters = (NSMutableDictionary *)parameters;
    user.photos = (NSMutableArray *)photos;

}

I would be grateful for any provided assistance.
Answer: Is the first code you posted, the call to observeEventType, the code that is taking a long time to complete? And what does the configureController method do? Does it do any UIKit code, like setting up a view controller or view objects?
Does FireBase call it's completion handlers on a background thread? (You can either check the docs or test it by reading the value of Thread.isMainThread inside your completion handler.
Comment: Method [self configureController]; configures the controller, sets the user avatar and adds all the parameters labels. Name, age, sex and place of residence user. You offer to run the code in a background thread, asynchronously. But then the controller would be empty a 5 minute ... If I understood you correctly...


Exception in Nested StreamWriter and StreamReader

Question: I have 2 pieces of code.
Take a look at this one.
static void Main(string[] args)
    {
        using (FileStream fs = new FileStream("temp.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite))
        {
            using (StreamWriter writer = new StreamWriter(fs))
            {
                writer.WriteLine("Hello World");
                using (StreamReader reader = new StreamReader(fs))
                {
                    Console.WriteLine(reader.ReadToEnd());
                } // Line-1
            } //Line-2 -> System.ObjectDisposedException: 'Cannot access a closed  file.'
        }
    }

At the Line-2 I get System.ObjectDisposedException occurs.
Why do I get this exception here?
After a little bit of thinking I thought that the exception occurred at Line-2 because the Stream associated with reference 'fs' is already closed at Line-1. And at Line-2 it is trying to close the same stream again. And this answer made sense. Hence, I thought I had found the right answer to my question but then I tried something a little bit different.
Now look at this piece of code.
static void Main(string[] args)
    {
        using (FileStream fs = new FileStream("temp.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite))
        {
            using (StreamReader reader = new StreamReader(fs))
            {
                Console.WriteLine(reader.ReadToEnd());
                using (StreamWriter writer = new StreamWriter(fs))
                {
                    writer.WriteLine("Hello World");
                } // Line-1
            } // Line-2 -> No Exception occurred.
        }
    }

In this piece of code I didn't get any exception. Even though I am doing the same thing again. Here also the stream associated with reference 'fs' is already closed at Line-1 and it is also trying to close the stream at Line-2.
So why didn't I get any exception here?
My question is different from this Is there any way to close a StreamWriter without closing its BaseStream? because I am trying to do the same thing with the second code and despite the fact (in second code) that using statement already closed the base stream (fs) in Line-1. I still don't get any exception in Line-2.
Since @mjwills and @evk said the exception occurred because of flushing the contents of the stream after the file had been closed.
I tried this.
static void Main(string[] args)
    {
        using (FileStream fs = new FileStream("temp.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite))
        {
            using (StreamWriter writer = new StreamWriter(fs))
            {
                writer.WriteLine("Hello World");
                writer.Flush(); // Flushed the contents explicitly.
                using (StreamReader reader = new StreamReader(fs))
                {
                    Console.WriteLine(reader.ReadToEnd());
                } // Line-1
            } // Line-2 -> System.ObjectDisposedException: 'Cannot access a closed  file.'
        }
    }

And the result is same I still have that exception even though I have explicitly flushed the contents. Please help.
Comment: Possible duplicate of [Is there any way to close a StreamWriter without closing its BaseStream?](https://stackoverflow.com/questions/2666888/is-there-any-way-to-close-a-streamwriter-without-closing-its-basestream)
Comment: Problem is not in closing file multiple times. You can call Close\Dispose on FileStream multiple times with no issues. But you can't read\write to file after it has been closed, which includes flushing contents from buffer to disk - that's what happens in your first example (while in second example there is nothing to write\read on second close).
Comment: Yes but difference is - `StreamWriter` will try to flush on close anyway. This try (even if there is nothing to flush really) is rejected when file is closed. `StreamReader` on the other hand does not try to flush anything (it's reader after all).
Comment: I am saying I have tried to flush the writer before entering the StreamReader's using block.
Comment: @Evk I called the the flush explicitly before even entering the StreamReader's using block.
Comment: Thanks @Evk I got your point.
Comment: I think part of the issue here Learner is that you are looking at two 'wrong' ways of doing things, and asking 'why does Wrong Way A not work, when Wrong Way B did work'. I suggest you are thinking about the problem the wrong way around. Both Wrong Ways are ill advised - since you are interacting with an object that you **know** to be disposed. There are good (underlying) reasons why Wrong Way B did work, and Wrong Way A didn't (as per my and @Evk's comments) - but they are implementation details at best. _The right direction is to stop interacting with disposed objects._
Answer: StreamWriter's Dispose method flushes to disk.
StreamReader's Dispose method does not (why would it? it is just a reader...).
As such, it is "kind of" safe to dispose the writer then the reader (in the sense that it works), but not vice versa.
Consider using leaveOpen on your StreamWriter and StreamReader to avoid this class of problem. By using leaveOpen, you are then able to manually Dispose the Stream which means you can be 100% confident the code will work - and not have to concern yourself with flushing behaviour etc etc.
Comment: Thanks for you opinion


Formatting Time-series data for Cross-correlation

Question: In an experiment we measured 100 response times for each subject. The data has the following format:
ID    Trial    ResponseTime    ResponseTime(Z)
1     1            1000             ...
1     2            1200
1     3            1100
.     .               .
.     .               .
.     .               .
2     1             700
2     2             900
2     3             800

In SPSS I would like to compute the cross-correlation between participants' performance for the (z-transformed) time series:
Trial (x)    1    2    3
ID1 (y1)    1000 1200 1100
ID2 (y2)    700   900  800

Upon visual inspection the time-series appear similar but lagged. I wish to use the SPSS cross-correlations command, but need to reformat the data prior to input to allow comparisons across trials between subjects. How should I reformat the data?
Solutions in SPSS, R, or MATLAB are welcome.
Answer: The solution was to use the Restructure command:
SORT CASES BY Trial .
CASESTOVARS
    /ID=Trial
    /GROUPBY=VARIABLE.