Ionic 3 - image loader not working for firebase storage images

Question: I am using the Ionic image Loader plugin to cache and load images within my app
https://github.com/zyra/ionic-image-loader

This works fine when the image is not from my firebase storage, however when it is the download URL provided by firebase storage - it fails to loads and gives me a useless error on the xcode console.
ERROR: ERROR [object Object]

This problem is limited to the app running on the physical IOS device, but on chrome, it is absolutely fine.
MODULE.TS FILE
import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { EditSkillPage } from './edit-skill';
import { IonicImageLoader } from 'ionic-image-loader';

@NgModule({
  declarations: [
    EditSkillPage,
  ],
  imports: [
    IonicPageModule.forChild(EditSkillPage),
    IonicImageLoader,
  ],
})
export class EditSkillPageModule {}

Comment: Can you add more code? your line here doesn't look right: ` that you put in the question, you are missing the ending `"`
Comment: @SergeyRudenko the npm package, once installed, handles everything - all that is required to have it working is the 'img-loader' tag and the ImageLoader in the module.ts file - as i stated, it all works fine for any image, apart from the images from firebase storage
Comment: Debug your src, isn't the full path of the image...Go deeper
Comment: Possible duplicate of [Ionic 3 + Firebase Storage Get Profile Image](https://stackoverflow.com/questions/46864505/ionic-3-firebase-storage-get-profile-image)
Answer: It works for me (With firebase storage):

The doc is pretty clear.


Should I play G or G# for this note?

Question: This piece is in C# minor, which means that it has 4 sharps, F#, C#, G# and D#. While practising, I came across this note: F double sharp. It seems like an obvious answer at first: I should play G. However, I have two music teachers, both of whom are professionally trained musicians. Let them be teachers A and B. A told me to play G#, while B told me to play G. Teacher A said that I should play G# due to the F# in the key signature, while B told me that I should ignore the key signature in front while playing this. Who should I listen to? And what note should I play?
Comment: Also, fire teacher A
Comment: Agreed, fire teacher A.
Comment: Please at very least show this Q&A to teacher A.
Comment: So, if i play with 1 sharp, and the composer deceded to add a single sharp in front of an F as a mnemonic, teacher A would play a G instead?
Comment: Teacher A may be a decent, kind person with a rich and complex emotional life, who has maintained a cheerful disposition whilst struggling selflessly through remorseless adversities any one of which might have turned you and me into vindictive beasts baying for his or her dismissal over a *semitone*. A **semitone**!
Comment: @OldBrixtonian Uhhh? Teacher A is probably better suited to teaching beginners who are not working on pieces with double-sharps, also teacher A seems to not be qualified to teach piano if they don't even know how to read a double sharp, and finally one student probably only makes up 1/20th of teacher A's income at the most, so it's not like we're advocating teacher A be made destitute or something. And teacher B (and all the other **qualified** teachers out there) deserve the income from teacher A's students because they know what a double sharp is!
Comment: @Todd Wilcox I know, Todd. My comment was not to be taken seriously.
Answer: You should play an F doublesharp, which is enharmonically equivalent to a G.
This is because accidentals are not cumulative; the doublesharp does not raise the F♯ by two half steps, but rather it replaces the single sharp already present on the F. Thus you should play F raised by two half steps, which is enharmonic to G.
And as it turns out, this F doublesharp will likely end up resolving to a succeeding G♯, so playing the F doublesharp as a G♯ will ruin this chromatic effect.
Answer: Two TEACHERS?   One of them shouldn't really be teaching!
Key signatures and accidentals aren't cumulative.   Fx is two semitones above F, whether the key signature includes F sharps, F naturals or F flats (it COULD happen!  Just...)

Sometimes it's convenient to spell Fx as G.  Usually, this will do no practical harm to the music.  Though, paradoxically, it might make the score harder to read!
Answer: Your one teacher's logic says since it's become a G, and that's sharp in the key sig. it needs to be played as G♯. That teacher needs to find a teacher! Possibly listening to the suggestion being played is enough to prove him wrong!
The other says play a G. That's not strictly correct either. You're playing Fx (F♯♯), which happens to live where G lives, but it's never going to be a G. It'll always, in that piece, be some sort of F.
Any accidental is what it is - telling what the next note actually is, overriding anything before, including the key signature, along with any other same pitch notes in that bar. Sounds like a good opportunity to consider unusual accidentals - double flats, why C♭ is the same place as B, etc.
Comment: "not strictly correct," true, but it is nonetheless a useful if imprecise way of saying "F-double-sharp is enharmonically equivalent to G."
Comment: Point taken, but I still maintain that "play G" is not all bad.  It's certainly better than "play G♯."
Comment: @phoog - say that by all means. Do not say 'play G'.

Should I play G or G# for this note?


Dynamic CSS with AnguarJS / Ionic Framework

Question: I need set a custom style of dynamics div.
Div are conforms to the balise :

{{letter}}

The color of each letter must be defined in function of a level and by the value of the index that are declared in an array. I have three levels (low, medium, high), so the low-style, the medium-style and the high-style. The array can be for example: ['color': 'white', 'border-color': 'blue', ..., 'color': 'white', 'border-color': 'red']. For each letter there are an element of the array.
Could you suggest a smart solution for this case ?
Thanks
EDIT: The variables used in the controller are:
var word = getWord(objectWord, getLanguage());
$scope.letters = word.split('');
$scope.level = getLevelCSS(getLevel());
var arrStyles = getStyles(letters.length);

Comment: Can you add arrays/object you are working with? What you posted is not valid. Post `letters` array.
Answer: You could pass your ng-style a directive function like this

And the directive would look smth like this
.directive('colordirective', function (Ls) {
         return function (scope, element, attr) {

             scope.changetheColor = function (level, color) {
                   if(level == 'medium'){

                    return color;

                    }else if(level == 'high'){

                        return color;

                    }
        }
    }

})

If u want u can pass the Level and the style info from the array and return it in the directive
Comment: Could you be more specific about ? Thanks
Comment: well the changetheColor function is called for every element which has "colordirective" so when u for example ng-repeat over some array every element gets the color depending on the "style-level" (medium - high....)
Comment: you said every letter has an array element so basicly every letter would get a different color depending on the level in my example medium would be green and high would be red
Comment: I need pass the level info and the array of styles. Both parameters are important for me
Comment: i just changed my answer so u need to pass the level and the colorinfo to the directive function and there u just return the colorinfo depending on the style-level


Nginx: Cache uWSGI as accessible files

Question: I'm still pretty new to Nginx, but I know that it serves static files very well. For this reason I want to use Nginx together with TileStache as a map server.
TileStache has got a WSGI application that should work well with Nginx's uWSGI module (haven't tested yet). The map tiles should be cached as static PNG files that could be delivered directly to the user, I'm not sure how though.
How far have I come to achieve this, or have I taken the wrong path?
Answer: I was wrong. Nginx supports the protocol, but doesn't seem to have its own application. Now I'm using Gunicorn as a middleman, and it works very well.

Nginx: Cache uWSGI as accessible files


Probabilistic Proof of $\prod\limits_{i=1}^\infty\cos\left(\frac t{2^i}\right)=\frac{\sin t}t$

Question: Using probability methods (characteristic function?) prove
$$\prod_{i=1}^\infty\cos\left(\frac t{2^i}\right)=\frac{\sin t}t$$
I know what is characteristic function but I have no idea how use it in this task. I will grateful for help.
Comment: @GuyFsone:  As far as I can tell, there's not a probabilistic method in that proposed duplicate.
Answer: Consider the following variable
$$
Y=\sum_{j=1}^{\infty}X_j2^{-j}
$$
where $X_i$'s are i.i.d. unbiased Bernoulli$\{-1,1\}$. The characteristic function of the right hand side turns out to be
$$
\prod_{j=1}^{\infty}\cos(t2^{-j})
$$
On the other hand you can convince yourself that $Y$ is Uniform$(-1,1)$ (I am not doing this part of the proof, but you can think of Uniform measure as a ''uniform" binary expansion.)
Then the characteristic function of $Y$ is
$$
\int_{-1}^{1}\frac{e^{itx}}{2}dx=\frac{e^{it}-e^{-it}}{2it}=\frac{\sin (t)}{t}
$$
and we are done.
Comment: For Bernoulli times $2^{-j}$, the characteristic function is $\phi(t) = 1/2(e^{it2^{-j}} + e^{-it2^{-j}}) = cos(t2^{-j})$
Answer: Hint:
Let $b\in\mathbb{N}$, $b\ge2$, $Y=\{0,1,...,b-1\}$ with fair probabilities assigned, and let $F:Y^\infty\to[0,1]$ be the map defined by
$$F(x_1,x_2,x_3,...)=\frac{x_1}b+\frac{x_2}{b^2}+\frac{x_3}{b^3}+..., \text{for all}~(x_1,x_2,x_3,...)\in Y^\infty;$$
that is, $F=\sum_{n=1}^\infty\frac1{b^n}f_n$ where $f_n=\sum_{k=1}^{b-1}k\chi_{A_{nk}}$ and $A_{nk}=Y\times...\times Y\times\{k\}\times Y^\infty$
with ${k}$ in the $n$th spot. If $\mu:\mathcal{S}(\mathscr{C})\to[0,1]$ is the infinite product measure, then
$A\in\mathscr{B}$  if and only if $F^{-1}(A)\in\mathcal{S}(\mathscr{C})$, in which case $\mu(F^{-1}(A))=\mathfrak{m}(A)$.
Use this result and show that $f:[0,1]\to\overline{\mathbb{R}}$ is Borel
measurable if and only if $f\circ F:Y^\infty\to\overline{\mathbb{R}}$ is Borel measurable, and
$$\int_{[0,1]}f(x)dx=\int_{Y^\infty}f\circ F~d\mu\tag{*}$$
provided $f$ is nonnegative or integrable; in particular, it holds when $f:[0,1]\to\mathbb{C}$ is integrable.
Fix $z\in\mathbb{C}$. Then applying (*) to the function $f(x)=e^{2zx}$, prove that
$$e^z\frac{\sinh z}z=\lim_{N\to\infty}\int_{Y^\infty}\prod_{n=1}^N e^{2zf_n/b^n}d\mu$$
Write $\prod_{n=1}^N e^{2zf_n/b^n}=\prod_{n=1}^N\prod_{k=1}^{b-1}e^{2zk\chi_{A_{nk}}/b^n}$ as a simple function and use the
formula to compute $\int_{Y^\infty}\prod_{n=1}^N e^{2zf_n/b^n}d\mu$. Deduce the very interesting formula
$$e^z\frac{\sinh z}z=\prod_{n=1}^\infty\prod_{k=1}^{b-1}\left(1+\frac{2e^{kz/b^n}}b\sinh\left(\frac{kz}{b^n}\right)\right)$$
With $b=2$ and $z=it$, prove that
$$\frac{\sin t}t=\prod_{n=1}^\infty\cos\left(\frac t{2^n}\right)$$
Answer: I don't know if it answers your question since I don't use characteristic function. By using
$$ \sin(2\theta)=2\sin\theta\cos\theta $$
one has
\begin{eqnarray}
\prod_{i=1}^n\cos\left(\frac t{2^i}\right)&=&\cos\left(\frac t{2}\right)\cos\left(\frac t{2^2}\right)\cdots\cos\left(\frac t{2^{n-1}}\right)\cos\left(\frac t{2^n}\right)\\
&=&\frac{\cos\left(\frac t{2}\right)\cos\left(\frac t{2^2}\right)\cdots\cos\left(\frac t{2^{n-1}}\right)\cos\left(\frac t{2^n}\right)\sin\left(\frac t{2^n}\right)}{\sin\left(\frac t{2^n}\right)}\\
&=&\frac{\cos\left(\frac t{2}\right)\cos\left(\frac t{2^2}\right)\cdots\cos\left(\frac t{2^{n-1}}\right)2\cos\left(\frac t{2^n}\right)\sin\left(\frac t{2^n}\right)}{2\sin\left(\frac t{2^n}\right)}\\
&=&\frac{\cos\left(\frac t{2}\right)\cos\left(\frac t{2^2}\right)\cdots\cos\left(\frac t{2^{n-1}}\right)\sin\left(\frac t{2^{n-1}}\right)}{2\sin\left(\frac t{2^n}\right)}
\end{eqnarray}
and continue doing this, one has
\begin{eqnarray}
\prod_{i=1}^n\cos\left(\frac t{2^i}\right)
&=&\cdots\\
&=&\frac{\cos\left(\frac t{2}\right)\sin\left(\frac t{2}\right)}{2^{n-1}\sin\left(\frac t{2^n}\right)}
&=&\frac{\sin t}{2^{n}\sin\left(\frac t{2^n}\right)}.
\end{eqnarray}
Thus
$$ \prod_{i=1}^\infty\cos\left(\frac t{2^i}\right)=\lim_{n\to\infty}\prod_{i=1}^n\cos\left(\frac t{2^i}\right)=\lim_{n\to\infty}\frac{\sin t}{2^{n}\sin\left(\frac t{2^n}\right)}=\frac{\sin t}{t}.$$
Comment: Maybe it would be useful if you explain how you managed the third equation.
Comment: @NathanaelSkrepek, see the update.
Comment: great! very elegant solution.
Comment: Did you evaluate the limit using Taylor Series?
Comment: I used $\lim_{x\to0}\frac{\sin x}{x}=0$.


Como separar o titulo e o conteudo em html?

Question: <!DOCTYPE html>

    <title> Meu teste </title>
    <meta charset="utf-8">

 Meu titulo

 Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse quis velit a libero pretium fringilla in vel eros. Fusce vitae metus sit amet nisi consectetur semper. Duis et sem vitae dolor iaculis eleifend in vel lorem. Morbi egestas blandit turpis, dignissim vulputate metus eleifend non. Phasellus consequat erat eget justo ullamcorper, eu accumsan lacus facilisis. Donec hendrerit non nibh scelerisque aliquam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Nullam posuere massa ac porttitor aliquam. Vivamus tempus nibh mi. Duis eros erat, fringilla vitae ligula quis, mollis laoreet diam. Quisque tempus dolor in risus vehicula interdum. Sed suscipit leo a sagittis pellentesque. Nunc sed vulputate dolor. Proin convallis iaculis condimentum. Suspendisse finibus feugiat nisl sollicitudin dapibus. Nunc euismod, felis ut cursus scelerisque, lectus lorem sollicitudin nunc, vel posuere diam erat eget leo.

Eu estava querendo criar um menu que move junto com a página quando navegamos pelo site movendo com o mouse, porém, ao adicionar o position:fixed o conteúdo fica dentro do titulo. Como faço para deixar tudo em ordem,tipo, o titulo lá em cima, e o conteudo em baixo sem uma ficar entrando dentro da outra? Qual tag utilizo?
Comment: Já cogitou colocar `margin-top` no elemento do conteúdo?
Answer: Aí é preciso adicionar vários estilos, tanto no título quando na página:

html, body{
   margin: 0;
   padding: 0;
}

#titulo {
   background-color: blue;
   position:fixed;
   display: block;
   width:100%;
   margin: 0;
}
#conteudo{
 padding-top: 40px;
}

 Meu titulo

 Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse quis velit a libero pretium fringilla in vel eros. Fusce vitae metus sit amet nisi consectetur semper. Duis et sem vitae dolor iaculis eleifend in vel lorem. Morbi egestas blandit turpis, dignissim vulputate metus eleifend non. Phasellus consequat erat eget justo ullamcorper, eu accumsan lacus facilisis. Donec hendrerit non nibh scelerisque aliquam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Nullam posuere massa ac porttitor aliquam. Vivamus tempus nibh mi. Duis eros erat, fringilla vitae ligula quis, mollis laoreet diam. Quisque tempus dolor in risus vehicula interdum. Sed suscipit leo a sagittis pellentesque. Nunc sed vulputate dolor. Proin convallis iaculis condimentum. Suspendisse finibus feugiat nisl sollicitudin dapibus. Nunc euismod, felis ut cursus scelerisque, lectus lorem sollicitudin nunc, vel posuere diam erat eget leo.

