Como fazer upload de uma imagem através da área de transferência (copiar e colar)?

Question: Eu estava dando uma olhada na funcionalidade do site Imgur. Quando você faz um printscreen ou mesmo copia uma imagem (não o link, mas a imagem, que é uma opção que está disponível na maioria dos navegadores atuais) e, em seguida, cola na página, é feito o upload da imagem que estava salva na área de transferência (clipboard).
Eu não faço a mínima ideia de como o Javascript pode ter acesso à essa parte da memória onde foi salvo o "Copiar".
Eu gostaria de uma demonstração simples de como posso fazer para transferir a imagem da memória e enviar através do upload. E também gostaria de saber se é possível transferir o conteúdo da área de transferência (CTRL+C) para um Blob do Javascript.
Answer: Quando algo é colado em uma página, o js dispara um evento na função onpaste.
Quando colamos uma imagem, o js através da função onpaste nos retorna um objeto com a interface File (Apenas no caso de binários, óbvio). Com esse objeto, nós podemos utilizar o método getAsFile() que utilizaremos com a classe FileReader.
Para ler esse conteúdo, podemos utilizar o método readAsDataURL da classe FileReader. Com isso nós conseguimos capturar o código base64 da imagem, e é basicamente isso que o código do site faz. Ele basicamente envia um base64, ao invés de um arquivo, para o servidor.
Segue um exemplo bem simples.

var reader = new FileReader();

reader.onload = function(result) {
  let img = document.createElement("img");
  img.src = result.target.result;
  document.body.appendChild(img);
}

document.querySelector("input").onpaste = function(event){

  let items = event.clipboardData.items;

  for (itemIndex in items) {
      let item = items[itemIndex];

      if (item.kind == 'file') {
        reader.readAsDataURL(item.getAsFile());
      }
  }
}
<input type="text" placeholder="Cole sua imagem aqui" />

Errata: Por que o Javascript precisa de um for pra achar a imagem?
O js precisa desse for porque, quando você copia uma imagem da internet, é lançando uma ação no onpaste com dois DataTransferItem.
O primeiro item é um código html com um elemento . Nesse elemento recebemos um código base64 ou a URL da imagem. Por isso você está recebendo um text/html (Você também pode receber um text/plain).
O segundo, já é uma imagem em si. Podendo ser capturada através do método DataTransferItem.getAsFile()
Comment: Bacana, cara. Simples e direto. +1
Comment: Eu só tenho uma dúvida: Por que o Javascript precisa de um `for` pra achar a imagem? Estranhamente num código que fiz semelhante ao seu, o valor `0` da iteração sempre traz um `item` com o valor `text/html` no `type` ou vazio, kkkkk...
Comment: Quando copia um arquivo da web, ao invés de vir o binário, ele como html. Fiz uma alteração que "burla" isso.
Comment: Inconformado com meu código, pesquisei um pouco mais e, fazendo alguns testes adicionais, encontrei uma resposta "descente" para a pergunta acima.


Dependency inject a class with values from a config object?

Question: Is it possible to DI dependencies in Drupal 8 but initialize it with values from a config object?
For example, SoapClient requires specifying the WSDL when called. I have different WSDL URLs depending on what environment I am using (test/prod etc).
I know you can do this from the services yaml file, but I have not read of a way where you can reference a value or value(s) from a config object.
My ultimate goal is to create a decorator or factory for SoapClient, but I'm not sure which.
edit: updated with code.
An interface:
<?php

namespace Drupal\iana_netforum_auth\Factory;

use SoapClient;

interface SoapClientFactoryInterface {

  /**
   * Create a SoapClient.
   *
   * This method should prepopulate the SoapClient with values from our
   * module configuration so it is ready to use.
   *
   * @return SoapClient
   */
  public function create() : SoapClient;

}

The factory:
<?php

namespace Drupal\iana_netforum_auth\Factory;

use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\iana_netforum_auth\Exception\NetforumException;
use SoapClient;

class SoapClientFactory implements SoapClientFactoryInterface {

  public function __construct(ConfigFactoryInterface $config_factory) {
    $this->configFactory = $config_factory;
  }

  public function create() : SoapClient {
    $config = $this->configFactory->get('iana_netforum_auth.settings');
    $arguments = [];

    try {
      if ($config->get('mode') == 'live') {
        $endpoint = $config->get('live_endpoint');
      }
      else {
        $endpoint = $config->get('dev_endpoint');
        $arguments = [
          'trace' => $config->get('enable_trace'),
          'exceptions' => $config->get('enable_exceptions')
        ];
      }

      return new SoapClient($endpoint, $arguments);
    }
    catch (SoapFault $error) {
      throw new NetforumException('Invalid WSDL endpoint specified.');
    }
  }

}

The class:
class NetforumClient implements NetforumClientInterface {

  protected $username;
  protected $password;
  protected $token;
  protected $authorizationHeaders;

  /**
   * Drupal\Core\Config\ConfigFactoryInterface definition.
   *
   * @var \Drupal\Core\Config\ConfigFactoryInterface
   */
  protected $configFactory;

  /**
   * Drupal\iana_netforum_auth\Factory\SoapClientFactoryInterface definition.
   *
   * @var \Drupal\iana_netforum_auth\Factory\SoapClientFactoryInterface
   */
  protected $soapClient;

