How to execute javascript within drupal for a specific field on a specific page?

Question: The Initil question
I have a input field which should activate a function on the onfocus javascript event on a field on the user page.
Step 1
Add code to a custom module:
(function ($) {
  $(document).ready(totalname(){
    document.getElementById("fullname").style.background = "yellow";
  });
})(jQuery);

The currently HTML is:
<input type="text" id="fullname">

And it should become like this:
<input type="text" id="fullname" onfocus="totalname()">

How to get the onfocus=... inside the input element?
Is the custom code ok?
Addition to this question.
Thxs you so much for all the comments. Based on that I learned i few things more so I now understand what the real question should be.
To understand how I can executed javascript code in a certain field on a certain page in drupal.
I assumed this was needed by a callback but this is not encoured according to @Jimmy so I'm trying to understand the way it should be according to drupal standards. Also I was suprised that no change in HTML was needed as @Adrian gave an example. I could not get it run because of the typo :-( So in mean time I made another solution.
The  script is basicly just a real time concatination of first, middle and last name into a fullname field.
(function ($) {
  $(document).ready(function(){

        function setFullName() {
            var nameParts = [document.getElementById("edit-field-voornaam-und-0-value").value,
                             document.getElementById("edit-field-tussenvoegsel-und-0-value").value,
                             document.getElementById("edit-field-achternaam-und-0-value").value],
                name = nameParts.join(" ").trim();

            document.getElementById("edit-field-naam-und-0-value").value = name;
        }

        var fields = [document.getElementById('edit-field-voornaam-und-0-value'),
                      document.getElementById('edit-field-tussenvoegsel-und-0-value'),
                      document.getElementById('edit-field-achternaam-und-0-value')];

        for (var i = 0; i < fields.length; i++) {
            fields[i].addEventListener("keyup", setFullName);
        }

  });
})(jQuery);

So this is working and I put it in a custom module.
I still do not understand how I should be if I rewrite the code following the example of @adrian as this code is still executed on every page and not a specific page.
Thank you for learning !! and not using the correct words. I'm not native english ...
Comment: @AdrianCidAlmaguer Please don't edit random stuff into the question in an attempt to make it on topic - the OP didn't say anything even remotely related to the edit you made. This is a plain JS question, so will always be off topic here.
Comment: @adrian, 100% agree !!!
Comment: Please note that adding callback function in attributes is not encouraged in Drupal project.
Comment: Ok, what is the correct way for implementing this in drupal?
Comment: Check @AdrianCidAlmaguer answer
Comment: I edit the answer, take a look at the end
Comment: It is not plain js question as I do not understand how to activate from drupal
Comment: I don't know what that means @Justme - the question you've asked its about Javascript functionality, not about Drupal's use of javascript. Specifically: _How to get the onfocus=... inside the input element? Is the custom code ok?_. That's clearly not about Drupal. If you were asking how to add javascript to a page, we'd have pointed you to the [documentation](https://www.drupal.org/node/756722), and/or closed this as one of the many duplicates that ask the same thing. [This one](http://drupal.stackexchange.com/questions/12851/how-to-add-javascript-to-my-drupal-site), for example
Comment: @Justme I think that you need to edit your question with more additional information about your really problem
Comment: @AdrianCidAlmaguer Ah sorry - that's entirely my fault, I thought I'd read every comment but I obviously missed one
Comment: @Justme In this case edit your question please, maybe we're missing something.
Comment: and finally do you found the solution?
Comment: Hi Adrian, no, it is stil running on every page. I have on my todolist to try to get it on a specific page with the help of module js injector.
Answer: Your jQuery:
//Making a focus over the element
(function ($) {
    $('#fullname').blur(function() {
        $(this).removeClass("color");
      })
      .focus(function() {
        $(this).addClass("color");
      });
})(jQuery);

Your HTML:
<input type="text" id="fullname">

Your CSS:
.color {
  background-color : yellow;
}

EDIT:
To attach the js code to your page you can use #attached in a renderable array (this is the recommended way). I think that you should read: How to add jQuery UI libraries to a page.
Comment: @JimmyKo thanks for the edit, I just see the error now
Comment: @Pierre.Vriens I think that I made the error because I copy the code from one site that I made and I don't see the problem between the id and the class element.
Comment: Adrian, I'm trying to learn and I understand the answer. But I need lots more of javascript to execute around this element. Therefore the question is how to inject JS instead of how to make a the field yellow :-)
Comment: I think @NoSssweat is right. However, the nature of the suggested edit by Jimmy Ko is a bit difficult to judge as a reviewer. Therefor I think Adrian is the only one who should decide to yes or no accept that edit. If needed, perform a rollback to the prior version (and apply any other/similar fixes where appropriate). Good luck!
Comment: @Justme there is an error in Adrian's answer. should be $(`'#fullname')`
Comment: ok understand that typo but don't understand the code :-( What is the general code to activate a js function (totalname on element fullname?
Comment: @Pierre.Vriens would you mind telling me what is the difficult point? :)
Comment: Please don't edit code in people's answers @JimmyKo, you don't know what their intention was. Thanks :)
Comment: @Clive fine. I thought it is a obvious error. BTW, you changed it back :)
Comment: Yeah I know, just caught that @JimmyKo ;) You're almost definitely right, but we tend not to 2nd-guess with code. Cheers
Comment: @JimmyKo : glad you asked! "I" think your suggested edit made sense, and is correct, and I approved it, right? However this was your 2nd suggestion (same content), after your first (identical) suggestion was also approve "by me", but which was then "rejected" by 2 other reviewers (so that the first suggestion verdict = rejected). However, the [Rules](https://www.drupal.org/project/rules)  (oeps ...) of this site here (which I did not invent) do not allow such edits (only the OPer can apply such changes ... I think). So that is why "I" believe only Adrian in the end should decide. OK?
Comment: Hm, I just saw Clive's note (and rollback), which seems to confirm my perception also. I trust later on Adrian will seriously consider Jimmy's edit again (or maybe extend his answer to further clarify). PS to @JimmyKo : any other edit suggestions (without changing code ...)?


Não estou conseguindo visualizar o ListView

Question:

#

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        Button botaoespecialidades = (Button) findViewById(R.id.botaoespecialidades);

        botaoespecialidades.setOnClickListener(new View.OnClickListener() {

            public void onClick(View arg0) {

                CarregaTela2();
            }
        });
    }

    public void CarregaTela2() {
        setContentView(R.layout.activity_especialidades);

    }
}

#

public class Especialidades extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_especialidades);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

    String[] atividades = new String[]{"Especialidades 1", "Especialidades 2", "Especialidades 3"};

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, atividades);

    ListView lv = (ListView) findViewById(R.id.lv);
    lv.setAdapter(adapter);
    lv.setOnItemClickListener(chamaAtividades(this));
}

    public AdapterView.OnItemClickListener chamaAtividades(final Context context){
        return (new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> av, View v, int position, long id) {

                Intent intent;
                switch(position){
                    case 0:
                        intent = new Intent(context, Atividade1.class);
                        startActivity(intent);
                        break;
                    case 1:
                        intent = new Intent(context, Atividade2.class);
                        startActivity(intent);
                        break;
                }

            }
        });
    }

    public void  btsair(View view){
        finish();

    }
}

Answer: No método CarregaTela2() deverá criar um Intent para lançar a Activity Especialidades.
Aquilo que você está a fazer é apenas a mudar o layout que a MainActivity apresenta.
Altere o método assim:
public void CarregaTela2() {
    intent = new Intent(this, Especialidades.class);
    startActivity(intent);
}

Comment: Obrigado pela ajuda ramaral, deu certo.


Checking Normality of Numerical, and Categorical Data

Question: I have come across 3 questions on the title subject.

Why is it necessary to do a normality test? To check if data is imbalanced or not?
Are these 4 methods of checking if the data follows normal distribution criteria both applicable to numerical and categorical variable? I am trying to check if the data follows normal distribution by following 4 methods.

Checking Distribution
Drawing Box Plot
Drawing QQ Plot
Use skewness, kurtosis criteria