O padding-top pode variar de acordo com a altura esperada do seu título.
Answer: Se você quer separar de cima é so colocar (html):
!DOCTYPE html>

    <title> Meu teste </title>
    <meta charset="utf-8">

 Meu titulo

 Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse quis velit a libero pretium fringilla in vel eros. Fusce vitae metus sit amet nisi consectetur semper. Duis et sem vitae dolor iaculis eleifend in vel lorem. Morbi egestas blandit turpis, dignissim vulputate metus eleifend non. Phasellus consequat erat eget justo ullamcorper, eu accumsan lacus facilisis. Donec hendrerit non nibh scelerisque aliquam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Nullam posuere massa ac porttitor aliquam. Vivamus tempus nibh mi. Duis eros erat, fringilla vitae ligula quis, mollis laoreet diam. Quisque tempus dolor in risus vehicula interdum. Sed suscipit leo a sagittis pellentesque. Nunc sed vulputate dolor. Proin convallis iaculis condimentum. Suspendisse finibus feugiat nisl sollicitudin dapibus. Nunc euismod, felis ut cursus scelerisque, lectus lorem sollicitudin nunc, vel posuere diam erat eget leo.

E pronto mais se quiser em outros lados so colocar margin-left(para esquerda), margin-bottom(pra baixo) e margin-right(pra direita).
Answer: Primeiro, você precisa configurar o menu (#titulo) para ficar no topo e também na camada mais alta das tags (de uma lida sobre z-index). Depois precisa adicionar um espaço no topo do  para deixar o texto "aparecer" quando abrir o seu site, ele pode ter a altura maior ou igual a altura do seu #titulo.
Eu já sofri bastante com esse tipo de estilo, costumam chamar de sticky header css.

<!DOCTYPE html>

  <title> Meu teste </title>
  <meta charset="utf-8">

 Meu titulo

 Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse quis velit a libero pretium fringilla in vel eros. Fusce vitae metus sit amet nisi consectetur semper. Duis et sem vitae dolor iaculis eleifend in vel lorem. Morbi egestas blandit
      turpis, dignissim vulputate metus eleifend non. Phasellus consequat erat eget justo ullamcorper, eu accumsan lacus facilisis. Donec hendrerit non nibh scelerisque aliquam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames
      ac turpis egestas. Nullam posuere massa ac porttitor aliquam. Vivamus tempus nibh mi. Duis eros erat, fringilla vitae ligula quis, mollis laoreet diam. Quisque tempus dolor in risus vehicula interdum. Sed suscipit leo a sagittis pellentesque. Nunc
      sed vulputate dolor. Proin convallis iaculis condimentum. Suspendisse finibus feugiat nisl sollicitudin dapibus. Nunc euismod, felis ut cursus scelerisque, lectus lorem sollicitudin nunc, vel posuere diam erat eget leo.

Comment: Obrigado man :D


Splitting fields and Conjugate fields of Number Fields

Question: Let $f$ be a monic irreducible polynomial of degree $n$ over $\mathbb{Z}[x]$. This means that $K:=\mathbb{Q}[x]/f(x)$ is a number field.
Let $\theta_1:=\theta,\theta_2,\ldots,\theta_n$ be all roots of $f$, then $K\cong \mathbb{Q}(\theta)$ and all conjugate fields $K_i:=\mathbb{Q}(\theta_i)$, for $2\leq i\leq n$ are also isomorph to $K$. On the other hand, $L:=\mathbb{Q}(\theta_1,\theta_2,\ldots,\theta_n)$ is the splitting field of $f$ over $\mathbb{Q}$.
We also know that $L=\mathbb{Q}(\gamma)$ for a primitive element $\gamma$. Does is mean that $L\cong K\cong K_i$, for $2\leq i\leq n$ through natural automorphisms of type $\gamma\mapsto\theta_i$? Is this the case only for algebraic number fields? Does this imply that all such $K$ are Galois extensions of $\mathbb{Q}$?
Comment: If you meant $\;K_i\cong\Bbb Q(\theta_i)\;$ (you didn't define it), then $\;K\cong Ki\;$ for all $\;i\;$, but of course **not necessarily** $\;L\cong K\;$ . And who told you that $\;\gamma\mapsto\theta_i\;$ is an automorphism and even more "natural"?
Comment: Concretely, if $K_i =\mathbb Q(\zeta_3^i \sqrt[3]2)$ (where $\zeta_3^3 =1$), then $\gamma$ would be something like $\zeta_3 + \sqrt[3]2$. The map sending $\zeta_3+\sqrt[3]2\mapsto \sqrt[3]2$ is most certainly not an homomorphism of fields.
Comment: @DonAntonio Yes I meant $K_i:=\mathbb{Q}(\theta_i)$, now edited. And for your other question, I just thought that I can simply send $\gamma$ to $\theta_i$, which apparently is not true in terms of degrees of extension.
Comment: @Mathmo123 Thanks for the example, although one should be careful with the index $i$ that I defined in the question and what you have in your exaple.
Comment: @Luckyluck63 Indeed you can't: remember we're talking of "embeddings" over $\;K\;$ into an algebraically closed field containing $\;\Bbb Q\;$ , so any element must be mapped to a root of its minimal polynomial.
Answer: If $K_i \cong \mathbb{Q}(\theta_i)$, then you are correct in that $K \cong K_i$ for all $i$.  We do not have $L \cong K_i$ in general.

Consider any field $F$.  We can view $F$ as a vector space over the smallest subfield of $F$ containing $1$ (call it $F'$).  Now suppose we have an isomorphism $\phi: F \rightarrow F_1$.
Claim: $[F:F'] = [F_1:F']$.
Proof:  As with any linear map between vector spaces, $\phi$ is determined by its action on a set of basis vectors in $F$, say $\{\alpha_i\}_{i=1}^n$.
Since $\phi$ is injective, it must map the $\alpha_k$'s to a set of linearly independent elements $\{\beta_i\}_{i=1}^n$ in $F_1$.  Otherwise, if the $b_k$'s were linearly dependent, we could write $c_1\beta_1 + \cdots + c_n\beta_n = 0$ for $c_k \in F'$ not all zero.  By linearity, this would mean $\phi$ maps $c_1\alpha_1 + \cdots + c_n \alpha_n$ to $0$, contradicting injectivity since $0$ itself maps to $0$.
Further, since the $\alpha_k$'s are independent and span $F$, it is clear that the set $\{\beta_i\}$ spans $\text{Image}(\phi) = F_1$ per linearity.  Therefore, the dimension of $F$ over $F'$ equals the dimension of $F_1$ over $F'$.  In other words, $[F:F']=[F_1:F']$.  $\qquad \blacksquare$

In the given scenario, $F' = \mathbb{Q}$.  Let's look at a concrete example: $f(x) = x^3 -2$, which is irreducible over $\mathbb{Z}$.  It's roots are $\sqrt[3]{2}, \ \omega \sqrt[3]{2}, \ \omega^2 \sqrt[3]{2}$ with $\omega$ a primitive cube root of unity. If we adjoin a single root, say $\mathbb{Q}( \sqrt[3]{2})$, this yields a degree $3$ extension.  Notice, however, that this field has no non-real elements, whereas the splitting field of $f$ clearly does.  To arrive at a splitting field, we must adjoin at least one more element to $\mathbb{Q}(\sqrt[3]{2})$ -- and the resulting field has degree greater than $1$ over $\mathbb{Q}(\sqrt[3]{2})$.  Per multplicativity of degrees, we see that the splitting field must have greater degree over $\mathbb{Q}$ than $\mathbb{Q}(\sqrt[3]{2})$ has over $\mathbb{Q}$.
Due to the claim above, we thus cannot have an isomorphism between the splitting field and $\mathbb{Q}(\sqrt[3]{2})$.  Further, since $\mathbb{Q}(\sqrt[3]{2}) \cong \mathbb{Q}(\omega^k \sqrt[3]{2})$, indeed we cannot have an isomorphism between the splitting field and $\mathbb{Q}(\theta_i)$ for any of the roots $\theta_i$.


Supabase won't take UPDATE query

Question: I'm currently using supabase to make quick MVP for college work. I create feedback feature, so I have to update some columns in row. There is my JS query:
const { error: updateError } = await supabase.from('route').update({ total_score: 5 }).eq('id', 1);

Getting this error:
screenshot of "preview" page error in dev tools
Error code in dev tools: 400
If you don't want to look at screenshot:
{"code":"21000",
"details":null,
"hint":null,
"message":"UPDATE requires a WHERE clause"}
And zero updates at supabase after this query. I have no idea what to do. I was using this query in my project some time ago, and it was fine. But here - no.
Any ideas how to fix this?
UPD:
Function that calls and update query:
   async function setRating() {
    const rate = range.value.value
    const { error: updateError } = await supabase.from('route').update({ total_score: 5 }).eq('id', 1);

    console.log(updateError);
    // Commented this section cuz update query above doesn't work
    // if (!update_error) {
    //   console.log(update);
    //   route_feedback.value.classList.add('hide')
    //   route_ended.value.classList.add('show')
    //   setTimeout(() => {
    //     route_feedback.value.classList.remove('show')
    //     route_feedback.value.classList.remove('hide')
    //   }, 500);
    // }
  }
  }

RLS Policy on update in supabase:

Policy name: allow_update_on_route
Target roles: public
USING expression: true
WITH CHECK expression: true

Policy name: Authorized users can select from route table
Target roles: public
USING expression: (auth.role() = 'authenticated'::text)

UPD2:
table route defenition:
create table
  public.route (
    id bigint generated by default as identity not null,
    name text null,
    country text null,
    city text null,
    description text null,
    imageName text null,
    created_at timestamp with time zone null default now(),
    total_reviews numeric null,
    total_score numeric null,
    duration numeric not null default '30'::numeric,
    rating double precision null,
    isAdult boolean not null default false,
    constraint route_pkey primary key (id)
  ) tablespace pg_default;

create trigger update_route_rating_trigger
after insert
or
update on route for each row
execute function update_route_rating ();

Without RLS still same error.
update_route_rating function defenition:
 BEGIN
    IF pg_trigger_depth() <> 1 THEN
        RETURN NEW;
    END IF;
   UPDATE route SET rating = ROUND((total_score / total_reviews), 1);
   return new;
END;

Comment: Could you show the entire method for when this update is happening, as well as the RLS policy on your `route`  table?
Comment: I can't post all in comment. Made an UPD in question. Is it okay?
Comment: Made an upd in question*
Comment: Does the `route` table have only update RLS policy, or does it have other policies as well? Could you share all RLS policies applied to the `route` table?
Comment: @dshukertjr, okay. There it is!
Comment: Hmm, since anyone can sign in to your app, and any one can update or view any of the data, your RLS policy is not very secure, but that probably is not the issue here. Have you tested to run the query with RLS turned off?
Comment: Also, could you share the table definition of `route` just in case?
Comment: @dshukertjr made an another upd.
Answer: update_route_rating() function that you have set as the trigger is the cause here.
The following statement within your trigger function is attempting to update every row in your route table, because it does not have any where clause.
UPDATE route SET rating = ROUND((new.total_score / new.total_reviews), 1);

I'm assuming what you want to achieve here is to update the rating column for the newly inserted/updated row. In that case, you could use the following within your trigger function.
begin
    if pg_trigger_depth() <> 1 then
        return new;
    end if;
   new.rating = ROUND((total_score / total_reviews), 1);
   return new;
end;

Comment: Hm, made an another update with that function definition. What do you think?
Comment: @Scheffio Yup, that was precisely the cause. I have updated my answer.
Comment: I guess it helped, but there is another one error `"column \"total_score\" does not exist"`. I additionally checked the code and `route` definition, and `total_score` exist. Have no idea...
Comment: I added `new.` to `total_score` and to `total_reviews`. Now the query is updating the table, but function isn't working. I mean, `new.rating = ROUND((new.total_score / new.total_reviews), 1);` doesn't do any calculations. Column `rating` is the same.
Comment: @Scheffio That seems like a separate question, so it would be nice if you could open another question.
Comment: Sure! Made a new one - [Here it is!](https://stackoverflow.com/questions/76386634/supabase-function-doesnt-do-any-calculations)

Supabase won't take UPDATE query


How do I get apache to load an index file inside a folder from a github repo that is cloned into my EC2 instance?

Question: I've installed apache on my EC2 instance but can't configure my .htacess  to redirect to an index file located inside a folder.
This is what I have:
RewriteEngine on

RewriteCond %{HTTP_HOST} ^[domain name] [NC,OR]
RewriteCond %{HTTP_HOST} ^[domain name]
RewriteCond %{REQUEST_URI} ![repository folder]/
RewriteRule ^(.*)$ /[repository folder]/$1 [L]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.html -f
RewriteRule ^(.*)$ $1.html`

I was trying to have the index.html file that's located in the repository folder to be used as the index page.
Answer: If you configure your Apache  document root to be the repository folder, no redirect is needed. Be sure to set your default index file to be index.html (probably the default).
<VirtualHost *:80>
   DocumentRoot "/home/git/public_html/my_repo_name"
   ServerName www.mydomain.com
   DirectoryIndex index.html
</VirtualHost>


Retornar array ASP 3 e popular select com each JQUERY

Question: Preciso popular um select (Html). Acredito que o passo seria esse, mas como fazer? Alguém tem um link que possa me direcionar?

Clicar no select (OnChange talvez)
Colocar os dados da Query (Consulta) em ASP nesse Array
Retornar esse Array para JQUERY e popular através do Each.

O foda é, como criar esse array em ASP 3, e como passar para o JQUERY e ler através do Each.
Alguém me dá uma luz de como fazer?
Comment: O que seria enviado pelo Ajax?
Comment: @sam enviado ou trazido pelo ajax? Enviado uma página asp, trazido dois campos dentro de um array para eu dar o loop com each no Jquery. Seria para popular um select.
Comment: Me parece que seu problema é mais na criação do array em ASP, porque o resto é bem simples.
Comment: @sam os dois. Tô pesquisando aqui como colocar os dados de uma query no array (ASP), tá difícil de achar algo. Primeiro tenho que resolver isso, depois penso na parte do JQUERY.
Comment: Esse array que espera seria um array simples, tipo: `array("item 1","item 2",...)`?
Comment: @sam então, não sei como tem que ficar, para dar certo lá no Jquery.
Comment: Vamos [continuar esta discussão no chat](https://chat.stackexchange.com/rooms/80454/discussion-between-sam-and-rod).
Comment: @sam de eu achasse algo parecido em php, talvez me desse uma luz.
Comment: @sam dá uma olhada no chat
Comment: @sam falei com vc no chat. rs
Answer: Você pode chamar o Ajax clicando no select e passar o id do select clicado como parâmetro na URL a ser requisitada. Desta forma você pode controlar quais informações serão enviadas pelo ASP com request("id").
Crie um evento click que irá detectar o clique no select e enviar via $.get o id do respectivo elemento. O retorno do ASP (veremos mais a frente) irá retornar objetos com dois valores cada, separados por vírgula, onde um valor será o value e o outro o texto das option a popularem o select clicado.
No retorno do Ajax você converte esses objetos em array JSON com o método JSON.parse(), e usando $.each você monta o HTML das option. Após o $.each basta você jogar o HTML montado para dentro do select com .html().
Demais explicações nos códigos.
Exemplo do select com uma id:
<select id="cursos"></select>

Código do evento e do Ajax:
$('select').click(function(){ // evento click
   // este if verifica se o select já foi populado
   // evitando que ele seja populado mais de uma vez
   // ao ser clicado
   if(!$('option', this).length){
      $(this).prop("disabled", true); // desabilita o select
      var id = this.id; // pega o id do select
      var url_ = 'pagina.asp?id='+id; // monto a URL do Ajax passando o id como parâmetro para o ASP

      $.get(url_, function(data){
         // aqui é o retorno do Ajax
         data = data.replace(/,$/, ''); // removo a última vírgula que virá
         data = JSON.parse('[' + data + ']'); // converto os objetos em array JSON
         var opts = ''; // declaro a variável que irá montar o HTML das options
         $.each(data, function(index, item) {
            // monto as options concatenando os valores de cada objeto
            opts += '<option value="'+item.id+'">'+item.campo+'</option>';
         });

         $('#'+id).html(opts) // envio o HTML montado para o devido select
         .prop("disabled", false); // habilita o select novamente
      });
   }
});

Troque pagina.asp pela sua página ASP.

Montando os objetos no ASP e retornando para o Ajax:
No ASP você recebe o id enviado pelo Ajax com request("id"), e de acordo com o valor recebido, você monta a query ao banco de dados.
Faça o loop normal da consulta ao banco e coloque o response.write dentro desse loop montando os objetos que serão enviados para o Ajax. Exemplo:
<%
conn = conexão com o banco
set rs = conn.execute(aqui a sua query)
if not rs.eof then
   while not rs.eof
      response.write("{""id"":"""& rs("coluna_id") &""",""campo"":"""& rs("coluna_campo") &"""},")
   rs.movenext
   wend
end if
rs.close
set rs = nothing
%>

A página ASP deverá ter apenas o código acima. Não é uma página normal
  com tags.
Comment: Funcionou não. Coloquei um link no chat pra vc ver.
Comment: nada ainda, dando um alert antes dessa linha os dados estão vindo.
Comment: vou atualizar o jquery pra ver.
Comment: localhost funcionou uhuuuu. Agora quero ver porque não no server
Comment: precisaria que iniciasse um com valeu=" " (vazio) deixando a opção do usuario de não selecionar nada. Colocando Disciplina (todas) no proprio select não vai, então terei qie fazer isso antes do each no Jquery. É isso?
Comment: não dá, tem que já vir ao carregar a página e não quando clicar no select. tentei colocar no proprio select, mas ai para de trazer.
Comment: porque que ao colocar assim:
Disciplina (todas)
Comment: ele para de trazer, não entendi.
Comment: é por causa do if que eu coloquei rs.... altere para `if($('option', this).length == 1)`... mas tb tem que trocar o `$('#'+id).html(opts);` para `$('#'+id).append(opts);`
Comment: cara, valeu. Vou estudar mais aqui e tentar fazer alguns ajustes. Fazendo essa modificação do if, as vezes ele dá um bug, não carrega, tem que dar dois cliques.
Comment: só uma ultima coisa, qual a função do index na função: function(index, item)?
Comment: Blz... qualquer coisa chama aí. Isso aí que vc está querendo fazer é mamão com açúcar. Não tem que ter bug não. É muito simples: clicou no select, chama o Ajax. Agora o ideal era desabilitar o select até a resposta do Ajax.
Comment: O index é o índice da array, começando do 0
Comment: entendi. valeuuu


How to determine which is the latest hook_update_N() function invoked in a Drupal 7 environment

Question: I have written my first deployment_module for a Drupal 7 site and installed it into a virtual host on my development server.
I would like to check to see if my hook_update_N() functions have been invoked correctly and so am wondering how to determine which is the latest hook_update_N() function invoked in a Drupal 7 environment.
I imagine some Drush command would be easiest way to find out. Failing that, it is probably set in the database somewhere.
Any ideas?
Answer: It's in the system table. This query:
SELECT schema_version FROM system WHERE name='mymodule';

will let you know the last update hook successfully completed.
if you want to use drush, there's drush sql-query
drush sql-query "SELECT schema_version FROM system WHERE name='mymodule'"

Comment: I have tried this and it seems to have worked. Thanks.


How do I install Server Manager on Windows 8 Professional?

Question: I have downloaded and installed Remote Server Administration Tools for Windows 8 on my Windows 8 Enterprise machine.
Online resources suggest installing RSAT should also install Server Manager GUI, but I am unable to find it.
Do I need to perform some additional steps to enable Server Manager?

I have tried researching this, but haven't come across any solutions.
Edit:
Comment: Have you already gone to "Turn Windows Features on or off" and checked under either Role Administration Tools or Feature Administration Tools?
Comment: @Cole I have neither of those. Does this mean RSAT installation did not complete successfully?
Comment: Hm, that does look a bit funny. I'd try a quick reinstall.
Comment: @Cole Tried reinstalling. Installer reports success, but I think it is actually failing quietly. "Programs and Features" contains no mention of RSAT (I have tried searching by name and KB number).
Comment: It looks like this is an issue with language packs. Download the Windows 8 language pack from the TechNet, copy out the cab file for en-US , change the extension to .mlc and run it. Then, the tools should show up.
Answer: I managed to fix this by going to...

Control Panel > Language
Click 'Add a Language'
Select 'English' > 'English (United States)'
Click 'Download'

Then reinstall the Remote Server Administration Tools.
Not too impressed by the lack of error messages!
Answer: After installing the RSAT tools, under Turn Windows Features on or off you should see these options:

It looks like this is a common issue that has to do with language packs. Download the Windows 8 language pack from the TechNet, copy out the cab file for en-US , change the extension to .mlc and run it. Then, the tools should show up once completed.
Link to language pack install.
Then verify that the language pack is installed by running get-windowspackage -online in a Windows PowerShell (Run As Admin)
Comment: I was seeing the same thing on W8Pro with en-gb. Installing the en-us language pack and then re-applying the RSAT update fixed it for me. Thanks!
Comment: It looks like installer is actually failing quietly. "Programs and Features" contains no mention of RSAT (I have tried searching by name and KB number).
Comment: "Link to language pack" actually points to RSAT download page.
Comment: I can see 1 LanguagePack installed: "Microsoft-Windows-Client-LanguagePack-Package~31bf3856ad364e35~amd64~en-GB~6.2.9200"
Comment: You have "en-GB" installed, you need "en-US".
Comment: I could only find a 2GB MultiLanguage pack on MSDN, so I will have to install that later tonight (slow internet connection).


svg creates http instead https on non-absolute URL

Question: I'm using SVG on a page using HTTPS, but SVG creates an HTTP instead of HTTPS link to an image, causing that the browsers treat the page insecure. SVG is used with the following fragment:
<code><svg id="head-image-1000" width="1000" height="130" xmlns="https://www.w3.org/2000/svg" xmlns:xlink="https://www.w3.org/1999/xlink">
    <g>
        <a xlink:href="/">
            <image xlink:href="/layout/panorama-winter-1400.jpg" height="97" width="1000" y="0" x="0"/>
        </a>
    </g>
</svg>
</code>
Is the only possibility to use absolute URL?
Comment: Wild guess: Does the same happen if you use the HTTP namespace URIs (`http://www.w3.org/2000/svg` and `http://www.w3.org/1999/xlink`)? I think it's not correct to use HTTPS here.
Comment: the UA should use the same protocol as the parent document.
Comment: unor is correct. It is incorrect to use https in the namespace values. Those values are defined namespace constants. They are not real URLs.
Comment: Thx. I've set back all `http://www.w3.org` to http.
Comment: My website has these links in the CSS files of plugins. When I complete a scan for links it says "insecure page". I was going to change them, but after seeing this post I didn't. I am wondering if this could affect SSL or your SEO for security, how does google view this link?   All links were HTTP to this site www.w3.org/1999/xlink
Answer: The problem was caused by some caching in the browser (Firefox). After clearing the cache and restarting the browser the image is downloaded with HTTPS.


CentOS 6.3 task blocked for more than 120 seconds

Question: Recently have been getting Zabbix alerts about our mail system being unavailable, the uptime on the machine is 30+ days. I've been tracing the Zabbix logs and it looks like the communication between the Zabbix agent & server failed to respond in time which triggered the alert.
To find out if it was a network issue, etc. I viewed /var/log/messages and found the following entries:
<code>Nov 14 21:48:49 iw kernel: INFO: task zabbix_agentd:3316 blocked for more than 120 seconds.
Nov 14 21:48:49 iw kernel: "echo 0 > /proc/sys/kernel/hung_task_timeout_secs" disables this message.
Nov 14 21:48:49 iw kernel: zabbix_agentd D 0000000000000003     0  3316   3311 0x00000080
Nov 14 21:48:49 iw kernel: ffff880069075c50 0000000000000086 ffffffff817a8d69 ffff880069075c68
Nov 14 21:48:49 iw kernel: ffff880486ea3000 ffff880069075c58 ffffffff8127cb66 0000000000000009
Nov 14 21:48:49 iw kernel: ffff88042085bab8 ffff880069075fd8 000000000000fb88 ffff88042085bab8
Nov 14 21:48:49 iw kernel: Call Trace:
Nov 14 21:48:49 iw kernel: [<ffffffff8127cb66>] ? vsnprintf+0x2b6/0x5f0
Nov 14 21:48:49 iw kernel: [<ffffffff814ffec5>] rwsem_down_failed_common+0x95/0x1d0
Nov 14 21:48:49 iw kernel: [<ffffffff81500056>] rwsem_down_read_failed+0x26/0x30
Nov 14 21:48:49 iw kernel: [<ffffffff8127e664>] call_rwsem_down_read_failed+0x14/0x30
Nov 14 21:48:49 iw kernel: [<ffffffff814ff554>] ? down_read+0x24/0x30
Nov 14 21:48:49 iw kernel: [<ffffffff81140511>] __access_remote_vm+0x41/0x1f0
Nov 14 21:48:49 iw kernel: [<ffffffff81144052>] ? vma_merge+0x1d2/0x3e0
Nov 14 21:48:49 iw kernel: [<ffffffff8114071b>] access_process_vm+0x5b/0x80
Nov 14 21:48:49 iw kernel: [<ffffffff811e295d>] proc_pid_cmdline+0x6d/0x120
Nov 14 21:48:49 iw kernel: [<ffffffff8115c30a>] ? alloc_pages_current+0xaa/0x110
Nov 14 21:48:49 iw kernel: [<ffffffff811e357d>] proc_info_read+0xad/0xf0
Nov 14 21:48:49 iw kernel: [<ffffffff8117b9e5>] vfs_read+0xb5/0x1a0
Nov 14 21:48:49 iw kernel: [<ffffffff810d6b12>] ? audit_syscall_entry+0x272/0x2a0
Nov 14 21:48:49 iw kernel: [<ffffffff8117bb21>] sys_read+0x51/0x90
Nov 14 21:48:49 iw kernel: [<ffffffff8100b0f2>] system_call_fastpath+0x16/0x1b
</code>
Kernel info:
Linux mail 2.6.32-279.2.1.el6.x86_64 #1 SMP Fri Jul 20 01:55:29 UTC 2012 x86_64 x86_64 x86_64 GNU/Linux
Memory info:
<code>             total       used       free     shared    buffers     cached
Mem:         24031      21497       2533          0        606      14562
-/+ buffers/cache:       6328      17702
Swap:        31999         49      31950
</code>
I'm looking for some guidance on where to begin narrowing down the root cause of these issues.
Comment: This is also happening in Ubuntu 11.04 where it blocks vmware-vmx during heavy IO periods.
Comment: Physical or virtual?
Comment: I am reading some of the threads and people start facing this issue after upgrading to RHEL6.3(2.6.32-279),where they initially faced issue with processes writing to NFS device and later on with all processes.The first thing I would prefer is to downgrade the kernel or if that option is not the option there try to disable transparent huge pages which will resolve issue in some cases echo never >/sys/kernel/mm/redhat_transparent_hugepages/enabled.Please test in your test machine before implementing it in PRD env as I am really not sure that will fix your issue.
Comment: Sorry, physical server
Comment: Is this reproducible? E.g. can you force it to happen? What's the system load at the time you see the messages?
Answer: Found this post, not sure if it applies to you or not. http://blog.ronnyegner-consulting.de/2011/10/13/info-task-blocked-for-more-than-120-seconds/
How much CPU do you have? Looks like you have quite a bit of memory (24GB). If the blog post is correct then you system may not be able to dump memory from the cache fast enough to deal with the IO you have coming it.
You can set "vm.dirty_ratio=10″ in /etc/sysctl.conf to force it to flush sooner. This may help your issue.


syntax error, unexpected ( arg, expecting end-of-input )

Question: Me deparei com esse erro de sintaxe:

syntax error, unexpected ( arg, expecting end-of-input )

larguraDaLinha = 40
str = '--> text <--'
puts str.ljust  larguraDaLinha
puts str.center larguraDaLinha
puts str.rjust  larguraDaLinha
puts str.ljust (larguraDaLinha/2) + str.rjust (larguraDaLinha/2)

https://repl.it/KtDA/0
Answer: Falta parênteses nas chamadas da funções. Procure manter o código organizado e dentro de um padrão, assim evita erros assim.
larguraDaLinha = 40
str = '--> text <--'
puts str.ljust(larguraDaLinha)
puts str.center(larguraDaLinha)
puts str.rjust(larguraDaLinha)
puts str.ljust(larguraDaLinha/2) + str.rjust(larguraDaLinha/2)

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Comment: Obrigado pela dica.
Comment: @shxrk veja o **[tour]** a melhor foram de dizer obrigado.


Unable to use setwd() to change directory from absolute to relative pathway

Question: I get 'cannot change working directory' when I try using setwd() to change my working directory from using an absolute pathway (from C:/examplename/Dropbox/Files) to a relative pathway (~/Dropbox/Files)
I am using code that works in a shared Dropbox, and has syntax that uses relative pathways such as:
setwd(paste0("~/Dropbox/Files/", site))

However, when I run this code on my computer, I get an error that the file pathway cannot be found. I think it's because my working directory looks like:
getwd()

however, when I go to change it, I get the following error:
> setwd("~/Dropbox/Files")
Error in setwd("~/Dropbox/Files") : cannot change working directory

I've checked that I use the correct spelling, and I have tried file.path
> setwd(file.path("~","Dropbox","Files"))
Error in setwd(file.path("~", "Dropbox", "Files")) :
  cannot change working directory

I was curious if anyone has any idea why I can't change it? If it matters, the person who wrote the code used a mac and I have a PC.
Comment: I think you finding out that `path.expand("~")` returns `".../Documents"`, and the fact that `"~/Dropbox"` appears to not exist, suggests that you need to either change your path to `"~/../Dropbox/Files"` or update the `HOME`. See https://cran.r-project.org/bin/windows/base/rw-FAQ.html#What-are-HOME-and-working-directories_003f (and/or https://stackoverflow.com/a/53671435/3358272).
Comment: What does `path.expand("~")` return? I think on Windows your "home" directory is actually your desktop. Maybe `setwd("~/../Dropbox/Files")` will work
Comment: path.expand brings up "C:/Users/examplename/Documents" so that may be something I want to fix? Can I change it to direct to the dropbox?
Comment: You say your *"working directory looks like"*: `getwd()` but don't give the output from that command, perhaps you missed something in your copy/paste? Does `dir.exists(c("~", "~/Dropbox", "~/Dropbox/Files"))` return three `TRUE`s? What is your OS?
Comment: When I run dir.exists, I get TRUE FALSE FALSE. And Windows 10. The getwd() comes out as "C:/Users/examplename/Dropbox/Files
Comment: Don't they use these **backslashes** on windows?
Answer: In my case, I work on different computers shared with files shared by Dropbox. It seems to be a similar setup as yours, except that you have different users. Here's a script I use for several projects:
# Initialize environment and load data --------------

run_location <- "work"  # work | laptop | tablet
dropbox_path <- switch(
  run_location,
  "work" = "C:/Dropbox/",
  "laptop" = "S:/Dropbox/",
  "tablet" = "C:/Dropbox/"
)
defaultRFolder <- paste0(dropbox_path, "Travail/R/para")

wd <- paste0(dropbox_path, "Travail/Research/project_path")
setwd(wd)

All I need to change is the value of run_location at the beginning, then the script works based on my location. Here's a modification that might work for you:
run_location <- "windows_user"  # mac_user | windows_user
dropbox_path <- switch(
  run_location,
  "mac_user" = "~/Dropbox/",
  "windows_user" = "C:/examplename/Dropbox/"
)

wd <- paste0(dropbox_path, "Files")
setwd(wd)

So, on your computer, you should set
run_location <- "windows_user"  # mac_user | windows_user

while your colleague should set
run_location <- "mac_user"  # mac_user | windows_user

on theirs. That's the only thing you would need to change for the files to work on your respective computers.


Get created file's path from SaveFileDialog in electron

Question: I am trying to store my created file's path after using SaveFileDialog, here is my code:
    let path;
    dialog.showSaveDialog((fileName) => {
        if (fileName === undefined){
            console.log("You didn't save the file");
            return;
        }

        fs.writeFile(fileName, text, (err) => {
            if(err){
                alert("An error ocurred creating the file "+ err.message)
            }
            alert("The file has been succesfully saved");
        });
    });

What I want to happen is that after the user creates the file he would enter file's path in the variable path, is it even possible?
Comment: are you talking about extension name or absolute path of the select file ?
Answer: you can use the sync version of dialog.showSaveDialog. with the sync version no need for you to declare the path variable without intializing it
   let path = dialog.showSaveDialog( {
        title: "Save file",
        filters: [ { name:"png pictures", ext: [ "png" ] } ], // what kind of files do you want to see when this box is opend
        defaultPath: app.getPath("document") // the default path to save file
    });

    if ( ! path ) {
        // path is undefined
        return;
    }

    fs.writeFile( path , text , ( err , buf ) => {
        if ( err )
            return alert("saved");
        return alert("not saved");
    });

or the async version
  dialog.showSaveDialog( {
        title: "Save file",
        filters: [ { name:"png pictures", ext: [ "png" ] } ], // what kind of files do you want to see when this box is opend, ( users will be able to save this kind of files )
        defaultPath: app.getPath("document") // the default path to save file
    }, ( filePath ) => {
        if ( ! filePath ) {
            // nothing was pressed
            return;
        }

        path = filePath;
        fs.writeFile( path , text , ( err , buf ) => {
            if ( err )
                return alert("saved");
            return alert("not saved");
        });
    });

Answer: You are almost there. You need to wait for the result of the dialog through the callback. Check the docs.
So something like:
let path;

function saveProjectAs(text) {
    var options = {
        title: "Save project as ",
        message: "Save project as ",
        nameFieldLabel: "Project Name:",
        // defaultPath:  directory to show (optional)
    }

    dialog.showSaveDialog(mainWindow, options, saveProjectAsCallback);

    function saveProjectAsCallback(filePath) {
        // if user pressed "cancel" then `filePath` will be null
        if (filePath) {
         // check for extension; optional. upath is a node package.
            if (upath.toUnix(upath.extname(filePath)).toLowerCase() != ".json") {
                filePath = filePath + ".json"
            }

        path = filePath;

        fs.writeFile(path, text, (err) => {
           if(err){
                alert("An error ocurred creating the file "+ err.message)
            }
           alert("The file has been succesfully saved");
         });

        }
    }
}

Comment: Is that the only way to get the selected file's path? isn't there a function to get that without installing other packages?
Comment: Read up on what `upath` does. . .
Answer: this worked for me:
const { dialog } = require('electron')

dialog.showSaveDialog({
    title: "Save file"
}).then((filePath_obj)=>{
    if (filePath_obj.canceled)
        console.log("canceled")
    else
        console.log('absolute path: ',filePath_obj.filePath);
});

Comment: I just have `dialog.showSaveDialog(...).then is not a function` ...


Identify chord in progression

Question: Which chord is G+B+D+E ? It is a G in the bass.
<code>||||||
|*||||
*|||*|
</code>
On guitar it's like above displays. Is it G6?
The bass tones in the progression are A, F, G, A :|| and the progression I try to play is
Amin, Fmaj7, then this G chord that I can't identify. It's like a regular G on guitar but open E instead of G and the thinnest string.
Answer: Yes, it's G6. Basic G major triad (GBD) with the 6th note from the scale added. Seems like there's a progression of chords, with a static E note on the top string.
Comment: Yes. The static E note on the top string is like a "pedal tone" for every chord in the progression.

Identify chord in progression


Get difference of two address of array(use & operator)

Question: I want to get the address difference between two elements in an array.
int vector[] = { 28, 41, 7 };

printf("%d\n", &vector[2]); // 1703652
printf("%d\n", &vector[1]); // 1703648
printf("%d\n", &vector);    // 1703644

printf("%d\n", &vector[1] - &vector); // 1

The result I expect(Last Line) is 4 because the data type was int.
Further, each result of address has 4 differences.
But why is the result of
&vector[1] - &vector

1 and not 4?
And how do I get 4 by using subtraction operator?
Comment: `&vector[1] - &vector` is a type error. The left operand of `-` has type `int *`, but the right operand has type `int (*)[3]` (they need to have the same type).
Comment: `printf("%d\n", &vector[2]);` is a type error. `%d` takes an `int`, not a memory address.
Comment: How does the last one even compi!e?
Answer: pointer arithmetics in C language works on the type of the object. It does not matter how big the object is. The reference to the next object minus reference to the previous is always one object
So if we add 5 to the pointer it will point 5 objects ahead. If we increment the pointer it will reference the next object. It helps indexing and iterating across the objects.
When you printf the address (your format is wrong - you should use %p instead) it is printed in bytes. So the difference between the consecutive objects will be equal the size of the object (plus the optional padding).

And How to I get 4 by using subtraction operator???

Cast the pointers to the type which sizeof is one for example char.
(char *)&vector[1] - (char *)&vector

Answer: You can calculate the difference of pointers to byte-sized values by casting the pointers to char *:
printf("%d\n", (char*)&vector[1] - (char*)vector);

Comment: Also, if you want to get the number of bytes that spans the address range, you add +1 to the above.


how to generate logs in separate file when starting the appium server programmatically

Question: With this code appium logs are printed in console, how to generate appium logs in a separate file.
public class TestBaseclass {
static AppiumDriverLocalService appiumService;
<code>@BeforeClass
public static void startserver() throws Exception {
      appiumService = AppiumDriverLocalService.buildDefaultService();
        appiumService.start();
}

@AfterClass
public static void stopServer() throws Exception {

    System.out.println("Stop appium service");
    appiumService.stop();

}
</code>
Answer: <code>/**
 * Configures the appium server to write log to the given file.
 *
 * @param logFile A file to write log to.
 * @return A self reference.
 */
@Override
public AppiumServiceBuilder withLogFile(File logFile) {
    return super.withLogFile(logFile);
}
</code>
https://github.com/appium/java-client/blob/master/src/main/java/io/appium/java_client/service/local/AppiumServiceBuilder.java
AppiumServiceBuilder expose a method called withLogFile() that will write the logs into a given file.


LNK2005 error when integrating LuaJit in UE4 (Unreal Engine 4)

Question: lua51.lib(lua51.dll) : error LNK2005: _vsnprintf already defined in libcurl_a.lib(cryptlib.obj)
GameName.Build.cs ->
// Fill out your copyright notice in the Description page of Project Settings.

using System.IO;
using UnrealBuildTool;

public class GameName : ModuleRules
{
    private string ThirdPartyPath
    {
        get { return Path.GetFullPath(Path.Combine(ModuleDirectory, "../../ThirdParty/")); }
    }
    private bool LoadLua()
    {
        bool isLibSupported = false;

        string LibrariesPath = Path.Combine(ThirdPartyPath, "Lua", "libraries");

        PublicAdditionalLibraries.Add(Path.Combine(LibrariesPath, "lua51.lib"));

        PublicIncludePaths.Add(Path.Combine(ThirdPartyPath, "Lua", "includes"));

        Definitions.Add(string.Format("WITH_LUA_BINDING={0}", isLibSupported ? 1 : 0));

        return true;
    }
    public GameName(ReadOnlyTargetRules Target) : base(Target)
    {
        PCHUsage = PCHUsageMode.UseExplicitOrSharedPCHs;

        PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore" });

        PrivateDependencyModuleNames.AddRange(new string[] {  });

        LoadLua();

        // Uncomment if you are using Slate UI
        // PrivateDependencyModuleNames.AddRange(new string[] { "Slate", "SlateCore" });

        // Uncomment if you are using online features
        // PrivateDependencyModuleNames.Add("OnlineSubsystem");

        // To include OnlineSubsystemSteam, add it to the plugins section in your uproject file with the Enabled attribute set to true
    }
}

ActorName.cpp ->
// Fill out your copyright notice in the Description page of Project Settings.

#include "ActorName.h"

extern "C" {
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
#include "luaconf.h"
#pragma comment(lib, "lua51.lib")
}

// Sets default values
APart::APart()
{
    // Set this actor to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
    PrimaryActorTick.bCanEverTick = true;
}

// Called when the game starts or when spawned
void APart::BeginPlay()
{
    Super::BeginPlay();
    lua_State *L = luaL_newstate();
    luaL_openlibs(L);
    FVector NewLocation = GetActorLocation();
    NewLocation.Z = NewLocation.Z + 200.0f;
}

// Called every frame
void APart::Tick(float DeltaTime)
{
    Super::Tick(DeltaTime);
    /*FVector NewLocation = GetActorLocation();
    float DeltaHeight = (FMath::Sin(RunningTime + DeltaTime) - FMath::Sin(RunningTime));
    NewLocation.Z += DeltaHeight * 100.0f;
    NewLocation.Y += DeltaHeight * 800.0f;//Scale our height by a factor of 20
    RunningTime += DeltaTime;
    SetActorLocation(NewLocation);*/
}

I compiled LuaJit for 64x, I'm not including the 32x build, do I need to? I don't intend to release my game for 32 bit systems as there's no point lol (Other than IOS because I'm pretty sure you have to upload 32 bit and 64 bit versions of the app :3)
I only ever included Lua51.lib once? Have I done something wrong?
Answer: I know this is a pretty old question, but since I haven't seen an appropriate answer anywhere else and spent far too long figuring this out, I figured I'd help out any poor soul that is running into the same issue.
The basic, afaik unavoidable problem is that the msvcbuild version of LuaJIT has extra symbols in it for (apparently) no reason. Here are the steps I took to compile a working version:

Download the LuaJIT Windows source
Open the Makefile and

Set the mode to dynamic
OPTIONALLY enable the DLUAJIT_ENABLE_LUA52COMPAT flag

Compile using mingw32-make (mingw-w64)
Copy the lua51.dll file to another folder.
Using the x64 Native Tools Comand Prompt for VS 2017, export the external symbols found in the DLL
dumpbin /EXPORTS lua51.dll > lua51.exports
From the exports file, create a separate .def file pointing to the dll containing all the symbol references
Using the x64 Native Tools Comand Prompt for VS 2017, generate the lib and exp files based on the def file
lib /def:lua51.def /out:lua51.lib

You now have a DLL and a LIB that links to it!

You may now copy the dll, lib and exp file to the location you want to install Lua to.
Finish following the Installation instructions on the LuaJIT website, for my own paths, that was

Copy all files from K:/Git Repos/luajit205-52-libdll/luajit205-52-dll/src to C:/LUA
Copy the files from K:/Git Repos/luajit205-52-libdll/luajit205-52-dll/src/jit to C:/LUA/lua/jit

I wrote out the full procedure and how I worked through it, along with the dll/lib/exp I use to one of my git repos, so for extra doc and potentially useful files, head here:
https://github.com/Zaltu/luajit205-52-libdll
Comment: I'm sorry it took me so long to see this, you're a savior, I ended up recompiling several libraries that UE4 came with (the ones LuaJit was having issues with) and the _vsprintf error dissipated and everything was functioning correctly. Definitely using this when I start up UE4 again, thanks <3


Can an open set in $\mathbb{R}$ be described as the disjoint union of uncountably many open intervals?

Question: The lecture notes I'm working through pose the question of whether any open set in $\mathbb{R}$ can be described as the disjoint union of uncountably many open intervals.
The problem doesn't state which topology on $\mathbb{R}$ I'm using. I know that any open set can be written as a union of open balls, and an open ball in $\mathbb{R}$ with its usual topology is an open interval, so I assume this is using the standard topology. (If it doesn't matter, I'd be interested in knowing.)
Intuitively, I believe the answer is no, but here's my attempt at a proof. It essentially mimics the argument that any collection of non-overlapping discs in $\mathbb{R}^2$ is countable.

Let $U \subset \mathbb{R}$ be open, and $\{G_{\alpha}\}_{\alpha \in I}$ an uncountable collection of disjoint, open intervals such that $U = \bigcup\limits_{\alpha \in I} G_{\alpha}$. As each $\mathbb{Q}$ is dense in $\mathbb{R}$, in each $G_{\alpha}$, we can choose a rational $q_{\alpha}$. As the $\{G_{\alpha}\}$ are disjoint, if $q_{i}$ lives in $G_i$ for some $i \in I$, then $q_i \not \in G_{\alpha}$ for every $\alpha \neq i$. Therefore, we can write an injection $f: I \to \mathbb{Q}$ sending $\alpha \mapsto q_{\alpha}$. As $f$ is injective, $I \cong f(I) \subset \mathbb{Q}$. As $\mathbb{Q}$ is countable and a subset of a countable set is countable, $f(I)$ is countable, so $I$ is countble, and we have a contradiction.

I'd appreciate some advice on how to improve the proof. I don't think I need contradiction, for example. I could just just take $U$ to be a union of disjoint open intervals -- which may not even exist; at least, I haven't proved that -- and then prove that $I$ must be countable. I also found myself having trouble using appropriate notation to distinguish between the variable $\alpha$ and the specific index $i$.
Comment: You need to have the usual topology, in general this is not true. For example if you take $\mathbb{R}$ with the discrete topology then $\mathbb{R}=\cup_{x\in\mathbb{R}} \lbrace x\rbrace$.
Comment: Your proof is correct, but you're proving much more than is needed. As @Randall stated any open interval cannot be written as disjoint union of more than 1 open intervals. What you are proving is basically that there cannot be a family of disjoint open intervals, or even sets. Note that you can rephrase your prove: If $F$ is a family of open, disjoint sets then one can find a function that maps $F$ injectively into $\mathbb Q$, thus $F$ is at most countable.
Comment: About your proof, this looks good to me. Notice that you definition of $f$ implies the axiom of choice, but I don't think that there is a solution without it.
Comment: @Marcos Yes, I definitely used the axiom of choice. Do I need contradiction, though? This is my main uncertainty at this point. I appreciate the feedback.
Comment: @Marcos Is $\{x\}$ an open interval though?
Comment: No, you dont, I'll add a proof without contradiction in a few minutes, but it is not easier nor sorter, your approach is quite nice.
Comment: Well, I'm not sure what the definition of interval is in a non-euclidean space, so for other topologies this does not have much more sense. The result is that every open set of $\mathbb{R}$ can't be written as a non-countable disjoint union of connected open sets (but connected open sets in $(\mathbb{R},\tau_U)$ happens to be intervals).
Comment: I think the phrasing is off.  Maybe "prove *there is no open set* expressible as an disjoint union of uncountably many open intervals."
Answer: If $\Bbb R$ has the standard order, let $G_i, i \in I$ be a pairwise disjoint family of open intervals , say $G_i = (a_i, b_i)$ with $a_i < b_i$ two reals for each $i \in I$.
For each $i \in I$ we can pick a rational $q_i \in \Bbb Q$ so that $a_i < q_i < b_i$. This has nothing to do with any topology but with the construction/definition of $\Bbb R$ from $\Bbb Q$.
It follows that $I \to q_i$ is an injective function from $I$ (by disjointness) into a countable set. Hence $I$ is at most countable.
There simply doesn't exist any uncountable disjoint family of open intervals in $\Bbb R$, answering the question independently of any topology you might put on $\Bbb R$...
Comment: Note that if you use another unrelated order, like a well-order, there *can* be such a family.
Comment: What is your definition for interval in a general topology? I don't think that the statement of the problem has sense for an arbitrary topology.
Comment: @Marcos interval has nothing to do with a topology, only with an order. There are no "intervals" in a general space. But $\Bbb R$ *comes* with an order so interval is a defined notion.
Comment: but these are open intervals, so the topology is involved here. For example, in the discrete topology what is defined to be an open interval?
Comment: @Marcos On $\Bbb R$ an open interval is a set of the form $\{x\mid a < x < b\}$ for some $a<b$ in $\Bbb R$. It's called open because it's "open-ended" not because it is open in any topology.
Comment: Well, in that case you're right, but I am not convinced with the fact that an open interval can be non open.
Comment: @Marcos It's open in the standard topology from the metric, but not in the cofinite topology, e.g.
Comment: Yes, I guess you are right. Sorry for the inconvenience. I am not used to work in non standard topologies, so I've never thought that open intervals could be defined in general.
Answer: As I stated in a comment you are basically proving that there cannot exist an uncountable family of disjoint open sets (you can easily extend your proof to arbitrary separable spaces). But we can in facht prove this without AOC:
Let F be a family of open disjoint sets.
We define for $q\in\mathbb Q$ the set $F_q = \{O\in F:q\in O\}$. The disjoint property then means that $F_q$ has at most one element. But for each $O\in F$ there exists at least on $q\in O$, so
$$ F = \bigcup_{q\in\mathbb Q} F_q$$
and is thus at most countable.
The trick here is that we do not in fact need any uniqueness of this $q$.
Comment: Areyou sure this doesn't use the AOC? In my oppinion this is equivalent to all other proofs.
Comment: @Marcos Yes, this does not use AOC. The reason why the other versions require the AOC is because they try to find a *single* $q$ for each $O\in F$ to define an injection into $\mathbb Q$, while this does not care about such things and simply defines a surjection *from* $\mathbb Q$.
Comment: @Marcos Basically the other proof goes: We take the system of disjoint and nonempty sets defined by $O\cap \mathbb Q$ where $O\in F$ and then find by AOC a system of representatives $q_O$ to define this injection. Here we do the other direction, so for any $q$ we take the set of all $O\in F$ that contain $q$. Then we get that this can contain at most one set simply from the fact that all sets are disjoint.
Comment: @Marcos fix a bijection $h:\Bbb N \to \Bbb Q$ (this can be done explicitly) and define (in my version) $m(i)= \min \{n \in \Bbb N: a_i < h(n) < b_i\}$ (non-empty set so the min exists) and  set $q_i=h(m(i))$. No AC is required at all.
Comment: Thanks, honestly I'm quite suprised that this can be done withouth the AOC. Nice solution!!
Comment: @Marcos We do not really need the AOC in the other case either, to be honest, as we can prove it: If $X$ is countable it also has a well order. Having a well order is equivalent to the AOC, as we can choose our represenatives by the minimum of each set. So assuming that $\mathbb N$ is well-ordered suffices for this proof.
Comment: Only true if we don't have to choose a well-order but can give a bijection with $\Bbb N$ explicitly... There also is the axiom of countable choice which is independent of ZF..
Answer: This is the direct proof you want:
Let $U$ be an open set in $\mathbb{R}$ and let us define an equivalence relation:
$$x\sim y\Leftrightarrow\exists I\subset U\text{ open interval such that }x,y\in I$$
This is easily proven to be an equivalence relation and thus we can consider $U/\sim$. In this space, the equivalence classes are given by the open intervals of $U$. If we denote as $I_x$ the open interval containing $x\in U$, let us prove that $|U/\sim|\leq\aleph_0$:
For every $x\in U$ there exists $a_x\in\mathbb{Q}\cap I_x$ (because $\mathbb{Q}$ is dense in $\mathbb{R}$) and $x\nsim y\Rightarrow I_x\cap I_y=\emptyset$. Thus, using the axiom of choice, we can define $\phi:\mathbb{R}/\sim\to\mathbb{Q}$ by $\phi(I_x)=a_x$. Trivially $x\nsim y\Rightarrow \phi(I_x)\neq \phi(I_y)$ and then $|U/\sim|\leq|\mathbb{Q}|\leq\aleph_0$, as we wanted to prove.
Although this is a direct proof the idea is more or less the same as what you did in your contradiction proof.


Taylor's theorem without L'Hospital

Question:
Let $f:D \to \mathbb{R}$ be a real function with $U \subset D$ an open interval. Suppose that $f$ is $k$ times differentiable at $a \in U$. Then
$$R_k(x) \in o(|x-a|^k) \  \text{as} \ x \to a$$
where $R_k(x)=f(x)-P_k(x)$ and $P_k$ is the $k$th order Taylor polynomial of $f$  evaluated at $a$.

Like many, I am somewhat averse to the usage of L'Hospital's rule. Is there a proof of the above without it? Note the minimal conditions on $f$.
Comment: If i remember, most just use an extension of the mean value theorem, rsther than lhopitals rulr
Comment: @AndresMejia Those are for the formulae for the remainder term. Is this a corollary of those? If so, it's not immediately apparent to me how. Both Spivak and Wiki use L'hopital for this (asymptotic) result.
Comment: Even though I have marked your question as duplicate of my own question, +1 for you because of your statement "like many, I am somewhat averse to the use of L'Hospital's Rule".
Answer: Let's do it with $k=3$ and $a=0$ to illustrate. To simplify, let $g(x)=R_3(x).$ Then $0 = g(0)= g'(0)= g''(0)=g'''(0).$ By the MVT,
$$g(x)= g(x)-g(0) = g'(c_1)x = (g'(c_1)-g'(0))x$$ $$ = g''(c_2)c_1x = (g''(c_2)-g''(0))c_1x = \frac{g''(c_2)-g''(0)}{c_2}c_2c_1x.$$
As $x\to 0,$ $c_1,c_2$ are dragged along to $0$ with it. We have $c_2c_1x = O(x^3)$ and the fraction on the right $\to g'''(0) = 0.$ Thus $g(x) = o(x^3)$ as desired.
Comment: How do we know $g$ is differentiable at $c_1, c_2$ or any $x \neq 0$? The theorem assumes differentiability at a point, not a neighbourhood.
Comment: For $f'''(a)$ to exist, $f''$ must exist in a neighborhood of $a.$
Comment: Fine but I also have another issue. I don't think you can manipulate the mean value theorem derivative like that. As an example, consider simply $$h(x) := \frac{f(x) - f(a)}{x-a} = f'(c), c \in (a,x)$$

where $f$ is differentiable. As $x \to a$, $h(x) \to f'(a)$. However, even though $c$ is being dragged to $a$, $f'(c)$ does not necessarily $\to$ $f'(a)$ (suppose $f \notin C^1$, for example).
Comment: Or, what I mean is, taking the limit with the mean value theorem quantity ("$c$") isn't justified (without regularity conditions on $f$).
Comment: I don't follow you. Please read the proof carefully. Indicate exactly where you spot the first difficulty.
Comment: It's the term $\frac{g''(c_2) - g''(0)}{c_2}$. You are taking the limit as $x \to 0$ and arguing that $c_2$, the mean value theorem quantity, is being "dragged" to the limit $g'''(0) = 0$. The purpose of my comment is to suggest that this "dragging" may not be formally valid when taking limits.
Comment: It's not a question of "formally". And no, I'm not saying that. I am saying $c_2$ is being dragged to $0.$ Do you agree? (Recall $c_1$ is between $0$ and $x,$ and $c_2$ is between $0$ and $c_1.$)
Comment: Yes, I do, if you read my above comment. I am saying that taking the limit with the $c_2$ quantity, however, as you do, is problematic.
Comment: No it's not. If $c_2 \to 0$ as both you and I agree, then what do you think $(g''(c_2) - g''(0))/c_2$ goes to?
Comment: That's where my example comes in. If $h(x) = \frac{f(x) - f(a)}{x-a}$ and $f$ is differentiable, letting $x \to a$ is valid. $\lim_{x \to a} h(x) = f'(a)$. But $\frac{f(x) - f(a)}{x-a} = f'(c)$ for some $c \in (a,x)$. Now do you agree as $x \to a$, $c \to a$? You must also agree, then, that as $c \to a$, $f'(c) \to f'(a)$. But what if that limit does not exist? Say $f(x) = x^2\sin(\frac 1x)$.
Comment: No, you've misunderstood my argument. I'm looking at $g''(c_2)-g''(0))/c_2.$ I am not using the MVT on this. i'm just saying that, by definition, this $\to g'''(0).$

Taylor's theorem without L'Hospital


Do not request a billing address during checkout

Question: By default, Commerce 2 requests credit card info + address info (name, address, and company name) for all orders.  I want to have users enter their credit card information but I don't want to collect their name, address, or company name. Stripe does not require name/address info so I don't want to require it, either.
As my payment gateway, I am using Commerce Stripe, but this applies to all payment gateways, such as Commerce PayPal, and the Manual (no credit card) payment gateway.
So, how can I safely remove the address form from the checkout page?
I first tried to hack Commerce directly (bad practice, just trying to see how it worked) but I broke the module.
As I looked around, it appeared that the billing info is deeply wired into the Commerce code.  Is there a way to decouple it?  Not all stores (those that sell digital products, etc.) need their customers' physical addresses.
On the checkout "Payment information" screen, I want to remove all of the fields from "Country" down to "Postal code":
Comment: You can disable the order details in your checkout flow but I haven't been able to completely disable that step.
Comment: I would try to use hook_form_alter unset($form['field_address']); and if necessary override the validation function. Just might work.
Answer: It is quite hard to do indeed. One way to do this is by setting a dummy billing address and hide the address form.
You will need to do the following:

In a custom module, add a CommerceCheckoutPane plugin. The plugin class should extend \Drupal\commerce_payment\Plugin\Commerce\CheckoutPane\PaymentInformation.
Override the buildPaneForm() method, in there:

Set an #after_build callback. In this callback, make each address field non-required. The reason that you need an #after_build callback is that else address fields won't be available.
On the commerce_profile_select element, set an #element_validate callback. In this callback, set the address values. The reason that you need an #element_validate is because a general form validation callback is called too late in the validation process to set the address in time. This is because the address element has a constraint and the address is validated against this constraint after #element_validate and before a general form validate. Should you try to set the address in a general form validation callback, then you'll get address field required errors because of the constraint.
You can set the #element_validate callback as well in the #after_build callback, which I've done in the code example below.

To hide the address form, you'll need to set #access to FALSE for the address form. This needs to happen in the #after_build callback as well, because earlier the address form isn't available yet.
On the checkout flow settings, disable the default Payment information pane (and enable the custom Payment information pane if not yet enabled).
To hide the dummy billing address on the 'Review' step, copy the template commerce-payment-method--credit-card.html.twig (and/or commerce-payment-method.html.twig if you are using a non-credit card payment method) to your theme and remove the line {{ payment_method.billing_profile }} from it.

Code example (file name: mymodule/src/Plugin/Commerce/CheckoutPane/PaymentInformation.php):

namespace Drupal\custom_commerce\Plugin\Commerce\CheckoutPane;

use Drupal\commerce_payment\Plugin\Commerce\CheckoutPane\PaymentInformation as PaymentInformationBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element;

/**
 * Provides the payment information pane.
 *
 * @CommerceCheckoutPane(
 *   id = "custom_commerce_payment_information",
 *   label = @Translation("Custom Payment information"),
 *   display_label = @Translation("Payment information"),
 *   default_step = "order_information",
 *   wrapper_element = "fieldset",
 * )
 */
class PaymentInformation extends PaymentInformationBase {

  /**
   * {@inheritdoc}
   */
  public function buildPaneForm(array $pane_form, FormStateInterface $form_state, array &$complete_form) {
    $pane_form = parent::buildPaneForm($pane_form, $form_state, $complete_form);

    // Add an after build callback in order to make modifications on the address form.
    $pane_form['#after_build'][] = [$this, 'paneFormAfterBuild'];

    return $pane_form;
  }

  /**
   * After build callback for the pane form.
   */
  public function paneFormAfterBuild(array $pane_form, FormStateInterface $form_state) {
    // Get billing form element. Where it is located depends on the payment method that is chosen.
    if (isset($pane_form['add_payment_method']['billing_information'])) {
      $billing_form = &$pane_form['add_payment_method']['billing_information'];
    }
    elseif (isset($pane_form['billing_information'])) {
      $billing_form = &$pane_form['billing_information'];
    }
    else {
      // No billing information found.
      return $pane_form;
    }

    // Get the address form element.
    $address_form = &$billing_form['address']['widget']['0']['address'];

    // Add element validation callback to autofill the address.
    $billing_form['#element_validate'] = array_merge(
      [[$this, 'profileSelectValidate']],
      \Drupal::service('element_info')->getInfoProperty('commerce_profile_select', '#element_validate', [])
    );

    // Set all address fields to non-required.
    foreach (Element::children($address_form) as $key) {
      $address_form[$key]['#required'] = FALSE;
    }

    // Hide the address form.
    $address_form['#access'] = FALSE;

    return $pane_form;
  }

  /**
   * Element validation callback for the profile select element.
   */
  public function profileSelectValidate(array &$element, FormStateInterface $form_state) {
    // Set dummy address.
    $address = [
      'given_name' => 'A',
      'family_name' => 'A',
      'address_line1' => 'Dummy street',
      'postal_code' => '1234 AB',
      'locality' => 'Dummy city',
      'country_code' => 'NL',
    ];
    $form_state->setValue($element['address']['widget'][0]['address']['#parents'], $address);
  }

}

Comment: I haven't used these payment gateways yet (I'm still in the process of setting up a store), but if the payment method in question works with billing addresses, it will probably receive that dummy address, yes. I think I read 'X does not require address info' as 'X does not use address info'.
Comment: Thanks, this is an impressive answer.  I don't mind using dummy data if the form can't be completely unset, because it's better to fill the db with garbage data than to use actual data that might get exposed.  One question: if I use a dummy address as you described, will this address be passed to Stripe/PayPal/whatever other payment gateway I am using as part of the order process?  I don't want to use dummy data and then cause legitimate credit cards to fail because the dummy postal code is wrong for the card.
Comment: When I added this code to my site and replaced the payment information pane with the new custom one, the address was successfully hidden.  However, when using this custom pane, the payment is not sent to the payment gateway (Stripe in my case).  When I revert to the standard payment info pane, the payment is sent successfully, even when using a payment method (test credit card) that was saved with the custom pane (in other words, when using a payment method with the dummy address and the standard payment info pane, it works).
Comment: It sounds like that the code that I posted needs some work. We should aim for a solution where you don't need to use both payment info panes.
Comment: Yes, specifically, when the posted code is used by itself, the order completes but the payment does not get made (the resulting order has no payment attached, and the payment gateway does not receive the payment data).
Answer: TL:DR;
Go to admin/config/people/profiles/types/manage/customer/form-display and disable the form elements you want to hide (config applies to entire site)
Explanation
It should be fairly easy to do this, though let me just say up front that I haven't tested this myself.
What you are seeing as the address, is the "billing profile" (both the order and the payment method has a billing profile IIRC. DC has not created the billing profile themselves (unlike in Drupal 7) but are instead using the profile module.
When DC renders the "billing profile" or "billing information" it respects the global settings made for the profile type it uses (customer). This means you can configure how the form should appear, including disabling all elements. This can be done at admin/config/people/profiles/types/manage/customer/form-display. This also means that you can add additional fields to the profile, if you wanted to collect more information without touching DC itself.
Disclaimer - I have not tested this myself but having messed with Commerce quite a lot I'm pretty confident that this will work.
Comment: Wow, it really was that easy.  Address can be disabled in one click and the payment goes through.
Comment: @googletorp This is the real answer which not only solves this particular problem, but also other cases where you want to collect additional information. You can also create a new profile type and I think, I am not sure, but it should be available as a pane in the checkout process.
Comment: @googletorp Is it necessary to have a "customer" profile type in order to complete the checkout process?
Answer: Actually, according to this thread on drupal.org, the fact that you can hide the billing form and Commerce Stripe still works is an anomaly; usually, this should cause Commerce to crash.
At this time, Commerce 2 requires a billing address.
There is a experimental patch and a discussion of why Commerce requires a billing address on drupal.org.
Comment: I admit that on the Commerce site that I'm building, the billing address is asked at an earlier stage and the code example in my answer was created from the code in that project. In the code example I only added the dummy address part, assuming that would work for payment methods that don't require a billing address (like the payment method 'cash on delivery').


List of authors of articles in a view

Question: I am trying to create a page which lists the users who are an author of a node type of article.
I figured I would approach it by creating a view based upon article. So the view started out listing all articles. Then I set up a relationship to users where the user is the author of the article, and in the fields, I just have it output the author's name (user name).
Now I have a list of all of the authors, but it repeats. So you see John Smith a hundred times, if he wrote 100 articles.
How do you make it so that John Smith only shows up once? If I could edit the mysql, I would just use group by uid (so the user only shows once), but in drupal views, it will list that author as a heading for a group, and then list all the articles he was in (so in my setup, it would show his name followed by a listing of his name many times).
This is in Drupal 7
Comment: 0.25 bitcoins to whoever can gets me the best usable answer in the next 2 days. Just put your address in the comment to your answer.
Comment: this site is running on "points" ;-) If you ever need more or better answers try the "bounty"
Answer: you are almost there. Just set "Use aggregation" to yes. Also, make sure there is not other field in "sort criteria".

List of authors of articles in a view


NoSuchMethodError in google maps api android

Question: I am encountering frequent crashes of my app on devices running Android 2.3.x lately. They all boil down to the following stacktrace with the Google Maps API.
My app requires a minimum SDK version of 10 and includes the compat libraries v3 and v7 (via a library project). Interestingly enough it actually works on my test device running Android 2.3.6 so it does not crash on all old devices. On all newer Androids it works of course without a problem.
To my understanding this should not crash because the compat library adds this specific method requestSendAccessibilityEvent which has been added in API level 14.
STACK_TRACE
java.lang.NoSuchMethodError: android.view.ViewParent.requestSendAccessibilityEvent
at com.google.maps.api.android.lib6.c.bc.a(Unknown Source)
at com.google.maps.api.android.lib6.c.ai.a(Unknown Source)
at com.google.maps.api.android.lib6.c.ax.f(Unknown Source)
at com.google.maps.api.android.lib6.c.do.handleMessage(Unknown Source)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3687)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:842)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)

