Composer not applying patch: exceeded the timeout of 300 seconds

Question: Since my update to the new OSX (Ventura 13) I'm having problems using composer. The biggest problem I have is that my patches aren't patched and end up with and exceeded the timeout of 300 seconds after a while. I didn't change my composer.json file or the patches. This only occurs on my local site, the remote sites run smoothly.
What I tried to fix this is updating and reinstalling composer.
I'm running composer 2.4.4. at the moment.
A regular composer update or composer install works like it should except when I have patches added to the composer.json file. I gets stuck running the patch.
When I do ctrl+c a few times the patch is being patched but is not added to the composer.lock file. I add it to the lock file by hand to have everything working but I want to fix this so I don't have to hack to get everything like it should.
I tried composer install -v but I'm not getting any further. The out put is as follows:
patch '-p1' --no-backup-if-mismatch -d 'public_html/core' < '/var/folders/k0/fk82ww894lvcgdkm2485dyww0000gn/T/638dea49da104.patch'
Executing command (CWD): patch '-p1' --no-backup-if-mismatch -d 'public_html/core' < '/var/folders/k0/fk82ww894lvcgdkm2485dyww0000gn/T/638dea49da104.patch'
File to patch:
   Could not apply patch! Skipping. The error was: The process "patch '-p1' --no-backup-if-mismatch -d 'public_html/core' < '/var/folders/k0/fk82ww894lvcgdkm2485dyww0000gn/T/638dea49da104.patch'" exceeded the timeout of 300 seconds.

One other thing I've noticed is that since the update I get this kind of messages:
composer/installers contains a Composer plugin which is currently not in your allow-plugins config. See https://getcomposer.org/allow-plugins Do you trust "composer/installers" to execute code and wish to enable it now? (writes "allow-plugins" to composer.json)
Because of this I looked at my composer file to see if the patch plugin is added and it is.
"allow-plugins": {
            "composer/installers": true,
            "drupal/console-extend-plugin": true,
            "cweagans/composer-patches": true,
            "drupal/core-composer-scaffold": true,
            "drupal/core-project-message": true
        }