Skewness for Normal Dist is 0, Kurtosis for Normal Dist is 3. Is there a certain bound that I can use to guarantee that the data is normally distributed? (such as, 0 +/- 1 OR 3 +/- 1)
Comment: If a variable is categorical in any strong sense, then being normal is impossible and irrelevant any way.
Comment: I query the premise of the title. Is it even advisable, let alone necessary, to actually *test* normality?  See, for example, https://stats.stackexchange.com/questions/2492/is-normality-testing-essentially-useless
Comment: Duplicate of [this Q](https://stats.stackexchange.com/questions/462647/checking-normality-of-numerical-and-categorical-data/462660#462660) My attempt to answer is there.
Comment: Does this answer your question? [Checking Normality of Numerical, and Categorical Data](https://stats.stackexchange.com/questions/462647/checking-normality-of-numerical-and-categorical-data)
Answer: 1) Some statistical tests are exact only if data are a random sample from a normal population. So it can be important to check whether samples are consistent with having come from a normal population. Some frequently used tests, such as t tests, are tolerant of certain departures from normality, especially when sample sizes are large.
Various tests of normality ($H_0:$ normal vs $H_a:$ not normal) are in use. We illustrate Kolmogorov-Smirnov and Shapiro-Wilk tests below. They are often useful, but not perfect:

If sample sizes are small these tests
tend not to reject samples from populations that are nearly symmetrical and lack long tails.
If sample sizes are very large these tests
may detect departures from normality that are unimportant for practical purposes. [I don't know what you mean by 'imbalanced'.]

2) For normal data, Q-Q plots tend to plot data points in almost a straight line. Some sample points with smallest and largest values may stray farther from the line than points between the lower and upper quartiles. Fit to a straight line is usually better for larger samples. Usually, one uses Q-Q plots (also called 'normal probability plots') to judge normality by eye---perhaps without doing a formal test.
Examples: Here are Q-Q plots from R statistical software of a small standard uniform sample, a moderate sized standard normal sample, and a large
standard exponential sample. Only the normal sample shows
a convincing fit to the red line. (The uniform sample does not
have enough points to judge goodness-of-fit.)
set.seed(424)
u = runif(10);  z = rnorm(75);  x = rexp(1000)
par(mfrow=c(1,3))
  qqnorm(u); qqline(u, col="red")
  qqnorm(z); qqline(z, col="red")
  qqnorm(x); qqline(x, col="red")
par(mfrow=c(1,1))

[In R, the default is to put data values on the vertical axis (with the option to switch axes); many textbooks and some statistical software put data values on the horizontal axis.]
The null hypothesis for a Kolmogorov-Smirnov test is that data come from a specific normal distribution--with known values for
$\mu$ and $\sigma.$
Examples: The first test shows that sample z from above is consistent with sampling from $\mathsf{Norm}(0, 1).$ The second illustrates that the KS-test can be used with distributions other than normal. Appropriately, neither test rejects.
ks.test(z, pnorm, 0, 1)

        One-sample Kolmogorov-Smirnov test

data:  z
D = 0.041243, p-value = 0.999
alternative hypothesis: two-sided

ks.test(x, pexp, 1)

        One-sample Kolmogorov-Smirnov test

data:  x
D = 0.024249, p-value = 0.5989
alternative hypothesis: two-sided

The null hypothesis for a Shapiro-Wilk test is that data come from some normal distribution, for which $\mu$ and $\sigma$ may be unknown. Other good tests for the same general hypothesis are in frequent use.
Examples: The first Shapiro-Wilk test shows that sample z is consistent with sampling from some normal distribution. The second test shows good fit for a larger sample from a different normal distribution.
shapiro.test(z)

        Shapiro-Wilk normality test

data:  z
W = 0.99086, p-value = 0.8715

shapiro.test(rnorm(200, 100, 15))

        Shapiro-Wilk normality test

data:  rnorm(200, 100, 15)
W = 0.99427, p-value = 0.6409

Addendum on the relatively low power of the Kolmogorov-Smirnov test, prompted by @NickCox's comment. We took $m = 10^5$ simulated datasets of size $n = 25$ from each of three distributions: standard uniform, ('bathtub-shaped') $\mathsf{Beta}(.5, .5),$ and standard exponential populations. The null hypothesis in each case is
that data are normal with population mean and SD matching
the distribution simulated (e.g., $\mathsf{Norm}(\mu=1/2, \sigma=\sqrt{1/8})$ for the beta data).
Power (rejection probability) of the K-S test (5% level) was $0.111$ for uniform, $0.213$ for beta, and $0.241$ for exponential. By contrast, power for the Shapiro-Wilk, testing the null
hypothesis that the population has some normal distribution (level 5%), was
$0.286, 0,864, 0.922,$ respectively.
The R code for the exponential datasets is shown below. All power values for both tests and each distribution are likely accurate to within about $\pm 0.002$ or $\pm 0.003.$
set.seed(425); m = 10^5; n=25
pv = replicate(m, shapiro.test(rexp(n))$p.val)
mean(pv < .05); 2*sd(pv < .05)/sqrt(m)
[1] 0.9216
[1] 0.001700049
set.seed(425)
pv = replicate(m, ks.test(rexp(25), pnorm, 1, 1)$p.val)
mean(pv < .05); 2*sd(pv < .05)/sqrt(m)
[1] 0.24061
[1] 0.002703469

Neither test is very useful for distinguishing a uniform sample of size $n=25$ from normal. Using the S-W test, samples of this size from populations with more distinctively nonnormal shapes are detected as nonnormal with reasonable power.

A boxplot is not really intended as a way to check for normality. However, boxplots do show outliers. Normal distributions extend in theory to $\pm\infty,$ even though values
beyond $\mu \pm k\sigma$ for $k = 3$ and especially $k = 4$ are quite rare. Consequently, very many extreme outliers in a boxplot may indicate
nonnormality--especially if most of the outliers are in the same tail.
Examples: The boxplot at left displays the normal sample z. It shows a symmetrical distribution and there happens to be one near outlier. The plot at right displays dataset x; it is characteristic of exponential samples of this size to show many
high outliers, some of them extreme.
par(mfrow=c(1,2))
  boxplot(z, col="skyblue2")
  boxplot(x, col="skyblue2")
par(mfrow=c(1,1))

The 20 boxplots below illustrate that normal samples of size 100
often have a few boxplot outliers. So seeing a few near outliers in a boxplot is not to be taken as a warning that data may not be normal.
set.seed(1234)
x = rnorm(20*100, 100, 15)
g = rep(1:20, each=100)
boxplot(x ~ g, col="skyblue2", pch=20)

More specifically, the simulation below shows that, among normal samples of size $n = 100,$
about half show at least one boxplot outlier and the average
number of outliers is about $0.9.$
set.seed(2020)
nr.out = replicate(10^5,
         length(boxplot.stats(rnorm(100))$out))
mean(nr.out)
[1] 0.9232
mean(nr.out > 0)
[1] 0.52331

Sample skewness far from $0$ or sample kurtosis far from $3$ (or $0)$ can indicate nonnormal data. (See Comment by @NickCox.) The question is how far is too far. Personally, I have not found sample skewness and kurtosis to be more useful than other methods discussed above. I will let people who favor using these descriptive measures as normality tests explain how and with what success they have done so.
Comment: Hundreds of threads here on this. Poor or incorrect advice in many books or internet sources doesn't help. This is difficult territory for the learner. Reasons include (as also explained here) 1. Why is normality being checked for any way? There are several myths e.g. that you need marginal normal distributions for regression. 2. A test can reject normality for reasons that won't bite (minor deviations in a large sample) while small samples are often unclear either way. Nothing is fail safe. 3. Researchers  need to build up experience as well as apply formal procedures.
Comment: @NickCox: Thanks for all 3 comments. Fixed error on kurtosis.
Comment: Kurtosis is 3 for a normal, except that many programs subtract 3 any way, in which case it is 0 for a normal. So, people need to look at the documentation for explanations of procedure. If that fails, better than nothing is to simulate from a normal and see how kurtosis turns out. A value of 1 isn't a reference level either way. I agree that quantile plots are by far the best place to start, Of the tests mentioned here, Shapiro-Wilk is greatly preferable to Kolmogorov-Smirnov.
Comment: Skewness and kurtosis have _some_ descriptive use. For example, if a researcher has thousands of samples, looking at thousands of graphs may not be practical, but skewness and kurtosis can identify wild samples for further checks. L-moments are often as helpful as moment-based measures, but seemingly little used outside a few fields such as hydrology and climatology.
Comment: @NickCox: Simulation-based addendum prompted by your mention of poor power of K-S relative to S-W.
Answer: A lot of instructors recommend testing for normality because that is what they were taught to do. The practical implications are often quite different. We test for normality because the test statistics, and their resulting distributions, were derived under the assumption that the data is normally distributed.
In many circumstances the Central Limit Theorem will overcome almost any "departure" from normality because the tests rely more on the sampling distribution of the sample mean to be normal than the original data. As a rough rule of thumb, as long as the data is approximately symmetric and unimodal, then the test or method will perform quite well. This is why, for example, regression where y is integer valued (with a moderate range in values) can work quite well, even though by definition, y is clearly not normal.
Normality can matter if you are interested in prediction for new values, rather than inference for the mean. But most of the time, the importance of normality is completely over-emphasised.
Comment: Duplicate of [this Q](https://stats.stackexchange.com/questions/462647/checking-normality-of-numerical-and-categorical-data/462660#462660) My attempt to answer is there. Hope your answer doesn't get lost. (+1)


make mysql to share all cpu

Question: I am very new to linux server .I am using centos.Sometimes my cpu gets overloaded because of the process mysqld over 100%
PID   USER   PR    NI    VIRT    RES    SHR S    %CPU %MEM    TIME+  COMMAND
2221    mysql  20     0     2810m   797m  5648 S   99.3  5.0  262:15.91   mysqld

So To debug I ran top command in ssh and I got below
Cpu(s):  2.9%us,  2.3%sy,  0.0%ni, 94.7%id,  0.0%wa,  0.0%hi,  0.1%si,  0.0%st
Mem:  16291440k total, 14893024k used,  1398416k free,  1673232k buffers
Swap: 16433144k total,    30168k used, 16402976k free, 10713048k cached

I dont understand anything in this but i see , Only one CPU (94.7%id) is used alot and other CPU are free.How to make mysql to share more cpu and reduce the load.
Comment: `94.7%id` means the system spends 94.7% of its time doing nothing (id=idle).
Answer: Row 3 : in top command indicates how the cpu is used. Understand each one separately
% of the CPU for user processes (2.9%us)
% of the CPU for system processes (2.3%sy)
% of the CPU processes with priority upgrade nice (0.0%ni)
% of the CPU not used (94.7%id)
% of the CPU processes waiting for I/O operations(0.0%wa)
% of the CPU serving hardware interrupts (0.0% hi)
% of the CPU serving software interrupts (0.1% si)

Row 4 and 5: Gives RAM (physical memory) and SWAP details.

This shows the Processes List
%CPU – % of CPU used by this process (99.3)
%MEM – % of RAM used by the process (5.0)

For CPU allocation refer
https://stackoverflow.com/questions/14787046/how-to-allocate-more-cpu-and-ram-to-a-c-program-in-linux
https://askubuntu.com/questions/115478/how-do-i-assign-different-cpu-cores-to-different-processes

make mysql to share all cpu


Verificar se o reCAPTCHA foi marcado

Question: Estou utilizando um formulário de e-mail em PHP com método POST e utilizo o Google ReCaptcha. Preciso verificar em JavaScript ou jQuery, se o reCAPTCHA foi marcado para só então habilitar o botão de envio.
O código atual:
var checado = false;

jQuery("#recaptcha-anchor").each(function(){
 if($(this).prop("checked")=="checked")
   checado=true;
});

if(checado=true){
 return true;
 jQuery('#submitBtn').prop('disabled', false);

}else{
 return false;
}

OBS: Não tenho acesso ao código PHP caso precise ser alterado.
Answer: Tradução da resposta no StackOverflow em inglês:
Google has a call back option for when the checkbox is checked.

O Google tem um retorno para quando o checkbox está marcado.

Na div que faz a chamada do reCAPTCHA adicione isto:
data-callback="nome_da_funcao"
Vai ficar assim:

Então você cria sua função:
 function recaptchaCallback()
 {
    jQuery('#submitBtn').prop('disabled', false);
 }

Quando o reCAPTCHA for verificado, e a caixa marcada, o callback é acionado e sua função executada.
Você pode acessar a resposta original em inglês.
Lembrando que seu código original possui código depois do return, quando você usa o retorno você faz uma saída de sua função, e o código após o return fica inacessível, então ele deve vir antes do return.
Comment: Com esse retorno já posso ignorar todo o processo de verificação pelo PHP descrito nessa [resposta](https://pt.stackoverflow.com/questions/59952/como-implementar-recaptcha-do-google-no-meu-site)?
Comment: Não, porque o usuário pode simplesmente remover o script *client-side*. A verificação deve ser feita *server-side* também.

Verificar se o reCAPTCHA foi marcado


Big O notation where the "squeeze" starts at $0$?

Question: There is the standard notation : $$f = O(g) \iff \exists M > 0, \,\exists n_0 > 0, \,\forall n > n_0, \quad \left|f(n)\right| \leq M\cdot g(n)
$$
But this is not adequate for a paper I'm writing because I need to force $n_0$ to be $0$, i.e. : $$
\exists M > 0, \,\forall n > 0, \quad \left|f(n)\right| \leq M\cdot g(n)
$$
I'll be using this a lot, so a synthetic notation like $f = O(g)$ is required.
Is there a standard notation for this? Or a not so standard one?
Comment: Can you define $\hat{g}(n)=g(n-1)$?
Comment: @NicNic8, sure yes
Answer: What is often used in this case is
$$
|f(n)| \leq \operatorname{const} g(n)
$$
or
$$
|f| \leq \operatorname{const} g
$$
or
$$
|f| \leq C\, g.
$$
where it is understood that the constant does not depend on $n$.
However, it sometimes depends on the context, if $C$ can depend on $f$ and $g$.
I do not think that this is a standard notation.


hook_theme_suggestions_hook_alter() not working for Views

Question: I'm trying to create a custom template for a view page in Drupal 8.3.x. It's going in a custom theme, and needs to be a view-level template (so not page- or node-).
I've been fighting with it for a while and figured it might be an issue with the specific name, so I've made the code as sparse as possible - still no luck.
I have the following code in mytheme.theme:
function mytheme_theme_suggestions_views_view_alter(array &$suggestions, array $variables) {
  $suggestions[] = 'test_template';
}

And the following file structure:
- mytheme
  ~ templates
    * test-template.html.twig
  ~ mytheme.theme
  ~ mytheme.info.yml
  ~ ... etc.

I know that the theme_suggestions alter function is working properly; I have Twig debugging enabled, and when I pull up my site and look at the code, I can see the following: (note the "X" next to views-view.html.twig showing that as the currently used Twig file)

So it's adding the suggestion. And the template file is named correctly. I know it's not a directory issue, because I have other .html.twig files in that /templates/ folder that are working correctly.
Does anyone know why the file name suggestion is working, but the matching file isn't?

Edit: Kevin pointed out a possible duplicate ticket in the comment below. That's only half-related. It does solve the symptom in this particular example - I have been able to pull in one of the templates mentioned here, and it works for this case.
However, the title of the ticket and general issue still holds. I can't get the hook_theme_suggestions_hook_alter() to work with my custom theme_suggestion / template. While it turns out the view I used as my example could be solved another way, there are other instances where that won't be the case.
Comment: Possible duplicate of [Create a template for a specific view](https://drupal.stackexchange.com/questions/188529/create-a-template-for-a-specific-view)
Comment: I _think_ the linked question here can help. You don't necessarily need to invent new naming suggestions, there should be a handful to pick from. They're just not easy to come across.
Comment: @Kevin - In this case, I do need a new naming suggestion. I've been through the default suggestions, and there is no view-level default naming suggestion that pulls in the specific view ID.

If you know of one I haven't found, I'd be happy to use it, but everything I've searched has turned up no default options. Thus, the hook_alter function above.
Answer: Found the solution. As it turns out, for some reason Drupal doesn't play nicely with custom theme suggestions starting with a word + single dash.
I updated my HOOK_theme_suggestions_HOOK_alter() function to include $suggestions[] = 'test__template'; (with 2 underscores between the words) and updated my template name to test--template.html.twig (with 2 dashes to match the 2 underscores), and everything works as expected.
Comment: Perfect. Good question. Good answer. For others, just to be crystal clear, you need to replace ***all*** hyphens in the suggestion to underscores.


What is the difference between the Trigger and Rules modules?

Question: Both the Trigger and the Rules modules provide many event-driven actions, but there are still several difference. What's the major difference between them? When should I pick one module instead of the other one?
Answer: Loosely speaking, Rules is much more generic than triggers. As Johan Falk mentions, "you could say Rules is an extended version of Triggers.. it is technically true, but does not really cover at full extent."
Answer: Triggers is optional core module that provide basic functionality. Rules provide much more freedom and is more advanced module. But the both of them we can use together.
Here is an example for rules https://www.youtube.com/watch?v=j9SD2S69Fjw


Drupal multi-site in an add-on domain?

Question: How can I configure Drupal 8 with multi-site under an add-on domain using cPanel?  I'm getting a 404 when I browse to my subdomain after following these steps:

Clean install of Drupal to my add-on domain: /public_html/addondomain.com/drupal.  I can successfully browse to addondomain.com/drupal
In cPanel, create a sub-domain at sub.addondomain.com with a document root at /public_html/sub.addondomain.com
Create the directory /public_html/addondomain.com/drupal/sites/sub.addondomain.com
Create a sites.php within public_html/addondomain.com/drupal/sites that contains the following code:
<?php $sites = array('sub.addondomain.com' => 'sub.addondomain.com',);>.  File permissions are 644.
Copy /public_html/addondomain.com/drupal/sites/default/default.services.yml to /public_html/addondomain.com/drupal/sites/sub.addondomain.com/services.yml
Copy /public_html/addondomain.com/drupal/sites/default/default.settings.php to /public_html/addondomain.com/drupal/sites/sub.addondomain.com/settings.php
Remove the directory /public_html/sub.addondomain.com
Create a symbolic link in /public_html/: ln -s addondomain.com sub.addondomain.com

When I do all of the above, I get a 404 error when I browse to both sub.addondomain.com and sub.addondomain.com/drupal.  Why am I not redirected to the Drupal installation page where I can enter in my database info, etc.?  Is the error with my symlinks?  My server (cPanel) configuration?  My .htaccess under either my /public_html, public_html/addondomain.com, or /public_html/addondomain.com/drupal?
Comment: I deleted my answer because I didn't read your question thoroughly enough and it was wrong.
Comment: Could the user who downvoted my question provide a justification? I'd like the chance to revise my question before getting dinged.  Thanks!
Comment: I'm not the down-voter but it could be that it is a bit hard to say what the problem is without having access to the server to troubleshoot. It could possibly be a problem with server config & symlinks, it could be a problem with ownership/permissions of the website files and/or webroot folder (in my experience cPanel generally doesn't like you to do things like step 7 & 8 manually if it messes with the directory ownership), or it could be something else entirely.
Comment: Can you confirm that the 404 error is being returned by your main Drupal install at /public_html/addondomain.com/drupal? If so the watchdog log for that Drupal site should contain the 404 error. If so that should narrow it down to a Drupal multi-site configuration issue because it means that the server configuration is working correctly.
Comment: Also, make sure that your settings file for the sub-site doens't still contain the configuration for your main Drupal site. Otherwise Drupal will think it's already installed.
Answer: My solution was to point the document root of sub.addondomain.com to /public_html/addondomain.com/drupal.  I did this within cPanel, which - if I understand cPanel correctly - is going to directly edit the Apache VirtualHosts directives within Apache's config files for my site (something I wouldn't have access to directly with shared hosting).
Answer: You say this,

Drupal is installed under addondomain.com in /public_html/addondomain.com/drupal
The document root for sub.addondomain.com is set to /public_html/sub.addondomain.com

If this is accurate, they're looking for files in different places. Make sure these two are setup the same (either with or without the drupal suffix).

Create a sites.php within public_html/addondomain.com/drupal/sites that contains the following code:  'sub.addondomain.com',);>. File permissions are 644.

Move or remove this file. It's not needed with your naming scheme and it's simply adding another step to debug.

 * For example, for a fictitious site installed at
 * https://www.drupal.org:8080/mysite/test/, the 'settings.php' file is searched
 * for in the following directories:
 *
 * - sites/8080.www.drupal.org.mysite.test
 * - sites/www.drupal.org.mysite.test
 * - sites/drupal.org.mysite.test
 * - sites/org.mysite.test
 *
 * - sites/8080.www.drupal.org.mysite
 * - sites/www.drupal.org.mysite
 * - sites/drupal.org.mysite
 * - sites/org.mysite
 *
 * - sites/8080.www.drupal.org
 * - sites/www.drupal.org #THIS PATTERN WILL MATCH
 * - sites/drupal.org
 * - sites/org
 *
 * - sites/default

More info here, https://github.com/drupal/drupal/blob/17ebfff72673728bc8495d67f35061ad8bdcc299/sites/default/default.settings.php#L13

> My .htaccess under either my /public_html, public_html/addondomain.com, or /public_html/addondomain.com/drupal?
Could you explain a bit more why you have .htaccess files under /public_html/addondomain.com and under /public_html/addondomain.com/drupal?
I think I get my last question (above crossed out, leaving for reference of others). You created a directory under addondomain.com for drupal, /drupal. Now you are trying to access it via a subdomain. If you want to access it without /drupal at the end you should update the symlink to ln -s addondomain.com/drupal sub.addondomain.com

Drupal multi-site in an add-on domain?


Formatando valores com NumberFormatter() Swift

Question: Tenho uma função que desejo formatar os valores para decimais com o padrão brasileiro.
Hoje minha função está assim ...
func formatNumberToDecimal(value:Double) -> String {
        let numberFormatter = NumberFormatter()
        numberFormatter.numberStyle = NumberFormatter.Style.decimal
        numberFormatter.groupingSeparator = "."
        return numberFormatter.string(from: NSNumber(value:defaultValue)) ?? "Valor indefinido"
}

Mas ela retorna com um valor no formato EN por exemplo:
formatNumberToDecimal(1000.00)
// retorna o valor -> 1.000,00

Gostaria de saber como posso transformar para pt_br com duas casas após a virgula. No exemplo acima ele deveria retornar 1.000,00
Answer: A classe NumberFormatter possui uma propriedade locale, que pode ser atribuída para customizar o Locale usado como base nas formatações de números.
Segundo sua documentação, Locale é uma classe que possui convenções linguísticas, culturais e tecnológicas que devem ser usadas para formatar valores para exibição.
Desta maneira, você pode atribuir o locale desejado na instância de NumberFormatter que está usando, e fazer o seguinte para obter a formatação correta para "pt_BR", como você deseja:
func formatNumberToDecimal(value:Double) -> String {
    let numberFormatter = NumberFormatter()

    // Atribuindo o locale desejado
    numberFormatter.locale = Locale(identifier: "pt_BR")

    // Importante para que sejam exibidas as duas casas após a vírgula
    numberFormatter.minimumFractionDigits = 2

    numberFormatter.numberStyle = .decimal

    return numberFormatter.string(from: NSNumber(value:value)) ?? "Valor indefinido"
}

Comment: Formatter tem um method chamado `string(for: Any)` que voce pode passar um Double direto pra ele. Não tem necessidade de criar um objeto NSNumber `numberFormatter.string(for: value) ?? "Valor indefinido"`


Is "Does Theory/model X align with data?"-type of questions off-topic in Economics.se?

Question: The question  "Which school of economic thought aligns with past data better: Keynesian or Austrian?" has been put on hold as (generating answers that would be) "primarily opinion-based". The standard text accompanying this on-hold reason reads

"Many good questions generate some degree of opinion based on expert experience, but answers to this question will tend to be almost
  entirely based on opinions, rather than facts, references, or specific
  expertise."

"Alignment with data?" is one activity where Economics routinely "generates some degree of opinion based on expert experience", but alongside "facts, references, or specific expertise".
Moreover, "Alignment with data?" is one of the major challenges and points of assessment of economic models.
So I don't see why the question in question was closed as "primarily opinion-based". As I stated in the answer I provided, the question was rather "too broad" -but sometimes it is useful to say "this is difficult to assess" or "there does not appear to be any serious work on the matter". Sometimes, interesting questions may have "disappointing" answers like that, which nevertheless, are still useful.
I believe it would be helpful if the people that voted to close for the "opinion-based" reason shared their viewpoints as answers to this thread, so that maybe some collective guidance emerges as to how we should approach and assess future questions of this type.
Answer: I guess the issue is exactly what you stated in your answer:

First, the "empirical usefulness" of Keynesian, neo-Keynesian, meta-Keynesian, post-Keynesian, post-meta-Keynesian, after-Keynesian, beyond-Keynesian, etc models and theory strands, is one of the "everyday issues" in Economics, and there can be no single verdict on the matter

I don't think that most of these quantitative papers would give us anything but noise. This can be seen from how often theories have been "falsified" by data, only leading to followers of that theory saying "Yes, but this is a special case, and doesnt cound, because XYZ".
To the extent that the best answer - in my opinion - is an answer about there being no answers, and most likely many answers would rather be in style of the other answer (i.e., very political), I voted for closing. "There being no good answer" is sufficiently short for being put as a comment, and closing it prevents unscientific/opinion-based answers.
But I also see how, if we trust on having sufficient activity, we can let these questions open and down-vote the "bad" answers. Given my bad experience in the minimum wage question (many bad answers only at -1, and one relatively bad one - by my standards - even at +5), I chose to rather vote strictly.


Generation of synthetic data for Hierarchical clustering

Question: I wanted to test various hierarchical clustering algorithms to check which algorithm performs best. For this, I was considering simulating some ground truth. Is the possible to generate a correlation matrix having hierarchical structures whose hierarchical components (which can be overlapping) are known? I can generate a correlation matrix having one level structures but I don't know how to generate correlation matrices having 2 level structures.
Comment: Would method such as Stochastic Kronecker Graph Generation, Multiscale Planar Graph Generation work?
Answer: Derive them from generated data.
First generate data with the desired properties of nested structures.
Then compute the pairwise correlation matrix.
Comment: Can you please describe in detail?


Set-theoretical subleties in the equivalence between sets over $J$ and functors on $J$

Question: In the book Sheaves in Geometry and Logic by Moerdijk and MacLane it says on pages 28 and 29:

Each such object $h: X \to J$ over J determines a $J$-indexed
family $\{H_j \mid j \in J\}$ of sets, consisting of the sets
$$H_j = h^{-1}\{j\} = \{x \mid x \in X\ and\ hx =j\},$$
and then each arrow $f: h \to h'$ as in (8) determines a $J$-indexed family
of functions $f_j: H_j \to H_j$, $j \in J$. If we regard the set $J$ here as a
discrete category ..., then each $J$-indexed family of sets is just a
functor $H: J \to Sets$ and each $J$-indexed family of functions $f_j$ is just
a natural transformation $F: H \to H'$ between these functors. In other
words, the assignments $h \mapsto \{H_j\}$, $f \mapsto \{f_j\}$ constitute a functor
$$L: Sets/J \to Sets^J,$$
from the comma category to the functor category.
Reciprocally, each functor $H: J \to Sets$ determines a set $h: X \to J$
over $J$, with $X$ the disjoint union (the coproduct) $X = \coprod H_j$ of the sets
$H_j$ for $j \in J$ and $h$ the function which sends each $x \in X$ into its "index"
(that $j \in J$ with $x \in H_j$). These two reciprocal constructions amount
to constructing two functors $L$ and $M$
$$L: Sets/J \leftrightarrows Sets^J: M$$
with both $LM$ and $M L$ naturally isomorphic to the respective identity
functors. Therefore, these two constructions provide an equivalence of
the comma category $Sets/ J$ to the functor category $Sets^J$. This equivalence is not an isomorphism of categories because the composite functor
$M L$ is not the identity, on account of the choice available in the formation of the disjoint union involved in the construction of $M$. (That is,
many different sets over $J$ correspond under $L $ to the same functor on
$J$.)

I don't understand the last, italic, part.
I agree that $ML$ is not equal to the identity (but I also think that $LM$ is not equal to the identity as well, so I don't know why they talk about $ML$).
I don't agree with "(That is,
many different sets over $J$ correspond under $L $ to the same functor on
$J$.)" Firstly, $L$ has nothing to do with taking coproducts, so the text above can't be an explation for that. Also, it's just wrong: $L$ is injective on objects up to equality.
(As usual, $\coprod H_j := \{(j, e)\mid j\in J, e\in H_j\}$. Then I also think that a functor on $J$ can be really recovered up to equality from its corresponding set over $J$. Hence $M$ is injective on objects up to equality as well.)
Can you confirm that what I write is correct? I would be surprised if MacLane would make such elementary mistakes...
Comment: What is "up to equality"?
Comment: "$L$ is injective on objects up to equality" means the same as "$L$ is injective on objects". But I add "up to equality" to mean that here I'm *not* talking about $L$ being injective on objects only *up to isomorphism*: $LX\cong LY\implies X\cong Y$, which is usually the more sensible condition to discuss.
Comment: I see. I agree that with your definition of the disjoint union it has to be injective. (and with that $LM$ is also not identity) Strange.
Answer: I agree with you that $L$ and $M$ are injective on objects. It seems the point Mac Lane and Moerdijk should have made is that $L$ is not surjective, since functors in the image of $L$ have all their values pairwise disjoint. Incidentally, if one replaces the category of arbitrary functors on $J$ with the image of $L$ (that is, the category of functors with pairwise disjoint values) then one gets a reasonably natural isomorphism of categories replacing the equivalence discussed here by replacing $M$ with the union, rather than the disjoint union, of the values. It is not unheard of for Mac Lane to make simple mistakes; you can find at least one more example on this site. But it is indeed not very common.


Trabalhando com Git no dia a dia com dois computadores diferentes

Question: Tenho dois locais de trabalho onde trabalho em um projeto onde uso o controle de versão GIT. Em meus estudos já aprendi algumas coisas sobre o GIT usando o BitBucket.
Vamos pensar no seguinte cenário:

Meu branch para deploy é o "master".
Sempre que vou desenvolver estarei em um branch "dev".
Computador Casa.
Computador Escritório.

Estou trabalhando de casa em uma primeira melhoria e para isso crio pela primeira vez o branch "dev".
git branch dev
git checkout dev

Ok, fiz as melhorias, fiz os commits no branch dev e agora vou mandar tudo para o bit bucket (lembrando que estou no branch dev)
git push origin dev

Mandei minhas alterações pro Bit Bucket e agora vou ter que ir pro Escritório trabalhar de la.
Chegando no escritório eu faço o clone do meu repositório e em um primeiro momento ele vai vir vazio já que lá estarei no branch master. Então dou o comando para ver todos os branch
git branch -a

e tenho como resultado
remotes/origin/HEAD -> origin/master
remotes/origin/master
remotes/origin/dev

Então crio um branch no computador do escritório baseado no branch remoto dev
git checkout -b dev origin/dev

Faço as alterações do meu projeto pelo computador do escritório, dou commit nessas melhorias e mando pro servidor para o branch dev
git push origin dev

Agora estou voltando para casa e vou continuar a trabalhar no projeto. Então dou o comando git pull para baixar as últimas alterações. Só que eu já tenho no computador de casa o branch dev. Então eu faço o seguinte:
git ckeckout -b dev_escritorio origin/dev

Ok, agora tenho a versão neste branch (dev_escritorio) com as melhorias que fiz por lá. Só que quero continuar as melhorias pelo meu branch dev então eu faria:
git checkout dev
git merge dev_escritorio

Bom é isso, eu queria saber se esse é mesmo a melhor maneira quando você tem que trabalhar com dois computadores diferentes usando git, branch, etc.
Answer: Você complicou-se a partir deste ponto:

Agora estou voltando para casa e vou continuar a trabalhar no projeto. Então dou o comando git pull para baixar as últimas alterações. Só que eu já tenho no computador de casa o branch dev. Então eu faço o seguinte...

Basta você dar sequência no desenvolvimento, apenas atualizando sua branch local:
git ckeckout dev;
git pull;

Depois fazer o push para a origin e continuar este ciclo, pull -> commit -> push
Entretanto,
recomendo um fluxo mais avançado com o uso de branchs tópicasm como você encontrará exemplificado no capítulo Branching Workflows e o uso do hack e ship mas isto você deixa mais para frente em seus estudos :)