I have raised this with the Dev team and include it here as a cross-reference:
https://code.google.com/p/gmaps-api-issues/issues/detail?id=7230
Comment: Show some code atleast.
Comment: As the google code is obfuscated I don't know where the crash is happening. I think it makes little sense to post my whole activity ;-)
Answer: I can see this happening here on some apps. Very few users have this crash, but its visible. I assume that google-api changed and they *****-up something. Lets wait 6 more weeks and test again (the time it takes them to deliver new APIs to phones).
Programming for Android is ... interesting... as your app depends on Google-APIs and they change in the lifecyle of your app, this means that your app gets modified by google without you knowing it.


Two square roots in an indeterminate

Question: Square roots are always causing trouble for me - especially finding the limit of a function when it's in the indeterminate form.
I got this far, but I don't know what to do next or even if it's right. Trying to go any further gives me my original problem.
This is the initial problem
$$
\lim_{x\to5}\frac{\sqrt{ x^2+5}-\sqrt{30}}{(x-5)}
$$
This is where I've gotten
$$
\lim_{x\to5}\frac{\sqrt{x^2+5}-\sqrt{30}}{(x-5)} * \frac{\sqrt{x^2+5}+\sqrt{30}}{\sqrt{x^2+5}+\sqrt{30}} = \frac{x^2+5-30}{(x-5)\left(\sqrt{x^2+5}+\sqrt{30}\right)}
$$
Comment: Can you factor $x^2 - 25$ in any interesting ways? You're almost there.
Comment: Your final equality should have a $\lim\limits_{x\to 5}$ on the right hand side of the equal sign as well.
Comment: @Joe: The correct answer to this problem is in fact not a whole number or a simple fraction.  It's an expression involving $\sqrt{30}$.  You (probably) don't need to give a decimal approximation but can just leave the answer in the form you already have.  (More precisely, in your previous comment, you should still be taking the limit as $x \rightarrow 5$.  In the form you currently have it this can be done just by substituting $x = 5$, and then you will be done.)
Comment: I've tidied up the LaTeX in your post, and also fixed a few typos.
Comment: @Dylan Moreland: I got it down to (x+5)/(sqrt(x^2+5)+sqrt(30)) but the answer is an ugly decimal and according to our teachers we shouldn't be getting those. I don't know if it's something I did wrong or what, but I'm pretty sure it has to either be a whole number or simple fraction.
Comment: I suppose my teacher made a mistake giving us that problem then. I got .91 (rounded), so I'll just keep that and move on. Thanks.
Answer: HINT $\ \ \ $ Factoring both of$\ \ \sqrt{x^2+5}^{\:2} - \sqrt{30}^{\:2}\ =\ x^2 - 5^2\ $ by difference of squares yields
$$\frac{\sqrt{x^2+5}-\sqrt{30}}{x-5}\ =\ \frac{x+5}{\sqrt{x^2+5}+\sqrt{30}} $$
Alternatively, if you're familiar with derivatives, note that the limit is $f\:'(5)$ for $f(x) = \sqrt{x^2+5}\:.$
Many limits can be simply calculated by recognizing them as instances of first derivatives and then calculating the derivatively rotely using known derivative rules. You can find a handful of examples in my prior posts starting here. Later in your course you will most likely encounter a generalization of this observation known as l'Hôpital's Rule.
Comment: @Joe: Have you gotten to derivatives in your calculus class?  If not, revisit this comment once you have.  Bill's comment turns this standard limit problem into a routine limit problem.
Comment: Why the downvote? If something is not clear please ask questions and I am happy to explain.
Comment: The problem is (x-5) in the denominator being multiplied by everything else in the denominator. I can't have 0 down there.
Comment: I can't vote on answers yet; I wouldn't vote anything with good intent down anyways. @DJC: Not that I recall. School only started for me about a week ago and the first thing we did in calculus were easy limits then we got indeterminates which is where I'm stuck at.