What can I do to find out why the patch is not running and giving me a timeout? And has s the allowed-plugin part anything to do with this?
The full composer.json file contains:
{
    "name": "drupal-composer/drupal-project",
    "description": "Project template for Drupal 8 projects with composer",
    "type": "project",
    "license": "GPL-2.0-or-later",
    "authors": [
        {
            "name": "",
            "role": ""
        }
    ],
    "repositories": [
        {
            "type": "composer",
            "url": "https://packages.drupal.org/8"
        }
    ],
    "require": {
        "composer/installers": "^1.2",
        "cweagans/composer-patches": "^1.6",
        "drupal/addanother": "^1.1",
        "drupal/admin_toolbar": "^3.0",
        "drupal/advagg": "^4.0",
        "drupal/animated_gif": "^1.1",
        "drupal/antibot": "^2.0",
        "drupal/console": "^1.0.2",
        "drupal/core": "^9.0",
        "drupal/core-composer-scaffold": "^9",
        "drupal/core-project-message": "^9",
        "drupal/core-recommended": "^9",
        "drupal/ctools": "^3.0",
        "drupal/devel": "^4.1",
        "drupal/eck": "^1.0@alpha",
        "drupal/editor_advanced_link": "^1.4",
        "drupal/entity_type_clone": "^1.7",
        "drupal/entityqueue": "^1.1",
        "drupal/field_group": "^3.2",
        "drupal/gin": "^3.0@alpha",
        "drupal/gin_login": "^1.0",
        "drupal/gin_toolbar": "^1.0@beta",
        "drupal/honeypot": "^2.0",
        "drupal/httpswww": "^2.0",
        "drupal/login_destination": "2.x-dev",
        "drupal/login_history": "^1.0",
        "drupal/mailsystem": "^4.3",
        "drupal/metatag": "^1.5",
        "drupal/node_view_permissions": "^1.2",
        "drupal/override_node_options": "^2.4",
        "drupal/paragraphs": "^1.5",
        "drupal/pathauto": "^1.2",
        "drupal/rabbit_hole": "^1.0@beta",
        "drupal/recaptcha": "^3.0",
        "drupal/redirect": "^1.3",
        "drupal/redis": "^1.4",
        "drupal/restui": "^1.16",
        "drupal/smtp": "^1.0",
        "drupal/tablefield": "^2.0@alpha",
        "drupal/token": "^1.3",
        "drupal/user_current_paths": "^2.0",
        "drupal/user_restrictions": "^2.0",
        "drupal/video_embed_field": "^2.0",
        "drupal/views_data_export": "^1.0",
        "drupal/views_field_view": "^1.0@beta",
        "drupal/webform": "^6.0",
        "drupal/weight": "^3.3",
        "drush/drush": "^10.3",
        "symfony/var-dumper": "^5.1",
        "vlucas/phpdotenv": "^2.4",
        "webflo/drupal-finder": "^1.0.0",
        "webmozart/path-util": "^2.3"
    },
    "conflict": {
        "drupal/drupal": "*"
    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "config": {
        "sort-packages": true,
        "allow-plugins": {
            "composer/installers": true,
            "drupal/console-extend-plugin": true,
            "cweagans/composer-patches": true,
            "drupal/core-composer-scaffold": true,
            "drupal/core-project-message": true
        }
    },
    "autoload": {
        "classmap": [
            "scripts/composer/ScriptHandler.php"
        ],
        "files": ["load.environment.php"]
    },
    "scripts": {
        "pre-install-cmd": [
            "DrupalProject\\composer\\ScriptHandler::checkComposerVersion"
        ],
        "pre-update-cmd": [
            "DrupalProject\\composer\\ScriptHandler::checkComposerVersion"
        ],
        "post-install-cmd": [
            "DrupalProject\\composer\\ScriptHandler::createRequiredFiles"
        ],
        "post-update-cmd": [
            "DrupalProject\\composer\\ScriptHandler::createRequiredFiles"
        ]
    },
    "extra": {
        "installer-paths": {
            "public_html/core": ["type:drupal-core"],
            "public_html/libraries/{$name}": ["type:drupal-library"],
            "public_html/modules/contrib/{$name}": ["type:drupal-module"],
            "public_html/profiles/contrib/{$name}": ["type:drupal-profile"],
            "public_html/themes/contrib/{$name}": ["type:drupal-theme"],
            "drush/Commands/{$name}": ["type:drupal-drush"]
        },
        "patches": {
            "drupal/core":{
                "Entity reference Fix": "https://www.drupal.org/files/issues/2019-03-26/user_cant_reference_unpublished_content-2845144-24.patch"
            },
            "drupal/token":{
                "Path Alias Language Fix - Token Issue": "https://www.drupal.org/files/issues/2019-03-14/2945272-8-token-language.patch"
            },
            "drupal/rules":{
                "Drupal Rules Fix": "https://www.drupal.org/files/issues/2725525-14.fatal_error_call_to_role_id.patch"
            },
            "drupal/recaptcha":{
                "Drupal Captcha Fix": "https://www.drupal.org/files/issues/2019-11-15/3035883-29-workaround.patch"
            }

        },
        "drupal-scaffold": {
            "locations": {
                "web-root": "public_html/"
            },
            "file-mapping": {
                "[web-root]/sites/development.services.yml": false
            }
        }
    }
}

Thanks a lot.
Comment: This looks like a bug in the `patch` program: https://github.com/cweagans/composer-patches/issues/423
Comment: This is another Composer question that doesn't provide the `composer.json` file which we could easily use to reproduce the problem.
Comment: Added the composer file, thanks for the tip
Comment: `php -d memory_limit=-1 $(which composer) install -n`
Answer: Thanks @cilefen for pointing me in the right direction. For me solution 423 of this thread fixed the problem: https://github.com/cweagans/composer-patches/issues/423#issuecomment-1301026697
The solution suggested in the comment by Mike Ohara is:
On that note, what seemed to fix this for me with additional testing was installing the gnu patch via homebrew. (https://formulae.brew.sh/formula/gpatch) brew install gpatch which installs patch GNU patch 2.7.6
After which, no issues with patches applying, including the one that failed for @dpi
Comment: This fixed my issue too. Thanks Joost!


How to prove this cosine equation using these points on the unit circle?

Question:
Prove that: $$\cos(u+v) = \cos(u)\cos(v) - \sin(u)\sin(v)$$ using the fact that the distance from A to C is the same as the distance from B to D in the picture below:

I tried using the laws of cosine and sine by looking at the triangles OBD and OAC (where O is the point at the center of the circle) but I never managed to get anywhere with these equations. The problem is taken from my math textbook and there is no solution to the problem there.
Could someone please guide me in the right direction of an answer while not giving the full solution?
Comment: Draw the altitudes from $A$ and $C$. Then Thales and Pythagoras in the triangles that appear.
Comment: Do you know how to compute the squares of the distances $CA$ & $DB$ using Pythagoras from the coordinates of $A,B,C,D$ ?
Comment: For a proof from another viewpoint, see https://math.stackexchange.com/q/4723650.
Answer: The line segments $AC$ and $BD$ both have the same
central angle $u+v$ and hence the same length which
is $2\sin((u+v)/2)$. Now use the Cartesian
coordinates of $A = (\cos(u),-\sin(u))$ and
$C = (\cos(v),\sin(v))$ to find the distance between
them. Use the identity $\cos(x)=1-2\sin^2(x/2)$
with $x=u+v.$ The rest is easy algebra and trig.


Aspas dentro de aspas para enviar parametro string

Question: A linha de código PHP abaixo deve ser exibida no site e é chamada utilizando JavaScript.
        echo "

{$row['ESPECI']}

    ";

Na segunda linha, na tag div.. tenho chamar a função 'SelecionarTipoPagamento(int, str)'.
Como indiquei, ela tem um parametro inteiro e outro string.. por isso coloco a variável $row['TIPO'] entre aspas. Porém a função não está sendo chamada, pois está com erro.
Removendo o parametro da string tudo funciona bem e o código fica assim:
            echo "

{$row['ESPECI']}

    ";

Creio que eu não esteja sabendo utilizar as aspas corretamente, porém pelo que vi na internet está correto... o que seria o erro?
Estou usando os seguintes scripts: (estou especificando pois ouvi falar que alguns não aceitam aspas simples ou algo assim)

        <link rel="stylesheet" href="css/skel.css" />
        <link rel="stylesheet" href="css/style.css" />
        <link rel="stylesheet" href="css/style-wide.css" />
        <link rel="stylesheet" href="css/style-normal.css" />

A função 'SelecionarTipoPagamento()' é esta:
function SelecionarTipoPagamento(cod, tipo){
alert("oi");
alert(cod);
alert(tipo);
codTipoPagamento = cod;}

Answer: Já resolvi o problema, após muito pensar percebi que o problema não está no php em si, mas na string que o HTML executa, pois o HTML ficaria assim:
onclick='funcao('str');'

E isso gera aspas simples dentro de aspas simples, pra funcionar então o código ficou:
echo "

{$row['ESPECI']}

    ";

Answer: Fecha as aspas na função e depois abre de novo.
Realmente, esse pode ser o erro.
echo "

{$row['ESPECI']}

    ";

Comment: Não funcionou.. parece que ele chama a função ao invés de geral o HTML com a string... já que retorna o erro:

"Call to undefined function SelecionarTipoPagamento() in ... "


Where am I supposed to check on input data?

Question: I started to think of when should I check the input data. I'm in this scenario:
class Father
{
    string name;
    public Father(string n)
    {
        name = n;
    }
}

class Child extends Father
{
    private Child(string n)
    {
        base(n);
    }

    public NewChild(string n)
    {
        return new Child(n);
    }
}

Let's say I want to check if the string that comes from outside is not null and at least 5 chars long.
Where should I do the check?
Answer: The Father class should check it as a precondition in the constructor and throw an exception if the input is not valid.


Command 'Python: Select Interpreter' resulted in an error (command 'python.setInterpreter' not found)

Question: I have been using VSCode for a while and so far everything was good. Yesterday I created a new django project with it's own virtual environment. However, something happened to VSCode that it cannot find any interpreters. When I click shift+command+P and type >python: select interpreter, it gives me an error. I can still run my code and it works, which is weird but it is very uncomfortable to work like that because the colors are not highlighted in the code.
Comment: Click the triangle button in top right corner to run python file in terminal, which python.exe is used? the global python or the virtual environment?Besides, please post your error content and vscode screenshot.
Answer: I ran into this problem with my newly installed VSCode on my Win10,and I fixed it by referring to other people's blog. The solution is somewhat complicated as follows:
First find the location where Microsoft VS Code is installed, then create a test folder in the same level directory, open this folder with VSCode, create a new VSCode window and open the folder where your python files are located, then select python interpreter.
Answer: I also faced the same issue and was able to solve it by doing the following:
I tried reverting to an older version of the python extension to see if that would fix the problem and it fixed the problem.
To install older version of python extension on VScode: Go to Extensions(Ctrl+Shift+X) then right click on the python extension, click on Install Another Version and choose an older version.
I hope this helps others who are facing the same issue!
Answer: I created file .ipynb and open it with VS Code. I had the same error.
Then I created folder and put this file to folder. After that, I opened folder with VS Code and try command Python: Select interpreter again. And it works. I was able to choose version of interpreter.
I hope this will be useful to you.


C++ chooses 'wrong' overloaded method with default parameters

Question: I have the following interface
virtual void send_command( const std::string& command, const std::string& key, const std::string& value, bool pipeline = true );
virtual void send_command( const std::string& command, const std::string& key, bool pipeline = true );
virtual void send_command( const std::string& command, bool pipeline = true );

that is fully implemented in one class which I will then call as the following:
c.send_command("MUTLI");
c.send_command("SET", "foo", "bar");
c.send_command("GET", "foo");
c.send_command("EXEC");

When I check which method implementation get's called, I see that the third call (GET foo) ends up to hit the last implementation:
virtual void send_command( const std::string& command, bool pipeline = true );

where "foo" is implicit converted to bool. The same counts for "SET", "foo", "bar" which hits the second implementation (string, string, bool)
When I make the call with an explicit c-cast to a string like this
c.send_command("GET", (std::string)"foo");

The expected method gets called.
I am using gcc (GCC) 4.7.2 20121109 (Red Hat 4.7.2-8) with C++11.
Comment: To avoid that, you may write the `send_command` version taking a `const char*`
Comment: Do the default parameters have anything to do with this?
Comment: Yes, in some cases I want to set them to false, so `c.send_command("GET", "foo", false)` works as well
Comment: I don't see how that is related to the problem you are reporting.
Comment: Well, I don't want to put casts in every method call. Why is the second parameter converted from string to bool and how can I avoid that?
Comment: c.send_command("GET", std::string("foo")); will call the one that you want
Comment: I would expect that `c.send_command("SET", "foo", "bar");` also calls `virtual void send_command( const std::string& command, const std::string& key, bool pipeline = true );`
Comment: Yes, in fact it does. Sorry about being inconsistent - will edit my post.
Answer: The compiler prefers the conversion from const char* to bool over a conversion to a UDT (std::string). If needed, just add more overloads for const char* as well.
Answer: You're hitting the fact that pointers can implicitly be converted to bool (testing that they're not null), and that a string literal is not a std::string, but a const char[] which decays into a const char* on call. What you can do is provide an additional overload taking a const char*:
void send_command(const std::string& command, const char* key)
{ send_command(command, std::string(key)); }

Live example
Comment: Well, that's an option. But `std::string key = "key"; client->send_command( "GET", key );` will lead to the same behaviour. Does this mean, that the std::string is represented as const char?
Comment: @Tobi Sure, but I kinda assume you want to call it with arbitrary literals, and not have to define a variable for each one.
Comment: There are fixed strings in unit tests, but there will be string instances in prod use
Comment: +1 And that has absolutely nothing to do with default parameters.
Comment: @Tobi I don't quite understand your question "Does this mean, that the std::string is represented as const char?" `std::string` is a `std::string`. A string literal (such as `"foo"`) is not an instance of `std::string`, it's a `const char [4]`. Does that answer you?
Comment: @Angew yes, it should be that way - but I tried to create an instance of std::string and pass it to the send_command (very first comment). That still did not fix the conversion to bool. I am not sure whether there are compiler optimizations turned on or not.
Comment: @Tobi Oh, I misunderstood slightly. But you must have made something else wrong - it's impossible for `std::string key = "key"; client->send_command( "GET", key );` to call the `(std::string, bool)` overload - `std::string` does not have a conversion to `bool`, simple as that.
Answer: Overload resolution has several steps: First, a set of viable functions is selected. These viable functions must have enough parameters for the call, considering ellipsis and/or default arguments. In addition, each argument has to be convertible to the corresponding parameter type. For c.send_command("GET", "foo"); you have as viable candidates
virtual void send_command( const std::string&, const std::string&, bool);
virtual void send_command( const std::string&, bool);

because the third parameter of the former is defaulted and the string literal arguments are convertible to string const& and bool.
After having the viable set, the compiler looks at the argument conversions needed. No conversion is prefered, then builtin conversions, then user defined conversions. In this case, the conversion for the first argument is the same in both viable functions. For the second argument, the conversion to bool is buitlin, while the conversion to string const& is not. Therefore send_command( const std::string&, bool); is prefered over the alternative.


Drupal 7 Themeing - template.tpl.php vs template.php - variables

Question: I am interested in learning what disadvantage, if any, there are in calling variable fields directly within the template.tpl.php files.
Is it ok to place a field variable within the template.tpl.php file if doing it as simply as:
<?php
//--------------------------------
// COLOR
if(!empty($content['product:title']['#product']->field_taxonomy_color['und'][0]['taxonomy_term']->name)): ?>

    <?php
        $max_length = count($content['product:title']['#product']->field_taxonomy_color['und'])-1;
        for($x = 0; $x <= $max_length; $x++){
            echo '
'. $content['product:title']['#product']->field_taxonomy_color['und'][$x]['taxonomy_term']->name .'
';
        }
    ?>

<?php endif; ?>

My understanding is that this code should be placed a preprocess function and called into the tpl.php file such as:
TEMPLATE.PHP
function theme_preprocess_node(&$variables) { $variables['color'] = ... }

TEMPLATE.TPL.PHP
<?php echo $color; ?>

If this is the case, how would i return all values of the loop from template.php into template.tpl.php?
---------EDIT---------
Should I create complex logic within its own field--template.tpl.php file, set the field to a variable in template.php and call upon the variable inside the node--template.tpl.php?  Would there be a problem with creating over a hundred field--template.tpl.php files?
Comment: Thank you, If I declare all the variables within template.php, wont the file get rather large and bog down on site speed?

Also, within the preprocess_node function, what would the above code look like?
Comment: AFAIK you shouldnt be using a template.tpl.php because it isn't attached to anything in Drupal... look at this [DO article](https://www.drupal.org/docs/7/theming/overview-of-theme-files) you should only use template.php for general theme functions and YOUR_TEMPLATE_NAME.tpl.php for specific pages which you need to let Drupal know using theme suggestions when to use (ie with a specific content type, a specific view, or panel etc)
Comment: The way you have it is fine and I don't see how this would bog down your site speed... you're just aliasing the variables for ease of access. The only thing you have to change is make your template.tpl.php into page.tpl.php or node--YOUR_CONTENT_TYPE_NAME.tpl.php for example, it depends upon your theme suggestions schema.
Comment: You do not want code like that in the first block at all in templates. Do that logic in template.php thats what it is there for. Its up to you to decide how you want to create new variables to pass into the template to render. Example, just create an array of color names in template.php, loop that in the template and output it. Easy... and less spaghetti code.
Answer: The disadvantage is you leak a lot of PHP code processing Drupal inner structures to the template file.
I would preprocess $content in template.php to expose a simple array of strings as a custom variable:
$colors = $content['product:title']['#product']->field_taxonomy_color['und'];
$colorNames = Array();
for ($x = 0; $x < count($max_length); $x++) {
  $colorNames[$x] = $colors[$x]['taxonomy_term']->name;
}
$variables['color_names'] = $colorNames;

Then the template code could be:
<?php if ($color_names): ?>

  <?php foreach ($color_names as $cn)
    print '
' . $cn  . '
'; ?>

<?php endif; ?>


Performing power analysis with clustered standard errors, interaction effects, and covariates using pilot data

Question: Let's say I run an experiment where participants play a behavioral game with someone that is either their same gender, or not their own gender.  The primary criteria of interest is a pre and post measure of some outcome (taken before and after the game), captured as a change-score.
My approach for modeling this looks like the following:
 felm(change_score ~ my_gender + other_gender_pairing + my_gender:other_gender_pairing | team_id | 0 | 0)

Where other_gender_pairing is a dummy variable set to 1 if you're paired with someone of the opposite gender. Standard errors are clustered a the team_id level, since all dyads will have correlated error terms.
I have already conducted a pilot of this experiment involving 80 participants in each "cluster."   Where a 0 or 1 indicates whether somebody was paired with their same gender (M-M or F-F = 0) or opposite gender (M-F or F-M = 1)
              0  1
  Male       80 80
  Female     80 80

I would like to conduct power analysis to figure out the size of the effects I can detect given some fixed sample size per cell, informed by the coefficients estimated in the pilot. Unfortunately, because this design is somewhat complicated by the interaction effect and clustered standard errors, I cannot find any useful guides.
Can somebody point me in the right direction?
For reference, here are the coefficients identified in the regression run on the pilot.  I'd like to be able to incorporate these estimates for more accurate power analyses.
Coefficients:
                                                Estimate Std. Error t value  Pr(>|t|) CI Lower CI Upper  DF
(Intercept)                                      -0.8254      1.169 -0.7061 0.4817274   -3.144    1.493 101
my_gender                                         3.1266      2.092  1.4947 0.1381022   -1.023    7.276 101
other_gender_pairing                             11.6639      3.330  3.5023 0.0006886    5.057   18.270 101
my_gender:other_gender_pairing                   -5.0025      4.645 -1.0769 0.2840919  -14.218    4.213 101

I use post-estimation tools to estimate contrasts where I compare means of M:M to M:F and F:F to F:M.  This results in the following:
 contrast estimate   SE  df t.ratio p.value
 0 - 1      -11.66 3.33 199 -3.502  0.0006

gender = Female:
 contrast estimate   SE  df t.ratio p.value
 0 - 1       -6.66 3.27 199 -2.040  0.0427

I'd like to know how big of a sample size to have in each cell in order to detect effects for the interaction effect.
Edit: I should note that my preferred language is R.  It would be very helpful to see some template code for how to deal with experimental designs like this.
Comment: Is the game symmetric? Do players ever play again with a different partner?
Comment: Is there one change-score per person per game, or one per dyad per game?
Comment: Players only play the game once. Think of it like a collaborative jigsaw puzzle. The change score is one person per game. All measures are at the individual level
Comment: Are you looking for an analytical solution, or could you just run simulations?
Comment: What is the difference between "MF" and "FM"?
Comment: Is it that the mean is taken over the change-score of the first individual, i.e. M in MF and F in FM?
Comment: I can just run simulations, It doesn't have to be an analytical solution. I just don't know the right way to set up a simulation given the clustered nature of the game.
Comment: And your intuition is right about the difference between MF and FM. The first person is the perspective the change score is from and the second person is the person who they're paired with. All change scores are from an individual level, so there is a difference in the change scores between males paired with females and females paired with males
Answer: Since players only play the game once, dyads can reasonably be assumed to be independent of one another. It could potentially simplify your analysis, while maintaining your goals, if you worked with "one observation = one dyad" rather than "one observation = one person." You could dispense with the clustered errors and just estimate your interaction directly as
$$(\mu_{MM} - \mu_{MF}) - (\mu_{FF} - \mu_{FM})$$
where $\mu_{MF}$ is the mean over all change-scores of males paired with females. The possible issue here is that, depending on how your notation is understood, $\mu_{MF}$ and $\mu_{FM}$ are not statistically independent: they are the same set of games, just with the opposite person measured. That would sink this solution and then you'd be back to the drawing board.
Comment: You are correct with your last sentence, Eric. The mean of MF and FM are the same set of games, just with the opposite person measured. And therein lies the trouble with power analysis simulations. Any ideas?


Stationarity of MA($\infty$) process

Question: In my time series class, we got taught, that an MA($\infty $) process with
$$
\sum_i^\infty \theta_i^2 < \infty
$$
is weakly stationary.
Obviously the mean exists and is time independent, but why does the second moment, so the covariance, also exist? From the assumption I can only derive, that the variance, but not the covariance with some lag $h$
$$
Cov(x_t, x_{t-h}) = \sum_i^\infty \theta_i \theta_{i+h}
$$
exist, which is, as far as I know, required for weak stationarity.
Answer: For any pair of random variables $x_t$ and $x_{t-h}$, the squared-covariance obeys the upper bound:
$$\mathbb{Cov}(x_t, x_{t-h})^2 = \mathbb{Corr}(x_t, x_{t-h})^2 \mathbb{V}(x_t) \mathbb{V}(x_{t-h}) \leqslant \mathbb{V}(x_t) \mathbb{V}(x_{t-h}).$$
Hence, if the variance values are both finite, the squared-covariance must also be finite, which means that the covariance is also finite.  This is a general property that works in any context, so you don't need to use the specific form for the covariance that occurs in an MA model.
Alternatively, if you particularly want to establish this result just for the particular case of the MA($\infty$) process, you could do this as follows.  Using the Cauchy-Schwartz inequality combined with your finite variance condition you have:
$$\begin{equation} \begin{aligned}
\mathbb{Cov}(x_t, x_{t-h})^2 &= \Bigg( \sum_{i=0}^\infty \theta_i \theta_{i+h} \Bigg)^2 \\[6pt]
&\leqslant \Bigg( \sum_{i=0}^\infty \theta_i^2 \Bigg) \Bigg( \sum_{i=0}^\infty \theta_{i+h}^2 \Bigg) \\[6pt]
&\leqslant \Bigg( \sum_{i=0}^\infty \theta_i^2 \Bigg)^2 < \infty.
\end{aligned} \end{equation}$$

Stationarity of MA($\infty$) process


How do I use a referenced entity in a Views contextual filter?

Question: I'm building a media server for my university.   I have an "artist" content type for each performer, and then a 'track' content type for individual track (there are no 'albums', BTW).  For each track, you can select the artist in edit mode, using an Entity Reference.  So far so good!
On each Artist page is a block view with a table listing that artist's songs (the filter is 'show all tracks with a contextual filter of "artist").  Still good!
On each track page, I want to show "all tracks by this artist" as a table.   I've tried "artist" as the contextual filter, and even tried both "referencing entity" and "referenced entity" as relationships, to no avail.    If I put an artist NID in to the fixed value in the 'artist' contextual filter, it works fine.  But I'm pulling my hair out, trying to get the artist to dynamically be referenced by the block's contextual filter, using the tracks 'artist' entity reference.
Am I missing something here?  It really seems like it shouldn't be that hard.    Thanks in advance!
Comment: Create a view -> filter node type: track -> relationship to field reference artist. Is this the way you have tried it?
Comment: You could probably do this dynamically, when you provide a default value in your contextual filter. Use PHP-Code, get the current node id -> load your node and return your artist nid.
Comment: I tried view -> filter node type: track -> relationship to field reference artist, and was surprised that it didn't work.    If attempting to use PHP code...since contextual filters don't have a php option, would you recommend installing Views PHP, or is there a smarter module/means?
Comment: You don't have an php option? I don't think you need a separate module for this.
Comment: Aha, PHP Filter module hadn't been enabled on this install.  Enabled and trying now....
Comment: The token for this field would be [node:field_performer].   How can I pass that off as a PHP argument in the PHP contextual filter code box?  (also googling, to try to teach myself to fish). :)
Comment: In PHP-Code you have several variables. One is $argument. You could install [devel](https://www.drupal.org/project/devel) and use the function dpm() to debug your code.
Comment: Success!  This had the PHP code I needed: http://drupal.stackexchange.com/q/25148/51570.   Your guidance helped tremendously, happy to mark this of as answered.      Entity references are just a little extra tricky to get into contextual filters, it seems.
Answer: For the curious, with Huelfe's help I solved it with a custom PHP code, in order to obtain the applicable NID for that contextual filter.  Seems like something that should be built in to Views already...!   I've successfully reused the string or several other projects as well.


HTML/CSS: div, anchor and image tag with space below

Question: please read the full post before marking this as a duplicate
We're all familiar with the annoying default agent stylesheet from browsers. We're probably also familiar with the annoying anchor and image tags with whitespace underneath it.
So here's my issue:
HTML:

I used some social icons for test purposes and it looks like this:

I want the anchor to be a square, so in my CSS I simply say a { display: inline-block; }

But now there's a whitespace underneath the image, so in my CSS I say img { display: block }

Everything with the anchor tag and image tag seems to be fine now, but...
Now there's a whitespace inside the div, without there's any evidence it's either the anchor tag or the image tag.

You might think: "well that's easy. Just say div { font-size: 0 } in your CSS". Well that causes another issue: the div does not measure the height very well. It slices off one pixel on the top:

So if there are any fixes: how would I fix this without ugly fixes like: padding-top: 1px or margin-bottom: ...px
If there are no fixes: that would be weird
Comment: @caramba do you read?
Comment: css => a img {display:inline-block}
Comment: guys, please read carefully
Comment: I read my friend...
Comment: use `display:block` or `inline-block` to get `a` tag in square
Comment: @caramba yes, that did not solve my problem, as I explained in my question that I put the anchor tags to `display inline-block` and image tags to `display block` There is **no whitespace** below either the image or anchor tag (see the uploaded GIF), but inside the div tag. The answers on *the duplicate answer* did not solve my problen
Comment: @LKG already have that
Comment: Posted working example @DerkJanSpeelman
Comment: It's old but maybe it help some one.
I solved this by setting `a { display: inline-flex; }` for the anchor.
Answer: Try adding a { float:left } or a { vertical-align: middle }
Comment: That's interesting, now it slices off 1 pixel on the top **and** it still has the whitespace inside the div tag
Comment: @DerkJanSpeelman try the update
Comment: `a { float: left }` does do the trick altough I need to wrap it up inside another div tag to align the icons to the center using `text-align: center`, but this does work indeed. `a { vertical-align: middle }` works as well, I discovered
Comment: @DerkJanSpeelman will you accept then please :)
Comment: I requested an edit ready to be peer reviewed, than I can accept it
Answer: Flexbox works nice.

