Arduino Loop Break

Question: at school currently we are creating a robot using an arduino that can be controlled by Bluetooth, using Thunkable. Currently the app sends the arduino characters that the arduino will recognise and will follow an IF STATEMENT. I've created a Figure 8 command, which works as of now, but it's stuck in loop and won't stop, even if the STOP button is pressed. I made sure to set x = false in the off if statement, but I don't think it's working with the current code. I've tried using a break, but to no avail. All I want to do, is stop the loop from continuing, using the off command. Any help would be appreciated.
<code>//L293D
// connect motor controller pins to Arduino digital pins
// motor one
char input;
boolean x = false;
boolean timer = true;
int enA = 12;
int in1 = 11;
int in2 = 10;
// motor two
int enB = 8;
int in3 = 9;
int in4 = 7;

void setup()
{
  // set all the motor control pins to outputs
  pinMode(enA, OUTPUT);
  pinMode(enB, OUTPUT);
  pinMode(in1, OUTPUT);
  pinMode(in2, OUTPUT);
  pinMode(in3, OUTPUT);
  pinMode(in4, OUTPUT);

  Serial.begin(9600);
  Serial.println(">> START <<");
}
void demoOne()
{
  if(Serial.available() >= 0)
  {
    input = Serial.read();
    if(input=='k')
    {
      Serial.println("ON");
      digitalWrite(in1, HIGH);
      digitalWrite(in2, LOW);
      digitalWrite(in3, HIGH);
      digitalWrite(in4, LOW);
      analogWrite(enA, 200);
      analogWrite(enB, 200);
    }
    else if(input == 'q')
    {
      Serial.println("REVERSE");
      digitalWrite(in1, LOW);
      digitalWrite(in2, HIGH);
      digitalWrite(in3, LOW);
      digitalWrite(in4, HIGH);
      analogWrite(enA, 200);
      analogWrite(enB, 200);
    }
    else if(input == 'l')
    {
      x = false;
      Serial.println("OFF");
      digitalWrite(in1, LOW);
      digitalWrite(in2, LOW);
      digitalWrite(in3, LOW);
      digitalWrite(in4, LOW);
    }
    else if(input == 'c')
    {
      Serial.println("CIRCLE MODE");
      digitalWrite(in1, HIGH);
      digitalWrite(in2, LOW);
      digitalWrite(in3, LOW);
      digitalWrite(in4, LOW);
      analogWrite(enA, 200);
      analogWrite(enB, 200);
    }
    // THIS IS THE HIGHLIGHTED CODE THAT I NEED HELP WITH
    else if(input == 'i')
    {
      for(x == true; x = true;)
      {
        if(x == false)
        {
          break;
        }
      Serial.println("FIGURE EIGHT MODE");
      digitalWrite(in1, LOW);
      digitalWrite(in2, LOW);
      digitalWrite(in3, HIGH);
      digitalWrite(in4, LOW);
      analogWrite(enA, 200);
      analogWrite(enB, 200);
      delay(1000);
      digitalWrite(in1, HIGH);
      digitalWrite(in2, LOW);
      digitalWrite(in3, LOW);
      digitalWrite(in4, LOW);
      analogWrite(enA, 200);
      analogWrite(enB, 200);
      delay(1000);

      }
    }

    else if(input == 'r')
    {
      Serial.println("CIRCLE MODE");
      digitalWrite(in1, LOW);
      digitalWrite(in2, LOW);
      digitalWrite(in3, HIGH);
      digitalWrite(in4, LOW);
      analogWrite(enA, 200);
      analogWrite(enB, 200);
    }
    else
    {
      Serial.println("NO INPUT");
      Serial.println(input);
      delay(1000);
    }
  }

  /* this function will run the motors in both directions at a fixed speed
  // turn on motor A
  // digitalWrite(in1, HIGH);
  // digitalWrite(in2, LOW);
  // set speed to 200 out of possible range 0~255
  // analogWrite(enA, 200);
  // turn on motor B
  // digitalWrite(in3, HIGH);
  // digitalWrite(in4, LOW);
  // set speed to 200 out of possible range 0~255
  analogWrite(enB, 200);
  delay(2000);
  // now change motor directions
  digitalWrite(in1, LOW);
  digitalWrite(in2, HIGH);
  digitalWrite(in3, LOW);
  digitalWrite(in4, HIGH);
  delay(2000);
  // now turn off motors
  digitalWrite(in1, LOW);
  digitalWrite(in2, LOW);
  digitalWrite(in3, LOW);
  digitalWrite(in4, LOW); */
}
void demoTwo()
{
  /* this function will run the motors across the range of possible speeds
  // note that maximum speed is determined by the motor itself and the operating voltage
  // the PWM values sent by analogWrite() are fractions of the maximum speed possible
  // by your hardware
  // turn on motors
  digitalWrite(in1, LOW);
  digitalWrite(in2, HIGH);
  digitalWrite(in3, LOW);
  digitalWrite(in4, HIGH);
  // accelerate from zero to maximum speed
  for (int i = 0; i < 256; i++)
  {
    analogWrite(enA, i);
    analogWrite(enB, i);
    delay(20);
  }
  // decelerate from maximum speed to zero
  for (int i = 255; i >= 0; --i)
  {
    analogWrite(enA, i);
    analogWrite(enB, i);
    delay(20);
  }
  // now turn off motors
  digitalWrite(in1, LOW);
  digitalWrite(in2, LOW);
  digitalWrite(in3, LOW);
  digitalWrite(in4, LOW); */
}

void loop()
{
  demoOne();

}
</code>
Answer: Arduino loops are not exactly the same as loops you might write in a normal piece of code. What I like to do for my arduino programs is to declare a global boolean variable called "isOn" or something similar. If you surround the entire loop with an if statement checking if this is true, then you will be able to shut off your figure 8 loop by changing the value of this global variable so that your loop stops running. Break statements won't work on the entirety of this loop as you might expect from other programming you have done in the past.

Arduino Loop Break


Taxonomy in multilingual site

Question: I have developed a multilingual blog (two languages). Some of my articles are both languages.
I'm trying to do the following:
As you can see, this article is tagged with the 'Drupal Gardens' tag: (This is not my site. It's a blog with the functionality I would like to implement)
http://reyero.net/es/drupal/construyendo_sitios_web_multilingues_con_drupal_gardens
When you click on the taxonomy link, the next page is showing the articles with the 'Drupal Gardens' tag, but only in spanish.
http://reyero.net/es/taxonomy/term/85
Then, if you change the language to english http://reyero.net/taxonomy/term/85 is showing the articles with the 'Drupal Gardens' tag, but only in english.
How can I implement this functionality in my blog. reyero.net is not my site. It's a blog with the functionality I am searching for.
Comment: The question is how can I implement this functionality in my blog. reyero.net is not my site. It's a blog with the functionality  I am searching for
Answer: You must activate the module Taxonomy translation (i18n_taxonomy) then go to admin/structure/taxonomy/YOUR_TAXONOMY_NAME/edit and select:

Translate. Different terms will be allowed for each language and they can be translated.

Add a term and select the language and click the button Save and translate in the next page click the link add translation and create the translation.
Then create a node with this term that you hace create and you will have this functionality in your site.
Comment: Taxonomy translation (submodule from i18n module) must be activated too.
Comment: @user2132478 I see that was an error, you have reason, I edit now
Comment: Hm, didn't know you could use the 'kbd'-tag around here too!
Comment: @Pierre.Vriens there is a tag for a button? I think now that the kbd-tag is for keyboard input, but I don't sure.
Comment: I mean the HTML tag 'kbd' as you used for that 'Save and translate' in your answer ...
Comment: @Pierre.Vriens I know, I use the kbd to simulate the button 'Save and translate', It this correct? Et je viens de vouz ecrire un email, merci pour votre aide ;-)

Taxonomy in multilingual site


Does mean independence imply zero covariance?

Question: I've got a question where there is a population of observations in (x,y) data points. y is mean independent of x (equal to zero no matter where x is conditioned at).
Could the covariance change if we added more data points that keep y mean independent?
Answer: mean independence does indeed imply zero covariance.
I will show it for the discrete case.
Mean independence is defined as follows:
$$
\forall x E(Y|X=x)=E(Y)
$$
Therefore
$$\forall x \sum_y P(Y=y|X=x)y = \sum_y P(Y=y) y$$
Now, the covariance of $X$ and $Y$ is defined as
$$ Cov(X,Y)=E(XY) - E(X) E(Y)$$
Now we need to check whether the covariance is 0. Here, I focus on $E(X)E(Y)$.
\begin{align}
E(X) E(Y) &= \left[ \sum_y P(Y=y)y \right] \left[ \sum_x P(X=x) x \right] \\
&= \sum_x \left[P(X=x) x \sum_y P(Y=y)y \right]    \\
&= \sum_x \left[P(X=x) x \sum_y P(Y=y|X=x)y \right] \\
&= \sum_x \sum_y \left[P(X=x, Y=y)x y \right] \\
&= E(XY)
\end{align}
That means
$$ Cov(X,Y)=E(XY) - E(X) E(Y) = E(XY) - E(XY) = 0$$
Comment: thanks. I added more data points that kept the y mean 0, but the covariance changed by 0.538. These data points made the originally symmetrical (on the x-axis) graph non-symmetrical, so i've found the covariance only stays 0 if the graph is symmetrical on the x-axis.
does mean independence still imply zero covariance in this case, because i'm a bit confused with the discrepancy between the mathematical proof and the data?
Comment: Are you sure that x and y are still mean independent? Your additional data points probably represent a dependency.
Comment: my mistake, i didn't exactly understand the meaning of conditional mean so i was adding points that did not result in mean independence. i've fixed it now :)


Counter-intuitive zero measure thorem

Question: I just started learning about zero measure sets for multivariable integral calculus. The definition of a zero measure set is the following:

Let $A \subset \mathbb{R}^n$. We say it has zero measure if $\forall \epsilon > 0$ there exist a family of closed and bounded intervals $\{I_j\}$ finite or countably infinite such that $A \subset \cup_j I_j$ and $\sum_j V(I_j)<\epsilon.$

The interval $(0,2) \in \mathbb{R}$ is given as an example of non zero measure set.
After this, the following theorem is stated and proven:

Let $I$ be a closed and bounded interval of $\mathbb{R}^n$ and $g:I \rightarrow \mathbb{R}$ integrable in $I$. Then the set:
$A=\{(x_1,...,x_n,x_{n+1}) \in \mathbb{R}^{n+1} : (x_1,...,x_n)\in I, x_{n+1}=g(x_1,...,x_n)\}$ has zero measure.