Two square roots in an indeterminate


Parênteses em um ponteiro para ponteiro

Question: Estou estudando uma estrutura de árvore binária e fiquei em dúvida em uma parte do código.
#include <stdio.h>
#include <stdlib.h>

typedef struct tree
{
  int num;
  struct tree* sad;
  struct tree* sae;
} Tree;

void insertTree(Tree** t, int num)
{

  if(*t == NULL)
  {
    *t = (Tree*)malloc(sizeof(Tree));
    (*t)->sae = NULL;
    (*t)->sad = NULL;
    (*t)->num = num;
  }
}
// Código continua, porém não achei necessário colocá-lo

int main()
{
  Tree* t = NULL;

  insertTree(&t, 12);
}

Minha dúvida é justamente quando se tem este parênteses no ponteiro (*t)->sae = NULL;
O que ele quer dizer?
Answer: Existe uma tabela de precedência de operadores, como você conhece na matemática (multiplicação e divisão acontece antes de adição e subtração). No caso um código de uma linguagem tem diversos operadores.

Como é possível ver na tabela os parênteses tem precedência máxima então tudo o que estiver dentro dele será feito antes.
(1 + 2) * 4

dá 12, é diferente de
1 + 2 * 4

que dá 9 porque na verdade é isto que ocorre implicitamente:
1 + (2 * 4)