div, a {
  display: flex;
  justify-content: center;
}

a:not(:last-child) {
  margin-right: 1em;
}

Comment: Thank you for your post, but as I open the devtools I can see there is a whitespace inside the anchor tag. So this is not a fix
Comment: Than we use a nested flexbox. No more whitespace


What cross validation use with time series database?

Question: I'm using a regression tree to predict/forecast a daily bases data.
I'm wondering to use a cross validation to train and predict all the data.
What cross validation procedure I may use?
Answer: You'll likely want some sort of Roll Forward Cross-Validation. Roll-forward works like regular cross validation, only it stipulates that the testing data will always be immediately following the training data. Think of testing known observations by applying the model to a subset of your data that ends at a certain point, and then comparing the model results to a subset of your data that begins immediately after the point you ended your training on.
Robert Hyndman has an excellent blog post on implementation of this is R here.
Answer: There are several good questions embedded in your post. Let me try to tackle them in turn:

Should I use cross-validation, and if so which procedure?
Using cross validation to tune your model and hyper-parameters is a good idea. If you are considering using Python for your project then Scikit-Learn is a popular machine-learning package that may be useful. You will find more specifics on how to use the cross-validation function in Scikit-Learn here:  Cross-Validation on SKLearn
Importantly, for time-series, you should use the correct roll-forward split of data. The SKLearn team kindly included a time-series splitter in the recent v0.18 of Scikit-Learn:  SKLearn Time Series cross-validator
Should I use the model to train and predict all the data?
Even if you use cross-validation, it is still advised that you split a portion of test data off before you start training and validation. You can then keep this data for final testing once you have created your model. More discussion here:  Should I split my data to train/test split or train/validation/test subset?
Comment: thanks Gung. Have expanded on the answer - please let me know if this is helpful.


Establishing convergence in probability from a related convergence in distribution

Question: Is it true that $\sqrt n (\hat{\theta}-\theta) \ \rightarrow_d \ N(0,\sigma^2)$
implies
$\text{plim} \ \hat{\theta} = \theta $?  If so, how can I prove this?