Fonte da imagem: git-scm.com
Comment: Então se eu der um git pull quando meu branch atual é o "dev" ele baixaria do repositório somente as alterações desse branch?
Comment: @rodrigoum exatamente. Entretanto, aconselho o estudo do uso de branchs tópicas, e de um fluxo mais avançado (complementarei minha resposta falando sobre este fluxo)
Comment: Se na hora do pull o git disser que não sabe qual branch pegar, use `git pull origin dev`. @rodrigoum
Comment: @gpupo muito obrigado pelas informações. Como é bom ter um histórico de tudo que fiz :D
Answer: Sugeriria utilizar a estrutura de git flow.
Você teria a branch master que é exclusiva para deploy
Branch develop para ir recebendo as features conforme for finalizando cada nova funcionalidade
Então tanto em casa como no trabalho você daria um publish nas funcionalidades para poder trabalhar nos dois locais de forma mais organizada.
Sugiro ver:
https://danielkummer.github.io/git-flow-cheatsheet/index.pt_BR.html


How to solve the collision of TAB key mapping of `UltiSnips` plugin in the Vim

Question: I've set the mapping keys as follows:
" Easy indent for code blocks
  nmap <tab>      v>
  nmap <s-tab>    v<
  vmap <tab>      >gv
  vmap <s-tab>    <gv