O ponteiro tem uma precedência um pouco menor. Mas o ponteiro de um membro tem a precedência máxima, então se você tiver um ponteiro normal e de um membro o do membro será resolvido antes. A não ser que tenha parênteses forçando nova precedência. Assim
*t->num

pega o valor de t e tenta então pegar o objeto referenciado por num (->). Depois o que ele achar tentará derreferenciar com o *. Isso dará erro, não faz sentido.
O que está fazendo no seu código é derreferenciar t com * em primeiro lugar e o resultado disso é que deve pegar o objeto referenciado por num (->). Então você tem que garantir que o ponteiro (*) seja executado antes do ponteiro para membro (->).
(*t) -> num

O padrão sem nada seria o mesmo que escrever assim:
*(t->num)

Coloquei no GitHub para referência futura.
Não é o que deseja.
O (*t) -> num está guardando algo no membro num, que é o desejado.
O *(t->num) está guardando algo no local que t->num indicar, que não é o que deseja.

Parênteses em um ponteiro para ponteiro


Finding: $\displaystyle\lim_{x\to\infty}x\big((1+\tfrac1x)^x-\mathrm{e}\big) $

Question:
Find: $$\displaystyle\lim_{x\to\infty}x\Big(\big(1+\tfrac1x\big)^x-\mathrm{e}\Big) $$