Attempted proof: My proof is like this:
Since $\hat{\theta} \rightarrow_{asy.} N(\theta, \frac{\sigma^2}{n})$ I have $\lim_{n \to \infty} E(\hat{\theta})= \theta  \ $ and
$\lim_{n \to \infty} Var(\hat{\theta})=0 $.  Therefore, from convergence in quadratic mean, $\text{plim} \ \hat{\theta} = \theta $.  Is this proof correct?
Comment: Here's something to contemplate.  Let $X$ be a Rademacher$(1/2)$ variable; that is, $\Pr(X=-1)=\Pr(X=1)=1/2.$ Define the sequence $X_n = (-1)^nX, n=1,2,3,\ldots.$  All the $X_n$ are identically distributed, so they converge in distribution trivially.  What random variable would they converge to in probability?  Do they converge to it?  Now, although this is not the situation you have, it might provide some insight into what could go wrong with your proof.
Comment: See https://stats.stackexchange.com/questions/207264/root-n-consistent-estimator-but-root-n-doesnt-converge/207281#207281
Comment: @whuber Thank you for your reply. $ X_n $ do not converge in probability, because for all n $ X_n $ takes -1 or 1 with probability 1/2, do they? But I don't understand how do your example relate to my proof. I would appreciate if you give me a little more information.
Comment: @christoph Thank you for your reply. I understand the proof of the link.
Comment: Let $Z_n$ be any sequence of variables that converge to a standard Normal variable.  Consider the sequence $X_nZ_n.$
Answer: We are given that
$$\sqrt n (\hat{\theta}-\theta) \to_d  N(0,\sigma^2) \tag{1} $$
Make the additional assumptions that
1) For the finite distribution of $\sqrt n (\hat{\theta}-\theta)$, the $2+\delta,\; \delta >0$ absolute moment exists and is finite.
2) The sequences of 1st and 2nd moments of $\{\sqrt n (\hat{\theta}-\theta)\}$ converge each to a constant.
Then these constants are the corresponding moments of the limiting distribution.
In particular, this means that
$$\lim \text {Var}[\sqrt{n}(\hat \theta -\theta)] = \sigma^2 \tag{2}$$
At the same time, we have
$$\lim \text {Var}[\sqrt{n}(\hat \theta -\theta)] = \lim \mathbb E[\sqrt{n}(\hat \theta -\theta)]^2 - \lim\left(\mathbb E[\sqrt{n}(\hat \theta -\theta)]\right)^2$$
$$= \lim \mathbb E[\sqrt{n}(\hat \theta -\theta)]^2 - \left(\lim\mathbb E[\sqrt{n}(\hat \theta -\theta)]\right)^2 = \lim \mathbb E[\sqrt{n}(\hat \theta -\theta)]^2 - 0 \tag{3}$$
Combining $(2)$ and $(3)$ we have
$$\lim \mathbb E[\sqrt{n}(\hat \theta -\theta)]^2 = \sigma^2 \implies \lim n\mathbb E(\hat \theta -\theta)^2 = \sigma^2 < \infty \implies \mathbb E(\hat \theta -\theta)^2 = O(1/n) $$
$$\implies \mathbb E(\hat \theta -\theta)^2 = o(1) \implies \mathbb E(\hat \theta -\theta)^2 \to 0 $$
The last result is convergence in quadratic mean - and convergence in quadratic mean of a random variable to a constant, implies that this constant is also its probability limit (see here for an exposition why).
So $\hat \theta_n \to_p \theta$.
While in general it does not hold that convergence in distribution implies convergence in probability, we see how, for a subset of cases and under some additional conditions, we can go from the limiting distribution to the probability limit.
Comment: @sonicbomm They do but you don't really need this because convergence in probability is proved on its own for the $Q^{-1}$ matrix. Proving the convergence in distribution is done to be able to improve on the rate of convergence, not to prove convergence in probability.
Comment: @sonicboom As I wrote you do not need to invoke them. Just prove convergence in probability directly.
Comment: There seems to be a typo and we should have $E(\hat \theta - \theta)^2 = O(1/n)$.
Comment: How strong are the assumptions 1) and 2) in the case where $\theta$ and $\hat \theta$ are the coefficients and estimated coefficients of multiple linear regression in the usual setting (e.g. finite error variance with the errors independent of the predictors)? I assume these assumptions are underlying Hansen's statement in [equation (6.13)](https://www.ssc.wisc.edu/~bhansen/econometrics/Econometrics2013.pdf)?
Comment: I see how it works but it just seems a bit arbitrary because in 1) and 2) you make an assumption that involves $\sqrt{n}$ and ultimately this assumption results in the $O_p(n^{-1/2})$ convergence in probability and $O(1/n)$ in quadratic mean. You could have just as easily replaced the $\sqrt{n}$ with $n$ or $n^2$, etc., in 1) and 2) and obtained a different rate of convergence in probability and expectation.
Comment: I know $\sqrt{n}$ is special in the context of the CLT and thus your equation (1), but as things stand it seems very arbitrary in 1) and 2) because these are merely assumptions. We can get any convergence rate we want if we just make arbitrary assumptions. Is there some reason why 1) and 2) should be considered more than just arbitrary assumptions?


What is correct path in .js file in Rails?

Question: I have a js script which plays a video on my home page and I can't get the correct path to the video folder in this script. It only works in an html static project.
assets/javascript/common.js
var videobackground = new $.backgroundVideo($('#background-video'), {

  "path": "/video/"

});

assets/javascript/video/ - my videos in this folder

I tried sending the root_path variable in my application file, but it doesn't work either.
application.html.haml
:javascript

  var ROOT_URL = '#{Rails.root}';

application.html.haml
var videobackground = new $.backgroundVideo($('#background-video'), {

  "path": ROOT_URL + "/app/assets/javascripts/video/"

});

Comment: Have you tried putting your videos in `/public/...`? You shouldn't put large files like videos in the asset pipeline.
Comment: `Rails.root` returns the actual path of your app's folder (on Ubuntu, something like `/home/user_name/your_rails_app`).
Comment: Yes, I know. I tried both methods and they don't work.
Comment: Agree with Beartech, put it in a video directory in public, so http://www.siteurl/public/video/
Comment: Do not use _ROOT_URL_ in your views, especially as href or src for some resource. All your requests go through Rails routes or directly (in production) to the file that is (usually) in your public dir. So the request path and the absolute path of file at hard drive is not same
Comment: "path": "http://localhost:3000/public/video/" still doesn't work for me
Comment: don't add localhost, try with public/videos
Answer: I am not sure, if you really want than i assets, try putting that video in app/assets/videos and then in the config/application.rb do
config.assets.paths << "#{Rails.root}/app/assets/videos"
config.assets.enabled = true

else put it in public/videos then, your video_tag "video.mp4" should automatically loaf from there
Comment: I need write path to folder with my videos in js file which locates in assets and I don't know what is correct path.

video_tag - for views, not js


Compilation issue with typescript file

Question: I'm new to typescript and was trying to work on it where in I came across this issue, where I saved a file using .ts extension and instead of recognizing the file as a typescript file,the system is recognizing it as a Transport Stream file. I have already installed all the typescript files using node. Whenever I try to compile the code the error displayed is as follows:

PS D:\WorkSpace\typescript> tsc basics.ts tsc : File
  C:\Users\mn\AppData\Roaming\npm\tsc.ps1 cannot be loaded because
  running scripts is disabled on this system. For more information, see
  about_Execution_Policies at
  https:/go.microsoft.com/fwlink/?LinkID=135170.

At line:1 char:1

tsc basics.ts
+ CategoryInfo          : SecurityError: (:) [], PSSecurityException
+ FullyQualifiedErrorId : UnauthorizedAccess

This is how the file appears in the folder:
Folder image
Answer:
Run the Windows PowerShell as RunAsAdministrator
type Set-ExecutionPolicy Unrestricted
exit and run compiler again
Answer: For now, I suggest removing all .ps1 files from your npm bin folder.
Sometimes changing the execution policy is not a good practice. A more restricted Execution policy (RemoteSigned) helps users from unintentionally running malicious code.
The issue is still open in the npm/cli repository, labeled as 'Needs Discussion' Necessity of Powershell Script Support for Global Packages.
Comment: For me, the `tsc.ps1` it was in `C:\Users\xxx\AppData\Roaming\npm`
Answer:
CategoryInfo          : SecurityError: (:) [], PSSecurityException
FullyQualifiedErrorId : UnauthorizedAccess

I got the same error in visual studio. But using command prompt  it has been solved
Thank you

Compilation issue with typescript file


Find the image of set under the mapping

Question:
Let $D = \{ (x, y) \in \mathbb{R}^2 | 1 \le x^2 + y^2 \le 2, -x \le y \le x \}$ and let $(u, v) = F(x, y) = (x^2 + y^2, 2xy)$. Find the image of $D$ under the mapping $F$

Can someone give me some ideas?
So the region is between the circle of radius $1$ and $2$, but with restriction $y \le |x|$. How do I fit this in?
Thanks!
Answer: The condition $-x\leqslant y\leqslant x$ is valid only when $x\geqslant0$. Asserting that $-x\leqslant y\leqslant x$ means then that if you express $(x,y)$ in polar coordinates ($x=r\cos\theta$ and $y=r\sin\theta$), then $-\frac\pi4\leqslant\theta\leqslant\frac\pi4$.
If $x=r\cos\theta$ and $y=r\sin\theta$, then$$F(x,y)=F(r\cos\theta,r\sin\theta)=\bigl(r^2,r^2\sin(2\theta)\bigr)=r^2\bigl(1,\sin(2\theta)\bigr).$$Since, for the points of $D$, $r\in\bigl[1,\sqrt2\bigr]$ and $\theta\in\bigl[-\frac\pi4,\frac\pi4\bigr]$, the image of $D$ by $F$ is the set of those points of the form $R(1,\sin\alpha)$ with $R\in[1,2]$ and $\alpha\in\bigl[-\frac\pi2,\frac\pi2\bigr]$. This is a trapezium, whose vertices are $(1,\pm1)$ and $(2,\pm2))$.
Comment: Shouldnt it be $r \in [1, \sqrt{2}]$, since the restriction was $1 \le x^2 + y^2 \le 2 \implies 1 \le r^2 \le 2$?
Comment: @Bana Right! I will edit my answer.

Find the image of set under the mapping


How to get the nodeid in node_grants so that it works in a view?

Question: I am exploring the node_grants and node_access_records with the following objective:
I want to be able to hide nodes where the current logged-in user is not 'friends' with the node author. The node author selects if they want to limit it to friends or not with a boolean field. Here, the subtlety is that there are a few views which list nodes on my site, so I want it to work for views too.
I am using drupal 7, user relationships for the 'friends' relationship and here is my node_grants code. How do I get the node id, especially in the context of views?
function mymod_access_node_grants($account, $op) {
// Grants all rights if the author
$grants['mymod_access_author'] = array($account->uid);

    $value_friends = field_get_items('node', $node, 'field_friends_only');
    $value_friends = $value_friends[0]["value"];
    $value_friends = 1;

    if ( $value_friends == NULL) {
        $value_friends = 0;
    }
    if ($value_friends == 0) {
        $grants['mymod_access_public'] = array(1);
        $grants['mymod_access_friends'] = array(1);
        $grants['mymod_access_notfriends'] = array(1);

    } else if ($value_friends == 1)  {
        //if node is for friends only, then check if relationship exists...
        $current_user_uid = $account->uid;
        $node_author_uid = $node->uid;

        // Set up the parameters
        $params = array('between' => array($current_user_uid, $node_author_uid));

        // Get the relationships
        $relationships = user_relationships_load($params);

        if ($relationships) {
            $grants['mymod_access_public'] = array(2);
            $grants['mymod_access_friends'] = array(2);
            $grants['mymod_access_notfriends'] = array(2);
        } else {
            $grants['mymod_access_public'] = array(3);
            $grants['mymod_access_friends'] = array(3);
            $grants['mymod_access_notfriends'] = array(3);
        }
    } else {
    }
}

