Notepad++: Extracting all words from a very long string that contains a set of rounded brackets

Question: I have a large .txt file written in German. It is a transcript of many people speaking. When an abbreviate form of a word is used, the correct form of the word is written around it, or inside it, in brackets. I would like to extract, as a list, all such examples that exist in this .txt. I have tried a few Regex but I can't seem to get it to highlight the entire "word".
Any ideas?
Here is a part of the .txt with the words I'd like extracted highlighted:
Ich hab(e) am Achtundzwanzigsten achten neunzehnhundertneunzig Geburtstag. Also wenn ich mich beschreiben sollte, dann muss ich sagen freundlich, unkompliziert und bescheiden. Hallo wie gehts (geht es) dir. Na was machst (machst du) den jetzt heut(e). Und, eh, hm, was noch? Stör(e) ich? Ja das is(t), eh, so, würd(e) ich das so sagen....
Thanks!
Answer: If I well understand your needs, how about:
(\w+\(\w+\))| \([\w\s]+\)

Explanation:
The regular expression:

(?-imsx:(\w+\(\w+\))| \([\w\s]+\))

matches as follows:

NODE                     EXPLANATION
----------------------------------------------------------------------
(?-imsx:                 group, but do not capture (case-sensitive)
                         (with ^ and $ matching normally) (with . not
                         matching \n) (matching whitespace and #
                         normally):
----------------------------------------------------------------------
  (                        group and capture to \1:
----------------------------------------------------------------------
    \w+                      word characters (a-z, A-Z, 0-9, _) (1 or
                             more times (matching the most amount
                             possible))
----------------------------------------------------------------------
    \(                       '('
----------------------------------------------------------------------
    \w+                      word characters (a-z, A-Z, 0-9, _) (1 or
                             more times (matching the most amount
                             possible))
----------------------------------------------------------------------
    \)                       ')'
----------------------------------------------------------------------
  )                        end of \1
----------------------------------------------------------------------
 |                        OR
----------------------------------------------------------------------
                           ' '
----------------------------------------------------------------------
  \(                       '('
----------------------------------------------------------------------
  [\w\s]+                  any character of: word characters (a-z, A-
                           Z, 0-9, _), whitespace (\n, \r, \t, \f,
                           and " ") (1 or more times (matching the
                           most amount possible))
----------------------------------------------------------------------
  \)                       ')'
----------------------------------------------------------------------
)                        end of grouping

Comment: @Retsam: Yes, with a Perl module : YAPE::Regex::Explain available at CPAN http://search.cpan.org/~gsullivan/YAPE-Regex-Explain-4.01/Explain.pm
Comment: this does not seem to be working on the sample text provided in Notepad++. I am using v5.9.2
Comment: Is this explanation automatically generated from somewhere?
Answer: This regular expression finds all the contents between ( and ) included and also everything before ( and its preceeding space character:
[^ ]*\([^)]*\)

Now to transform your text into a nice list:

open find/replace dialog (Ctrl-H)
Find what: .*?([^ ]*\([^)]*\))
Replace with: \1\n
"Regular expression" with "Matches newline" checked
Press "Replace All" with cursor at the beginning of file (Ctrl-Home)
Ignore or delete last line

Now you have a nice list of all these words each on separate line.
Comment: but it would not capture something like "freu(sd)ich"
Comment: I dont speak german and that wasnt in original test data, this could be accomplished by adding `[^ ]*` to the end of current regexp. Or `[^\s\.\,\;\?\!]*` like you do to get rid of some other punctuation characters that may be at the end of words.
Answer: Notepad++ uses a regex flavor that may not be POSIX compliant, hence does not support word boundaries. (Atleast v5.9.2 does not support it)
Try this regular expression:
[^\s]*\([^)]*\)[^\s\.\,\;\?\!]*

[^\s]* : detects beginning of a word by not matching any whitespace before a word (tab, space, etc..)
\([^)]*\) : matches the brackets and its content
[^\s\.\,\;\?\!]* : detects ending of a word by not matching any whitespace or possible punctuation symbols.

You can extend this by adding more punctuation marks before or after the word (like quotes).
Successfully tested this on Notepad++ v5.9.2 on your sample text.


How to properly attach a library to CheckoutPaneForm

Question: I'm attempting to attach a library to a CommerceCheckoutPane plugin.  I first started with using $pane_form['#attached']['library'][] = 'commerce_paypal/express-checkout';.  There were some errors in my commerce_paypal.libraries.yml file but once those were resolved the libaries still don't appear to be loaded.
Right now, my setup looks like:
commerce_paypal.libraries.yml:
paypal.checkout:
  remote: https://www.paypalobjects.com/api/checkout.js
  license:
    name: MIT
    gpl-compatible: true
  js:
    https://www.paypalobjects.com/api/checkout.js
express-checkout:
  js:
    js/paypal_ec.js
  dependencies:
    - commerce_paypal/paypal.checkout

Drupal\commerce_paypal\Plugin\Commerce\CheckoutPane\ExpressCheckout:
public function buildPaneForm(array $pane_form, FormStateInterface $form_state, array &$complete_form) {
  $pane_form['#theme'] = 'commerce_paypal_express_checkout';

  return $pane_form;
}

commerce-paypal-express-checkout.html.twig
{{ attach_library('commerce_paypal/express-checkout') }}

asdfas

js/paypal_ec.js:
console.log('here');

When I place the pane form I see asdfas but the JS is not added.  I've checked the source, no sign of paypal_ec.js.
Answer: As usual, I was messing something up.  JS libraries need : {}.  Updating commerce_paypal.libraries.yml to this solves it:
paypal.checkout:
  remote: https://www.paypalobjects.com/api/checkout.js
  license:
    name: MIT
    gpl-compatible: true
  js:
    https://www.paypalobjects.com/api/checkout.js: {}
express-checkout:
  js:
    js/paypal_ec.js: {}
  dependencies:
    - commerce_paypal/paypal.checkout


How to load all information Currency properties by currency code?

Question: I used module Currency version 8.x-3.1 . I had currency Code so I looking up function to load all properties currency by currency code , What API or function do it ?
Thanks
Comment: Maybe it would be more helpful for you to ask in the module's issue forum?
Answer: As a currency is just an entity you can do the following:
<code>$currency_code = 'AUD';
$entity_type_manager = \Drupal::service('entity_type.manager');
$currency = $entity_type_manager->getStorage('currency')->load($currency_code);
ksm($currency); //check out what's available

//eg get sign
$sign = $currency->get('sign');
</code>
Good Luck
Answer: You need to load the commerce_currency entity with entity manager
<code>    $entity_manager = \Drupal::entityManager();
    $currency_code = 'USD';
    $currency = $entity_manager->getStorage('commerce_currency')->load($currency_code);
    kint($currency);
</code>


show this sequence always is rational number

Question: let $\{a_{n}\}$ such $a_{1}=-8$,and such
$$4\sqrt[3]{a_{n}}+5\sqrt[3]{a_{n+1}}=3\sqrt[3]{7(a_{n}+1)(a_{n+1}+1)}$$
show that
$$a_{n}\in Q,\forall n\in N^{+}$$
I  try let $a_{2}=x$,and for $n=1$, then we have
$$-8+5\sqrt[3]{x}=3\sqrt[3]{-49(x+1)}\Longrightarrow x=-1/8$$
and for $n=2$ I get $a_{3}=-\dfrac{389017}{4913}$ and so on
The first observation
i want use this well known identity: $$a^3+b^3+c^3=3abc ~~~~~~~~~~~~~~~~~~if~~~~~ a+b+c=0$$
let $a=4\sqrt[3]{a_{n}},b=5\sqrt[3]{a_{n+1}},c=-3\sqrt[3]{7(a_{n}+1)(a_{n+1}+1)}$,so
$$64a_{n}+125a_{n+1}-189(a_{n}+1)(a_{n+1}+1)=-180\sqrt[3]{7a_{n}a_{n+1}(a_{n}+1)(a_{n+1}+1)}$$
ADD it by 2021,11.6.PM.18:05
The second observation
and Now I have found this interesting:
if $x,y,p,q,a,b\ge 0$, Hölder's inequality :
$$(x^3+y^3)(p^3+q^3)(a^3+b^3)\ge (xpa+yqb)^3$$
$1+\sqrt[3]{e^{2a}}\sqrt[5]{e^{b}}\sqrt[15]{e^{2c}} \leq \sqrt[3]{(1+e^{a})^2}\sqrt[5]{1+e^{b}}\sqrt[15]{(1+e^{c})^2}$
the condition it's
$$(a_{n}+1)(1+a_{n+1})(4^3+5^3)= (4\sqrt[3]{a_{n}}+5\sqrt[3]{a_{n+1}})^3$$
or
$$4\sqrt[3]{a_{n}}+5\sqrt[3]{a_{n+1}}=3\sqrt[3]{7(a_{n}+1)(a_{n+1}+1)}$$
but this sequence $a_{n}<0$ or $a_{n}>0$,so this Hölder inequality seem can't hold
Comment: so maybe $a_{n}=b^3_{n}$?,where $b_{n}\in Q$
Comment: paste a link to the exam
Comment: where did you get this????
Comment: It comes from an online exam, which is now over, and there are no official answers
Comment: soory,There are no websites, only groups
Comment: $a_3=(73/17)^3$.
Comment: @GerryMyerson  yes, next $ \left( \frac{-65882}{90271} \right)^3 $  Actually, I got $a_3$  negative as well
Comment: Observe that $ a_n+1 =7c_n^3$, so we might want to study rational points on $7y^3 = x^3 + 1$.
Comment: As a starting point, define $b_1=-2$ and $b_{n+1}$ as the real solution to $-189 b_n^3 y^3-125 b_n^3+240 b_n^2 y+300 b_n y^2-64 y^3-189=0$. Then $a_n=b_n^3$
Comment: Using Mathematica I find 3 solutions for a[n+1] as 3 functions f, g, h, of a[n]. Starting with a[1]=-8 I find in each step one of the functions is rational, the two others have complex conjugate values. Picking each time the rational solution the first elements of the sequence (expressed here in decimal fractions approximation) are {-8., -0.125, -0.0126293, -0.388737, 11463.1, 29.4354, -0.927405, 4.14991, -0.996977, 1.02806, -1.00236, 0.256966} which looks rather erratic,
Answer: We could write a cubic curve in equation$\sum_{i=1}^3\sum_{j=1}^3\sum_{k=1}^3a_{ijk}x_ix_jx_k=0$, where we use $x_1,x_2,x_3$ to replace symbol $x,y,1$ here. And the equation is symmetric so that $a_{123}=a_{321}$ etc, similar as a symmetric matrix could be used to represent a quadratic curve. And we could use symbol $A=(a_{ijk})$ to represent the 3-D tensor.
For any point in homogenous coordinates $p=(p_1,p_2,p_3), q=(q_1,q_2,q_3),r=(r_1,r_2,r_3)$, define $A_p=\sum_{i=1}^3\sum_{j=1}^3\sum_{k=1}^3a_{ijk}p_ix_jx_k, A_{pq}=\sum_{i=1}^3\sum_{j=1}^3\sum_{k=1}^3a_{ijk}p_iq_jx_k, A_{pqr}=\sum_{i=1}^3\sum_{j=1}^3\sum_{k=1}^3a_{ijk}p_iq_jr_k$.
If any point p in the cubic curve, we have $A_{ppp}=0$.
If a line intersect with the cubic curve in three different points p,q,r, we have $A_{pqr}=0$.
It is because for any p and q in the curve, we have $A_{ppp}=A_{qqq}=0$, using homogenous coordinates, for any point r in the line passing p&q, we have $r=p+\lambda q$, where $\lambda$ is a real number.
If r is also in the curve, we could have $A_{qqq}\lambda^3+3A_{qqp}\lambda^2+3A_{qpp}\lambda+A_{ppp}=0$.
Since $A_{qqq}=A_{ppp}=0$, we have $A_{qqp}\lambda+A_{qpp}=0$, or $ r=A_{qqp} p - A_{qpp} q$.
So $A_{pqr}=A_{qqp} A_{pqp} - A_{qpp}A_{pqq}$.
Since $A_{qqp}=A_{pqq}, A_{pqp}=A_{qpp}$, we got $A_{pqr}=0$.
Calvin has constructed cubic curve $x^3+1-7y^3=0$ so that it means that if a line intersect with the curve in $(x_1,y_1), (x_2,y_2), (x_3,y_3)$, we must have $x_1x_2x_3+1-7y_1y_2y_3=0$.
Let $(x_3,y_3)=(\frac45,\frac35)$, we have $4x_1x_2+5=21y_1y_2$.
And according to Calvin's another construct, so that we could replace $(x_2,y_2)$ by  $(\frac{1}{x_4},\frac{y_4}{x_4})$ and get formula that $4x_1+5x_4=21y_1y_4$.
continue to use condition that 3 points in same line and finally we could get formula:
$\begin{cases}
u_1=-2,v_1=1,w_1=-1\\
u_{h+1}=-20u_h^2 + 16u_hv_h -63v_hw_h + 105w_h^2\\
v_{h+1}=25u_hv_h - 63u_hw_h-20v_h^2 + 84w_h^2\\
w_{h+1}=-12u_h^2 + 16u_hw_h -15v_h^2 + 25v_hw_h\\
a_h=(\frac{u_h}{v_h})^3
\end{cases}$