So the set $\{(x,y) \in \mathbb{R}^2: 0 \le x \le 10, y=x^2\}$ would have zero measure. Intuitively the interval $(0,2)$ is "smaller" than the set $A$ so how is it possible to cover $A$ with arbitrarily small closed and bounded sets but it is not possible to do the same with $(0,2)$? I know we can' t really compare them because closed and bounded sets in $\mathbb{R}^2$ are not the same as the ones in $\mathbb{R}$ but I still see this as counter-intuitive.
Comment: In $\Bbb R^2$ the measure is "area" but in $\Bbb R^1$ the measure is "length".
Comment: Oh okay. So then if a set covers $(0,2)$ we would have that $\sum_j V(I_j)$ would be at least 2 but in $\mathbb{R}^2$ the areas of a  family of sets that cover a curve can be made as small as we want?
Comment: What is an "interval of $\mathbb R^n$"?
Comment: @JackM From the book i'm following it's the cartesian product of n intervals of $\mathbb{R}$
Answer: One-line explanation: We're talking about different notions of "zero area". If $\delta>0$ is vvery small then $\delta^2$ is much smaller than $\delta$, so there's no problem having $\sum\delta_j=1$ and $\sum\delta_j^2<\epsilon$.
More formally: Let $A=[0,1]\subset\Bbb R$ and $B=[0,1]\times\{0\}\subset\Bbb R^2$. Then
(i) $A$ is not a zero-area subset of $\Bbb R$.
(ii) $B$ is a zero-area subset of $\Bbb R^2$.
These both seem intuitively clear to me: The "area" in $\Bbb R$ is just the length, and $A$ has positive length. Otoh the "area" in $\Bbb R^2$ is "two-dimensional area", and $B$ certainly looks like it has zero two-dimensional area.
The actual proof of (i) is not quite trivial; I'm going to ignore that, since I think it seems plausible and I gather there's a proof in the book.
Proof of (ii): Let $I_j=[(j-1)/n,j/n]\times[0,1/n]$. Then $B\subset\bigcup_{j=1}^n I_j$, and $$\sum V(I_j)=n\sum_{j=1}^n\frac1{n^2}=\frac1n<\epsilon\quad(n>1/\epsilon).$$
More to the point, why (ii) does not contradict (i): Saying $B\subset\bigcup I_j$ says just that $A\subset\bigcup I_j'$, where $I_j'=[(j-1)/n,j/n]$. And $$\sum V(I_j')=n\sum\frac1n=1.$$
Probably it would be better to write $V_n(I)$ instead of $V(I)$. The point being that $V(I_j')=V_1(I_j')=1/n$, while $V(I_j)=V_2(I_j)=1/n^2$, much smaller.
Comment: Thanks! My confusion came from reading the definition of zero measure before understanding the concept of $V(I)$.

Counter-intuitive zero measure thorem


Why I need to Rebuild whole solution when make change in razor cshtml file

Question: I wonder why every time I need to rebuild whole solution when I make changes to .cshtml file to see changes on web. It takes so much time and it is annoying when I just want to check some minor change in html (for example adding  element into table which will be filled with value from model)
Please can somebody explain it to me? I'm not very experienced in this area and I want to understand it more :)
Comment: Are you sure this isn't a caching issue?  If you're using Chrome or Firefox, keep the dev tools open and right click the refresh icon in your browser to do a hard reload of the page.
Comment: I´m sure, I always reload page with hard reload and clearing cache. Also tried to restart IIS. It is strange. I also thought it is compiled runtime because of that I posted this question, cos' im confused of it.
Comment: You're hosting it in IIS?  Is the website published to a folder there, or do you host the site out of the source folder?  Does this happen if you use Visual Studio's host process instead of IIS?
Comment: Yes it is hosted in IIS but I don´t know how it is published :( How can I discover please? Sorry for being such unusable in clarifying our working environment. I´m new to this and don't properly understand it :P
Comment: I have this problem as well, with one specific project. Never had this issue before. No idea what's causing it, but it's very annoying.
Answer: Late for the party?
I had the same issue in VS 2019 RC2 while working with out of the oven, still warm demo project based on the Razor Components App template. For each change to take effect I had to rebuild the project. I excluded browser cache issues and everything else I could think of or found mentioned on the web.
I found that in the .csproj file the razor file extensions was set to .cshtml:
  <PropertyGroup>
    <TargetFramework>netcoreapp3.0</TargetFramework>
    <LangVersion>7.3</LangVersion>
    <_RazorComponentInclude>Components\**\*.*cshtml*;</_RazorComponentInclude>
  </PropertyGroup>

...while the actual file extensions were .razor. After renaming the .razor files to have .cshtml extension everything worked as expected.
Note, it didn't work the other way around, editing the .csproj file to look for .razor extension because there was a conflict in two stock .target files that I didn't want to touch.
Answer: That depends on the change.
If it is a razor change, yes you need to build (compile dlls). If it is not, that you don't.
Razor syntax is a view syntax of c#. It is used in views and transformed into html via the Razor View Engine.
By being C# code, you need to generate it's IL by doing a build or rebuild. Basically you are telling the compiler to generate a new IL based on your changes. Than the web server uses the dlls to run the app.


Can Mezzanine send an email to admin when a user signs up?

Question: Is there any way to configure Mezzanine so that the admin user gets an email when a new (regular) user signs up? I have ACCOUNTS_VERIFICATION_REQUIRED=True, so the would-be user gets an email, but I don't want to have to approve accounts myself (ACCOUNTS_APPROVAL_REQUIRED).
If this isn't possible out of the box, do I need to customize the accounts app? Or monkey-patch UserProfileAdmin.save_model? What is the best approach?
Comment: Don't know off the top of my head if there's an easier solution but before you go monkey-patching *any* `save_model` method in Django, consider using the `pre_save` or `post_save` signal instead. https://docs.djangoproject.com/en/stable/topics/signals/
Answer: For the sake of closure, here is the solution I was more or less handed from Steve MacDonald himself on the mezzanine-users mailing list. The setting ACCOUNTS_PROFILE_FORM_CLASS allows one to specify a custom form class for user profile signup/update. So, in settings.py set:
ACCOUNTS_PROFILE_FORM_CLASS = "myapp.forms.MyCustomProfileForm"

And in myapp.forms.py send the email on save:
from mezzanine.accounts.forms import ProfileForm

class MyCustomProfileForm(ProfileForm):
    def save(self, *args, **kwargs):
        user = super(MyCustomProfileForm, self).save(*args, **kwargs)
        if self._signup:
            # send email here
        return user

This worked very well for me.


How many open sets are needed to separate all pairs of disjoint closed sets?

Question: Let $\mathscr{U}$ be a collection of open subsets of $\mathbb{R}$ which separates closed sets. That is, for every pair of disjoint closed sets $A,B \subset \mathbb{R}$, there exist disjoint $U,V \in \mathscr{U}$ such that $A \subset U$ and $B \subset V$. Is it obvious that $\mathscr{U}$ needs to have $\mathfrak{c}$ elements?
Answer: Every subset of $\mathbb Z$ is closed. Let as assign to each $A\subseteq\mathbb Z$ disjoint open sets $U_A$, $U_{\mathbb Z\setminus A}$ such that $A\subseteq U_A$ and $\mathbb Z\setminus A\subseteq U_{\mathbb Z\setminus A}$. Then the map $A\mapsto U_A$ is an injective map from $\mathcal P(\mathbb Z)$ to $\mathscr U$.
Proof of injectivity: Let $B\ne A$, w.l.o.g $B\subsetneqq A$. Let  $a\in A\setminus B$. Then $a\in U_A$, since $a\in A$. Also $a\in\mathbb Z\setminus B$ implies $a\notin U_B$. Thus $U_A\ne U_B$.

EDIT: The above answers the original question. I just want to add some thoughts what can change if we work with a compact subspace of $\mathbb R$ instead of the whole real line.
So let us ask the same question about $[0,1]$ instead of $\mathbb R$. Since $[0,1]$ is compact, we cannot find infinite closed discrete subspace in it, so the above trick will not work.
We have a countable basis $\mathcal B=\{(p,q)\cap[0,1]; p<q, p,q\in\mathbb Q\}$ for this space. Using compactness we can show that any two closed subsets can be separated by sets $U$, $V$ such that each of them is a finite intersection of finite unions or a finite union of finite intersections of basic sets from $\mathcal B$. (See bellow.)  I.e., every separating set is of the form $\bigcap_{i=1}^k \bigcup_{j=1}^l B_{ij}$ or of the form $\bigcup_{i=1}^k \bigcap_{j=1}^l B_{ij}$, where each $B_{ij}$ is in $\mathcal B$. The system $\mathscr U$ consisting of all such sets is countable system of open sets. (The set of all finite sequences of element of given countable set is again countable.) So in this space, a set of size $\aleph_0$ is sufficient.
Basically the same proof would work in any second countable compact space.

We know that any two points can be separated by basic sets from $\mathcal B$. Suppose we are given two disjoint closed sets $A$ and $B$. Closed subsets of compact space are compact.
We can show that for any $x\notin A$ there exist sets $U_x$ and $V_x$ such that:

$A\subseteq U_x$, $x\in V_x$ and $U_x\cap V_x = \emptyset$ (i.e., these sets separate $U$, $V$)
$U_x$ is a finite union of sets from $\mathcal B$
$V_x$ is a finite intersection of sets from $\mathcal B$

The proof of this fact is exactly the same as in this answer with the only exception that we have to work with basic sets only.
Now we can repeat basically the same argument again. For every $b\in B$  we have sets $U_b$, $V_b$ with the above properties. Now as $V_b$ is an open cover of $B$, thus there exists finite subcover $\{V_b; b\in F\}$. The sets $U:=\bigcap_{b\in F} U_b$ and $V:=\bigcup_{b\in F} V_b$ separate $A$ and $B$ and they belong to the family $\mathscr U$ described above.
Comment: Perfect, thank you Martin.


Fourier transform inversion formula for $f\in L_1(\mathbb{R}^n)$ and Dini condition

Question: Let us define the Dini condition for a function $f\in L_1(-\infty,\infty)$, i.e. Lebesgue summable on $\mathbb{R}$, as

Given an $x\in\mathbb{R}$ there is a $\delta>0$ such that the Lebesgue integral $\int_{[-\delta,\delta]}|\frac{f(x+t)-f(x)}{t}|d\mu_t$ exists.

In all the post the integrals are to be intended as Lebesgue integrals. I know (p. 423, here, of Kolmogorov-Fomin's Элементы теории функций и функционального анализа) that, if $f\in L_1(-\infty,\infty)$ satisfies the Dini condition in $x\in\mathbb{R}$, then the inversion formula for the Fourier transform holds: $$f(x)=\frac{1}{2\pi}\lim_{N\to+\infty}\int_{[-N,N]}\Bigg(\int_{\mathbb{R}}f(t)e^{-i\lambda t)}d\mu_t\Bigg)e^{i\lambda x} d\mu_\lambda.$$
The same famous text proves (p. 437-438) a similar theorem for functions $f\in L_1(\mathbb{R}^n)$, under conditions that I do not fully understand, stated in the following way:

Let function $f(x_1,x_2,\ldots,x_n)$ ne integrable on the whole space $\mathbb{R}^n$ and let it satisfy the conditions:
  $$|f(x_1+t_1,x_2,\ldots,x_n)-f(x_1,x_2,\ldots,x_n)|\leq C|t_1|^a,$$ $$|f(x_1,x_2+t_2,\ldots,x_n)-f(x_1,x_2,\ldots,x_n)|\leq C(x_1)|t_2|^a,$$$$\ldots\ldots\ldots\ldots\ldots\ldots\ldots\ldots\ldots\ldots\ldots\ldots\ldots\ldots\ldots\ldots$$$$|f(x_1,x_2,\ldots,x_n+t_n)-f(x_1,x_2,\ldots,x_n)|\leq C(x_1,x_2,\ldots,x_{n-
> 1})|t_n|^a,$$where $0\le a\le1,\quad\int_{\mathbb{R}}C(x_1)d\mu_{x_1}<\infty,\ldots,\quad\int_{\mathbb{R}}\ldots\int_{\mathbb{R}}C(x_1,\ldots,x_{n-1})d\mu_{x_1}\ldots d\mu_{x_{n-1}}<\infty.$
  Then $$(2\pi)^nf(x_1,x_2,\ldots x_n)=$$$$=\lim_{N_1\to\infty}\int_{-N_1}^{N_1}\Big(\ldots\lim_{N_{n-1}\to\infty}\int_{-N_{n-1}}^{N_{n-1}}\Big(\lim_{N_n\to\infty}\int_{-N_n}^{N_n}g(\lambda_1,\ldots,\lambda_n)e^{ix_n\lambda_n }d\mu_{\lambda_n}\Big)e^{ix_{n-1}\lambda_{n-1}}d\mu_{\lambda_{n-1}}...\ldots\Big)e^{ix_1\lambda_1}d\mu_{\lambda_1} $$

where the integrals are Lebesgue integrals and $g(\lambda_1,\ldots,\lambda_n):=\int_{\mathbb{R}}\ldots\int_{\mathbb{R}}f(x_1,\ldots,x_n)e^{-i\sum_{k=1}^nx_k\lambda_k}d\mu_{x_1}\ldots d\mu_{x_n}$.
The theorem is precisely stated in this way in the book (I've only changed some notation to clearly show the integrals are Lebesgue integrals), but I am not sure to understand what are $a$ and the $t_k$ in this wording. Does anybody passing by know the theorem and what the inequalities mean: must they hold for some $a\in[0,1]$ or for all $a\in[0,1]$? As to the $t_k$, $k=1,\ldots ,n$ must they satisfy the inequality for some $\delta>0$ such that $t_1,\ldots,t_n\le\delta$?
The proof seems to use the fact that the function $f(-,x_2,\ldots ,x_n)$ as a function of $x_1$ satisfies the above defined Dini condition: does it? Why can we see that? In particular, I am not convinced that $a=0$ could guarantee the Dini condition ($\int_{0}^1 x^{-1}dx=+\infty$).
I think that my greatest problem is that I do not understand the conditions in the theorem's statement... Thank you so much for any explanation!
Comment: The mentioned book is the "Elements of theory of functions and functional analysis" by Kolmogorov and Fomin.
Comment: Tочно. Cпасибо за комментарий!
Answer: The Riemann-Lebesgue lemma states that, for any $f \in L^{1}(\mathbb{R})$,
$$
                 \lim_{R\rightarrow\pm\infty}\int_{-\infty}^{\infty}f(t)e^{-iRt}\,dt = 0.
$$
This becomes the basis for a lot of basic pointwise convergence theorems. If $\mathcal{F}$ denotes the Fourier transform on $\mathbb{R}$, and $\mathcal{F}^{-1}$ its inverse transform, then
$$
             \mathcal{F}^{-1}(\chi_{[-R,R]}\mathcal{F}f)|_{x}-L=\frac{1}{\pi}\int_{-\infty}^{\infty}\frac{f(t)-L}{t-x}\sin(R(t-x))\,dt.
$$
The function $\frac{f(t)-L}{t-x}$ is absolutely integrable for $t \in (-\infty,x-\delta]\cup[x+\delta,\infty)$ whenever $\delta > 0$. If it is also integrable on $[x-\delta,x+\delta]$, then the Riemann-Lebesgue lemma gives
$$
           L = \lim_{R\rightarrow\infty}\mathcal{F}^{-1}(\chi_{[-R,R]}\mathcal{F}f)|_{x}.
$$
The Dini condition is nothing more than the additional assumption required to guarantee that $f \in L^{1}$ or $f\in L^{2}$ gives rise to a function $\frac{f(t)-L}{t-x}$ which is absolutely integrable in $t$ for a fixed $x$, where $L=f(x)$. One way to guarantee this condition is by assuming $f$ is $\alpha$-Holder continuous at $x$ with exponent $\alpha \in (0,1]$:
$$
                          |f(t)-f(x)| \le C|t-x|^{\alpha}.
$$
This condition is sufficient in order the Dini condition to hold, but not necessary, but Holder continuity is convenient, especially for Sobolev spaces.
The conditions stated in your theorem allow you to evaluate the full inverse Fourier transform on $\mathbb{R}^{n}$ by evaluating with iterated integrals. That's why the conditions stated are "staggered" in some sense. But they're set up so that the inversion integral can be evaluated using iterated integrals and limits. That is, if $B_{N}$ is the box in $\mathbb{R}^{n}$ described by $\{ x : |x_{k}| \le N_{k},\; 1 \le k \le n\}$, then
$$
        \mathcal{F}^{-1}(\chi_{B_{N}}(x)\mathcal{F}f)
           = \mathcal{F_{n}}^{-1}\chi_{[-N_n,N_n]}\mathcal{F_{n-1}}^{-1}\chi_{[-N_{n-1},N_{n-1}]}\cdots \mathcal{F_{1}}^{-1}\chi_{[-N_1,N_1]}\mathcal{F}f,
$$
where $\mathcal{F_{k}}^{-1}$ is the inverse Fourier transform in the $k$-th coordinate variable only.
Knowing that the inversion integral exists on the whole space allows you to evaluate by iterated limits, and the imposed conditions allow you to move the limits inside the transforms to the location where they can be evaluated using the Riemann-Lebesgue/Dini procedure described above for a single variable, one at a time.
Comment: Thank you very much! In the language of the Dini condition expressed by Kolmogorov and Fomin, the $n$ inequalities for $|t_1|,...,|t_n|<\delta$, guarantee that $|\frac{f_{k-1}(x_1,...,x_k+t_k,...,x_n)-f_{k-1}(x_1,...,x_k,...,x_n)}{t_k}|\le \int_{\mathbb{R}} ...\int_{\mathbb{R}}C(x_1,...,x_{k-1})|t_k|^{a-1}d\mu_{x_1}...d\mu_{x_{k-1}}$ and this inequality, if $a\in(0,1]$ (but not $a=0$: a misprint?), guarantees...
Comment: ...that $\int_{[-\delta,\delta]}\Big|\frac{f_{k-1}(x_1,...,x_k+t_k,...,x_n)-f_{k-1}(x_1,...,x_k,...,x_n)}{t_k}\Big|d\mu_{t_k}\le\int_{[-\delta,\delta]}\int_{\mathbb{R}}...\int_{\mathbb{R}}C(x_1,...,x_{k-1})|t_k|^{a-1}d\mu_{x_1}...d\mu_{x_{k-1}}d\mu_{t_k}<\infty$


Pie chart wont generate - dash/plotly

Question: I'm trying to create a Pie chart in plotly. There are no errors, but it won't show up.
I've created a date range picker which works and provides the results I need, but I haven't tried it with the pie chart just yet, as I want to test the chart with some arbitrary numbers first. Can you help me get it running please? Below is the code:
app = dash.Dash()

app.layout = html.Div([

    dcc.DatePickerRange(
        id='my-date-picker-range',
        min_date_allowed=dt(2019, 4, 1),
        max_date_allowed=dt(2019, 6, 30),
        #initial_visible_month=dt(2019, 4, 1),
        end_date=dt(2019, 4, 2),
        start_date=dt(2019, 4, 1)
    ),
    html.Div(id='output-container-date-picker-range')
])

@app.callback(
    dash.dependencies.Output('output-container-date-picker-range', 'children'),
    [dash.dependencies.Input('my-date-picker-range', 'start_date'),
     dash.dependencies.Input('my-date-picker-range', 'end_date')])

def update_output(start_date, end_date):

    #some calculations

    return{
            'data': [go.Pie(labels=['Navy','Sand'], values=[50,50],
                             marker={'colors': ['#EF963B','C93277']},textinfo='label')
                    ],

            'layout': go.Layout(
                title='distribution',
                margin={'l': 100, 'r': 10},
                legend={'x': 0, 'y': 1.5},

            )
        }

if __name__ == '__main__':
    app.run_server()

Answer: Your callback right now returns a dict into the children of an html.Div component, so you're missing a dcc.Graph somewhere. Try return dcc.Graph({...}) instead of return {...}
Comment: nah just tried it, the datepickerrange still works but nothing is generated
Comment: That's very surprising... can you post your updated code? You definitely will not see a graph without invoking `dcc.Graph()` somewhere :)

Pie chart wont generate - dash/plotly


Limits to infinity of exponential functions

Question: I am completly blocked trying to prove the solution of the limits below
1)
$$
\lim _{m\to\infty}\left(\cos\left(\frac{x}{m}\right)\right)^m\\1 \quad \text{ for }  a\to +\infty;\quad 0 \quad \text{ for } \quad a \to -\infty
$$
2)
$$
\lim _{a\to\infty}\frac{a^x-1}{x}, a>1\\+\infty\, \text{ for }\,  x\to +\infty;0\, \text{ for }\, a \to -\infty
$$
I believe both limits are related to $\lim_{x\to\infty}(1+\frac{1}{x})^x =e$, but I just can't find a way to get there.
In case 1) I get $(1^+)^\infty$ which I can't simplify and get to a clear limit
In case 2) using the change of variable $y = a^x-1$, I can get to
$$
\lim _{a\to\infty}\frac{a^x-1}{x} = \lim _{a\to\infty}\frac{\ln(a)}{\ln(1+y)^\frac{1}{y}}
$$
but I then obtain a $\infty^\frac{1}{\infty}$, which, again, I can't solve.
Can someone give some hints on what I am missing here? Or am I using a completly wrong approach?
Comment: the dneominator in (2) should be $a$ and not $x$, no?
Comment: 2) can be $\lim\limits_{a\to 0}\frac{a^x-1}{a}$ or $\lim\limits_{x\to 0}\frac{a^x-1}{x}$, both can be looked up via searchonmath
Comment: @hunter the denominator is $x$.
Comment: problem 2) is correct as I have written in the question. There is no typo
Answer: For (1), take a logarithm to get
$$
\lim_{m \to \infty} \frac{\log \cos\left( \frac{x}{m} \right)}{\frac{1}{m}},
$$
which by L'Hôpital is
$$
\lim_{m \to \infty}\frac{-\sin \left( \frac{x}{m} \right)\frac{x}{m^2}}{\cos\left(\frac{x}{m}\right)\frac{1}{m^2}},
$$
which simplifies to
$$
\lim_{m \to \infty} -x\tan\left(\frac{x}{m}\right),
$$
which is $0$, so the answer is $1$ since we took a logarithm.
For (2), the limit of the given function is clearly infinite, but I suspect there should be an $a$ in the denominator instead of an $x$. Then you can use L'Hôpital directly to get
$$
\lim_{a \to \infty} xa^{x-1}
$$
which is $1$ if $x = 1$, $0$ if $x < 1$, infinite otherwise.
Comment: Thank you for your answer, @hunter. I apologise, but I forgot a detail. I am not supposed to use L'hôpital's rule. That would be too easy :)
Answer: I'm taught to do $1^\infty$ only such way:
$$\begin{align*}
\lim\limits_{m\to\infty}\left(\cos\left(\frac{x}{m}\right)\right)^m &=
\lim\limits_{m\to\infty}\left(1+\cos\left(\frac{x}{m}\right)-1\right)^m\\
&=\lim\limits_{m\to\infty}\left(1+\cos\left(\frac{x}{m}\right)-1\right)^
{\frac{1}{\cos\left(\frac{x}{m}\right)-1}\cdot
\left(\cos\left(\frac{x}{m}\right)-1\right)m}\\
&=\left(
\lim\limits_{m\to\infty}\left(1+\cos\left(\frac{x}{m}\right)-1\right)^
\frac{1}{\cos\left(\frac{x}{m}\right)-1}\right)^{
\lim\limits_{m\to\infty}
\left(\cos\left(\frac{x}{m}\right)-1\right)m}\tag{1}\\
&=e^{
\lim\limits_{m\to\infty}
\left(\cos\left(\frac{x}{m}\right)-1\right)m};
\end{align*}$$
$$\begin{align*}
\lim\limits_{m\to\infty}
\left(\cos\left(\frac{x}{m}\right)-1\right)m
&=
\lim\limits_{m\to\infty}
\left(1-2\sin^2\left(\frac{x}{2m}\right)-1\right)m\\
&=-2\lim\limits_{m\to\infty}
\sin^2\left(\frac{x}{2m}\right)\cdot\frac{4m^2}{x^2}\cdot\frac{x^2}{4m}\\
&=-\frac{x^2}{2}\left(\lim\limits_{m\to\infty}
\sin^2\left(\frac{x}{2m}\right)\cdot\frac{4m^2}{x^2}\right)\cdot
\left(\lim\limits_{m\to\infty}\frac{1}{m}\right)\tag{2}\\
&=-\frac{x^2}{2}\cdot 1\cdot 0
\end{align*}$$
We can $(1)$ and $(2)$ because both limits exist and are finite.
Unless $x=0$ which can be simply plugged to the original limit as $\cos 0=1$
Answer: For $m$ near $\infty$,
$$\cos(\frac xm)=1-\frac{x^2}{2m^2}(1+\epsilon(m))$$
$$\ln(\cos(\frac xm))=-\frac{x^2}{2m^2}(1+\epsilon(m))$$
$$(\cos(\frac xm))^m=e^{m\ln(\cos(\frac xm))}=$$
$$\Large{e^{-\frac{x^2}{2m}(1+\epsilon(m))}}$$
So, $$\lim_{|m|\to+\infty}(\cos(\frac xm))^m=1$$
Answer: After almost 2 weeks, and with your help, I managed to find the obvious solution to problem 1)
$$
\lim_{m\to\infty}\left(\cos\left(\frac{x}{m}\right)\right)^m =  \lim_{m\to\infty}\left[\cos^2\left(\frac{x}{m}\right)\right]^{m/2} =  \lim_{m\to\infty}\left[1-\sin^2\left(\frac{x}{m}\right)\right]^{m/2} = \lim_{m\to\infty}\left[1-\left(\sin\left(\frac{x}{m}\right)/\frac{x}{m}\right)^2\frac{x^2}{m^2}\right]^{m/2} = \lim_{m\to\infty}\left[1-\lim_{m\to\infty}\left(\sin\left(\frac{x}{m}\right)/\frac{x}{m}\right)^2\frac{x^2}{m^2}\right]^{m/2} = \lim_{m\to \infty}\left[1-\lim_{w\to 0}\left(\sin\left(w\right)/w\right)^2\frac{x^2}{m^2}\right]^{m/2} =  \lim_{m\to \infty}\left[1-1\times\frac{x^2}{m^2}\right]^{m/2} = \lim_{m\to \infty}\left[\left(1-\frac{x}{m}\right)\left(1+\frac{x}{m}\right)\right]^{m/2} = \lim_{m\to \infty}\left(1-\frac{x}{m}\right)^{m/2} \times \lim_{m\to \infty}\left(1+\frac{x}{m}\right)^{m/2} = \lim_{y\to \infty}\left(1+\frac{1}{y}\right)^{-xy/2} \times \lim_{m\to \infty}\left(1+\frac{1}{z}\right)^{xz/2}
$$
Thanks everyone for your help