return $grants;
}

PS: although I have $node in my code, it is empty at the moment!
Answer: You actually need to implement two hooks:

hook_node_grants() which returns the grants a user has
hook_node_access_records() which returns the grants a node needs

It's the second hook that gets a node object, not the first. Keep in mind that you need to implement both the hooks.
As for hook_node_access(), this hook is called when a node is fully loaded, and it not called for node listings, as reported in the documentation.

Also note that this function isn't called for node listings (e.g., RSS feeds, the default home page at path 'node', a recent content block, etc.) See Node access rights for a full explanation.

As for views, a view doesn't full load a node, but executes a SQL query to get node data. merlinofchaos clearly states it in Views does not respect hook_node_access.

hook_node_access() is something that is run after a node is fully loaded. Since Views is loading nodes via query, you can't get the query to respect it unless you also use hook_db_rewrite_sql() which is what Views hooks into.
This is not true of just Views, but any query that loads nodes. For example, the default Drupal front page will not respect hook_node_access() that isn't paired with hook_db_rewrite_sql() any better.
hook_node_grants() and hook_node_access_records() will be used, however, if you set "Disable SQL rewriting" then you are specifically skipping that stuff.

Notice that hook_db_rewrite_sql() is not used from Drupal 7 and higher, though. The equivalent for Drupal 7 and higher is hook_query_alter().
Comment: Thanks Kiamlaluno.
I do have both functions, it's just that node_grants tells which nodes the current user can see or not in the end. Can I create for a same realm many grant-ids? For example, for a 'friends_realm', have grant ids be the $uid of each of these friends?
Comment: No, `hook_node_grants()` returns the grant IDs associated with the passed account. They aren't node IDs, but integers; if they are IDs, they could be user IDs, such as in `$grants['example_author'] = array($account->uid);`. Yes, you can return more grant IDs for the same realm, as in `$grants['node_access_test'] = array(8888, 8889);`.
Comment: Hi Kiamlaluno, my question was in the opposite way: when you create the grants for nodes in node_Access_records, can you provide multiple values of the grant ids for the same realm? For example, if following the example on the Drupal function page: `code`$grants[] = array('realm' =>'example_author','gid' => $node->uid,'grant_view' => 1,'grant_update' => 1,'grant_delete' => 1,'priority' => 0,);`code`
Comment: With the Book access module, I used multiple grant IDs for the same realm; so, yes, it is possible.
Answer: I think that the hook you must use in your case is hook_node_access https://api.drupal.org/api/drupal/modules%21node%21node.api.php/function/hook_node_access/7
which is fired every time a node is requested and thus the $node variable is not provided by the system and is not empty
Comment: `hook_node_access()` doesn't work with a view because it is never invoked with a list of nodes, such as in the case of a view. See the code invoking that hook.
Comment: seems like a bug that has been fixed. See here https://www.drupal.org/node/1266388 and here http://drupal.stackexchange.com/questions/23225/having-views-respect-hook-node-access
Comment: No, it has not been fixed. merlinofchaos clearly states that the Views module doesn't respect `hook_node_access()` since that hook is invoked when a full node is loaded, which is not what the Views module does.
Comment: Thanks both for your contribution. I have looked a lot on the web, and it does seem like the only way to get Views to respect access to nodes is through the node_Grants and node_access_records...


Check for domain extension with PHP or JS

Question: First of all I am a php beginner so please be as specific as possible.
Basically I want a php/javascript that does the following:
if the domain has a  .de extension then add the text "this is a german site"
else add the text "this is not a german site"
it's also ok if you do it with the lang="de-DE" instead of the domain extension.
Comment: it depends. From where you get the domain extension? if the string only contains a domain name, `parse_url()` so better, otherwise `preg_match()`.
Answer: To get the domain extension use php's pathinfo
$extension = pathinfo($_SERVER['SERVER_NAME'], PATHINFO_EXTENSION);

if($extension == "de")
{
echo "this is a german site";
}

Also see: $_SERVER
Comment: doesn't seem to work for me. I get Parse error: syntax error, unexpected T_VARIABLE
Answer: In PHP, try something like this:
<?php
//~ $domain = $_SERVER['HTTP_HOST'];
$domain = "domain.de";

if (preg_match('/(.*?)\.de$/', $domain)) {
    echo "is german";
} else {
    echo "is not german";
};
?>

Greatings.
Comment: I get no error at all. I don't get any messages either. I am using joomla.
Answer: var isDE="";
var extension=location.hostname.split(".");
extension=extension[extension.length-1];
if (extension=="de") isDE="this is a german site".
//do whatever you need with isDE, e.g. document.write(isDE);


SQL server authentication is grayed out when connecting to integration services

Question: Why SQL server authentication is only available for connecting to Database Engine but grayed out for rest of all services, AS, RS and IS?
I am on SQL Server 2012.
How can I enable the sa login to AS, RS and IS?
Answer: Analysis and Integration services only use Windows Authentication. SQL Server Reporting Services would require different configuration to handle different authentication. More detail can be found by clicking on the service links. As such, sa is a SQL Server authentication and cannot be used for logging into those services.


Failed to load module script: Expected a JavaScript module

Question:
I am using vite as build tool for my react app and golang as backend.
I built the app for production and host the app on my http server.
my directory structure:
server
  |- dist
  |    | index.html
  |    |- assets
  |         | index.js
  |         | index.css
  | main.go

To host my files the code looks like (inside main.go)
fs := http.FileServer(http.Dir("./dist"))
http.Handle("/", fs)

in index.html

<link rel="stylesheet" href="/assets/index.bdcfd918.css">

The code did actually send correct files but with wrong headers.
Answer: So I had to write my own file server to set the headers manually like:
contentTypeMap := map[string]string{
    ".html": "text/html",
    ".css":  "text/css",
    ".js":   "application/javascript",
}

filepath.Walk("./dist", func(path string, info os.FileInfo, err error) error {
    if err != nil {
        log.Fatalf(err.Error())
    }
    if info.IsDir() {
        return err
    }

    dirPath := filepath.ToSlash(filepath.Dir(path))
    contentType := contentTypeMap[filepath.Ext(info.Name())]
    handlePath := "/" + strings.Join(strings.Split(dirPath, "/")[1:], "/")

    hf := func(w http.ResponseWriter, r *http.Request) {
        w.Header().Add("Content-Type", contentType) // <---- key part
        http.ServeFile(w, r, path)
    }

    if handlePath != "/" {
        handlePath += "/" + info.Name()
    }

    mainRouter.HandleFunc(handlePath, hf)
    return nil
})

(please optimize if the code is bad, I made the solution myself and I tried so many stuff to fit my needs)
Now with that I recevied the correct files with correct headers.
And I couldn't find any solutions to work with custom headers using http.FileServer in http package. And please provide a easy solution if it exists.


At what rate does the volume (velocity) of a note decay?

Question: Forgive me if this is more a physics question than a music question! My question is: When a note is struck on a piano and held down (or a tuning fork is struck, or any instrument where there is just a one-time impact that then rings until dampened), what is the rate of decay in volume (aka velocity)? I strongly suspect that it is not linear; that the volume after two seconds is not half the volume after one second.
By extension, is it possible to calculate, or even just estimate, how long a note continues to reverberate on a piano if struck at maximum impact, versus lightly pressed, when held down in both cases?
Background, not essential:
I have a beautiful AvantGrand N2, which includes a standard MIDI output via a UX16 capble that allows one to record on a computer when and how forcefully a note was struck. While MIDI will never capture the complete soul of a piano, I want to use this just to see how accurately I'm expressing certain notes in a chord versus others.
The way MIDI works, it just sends a signal when a note was struck and how forcefully (known as "velocity"), and a second signal when that note was released, even if one removes one's finger 30 seconds later, long after the note has decayed. (It can read the pedals too, but that's a future endeavor.) So my question is: When a note is struck, and I want to visualize the velocity over time, what sort of function should I apply to the initial velocity?
Thank you!
Comment: It's nowhere near that simple. Quick experiment. hit the top note & bottom note... which decays first?
Comment: "what is the rate of decay in volume (aka velocity)?"

For a start, volume isn't velocity.
Comment: Velocity is basically how **fast** you hit the note. The way the sensors work that's all it can do - times how long it takes for the note to travel from rest to pressed. That is translated to 'weight'. Once the note is then generated, real or imaginary, what you then hear is 'volume'.
Comment: Velocity is "the rate at which a keyboard controller key is pressed" according to a paper about how to interpret and implement it.  https://pdfs.semanticscholar.org/92a7/dc5007d770e0c5a3a637f66ee128ba107a92.pdf
Comment: Once you're in the realm of actual sound, midi then has no job to do until you let go of the note, at which point the processor then determines what should occur [good ones have all kinds of ancillary functions at that point - sympathetic resonance, mechanical noise, subtle stuff, but that's why the Avants are  expensive]
Comment: @Tetsujin Great little demonstration!
Comment: @LaurencePayne out of curiosity, any idea why the (much criticized) MIDI specs describe the force of the key strike as "velocity"? The same term applies to the depth of the dampening pedal touch and various other measures
Comment: @Tetsujin Yeah, the Avant delivers a "Polyphonic Aftertouch" (midi code 10100000/A0/160 for Channel 1), which I'm still figuring out
Comment: Not sure how much use that's ever going to be for a piano, but it's useful in synthesis & sound manipulation. Check your midi recorder can record it [many don't by default], but only if you can find a real use for it, as it's data intensive.
Comment: You're using a synth (hence the MIDI output) - this is not an acoustic piano so far as I can tell from the ad blurb.  The decay is thus determined with a bunch of algorithms and the prerecorded sound samples.
Comment: You hit the key with force.  The result of the force is to give the key movement velocity.  And, whether it's an acoustic piano or a MIDI keyboard, the velocity is what matters.   In a piano the hammer is thrown at the string.  Like a baseball once it's left the pitcher's hand, the only information the batter receives is its (fixed) mass and its velocity.  And the MIDI keyboard simply measures elapsed time from the top of the key travel to the bottom.   I.e. the velocity.   Some MIDI controls that are just switches use nominal velocity values - perhaps 0 for off, 64 for on - for convenience.
Answer: You needn't calculate or estimate or do fancy math.  Others have measured piano string decay rates, and they're messy:

Measurements have been made on a high‐quality spinet piano to determine the initial amplitude and decay characteristics of the principal harmonic components of notes covering the entire scale. Decay rates of individual components varied from 1 to 100 db/sec as a function principally of frequency and string position in the scale rather than of harmonic number. An exception was noted in the third to fifth octaves, where the fundamental of a given string decayed at a considerably higher rate than the harmonics. This pattern appears to have a strong influence in determining typical piano tone in this region. Frequency spectra of the initial amplitudes of individual notes over the entire scale show, on the average, a sharp cutoff below 100 cps, a fairly flat region between 100 and 1000 cps, and a roll‐off of at least 12 db per octave above 1000 cps, with negligible energy above 8000 cps.

Here's another technical paper whose abstract confirms your hunch that the decay is nonlinear.
Comment: Thank you! Seeing as I'm not trying to recreate a realistic piano from mere MIDI, this will suffice just fine. Thank you!


generator to list conversion yields different results when it is done in or outside the a list comprehension

Question: I had a code snippet behaving weirdly; I made another to illustrate the problem.  I think the two snippets should yield identical results but don't :
alphas = np.arange(5)
args = zip(np.arange(5), np.arange(5))

output = [np.mean([ a+b for a, b in args]) for _ in alphas]

yielding
[4.0, nan, nan, nan, nan]

and
alphas = np.arange(5)
args = zip(np.arange(5), np.arange(5))
args = list(args)  # <- this is the only difference

output = [np.mean([ a+b for a, b in args]) for _ in alphas]

yielding
[4.0, 4.0, 4.0, 4.0, 4.0]

The only difference is that the generator is converted to a list inside the list comprehension.
Does anyone understand the underlying mechanism that makes the results different ?
Comment: Fixed the outputs for you.
Comment: `zip` returns an iterator, and you're trying to iterate over it multiple times (once for each `_ in alphas`).
Comment: Thank you for your answer and for your edit. Sorry for swapping the outputs.
Answer: A generator produces the output sequence only once.  Your first expression uses the entire sequence on the out for's first iteration.  When _ advances from 0 to 1 and cycles around to iterate through args again, there's nothing left to yield, and you have an empty return.  This results in nan for the mean value.
In your second example, args is a static list; you can iterate through that as many times as you like.
Comment: Oh I see ! Thank you for the explanation :)
Comment: And thank you for the edit. I apologize for the mistakes I made.