EDIT: so we have here a $\infty\cdot0$ so I'll try LHR, Edit2: I don't think LHR will get me anywhere since it will always be zero in the denominator...
Maybe develop a Taylor series ?
Wrong try:
$\displaystyle\lim_{x\to\infty}(1+\frac1x)^x=\frac 1e$ is a well known limit so:
$\lim_{x\to\infty}x(\displaystyle\lim_{x\to\infty}(1+\frac1x)^x-e)=\lim_{x\to\infty}x(\frac 1e-e)=-\infty $
Comment: In fact $$\lim_{x\to\infty} \left(1 + \frac{1}{x}\right)^x = e.$$ To find the desired limit, you must see how fast the convergence is, for that it is useful to write $$\left(1 + \frac{1}{x}\right)^x= \exp \left( x\log \left(1 + \frac1x\right)\right).$$
Comment: If it's any help, Wolfram says the limit is $-\frac{e}{2}$.
Comment: Do not use LHR. Just look at Daniel Fischer's hint and try to apply following limit: $\frac{e^{f(x)}-1}{f(x)} \to 1$ as $f(x) \to 0$. It'll remain to calculate another limit and but it is an easy excercise for Taylor.
Answer: Note that
$$\lim_{x\to\infty}\left(1+\frac 1x\right)^x=e.$$
You can use l'Hôpital's rule.
Yours will be
$$\begin{align}\lim_{x\to\infty}\frac{(1+(1/x))^x-e}{(1/x)}&=\lim_{x\to\infty}\frac{(1+(1/x))^x \{-1+(1+x) \ln(1+(1/x))\}}{-(x+1)/x^2}\\&=\lim_{x\to\infty}\frac{(1+(1/x))^x \{-x+x(1+x) \ln(1+(1/x))\}}{-(x+1)/x}\\&=\frac{e\times (1/2)}{-1+0}\\&=-e/2\end{align}$$
where
$$\begin{align}\lim_{x\to\infty}\{-x+x(1+x)\ln(1+1/x)\}&=\lim_{x\to\infty}\frac{-1+(1+x)\ln(1+(1/x))}{1/x}\\&=\lim_{x\to\infty}\frac{\ln(1+(1/x))-(1/x)}{-1/x^2}\\&=\lim_{x\to\infty}\frac{1/(x^2+x^3)}{2/x^3}\\&=\lim_{x\to\infty}\frac{1}{2+(2/x)}\\&=1/2.\end{align}$$
Comment: Because $$\left(-1+(1+x)\ln(1+(1/x))\right)^\prime=\ln(1+(1/x))-(1/x).$$
Comment: It can not be a positive limit, as $(1+\frac{1}{x})^{x}<\mathrm{e}$.
Comment: @YiorgosS.Smyrlis: Of course, my answer is $-e/2$. Please read my answer carefully.
Comment: Thanks, it was pretty hard to read because you've omitted a few steps.