Problema com routerLink no angular 6

Question: Estou tendo o seguinte erro:
Can't bind to 'routerLink' since it isn't a known property of 'a'. ("

            Do not have an account yet?
            ][routerLink]="['/signup']">Sign up now!

Fiz algumas pesquisas, mas não encontrei nada que resolvesse.
Eu já importei o RouterModule e Routes em meu arquivo app-routing.module.ts: import { RouterModule, Routes } from '@angular/router';
E esse arquivo, estou importando no meu app.module.ts.
Esta funcionando perfeitamente, e do anda esta gerando o erro quando eu uso a propertyBinding do RouterLink.
Comment: poste seu código... e mais fácil identificar o erro
Comment: Da uma olhada [nessa pergunta](https://stackoverflow.com/questions/34317044/) do SOen
Comment: Eu já vi... não é isso...
Comment: #Tutorial [Suporte](http://jasonwatmore.com/post/2018/05/16/angular-6-user-registration-and-login-example-tutorial) tem vários objetos de suporte nesse tutorial tanto router, formbuild você cadastrou o router no constructor?
Comment: Só estou chamando o routerLink dentro de uma tag .
Não tem nada relacionando a formulário....
Também não instanciei o Router no contrutor
Answer: Importa o RouterModule no modulo que vc declara seu componente e não so no app module.
Comment: Perfeito. Obrigado!

Problema com routerLink no angular 6


Making a string out of pandas DataFrame

Question: I have pandas DataFrame which looks like this:
 Name  Number    Description
 car   5         red

And I need to make a string out of it which looks like this:
"""Name: car

Number: 5

Description: red"""

I'm a beginner and I really don't get how do I do it? I'll probably need to apply this to some similar DataFrames later.
Comment: What should be displayed if you have several entries in your dataframe?
Comment: Then I have to somehow print that info for only one row.
For example I have rows "car1", "car2", "car3". If user types "car1" I need to print car1 line
Answer: You can use iterrows to iterate over you dataframe rows, on each row you can then get the columns and print the result the way you want. For example:
import pandas as pd

dtf = pd.DataFrame({
    "Name": ["car", "other"],
    "Number": [5, 6],
    "Description": ["red", "green"]
})

def stringify_dataframe(dtf):
    text = ""
    for i, row in dtf.iterrows():
        for col in dtf.columns.values:
            text += f"{col}: {row[col]}\n"
        text += "\n"
    return text

s = stringify_dataframe(dtf)

Now s contains the following:
>>> print(s)
Name: car
Number: 5
Description: red

Name: other
Number: 6
Description: green

Comment: Thanks a lot! But can I somehow put it in a string, so I can just use it as variable in different needs
Comment: Yes sure, I'll update my answer (do you need one string per entry or one big string?)
Comment: I need one big string
Answer: Iterating over a Dataframe is faster when using apply.
import pandas as pd

df = pd.DataFrame({
    "Name": ["car", "other"],
    "Number": [5, 6],
    "Description": ["red", "green"]
})

s = '\n'.join(
        df.apply(
            lambda row:
            '\n'.join(f'{head}: {val}' for head, val in row.iteritems()),
            axis=1))

Of course, for this small data set a for loop is faster, but on my machine a data set with 10 rows was already processed faster.
Comment: ```for i in range (len (dtf)):
        print(f'{dtf.loc[i]}\n')``` or ```for row in dtf.to_string(index = False).split('\n'):
    print(row)``` may also be used but not what author has asked.
Answer: Another approach,
import pandas as pd

dtf = pd.DataFrame({
    "Name": ["car", "other"],
    "Number": [5, 6],
    "Description": ["red", "green"]
})

for row_index in range(len(dtf)):
    for col in dtf.columns:
        print(f"{col}: {dtf.loc[row_index, col]}")

Name: car
Number: 5
Description: red
Name: other
Number: 6
Description: green

[Program finished]

Making a string out of pandas DataFrame


Entity Framework Code First two relations between tables

Question: I have two tables which are kind of problematic.

The first table is about users and has - userId, username, password, etc.
The second is handling messages, so it has - messageId, senderId, receiverId, messageContent.

As you can see, both senderId and receiverId need to be related to userId from the users table.
But as I'm trying to use Code First, it just crashes.
I get an exception :

"Introducing FOREIGN KEY constraint 'FK_dbo.Messages_dbo.Users_ReceiverId' on table 'Messages' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints."

This is how I made the relations in the Message class :
    [ForeignKey("Sender")]
    public int SenderId { get; set; }
    public virtual User Sender { get; set; }

    [ForeignKey("Receiver")]
    public int ReceiverId { get; set; }
    public virtual User Receiver { get; set; }

Any ideas? I'm stuck right now. It works perfectly fine if I do it database-first, but not if I try it Code First.
Answer: In the generated .cs file in the Migrations folder, replace cascadeDelete: true with cascadeDelete: false, so for example:
AddForeignKey("dbo.Messages", "ReceiverId", "dbo.Users", "Id",
    cascadeDelete: true);
AddForeignKey("dbo.Messages", "SenderId", "dbo.Users", "Id",
    cascadeDelete: true);

Becomes:
AddForeignKey("dbo.Messages", "ReceiverId", "dbo.Users", "Id",
    cascadeDelete: false);
AddForeignKey("dbo.Messages", "SenderId", "dbo.Users", "Id",
    cascadeDelete: false);

Comment: For the record, if I only use a foreign key for one of the fields (for example only for Sender), it works flawlessly. However, the name of the receiver field would be something strange like "Receiver_User_UserId"...
Answer: By Default EF code first creates Cascade option set to true on Delete and Update Rule of Foreign Key table. you can check this from SQL Server management studio, by right clicking on the foreign key column of table then expand 'Insert and Update Specifications'.

for quick solutions to this problem just add this code on DBContext.cs or YourContext.cs class which you have setup DBSet information.
 protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();

    }