  /**
   * Class constructor.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   An instance of ConfigFactoryInterface.
   * @param \Drupal\iana_netforum_auth\Factory\SoapClientFactoryInterface $soap_client_factory
   *   An instance of SoapClientFactoryInterface.
   */
  public function __construct(ConfigFactoryInterface $config_factory, SoapClientFactoryInterface $soap_client_factory) {
    $this->configFactory = $config_factory;
    $this->soapClient = $soap_client_factory->create();
  }

Comment: Can you share a bit more of what you're trying to create exactly? You could always inject the config factory, get the config object and pass it to the parent constructor. Or you could make a factory service that creates SoapClient instances that you then use.
Comment: Maybe that's what I'm looking for, could you explain a bit more? I want a soap client ready to go with different config from my config settings when I call my wrapper class (that uses the soap client).
Answer: Not sure which part exactly is unclear. There are lots of examples in core.services.yaml that inject the config.factory service to read a configuration object, for example this:
diff.formatter:
  class: Drupal\Core\Diff\DiffFormatter
  arguments: ['@config.factory']

The constructor for that then looks like this:
/**
 * Creates a DiffFormatter to render diffs in a table.
 *
 * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
 *   The config factory.
 */
public function __construct(ConfigFactoryInterface $config_factory) {
  $config = $config_factory->get('system.diff');
  $this->leading_context_lines = $config->get('context.lines_leading');
  $this->trailing_context_lines = $config->get('context.lines_trailing');
}

Once you have the config object, you get the configuration you want and pass it along to the SoapClient constructor.
Comment: It's weird, because when I created a factory for the soap client, the soap client started throwing errors about it not being an object, but a reference _to_ an object when I was using it. Perhaps it is something peculiar about SoapClient that I don't understand yet. The Symfony docs for using a factory in services.yml also threw errors, seems that it needs a key and not a path to a class.
Comment: It sounds a lot like this error, actually: https://stackoverflow.com/questions/22140917/object-reference-is-not-set-to-an-object-when-try-to-implement-abstract-factory
Comment: That's C#, that has nothing to do with PHP ;) I won't be able to help you as long as you don't share the the relevant part of your code
Comment: Hang on... forgot to stash that and had to redo.
Comment: Oddly enough - I rewrite the code and don't get the linked error anymore about "Object reference is not set to an object", but I posted it above. Is this the "right" way of injecting a factory?
Comment: That's one option yes. Depends on what you want. Now you have a low-level soap client object that you need to interact with. Instead of a factory, you could as you suggested also have an adapter/wrapper and expose higher-level API functions. Maybe thats what NetforumClient is. You could also inline the factory method into that class then unless you will have multiple services such as NetforumClient. But in general, this is fine, yes.
Comment: Yes, this is intended to be a wrapper to fill in gaps that SoapClient does not have that I need to perform while passing Soap calls through to it. Why does the `factory` key not get used in services.yml?


Matrix representation of idempotent operator

Question: $V$ is a finite dimensional vector space over $F$, and $:  → $ be an idempotent operator, i.e. $P^2=P$. It can be proved that $( − )$ is also an idempotent operator and $ker(P^m) = im((I - P)^n)$ for all $,  ≥ 1$.
The question is to show that under some choice of basis $B$ of $V$, there exists $0 ≤  ≤ dim()$ such that the matrix representation of $P$ with basis $B$ is
 $$
    \begin{matrix}
    1 & 0 & ... & 0 & 0& ... & 0 \\
    0 & 1 & ... & 0 & 0& ... & 0 \\
    0 & 0 & ... & 1 & 0& ... & 0 \\
    0 & 0 & ... & 0 & 0& ... & 0 \\
    0 & 0 & ... & 0 & 0& ... & 0 \\
    \end{matrix}
$$
where there are k ones in total.
I think it can be solved by proving $(b_i)=b_i$ for $I=1,...,k$. But what is the next and how can prove this?
Comment: Hi and welcome to MSE. Your question is phrased as an isolated problem statement and is not showing any effort of you approaching the problem. Please edit the question to include what you have tried and where you're struggling. As of now the question is likely to attract down votes, close votes and not getting any answers.
Comment: Thanks. Some thoughts added
Answer: Hints: Proceed as follows:

Show that for all $v \in im(P)$, we have $P(v) = v$.
Prove that $ker(P) \cap im(P) = \{0\}$ and conclude that $V = im(P) \oplus ker(P)$.
Take bases of $ker(P)$ and $im(P)$ö. This gives you a basis of $V$ (why?). Then calculate the matrix of $P$ with respect to this basis.
Comment: Helps a lot, thanks!


Set maximum / disable custom block cache for anonymous users

Question: I have a little issue regarding my custom block module. The module itself fetches weather data via json-request and the data is shown as a 4-day weather forecast to the user. As the weather should be actualized every day I want to set a "maximum cache time" or even disable caching for the whole block.
Right now I would have to flush the cash manually every day.
After a little bit of research to that topic I found out that using 'max-age' in the build() function would do the trick but it does not affect the caching for anonymous users at all.
Using \Drupal::service('page_cache_kill_switch')->trigger(); would disable the cache for a specific page or content-type but I don't want to disable the caching for a whole page at once.
So how can I trigger the caching for my custom-block? Or is there even a way to disable the caching for a certain part of the code e.g. the json-request in my case?
Comment: You can use lazy builder or fetch data in js.
Answer: This is a known issue Bubbling of elements' max-age to the page's headers and the page cache.
The Internal Page Cache is designed for database content, which is handled by cache tags. So a workaround would be to add a custom cache tag to the block
$build['#cache']['tags'][] = 'weather_forecast';

which will bubble up to the page level and so you can invalidate both cached items, block and page, in a cron job:
/**
 * Implements hook_cron().
 */
function mymodule_cron() {
  \Drupal\Core\Cache\Cache::invalidateTags(['weather_forecast']);
}

All credit goes to @Berdir: Cache max-age and varnish ESI
Comment: Thank you. That did the job for me!
In my case i had to declare the custom cache tag with `'#cache' => [ 'tags' => ['weather_forecast'], ],` to get it to work.
Answer: Limitations of max-age
Unfortunately, max-age does not work for anonymous users and the Drupal core Page Cache module. For example, see these issues:

#2352009: [pp-3] Bubbling of elements' max-age to the page's headers and the page cache
#2449749: Add #cache['downstream-ttl'] to force expiration after a certain time and fix #cache['max-age'] logic by adding #cache['age']
#2835068: PageCache caching uncacheable responses (violating HTTP/1.0 spec) + D8 intentionally disabling HTTP/1.0 proxies = WTF
#2951814: Always set X-Drupal-Cache and X-Drupal-Dynamic-Cache headers, even for responses that are not cacheable

Until these (and perhaps other) issues are resolved, beware that setting max-age on a render array included in a page is insufficient to ensure that anonymous users will see a new version after the max-age as elapsed. In the meanwhile, the Cache Control Override contributed module tries to mitigate the problems. You might also have more luck setting a custom cache tag on pages with time-dependent content and invalidating those cache tags manually via hook_cron(). Good luck!
Source:
https://www.drupal.org/docs/drupal-apis/cache-api/cache-max-age#s-limitations-of-max-age


Prove that there exists $b \in B$ that is an upper bound for $A$

Question: Given that $ \ Sup A < \ Sup B$
Now $\forall \epsilon, \exists b \in B \ such \ that $
$ \ Sup A - \epsilon < \ Sup B - \epsilon < b$
SO,
$ \ Sup A - \epsilon < b $
So we have now
$\forall \epsilon, \exists b \in B \ such \ that $
$ \ Sup A - \epsilon < b $
Also $ \forall a \in A, a \leq \ SupA. \ So,    a - \epsilon \leq \ SupA - \epsilon  $
So we have $ \forall a \in A, \exists b \in B \ and  \forall \epsilon >0$
$a - \epsilon < b $
$a < b- \epsilon$
How do i procced ?
Thanks
Comment: Instead of going "for all $\epsilon$" everywhere, let $\delta = \sup B - \sup A > 0$. Take $\epsilon = \frac \delta 2$ in the definition of $\sup B$ to  get an element $b\in B$. Is this element $b$ an upper bound of $A$?
Comment: @астонвіллаолофмэллбэрг i am not getting yourt comment. what about my attempt ?
Comment: No issue with your attempt, you are getting correct statements everywhere. However, there comes a point when rather than going on  with general $\epsilon$, you should use a  specific value of $\epsilon$ as I suggested to get a $b \in B$, which is useful for solving your question. This $\epsilon$ to be used should come from the fact that $\sup A < \sup B$ so their difference is positive.
Comment: @астонвіллаолофмэллбэрг Does sup B < Sup A implies that B is subset of A ? Also have i proved the question ? i am not sure
Comment: The answer to the first question is no, in fact $A$ and $B$ can be disjoint. For example take $A = \{1\}$ and $B = \{0\}$. You have not proved the question, because I don't see anywhere, a concrete $b \in B$ which is an upper bound of $A$ in your answer. At the end it says : $\forall a\in A, \exists b \in B, \forall \epsilon > 0$  we have $a < b - \epsilon$. This is a true statement, so now you need a specific value of $\epsilon$ to get $b > \sup A$. So you are almost there but not done yet.
Comment: @астонвіллаолофмэллбэрг We have $a > \ Sup A - \epsilon$. So,  Sup A $< a + \epsilon < b$
Comment: Also if i take $\epsiolon = \ Sup A - a$ in the $a < b - \epsilon$. i will get result. Is that right ? But problem is that here epsilon ca be equal to 0
Comment: I think the part after : $\forall \epsilon \exists b, \sup A -\epsilon < \sup B - \epsilon < b$ is not required i.e. you don't need to look at $a \in A$ at all, since you are just comparing $b$ and $\sup A$.  Now, the point is this : find an $\epsilon_0 > 0$ such that $\sup A < \sup B - \epsilon_0$, using the fact that $\sup A < \sup B$. Now for this $\epsilon_0$ find $b_0 \in B$ such that $b_0 > \sup B - \epsilon_0$. From there, since $\sup B - \epsilon_0 > \sup A$ you get $b_0 > \sup A$, so $b_0$ is an upper bound of $A$. It seems you have overworked.
Comment: As the answer below seems  to suggest, you have not made any wrong statements, but as you have proceeded, the statements have become weaker(i.e. carry less information than the hypothesis), so you are not able to extract any information useful to the problem from them. Of course, this is a trait of problem solving i.e. knowing which information is useful in the problem out of a lot of given information, so it will come with practice and exposure to the current field of study and its techniques.
Comment: i m confused. can you post answer
Comment: Yes, I think our discussion is worth one.
Comment: Here is my proof. WE have to show that $\exists b \in B $ such that Sup A < b. Now we have $ \forall \epsilon, b > Sup B - \epsilon$. Choose \epsilon = Sup B - Sup A. we get b > Sup A. Is this correct ?
Comment: Yes, that is right. I have provided a discussion of your previous answer below. I would like to thank you, I had fun  writing this answer!
Comment: pleasure is mine
Answer: Think of a strong statement as one that applies in many cases, and a weak statement as one that does not apply in too many cases. For example, the statement : "every odd number is not a multiple of $2$" is stronger than the statement : every power of an odd prime is not a multiple of $2$, which is stronger than the statement : a power of three is never a multiple of $2$ , which is stronger than the statement : $27$ is not a multiple of $2$.
Now, imagine I gave you the first statement. It has a lot of information, since it's saying something for each odd number. After that, we are going down  to smaller and smaller classes of odd numbers, till we reach a statement which is so easy to verify and contains information only about one number, $27$.
Now, the problem with proceeding like this, is that while we have a lot of true statements with us, as we have proceeded we have weakened each statement, so that the last statement is something which you really cannot do anything with.
Something like this has happened in your working. Let me explain.

Now, you started off with $\sup A < \sup B$.

Now, $\forall \epsilon \exists b \in B$, such that $\sup A - \epsilon < \sup B - \epsilon < B$.

Fine, this is by definition, so it is just a rewrite and using the fact that $\sup A < \sup B$.

So, $\mathit{\sup A - \epsilon < b}$.

This is a weakening of the previous line. The point is that you have now left out the fact that $\sup B - \epsilon$ lies in between these (sure, it is bigger than $\sup A - \epsilon$, but you have now forgotten that $b$ is bigger than it, or are not planning to use that information, which could be key in solving the problem).

Also, $\forall a \in A, a \leq \sup A$ so $a - \epsilon \leq \sup A - \epsilon$.

Once again, a correct statement, but one drifting away from the problem since to show that any $b$ is an upper bound of $A$ you only need to show that $b \geq \sup A$, so you don't need to involve individual elements of $a$, which unfortunately is being done here.

So we have $\forall a \in A$ there is $b \in B$ such that $\forall  \epsilon >0$ , $a \leq b - \epsilon$.

The problem with this statement, is that again while it is correct, you actually are saying that for each $a$ there is a $b$ depending on $a$ so that for each $\epsilon$ we have $a-\epsilon < b$. Now, first of all the $b$ depends on $a$, so how are you going to pick one of these $b$s to satisfy the solution? Next, $\sup A$ is part of the conclusion (as I mentioned, it is enough to find $b \geq \sup A$) but is not involved in this reasoning. Therefore, this weakest statement of your reasoning, while being correct, does not seemingly have the required information to achieve the conclusion.

That is, if you want to rescue the conclusion from your last line of working ,you are now left with the following question :

Suppose $A,B$ are sets such that for all $a \in A$ there is $b \in B$ such  that for every $\epsilon > 0$ we have $a -\epsilon< b$. Is it true that some $b \in B$ is an upper bound of $A$?

Now, it turns out that this is false! First of all, note that the "$\forall \epsilon > 0$ we have $a-\epsilon < b$" is the same as $a \leq b$. The counterexample is just $A = B = [0,1)$, since here one sees that no element of $B$ is an upper bound of $A$, since no element of $B$ is bigger than $\sup A = 1$. But $A,B$ satisfy the hypothesis of this question.

Which is the classical situation of overworking : you reach a very weak statement which does not imply the conclusion in general. Then, you have to work back carefully and find out what things you neglected : where did you weaken your hypothesis so much that the conclusion could not be derived.

That is what I pointed out earlier : neglecting $b > \sup B - \epsilon$ was crucial to the proof. Without that, you cannot really proceed.
So, in your working, you have to (unfortunately) scratch out everything after $\sup A - \epsilon < \sup B - \epsilon < b$.
Now, you have to think : I want a single $b$. To get a single $b$, I need a specific value of $\epsilon$. Which one can I use?

The point is, that imagine a seemingly very small change in your question : given $\sup A \color{blue}{\leq} \sup B$, prove that some $b \in B$ is an upper bound of $A$. This statement is false with the same $A,B$ which I used earlier.
Therefore, we have to use the fact that $\sup A \color{green}{<} \sup B$. The fact that the separation $\sup B - \sup A$ is strictly positive hass to be used for the question. Let us call $\sup B - \sup A = \delta > 0$.
Now, the idea is this : if $L =  \sup A$, then all we need to show that there is some $b \in B$ with $b \geq L$. However, note that if $(L+\delta) - b < \delta$ then rearranging  gives us $b > L$.
But $(L+\delta) = \sup B$, so we are essentially saying that if $\sup B - b < \delta$ then $b > L$. Can we find such a $b$? Yes, from the property of supremum and the fact that $\color{orange}{\delta > 0}$.

Now, finally let me propose a proof:
Let $\sup B - \sup A = \delta > 0$. By the property of supremum there is a $b \in B$ such that $\sup B -  b < \delta$. Rearrange to get $b > \sup B - \delta = \sup A$, so that $b > \sup A$ and hence $b$ is an upper bound of $A$.

Even when you are getting correct statements, you should be careful that you do not encounter yourself in the presence of a very weak statement. This will force you to go back to an earlier statement. So, try to explore your options in full generality : a chase for "correct statements" is ok, but you must cut to the chase of the answer, for that is your aim. This will come both with practice and with exposure to the specific topic and its techniques.
Comment: i understand. actually i have no formal training in math, i am a clerk who does math in his free time
Comment: thanks. my dream is to get Phd in number theory someday
Comment: Very nice to hear! Wish you the best of luck in your journey in mathematics!
Answer: Assume $\sup  < \sup $
$\exists b\in B$ st. $ \sup  < b < \sup B$ and thus $\sup  < b$
(Because if there's no such $b \in B$, $\sup A$ would be an upper bound of B, contradiction.)
Answer: Attempt:
0) Given: $\sup A < \sup B$
1) $\sup A$ is an upper bound for $A$, the least upper bound, hence:
For $a \in  A$: $a \le \sup A$ ,
2) Since $ \sup A < \sup B$ , $\sup B$ is an upper bound for $A$:
For $a \in A$: $a < \sup B$.
3)Since $ \sup B$ is the least upper bound for $B$:
For $b \in B$: $b \le \sup B$.
4) Set $d:=  (1/2)(\sup B- \sup A) >0.$
A bit trickier now:
5) Since $\sup B$ is the the least upper bound for $B$:
For every $\epsilon > 0$:
$\sup B - \epsilon$ is NOT an upper bound for $B$.
Hence there is a $b_{\epsilon} \in B$ s.t.
$\sup B - \epsilon < b_{\epsilon} \le \sup B.$
(Note: If the above statement were not true $\sup B -\epsilon$ would be a bound for $B$, less than $\sup B$, a contradiction)
6) Let $\epsilon = d;$
Then
$\sup A < \sup B - d=$
$ (1/2)(\sup A +\sup B) < b_{d}$ .
Hence $b_{d}$ is an upper bound for $A$.


Function returns -nan