In the picture above, slope of $OA_h$ gives $\sqrt[3]{a_h}$, where $B_h, A_{h-1}, S$ is in one straight line and $A_h$ is the point of symmetry of $B_h$ about y=x. The orange curve is $x^3+y^3=7$. $S(\frac53, \frac43), A_1=B_2(-1,2)$
Weierstrass normal form $U^2=V^3-\frac2{6^37^4}$. $E_0: U_0=\frac1{9*6*7^2}, V_0=\frac{2}{3*6*7}, E_1: U_1=-\frac3{6*7^2}, V_1=\frac2{6*7}$
$x_h=\frac1{42V_h}+\frac{7U_h}{V_h}, y_h=\frac1{42V_h}-\frac{7U_h}{V_h}, a_h=\left(\frac{y_h}{x_h}\right)^3$. $E_h=(h-1)E_0+E_1$(Add in elliptic cure group)
pari/gp code
<code>getslope(n)={
 local(E,S0,S1);
 local(R,V,U,x,y);
 E=ellinit([0,-2/(6^3*7^4)]);
 S0=[2/(3*6*7), 1/(9*6*7^2)];
 S1=[2/(6*7), -3/(6*7^2)];
 R=ellmul(E,S0,n-1);
 R=elladd(E,R,S1);
 V=R[1];
 U=R[2];
 x=1/(42*V)+7*U/V;
 y=1/(42*V)-7*U/V;
 y/x
}
</code>
<code>? getslope(1)
%27 = -2
? getslope(2)
%28 = -1/2
? getslope(3)
%29 = -73/17
? getslope(4)
%30 = -65882/90271
? getslope(5)
%31 = 4309182809/191114642
</code>
Comment: This is a really nice demonstration. Of course it needs to be hauled to completion which can be done with Calvin's observation, but I'm blown away by this!
Comment: Oh wow, that's a nice proof of the claim. I guessed that equation had to be true (esp given the coefficients), but didn't know how to prove it.  $\quad$ Note that your $A_{pq}, A_{pqr}$ definitions might have a typo since they are missing $q_j$.
Comment: updated, $p_j$ should be $q_j$
Answer: By looking at the initial values, we hypothesize that

$a_n  = x_n^3, x_n \in \mathbb{Q}$
$a_n + 1 = 7y_n^3, y_n \in \mathbb{Q}$