run the Add-Migration InitialContext command and Update-Database -Verbose command from Package manager console window of your project.
Answer: I think your answer is in this post
Entity Framework 4.1 InverseProperty Attribute
It says there is another decorator called InverseAttrivuteProperty which helps you define which end of the relationship in the origin table matches which end on the destiny table.
But, don´t use it as it is explained. I had to leave your decorator on the Foreign Keys.
Just tested it and it worked. Soon I´ll post something explanatory.
Answer: simply manually configure your entity relationships to avoid confusion to EF.
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Message>()
                .HasOptional(x => x.Sender)
                .WithMany(x => x.SenderMessages);
    modelBuilder.Entity<Message>()
                .HasOptional(x => x.Reciever)
                .WithMany(x => x.RecieverMessages);

}


Suppose $f$ is a measurable function and $f(x) > 0$ for all $x$. Let $g(x) = \frac{1}{f(x)}$. Prove that g is a measurable function.

Question: Suppose $f$ is a measurable function and $f(x) > 0$ for all $x$. Let $g(x) = \frac{1}{f(x)}$. Prove that g is a measurable function.
Using the definition of a measurable function I have,
$\{x : f(x) > a\} \in \mathcal{A}$ for all $a \in \mathbb{R}$.
Can I rewrite $\{x : f(x) > a\} = \{x : \frac{1}{f(x)} < \frac{1}{a} \} = \{x : g(x) < b, \frac{1}{a} = b\}$
Comment: You forgot to flip the inequality when taking reciprocals. Otherwise, you are essentially done.  If you want to convince yourself further, you can run the argument backwards and say "fix $b \in \mathbb{R}$, then $\{x : g(x)>b\} = ... \in \mathcal{A}$.  [edited comment: It looks like the existing answer that I just read does just this].
Comment: What makes you think that you *can't* write what you have written?
Comment: I'm worried making the change to the reciprocal would be removing some values of $x$.
Comment: Is your function target the reals or extended reals?
Answer: To show that a function is measurable, it is necessary to show that the preimage of each measurable set is measurable.  To do this, it is sufficient to show that the preimage of each interval of the form $(b,\infty)$ is measurable.  So, suppose that $b \in \mathbb{R}$.
If $b \in \mathbb{R}$, then we have
\begin{align}
g^{-1}((b,\infty))
&= \left\{ x : g(x) > b\right\} \\
&= \left\{ x : \frac{1}{f(x)} > b \right\} \\
&= \left\{ x : \frac{1}{b} > f(x) \right\} \\
&= f^{-1}\left( \left(-\infty, \frac{1}{b} \right)\right). \tag{$\ast$}
\end{align}
Since $f$ is a measurable function, the preimage of every open set is measurable, which implies that the set at ($\ast$) is measurable.  But this is what we needed to show, therefore $g = \frac{1}{f}$ is measurable.
Note that if we allow the range of $g$ to include $\pm\infty$ (i.e. if we work in the extended real numbers), this proof works perfectly well (with only slight modification) when we allow $f$ to take nonpositive values.  Thus the hypothesis that $f(x) > 0$ is not strictly necessary, though we do have to enlarge the codomain to make sense of the argument.
Comment: This makes plenty of sense. Aside from the fact it was incomplete thought. Is there anything you dislike about my approach. It seems very similar to your response, but you came from the other direction.
Comment: When proving a statement, I like to keep the end result in mind.  To show that $g$ is (Borel) measurable, I need to show that the preimage of **any** open set is measurable (since the open sets generate the Borel $\sigma$-algebra).  To do this, it is sufficient to show that the preimage of every interval (of whatever specific form I require) is measurable, since intervals generate the same $\sigma$-algebra.  Thus I start with an arbitrary interval, and work from there.  Your approach can be made to work, but feels backwards to me.


How to reference a hiera variable from elsewhere the hierarchy?

Question: So suppose in a very specific hiera YAML file I define a variable, such as "env_name".

env_name: "dev-unstable"

Now in a more general hiera file I'd like to interpolate that variable into a string.

server_name: "service-%{env_name}.%{::domain}"

My testing seems to imply that hiera variables from elsewhere in the hierarchy aren't made available for interpolation in general cases. Is that true, unfortunately?
Answer: For Hiera 5, used in Puppet 5+, use the following syntax:
server_name: "service-%{lookup('env_name')}.%{::domain}"

...where %{lookup('env_name')} is the part that gets the data from the other hiera key, env_name.
(Source)
Comment: Note: save yourself an hour and notice that there is a Puppet `lookup`  function and a Hiera `lookup` function with different signatures. The documentation is not clear about this (just includes a subnote) and as a reader, it is very difficult to search for one or the other.
Answer: You can use Hiera lookup functions within Hiera. Documentation here: https://docs.puppetlabs.com/hiera/1/variables.html#using-lookup-functions
In your case you would use:
server_name: "service-%{hiera('env_name')}.%{::domain}"

This is a priority lookup and will get the value for the key env_name from the highest (most specific) hierarchy level in which it finds the key.
This requires Hiera 1.3 or higher.
Answer: See the answer from Greg Dubicki.
To quote
"The hiera, hiera_array, hiera_hash, and hiera_include functions are all deprecated. The lookup function is a complete replacement for all of these."
For details see:
https://puppet.com/docs/puppet/5.5/hiera_migrate.html#updated_classic_hiera_function_calls


NodeJS readdirSync() not executed

Question: I'm a beginner in non-blocking environment, such NodeJS. Below is my simple code, which list all files in directory :
var readline = require('readline');
var rl = readline.createInterface(process.stdin, process.stdout);
var fs = require('fs');

var datafolder = './datafolder';
var datafoldername = 'datafolder';

rl.setPrompt('Option> ');
rl.prompt();
rl.on('line', function(line) {
    if (line === "right") rl.close();

    if (line == '1') {
        listFile();
    }

    rl.prompt();
}).on('close', function() {
    process.exit(0);
});

function listFile() {
    console.log(`File(s) on ${datafolder}`);
    fs.readdirSync(datafolder, (err, files) => {
        if (err) {
            console.log(err);
        } else {
            files.forEach(filename => {
                console.log(filename);
            });
        }
    });
}

If user press 1, it's suppose to execute method listFile and show all files inside.
My question is, why fs.readdirSync not executed? The program works if I do it with readdir(), but it'll mess the output to user.
Answer: You are passing a callback to fs.readdirSync() but *Sync() functions don't take callbacks. The callback is never run (because the function does not take a callback), so you see no output. But fs.readdirSync() does in fact execute.
fs.readdirSync() simply returns it's value (which may make the program easier to read, but also means the call will block, which may be OK depending on what your program does and how it is used.)
var resultsArray = fs.readdirSync(datafolder);

(You may want to wrap it in a try/catch for error handling.)

NodeJS readdirSync() not executed


Recurrence for integral $I_{n}=\int_{0}^{1}x^{n}\sqrt{1-x^2}\: dx$