Question: I have this code. Why does it produce -nan upon returning a value in main program?
#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <cmath>

using namespace::std;

float f(float x)
{
    float result = -5 * x * x - 2 * x + 1;
    return powf(result, (float)1/(float)3);
}
int main()
{
    cout<<f(-1)<<endl;
    getchar();
    return 0;
}

This confuses me. As I far as I know, I use suitable data type.
Comment: `If the base is finite negative and the exponent is finite but not an integer value, it causes a domain error.` It says right on the reference page.
Comment: `-5 * x * x - 2 * x + 1` is negative for `-1`
Comment: @slawekwin: Actually, negative numbers do have odd roots (e.g., cube root of -27 is -3). It's only even roots of negative numbers that require imaginary numbers.
Comment: @JerryCoffin: Actually all roots require imaginary numbers: cubic root has 2 imaginary results and 1 real.
Comment: @AdrianMaire: It's true that there are complex roots as well (just as there are complex roots of positive numbers), but there are purely real odd roots of negative numbers. So no, not all roots *require* imaginary numbers.
Answer: When you call your function with negative one the base is equal to -2 and the exponent is 1/3 (non-integer).
According to the specification for powf:

pow(base, exponent) returns NaN and raises FE_INVALID if base is finite and negative and exponent is finite and non-integer.

Which explains why your function is returning NaN.
If you're trying to calculuate the cubic root I suggest you use cbrt instead.
Answer: cplusplus reference say:

The NaN values are used to identify undefined or non-representable
  values for floating-point elements, such as the square root of
  negative numbers or the result of 0/0.
The argument can be used by library implementations to distinguish
  different NaN values in a implementation-specific manner.
Answer: As others have mentioned, the desired functionality is not available with std::pow. Instead you could use std::cbrt or simply do like so:
#include<cstdio>
#include<iostream>
#include<cstdlib>
#include<cmath>

using namespace::std;

float f(float x)
{
    float result = -5 * x * x - 2 * x + 1;
    float intermediate = powf(std::abs(result),(float)1/(float)3);
    if (std::signbit(result))
        return -intermediate; // Negate if 'result' is negative
    return intermediate;
}
int main()
{
    cout<<f(-1)<<endl;
    getchar();
    return 0;
}

You can also just use one of the overloads of std::pow instead of powf
#include<iostream> // std::cout, std::endl
#include<cstdio>   // getchar
#include<cmath>    // std::pow, std::abs, std::signbit

float f(float x)
{
    float result = -5.0f * x * x - 2.0f * x + 1.0f;
    float intermediate = std::pow(std::abs(result),1.0f/3.0f);
    if (std::signbit(result))
        return -intermediate; // Negate if 'result' is negative
    return intermediate;
}

int main()
{
    std::cout << f(-1) << std::endl;
    getchar();
}

Online here

Function returns -nan


How to prove $\sum\limits_{m = 0}^{M - 1} {\frac{{{{( - 1)}^m}{c_{(m)}}}}{{m!}}} > 0$?

Question: How to prove $\sum\limits_{m = 0}^{M - 1} {\frac{{{{( - 1)}^m}{c_{(m)}}}}{{m!}}}  > 0$? Here, ${c_{(m)}} = c\left( {c - 1} \right) \cdots \left( {c - m + 1} \right)$ and $0<c<1$.
Comment: Out of curiosity: where did this come from?
Comment: ${c\choose m}$ is a standard notation for $\frac{c(c-1)\cdots (c-m+1)}{m!}$, where $m$ is an integer and $c$ can be any complex number.
Comment: @pigeon, Thanks a lot, I got it now.
Answer: Using Pascal's identity and induction on $M$, one can show that
$$
\sum_{m=0}^{M}(-1)^m\binom{c}{m}=(-1)^M\binom{c-1}{M}.
$$
Since
$$
(-1)^M\binom{c-1}{M}=\frac{(1-c)(2-c)\cdots(M-c)}{M!}
$$
and $c<1$, each factor is positive and thus so is the product.


OData filter nested query