Why is the ROC curve of a random classifier the line $\text{FPR}=\text{TPR}$?

Question: The title is my whole question.  FPR is the false positive rate. TPR is the true positive rate.
Answer: If you classify a fraction $k$ of your cases as positive then, because of the randomness, the same fraction $k$ of cases which should be positive will be classified positive (true positives), and the same fraction $k$ of cases which should be negative will be classified positive (false positives).
So the true positive rate and the false positive rate are the same.
Comment: can you possibly write that with probabilistic statements?
Comment: @ℕʘʘḆḽḘ   Call $T$ the event that a case is actually positive and $R$ the event that it is predicted to be positive with this random predictor.  Then $\mathbb P(R \mid T) = k = \mathbb P(R \mid T^{c})$
Comment: thanks sure but I mean could you explain how you derive this result?
Comment: @ℕʘʘḆḽḘ "a random classifier" is stated in the title, so the probability of being predicted positive does not depend on any property of the event
Comment: You may want to have a look at this: https://datascience.stackexchange.com/a/31877
Answer: Identity
Let $T$ be the event that a case is positive, and $R$ the event a case is predicted to be positive by a classifier.
Since $T$ and $T^c$ are mutually exclusive and collectively exhaustive, we can decompose $\mathbb{P}(R)$ as follows:
\begin{split}
\mathbb{P}(R) & = \mathbb{P}(R|T)\mathbb{P}(T)+\mathbb{P}(R|T^c)\mathbb{P}(T^c)\\
 & = \mathbb{P}(R|T)(1-\mathbb{P}(T^c))+\mathbb{P}(R|T^c)\mathbb{P}(T^c)\\
& = [\mathbb{P}(R|T^c)-\mathbb{P}(R|T)]\mathbb{P}(T^c)+\mathbb{P}(R|T).
\end{split}
The identity
$$\mathbb{P}(R)-\mathbb{P}(R|T) = [\mathbb{P}(R|T^c)-\mathbb{P}(R|T)]\mathbb{P}(T^c),$$
means that $\mathbb{P}(R)-\mathbb{P}(R|T) = 0$ if and only if $\mathbb{P}(R|T^c)-\mathbb{P}(R|T)=0$, for $\mathbb{P}(T^c)>0$.
Random guessing
To begin, inspect the left-hand side condition: $\mathbb{P}(R)=\mathbb{P}(R|T)$. This condition implies the independence between events $R$ and $T$. A classifier that is based on random guessing has to satisfy this condition.
Suppose the classifier is random guessing but it does not satisfy the left-hand side condition, i.e. $\mathbb{P}(R)\ne\mathbb{P}(R|T)$. Then, the guesses are biased for cases that are in $T$, i.e. the classifier guesses differently when encountering a positive case. This contradicts the notion of a random guess.
In other words, if the classifier is random guessing unconditionally, or conditionally on positive cases, it should perform equally well in both cases.
Line y = x
Next, inspect the right-hand side condition: $\mathbb{P}(R|T)=\mathbb{P}(R|T^c)$. This condition means that the true-positive rate equals to the false-positive rate. Geometrically, the line $y=x$ on the ROC graph represents this right-hand side condition. This is because, the ROC graph y-axis and x-axis represent the true-positive rate and false-positive rate respectively.
Equivalance
To conclude, the left-hand side condition represents a random-guessing classifier, and the right-hand side condition represents the line $y=x$. They are in fact equivalent.
Answer: A general classifier produces a point in the ROC space rather than a curve.
In order to consider a curve you typically further assume a parameterized classifier class of the form $f_t(X) = \mathbb{1}[h(X)>t]$, where $h(X)$ is a continuous random variable.
Now $(P(h(X)>t|Y=0),P(h(X)>t|Y=1))$ is a curve in the ROC space (parametrized by t).
In this case and if in addition $h(X)$ is independent of $Y$ then
$$P(h(X)>t | Y=1) = P(h(X)>t) = P(h(X)>t|Y=0)$$
and the curve is the line $(P(h(X)>t),P(h(X)>t))$.


Integrate $I = \int_{-\infty}^{+\infty}\exp\left\{-\gamma\, t + i\,( \omega_0-\omega)\,t\right\}\,\mathrm{dt}$

Question: When deriving the line-shape for natural lifetime broadening this integral has to be solved.
Some sources give the answer as follows:
$$
I = -\left(\dfrac{1}{i\,(\omega_0-\omega)-\gamma}-\dfrac{1}{i\,(\omega_0+\omega)+\gamma}\right)
$$
How do they get there? When I evaluate the Integral I only get:
$$
\dfrac{1}{i\,(\omega_0-\omega)-\gamma}\,\left[\exp\left\{-\gamma\, t +  i\,( \omega_0-\omega)\,t\right\}\right]_{-\infty}^{+\infty}
$$
Which somehow diverges ($\exp\{t\to\infty\}$). So where is my reasoning wrong?
Answer: You overlooked two things:
Following your source, we have
$$E(t) = E_0 e^{-\gamma t} \left( e^{i \omega_0 t} + e^{-i\omega_0t}\right)\tag{1}$$
Note that I added the complex conjugated.
Then:

Excitation takes place at t = 0; observation follows for t > 0.

Meaning there's an implicit heaviside function $\theta(t)$ in $E(t$), so that $E(t)$ is $0$ for $t < 0$.
The general formula is given by
$$a(\omega) = \int \limits_{-\infty}^{\infty}E(t) e^{-iwt}\mathrm{d}t$$
Plugging in $E(t)$
$$a(\omega) = \int \limits_{-\infty}^{\infty} \theta(t) E_0 e^{-\gamma t} \left( e^{i (\omega_0-\omega) t} + e^{-i(\omega_0+\omega)t}\right) \mathrm{d}t$$
Exploiting the heaviside function, the integral boundaries become
$$a(\omega) = E_0 \int \limits_{0}^{\infty}\left( e^{[i (\omega_0-\omega)-\gamma] t} + e^{[-i(\omega_0+\omega)-\gamma]t}\right) \mathrm{d}t$$
$$=E_0 \left( \frac{1}{i (\omega_0-\omega)-\gamma} + \frac{1}{-i(\omega_0+\omega)-\gamma} \right)\left( e^{[i (\omega_0-\omega)-\gamma] t} + e^{[-i(\omega_0+\omega)-\gamma]t}\right) \Bigm|^\infty_0$$
The integral vanishes for $t\to \infty$, as you can easily convince yourself by writing the exponential function as a product or by looking at the graph of the amplitude. Thus, we only have to evaluate at $t=0$ where it is of course $1$.
$$=E_0 \left( \frac{1}{i (\omega_0-\omega)-\gamma} + \frac{1}{-i(\omega_0+\omega)-\gamma} \right) \cdot (0-1)$$
a bit of algebra
$$=-E_0 \left( \frac{1}{i (\omega_0-\omega)-\gamma} - \frac{1}{i(\omega_0+\omega)+\gamma} \right) \cdot$$
There you go.
Comment: Thank you! I could have been pondering about this for ages since I had never spotted these details.


Convert GUID array to int array

Question: I'm using linq query to create my collection based on it's id which is a guid.I've an item which can be associated to 1 or more products.What I need is to show all the productnames associated to that item and other datas like name,summary,date aswell.My issue here is when i try to use the variable i which is a guid in my array it throws error that Guid cannot be converted to int.I'm very sure that I've to convert my Guid array to int array but not sure how to implement it. below is my code.
       foreach( Guid  i in itemid)
       {

          var vals = from r in datacontext.ItemTable_s where r.itemID == i select r;

            ItemTable_s[] tempdata = vals.ToArray<.ItemTable_s>();

            Facet[] ftemp= new Facet[tempdata.Length];

   ItemImage image = null;
   string s1="";

      for (int iv = 0; iv < tempdata.Length; iv++)
          {
          s1 += tempdata[i].productname + "\n";

          }

           ftemp[3] = new facet("Productname",facettype.text,s1);
          collection.AddItem( tempdata[i].ItemName, null, null,
                               new ItemImage(new Uri(-tempdata[i].location))
                                                                );

   }

In my above code tempdata[i] is where i get error msg saying guid cannot be converted to int implicitly.How do i fix this is there any other better approach?
Comment: Whats a Facet and what is the constructor Arguments.
It seems more logical to me that the 3 parameter for the Facet class is an Integer and not a GUID
Comment: You can convert Guids into ints but it is very ugly. http://stackoverflow.com/questions/4518684/convert-guid-to-int
Comment: my variable i is a GUID as per my foreach loop.my facet are all string but my tempdata is an array of my items guid's.
Comment: It's complaining because an array's `Count` is a method, not a property. Use `items.Length`, or actually execute the method by using `items.Count()` instead.
Answer: Change your logic. Instead of using a foreach, use an int for statement. Then access the itemid's from the array. Something like this:Something like this:
    for( int i=0; i<items.Count; i++)
{
    ...
    var vals = from r in datacontext.ItemTable_s where r.itemID == itemid[i] select r;
    ...
    s1 += tempdata[i].productname + "\n";
}

Didn't try the code, but I hope you'll get the idea...
Comment: i tried your code but it throws error on i<items.count saying Operator '<' cannot be applied to operands of type 'int' and method 'group'.Any help?
Answer: A GUID looks like this
7c9e6679-7425-40de-944b-e07fc1f90ae7
As you can see there is not an Int Representation of that character. your Facet Constructor would need to take a GUID instead of an int.
Comment: but y when i try to use tempdata[i].description shows error saying i cannot be converted to int from guid? Any suggestions.I just don't want to get into convertions if it's not necessary.
Answer: (A GUID is 128 bits, so it cannot safely be converted into a 32-bit integer.)
A better option might be to use a Dictionary<Guid, ItemTable_s>.  Then you can still use GUIDs to index it.
var tempdata = new Dictionary<Guid, ItemTable_s>;
foreach(var anItem in datacontext.ItemTable_s)
{
    tempdata.Add(anItem.ItemID, anItem);
}