Question: If $$I_{n}=\int_{0}^{1}x^{n}\sqrt{1-x^2}\: dx$$
show that $$(n+2)I_{n}=(n-1)I_{n-2}$$
Ok, here is what I've tried $$I_{n}=\int_{0}^{1}x^{n-1}x\sqrt{1-x^2}\:dx$$ and the I use integration by parts with $x\sqrt{1-x^2}=(-\frac{1}{3}\sqrt{(1-x^2)^3})^{'}$ wich gives me problems with that $-\frac{1}{3}$. This is one of my aproaches, the other ones are in this method, with integration by parts. But nothing. Also, I need a solution without using gamma function.
Comment: Please don't tell us to not tell you to share the own thoughts, 'cause we are so many...
Comment: Could you at least tell us what approaches you've tried?
Comment: Yes, I can, but not right now cause I'm not home and it s not easy to go on the phone
Comment: Try integrating $\int_0^1x^n\sqrt{1-x^2}\,\mathrm{d}x=-\frac13\int_0^1x^{n-1}\,\mathrm{d}\sqrt{1-x^2}^3$ by parts
Answer: Integrate by parts instead as follows
\begin{align}
(n+2) I_n &= (n+2)\int_0^1 x^n \sqrt{1-x^2} \;dx \\
&= -\int_0^1 x^{n-1}{(1-x^2)^{\frac{1-n}2}}\ d\left[(1-x^2)^{\frac{n+2}2}\right]\\
&= -x^{n-1}(1-x^2)^{3/2}\bigg|_0^1
+(n-1)\int_0^1 x^{n-2} \sqrt{1-x^2} \;dx \\
&=  (n-1)I_{n-2}
\end{align}
Answer: We may use immediately the beta function,
https://en.wikipedia.org/wiki/Beta_function
directly or indirectly after the substitution $x=\sin t$,
then obtain the wanted relation by passing to the gamma function and using its functional equation $\Gamma(x+1)=x\Gamma(x)$:
$$
\begin{aligned}
I_n
&=
\int_0^1 x^n(1-x^2)^{1/2}\; dx
\\
&=
\int_0^{\pi/2}\sin^n t\; \cos^2 t\; dt
\\
&=
\frac 12B\left(\frac{n+1}2,\; \frac{2+1}2\right)
\\
&=
\frac 12
\frac
{
\Gamma\left(\frac{n+1}2\right)
\Gamma\left(\frac{2+1}2\right)}
{
\Gamma\left(\frac{n+4}2\right)
}
\\
&=
\frac 12
\frac
{
\color{blue}{\frac{n-1}2}
\Gamma\left(\frac{n-1}2\right)
\Gamma\left(\frac{2+1}2\right)}
{
\color{blue}{\frac{n+2}2}
\Gamma\left(\frac{n+2}2\right)
}
\\
&=
\color{blue}{\frac{n-1}{n+2}}
I_{n-2}\ .
\end{aligned}
$$
Comment: If we are going to use an explicit solution using the Beta function, we don't really need a recurrence. All that is really needed for the recurrence is integration by parts; a lot less machinery.
Comment: There are some vestigial $B$s in lines $4$ and $5$.
Comment: @robjohn This was important, i am always grateful for such hints, the only way to avoid my systematic errors. (I have to see them explicitly and make a knot in my mind to have one more check in similar cases.) Thanks a lot!


interval regular expression in awk doesnt work as expected

Question: I have a bunch of files that have comma separated fields and I'm on redhat linux. I'm executing the following awk command like this:
 awk  --re-interval -F "," '$4~/xyz:8080\/proxyval\/getPages.do\?fd=1d[0-9]{1}/ { print }' *

204:1,204,null,xyz:8080/proxyval/getPages.do?fd=1d7d7 ----> dont expect to see this
204:1,204,null,xyz:8080/proxyval/getPages.do?fd=1d8
204:1,204,null,xyz:8080/proxyval/getPages.do?fd=1d8d8  ----> dont expect to see this
204:1,204,null,xyz:8080/proxyval/getPages.do?fd=1d3

The fd=1d[0-9]{1} part of regxp  should match only fd=1d8 fd=1d3 but it seems to match  fd=1d7d7 and 'fd=1d8d8' also. Please let me know If I'm missing something here.
Thanks in advance
Regards
Comment: If you need the `--re-interval` flag to enable RE intervals then you are using an extremely old version of gawk, get a new one. Also, `{print}` is the default action given a true condition, you don't need to write it explicitly.
Answer: Regexp matches find substrings, not whole strings; to find an exact match, you must anchor the start (^) and end ($) of string. [0-9]{1} is equivalent to [0-9] (one character from 0 to 9).
I.e. fd=1d[0-9]{1} will find blahfd=1d8732, with the matched region being fd=1d8; ^fd=1d[0-9]$ will not match it, but will match fd=1d8.


How to iterate through all pages in Space in Confluence Cloud using REST API in Python

Question: I have a set of pages for "SOW","Data from Client", "Deliverable", etc inside many Spaces. I am reading the Space Key from Excel and able to iterate through all Spaces. However, I'm unable to figure out a way to loop through each page inside the Space. I have to look at each one to see its type before uploading the right document. Can you please let me know how to do this.
wiki/rest/api/search?cql=space= " + keyName
Use this line for getting the Space. Extract the Json - res1 = response11.json() and loop through                 while x <= 6:
name = str(res1['results'][x]['title'])
However, this does not look for all the pages. In fact, it picks up the pages randomly.
I would appreciate it if you could give me a code snippet for performing this please.
Answer: Even better answer is to extract the results from the REST API response and loop through them using this code -
<code>            pages = res1['children']['page']['results']
            i = 0
            for p, page in enumerate(pages):
                if(projectName == str(page['title'])):
                    print("Page Name - " + str(page['title']))
                    pageID = page['id']
</code>
Answer: Was able to figure out how to do this.
Below is the API I am using -
wiki/rest/api/space/" + spaceName + "/content"
Following is the code I am using for iterating through each page -
<code>headers = {"Accept": "application/json"}
response11 = requests.request("GET", url, auth=auth)
if response11.status_code != 404:
    res11 = response11.json()
    x = 0
    while x < len(res11['page']['results']):
        name = str(res11['page']['results'][x]['title'])
        x = x + 1
 time.sleep(6)
</code>
Comment: Apparently what I thought is not the solution. I want to find a way for iterating through the Json results returned after firing the Rest API. Please let me know if any of you have any idea on this.


Does $\int_0^\infty\frac{\ln(1+x)}{x(1+x^n)}dx$ have a general form?

Question:
Does $$I_n=\int_0^\infty\frac{\ln(1+x)}{x(1+x^n)}dx$$ have a general form?

I tried to evaluate some small $n$s.
For $n=1$, $I_1$ is obviously $\frac16\pi^2$.
For $n=2$, see here.
$I_2=\frac5{48}\pi^2$.
For $n=3$, I put it in Mathematica and get $$\small{\frac{1}{108} \left(9 \left(4 \left(\text{Li}_2\left(\frac{\sqrt[6]{-1}}{\sqrt{3}}\right)+\text{Li}_2\left(-\frac{(-1)^{5/6}}{\sqrt{3}}\right)\right)+\log ^2(3)\right)+5 \pi ^2\right)}$$ Use the result $$\Re\operatorname{Li}_2\left(\frac{1+ti}2\right)=\frac1{12}\pi^2-\frac12\arctan^2t-\frac18\ln^2\frac{1+t^2}4,$$ I'm able to show $I_3=\frac5{54}\pi^2$.
For $n=4$, I numerically found $I_4=\frac{17}{192}\pi^2$.
I'm not able to find the general form with $n\in \mathbb{Z}^+$.
Comment: Sorry for not perceiving the answer in the linked question can be applied in this question. Feel free to close this question as a duplicate of that one.
Answer: $$\begin{aligned}
I_n &= \int_0^1 \frac{\ln(1+x)}{x(1+x^n)}dx + \int_1^\infty \frac{\ln(1+x)}{x(1+x^n)}dx \\
&= \int_0^1 \frac{\ln(1+x)}{x(1+x^n)}dx + \int_0^1 \frac{x^n \ln(1+x)}{x(1+x^n)}dx - \int_0^1 \frac{x^{n-1} \ln x}{1+x^n}dx \\
&= \int_0^1 \frac{\ln(1+x)}{x}dx + \frac{1}{n}\int_0^1 \frac{\ln(1+x^n)}{x}dx \\
&= \int_0^1 \frac{\ln(1+x)}{x}dx+\frac{1}{n^2}\int_0^1 \frac{\ln(1+u)}{u}du = \color{blue}{(1+\frac{1}{n^2})\frac{\pi^2}{12}}
\end{aligned}$$

Second line: $x\mapsto 1/x$
Third line: Integration by parts
Fourth line: $x=u^{1/n}$

Note that $n$ need not be an integer.
Comment: @Zacky  The third term in the second line.
Comment: Hi, can you tell me which one of the integral in the third line have you integrated by parts?
Answer: We first split the integral into two.
$$
I=\int_0^{\infty} \frac{\ln (1+x)}{x\left(1+x^n\right)} d x
= \int_0^1 \frac{\ln (1+x)}{x\left(1+x^n\right)} d x+\int_1^{\infty} \frac{\ln (1+x)}{x\left(1+x^n\right)} d x
$$
For the second integral, let $x\mapsto \dfrac{1}{x} $, then
$$
\int_1^{\infty} \frac{\ln (1+x)}{x\left(1+x^n\right)} d x =\int_0^1 \frac{x^{n-1}[\ln (1+x)-\ln x]}{x^n+1}dx
$$
Plugging back yields
$$
\begin{aligned}
I & =\int_0^1\left[\frac{\ln (1+x)}{x\left(1+x^n\right)}+\frac{x^{n-1} \ln (1+x)}{x^n+1}\right] d x-\int_0^1 \frac{x^{n-1} \ln x}{x^n+1} d x \\
& =\int_0^1 \frac{\ln (1+x)}{x} d x-\frac{1}{n} \int_0^1 \ln x d \ln \left(x^n+1\right) \\
& =\int_0^1 \frac{\ln (1+x)}{x} d x+\frac{1}{n} \int_0^1 \frac{\ln \left(x^n+1\right)}{x} d x
\end{aligned}
$$
For any natural number $n$,
$$
\begin{aligned}
\int_0^1 \frac{\ln \left(x^n+1\right)}{x} d x = & \int_0^1 \frac{1}{x} \sum_{k=0}^{\infty}(-1)^k x^{n k} \\
= & \sum_{k=1}^{\infty} \frac{(-1)^{k-1}}{k} \int_0^1 x^{n k-1} d x \\
= & \frac{1}{n} \sum_{k=1}^{\infty} \frac{(-1)^{k-1}}{k^2} \\
= & \frac{\pi^2}{12 n}
\end{aligned}
$$
Now we can conclude that
$$
\boxed{I=\left(1+\frac{1}{n^2}\right) \frac{\pi^2}{12}}
$$


IISAdmin won't start, error 0x80090006 - how to troubleshoot further?

Question: A while back my Windows Server 2003 machine hung up and I needed to force-reboot by power-cycling it. When it was restarting it ran chkdsk, and chkdsk reported some problems.
Since then IISAdmin has not been able to start (which means that IIS doesn't work at all):
C:\WINDOWS\system32>sc query iisadmin

    SERVICE_NAME: iisadmin
    TYPE               : 20  WIN32_SHARE_PROCESS
    STATE              : 1  STOPPED
                            (NOT_STOPPABLE, NOT_PAUSABLE, IGNORES_SHUTDOWN))
    WIN32_EXIT_CODE    : 1066  (0x42a)
    SERVICE_EXIT_CODE  : -2146893818  (0x80090006)
    CHECKPOINT         : 0x0
    WAIT_HINT          : 0x0

I suspected a corrupt Metabase so I tried restoring from a Metabase History file dated earlier than the crash -- but no luck.
Not really sure how to troubleshoot this further. There's one apparently-related error in the SYSTEM log that comes up regularly, event ID 10010 from DCOM:
The server {A9E69610-B80D-11D0-B9B9-00A0C922E750} did not register with DCOM
within the required timeout.