That works good. But, when I installed UltiSnips by vundle, the Tab key does't work as indent action, it will remove multi-line codes which I selected. I know this is because the default setting of UltiSnips. I would like to remain the Tab mapping for UltiSnips to trigger its functions, How do I solve the problem of using the TAB key to indent code blocks? Thanks!
Answer: Looking at UltiSnips documentation via :h UltiSnips-triggers says this:
You can define the keys used to trigger UltiSnips actions by setting global
variables. Variables define the keys used to expand a snippet, jump forward
and jump backwards within a snippet, and list all available snippets in the
current expand context. The variables with their default values are: >
   g:UltiSnipsExpandTrigger               <tab>
   g:UltiSnipsListSnippets                <c-tab>
   g:UltiSnipsJumpForwardTrigger          <c-j>
   g:UltiSnipsJumpBackwardTrigger         <c-k>

So set something like this in your ~/.vimrc` file:
let g:UltiSnipsExpandTrigger = '<f5>'

However you may want to reconsider your <tab> mappings. I suggest you remove them and use >> or << in normal mode and > or < in visual mode to do the initial indent/un-indent then repeat the action via ., the redo command. If you ever indent/un-indent too far then just undo it via u.
For more help see:
:h >>
:h .
:h u

Comment: In my case `tab` collided with the supertab plugin. Note if you're using vim over putty then certain key combos may not work out of the box such as `` or `` in that case try something like `let g:UltiSnipsExpandTrigger = ''` which also has the benefit of being more comfortable to type than ``
Comment: @PeterRincker When I use any function key e.g. ``, it just types `` while in insert mode. It works in gvim, however. But my problem with Putty persists :/
Answer: You can change the default expand trigger  to other key, but I think It's better to use maps as follow:
nnoremap > v>
nnoremap < v<
vnoremap > >gv
vnoremap < <gv

It works well for me.
What's more, <Tab> remove multi-line codes which you selected is a feature of UltiSnips. You can use selected text in UltiSnips snippets. Have a look at here.


Achieving very fast (300+MB/sec) file transfer on Linux

Question: I'm working with high end hardware, however I'm hitting cpu bottlenecks in all situations when attempting to move large amounts of data.
Specifically, I'm moving large virtual machine image (VHD) files of 2TB  between two Ubuntu hosts.
My latest attempt took 200 minutes to transfer 2TB.  Resulting in a throughput of about 170MB/sec transfer.
I'm trying techniques such as netcat, and scp with basic arcfour cipher.
The hardware on each end is 6 x enterprise grade SSDs in RAID 10, on a hardware raid controller.  256GB memory, and Xeon V4 CPUs.  Network is 20Gbe ( 2 x 10Gbe LACP ).
In all cases, the network and disk i/o has plenty of capacity left, the bottleneck is pegging 1 CPU core to 100% constantly.
I've performed basic benchmarks using various methods, as follows:
30GB test file transfer
scp:
real    5m1.970s
nc:
real    2m41.933s
nc & pigz:
real    1m24.139s
However, because I dd'd an empty file for testing, I don't believe that pigz was having to work too hard. When I attempted pigz on a production VHD file,  pigz hit  1200% CPU load, I believe this started to become the bottleneck.  Therefor my fastest time was set by nc on it's own.
nc hits 100% CPU on each end, I'm assuming just processing the i/o from the disk to the network.
I did think about splitting the file into chunks and running multiple nc to make use of more cores, however, someone else may have a better suggestion.
Comment: Would you add details such as network infrastructure and hardware? And what about RAM amount and its usage? Was scp run with or without compression? Pigz is hitting all cores because it supports multiple threads but I don't think scp does. Therefore it sooner has data available to be sent through nc and it achieves much faster throughput .
Comment: Also test your network bandwidth with `iperf`/`iperf3` and post the results.
Comment: Apologies, should have had the network in from the start.  It's 20Gbe (2 x 10Gbe LACP), network bandwidth isn't the issue as I can see nc hitting 100% cpu and staying there.

Just tested further with pigz, it's using about 800% on sending, however I've just read Pigz can't offer multi threaded decompression, so it's the receiving end which is holding it up on a single thread.

Also tested netcat with udp mode, no difference vs tcp on that, also tried udp-sender and udp-receiver, single theaded udp sender maxes out 1 core.
Answer: A few thing to try:

use a program that uses sendfile (e.g. apache)
tune the Linux network stack and NIC
enable a larger MTU
enable NIC offloading
use a better performing filesystem (xfs or zfs)

The ESnet Fasterdata Knowledge Base is a great resource for optimizing moving data across fast networks.
Answer: Are your endpoints physically near each other? Maybe consider a different network medium which is designed for moving buttloads of data around. CPU processing can be offloaded to an adapter card and your ethernet wont be saturated for minutes at a time.
Below is a (low-end) Infiniband setup that cost around $500 bucks from Ebay parts (Mellanox IS5022 switch, 2 CX353A QDR cards (maybe FDR, don't remember) and (new) cables). I ran dd from a hypervisor with 20+ VMs running on it so there is a fair amount of I/O delay in it. The SSD transfer (an iSCSI mount) is still noteworthy however.
To a SATA array (RAID 10):
# time dd if=/dev/zero of=foo.bin bs=1M count=30000
30000+0 records in
30000+0 records out
31457280000 bytes (31 GB, 29 GiB) copied, 106.652 s, 295 MB/s

real    1m52.795s
user    0m0.022s
sys     0m12.531s

And to an SSD array
# time dd if=/dev/zero of=foo.bin bs=1M count=30000
30000+0 records in
30000+0 records out
31457280000 bytes (31 GB, 29 GiB) copied, 19.1353 s, 1.6 GB/s

real    0m19.137s
user    0m0.020s
sys     0m18.782s

Comment: Yes it's in the same rack.  Network is 10Gbe (should have mentioned that).  I don't have the ability to get infiniband into it due to lack of pcie space. That 1.6GB/s is impressive though.  Perhaps an NFS mount may be faster, i'm expecting i should get close to saturating the link, if I can just around the CPU issue.
Answer: It's been a while since I posted this and it's getting some views, in the end I used bbcp: https://github.com/eeertekin/bbcp to saturate the network, it works extremely well.


Problem with flipping images in Pygame (python)

Question: I am trying to create a game in which you can move a character with arrow keys. When moving left or right, I want the character (an image) to flip and point left/right accordingly. The original image/character is pointing left.  But I cannot get the character to flip, please help me, thanks.
import pygame
pygame.init()#initiate pygame
black = (0,0,0)
white = (255,255,255)
red = (255,0,0)
display_width = 1200
display_height = 800
display = pygame.display.set_mode((display_width,display_height))
characterimg = pygame.image.load(r'/Users/ye57324/Desktop/Make/coding/python/characterimg.png')
def soldier(x,y):
    display.blit(characterimg, (x,y))
x = (display_width * 0.45)
y = (display_height * 0.1)
pygame.display.set_caption('Game')
clock = pygame.time.Clock()#game clock
flip_right = False
x_change = 0
y_change = 0
start = True

while start:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            start = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                x_change += -5
                if flip_right == True:
                    pygame.transform.flip(characterimg, True, False)
                    flip_right = False
            elif event.key == pygame.K_RIGHT:
                x_change += 5
                if flip_right == False:
                    pygame.transform.flip(characterimg, True, False)
                    flip_right = True
            elif event.key == pygame.K_UP:
                y_change += -5
            elif event.key == pygame.K_DOWN:
                y_change += 5
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT:
                x_change += 5
            elif event.key == pygame.K_RIGHT:
                x_change += -5
            elif event.key == pygame.K_UP:
                y_change += 5
            elif event.key == pygame.K_DOWN:
                y_change += -5

    x += x_change
    y += y_change
    display.fill(white)
    soldier(x,y)
    pygame.display.update()
    clock.tick(60)#fps

Comment: You're never changing the value of `flip_right`. I'm assuming you meant to adjust its value after you flip the image to reflect eh direction your character is currently looking.
Comment: Oh yeah right, but after I added it, it still doesnt work
Comment: I just looked up the documentation of `flip`, as you could've done. It says "Flipping a Surface is non-destructive and returns a new Surface with the same dimensions.". This means the surface you path isn't altered, i.e., you should write `characterimg = pygame.transform.flip(characterimg...)`. Learn to read the docs! :)
Comment: Read it up yourself: https://www.pygame.org/docs/ref/transform.html#pygame.transform.flip
Comment: This means that the method `flip` doesn't alter any data contained in the surface you pass, i.e. `characterimg`. It only reads the data and then writes the flipped image onto a _new_ surface, which it then returns. (PS: I meant to  say "the surface you **pass** isn't altered"). This is why you have to overwrite your `characterimg` variable. So that it contains the new, flipped version of your surface.
Comment: No, I'm **re**-assigning `characterimg`. Your `characterimg` is the surface that you blit in your `soldier` method, right? So whatever surface `characterimg` currently points to gets blitted on screen. So we need to make `characterimg` to point to the new, flipped version returned to by pygame.transform.flip(...).
Comment: @Nearoo Thank you so much! I solved it!
Comment: @Nearoo you should post that as an answer.
Comment: I'd also remove the `flip_right` variable and create the left and right images beforehand. Then you can just assign the current image to the `characterimg` variable when the user presses left or right, e.g. `characterimg = characterimg_left` and `characterimg = characterimg_right`.
Comment: @skrx good point. I've added this to the answer.
Answer: Pygame's doc-page about pygame.transform.flip states

Flipping a Surface is non-destructive and returns a new Surface with the same dimensions.

This means that the surface you pass to that method remains unaffected. You have to keep the return-value around in order to see any effect.
In practice, this means that you should replace
pygame.transform.flip(characterimg, True, False)

with
characterimg = pygame.transform.flip(characterimg, True, False)

So that characterimg point to the new, flipped version of the image.
Note: Performance wise, this is not a very good method of doing things. Each time you call pygame.transform.flip, pygame has to allocated new memory for the new surface, go over each pixel of the original surface and copy it over to the new surface, transforming its position in the process. You'd better flip the image once at the beginning of your program, so that you have a variable characterimg_left and characterimg_right and then just assign those to your characterimg variable.


Como calcular a idade de uma pessoa no SQL Server?

Question: Suponha a tabela Pessoa e o campo DataNascimento.
Em uma consulta SQL, qual a melhor forma de se calcular a idade de uma pessoa em formato inteiro na linguagem T-SQL do SQL Server?
Comment: As respostas que usam datediff calculam a idade matemática, mas a idade como é aceita em formulários depende do dia do mês.
Comment: Alguma resposta ajudou a resolver o problema e pode sanar dúvidas similares de outros usuários? Caso positivo não esqueça de marcar a resposta como aceita. Pra fazer isso é só clicar no ✓ do lado esquerdo da mesma (abaixo do indicador de up e down votes).
Answer: O jeito mais correto que conheço é:
SELECT FLOOR(DATEDIFF(DAY, DataNascimento, GETDATE()) / 365.25)

Esta forma é mais correta que utilizar as horas de um ano (como @rodrigorgs sugeriu) pois a hora do dia em que a query é executada não é considerada. Em alguns casos, se uma pessoa faz aniversário no dia seguinte ao dia de hoje, a query considerando as horas irá informar como se a pessoa já tivesse feito aniversário, quando na verdade não fez (a não ser que ela seja executada exatamente no horário 00:00).
Exemplo:
DECLARE @DataNascimento DATETIME = '1991-12-12'
DECLARE @Hoje DATETIME = '2013-12-11 17:00:00' -- exemplo de horário da função GETDATE()
                           -- funciona corretamente se alterado acima para hora 00:00:00

SELECT FLOOR(DATEDIFF(DAY, @DataNascimento, @Hoje) / 365.25) -- retorna 21, idade correta
SELECT DATEDIFF(HOUR, @DataNascimento, @Hoje) / 8766 -- retorna 22

Comment: Esta forma falha em algumas situações, por exemplo, considerando a @DataNascimento `07/01/1987` e @Hoje `07/01/2016`, retorna 28 quando o correto é 29. Isto porque o valor mais preciso para divisão deveria ser `365.23076923074`.
Comment: @ricidleiv, de onde saiu esse número todo? Sei que um ano possui 365 e 4 horas, porém no banco, como isso se comporta para fins matemáticos?
Comment: @bruno101 O número se dá porque um ano não tem exatamente 365 dias e 4 horas, mas 365 d 06h 09 mim 13 s.
Comment: @ricidleiv, aquele valor é a conversão desses 6d, 9 min e 13s então, é isso?
Answer: Prefiro ir pro lado mais extenso e seguro e usar uma função com lógica tradicional de cálculo de idade, para não ter problemas com arredondamento e fórmulas:
SELECT YEAR(dHoje)-YEAR(dNasc)-IIF(MONTH(dHoje)*32+DAY(dHoje)<MONTH(dNasc)*32+DAY(dNasc),1,0)

Você pode trocar o dHoje por GETDATE() (CURDATE() no MySQL) ou mesmo CURRENT_TIMESTAMP quando for aplicar na base de dados. Fiz com variáveis o exemplo para que se possa testar facilmente usando DECLARE (entretanto, lembre de por @ antes das variáveis).
Notas:

Usei 32 como multiplicador do mês apenas como boa prática (potência
de 2), mas sendo de 31 pra cima está ok;
Como não consideramos hora no cálculo de idade, o IIF está ajustado para que o numero de anos de idade "suba" exatamente no dia do aniversário da pessoa;
Lembre-se de que neste caso estamos considerando o aniversário dos nascidos em 29 de fevereiro como sendo 1 de março nos anos não bissextos. Caso prefira de outra forma provavelmente vai ter que acrescentar uma condição especial para isso;
Finalmente, caso queira usar isso em outros "dialetos" de SQL, como no MySQL por exemplo, troque o IIF por IF.
Answer: Pensando na vida real, em quando queremos saber nossa idade, a gente simplesmente pensa da seguinte maneira:
se eu nasci em 1990: tenho 29 anos ou tenho 28 anos (Diferença em anos entre o ano do meu nascimento e o ano atual).
Terei 29 se eu já fiz aniversário neste ano (se a data atual em relação a dia e mês já passou da minha data de aniversário) e;
terei 28 se ainda não fiz aniversário este ano.
Seguindo este raciocínio, conseguimos chegar a esta lógica, em sql:
DECLARE @dataNascimento Date = '2016-1-1';
DECLARE @dataReferencia Date = '2020-12-31'

select
(
    CASE
        WHEN
        MONTH(@dataReferencia) > MONTH(@dataNascimento) -- *1
        OR
        -- *2
        (
            MONTH(@dataReferencia) = MONTH(@dataNascimento)
            AND DAY(@dataReferencia) >= DAY(@dataNascimento)
        )
    THEN DATEDIFF(YEAR, @dataNascimento, @dataReferencia)
    ELSE DATEDIFF(YEAR, @dataNascimento, @dataReferencia) -1 END
) AS IDADE;

*1 : Basta que O mês da data atual seja maior que o mês do meu aniversário, que devemos considerar já ter feito aniversário no ano corrente (dataReferencia).
*2 : Ou, como o mês da data atual ainda não é maior que o mês do meu aniversário, os meses devem ser iguais e o dia do mês atual maior ou igual o dia do meu aniversário.
Agora é só testar com alguns exemplos.
Obs: considerando quem nasceu no dia 29/02, esta pessoa sempre faria aniversário no dia 01/03 para anos não bissextos (?) . A lógica aplicada segue este raciocínio.
Comment: A forma natural de contarmos a idade é a mais assertiva. Todas as fórmulas que envolvem operações de divisão falham em algum momento.
Answer: Você pode pegar a data de hoje usando getdate() e subtrair a data do registro banco usando DATEDIFF:
SELECT DATEDIFF(hour, DataNascimento, getdate()) / 8766 FROM Pessoa

8766 é o número de horas em um ano (aproximadamente, pois há anos bissextos).
Fonte: https://stackoverflow.com/questions/1572110/how-to-calculate-age-in-years-based-on-date-of-birth-and-getdate.
Answer: O método mais preciso de calcular a idade no SQL Server é considerar o dia de nascimento e o dia base do cálculo e calcular a diferença de anos com DATEDIFF. A função abaixo realiza o cálculo:
IF OBJECT_ID('calcular_idade', 'FN') IS NULL
BEGIN
  EXEC('CREATE FUNCTION calcular_idade() RETURNS INT AS BEGIN RETURN 1 END');
END;
GO

ALTER FUNCTION calcular_idade(@nascimento DATE,
                              @data_base  DATE)
RETURNS INT
AS
BEGIN
  DECLARE @idade      INT;
  DECLARE @dia_inicio INT;
  DECLARE @dia_fim    INT;

  SET @data_base = ISNULL(@data_base, GETDATE()); -- Caso seja nula considera a data atual
  SET @idade = DATEDIFF(YEAR, @nascimento, @data_base);
  -- Deve ser feito dessa forma por conta do ano bissexto
  -- Por exemplo: dia 16/06 ficará 616 e 14/12 ficará 1214
  SET @dia_inicio = (MONTH(@nascimento) * 100) + DAY(@nascimento);
  SET @dia_fim = (MONTH(@data_base) * 100) + DAY(@data_base);

  -- Se ainda não passou no ano base
  IF @dia_fim < @dia_inicio
  BEGIN
    SET @idade = @idade - 1;
  END;

  RETURN @idade;
END;
GO

A chamada com a data atual (28/07/2017) resultado 29 anos para a data de nascimento 16/06/1988 seria a seguinte:
SELECT dbo.calcular_idade('1988-06-16', '2017-07-28') AS idade

Resultando em:
╔═══╦═══════╗
║   ║ idade ║
╠═══╬═══════╣
║ 1 ║ 29    ║
╚═══╩═══════╝

ISNULL
Substitui NULL pelo valor de substituição especificado.

GETDATE
Retorna o carimbo de data/hora do sistema do banco de dados atual como um valor datetime sem o deslocamento de fuso horário do banco de dados. Esse valor é derivado do sistema operacional do computador no qual a instância do SQL Server está sendo executada.

DATEDIFF
Retorna a contagem (inteiro com sinal) dos limites especificados de DATEPART cruzados entre os parâmetros especificados startdate e enddate.

MONTH
Retorna um inteiro que representa o mês da date especificada.

DAY
Retorna um inteiro representando o dia (o dia do mês) da date especificada.
Comment: Show! Testado e aprovado!

SELECT dbo.calcular_idade('1973-07-01', GETDATE()) AS idade

Valeu!
Answer: declare @dataNasc datetime ='1973-06-03'

SELECT
idade= convert (int, convert( decimal,convert (varchar( 10), getdate(), 112)) /10000 - convert( decimal,convert (varchar( 10), @dataNasc , 112)) /10000 )

Answer: Caros amigos, eu acabei desenvolvendo este script para rodar em Access:
iif(year(Date())-year([DATA DE NASCIMENTO])<=0,0,iif(month(date())>month([DATA DE NASCIMENTO],year(Date())-year([DATA DE NASCIMENTO],iif(day(date())>day([DATA DE NASCIMENTO],year(date())-year([DATA DE NASCIMENTO],(year(date())-year([DATA DE NASCIMENTO])-1))) as IDADE

Rodou perfeitamente na versão 360, onde [DATA DE NASCIMENTO] deve ser o campo na tabela ou view (consulta) que contenha a data de nascimento da pessoa a ser calculada a idade. Testei até com Bi-Sexto e funciona bem.
Answer: Fiz de um modo diferente, bem simples, mas não sei se pode trazer algum tipo de erro, com relação a ano bissexto ou outra coisa, deem uma olhada e comentem, ok
se tiver algum problema, se puderem me comunicar seria muito bom!
declare @data1 datetime set @data1 = '02/02/2000'
declare @data2 datetime set @data2 = '12/28/2000'
declare @data3 datetime set @data3 = '12/28/1977'

select year(GETDATE() - @data1)-1900 union
select year(GETDATE() - @data2)-1900 union
select year(GETDATE() - @data3)-1900

Comment: Considerando alguém nascido no dia 29/02 em ano bissexto, desta forma ele considera aniversário já no dia 28/02.
Answer: Precisei agorinha e fiz de duas formas:
declare @dt_nasc datetime = '2002-10-16',
  @agora datetime = getdate(),
  @idade int
select @idade = year(@agora)-year(@dt_nasc)
if dateadd(year,@idade,@dt_nasc) > @agora
  set @idade -= 1
print @idade

ou dentro do select...
select idade = year(getdate())-year('2002-10-16')-
  case when
    dateadd(year,year(getdate())-year('2002-10-16'),'2002-10-16') > getdate() then 1
    else 0
  end

Comment: Sua resposta pode ser melhorada adicionando informações fundamentais. Basta [edit] para adicionar mais detalhes, como citações ou documentação para que outras pessoas possam confirmar que sua resposta está correta. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).


RecyclerView doesn´t keep items scrolled at bottom when softkeyboard pops up

Question: When I focus on an edittextview on my chat activity, the recyclerview doesn´t keep the items stacked at the bottom when resizing the view. Previuosly with a ListView was working. I´ve tried any stackFromEnd, reverseLayout parameter.
Basically I want the same behaviour as any chat: whatsapp, telegram, etc.
Somebody has any idea why does it happen?
Answer: I had the same situation, and this is how it is fixed:
Use mLayoutManager.setStackFromEnd method in code. Setting in XML is not respected by android (in my situation).
    mLayoutManager = new LinearLayoutManager(this);
    mLayoutManager.setStackFromEnd(true);
    mRecyclerView.setLayoutManager(mLayoutManager);

Comment: `mLayoutManager.setStackFromEnd(true);` works for me. Thank you!
Comment: Thank you. Exactly what i search


How many odd coefficients will there be when expanding $(x^2+x+1)^{33}$

Question:
How many odd coefficients will there be when expanding $(x^2+x+1)^{33}$

This question seems hard to me because of the $x^2$. I tested it out on wolfram alpha and I got $6$ odd coefficients (coefficients of $x^0 \text{, } x^1 \text{, }x^2 \text{, } x^{64} \text{, } x^{65} \text{, } x^{66}$). I tried to use logic to see the different ways of getting $x^n$ but I am unable to keep track as we can go all the way to $x^{66}$. Is there any simple and algebraic way to prove it. Thank you anyways.
Answer: If you know about the Frobenius Automorphism, you can work modulo 2 and write $(x^2+x+1)^{33}=(x^2+x+1)^{2^5}×(x^2+x+1)=(x^{2^6}+x^{2^5}+1)(x^2+x+1)$ and from here we see there is enough space between $1$, $2^5$ and $2^6$ so that the answer is $3×3=9$. I think you forgot some coefficients in the middle of the expression around the coefficient of $x^{32}$.
(I initially posted a comment but this is an answer after all.)
Answer: We have that
$$[x^n](1+x(1+x))^{33}=[x^n]\sum_{j=0}^{33}\binom{33}{j}x^{33-j}(1+x)^{j}=\sum_{j=0}^n\binom{33}{j}\binom{j}{n-j}.$$
Now note that by Lucas's Theorem $\binom{33}{j}=\binom{32+1}{j}$ is odd for $j=0,1,32,32+1$ and even otherwise. Hence
$$[x^n](1+x(1+x))^{33}\equiv \binom{0}{n}+\binom{1}{n-1}+
\binom{32}{n-32}+\binom{33}{n-33}\pmod{2}.$$
It is easy to verify that the right-hand side is odd if and only if $n=0,1,2,64,65,66$ (recall that for any non-negative integer $N$, $\binom{N}{K}=0$ when $K<0$ or $K>N$).


C++ array of base class which has instances of derived classes stored in the elements of the array

Question: I am creating an application that allows a user to define dimensions for different shapes and returns the area to the user using the dimensions they specified.
My base class is Shape. Derived classes are Triangle, Circle, Square and Rectangle.
I have created an array of Shape in the hope of creating and storing instances of any of the derived classes in the array during runtime.
Shape** shape = new Shape*[TOTAL_SHAPES];

shape[i] = new Circle(radius);

I have managed this, however I am unable to access the instantiated classes methods. Sorry if this is a stupid question I am fairly new to C++.
Comment: The instantiated methods need to be virtual methods of base class. Otherwise you need to downcast.
Comment: "Unable" how? Explain.
Comment: Please show the class definition and just the area function, either your inheritance or virtual function is likely not defined quite right
Answer: Let's assume your types had the following definition
class Shape {
public:
  void Method1() { ... }
};

class Circle : public Shape {
  void Method2() { ... }
}

With this definition you could access methods on Shape by doing the following
shape[i]->Method1();

In this context though it wouldn't be possible to access Method2 though because the compiler only knows about Shape, not Circle.
shape[i]->Method2(); // Error!

Comment: Shouldn't Method be virtual?
Comment: @GlennTeitelbaum - no it doesn't need to be virtual. You can call any public methods on the base class. If it was virtual then it could be overriden by the derived class in which case the derived class Method would be called.
Comment: @GlennTeitelbaum it could be virtual but it does not need to be for this sample to work
Answer: You have three options:

Make Shape an abstract base class and call virtual methods that are members of Shape
Use static_cast to cast from a Shape* to a Circle*, and call methods through that.
Use dynamic_cast to cast from a Shape* to a Circle*, and call methods through that.

The first option is likely best in many cases.  Among other reasons, you almost surely need to have a virtual destructor (which can be a by-product of making Shape an ABC), and you may prefer to not have to know what type of object is being pointed to, rather you'd like to simply call methods on whatever it may be.  If you can use this idiom, use it.
The second option is dangerous.  You must absolutely know that the object being pointed to is a Circle (or whatever) in order to use static_cast, else you will get Undefined Behavior.
The third option is only possible if your class is polymorphic, which means Shape must have at least one virtual method.  You surely should have a virtual destructor, and this would serve that purpose.
Answer: How about that:
shape[i]->aMethod();

Comment: @Mark: Please get into the habit of going further than just saying "it doesn't work". You need to explain, in detail, what happens.
Comment: Sorry but it doesn't seem to work, neither does the dot operator.
Answer: For starters, I highly recommend using a smart pointer wrapper instead of using raw pointers (especially if you are new to the language).
std::vector<std::shared_ptr<Shape>> shapes(TOTAL_SHAPES);

That will define a vector with an initial size of TOTAL_SHAPES.
To the root of your problem, any method you wish to call using a Shape* must be valid for Shape, or you must do a risky downcast to the appropriate type.  For example:
class Shape
{
public:
    // constructors and other methods go here
    virtual ~Shape() { } // virtual destructor

    virtual void Draw() { } // virtual function to be used by derived classes
};

class Circle
{
public:
    // ...
    virtual ~Circle() { }
    virtual void Draw() { } // override the virtual function
};

Then, in your application code,
std::vector<std::shared_ptr<Shape>> shapes(TOTAL_SHAPES);
shapes[0] = std::make_shared(new Circle);
shapes[0]->Draw(); // calls Circle::Draw

Note that depending on your usage, std::unique_ptr may replace std::shared_ptr.


Can I use the Cholesky-method for generating correlated random variables with given mean?

Question: I want to generate correlated random variables with a given correlation matrix, means, and variances. Does the Cholesky decomposition only work when the initial random variables are iids with the same mean and variance?
Comment: If you generate correlated random variables with each having mean zero, then add a constant to each individual variable, what is the outcome?
Comment: Same concept. If you generate correlated random variables with mean 0 and standard deviation 1, then multiply each univariate series by their respective standard deviations, then what is the outcome? Of course, if you have the correlations and variances, you can save yourself the trouble by just using the covariance matrix.
Comment: Okay, but how do I manipulate the variance?
Comment: @John I thought this was a duplicate but I can't seem to locate one, so you might want to consider making your comments into an answer (though you may want to try your own search first).
Comment: kanbhold: [This answer](http://stats.stackexchange.com/questions/76820/generating-normal-random-samples-given-covariance-matrix-and-observations-on-som/76835#76835) deals with a more general case. There's also some good information in the top two answers [here](http://stats.stackexchange.com/questions/38856/how-to-generate-correlated-random-numbers-given-means-variances-and-degree-of), but you'd have to combine them to get what you're asking. Neither is quite a duplicate, so you may get some more direct answers along the lines of John's suggestion.
Comment: @Glen_b I'm surprised there isn't another similar question (I didn't find one either), which is why I didn't do much more than provide suggestions so that he could figure it out himself. I'll write something up.
Answer: Let Z be uncorrelated random variables normally distributed with mean 0 and variance 1. This means
$$Z\sim N\left(0,I\right)$$
If you make an affine transformation
$$X\equiv A+BZ$$
then $X$ has a distribution
$$X\sim N\left(A,BB'\right)$$
In our case, we want $BB'=\Sigma$, so applying the cholesky decomposition to $\Sigma$ is one way to find a suitable $B$. Thus, to simulate from $X\sim N\left(\mu,\Sigma\right)$, you would simulate $Z$, set $A=\mu$ and $B=chol(\Sigma)$, and apply the transformation above.
So to answer your question, uncorrelated variables of mean 0 and variance 1 can be transformed to generic multivariate normal distributions through the use of affine transformations, depending on the mean vector and cholesky decomposition of the covariance matrix. This is how multivariate normal random number generators generally work.
To address your other point in the comments, suppose you simulate $Z$ and make a transformation
$$Y\equiv chol(C)Z$$
so that $Y\sim N(0, C)$. You can still get to $X$ from $Y$. As I discussed in the comments, you can easily do this by multiplying the univariate distributions by the respective standard deviations and adding the respective mean.
More formally, you can consider this another affine transformation
$$X\equiv A+SY$$
However, since $Y$ is not uncorrelated, the affine transformation would give
$$X\sim N\left(A,SCS'\right)$$
In this case, to get $SCS'=\Sigma$, you would need to set $S$ equal to a matrix with the standard deviations on the diagonal and zeros elsewhere. This is equivalent to applying the transformations on a univariate basis.
Comment: great answer, the set up is very clear.
Answer: Additionnal items:
We need to decompose the convariance matrix Σ into orthogonal matrix product as mentionned above.
There are different ways to get the orthogonal matrix B, Cholesky is one of them.
We can also use SVD (Singular Value Decomposition) to get B, equivalent to calculate the eigenvalues/vectors for PDM.
If you want to use the decomposition to simulate brownians over time, you can also use Brownian Bridge with Haar transformation.


Sistema de seguir e postagem (tipo rede social)

Question:
Estou a desenvolver um novo projecto e estou a criar um sistema de seguidores de perfil, em que o objectivo é mostrar apenas as publicações de quem eu sigo.
Como por exemplo o de uma rede social.
Eu sigo a pessoa, portanto recebo as publicações dessa pessoa na pagina inicial.
A minha dificuldade está em mostrar apenas as publicações de quem sigo.

Exemplo:

O que eu penso é que tenho de unir as minhas 2 tabelas em apenas 1 query, mas penso nao consigo usar "UNION" de forma nenhuma...
É provavel que esteja no raciocinio errado, me perdoem...
Aqui ficam as minhas tabelas mysql necessarias.

Já testei varias querys mas nao consegui chegar a uma resolução.
Será melhor fazer 2 querys e comparar com um while ou if?
Se sim... como?
Cumprimentos a todos e obrigado mais uma vez.

PS: Estou a fazer em pdo.
Comment: O problema de PDO é que ele precisa se adequar a qualquer banco de dados, mas nem sempre funciona. Por exemplo, a solução em MySQL é diferente da solução em SQL Server, que tende a ser diferente em PostgreSQL. Genericamente voce faria algo como [SELECT post.* FROM post, follow WHERE follow.userid=post.userid and follow.whofollowid=CODIGO_USER_LOGADO_ATUAL ORDER BY POST.data_registro desc]. Mas você não informou o conteúdo dos campos userid e whofollowid. Eu comparei os userid das duas tabelas, mas talvez seja [WHERE follow.whofollowid=post.userid and follow.userid=CODIGO_USER_LOGADO_ATUAL]
Comment: Pode dizer se funcionou?
Comment: Peço desculpa, so pude voltar hoje. Testarei agora.
Comment: Olá novamente. Muito obrigado pela sua resposta, com algumas alterações funcionou como queria perfeitamente. Muito obrigado. Vou postar em baixo como ficou o codigo.
Comment: SELECT post.* FROM post, follow WHERE follow.whofollowid = post.userid and follow.userid = ? ORDER BY `date` DESC, `time` DESC
Comment: Portanto, eu uso bind's para variaveis que a bind 1 - userid actual logado. = ?, da forma como postou o codigo mostrava os meus post's assim desta forma vai mostrar os post's de quem sigo. Muito obrigado.
Comment: Vou transformar em resposta então pra ficar documentado como solução.  Como fiz no comentário, postarei as duas soluções possíveis.
Answer: O problema de PDO é que ele precisa se adequar a qualquer banco de dados, mas nem sempre funciona.
Por exemplo, a solução em MySQL é diferente da solução em SQL Server, que tende a ser diferente em PostgreSQL.
Genericamente voce faria algo como
SELECT post.* FROM post, follow WHERE follow.userid=post.userid and follow.whofollowid=CODIGO_USER_LOGADO_ATUAL ORDER BY POST.data_registro desc

Mas você não informou o conteúdo dos campos userid e whofollowid. Eu comparei os userid das duas tabelas, mas talvez seja invertido, tal como:
SELECT post.* FROM post, follow WHERE follow.whofollowid=post.userid and follow.userid=CODIGO_USER_LOGADO_ATUAL

Como você mencionou que funcionou para você foi a minha segunda opção que eu tinha postado no comentário (e postei acima também):
SELECT post.* FROM post, follow WHERE follow.whofollowid = post.userid and follow.userid = ? ORDER BY date DESC, time DESC

Comment: "O problema de PDO é que ele precisa se adequar a qualquer banco de dados, mas nem sempre funciona". A ideia do PDO é padronizar somente a conexão e os métodos de consultas com o banco de dados, e não a implementação com o banco com o SQL. Isso não é exatamente um problemas pois seu propósito não é ser uma [camada de abstração do Banco de Dados](https://github.com/doctrine/dbal)
Comment: O comentário é para deixar claro a finalidade do PDO. Ele cumpre o que se propõe a fazer: abstração da camada de acesso aos dados. Não vejo como problema do PDO ter que se adequar aos diversos bancos de dados.
Comment: Conforme eu tinha dito nos comentários da pergunta, já que a minha solução dada foi utilizada por ele, eu transformei em resposta.