Question: Let's assume we have an employee json resultset and assigned reviewer (as nested json resultset) available. I would like to find out case where a reviewer is assigned/and reviewer not assigned to the employee.
By using the query below I was able to get assigned reviewer.
<code>$filter=Reviewer/any(reviewer: reviewer/ReviewerId gt 0)
</code>
This returns all employees where reviewer is available. But how do I return result where reviewer is unavailable (or empty)? Thanks.
Answer: If you're looking to get all the entities that weren't returned by your original filter query, you could just put a "not" in front of what you have already:
<code>$filter=not Reviewer/any(reviewer: reviewer/ReviewerId gt 0)
</code>
Comment: I knew "not" was there, just didn't figure out where to put it!. Great, and many thanks.
Comment: i tried like thishttp://192.168.1.105:33396/FalconCPDataService.svc/DEPhysicians?$format=json&$expand=DEPatientVisits&$filter=DEPatientVisits/any(value:value/StimulatorGroupID+eq+guid%2756F18F45-CD99-4D41-8128-F9BAD7A8892F%27) but it showing empty json array
Comment: the DEPatientVisits table response is       {"odata.metadata":"localhost:33396/FalconCPDataService.svc/$metadata#DEPatientVisits","value":[{"VisitID":"f321edab-14c6-4ff2-9485-00abd176ebc4","PatientID":"c588df3b-9ea4-439b-9ab6-968a793dad2b","StimulatorGroupID":"b08d89e2-7dba-48ce-9430-282501397550","PhysicianID":null,"UserName":null,"PainMapID":null,"VisitDate":"2014-02-19T10:18:42","VisitReason":"usLro4OooDlMNJuWZHqeSXEKFwphz3Y9dvUr37RxHFz0h86aCImdsxUjuMWX64RG"}
Comment: can please explain where is problem @Jen S
Comment: the response like for above url             {"odata.metadata":"192.168.1.105:33396/FalconCPDataService.svc/$metadata#DEPhysicians","value":[]}
Comment: @mekala, could you please make a separate StackOverflow question? It's really tough to share code in comments, and making it its own question will give it much wider visibility.
Comment: these are the my questions   http://stackoverflow.com/questions/23290813/odata-filter-query      http://stackoverflow.com/questions/23362275/odata-url-conversion-with-descending-orderby/23377463?noredirect=1#23377463
Comment: @Jen S can you try to answer my questions.
Answer: $filter=Reviewer/all(reviewer: reviewer/ReviewerId lt 0 or reviewer/ReviewerId eq 0)
:)

OData filter nested query


Estimating sigma in Bayesian inference

Question:
I'm currently testing the Bayesian inference approach for a model given some data. However, I am running into the problem of estimating $\sigma$ (I am assuming a normal distribution of the data at each time step). I currently treat $\sigma$ in the same way as the other model parameters, i.e. I also estimate it using the MCMC algorithm. I set the prior for $\sigma$ to the uniform distribution. When I now run the MCMC algorithm, I notice that the derived samples of $\sigma$ are always very close to the upper bound, even when I set it urealistically high values.
To test whether my model is working, I have also used a fitting approach, which gives really good results and a $\sigma=0.5$, but my posterior distribution hovers around 10 when I set the uniform distribution to the interval $[0,10]$ and doesn't even come close to $0.5$.
Why does this happen and how can I fix it?
My only idea at the moment is to simply infer $\sigma$ deterministically given the current set of parameters, but this seems out of flavour in a Bayesian inference approach. Maybe a better prior distribution?
As a remider to other i just want to give a small update to what was the cause of my problem.
When defining the log_likelihood function I forgot that when multiplying the normal distribution that in addition to getting the square sum of the distance to the mean the exponent you also need to change the normalisation part of the function where the $\sigma$ gets an additional exponent which is the multiplication. :/.
Comment: You should make your question precise by providing entirely the posterior distribution rather than a vague description of the potential issue.
Comment: Perhaps you could try a different prior for $\sigma$ which covers $[0,\infty)$  (I believe the conjugate prior for $\sigma^2$ is an inverse gamma distribution)
Answer: A completely flat inverse-Gamma, i.e. letting the shape and scale tend to zero, will often lead to the same problems in practice.
Gelman's 2006 paper on prior distributions for variance parameters is a good place to start (link). It illustrates some of the issues with uninformative priors, and suggests some better solutions.

Estimating sigma in Bayesian inference


What is the order of the subgroup of G (rubiks cube group) generated by ?

Question: I got:
=1,FF,RR,FFRR,RRFF
But in my text book the answer is 12? Does any one else know the other elements?
I assumed since FFFFRRRR=1 there were no more?
Comment: What about FFRRFFRR? This is not FFFFRRRR.
Comment: Ahhhh yes... seems obvious now. Cheers
Answer: Let $f=FF$ and $g=RR$. Note that $f$ and $g$ have order $2$, and $fg$ and $gf$ have order $6$, i.e., we have $(fg)^6=e$ and no smaller power of it. This still is not enough to show that the group generated by $f$ and $g$ has order $12$. We also have
$$
g(fg)^2=(fg)^3f.
$$
So the $12$ elements are
$$
e,f,fg,(fg)f,(fg)^2,(fg)^2f,g,gf,(gf)g,(gf)^2,(gf)^2g,(gf)^3=(fg)^3.
$$
Comment: I needed to write out the elements rather than a proof the order is 12. Just struggling to see what the other elements would be.
Answer: using $f=FF$ and $g=RR$ (borrowing from @dietrich) isn't the answer just:
$$
e,f,fg,fgf,(fg)^2,(fg)^2f,(fg)^3,(fg)^3f,(fg)^4,(fg)^4f,(fg)^5,(fg)^5f
$$
and then $(fg)^6=e$?
Comment: But what about gf? Would this not be an element?
Comment: same as $(fg)^5$


Let G be a group, $N<K<G$ and $N\trianglelefteq G$. Prove that $K/N \trianglelefteq G/N$

Question: Let G be a group, $N<K<G$ and $N\trianglelefteq G$. Prove that $K/N \trianglelefteq G/N$
What I have tried is:
Note that $1\in G$. So $1\in K$ and $N1=N\in K/N$ which shows that $K/N$ is non-empty.
Then, let $a,b\in K$. This implies that $Na,Nb\in K/N$. So $Na(Nb)^{-1}=NaNb^{-1}\in K/N$ since $ab^{-1}\in K$. So this shows that $K/N\leq G/N$.
Lastly, let $Ng\in G/N$. Then for $Nk\in K/N$, $Ng^{-1}NkNg=N(g^{-1}kg) \in K/N$.
But the problem is I can't ensure that $K \trianglelefteq G$ and $g^{-1}kg\in K$
Comment: What you are trying to prove, ain't true. E.g., let $G$ be $S_3$, let $K$ be the non-normal subgroup generated by $(12)$, let $N$ be trivial. Then $N$ is normal in $G$, $K/N$ is basically $K$, $G/N$ is basically $G$, and $K$ isn't normal in $G$. So I suspect somewhere along the way a mistake has crept into the statement of the question.
Comment: see Rotmann . Group Theory and the correspondence theorem.
Comment: @GerryMyerson or the question should be $K \trianglelefteq G$?
Answer: Your statement is not true in general. What is true is:
Let $G$ be a group, $N \leq K \leq G$ and $N\trianglelefteq G$. Then $K/N \trianglelefteq G/N$ if and only if $K \unlhd G$.
A counterexample to your statement would be $N \cong V_4=\{(1),(12)(34),(13)(24),(14)(23)\} \leq K \cong D_4=\langle(13),(1234)\rangle \leq G=S_4$.


Netezza Loading table from SQL Server

Question: I have a very large table stored in SQL Server and I now want to transfer this table to the Netezza system. Do I need to use SSIS in order to accomplish this task?
Before this, I've only had to use Aginity to load tables that were stored on the network and not in a server to Netezza, so loading from another server is new to me. Can someone guide me in the right direction please?
Answer: I would unload to a file in UNIcode format and load to Netezza with an external table. Just remember to change all string datatypes to nvarchar unless you are 100% English in your data (not likely these days)
I know it sounds 1980 but it's (still) the most performant and reliable method

Netezza Loading table from SQL Server


Typo3 Introduction Package version 9.5

Question: Im trying to install the installation package from Typo3 with Composer but not the latest version. I need 9.5.
Do you know how can i do it with composer ?
installing the extension installs only the latest version. In the Webpage there´s a zip file but i dont know if i can use it with composer..
Thank you!
Comment: What **exactly** have you tried? There should be tons of tutorials out in the wild that tell you how to install a specific package version through composer
Answer: Just add the version you want to install as parameter to composer:
composer create-project typo3/cms-base-distribution my-new-project 9.5

Answer: You can use following:
e.g. in your composer.json
"require": {
    "vendor/package": "1.3.2", // exactly 1.3.2

in your case:
 {
    "require": {
        "typo3/cms": "9.5"
    }
}

For more info on versioning, have a look at Composer - Version and Constraints
EDIT:
Error: When running a composer-based TYPO3 instance, it is not possible anymore to require the whole TYPO3 Core via composer require typo3/cms. This package is solely used for Core-development purposes from now on.
Instead, all system extensions maintained by the TYPO3 Core Team must be required individually.
Some examples:
composer require typo3/cms-core:^9
composer require typo3/cms-fluid-styled-content:^9
composer require typo3/cms-extbase:^9
composer require typo3/cms-workspaces:^9
composer require typo3/cms-sys-note:^9

For convenience, TYPO3 projects can simply require composer require typo3/minimal to get the main system extensions that are needed for a running TYPO3 instance, and add custom system extensions as mentioned above.
Impact:
Installing or updating the composer package typo3/cms will show an error for TYPO3 v9.
i.e. use:
{
    "require": {
        "typo3/minimal": "9.5"
    }
}

Comment: Thank u for your answer. Do i have to composer update? and its the composer.json from the introduction package or the one from my project?
Comment: Not sure what _the introduction package_ is, but normally your project would have a `composer.json` file that specifies all the required packages for your project. Use `composer install` to install the dependencies for your project.
Answer: You can try following :
composer require typo3/cms-introduction:4.0.1

Introduction package version 4.0.1 is compatible with TYPO3 9.5, you can check : https://extensions.typo3.org/extension/introduction/

Typo3 Introduction Package version 9.5


RegExp extraction

Question: Here's the input string:
loadMedia('mediacontainer1', 'http://www.something.com/videos/JohnsAwesomeVideo.flv', 'http://www.something.com/videos/JohnsAwesomeCaption.xml', '/videos/video-splash-image.gif)

With this RegExp: \'.+.xml\'
... we get this:
'mediacontainer1', 'http://www.something.com/videos/JohnsAwesomeVideo.flv', 'http://www.something.com/videos/JohnsAwesomeCaption.xml'

... but I want to extract only this:
http://www.something.com/videos/JohnsAwesomeCaption.xml

Any suggestions? I'm sure this problem has been asked before, but it's difficult to search for. I'll be happy to Accept a solution.
Thanks!
Comment: what flavour of regex is this?
Answer: in .net this regex works for me:
\'[\w:/.]+\.xml\'

breaking it down:

a ' character
followed by a word character or ':' or '/' or '.' any number of times (which matches the url bit)
followed by '.xml' (which differentiates the sought string from the other urls which it will match without this)
followed by another ' character

I tested it here
Edit
  I missed that you don't want the quotes in the result, in which case as has been pointed out you need to use look behind and look ahead to include the quotes in the search, but not in the answer.  again in .net:
(?<=')[\w:/.]+\.xml(?=')

but I think the best solution is a combination of those offered already:
(?<=')[^']+\.xml(?=')

which seems the simplest to read, at least to me.
Comment: You've mixed up the escaping of the dots - remove the backslash inside the character class, add one before the final dot.
Comment: @Tim both variations work on the given input, but you are right about the backslash before the final dot as we want it to be explicitly a dot
Answer: Knowing the language would be helpful. Basically, you are having a problem because the + quantifier is greedy, meaning it will match the largest part of the string that it can. you need to use a non-greedy quantifier, which will match as little as possible.
We will need to know the language you're in to know what the syntax for the non-greedy quantifier should be.
Here is a perl recipe. Just as a sidenote, instead of .+, you probably want to match [^.]+.xml.
\'.+?.xml\'

should work if your language supports perl-like regexes.
Comment: glad it helped! understanding greedy vs non-greedy (sometimes called "stingy") will save you many debugging headaches in the future!
Comment: I selected the other answer, but your information still proved useful and I learned greedy vs. non-greedy. It'll help me write regexes in the future. Cheers.

The language is Java/JSP by the way. We're using the "transformText" JSP tag library (found in www.infoglue.org, a Java-based CMS like Drupal etc.). I'm not exactly sure if if that's Perl style.
Answer: This should work (tested in javascript, but pretty sure it would work in most cases)
'[^']+?\.xml'

it looks for these rules

starts with '
is followed by anything but '
ends in .xml'

you can demo it at http://RegExr.com?2tp6q
Comment: This worked too. I accepted the other answer because I wanted the output to not include the quotes. Upvoted anyway. Cheers.
Answer: If you want to get everything within quotes that starts with http:
(?<=')http:[^']+(?=')

If you only want those ending with .xml
(?<=')http:[^']+\.xml(?=')

It doesn't select the quotation marks (as you asked)
It's fast!

Fair warning: it only works if the regex engine you're using can handle lookbehind
Comment: It's part of the look-behind syntax: (?<=). It's covered pretty well here: http://www.regular-expressions.info/lookaround.html
Comment: I tried to study your solution so that I can understand it, but I'm uncertain about the = sign. What does it do? A few popular RegEx sites I've checked do not mention the = sign at all. Thanks.

RegExp extraction


While clearing cache i am getting 'Page isnt working'

Question: Whenever i use classname extends FormBase the clear cache crashes and whenever i remove it it works again.

<?php

namespace Drupal\API_crud\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

class ApiCrud extends FormBase {
    public function getFormId() {
        return 'api_form';
    }

    public function buidForm(array $form, FormStateInterface $form_state) {
        $form['title'] = [
            '#type' => 'textfield',
            '#title' => $this->t('API: '),
            '#required' => TRUE,
        ];
        $form['actions'] = [
            '#type' => 'actions',
        ];
        $form['actions']['submit'] = [
            '#type' => 'submit',
            '#value' => $this->t('Submit'),
        ];
        return $form;
    }

}

apiAuth.form:
  path: '/apiAuth'
  defaults:
    _form: '\Drupal\API_crud\Form\ApiCrud'
    # _controller: '\Drupal\API_crud\Controller\apiCrudController::Welcome'
    _title: 'API_Authentication'
  requirements:
    _permission: 'access content'

Comment: It's worth investing time (and/or money) in learning to use a good IDE. VS code is a nice free one, PHPStorm is a nice paid one, for example. If you were using such an IDE it would have altered you to the fact your form class is missing methods from `FormInterface`, and you would've fixed it quickly.
Comment: See https://drupal.stackexchange.com/questions/127182/how-do-i-enable-developer-debug-mode/223964#223964
Answer: As Clive is hinting in his comment some methods are missing in your class.
You need to add at least the methods "buildForm" and "submitForm" to you class. (you also have a typo in buidForm)
This should work:
<?php

namespace Drupal\API_crud\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

class ApiCrud extends FormBase {
  public function getFormId() {
    return 'api_form';
  }

  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['title'] = [
      '#type' => 'textfield',
      '#title' => $this->t('API: '),
      '#required' => TRUE,
    ];
    $form['actions'] = [
      '#type' => 'actions',
    ];
    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Submit'),
    ];
    return $form;
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {
    // TODO: Implement submitForm() method.
  }

}


What does standard error of the mean ACTUALLY show?

Question: I'm brushing up on my stats, so please bare with me (and correct me) for any mistakes. I really hope someone can help me out!
Let's consider two separate experiments that are designed to measure the length of a string.
Experiment One - (Or: How I view a statistician would determine the length of a string)
Imagine I have a population of 500 strings. I randomly sample 20 strings from this population, measure their lengths, and calculate the sample mean. I then repeat this process 100 times. By the end of the experiment, I will have 100 means, one for each time I sampled the population. This is the sampling distribution of the mean.
As I understand it, the standard deviation of this sampling distribution is the standard error of the mean. We want the standard error of the mean to be small as it means we are better zeroed in on the true population mean.
However, the standard error of the mean is also expressed as the ratio of the standard deviation of the population to the square root of the sample size (here, 20). Furthermore, it can be estimated as the ratio of the standard deviation of a single sampling of 20 strings to the square root of that sample size (again, 20).
Question one:
So my question is, how does the second definition using only the standard deviations of the population or sample along with the sample size connect to the original definition in which standard error of the mean is defined as the standard deviation of our sampling distribution? I can't wrap my head around the connection.
For instance, as we conduct more and more samplings, the standard deviation of the resulting sampling distribution will continue to decrease more and more, right? So how is this fact taken into account in the equation that only uses standard deviation of a single sample divided by that sample size? Surely the standard deviation of the sampling distribution (which is the standard error!) consisting of 20000000 means will be smaller than the value we get if we simply calculate it by taking the ratio of a single sample standard deviation to the sqrt of the sample size, right?
Question two:
Using the second definition, we are calculating standard error by looking at a single sample consisting of 20 measurements. But this isn't even a sampling distribution of the mean, but rather a point estimate of the mean. So how is it possible for it to even have a standard error when it's just ONE estimate?
Experiment Two - (Or: How I view a chemist/physicist would measure the length of a string)
Suppose I have a single string. I then measure that string 20 times. That's it.
Question three: In this experiment, there isn't really a 'population' from which I'm sampling. I'm just measuring the same string over and over. So how am I supposed to calculate a standard error from this? If each sampling has sample is size one, then its impossible to calculate any means nor any sampling distribution of those means. Alternatively, if we assume the 20 measurements belonged to a SINGLE sampling, then I'm still not able to construct a sampling distribution of the means, since I only got ONE mean. Sure, I could calculate the standard error of the 20 measurements, but that's not standard error, it's just the standard deviation!!
Or is it? What is it??WHAT IS ANYTHING????
Comment: "as we conduct more and more samplings, the standard deviation of the resulting sampling distribution will continue to decrease more and more, right?" No. The sampling distribution of the mean depends on the distribution of the original data and on how many observations each separate mean is calculated from (i.e., $n$). It does *not* depend on *how often* you sample $n$ points and calculate a mean. This is just drawing more and more samples from the sampling distribution of the mean. The SD of these samples will not decrease just because you draw more and more often.
Comment: Simulations in R are a great tool to understand stuff like this. For instance, you could draw 100, 1000, 10000, ... means, each based on $n$ observations from the original data, and you could observe that the SD of the means does not budge a lot.
Comment: Im still chewing on this, but thank you for your answer!
Comment: See https://stats.stackexchange.com/questions/16413.
Answer: I agree that the nomenclature and the formulas for the standard mean can be confusing. (Not complicated, actually, just confusing.) Our highly-voted threads in the "standard-error" tag may be enlightening.
I'll take your question step by step.

Imagine I have a population of 500 strings. I randomly sample 20
  strings from this population, measure their lengths, and calculate the
  sample mean. I then repeat this process 100 times. By the end of the
  experiment, I will have 100 means, one for each time I sampled the
  population. This is the sampling distribution of the mean.

Correct!

As I understand it, the standard deviation of this sampling
  distribution is the standard error of the mean. We want the standard
  error of the mean to be small as it means we are better zeroed in on
  the true population mean.

Also correct! This is actually the definition of the standard error of the mean (or actually of any estimated parameter!): any parameter estimate will have a distribution, and the standard deviation of this distribution is defined to be the standard error of the parameter.

However, the standard error of the mean is also expressed as the ratio
  of the standard deviation of the population to the square root of the
  sample size (here, 20). Furthermore, it can be estimated as the ratio
  of the standard deviation of a single sampling of 20 strings to the
  square root of that sample size (again, 20).

Almost. The first statement is not an alternative definition of the SE. It is a mathematical equality that holds under certain assumptions (which are in practice usually fulfilled) that the SE of the mean is equal to $\frac{\sigma}{\sqrt{n}}$. And the second statement is correct: you can estimate the SEM by using an estimate $\hat{\sigma}$ of $\sigma$.

So my question is, how does the second definition using only the
  standard deviations of the population or sample along with the sample
  size connect to the original definition in which standard error of the
  mean is defined as the standard deviation of our sampling
  distribution? I can't wrap my head around the connection.

As above: that the two are equal is not a question of competing definitions. It's a question of having one definition (as above) and a mathematical theorem than the SEM so defined is equal to $\frac{\sigma}{\sqrt{n}}$.

For instance, as we conduct more and more samplings, the standard
  deviation of the resulting sampling distribution will continue to
  decrease more and more, right? So how is this fact taken into account
  in the equation that only uses standard deviation of a single sample
  divided by that sample size? Surely the standard deviation of the
  sampling distribution (which is the standard error!) consisting of
  20000000 means will be smaller than the value we get if we simply
  calculate it by taking the ratio of a single sample standard deviation
  to the sqrt of the sample size, right?

No. The sampling distribution of the mean depends on the distribution of the original data and on how many observations each separate mean is calculated from (i.e., $n$). It does not depend on how often you sample n points and calculate a mean. This is just drawing more and more samples from the sampling distribution of the mean. The SD of these samples will not decrease just because you draw more and more often.
Simulations in R are a great tool to understand stuff like this. For instance, you could draw 100, 1000, 10000, ... means, each based on $n$ observations from the original data, and you could observe that the SD of the means does not budge a lot. For instance, here are the standard deviations of 10, 50, 100, 500, 1000, 5000, 10000 means, each one based on $n=20$ observations of the original population. It's a flat line, up to variability (meta: we could also investigate the standard error of the estimate of the standard error of the means, but I don't think we want to go there right now...):

R code:
<code>set.seed(1) # for reproducibility
string_lengths <- runif(500)
nn <- 20
n_means <- c(10,50,100,500,1000,5000,10000)
sds <- sapply(n_means,function(kk)sd(replicate(kk,mean(sample(string_lengths,nn,replace=TRUE)))))
plot(n_means,sds,type="o")
</code>

Using the second definition, we are calculating standard error by
  looking at a single sample consisting of 20 measurements. But this
  isn't even a sampling distribution of the mean, but rather a point
  estimate of the mean. So how is it possible for it to even have a
  standard error when it's just ONE estimate?

Per above: the standard error is not a property of an observation, but of a distribution. And we can happily estimate it from a single observation of the distribution of the means... because this single observation is in turn based on $n$ observations from the underlying distribution of the original data!

Suppose I have a single string. I then measure that string 20 times.
  That's it.
Question three: In this experiment, there isn't really a 'population' from which I'm sampling. I'm just measuring the same
  string over and over. So how am I supposed to calculate a standard
  error from this? If each sampling has sample is size one, then its
  impossible to calculate any means nor any sampling distribution of
  those means. Alternatively, if we assume the 20 measurements belonged
  to a SINGLE sampling, then I'm still not able to construct a sampling
  distribution of the means, since I only got ONE mean. Sure, I could
  calculate the standard error of the 20 measurements, but that's not
  standard error, it's just the standard deviation!!

Well, if you just wrote down a single observation 20 times, then you can't estimate the population standard deviation $\sigma$, because you have only one observation. (Technically, you have 20 observations, but they are not independent, which is one of the technical conditions I mentioned above. If your conditions are not met, of course all bets are off.) So in this situation, there is really nothing you can't do, and theory won't help you.
(Incidentally, there is a population you are sampling from. It may be the 500 strings we started out with, or it could be just a single one, but we always have a population. We are just not sampling from it independently.)
Comment: Thank you for this answer! It's bed time here, so I'll think it over in my sleep and come back to it tomorrow morning and see if it clicks!
Comment: Wouldn't the sampling distribution require every posible size 20 sample from the size 500 population -without repetition- to be drawn? This would yield 2.667199 x 10^23 samples. So **no**, 100 samples are **not** enough to construct the sampling distribution of the mean.
Comment: @Zweifler: yes, of course you are correct. I should have written that this gives an *approximation* to the sampling distribution of the mean. Then again, to get the "real" distribution, we would need the actual underlying distribution of the data, not just observations drawn from it.


executing a command after ssh

Question: The following command works as expected:
ssh email@example.com "ssh firstname.lastname@example.com "mysqlshow""

But the following does not:
ssh firstname.lastname@example.com "ssh email@example.com "mysql test -Bse"show variables"""

The following part works at the command prompt but fails when I do ssh before executing it as shown above.
mysql test -Bse"show variables"

Answer: You can't nest double-quotes like that.  You either need to escape them or change your approach.
Try this:
ssh email@example.com "ssh email@example.com \"mysql test -Bse'show variables'\""

Comment: ssh email@example.com "ssh firstname.lastname@example.com \"mysql test -Bse'show variables'\""
Comment: Ah, yeah, of course you need the outer most quotes too.  I'll fixup my answer.
Answer: In the command ssh email@example.com "ssh email@example.com "mysql test -Bse"show variables""" you have multiple double quotes. Try escaping them
ssh firstname.lastname@example.com "ssh firstname.lastname@example.com \"mysql test -Bse\\\"show variables\\\"\""

Answer: Alternatively, you can put
mysql test -Bse"show variables"

into a script on your server and then just call that script via SSH as you showed in your first example. If you do this, make sure the executable bit is set properly to allow user soak to run it.

executing a command after ssh


Missing daily data for one month

Question: I have a two years of daily data. The data for one month is missing as it was not recorded due to some problems at the company. How should I treat the data with no values for a month.
Comment: I think it really depends on your goals.  Are you trying to fit a certain model, or generate plots, or make predictions about the future?
Answer: The missing observation would be best handled by identifying the normal patterns in the data.  Once you have modeled the time series, this missing observation will be flagged as an outlier.  The fitted value in the model will tell you what the value should have been.
This is how we do it.....
I would create 6 day of the week fixed effects variables and 51 week of the year fixed effect variables. I would create regression variables for each public holiday. I would use the cross-correlation function to identify lead/lag relationships around those holidays. I would search for outliers, level shifts, local time trends and seasonal pulses. I would also consider adding in any other macro causals (ie population, unemployment) or know historical events.
I would search for monday after holiday landing on friday impacts (ie using a regressor). I would search for friday before after holiday landing on monday impacts (ie using a regressor).
I would search for "fixed days of the month" impacts due to paycheck distribution.
If you are trying to forecast energy consumption then also add in weather variables.
All of this is done to get a good read on the "model" and hence a quality forecast.
I'd be happy to discuss with you "off line" how to do this....automatically.
Answer: What I would do is to use day-of-the=wekk averages for the 4 months surrounding the "missing month" to obtain initial estimates of the daily vales for the "missing month". I would then entertain a model that used day-of=the-week and week-of-the-year indicators. I would then detect anomalies which would then allow me to replace the "current values" for the "missing month" and re-iterate until some convergence was reached.

Missing daily data for one month


How to initialize a Future and then replace it in Flutter/Dart?

Question: How do I do the initialize the Future correctly for a FutureBuilder in Flutter?
As you can see, there is an exception being thrown because the late Future is not yet initialized. (please ignore that parameter v is not used in the method, removed method details for simplicity, but v is important).
late Future<int> myIntvalue;

Future<int> getStackInit(int v) async {
  await Future.delay(Duration(seconds: 5));
  return 5;
}

@override
void initState()
{
  SharedPreferences.getInstance().then((sp) {
       int value = sp.getInt("StartValue") ?? 0;
       myIntvalue = getStackInit(value);
  });
  super.initState();
}

@override
Widget build(BuildContext context) {
  return Scaffold(
      body: FutureBuilder(
            future: myIntvalue,     <-- Exception, not initialized
            builder: (context, AsyncSnapshot snapshot) {
              ....

The problem ist, that myIntvalue is not yet initialized when the FutureBuilder is reached. What is the best way to initialized the future before it is "really" initialized? Or is it possible to define a future during initialization and "replace" the result later on?
Is there any more elegant way?
Thanks!
Answer: In general, if you need to be able to check if something's been initialized, you need to make it nullable.
Or you could set your Future to an initial sentinel value (e.g. Future.value(0)), replace it later, and call setState to rebuild your widget tree, just as you would if you had to update any other member variable.
However, in your case you should just initialize myIntvalue to the desired Future as soon as possible.  For example:
@override
void initState()
{
  Future<int> initializeIntValue() async {
    var sp = SharedPreferences.getInstance();
    int value = sp.getInt("StartValue") ?? 0;
    return await getStackInit(value);
  }

  myIntvalue = initializeIntValue();
  super.initState();
}


How does a three team trade work?

Question: Now that we are approaching the MLB trade deadline, I would like to ask some questions about unusual trades. The first is about three team trades.
Suppose a manager of team A goes to the manager of team B and says, I want Y from you and I'm willing to offer X. If they agree that X and Y are equivalent, and that a trade would benefit both sides, the deal is done.
But suppose the manager of Team B says, "I think that X is equivalent to Y, but that's not really what I want. But I think Team C will accept X in trade for Z, and Z is what I really want for Y." Then there is a possible three way trade if team C is really is willing to trade Z for X.
Is this how a three way trade gets done? Or are there other means/mechanisms?
Comment: Related question in regards to basketball (NBA): http://sports.stackexchange.com/questions/1181/why-would-a-team-choose-to-become-involved-in-a-multi-team-trade
Comment: @edmastermind29: I'd say that the dynamics of a four team trade are "different" (and far more complicated) than a three team trade. Think the difference between three SQUARED and four squared.
Comment: 3 SQUARED and 4 squared are still fundamentally done the same (multiply the number by itself). I think it's no different here: it just adds another team into the mix, which increases the complexity of understanding the trade.
Answer: Three team trades are complicated, but they are done. Here's essentially how this goes down. We'll identify three teams here, team A, team B and team C. Team A and B are the primaries in the trade, team C will be our intermediary.

Team A is in playoff contention, they desperately need a closer. But don't have the right players to pull off the trade directly with team B, but has players who are desirable to team C.
Team B is out of contention, has a closer on an expiring contract, they don't want anyone in team A's system enough to trade their closer, but have had their eye on a couple of guys in Team C's system.
Team C is usually out of contention as well, but can sometimes be in contention (it doesn't usually benefit a contending team to do this, but an out of contention team can do well in a trade like this).

So team A will send their players who weren't the right mix for team B to team C, and team C will send their players to team B, who will send the closer to team A.
A recently revealed potential scenario actually has some interesting details and insights into this. The author there gets into the details, but it amounts to this:

Tampa wants young, good positional talent for David Price
Seattle doesn't have any, but has some decent young pitching
Chicago has young near ML ready positional talent and needs young pitching

A deal like this that has Seattle sending young pitching to Chicago, Chicago sending young positional talent to Tampa and Tampa sending Price to Seattle could workout. However, it requires that all sides, especially the intermediary thinking they are getting a good deal. This is largely why these deals don't happen. If a team doesn't have the players to get a deal done directly, it's very difficult to convince a third party that to give up their prospects (or ML talent in some cases) for players who weren't good enough for the 2 parties to swap directly.
Comment: Ok, it seems like the "trick" is to find an appropriate intermediary "Team C" to complete the trade.
Comment: @TomAu That's pretty much it. For something like this to work, all the teams have to feel good about it, so Team C has to get something they like out of it. In the Cubs example I linked, there is no one (or even 2-3 pitchers) in Seattle's system that would cause them to drop in as an intermediary in that deal, giving up any of their top hitting prospects (Baez/Bryant/Alcantara/Almora/etc)

How does a three team trade work?


if statement meets multiple conditions but stops at first condition that matches

Question: I am using an if statement and trying to make sure that it stops when it meets most of the conditions that it can. For example, if I have the following code:
  const determineLevel = () => {
    const wentToKindergarten = true;
    const wentToElementary = true;
    const wentToHighSchool = true;
    const wentToCollege = false;

    if (wentToKindergarten) {
      return 1;
    }

    if (wentToKindergarten && wentToElementary) {
      return 2;
    }

        if (wentToKindergarten && wentToElementary && wentToHighSchool) {
      return 3;
    }

     if (wentToKindergarten && wentToElementary && wentToHighSchool && wentToCollege) {
      return 4;
    }

    return;
  };

In this example, if a student went to kindergarten, elementary, and high school, but skipped out of college, how do I implement this? Right now, it just stops at the first condition it meets.
Answer:   const determineLevel = () => {
    const wentToKindergarten = true;
    const wentToElementary = true;
    const wentToHighSchool = true;
    const wentToCollege = false;
    var returnme=0;

    if (wentToKindergarten) {
      returnme= 1;
    }

    if (wentToKindergarten && wentToElementary) {
      returnme= 2;
    }

        if (wentToKindergarten && wentToElementary && wentToHighSchool) {
      returnme= 3;
    }

     if (wentToKindergarten && wentToElementary && wentToHighSchool && wentToCollege) {
      returnme= 4;
    }

    return returnme;
  };

Edit: Or you might prefer to place the conditionals in reverse order so that hardest to satisfy is checked first. Whatever you prefer.
Answer: The return statement finishes the function, a function will not execute past the first return statement that it finds. So a better way to do your code would be something like:
const determineLevel = () => {
    var returnNumber;
    const wentToKindergarten = true;
    const wentToElementary = true;
    const wentToHighSchool = true;
    const wentToCollege = false;

    if (wentToKindergarten) {
      returnNumber = 1;
    }

    if (wentToKindergarten && wentToElementary) {
      returnNumber = 2;
    }

        if (wentToKindergarten && wentToElementary && wentToHighSchool) {
      return = 3;
    }

     if (wentToKindergarten && wentToElementary && wentToHighSchool && wentToCollege) {
      returnNumber = 4;
    }

    if(returnNumber > 0)
    {
        return returnNumber;
    }
    return;
  };

This way you check through all scenarios then return whatever number you need at the end.
Answer: Your code was not working for your logic because, you are returning a value inside each if condition check, which will cause the function to stop execution after the first condition becomes true.
You can change the if condition to else-if conditions.
Or you can have a variable to keep track off,
const determineLevel = () => {
const wentToKindergarten = true;
const wentToElementary = true;
const wentToHighSchool = true;
const wentToCollege = false;
let condition;
if (wentToKindergarten) {
  condition= 1;
}

if (wentToKindergarten && wentToElementary) {
  condition= 2;
}

if (wentToKindergarten && wentToElementary && wentToHighSchool) {
  condition= 3;
}

 if (wentToKindergarten && wentToElementary && wentToHighSchool && wentToCollege) {
  condition= 4;
}

 return condition;
};

Answer: 1 - in the reverse order.
if ( wentToKindergarten
   && wentToElementary
   && wentToHighSchool
   && wentToCollege     )   return 4;

if (wentToKindergarten
   && wentToElementary
   && wentToHighSchool  )   return 3;

if ( wentToKindergarten
   && wentToElementary  )   return 2;

if (wentToKindergarten  )   return 1;

2 - with some else.
if (wentToKindergarten)
  if (wentToKindergarten)
    if (wentToHighSchool)
      if (wentToCollege)  return 4
      else                return 3
    else                  return 2
  else                    return 1
else  return

3 - using a binary representation :
let rep = 0b0000

if (wentToKindergarten) rep |= 0b0001
if (wentToElementary)   rep |= 0b0010
if (wentToHighSchool)   rep |= 0b0100
if (wentToCollege)      rep |= 0b1000

if ( rep |= 0b0001 ) return 1
if ( rep |= 0b0011 ) return 2
if ( rep |= 0b0111 ) return 3
if ( rep |= 0b1111 ) return 4

return

Comment: Nested if statements will greatly hinders the readability.
Answer: You are looking for the first false and a false must be followed by false.  So change the value of each of wentToKindergarten etc to a 1 if true and 0 if false.  Then the answer is:
wentToKindergarten+wentToElementary+wentToHighSchool+wentToCollege


Não estou sabendo onde colocar os array

Question: Olá, boa tarde. Estou com uma lista de exercício para praticar mais sobre os arrays, funções e retornos e tem uma questão que não estou conseguindo como vou colocar os arrays. A questão é o seguinte:

Desenvolva uma função chamada stringTripletGroup que recebe um parâmetro:

string, sendo uma string representando uma frase.
E deve retornar um novo array com esta frase fatiada em 3 em 3 caracteres posicionados ao longo do array. Caso a quantidade de letras da última posição seja menor que 3, deverá ser completado com espaços vazios.

Exemplo:
stringTripletGroup("Os três mosqueteiros");

// Deve retornar:
// ["Os ", "trê", "s m", "osq", "uet", "eir", "os "] e fiz assim: stringTripletGroup[]

Eu fiz assim:
function stringTripletGroup(frase) {
    let r = 0;
      for ( let i = 0; i <= frase.length; i++) {
      if (frase[i] == frase) {
        r++;
      }
    }
      return r;
  }
  console.log(stringTripletGroup("Os três mosqueteiros"));

Está me retornado 0 ao invés de retornar como o exemplo
Comment: Parece que vc so jogou qualquer codigo como tentativa. Sua funcao nao faz sentido algum.
Answer: Abaixo iniciei um array (resultado) vazio e através de um loop for com incrementos de 3 em 3 fui pegando 3 posições ao longo da frase. Acredito que resolva seu problema:

function stringTripletGroup(frase) {
  const resultado = [];

  for (let i = 0; i < frase.length; i = i + 3) {
    resultado.push(frase.substr(i, 3).padEnd(3, ' '));
  }

  return resultado;
}

console.log(stringTripletGroup("Os três mosqueteiros"));

Não estou sabendo onde colocar os array


Show that $x\delta^{\prime}(x)=-\delta(x)$

Question: The reasoning given in my book is as follows:

Multiply $x\delta^{\prime}(x)$ by $\phi(x)$ and integrate; where $\phi(x)$ is an arbitrary test function that is zero for large $\mid x \mid$ and $\delta^{\prime}(x)$ is the derivative of $\delta(x)$:
  $$\begin{align}\underbrace{\int_{x=-\infty}^{\infty}x\delta^{\prime}(x)\phi(x)\,\mathrm{d}x}_{\color{red}{\Large 1}}\\ & =\underbrace{-\Big(x\phi(x)\Big)^{\prime}\Big \lvert_{x=0}^{\infty}}_{\color{blue}{\Large 2}}\\ &
=\underbrace{-\Big(x\phi^{\prime}(x)+\phi(x)\Big)\Big \lvert_{x=0}^{\infty}}_{\color{#180}{\Large 3}}
\\&=\underbrace{-\phi(0)}_{\color{#F80}{\Large 4}}
\\&=\underbrace{-\int_{x=-\infty}^{\infty}\delta(x)\phi(x)\mathrm{d}x}_{\color{purple}{\Large 5}}\end{align}$$

So in short
$$\int_{x=-\infty}^{\infty}x\delta^{\prime}(x)\phi(x)\,\mathrm{d}x=-\int_{x=-\infty}^{\infty}\delta(x)\phi(x)\mathrm{d}x$$
Differentiation of both sides with respect to $x$ and then dividing both sides by $\phi(x)$ and the result follows: $$x\delta^{\prime}(x)=-\delta(x)$$

I can't understand what steps were carried out to get from $\large\color{red}{1}$ to $\large\color{blue}{2}$. I tried by integrating by parts but this led to a dead end.
I think that the product rule was used to get from $\large\color{blue}{2}$ to $\large\color{#180}{3}$.
By my calculation, to get from $\large\color{#180}{3}$ to $\large\color{#F80}{4}$ there should not be a negative sign in front of $\phi(0)$. Since $$-\Big(x\phi^{\prime}(x)+\phi(x)\Big)\Big\lvert_{x=0}^{\infty}=-\Big((\infty\cdot 0+0)-\big(0\cdot \phi^{\prime}(0)+\phi(0)\big)\Big)=-\big(-\phi(0)\big)=\phi(0)$$
I have absolutely no idea how to get from $\large\color{#F80}{4}$ to $\large\color{purple}{5}$. But I guess this depends on whether the previous step is correct.

Could someone please give me some hints or tips or better yet show the intermediate steps that were omitted from the book?
Thank you.

EDIT:
Please ignore all of the above as it is wrong due to a book error. A special thanks goes to @mjqxxxx , @Augustin and @ForgotALot for pointing this out to me.
I apologize for the inconvenience.
The (correct) reasoning given is as follows:

Multiply $x\delta^{\prime}(x)$ by $\phi(x)$ and integrate; where $\phi(x)$ is an arbitrary test function that is zero for large $\mid x \mid$ and $\delta^{\prime}(x)$ is the derivative of $\delta(x)$:
  $$\begin{align}\underbrace{\int_{x=-\infty}^{\infty}x\delta^{\prime}(x)\phi(x)\,\mathrm{d}x}_{\color{red}{\Large 1}}\\ & =\underbrace{-\Big(x\phi(x)\Big)^{\prime}\Big \lvert_{x=0}}_{\color{blue}{\Large 2}}\\ &
=\underbrace{-\Big(x\phi^{\prime}(x)+\phi(x)\Big)\Big \lvert_{x=0}}_{\color{#180}{\Large 3}}
\\&=\underbrace{-\phi(0)}_{\color{#F80}{\Large 4}}
\\&=\underbrace{-\int_{x=-\infty}^{\infty}\delta(x)\phi(x)\mathrm{d}x}_{\color{purple}{\Large 5}}\end{align}$$

So in short
$$\int_{x=-\infty}^{\infty}x\delta^{\prime}(x)\phi(x)\,\mathrm{d}x=-\int_{x=-\infty}^{\infty}\delta(x)\phi(x)\mathrm{d}x$$
Differentiation of both sides with respect to $x$ and then dividing both sides by $\phi(x)$ and the result follows: $$x\delta^{\prime}(x)=-\delta(x)$$
Could someone please give me some hints or tips or better yet show the intermediate steps that were omitted from the book?
Comment: What's your definition of $\delta'(x)$?  The first step should just follow from that definition.  Usually one has $\int_{-\infty}^\infty \delta'(x) f(x) dx = -\int_{\infty}^{\infty} \delta(x) f'(x) dx$ by parts, which equals $-f'(0)$ by the definition of the delta function.  I think your first result should be $-\left(x\phi(x)\right)'\vert_{x=0}$... that is, the derivative evaluated at $x=0$.  In which case the minus sign is correct.  The final step is the definition of the delta function.
Comment: I agree with @mjqxxxx. I think there should not be $\infty$ but just evaluation at $0$. Another way to find the result:
$=<\delta',x\phi>=-<\delta,(x\phi)'>=-<\delta,x\phi '+\phi>=-(0\times\phi '(0)+\phi(0))=-\phi(0)=-<\delta,\phi>$. Hence $x\delta '=-\delta$.
Comment: @mjqxxxx $\delta^{\prime}(x)$ is the derivative of $\delta(x)$.
Comment: @mjqxxxx Please see my edit regarding the minus sign for $\phi(0)$
Comment: $x\delta(x)=0$. Differentiate both sides using product rule.
Comment: @A.S. Yes I understand that method completely, it's this method in this post I would like to understand, thanks all the same, I changed the title as it was not clear what I was asking before, sorry.
Comment: @Augustin So where did the upper limit go then?
Comment: I don't understand why it's there in the first place. If you just apply the definitions, it should not be.
Comment: @Augustin The integration began at $[-\infty,\infty]$, upper limits can't just disappear. Or can they?
Comment: I just have a limited knowledge of distribution theory, so I may be wrong, but as I see it, the integral is just a notation. It's not a real integration as $x\delta '$ is not a function, it's a distribution, that is a functional on the space of test functions. We can use this notation because it's consistent with what we obtain in the case where the distribution is actually a real function. Note that I didn't use it in my proof, because I find it confusing.
Answer: You don't say what your book is. Let me first give some background and then address your book's derivation.  For background I look at Rudin's Functional Analysis ch. 6 which discusses distributions, which I believe to be the usual framework in which mathematicians view "the Dirac delta function."  There's also Yosida's Functional Analysis, Hörmander volume 1, the old Schwartz book in French, etc.
Background.  In this framework, the "delta function" is actually a continuous linear function from $\mathscr{D}$ to $\mathbb{C}$, where  $\mathscr{D}$ is the $C^\infty$ functions on $\mathbb{R}$ with compact support, endowed with a suitable topology.  By definition (Rudin 6.9), $\delta(\phi) = \phi(0)$ for any $\phi\in\mathscr{D}$.  Also by definition, the first derivative $\delta'$ is defined by $\delta'(\phi)=-\delta(\phi')=-\phi'(0)$ (Rudin 6.12) for any $\phi\in\mathscr{D}$.  The value $\phi'(0)$ can alternately be written $d\phi(x)/dx|_{x=0}$.
The product of a function mapping $x$ to $x$ by a distribution is, yet again by definition (Rudin 6.15), a distribution satisfying $(x\delta)(\phi)=\delta(x\phi)$ for any $\phi\in\mathscr{D}$, where we use $x$ to denote the function which maps $x$ to $x$ (others would get fancier and say $Id$ for identity or something like that).
Now, putting these definitions together, $(x\delta')(\phi)=\delta'(x\phi)=-\delta(d(x\phi(x))/dx)$.  Now, $x\phi$ is a good ol' $C^\infty$ function, the product rule applies, and so $d(x\phi(x))/dx= \phi(x)+x\phi'(x)$.  Substituting in the prior formula and remembering that $\delta(\phi_1)=\phi_1(0)$ for all $\phi_1\in\mathscr{D}$, we get $(x\delta')(\phi)=-\phi(0)=-\delta(\phi)$.  Since $\phi\in\mathscr{D}$ was arbitrary, this means $x\delta'=-\delta$.
If $\Lambda$ is a distribution and $\phi\in\mathscr{D}$, one sometimes writes
$$\Lambda(\phi)=\int_{-\infty}^\infty \Lambda(x)\phi(x)\,dx$$
That is what your book seems to be doing.  However, it helps to keep the definitions and the distinction between distributions and functions clearly in mind, especially at the beginning when one is learning about them.
The answer to your question.  Turning now at last to your book's reasoning, the big oddity is the $|_{x=0}^\infty$ in step 2.  Remember that step 1 is just the intuitively helpful (or not) way of writing the action of a distribution on a test function as an integral.  Suppose it were a real integral of good ol' functions on $\mathbb{R}$:  then integration by parts would apply to it, and then one would apply something like $$\int_{-\infty}^\infty f(x)g'(x)\,dx=f(x)g(x)|^\infty_{-\infty}-\int_{-\infty}^\infty f'(x)g(x)\,dx.$$  Now, here $f(x)=x\phi(x)$ and $g(x)=\delta(x)$.  Because $\phi(x)$ is a test function $\in \mathscr{D}$, it equals to $0$ outside a compact set, and so the product $f(x)g(x)|_{-\infty}^\infty$ should equal $0$ with the identifications of $f$ and $g$ we've made (plus, as conventionally understood, $g(x)=\delta(x)=0$ for $x\ne 0$).  Then, to eliminate the second integral sign, one would apply the definition of $\delta$, but the book does it wrong by using $|_{x=0}^\infty$ rather than the correct $|_{x=0}$.  The book's mistake introduces a sign error since it's subtracting the value at $x=0$ rather than just plunking it into the formula.  Step 4, as you correctly point out, makes a further sign error, and the two cancel out.
In sum, your book's derivation is wrong at step 2, and it corrects the error at step 4 by introducing a further error.
Comment: The formula referred to would be the result of making the substitutions $f(x)=x\phi(x)$ and $g(x)=\delta(x)$ into the last displayed formula in my answer, i.e., $\int_{-\infty}^\infty x\phi(x)\delta'(x)\,dx$ $=x\phi(x)\delta(x)|^\infty_{-\infty}$ $-\int_{-\infty}^\infty (x\phi(x))'\delta(x)\,dx.$
Comment: The first term $x\phi(x)\delta(x)|_{-\infty}^\infty$ is zero for reasons explained in my previous comment.  We have generally $\int_{-\infty}^\infty h(x)\delta(x)\,dx=h(x)|_{x=0}$ whence, with $h(x)=(x\phi(x))'$, we get $\displaystyle -\Big(x\phi(x)\Big)^{\prime}\Big \lvert_{x=0}$.  As for why $\int_{-\infty}^\infty h(x)\delta(x)\,dx=h(x)|_{x=0}$, it's the definition of $\delta$ (Rudin 6.9) combined with the convention of writing $\delta(h)$ as $\int_{-\infty}^\infty h(x)\delta(x)\,dx$, mentioned at the end of the Background of my original answer.
Comment: Thank you for an excellent answer (+1); and also for pointing out the book error. I got hold of another copy of that book to check and it was exactly as you mentioned $\left(|_{x=0}\right)$. To finish this post I just need to know what you mean by "rather than just plunking it into the formula". _What_ __formula__ are you referring to? Best regards.
Comment: First as I explained $\phi$ is of compact support, and $\delta(x)=0$ for $x\ne 0$, so the term $x\phi(x)\delta(x)|_{-\infty}^\infty$ equals $0$.  Second, one applies the product rule for derivatives to compute $(x\phi(x))'$ as the product $(x\phi'(x)+\phi(x))$.  Third, because one is applying $\delta$ to the latter product (shown as taking the integral of the product multiplied with $\delta$), one gets the product$|_{x=0}$.
Comment: Sorry here is what I was asking before: I just need to know how $\displaystyle \int_{-\infty}^{\infty} x\phi(x)\delta'(x)\,\mathrm{d}x=x\phi(x)\delta(x)| ^{\infty}_{-\infty}-\int_{-\infty}^{\infty} (x\phi(x))'\delta(x)\,\mathrm{d}x= -\Big(x\phi(x)\Big)^{\prime}\Big \lvert_{x=0}$?
Comment: So if I'm understanding you correctly $\int_{-\infty}^\infty h(x)\delta(x)\,dx$ 'sifts' out the value at $x=0$ such that $\int_{-\infty}^\infty h(x)\delta(x)\,dx=h(0)$. Is that it?
Comment: That might be a way to put it.


SplashScreen not working on Android Cordova 4.0.2

Question: I installed cordova-plugin-splashscreen but this doesnt help me.
What lines should I add to my config.xml file and where to place the splash.9.png file?
Previously (before updating my Cordova version to the latest one) splashscreen was working fine with the following options:
<code>  <preference name="splashscreen" value="splash" />
  <preference name="splashScreenDelay" value="10000" />
</code>
and one splash.9.png file in res/drawable folded.
What am I doing wrong?
Comment: manually display splash using navigator.splashscreen.show() and hide()
Comment: Not a good idea because I can use this method only when deviceready is fired, not from the app start
Answer: Add your splash screen in respective drawable folder to match for all density devices.
and dont mention the value screen.png in preference.mention as like .(make sure your value is the file name of your splash image)

Reference Link
Answer: Finally I got it!
The problem was in the external ad SDK - AppJolt. As soon as I turned it off it began working again!


How can I expose a std::vector via an extern "C" ABI?

Question: I'm looking for the right way to access a vector of strings via a C ABI. My code looks broadly like this:
#include <iostream>
#include <vector>
#include <cstring>

// A C++ class containing information in a std::vector<std::string> that I want to expose in C (for eventually exporting to python via shared library)

class AVectorOfStrings{
private:
    std::vector<std::string> vec;
public:
    explicit AVectorOfStrings(std::vector<std::string> vec) : vec(std::move(vec)){}

    const vector<std::string> &getVec() const {
        return vec;
    }

    void setVec(const vector<std::string> &vec) {
        AVectorOfStrings::vec = vec;
    }
};

extern "C" {
    // function for accessing the strings
    char** getArrayOfCharStars(AVectorOfStrings* vec){
        std::vector<std::string> strings = vec->getVec();
        char **arr = (char **) malloc(strings.size() * sizeof(char *));

        for (int i = 0; i < strings.size(); i++) {
            arr[i] = (char *) malloc(sizeof(strings[i].c_str()));
            strcpy(arr[i], strings[i].c_str());
        }
        return arr;
    }

}
// usage
int main(){

    std::vector<std::string> input = {"1string", "2string", "3string"};
    AVectorOfStrings vec(input);

    char** arr = getArrayOfCharStars(&vec);

    // A bunch of attempts to access the three strings.
    std::cout << *arr << std::endl;
    std::cout << *arr[1] << std::endl;
    std::cout << *(arr[1]) << std::endl;
    std::cout << **arr << std::endl;

    return 0;
};

This code returns the following
1string
2
2
1

What would be the right way to get access to these strings? More generally, is this the right approach for handling an array of strings in C++? My end goal is just to have the strings stored in a way that I can access in Python using ctypes.
Comment: The second `sizeof` should be `strlen(...) + 1`.
Answer: It seems that it would be much more simple to use pybind and wrap the stl std::vector<std::string> directly. You have an example of that here.
class AVectorOfStrings {
    std::vector<std::string> vec;
};

/* ... binding code ... */

py::class_<AVectorOfStrings>(m, "AVectorOfStrings")
    .def(py::init<>())
    .def_readwrite("contents", &AVectorOfStrings::contents);

Comment: Very interesting. I'm already (and have to) work with `ctypes` but perhaps these two mechanisms of communication are not mutually exclusive.


Proving statement in modular arithmetic

Question: I am revisiting Euler's criterion, so I bumped into the following statement which I don't know how to prove.
Let $p$ be some prime number and $a \in \mathbb{Z}$.
How to prove that for every $x \in \{1, 2, ..., p - 1\}$ there exist exactly one $y \in \{1, 2,  ..., p - 1\}$  such that $xy \equiv a \pmod p$? (Of course, "exatcly one" in terms of modulo $p$.)
How to generalise this when $p$ is not a prime number?
Comment: Uniqueness comes from $p$ being a prime dividing $x(y_1-y_2)$, if both $xy_1$ and $xy_2$ give the same remainder. Note that $p$ doesn't divide $x$ and therefore, must divide $y_1-y_2$. For existence note that $x\cdot 1,x\cdot 2,...,x\cdot(p-1)$, by the argument above, give $p-1$ different non-zero remainders modulo $p$, but there are only $p-1$ such remainders. Therefore, one of the must be the same remainder as $a$.
Answer: This is a consequence of Bezout's theorem. If $(a,b)=1$ then there exists integers $x,y$ such that $ax+by=1$. Therefore $ax\equiv 1 \mod b$. Since $p$ is prime, just set $b=p$(b in my notation) and now we know that we can invert $a$(which is $x$ or $y$ in your example).
Lets look at your example again, $xy\equiv a \mod p$. From what I've just said, we know since $(x,p)=1$, the inverse $x^{-1}$ exists thus
$$x^{-1}xy\equiv x^{-1}a \mod p$$
$$y\equiv x^{-1}a \mod p$$
so $y$ is unique mod $p$. As I also mentioned, $p$ being prime was never required, we just needed $x$ and $p$ to be coprime.
This can also be interpreted as, for any integer $n$, the integers less than $n$ which are coprime to $n$ form a group, therefore have inverses.
Comment: Thanks for the answer.
Comment: Please strive not to add more dupe answers to dupes of FAQs, cf. site policy [here](https://math.meta.stackexchange.com/q/33508/242).

Proving statement in modular arithmetic


Sum of two squares

Question:
Possible Duplicate:
Prove that $n$ is a sum of two squares?

I was reading this and began wondering if there is a general theorem that a number of a given form is the sum of two squares. I know about Fermat's Theorem, but I am thinking about the general case. The question is

For which positive integer $n$ we can find positive integers $a,b$ with $n=a^2+b^2$?

I found a related question: Prove that $n$ is a sum of two squares?
If this is a duplicate, I am sorry. I have searched the site and didn't find this question posted. Any reference would be useful.
Comment: See [Fermat's theorem on sums of two squares](http://en.wikipedia.org/wiki/Fermat's_theorem_on_sums_of_two_squares). It has been said that is the result Fermat was most proud of.
Answer: The answer is on the page you linked to: $n$ is a sum of two squares if and only if $n$ is a square times a product of different primes which are either 1 modulo 4 or 2.
Comment: Ok. I'll delete the question. I am sorry I didn't read through the entire post I linked to.
Comment: @amWhy: The answer is not specific, whatever you mean by this. (One considers the number 1 as the empty product, as is usual, and the emptyset is a part of the set of primes. Ergo.)
Comment: Perhaps part of the confusion comes from not realizing that **every** positive integer has a **unique** decomposition as a square times a product of different primes (product over a possibly empty set of primes).

Sum of two squares


Exponential form of a log

Question: I'm a bit confused on the wording of this question:
An equation is shown below
x = log(20)
What is the exponential form of this equation?
So my answer is $10^x$=20. But I am not sure if that is even the right format of an exponential form or if that is the most simplified answer I can give?
Comment: Yes, it means taking $\exp$ on both sides: $\exp(x)=\exp(\log(20))$. More generally, $a^x=a^{\log(20)}$ for base $a$.
Comment: If by $x = \log 20$, you mean $x = \log_{10} 20$, your answer is correct.
Answer: Remember that $e^{x}$ is the inverse function of $\ln(x)$, so they "undo" each other: $e^{\ln(x)}=x$ and $\ln(e^x)=x$. Therefore you can rearrange your equation by doing this:
\begin{equation}
e^x = e^{\ln20} \\
\therefore e^x = 20
\end{equation}
which is the "exponential form" of the equation.

Exponential form of a log


Why is the empty set considered a family of sets?

Question: As far as I understand, a set is considered to be a family of sets if and only if it is the case that the elements of this set are sets themselves. Since the empty set does not contain any elements by definition, should it not be the case that the empty set is not a family of sets? Thank you in advance for your help.
Comment: Every element of the empty set is a set. Look up the term "vacuously true".
Comment: Equally true is that every element of the empty set is _not_ a set. Lookup the previous comment.
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Comment: The only way for " every element in a set, is a set" to be false is if there is an element in the set, which is not a set. i.e. A counterexample. There are no such for the empty set. Note: Rather than family of sets, it is common terminology to call such a set a hereditary set.
Answer: The rationale presumably comes from a vacuous argument: can you find an element $x$ of $\emptyset$ such that $x$ is not a set?
This would require that $x \in \emptyset$ to begin with, so it can't hold.
You may think of this instead, perhaps, as "all zero of the elements of the empty set are sets" -- it's not the "zero" that matters, but the "all".
Answer: There's an old joke that goes like this: In a butcher's shop, a customer asks the butcher what the price of brisket is. The butcher says the price is $\$1.20$ per pound. (This is a very old joke!)
"But at Mr. Fink's shop across the street, his price is $\$1.10$."
"Well, why don't you go buy your brisket from Mr. Fink?"
"He's all out of brisket."
"If I were out of brisket, my price could be $\$1.10$ too."

In mathematical logic, if your set is "all out of" elements -- that is, if it's the empty set, which has no elements -- then you can declare that the elements of your set are anything you like, just as a butcher who has no brisket to sell can afford to set its price at anything he likes.
But that's not a complete answer to the question, in my opinion, because we could have defined a family of sets to be a non-empty set whose elements are sets themselves.
So why don't we do that?
I think the reason is that there are times when mathematicians would like to be able to take intersections or set differences of families of sets and be able to call the result also a family of sets. And in some of those cases, the intersection of set difference might be empty. So if the empty set were not a family of sets, there would be times when someone either would have to call the intersection or set difference of families of sets something other than a family of sets, or would have to somehow ensure that the intersection or set difference was never empty, and this would make some definitions and proofs more complicated.
On the other hand, if (for some reason) someone needs a family of sets not to be empty, they can say "non-empty family of sets." And if we have a collection of families of sets, there is nothing that says that the empty set has to be an element of that particular collection.
So the usual definition of a family of sets avoids inconveniences and creates very little inconvenience itself, compared to a definition that requires the family to be non-empty. And mathematicians like definitions that are convenient to use.
Comment: The math.se interface is missing the ability for me to give you a rim shot. So here's the closest I can get >ba-dum, tish<.


Margin bigger even though same css is being used

Question: https://www.opheliajewellery.co.uk/about/
On this page there's a margin on the bottom and right of each div in the middle, The top and middle have the right size between eachother but the bottom and middle has a slightly larger gap,
After using the inspector I can't seem to find the cause, It's not actually a margin, it's just white space.
It works find on my localhost, but as soon as I put the code into wordpress it does this.
Here's some of the css and the html.
.ophelia-shortDiv{
    width: 37%;
    margin-bottom: 1%;
    display: inline-block;

}

.ophelia-aboutText{
    margin-top: 15%;
    margin-bottom: 15%;
    margin-left: 10%;
    margin-right: 10%;
}

.ophelia-wideDiv{
    width: 62%;
    margin-bottom: 1%;
    min-height: 345px;
    display: inline-block;
}

.cover{
    background-size: cover;
}

.ophelia-leftDiv{
    float: left;
    margin-right: 1%;
}

.ophelia-color1{
    background-color: #e7e7e7;
}

.ophelia-color2{
    background-color: #c5c6cd;
}

.ophelia-color3{
    background-color: #ced6d8;
}

.ophelia-aboutMain{
    margin-bottom: 5%;
    margin-top: 5%;
}

                ...

                ...

               ...

               ...

               ...

               ...

Changing 'inline-block' to 'inline-flex' on the divs fixed the problem.
There is a fiddle below to show an example of the problem
Comment: Please create a [mcve] in the question itself - this site is meant to be a repository for future visitors, once you fix your error on the site, the link will be no use and future visitors cannot see the original problem
Comment: Check your markup and make sure there's no spaces in between those two elements. If that's not an option use something other than `display: inline-block`
Comment: Possible duplicate of [How do I remove the space between inline-block elements?](https://stackoverflow.com/questions/5078239/how-do-i-remove-the-space-between-inline-block-elements)
Comment: he is not talking about the margin between inline-block elements. it's not a duplicate. he means the margin between rows. You could have just checked his link before flagging the question as duplicate.
Comment: It is a duplicate. `line-height` is not the answer. Change them to `inline-flex` and you'll see that `line-height` does not remove the space completely... just makes it smaller due to smaller `line-height`.
Comment: It was indeed changing it to inline-flex. Cheers
Answer: Your gap between your elements is caused by this css rule you have:
.kleanity-body, .kleanity-body p, .kleanity-line-height, .gdlr-core-line-height {
    line-height: 1.7;
}

Your are applying line-height to many different elements including the body of your html.
remove this rule and apply  the line-height only where you need it.
Answer: I put this into a fiddle, and indeed the margin issue is there. This has nothing to do with any styles applied to body, since it appears without any other context (though changes there might well have the desired effect).
I am not sure what is causing this, but it seems that if the image above is removed, the issue disappears, and also if the middle image has float:right - so I suspect this is something to do with the float:left in your ophelia-leftDiv class.


Extend a C++/MFC application with plugins in C++/MFC and C#

Question: I wonder how to best develop a plugin framework where you can develop plugins with both C++/MFC and C#.
The Host Program is an existing program developed in native C++/MFC. To extend the functionality of this program, we have so far developed separate programs in C++/MFC and C# that run as separate applications or windows services. These programs are now communicating with the host application via files. This is obviously a rather clumsy method, and we therefore wish to bring them under a common plug-in framework.
Each program also has a separate management of settings. We therefore want each plugin to expand the settings window in the host application so that all settings can be managed in one place. How can we do that in a flexible and easy way?
Answer:
(...) we therefore wish to bring them under a common plug-in framework. (...)

You can do that by creating a set of COM interfaces in a type library that you can wrap in a C++/MFC dll project. Then from either C++ or C# you can import this type library and create new COM classes that implement the predefined interfaces. Two disadvantages of these approach are: 1- That your main application will need to know the class IDs somehow to create instances of the COM classes. 2- Your plugins will need to be registered on the system or you will need to provide manifest files.

(...) We therefore want each plugin to expand the settings window in the
  host application so that all settings can be managed in one place. (...)

This one is a bit more tricky, but you could try having a tab control with one tab for each plug-in,  then pass the window handle of the corresponding tab to each plug-in during initialization, and then use that to place an ActiveX control on it. Creating ActiveX controls in MFC is well documented, and there is a sample project here for doing the same in C#: CSActiveX Sample