But I'm not sure if this actually sheds additional light or if it's just another warning that IISAdmin can't start.
Otherwise the Event logs are pretty empty of help. What's the next step to isolate this problem and fix it? I should point out that I don't have the luxury of rebooting this server very often -- it's an app server, and the users who depend on the app work until late at night, and I would need to be on-site to reboot it because it doesn't always restart reliably -- but I normally work off-site.
So if there's any way to keep investigating this without needing to reboot, I'm eager to hear it.
Answer: According to winerror.h, 0x80090006 means "NTE_BAD_SIGNATURE", which is a return from the Win32 API call "CryptVerifyMessageSignature", and means that "The message's signature was not verified."  Looks like a failure of a cryptographic signature check on some file related to the iisadmin startup, to me.
I'd consider doing an "SFC /SCANNOW" to see if you can replace the screwed-up file, assuming that the System File Checker can get to some Windows installation files, and assuming that it is a screwed-up file. (Yes-- "screwed-up" is a technical term. Sounds better than "corrupt" to me. Corrupt? Was the file taking bribes?)
If you're not getting it to work after an "SFC /SCANNOW", I'd probably fire up "Process Monitor" and watch what files are getting loaded. There will be a LOT of log entries generated, but you might find the needle in that haystack.
Given that the machine took a hard power-down and had some filesystem corruption, I'd put my money on "SFC /SCANNOW" finding one or more damaged files.
Aside: So, it won't restart reliably, eh?  Gives me a "The web site is down!"  kind of feeling... (DO NOT REBOOT THE WEB SERVER!!!!!! Heh heh...)
Comment: I looked into SFC and chickened out -- couldn't find any way to run it so that it would just report on possible problems, rather than automatically correcting them. So I've been using Process Monitor instead and unfortunately it hasn't shed too much light. I did finally find MSDN blog entry that seems related, though, and it keeps coming back to "reinstall IIS": http://blogs.msdn.com/vivekkum/archive/2009/02/14/machinekey-in-iis.aspx
Comment: "SFC /SCANNOW", from a command prompt, will do what you want. I'd do that before I'd reinstall IIS.
Comment: It just occurred to me -- do you happen to know if the SFC utility uses VSS? Because that doesn't work on this server (yes, I know, the server is a wreck. Unfortunately it's also our primary machine and the most expensive piece of equipment in the building). It was actually a VSS operation that caused the lock-up that led to the hard-restart... ugh.
Comment: OK it's not as expensive as our digital printing press. Most expensive piece of strictly-IT equipment in the building.
Comment: No, SFC doesn't use VSS.
Comment: OK, thanks. I've found a workaround for the time being that doesn't require IIS but I will almost certainly need to get IIS running on this server soon - so I will fiddle with it during off-peak hours and report back.
Answer: Just re-install IIS from Add/Remove Programs > Windows Components.  I have installed it before on Windows 2003 servers before and have not had to reboot.
Comment: Oh. Didn't realize I could do that. I thought I had to remove and then re-add the "application server" role -- which would also turn off some other stuff that our non-web-based apps rely on, thus being the practical equivalent of a reboot. I will try the Windows Components approach if I can't dig anything up with SFC or Procmon, thanks.


custom field - How to get saved term selected for entity_autocomplete

Question: I've looked all over, and for my level of understanding, I can't figure out how to get the stored value of an entity autocomplete field targeting taxonomy term type. I thought I could do something similar to what I have for select field, but it breaks the page. This is for a custom field...
<code>    $element['description_term'] = array(
      '#type' => 'entity_autocomplete',
      '#target_type' => 'taxonomy_term',
      '#selection_settings' => [
        'target_bundles' => [
          'descriptors'
        ],
      ],
      '#title' => t('descriptor'),
      'default_value' => previously-entered-value,
      // this didn't work... '#default_value' => isset($items[$delta]->descriptor) ? $items[$delta]->descriptor : NULL,
      '#required' => FALSE,
  );
</code>
Comment: Where is your "description_term" field saved?
Comment: Please forgive...I'm not sure I understand the question? I'm building a custom compound field in Drupal 8. The snippet above is from the Widget php of my custom module.
Comment: Your question is " How to get saved term selected for entity_autocomplete" I am asking where you are saving your field? In taxonomy or any other place?
Comment: If I understand correctly, the field in the database looks like it contains the TID of the taxonomy term. So, I think yes - Taxonomy.
Comment: The to set default value it should be like Drupal\taxonomy\Entity\Term::load($items[$delta]->description_term->target_id). To provide default value in auto complete you need to pass full entity to it.
Comment: I tried this: $default_value = \Drupal\taxonomy\Entity\Term::load($items[$delta]->description_term)->get('name')->value;  ... it does switch out the id for the term, but it's not populating the field, for some reason.
Comment: Any entity reference should be target id not value...
Answer: with some help above from Ajay Reddy, I was able to finally get to something that worked... Here's what did it:

'#default_value' =>
  \Drupal\taxonomy\Entity\Term::load($items[$delta]->description_term),
Comment: You can also get the associated term entities with $items->referencedEntities()


Configuring Dovecot to Authenticate Against LDAP Without Access to the Password Field

Question: We have an LDAP server that everyone authenticates against. I need to configure Dovecot to authenticate against it, however I'm running into a major issue.
As per the documentation, Dovecot requires access to the password field in order to do authentication:

Normally LDAP server doesn't give anyone access to users' passwords, so you'll need to create an administrator account that has access to the userPassword field.

Due to the security policies, there is no way that this is happening. Is there a way to bypass this requirement? Eg just send the password to LDAP and look for a 'passed/failed' reply?
OS: Centos 6 x86_64
Dovecot: 2.0.9-22
Answer: The site you linked named the alternative on the very top: Authentication binds. With this, you just need auth ACLs for the password field in LDAP and Dovecot does essentially exactly what you want to do.
Note that having auth access rights for this is absolutely mandatory and if your security policy also forbids that, you need to scrap it because it doesn't make any sense :)
Comment: Yeah, this turned out to be the correct solution. I did initially try using this but was getting rather confusing error messages so I sort of... forgot about this option. I reimplemented it and fixed the errors I was getting and everything is now working :)


Animating a circle using PIXI.js with Typescript

Question: I am using Typescript to animate a circle using PIXI.js. Currently, the circle is bouncing off of the bottom boundary then from the right boundary. I also need it to bounce from the top and left.
I am very new to this language and I'm having some difficulties understanding, well, most of it. I have tried nestling 'else' statements but I'm not sure if that's even suppose to be incorporated in this case.
'main.ts'
<code>///<reference path="PIXI.d.ts"/>
///<reference path="setup.ts"/>

var drawing:PIXI.Graphics = new PIXI.Graphics();
stage.addChild(drawing);

animate();
function animate() {
    renderer.render(stage);
    draw();
    requestAnimationFrame(animate);
}

var x:number = 0;
var y:number = 0;

var xspeed:number = 2;
var yspeed:number = 2;

// MY CODE

function draw(){

    // clear drawing
    drawing.clear();

    // draw circle
    drawing.beginFill(0x999999);
    drawing.drawCircle(x,y,100);

    // move circle down and to the right for the next frame
    x += xspeed;
    y += yspeed;

    // set boundary for circle to bounce from y
    if(y > 600){
        // bounce the circle
        yspeed *= -1;
        // affix to the bottom of the stage
        y = 600;
    }

    // set boundary for circle to bounce from x
    if(x > 800){
        xspeed *= -1;
        x = 800;
    }

}
</code>
HTML

<code>    <script src="src/pixi.js"></script>
    <script src="src/setup.js"></script>
    <script src="src/main.js"></script>
</body>
</html>
</code>
Comment: What approaches have you tried?
Answer: I think what you've got so far is good. You just need to add checks for the zero boundaries:
<code>// set boundaries for circle to bounce from y
if(y > 600){
    // bounce the circle
    yspeed *= -1;
    // affix to the bottom of the stage
    y = 600;
}
else if(y < 0) {
    // bounce the circle
    yspeed *= -1;
    // affix to the top of the stage
    y = 0;
}

// set boundaries for circle to bounce from x
if(x > 800){
    xspeed *= -1;
    x = 800;
}
else if(x < 0){
    xspeed *= -1;
    x = 0;
}
</code>
Another thing you might like to try is drawing the circle once, and setting its x and y properties instead of redrawing it every frame:
<code>var drawing:PIXI.Graphics = new PIXI.Graphics();
drawing.beginFill(0x999999);
drawing.drawCircle(0,0,100);
stage.addChild(drawing);