Then the line that's currently raising an exception (s1 += tempdata[i].productname + "\n";) should work as-is.
This will also make your itemid array unnecessary.   Alternatively you could keep the two arrays you're using.  Then you would have to change that line to:
s1 += tempdata[itemid.IndexOf(i)].productname + "\n";

It looks like that is what you were intending to do.  But that will be much slower than using a dictionary. It means you'll be doing a sequential search of the itemid array every time you need to figure out where an entry is in tempdata.
Comment: Thanks for the suggestion.How do i declare the tempdata in an array.how do i handle   foreach( Guid  i in itemid)
       {

          var vals = from r in datacontext.ItemTable_s where r.itemID == i select r;

            ItemTable_s[] tempdata = vals.ToArray<.ItemTable_s>();

Convert GUID array to int array


What is the fastest ASSISTED human running speed ever attained?

Question: I'm trying to find records/history of assisted running speeds, e.g. using cheetah boots/the things Oscar Pistorious wore, bionics, etc. (I have tried searching Google to no avail.)
What is the fastest ASSISTED human running speed ever attained?
Comment: What are "cheetah boots"?
Comment: If you count wind as being assisted, there are NFL players that have got into the 23-24 MPH range.
Comment: @Coach-D I found "assisted" to be with respect to lower body disabilities based on the context of the question. However, the question isn't clear enough to determine whether this or external factors (ie, you mention wind, etc.) is what the OP had attributed to being "assisted."
Answer: There are many different classifications in para-athletics. As it pertains to "assisted" running, the relevant classifications based on "the things Oscar Pistorious wore, bionics, etc." are T42(1) ("single above knee amputation"), T43(2) ("double leg, below knee amputation"), and T44(3) ("single below knee amputation"). NOTE: the T42 and T44 classifications include "impairment comparable to an amputation." Oscar Pistorious is classified as T44.
Taking men's and women's 100m dash world record times among these classes, the fastest time recorded is 10.57 seconds in men's class T43(4), which is approximately an average speed of 21.16 miles per hour over a distance of 100 meters(5). Taking men's and women's 200m dash world record times among these classes, the fastest time recorded is 20.66 seconds in men's class T43(6), which is approximately an average speed of 21.65 miles per hour over a distance of 200 meters(7).
The above suggests that the top speed that can be attained is slightly greater than 21.65 miles per hour. Using a crude estimation, subtracting the 100m world record time in men's class T43 from the 200m world record time in men's class T43, the difference is 10.09 seconds or approximately an average speed of 22.17 miles per hour(8).
However, this graph as it pertains to unassisted running shows that the second 100m split from the 200m world record in men's class T43 can be less than 10.09 seconds, suggesting that an even higher top speed can be attained. Unlike Usain Bolt's men's 100m dash world record time of 9.58 seconds(9) as it pertains to unassisted running, I was unable to find 10m splits for the 100m/200m dash in men's class T43 or other records/history to further determine a top speed for assisted human running.

The paralympic records site has a nice selection for recalling records based on event type, men and/or women, and record types.
Comment: Well this has to be incorrect because watching the NFL network they actually have a MPH tracker on some of the players and some of the data has been 22+ MPH.  It seems that you are looking at average top speed instead of maximum top speed.
Comment: @Coach-D Was there a player wearing [these](http://cdn.3news.co.nz/3news/AM/2013/3/2/288703/pistorius.jpg) while running 22+ MPH?
Comment: Point was just that if a football player can reach 22 MPH in pads then obviously someone can run at least a little faster assisted.


Keeping Data in GridView after PostBack

Question: I have a GridView which is associated with an SqlDataSource.
When I click a Button, I change the SelectCommand and then I use DataBind to update the GridView.
After PostBack, I want the latest Data to Remain, I don't want the GridView to be loaded by the original SelectCommand.
I know this is done by something called ViewState, but I didn't manage to implement it in the right way.
I tried both EnableViewState="true" and EnableViewState="false" on the Grid itself, with no luck.
Code
<asp:GridView ID="GridView1" ...... DataSourceID="UsersSource" >
<asp:SqlDataSource ID="UsersSource" ... SelectCommand="SELECT * FROM USERS"></asp:SqlDataSource>

On Startup, the GridView is filled with the results of SELECT * FROM USERS.
Now I click a Button, that does the following:
UsersSource.SelectCommand = "SELECT * FROM USERS WHERE user_id = 1";
GridView1.DataBind();

The GridView is filled with the new Data.
Now let's say, I click on a header to sort this table, there will be a postback, and after it, the data in this table will contain the results of the first query.
What needs to be done here?
More Info
Declaration:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Admin.aspx.cs" Inherits="Admin" %>
There's nothing in the Page Load method.
Comment: Can you show your <%@ Page  %> declaration of the page containing the gridview. Also is there any code in your Page_Load event ?
Answer: This is by design. The problem here is that the SqlDataSource gets re-created when the page loads it does NOT maintains the selectcommand on postback but rather reverts to the one that was set when the DataSource was created.
So you need to tell the the SqlDataSource what it had for SelectCommand  when it last loaded correctly.
Just store the SQL COMMAND in ViewState and enable encryption to protect the contents by setting ViewStateEncryptionMode on the Page directive. [ Always choose security as a standard ]
<%@ Page ViewStateEncyptionMode="Always" %>

In your button click event store your new command in view state:
ViewState["currentCommand"] = "SELECT * FROM USERS WHERE user_id = 1";
UsersSource.SelectCommand = ViewState["currentCommand"];
GridView1.DataBind();

Now in your page load event, set it:
if( ViewState["currentCommand"] !=null)
    UsersSource.SelectCommand = ViewState["currentCommand"];

Refer to this post by Microsoft: http://connect.microsoft.com/VisualStudio/feedback/details/105069/sqldatasource-selectcommand-not-persisting-on-postback

Keeping Data in GridView after PostBack


Generalization of Gauss's summation trick, relationship with proof of fundamental theorem of calculus?

Question: Consider the following excerpt from Nets Katz's notes on calculus here, from pages 5 and 6.

As you can imagine, the argument generalizes to the sum of $k$th powers.$$S_k(n) = \sum_{j = 1}^n j^k.$$Keeping track of $k + 1$-tuples with some entries the same is tricky, but the highest order term in the formala is easy to guess. Gauss's trick is that $k + 1$-tuples with a single largest component have that component in one of $k + 1$ places. So what we get is that$$S_k(n) = {1\over{k + 1}}n^{k + 1} + \text{lower order terms.}$$You guys know some calculus so this should be familiar to you as one of the most basic facts in calculus. It encodes that the indefinite integral of $x^k$ is ${1\over{k + 1}}x^{k + 1}$. That's the same factor of ${1\over{k+1}}$ in both places. So what's actually happening is that Gauss' trick gives you a new (and perhaps unfamiliar) way of proving this fundamental fact. What is the way you're used to deriving it? Basically you work through the fundamental theorem of calculus, you know how to take derivatives and you know you have to guess a function whose derivative is $x^k$.

Question. How are these different proofs related, and if possible, is there a way to visualize the relation between these different proofs?
Comment: Also posted to math.overflow: https://mathoverflow.net/questions/279908/generalization-of-gausss-summation-trick-relationship-with-proof-of-fundamenta
Comment: The integral of $x^{k} $ can be easily calculated by using limit of an appropriate Riemann sum independently of the formula for $S_{k} (n) $. Moreover if you see the answer to your previous question you note from the inclusion exclusion principle $$n^{k+1}=\sum_{j=1}^{k+1}(-1)^{j-1}\binom{k+1}{j}S_{k+1-j}(n)$$ which is nothing more than summation applied to identity (which is a consequence of binomial theorem) $$n^{k+1}-(n-1)^{k+1}=\sum_{j=1}^{k+1}(-1)^{j-1}\binom{k+1}{j}n^{k+1-j}$$
Comment: These formulas for $S_{k} (n) $ are totally mysterious when you see them the first time and become trivial once you see the expression for $n^{k+1}-(n-1)^{k+1}$.
Answer: Only a comment, because I'm not sure that I understand what you like to know.
$\,(A)\enspace$ With the Bernoulli polynomials we have the following formula  :
$$ S_k(n)=\frac{B_{k+1}(n+1)-B_{k+1}(1)}{k+1}$$
$B_k(x)\,$ is a polynomial of $\,x\,$ of degree $\,k$ .
We have $\enspace B_0(x)=1\,$ , $\enspace\displaystyle\frac{d}{dx}B_k(x)=k B_{k-1}(x)\enspace$ and $\enspace\displaystyle\int\limits_0^1 B_k(t)dt=0\enspace$ for $\,k\geq 1\,$ .
It follows $\,B_k(x+1)-B_k(x)=k x^{k-1}\,$ and therefore the summation formula.
$\,(B)\enspace$ If you are looking for a generalization of the summation by differences for $S_k(n)$,
$\hspace{1cm}$ you will find that in Concrete Mathematics.
For a polynom $\,f_m(x)\,$ of degree $\,m\,$ we have with the method of differences the summation formula $$\sum\limits_{j=0}^n f_m(j) = \sum\limits_{k=0}^m {\binom {n+1}{k+1}} \sum\limits_{v=0}^k (-1)^{k-v} {\binom k v} f_m(v) \enspace\enspace .$$
With $\,f_m(j):=j^m\,$ one gets the well-know formula for $\,S_m(n)\,$ with the Stirling numbers of the second kind.
Some hints:
Given: $\enspace\Delta f(x):=f(x+1)-f(x)\,$, $\enspace If(x):=f(x)\,$ , $\enspace Ef(x):=f(x+1)$
with their generalisations
$\hspace{1.45cm}\Delta^{n+1} f(x):= \Delta(\Delta^n f(x))$ , $I^{n+1} f(x):=I (I^n f(x))$ and $E^{n+1} f(x):=E (E^n f(x)) \,$ .
Be $\,m\in\mathbb{N}_0\,$ and $\,v\in\{0,1,2,…,m\}\,$ .
For $\, x^{\underline{n}}:= x (x-1) … (x-n+1) \,$ follows $\,\Delta^v x^{\underline{m}}=m^{\underline{v}}x^{\underline{m-v}}\,$ .
And we get, written in a symbolic way (using the linearity of the difference $\,\Delta:=E-I\,$ which
means $\,\Delta f(x)=(E-I)f(x)=Ef(x)-If(x))\,$ to simplify the method of differences:
$$ \Delta^k f_m(x) = (E-I)^k f_m(x) = \sum\limits_{v=0}^k (-1)^{k-v} {\binom k v} E^v f_m(x) =  \sum\limits_{v=0}^k (-1)^{k-v} {\binom k v} f_m(x+v)  $$
Be $\,\displaystyle f_m(x) := \sum\limits_{k=0}^m b_k x^{\underline{k}}\,$ .
It follows $\,\displaystyle \Delta^v f_m(x) = \sum\limits_{k=0}^m b_k \Delta^v x^{\underline{k}} = \sum\limits_{k=0}^m b_k k^{\underline{v}} x^{\underline{k-v}} \,$ and the special case $\,\Delta^k f_m(0)= b_k k! \,$ .
Substituting $\, b_k\,$ by $\, \displaystyle \frac{\Delta^k f_m(0)}{k!}\,$ and using the formula for $\,\Delta^k f_m(x)\,$ with $\,x:=0\,$ gives us the summation formula
$$f_m(x)=\sum\limits_{k=0}^m \frac{x^{\underline{k}}}{k!} \Delta^k f_m(0)= \sum\limits_{k=0}^m {\binom x k} \sum\limits_{v=0}^k (-1)^{k-v} {\binom k v} f_m(v) \enspace .$$
Finally $\,x\,$ substituted by the counter $\,j\in\{0,1,2,…,n\}\,$ with $\,n\in\mathbb{N}_0\,$ and
$\displaystyle \sum\limits_{j=0}^n {\binom j k} = {\binom {n+1}{k+1}}\,$ we get the formula for $\,\displaystyle\sum\limits_{j=0}^n f_m(j)\,$ above.
For further informations please see Concrete Mathematics .


How to hide the text formats help text?

Question: I want to hide the description of the text format under the "Comment" box which says:

No HTML tags allowed.
Lines and paragraphs break automatically.

There are a variety of ways to do this on Drupal 7, but what about Drupal 8?
Comment: @dxvargas That's right; we should refresh this question.  Please add that as an answer and I will accept.
Comment: After Drupal core 10 the allowed formats can be set as an option in text fields configuration. See:https://www.drupal.org/node/3318572.
Answer: AFAIK there is currently no core UI to control showing/hiding of those tips.
Th simplify module, one of the D7 choices you link to, has a D8 port that may still help with this.
The Allowed formats module is an incubator for future core improvements in the area of giving sitebuilder's UI control over text format and their help tips.
== UPDATE ==
A patch just committed to that module gives sitebuilders considerable control over help tips, using UI settings on the widgets.
== OLD ==
There are a couple of relevant issue in the issue queue for that module:
Allow to control if "About text formats" link should be shown or not
Allow to hide text format help text for Text(formatted)
The first of those issues contains this code from floretan, which points in the direction you would need to go to hide the help by custom code:
<?php
/**
 * Implements hook_field_widget_form_alter().
 */
function allowed_formats_field_widget_form_alter(&$element, FormStateInterface $form_state, $context) {
  if ($context['widget'] instanceof \Drupal\text\Plugin\Field\FieldWidget\TextareaWidget) {
    $element['#after_build'][] = '_allowed_formats_remove_textarea_help';
  }
}

/**
 * #after_build callback.
 */
function _allowed_formats_remove_textarea_help($form_element, FormStateInterface $form_state) {
  if (isset($form_element['format'])) {
    // All this stuff is needed to hide the help text.
    unset($form_element['format']['guidelines']);
    unset($form_element['format']['help']);
    unset($form_element['format']['#type']);
    unset($form_element['format']['#theme_wrappers']);
  }

  return $form_element;
}
?>

Comment: Unfortunately removes this the tips and guidelines etc. on all admin pages too ;( To use this only on node edit pages you can check this with `if ('entity.node.edit_form' === \Drupal::routeMatch()->getRouteName() && $context…`. And you should thinking about `TextareaWithSummaryWidget` as other possible widget type.
Comment: The second portion of the code helped me. Thanks
Answer: This work for me in drupal 8, You have to change the field machine name
<?php

use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_field_widget_form_alter().
 */
function YOURMODULENAME_form_alter(&$form, &$form_state, &$form_id) {
    $form['field_short_description']['widget']['#after_build'][] = '_allowed_formats_remove_textarea_help';
}

function _allowed_formats_remove_textarea_help($form_element, FormStateInterface $form_state) {

  if (isset($form_element[0]['format'])) {
    // All this stuff is needed to hide the help text.
    unset($form_element[0]['format']['guidelines']);
    unset($form_element[0]['format']['help']);
    unset($form_element[0]['format']['#type']);
    unset($form_element[0]['format']['#theme_wrappers']);
    $form_element[0]['format']['format']['#access'] = FALSE;
  }

  return $form_element;
}

Comment: This should be marked as a correct answer for Drupal 8
Comment: Somehow my $form_element does not have the same values as above, so nothing to disable :-(
Answer: As simple and general solution (for all fields)  is to install a contributed theme outside core and use that as a administration theme and simply do something like
.filter-guidelines-item .tips  {
    display:none;
}
Or patch one of the themes inside core and make a note to repatch when you do an upgrade.
Answer: If you are wondering how to do this in Form API, so when you are creating form elements in a Form class instead of altering form elements afterwards:
Your form element:
$form['my_field'] = [
  '#type' => 'text_format',
  '#title' => 'My Title',
  '#allowed_formats' => ['basic_html'],
  '#after_build' => [[get_class($this), 'hideTextFormatHelpText'],],
];

Add this function to your class:
  public static function hideTextFormatHelpText(array $element, FormStateInterface $form_state) {
    if (isset($element['format']['help'])) {
      $element['format']['help']['#access'] = FALSE;
    }
    if (isset($element['format']['guidelines'])) {
      $element['format']['guidelines']['#access'] = FALSE;
    }
    if (isset($element['format']['#attributes']['class'])) {
      unset($element['format']['#attributes']['class']);
    }
    return $element;
  }

I specifically also removed the classes because you will otherwise see some padding and a border around something empty that you probably don't want.
Answer: There is a very simple way to do this. Filter tips are displayed within a block so you can go to appearance/settings and than go to theme customize css.
Add following:
.filter-wrapper {
    display: none;
}
You can also add.
.description {
    display: none;
}
Answer: After Drupal core 10 the allowed formats can be set as an option in text fields configuration.
See: https://www.drupal.org/node/3318572.

How to hide the text formats help text?


Am I hearing overtones or beats? is it normal to hear them?

Question: I started learning piano not so long ago and there is something that's confusing me a lot: when I play some notes at the same time (chords or two notes) sometimes I hear a second higher vibrating sound besides the notes I play. It depends on which notes, for example I can hear it very clearly when I play G#3 and C4 in my digital piano. I've been researching and I suppose this might come from the overtones or maybe from the acoustic beats that they might produce.
I'm pretty sure this is not a problem with my keyboard since I hear this everywhere I play these two notes.
I uploaded a recording of these two notes being played together in some random website where I can clearly hear what I'm saying: https://on.soundcloud.com/rvJT6
So my question is: Is this normal? Does everyone hear this? I get very distracted by this while playing, could it be that they bother me more than to other people? When I play the Fm chord for example I hear this very loud
EDIT: I was just playing around with audacity and the same audio file that I shared and I found out that if I equalize it muting the 1000 Hz frequency I stop hearing the sound I mention, just and only that frequency (I suppose it's a range). If I make it louder I hear the thing louder of course and if I only play that frequency alone, then I still hear it.
So what I'm thinking is that this is a beat caused by the 4th harmonic of C4 (1046.502 Hz) and the 5th harmonic of G#3 (1038.262 Hz)
screenshot: https://imgur.com/MEsmVMA
Answer: I don't know what you hear, but I can suggest some ideas.
Equal temperament is kind of out of tune, especially the thirds. The bottom note you're playing, G#3, which I would prefer to call Ab3, has a frequency of f_Ab3 = 207.65 Hz. Its fifth harmonic is a note a two octaves and a major third higher, that is C6, and its frequency is 5·f_Ab3 = 1038.25 Hz. Frequency of the note C4 is f_C4 = 261.63 Hz, and its fourth harmonic, also C6, has a frequency of 4·f_C4 = 1046.52 Hz. Difference between these two C6 is 8.27 Hz, which results in beating between these two harmonics, with a frequency of 8.27 Hz. This could be perceived as quick fluttering of the sound. This is the reason some people dislike equal temperament.
Edit: I just see your edited version of the post and it seems that the above guess is correct. Still, below I provide some other possible effects producing additional tones.
You may also hear a combination tone between the two notes, the most prominent one has the frequency equal to the difference between the two notes. In your case that would be f_C4 – f_Ab3 = 261.63 Hz – 207.65 Hz = 53.98 Hz. This is a note between Ab1 and A1, that is low pitch, and out of tune. But in order to hear it, you either need some kind of distortion (e.g. due to poor quality small speakers), or play it very loud (apparently ears can distort sound a bit too). But if played with moderate volume, on decent speakers, it shouldn't be the case. On the other hand, in an extreme scenario when large distortion is added e.g. with an electric guitar pedal effect, you would hear more harmonics and more combination/intermodulation toned between them.
There is some little hiss in the recording. I'm not sure if that's relevant for the question?
I recall with some older pianos you could hear quantization noise, in particular with very quiet notes, or at the end of the tails of decaying notes. This could be heard as a high frequency buzzing accompanying the note. I would hope recently made that instruments use enough bit depth for this not to happen.
Comment: Thank you so much! I was amazed to see that what you mentioned first was what actually happend and I can fully understand it now. I'm still a little bit confused on why I get bothered by this but I suppose we don't all hear the same way.

It also called my attention that you mentioned a hissing sound in the recording. Of course it was recorded with very low quality but I wonder if the hissing sound you mention is the actual sound I'm talking about which at least for me is very noticable mainly in the middle of the sound
Comment: @user93987 There is some little hiss or noise in between the notes.
Comment: The question mentions a digital *piano*. The synth could be emulating the tendency of a real piano to have 'stretched' harmonics due to the physical properties of the strings, which would impact on the frequency of the beating. Although I don't know what to make of "higher vibrating sound".
Answer: Overtones and Harmonics
Overtones are higher-sounding-tones (notes) that are produced when you play a tone (base frequency) on an acoustic or electric instrument. As you might already know, harmonics (or harmonic overtones) are a specific category of overtones, whose frequency is an integral multiple of the base frequency.
Harmonic vs non-harmonic sounds
A sound which predominantly features harmonic overtones is usually perceived as harmonic, which means that we can accurately gauge its pitch.
A sound that heavily features non-harmonic overtones is usually perceived as the opposite; you'll have some difficulty discerning the pitch.
When I first learned of this in an acoustics course, I was immediately reminded of the church bells in my hometown. I was always having trouble figuring out their melodies.
Consonance and Dissonance
Now as to how these relate to your question. Base frequency and overtones both have everything to do with consonance and dissonance. The more two sounds' overtones overlap, the more consonant we perceive them to be. That's why the octave is the most consonant interval: the notes share all of their overtones.
Hearing overtones is completely normal
While not everyone finds it easy to spot overtones, under certain conditions they can be quite audible. I was tuning a spinet in my school, and playing the octave interval of E - e produced a very audible overtone of a B, which (expressed as a simple interval) is a fifth.
Are you hearing overtones or beats?
I am not very acoustics-savvy, but my understanding is that the beats you are hearing are the result of some of the overtones of your interval (I'd call it Ab - C, a Major third) are not matching up exactly. In a way, if you're hearing beats, you're hearing overtones too. Whether you can discern both of the overtones, which probably are only a few cents apart, is another matter entirely.
tl;dr
Hearing overtones is normal, although sometimes a bit challenging. Overtones are easier to discern when they are harmonic, especially when boosted by a resonant harmonic sound (e.g. an octave below).