This suggests to study rational points on $7y^3 = x^3 + 1$.
We map $ a_i$ to the point $ ( \sqrt[3]{a_i}, \sqrt[3]{\frac{a_i + 1}{7} } )$.
We have the starting points $a_1: (-2, -1), a_2: (-1/2, 1/2)$.
Notice that we also have the rational points $ (-1, 0), (4/5, 3/5)$ on the curve. The latter was inspired by the coefficients in the question, and you will see how this is applicable in a moment.
We apply the usual tricks with group addition to determine the sequence.
Given a solution $(x,y)$, divide throughout by $x^3$ to get $ 7 (\frac{y}{x} ) ^3 = ( \frac{1}{x} ) ^3 + 1 $, so observe that $(\frac{1}{x}, \frac{y}{x} )$ is also a solution.
Given a solution $(x,y)$, we can construct the line that passes through $(x,y)$ and $(\frac{4}{5}, \frac{3}{5} )$ which intersects the cubic again at $(x', y')$.
Furthermore, if $(x,y)$ is a rational point, then so is $(x', y')$.  (Prove this.)
We combine this with the previous observation and send $(x,y)$ (to $(x',y')$ and then ) to $(\frac{1}{x'} , \frac{y'}{x'} ) $.
Claim: $(x,y)$ and $(\frac{1}{x'} , \frac{y'}{x'} )$ satisfy $4x + \frac{5}{x'} = 21 y \frac{y'}{x'}$.
See Zhaohui's solution for a beautiful proof that if the cubic intersects a line at 3 points, then $x_1x_2x_3 + 1  = 7 y_1y_2y_3$.
Applying it to the 3 points on the line, we get $\frac{4}{5} x x' + 1 = 7 \times \frac{3}{5} y y'$, and hence the claim follows.
Corollary: This shows that we send $ a_n : (x_n, y_n) $  to $a_{n+1} : (x_{n+1}, y_{n+1}) $ via the above description.
Since the starting point $a_1$ is rational, hence all of these are rational points.
So $ x_n \in \mathbb{Q}$ and $ a_n \in \mathbb{Q}$.
Notes

Someone who is more familiar with elliptic curves might be able to manipulate the equations better. (IE See Zhaohui's solution)
This approaches illustrates the theory behind the question, and why the question isn't just "magic".
If one knew the fact that Zhaohui showed, then this approach would have felt natural. My guess is that similar questions like this can be dealt with in a similar way, especially for quadratic (and cubic) terms. Previously, I mainly dealt with similar questions previously via heavy-handed induction + guessing what the sequence is (EG Zhaohui's formulas at the end). I'm excited to apply this to future questions.
For $a_1$, the line is actually tangential at $a_1$. So the 3rd point of intersection is $a_1$ (which explain why $a_1, a_2$ are related via $ (\frac{1}{x}, \frac{y}{x} )$.

Uncompleted attempt at proof: The line that passes through $(x,y)$ and $(\frac{4}{5}, \frac{3}{5} )$ is $ (Y' - y) ( \frac{4}{5} - x )  = (X' - x) ( \frac{3}{5} - y ) $, or that $Y' = X'\frac{5y-3}{5x-4} + \frac{3x-4y}{5x-4} $.
Substituting this into $7Y^3 = X^3 + 1$, and applying vieta's formula to find the sum of roots, we get that $\frac{4}{5} + x + x' = \frac{3 (\frac{5y-3}{5x-4})^2 (\frac{3x-4y}{5x-4}) } {1 - (\frac{5y-3}{5x-4})^3 } $, so $ x' = -\frac{625 x^4 - 1000 x^3 - 625 x y^3 + 675 x y + 370 x + 1000 y^3 - 900 y^2 - 148}{5 (5 x - 5 y - 1) (25 x^2 + 25 x y - 55 x + 25 y^2 - 50 y + 37))}$.
I'm unwilling to continue this tedious calculations, but one can find $y'$ and then verify that the equation holds.
Comment: wait, so can one prove the claim by just proceeding with the 'tedious calculation'? I don't think it should be too hard with Mathematica (for instance).
Comment: @mathworker21 I believe yes theoretically. Given that this is a contest-math problem, I didn't want to procceed with this approach.
Answer: This problem is about the sequence $\,\{a_n\}\,$ where$\,a_ 1 = -8\,$
and it satisfies the recurrence relation
$$ 4\sqrt[3]{a_{n}}+5\sqrt[3]{a_{n+1}} =
 3\sqrt[3]{7(a_{n}+1)(a_{n+1}+1)}. \tag{1} $$
Notice that the real cube root is a one-to-one and onto
function. Thus, define the related real sequence
$$ t_n := \sqrt[3]{a_{n}} \quad \text{ for all }\quad n>0. \tag{2} $$
Also, define the function
$$ f(u,v) := (4u + 5v)^3 - 3^3\,7(u^3+1)(v^3+1). \tag{3} $$
Notice that
$$ (u\,v)^3\, f(1/v,1/u) = f (u,v) \tag{4} $$
for all nonzero real $\,u,v.\,$ Now redefine $\,t_n\,$ as the
unique real solution to the recurrence relation
$$ f(t_{n-1}, t_n) = 0 \quad \text{ for all }\quad n>1. \tag{5} $$
Also, define $\,t_n\,$ for $n<1$ as the real solution to
$\,f(t_n,t_{n+1}) = 0\,$ and notice that
equation $(4)$ with equation $(5)$ together imply that
$$ t_n = 1/t_{3-n}\quad \text{ for all }\quad n\in \mathbb{Z}. \tag{6} $$
The question asks for a proof that $\,\{a_n\}\,$ is a rational sequence.
Since $\,a_n = t_n^3,\,$ It is sufficient to prove that $\,t_n=x_n/y_n\,$
for some rational sequences $\,x_n,y_n.\,$
The proof of this requires a lemma as follows.
Lemma: Define three sequences by recursion
$$ x_{n+1}  :=  12y_n^2 - 25x_nz_n,\;\;
y_{n+1} := 15x_n^2 - 16y_nz_n,\;\;
z_{n+1} := 20z_n^2 - 9x_ny_n. \tag{7} $$
using these sequences, define the special sequence
$$ e_n := x_n^3 + y_n^3 - 7z_n^3. \tag{8} $$
Verify using algebra that
$$ 4x_ny_{n+1} + 5y_nx_{n+1} - 21z_nz_{n+1} = 60e_n. \tag{9} $$
Also, verify that
$$ e_{n+1} \!=\! e_n (15x_n \!+\!12y_n \!+\!20z_n)
((15x_n)^2 \!+\!(12y_n)^2 \!+\!(20z_n)^2
- 180(3x_ny_n \!+\!5x_nz_\!+\!4y_nz_n). \tag{10} $$
This implies that if $\,e_1 = 0\,$ then $e_n = 0\,$ for all $n>0.\,$
Using equation $(9)$ this implies that
$\, 4x_ny_{n+1} + 5y_nx_{n+1} - 21z_nz_{n+1} = 0\,$ for all $n>0.\,$
Also, verify that if $\,t_n:=x_n/y_n,\,$ then
$$ f(t_n,t_{n+1}) = e_n\frac{-27((5x_n - 4y_n)
  (25x_n^2 + 20x_ny_n + 16y_n^2))^2}{(y_ny_{n+1})^3}. \tag{11} $$
This implies that if $\,e_1=0\,$ then $\,f(t_n,t_{n+1}) = 0\,$
for all $n>0.\,$
Note that if the initial values $\,x_1,y_1,z_1\,$ are integers, then
$\,x_n,y_n,z_n\,$ are integers and hence $\,t_n\,$ are rational
for all $n>0.\,$
In the application of the lemma, let $\,x_1 = -2,\, y_1 = 1, \, z_1 = -1\,$ which
gives $\,e_1 = 0\,$ and hence
$$ x_n^3 + y_n^3 - 7z_n^3 = 0 \quad \text{ for all } n>0. \tag{12} $$
and also
$$ f(t_n,t_{n+1}) = 0  \quad \text{ for all } n>0. \tag{13} $$
As a check, here is a small table of sequence values:
$$\begin{array}{|c|c|c|c|} \hline
 n  &  x_n & y_n & z_n \\ \hline
 1 & -2 & 1 & -1 \\ \hline
 2 & -38 & 76 & 38 \\ \hline
 3 & 105412 & -24548 & 54872 \\ \hline
 4 & -137372929952 & 188227311856 & 83507611664 \\ \hline
 \end{array}$$
Note that $\,x:y:z = u:v:w\,$ from the Zhaohui Du answer.
Note that I used Mathematica to verify these computations.
My original answer is below
This answer uses generalized Somos-$4$ sequences, which
are sequences that satisfy
$$ s_{n+2}s_{n-2} = p_1 s_{n+1}s_{n-1} + p_2 s_ns_n, \quad
\text{ for all }\quad n\in \mathbb{Z} $$
where $\,p_1,\,p_2\,$ are two parameters. In this question we have
$\,p_1 = -3721,\; p_2 = 1663260.\,$ Using these two parameters, define
the sequences $\,x_n,y_n,z_n\,$ with this recursion and initial values:
$$ x_0 = -17,\; x_1 = -2,\; x_2 = -1,\; x_3 = -73,\; z_2 = 1,\; z_3 = -38. $$
They satisfy the equations $\, z_n = z_{3-n}\,$ and $\, y_n = -x_{3-n} \,$
for all $\, n\in \mathbb{Z}.\,$
Now define $$ t_n := x_n/y_n,\qquad a_n := t_n^3. $$
The three sequences $\,x_n,y_n,z_n\,$ satisfy
$$ x_n^3 + y_n^3 = 7z_n^3,\quad 4x_ny_{n+1} + 5x_{n+1}y_n = 21z_nz_{n+1}. $$ These equations imply
$$ 4\sqrt[3]{a_{n}}+5\sqrt[3]{a_{n+1}}=3\sqrt[3]{7(a_{n}+1)(a_{n+1}+1)}.$$
Note that all sequences here except $\,t_n\,$ and $\,a_n\,$ are
integer sequences, although it is sufficient that $\,x_n,y_n,z_n\,$
are rational sequences which implies that $\,t_n\,$ and hence $\,a_n\,$
are rational sequences also.
As a check, here is a small table of sequence values:
$$\begin{array}{|c|c|c|c|} \hline
 n  &  x_n & y_n & z_n \\ \hline
 1  & -2 & 1 & -1 \\ \hline
 2  & -1 & 2 & 1 \\ \hline
 3  & -73 & 17 & -38 \\ \hline
 4  & -65882 & 90271 & 40049 \\ \hline
 5  & -4309182809 & -191114642 & -2252725111 \\ \hline
\end{array}$$
Note that $\,x:y:z = u:v:w\,$ from the Zhaohui Du answer.
L. E. Dickson, History of the Theory of Numbers, Volume II, Chapter XXI, section "Numbers the sum of two rational cubes: $x^3+y^3=Az^3$, pp. $572$-$578$ has several solutions for $\,A=7.$
Comment: I haven't downvoted, but can you explain how you got $3721$ and $1663260$? Keep in mind that this is a contest question : if you've derived this information from some kind of computer program, then you should be stating it.
Comment: @TeresaLisbon Thank you for your helpful comment! I appreciate it. Yes, I used Mathematica and PARI/gp. I will try to include relevant details later. I do not see any evidence that this is a "contest question". The bounty just asks "for **an answer from a reputable source**".
Comment: Ah yes, you're right : there's no evidence of this being a contest question, I probably got carried away because the other attempts were made in this spirit. Having said that , I will wait for your details, thanks and +1.
Comment: (I'm impressed that you're posting an answer using something named after you!) I don't have any experience with Somos sequence other than a quick Wikipedia read, so I apologize if this is a basic/obvious question. Is the relationship between those sequences and elliptic curves well understood? EG Can we relate an integer somos sequence to rational points on a curve?
Comment: @CalvinLin  Thanks for your comment! There **is** a relation between rational points on elliptic curves, but "well understood" is not quite there yet. For a positive example, see [OEIS sequence A006769](https://oeis.org/A006769). For this question I have an [elliptic curve $E: y^2 + y = x^3 - 331$](https://www.lmfdb.org/EllipticCurve/Q/441/d/1) and point $(21,94)$ but I have not got all the details I would like yet. The curve has $j$-invariant $0$.
Comment: The lemma seems magical to me. How did it arise? EG Was it from some underlying theory?
Comment: @CalvinLin Thanks for your comment! There are several underlying theories, but I am not an expert in any of them. I only have lots of experience with sequences defined by linear and nonlinear recursions such as Somos sequences. I may later add a bit more explanation of the different sequence recursions that appear in my answer.
Comment: @CalvinLin and I am still working on the connection with elliptic curves and other cases of $x^3+y^3=Az^3$ but it is taking much more time than I expected. Same thing with nonlinear recursions.I will try to have an updated solution with more details by years end.
Answer: This isn't an answer, really more of a musing on the problem, a full expression for $a_{n+1}$ in terms of $a_n$, and a way forward. Assuming that this problem is well posed (that is, $a_n$ can always be calculated from $a_{n-1}$ without ambiguity) then to get this expression, define $a_n=b_n^3$. Then the formula relating the $n$th and $(n+1)$th members (after cubing both sides) becomes
$$0=(4 b_n + 5 b_{n+1})^3 - 27 (7 (b_n^3 + 1) (b_{n_+1}^3 + 1))$$
$$=-189 b_{n+1}^3 b_n^3-125 b_n^3+240 b_{n+1} b_n^2+300 b_{n+1}^2 b_n-64 b_{n+1}^3-189$$
Since we are assuming that this cubic in $b_{n+1}$ has one real solution (otherwise the problem would be ill-posed) we can solve for $b_{n+1}$ in terms of $b_n$:
$$b_{n+1}=3 \sqrt[3]{\frac{7}{2}} \left(\sqrt[3]{-\frac{125 b_n^6+61 b_n^3-64}{\left(189
   b_n^3+64\right){}^2}-\frac{23625 b_n^9+27721 b_n^6+8192 b_n^3+4096}{\left(189
   b_n^3+64\right){}^3}}+\sqrt[3]{\frac{125 b_n^6+61 b_n^3-64}{\left(189
   b_n^3+64\right){}^2}-\frac{23625 b_n^9+27721 b_n^6+8192 b_n^3+4096}{\left(189
   b_n^3+64\right){}^3}}\right)-\frac{100 b_n}{-189 b_n^3-64}$$
We then use the above expression to get an expression for $a_{n+1}$ which is
$$a_{n+1}=\frac{\left(100 \sqrt[3]{a_n}-45\  \sqrt[3]{49a_n^2 \left(a_n+1\right)}-48
    \sqrt[3]{7\left(a_n+1\right){}^2}\right){}^3}{\left(189
   a_n+64\right){}^3}$$
One method to go forward here is to assume that $a_n=r^3$, and then it is sufficient to show that
$$a_n+1=7q^3$$
(for some rational $q$). This is because if this is the case then $a_{n+1}$ can also be written as $s^3$ for some rational $s$. Of course, it is not enough to simply assume $a_n=r^3$ because there are many rational $r$ for which the above equation does not hold (for example $r=1$). It is only for some $r$ (for example $r=-2$) where the above expression evaluates correctly and showing that this will always be the case for $a_n$ seems to be the difficult thing.


Como limito uma caixa de texto?

Question: Preciso colocar um limite de linhas em uma caixa de texto, e também usar um trasition para que quando a pessoa click no texto ele abra e mostre toda a mensagem.
Se alguem tiver alguma ideia Agradeço XD
Comment: O que você quer dizer com limitar linhas? você se refere a quebra de linha inserida pelo usuário? ou a que é feita automaticamente quando atinge a borda do textarea?
Answer: Segue exemplo onde o tamanho do campo vai aumentar caso o texto seja maior que o tamanho inicial definido.
Clique coloque um texto, clique fora e clique no input novamente para testar!

$( "#texto" ).click(function() {
  var tamanhoTexto = $(this).val().length;
  if (tamanhoTexto > 2){
     console.log(tamanhoTexto);
     $(this).attr('size',tamanhoTexto);
  }
});

<input id="texto" type="text"  maxlength="20" size="2"/>
Answer: Segue um exemplo, ela tem a altura de 1rem ou seja, 100% da altura da font padrão. E quando vc foca nela ela fica com altura de 3em, ou seja 3x a altura da font do elemento pai. Isso deixa o tamanho um pouco mais responsivo.
Usei o required para fazer as regras de estilos no CSS, assim se o campo não estiver preenchido ele sempre fica no tamanho original. Também coloque resize:none; para não deixar o usuário aumentar o tamanho do box
A animação vc pode fazer com transition como no exemplo abaixo:

textarea {
    width: 300px;
    height: 1rem;
    resize: none;
    transition: height 700ms;
}
textarea:focus, textarea:valid  {
    height: 3em;
}
<form action="">
    <textarea required></textarea>
    <input type="submit">
</form>
Answer: Usando os atributos do <textarea>:
<textarea name="textarea" cols="10" rows="10" wrap="textarea">

cols -> número de colunas
rows -> número de linhas
wrap -> quebra de texto

Referência do textarea
Answer: Eu prefiro separar as responsabilidades para evitar command-inline. Acho melhor você também se acostumar dessa forma, mas as duas formas acima não estão erradas.
textarea {
    width: 100%;
    height: 150px;
    padding: 12px 20px;
    box-sizing: border-box;
    border: 2px solid #ccc;
    border-radius: 4px;
    background-color: #f8f8f8;
    resize: none;
}

Answer: Tente usar o campo como:
textarea {
    width: 300px;
    height: 1rem;
    resize: none;
    transition: height 700ms;
}
textarea:focus, textarea:valid  {
    height: 3em;
}

Como limito uma caixa de texto?


A little help on the homology of a torus relative to a circle

Question: First I'll go through my working. Throughout we assume the homology groups of the torus and circle are known.

Let $X=S^1 \times S^1$ be the torus, and $A=S^1 \times \{1\}$. The following is part of a long exact sequence:
$$
\dots \to H_n(X) \to H_n(X,A) \to H_{n-1}(A) \to \dots
$$
For $n\geq 3$, we have $H_n(X) = H_{n-1}(A) = 0$, so $H_n(X,A) = 0$. Using the 'reduced version' of the sequence, we have
$$
\dots \to H_2(A) \to H_2(X) \to H_2(X,A) \xrightarrow{f} H_1(A) \xrightarrow{i_*} H_1(X)\qquad\qquad\qquad\qquad
$$
$$
\qquad\qquad\qquad\qquad\qquad \to  H_1(X,A)\to \tilde{H}_0(A) \to \tilde{H}_0(X) \to \tilde{H}_0(X,A) \to 0.
$$
Step 1. Now, $A, X$ are path connected so $\tilde{H}_0(A) =\tilde{H}_0(X) = 0$. So $\tilde{H}_0(X,A)=0$ by the long exact sequence, which gives us that $H_0(X,A) \cong \mathbb{Z}$.
Step 2. The map $i_*: H_1(A) \to H_1(X)$ takes $[\alpha] \mapsto [i(\alpha)]$ where $i$ is the inclusion. In other words, it is injective, and so $0 = \ker i_* = \text{im}\:f$, and so $f$ is the zero map. This then leaves two short exact sequences, and implies that $H_2(X,A) \cong H_2(X) \cong \mathbb{Z}$.
Step 3. It is an immediate consequence of the other remaining short exact sequence that $H_1(X,A) \cong H_1(X)/\text{im }i_* \cong \mathbb{Z} \oplus \mathbb{Z}/\mathbb{Z} \cong \mathbb{Z}$.

What I'm looking for are mainly comments on if this was done properly, but I also have two specific queries:
1. Have I used the reduced homology 'version' of the long exact sequence correctly? I'm very iffy with reduced homology...
2. My reason for $i_*$ being injective was a little handwavy. Is it always the case that a homomorphism induced by inclusion of spaces $A\hookrightarrow X$ is injective?
Answer: Overall, this looks pretty good. You probably want to point out that $H_2(A)\cong0$.
Specifically:

Yes. You wrote the sequence down properly. Reduced homology is largely used to make computations easier. It arises from augmenting the (singular, simplicial, etc.) chain complex associated to a space with an additional map $\cdots\to C_0(X)\xrightarrow{\epsilon}\mathbb{Z}\to 0$ where $\epsilon(\sum_i n_i\sigma_i)=\sum_i n_i$.
It is not always the case that the map induced by an inclusion of spaces is an injection on homology. Consider the inclusion $S^1\hookrightarrow D^2$. The disc is contractible, and so has the same homology as a point, where as $S^1$ has nontrivial $H_1$. In your case, you can see that the inclusion of $S^1$ into $S^1\times S^1$ as $S^1\times \{*\}$ induces an inclusion on homology by giving both spaces suitable cell-complex structures (be it CW-, $\Delta$-, or simplicial-) and explicitly following the map induced on the chain complex level to homology.
Comment: About 2:  Since $i$ has  a retraction $r:X\to A:(s,t)\mapsto  (s,1)$, the map $i_{\ast}$ is injective by functoriality:  $(r\circ i)_{\ast}=Id_{H_1(A)}=r_{\ast} \circ i_{\ast}$
Comment: @Fahad Sperinck Be sure to take @Georges Elencwajg's comment seriously!
Answer: I can't comment because I don't have enough points, but I'd like to remark that $\tilde H_n(X,A)$ is the same as $H_n(X,A)$ for all $n$ when $A\ne \emptyset$, so this step 1 conclusion seems incorrect...
Comment: Indeed $H_0(X,A)=0$ for any two path connected spaces $A,X$.


React function to wrap a jsx element

Question: I'm trying to create a function that will return a jsx element wrapped with  and  elements. How to do this?
In my code, I have a lot of the following:
<Top />
<Home />
<Bottom />

<Top />
<About />
<Bottom />

<Top />
<Contact />
<Bottom />

<Top />
<Blog />
<Bottom />

<Top />
<API />
<Bottom />

etc.
How can I make a function which takes say <Home /> as an input parameter and returns a wrapped jsx element?
I've tried:
function wrap(???){
  return (
    <Top />
    //what goes here????
    <Bottom />
  )
}

I'm afraid I'm still getting used to the syntax and can't figure it out
Comment: Don't you need just to pass a React.Component object to wrap() and insert {component} where you put the comment?
Comment: Thanks @Carlo, but I'm afraid I can't figure out the required syntax... ;(
Answer: first, you need to wrapp the return with a root element, a div for exp, or a Fragment which is released in React 16.2, in this exp i used a div:
function wrap(Wrapped) {
  return (

      <Top />
        <Wrapped />
      <Bottom />

  )
}

Edited: you could use the render children method also:
const WrapperExp = props => {
    return (

top

          {props.children}

bottom

    )
};

const App = () => (
  <WrapperExp>

tada...

  </WrapperExp>
);

take a look at this codesandbox exp.
Answer: The correct syntax should be
function wrap(component) {
  return (
    <Top />
      {component}
    <Bottom />
  );
}

and maybe if you use wrap in a render method
render() {
  const aComponent = (<Home/>);
  return (
    {wrap(aComponent)}
  );
}

Comment: Interesting... Excellent!

React function to wrap a jsx element


Retornar string em C para manipulação fora da função em que foi declarada

Question: Devo desenvolver uma calculadora que lê strings da forma algébrica da operação com números complexos. Preciso manipular o vetor "principal" fora da função em que foi declarado (recebe). Como proceder? Deve-se usar ponteiros? Como usá-los?
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>

int tam_max = 256;

int recebe(){

    int i = 0;
    int erro = 0;
    char principal[tam_max];
    char real1[tam_max];

    setbuf(stdin, NULL);
    fgets(principal, tam_max, stdin);

    for (i = 0; i < strlen(principal); i++){

        if (principal[0] == '\n'){
            erro++;
        } else if ( principal[i] == '+' || principal[i] == '-' ||
            principal[i] == '*' || principal[i] == '/' ||
            principal[i] == '=' || principal[i] == '^' ||
            principal[i] == 'i' || principal[i] == 'p' ||
            principal[i] == '0' || principal[i] == '1' ||
            principal[i] == '2' || principal[i] == '3' ||
            principal[i] == '4' || principal[i] == '5' ||
            principal[i] == '6' || principal[i] == '7' ||
            principal[i] == '8' || principal[i] == '9' || principal[i] == '\n'){
            erro == 0;
        } else {
            erro++;
        }
    }
    return erro;
}

int validaDados(){

    int verifica = 0;
    verifica = recebe();

    if (verifica > 0){
        printf("\nCaracteres invalidos inseridos. Por favor, tente novamente.\n\n");
        validaDados();
    }

    if (verifica == 0){
        divide();
    }
}

int divide(){
    printf("OK ate aqui\n");
}

int main(){

    validaDados();

}

Comment: Quer retornar o que? Vai usar esse retorno como? O código não indica o que deseja e não há descrição na pergunta do que deve ser feito. Precisa dar detalhes.
Comment: @bigown Preciso retornar o vetor "principal" para manipulá-lo fora do escopo em que foi declarado (recebe()). Posteriormente esse vetor será modificado dentro de outra função. Minha dificuldade é manipular strings próprias de cada escopo sem declará-las globalmente.
Answer: O correto é sempre alocar a memória necessária onde precisa e passar esse endereço para quem for manipular. Em exercícios a alocação de um array no stack  não costuma ser problema. Em aplicações mais complexas pode querer fazer alocação dinâmica no heap.
A pergunta não informa claramente como vai usar então vou tentar alguma coisa aqui criando e usando a string em validaDados() e passo ela como argumento (como é passado como um ponteiro tudo o que for alterado nela será refletida na variável original passada como argumento.:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>

#define tam_max 256

int recebe(char principal[tam_max]) {
    int erro = 0;
    setbuf(stdin, NULL);
    fgets(principal, tam_max, stdin);
    for (int i = 0; i < strlen(principal); i++) {
        if (principal[0] == '\n') {
            erro++;
        } else if ( principal[i] == '+' || principal[i] == '-' ||
            principal[i] == '*' || principal[i] == '/' ||
            principal[i] == '=' || principal[i] == '^' ||
            principal[i] == 'i' || principal[i] == 'p' ||
            principal[i] == '0' || principal[i] == '1' ||
            principal[i] == '2' || principal[i] == '3' ||
            principal[i] == '4' || principal[i] == '5' ||
            principal[i] == '6' || principal[i] == '7' ||
            principal[i] == '8' || principal[i] == '9' || principal[i] == '\n') {
            erro = 0;
        } else {
            erro++;
        }
    }
    return erro;
}

void divide() {
    printf("OK ate aqui\n");
}

void validaDados() {
    int verifica = 0;
    char principal[tam_max];
    verifica = recebe(principal);
    printf("%s\n", principal);
    if (verifica > 0) {
        printf("\nCaracteres invalidos inseridos. Por favor, tente novamente.\n\n");
        validaDados();
    }
    if (verifica == 0) {
        divide();
    }
}

int main() {
    validaDados();
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Arrumei alguns outros problemas. Mas deixei outras coisas que poderiam ficar melhor. N ão sei se o código faz o que deseja, mas está aí a solução pedida na pergunta.
Answer: Seguem algumas opções para o seu caso:
Opção 1 - O cliente aloca um buffer e passa seu ponteiro como parametro para ser preenchido internamente pela função:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define MAXBUF  (100)

char * obter_msg( char * msg, size_t tam )
{
    strncpy( msg, "Ola Mundo!", tam );
    return msg;
}

int main( void )
{
    char msg[ MAXBUF + 1 ] = {0};
    obter_msg( msg, MAXBUF );
    printf("%s\n", msg );
    return 0;
}

/* OU... */

int main( void )
{
    char * msg = (char*) malloc( (MAXBUF + 1) * sizeof(char) );
    obter_msg( msg, MAXBUF );
    printf("%s\n", msg );
    free(msg);
    return 0;
}

Opção 2 - A função possui um buffer estático interno e sempre retorna seu ponteiro para o cliente:
#include <stdio.h>
#include <string.h>

#define MAXBUF  (100)

char * obter_msg( void )
{
    static char msg[ MAXBUF + 1 ] = {0};
    strncpy( msg, "Olah Mundo!", MAXBUF );
    return msg;
}

int main( void )
{
    printf("%s\n", obter_msg() );
    return 0;
}

Opção 3 - A função aloca dinamicamente um buffer e retorna seu ponteiro para o cliente (que por sua vez, libera o buffer após o uso):
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define MAXBUF  (100)

char * obter_msg( void )
{
    char * msg = (char*) malloc( (MAXBUF + 1) * sizeof(char) );
    strncpy( msg, "Olah Mundo!", MAXBUF );
    return msg;
}

int main( void)
{
    char * msg = obter_msg();
    printf("%s\n", msg );
    free(msg);
    return 0;
}

Espero ter ajudado!


Why is $\sum_{n=1}^\infty {1\over{n^{1+ {1\over\ln \ln n}}}}$ divergent?

Question: I am just starting to learn Calculus. If anyone could help me that would be very useful. Thanks ahead
From here:
how to prove $\sum {\frac{1}{n^{1+1/n}}}$ is divergent
I don't really get how to use induction from
$\dfrac{1}{n ^ {1+ \frac{1}{n}}} \lt \dfrac{1}{2n}$
And another one is why
$\sum_{n=1}^\infty {1\over {n ^ {1+ {1\over n}}}}$ is divergence and
$\sum_{n=1}^\infty {1\over{n^{1+ {1\over \ln n} }}}$ Is not?
I mean
$\sum_{n=1}^\infty {1\over{n^{1+ {1\over \ln (\ln n) } }}}$
(Sorry)
Comment: From the last sentence of your post: what makes you think that $\sum_n \frac{1}{n^{1+\frac{1}{\ln n}}}$ is not divergent as well? **It is divergent**: you have $n^{\frac{1}{\ln n}} = e^{\frac{1}{\ln n}\cdot \ln n} = e^1 = e$, so $\frac{1}{n^{1+\frac{1}{\ln n}}}= \frac{e^{-1}}{n}$, and $\sum_n \frac{1}{n^{1+\frac{1}{\ln n}}}=\sum_n \frac{e^{-1}}{n} = \infty$.
Comment: Typesetting note: I do not recommend using `\over` as it can cause a great deal of confusion.  Instead, `\frac{ }{ }` or if you want larger display, `\dfrac{ }{ }` are easier to manipulate.
Comment: and why did $\sum_{n=0}^\infty {1\over{n^{1+ {1\over \ln {\ln (n)}} }}}$ converge?
Comment: Note that your series is undefined at the $n=0$ term, unless you interpret $1/\ln(0)$ as $0$.
Answer: After your edit: we will show that the series with general term $\frac{1}{n^{1+\frac{1}{\ln \ln n}}}$ (for $n\geq 3$) is convergent. To do so, we will compare it to the (convergent) series $\sum_{n=2}^\infty \frac{1}{n(\ln n)^2}$, which is a convergent Bertrand series.
Rewrite $$
n^{1+\frac{1}{\ln\ln n}} = n\cdot n^{\frac{1}{\ln\ln n}}= n\cdot e^{\frac{\ln n}{\ln\ln n}}
$$
and
$$n(\ln n)^2 = n\cdot e^{2\ln \ln n}$$
We have asymptotically that $\ln \ln n = o\left(\frac{\ln n}{\ln\ln n}\right)$, i.e. for $n$ big enough $\frac{\ln n}{\ln\ln n} > 2\ln \ln n$. This implies $$\frac{1}{n^{1+\frac{1}{\ln\ln n}}} < \frac{1}{n(\ln n)^2}$$ for $n$ big enough, and by comparison that the series $\sum_{n=3}^\infty \frac{1}{n^{1+\frac{1}{\ln \ln n}}}$ converges.
Answer: HINT:
Note that we have
$$n^{1/\log(n)}=e$$

Note that in the original post, the series of interest was $\sum_{n=2}^{\infty}\frac{1}{n^{1+\frac{1}{\log(n)}}}$


How do i avoid of installing a bunch of node modules that are not even listed in my package.json file?

Question: "dependencies": {
"jquery": "^2.2.3",
"normalize.css": "^4.1.1"
  },
"devDependencies": {
"browser-sync": "^2.12.3"
  }
}

Here is my package.json file, and when i delete folder named node_modules and then run npm install, as expected it should only install those that are in my package.json file but instead,  it installs a bunch of different(over 100)modules that i don't even need.
What do i need to do here?
Comment: Each module in your `package.json` has dependencies to own used modules.
Answer: There is now way to avoid that. Each module from your package.json file has dependencies to its own modules so that is why you are getting

a bunch of different

ones.
See this:

Your dependencies will now be installed maximally flat. Insofar as is possible, all of your dependencies, and their dependencies, and THEIR dependencies will be installed in your project's node_modules folder with no nesting. You'll only see modules nested underneath one another when two (or more) modules have conflicting dependencies.
  This will hopefully eliminate most cases where windows users ended up with paths that were too long for Explorer and other standard tools to deal with.


Edit index config (Search API) programmatically and get the status index updated

Question: I have a site with 14 pieces of news and 44 basic pages.

I have created an index (Search API) with this bundle:

and this is the index status (the content is already indexed during cron):

When I edit the config, add the Basic page bundle and save it:

The index status is updated:

I want to do the part 2 programmatically.
I tried two ways:
<code>$index = Index::load('my_index');
$index->setOption('datasource_settings', [
  'entity:node' => [
    'bundles' => [
      'default' => 0,
      'selected' => ['news', 'page'],
      'languages' => [
        'default' => 1',
        'selected' => [ ],
      ],
    ]
  ],
]);
$index->save();
</code>
and
<code>$datasource_settings = [
  'entity:node' => [
    'bundles' => [
      'default' => 0,
      'selected' => ['news', 'page'],
      'languages' => [
        'default' => 'TRUE',
        'selected' => [ ],
      ],
    ]
  ],
];
$search_index = \Drupal::configFactory()->getEditable('search_api.index.my_index');
$search_index->set('datasource_settings', $datasource_settings)->save();
</code>
The config is saved, but the status index is not updated:

I tried to use these codes:
Option 1:
<code>$index = Index::load('my_index');
$index->reindex();
</code>
But the nodes number are not updated, and I lose the nodes indexed:

Option 2:
<code>$index = Index::load('my_index');
$index->rebuildTracker();
</code>
Result:

Option 3:
<code>$index = Index::load('my_index');
$index->clear();
</code>
Result:

So my question is: How to update an index config programmatically and get the index status updated like the UI does when you click the Save button.
I tried to look inside the search_api module code, but I got lost :(
Thank you in advance.
Comment: What are you trying to do exactly? If you are updating config, usually you load it from its config factory by its ID.
Comment: I still don't understand what the point of this is. There are a variety of Drush commands for search API to index, clear, etc. I also don't see any explanation of why you are changing configuration programmatically or not using the config factory interface.
Comment: As the search index is a config item you could try updating the config for it programatically https://www.drupal.org/docs/drupal-apis/update-api/updating-configuration-in-drupal-8
Comment: @unusedspoon I tried it like that, but the index status does not update well, and it shows old information, I can fix it reindexing/clearing the index, or rebuilding track information, but I don't want to lose the indexed items.
Comment: @Kevin I updated the question.
Comment: @KevinI I want to do it when some specific contents type are created.
Comment: What's with https://drupal.stackexchange.com/q/309703/15055?
Answer: You can update the configuration of the search index with the following code
<code>use Drupal\search_api\Entity\Index;

$index = Index::load('my_index');
$datasources = $index->getDatasources();
foreach ($datasources as $datasource_id => $datasource) {
  if ($datasource_id == 'entity:node') {
    $configuration = $datasource->getConfiguration();
    // This will add the 'page' bundle to the configuration.
    $configuration['bundles']['selected'][] = 'page';
    $datasources[$datasource_id]->setConfiguration($configuration);
  }
}
$index->save();
</code>
After saving the index, automatically a batch process will be called, if the changes are submitted in a form.
Otherwise you manually need to add the new items to the index or reindex the whole index.
For manually adding the new items, you can for example use the following code
<code>$tracker = $index->getTrackerInstance();
$entity_type_manager = \Drupal::entityTypeManager();
$node_storage = $entity_type_manager->getStorage('node');
// Get the IDs of the new items.
$query = $node_storage->getQuery();
$query->condition('type', 'page');
$new_ids = $query->execute();
$entities = $node_storage->loadMultiple($new_ids);
$content_entity_tracking_manager = \Drupal::service('search_api.entity_datasource.tracking_manager');
foreach ($entities as $entity) {
  // Index the newly added item.
  $content_entity_tracking_manager->entityInsert($entity);
}
</code>
This may only works if you just have a few hundred new nodes, because you otherwise will get a timeout. Thats the reason, why the indexing happens in the batch process.
Answer: To reindex items as it's done through the UI, you can do the following (but this won't queue the action so it can be super slow and you should avoid calling it inside a controller action for example):
<code>$index = Index::load('my_index');
$index->reindex();

$datasource_ids = $index->getDatasourceIds();

foreach ($datasource_ids as $datasource_id) {
    // The method returns the number of indexed elements if needed.
    $index->indexItems(-1, $datasource_id);
}
</code>


Servo motor keeps trying to reach beneath 134°, what is wrong?

Question: I am trying to get the Arduino Uno board to control a gripper driven by a servo motor. The servo tries to go beneath 134° which is mechanically impossible. What can I do to fix this?
I tried to limit the motor to 180°, when it was not a reading of wanted buttons it would keep main position (closed, 180)
#include <Servo.h>

Servo myservo;

char reading;
int pos;

void setup() {
  // put your setup code here, to run once:
  myservo.attach(9);
  Serial.begin(9600);
}

void loop() {

  if (Serial.available() > 0) {

    reading = Serial.read();
    Serial.print(reading);
    if (reading == 'W' || reading == 'w') {
      pos = 134;
      myservo.write(pos);
      Serial.println("Open");
    }
    else if (reading == 'C' || reading == 'c') {
      pos = 180;
      myservo.write(pos);
      Serial.println("Close");
    }
    else if (reading != 'W' || reading != 'C') {
      myservo.write(180);
    }
  }
}

Answer: In your code, you only call attach() passing in the pin number.
The servo library requires you to specify the minimum and maximal position of the servo shaft when calling attach(). If you don't, you could end up in a situation where you're calling valid positions, but the servo either won't go far enough or tries to go further than mechanically possible.
The library needs to the know the minimum and maximum signal pulse widths so that when you call Servo.write() passing in the shaft angle, it can work out the corresponding duty cycle.
Comment: Oh, so i set a minimum and maximum value in the attach? like this: myservo.attach(9, 1700,2400);                                                                                I can't find exact values for the the different degrees. what does the numbers stand for? Sorry im a bit new to this :)
Comment: @Herman Yes; the actual pulse widths you pass in need to correspond with the minimum and maximum positions, which may or may not be (0° - 180°) for your particular servo.
Comment: @Herman Servos like the one you have operate from something called pulse-width modulation. Have a look at [this](https://en.wikipedia.org/wiki/Pulse-width_modulation).
Comment: Thanks, but this did not seem to fix the problem. The servo still tries to reach  the "wrong" angles" even though i tried different values with no luck
Comment: @Herman It may still not work depending on the numbers you used. You need to know the exact numbers to use. You have to work out what signal pulse width gives you the min/max shaft positions. That information is typically in the datasheet.
Comment: Sadly i do not have the datasheet... It did not come with the servo. But thanks for the help!
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/195408/discussion-between-delimiter-and-herman).


Array sorting as per value and corresponding key

Question: I have one array like this:
        Array
        (
           [1] => 0
           [2] => 1
           [4] => 1
           [5] => 4
           [6] => 2
           [7] => 0
           [8] => 2
           [9] => 7
           [10] => 2
           [11] => 2
           [12] => 2
           [17] => 12
           [18] => 17
           [19] => 0
           [20] => 19
           [21] => 20
           [22] => 20
           [23] => 20
           [24] => 0
         )

And i want to sort array like first all the 0 value key index find and and using this key value index find in array like 0 value key index is 1,7,19,24 and now 1,7,19,24 value find in array and corresponding key is get and at last all the key sequence is get in new array. is it possible?
Comment: What have you tried? Also, your question does not seem clear to me. What's your expected result array?
Comment: What is your expected array(result) look like ?
Comment: 0 is my root element then corresponding key index find which is 1,7,19,24 then 1,7,19,24 value find in array so for 1 we get 2,4 and now this 2,4 is further check so for 2 we get 6,8,10,11,12 and this value further check so for 6,8,10,11 we get nothing so skip and for 12 we get 17 so this type i want to check value
Comment: my array is look like Array
(
    [0] => 1
    [1] => 2
    [2] => 6
    [3] => 8
    [4] => 10
    [5] => 12 [6] => 17 and so on
Answer: asort($cars);

example:
asort($cars);
echo "
";
print_r($cars);
echo "
";

Answer: asort($arr);
$arr = array_keys($arr);
print_r($arr);

Output:
Array
(
    [0] => 7
    [1] => 1
    [2] => 19
    [3] => 24
    [4] => 2
    [5] => 4
    [6] => 10
    [7] => 12
    [8] => 11
    [9] => 8
    [10] => 6
    [11] => 5
    [12] => 9
    [13] => 17
    [14] => 18
    [15] => 20
    [16] => 21
    [17] => 23
    [18] => 22
)

Answer: $newTab = array();

foreach ($tab as $k => $v)
{
    $newTab[$v][] = $k;
}

Produces:
array (size=9)
  0 =>
    array (size=4)
      0 => int 1
      1 => int 7
      2 => int 19
      3 => int 24
  1 =>
    array (size=2)
      0 => int 2
      1 => int 4
  4 =>
    array (size=1)
      0 => int 5
  2 =>
    array (size=5)
      0 => int 6
      1 => int 8
      2 => int 10
      3 => int 11
      4 => int 12
   ....


dplyr::filter multiple criteria from other data.frame

Question: Refering on this topic:
dplyr::filter criteria from other data.frame
I adjusted the df to fit better to my complex df.
df1<-data.frame(A=c(1:10),
                B=c(3:12))
df2<-data.frame(A_min=c(2,3),
                A_max=c(3,3),
                B_min=c(1,2),
                B_max=c(2,2))

I was not able to put multiple criteria in the code with dplyr::map2
df2 |>
  mutate(Score = map2(A_min, A_max, ~ nrow(filter(df1, between(A, .x, .y)))))

I needed to adjust the code so it works in my case (don´t know exactly why between is not working).
mutate(Score=map2_dbl(A_min,A_max,~nrow(filter(df1,A>=.x & A<=.y))))

How can I add a second criteria e.g. B_min and B_max to filter at the same time to get a combined score with both criteria?  (Edited the question to make it clear what the goal is).
Comment: It is working fine for me.  Can you show your output
Comment: Sorry for the change in last minute, had to edit the question beacuse I had an mistake in my code.... but main question is left: how can I add multiple criteria to the filter step?
Comment: Does the `pmap` in the solution helps? Or are you looking for a more general solution?
Comment: Thanks for the solution @akrun but I need a single score for both criteria. I want to filter df1 with the criteria for A and for B giving a combined score. I know the example df´s are not good showing the problem ....
Comment: I got it! With your code I can just add and "&" and it works fine now. I guess it was not working for me since I did not use the across(everything()). Thanks so much!
Answer: We may use pmap
library(dplyr)
library(tidyr)
library(purrr)
 df2 |>
  mutate(Score = pmap(across(everything()),
  ~ tibble(A= nrow(filter(df1, between(A, ..1, ..2))),
   B= nrow(filter(df1, between(B, ..3, ..4)))))) %>%
   unnest_wider(Score, names_sep = "")

-output
# A tibble: 2 × 6
  A_min A_max B_min B_max ScoreA ScoreB
  <dbl> <dbl> <dbl> <dbl>  <int>  <int>
1     2     3     1     2      2      0
2     3     3     2     2      1      0

Or if there are multiple sets of columns, reshape to 'long' format before doing the processing and then reshape it back to 'wide' format
df2 %>%
  mutate(rn = row_number()) %>%
  pivot_longer(cols = -rn, names_to = c("name",  ".value"),
      names_sep = "_") %>%
   rowwise %>%
   mutate(name, Score = df1 %>%
   filter(between(cur_data()[[name]], min, max)) %>%
     nrow, .keep = 'unused') %>%
   ungroup %>%
   pivot_wider(names_from = name, values_from = Score,
    names_glue = "Score{name}") %>%
   select(-rn) %>%
   bind_cols(df2, .)
   A_min A_max B_min B_max ScoreA ScoreB
1     2     3     1     2      2      0
2     3     3     2     2      1      0


How to render a field above the node title using omega sub-theme

Question: I am trying to render a slideshow in a node above the page title
So far I have in my template.php
function MYTHEME_preprocess_region(&$vars) {
  $theme = alpha_get_theme();
  if ($vars['elements']['#region'] == 'content') {
    $vars['node'] = $theme->page['node'];
  }
}

this passes a $node variable into a custom region--content.tpl.php
I was then expecting to be able to use this snippet to render the field but it fails
print render($node['field_slideshow_images']);

Answer: You might get a bit more luck using the field_view_field function:
function MYTHEME_preprocess_region(&$vars) {
  $theme = alpha_get_theme();
  if ($vars['elements']['#region'] == 'content') {
    $node = $theme->page['node'];

    $vars['slideshow'] = field_view_field('node', $node, 'field_slideshow_images');
  }
}

And then use print render($slideshow); in your template file.
You might need to play with the 4th parameter to field_view_field() ($display) a bit if you have custom settings on your display for that field, but it should be a good place to start.
Comment: Thanks Clive, this has done the job. Display 'default' and it has triggered the slideshow module. Unfortunately though the inline styles from jquery.cycle are not present so the images are not sliding. I shall investigate further.
Comment: @James Hah I only just realised which James you are. See you next week mate :)
Answer: For anyone else who needs to do this, here is a shorter version with better validation and using menu_get_object instead of getting the node from the theme.
function MYTHEME_preprocess_region(&$vars) {
  if ($vars['elements']['#region'] == 'content') {
    if ($node = menu_get_object()) {
      $vars['slideshow'] = field_view_field('node', $node, 'field_slideshow_images', 'default');
    }
  }
}

Then in region--content.tpl.php
print render($slideshow);


Proof by Induction: The Cartesian product of a denumerable set A and a finite set B are denumerable

Question: Assume A is finite and B is denumerable then AxB is denumerable.
Let n=A>0
Argue by induction on N.
Basic step: n=1: {(A1,B1),(A1,B2),...,(A1,Bk)} <-is denumerable
n:
{(A1,B1),...,(A1,Bk),(A2,B1),...,(A2,Bk),...(An,Bk)}
n+1:
{(A1,B1),...,(A1,Bk),(A2,B1),...,(A2,Bk),(An,B1),...,(An,Bk),(An+1,B1),...,(An+1,Bk)}
I'm not quite sure how to proceed.
Answer: If $Card(A)=n+1$, then $A=C\cup \{a_{n+1}\}$ with $Card(C)=n$.
Can you now write $A \times B$ has the union of two denumerable set, $C \times B$ as in the $n$-th step, and $\{a_{n+1}\} \times B$ as in the first step ? And the union of two denumerable sets being denumerable...
Comment: Would there be a proof necessary to show that CxB is denumerable? because we would be trying to show (CxB) U {An+1}xB, or are we just assuming that (AxB) is denumerable is true
Comment: @Soo lee : not sure what you mean. CxB is denumerable according to your induction hypothesis. The union of two denumerable sets being denumerable is a standard property, usually one of the very first you see just after learning the definition of denumerable. (if you want to prove it, just number one set with odd numbers and the other set with even numbers...)
Answer: You can prove a stronger statement.
See the link below
https://proofwiki.org/wiki/Cartesian_Product_of_Countable_Sets_is_Countable


How to properly parse and type graphql results?

Question: Q: How do I parse and type a server response in a generic way when one of the parent keys in the response will constantly change?
As a preface: I'm still new to TS and parsing server responses - so maybe this is obvious - but after a day I've not found a good solution.
Background: I'm using Typescript and AWS Amplify. I have a graphql mutation called CreateGroup. It requires input of a code-generated type CreateGroupInput defined as such:
export type CreateGroupInput = {
  id?: string | null,
  name: string,
  createdAt?: string | null,
  updatedAt?: string | null,
};

//I'm using this as input to create a new db entry
const groupInfo: CreateGroupInput = {
  name: "new group",
  createdAt: time,
  updatedAt: time
};

I want to parse and type the result of the mutation so that I can access the id that gets created during the mutation process. IDEALLY this is what I would like to do:
const data = API.graphql(graphqlOperation(mutations.createGroup, {input: groupInfo}) as CreateGroupInput;

and have the data variable be of type CreateGroupInput with the server response all in the correct place. However the result I get back doesn't parse nicely because the structure is a bit different:
{
    "data": {
        "createGroup": {
            "id": "1d720f68-56bd-46a9-82ef-e060a5b07177",
            "name": "new group",
            "createdAt": "1580278766358",
            "updatedAt": "1580278766358"
        }
    }
}

I tried doing different combinations of JSON.Parse and JSON.stringify - but none of them work and honestly it feels like I am doing something really wrong. This function will eventually handle many different mutations - and I expect the name "createGroup" in the response to change for each of these - so I can't just parse "result.data.createGroup" either.
Which leads me to posting this question. How do I parse and type the server response in a generic way when the key "createGroup" in the response will constantly change?
Answer: I found out the results can ALSO be accessed by a key (in retrospect - this should have been obvious) - which allows me to use variables.
I added an extra input to the function "queryName" and then accessed the data using
result.data[queryName]
it's not IDEAL - but way better than the alternatives.


Simplifying a three-index sum that depends only on the differences between indices

Question: I have the following sum:
\begin{equation}
S = \sum_{i,j,k=1}^La^{|i-j|}a^{|i-k|},
\end{equation}
where, to be clear, all indices run from $1$ to $L$ and $a<1$ is real. I sense that I should somehow change variables to $x=i-j$ and $y=i-k$, but I'm not exactly sure how to do this. I've been trying to think about this in a combinatoric way (imagining a line of length $L$ and the two terms in the sum being subsections of length $|i-j|$ and $|i-k|$), but I didn't get far.
The sum has an analytic solution according to Mathematica.
Comment: If you fix $i$, can you compute $\sum_{j=1}^L a^{|i-j|}$?
Answer: Define $P$ by taking $i$ to be a constant as follows
$$P=\sum\limits_{k=1}^La^{|i-k|}=\sum\limits_{k=1}^ia^{k-1}+\sum\limits_{k=1}^{L-i}a^{k}=\frac{a^i-1}{a-1}+\frac{a(a^{L-i}-1)}{a-1}=\frac{a^{i}+a^{L-i+1}-a-1}{a-1}$$
$$\sum\limits_{j,k=1}^La^{|i-j|}a^{|i-k|}=\left(\sum\limits_{j=1}^La^{|i-j|}\right) \left(\sum\limits_{k=1}^La^{|i-k|} \right) =P^2$$
$$S=\sum_{i,j,k=1}^La^{|i-j|}a^{|i-k|}= \sum_{i=1}^LP^2=\sum_{i=1}^L  \left(\frac{a^{i}+a^{L-i+1}-a-1}{a-1} \right) ^2$$
$$S=\frac{2a^{2L+2}-2(L+2)a^{L+1}-8a^{L+2}+2(L-2)a^{L+3}+a^4L+2a^3 (L+2)+6a^2-2a(L-2)-L}{(a-1)^3(a+1)}$$
I did the summation with help of wolfram alpha and I also checked the case when $L=2, a=2$.


Noise in polynomial systems.

Question: Consider equations of the form
\begin{equation}
n_1 x^i + n_2 y^i = s_i
\end{equation}
where $n_1, n_2 \in \mathbb{N}$ are known coefficients and
$s_i > 0$ is a real constant.
Fix two indices $i<k$ and consider the following polynomial system
\begin{align*}
n_1 x^i + n_2 y^i = s_i\\
n_1 x^k + n_2 y^k = s_k
\end{align*}
with solutions
$(x_1, y_1), \ldots,(x_{ki}, y_{ki}) \in \mathbb{C}^2$. I know that
for this system there exists at least one solution
$(x*, y*) \in (0,1)^2$.
Now consider the following perturbed system
\begin{align*}
n_1 x^i + n_2 y^i = \widetilde{s}_i\\
n_1 x^k + n_2 y^k = \widetilde{s}_k
\end{align*}
where $|\widetilde{s}_i - s_i | < \epsilon_i,\ |\widetilde{s}_k - \widetilde{s}_k| < \epsilon_k$. Let $(\widetilde{x}_1, \widetilde{y}_1),
\ldots, (\widetilde{x}_{ki}, \widetilde{y}_{ki}) \in \mathbb{C^2}$ be the solutions of the perturbed system.
Question

I would like to measure the "impact" of the perturbations of the coefficients $s_i, s_k$ on the solutions of the system. References on similar topics are welcome.
Comment: Have you considered a first-order Taylor series expansion about $(x^*,y^*)$?
Comment: @Rahul You mean consider the solution $(x^*, y^*)$ as a function $G(x,y, s_i, s_k) =0$ and then take the partial derivatives with respect to $s_i, s_k$ ?
Comment: No, I mean what N74 has just posted in an answer.
Answer: First of all it is better to write the solution to the perturbed system this way
\begin{align*}
n_1 \widetilde{x} ^i + n_2 \widetilde{y} ^i = \widetilde{s}_i\\
n_1 \widetilde{x}^k + n_2 \widetilde{y} ^k = \widetilde{s}_k
\end{align*}
Where $\widetilde{x}=x(1+\delta_x)$ and $ \widetilde{y}=y(1+\delta_y)$.
When the deltas are little we can rewrite the system as :
\begin{align*}
n_1 x^i (1+i\delta_x) + n_2 y^i (1+i\delta_y) = {s}_i+\epsilon_i\\
n_1 x^k  (1+k\delta_x)+ n_2 y^k  (1+k\delta_y)= {s}_k+\epsilon_k
\end{align*}
Simplifying out the known factors
\begin{align*}
n_1 x^i i\delta_x+ n_2 y^i i\delta_y= \epsilon_i\\
n_1 x^k  k\delta_x+ n_2 y^k  k\delta_y= \epsilon_k
\end{align*}
This is a first order linear system for $(\delta_x,\delta_y)$. You can solve it and study the range of variation of the deltas as $(x, y)$ vary in $(0,1)^2$.
Comment: You can start here: https://en.m.wikipedia.org/wiki/Experimental_uncertainty_analysis and follow the references.
Comment: Thanks, is there any text on such methods ?

Noise in polynomial systems.


Jquery and Slimframework - Status Request

Question: How can I response a Jquery $.post call with Slimframework 3 with multiples status code?
my code is:
Javascript:
<code>$.post('/insert/table/' + $pedido, table_data)
     .done(function(data, statusText, xhr) {
         alert(xhr.status);
         if (xhr.status == 201) {
            alert('Done');
         } else {
            alert('Error');
         }
      })
      .fail(function(xhr, textStatus, errorThrown) {
         alert(xhr.responseText);
      });
</code>
PHP:
<code>$this->post('/insert/table/{pedido}',
 \App\Controller\Master\MasterController:SaveTable');

public function SaveTable($request, $response, $args) {
    $params = (object) $request->getParams();
    $logger = $this->container->get('logger');
    $pedido = $args['pedido'];
    if($pedido < 1){
        $logger->error('Arg:Cod Pedido error.');
        $response->withStatus(503);
        return $response;
    }

    $conn = $this->container->get('DB_Producao');
    if($conn) {
        $tsql= "INSERT INTO .......";
        if(!sqlsrv_query($conn, $tsql)) {
            $logger->error('error');
            $response->withStatus(503);
            return $response;
            die();
        }
    }
    $response->withStatus(201)
             ->withHeader('Content-Type', 'text/plain')
             ->write('Done');;
    return $response;
}
</code>
With this code, I always receive a status code 200 from post action. And I was expecting a 201 or 503 status code.
Comment: Is there a missing quote before `\App\Controller\Master\MasterController:SaveTable'`?  If not can you check you get `Done` back (use the network tab on the browser to check).
Answer: The request and response headers are "immutable".
Instead of this:
<code>$response->withStatus(503);

return $response;
</code>
Try this:
<code>return $response->withStatus(503);
</code>
or
<code>$response = $response->withStatus(503);

return $response;
</code>
<code>// The headers are immutbale
$response = $response->withStatus(201)
    ->withHeader('Content-Type', 'text/plain');

// The body is not immutable
$response->getBody()->write('Done');

return $response;
</code>


O Loop do meu código JavaScript não está funcionando corretamente

Question:

function contar() {
    let inicio= document.getElementById('inicio').value
    let fim= document.getElementById('fim').value
    let passo= document.getElementById('passo').value
    let res= document.getElementById('res')
    res.innerHTML=`Resultado:<br>`

    if(inicio!=0 && fim!=0 && passo!=0){

       for(let c = inicio ; c <= fim ; c += passo) {

            res.innerHTML+=`${c}`

        }
    }
    else{
        alert('[ERRO] Não foi inserido os valores     corretamente, tente novamente.')
    }
}
body{
    background: rgb(2, 168, 168);
    font: normal 20pt Arial;
    width: 600px;
    margin: auto;
    margin-top: 200px;
}
header{
    color: white;
    text-align: center;
}
section{
    background: white;
    border-radius: 10px;
    padding: 15px;
    width: 500px;
    margin: auto;
    box-shadow: 6px 6px 6px 6px rgba(0, 0, 0, 0.288);
    text-align: left;
}
footer{
color: white;
    text-align: center;
    font-style: italic;
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Exercício Repetição</title>
    <link rel="stylesheet" type="text/css" href="estilo.css">

Repetições

                Início:
                <input type="number" id="inicio">

                Fim:
                <input type="number" id="fim">

                Passo:
                <input type="number" id="passo">

                <input type="button" value="Contar" onclick="contar()">

© Joao

Aqui:
if(inicio!=0 && fim!=0 && passo!=0){

   for(let c = inicio ; c <= fim ; c += passo) {

        res.innerHTML+=`${c}`

    }
}

Comment: Relacionada (de modo geral sobre a importância de ser explícito em relação às conversões de tipos): https://pt.stackoverflow.com/questions/478394/math-random-definindo-valores-m%C3%ADnimos-e-máximos-diferentes-de-0/478396#478396
Comment: Seja bem-vindo. Imagino que não tenha ouvido falar em _debugging_, debugar ou depurar código. É possível em diversos navegadores também, é só apertar F12 e aprender como usar para inspecionar seu código e ver como ele está se comportando. Dê uma pesquisada a respeito.
Answer: O seu problema é que você está realizando operações matemáticas com string. document.getElementById('..').value retorna uma string, por mais que o input seja do tipo "number", e isso gera comportamentos inesperados.
Como resolver isso?

Conversão!

Converta os tipos string para número simplismente adicionando um + na frente da variável.
Veja como:
let inicio = document.getElementById('inicio').value;
let fim = document.getElementById('fim').value;
let passo = document.getElementById('passo').value;
let res = document.getElementById('res');

// convertemos aqui o "fim", "passo" e "inicio" para número
fim = +fim;
passo = +passo;
inicio = +inicio;

Veja como ficaria a função contar:
function contar() {
  let inicio = document.getElementById('inicio').value;
  let fim = document.getElementById('fim').value;
  let passo = document.getElementById('passo').value;
  let res = document.getElementById('res');

  fim = +fim;
  passo = +passo;
  inicio = +inicio;

  res.innerHTML = `Resultado:<br>`;

  if (inicio != 0 && fim != 0 && passo != 0) {
    for (let c = inicio; c <= fim; c += passo) {
      res.innerHTML += ` - ${c}`;
    }
  } else {
    alert(
      '[ERRO] Não foi inserido os valores corretamente, tente novamente.',
    );
  }
}

O código funcionando:

function contar() {
  let inicio = document.getElementById('inicio').value;
  let fim = document.getElementById('fim').value;
  let passo = document.getElementById('passo').value;
  let res = document.getElementById('res');

  fim = +fim;
  passo = +passo;
  inicio = +inicio;

  res.innerHTML = `Resultado:<br>`;

  if (inicio != 0 && fim != 0 && passo != 0) {
    for (let c = inicio; c <= fim; c += passo) {
      res.innerHTML += ` - ${c}`;
    }
  } else {
    alert(
      '[ERRO] Não foi inserido os valores corretamente, tente novamente.',
    );
  }
}
body {
  background: rgb(2, 168, 168);
  font: normal 20pt Arial;
  width: 600px;
  margin: auto;
  margin-top: 200px;
}
header {
  color: white;
  text-align: center;
}
section {
  background: white;
  border-radius: 10px;
  padding: 15px;
  width: 500px;
  margin: auto;
  box-shadow: 6px 6px 6px 6px rgba(0, 0, 0, 0.288);
  text-align: left;
}
footer {
  color: white;
  text-align: center;
  font-style: italic;
}
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Exercício Repetição</title>
    <link rel="stylesheet" type="text/css" href="estilo.css" />

Repetições

          Início:
          <input type="number" id="inicio" />

        Fim:
        <input type="number" id="fim" />

          Passo:
          <input type="number" id="passo" />

        <input type="button" value="Contar" onclick="contar()" />

© Joao

Adicionei um - em res.innerHTML += ' - ${c}'; apenas para facilitar a visualização...
com uso de TypeScript, evitariamos esses problemas ...


Proof of every finite group is finitely presented.

Question: I'm reading the proof that every finite group is finitely presented from Dummit's Abstract Algebra, but there's a part that I don't understand. In the proof below, what are the elements $\tilde{g_i}$? I think they are the cosets $g_iN$, but how do we know that they generate $\tilde{G}$? And why does $|\tilde{G}|=|G|$ lead to $N=\ker \pi$? And finally, how do we get the sufficient condition (ii) in the final sentence?
I really do not understand these parts and I'd greatly appreciate any explanations.
Comment: But really, although of course it is necessary to give a rigourous proof, this fact should be completely obvious : if a group is finite, it is given by a finite number of generators and relations (you can just give its whole multiplication table, which is finite).
Comment: Yes $\tilde g_i = g_iN$. They generate $\tilde G$ because the $g_i$ generate $F(S)$. We know that $N \le \ker \pi$, and $|G| = |F(S)|/|\ker \pi|$, $|\tilde G| = |F(S)|/|N|$, so $|G| = |\tilde G| \Rightarrow N=\ker \pi$.
Answer: I'll try to clarify the proof though you might have done it already (I was struggling with this theorem too so the answer could be useful for someone).
First of all, let's check that $N$ $\leq$ ker $\pi$. It is true since $N$ is the intersection of all normal subgroups containig $R_0$, and ker $\pi$ is one of such subgroups. Now we apply the following theorem. Let $h:A\rightarrow B$ be a homomorphism and $A$ $\rhd$ $X$ $\leq$ ker $h$, then for the projection $p:A\rightarrow A/X$ there is a unique homomorphism $f$ such that the following diagram commutes ($h=f\circ p$):
$\hskip2.8in$
Let say that in our case there is a unique homomorphism $\phi$ such that the following diagram has to commute:
$\hskip2.8in$
Now consider the cosets $g_1N,...,g_nN\in F(S)/N$. Note that they are pairwise distinct. Indeed, we have $i\neq j\rightarrow\pi(g_i)=g_i\neq g_j=\pi(g_j)$, and the commutativity implies $\pi(g_i)=\phi(p(g_i))=\phi(g_iN)$, $\pi(g_j)=\phi(p(g_j))=\phi(g_jN)$. Thus $i\neq j\rightarrow\phi(g_iN)\neq\phi(g_jN)$. So it's not the case that $g_iN=g_jN$ for $i\neq j$.
It's easy to verify that $F(S)/N=\langle g_1N,...,g_nN\rangle$. With this if we'll prove that $\{g_1N,...,g_nN\}$ is closed under the multiplication and inversion, then we'll get $F(S)/N=\{g_1N,...,g_nN\}$.
Let's begin from the multiplication. We have $g_iNg_jN=g_ig_jN$. Let $g_ig_j=g_k$ then $g_ig_jN=g_kN$. Indeed, $g_ig_jg_k^{-1}\in N$ thus $g_ig_j\in Ng_k=g_kN$. Further we have $(g_jN)^{-1}=g_j^{-1}N$. Let $g_j^{-1}=g_k$ then $g_j^{-1}N=g_kN$. Indeed, let $g_i=e_G$ then $g_ig_kg_j\in N$. So $g_ig_k\in Ng_j^{-1}=g_j^{-1}N$. This implies $g_j^{-1}N=g_ig_kN$. But $g_ig_kN=g_kN$ as we have proved.
We conclude that $F(S)/N$ consists of $n$ distinct elements: $\{g_1N,...,g_nN\}$. The commutativity of our diagram implies $\phi(g_iN)=g_iN$. This means $\phi$ is injective. Now, if we assume that ker $\pi$ - $N$ contains some element $a$, then $aN\neq N$ and $\phi(aN)=e_G$. This gives a contradiction with the injectivity. Thus we have $N$ $=$ ker $\pi$ and $G\cong(S|R_0)$.
Comment: I think it should be:$\phi(g_iN)=g_i$


t:inputFileUpload in JSF throws NullPointerException on myBean.submit()

Question: Since yesterday I struggle with uploading a file in my jsf web application. The tutorials (one from balusC, the other one from some offical java-tutorial page) I found were very good, but somehow it still won't run. I guess there's something wrong with the web.xml, because that were the answers I found on google, but still no good results for me.
Now in details:
Firstly: I build a new project just to test the upload, so if there are too many libraries (if there is s.th. like that), pls let me know.
Secondly: it's a course projekt at my university, so there are some things, I have to use, like the h2-database and the glassfish application server.
libraries I use:
commons-el-1.0.jar
commons-fileupload.1.2.1.jar
commons-io-1.3.2.jar
commons-logging.1.1.1.jar
tomahawk20-1.1.10.jar
h2-1.2.141.jar
jboss-el-2.0.1.GA.jar
jstl-1.2.jar
jsf-api.jar
my web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">

<display-name>Test</display-name>

<session-config>
    <session-timeout>15</session-timeout>
</session-config>

<servlet>
    <servlet-name>FacesServlet</servlet-name>
    <servlet-class>
        javax.faces.webapp.FacesServlet
    </servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>FacesServlet</servlet-name>
    <url-pattern>/faces/*</url-pattern>
</servlet-mapping>

<servlet-mapping>
    <servlet-name>FacesServlet</servlet-name>
    <url-pattern>*.faces</url-pattern>
</servlet-mapping>

<filter>
    <filter-name>ExtensionsFilter</filter-name>
    <filter-class>
        org.apache.myfaces.webapp.filter.ExtensionsFilter
    </filter-class>
    <init-param>
        <param-name>uploadMaxFileSize</param-name>
        <param-value>10m</param-value>
    </init-param>
    <init-param>
        <param-name>uploadThresholdSize</param-name>
        <param-value>100k</param-value>
    </init-param>
</filter>

<filter-mapping>
    <filter-name>ExtensionsFilter</filter-name>
    <servlet-name>FacesServlet</servlet-name>
</filter-mapping>

<welcome-file-list>
    <welcome-file>index.html</welcome-file>
</welcome-file-list>

<context-param>
    <param-name>com.sun.faces.expressionFactory</param-name>
    <param-value>org.jboss.el.ExpressionFactoryImpl</param-value>
</context-param>

my test.xthml
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  <ui:composition xmlns="http://www.w3.org/1999/xhtml"
  xmlns:ui="http://java.sun.com/jsf/facelets"
  xmlns:h="http://java.sun.com/jsf/html"
  xmlns:f="http://java.sun.com/jsf/core"
  xmlns:t="http://myfaces.apache.org/tomahawk"
  xmlns:sf="http://www.springframework.org/tags/faces"
  xmlns:x="http://myfaces.apache.org/extensions"
  template="template.xhtml">

<ui:define name="header">

List of Matches

</ui:define>

<ui:define name="content">
<f:view>

        <title>File upload test</title>

        <h:form id="uploadForm" enctype="multipart/form-data">
            <h:panelGrid columns="3">
                <h:outputLabel for="file" value="Select file" />
                <t:inputFileUpload id="file" value="#{myBean.uploadedFile}" storage="file" required="true" />
                <h:message for="file" style="color: red;" />

                <h:panelGroup />
                <h:commandButton value="Submit" action="#{myBean.submit()}" />
                <h:message for="uploadForm" infoStyle="color: green;" errorStyle="color: red;" />
            </h:panelGrid>
        </h:form>

        <h:outputLink value="file/#{myBean.fileName}" rendered="#{myBean.fileName != null}">
            Download back
        </h:outputLink>

</f:view>
</ui:define>
</ui:composition>

MyBean.java
package managedbean;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

import javax.faces.bean.ManagedBean;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.myfaces.custom.fileupload.UploadedFile;

@ManagedBean (name = "myBean")
public class MyBean {

private UploadedFile uploadedFile;
private String fileName;

public void submit() {

    String prefix = FilenameUtils.getBaseName(uploadedFile.getName());
    String suffix = FilenameUtils.getExtension(uploadedFile.getName());

    File file = null;
    OutputStream output = null;

    try {
        file = File.createTempFile(prefix + "_", "." + suffix, new File("/Users/"));
        output = new FileOutputStream(file);
        IOUtils.copy(uploadedFile.getInputStream(), output);
        fileName = file.getName();

    } catch (IOException e) {

        if (file != null) file.delete();

        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(output);
    }
}

public UploadedFile getUploadedFile() {
    return uploadedFile;
}

public String getFileName() {
    return fileName;
}

public void setUploadedFile(UploadedFile uploadedFile) {
       this.uploadedFile = uploadedFile;
}

}

And my full stack traces, when I submit
[#|2011-03-18T22:00:08.768+0100|WARNING|oracle-glassfish3.1|javax.enterprise.resource.webcontainer.jsf.lifecycle|_ThreadID=19;_ThreadName=http-thread-pool-8080(4);|#{myBean.submit()}: java.lang.NullPointerException
javax.faces.FacesException: #{myBean.submit()}: java.lang.NullPointerException
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:118)
    at javax.faces.component.UICommand.broadcast(UICommand.java:315)
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:794)
    at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1259)
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:409)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1534)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:343)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:215)
    at org.apache.myfaces.webapp.filter.ExtensionsFilter.doFilter(ExtensionsFilter.java:349)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:215)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:279)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:98)
    at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandardPipeline.java:91)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:162)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:326)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:227)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:170)
    at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:822)
    at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:719)
    at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1013)
    at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:225)
    at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
    at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
    at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
    at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
    at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
    at java.lang.Thread.run(Thread.java:680)
Caused by: javax.faces.el.EvaluationException: java.lang.NullPointerException
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:102)
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
    ... 37 more
Caused by: java.lang.NullPointerException
    at managedbean.MyBean.submit(Unknown Source)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.jboss.el.util.ReflectionUtil.invokeMethod(ReflectionUtil.java:329)
    at org.jboss.el.util.ReflectionUtil.invokeMethod(ReflectionUtil.java:274)
    at org.jboss.el.parser.AstMethodSuffix.getValue(AstMethodSuffix.java:59)
    at org.jboss.el.parser.AstMethodSuffix.invoke(AstMethodSuffix.java:65)
    at org.jboss.el.parser.AstValue.invoke(AstValue.java:96)
    at org.jboss.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:276)
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88)
    ... 38 more
|#]

[#|2011-03-18T22:00:08.774+0100|WARNING|oracle-glassfish3.1|javax.enterprise.system.container.web.com.sun.enterprise.web|_ThreadID=84;_ThreadName=http-thread-pool-8080(4);|StandardWrapperValve[FacesServlet]: PWC1406: Servlet.service() for servlet FacesServlet threw exception
javax.faces.el.EvaluationException: java.lang.NullPointerException
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:102)
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
    at javax.faces.component.UICommand.broadcast(UICommand.java:315)
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:794)
    at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1259)
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:409)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1534)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:343)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:215)
    at org.apache.myfaces.webapp.filter.ExtensionsFilter.doFilter(ExtensionsFilter.java:349)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:215)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:279)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:98)
    at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandardPipeline.java:91)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:162)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:326)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:227)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:170)
    at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:822)
    at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:719)
    at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1013)
    at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:225)
    at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
    at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
    at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
    at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
    at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
    at java.lang.Thread.run(Thread.java:680)
Caused by: java.lang.NullPointerException
    at managedbean.MyBean.submit(Unknown Source)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.jboss.el.util.ReflectionUtil.invokeMethod(ReflectionUtil.java:329)
    at org.jboss.el.util.ReflectionUtil.invokeMethod(ReflectionUtil.java:274)
    at org.jboss.el.parser.AstMethodSuffix.getValue(AstMethodSuffix.java:59)
    at org.jboss.el.parser.AstMethodSuffix.invoke(AstMethodSuffix.java:65)
    at org.jboss.el.parser.AstValue.invoke(AstValue.java:96)
    at org.jboss.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:276)
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88)
    ... 38 more
|#]

Like I said, it's just the tutorial I put together; the name of the file is shown in the textfield, but when hitting submit, there's just the exception.
Thanks in advance.
EDIT: I just thought it might be useful to know that work with the 1.6.0jdk.
Comment: Got it working with primefaces now, but if someone solves the problem above pls feel free to answer, I rly want to know, why it's not working.
Answer: I had the same problem, but worked in linux and fail in windows. To pass over this issue i found this solution:
Do not forget to add the "enctype" attribute to your Form and set this attribute to "multipart/form-data".
<h:form enctype="multipart/form-data">

See more here: Source
Comment: If you look over my code, you'll see that I did that. So, that wasn't the problem.
Comment: LOL, you are right, mmm that was enough for me. I replicated this problem when I used ajax4jsf, because some browsers has limitations on this input field ... but seems that you don't use any javascript in your example.


Float to Double conversion - Best assertion in a unit test?

Question: Given the statements
float f = 7.1f;
double d = f;

What can we assert in a unit test about d?

For example this does not work:
Console.WriteLine(d == 7.1d); // false
Console.WriteLine(d < 7.1d + float.Epsilon); // true by luck
Console.WriteLine(d > 7.1d - float.Epsilon); // false (less luck)

The best way I found so far is to convert the value back:
float f2 = (float)d;
Console.WriteLine(f2 == f); // true

Which would be the same as the brute way to say
Console.WriteLine(d == 7.1f); // 7.1f implicitly converted to double as above

This question is NOT about double and float precision in general but really JUST about the pragmatic question how a unit test can best describe the confines of d. In my case, d is the result of a conversion that occurs in code generated by light weight code generation. While testing this code generation, I have to make assertions about the outcome of this function and this finally boils down to the simple question above.
Comment: Which unit testing framework are you using? You might not necessarily assert against a condition you derive e.g. `Assert.IsTrue(condition)`, you might be able to use e.g. `Assert.AreEqual(value1, value2)` that could handle equivalence between numeric formats.
Comment: I'm still not sure what you're trying to test here. A double has more precision than a float and they will thus hardly ever be "equal" to each other.
Comment: If you omit the final f in the constant used for initializing the float, it might be even worse, see a crafted example here http://stackoverflow.com/questions/13276862/c-c-notation-of-double-floating-point-values/13279512#13279512
Answer: Your "best way" is asserting that your generated code returns something that is, within float's margin of error, 7.1. This may be what you want to check, in which case, carry on.
On the other hand, you might want to assert that your generated code returns specifically the result of casting 7.1f to a double, in which case you could do:
Console.WriteLine(d == (double)f);

This is more stringent - your test asserts that d is within a small range, while the above test asserts that d is a specific value.
It really depends on what you'll be using d for. If it's a case where things will go wrong if it's not the exact value, test the exact value, but if it's OK to be within a float of the value, check against the float.
Comment: Rawling, that is it for me. I expect my code to convert 7.1f into a double, so my assertion now is

    d.Should().Be((double)7.1f);

that makes my expectation most clear. thx for your input.
Answer: To compare two float point values ibm sugests to test abs(a/b - 1) < epsilon
an msnd states that Epsilon property reflects the smallest positive value that is significant in numeric operations or comparisons when the value of the instance is zero.
so actually you should check
Math.Abs(d/(double)f) - 1) < float.Epsilon)

Comment: thx for the hint from ibm: If you don't know the scale of the underlying measurements, using the test "abs(a/b - 1) < epsilon" is likely to be more robust than simply comparing the difference.
Comment: +1. Yes, it makes no sense to add epsilon to a possibly big number. It would have no effect at all. This would only work for fixed point numbers.
Comment: The document you point to is published by IBM, but it is identified as authored by a person and corporation other than IBM. So it is not clear IBM is making that suggestion, anymore than a book publisher agrees with everything the authors they publish state. And it is not entirely fair to accuse IBM of promoting this sloppy practice based on that.
Comment: @EricPostpischil how exactly is this 'sloppy'?  To me, it looks like a fairly reasonable approximation of how to test the underlying question.
Comment: @RonLugge: Reasons it is sloppy are too numerous and complex to detail in a comment. Suffice it to say that this technique decreases "false" not-equal results at the expense of increasing false is-equal results, the value `epsilon` should generally not be the `Epsilon` this answer refers to, a relative threshold is not the correct criterion to use if the error derives from values other than the final result, this test is inappropriate for the situation in this question where exact equality may be tested for, and software generally ought to be designed to avoid a need for these comparisons.
Answer: (float) d == f.
Another answer suggested d == (double) f, but this is a useless test because (double) f performs the same conversion that d = f implicitly performs. So the only thing this assertion could be testing is whether some aspect of the implementation is broken (e.g., the compiler implemented one of the conversions incorrectly and in a way different from the other), some external mechanism altered d or f between the assignment and the assertion, or the source code were broken so that d was neither double nor float nor any type that can hold the value of f exactly or the assignment d = f was not performed.
Generally, we expect no floating-point error, because, in every normal implementation of floating-point, converting from a narrower precision to a wider precision of the same radix has no error, since the wider precision can represent every value the narrower precision can. In uncommon situations, a wider floating-point format might have a smaller exponent range. Only in this case, or in perversely defined floating-point formats, could converting to a wider format cause a change in value. In these cases, performing the same conversion would not detect the change.
Instead, we convert from the wider format back to the narrower format. If d differs from f, this conversion has a chance of detecting the error. E.g., suppose f contained 0x1p-1000, but, for some reason, that is not representable in the format of d, so it was rounded to zero. Then (float) d == f evaluates to (float) 0 == 0x1p-1000, then to 0 == 0x1p-1000, then to false. Additionally, this test may detect the same errors as the other suggestion: a broken implementation, alteration of d or f, an incorrect type of d, and a missing assignment of d = f.
Other than that, what errors would you be trying to detect with an assertion here?
Comment: It's worthwhile to note that conversion from `float` to `Decimal`, or `double` to `Decimal` may be lossy *even for values which are precisely representable in both formats*.  For example, converting `16777215f` to `Decimal` yields a value of 16777220, even though the `float` precisely represents the value 16,777,215, and a `Decimal` can also hold that value.
Comment: @supercat: "… in every normal implementation, converting… to a wider precision **of the same radix** has no error…".
Comment: It's true that one cannot not expect every `float` value to be *representable* in `Decimal`, given that they use different radix, and one certainly cannot not expect a conversion to be precise in cases where the destination format has no representation for the value in question.  My intention was not to contradict you, but rather to emphasize that if radixes differ, even values which are precisely representable in old and new formats may convert strangely (perhaps the rounding of 16777215f to 16777220m is documented, but it seems odd to say the least).
Comment: @supercat: If a conversion from `float` to `Decimal` produces a different value than the original `float` even though it is exactly representable in `Decimal`, then the software that performs the conversion is defective.
Comment: My particular example above was defective, since I'd been using a wrong conversion method, and the real problems don't appear until numbers get larger, but what happens is that the conversion from `Double` to `Decimal` assumes that a `double` value like 12345678.900000000372529 (which would be the best representation for values between 12345678.89999999944120646 and 12345678.9000000013038516) is "more likely" to be intended to represent 12345678.9 exactly than 12345678.900000000372529.  The routine is pretty sloppy, though, since it rounds off what should clearly be relevant bits of precision.