Alternatives to ANOVA to find differences between three groups?

Question: So my data is looking at the incidence of emotions within therapy sessions. I am looking at three groups that I suspect have different pattern across several emotions
Group 1 n=36
Group 2 n=12
Group 3 n=6
The variables are measured in terms of time spent in that emotion (e.g., 10 minutes of anger, 5 minutes of sadness). I have also constructed a proportion for each emotion based on how much time spent in a given emotion divided by the total time spent experiencing any emotion (e.g., 10 minutes of anger divided by 20 minutes in emotion = 50% anger in that session).
I am aware that the group sizes are uneven, and that one group is quite small - these are exploratory analyses so I would just like to find a way to compare them statistically as a starting point.
Given that the groups are different across emotions - there is a low incidence of certain emotions in some groups, thus violating normality and homogeneity of variance.
What I want to know is whether these groups are different across each emotion type. Any ideas of what would be appropriate or other considerations before making a decision?
Comment: There is always a non-parametric alternative, which is [randomization test](http://www.uvm.edu/~statdhtx/StatPages/Randomization%20Tests/RandomizationTestsOverview.html) (closely related to [bootstrap](http://stanfordphd.com/Bootstrap_Sampling.html)).
Answer: If at each evaluation time there is either no emotion or exactly 1 emotion, then multinomial regression should be a good choice. That models the log-odds of each of a defined set of categorical outcomes against a reference category, in a situation where there is exactly one outcome per observation. This is effectively a set of binomial regressions modeled in a way that ensures the probabilities over all outcomes sum up to 1. Normality isn't an issue. Unequal group sizes will limit the ability to detect true differences but shouldn't matter otherwise.
You should include "emotion-free" as one of the outcomes, at least to start your model, as you want there to be exactly 1 outcome at each observation. "Emotion-free" might be a reasonable choice for the outcome reference category. Group membership would be the predictor/independent variable. The above link illustrates the procedure for single observations, but the help page for the multinom function used there shows how to set up the outcome as a set of columns of counts for each of the outcomes. Those values should be integers. For example, with evaluation of emotion done once per minute, they would be the number of minutes in each state.
After you've built that model, you can interrogate the results in terms of probabilities to perform the comparisons the you want. That could include comparisons among groups of proportion of any emotion time in each emotion. Post-modeling tools like those in the emmeans package can make that task easier.
Comment: I appreciate your answer! This sounds very useful - but would there be a benefit to using this rather than a Kruskal-Wallis test instead?
Comment: @user380249 with Kruskal-Wallis (K-W) tests you would have to do a separate test for each emotion, leading to possible [multiple-comparison](https://en.wikipedia.org/wiki/Multiple_comparisons_problem) problems. Also, unless the distributions within groups have the same shapes and scales (which doesn't seem likely here) it's hard to [interpret K-W](https://en.wikipedia.org/wiki/Kruskal–Wallis_one-way_analysis_of_variance) with respect to anything other than stochastic dominance. Multinomial models directly evaluate probabilities and probability differences.
Comment: Thanks @EdM!! I have done logistic regressions before but didn't know the option of multinomial. This will work great for my data :)
Comment: @EdM wouldn't the dependent variable be the group membership? Then the IV's would be predictors of group membership?
Comment: @Statsyy you can use "emotion" as the dependent variable in a multinomial regression if, at any observation time, there is either no emotion or exactly 1 emotion among a list of possible emotions. Then Group could be used as a predictor variable. You could consider analyzing the other way around, as your comment suggests, although results might differ. For example, with a 2-class situation you could evaluate class membership as a function of predictor values, or distributions of predictor values among classes. This is just the multi-class extension of that principle.


Are my piano keys defect (Yamaha YDP143)?

Question: I hope it is the right place to ask. I am a beginner to piano and I have a Yamaha YDP143 Digital Piano for practicing.
I have noticed that, there are strange noises with some keys (not Piano sound, but the key sound), and I am not sure if I shall contact seller for repair/replacement?
The problem (clicking noise) only occurs with middle C and D keys (C3 and D3), that I often encounter and it is quite irritating to have such an issue.
Could you please let me know if it sound OK, or is it something common that can occur and needs to be repaired?
Here I have added a video for it (Piano on, Volume down to zero)
YouTube Video of Clicking Keys on Piano
Thank you all for your help and support!
Comment: I just wanted to be sure that I am not being extra suspicious and wanted to have the opinion of the some experienced users, as I am being a beginner as mentioned. Thanks for the info, though.
Comment: Contacting seller is no. 1. Also check Yamaha forums. Why haven't you?
Answer: Definitely a reason for repair/replacement. It is only a matter of time until the key won't work any longer. Plus, the sound is annoying enough to disturb your musical pleasure.
Answer: Yes, C and D are "looser" than the other keys.  Just normal wear-and-tear on heavily-used notes I think.  On a real piano there are adjustments.  Not so much on an electric keyboard I'm afraid.


Find all integers such that polynomial $x^4+n$ is reducible in $\mathbb{Z}[x]$

Question: In my studies of abstract algebra and polynomials, I have the following question:

We are asked to find all integers $n$ such that the polynomial $x^4+n$ is reducible in $\mathbb{Z}[x]$.

The only thing I can think of is Eisenstein's criterion but that just tells me for $n$ that have a prime factor of power 1, it is irreducible. How would I handle the rest? I thank all helpers.
Comment: Obviously $x^4-m^2$ will be reducible, but there are other examples too....
Comment: Everyone should know the famous factorization $x^4+4=(x^2-2x+2)(x^2+2x+2)$.
Comment: Eisenstein works for any $n$ which is divisible by some prime $p$ but not  by $p^2$.
Comment: Sorry, what I said was incorrect.  The first part was correct.  Eisensten works if there is a prime $p$ such that $p\,|\,n$ but $p^2\,\nmid \,n$.  But that's not the same as saying that $n$ is not a perfect square.
Comment: To the general question:  if there is a root then it is easy. If there is not a root then, if it is reducible, it must factor as the product of two quadratics.  That form can be studied.
Comment: I think so, yes. And I don't think you even need the bit about Eisenstein (though that was certianly the first line of attack I thought of).
Comment: See [Bill Dubuque's old answer](https://math.stackexchange.com/a/133598/11619). Either $n=-m^2$ or $n=4m^4$ for some integer $m$.
Comment: I would rather not for I cannot add anything to that old answer. I need to think about it a bit more. At least I want to able to give a proof for this special case $n=4$. Sorry.
Comment: @lulu thank you very much but what about $n$ which are perfect squares? How do I handle those?
Comment: @lulu I think you mean $n$ which have a prime factor of power 1
Answer: Let's assume the polynomial is reducible. Then we can see that it must have a quadratic factor - for if it had a linear factor, it must be in form $x-p$, but then $p$ is a root and so is the $-p$ (since the polynomial has only even exponents), and so $(x-p)(x+p)=x^2-p^2$ is a quadratic factor.
So assume a generic factorization $x^4+n=(x^2+ax+b)(x^2+cx+d)$. Comparing the coefficients, we have $a+c=0$, $ac+b+d=0$, $ad+bc=0$ and $bd=n$. Hence $c=-a$, and so $0=ad+bc=ad-ab=a(d-b)$. So either $a=0$, or $d=b$.
If $a=0$, then $c=0$ and $b+d=0$. Thus we have $n=-b^2$ and $x^4+n=(x^2-b)(x^2+b)$.
If $d=b$, then $-a^2+2b=0$, and so $a=2k$ is even. But then $-4k^2+2b=0$, so $-2k^2+b=0$, and so $b=2l$ is even. So, $-k^2+l=0$, thus $a=2k$, $b=2k^2=d$. Thus we have $n=bd=4k^4$ and $x^4+n=(x^2+2kx+2k^2)(x^2-2kx+2k^2)$.
So we have found that if $x^4+n$ is reducible, then necessarily $n=-k^2$ or $n=4k^4$, and in both cases we have found these factorizations, so it is also sufficient.
Answer: Assume $m=-n > 0$.
If $m$ isn't a fourth power, and $X^4+n$ is reducible, it means that there is a quadratic algebraic integer $\alpha$ with $\alpha^4=m$.
$\alpha$ is a quadratic algebraic integer so it can be written as $a+b\sqrt{D}$ for integers $a,b$ and square-free $D \neq 1$, or $\frac{a+b\sqrt{D}}{2}$ with furthermore $4|D-1$ and $2|a-b$.
Then $\alpha^2$ is real, so if $D < 0$, $\alpha$ is pure imaginary and $\alpha^2$ must be a real element of an imaginary quadratic field over $\mathbb{Q}$, so is rational, and $m$ is a perfect square – we are in the case $X^4-p^2$.
If $D > 0$, then $\alpha$ is real so $\alpha=\pm m^{1/4}$, so, $\alpha^2$ is $\sqrt{m}$ and is a rational linear combination of $1$ and $\sqrt{D}$, which implies $m=c^2D$ for some integer $c$.
Thus $\alpha=\pm \sqrt{c\sqrt{D}}$ is a quadratic integer over $\mathbb{Q}$. But $\alpha=a+b\sqrt{D}$ where $2a,2b$ are integers. Taking squares, we find $a^2+b^2D=0, 2ab=c$, which implies (as $D$ is square free) a contradiction.
So if $n < 0$, $X^4+n$ is reducible iff $-n$ is a perfect square ($X^4-m^2=(X^2-m)(X^2+m)$).
Assume $n > 0$ and $X^4+n$ reducible. Then there is a quadratic algebraic integer $\alpha$ such that $\alpha^4=-n$, ie $\alpha^2=\pm i\sqrt{n}$.
Let $d$ be the product of prime factors with odd valuation of $n$, (so that $\sqrt{n} \in \mathbb{N}\sqrt{d}$) it follows that $\alpha=a+ib\sqrt{d}$ where $2a,2b$ are integers. As $\alpha^2 \in i\mathbb{N}\sqrt{d}$, it follows $a^2=db^2$, which forces $d=1$ ie $n$ is a square.
As $n=c^2$, $c>0$, then $\alpha^2=\pm ic$, so that $\alpha=(\pm 1 \pm i)(c/2)^{1/2}$.
So (with complex conjugation), the question is as follows: when is $u=(1+i)\sqrt{c/2}$ a quadratic integer?
Assume $u$ quadratic integer. Then $K=\mathbb{Q}(u)$ is stable under conjugation and $\overline{u} \in K$. But $\frac{u}{\overline{u}}=(1+i)(1-i)^{-1}=(1+i)^2/2=i$, so $i \in K$ and $K=\mathbb{Q}(i)$. Thus the real part of $u$ is rational, ie $c/2$ is a square.
Finally, it follows that the only cases where $X^4+n$ is reducible are the "trivial ones":

if $-n$ is a square (difference of squares)

if $n=4a^4$ (Sophie Germain)


Given latitude and longitude and facing north, how can I calculate the rotation needed to face another latitude and longitude (namely 0,0)?

Question: As the title says, given I'm somewhere on earth facing north, I can determine the magnitude  of the distance to get to 0°,0°, but I am not sure how to calculate the rotation needed to be facing 0°,0°.
For what it's worth:
Assuming 0°,0° is the other point,  the magnitude is calculated as: $Radius Of The Earth$ * $\arccos$ ( $\cos$ ($latitude$) * $\cos$ ($longitude$) )
From here: https://en.wikipedia.org/wiki/Great-circle_distance#:~:text=.%5B1%5D-,Formulae,-%5Bedit%5D
Comment: The formula you ask for is also in Wikipedia, alas, even closely related to the GC distance, [on a separate page](https://en.wikipedia.org/wiki/Great-circle_navigation).
Answer: Since we're talking about angles, the radius of Earth doesn't matter, and we can take it as $1$.  The coordinates in $(x,y,z)$ of a point on Earth, assumed a sphere centered at the origin $(0,0,0)$ and with radius $1$ are given by
$ P = (\cos \theta \cos \phi, \cos \theta \sin \phi, \sin \theta ) $
You are at $P_1 = (\cos \theta_1 \cos \phi_1, \cos \theta_1 \sin \phi_1, \sin \theta_1) $  where $ \theta_1$ is your latitude and $\phi_1$ is your longitude, and $ -90^\circ \le \theta_1 \le 90^\circ$ and $ -180^\circ \le \phi \le 180^\circ $.
The local north at your location is
$ N = ( - \sin \theta_1 \cos \phi_1, - \sin \theta_1 \sin \phi_1, \cos \theta_1) $
and the local east is
$ E = ( -  \sin \phi_1 , \cos \phi_1 , 0 ) $
Your final direction is a combination of these two directions, and since your initially facing north, and assuming the angle of rotation is $\phi$, then
you final direction will be
$ V = \cos \phi N + \sin \phi E $
If this vector is pointing towards the point
$ Q = (\cos 0^\circ \cos 0^\circ, \cos 0^\circ \sin 0^\circ, \sin 0^\circ) = (1, 0, 0) $
Then the vector $V$ lies in the plane whose normal vector is $ P_1 \times Q $
which means the vector $V$ is orthogonal to $P_1 \times Q $
Now,
$W = P_1 \times Q = (\cos \theta_1 \cos \phi_1, \cos \theta_1 \sin \phi_1, \sin \theta_1) \times (1, 0, 0)  = (0, \sin \theta_1 , - \cos \theta_1 \sin \phi_1 ) $
And since we want $ V \cdot (P_1 \times Q) = 0 $, then this means that
$ \cos \phi (N \cdot W) + \sin \phi (E \cdot W) = 0 $
The solution of this trigonometric equation will give two values for $\phi$ that are separated by $180^\circ$.
As an example, suppose that you are at latitude $45^\circ$, and longitude $-75^\circ$ (i.e. $45^\circ$ North, and $75^\circ$ West).  Then
$ W = (0, 0.7071, 0.683 ) $
while
$ N =  ( - \sin \theta_1 \cos \phi_1, - \sin \theta_1 \sin \phi_1, \cos \theta_1) = (-0.183, 0.683, 0.7071)$
and the local east is
$ E = ( -  \sin \phi_1 , \cos \phi_1 , 0 ) = (0.9659, 0.2588,0)$
Hence,
$ W \cdot N = 0.9659 $
$ W \cdot E = 0.183 $
Hence, the trigonometric equation to solve is
$ 0.9659 \cos \phi + 0.183 \sin \phi = 0 $
From which
$ \tan \phi = - \dfrac{0.9659}{0.183} = -5.278$
Therefore, $\phi = -79.272^\circ $  or $ \phi = 100.728 $
Remember that $\phi$ is a clockwise rotation (from north through east).
But only one value of $\phi$ is correct. To choose the correct one, we have to ensure our direction $ V $ makes an acute angle with $ Q - P_1$.
Now
$ Q - P_1 = (1, 0, 0) - (0.25882, -0.683, 0.7071) = (0.74118, 0.683, -0.7071) $
And with $\phi = -79.272 $ our vector $V$ is
$ V = \cos(-79.272) (-0.183, 0.683, 0.7071) + \sin(-79.272) (0.9659, 0.2588,0) \\= (-0.9831, -0.12714, 0.13162) $
So
$ (Q - P_1) \cdot V = -0.90856 \lt 0 $
So $-79.272$ is not the correct value of $\phi$.
With $ \phi = 100.728$, our vector $V$ is
$ V = \cos(100.728) (-0.183, 0.683, 0.7071) + \sin(100.728) (0.9659, 0.2588, 0) \\= (0.9831, 0.12714, -0.131620 ) $
And
$ (Q - P_1) \cdot V = 0.90856 \gt 0 $
So $100.728$ is the correct value of $\phi$.
Note that you don't have to do the calculations for $V$ twice (i.e. for both $\phi$'s), do the calculation for only one of the two values of $\phi$, if the dot product with $Q- P_1$ is positive then this is your $\phi$, otherwise, the correct $\phi$ is the other value.
Comment: Wow this is amazing!! Thank you so much! This question was an abstraction from Euler angle manipulation so to change the frame into x,y,z coordinates was really enlightening. And I greatly appreciate the very clear step by step explanation and example.
Comment: You're welcome.  Thanks for accepting my answer.


Python Pip: No module named pkg_resources

Question: I am a bloody beginner with programming in general and am just getting started with python. I tried installing pygame (on Mac OS) with pip by using
§ pip install pygame

but got an error message:
Traceback (most recent call last):
  File "/usr/local/bin/pip", line 6, in <module>
    from pkg_resources import load_entry_point
ImportError: No module named pkg_resources

So i tried (for some reason) installing pip again. with
§ sudo pip uninstall pip
§ sudo pip install pip

both resulting in the same error message as before. I uninstalled python to make sure I am on the newest version but if anything it's made things worse. Pretty much any command containing pip yields the same eroor message.
I have literlly zero experience working with the terminal window so if you know the answer, please dumb it down a little.
EDIT: Here is a list of commands that I tried, that give the same error message:
pip
sudo pip
sudo pip install setuptools --upgrade

A list of commands I tried that result in other error messages:
sudo easy_install install setuptools --upgrade

results in
    Traceback (most recent call last):
  File "/usr/bin/easy_install", line 8, in <module>
    from pkg_resources import load_entry_point
ImportError: No module named pkg_resources

Comment: Does this answer your question? [No module named pkg\_resources](https://stackoverflow.com/questions/7446187/no-module-named-pkg-resources)
Comment: I don't think so. The solution they propose just results in another error message.
Answer: This mostly should be the issue regarding the setuptools, as python requires OS and version specific setup tools.
You can try installing Setup tools using the following command.
pip install setuptools

You Can Also Try The Following:
sudo pip install setuptools --upgrade
or sudo easy_install install setuptools --upgrade

According to some similar posts on Internet this should work
sudo apt-get install --reinstall python-pkg-resources

Comment: For py3 crowd, `sudo apt install --reinstall python3-pkg-resources python3-setuptools`
Comment: I just tried that and got the same error message from before
Comment: Which Os Are you Using? // Check my recent changes to the post if that helps
Comment: MacOS Catalina. First one results in the same error message. Second one results in a similar error message (see edited post). Do you think there ist a way to just reinstall the whole thing?
Comment: You can try reinstalling python maybe
Comment: How are you installing Python?  If you use Anaconda to install python, don't use pip!  Use conda instead.


'cat' is not recognized as an internal or external command, operable program or batch file

Question: <code>cat .ssh/id_rsa.pub | ssh email@example.com 'cat >> .ssh/authorized_keys'
</code>
I'm running this command on my Ubuntu server to send my public key to my Windows. And I got this:

'cat' is not recognized as an internal or external command,
operable program or batch file.
ote

How can I solve this?
Comment: The error message indicates that one of the systems is a Windows box, not Unix/Linux at all. We can't tell from your question whether that is the system where you are trying to run this command, or the remote system you `ssh` into.
Answer: Looks like your target is windows machine and it didn't understand cat. Can you give it a try after installing the Cygwin software on Windows machine,


Exact time measurement in football

Question: Why is the time measurement in football(soccer) not handled exact like in basketball?
Comment: Why is the time management in basketball not handled exactly like in rugby? Why is the time management in rugby not handled exactly like in cricket? Answer: because it just isn't. **VTC.**
Comment: I think this can definitely be answered, based on the historical reasoning behind the introduction of additional time and the traditional role of the referee being the sole controller of the match. See [my answer](http://sports.stackexchange.com/a/14884/3526) for more information.
Answer: In football, there is a strong tradition that the referee is responsible and accountable for every single decision. This is due to the fact that historically (and even at the lowest levels of the game at present) there was only one neutral official present at a game. Tasking a single official with stopping and starting a clock every time the ball went out as well as supervising and indicating the restart of play would make officiating a very difficult task, hence why it is a discretionary process.
Furthermore, additional time was added in football only to combat deliberate time-wasting, and time lost due to injuries, substitutions and disciplinary action. It was never intended to be used to add on time simply due to the ball being out of play. Up until that point, a match was exactly two periods of 45 minutes, and this included when the ball was out of play. This is still the way it is today.
Law 7.3 - The Duration of the Match, Allowance for time lost:

Allowance is made by the referee in each half for all time lost in that half through:

substitutions
assessment and/or removal of injured players
wasting time
disciplinary sanctions
stoppages for drinks or other medical reasons permitted by competition rules
any other cause, including any significant delay to a restart (e.g. goal celebrations)

IFAB, the organisation responsible for changes to the Laws of the Game, up until recently, only met annually and required a 75% supermajority to change any Law. As a result, changes to the Laws have always been very minor. This is why, in spite of there being better timing technology available and more budget to train and pay a separate timekeeper at the highest levels of the game, this area of the game hasn't changed since additional time was introduced decades ago in 1987.
However, as of 2014, this has changed, with IFAB now having two panels that consistently are trialling and studying the impact of changes to the Laws through the year. The recommendations are presented to IFAB, leaving IFAB's members to more or less rubber stamp new changes. It is possible that the method of timing at the highest levels of the game may change in the near future, even though it seems unlikely that it will change at the amateur level.
It is worth noting in some amateur competitions, due to scheduling constraints, there is no allowance for added time at all.

Exact time measurement in football


Using parameterization of a circle to find all integer solutions to $X^2 + Y^2 = Z^2$?

Question: I'm self-studying algebraic geometry through this book and am stuck right at the start.
The author states that to find all $X, Y, Z \in \mathbb{Z}$ such that $X^2 + Y^2 = Z^2$ one can simply use this parameterization of the circle $x^2 + y^2 = 1$:
$$x = \frac{2 \lambda}{\lambda^2 + 1}, y = \frac{\lambda^2 - 1}{\lambda^2 + 1}, \text{ where } \lambda = \frac{x}{1-y}.$$
Which, the author continues, leads directly to the fact that all solutions are given by:
$X = 2lm$, $Y = l^2 - m^2$, $Z = l^2 + m^2$, with $l, m$ coprime.
I don't follow this line of reasoning at all -- how he got the parameterization, what he means by setting the parameter $\lambda$, and how all that leads to the final assertion -- which I verified by computer is indeed the set of integer solutions.
I'm also interested in how I would do this over $\mathbb{Q}$, and for arbitrary curves. The first problem in section 1 is related to proving something similar for a circle of radius 5 over the rationals :)
Thanks in advance!
Comment: Take lambda to be the slope of the line that passes through the circle. It intersects the circle at two points (1,1) and the second point say (x,y). If lambda is known,the point (x,y) can be found by using the equation of a line where a slope and co-ordinates of one point is known.
Answer: Draw the circle and show the $x$- and $y$-axes. Look at a point $(x,y)$ on the circle. Draw the line that passes through that point and through the point $(0,1),$ which is also on the circle. The slope of that line is $-\lambda = (y-1)/x.$ Now we have a system of two equations:
$$
-\lambda = \frac{y-1} x \\[10pt]
x^2+ y^2 = 1
$$
The solution for $x$ and $y$ is what you wrote.
Observe that $x$ and $y$ are rational if and only if $\lambda$ is rational. Thus letting $\lambda$ run through $\mathbb Q$ gives all rational points on the circle (except $(0,1).$) (And this shows that there are infinitely many rational points on the circle and thus infinitely many primitive Pythagorean triples. I don't know a simpler way to show that.)
Letting rational $\lambda= \dfrac \ell m$ with $\ell,m\in\mathbb Z,$ we have
\begin{align}
x & = \frac{2\lambda} {\lambda^2 + 1} = \frac{2\ell m}{\ell^2 + m^2}
\end{align}
and then treat $y$ similarly.
Comment: A simple way to show that there are infinitely many primitive Pythagorean triples is to construct an infinite family. I think this observation is often made by schoolchildren: for any odd number $k$, the triple $k, \frac{k^2-1}{2}, \frac{k^2+1}{2}$ is a Pythagorean triple. For example, $(3,4,5), (5, 12, 13), (7, 24, 25), (9, 40, 41),\ldots$


How to add a dynamic select field to a content type form?

Question: I would like to add a dynamic select field where options change from time to time. New options will be added along with old options in future. I know i can add form element using hook_form_alter and save values using node api in custom table created using install file of a module.
Is there any inbuilt mechanism where i can create a field and avoid dealing with schema and schema related queries ? My only concern is field should support dynamic options in future... Something like select field values will be pulled using a query.
PS: I hope above questions is not primarily opinion based. I believe many Drupalers might have faced above situation :-) Please do add a comment if form alter approach is the right one !
Comment: Can you explain more how the options will change? Could you perhaps do this with a hierarchical taxonomy?
Comment: Options will be queried from a table.. More like dynamic options.. Let's say at a point of time A1, A2, A3 are the options..  Some other point of time it will be A1, A2, A3, A4 ...
Comment: What is A1,A2,A3,A4? Are they taxonomy terms, nodes or just values? If they are not entities in Drupal it sounds like you need a settings page that holds available values and then through a hook_form_alter you could set the available options in your form element.
Comment: They are just text values :-) Form alter is already in my list as i mentioned in my question.. I am looking for Out of the box solution where i don't need to deal with schema related operations like create/update/delete..
Comment: Have a look at https://api.drupal.org/comment/23028#comment-23028 there a settings page is built where the values are saved in a variable_set(). These values can then be retrieved in variable_get() in your form_alter and set as #options for your form element.
Comment: Check this https://drupal.org/project/entityreference_dynamicselect_widget
Comment: I would suggest to create a new field and pull the data, or create a new entity and use Entity Reference fields for this. You are basically reinventing the Field API with a form alter method.
Answer: You can probably do that using the field API and setting an allowed_values_function for the list field.
e.g:
/**
 * Implements hook_form_alter
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id){

  if ($form_id == 'field_ui_field_settings_form') {
    // Make the allowed_values_function editable as a textfield
    // Possible to inspect $form or $form_state to vary by field
    if(isset($form['field']['settings']['allowed_values_function'])) {
      $form['field']['settings']['allowed_values_function'] = array(
        '#type' => 'textfield',
        '#title' => t('Allowed value function'),
        '#description' => t('Returns an array of allowed values'),
        '#default_value' => $form['field']['settings']['allowed_values']['#field']['allowed_values_function']
      );
    }
  }

}

The allowed_values_function then returns an array of values for the field.
e.g:
/**
 * Allowed values callback
 */
function MYMODULE_custom_field_allowed_values($field){

  if(CONDITION){
    return drupal_map_assoc(array('A1','B1','C1'));
  }elseif(OTHER_CONDITION){
    return drupal_map_assoc(array('A2','B2','C2'));
  }

}

Comment: Great !! Seems like allowed_values_function property should solve the issue.. Also found a relevant tutorial [here](http://www.phase2technology.com/blog/setting-the-allowed-values-function-property-on-text-fields/)


request missing from url

Question: Does htaccess removes request parameters when we place rewrite rules in it?
Answer: No, It just pass the request to next redirecting url.

request missing from url


Question about conditional probability and Baye's formula

Question: I have the following sentence:
If I toss a biased coin with 2/3 chance of landing on heads, given that there was at least one head in 3 flips, what is the probability that there is only 1 head?
If we let $X$ represent the number of heads, then I can use $Baye's$ formula to find out the probability.

Which of the following would be the formula?
$$P(X=1 | X \geq 1)$$
$$P(X \geq 1 | X=1)$$
I think its the first one, but my sheet is saying the second one. I think it might have made a mistake. Which is the right probability?
Comment: Bayes' theorem addresses the problem of inverse probability. This is different from conditional probability.
Comment: Perhaps I'm mixing two concepts, but which would be the right one to choose?
Comment: https://en.wikipedia.org/wiki/Bayes'_theorem I don't think I'm wrong?
Comment: Nope, question still open
Comment: "Which of the following would be the formula?" Obviously, the first one. Additionally, note that the value of the second expression is always 1.
Comment: Yeah, okay my sheet made a mistake then
Answer: Since there is some confusion, let me post some details.
There are $8$ possible outcomes for the three tosses.  As the probabilities for $T,H$ are not the same, these outcomes are not equally probable.
There are seven outcomes that have at least one $H$.  They are $$HHH,HHT,HTH,THH,HTT,THT,TTH$$
The probability that we have at least one $H$ is $$P_{≥1}=1-P(TTT)=1-\left(\frac 13\right)^2=0.962962963$$
How do we compute the conditional probability?  Well, in this case we simply divide the unconditional probability by $P_{≥1}$.  Why?  Well, in general, conditional probability is defined by $$P(A\,|\,B)=\frac {P(A\cap B)}{P(B)}$$ Here $A$ is the event "you get exactly one $H$"  and $B$ is the event "you get at least one $H$".  Of course, in this case $$A\cap B=A\implies P(A\cap B)=P(A)=P(HTT)+P(THT)+P(TTH)$$  Thus our answer is the ratio $$\frac {P(HTT)+P(THT)+P(TTH)}{P_{≥1}}$$
Of course all three of those events, $HTT,THT,TTH$ have the same probability, namely $\left( \frac 13 \right)^2\times \frac 23$.  Thus our numerator is $3\times \left( \frac 13 \right)^2\times \frac 23=\frac 29=.222\cdots$
Finally the answer we seek is $$\frac {.2222\cdots}{0.962962963}=\boxed {0.230769231
}$$
Comment: `mat = replicate(10^6, sample(c(1,0),3,replace=T,prob=c(2/3,1/3))); at_least_one_H = mat[,colSums(mat)>0]; only_one_head = mat[,colSums(mat)==1]; ncol(only_one_head) / ncol(at_least_one_H) [1] 0.230344`
Comment: I was following until you said at the end that the probability for $HTT$, $THT$ and $TTH$ is $(1/3)^3$. It's not a fair coin, and you had calculated it differently in the comments to my answer. Is it a slight of pen?
Comment: @AntoniParellada  There was a typo...which is now corrected (I believe).
Comment: Very nice! +1 Thank you for writing it up.
Comment: Which is $\frac{3}{13}$, as i got, thanks lulu!
Comment: @AntoniParellada  Looks good!  Thanks.


Correct fingering for The Frail

Question: I'm learning to play E-Piano by myself and right now, I'm trying to play the The Frail. I don't have any problems in the first sixteen bars. But at bars 17 and 18 I'm struggling with the correct fingering. Can someone with more experience in playing the piano help me out?
Answer: For bar 17, on the right hand you can use :

4th finger on E
1st finger on G (thumb)
2nd finger on C
4th finger on E

and moving on to bar 18:

5th finger on F
2nd finger on C
1st finger on G

So basically, you can play these two bars without changing the position of your right hand at all.
For your left hand on bar 17 you can use 5th and 1st fingers for the octave and bar 18 you can use your 5th finger on low Eb and 2nd and 1st for the Eb (octave) and F.
Comment: Many thanks for the fast reply. I always tried to press Eb and F simultaneously with my first finger on the right hand, which seemed to be wrong, as I didn't found a way to play Eb and F with my left hand. Hopefully, I can now play this composition.
Answer: As with any piece you may have fingering difficulties, place your hand over all the notes you feel are within that span. Your thumb (r.h.) will look after the lowest note, and with a stretch such as this, which is less than an octave, your pinky could play the highest note. Then look at where your other fingers arre in comparison to the notes needed.
I'm not prescribibg what fingers you use - hat's up to you, and part of the practice of playing something new. But I'm sure you will work out the best fingering (your fingering) for this, and any other piece. Moving laterally when you can already reach most/all the keys isn't a good move.
On bar 20 or 21, looking ahead, you can see there's no note lower than C, so your whole hand can be moved up, using the same span idea, putting your pinky, if you like, on the top B♭. Pinky or ring finger - it's a black key, so ring may reach more easily.
Comment: Many thanks for this generic advice. I'll try to incorporate it into my daily exercises.

Correct fingering for The Frail


Why is my interactive chart not responsive on iOS?

Question: I have a blog post that contains an interactive chart. The chart container is designed to be responsive and works well on Chrome, Firefox and Safari for desktop. However, on iOS devices, it does not load as intended. (See the screenshots for how it looks in portrait and landscape. After trying to troubleshoot this with a developer, I have had no luck figuring out the issue. Anyone have any suggestions as to what I can try next?
Answer: Set this property of your webview:
<code>self.webView.scalesPageToFit = YES;
</code>
Comment: I've been told this is Objective C code and that we need a web solution so this won't help.


Media html not rendering in blocks

Question: I'm experiencing an issue on multiple sites where (image) media aren't appearing in blocks despite working fine in node fields.
I first thought it only happened to me when using the linkicon module, but since then i created a custom block type for image blocks (using entity reference media fields) and the same thing happens, ie. the html renders nothing:

There's no problem rendering the fields in nodes on the same sites using the exact same display settings.
I've checked both the media, block and block_content logs and they show no errors.
My setup:

Drupal 8.9.7
Barrio 5.1.3
Local environment running on ddev
Remote environment running on cloudways

Any ideas what the issue might be?
Answer: This turned out to be a conflict with the songkick module. I'm a maintainer  so I'll make sure the issue is handled and post further updates in the issue cue on Drupal.org here.

Media html not rendering in blocks


Python turtle, using colours from a list

Question: colours =  [turtle.color("red"),turtle.color("blue"),turtle.color("yellow"),turtle.color("green")]

fred = colours[0],turtle.forward(100),turtle.left(90),colours[1],turtle.forward(100),turtle.left(90),colours[2],turtle.forward(100),turtle.left(90),colours[3],turtle.forward(100),turtle.left(90)

Attemping to make a square with 4 different colours from a list, type(colours[0]) returns class Nonetype. How can I access the colours from my list?
Comment: I would seem that `turtle.color("red")` returns `None`?
Comment: It does, type(turtle.color("red")) returns None, but if you enter turtle.color("red") it will change the colour. I thought that using colours[0] should have the same effect, but it accepts the command with no output.
Answer: Your code:
colours =  [turtle.color("red")]
Will run the function turtle.color("red"), and store the return value in the list.
This is exactly the same as doing:
colours =  [None]
If you call colours[0] you get the return value, not the function. Python has no idea if the None ended up there through a function call, or if you just assigned it manually.
You only posted 2 lines of code, so I don't quite know what the context is here, but you may want to do something like:
colours =  [lambda: turtle.color("red"), lambda: turtle.color("blue")]

What this does, is store a lamba (or 'anonymous function') in your list. This function is not executed. You will now get:
>>> colours[0]
<function <lambda> at 0x80089e710>

And you can execute this as many times as you want by appending parenthesis, like so: colours[0]()
This technique is known as 'currying' by the way.
Comment: Thank you very much, that was a nice clear explanation and works perfectly.


AJAX callback on form item generated by AJAX

Question: I'm trying to add AJAX callback to form element that was previously rendered by AJAX but with no luck. Code below.
A bit of description. There are three main methods here:

buildForm - base form
extraField - AJAX callback attached to ['month']
choosePerson - AJAX callback attached to: ['week_day']['hour']

In the buildForm method I create base form with AJAX callback on 'month' select element. In the AJAX callback you can find an extraField method. This method contains form element called 'hour' ($form['week_day']['hour']) and this element renders well. But this element also contains AJAX callback, which doesn't work, it does not generate 'person_container' element and the 'person' select.
Any idea how to ajaxify elements that previously were rendered by ajax?
class ReservationForm extends FormBase {

  public function getFormId() {
    return 'reservation_form';
  }

  public function buildForm(array $form, FormStateInterface $form_state) {

    $form['month'] = array(
      '#type' => 'select',
      '#title' => $this->t('Select month'),
      '#options' => array($this->t('January'), $this->t('February'), $this->t('March')),
      '#ajax' => array(
        'callback' => array($this, 'extraField'),
        'event' => 'change',
        'wrapper' => 'week-day',
      ),
    );

    // Disable caching on this form.
    $form_state->setCached(FALSE);

    $form['week_day'] = [
      '#type' => 'container',
      '#attributes' => ['id' => 'week-day'],
    ];
  }

  public function extraField(array &$form, FormStateInterface $form_state) {
    $month = $form_state->getValue('month');

    $hour_options = array();

    if ($month == '0') {
      $hour_options[0] = $this->t('08:00');
      $hour_options[1] = $this->t('09:00');
      $hour_options[2] = $this->t('10:00');
    }

    if ($month == '1') {
      $hour_options[0] = $this->t('12:00');
      $hour_options[1] = $this->t('13:00');
      $hour_options[2] = $this->t('14:00');
    }

    if ($month == '2') {
      $hour_options[0] = $this->t('18:00');
      $hour_options[1] = $this->t('19:00');
      $hour_options[2] = $this->t('20:00');
    }

    $form['week_day']['hour'] = array(
      '#type' => 'select',
      '#title' => $this->t('Choose hours @month', array('@month' => $month)),
      '#options' => $hour_options,
      '#ajax' => array(
        // tried with that callback too: [ $this, 'choosePerson']
        'callback' => array($this, 'choosePerson'),
        'event' => 'change',
        'wrapper' => 'person',
      ),
    );

    $form['week_day']['person_container'] = array(
      '#type' => 'container',
      '#attributes' => ['id' => 'person-container'],
    );

    $form['week_day']['person_container']['person'] = array(
      '#type' => 'select',
      '#title' => $this->t('Choose person'),
      '#options' => ['John', 'Sarah', 'Peter'],
    );

    return $form['week_day'];
  }

  public function choosePerson(array &$form, FormStateInterface $form_state) {
    $form['week_day']['person_container']['person'] = array(
      '#type' => 'select',
      '#title' => $this->t('Choose person'),
      '#options' => ['John', 'Sarah', 'Peter'],
    );

   return $form['week_day']['person_container'];
  }
}

Comment: @Wolf, there are hundreds of these questions on DA, you just picked one. Not all are answered, because there are so many. You can't build form elements in an ajax callback. See [Ajax Forms in Drupal 7](https://www.drupal.org/docs/7/api/javascript-api/ajax-forms-in-drupal-7), which is still valid for D8.
Comment: I have the same problem, is there a solution for that?
Comment: Thank you, for the link, now I got it. I will post the right solution in an answer.
Comment: @schneidolf can you share the link for the answer where you've shared your findings?
Answer: The Link 4k4 posted in the discussion of the question gives the solution:

Create a callback function (named by the #ajax['callback']). This is generally a very simple function which does nothing but select and return the portion of the form that is to be replaced on the original page. Note, that as part of the Form APIs security system, you cannot create new form elements in the callback function, as they will throw errors upon submission, and any #ajax on elements created in the callback will also not work. If you need to create new elements on ajax submit, they must be added in the form definition. You can use the values in $form_state to determine whether the form build process is the initial form load, or an #ajax initiated load.

So the following code example is working.
class ReservationForm extends FormBase {

  public function getFormId() {
    return 'reservation_form';
  }

  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['month'] = [
      '#type' => 'select',
      '#title' => $this->t('Select month'),
      '#options' => [
        $this->t('January'),
        $this->t('February'),
        $this->t('March'),
      ],
      '#ajax' => [
        'callback' => [$this, 'extraField'],
        'event' => 'change',
        'wrapper' => 'week-day',
      ],
    ];

    // Disable caching on this form.
    $form_state->setCached(FALSE);

    $form['week_day'] = [
      '#type' => 'container',
      '#attributes' => ['id' => 'week-day'],
    ];

    if ($form_state->getUserInput()['_triggering_element_name'] == 'month') {
      $month = $form_state->getValue('month');
      $hour_options = [];

      if ($month == '0') {
        $hour_options[0] = $this->t('08:00');
        $hour_options[1] = $this->t('09:00');
        $hour_options[2] = $this->t('10:00');
      }

      if ($month == '1') {
        $hour_options[0] = $this->t('12:00');
        $hour_options[1] = $this->t('13:00');
        $hour_options[2] = $this->t('14:00');
      }

      if ($month == '2') {
        $hour_options[0] = $this->t('18:00');
        $hour_options[1] = $this->t('19:00');
        $hour_options[2] = $this->t('20:00');
      }

      $form['week_day']['hour'] = [
        '#type' => 'select',
        '#title' => $this->t('Choose hours @month', ['@month' => $month]),
        '#options' => $hour_options,
        '#ajax' => [
          'callback' => [$this, 'choosePerson'],
          'event' => 'change',
          'wrapper' => 'person-container',
        ],
      ];

      $form['week_day']['person_container'] = [
        '#type' => 'container',
        '#attributes' => ['id' => 'person-container'],
      ];

      $form['week_day']['person_container']['person'] = [
        '#type' => 'select',
        '#title' => $this->t('Choose person'),
        '#options' => ['John', 'Sarah', 'Peter'],
      ];
    }

    if ($form_state->getUserInput()['_triggering_element_name'] == 'hour') {
      $form['week_day']['person_container']['person'] = [
        '#type' => 'select',
        '#title' => $this->t('Choose person'),
        '#options' => ['Hans', 'Frank', 'Emma'],
      ];
    }

    return $form;
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {
  }

  public function extraField(array &$form, FormStateInterface $form_state) {
    return $form['week_day'];
  }

  public function choosePerson(array &$form, FormStateInterface $form_state) {
    return $form['week_day']['person_container'];
  }

}

Comment: Ok - my answer lacked the callback and show hide part. Was a quicky ;)
Comment: For the triggering element name see https://drupal.stackexchange.com/a/223290/47547
Comment: This is almost working for me. The only problem was the week_day field is not updated with new value. But on the xhr it return correct html, the selector was empty. What did I miss?
Comment: I forgot to make the callback function as static, but the problem now is I can't submit the form, it always return 'The value you selected is not a valid choice.' error.
Answer: You can't change elements on callback or validateForm(), you need to put it on buildForm() method.
Here is a full example:
    /method buildForm
    $result = \Drupal\my_module\Controller\Contaminante::list(); //database logic
    foreach ($result as $it){
        $arrSelectContaminantes[$it["id_contaminante"]] = t($it["descripcion"]);
    }

    $form['select_contaminantes'] = array(
        '#type' => 'select',
        '#options' => $arrSelectContaminantes,
        '#ajax' => [
            'callback' => '::seleccionContaminantes',
            'disable-refocus' => false,
            'event' => 'change',
            'wrapper' => 'el-select-estaciones',
            'method' => 'replaceWith'
        ]
    );

    $selected_value = $form_state->getValue('select_contaminantes');
    $opciones = array();

    if(isset(selected_value)){
         $resultado;
         if($form_state->getValue("select_contaminantes") != 0){
            $opciones["0"] = t("ALL");
            $resultado = \Drupal\montar_mapa\Controller\Estacion::lista($form_state->getValue("select_contaminantes")); //DB LOGIC
        }else{
            $resultado = \Drupal\montar_mapa\Controller\Estacion::lista(); //DB LOGIC
        }

        foreach ($resultado as $it){
            $opciones[$it["id"]] = t($it["nombre"]);
        }
    }

    $form['select_estaciones'] = array(
        '#type' => 'select',
        '#id' => "el-select-estaciones",
        '#options' => $opciones,
        '#empty_option' => $this->t('-Select contaminante first'),
        '#validated' => TRUE,
    );

Really important:
Each time you print the dependent field ($form['select_estaciones') in example), must be validated ('#validated' => TRUE in options)
You need to compare the selected value of triggering field ($form['select_contaminante] in example) if is null or not, if you compare directly, in case you get 0 value, interpretates as "no selection".


Difficulty booting HPE server via PXE in UEFI mode

Question: We have some HPE ProLiant blade servers, Gen9, which we would like to network boot to install CentOS.
We are using Cobbler to produce a configuration.
At boot time, the server will request a file named for its UUID, which fails.  It then asks by MAC, which succeeds.  It loads GRUB from a .efi file and GRUB is able to present a boot menu.
When we select the only option from the boot menu, it advances to a blank screen and . . . does nothing.
By looking at the Cobbler server's logs, I can see that the server is requesting vmlinuz and, as far as I can see, it completely retrieves the file, but what I do not see is it ever downloading initrd.img.
I've tried playing with the GRUB config, but not found the right magic yet.
Has anyone else encountered this problem, and, if so, can you share what you did to get past it?
It is worth noting that when we try a legacy BIOS boot rather than UEFI, it works fine.  I am aware that it pulls down a different set of files for that, but I wanted to mention this because it indicates that there is nothing wrong with the target server, the TFTP service on the Cobbler server, or the network between them.  We don't want to use this as a workaround, though, because BIOS is not going to be around forever.
Comment: FWIW I ended up using https://ipxe.org when netbooting UEFI systems (Oracle/Sun X7)
Comment: I appreciate the link, but unfortunately, this is an enterprise system and needs to be stock.
Comment: ipxe is only used on the network install server, the resulting install on the server itself is not affected.
Comment: Yes, but I would have to flash this not-stock firmware onto the server.  The firmware must be stock.
Comment: Again, no; it's a bit of code that gets loaded via uefi network boot and bootstraps the rest of the install. No trace is left behind on the server.
Comment: Alright, I have gone this route within the context of Cobbler.  Here's what happens:  Server loads iPXE, and as soon as it loads it, goes to the System Utilities menu within the server's firmware.  This leads me to think that it's crashing as soon as it loads?
Answer: The winning solution was to move to GRUB2 from GRUB Legacy (0.97).
There is a straight-line distance of about 120 miles between the DC where the server being booted is located, and the one where the TFTP/DHCP server is located.  This necessarily causes some latency.  Since TFTP is a non-windowing protocol, a packet has to be acknowledged before the next one is sent.  By extension, if the packets are larger, the overall transfer will take less time, assuming everything works well.
GRUB Legacy imposed a timeout of five minutes and a packet size of 512 bytes.  GRUB2 uses a packet size of 1024 bytes and didn't time out.  It took about 14 minutes for the server to boot.
Legacy-mode boot worked because the server then uses Syslinux rather than GRUB.
The downside is that the configuration is created using Cobbler.  No currently-released version of Cobbler supports GRUB2, so I had to create a script that would modify the dhcpd.conf file after Cobbler was done building it, and to create a suitable grub.cfg-01-${mac_address} file.


Compensa usar Assembly, C e C++ num mesmo programa?

Question: Para otimizar e deixar o programa mais rápido, haveria utilidade ou necessidade de eu fazer tudo o que puder em Assembly, o que não puder fazer Assembly, faço em C, e o que não puder fazer em C faço em C++?
Referências:

https://isocpp.org/wiki/faq/mixing-c-and-cpp#overview-mixing-langs
https://arne-mertz.de/2018/10/calling-cpp-code-from-c-with-extern-c/
Comment: Em casos muito, mas muito (mas muito (...)) específico compensa. Em 99.9% dos casos compensa rever o algoritmo ou a forma que implementou em C++. Para garantir que a linguagem seja um gargalo você precisa garantir que foi bem feito antes. Para garantir que deixará de ser um gargalo em outra linguagem você precisará garantir que será bem feito nela. Na grande maioria das vezes o seu resultado em Assembly não será melhor do que do compilador, então será tempo perdido.
Answer: Quase tudo o que é feito em Assembly fica mais lento que feito em C e C++. É possível fazer mais rápido, mas é muito difícil e isto acontece menos do que as pessoas imaginam.
Na verdade só pessoas ingênuas acreditam nisso e são as que menos poderão fazer o Assembly ser rápido. É verdade que essa ingenuidade fará a pessoa produzir códigos ruins em C ou C++ também.
Para programar bem nessas linguagens é preciso domínio muito grande da computação, elas não são mágicas e qualquer coisa que você fizer deixa tudo rápido, elas podem ser rápidas porque permitem fazer códigos complicados, difíceis e que podem alcançar uma ótima velocidade se tudo estiver certo.
Algumas linguagens não dão esse poder todo, mas também pode facilitar algumas coisas. Já vi C# ser mais rápido que C++ e depois a pessoas que escreveu o código em C++ ir melhorando até conseguir bater o mesmo código em C#. Em C++ levou dias pra criar um código ligeiramente mais rápido, em C# levou minutos, e hoje talvez ele seja mais rápido, na época o compilador e biblioteca do C# era muito ruim, do C++ era boa.
É frequente programadores conseguiram mais velocidade com C# ou até Java fazendo código de forma simples comparado com o que elas fariam em C ou C++ ou mais ainda em Assembly, sem falar na produtividade. Você não conseguirá boa velocidade em linguagens de script a não ser que compare com um código muito ruim em C/C++, mesmo isso não é fácil, precisar se esforçar.
Answer: Assembly de fato, em tempo de execução, é mais rápido. Porém  é custoso no desenvolvimento e complexo em implementação / manutenção sem contar que seu código fica preso na arquitetura do hardware. Por tanto, dependendo da aplicação, qualquer outra linguagem, compilada ou interpretada será mais rápida. Imagina implementar uma consulta a banco de dados em assembly?
Mas quando falamos de processamento digital de sinais ou desenvolvimento de drivers, assembly pode ser uma solução, uma vez que desejamos no meio de um código C/C++ acessar um periférico ou acessar uma instrução do processador digital de sinais. Contudo não é todo dia que se usa esse tipo de tecnologia e vale lembrar que os compiladores estão cada vez mais otimizados para gerar o código de máquina mais eficiente que o escrito em assembly.


SSH daemon fails to run

Question: On my Linux machine, I have services enabled for SSH. However, whenever /usr/sbin/sshd is init, it fails to daemonize. No sshd.pid file is generated under /var/run and sshd is not running when I do a 'ps'.
The strange thing is that when I run sshd in non-daemon mode (ie. '/usr/sbin/sshd -D') or if I run it in debug mode (ie. 'usr/sbin/sshd -d'), sshd is able to run and sshd.pid file is generated under /var/run.
I've also verified that default port 22 is available and not being used by another process. Also, when I try different ports, I observe the same behavior detailed above.
Any idea why this might be happening?
Thanks
Comment: Have you looked at the logs?
Comment: Yes, unfortunately, the logs are not showing any useful info on why this is happening
Answer: Can I ask what you see if you do:
<code> /usr/sbin/sshd -p 10022 -d
</code>
What that will do is start a brand new sshd on port 100222 in debug mode (remaining in the foreground). This is one from my system where it has started ok:
<code>This is the output I see from a working one:
debug1: sshd version OpenSSH_7.4, OpenSSL 1.0.2k-fips  26 Jan 2017
debug1: private host key #0: ssh-rsa SHA256:MSjzB8S5CxN8QBBis8FWehZT66qV0IgUT1ayBjUxRJc
debug1: private host key #1: ecdsa-sha2-nistp256 SHA256:rc8cgnqJVCdab+vzUZMlGxr9a9R9Bq9kv+VsMitLpjE
debug1: private host key #2: ssh-ed25519 SHA256:c1TzuNsEHvgqObVuKe1E5Km9pYDg76yqeZzZim3XJWI
debug1: rexec_argv[0]='/usr/sbin/sshd'
debug1: rexec_argv[1]='-p'
debug1: rexec_argv[2]='10022'
debug1: rexec_argv[3]='-d'
debug1: Set /proc/self/oom_score_adj from 0 to -1000
debug1: Bind to port 10022 on 0.0.0.0.
Server listening on 0.0.0.0 port 10022.
debug1: Bind to port 10022 on ::.
Server listening on :: port 10022.
</code>
If you could run the above and post the output it might reveal more about what is not working.
Comment: This works and I see what you are seeing. I've actually narrowed down to the daemon() function in the sshd code that is not returning for some reason.
Comment: Can you run it under ```strace -f ``? fromt the command line?

SSH daemon fails to run


Como usar herança e polimorfismo ao passar um JSON para um Controller MVC C#?

Question: Possuo um método MVC que recebe uma classe cliente como parâmetro:
      public async Task<ActionResult> Cadastrar(cliente model)
      {
      }

Acontece que essa classe tem dois filhos, uma classe chamada pessoa.
e outra classe chamada empresa que também herda de cliente.
Gostaria de saber se é possível (e como) eu faço para passar um JSON
genérico para esse método? podendo tanto ser um objeto PESSOA como um objeto EMPRESA. Um polimorfismo mesmo.
Já tentei passar objeto pessoa ou empresa e não deu certo.
mas se coloco pessoa ou empresa no lugar de cliente e passo o JSON recebo
normalmente os dados.
Answer: Basicamente, usando um Model Binder escrito por você e um pouco de Reflection:
public class ClienteModelBinder : DefaultModelBinder
{
    protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
    {
        var tipoString = bindingContext.ValueProvider.GetValue(bindingContext.ModelName + ".Tipo");
        var tipo = Type.GetType(
            (string)tipoString.ConvertTo(typeof(string)),
            true
        );

        var model = Activator.CreateInstance(type);
        bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, tipo);
        return model;
    }
}

No evento Application_Start do seu Global.asax.cs, registre seu Model Binder:
protected void Application_Start()
{
    ModelBinders.Binders.Add(typeof(Cliente), new ClienteModelBinder());
}

No form ou no JSON, você precisará passar um campo Tipo para que o Model Binder saiba o que está sendo passado:
@Html.Hidden("Tipo", Model.GetType())

Ou:
{ 'Tipo': 'Pessoa' }

Ou ainda, você pode testar outra coisa. Por exemplo, se o valor passado tem definido um CPF ou CNPJ, ou ainda um nome ou uma razão social, aí não precisa de um campo Tipo no form ou no JSON:
var cpf = bindingContext.ValueProvider.GetValue(bindingContext.ModelName + ".Cpf");
if (cpf != null)
{
    /* É Pessoa Física */
    var model = Activator.CreateInstance(typeof(Pessoa));
    bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, typeof(Pessoa));
    return model;
}

Comment: valeu, testando aqui agora


Generics with nested maps

Question: Currently I am using some code like this:
package hello

type object map[string]interface{}

func (o object) get(key string) object {
   val, _ := o[key].(object)
   return val
}

func (o object) getInt(key string) int {
   val, _ := o[key].(int)
   return val
}

but the issue is, I have to write a function for every type I want to return. I
tried using something like this:
package hello

type object map[string]interface{}

// syntax error: method must have no type parameters
func (o object) get[T object|int](key string) T {
   val, _ := o[key].(T)
   return val
}

then I did this:
package hello

type object map[string]interface{}

type token[T object|int] struct {
   in object
   out T
}

func (t token[T]) get(key string) token[T] {
   t.out, _ = t.in[key].(T)
   return t
}

which compiles, but since in never gets updated, I don't think I could do chaining, for a nested map:
something.get("one").get("two").get("three")

Is it possible to do something with generics, to give a similar result to my original code, but without having the copy paste functions?
Comment: @blackgreen it can be many levels, not a specific number. I was thinking about it some more, I don't think you can do it with one function, but maybe with two. One to move through the maps, one to output/convert
Comment: @blackgreen I think I figured it out, see answer. If you have any other option, let me know
Answer: I think I figured it out. You can create a wrapper type, that holds the current
object, as well as the output value. If anyone has other ideas, I am interested
in them as well:
package main

type object map[string]interface{}

type token[T any] struct {
   object
   value T
}

func newToken[T any](m object) token[T] {
   return token[T]{object: m}
}

func (t token[T]) get(key string) token[T] {
   switch val := t.object[key].(type) {
   case object:
      t.object = val
   case T:
      t.value = val
   }
   return t
}

Example:
package main

func main() {
   obj := object{
      "one": object{
         "two": object{"three": 3},
      },
   }
   three := newToken[int](obj).get("one").get("two").get("three")
   println(three.value == 3)
}

Generics with nested maps


Showing $d\pi$ is non-zero in module of Kähler differentials

Question: While reading about Kähler differentials I came across the seemingly innocent statement that $d\pi \in \Omega_{\mathbb{R/Q}}$ in non-zero. This is kind of "obvious" as if $\alpha$ is algebraic then there is a simple way of showing $d\alpha=0$ which fails if $\alpha$ is transcendental.
To actually prove $d\pi \neq 0$ though seems quite tricky, I imagine we must use the universal property of $\Omega_{\mathbb{R/Q}}$ somewhere, but how I have no idea.
Any ideas would be much appreciated.
Comment: Well $\Omega_{\mathbb{R/Q}}$ is defined by taking the free $\mathbb{R}$-module with generators just formal symbols $d\alpha$ (one for each real number $\alpha$), then taking the quotient by the submodule with generators such as $d(st)-sdt-tds$ (as is described in the link you gave). So to say $d\pi \neq 0$ is to say $d\pi$ does not lie in this submodule, which is hard to show directly, but by the universal property it is enough to show we can find an $\mathbb{R}$-module $M$ with derivation $\delta$ say such that $\delta \pi \neq 0$, though this is still hard to do, hence my question.
Comment: I'm totally new to this topic, so my question might be stupid. When I read [the definition](https://en.wikipedia.org/wiki/K%C3%A4hler_differential#Definition_using_derivations) I see nothing that hinders the derivation $d$ to be just the zero map, i.e. $ds=0$ for all $s \in S.$ In this case you would have $d\pi=0.$ But I guess that you are considering non-trivial cases or that there is something more in the definition that I am missing.
Answer: The general fact you're looking for is that if $E/F$ is a field extension and $t_1,\cdots,t_n$ is a transcendence basis for $E$ over $F$ (not necessarily finite), then $dt_i$ are a basis for $\Omega_{E/F}$. All the facts necessary for this should be in your favorite commutative algebra textbook, and I'll sketch the proof below:

$\Omega_{k[x_1,\cdots,x_n]/k}$ is free on $dx_i$. This follows from Yoneda and the product rule: we can arbitrarily assign any value to all the $dx_i$ and that determines a derivation. Note that there is no reason to restrict to finite $n$ here.
$\Omega$ commutes with localization. This lets us pass from $k[x_1,\cdots,x_n]/k$ to $k(x_1,\cdots,x_n)/k$, and see that $\Omega$ is still free on the $dx_i$.
$\Omega$ plays well with algebraic field extensions, ie if $E/F/k$ is a tower of field extensions with $E/F$ algebraic, then $E\otimes_k \Omega_{F/k} \to \Omega_{E/k}$ is an isomorphism. This can be proven from the first exact sequence: one treats the case of a finite extension using the theorem of the primitive element, and then uses the fact that every algebraic field extension is the colimit of it's finite subextensions to get the result.
So if we set up a tower $\Bbb R/\Bbb Q^{tr}/\Bbb Q$ where $\Bbb Q^{tr}$ is a maximal purely transcendental subextension of $\Bbb R/\Bbb Q$ chosen so that $\pi$ is in it's transcendence basis over $\Bbb Q$, we see the result we were after.
Comment: Thanks, this is a lovely "Grothendieck-style" proof.


Finding why there is no solution or why there is only one

Question: The given function is $$ f(x) = \frac{x^2 -5x+4}{x-3} $$
Part A of the question where the domain is $(3, \infty)$  $f(x)$ = inverse function of $x$ has no real solution ( according to the book) however the function and its inverse actually do intersect once.
meanwhile part b the domain is $(-\infty,3)$ and the function of its inverse intersect twice when plotted but according to the book there is only one solution.
Am I wrong tp think that there is a huge error in these questions or am I interpreting the question wrong?
Comment: Did you consider that the $x$-values of the intersection points have to be in the domain ? It would be helpful, if you would mention the approximate positions of the intersections.
Comment: Not sure whether this idea is correct, but don't we just need the fix-points of $f(x)$ ? In this case, the only solution would be $x=2$, approving the result in the book.
Answer: You have to look at the inverse in the domain where they are defined.
For $x>3$ the inverse is $g(x)=\dfrac{1}{2} \left(\sqrt{x^2-2 x+9}+x+5\right)$
And $f(x) = \dfrac{x^2 -5x+4}{x-3}$ intersects $g(x)$ at $x=4 - \sqrt 2\approx 2.59<3$
So they don't intersect.
For $x<3$ the inverse is $h(x)=\dfrac{1}{2} \left(x+5-\sqrt{x^2-2 x+9}\right)$
which intersects $f(x)$ at $x=2$. The other intersection is $x=4+\sqrt 2\approx 5.41>3$
Thus they intersect only once.
Hope this helps


Sistema não adiciona e edita, somente visualiza

Question: Estou com problemas num sistema de cadastro de marcas.
O sistema está visualizando as marcas corretamente, porém não edita nem inclui novas marcas, somente recarrega a pagina.
models>marcas_model.php
<?php
class Marcas_model extends CI_Model {

    function __construct() {
        parent::__construct();
    }

    function get($table,$fields,$where='',$perpage=0,$start=0,$one=false,$array='array'){

        $this->db->select($fields);
        $this->db->from($table);
        $this->db->order_by('idMarcas','desc');
        $this->db->limit($perpage,$start);
        if($where){
            $this->db->where($where);
        }

        $query = $this->db->get();

        $result =  !$one  ? $query->result() : $query->row();
        return $result;
    }

    function getById($id){
        $this->db->where('idMarcas',$id);
        $this->db->limit(1);
        return $this->db->get('marcas')->row();
    }

    function add($table,$data){
        $this->db->insert($table, $data);
        if ($this->db->affected_rows() == '1')
        {
            return TRUE;
        }

        return FALSE;
    }

    function edit($table,$data,$fieldID,$ID){
        $this->db->where($fieldID,$ID);
        $this->db->update($table, $data);

        if ($this->db->affected_rows() >= 0)
        {
            return TRUE;
        }

        return FALSE;
    }

    function delete($table,$fieldID,$ID){
        $this->db->where($fieldID,$ID);
        $this->db->delete($table);
        if ($this->db->affected_rows() == '1')
        {
            return TRUE;
        }

        return FALSE;
    }

    function count($table){
        return $this->db->count_all($table);
    }}

**controllers>marcas.php**
<?php

class Marcas extends CI_Controller {

    function __construct() {
        parent::__construct();
        if ((!$this->session->userdata('session_id')) || (!$this->session->userdata('logado'))) {
            redirect('mapos/login');
        }

        $this->load->helper(array('form', 'codegen_helper'));
        $this->load->model('marcas_model', '', TRUE);
        //$this->data['menuMarcas'] = 'Marcas';
    }

    function index(){
        $this->gerenciar();
    }

    function gerenciar(){

        if(!$this->permission->checkPermission($this->session->userdata('permissao'),'aServico')){
           $this->session->set_flashdata('error','Você não tem permissão para visualizar serviços.');
           redirect(base_url());
        }

        $this->load->library('pagination');

        $config['base_url'] = base_url().'index.php/marcas/gerenciar/';
        $config['total_rows'] = $this->marcas_model->count('marcas');
        $config['per_page'] = 10;
        $config['next_link'] = 'Próxima';
        $config['prev_link'] = 'Anterior';
        $config['full_tag_open'] = '

';
        $config['full_tag_close'] = '

';
        $config['num_tag_open'] = '
';
        $config['num_tag_close'] = '
';
        $config['cur_tag_open'] = '
';
        $config['cur_tag_close'] = '
';
        $config['prev_tag_open'] = '
';
        $config['prev_tag_close'] = '
';
        $config['next_tag_open'] = '
';
        $config['next_tag_close'] = '
';
        $config['first_link'] = 'Primeira';
        $config['last_link'] = 'Última';
        $config['first_tag_open'] = '
';
        $config['first_tag_close'] = '
';
        $config['last_tag_open'] = '
';
        $config['last_tag_close'] = '
';

        $this->pagination->initialize($config);

        $this->data['results'] = $this->marcas_model->get('marcas','idMarcas,nome,descricao,preco','',$config['per_page'],$this->uri->segment(3));

        $this->data['view'] = 'marcas/marcas';
        $this->load->view('tema/topo',$this->data);

    }

    function adicionar() {
        if(!$this->permission->checkPermission($this->session->userdata('permissao'),'aServico')){
           $this->session->set_flashdata('error','Você não tem permissão para adicionar serviços.');
           redirect(base_url());
        }

        $this->load->library('form_validation');
        $this->data['custom_error'] = '';

        if ($this->form_validation->run('marcas') == false) {
            $this->data['custom_error'] = (validation_errors() ? '
' . validation_errors() . '
' : false);
        } else {
            $preco = $this->input->post('preco');
            $preco = str_replace(",","", $preco);

            $data = array(
                'nome' => set_value('nome'),
                'descricao' => set_value('descricao'),
                'preco' => $preco,
            );

            if ($this->marcas_model->add('marcas', $data) == TRUE) {
                $this->session->set_flashdata('success', 'Serviço adicionado com sucesso!');
                redirect(base_url() . 'index.php/marcas/adicionar/');
            } else {
                $this->data['custom_error'] = '

Ocorreu um erro.

';
            }
        }
        $this->data['view'] = 'marcas/adicionarMarca';
        $this->load->view('tema/topo', $this->data);

    }

    function editar() {
        if(!$this->permission->checkPermission($this->session->userdata('permissao'),'eServico')){
           $this->session->set_flashdata('error','Você não tem permissão para editar serviços.');
           redirect(base_url());
        }
        $this->load->library('form_validation');
        $this->data['custom_error'] = '';

        if ($this->form_validation->run('marcas') == false) {
            $this->data['custom_error'] = (validation_errors() ? '
' . validation_errors() .'
' : false);
        } else {
            $preco = $this->input->post('preco');
            $preco = str_replace(",","", $preco);
            $data = array(
                'nome' => $this->input->post('nome'),
                'descricao' => $this->input->post('descricao'),
                'preco' => $preco,
            );

            if ($this->marcas_model->edit('marcas', $data, 'idMarcas', $this->input->post('idMarcas')) == TRUE) {
                $this->session->set_flashdata('success', 'Serviço editado com sucesso!');
                redirect(base_url() . 'index.php/marcas/editar/'.$this->input->post('idMarcas'));
            } else {
                $this->data['custom_error'] = '

Ocorreu um errro.

';
            }
        }

        $this->data['result'] = $this->marcas_model->getById($this->uri->segment(3));

        $this->data['view'] = 'marcas/editarMarca';
        $this->load->view('tema/topo', $this->data);

    }

    function excluir(){

        if(!$this->permission->checkPermission($this->session->userdata('permissao'),'eServico')){
           $this->session->set_flashdata('error','Você não tem permissão para excluir serviços.');
           redirect(base_url());
        }

        $id =  $this->input->post('id');
        if ($id == null){

            $this->session->set_flashdata('error','Erro ao tentar excluir serviço.');
            redirect(base_url().'index.php/marcas/gerenciar/');
        }

        /*$this->db->where('marcas_id', $id);
        $this->db->delete('marcas_os');*/

        $this->marcas_model->delete('marcas','idMarcas',$id);

        $this->session->set_flashdata('success','Serviço excluido com sucesso!');
        redirect(base_url().'index.php/marcas/gerenciar/');
    }
}

views>marcas>marcas.php
   <?php if($this->permission->checkPermission($this->session->userdata('permissao'),'aServico')){ ?>
        <a href="<?php echo base_url()?>index.php/marcas/adicionar" class="btn btn-success"> Adicionar Marca
    <?php } ?>

    <?php

    if(!$results){?>

Marcas

                #
                Nome
                Preço
                Descrição

                Nenhuma Marca Cadastrado

    <?php }
    else{ ?>

Marcas

                #
                Nome
                Descrição
                Preço

            <?php foreach ($results as $r) {
                echo '
';
                echo ''.$r->idMarcas.'	';
                echo ''.$r->nome.'	';
                echo ''.number_format($r->preco,2,',','.').'	';
                echo ''.$r->descricao.'	';
                echo '';
                if($this->permission->checkPermission($this->session->userdata('permissao'),'aServico')){
                    echo 'idMarcas.'" class="btn btn-info tip-top" title="Editar Serviço">';
                }
                if($this->permission->checkPermission($this->session->userdata('permissao'),'aServico')){
                    echo 'idMarcas.'" class="btn btn-danger tip-top" title="Excluir Serviço">  ';
                }

                echo '	';
                echo '
';
            }?>

    <?php echo $this->pagination->create_links();} ?>

      <form action="<?php echo base_url() ?>index.php/marcas/excluir" method="post" >

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

Excluir Serviço

        <input type="hidden" id="idMarca" name="id" value="" />

Deseja realmente excluir este serviço?

        <button class="btn" data-dismiss="modal" aria-hidden="true">Cancelar</button>
        <button class="btn btn-danger">Excluir</button>

      </form>

adicionarMarca.php

Cadastro de Marca

                <?php echo $custom_error; ?>
                <form action="<?php echo current_url();?>" id="formMarca" method="post" class="form-horizontal" >

                        Nome*

                            <input id="nome" type="text" name="nome" value="<?php echo set_value('nome'); ?>"  />

                        Preço*

                            <input id="preco" class="money" type="text" name="preco" value="<?php echo set_value('preco'); ?>"  />

                        Descrição

                            <input id="descricao" type="text" name="descricao" value="<?php echo set_value('descricao'); ?>"  />

                                <button type="submit" class="btn btn-success"> Adicionar</button>
                                <a href="<?php echo base_url() ?>index.php/marcas" id="btnAdicionar" class="btn"> Voltar

                </form>

editarMarca.php

Editar Serviço

                                                <?php echo $custom_error; ?>
                                                <form action="<?php echo current_url(); ?>" id="formMarca" method="post" class="form-horizontal" >
                                                    <?php echo form_hidden('idMarcas',$result->idMarcas) ?>

                                                            Nome*

                                                                  <input id="nome" type="text" name="nome" value="<?php echo $result->nome ?>"  />

                                                            Preço*

                                                                <input id="preco" class="money" type="text" name="preco" value="<?php echo $result->preco ?>"  />

                                                            Descrição

                                                                  <input id="descricao" type="text" name="descricao" value="<?php echo $result->descricao ?>"  />

                                                            <button type="submit" class="btn btn-primary"> Alterar</button>
                                                            <a href="<?php echo base_url()?>index.php/marcas" id="btnAdicionar" class="btn"> Voltar

                                                </form>

Comment: Chegou a realizar o debug do submit desses formulários para ver se está chegando na aplicação e como está chegando?
Comment: @Bruno Rigolon Inclui essa linha no controller e os valores digitados foram retornados corretamente

        //inicio
  if(isset($_POST['nome'])){echo "VERIFICANDO OK: - ".$_POST['nome'];}else {echo "ERRO";}
  if(isset($_POST['preco'])){echo "VERIFICANDO OK: - ".$_POST['preco'];}else {echo "ERRO";}
  if(isset($_POST['descricao'])){echo "VERIFICANDO OK: - ".$_POST['descricao'];}else {echo "ERRO";}
//fim
Answer: Tente fazer esta alteração, veja se vai inserir os registros.
// Arquivo
# models>marcas_model.php

// Altere isto (function adicionar)
$data = array(
    'nome' => set_value('nome'),
    'descricao' => set_value('descricao'),
    'preco' => $preco,
);

// Para isso
$data = array(
    'nome' => $this->input->post('nome'),
    'descricao' => this->input->post('descricao'),
    'preco' => $preco,
);

Answer: @Bruno Rigolon
Obrigado pela resposta, mas o problema não estava nesse ponto. Porém analisando o código logo abaixo descobri o problema.
if ($this->form_validation->run('marcas') == false)

Acabei esquecendo de incluir a tabela "marcas" no form_validation.
Agradeço a atenção!


SwiftUI: Issue with longer text in TextField on macOS

Question: When I enter (or paste) text in a TextField on macOS and the string requires more space than available in TextField I would expect some sort of scrolling behaviour that moves along with the text cursor - like in almost every text field in the world. Instead I only see the beginning of the text and can't see my new input anymore. I cannot even scroll manually. Only if I enlarge the TextField and then shrink it again, I am able to scroll through it. See video:

Is this a SwiftUI bug? Any known solutions for this?
Here's the code:
struct ContentView: View {
    @State private var text: String = ""
    var body: some View {
        TextField("", text: $text)
            .padding()
    }
}

Comment: Unfortunately not. Kinda hope Apple will fix this with the release of macOS Ventura (have not tested this with the beta yet though).
Comment: I have not upgraded to MacOS 13 yet, but [the TextField documentation](https://developer.apple.com/documentation/swiftui/textfield) mentions some new initializers for "Creating a Scrollable Text Field". Hopefully while working on the new API, they also caught and fixed this MacOS bug.
Comment: CNR. Needed MRE to debug.
Comment: I can reproduce this but I have no idea how it can be fixed.
Comment: it's definitely a bug.
Comment: you could try adding `.scaledToFill()`, it does some sort of scrolling, but it may not be what you are looking for. Also you could try `.fixedSize()` and a frame
Comment: Have you found a solution?
Comment: Maybe try a horizontal scroll view? I have no idea.
Answer: Yes, this seems to be a bug. I could reproduce it in 12.0 and 12.5 but Ventura beta release behaves much better.


Error in final launch sequence Failed to execute MI command -gdb-set target-async off

Question: I have two projects on eclipse, one produces an so and the other is Android application which uses it I am trying to debug the native code in the so using this guide.

I set my application debuggable
I started my application in the debug mode
I run ndk-gdb

When I run the native debugger I am getting:
Error in final launch sequence
Failed to execute MI command:
-gdb-set target-async off
Error message from debugger back end:
Cannot change this setting while the inferior is running.
Cannot change this setting while the inferior is running.

Comment: Not strictly and answer, but given the age of this question, consider migrating to gradle for build? It has much improved support for `ndk`
Comment: which os are you using
Comment: The operating system is Windows 7
Answer: I found this link here link and actual author is marc.
Since you followed the guide and have installed CDT.
When CDT launches, it tries to set a breakpoint at main, so it will interrupt execution when your program starts. However, your target is already running so the breakpoint cannot be set and the whole things fails.
You could simply tell your launch not to set that breakpoint and let it connect to your target.
Go to: Run->Debug Configurations... and find your launch configuration. Then select the Startup subtab, scroll down and uncheck "Set breakpoint at" in the "Runtime options" subsection.
****It may be also related to OS you are using since this is an issue with inferior execution.**** and thus a patch may be needed.But before doing anything try above.It may solve your issue.
Also removing the "target" command from the .gdbinit file may help as the eclipse plugin already issues this command.
If nothing works you may look for changing debugger because at last its a gdb compilation problem.
My answer is purely based on r&d.
Answer: There is a mismatch between the gdb client inside eclipse and the gdb server. Try changing the gdb client in eclipse

debug settings --> Debugger --> Main Tab --> Browse to gdb compiled
  for the same platform


Permissions not working with Tabs menus?

Question: I have Menus with Tab structure Working from my custom module. But When I built permissions for each Tab It does not work according to assigned user roles in permissions, also it just made those url's not accessible. Please suggest what I am doing wrong, Thanks!
function my_module_permission() {
  $arr = array();
  $arr['access one_type_titles'] = array(
    'title' => t('Access First Type Titles'),
    'description' => t('Allow users to First Type Titles page.')
  );

  $arr['access second_type_titles'] = array(
    'title' => t('Access Second type Title page'),
    'description' => t('Allow users to access Second type Title page.')
  );

  return $arr;
}

function my_module_menu() {

  $items['type'] = array(

    'description' => t('Page for translation'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('custom_list'),
    'access arguments' => array('access one_type_titles content'),

  );

  $items['type/fr'] = array(
    'title' => t('French Links'),
    'type' => MENU_LOCAL_TASK,
    'weight' => 1,
    'page arguments' => array('custom_list'),
    'page callback' => 'drupal_get_form',
    'access arguments' => array('access one_type_titles content'),
  );

  $items['type/en'] = array(
    'title' => t('English Links'),
    'type' => MENU_LOCAL_TASK,
    'weight' => 2,
    'page arguments' => array('custom_list'),
    'page callback' => 'drupal_get_form',
    'access arguments' => array('access second_type_titles content'),

  );

  return $items;
}

Using 'access callback' => can_the_user_see_this_item, and then coding access according to user role make it works but not with above method.
function can_the_user_see_this_item(){
 if (condition....) ) {
    return TRUE;
  }else{
    return FALSE;
  }
}

Answer: Try to remove 'content' word from 'access arguments' in hook_menu, because you custom permissions don't contain it. Clear cache.

'access arguments' => array('access one_type_titles'),

Comment: Thanks it works great now, that will be very helpful if you can little explain for what content word is used in permissions!
Comment: I'm not sure that there is a special meaning for 'content' word. You define new permissions in hook_permission and you should use them with the same names 'access one_type_titles' , 'access second_type_titles'


integrating by parts $9e^{2x}\cos(3x)$

Question: integrating by parts:
$$\int 9e^{2x}\cos(3x)dx$$
It seems like whichever part I start with integrating or deriving It still leads to a "by parts" integral. How Do I deal with it?
Comment: Do the "by parts" twice, you get back to original and you can just solve the equation.
Comment: Integrate by parts twice, & then do some linear algebra.
Answer: Here's a nice and easy way to evaluate the integral using the tabular method. First, choose a function to differentiate. We'll let our $u$ be $\cos 3x$ and $\mathrm dv$ to be $e^{3x}$. Setting up the table gives$$\begin{array}{|c|c|c|}\hline \text{sign} & u & \mathrm dv\\\hline+ & \cos 3x & e^{3x}\\\hline\end{array}$$Now differentiate and integrate $u$ and $\mathrm dv$ respectively until you either return back to your original integral or when $u$ reaches zero (when you differentiate a constant).$$\begin{array}{|c|c|c|}\hline\text{sign} & u & \mathrm dv\\\hline + & \cos 3x & e^{3x}\\\hline - & -3\sin 3x & \frac 13e^{3x}\\\hline + & -9\cos 3x & \frac 19e^{3x}\\\hline\end{array}$$Hence, if we call the integral $\mathfrak{I}$, then$$\begin{align*}\mathfrak{I} & =\frac 13e^{3x}\cos 3x+\frac 13e^{3x}\sin 3x-\int\mathrm dx\, e^{3x}\cos 3x\\ & =\frac 13e^{3x}\cos 3x+\frac 13e^{3x}\sin 3x-\mathfrak{I}\end{align*}$$Therefore, isolating $\mathfrak{I}$, we get that$$\int\mathrm dx\, e^{3x}\cos 3x\color{blue}{=\frac 16e^{3x}\cos 3x+\frac 16e^{3x}\sin 3x+C}$$
Comment: Yup!!!! Thankss
Comment: @NPLS I just realized, your problem is $e^{\color{red}{2}x}$ instead of $e^{\color{blue}{3}x}$. Anyways, I hope you get the point of my answer.
Comment: yeah yeah I got it
Answer: Straightforward... use:
$$\int f(x) g'(x)\ dx = f g - \int f'(x) g(x)\ dx$$
where $g \propto e^{2 x}$ and $f \propto \cos (3 x)$.
Result:
$$\frac{9}{13} e^{2 x} (3 \sin (3 x)+2 \cos (3 x))$$
Comment: @NPLS : Integrate by parts twice. You end up with something like $\int = f + c\cdot\int$, so you conclude that $\int = f/(1-c)$.
Comment: I'd like the explanation, on how to derive the resut
Answer: If you need
$$I=\int e^{ax}\cos(bx)\,dx$$ consider instead
$$J=\int e^{ax} e^{ibx}\,dx=\int e^{(a+i b)x}\,dx=\frac{e^{(a+i b)x} }{a+ib }$$ and take the real part of it.
No need of integration by parts.

integrating by parts $9e^{2x}\cos(3x)$


Linha de código ignorada

Question: A linha marcada com /*ISSO AQUI*/ está sendo ignorada, ou seja, o nome para o segundo empregado não é lido, apenas o sobrenome.
import java.util.Scanner;

public class EmployeeTest {

public static void main(String[] args) {

    Scanner input = new Scanner(System.in);
    Employee Empregado1 = new Employee();
    Employee Empregado2 = new Employee();

    System.out.print("Enter your name: ");
    String nome = input.nextLine();
    Empregado1.setName(nome);

    System.out.print("Enter your last name: ");
    String sobreNome = input.nextLine();
    Empregado1.setLastName(sobreNome);

    System.out.print("Enter you salary: ");
    double salario = input.nextDouble();
    Empregado1.setSalary(salario);

    double novoSalario = Empregado1.getSalary() + (0.10*Empregado1.getSalary());

    Empregado1.setSalary(novoSalario);
    Empregado1.showEmployee();

    //-----------------------------------------------------------------------------

    System.out.print("\n\nEnter your name: ");
    /*ISSO AQUI*/ nome = input.nextLine(); /*ISSO AQUI*/
    Empregado2.setName(nome);

    System.out.print("Enter your last name: ");
    sobreNome = input.nextLine();
    Empregado2.setLastName(sobreNome);

    System.out.print("Enter you salary: ");
    salario = input.nextDouble();
    Empregado2.setSalary(salario);

    novoSalario = Empregado2.getSalary() + (0.10*Empregado2.getSalary());

    Empregado2.setSalary(novoSalario);
    Empregado2.showEmployee();

    input.close();
}

}

Answer: Isto ocorre por causa de uma particularidade dos métodos da classe  Scanner. Quando você faz esta chamada:
System.out.print("Enter you salary: ");
double salario = input.nextDouble();

Ao dar o enter, há uma quebra de linha que não é capturada pelo nextDouble(). Porém, ao fazer isso:
System.out.print("\n\nEnter your name: ");
nome = input.nextLine(); /*ISSO AQUI*/

o nextLine() pegará a string até a quebra de linha ocorrer. E como já há uma quebra de linha não capturada, este método acaba consumindo essa quebra de linha e passando o código em diante.
Uma solução seria capturar a quebra de linha antes de chegar ai, adicionando um simples input.nextLine() logo após o nextDouble().
System.out.print("Enter you salary: ");
double salario = input.nextDouble();
input.nextLine();
Empregado1.setSalary(salario);

Lembrando que esse problema ocorrerá sempre que você efetuar captura de dados primitivos com captura de string através do nextLine(), e não somente como o nextDouble().
Nesta resposta é dada uma solução melhor para lidar com este problema, apesar de parecer um pouco mais trabalhosa de se implementar.
Answer: Boa tarde,
O causador está nesta linha:
 double salario = input.nextDouble();

A função lê apenas até o próximo token e não a linha inteira, então quando você chama o nome = input.nextLine(); ele termina de ler a linha.
Você pode usar mais um input.nextLine(); para ler a linha anterior, sem atribuir a nada, ou pode tentar assim:
//tente substituir
double salario = input.nextDouble();
// por
double salario = Double.parseDouble(input.nextLine());

Comment: Na verdade o que o nextdouble não lê é a quebra de linha deixada pelo enter, e como o nextLine consome a string até houver uma quebra de linha, ele acaba consumindo a quebra de linha deixada pelo nextdouble.
Comment: Obrigado pela correção.
Answer: Isso é porque o nextDouble não consome o último caractere de nova linha de sua entrada e, portanto, a nova linha é consumido na próxima chamada, uma solução é utilizar o next() ao invés do nextLine(), desta forma:
public static void main(String[] args) {

    Scanner input = new Scanner(System.in);
    Employee Empregado1 = new Employee();
    Employee Empregado2 = new Employee();

    System.out.print("Enter your name: ");
    String nome = input.next();
    Empregado1.setName(nome);

    System.out.print("Enter your last name: ");
    String sobreNome = input.next();
    Empregado1.setLastName(sobreNome);

    System.out.print("Enter you salary: ");
    double salario = input.nextDouble();
    Empregado1.setSalary(salario);

    double novoSalario = Empregado1.getSalary() + (0.10 * Empregado1.getSalary());

    Empregado1.setSalary(novoSalario);
    Empregado1.showEmployee();

    // -----------------------------------------------------------------------------

    System.out.print("\n\nEnter your name: ");
    /* ISSO AQUI */ nome = input.next(); /* ISSO AQUI */
    Empregado2.setName(nome);

    System.out.print("Enter your last name: ");
    sobreNome = input.next();
    Empregado2.setLastName(sobreNome);

    System.out.print("Enter you salary: ");
    salario = input.nextDouble();
    Empregado2.setSalary(salario);

    novoSalario = Empregado2.getSalary() + (0.10 * Empregado2.getSalary());

    Empregado2.setSalary(novoSalario);
    Empregado2.showEmployee();

    input.close();
}

Linha de código ignorada


How to show that $\operatorname{span} (A)=\mathbb{R}^3$ where $A=\{(t,t^2,t^3):t\in \mathbb{R}\}$?

Question: Let $A=\{(t,t^2,t^3):t\in \mathbb{R}\}$. Show that $\operatorname{span} (A)=\mathbb{R}^3$.

[My thoughts.]
In order to show  $\text{span} (A)=\mathbb{R}^3$ I have to show that every vector in $\mathbb{R}^3$ is a linear combination of vectors in $A$. But I don't know how to do this.
Comment: Google Vandermonde matrices.
Answer: Hint
Take, for example, $t=1$, $t=2$ and $t=3$ and show that $\left(1,1^2,1^3\right)$, $\left(2,2^2,2^3\right)$ and $\left(3,3^2,3^3\right)$ are linearly independent and hence span the (three-dimensional) space $\mathbb{R}^3$.
Comment: @Suresh_iit The same way you show that any set of vectors is linearly independent (in other words, there is nothing special about this one). One way is to take a linear combination of them that adds up to $\vec 0$, then show that the linear combination must have all coefficients $0$.
Comment: @Suresh_iit See above (Arthur's answer); equivalently you can put them in a 3 by 3 matrix and verify that the determinant is non-zero, this gives you a more "direct, computational" way.
Comment: @StackTD..how to we prove it
Comment: @StackTD.....suppose $(x,y,z)\in R^3$ and $(x,y,z)=a(t,t^2,t^3)+b(t,t^,t^3)+c(t,t^2,t^3)$ like this way going to solve ?
Comment: @Arthur...here is single vector is there then how to write linear combiamtion..i missing something i think..sorry
Answer: Alternative approach: the moment curve is not a planar curve, since its torsion is given by
$$ \tau =\frac{((1,2t,3t^2)\times(0,2,6t))\cdot(0,0,6)}{\|(1,2t,3t^2)\times(0,2,6t) \|^2}=\frac{3}{1+9t^2+9t^4}\neq 0. $$
$3\times 3$ real Vandermonde matrices are invertible since the moment curve is non-planar is a nice way to put it. In the classical way, given three distinct real numbers $a,b,c$, the problem of finding a solution to
$$ \begin{pmatrix}1 & a & a^2 \\ 1 & b & b^2 \\ 1 & c & c^2\end{pmatrix}\begin{pmatrix}k_1 \\ k_2 \\ k_3\end{pmatrix}=\begin{pmatrix}y_1 \\ y_2 \\ y_3\end{pmatrix}$$
given $y_1,y_2,y_3\in\mathbb{R}$ is equivalent to finding the coefficients of a quadratic polynomial $q$ such that $q(a)=y_1, q(b)=y_2, q(c)=y_3$. A solution always exists, by Lagrange's interpolating polynomials, and such a solution is also unique. It follows that the matrix appearing in the LHS is invertible, hence if $A,B,C\neq 0$ are three distinct points on the moment curve, $\text{Span}(A,B,C)=\mathbb{R}^3$.


Como usar JQuery para acionar uma função quando o title da pagina for alterado?

Question: Olá, eu sou novo nesta plataforma, não sei se minha pergunta vai cumprir os requisitos, mas vou tentar ser o mais especifico possível!
Eu quero acionar um evento usando o Jquery, para quando o  for alterado, estava tentando usar a seguinte função:
$('title').change(function(){
console.log('O titulo foi alterado!')
})

Porem quando altero o valor da tag  simplesmente nada acontece, alguém poderia me explicar o motivo disso, ou se for possível me apresentar uma forma valida de se fazer isso.. Desde já agreço :D!
Comment: Voce altera o valor de `title` atraves de um `input`?
Comment: Não, através do devtools
Comment: Na verdade, quero que esse evento seja disparado quando eu receber uma nova mensagem no WhatsApp, quando existe uma mensagem no WhatsApp o título dele é alterado e eu quero capturar esse evento
Answer:
se for possível me apresentar uma forma valida de se fazer isso..

Usando JavaScript puro você pode usar o MutationObserver que é uma API que observa mudanças no DOM e dispara uma funcão quando a detecta.
De exemplo, você seleciona o title via querySelector e atribui ele a instância MutationObserver usando o método observe. Passe uma funcão de callback para o objeto MutationObserver que dispara quando ocorrer uma alteração no title.
Código de exemplo:
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>

Não sei se essa API é implementada em JQuery.
Comment: woww! muito obrigado funcionou perfeitamente bem, MUITO OBRIGADO mesmo !
Comment: E se eu quiser observar uma classe por exemplo, isso funcionaria?
Comment: Se fala de um elemento com uma classe especifica sim, basta fazer `const elemento = document.querySelector('.nome-da-classe);`. Passe `.nome-da-classe` para o `querySelector`. Pode ser id, classe, tag, etc...
Comment: Ok muito obrigado!


TypeError: Cannot create property 'href' on string 'about:blank'

Question: Ran into an error after testing the Firebase authentication with Google on ElectronJS.
Authentication used to work before, even though I haven't made any significant changes in my code that would affect the Google authentication part.
Authentication still works correctly when I am running my project in the browser (npm run serve). In Electron I can see the
TypeError: Cannot create property 'href' on string 'about:blank' when clicking on the Google authentication button.

TypeError: Cannot create property 'href' on string 'about:blank'
My code that is being executed on click -
googleLogin() {
  fb.auth
    .signInWithPopup(fb.googleProvider)
    .then(credential => {
      this.$store.commit("setCurrentUser", credential.user)

      fb.usersCollection.doc(credential.user.uid).set({

      }).then(() => {
        this.$store.dispatch("fetchUserProfile")
        this.updateGmailData()
        this.$router.push("/dashboard")
      }).catch(err => {
        console.log(err)
      })
    }).catch(err => {
      console.log(err);
    });
},

On second click on the button, I can see another typeError -
TypeError: Cannot create property 'href' on string ''

Why does the authentication work on browser but not in Electron?
What is the cause of this issue?
Answer: see this issue https://github.com/firebase/firebase-js-sdk/issues/1334.
Electron is not officially supported by Firebase Auth. Since Electron is a combination of a browser and Node.js server environment, some features may not work as expected, such as signInWithPopup.
But @diggabyte (thx to him) seems to have found a way to handle it:

I was able to get it to work via signInWithRedirect + getRedirectResult
  https://github.com/firebase/firebase-js-sdk/issues/1334#issuecomment-434094783


How to make iptables not SNAT locally generated packets

Question: Most SNAT examples give following
iptables -t nat -A POSTROUTING -o eth0 -j SNAT --to-source 18.104.22.168

but, it appears that this apply not only to forwarded packets but also to packets coming from localhost. This is unwanted. Outgoing packets from localhost may be something important (SMTP, etc), I don't want to change it's IP to one used for NAT.
I saw examples with
iptables -t nat -A POSTROUTING -s 10.0.0.0/8 -o eth0 -j SNAT --to-source 22.214.171.124

but this seems to be unreliable to me as it is one more place that you need to keep an eye on when you want change something. Is there a way to define that outgoing packets from localhost should not be SNAT'ed no matter what?
Comment: iptables -t nat -A POSTROUTING -o lo -j LOG --log-prefix "test: "
   nat.POSTROUTING applies to all packets, check iptables diagram
Comment: How have you verified that the source IP of those packets coming from localhost have that address? POSTROUTING chain only applies to packets that are routed via the machine. OUTPUT chain applies to locally generated packets, and therefore I find your issue quite odd.
Answer: If you look at iptables diagram
(choose any https://gist.github.com/nerdalert/a1687ae4da1cc44a437d)
you can see that nat.POSTROUTING is applied not only for forwarded packets but also for outgoing packets from this host. So, if you have 2 IP's (126.96.36.199 and 126.96.36.199) assigned to this host and have something like this in your iptables
iptables -t nat -A POSTROUTING -o eth0 -j SNAT --to-source 18.104.22.168

all connections from this host outgoing to eth0 will be changed by SNAT. Even when software binds to certain IP. Thats could be bad.
This can be easily avoided by adding above previous setting
iptables -t nat -A POSTROUTING -m addrtype --src-type LOCAL -j ACCEPT

this will accept any packet generated by this host, without SNAT, works for all IP's that are assigned to this host - 127.0.0.1 or 220.127.116.11 or 22.214.171.124 (secondary ip), etc
Comment: How we can test to verify this is happend??