Why does $A^TA=I, \det A=1$ mean $A$ is a rotation matrix?

Question: I know
if $A^TA=I$, $A$ is an orthogonal matrix. Orthogonal matrices also contain two different types: if $\det A=1$, $A$ is a rotation matrix; if $\det A=-1$, $A$ is a reflection matrix.
My question is: what is the relationship between the determinant of $A$ and rotation/reflection. Can you explain why $\det A=\pm 1$ means $A$ is a rotation/reflection from the geometric perspective?
EDIT:
I think the following questions need be figured out first.

Do rotation matrices only exist in 2D and 3D space? That is: for any dimensional matrix, as long as it is orthogonal and with determinant as 1, the matrix represents a rotation transformation, right? Note the orthogonality and determinant are applicable to arbitrary dimensional matrices.
What is the most fundamental definition of a rotation transformation?
Since an orthogonal matrix preserves length and angle, can we say an orthogonal matrix represents a "rigid body" transformation? "Rigid body" transformation contains two basic types: rotation and reflection?
Comment: Do you mean in 2x2 matrices, or in general?
Comment: @Michael: thanks, but non-square matrices don't have determinant:) I understand what you mean, of course, we consider square matrices herein.
Comment: @Juan S, I know the rotation/reflection is valid in 2D and 3D. They should also exist in higher dimensional space, right? If yes, I mean nxn matrices.
Comment: If $A^TA=I$ and $A$ is a _square_ matrix, i.e. has equally many rows and columns, _then_ $A$ is an orthogonal matrix.  But there are non-square matrices with orthonormal columns.  If you take away some columns from an orthogonal matrix, the non-square matrix you're left with satisfies $A^TA=I$ but is not an orthogonal matrix.
Answer: Others have raised some good points, and a definite answer really depends what kind of a linear transformation do we want call a rotation or a reflection.
For me a reflection (may be I should call it a simple reflection?) is a reflection with respect to a subspace of codimension 1. So in $\mathbf{R}^n$ you get these by fixing a subspace $H$ of dimension $n-1$. The reflection $s_H$ w.r.t. $H$ keeps the vectors of $H$ fixed (pointwise) and multiplies a vector perpendicular to $H$ by $-1$. If $\vec{n}\perp H$,  $\vec{n}\neq0$, then $s_H$ is given by the formula
$$\vec{x}\mapsto\vec{x}-2\,\frac{\langle \vec{x},\vec{n}\rangle}{\|\vec{n}\|^2}\,\vec{n}.$$
The reflection $s_H$ has eigenvalue $1$ with multiplicity $n-1$ and eigenvalue $-1$ with multiplicity $1$ with respective eigenspaces $H$ and $\mathbf{R}\vec{n}$. Thus its determinant is $-1$. Therefore geometrically it reverses orientation (or handedness, if you prefer that term), and is not a rigid body motion in the sense that in order to apply that transformation to a rigid 3D body, you need to break it into atoms (caveat: I don't know if this is the standard definition of a rigid body motion?). It does preserve lengths and angles between vectors.
Rotations (by which I, too, mean simply an orthogonal transformations with $\det=1$) have more variation. If $A$ is a rotation matrix, then Adam's calculation proving that the lengths are preserved, tells us that the eigenvalues must have absolute value $=1$ (his calculation goes through for a complex vectors and the Hermitian inner product). Therefore the complex eigenvalues are on the unit circle and come in complex conjugate pairs. If $\lambda=e^{i\varphi}$ is a non-real eigenvalue, and $\vec{v}$ is a corresponding eigenvector (in $\mathbf{C}^n$), then the vector $\vec{v}^*$ gotten by componentwise complex conjugation is an eigenvector of $A$ belonging to eigenvalue $\lambda^*=e^{-i\varphi}$.
Consider the set $V_1$ of vectors of the form $z\vec{v}+z^*\vec{v}^*$. By the eigenvalue property this set is stable under $A$:
$$A(z\vec{v}+z^*\vec{v}^*)=(\lambda z)\vec{v}+(\lambda z)^*\vec{v}^*.$$ Its components are also stable under complex conjugation, so $V_1\subseteq\mathbf{R}^n$. It is obviously a 2-dimensional subspace, IOW a plane. It is easy to guess and not difficult to prove that the restriction of the transformation $A$ onto the subspace $V_1$ is a rotation by the angle $\varphi_1=\pm\varphi$. Note that we cannot determine the sign of the rotation (clockwise/ccw), because we don't have a preferred handedness on the subspace $V$.
The preservation of angles (see Adam's answer) shows that $A$ then maps the $n-2$ dimensional subspace $V^\perp$ also to itself. Furthermore, the determinant of $A$ restricted to $V_1$ is equal to one, so the same holds for $V_1^\perp$. Thus we can apply induction and keep on splitting off 2-dimensional summands $V_i,i=2,3\ldots,$ such that on each summand $A$ acts as a rotation by some angle $\varphi_i$ (usually distinct from the preceding ones). We can keep doing this until only real eigenvalues remain, and end with the situation:
$$
\mathbf{R}^n=V_1\oplus V_2\oplus\cdots V_m \oplus U,
$$
where the 2D-subspaces $V_i$ are orthogonal to each other, $A$ rotates a vector in $V_i$ by the angle $\varphi_i$, and $A$ restricted to $U$ has only real eigenvalues.
Counting the determinant will then show that the multiplicity of $-1$ as an eigenvalue of $A$ restricted to $U$ will always be even. As a consequence of that we can also split that eigenspace into sums of 2-dimensional planes, where $A$ acts as rotation by 180 degrees (or multiplication by $-1$). After that there remains the eigenspace belonging to eigenvalue $+1$. The multiplicity of that eigenvalue is congruent to $n$ modulo $2$, so if $n$ is odd, then $\lambda=+1$ will necessarily be an eigenvalue. This is the ultimate reason, why a rotation in 3D-space must have an axis = eigenspace belonging to eigenvalue $+1$.
From this we see:

As Henning pointed out, we can continuously bring any rotation back to the identity mapping simply by continuously scaling all the rotation angles $\varphi_i,i=1,\ldots,m$ continuously to zero. The same can be done on those summands of $U$, where $A$ acts as rotation by 180 degrees.
If we want to define rotation in such a way that the set of rotations contains the elementary rotations described by Henning, and also insist that the set of rotations is closed under composition, then the set must consist of all orthogonal transformations with $\det=1$. As a corollary to this rotations preserve handedness. This point is moot, if we defined a rotation by simply requiring the matrix $A$ to be orthogonal and have $\det=1$, but it does show the equivalence of two alternative definitions.
If $A$ is an orthogonal matrix with $\det=-1$, then composing $A$ with a reflection w.r.t. to any subspace $H$ of codimension one gives a rotation in the sense of this (admittedly semi-private) definition of a rotation.

This is not a full answer in the sense that I can't give you an 'authoritative' definition of an $n$D-rotation. That is to some extent a matter of taste, and some might want to only include the simple rotations from Henning's answer that only "move" points of a 2D-subspace and keep its orthogonal complement pointwise fixed. Hopefully I managed to paint a coherent picture, though.
Comment: I'm thinking any "rotation matrix" ought to be decomposable as a product of modified identity matrices with cosines and sines in all the proper places... and orthogonal matrices with negative determinant could be reflections or improper rotations...
Comment: @J.M. Thanks for the edits. My only excuse is the lateness of the hour. Some people (numerists and engineers) use [Givens rotations](http://en.wikipedia.org/wiki/Givens_rotation) as  building blocks. I would like to include all transformations that rotate **any** 2D-subspace and keep its orthogonal complement pointwise fixed to the collection of elementary rotations. A Givens rotation would insist the 2D-subspace to be spanned by any two vectors of the standard basis. If we allow arbitrary compositions of such transformations the end result is the same.
Comment: @J.M.isapoormathematician: Group of Isometries is generated by reflections so you can definitely express them as combinations of reflections.
Answer: This depends on how we want to define "rotation" in the first place. Some people prefer a narrow definition where the only things that qualify as "rotations" are things that can be expressed as a $(2+n)\times(2+n)$ block matrix
$$\pmatrix{\pmatrix{\cos\theta&\sin\theta\\-\sin\theta&\cos\theta}&0\\0&I}$$ with respect to some orthogonal basis. Under this definition there are $4\times 4$ matrices that are orthogonal and have determinant 1 but are not rotations - for example,
$$\pmatrix{0.6&0.8&0&0\\-0.8&0.6&0&0\\0&0&0&1\\0&0&-1&0}$$
But one might also say that a "rotation" is any matrix $A$ such that there is a continuous family of matrices $(A_t)_{0\le t\le 1}$ such that $A_0=I$, $A_1=A$ and $A_t$ is always orthogonal. This captures the idea of a gradual isometric transformation away from a starting point. Such a definition immediately tells us that the determinant of a rotation must be 1 (because the determinant is continuous), but it is harder to see that we get all orthogonal matrices with determinant 1 this way.
I don't have a quick proof of the latter, but I imagine that it can be done fairly elementarily by induction on the dimension, first a series of rotations to make the first column fit, then sort out the remaining columns recursively working within the orthogonal complement of the first column.
Comment: One might also say that "rotations" are exponentials (in the Lie group sense) of members of the Lie algebra $so_n$ (which in this case can be identified as the skew-symmetric matrices).  The member of the Lie algebra represents an "infinitesimal rotation" which generates a one-parameter group containing the given transformation.  You can use the Spectral Theorem to show that every member of $SO_n$ can be obtained in this way.
Comment: @Shiyu, Henning: I think it can be intuitive if one thinks of $\exp\Omega$ as $\lim\limits_{n\to\infty}(I+\frac1n\Omega)^n$. Basically, $I+\frac1n\Omega$ is a small transformation that moves each vector a little bit in a direction orthogonal to itself, so that (to first order) the vector's length is preserved. Then $\exp\Omega = \lim\limits_{n\to\infty}(I+\frac1n\Omega)^n$ means do a lot of these little length-preserving transformations one after another — so the net transformation is also length-preserving, and you end up with a rotation.
Comment: thanks. But I don't understand your 4 by 4 matrix example. The 'rotation' is not defined only in 2D and 3D space, right? Of course, the geometric meaning of a rotation in higher dimensional space is not intuitive. But any orthogonal matrix with determinant as 1 in arbitrary dimensional space can be called a rotation matrix, right?
Comment: @Henning: admittedly it wasn't quite as trivial as I remembered.
Comment: @Robert Israel: Interesting! I'm not familiar with Lie algebra. But I do know that any rotation matrix can be expressed as an exponential of a skew-symmetric matrix. This actually is the axis-angle representation of a rotation. It may also known as "Rodrigues' rotation formula". If from this perspective, given a rotation matrix $R$, it can be written as $R=\mathrm{exp}(\Omega)$ with $\Omega$ as an skew-symmetric matrix. Then substituting $R=\mathrm{exp}(\Omega)$ into $\det R=\mathrm{exp}(\mathrm{tr}\ln R)$ gives $\det R=1$.
Comment: @Robert Israel: but one question is why rotation is an exponential? Or why an exponential represent a rotation transformation?
Comment: @Shiyu, I think you'd need some familiarity with Lie groups and Lie algebras in order to appreciate the exponential characterization. It is in fact rather related to my "gradual isometric transformation" proposal (and shows that the gradual rotation can alwyas be much more uniform than my definition in itself demands), but I don't think it is very intuitive as a _definition_, unless one has already connected it to one of the other characterizations.
Comment: @Henning: the statement you want is a fairly straightforward corollary of the spectral theorem.
Comment: @Qiaochu, is there a real version of the spectral theorem that applies here? The ones I know are complex, and if we accept complex intermediates, I don't think we get to exclude endpoints with determinant $-1$ easily.
Comment: @Henning: I'm not sure what you mean by "endpoints with determinant $-1$." I see that Robert Israel gave the same comment above; the spectral theorem shows pretty straightforwardly that any element of $\text{SO}_n$ is a direct sum of 2D rotation matrices (pair the $-1$ eigenvalues) and an identity matrix, and writing down the infinitesimal generator from here is also straightforward.
Comment: @Qiaochu, again, that must be a different spectral theorem from the variants I know (which all give me a possibly _complex_ basis change to diagonalize a matrix). Which is not to say that there can't be an applicable variant I _don't_ know, but just repeatedly pointing to "the" spectral theorem does not enlighten me, I'm afraid.
Comment: @Henning: if $T$ is an orthogonal linear operator on a real inner product space $V$, then the spectral theorem equips $V \otimes \mathbb{C}$ with an orthonormal basis with respect to which $T$ is diagonal. On $V \otimes \mathbb{C}$ one can take complex conjugates, and the complex conjugate of an eigenvector is still an eigenvector, so given any eigenvector $v$ one can consider the action of $T$ on $\text{span}(v, \bar{v})$ in the basis $v + \bar{v}, \frac{v - \bar{v}}{i}$, which is a 2D rotation matrix.
Comment: @Qiaochu, ingenious. I see it now, but apparently it didn't meet my personal threshold for straightforwardness.
Answer: The reason why it is called a rotation matrix is because lengths and angles are preserved.
Consider any $v \in \mathbb{R}^n$.  Now consider the $\ell_2$ norm of $Av$:
$$
\|Av\|_2^2=v'A'Av = v'Iv=\|v\|_2^2.
$$
Hence, the Euclidean length is invariant under an orthonormal linear transformation $A$.  Furthermore, for any $u, v \in \mathbb{R}^n,$ we have the following equivalence in the inner products:
$$
\langle Au, Av \rangle_2 = u' A'A v = u'Iv = u'v = \langle u, v \rangle_2.
$$
Note that since the range of cosine is $[-1,1]$, we may simply define the cosine of two vectors in a Euclidean space to be the normalized inner product as:
$$
\cos \phi := \frac{\langle u, v \rangle_2}{\|u\|_2 \|v\|_2}
$$
Given this definition and the preceding, it's easy to see that angles are preserved as well.
(Added clarification for difference between rotation and reflection in the comments).
Comment: That's not why it's a rotation: it's also true for reflections.
Comment: @Adam: thanks. However, if the length and angle are preserved, then the matrix is called a rotation matrix?
Comment: @Adam: can we interpret it in the following way? Because the length and angle are preserved, the orthogonal transformation is a rigid body transformation, which only contains rotation and reflection transformation? So an orthogonal matrix is either a rotation or reflection transformation?
Comment: @Robert: I didn't really pay attention to the "reflection" bit above because the only difference between the two is -1. Take any rotation matrix and multiply by -1: voila, you have a reflection matrix.
They're essentially the same thing but for the latter the direction of the vectors is flipped.  In particular, for any vector v parallel to the rotation axis (under rotation matrix A) we have Av = v, whereas for any vector v parallel to the reflection axis (under reflection matrix B = -A) we have Bv = -v (for either case notice that the angle between the vector and its transformation is 0).
Comment: @Shiyu: Sure, you can view them as rigid body transformations, but just consider the directionality change I mentioned above for the reflection case.  Note that both are isometries: distances between any two points are preserved (hence rotation/reflection -- nothing is being "stretched" or "shrunk").
Comment: @Adam, that's not the way it goes. For example in 2 dimensions: if you multiply the matrix representing rotation by angle $\phi$ with $-1$, you end up with another rotation matrix. This time by angle $\pi+\phi$.
Comment: @Adam: In any even dimension, $\det(-A)=\det(A)$. In any odd dimension, $\det(-A)=-\det(A)$. This is why an anti-symmetric matrix in an odd dimension must have determinant $0$.
Answer: I think John Stillwell's book Naive Lie Theory pretty much summarises the required points in this case.
He starts off by stating that it follows from the Cartan-Dieudonne theorem that a rotation about $O$ in $\mathbb{R^2}$ or $\mathbb{R^3}$ is a linear transformation that preserves length and orientation. He then goes on to justify that a transformation preserves length iff it preserves the inner product. By defining the rotation criterion in $\mathbb{R^n}$ as you have stated, it is shown that $AA^T=I\iff A$ preserves the inner product for a square matrix $A$ of order $n$. The two solutions $\det(A)=1$ and $\det(A)=-1$ occur accordingly as $A$ preserves orientation or not.
Answer: A perfect answer for your question can be found in the freely available paper: "A Disorienting Look at Euler's Theorem on the Axis of a Rotation" By Bob Palais, Richard Palais, and Stephen Rodi.
In the paper, a linear algebra proof is discussed, that specifically deals with the relation between reflection, proper rotation, and the sign of the determinant. The proof is constructive in the sense that explicitly tackles the issue of invariant vectors compared to vectors that get reversed.
As bonuses, Euler's E478 proof is recast into modern notation. A Topological proof is mentioned, as well as a Differential Geometry Lie Theory one.
Answer: Two reflections through a point $R_1R_2$ make a rotation $S$:
$$R_1R_2 = S$$
and $$det(AB) = det(A)*det(B) = ±1$$
Answer: You could just write out the components to confirm that this is so -- a much more interesting way to understand things, however, is to write down the condition as:
$$A^TIA=I$$
The idea is that the matrix $A$ preserves the identity quadratic form -- note that $I$ is a quadratic form here and not a linear transformation, as this is the transformation law for quadratic forms ($A^TMA$ instead of $A^{-1}MA$).
The hyperconic section corresponding to the identity quadratic form is the unit sphere -- thus the orthogonal transformations are all those that preserve the unit sphere. Another way of putting this is that $(Ax)^TI(Ay)=x^TA^TIAy=x^TIy$, i.e. the Euclidean dot product $I$ is preserved by $A$. This is equivalent to preserving the unit sphere, because the unit sphere is determined by the dot product on the given space.
What sort of transformations preserve the unit sphere?

The reason this is a good way of understanding things is that there are plenty of other "dot products" you can define. One elementary one from physics is the Minkowski dot product in special relativity, $\mathrm{diag}(-1,1,1,1)$ -- the corresponding quadric surface is a hyperboloid, and the transformations that preserve it, forming the Lorentz group, are boosts (skews between time and a spatial dimension), spatial rotations and reflections.

As for discriminating between rotations and reflections, suppose we define rotations in a completely geometric way -- for a matrix to be a rotation, all its eigenvalues are either 1 or in pairs of unit complex conjugates.
What do the eigenvalues of orthogonal matrices look like? For each eigenvalue, you need $\overline{\lambda}\lambda=1$, i.e. all the eigenvalues are unit complex numbers. If a complex eigenvalue isn't paired with a corresponding conjugate, you will not get a real-valued transformation on $\mathbb{R}^n$. Meanwhile if an eigenvalue of -1 isn't paired with another -1 -- i.e. if there are an odd number of reflections -- you get a reflection. The orthogonal (or rather unitary) transformations that do not behave this way are precisely the rotations.
The similarity between unpaired unit complex eigenvalues and unpaired -1's is interesting, by the way -- when thinking about reflections, you might have gotten the idea that reflections are $\pi$-angle rotations in a higher-dimensional space -- like the vector was rotated through a higher-dimensional space and then landed on its reflection -- like it was a discrete snapshot of a process as smooth as any rotation.
Well, now you know what this higher-dimensional space is -- precisely $\mathbb{C}^n$. And the determinant of a unitary matrix also takes a continuous spectrum -- the entire unit circle. In this sense (among other senses) complex linear algebra is more "complete" than real linear algebra.


Add author to a newly created node

Question: When users sign up, I create a new node and add that user into one of the entity reference fields through rules.
What I built so far is the following.

After saving a new user event
Create a new content item action (Parameters: type: advisor_student_matching_program, title: title comes here)
Set a data value (Parameters: data: node_created.field_university_student, value: @user.current_user_context:current_user)
Save entity (Parameters: entity: node_created, immediate: 1)

Everything works fine except for the third step.
uuid: 692696f4-4c6d-45cc-8a5b-3b69f1925bd0
langcode: en
status: true
dependencies: {  }
id: register_university_student
label: 'Register University Student'
events:
  -
    event_name: 'rules_entity_insert:user'
description: ''
tags: {  }
config_version: '3'
expression:
  id: rules_rule
  uuid: 6f4c1ccb-973c-48ec-aed1-637bdb50e301
  weight: 0
  conditions:
    id: rules_and
    uuid: 3f479a19-06b2-4e05-80c2-4cff28650409
    weight: 0
    conditions: {  }
  actions:
    id: rules_action_set
    uuid: abbb62e5-a610-4ab7-8e3a-f96a4570f049
    weight: 0
    actions:
      -
        id: rules_action
        uuid: 3bce44f5-accb-4239-9c1d-377f29debebf
        weight: 0
        context_values:
          type: advisor_student_matching_program
          title: 'title comes here'
        context_mapping: {  }
        context_processors:
          type:
            rules_tokens: {  }
          title:
            rules_tokens: {  }
        provides_mapping: {  }
        action_id: 'rules_entity_create:node'
      -
        id: rules_action
        uuid: eba88823-1ab3-493a-9b62-e22e49a2db4a
        weight: 0
        context_values: {  }
        context_mapping:
          data: node_created.field_university_student
          value: '@user.current_user_context:current_user'
        context_processors: {  }
        provides_mapping: {  }
        action_id: rules_data_set
      -
        id: rules_action
        uuid: 779eadc9-f208-4cfa-b37e-351126c56243
        weight: 0
        context_values:
          immediate: '1'
        context_mapping:
          entity: node_created
        context_processors:
          immediate:
            rules_tokens: {  }
        provides_mapping: {  }
        action_id: rules_entity_save
      -
        id: rules_action
        uuid: 18d0c0d6-d9c6-4fc9-8127-4291fe80081c
        weight: 0
        context_values:
          url: /register-uni-basic-information
        context_mapping: {  }
        context_processors:
          url:
            rules_tokens: {  }
        provides_mapping: {  }
        action_id: rules_page_redirect

Answer: Should have used user, instead of @user.current_user_context:current_user.

Add author to a newly created node


How can i make this matrix example with jagged array in java

Question: I've this codes:
public class matrixExample {
    public static void main(String[] args)   {

        int m[][] = new int[5][5];

        int count = 1;
        for (int i=0; i<m.length; i++)
            for(int j=0; j<i+1; j++)
                m[i][j] = count++;

        for (int i=0; i<m.length; i++)
        {
            for (int j=0; j<m[i].length; j++)
                System.out.print(m[i][j] + "  ");
            System.out.println();
        }
    }
}

And output:

How can I do as in the screenshot below?
Answer: int size = 5;
int[][] m = new int[size][size];
int count = 1;
for (int i = 0; i < size; ++i)
    for (int j = size - i - 1; j < size; ++j)
        m[i][j] = count++;

Answer: You may populate the matrix as suggested in saka1029's answer above and then print it using formatted output:
    for (int i = 0; i < m.length; i++) {
        for (int j = 0; j < m[i].length; j++) {
            System.out.printf(" %2d ", m[i][j]);
        }
        System.out.print('\n');
    }

Or, it is possible to keep "normal" matrix, and change only its output:
public static void main(String []args){
    int m[][] = new int[5][5];

    int count = 1;
    // keeping initial array as is
    for (int i=0; i<m.length; i++)
        for(int j=0; j<i+1; j++)
            m[i][j] = count++;

    for (int i = 0; i < m.length; i++) {
        StringBuilder sb = new StringBuilder();
        for (int j = 0; j < m[i].length; j++) {
            if (m[i][j] > 0) {
                sb.append(String.format(" %2d ", m[i][j]));
            } else {
                sb.insert(0, String.format(" %2d ", m[i][j]));
            }
        }
        System.out.println(sb.toString());
    }
}

Output in both cases is identical:
  0   0   0   0   1
  0   0   0   2   3
  0   0   4   5   6
  0   7   8   9  10
 11  12  13  14  15


PHPSTAN: Laravel 9 mutators producing "Access to undefined property" error

Question: I am trying to store a key into my database and I want it to be encrypted and decrypted.
So I use Laravel 9 mutator: https://laravel.com/docs/9.x/eloquent-mutators
protected function privateKey(): Attribute
{
    return Attribute::make(
        get: fn ($value) => Crypt::decryptString($value),
        set: fn ($value) => Crypt::encryptString($value),
    );
}

and I accessed it to one of my service class:
$provider = Provider::findOrFail($id);
$privateKey = $provider->private_key;

However, phpstan throws error saying:
Access to an undefined property App\Models\Method|Illuminate\Database\Eloquent\Collection<int,
         App\Models\Provider>::$private_key

However, when I tried using the old way of mutating and accessing attributes, it worked:
public function setPrivateKeyAttribute(string $value): void
{
    if (!empty($value)) {
        $this->attributes['private_key'] = Crypt::encryptString($value);
    }
}

public function getPrivateKeyAttribute(string $value): string
{
    return Crypt::decryptString($value);
}

and at this point, I don't have any idea why. is this a bug in the side of phpstan? if not, how can I resolve the issue?
Answer: The answer from Kobayakawa in this post from Laracast helped me to answer this.
You should define the return type and what it allowed to be inserted in the mutator. For your example it should be something like this:
/**
 * @return \Illuminate\Database\Eloquent\Casts\Attribute<Provider, string>
 */
protected function privateKey(): Attribute
{
    return Attribute::make(
        get: fn ($value) => Crypt::decryptString($value),
        set: fn ($value) => Crypt::encryptString($value),
    );
}

In my own example I don't define a 'getter'. But you should still define it, because it will still be returned.
/**
 * @return \Illuminate\Database\Eloquent\Casts\Attribute<Webhook, array>
 */
protected function webhook(): Attribute
{
    return Attribute::make(
        set: fn (array $value) => self::createWebhook($value),
    );
}


Can't access website or restart apache2 server

Question: Error I'm getting when typing in: sudo /etc/init.d/apache2 restart
 * Restarting web server apache2                                                                               [fail]
 * The apache2 configtest failed.
Output of config test was:
apache2: Syntax error on line 204 of /etc/apache2/apache2.conf: Syntax error on line 1 of /etc/apache2/mods-enabled/authz_default.load: Cannot load /usr/lib/apache2/modules/mod_authz_default.so into server: /usr/lib/apache2/modules/mod_authz_default.so: cannot open shared object file: No such file or directory
Action 'configtest' failed.
The Apache error log may have more information.

Also, I installed php version 5.5.9 and now the website won't load at all. Should I downgrade to 5.4 ? and if so how do I go about doing this?
Nothing is working anymore!
apache2.conf
#
# Based upon the NCSA server configuration files originally by Rob McCool.
#
# This is the main Apache server configuration file.  It contains the
# configuration directives that give the server its instructions.
# See http://httpd.apache.org/docs/2.2/ for detailed information about
# the directives.
#
# Do NOT simply read the instructions in here without understanding
# what they do.  They're here only as hints or reminders.  If you are unsure
# consult the online docs. You have been warned.
#
# The configuration directives are grouped into three basic sections:
#  1. Directives that control the operation of the Apache server process as a
#     whole (the 'global environment').
#  2. Directives that define the parameters of the 'main' or 'default' server,
#     which responds to requests that aren't handled by a virtual host.
#     These directives also provide default values for the settings
#     of all virtual hosts.
#  3. Settings for virtual hosts, which allow Web requests to be sent to
#     different IP addresses or hostnames and have them handled by the
#     same Apache server process.
#
# Configuration and logfile names: If the filenames you specify for many
# of the server's control files begin with "/" (or "drive:/" for Win32), the
# server will use that explicit path.  If the filenames do *not* begin
# with "/", the value of ServerRoot is prepended -- so "/var/log/apache2/foo.log"
# with ServerRoot set to "" will be interpreted by the
# server as "//var/log/apache2/foo.log".
#

### Section 1: Global Environment
#
# The directives in this section affect the overall operation of Apache,
# such as the number of concurrent requests it can handle or where it
# can find its configuration files.
#

#
# ServerRoot: The top of the directory tree under which the server's
# configuration, error, and log files are kept.
#
# NOTE!  If you intend to place this on an NFS (or otherwise network)
# mounted filesystem then please read the LockFile documentation (available
# at <URL:http://httpd.apache.org/docs-2.1/mod/mpm_common.html#lockfile>);
# you will save yourself a lot of trouble.
#
# Do NOT add a slash at the end of the directory path.
#
ServerRoot "/etc/apache2"

#
# The accept serialization lock file MUST BE STORED ON A LOCAL DISK.
#
#
#<IfModule !mpm_winnt.c>
#<IfModule !mpm_netware.c>
LockFile /var/lock/apache2/accept.lock
#</IfModule>
#</IfModule>

#
# PidFile: The file in which the server should record its process
# identification number when it starts.
# This needs to be set in /etc/apache2/envvars
#
PidFile ${APACHE_PID_FILE}

#
# Timeout: The number of seconds before receives and sends time out.
#
Timeout 300

#
# KeepAlive: Whether or not to allow persistent connections (more than
# one request per connection). Set to "Off" to deactivate.
#
KeepAlive On

#
# MaxKeepAliveRequests: The maximum number of requests to allow
# during a persistent connection. Set to 0 to allow an unlimited amount.
# We recommend you leave this number high, for maximum performance.
#
MaxKeepAliveRequests 100

#
# KeepAliveTimeout: Number of seconds to wait for the next request from the
# same client on the same connection.
#
KeepAliveTimeout 15

##
## Server-Pool Size Regulation (MPM specific)
##

# prefork MPM
# StartServers: number of server processes to start
# MinSpareServers: minimum number of server processes which are kept spare
# MaxSpareServers: maximum number of server processes which are kept spare
# MaxClients: maximum number of server processes allowed to start
# MaxRequestsPerChild: maximum number of requests a server process serves
<IfModule mpm_prefork_module>
    StartServers          5
    MinSpareServers       5
    MaxSpareServers      10
    MaxClients          150
    MaxRequestsPerChild   0
</IfModule>

# worker MPM
# StartServers: initial number of server processes to start
# MaxClients: maximum number of simultaneous client connections
# MinSpareThreads: minimum number of worker threads which are kept spare
# MaxSpareThreads: maximum number of worker threads which are kept spare
# ThreadsPerChild: constant number of worker threads in each server process
# MaxRequestsPerChild: maximum number of requests a server process serves
<IfModule mpm_worker_module>
    StartServers          2
    MinSpareThreads      25
    MaxSpareThreads      75
    ThreadLimit          64
    ThreadsPerChild      25
    MaxClients          150
    MaxRequestsPerChild   0
</IfModule>

# event MPM
# StartServers: initial number of server processes to start
# MaxClients: maximum number of simultaneous client connections
# MinSpareThreads: minimum number of worker threads which are kept spare
# MaxSpareThreads: maximum number of worker threads which are kept spare
# ThreadsPerChild: constant number of worker threads in each server process
# MaxRequestsPerChild: maximum number of requests a server process serves
<IfModule mpm_event_module>
    StartServers          2
    MaxClients          150
    MinSpareThreads      25
    MaxSpareThreads      75
    ThreadLimit          64
    ThreadsPerChild      25
    MaxRequestsPerChild   0
</IfModule>

# These need to be set in /etc/apache2/envvars
User ${APACHE_RUN_USER}
Group ${APACHE_RUN_GROUP}

#
# AccessFileName: The name of the file to look for in each directory
# for additional configuration directives.  See also the AllowOverride
# directive.
#

AccessFileName .htaccess

#
# The following lines prevent .htaccess and .htpasswd files from being
# viewed by Web clients.
#
<Files ~ "^\.ht">
    Order allow,deny
    Deny from all
    Satisfy all
</Files>

#
# DefaultType is the default MIME type the server will use for a document
# if it cannot otherwise determine one, such as from filename extensions.
# If your server contains mostly text or HTML documents, "text/plain" is
# a good value.  If most of your content is binary, such as applications
# or images, you may want to use "application/octet-stream" instead to
# keep browsers from trying to display binary files as though they are
# text.
#
DefaultType text/plain

#
# HostnameLookups: Log the names of clients or just their IP addresses
# e.g., www.apache.org (on) or 18.104.22.168 (off).
# The default is off because it'd be overall better for the net if people
# had to knowingly turn this feature on, since enabling it means that
# each client request will result in AT LEAST one lookup request to the
# nameserver.
#
HostnameLookups Off

# ErrorLog: The location of the error log file.
# If you do not specify an ErrorLog directive within a <VirtualHost>
# container, error messages relating to that virtual host will be
# logged here.  If you *do* define an error logfile for a <VirtualHost>
# container, that host's errors will be logged there and not here.
#
ErrorLog /var/log/apache2/error.log

#
# LogLevel: Control the number of messages logged to the error_log.
# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
#
LogLevel warn

# Include module configuration:
Include /etc/apache2/mods-enabled/*.load
Include /etc/apache2/mods-enabled/*.conf

# Include all the user configurations:
Include /etc/apache2/httpd.conf

# Include ports listing
Include /etc/apache2/ports.conf

#
# The following directives define some format nicknames for use with
# a CustomLog directive (see below).
# If you are behind a reverse proxy, you might want to change %h into %{X-Forwarded-For}i
#
LogFormat "%v:%p %h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" vhost_combined
LogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %O" common
LogFormat "%{Referer}i -> %U" referer
LogFormat "%{User-agent}i" agent

#
# Define an access log for VirtualHosts that don't define their own logfile
CustomLog /var/log/apache2/other_vhosts_access.log vhost_combined

# Include of directories ignores editors' and dpkg's backup files,
# see README.Debian for details.

# Include generic snippets of statements
Include /etc/apache2/conf.d/

# Include the virtual host configurations:
Include /etc/apache2/sites-enabled/

Comment: Why did you upgrade to 5.5.9? Post your apache config.
Comment: @Mxx it wasn't my intention to do so. How do I copy the contents when using vim to post here ?
Comment: ls -l /usr/lib/apache2/modules/mod_authz_default.so ?
Comment: @Mxx Nevermind, edited my post.
Comment: @c4f4t0r No such file exists.
Comment: but it was there before you php upgrade?
Comment: @c4f4t0r I can't be 100% but it is available on my dev server and not on the production server. Both servers would have been very identical so my assumption would be that it was there before.
Comment: Dumping your entire configuration on us with a "please fix!" post like this is ***incredibly*** poor form. For the future, please put in a modicum of effort (*read your own configuration file, paying special attention to the line the error message is pointing you at*, and if you still can't figure out the problem post the *relevant* section of your configuration file, not the whole bloody thing!) It would be very much appreciated if you would clean up your post...
Comment: @voretaq7 Lol get on with your life. I posted it upon Mxx's request. I'll think about taking your advice in the future.
Answer: If you do not require the mod_authz_default module, disable it and try again.
Possibly the module mod_authz_default is corrupted or incorrectly installed.
# a2dismod mod_authz_default

If you require the mod_authz_default, try to reinstall it.
Answer: It's look like you have the file to load mod_authz_default but not the library itself (the file with the .so extension).
If you don't need this functionality you should go to your /etc/apache2/mods-enabled directory and delete mod_authz_default.load that should be a symlink to a file of the same name in the /etc/apache2/mods-available/ directory.
This will allow your apache server to start, unless you have other configuration files in the same directory trying to load Apache modules which don't exist anymore. Then repeat the same operation for any subsequent errors.
Unfortunately, the start script of Apache cannot tell you at once all errors in the configuration file, it will just report the first one that abort the startup process.


APN settings in Java ME

Question: Since it is not possible to specify the APN for HttpConnection in plain Java ME, are there  vendor specific hacks other than BlackBerry OS URL suffixes?
Comment: are you asking about Blackberry specific hacks? if not, what device are you interested to know about?
Comment: I'm interested any Java ME device that does not come from RIM
Answer: The only way I know is using a suffix:
<code>"http://somenonexistingurl.fake;apn=<myapn>"
</code>
I think it should also work in a J2ME MIDlet running on BB.
As for the other non-bb devices, my guess is no. In J2ME you are not programming to a "phone" but to a "connected limited device" which may not have internet at all.

APN settings in Java ME


How do I run docker agent in Jenkins on RHEL base image?

Question: I have Jenkins running on RHEL 8. I am trying to run my pipeline, but it is not working, and I think it might be an issue with Podman, because I am able to run the pipeline on my machine which uses docker-ce.
I have already configured the jenkins user on /etc/subuid file and rebooted.
Now I am getting another docker related error.
Here is the log:
Checking out Revision 113a2a700837d2de2ed99eabec4ff994b1392a6a (origin/master)
 > git config core.sparsecheckout # timeout=10
 > git checkout -f 113a2a700837d2de2ed99eabec4ff994b1392a6a # timeout=10
Commit message: "Jenkins"
[Pipeline] }
[Pipeline] // stage
[Pipeline] withEnv
[Pipeline] {
[Pipeline] isUnix
[Pipeline] sh

+ docker inspect -f . node:12
.
[Pipeline] withDockerContainer
ERROR: Failed to parse docker version. Please note there is a minimum docker version requirement of v1.7.
Jenkins does not seem to be running inside a container
$ docker run -t -d -u 993:990 -p 3000:3000 -w /var/lib/jenkins/workspace/blade-runner-pipeline -v /var/lib/jenkins/workspace/blade-runner-pipeline:/var/lib/jenkins/workspace/blade-runner-pipeline:rw,z -v /var/lib/jenkins/workspace/blade-runner-pipeline@tmp:/var/lib/jenkins/workspace/blade-runner-pipeline@tmp:rw,z -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** node:12 cat
$ docker top c35bc763bb7bfedffa2a3629ee8e48132d9175df6e43fea207262c13c1372f3f -eo pid,comm

[Pipeline] // withDockerContainer
[Pipeline] }
[Pipeline] // withEnv
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
java.io.IOException: Cannot retrieve .Image from 'docker inspect c35bc763bb7bfedffa2a3629ee8e48132d9175df6e43fea207262c13c1372f3f'
    at org.jenkinsci.plugins.docker.workflow.client.DockerClient.inspectRequiredField(DockerClient.java:225)
    at org.jenkinsci.plugins.docker.workflow.client.DockerClient.getContainerRecord(DockerClient.java:352)
    at org.jenkinsci.plugins.docker.workflow.WithContainerStep$Execution.start(WithContainerStep.java:209)
    at org.jenkinsci.plugins.workflow.cps.DSL.invokeStep(DSL.java:286)
    at org.jenkinsci.plugins.workflow.cps.DSL.invokeMethod(DSL.java:179)
    at org.jenkinsci.plugins.workflow.cps.CpsScript.invokeMethod(CpsScript.java:122)
    at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.call(PogoMetaClassSite.java:48)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)

and my Jenkinsfile
pipeline {
      agent {
        docker {
          image 'node:12'
            args '-p 3000:3000'
        }
      }
      stages {
        stage('Build') {
          steps {
            sh 'yarn install'
            sh 'yarn test'
            sh 'echo " ==== PASSED ===="'
          }
        }
      }
    }

Answer: This is likely a podman related bug, caused by https://github.com/containers/libpod/issues/4193.
Not quite sure, which podman version is fixing this, I guess it's >= 1.6.1.
You may verify this and a possible fix by running
podman inspect -f "{{.Image}}" c35bc763bb7bfedffa2a3629ee8e48132d9175df6e43fea207262c13c1372f3f
on your RHEL machine.


O que significa -rf após rm?

Question: Tenho um comando em SSH na platafoma Magento (instalado em um servidor Apache) para excluir o conteúdo da pasta cache rm -rf path/to/folder/* mas na verdade não sei bem ao certo o que -rf significa.
Comment: @Machado o executável ssh do linux é o cliente do protocolo SSH, assim como sshd é o executável do servidor de SSH. E o comando rm não é um "comando do SSH". Localmente você executa o rm da mesma forma. Sem precisar de SSH. E o Magento não guarda relação com nenhuma destas coisas.
Comment: Só para esclarecer o conceito: o comando `rm` é do shell remoto, assim como o `ssh` é um comando do seu shell local.
Comment: `ssh` no caso seria só o protocolo, não?
Comment: O Magento é só a plataforma onde o script está localizado. Em poucas palavras estou usando eventos registrados na Cron do CPanel para ler um arquivo com um conjunto destes comandos para _limpar_ a pasta **cache** do Magento. Se puder então me corrigir quanto ao meu entendimento, agradeço.
Comment: não esquecer o velho manual: `man rm`
Answer: -r modo recursivo, ou seja, remove a pasta e subpastas e
-f remove de modo forçado, sem perguntar ao usuário
Esse comando deve ser usado com cuidado, pode danificar todo o sistema.
Answer: Com um pouco mais de pesquisa encontrei o seguinte:
rm remove / delete:

-r recursivo (recursively): recursivamente deleta todos os diretórios/arquivos que correspondam.
-f forçar (force): força a exclusão sem considerar confirmação.

src: http://dustyreagan.com/how-to-delete-an-entire-directory-via-ssh/
Comment: Oi Machado. Eu restaurei sua resposta porque ela acrescenta conteúdo, e a edição que você fez na outra foi radical demais, e por isso acabou rejeitada pela comunidade. Achei melhor não perder as informações adicionais que você colocou. Não tem problema ter mais de uma resposta na pergunta; na verdade, isso é desejável.
Comment: Obrigado pela explicação, usuários assim são os que fazem novatos como eu quererem se aprofundar na comunidade.

O que significa -rf após rm?


What are the differences between "Mixed Effects Modelling" and "Latent Growth Modelling"?

Question: I'm decently familiar with mixed effects models (MEM), but a colleague recently asked me how it compares to latent growth models (LGM). I did a bit of googling, and it seems that LGM is a variant of structural equation modelling that is applied to circumstances where repeated measures are obtained within each level of at least one random effect, thus making Time a fixed effect in the model. Otherwise, MEM and LGM seem pretty similar (eg. they both permit exploration of different covariance structures, etc).
Am I correct that LGM is conceptually a special case of MEM, or are there differences between the two approaches with respect to their assumptions or capacity to evaluate different types of theories?
Comment: Terms random effects, fixed effects, latent growth might mean different things in different contexts. Concerning the second one Andrew Gelman had a blog post with examples of several definitions. So it would be great if you provided the links to the definitions of these models. In general I think you are right in your assumption. Time trends are usually treated separately, since the usual assumption that variance of the regressors is bounded does not hold, so you have to show that for time trend this does not actually change anything in terms of model estimation and interpretation.
Answer: LGM can be translated to a MEM and vice versa, so these models are actually the same. I discuss the comparison in the chapter on LGM in my multilevel book, the draft of that chapter is on my homepage at http://www.joophox.net/papers/chap14.pdf
Comment: Thank you for your reply and welcome to our site!  (For the reasons why I removed the closing remarks in your reply, please visit our [FAQ](http://stats.stackexchange.com/faq).)
Answer: Here is what I found when looking into this topic.  I'm not a stats person so I tried to summarise how I understood it using relatively basic concepts :-)
These two frameworks treat "time" differently:

MEM requires nested data structures (e.g. students nested within classrooms) and time is treated as an independent variable at the lowest level, and the individual on the second level
LGM adopts a latent variable approach and incorporate time via factor loadings (this answer elaborates more on how such factor loadings, or "time scores", work).

This difference leads to different strengths of both frameworks in handling certain data.  For example, in MEM framework, it is easy to add more levels (e.g. students nested in classrooms nested in schools), whilst in LGM, it is possible to model measurement error, as well as embed it in a larger path model by combining several growth curves, or by using growth factors as predictors for outcome variables.
However, recent developments have blurred differences between these frameworks, and they were termed by some researchers as the "unequal twin".  Essentially, MEM is a univariate approach, with time points treated as observations of the same variable, whereas LGM a multivariate approach, with each time point treated as a separate variable.  The mean and covariance structure of the latent variables in LGM correspond to the fixed and random effects in MEM, making it possible to specify the same model using either framework with identical results.
So rather than considering LGM as a special case of MEM, I see it as a special case of factor analysis model with factor loadings fixed in such a way, that the interpretation of the latent (growth) factors is possible.


What happens when rain interrupts an ODI game in second innings before 20 overs and the chasing team is well ahead of D/L par score?

Question: In ODI cricket, minimum 20 overs to be bowled to use Duckworth–Lewis rule. But my question is even if chasing team scored the D/L 20 over par score target in just 10 or 15 overs, will it be mandatory to bat full 20 overs?
Example:
If team A batting first, scored 150 runs in 30 overs & all out (150/10 - 30 overs)
Target is 151 in 50 overs.
Team B batting second, scores 120 runs in 12 overs & lost 2 wickets. (120/2 - 12 overs)
Rain interrupts now. As per D/L method, revised D/L target would be 80 runs in 20 overs.
But play couldn't resume as rain continues till the end. But team B is well ahead of D/L par score. but didn't complete the 20 overs. Now what will be the result?
Will team B be declared the winner or the match is abandoned due to rain?
Answer: My reading of the ICC regulations indicates that the above scenario would be a no-result.
The regulations are available here.
The relevant sections are:
Section 12.4.2.B.iii states that a minimum of 20 overs in the second innings is required, subject to a result not being achieved earlier. In the example above, a result isn't achieved, as when the rain came they were chasing 151.
Section 27.7.2 says that a minimum of 20 overs is required in the second innings before applying the D/L par score. Hence, the D/L score above is irrelevant, and the match is declared a no-result
Answer: In the given scenario, if the rain interrupts the game after 12 overs of the second innings and the play can't resume (i.e. not possible) after that, the game will be declared as "no result" sadly.
To get result of the match by D/L method, the target must be set by D/L method. To set the target by D/L method, all the conditions (e.g. no rain, fit ground etc) must allow to play the match further. If that happens (the conditions allows to resume the play) the target will be set by D/L. But still the team batting second do not win the match! They have to play at least one delivery to win the match.
In the match between New Zealand and England in World Cup 2015, someone asked if the rain interrupts the match (when NZ needed just 12 off 41 overs and the dinner break was taken) and no further play is possible will NZ win the match. In the reply they said:

that happens only when the ground is deemed fit to play and a target
  has been set for 20 overs. If there were to be rain now, and the
  ground were not deemed to be fit to play, there would be no target in
  20 overs (which I am sure New Zealand have crossed because they are
  just one down), and there would be no result.


How to color a field in tree view with today as filter

Question: I am  new to openERP.  I am working on changing the color in tree view for those record whose due_date is less then Today.  Those record should be in red color.
I am not able to get the current date as filter in tree view.
xml what I need but not working:
<tree colors="blue:Due_date < Today()" string="Invoice">
                    <field name="Due_date" />
                    <field name="date_invoice"/>
                    <field name="state"/>
                </tree>

Working code
<tree colors="blue:state == 'open'" string="Invoice">
                    <field name="partner_id" groups="base.group_user"/>
                    <field name="date_invoice"/>
                    <field name="state"/>
                </tree>

I tried with
context_today()

and
datetime.datetime.now()

Nothing work.
Please help me on this.
Answer: In .xml side <, >, <=, >= is not supported. So we need to use <, >, <= and >=
This will work, try this,
<tree colors="blue:due_date < current_date;" string="Invoice">
    <field name="Due_date" />
    <field name="date_invoice"/>
    <field name="state"/>
</tree>

Comment: Great.  Its working. However, it is coloring for the lines which are did not have 'Due_date'.  Any suggestion for me to skip those data without date.  Thanks in advance.
Comment: Thanks, it's work than you may accept answer and also upvote for it. You can also use `&gt.` And for skip data without date, use filter. That will shows only data which has due date. Thanks
Comment: how to add current_date +days ?? for exemple 1 day
Comment: @Caludio You can add new function field in object which value must be store in database. Afterwards, you may try it on condition view side.
Comment: how to do that ? have you an example please !
Answer: This will work, try this:
<tree colors="red:due_date < datetime.datetime.combine(context_today(), datetime.time(23,59,59));" string="Invoice"></tree>


Como faço uma Alert message UIAlertController

Question: Boas,
Como faço um alert? do jeito que fiz parece estar tudo correcto excepto pelo erro da função.
alguma ajuda, desde ja agradeço.
Answer: No Swift 3, o método presentViewController(_:animated:completion:) foi substituído por present(_:animated:completion:)
<code>self.present(myAlert, animated: true, completion: nil)
</code>
Comment: Boas, Rafael essa ja foi, obrigado
Answer: O erro original era que você havia chamado "presentedViewController", que é uma propriedade, em vez de "presentViewController()" que é um método. Foram duas letrinhas, é fácil confundir :-)


8 - How to Get Values From $variables hook_preprocess_commerce_order_receipt?

Question: So thankful for all the help on here, but still so baffled as to how Im not able to just quickly determine how to pull these values out of certain arrays and objects.
Trying to get the order id (and other values) from the frickin $variables array in hook_preprocess_hook
Code
afc.theme
function afc_preprocess_commerce_order_receipt(&$variables) {
  dpm($variables['order_entity']);
  \Drupal::logger('afc_theme')->notice('running');
}

Some of the Output
stdClass Object
(
    [__CLASS__] => Drupal\commerce_order\Entity\Order
    [values:protected] => Array
        (
            [order_id] => Array
                (
                    [x-default] => 182
                )

            [type] => Array
                (
                    [x-default] => default
                )

            [uuid] => Array
                (
                    [x-default] => c8b1c210-0e6e-4efb-a59d-84b28d4dadfe
                )

            [order_number] => Array
                (
                    [x-default] =>
                )

            [store_id] => Array
                (
                    [x-default] => 1
                )

            [uid] => Array
                (
                    [x-default] => Array
                        (
                            [0] => Array
                                (
                                    [target_id] => 1
                                )

                        )

                )

Ive tried various wrong things like:
$variables['order_entity'] = $order;
dpm($order->get("order_id")->getValue());
dpm($variables->get("order_id")->getValue());
dpm($variables['order_entity']['order_id'];

1. How do I get the order_id from this $variables object?
2. How/where did you find this information telling you how to get this value out?
Answer:
How do I get the order_id from this $variables object?

All entities have an id method, inherited (or perhaps overridden) from Entity::id. From your debug output $variables['order_entity'] appears to be one such entity, so:
$order_id = $variables['order_entity']->id();

How/where did you find this information telling you how to get this value out?

Short answer, in the source and the docs (following/finding isn't always straightforward though). For example if you've read the Introduction to Entity API in Drupal 8, you'll intuitively know that a Drupal\commerce_order\Entity\Order is an entity type, both by the folder structure and its annotation, and you can start thinking about how to address an object of that type in more generic terms.
That leads to searches like "Drupal 8 get entity id" or "Drupal 8 get entity field value programatically", and Google will dutifully tell you everything you need to know.
If you can spare a bit of time to follow the class hierarchy up the chain, and get at least a broad idea of what each class does and how it works, that will probably take some pain out of future encounters with the entity API too.


$\lim_{x\to\ \frac{\pi}{2}^-}\frac{1}{x-\frac{\pi}{2}}+\tan{x} $

Question: $$\lim_{x\to\ \frac{\pi}{2}^-}\frac{1}{x-\frac{\pi}{2}}+\tan x $$
Can anyone give me a hint I'm struggle.
Edit maybe I should say what I've done:
I used the following change of variable: $t=x-\frac{\pi}{2}$ so I got:
$$\lim_{t\to\ 0^-}\frac{1}{t}+\tan \left(t+\frac{\pi}{2}\right)$$
$$\lim_{t\to\ 0^-} \frac{1+t\tan\left(t+\frac{\pi}{2}\right)}{t} $$
I used B.H and I got something like $\frac{1}{0}$ so it's undefined...
Comment: Well, I got $1/y-\cot y$.
Comment: Write $x-\pi/2=y$ maybe?
Comment: Yup I already try this change of variable but after I get somethink like $\frac{1+y\tan{y+\frac{\pi}{2}}}{y}}$ Which is not easy to evaluate... I got $\frac{1}{0}$
Comment: Oh yeah right $\tan{x-\frac{pi}{2}} = -\cot{x}$ Thanks !!
Comment: How about this: $$\begin{align}
& \lim_{x\,\downarrow\,\pi/2} \left(\frac{1}{x-\frac{\pi}{2}}+\tan x\right) = \lim_{t\,\downarrow\,0} \left( \frac 1 t + \frac 1{\cot(t+\frac\pi2)} \right) \\ \\
= {} & \lim_{t\,\downarrow\,0} \left( \frac 1 t + \frac 1 {-t+\text{higher-degree trems}} \right) \\ \\
= {} & \lim_{t\,\downarrow\,0} \left( \frac {\cot(t+\frac\pi2) + t} {t\cot(t+\frac\pi2)} \right)
\end{align} $$ Then see if L'Hopital's rule is applicable.
Answer: As you've already found, the limit is $\lim_{y\to 0^+}(\cot y -\frac{1}{y})$. For small $y$, $\cot y=\frac{\cos y}{\sin y}\approx\frac{1}{y}\frac{1-y^2/2}{1-y^2/6}\approx\frac{1}{y}(1-y^2/3)$ so $\cot y -\frac{1}{y}\approx-\frac{y}{3}$. The limit is therefore $0$.
Answer:
Thanks for the trigonometric identity: $\tan({x+\frac{\pi}{2})} = -\cot{x}$
Comment: The way how you wrote the trigonometric identity in your last line is incorrect. I needs brackets on the left hand side (edited)
Answer: Usually when it comes to L'Hospital's Rule, it is easier to take derivatives of sines and cosines, instead of tangents and cotangents, particularly when they are in fractions, like here. So if you write in your given limit $tanx=\frac{sinx}{cosx}$, and adding fractions together, you get $\lim_{x\to\ \frac{\pi}{2}^-}\frac{cosx+(x-\pi/2)sinx}{(x-\pi/2)cosx} $.
This is a zero over zero situation for which the Rule can be applied. While taking individual derivatives is easy, be ready to apply the Rule successively.(Patience!). Ultimately you will find the answer. NOTE The substitution as suggested by Lord.....is a better approach.


Examining the injectivity and surjectivity of $f(x) = x/(x^2+1)$

Question: I'm beginning with my self study in math from the $11$th grade, so bear with the simplicity.
I've got to test the objectivity of $x/(x^2+1)$, function is from $\Bbb R$ to $\Bbb R$.
First issue is, I think it is injective, because my algebra after equating the output of two inputs leads to both inputs coming equal to each other. The book answer says I'm wrong (without explanation).
With surjectivity, I can't find a simple expression for the inverse of the function, so I thought of this:
Let $g(x) = x, t(x) = x^2+1$
Then $f(x) = [g(x)/t(x)]$. Now $g(x)$ is surjective and $t(x)$ isn't. Can I argue that the ratio however, will be surjective because the numerator is surjective, and thus even if it is being divided only by numbers greater than or equal to $1$, the numerator's surjectivity will make the whole function surjective?
If I can, is there a rigorous way of arguing this? If I can't, a counterexample or counter-proof would help.
Comment: Unfortunately, the function is not surjective. It's not injective either. Have a look at the plot on [Wolfram Alpha](https://www.wolframalpha.com/input/?i=plot+x%2F%28x%5E2%2B1%29). Note that it comes to a maximum (of $0.5$) so it is not surjective, and it fails the horizontal line test, so it's not injective.
Answer: Another way, taking some shortcuts:

$\displaystyle f(x) = \frac{1}{x+\frac{1}{x}}\,$ for $\,x \ne 0\,$, so $\,f(x)=f\left(\frac{1}{x}\right)\,$, and therefore $\,f\,$ cannot be injective;

$\displaystyle |f(x)| = \frac{1}{|x|+\frac{1}{|x|}} \le \frac{1}{2}\,$ for $\,x \ne 0\,$, where the inequality follows from $\,|x|+\frac{1}{|x|} \ge 2\,$ by the AM-GM inequality, and therefore $\,f\,$ cannot be surjective.
Comment: Probably a bit much for a newbie to see off the bat, but I **love** the elegance and simplicity of these!
Comment: @EeveeTrainer Thanks. Yours is the more comprehensive answer, but it still helps to be aware of alternatives.  It's also a matter of context and "framing" the question. It *does* happen that a question of "*is $f$ is surjective*" may "lock" into a different mindset than "*find the maximum of $\,x /(x^2+1)$ over $\mathbb R^+$*".
Answer: In this case, I think there is a simpler way to check injectivity/surjectivity. Let $f(x)=c$. Surjective means that for any $c$ there is a solution. Injective means that for any solution, the solution is unique. $$\frac x{x^2+1}=c\\cx^2-x+c=0$$
This is a simple quadratic equation if $c\ne 0$. Then you have a real solution if the discriminant is positive. $$\Delta=1-4c^2$$
If the discriminant is negative you have no solution. In this case it means $|c|>\frac12$. So the function is not surjective. Also if $|c|<\frac12$ and $c\ne 0$ the quadratic has two distinct solution, so the function is not injective either.
Answer: For injectivity, note that you can "test" this graphically. Look at the graph: if any horizontal line crosses the graph twice or more, then it is not injective.
Here our graph is this:

To debunk it, you can simply use that, if $x,y$ are distinct yet $f(x),f(y)$ are equal, then it is not injective. Pick a point (e.g. $1/2$ or $1/4$) and find $f$ of that point. For instance,
$$f \left( \frac 1 2 \right) = \frac 2 5$$
The graph suggests there is another point $x$ with that value. Question is, what? We can solve for it by simply solving $f(x) = 1/4$; we can get the other value this way (you would get two solutions here), and you can ensure it is not some sort of extraneous solution by finding $f(x)$ after finding $x$.
You can also use a more analytical argument. Notice the following:

$f'(x) > 0$ on $(-1,1)$
It is negative elsewhere
$f$ achieves global extreme values of $\pm 1/2$
$\displaystyle \lim_{x \to \pm \infty} f(x) = 0$
Hence, $f$ maps both $(-1/2,1/2) \setminus \{0\}$ and $(-\infty,-1/2)\cup(1/2,\infty)$ onto (-1/2,1/2) \setminus {0}$, clearly violating injectivity

I'll leave justifying those arguments up to you.

As for surjectivity, the graph makes that quite obvious. You can argue against it a few ways:

As before, we can find the global extrema. Then by continuity and the intermediate value theorem, we can't achieve values outside that interval.

Suppose we want to argue nonsurjectivity from a more basic perspective. Suppose otherwise; then there is a $x$ such that $f(x) = 2$. Try solving
$$\frac{x}{x^2+1} = 2$$
to find applicable values of $x$. An issue will arise. (The discriminant in the resulting quadratic will be negative, so such an $x$ cannot be a real number.)

With surjectivity, I can't find a simple expression for the inverse of the function, so I thought of this:
Let $g(x) = x, t(x) = x^2+1$
Then $f(x) = [g(x)/t(x)]$. Now $g(x)$ is surjective and $t(x)$ isn't. Can I argue that the ratio however, will be surjective because the numerator is surjective, and thus even if it is being divided only by numbers greater than or equal to $1$, the numerator's surjectivity will make the whole function surjective?

Surjectivity or not of the denominator and numerator determine nothing really.
Half of the reason is simply because the choice of codomain is somewhat arbitrary of a decision. I can make (for $f(x) = x/(x^2+1)$) $f$ have codomain $\Bbb R, \Bbb C, \Bbb Q \cup (-1/2,1/2), [-10,10]$, or whatever. So long as the range of $f$ - $f(\Bbb R)$ in this case - is contained in that codomain, it's a valid function.
Comment: For injectivity, I would just use the graph to guess that $f(x)=1/4$ has two solutions and then solve the resulting quadratic.
Comment: I have no clue why that escaped my mind honestly.
Comment: @EeveeTrainer Wow, the amount of basic stuff that escaped me in this question is amazing. I haven't yet gotten to continuity and differentiability in my studies, but even without that its clear its not injective or surjective. The subjectivity counter proof with quadratics didn't occur to me, and I made an incredibly elementary algebra mistake while doing analytical proof of injectivity.
Answer: $\displaystyle \because f(x)=\frac{x}{x^{2}+1}=\frac{1}{x+\frac{1}{x}}, \quad $
$\therefore f(2)=f\left(\frac{1}{2}\right) \Rightarrow f$ is not injective.
$\forall x \in \mathbb{R} $, letting $ \displaystyle y=\frac{x}{x^{2}+1}$ yields
$$
y x^{2}-x+y=0 \cdots(*)
$$
$$\Delta_{(\star)}  \geqslant 0 \quad \Leftrightarrow \quad 1-4 y^{2} \geqslant 0 \quad \Leftrightarrow \quad |y| \leqslant \frac{1}{2}.$$
Therefore $\displaystyle \operatorname{Ran} (f)=\left[-\frac{1}{2}, \frac{1}{2}\right]$ and hence $f$ is NOT surjective.
Comment: You just showed that Ran$(f) = \left[-\dfrac{1}{2}, \dfrac{1}{2}\right]$.  Why did you conclude that $f$ is surjective?
Comment: Thank you very much for catching my typo.
Answer: Honestly I find the current answers overly complicated. The graph hits some horizontal lines more than once. For example, it looks like $f(x)=1/4$ has two solutions, and you can find that they are when $x$ is $2\pm\sqrt 3$.
Since the graph doesn't hit every horizontal line, the function is not surjective. For example, $f(x)=1$ implies $x=x^2+1$ has a solution, which is false (over the real numbers).
You only need the quadratic formula for both these claims.


Edit XPS content

Question: I have got an application that is supposed to send a formatted document to a printer with some barcodes.
I've made other applications that work with printers and print directly through the printserver by sending a xps file, so I thought I would try to see if I could make a .xps file, change the text and be done with it, however every article I can find on the net has to do with creating xps files and not changing them. I feel like it should be possible, and it would be nice not to have to resort to installing Office on the server and print through there. Then I might as well use Open XML and a .docx file.

It is very simple. Let's say I want to change the text INCNUMMER in a .xps file to "testing123". How would I go about that?
I have tried the whole unzip, open the xml, find the text, edit, rezip but I'm afraid there's too much about the .xps format I don't understand to make that work.
Best regards, Kaspar.
Comment: There's a native Windows API available to work with XPS documents as well: https://msdn.microsoft.com/en-us/library/windows/desktop/dd316976.aspx
Answer: As you already know, an XPS file is just a ZIP archive containing a number of files and folders that have particular names and a defined structure.
At the root level there is a Documents folder which will typically contain just a single document folder named 1. Inside that is a Pages folder containing one or more .fpage files: these define the content of each page in the document.
Documents
    1
        Pages
            1.fpage
            2.fpage
            etc

If you open up these .fpage files in a text editor you will see that they are just XML files. Each page is typically represented by a <Canvas> element that contains multiple <Path> and <Glyphs> elements (text is represented by the latter). However, even though <Glyphs> elements do have a UnicodeString attribute the value of that attribute cannot be changed in isolation.
Each <Glyphs> element also has an Indices attribute. If you remove this attribute altogether and change the UnicodeString attribute at the same time, this almost works. However, you will probably find that when viewing the file in the XPS Viewer application certain characters in the text are replaced by question mark symbols.
Font glyphs are embedded in the XPS file (odttf files in the Resources folder), and the software that generated the XPS file will only embed glyphs that are used in the source document. For example, this means that (for a given font) if you did not use the letter "A" in the source document, then the glyph for that letter will not be written to the resources of the XPS file. Hence if you change the UnicodeString attribute to include a letter "A" then that character will display as a question mark in the viewer because it has no glyph resource that tells it how that character must be drawn.
If you have control over the source document (the one that later gets converted to XPS) then I suppose you could include a piece of text containing all of the characters that you are likely to use, and set its colour to white so that it doesn't print, but I'm not sure whether the XPS printer driver would strip that text out anyway. If it didn't then you could probably do something like this:

Open the relevant .fpage XML file
Search all UnicodeString attributes of <Glyphs> elements to find the text you want
Replace that text with something else
Remove the Indices attribute from the changed <Glyphs> elements
Save the updated XML back to the file
Re-zip then change the extension from ZIP to XPS
Comment: That pointed me excatcly in the direction I needed!
I had tried unzipping it and findling with the xml but got some strange results.
Adding a line containing "0123456789abcdefghijklmnopqrstuvwxyz" i font-size 1, colored white, enabled me to change the content of the glyphs, when also taking care to add extra indices. I'll accept this as the solution.
Comment: I have the same problem right now and I don't have access to the source XPS. Question here: http://stackoverflow.com/questions/33524172/question-marks-in-xps-document
Comment: @Steven, Where we can see the .fpage files?
Comment: @SaravanakumarNatarajan It says in the answer: _"At the root level there is a `Documents` folder which will typically contain just a single document folder named `1`. Inside that is a `Pages` folder containing one or more .fpage files"._

Edit XPS content


Compare how fast two time-series grow

Question: I collected data from Pubmed containing articles published about two different topics.
The first is a yearly series of articles about omega 3 supplements.
The second is a yearly series of articles published about probiotics supplements.
I want to understand how fast the research has grown over time (in plain English, capture the scientific interest over time) and specifically whether the scientific interest grew somehow "faster" for a topic rather than the other.
Please find here the data in a public gdoc:
https://docs.google.com/spreadsheets/d/1yw2F8a6f0_v_-QmCYpWZfm12ev_qirdRNWcfwR71Qjk/edit?usp=sharing
I don't expect a full solution but at least some indication to where to start looking for my answer.
I assume it is something I can check with the time series slope, but I need some more inputs for going deeper in my research because I am kind of lost.
Thank you!
Comment: Your linked data shows a large jump in the value of "probiotics" from 1970 to 1974, changing from 59 to 475, but I do not see this on your plot of the data. Both "omega" and "probiotics" show a sudden drop from year 2018 to year 2019 but again I do not see this on your plots. Would you please chech that the posted data link and plots match in this?
Answer: This is very similar to looking at stock prices and other financial variables in econometric analysis.  The way to do this would be to plot $\log(x_{t+1}) - \log(x_t)$ at each time period $t = 1,...,T-1$.  This will show the rate of growth of each of the series, which is a good measure of "how fast they are growing".  (Note that if you have any zero values in your data then the growth to the next non-zero value is infinite.)
Answer: You might typically expect an 'interest' curve to follow an S-shape - interest starts low, accelerates quickly, then reaches a maximum.  It might fall again later, but that does not seem to be the case in your time period.
To model this, you could try to fit a logistic function to each of the data sets - one of the parameters of the logistic is the 'steepness' or rate of increase.
Comment: Thank you! I dont understand tho, to my knowledge a logistic function models a dicotomous outcome - either 0 or 1; how would it work with a continuous variable like the dataset here?
Comment: The logistic function is a continuous function, so it allows all values between 0 and 1. You would need to scale it to represent the range of your data, so multiply the logistic function by, say 200 or what you think might be a reasonable upper limit for the phenomenon you are modelling.  If you want to compare the rates between the two data sets, it might make sense to use the same maximum for both data sets, as long as you think it is reasonable that both data sets have the same theoretical maximum interest.

Compare how fast two time-series grow


WHM - add another user account via SSH

Question: I'm working for a crowd that have 'misplaced' the password for their WHM root login but I'm able to SSH to the server using the key file they've provided. I CAN'T change the password for root as they are concerned other functions are using it (and people possibly).
Is there any way so I can add another user account on the server that I can then use via the WHM login?
Answer: Give up and change the system root password.
WHM will allow a root login with the system root password, and if neither you nor the client actually knows it, you are going to have to reset the password anyway. You simply cannot avoid this without also avoiding doing any actual work, which defeats the purpose.
As for other processes using the root password, that seems unlikely, as even the most junior of admins will typically resist hard-coding any root password anywhere. People, on the other hand, might, and you can simply deal with them if they complain.
Comment: Yes that's what I ended up doing

WHM - add another user account via SSH


Putting text in a repeat without repeating the text

Question: I want to put text in a \repeat unfold in LilyPond without repeating the text, so that it only shows up on the first instance of the phrase.
I can't put it on the previous note because the repeat phrase is the start of the piece.
When I put it on a note in the repeat expression, the text appears above both instances of the note.
I've also tried using a spacing rest, but the duration of the invisible rest is added to the already full measure and causes other problems.
Is there a way to make the text not repeat with the note?
Answer: You can make the text into a parallel music passage that doesn't use \repeat, for example
{ \new Staff {
  << { \repeat unfold 3 { c''4 d'' } }
     { s4^"foo" s4^"bar" }
  >>
  e'' f''
} }

It doesn't matter that the parallel passages are different lengths, as the example demonstrates.
Answer: Since LilyPond version 2.23, there are a new some new commands for repeats.  The \volta command goes inside of a \repeat (unfold, volta, or segno) and specifies a musical expression that is applied to a particular iteration of the repeat loop.
To have only-markup as the musical expression, the trick is to attach the markup to a spacer with zero duration:
\repeat unfold 3 {
    \volta 1 { s1*0^\markup "text" }
    c'4 d' e' f'
}

See: 1.4.1 Long repeats - Other variation in repeated sections for more detail.


How to redeliver a STOMP message to the consumer in case of any processing failure?

Question: High-level architecture
JMS (Producer/Consumer) <----> Artemis(STOMP) <----> Websocket-Broker-Relay-Service <----> STOMP-over-Websocket-client (Producer/Consumer)
Some observations

In STOMP consumer, with client-individual ack-subscription, whether I NACK or ACK, the message is discarded by Artemis. I want the message to be redelivered to the same or any other consumer. Is there a way to achieve it?

In JMS consumer, the durable-message is not delivered if the consumer was down when the message was received on Artemis. My expectation was that once the consumer service comes back up again, the durable message will be delivered.

class StompSessionHandlerImpl implements StompSessionHandler {
    @Override
    public void afterConnected(StompSession session, StompHeaders connectedHeaders) {
        session.setAutoReceipt(Boolean.FALSE);
        StompHeaders headers1 = new StompHeaders();
        headers1.setDestination("/queue/msg");
        headers1.add("durable-subscription-name", messagingUtil.getServiceSubscriptionChannel());
        headers1.add("Authorization", "Bearer ".concat(token));
        headers1.setAck("client-individual");
        session.subscribe(headers1, this);

    }

    @Override
    public void handleException(StompSession session, StompCommand command, StompHeaders headers, byte[] payload, Throwable exception) {
        session.acknowledge(Objects.requireNonNull(headers.getMessageId()), false);
    }

    @Override
    public void handleTransportError(StompSession session, Throwable exception) {
        synchronized (StompSessionHandlerImpl.msgSenderLock) {
            if (exception instanceof ConnectionLostException && !getStompSession().isConnected()) {
                initStompSession();
            }
        }
    }

    @Override
    public Type getPayloadType(StompHeaders headers) {
        return COMessage.class;
    }

    @Override
    public void handleFrame(StompHeaders headers, Object payload) {
        if (payload == null) return;
        COMessage msg = (COMessage) payload;
     try {
        stompMessagingService.handleReceivedMessages(msg);
        self.stompMessagingService.getStompSession().acknowledge(headers.getMessageId(), true);
       } catch (Exception e) {
           self.stompMessagingService.getStompSession().acknowledge(headers.getMessageId(), false);
       }

    }

    @PreDestroy
    public void cleanUp() {
        self.stompMessagingService.getStompSession().disconnect();
    }

}

class WebSocketConfig extends WebSocketMessagingAutoConfiguration {
    @Bean
    public WebSocketStompClient stompClient() {
        WebSocketClient simpleWebSocketClient = new StandardWebSocketClient();
        List<Transport> transports = List.of(new WebSocketTransport(simpleWebSocketClient));
        SockJsClient sockJsClient = new SockJsClient(transports);
        WebSocketStompClient stompClient = new WebSocketStompClient(sockJsClient);
        MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter();
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        converter.setObjectMapper(objectMapper);
        stompClient.setMessageConverter(converter);
        ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
        scheduler.setPoolSize(10000);
        scheduler.initialize();
        stompClient.setTaskScheduler(scheduler);
        stompClient.setDefaultHeartbeat(new long[]{20000, 20000});
        stompClient.setReceiptTimeLimit(Integer.MAX_VALUE);
        ContainerProvider.getWebSocketContainer().setDefaultMaxTextMessageBufferSize(Integer.MAX_VALUE);
        return stompClient;
    }
}

public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    private String host;

    private String password;

    private String user;

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableStompBrokerRelay("/queue", "/topic", "/exchange")
                .setRelayHost(host)
                .setClientLogin(user)
                .setClientPasscode(password)
                .setSystemHeartbeatSendInterval(20000)
                .setSystemLogin(user)
                .setSystemPasscode(password)
                .setUserDestinationBroadcast("/topic/unresolved-user")
                .setUserRegistryBroadcast("/topic/log-user-registry");
        config.setApplicationDestinationPrefixes("/device");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/websocket").setAllowedOrigins("*").withSockJS().setWebSocketEnabled(Boolean.TRUE);
        registry.setErrorHandler(new StompSubProtocolErrorHandler());
    }

    @Bean
    public DefaultSimpUserRegistry getDefaultSimpRegistry() {
        return new DefaultSimpUserRegistry();
    }

    @Override
    public void configureWebSocketTransport(WebSocketTransportRegistration registry) {
        registry.setMessageSizeLimit(Integer.MAX_VALUE);
        registry.setSendBufferSizeLimit(Integer.MAX_VALUE);
        registry.setTimeToFirstMessage(300000);
        registry.setSendTimeLimit(300000);
        registry.addDecoratorFactory(new WebSocketHandlerDecoratorFactory() {
            @Override
            public WebSocketHandler decorate(WebSocketHandler webSocketHandler) {
                return new EmaWebSocketHandlerDecorator(webSocketHandler);
            }
        });

    }

}

class ArtemisConfig extends ArtemisAutoConfiguration {

    @Bean("mqConnectionFactory")
    public ConnectionFactory senderActiveMQConnectionFactory() {

        ActiveMQConnectionFactory connectionFactory =
               new ActiveMQConnectionFactory("tcp://".concat(host.concat(":").concat(port)));
        connectionFactory.setUser(user);
        connectionFactory.setPassword(password);
        connectionFactory.setConnectionTTL(-1L);
        connectionFactory.setClientID(clientID);
        connectionFactory.setEnableSharedClientID(true);
        connectionFactory.setPreAcknowledge(Boolean.FALSE);
        return connectionFactory;
    }

    @Bean("mqCachingConnectionFactory")
    @Primary
    public ConnectionFactory cachingConnectionFactory() {
        return new CachingConnectionFactory(senderActiveMQConnectionFactory());
    }

    @Bean("jmsTemplate")
    public JmsTemplate jmsTemplate() {
        JmsTemplate jmsTemplate = new JmsTemplate(cachingConnectionFactory());
        jmsTemplate.setMessageConverter(jsonMessageConverter);
        jmsTemplate.setSessionAcknowledgeMode(ActiveMQJMSConstants.INDIVIDUAL_ACKNOWLEDGE);
        jmsTemplate.setMessageIdEnabled(Boolean.TRUE);
        jmsTemplate.setTimeToLive(Integer.MAX_VALUE); // TODO : review
        return jmsTemplate;
    }

    @PreDestroy
    public void cleanUp() {
        if (connection.isStarted()) {
            try {
                connection.close();
            } catch (JMSException e) {
                log.error("Failed to close the JMS connection {0}", e);
            }
        }
    }

}

Answer: When using ActiveMQ Artemis a STOMP ACK frame tells the broker that the message has been consumed successfully so it should be removed from the queue. A STOMP NACK frame tells the broker that the message was not consumed successfully so the broker will discard it. The exact behavior here is not specified by the STOMP specification. It only says:

NACK is the opposite of ACK. It is used to tell the server that the client did not consume the message. The server can then either send the message to a different client, discard it, or put it in a dead letter queue. The exact behavior is server specific.
NACK takes the same headers as ACK: id (REQUIRED) and transaction (OPTIONAL).
NACK applies either to one single message (if the subscription's ack mode is client-individual) or to all messages sent before and not yet ACK'ed or NACK'ed (if the subscription's ack mode is client).

If you want the message to be redelivered you should neither ack nor nack the message and when the consumer's connection is closed the message will be placed back onto the queue for delivery to another (or the same) client.
In the future I expect this behavior will be configurable.
Comment: thanks for your response. The messages are time-critical. If we do not NACK/ACK, in that case for the message to be redelivered the connection-TTL needs to be very low. And even if the connection-TTL is low, as long as there are new incoming messages, the connection will stay alive, in which case the message will be stuck in the queue awaiting connection closure. What do you suggest? or am I missing something?
Comment: I'm not clear where connection-TTL enters the picture here, and I don't see why new messages arriving will force the connection to remain alive. If your application needs to close the connection to trigger a redelivery it can simply close the connection, no? The application is in control of its own connection. At least, that's true in most use-cases? Is your use-case different?
Comment: _Apache ActiveMQ Artemis makes all of this configurable via a connection TTL. Basically, the TTL determines how long the server will keep a connection alive in the absence of any data arriving from the client. The client will automatically send "ping" packets periodically to prevent the server from closing it down. If the server doesn't receive any packets on a connection for the connection TTL time, then it will automatically close all the sessions on the server that relate to that connection_
From this paragraph in the docs, I got that understanding.
Comment: Although, From your last comment, I understand, you mean in the event of failure, I should just deliberately close the connection and reconnect from the consumer as a workaround. It would be great if this behaviour could be configurable as you mentioned in your response.
Comment: The connection TTL is there to make sure the broker closes the connection and cleans up any server-side resources in case of a client or network failure or misbehaving client that simply doesn't close its connection properly. It doesn't really have any bearing on this use-case. As noted, you should close your connection deliberately to trigger redelivery. As far as making the behavior configurable please consider contributing a solution. ActiveMQ Artemis is, after all, open-source, and code contributions are always welcome.


Modo de criar página HTML com PHP

Question: Não possuo muito conhecimento e não sei se o modo que estou fazendo está correto ou possui algum ponto negativo. Tem alguma opção melhor para que eu possa fazer?
<?php
$ht = '
';
$ht .= '
';
$ht .= '<form id="searchthis" method="get">';
$ht .= '<input id="namanyay-search-box" name="search" size="40" type="text" placeholder="Search"/>';
$ht .= '<button id="namanyay-search-btn" type="submit" class="btn btn-primary"></button>';
$ht .= '</form>';
$ht .= '
Manage OneDrive Videos
';
$ht .= '
';
$ht .= '
';
$ht .= '
';

echo $ht;
?>

Answer: De forma geral não há problema em fazer assim, mas o pessoal costuma usar o sistema de template, ou seja, coloca-se em primeiro lugar o HTML e coloca um código PHP nas lacunas necessárias. O que não é o caso deste código, ou seja, esse exemplo deveria ser uma página estática HTML que nem passe pelo processador do PHP, seria absurdamente mais rápido assim.
Exemplo bem básico de como se costuma fazer:

        <title>PHP Test</title>

<?php echo "1 + 1 é " . (1 + 1); ?>

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Claro, o exemplo é bobo e assim também não precisaria passar pelo PHP, mas dá uma ideia de como é mais comum. O que você faria provavelmente é uma página que receberia o valor enviado pelo seu exemplo e trataria dando um resultado final que seria entregue para o navegador.

Modo de criar página HTML com PHP


PHP arrays, getting to loop index information

Question: Let me explain the array bellow:
1, 2 and 3 stand for Monday, Tuesday and Wednesday.
13, 14, and 15 are the days of the month.
And 15:00 - 16:20 (..) are the hours the movies are going to be shown.
Meaning on Monday 13th from 3pm to 4:20pm you can watch "Batman".
Also on Monday 13th from 6:10pm to 7:30pm you can watch "Misery"  … and so on.
$myarray
: array =
  1: array =
    13: array =
      15:00 - 16:20: array =
        Movie: string = Batman
      18:10 - 19:30: array =
        Movie: string = Misery
  2: array =
    14: array =
      15:00 - 16:20: array =
        Movie: string = The Avengers
      16:20 - 17:50: array =
        Movie: string = The Hours
  3: array =
    15: array =
      18:10 - 19:30: array =
        Movie: string = Gladiator

Could you please help me to echo this array so you can see the info in it in the following format?:
Monday - 13
15:00 - 16:20 - Batman
18:10 - 19:30 - Misery
Tuesday – 14
15:00 - 16:20 - The Avengers
16:20 - 17:50 - The Hours
Wednesday – 15
8:10 - 19:30  -  Gladiator

Thanks a lot!
Comment: Your array is not valid php format. Are `16:20 - 17:50` supposed to be a key? I.e. can you use `$myarray[1][13]['15:00 - 16:20']` to fetch `array("Movie"=>"Batman")` (I hope not!)? I am sorry, I don't understand the notation you are using.
Comment: Can you just add the exact array
Answer: I'm making an assumption about the true layout of your array, the following will create a $weekDays array to map an integer and a day of the week (I define the keys so you can shift them at any time):
$weekDays = (1=>'Monday', 2=>'Tuesday', 3=>'Wednesday', 4=>'Thursday', 5=>'Friday', 6=>'Saturday', 7=>'Sunday');

// loop through each week-day in the array
foreach ($myarray as $weekDay => $dates) {
    // loop through each "movie date" in the current week-day block
    foreach ($dates as $monthDate => $movies) {
        // output the day-of-the-week and the date-of-the-month
        echo $weekDays[$weekDay] . ' - ' . $monthDate . '
';

        // loop through all of the movies for the current date-of-the-month
        foreach ($movies as $movieTime => $movie) {
            // output the movie's time and name
            echo $movieTime . ' - ' . $movie . '
';
        }
    }
}

This is assuming the array in your example is really in the format:
$myarray = array(
    1 => array(
        13 => array(
            '15:00 - 16:20' => array(
                'Movie' => 'Batman'
            ),
            '18:10 - 19:30' => array(
                'Movie' => 'Misery'
            )
        ), // ... can repeat
    ), // ... can repeat
);

Answer: You can try the following code below : See Demo
$myarray = array(
    1 => array(
        13 => array(
            "15:00 - 16:20" => array(
                "Movie" => " Batman"
            ),
            "18:10 - 19:30" => array(
                "Movie" => " Misery"
            )
        )
    ),
    2 => array(
        14 => array(
            "15:00 - 16:20" => array(
                "Movie" => " The Avengers "
            ),
            "16:20 - 17:50" => array(
                "Movie" => " The Hours "
            )
        )
    ),
    3 => array(
        15 => array(
            "18:10 - 19:30" => array(
                "Movie" => " Gladiator"
            )
        )
    )
);

$days = array(1 => 'Monday',2 => 'Tuesday',3 => 'Wednesday');

echo "
";
foreach ( $myarray as $key => $value ) {
    foreach ( $value as $valueKey => $info ) {
        echo $days[$key], " - ", $valueKey, PHP_EOL;
        foreach ( $info as $infoKey => $infoValue ) {
            echo $infoKey, " - ", $infoValue['Movie'], PHP_EOL;
        }
        echo PHP_EOL;
    }
}

Output
Monday - 13
15:00 - 16:20 -  Batman
18:10 - 19:30 -  Misery

Tuesday - 14
15:00 - 16:20 -  The Avengers
16:20 - 17:50 -  The Hours

Wednesday - 15
18:10 - 19:30 -  Gladiator


Using arguments in addConstraint() for validation

Question: I implemented hook_entity_bundle_field_info_alter() to add validation to fields of a node type. I got $bundle as an argument in the hook and I need to pass it in $options argument like below:
$fields['field_tags']->addConstraint('NodeValidate', $bundle);

How can I access this argument in NodeValidateConstraintValidator? Am I passing the argument correctly?
$options provided in addConstraint can be accessed in the constructor using parent::__construct($options) in __construct() function build the options.
hook_entity_base_field_info_alter() doesn't contain a $bundle argument, as it is defined as function hook_entity_base_field_info_alter(&$fields, \Drupal\Core\Entity\EntityTypeInterface $entity_type). How can I validate the base field for a particular node type?
Answer:
Options needs to be an array I think. You can access it on the constraint object in your validator, see ListStringItem::propertyDefinitions() and LengthValidator, which then uses it as $constraint->max.
Base fields are exactly that. Base fields. There is no bundle, they are the same for all bundles of an entity type (they can be overriden per-bundle, but then they become accessible in the bundle hook).
You shouldn't ask two different questions together :)
Comment: Sorry for asking two questions on a single post. I'm a bit lazy :( . Can you please explain the 2nd point that states overriding per-bundle. If i need to validate title field of a particular node type which hook should I use?
Comment: I looked at `propertyDefinitions()` and `LengthValidator` and tried to do the same but it just throwed me an error. I think there is something to do with `constructor` in `Length.php` . But I can't get it
Answer: To pass arguments in addConstraint() something like:
$fields['field_tags]->addConstraint('NodeValidate', array('bundle' => 'article));

You should create a constructor in NodeValidateConstraint.php and calling the parent constructor like below:
You should need to declare a property name same as the name of the key in the options you passed. In this case it is bundle.
class NodeValidateConstraint extends Constraint {
  public $bundle;
  public function __construct($options = null)
  {
      parent::__construct($options);
  }
}

Now you could access the $options in NodeValidateConstraintValidator.php as
$bundle_name = $constraint->bundle;

Thanks berdir for guiding me in this and continuously responding to my queries in drupal 8:)


Single function for state change no multiple states whit similar name

Question: I'm trying to create a function for the state change, on multiple states ...
I have the following states in the constructor()
this.state={
  answer1:"",
  answer2:"",
  answer3:"",
  answer4:"",
  answer5:"",
  //answerN... (25 to be exact)
}

I have this Question component which is a
 tag and 6 radio buttons for the question  answers
I make 5 instances of this component
<Question addAnswer={this.addAnswer} title="...." />
<Question addAnswer={this.addAnswer} title="..." />
....

each  calling the same function named addAnswer()
addAnswer = (answerValue) => {
  this.setState({answer1:answerValue},()=>console.log(this.state.answer1))
}

this function  will change only the answer1 state
So  how to make it something like this to work
addAnswer = (answerNumber,answerValue) => {
    this.setState({ answer + answerNumber: answerValue },()=>console.log(this.state.answer + answerNumber))
}

Is function like this possible?
Is there an option of making the answer state an Array and how will I determine which index of this array is answered and on later changed ???
Answer: I prefer to pass the whole name of the attribute as a parameter to the function, instead of just a number. I think it looks more readable and easy to understand.
Like this:
addAnswer = (answerCode, answerValue) => {
    this.setState({ [answerCode]: answerValue }, () =>
        console.log(this.state[answerCode])
    )
}

If I were you I would probably change the structure to look something like this:
{
    "answers": {
        1: {
            "code": 1,
            "value": "Yes"
        }
    }
}

Then, when you are passing the value to the reducer, you can pass the whole answer object:
{
    "code": 2,
    "value": "No"
}

And to add a new answer:
addAnswer = (answer) => {
    this.setState({ [answer.code]: answer })
}

Answer: I'd suggest you to iterate over some data array, which holds e.g. titles:
someArray.map((title, i) => (
   <Question addAnswer={() => this.addAnswer(answerValue, i)} title={title} />
);

Then you will be able to reference to an item on specified index i.
addAnswer = (answerValue, i) => {
  this.setState({ `answer${i}`: answerValue });
};

Note: You didn't specify from where answerValue prop comes from + i starts at 0.
Comment: `answer${i}` gives me an unexpected token error ...  any ideas?
Comment: @ГеоргиДимитранов Maybe your ver doesn't support es6. Try simply `"answer" + i`.