How did you know to do this ?

$$\begin{align}&=\lim_{x\to\infty}\frac{(1+(1/x))^x \{-1+(1+x) \ln(1+(1/x))\}}{-(x+1)/\color{red}{x^2}}\\&=  \lim_{x\to\infty}\frac{(1+(1/x))^x \{-x+x(1+x) \ln(1+(1/x))\}}{-(x+1)/\color{red}{x}}\\\end{align} $$
Comment: Just because I've known $\{\cdots\}\to\ 1/2$ (actually I've known it goes to a limited value).
Comment: Why is it a minus there ? $$\lim_{x\to\infty}\frac{\ln(1+(1/x))\color{red}{-1/x}}{-1/x^2}$$

Also, before that step you derive and get $\frac{x+1}{\frac{x+1}{x}}$ so how did you get from that to -1/x ?
Answer: Hint. Set $t=\dfrac{1}{x}$, and hence $t\to 0$, and
$$
x\big((1+\tfrac{1}{x})^x-\mathrm{e}\big)=\frac{(1+t)^{1/t}-\mathrm{e}}{t}=\frac{f(t)-f(0)}{t}
=f'(s),
$$
for some $s\in (0,t)$ (due to the Mean Value Theorem),
where
$$
f(t)=\left\{
\begin{array}{cll}
(1+t)^{1/t} & \text{if} & t>0,\\
\mathrm{e} & \text{if} & t=0.
\end{array}
\right.
$$
Now
$$
f'(t)=\exp\big(\tfrac{1}{t}\ln (1+t)\big)\left(\tfrac{1}{t(1+t)}-\tfrac{\ln(1+ t)}{t^2}\right).
$$
So your limit is just $f'(0)$.
In fact, you don't need to find $f'(0)$ directly, but to compute $f'(t)$, for $t>0$ ,and observe that the limit $\lim_{t\to 0} f'(t)$ exists.
Clearly, $\exp\big(\tfrac{1}{t}\ln (1+t)\big)=(1+t)^{1/t}\to\mathrm{e}$, while, for $g(t)=\ln (1+t)$,
$$
\frac{1}{t(1+t)}-\frac{\ln(1+ t)}{t^2}=\frac{1}{t}\left(g'(t)-\frac{g(t)-g(0)}{t}\right)\to-\frac{1}{2}g''(0).
$$
Comment: @GinKin: I meant $x$. Fixed now
Comment: OK, can you explain a bit ? Is that LHR ? Why did you define another function ?
Answer: We have:
$$\log\left(1+\frac 1 x\right)^x=x\log\left(1+\frac 1 x\right)=x\left(\frac 1 x-\frac1{2x^2}+o\left(\frac1{x^2}\right)\right)$$
so
$$\left(1+\frac 1 x\right)^x=e\exp\left(-\frac1{2x}+o\left(\frac1{x}\right)\right)=e\left(1-\frac1{2x}+o\left(\frac1{x}\right)\right)$$
hence now it's simple to see that the desired limit is: $$-\frac{e}{2}$$
Comment: @SuperStamp Just replace the founded expression of $\left(1+\frac 1 x\right)^x$ in $x\left(\left(1+\frac 1 x\right)^x-e\right)$ and pass to the limit.
Comment: Can you explain how did you get the final result $- {e \over 2}$, it's a bit unclear to me. Thanks!
Answer: $\displaystyle \begin{aligned}L &= \lim_{x \to \infty}x\left(\left(1 + \frac{1}{x}\right)^{x}- e\right)\\
&= \lim_{x \to \infty}\dfrac{\left(\left(1 + \dfrac{1}{x}\right)^{x}- e\right)}{\dfrac{1}{x}}\\
&= \lim_{y \to 0^{+}}\dfrac{(1 + y)^{1/y} - e}{y}\text{ (by putting }y = 1/x)\\
&= \lim_{y \to 0^{+}}\dfrac{\exp\left(\dfrac{\log(1 + y)}{y}\right) - \exp(1)}{y}\\
&= \lim_{y \to 0^{+}}\dfrac{\exp\left(\dfrac{\log(1 + y)}{y}\right) - \exp(1)}{\dfrac{\log(1 + y)}{y} - 1}\cdot\dfrac{\dfrac{\log(1 + y)}{y} - 1}{y}\\
&= \lim_{z \to 1}\dfrac{\exp(z) - \exp(1)}{z - 1}\cdot\lim_{y \to 0^{+}}\dfrac{\log(1 + y) - y}{y^{2}}\,\,\{\text{by putting }z = (1/y)\log(1 + y)\}\\
&= \exp'(1)\cdot\lim_{y \to 0^{+}}\dfrac{\dfrac{1}{1 + y} - 1}{2y}\text{ (by L'Hospital's Rule)}\\
&= \exp(1)\cdot\lim_{y \to 0^{+}}\frac{-1}{2(1 + y)}\\
&= -\frac{e}{2}\end{aligned}$
One application of LHR is necessary, but the above procedure makes the application of LHR very simple. In the above derivation we have used the fact as $y \to 0^{+}$ the quantity $z = (1/y)\log(1 + y) \to 1$. This limit is pretty standard and a proof can be found in many textbooks and on MSE.
Comment: +1  nice  answer  and easy to understands
Answer: It will be easy if you use taylor formula. Let $t = \frac {1}{x}$,then $t \to 0$ as $x \to  \infty$,you will get $$ \lim_{ t \to 0} \frac{1}{t} ( e^{ \frac{1}{t} \log(1+ t)}-e)$$Note $\log(1+t) = t -\frac{t^2}{2}+o(t^2)$ as $t \to 0$ , and $ \frac{1}{t} \log(1+t) = 1 -\frac{t}{2}+o(t)$,then it becomes  $$ \lim_{ t \to 0} \frac{1}{t} ( e^{ \frac{1}{t} \log(1+ t)}-e) =  \lim_{ t \to 0} \frac{1}{t} ( e^{ 1- \frac{t}{2}+ o(t)}-e) = \lim_{ t \to 0} \frac{e}{t} (e^{ - \frac{t}{2}+ o(t)}-1) $$ use taylor formula again in $e^{ - \frac{t}{2}+o(t)} = 1 -\frac{t}{2} +o(t)$ you'll get $$\lim_{ t \to 0} \frac{e}{t} (e^{ - \frac{t}{2}+ o(t)}-1)  = \lim_{ t \to 0} \frac{e}{t} (1 -\frac{t}{2} +o(t)-1)= -\frac{e}{2}+o(1) $$  $o(1) \to 0$ as $t \to 0$ so the limit is $-\frac{e}{2}$