function draw(){

    // move circle
    drawing.x = x;
    drawing.y = y;

    // move circle down and to the right for the next frame
    x += xspeed;
    y += yspeed;
</code>
Comment: I was pretty close; I was setting the else-if to 10 instead of 0... But thank you so much for the help and for the other tip! That is something I'm going to incorporate.


Need help accessing a nested object in mongo though C# driver

Question: I'm trying to remove an object from an array, but I'm assuming this will be the same procedure for accessing nested objects for update as well.
Assuming my data looks like this
results myColl01 = {_id:1
                    a:100
                    b:[{aa:500,
                        bb:1000},
                       {aa:700,
                        bb:2000}]
                   }

I want to remove a doc from b where b.aa == 500
Here is what the C# code I'm using looks like:
int mc01_id = 1;
int mc01B_AA_val = 500;
IMongoQuery query = Query<MyColl01>.EQ(mc01=> mc01.Id, id);
IMongoUpdate update = Update<MyColl01>.Pull(mc01 => mc01.b,
                              Query<MyColl01_B>.EQ(mc01b => mc01b.aa, mc01B_AA_val));

WriteConcernResult updateResult =
        this.MongoConnectionHandler.MongoCollection.Update(query, update);
I know it can be done by taking out the , but I want to avoid using literals in the query.
The returned error follows:
Argument 2: cannot convert from
'MongoDB.Driver.IMongoQuery' to
'System.Func<MongoDB.Driver.Builders.QueryBuilder<MyProject.MyColl01_B>,
       MongoDB.Driver.IMongoQuery>'

Answer: So I found the answer by accident elsewhere.
To access the sub-class/document you will be pulling from you will need to use the builder.
IMongoUpdate update = Update<MyColl01>.Pull(mc01 => mc01.b,
                          builder => builder.EQ(b => b.aa, mc01B_AA_val));


Are Anti Static Foam Cleaners OK for cleaning all parts of a PC?

Question: Can anyone tell me whether anti static foam cleaners are good for cleaning motherboards, RAMs, VGAs etc?
Also if it's good for that purpose would anyone know a good brand that sells overseas? Preferably with an ebay shop..
Comment: What's wrong with compressed air?
Comment: I thought foam might do a better job than air..
Comment: You run the risk of doing mechanical damage by using any type of wipe on electronic components.  Depending on the age of the hardware, you may also find your wipes contaminated by lead, requiring special disposal precautions.  Compressed air is your friend...just don't let it overspeed any fans; they can be ruined by over-zealous air blowoff.
Comment: How clean do you need it?  You're not eating off your RAM, are you?
Answer: These cleaners are basically 2-BE, ethyl alcohol, and water. The only issue would be the water. If you find they dry quickly with no residue, it should be harmless so long as all of the cleaner remains on the surface.
Personally, however, I wouldn't do it. There's no advantage to getting things that clean -- they'll just get dirty again. And the risk of using a water-based cleaner doesn't seem worth it to me.
It's perfectly safe on external, non-porous surfaces that aren't near any actual electrical components.
Comment: What if theres a chance that dust may have been mixed with water vapors or something? We live close by the sea so that was one of my concerns..
Comment: I'm not sure I understand why you think that would be a problem. Your goal is to get the surface clean. The purpose of the cleaner is to loosen any dirt's grip on the surface. The water will evaporate rapidly because of the way water mixes with alcohol. The 2-BE is a no-residue surfactant which detaches dirt from a surface and makes greasy compounds soluable so they can be wiped off.
Comment: No no dude, I mean since everyone recommends air, how appropriate would that be in my scenario?
Comment: Just make sure the computer is dry before you use air on it. The idea is to get the dust blowing around and then most of it will wind up outside the computer. Trace amounts of dust won't really hurt a computer, it's the buildup that traps heat and moisture.
Comment: OK. Air it is then...
Comment: I used to work for a building firm and as such the pc's were often used on building sites and came back completely full of and covered in dirt. Compressed air was all I ever needed for the insides although I would carefully use foam cleaner on the outside to get the cases like new again. The only place I ever used it inside was on the blades of the fans, but then I would spray it on a tissue first then wipe the blades.


View To Show Tagged Comments Via Arguments

Question: Hello i like how you can add taxonomy to comments now in D7. Im having a few problems though creating a View that will take a tid contextual filter and show the comments in the taxonomy page as a block. Has anyone managed to achieve this?
Thanks
Comment: sorry i should mention that i am fine for showing a block showing comments that are attached to nodes that have the term. This is with Comment: Content relationship and a (Content) Content: Has taxonomy term ID context filter. ah wait a sec......brb
Comment: bah i thought i had it there. i added the realtionship (req) Field: newtag where newtag is the term ref field i added to my comments but this relationship is not available to me when adding the taxonomy term ID context filter. Im still stuck :(
Comment: nope its all working fine. Contextual filters
(term from field_newtag) Taxonomy term: Term ID, Relationships
Field: newtag - fixed :)
Answer: Add Relationships Field: newtag (whatever your term referance field is called)
Contextual filters (term from field_newtag) (add relationship from above)


gcloud crashed (AttributeError): 'NoneType' object has no attribute 'revisionTemplate'

Question: I'm working on Cloud Run, which seems to be beta yet, preventing from redeploying as shown below. It works if I delete the service from GCP console, then deploy the same Docker as a new service. I could not find a way to to set revisionTemplate.
I run this command to deploy a Cloud Run service using gcloud.
gcloud beta run deploy v2-cms --image gcr.io/my-project/v2-cms --quiet

Then, it fails saying like this.
X Deploying...
  . Creating Revision...
  . Routing traffic...
Deployment failed
ERROR: gcloud crashed (AttributeError): 'NoneType' object has no attribute 'revisionTemplate'

If you would like to report this issue, please run the following command:
  gcloud feedback

To check gcloud for common problems, please run the following command:
  gcloud info --run-diagnostics

Comment: What version of the CLI are you using? `gcloud version`. The current version is 253.0.0. I think you have an old version of the CLI. For Windows open an elevated prompt and run `gcloud components update`. For Linux run with sudo.
Comment: The gcloud I use was a bit old version. It works once I got it updated latest. Thanks a lot!
Comment: This appears to be a bug. If you can reliably reproduce this, please send the steps to ahmetb{@]google\.com
Answer: To fix this issue, please update gcloud to ite latest version with gcloud components update
Comment: All components are up to date. but still getting this error
Answer: I had the same problem on FreeBSD 13.2 after upgrading gcloud to 434.0.0 version:
ERROR: gcloud crashed (AttributeError): 'NoneType' object has no attribute 'clean_version'
I fixed it in /usr/local/google-cloud-sdk/lib/googlecloudsdk/core/transport.py, line 628:
  os=user_platform.operating_system,
#  os_version=user_platform.operating_system.clean_version,
  os_version='13.2',
  architecture=architecture,

Comment: Here's a better patch to fix the port https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=272414 .  I don't know how to report this upstream.
Answer: Make sure that your local Tensorflow version is still supported by GCloud https://cloud.google.com/ai-platform/training/docs/runtime-version-list
Answer: I ran into this recently and the issue was that my version of Python (3.11) was too new. I had to switch back to 3.9.


How to include nunit test results in sonarcube 4.5.1 c# plugin 3.3 sonar-project.properties file?

Question: I see that sonarcube re-added nunit test results support since Nov 7 2014:
http://docs.sonarqube.org/display/SONAR/C%23+Plugin
However, I did not find anything that showed how to do this in the sonar-project.properties file.
For example, see the one they provide on git hub here:
https://github.com/SonarSource/sonar-examples/blob/master/projects/languages/csharp/sonar-project.properties
What nunit specific line should be put in this file to replace the "sonar.cs.vstest.reportsPaths=TestResults/*.trx" mstest line?
Thanks!
Answer: The newly added key for NUnit test reports can be found on the project c# settings page - under UNit Tests tab, and its value is:
<code>sonar.cs.nunit.reportsPaths
</code>
Provided value should be the .xml output from the NUnit console runner.
Comment: this is not working any longer... i tried to set it to reportsPath, but it is not finding the xml
Comment: This worked (e.g. something like sonar.cs.nunit.reportsPaths=UnitTestResults/*.results.xml).  Thanks!
Comment: @entre can  you verify that the xml file is available (e.g. the tests are executed and the report is generated). My report file is in the same root folder as the sonar-project.properties file and is working ok.


Session Codeigniter PHP

Question: Tenho dois sistemas diferentes. Ambos criados com codeigniter.
O problema é o seguinte: Faço logon no 1 sistema e utilizo normalmente, então abro o 2 sistema, e então ocorre que o session desse novo sistema sobrescreve a do antigo. Então quando eu vou salvar o id do usuário guardado na session no db do primeiro sistema, ele insere o id do usuário logado do novo sistema.
Alguma dica ou sugestão?
Answer: Basta alterar o
$config['sess_cookie_name'] = "ci_session";

ele vem como padrão. então altere para um de sua preferencia que não seja igual o do outro sistema.
OBS:
O navegador salva a session como cookie, então quando os sistemas possui o mesmo nome de session ele acaba usando a do que foi iniciado depois.
então quando os nomes são diferentes ele cria outro cookie de uma nova session ao invés de sobrescrever à antiga.
Comment: Marque a resposta pra não deixar a pergunta aberta...
Answer: Isso está relacionado com as Session Preferences. Você tem que dizer para a aplicação em que contexto ela deve gerenciar/ler dados da sessão. A documentação diz que as opções de configuração cookie_domain e cookie_path influenciam no comportamento da sessão, conforme se verifica no link indicado acima:

In addition to the values above, the cookie and native drivers apply the following configuration values shared by the Input and Security classes:

Diga para a biblioteca de sessão qual o domínio ou o path para o qual a sessão atual se aplica. Se vc deixar isso em branco na configuração da aplicação (application/config/config.php), o browser vai entender que a sessão é válida para todos os contextos, e vai usá-la dessa forma.
Pra evitar isso, altere application/config/config.php para o domínio correto:
$config['cookie_domain']    = 'aplicacao.com.br';

Ou para o path correto:
$config['cookie_path']      = '/aplicacao';

Comment: obrigado pela resposta! mas no meu caso não se resolveu assim. eu dei uma lida na documentação  e vi que basta alterar o $config['sess_cookie_name'] padrão

Session Codeigniter PHP


How to output all elements of array after generating different random numbers different from previous one

Question: While entering random numbers in an array, my goal is to have a random number in element [x] different from the previous one [x-1] that's the only constraint.  I believe to be achieving this but my problem is that when I run the following code my output does not display all elements.
        int[] array = new int[10];
        Random number = new Random();

        for(int i = 0; i < array.Length; i++)
        {
            int randomNumber = number.Next(3) + 1;
            if (i == 0)
            {
                array[0] = randomNumber;
            }
            else
            {
                array[i] = randomNumber;

                while (array[i] == array[i - 1])
                {
                    array[i] = randomNumber;
                }
            }

            Console.Write(array[i] + " ");
        }
        Console.ReadLine();

Comment: After you read [ask] and take the [Tour], is the constraint that each number be different than just the *previous* value?  Then ask an actual question.
Comment: If you want a random number from 1 to 3, why not generate a random number from 1 to 3 instead of generating a random number from 0 to 2 and then adding 1 to it?
Answer: The issue is that, for each element, you only ever generate one random number. If that number happens to be the same as the previous one, you don't generate a new one but just keep using the same one.  This:
while (array[i] == array[i - 1])
{
    array[i] = randomNumber;
}

should be like this:
while (array[i] == array[i - 1])
{
    randomNumber = number.Next(3) + 1;
    array[i] = randomNumber;
}

Comment: Thanks! I'm still learning, can't believe I missed that.  I appreciate your help.
Comment: This is a perfect example of why you need to debug your code rather than just read it. When you simply read code, you see what you expect to see much of the time. If you actually debug the code then you see what actually happens.  If you don't know how to debug, learn. In future, if you haven't set a breakpoint and stepped through the code, it's too soon to post a question. If you'd debugged here then you'd have seen straight away that the number never changed at that point.
Comment: Yes, you're absolutely right.  I will keep this in mind, thanks again.


Como executar uma ação ao terminar o each() JQuery

Question: Estou usando a função each() do JQuery gostaria de saber se existe um mecanismo para que eu possa executar uma função depois que terminar o each().
Assim que terminar minha each(), já possa fazer outra coisa, mas assim não funcionou.
$(".budgetSelectedNumber").each(function () {
       let value = Number($(this).val());
       arrayProductSelecteds.push(value)
}).done(function(){
       console.log("finish")
});

Uncaught TypeError: $(...).each(...).done is not a function
Answer: A execução do código só prossegue após a finalização do $.each(). Ou seja, a próxima linha após o $.each() só será executada quando o $.each() finalizar:
$(".budgetSelectedNumber").each(function () {
    let value = Number($(this).val());
    arrayProductSelecteds.push(value);
});

console.log("O each terminou!");

Então não precisa de nenhuma função específica ou um callback pra isso, até porque ele não possui (veja a documentação).
Comment: Pensei que o meu problema era no each() mas você ta certo, obrigado.


how to solve vtigercrm webform error message? {"success":false,"error":{"message":"Webform not found."}}

Question: I have installed vtigercrm on my hostgator hosting when I create a webform from setting it did not show on html and on browser it display this error message.
I need step by step guide on creation of successful webform
error message I get is here
{"success":false,"error":{"message":"Webform not found."}}

Did any one know how to solve this. Any help will be appreciated .
Answer: I had the same problem and here is the solution that I used. VTiger has an error in their code for displaying the right url for the action url.
Here is the original code...
<form name="Webform Name" action="http://yourDomainName.commodules/Webforms/capture.php" method="post" accept-charset="utf-8"…
This is how the code should be…
<form name="Webform Name" action="http://yourDomainName.com/modules/Webforms/capture.php" method="post" accept-charset="utf-8"…
Notice they didn't include the forward slash (/) after .com. Once that is put into place then the link works. Hope that helped.


Let $f:K \to L$ a homomorphism of fields. Prove that $f$ induces a isomorphism of the prime fields of $K$ and $L$.

Question:
Let $f:K \to L$ a homomorphism of fields. Prove that $f$ induces a
  isomorphism of the prime fields of $K$ and $L$.

Here are my thoughts:
Assume $K$ is infinite. Then $L$ must be infinite as well, since $f$ is injective. I know that the prime field of a infinite field is isomorphic with $\Bbb Q$. So them I'm done.
Assume $K$ is finite. Then I don't know what to do ?
Comment: It is not true that the prime field of an infinite field is necessarily $\mathbb{Q}$.
Comment: (1) There are infinite fields with finite prime field, e. g. $\mathbb F_2(X)$.

(2) Even if the two prime fields are isomorphic, this does not show that $f$ induces that isomorphism.
Comment: @Sebastian oh wait, this prime field can be finite even if the field is infinite
Comment: Well then I don't have any clue how to proof this. :P
Comment: You are on the right track: consider the composition $\mathbb{Z} \to K \overset{f}{\to} L$. What is the kernel of this composition?
Comment: @Sebastian I don't know if $\varphi:\Bbb Z \to K$ is injective or not. But if it is not injective, then the kernel of $f\circ \varphi$ is $(p)$. If it is injective, then it is $(0)$.
Comment: Oh wait, I think I see what you mean.
Answer: Notice that every element of prime field of $k$, lets call it $P$, is of the form $1\frac nm$ because its the smallest subset of $k$ containing $1$ and $0$ closed on field operations. We know that $f(1)=1$ and $f(1\frac nm )=\frac nm f(1)$. This means that image of $f(P)$ is the prime field of $L$.
Comment: I've absolutely no clue where you are talking about.
Comment: Prime filed of $k$ is the smallest field contained in $k$. I has to contain $1$ so it contains elements $1+...+1=m1$. It is closed on division so so it has elements $1m/n$. And its easy to see that elements of this form are a subfield of $k$ and it have to be minimal.
Answer: Since $f$ is injective we may view $K$ as a subfield of $L$. Then the prime field of $L$ must be $\subseteq K$ as otherwise its intersection with $K$ would be a smaller field. And as it has no proper subfields it must also be the prime field of $K$.


Unable to get Admob ads in my app

Question: My xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#000000"
    android:orientation="vertical" >
<com.google.ads.AdView android:id="@+id/ad"
                           android:layout_width="wrap_content"
                           android:layout_height="wrap_content"
                           ads:adSize="SMART_BANNER"
                           ads:adUnitId="@string/admob_unit_id"
                           ads:testDevices="@string/test_device"
                           ads:loadAdOnCreate="true"/>

</LinearLayout>

Error in logcat:
11-05 09:32:30.593: I/Ads(2052): adRequestUrlHtml:
11-05 09:32:30.953: W/webcore(2052): Can't get the viewWidth after the first layout
11-05 09:32:30.953: I/Ads(2052): Received ad url: <url: "http://googleads.g.doubleclick.net:80/mads/gma?preqs=18&session_id=1804074505668833558&seq_num=19&u_w=320&msid=com.ad.aksharamaala.hd&js=afma-sdk-a-v6.2.1&bas_off=0&net=wi&app_name=3.android.com.ad.aksharamaala.hd&hl=en&smart_w=full&gnt=8&carrier=40407&u_audio=3&kw&u_sd=1&mv=8015016.com.android.vending&isu=EB83E0FCC98011A7D8B65831A838375F&cipa=0&format=320x50_mb&oar=0&smart_h=auto&u_h=480&bas_on=0&ptime=998246&u_so=p&output=html&region=mobile_app&u_tz=-330&client_sdk=1&ex=1&slotname=a150940f47b619f&kw_type=broad&askip=3&gsb=wi&caps=interactiveVideo_th_mediation_sdkAdmobApiForAds_di&jsv=40" type: "admob" afmaNotifyDt: "null" useWebViewLoadUrl: "false">
11-05 09:32:30.953: I/Ads(2052): Request scenario: Online server request.
11-05 09:32:30.973: W/Ads(2052): IOException connecting to ad url.
11-05 09:32:30.973: W/Ads(2052): java.net.ConnectException: googleads.g.doubleclick.net/127.0.0.1:80 - Connection refused
11-05 09:32:30.973: W/Ads(2052):    at org.apache.harmony.luni.net.PlainSocketImpl.connect(PlainSocketImpl.java:254)
11-05 09:32:30.973: W/Ads(2052):    at org.apache.harmony.luni.net.PlainSocketImpl.connect(PlainSocketImpl.java:533)
11-05 09:32:30.973: W/Ads(2052):    at java.net.Socket.connect(Socket.java:1055)
11-05 09:32:30.973: W/Ads(2052):    at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.<init>(HttpConnection.java:62)
11-05 09:32:30.973: W/Ads(2052):    at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnectionPool.get(HttpConnectionPool.java:88)
11-05 09:32:30.973: W/Ads(2052):    at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getHTTPConnection(HttpURLConnectionImpl.java:927)
11-05 09:32:30.973: W/Ads(2052):    at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:909)
11-05 09:32:30.973: W/Ads(2052):    at com.google.ads.internal.f.b(SourceFile:459)
11-05 09:32:30.973: W/Ads(2052):    at com.google.ads.internal.f.run(SourceFile:430)
11-05 09:32:30.973: W/Ads(2052):    at java.lang.Thread.run(Thread.java:1096)
11-05 09:32:30.973: D/webviewglue(2052): nativeDestroy view: 0x390bf8
11-05 09:32:30.973: I/Ads(2052): onFailedToReceiveAd(A network error occurred.)

Can anyone tell me where am I making mistake?
Comment: do you have an ad-blocker installed on your (probably rooted) phone ?
Comment: Have you checked, the url contains banner or not??
Comment: @zrgiu no, I do not have any ad-blocker
Answer: if you look closely in the log you posted, on line 6 you will notice that googleads.g.doubleclick.net resolves to 127.0.0.1. This usually means that the hosts file on your phone was tampered, with the purpose of blocking ads in all your apps.
If you're running this on an emulator, either your emulator's hosts file was tampered, or your computer's OS hosts file. You should check those out.
Comment: Thanks for the answer. May I know what could be done to solve this issue?
Comment: are you running on a phone or emulator ?
Comment: this app looks like it could do the job for you: https://play.google.com/store/apps/details?id=com.treb.hosts&hl=en  find the entry for googleads.g.doubleclick.net and remove it

Unable to get Admob ads in my app


Quantos dias tem o mês atual com Javascript?

Question: Eu gostaria de saber quantos dias tem o mês atual com Javascript, por exemplo com PHP, eu faria assim:
Date('t');

Muito simples com PHP, mas e com Javascript tem algum jeito fácil?
Obs. eu uso AngularJS caso ajude em alguma coisa.
Answer: function diasNoMes(mes, ano) {
    var data = new Date(ano, mes, 0);
    return data.getDate();
}

// Exemplo:
console.log(diasNoMes(2, 2017)); // Exibe 28.

Comment: Funcionou pq em JS o 2 é o mês três, e você pegou o ultimo dia do mes anterior. Precisa tomar cuidado com isso, se a pessoa usar com outras funções de JS que retornem o mês com base zero.
Comment: Como o @Bacco disse, é bom tomar cuidado quando se usa com um mês gerado pelo método `Date().getMonth();`. Se for o caso, o esquema é usar `var data = new Date(ano, mes + 1, 0);` ao invés disso.
Answer:

function _numDias(){
  var objData = new Date(),
      numAno = objData.getFullYear(),
      numMes = objData.getMonth()+1,
      numDias = new Date(numAno, numMes, 0).getDate();

  return numDias;
}

console.log(_numDias());
Answer: Retorna o numero de dias do mês em curso. Este mês de fevereiro de 2017 retorna 28. Mês de março 31 e assim por diante. Fevereiros bisextos retornarão 29.

Date.prototype.diasNoCorrenteMes = function() {
  var days = [30, 31],
  m = this.getMonth();

  if (m == 1) {
    return ( (this.getFullYear() % 4 == 0) && ( (this.getFullYear() % 100 != 0 ) || (this.getFullYear() % 400 == 0) ) ) ? 29 : 28;
  } else {
    return days[(m + (m < 7 ? 1 : 0)) % 2];
  }
}

var myDate = new Date();

console.log(myDate.diasNoCorrenteMes());
Comment: Tem um erro aí, anos múltiplos de 100 não sao bissextos, a não ser que sejam múltiplos de 400 também. Só fazer % 4 não basta.
Comment: Acredito que se você utilizar o [Ideone](https://ideone.com/) ou o [Repl.it](https://repl.it) para exibir seus códigos em funcionamento  terá melhores resultados. Se for apenas HTML/CSS/JS, pode utilizar a própria ferramenta do Stack Overflow.
Comment: Valeu Anderson Carlos Woss, ainda não descobri como fazer isso, sou novato!
Comment: https://pt.wikipedia.org/wiki/Ano_bissexto#Algoritmo_de_determina.C3.A7.C3.A3o
Comment: Bacco em 2100 estaremos todos no céu, rs. Será que isso tá correto? return this.getFullYear() % 4 == 0 && this.getFullYear() % 100 != 0 || this.getFullYear() % 400 == 0 ? 29 : 28;


How to add a list to a Map> dynamically

Question: I'm getting my documents from firebase keeping in a List. Currently I have this content in the list:
[{date: 02/02/2019, name: John}, {date: 03/03/2020, name: Louise}]

Then, in the following method, I transform this list to put in a map with my desired formatation.
Map formatMap(list){
    if(list.length > 1){
      for(int i = 0; i < list.length; i ++){
        dateFormatted = _formatDate(list[i]['date']);
        print(dateFormatted);
        if(i == 0){
          myMap[dateFormatted] = [];
        }
        myMap[dateFormatted].add({'date': list[i]['date'], 'name': events[i]['name']});
      }
    }else{
      dateFormatted = _formatDate(list['date']);
      myMap[dateFormatted] = [{'date': list['date'], 'name': list['name']}];
    }
    return myMap;
  }

I'm doing it because my expected result is:
{2020-12-31 12:00:00.000Z: [{date: 02/02/2019, name: John}, {date: 03/03/2020, name: Louise}]}

But running that method the return is:

[ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: NoSuchMethodError: The method '[]=' was called on null.
E/flutter (17862): Receiver: null
E/flutter (17862): Tried calling: []=(Instance of 'DateTime', Instance(length:0) of '_GrowableList')

What I'm doing wrong? How can I perform to achieve my expected result?
Answer: I guess you forgot to initialize the map:
myMap = {};

Comment: Also seems that `if(i == 0){ myMap[dateFormatted] = [];}` will cause `The method 'add' was called on null` if `_formatDate(list[i]['date'])` returns a different value.

How to add a list to a Map> dynamically


Knnclassify() matlab

Question: I am currently working on matlab and I am new to it. I would like to know how do i average the results from the folds (or otherwise combined) to produce a single estimation.
My dataset has 2 class labels +1 and -1. and k=5. I use the knnclassify() method in matlab in order to perform cross validation.
Kindly help!
Comment: Can you please make your question a bit more understandable? It seems as you want to use Cross-Validation to make classification itself, but this is nonsense.
Answer: The knnclassify() function uses the k-nearest neighbours classification algorithm to perform classification. The crossvalind() function is a separate one to divide a data set in to folds to perform cross-validation. Both are part of the Bioinformatics toolbox. I suggest that you read the documentation associated with them, so that you can be sure you are using them correctly.
In general, however, with a single n-fold cross-validation (CV) run, you don't really need to average results from folds. You just collect the results from the individual folds.
For example, with 5-fold CV, your dataset is divided into 5 separate folds, used as follows:

Train with Folds 1..4, Test on Fold 5
Train with Folds 1..3+5, Test on Fold 4
Train with Folds 1+2+4+5 Test on Fold 3
and so on.

So all of the data is used for testing exactly once. You can just combine the test results in a single list, and count how many it got right and wrong to compute the overall accuracy.
Answer: <code>load fisheriris
indices = crossvalind('Kfold',species,10);
cp = classperf(species); % initializes the CP object
for i = 1:10
    test = (indices == i); train = ~test;
    class = knnclassify(meas(test,:),meas(train,:),species(train));
    % updates the CP object with the current classification results
    classperf(cp,class,test);
end
cp.CorrectRate % queries for the correct classification rate
</code>
Comment: +1 but (1) You can format your code using indentation (with 4 spaces or through the online editor); (2) Some comments around your code might be appreciated because users that are not familiar with Matlab syntax will have hard time to understand what the above code chunk actually does. As far as I understand, predicted class memberships on the test sample are stored at each iteration, and then averaged to yield the classification CR.

Knnclassify() matlab


Effect of Reshaping Data in Deep Learning

Question: In the code for deep learning models in tensorflow, Keras I see that Reshaping of the data (numpy tensor or ndarray) is a very frequent operation.
It is used to fit different components of a model together.
Why can I reshape data and assume everything is fine? Stochastic gradient and Backprop will get job done?
Does this mean that while training a model I can do whatever kind of "improvisations" and just be happy if I get the end result right?
Answer: For the gradient descent algorithm (and its variations) you can apply any operation which is differentiable. Reshape operation is just a way to convert 4 dimensional tensor to 2 dimensional matrix. With matrix you can do matrix multiplication using built-in functions. Reshape operation doesn't influence gradient calculation, because you calculate it with respect to each variable in the matrix separately.


Bootstrap 3 gallery page crashes only on mobile

Question: I have a static HTML page with around 55 png images on it (~7MB total), displayed in the bootstrap 3 grid. When I visit the page on iPhone (both Chrome and Safari), the page refreshes automatically after 1-2 secs., and then it crashes. On the desktop, everything works fine:
https://teilecdn.com/test.html
Images are very big (3000x4000 pixels). When I replace the src of the images with a placeholder (https://via.placeholder.com/300), the page loads correctly, also on mobile. I discovered that images are the issue here, but I have no idea how to debug this problem. I tired with devtools, but on desktop everything works fine (even if I switch look from desktop to mobile in devtools).
Is this happening because of some special behavior of mobile browsers? Some image total size limitations?
EDIT: I just discovered that if I remove bootstrap.css, then page is not crashing.
Answer: I checked my iPhone crash logs via Xcode and get the following:
error   13:58:49.424690+0000    MobileSafari    0x10b0500c0 - GPUProcessProxy::didClose:
error   13:58:49.424722+0000    MobileSafari    0x10b0500c0 - GPUProcessProxy::gpuProcessExited: reason=Crash
error   13:58:49.424772+0000    MobileSafari    0x10c005880 - [PID=634] WebProcessProxy::gpuProcessExited: reason=Crash
error   13:58:49.441675+0000    MobileSafari    Error acquiring assertion: <Error Domain=RBSServiceErrorDomain Code=1 "target is not running or doesn't have entitlement com.apple.runningboard.assertions.webkit" UserInfo={NSLocalizedFailureReason=target is not running or doesn't have entitlement com.apple.runningboard.assertions.webkit}>
error   13:58:49.441700+0000    MobileSafari    0x10b01c120 - ProcessAssertion::acquireSync Failed to acquire RBS assertion 'GPUProcess Background Assertion' for process with PID=633, error: Error Domain=RBSServiceErrorDomain Code=1 "target is not running or doesn't have entitlement com.apple.runningboard.assertions.webkit" UserInfo={NSLocalizedFailureReason=target is not running or doesn't have entitlement com.apple.runningboard.assertions.webkit}

Would appear that the webpage is causing the GPU to crash. On further investigation it appears iPhone has a memory limit when using UIWebkit which is in the region of 10MB.
The workaround appears to be moving from IMG to background-image on the parent as per this demo: https://dev.cratrr.com/74841828/

ANTRIEB

becomes

ANTRIEB

With some additional CSS targeting .panel-body:
.panel-body {
    background-size:contain;
    background-position:center;
    min-height:300px;
    height:auto;
    background-repeat:no-repeat;
    max-width:100%;
}

The only thing this misses would be your onload error handling.
I would also consider using some lazy loading for slower networks!