Por que alguns métodos tem ' :: '

Question: Por que alguns métodos como por exemplo do Perl ou Ruby: Net::FTP, tem esses dois pontos; como é a construção dos métodos dessa classe e por que é criada desta forma (com essa sintaxe) e não da forma cmumente utilizada por bibliotecas atuais: HTTParty.get(), requests.get()?
Answer: Isto nada tem a ver com método e sim com a classe e o seu namespace. FTP é a classe e nela conterá métodos. Net é apenas o sobrenome desta classe. Namespaces são como módulos que contém classe, mas não exatamente. Em algumas linguagens ele se confunde com um pacote de classes que tem um conceito ligeiramente diferente, a maneira exata de cada linguagem deve ser vista em sua documentação.
Tem uma explicação de Como funciona namespaces no C#?. A linguagem escolheu usar o ponto para namespaces também, mas a ideia é a mesma.
Comment: Obrigado, já tinha visto `namespace` simples em código C++ pela internet porém não sabia da ligação que tu apontou.

Por que alguns métodos tem ' :: '


How to add TextView at the end of a WebView

Question: In my application I need to open a WebView that contains a long html file.
I would like to add a TextView at the end of the WebView, so that only when the user has finished scrolling the WebView, the TextView would show.
I have tried with this Layout, but, no surprise, when I have finished scrolling the WebView the TextView does not show
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<WebView
    android:id="@+id/webView1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    />

<TextView
    android:id="@+id/textView1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="TextView" />

</LinearLayout>

Comment: did you try putting them in a scrollview?
Answer: you should add a ScrollView which contains your LinearLayout. In you code :
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<WebView
    android:id="@+id/webView1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    />

<TextView
    android:id="@+id/textView1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="TextView" />

</LinearLayout>

 </ScrollView>


How to create Constructive Solid Geometry in OpenGL / C++

Question: I want to stencil out some objects with openGL.
<code>glClear(GL_STENCIL_BUFFER_BIT);
glColorMask(false, false, false, false);
glEnable(GL_STENCIL_TEST);
glStencilFunc(GL_EQUAL, 0, 1);
glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
glDisable(GL_DEPTH_TEST);
glColor4f(0,0,1,1.0f);

gl::draw(mVBO); //a sphere

glEnable(GL_DEPTH_TEST);
glColorMask(true, true, true, true);
glStencilFunc(GL_ALWAYS,0, 1);
glStencilOp(GL_REPLACE,GL_KEEP, GL_ZERO);

mTexture.enableAndBind();
gl::drawCube(Vec3f(0,3,0),Vec3f(13,13,13) );

glDisable(GL_STENCIL_TEST)
</code>
I tried so many hours to achieve a simple boolean operation, but I dont get it.
I want something like this:
Answer: OpenGL's stencil buffer operates on the 2 dimensional pixel grid of the frame buffer. OpenGL itself has no notion of objects or a scene. It's merely drawing points, lines and triangles. So a real CSG is not possible with just OpenGL. However there are techniques that emulate CSG with stencil buffer operations, but they're quite complex. Google for "OpenGL CSG in the stencil buffer" to find some papers from the mid 1990-ies on the subject.


Produto vetorial em C com entrada de arquivos .dat

Question: Seja o código abaixo, onde o arquivo de entrada vetores.dat, em cada linha, tem 6 números onde os 3 primeiros são componentes de um vetor "u" e os 3 últimos são componentes de um vetor "v".O arquivo de saída vetorial.dat deve ter 3 componentes em cada linha do produto vetorial de u por v.
<code>#include <stdio.h>
#define N 6
int main(){

FILE *entrada = NULL;
FILE *saida = NULL;
int i=0;
double componente;
double p[N];
double vetorial_x, vetorial_y, vetorial_z;

entrada = fopen("vetores.dat","r");
if(entrada == NULL) printf("O arquivo vetores.dat não existe\n");

saida = fopen("vetorial.dat","w");

while(fscanf(entrada,"%lf",&componente) != EOF){
    if(i < N){
        p[i] = componente;
        i++;
    }

    else if(i = N){
        vetorial_x = p[1]*p[5] - p[2]*p[4];
        vetorial_y = p[2]*p[3] - p[0]*p[5];
        vetorial_z = p[0]*p[4] - p[1]*p[3];
        fprintf(saida,"%.3lf\t%.3lf\t%.3lf",vetorial_x,vetorial_y,vetorial_z);
        i=1;
        p[0] = componente;
        }
    }
return 0;

}
</code>
O programa adiciona os 6 números encontrados em cada linha de "vetor.dat" em um array p[6] logo após ele realiza o produto vetorial.
O problema é que ao colocar um arquivo "vetor.dat" com 45 linhas o programa imprime um arquivo "vetorial.dat" com apenas 38 linhas (deveria imprimir 45). Ao colocar um arquivo "vetor.dat" com 4 linhas o programa gera um arquivo "vetorial.dat" com 3 linhas.
O código parece sempre gerar um arquivo com menos vetores de saída que vetores de entrada.
Não sei se o erro está na passagem
<code>  while(fscanf(entrada,"%lf",&componente) != EOF){
</code>
por exemplo.
Answer: Só encontrei esse erro:
<code> else if(i = N)
</code>
Onde certamente deveria ser:
<code>else if(i == N)
</code>


Making a Pivot Table in a SubQuery

Question: I have four tables in the database that I am trying to pull data from; a, b, c, d.
For each of these tables I want to pull count(distinct PolicyNumber) and InvestmentCode.
I would like my output to look something like this: (with 1,2,3,4,5 being the InvestmentCode)
  a_PolicyCount           b_PolicyCount         c_PolicyCount      d_PolicyCount
1        14                    56                     32                  74
2        36                    41                     25                  97
3        45                    98                     10                   2
4        12                    16                     13                   5
5        41                    22                     36                   4

I have tried a couple different ways but I keep getting errors. This is the code I have so far:
Select
    (Select count(distinct PolicyNumber), InvestmentCode
        from (Select distinct PolicyNumber, Investmentcode
            from a
        ) as a
            group by InvestmentCode
    ) as a,
    (Select count(distinct PolicyNumber), InvestmentCode
        from (Select count(distinct PolicyNumber), InvestmentCode
            from b
            ) as b
            group by InvestmentCode
    ) as b,
    (Select count(distinct PolicyNumber), InvestmentCode
        from (Select distinct PolicyNumber, InvestmentCode
            from c
            ) as c
            group by InvestmentCode
    ) as c,
    (Select count(distinct PolicyNumber), InvestmentCode
        from (Select distinct PolicyNumber, InvestmentCode
            from d
            ) as d
            group by InvestmentCode
    ) as d;

I am just starting to learn SQL so thank you in advance for your answer. I am not sure if it is best to use a Pivot table or by using Joins
Comment: GROUP BY and DISTINCT do not go hand in hand.
Answer: Sometimes "dirty" pivots an un-pivots are easier to write and outperform a traditional pivot/unpivot. Here is one way to do that. You can achieve the same thing with a PIVOT statement.
DECLARE @RunDate NVARCHAR(50)='20200531'

SELECT
    Investmentcode,
    INDCONEX_Count      = COUNT(CASE WHEN InvestmentType ='INDCONEX' THEN PolicyNumber ELSE NULL END),
    INTCRDEX_Count      = COUNT(CASE WHEN InvestmentType ='INTCRDEX' THEN PolicyNumber ELSE NULL END),
    RACT1CR1_01_Count   = COUNT(CASE WHEN InvestmentType ='RACT1CR1_01' THEN PolicyNumber ELSE NULL END),
    RACT3CR1_01_Count   = COUNT(CASE WHEN InvestmentType ='RACT3CR1_01' THEN PolicyNumber ELSE NULL END)
FROM
(
    Select InvestmentType = 'INDCONEX', PolicyNumber, Investmentcode from INDCONEX where RunDate = @RunDate
    UNION
    Select InvestmentType = 'INTCRDEX', PolicyNumber, Investmentcode from INTCRDEX where RunDate = @RunDate
    UNION
    Select InvestmentType = 'RACT1CR1_01', PolicyNumber, Investmentcode from RACT1CR1_01 where RunDate = @RunDate
    UNION
    Select InvestmentType = 'RACT3CR1_01', PolicyNumber, Investmentcode from RACT3CR1_01 where RunDate = @RunDate
)AS X
GROUP BY
    InvestmentType ,
    Investmentcode

Using a PIVOT
DECLARE @RunDate NVARCHAR(50)='20200531'

SELECT
    *
FROM
(
    Select InvestmentType = 'INDCONEX', PolicyNumber, Investmentcode from INDCONEX where RunDate = @RunDate
    UNION
    Select InvestmentType = 'INTCRDEX', PolicyNumber, Investmentcode from INTCRDEX where RunDate = @RunDate
    UNION
    Select InvestmentType = 'RACT1CR1_01', PolicyNumber, Investmentcode from RACT1CR1_01 where RunDate = @RunDate
    UNION
    Select InvestmentType = 'RACT3CR1_01', PolicyNumber, Investmentcode from RACT3CR1_01 where RunDate = @RunDate
)AS X
PIVOT
(
    COUNT(PolicyNumber) FOR InvestmentType IN(INDCONEX,INTCRDEX,RACT1CR1_01,RACT3CR1_01)
)
AS PV

Grouping each UNION'ed statement in the Sub-query may prove more performant depending on the size of the tables. If you turn on "Include Actual Query Plan" you can see the differences.
Actually, it is showing the first two queries above to outperform with 12% of total cost .vs 77% against the queries below. With both queries above drawing an identical plan.
SELECT
    Investmentcode,
    INDCONEX_Count      = CASE WHEN InvestmentType ='INDCONEX' THEN PolicyCount ELSE NULL END,
    INTCRDEX_Count      = CASE WHEN InvestmentType ='INTCRDEX' THEN PolicyCount ELSE NULL END,
    RACT1CR1_01_Count   = CASE WHEN InvestmentType ='RACT1CR1_01' THEN PolicyCount ELSE NULL END,
    RACT3CR1_01_Count   = CASE WHEN InvestmentType ='RACT3CR1_01' THEN PolicyCount ELSE NULL END
FROM
(
    Select InvestmentType = 'INDCONEX', PolicyCount=COUNT(PolicyNumber), Investmentcode from INDCONEX GROUP BY Investmentcode where RunDate = @RunDate
    UNION
    Select InvestmentType = 'INTCRDEX', PolicyCount=COUNT(PolicyNumber), Investmentcode from INTCRDEX GROUP BY Investmentcode where RunDate = @RunDate
    UNION
    Select InvestmentType = 'RACT1CR1_01', PolicyCount=COUNT(PolicyNumber), Investmentcode from RACT1CR1_01 GROUP BY Investmentcode where RunDate = @RunDate
    UNION
    Select InvestmentType = 'RACT3CR1_01', PolicyCount=COUNT(PolicyNumber), Investmentcode from RACT3CR1_01 GROUP BY Investmentcode where RunDate = @RunDate
)AS X

SELECT
    *
FROM
(
    Select InvestmentType = 'INDCONEX', PolicyCount=COUNT(PolicyNumber), Investmentcode from INDCONEX GROUP BY  Investmentcode where RunDate = @RunDate
    UNION
    Select InvestmentType = 'INTCRDEX', PolicyCount=COUNT(PolicyNumber), Investmentcode from INTCRDEX GROUP BY  Investmentcode where RunDate = @RunDate
    UNION
    Select InvestmentType = 'RACT1CR1_01', PolicyCount=COUNT(PolicyNumber), Investmentcode from RACT1CR1_01 GROUP BY  Investmentcode where RunDate = @RunDate
    UNION
    Select InvestmentType = 'RACT3CR1_01', PolicyCount=COUNT(PolicyNumber), Investmentcode from RACT3CR1_01 GROUP BY  Investmentcode where RunDate = @RunDate
)AS X
PIVOT
(
    MAX(PolicyCount) FOR InvestmentType IN(INDCONEX,INTCRDEX,RACT1CR1_01,RACT3CR1_01)
)
AS PV

Answer: I would suggest union all and group by:
select Investmentcode,
       sum(case when which = 'INDCONEX' then cnt end) as INDCONEX,
       sum(case when which = 'INTCRDEX' then cnt end) as INTCRDEX,
       sum(case when which = 'RACT1CR1_01' then cnt end) as RACT1CR1_01,
       sum(case when which = 'RACT3CR1_01' then cnt end) as RACT3CR1_01
from ((Select Investmentcode, count(distinct PolicyNumber) as cnt, 'INDCONEX' as which
       from INDCONEX
       where RunDate = '20200531'
       group by InvestmentCode
      ) union all
      (Select Investmentcode, count(distinct PolicyNumber) as cnt, 'INTCRDEX' as which
       from INTCRDEX
       where RunDate = '20200531'
       group by InvestmentCode
      ) union all
      (Select Investmentcode, count(distinct PolicyNumber) as cnt, 'RACT1CR1_01' as which
       from RACT1CR1_01
       where RunDate = '20200531'
       group by InvestmentCode
      ) union all
      (Select Investmentcode, count(distinct PolicyNumber) as cnt, 'RACT3CR1_01' as which
       from RACT3CR1_01
       where RunDate = '20200531'
       group by InvestmentCode
      )
     ) x
group by Investmentcode;

Making a Pivot Table in a SubQuery


Migrar Aplicação do Delphi 7 de Firebird para PostgreSQL

Question: Estou tentando migrar uma aplicação que foi desenvolvida no Delphi 7 e que utiliza do banco Firebird para salvar suas informação, para o banco de dados postgreSQL, a partir disso, já consegui realizar a conexão do postgreSQL com o Delphi com a ajuda do ZeosLib, porém essa aplicação utiliza de muitas particularidades do dbExpress que o Zeoslib não possui, então por este motivo vou tentar realizar a conexão do PostgreSQL com ODBC, para que assim eu consiga através do dbExpress realizar essa conexão com essa aplicação. A duvida é a seguinte, é possível através do ODBC realizar isso no Delphi 7, se sim como seria possível fazer isso, eu tentei desta forma porém esta dando erro quando tento conectar com o ODBC criado:

Dai quando chego nesta parte de configurar ele não permite fazer nada, apenas salvar, dai após salvar quando tento abrir o mesmo ele já esta com uma senha, que devido a não ter sido eu que configurei, eu não faço a minima ideia de qual seja, se tiverem alguma ideia...
Answer: Já tentou usar o próprio driver ODBC PostgreSQL ?

Product   psqlODBC Description     psqlODBC is the official PostgreSQL ODBC
  Driver.
Licence   Open source Publisher   PostgreSQL Global Development Group

Você pode baixa-lo em:
 www.postgresql.org
A configuração e bem tranquila, caso tente fazer e dê algum erro por favor postar para poder tentar te ajudar.
Comment: Como posso executar um comando SQL com o PgDAC? Por exemplo com o SQLConnection o comando esta assim: `SQLConnection.Execute('UPDATE NEXTID SET PROXIMOCODIGO = '+inttostr(sdsNextIDPROXIMOCODIGO.AsInteger+1)+
    ' WHERE TABELA = '''+TableName +'''', nil);`


How to prove: Moment Generating Function Uniqueness Theorem

Question: Many results are based on the fact of the Moment Generating Function (MGF) Uniqueness Theorem, that says:

If $X$ and $Y$ are two random variables and equality holds for their MGF's: $m_X(t) = m_Y(t)$ then $X$ and $Y$ have the same probability distribution: $F_X(x) = F_Y(y)$.

The proof of this theorem is never shown in textbooks, and I cannot seem to find it online or in any book I have access to.
Can someone show me the proof or tell me where to look it up?
Thanks for your time.
Comment: Indeed, the formulas are very handy, but I wish there were more "meat" on them (details).
Comment: Both, I don't see why the equalities are true - there need some intermediary calculations.
Comment: See also https://stats.stackexchange.com/questions/34956/proof-that-moment-generating-functions-uniquely-determine-probability-distributi
Comment: Got something from an answer below?
Comment: Which part(s) are you unable to complete after 30 seconds of thinking?
Comment: Why have you written two equations ? One for natural numbers and one for real numbers ? What is $s$ in this connection - a real number ?
Comment: Answering you in a comment to my answer.
Answer: Let us first clarify the assumption. Denote the moment generating function of $X$ by $M_X(t)=Ee^{tX}$.

Uniqueness Theorem. If there exists $\delta>0$ such that $M_X(t) = M_Y(t) < \infty$ for all $t \in (-\delta,\delta)$, then $F_X(t) = F_Y(t)$ for all $t \in \mathbb{R}$.

To prove that the moment generating function determines the distribution, there are at least two approaches:

To show that finiteness of $M_X$ on $(-\delta,\delta)$ implies that the moments $X$ do not increase too fast, so that $F_X$ is determined by $(EX^k)_{k\in\mathbb{N}}$, which are in turn determined by $M_X$. This proof can be found in Section 30 of Billingsley, P. Probability and Measure.

To show that $M_X$ is analytic and can be extended to $(-\delta,\delta)\times i\mathbb{R} \subseteq \mathbb{C}$, so that $M_X(z)=Ee^{zX}$, so in particular $M_X(it)=\varphi_X(t)$ for all $t\in\mathbb{R}$, and then use the fact that $\varphi_X$ determines $F_X$. For this approach, see Curtiss, J. H. Ann. Math. Statistics 13:430-433 and references therein or Roja's answer.

At undergraduate level, it is interesting to work with the moment generating function and state the above theorem without proving it. One possible proof requires familiarity with holomorphic functions and the Identity Theorem from complex analysis, which restricts the set of students to which it can be taught.
In fact, the proof is so advanced that, at such a point it usually makes more sense to accept working with complex numbers, forget about moment generating function and work with the charachteristic function $\varphi_X(t)=Ee^{itX}$ instead. Almost every graduate textbook takes this path and proves that the characteristic function determines the distribution as a corollary of the inversion formula.
This proof of the inversion formula is bit long, but it only requires Fubini Theorem to switch an expectation with an integral and Dominated Convergence Theorem to switch an integral with a limit. A direct proof of uniqueness without inversion formula is shorter and simpler, and it only requires Weierstrass Theorem to approximate a continuous function by a trigonometric polynomial.
Side remark. If you only admit random variables whose support are contained in $\mathbb{Z}_+$, then the probability generating function $G_X(z)=Ez^X$ determines $p_X$ (and thus $F_X$). This elementary result is proved in most undergraduate textbooks and is mentioned in Did's answer.
If you only admit random variables whose support are contained in $\mathbb{Z}$, then it is simpler to show that $\varphi_X$ determines $p_X$, as also mentioned in Did's answer, and the proof uses Fubini.
Comment: This is a super helpful answer. thanks.
Answer: $$(\forall n\geqslant0)\qquad \left.\frac{\mathrm d^n}{\mathrm ds^n}\mathbb E[s^X]\right|_{s=0}=n!\cdot\mathbb P[X=n]
$$
$$(\forall x\in\mathbb R)\qquad \int_0^{2\pi}\mathbb E[\mathrm e^{\mathrm itX}]\,\mathrm e^{-\mathrm itx}\,\mathrm dt=2\pi\cdot\mathbb P[X=x]
$$
Comment: Let me add that it is a tad unsettling to see that, when it is suggested that you perform yourself a trivial computation which would allow you to understand the general case, you do not even acknowledge the suggestion but fall back on demands already answered a long time ago. If you think maths can be learned as a spectator, you are wrong (but hey, this is your call).
Comment: I guess Did is giving a formula for recovering a discrete probability distribution from its MGF.
Comment: Then $E[s^X]=ps^j+(1-p)s^k$. Alternatively, in the general case, $E[s^X]=M_X(\log s)$.
Comment: Does your formula works for negative values of X ?
What is X is -16 ?
Comment: "If you think maths can be learned as a spectator, you are wrong " well put
Comment: The first formula only makes sense if the support of $X$ is $\mathbb{N}$. The second formula is only true if the support of $X$ is contained in $\mathbb{Z}$, so it makes no sense to write "$\forall x \in \mathbb{R}$". See that for a normal distribution, $\mathbb{E}[e^{itX}]=e^{-t^2/2}$ and this formula **assings a complex number to $\mathbb{P}(X=0)$, instead of zero**. It does not come close to answering the OP's question: "If $X$ and $Y$ are two random variables and equality holds for their MGF's: $m_X(t) = m_Y(t)$ then $X$ and $Y$ have the same probability distribution: $F_X(x) = F_Y(y)$."
Comment: @Erdogan CEVHER for the second formula de Normal is a counter-example as already pointed out. For the first formula take X=1/2 a.s. to see the equation fall apart.
Comment: "Can you explain what you are doing" ??
Comment: Yes, but I am having trouble interpreting what 's' means in this connection.
Comment: "what 's' means in this connection"... Answer: 's' means nothing, one can consider that 's' is any real number in [0,1].
Comment: Lets say X is a random variable with P(X = j) = p and P(X = k) = 1 - p.

Then M_X(t) = E[e^(tX)] = e^(t * j) * p + e^(t * k) * (1 - p)

How does your formula make sense in this connection ? Can you give an example :-) ?
Comment: Could you write this in terms of e^tX instead of s?
Comment: Try http://en.wikipedia.org/wiki/Laplace_Transform.
Comment: "Why have you written two equations ? One for natural numbers and one for real numbers ?" The second one yields the atoms of X at every value, not only integer ones (as is written explicitely in the answer). "What is s in this connection - a real number ?" Already answered 8 months ago. Do you read the comments answering your queries for explanations?
Comment: Again? What a passion...
Comment: @user334639, what is your source for the info on "if support is N" and "contained in Z"?
Answer: The following is a proof with two steps.
It requires familiarity with Cauchy-Riemann equations and the identity theorem from complex analysis. Dominated convergence theorem is also applied. Thus, it  fits for any advanced undergraduate or graduate student who is familiar with these topics.
Step 1:
Assume that $X$ is a random variable such that there exists $\delta\in(0,\infty]$ for which
$$M_X(s)=Ee^{sX}<\infty\ , \ \forall s\in(-\delta,\delta)\,.$$
Now, let's denote $\Omega\equiv\left\{z\in\mathbb{C};\text{Re}(z)\in(-\delta,\delta)\right\}$ and define
$$\phi_X(z)\equiv Ee^{zX}\ ,\ \forall z\in\Omega\,.$$
Let $z=s+it\in\Omega$ and observe that
$$\phi_X(z)=E\ \overset{u(s,t;X)}{\overbrace{e^{sX}\cos (tX)}}+iE\ \overset{v(s,t;X)}{\overbrace{e^{sX}\sin (tX)}}\,.$$
It is possible to apply dominated convergence theorem in order to show that $Eu(\cdot;X)$ and $Ev(\cdot;X)$ are differentiable on $(-\delta,\delta)\times\mathbb{R}$. To see this, notice that for every $(s,t)\in(-\delta,\delta)\times\mathbb{R}$
$$|\frac{\partial u(s,t;X)}{\partial t}|\ ,\ |\frac{\partial u(s,t;X)}{\partial s}|\ ,\ |\frac{\partial v(s,t;X)}{\partial t}|\ ,\ |\frac{\partial u(s,t;X)}{\partial s}|$$
are all dominated by the random variable $Y=|X|e^{sX}$. In addition notice that for every $\epsilon>0$
$$|X|=\epsilon^{-1}|\epsilon X|\leq\epsilon^{-1}\sum_{k=0}^\infty\frac{|\epsilon X|^k}{k!}$$
$$=\epsilon^{-1}e^{\epsilon |X|}\leq\epsilon^{-1}\left(e^{-\epsilon X}+e^{\epsilon X}\right)$$
and hence
$$|Y|\leq \frac{e^{sX}}{\epsilon}\left(e^{-\epsilon X}+e^{\epsilon X}\right)=\epsilon^{-1}\left(e^{(s-\epsilon) X}+e^{(s+\epsilon)X}\right)\,.$$
Therefore, since $M_X(\cdot)$ is finite on $(-\delta,\delta)$, then by taking small enough $\epsilon>0$ deduce that
$$E|Y|\leq\epsilon^{-1}\left[M_X(s-\epsilon)+M_X(s+\epsilon)\right]<\infty\,.$$
Thus dominated convergence theorem can be carried out to show that $Eu(\cdot;X)$ and $Ev(\cdot;X)$ have partial derivatives with respect to both of their coordinates. Moreover, these partial derivatives are obtained by differentiating inside the expectation. In addition, dominated convergence theorem can be applied once more (with the same dominating random variable) in order to show that these partial derivatives are continuous on $(-\delta,\delta)\times\mathbb{R}$, i.e., $Eu(\cdot;X)$ and $Ev(\cdot;X)$ are differentiable on $(-\delta,\delta)\times\mathbb{R}$. Now, it is straightforward to verify that the Cauchy-Riemann equations are satisfied on $(-\delta,\delta)\times\mathbb{R}$ and hence $\phi_X(\cdot)$ is holomorphic on $\Omega$.
Step 2:
Assume that $X$ and $Y$ are two random variables such that there exists $\delta\in(0,\infty)$ for which $M_X(s)=M_Y(s)<\infty$ for every $s\in(-\delta,\delta)$. Then, define
$$H(z)\equiv\phi_X(z)-\phi_Y(z)\ , \ \forall z\in\Omega$$
and by the result of Step 1, $H(\cdot)$ is holomorphic on $\Omega$ which is an open connected subset of $\mathbb{C}$. Now, denote a sequence $z_n=\frac{\delta}{2n}\in\Omega,\forall n\in\mathbb{N}$ and note that $z_n\rightarrow 0\in\Omega$ as $n\to\infty$. In addition, $H(z_n)=0,\forall n\in\mathbb{N}$ and hence using the identity theorem deduce that $H(z)=0,\forall z\in\Omega$. Then, as a special case, for every $t\in\mathbb{R}$ set $z=it$ and get
$$Ee^{itX}=Ee^{itY}$$
which means that $F_X(u)=F_Y(u),\forall u\in\mathbb{R}$ due to the uniqueness property of characteristic function (There are plenty of sources for the proof of this property and as mentioned by others its proof requires no advanced staff but dominated convergence and Fubini's theorems).
Comment: You could choose any sequence $(z_n)_{n=1}^\infty$ for which (1) $z_n\in\Omega,\forall n\in\mathbb{N}$, (2) $H(z_n)=0,\forall n\in\mathbb{N}$ and (3) $\exists\lim_{n\to\infty}z_n\in\Omega$. For more accurate details you may see the identity theorem for holomorphic functions, e.g., https://en.wikipedia.org/wiki/Identity_theorem.
Comment: Why the sequence $z_n=\delta/2n$. Can we take another sequence thats not zero as $n$ goes to infinity?
Answer: In the case where $X$ has density function $\phi(x)$,
$$
M_X(it) = E(e^{itX}) = \int_{-\infty}^\infty e^{itx}\phi(x)dx,
$$
which is the Fourier transform of $\phi(x)$. Therefore $\phi(x)$ can be recovered from its MGF using the Fourier inversion formula.
The function $M_X(it)$ is called the characteristic function of $X$. See Chapter 6 of Kai Lai Chung's book A Course in Probability Theory for more details.
Comment: I guess Did's answer above works nicely for random variables on a finite probability space.
Comment: @AmritanshuPrasad Actually, for every nonnegative integer valued random variable.
Comment: Thanks alot. So in order to understand the proof I must look into Fourier transformation theory ?
Comment: @Did Actually, you prove uniqueness *restricted* to that space. You don't rule out the possibility that other random variables happen to have the same MGF.


Binding com PHP e PostgreSQL

Question: Bom pessoal, estou com um problema ao fazer um insert no banco de dados postgreSQL, esse é o meu insert:
INSERT INTO dynfipemarca (codigomarca,marca,tipo, OID, fgenabled, fgsystem , nrversion) VALUES
                               (:codigomarca,'" . pg_escape_string(utf8_encode($nomeMarca)) . "',:tipo, '" . $codigoMarca . "' , 1 , 0, 0)

recebo os dados do back end de uma API, e insiro dinamicamente, aqui está meu Binding:
$cadastrarMarca     = conectar()->prepare($sql);
        $cadastrarMarca->bindValue(":codigomarca",$codigoMarca,PDO::PARAM_INT);
        $cadastrarMarca->bindValue(":marca", $nomeMarca);
        $cadastrarMarca->bindValue(":tipo",$tipo);
        $cadastrarMarca->execute();

e o erro que está me aparecendo é esse

PHP Warning:  PDOStatement::bindValue(): SQLSTATE[HY093]: Invalid parameter number: :marca

eu identifiquei onde está o erro, $cadastrarMarca->bindValue(":marca", $nomeMarca); porém não sei como resolver, alguma dica?
Comment: Onde está o parâmetro `:marca` no SQL?
Comment: é que na realidade no insert onde insiro o value da marca, eu estava fazendo com :marca, porém começou a dar erro ao inserir uma marca com acento, aí eu troquei e coloquei a função pg_escape_string e utf8_encode, como tá ali no exemplo. Aí dá o erro nesse parâmetro, tem como eu fazer o encoding direto no parâmetro?
Comment: Nesse SQL: `INSERT INTO dynfipemarca (codigomarca,marca,tipo, OID, fgenabled, fgsystem , nrversion) VALUES (:codigomarca,'" . pg_escape_string(utf8_encode($nomeMarca)) . "',:tipo, '" . $codigoMarca . "' , 1 , 0, 0)` tem o parâmetro `:tipo` e o parâmetro `:codigomarca`, porque não coloca o `:marca` também já que está fazendo o *bind* dele?
Comment: como eu expliquei, começou dar erro ao inserir marcas que tem acento, entende? aí eu tirei o parametro, e exibi o que vem do back end dentro das funções de encoding
Comment: Então porque fazer o *bind* de uma parâmetro que você removeu? Retire a linha: `$cadastrarMarca->bindValue(":marca", $nomeMarca);`
Comment: hummm beleza Laércio, no caso como eu estou inserindo o que vem do back end e já está definido o valor não precisa de bind, entendi. Removi e deu certo, obrigado.
Comment: Você tentou manter o parâmetro `:marca` e deixar o SQL como `INSERT INTO dynfipemarca (codigomarca,marca,tipo, OID, fgenabled, fgsystem , nrversion) VALUES (:codigomarca,'" . pg_escape_string(utf8_encode(:marca)) . "',:tipo, '" . $codigoMarca . "' , 1 , 0, 0)`? Dessa forma poderia manter o *`bind`*.
Comment: sim tentei, mas parou de inserir as marcas, depois eu faço outro teste e vejo melhor o que acontece
Comment: Setinha pra cima na resposta?
Answer: O erro está sendo apresentado porque o parâmetro :marca não está no seu SQL.
Você pode remover a linha abaixo que vai resolver o problema.
$cadastrarMarca->bindValue(":marca", $nomeMarca);

Binding com PHP e PostgreSQL


Mensagens personalizadas com laravel validator

Question: Não consigo aplicar regras personalizadas nos meus formulários, toda vez que tento aplicar alguma regra, ele me retorna um ValidationException padrão do Laravel, como faria para que a mensagem de erro seja personalizada?
<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class CriarContaPost extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {

        return [

            'nome' => 'required | max:255 | alpha',

        ];

    }

    public function messages()
    {

        return [

            'nome.required' => 'Nome obrigatório',
            'nome.max' => 'Nome deve ter até 150 caracteres',
            'nome.alpha' => 'Nome deve possuir apenas caracteres',

        ];

    }

}

Porém antes mesmo de eu tentar testar essa validação, eu uso o comando para listar minhas rotas, e no terminal próprio terminal ele me retorna:
   Illuminate\Validation\ValidationException  : The given data was invalid.

  at vendor\laravel\framework\src\Illuminate\Foundation\Http\FormRequest.php:130
          * @throws \Illuminate\Validation\ValidationException
         */
         protected function failedValidation(Validator $validator)
         {
           throw (new ValidationException($validator))
                         ->errorBag($this->errorBag)
                         ->redirectTo($this->getRedirectUrl());
         }

  Exception trace:

  1   Illuminate\Foundation\Http\FormRequest::failedValidation(Object(Illuminate\Validation\Validator))
      vendor\laravel\framework\src\Illuminate\Validation\ValidatesWhenResolvedTrait.php:26

  2   Illuminate\Foundation\Http\FormRequest::validateResolved()
      vendor\laravel\framework\src\Illuminate\Foundation\Providers\FormRequestServiceProvider.php:30

O que devo fazer para que a mensagem não apareça como "The given data was invalid" e sim algo personlizado?
Atualmente utilizo a versão 6.0 do Laravel, tentei procurar algo relacionado na documentação mas acabei não achando
Comment: Qual a versão do Laravel?
Answer: Opa, vamos tentar resolver o seu problema.
Vou passar um exemplo que está funcionando e é uma boa prática para validation no Laravel.
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Cliente;

class ClienteController extends Controller {

  public function store(Request $request) {

    $mensagens = [
        'required' => 'O :attribute é obrigatório!',
        'nome.min' => 'É necessário no mínimo 5 caracteres no nome!',
        'email.email' => 'Digite um email válido!'
    ];

    $request->validate([
        'nome' => 'required|min:5|max:10|unique:clientes',
        'idade' => 'required',
        'email' => 'required|email'
    ], $mensagens);

    $cliente = new Cliente();

    $cliente->nome = $request->input('nome');
    $cliente->idade = $request->input('idade');
    $cliente->endereco = $request->input('endereco');
    $cliente->email = $request->input('email');
    $cliente->save();
  }
}

Perceba que no código acima é definido as validações que eu vou querer utilizar, como required, min, email etc. Depois é feito uma atribuição do campo que quero utilizar com a validação.


Busca de duas colunas no banco de dados

Question: Preciso de ajuda de como fazer uma busca em duas colunas, sou iniciante.
Se eu digito uma categoria ele acha, se eu digito uma cidade ele acha, porem, se eu digitar categoria e cidade ex: agencias são paulo  ele não retorna nada. Alguém pode me ajudar?
Estou utilizando PDO
<?php
include("conexao.php");

$pesquisa = $_POST["pesquisa"];

$cidades = $conn->prepare("SELECT * FROM edicao WHERE categoria LIKE ? OR cidade LIKE ? ");
$cidades->bindValue(1, "%" . $pesquisa . "%");
$cidades->bindValue(2, "%" . $pesquisa . "%");
$cidades->execute();

$resultado = $cidades->fetchAll();

if (!empty($pesquisa)) {

    foreach ($resultado as $uf_s) {
        ?>

                    <?php
                    echo "
 " . $uf_s['nomefantazia'] . "
";
                    ?>

Categoria: <?php echo $uf_s['categoria'] . ''; ?>

SubCategoria: <?php echo $uf_s['subcategoria'] . ''; ?>

Segmentação:  <?php echo $uf_s['segmentacao'] . ''; ?>

Dados

                    Telefone: <?php echo $uf_s['telefone'] . ''; ?>

                    Cidade: <?php echo $uf_s['cidade'] . ''; ?>

                    Bairro: <?php echo $uf_s['bairro'] . ''; ?>

                    Endereço: <?php echo $uf_s['endereco'] . ''; ?>

                    <?php
                    if (!isset($uf_s['logo'])) {
                        ?>

                        <?php
                    } else {
                        ?>
                        <img src="<?php echo substr($uf_s['logo'], 1); ?>" style="width: 100%;">
                        <?php
                    }
                    ?>

                    <?php
                    echo ""
                    ?>

Saiba Mais...

        <?php
    }
} else {
    echo '
 Informe sua pesquisa no campo acima
';
}
?>

Comment: Poste todo o seu código para a pesquisa por favor
Comment: Se são dois campos em sua tabela então você tem que informar dois valores, um valor para categoria e outro valor para cidade. Da maneira como fez você está informando um único valor e utilizando este valor para comparar os dois campos de sua tabela.
Answer: Da maneira que esta realizando sua pesquisa esta passando o mesmo valor para as duas coluna, ou seja, nunca vai encontrar a categoria junto com a cidade. Uma solução seria criar uma nova tabela em seu select.
SQL em MYSQL:
SELECT *

  FROM
    (SELECT edicao.campo1, edicao.campo2, edicao.campo3, concat(categoria,' ', cidade) as categoria_cidade FROM edicao) nova_edicao
 WHERE nova_edicao.categoria_cidade LIKE "%agencias são paulo%"

Desta maneira as duas colunas estão unidas e poderá buscar nas duas colunas ao mesmo tempo.
Comment: muito obrigado , porem sou iniciante poderia explicar de uma forma mais fácil agradeço

Busca de duas colunas no banco de dados


Copy a file in a sane, safe and efficient way

Question: I search for a good way to copy a file (binary or text). I've written several samples, everyone works. But I want hear the opinion of seasoned programmers.
I missing good examples and search a way which works with C++.
ANSI-C-WAY
#include <iostream>
#include <cstdio>    // fopen, fclose, fread, fwrite, BUFSIZ
#include <ctime>
using namespace std;

int main() {
    clock_t start, end;
    start = clock();

    // BUFSIZE default is 8192 bytes
    // BUFSIZE of 1 means one chareter at time
    // good values should fit to blocksize, like 1024 or 4096
    // higher values reduce number of system calls
    // size_t BUFFER_SIZE = 4096;

    char buf[BUFSIZ];
    size_t size;

    FILE* source = fopen("from.ogv", "rb");
    FILE* dest = fopen("to.ogv", "wb");

    // clean and more secure
    // feof(FILE* stream) returns non-zero if the end of file indicator for stream is set

    while (size = fread(buf, 1, BUFSIZ, source)) {
        fwrite(buf, 1, size, dest);
    }

    fclose(source);
    fclose(dest);

    end = clock();

    cout << "CLOCKS_PER_SEC " << CLOCKS_PER_SEC << "\n";
    cout << "CPU-TIME START " << start << "\n";
    cout << "CPU-TIME END " << end << "\n";
    cout << "CPU-TIME END - START " << end - start << "\n";
    cout << "TIME(SEC) " << static_cast<double>(end - start) / CLOCKS_PER_SEC << "\n";

    return 0;
}

POSIX-WAY (K&R use this in "The C programming language", more low-level)
#include <iostream>
#include <fcntl.h>   // open
#include <unistd.h>  // read, write, close
#include <cstdio>    // BUFSIZ
#include <ctime>
using namespace std;

int main() {
    clock_t start, end;
    start = clock();

    // BUFSIZE defaults to 8192
    // BUFSIZE of 1 means one chareter at time
    // good values should fit to blocksize, like 1024 or 4096
    // higher values reduce number of system calls
    // size_t BUFFER_SIZE = 4096;

    char buf[BUFSIZ];
    size_t size;

    int source = open("from.ogv", O_RDONLY, 0);
    int dest = open("to.ogv", O_WRONLY | O_CREAT /*| O_TRUNC/**/, 0644);

    while ((size = read(source, buf, BUFSIZ)) > 0) {
        write(dest, buf, size);
    }

    close(source);
    close(dest);

    end = clock();

    cout << "CLOCKS_PER_SEC " << CLOCKS_PER_SEC << "\n";
    cout << "CPU-TIME START " << start << "\n";
    cout << "CPU-TIME END " << end << "\n";
    cout << "CPU-TIME END - START " << end - start << "\n";
    cout << "TIME(SEC) " << static_cast<double>(end - start) / CLOCKS_PER_SEC << "\n";

    return 0;
}

KISS-C++-Streambuffer-WAY
#include <iostream>
#include <fstream>
#include <ctime>
using namespace std;

int main() {
    clock_t start, end;
    start = clock();

    ifstream source("from.ogv", ios::binary);
    ofstream dest("to.ogv", ios::binary);

    dest << source.rdbuf();

    source.close();
    dest.close();

    end = clock();

    cout << "CLOCKS_PER_SEC " << CLOCKS_PER_SEC << "\n";
    cout << "CPU-TIME START " << start << "\n";
    cout << "CPU-TIME END " << end << "\n";
    cout << "CPU-TIME END - START " <<  end - start << "\n";
    cout << "TIME(SEC) " << static_cast<double>(end - start) / CLOCKS_PER_SEC << "\n";

    return 0;
}

COPY-ALGORITHM-C++-WAY
#include <iostream>
#include <fstream>
#include <ctime>
#include <algorithm>
#include <iterator>
using namespace std;

int main() {
    clock_t start, end;
    start = clock();

    ifstream source("from.ogv", ios::binary);
    ofstream dest("to.ogv", ios::binary);

    istreambuf_iterator<char> begin_source(source);
    istreambuf_iterator<char> end_source;
    ostreambuf_iterator<char> begin_dest(dest);
    copy(begin_source, end_source, begin_dest);

    source.close();
    dest.close();

    end = clock();

    cout << "CLOCKS_PER_SEC " << CLOCKS_PER_SEC << "\n";
    cout << "CPU-TIME START " << start << "\n";
    cout << "CPU-TIME END " << end << "\n";
    cout << "CPU-TIME END - START " <<  end - start << "\n";
    cout << "TIME(SEC) " << static_cast<double>(end - start) / CLOCKS_PER_SEC << "\n";

    return 0;
}

OWN-BUFFER-C++-WAY
#include <iostream>
#include <fstream>
#include <ctime>
using namespace std;

int main() {
    clock_t start, end;
    start = clock();

    ifstream source("from.ogv", ios::binary);
    ofstream dest("to.ogv", ios::binary);

    // file size
    source.seekg(0, ios::end);
    ifstream::pos_type size = source.tellg();
    source.seekg(0);
    // allocate memory for buffer
    char* buffer = new char[size];

    // copy file
    source.read(buffer, size);
    dest.write(buffer, size);

    // clean up
    delete[] buffer;
    source.close();
    dest.close();

    end = clock();

    cout << "CLOCKS_PER_SEC " << CLOCKS_PER_SEC << "\n";
    cout << "CPU-TIME START " << start << "\n";
    cout << "CPU-TIME END " << end << "\n";
    cout << "CPU-TIME END - START " <<  end - start << "\n";
    cout << "TIME(SEC) " << static_cast<double>(end - start) / CLOCKS_PER_SEC << "\n";

    return 0;
}

LINUX-WAY // requires kernel >= 2.6.33
#include <iostream>
#include <sys/sendfile.h>  // sendfile
#include <fcntl.h>         // open
#include <unistd.h>        // close
#include <sys/stat.h>      // fstat
#include <sys/types.h>     // fstat
#include <ctime>
using namespace std;

int main() {
    clock_t start, end;
    start = clock();

    int source = open("from.ogv", O_RDONLY, 0);
    int dest = open("to.ogv", O_WRONLY | O_CREAT /*| O_TRUNC/**/, 0644);

    // struct required, rationale: function stat() exists also
    struct stat stat_source;
    fstat(source, &stat_source);

    sendfile(dest, source, 0, stat_source.st_size);

    close(source);
    close(dest);

    end = clock();

    cout << "CLOCKS_PER_SEC " << CLOCKS_PER_SEC << "\n";
    cout << "CPU-TIME START " << start << "\n";
    cout << "CPU-TIME END " << end << "\n";
    cout << "CPU-TIME END - START " <<  end - start << "\n";
    cout << "TIME(SEC) " << static_cast<double>(end - start) / CLOCKS_PER_SEC << "\n";

    return 0;
}

Environment

GNU/LINUX (Archlinux)
Kernel 3.3
GLIBC-2.15, LIBSTDC++ 4.7 (GCC-LIBS), GCC 4.7, Coreutils 8.16
Using RUNLEVEL 3 (Multiuser, Network, Terminal, no GUI)
INTEL SSD-Postville 80 GB, filled up to 50%
Copy a 270 MB OGG-VIDEO-FILE

Steps to reproduce
 1. $ rm from.ogg
 2. $ reboot                           # kernel and filesystem buffers are in regular
 3. $ (time ./program) &>> report.txt  # executes program, redirects output of program and append to file
 4. $ sha256sum *.ogv                  # checksum
 5. $ rm to.ogg                        # remove copy, but no sync, kernel and fileystem buffers are used
 6. $ (time ./program) &>> report.txt  # executes program, redirects output of program and append to file

Results (CPU TIME used)
Program  Description                 UNBUFFERED|BUFFERED
ANSI C   (fread/frwite)                 490,000|260,000
POSIX    (K&R, read/write)              450,000|230,000
FSTREAM  (KISS, Streambuffer)           500,000|270,000
FSTREAM  (Algorithm, copy)              500,000|270,000
FSTREAM  (OWN-BUFFER)                   500,000|340,000
SENDFILE (native LINUX, sendfile)       410,000|200,000

Filesize doesn't change.
sha256sum print the same results.
The video file is still playable.
Questions

What method would you prefer?
Do you know better solutions?
Do you see any mistakes in my code?
Do you know a reason to avoid a solution?
FSTREAM (KISS, Streambuffer)
I really like this one, because it is really short and simple. As far is I know the operator << is overloaded for rdbuf() and doesn't convert anything. Correct?

Thanks
Update 1
I changed the source in all samples in that way, that the open and close of the file descriptors is include in the measurement of clock(). Their are no other significant changes in the source code. The results doesn't changed! I also used time to double-check my results.
Update 2
ANSI C sample changed: The condition of the while-loop doesn't call any longer feof() instead I moved fread() into the condition. It looks like, the code runs now 10,000 clocks faster.
Measurement changed: The former results were always buffered, because I repeated the old command line rm to.ogv && sync && time ./program for each program a few times. Now I reboot the system for every program. The unbuffered results are new and show no surprise. The unbuffered results didn't changed really.
If i don't delete the old copy, the programs react different. Overwriting a existing file buffered is faster with POSIX and SENDFILE, all other programs are slower. Maybe the options truncate or create have a impact on this behaviour. But overwriting existing files with the same copy is not a real world use-case.
Performing the copy with cp takes 0.44 seconds unbuffered und 0.30 seconds buffered. So cp is a little bit slower than the POSIX sample. Looks fine for me.
Maybe I add also samples and results of mmap() and copy_file() from boost::filesystem.
Update 3
I've put this also on a blog page and extended it a little bit. Including splice(), which is a low-level function from the Linux kernel. Maybe more samples with Java will follow.
http://www.ttyhoney.com/blog/?page_id=69
Comment: You forgot the lazy way: system("cp from.ogv to.ogv");
Comment: `fstream` definitely is a good option for file operations.
Comment: Sorry for chipping in so late, but I would describe none of these as 'safe', as they don't have any error handling.
Comment: `#include
copyfile(const char *from, const char *to, copyfile_state_t state, copyfile_flags_t flags);`
Comment: http://www.richelbilderbeek.nl/CppCopy_file.htm
Comment: Why are you only taking the time to copy the files, and not the open/close time?  If you're doing a number of iterations of this, the startup/shutdown time for each time you copy something could matter quite a lot.
Comment: I'd say to use [`boost::filesystem::copy_file`](http://www.boost.org/doc/libs/1_49_0/libs/filesystem/v3/doc/reference.html#copy_file).
Comment: Personally, I would decide only after adding error handling to each example and comparing the added code:  outright performance is obviously a big factor in deciding what to do, but it usually shouldn't be the **only** factor.
Comment: The blog page no longer exists. Is your article still available somewhere?
Comment: @AndrewHenle: I'm sorry, but the man-page says that it is allowed to pass [0|NULL|nullptr] and sendfile will start at the offset (the start of the file in this case).
Comment: @KeithM: To be honest, your suggestion sounds rather theoretical and changing this words wouldn't improve something. Because I don't maintain my blog anymore and the list of examples is missing *splice()* (which is neat) I looking forward to add *splice()* and try to merge this complete thing to the new documentation site, I think this would be really a good way. Please bear with me :)
Comment: I don't like the lazy way. Thats why I don't mention it. It is ugly. On the other hand, the code in coreutils is long tested and proven.
Comment: You are right Kevin. I changed the samples in this way with the update. My previous intention was, that the "file is already" accessed by the user and to monitor only the copy-progress itself. But the open/close of filedescriptor is a part of the copy-progress!
Comment: Could you please fix the "units" of the timing results.  "Clocks per second" makes no sense, that's a measure of processor clock speed, not anything to do with I/O.  Did you mean "clocks per file"?
Comment: I've changed the description to "CPU TIME", often refered also als "CPU TICKS". This matches the description of the man page of clock(). Better?
Comment: Currently not. I will set up the blog again within the next weeks.
Comment: If source is empty, then writing it's rdbuf will result in the failbit being set on the destination stream.  For this reason, you might prefer std::copy as a default C++ portable approach (if you intend to write other things to the destination stream).
Comment: The `sendfile` example is wrong.  [`sendfile` is declared as](http://man7.org/linux/man-pages/man2/sendfile.2.html) `ssize_t sendfile(int out_fd, int in_fd, off_t *offset, size_t count);`.  Note that the third argument is `off_t *offset`.  So `sendfile(dest, source, 0, stat_source.st_size);` will probably result in `SIGSEGV`.
Comment: @Peter `What method would you prefer? Do you know better solutions?` took this otherwise great question in an opinion-based direction, since preference and the ill-defined "better" is subjective (did you mean "faster"?). Questions like "What other methods exist? What are their advantages and disadvantages?" (like your `Do you know a reason to avoid a solution?`) is more appropriate for SO.
Comment: @Peter Theoretical how? Perhaps you missed my point; I'm saying that you're asking opinion-based questions, which is off-topic for Stack Overflow. The current answers are not opinions, so merely removing those two questions would improve this Q&A.
Comment: Measuring the CPU time of an I/O-bound operation is pointless. The only time of interest is the elapsed time by the wall clock.
Comment: The sendfile example will fail on files larger than 2GB
Comment: I think that one of the requirements should also be preserving the metadata (time, permissions, etc.) of the original file.
Answer: Copy a file in a sane way:
#include <fstream>

int main()
{
    std::ifstream  src("from.ogv", std::ios::binary);
    std::ofstream  dst("to.ogv",   std::ios::binary);

    dst << src.rdbuf();
}

This is so simple and intuitive to read it is worth the extra cost. If we were doing it a lot, better to fall back on OS calls to the file system. I am sure boost has a copy file method in its filesystem class.
There is a C method for interacting with the file system:
#include <copyfile.h>

int
copyfile(const char *from, const char *to, copyfile_state_t state, copyfile_flags_t flags);

Comment: `copyfile` is not portable; I think it's specific to Mac OS X. It certainly doesn't exist on Linux. `boost::filesystem::copy_file` is probably the most portable way to copy a file via the native file system.
Comment: @duedl0r: No. Objects have destructors. The destructor for streams automatically call close(). http://codereview.stackexchange.com/q/540/507
Comment: @duedl0r: Yes. But that's like saying "if the sun sets". You can run really fast west and you may make your day slightly longer but the sun is going to set. Unless you have bug and leak memory (it will go out of scope). But since there is no dynamic memory management here there can not be a leak and they will go out of scope (just like the sun will set).
Comment: Then simply wrap it in a { } scope block
Comment: @MikeSeymour: copyfile() seems to be a BSD extension.
Comment: `src.close(); dst.close();` ?
Comment: @MillieSmith: It does not need to. The C++ standard says that if the main function does not end in a return then the compiler will plant the `return 0;` for you. Also; it is common practice to leave out that return as an indication, to other developers, that the application can not fail (ie you always return the success status code back to the OS).
Comment: **Warning:** `dst << src.rdbuf();` will set `failbit` on `dst` if `src` is an empty file. [www.cplusplus.com:operator<<](http://www.cplusplus.com/reference/ostream/ostream/operator%3C%3C/): Sets failbit if ... For (2), it is set if no characters could be extracted from the object pointed by sb.
Comment: That's his KISS streambuffer C++ way.  It's the most natural way for a C++ programmer (although using `std::copy` is also pretty idiomatic).  And since the two idiomatic ways also happen to be the fastest portable ways...
Comment: @Vincent: Yes. See: http://stackoverflow.com/questions/12766636/difference-in-using-read-write-when-stream-is-opened-with-without-iosbinary-mo/12766972#comment17265240_12766972
Comment: @LokiAstari, that's great, although I just found that std::ios::binary is necessary for correct file copying on windows.
Comment: @mangledorf: No because C++ has no concept of a file system. For that you must use a library. The library you use will depend on the system you use (unless you use a lib to abstract the file system (like boost::filesystem)).
Comment: @LokiAstari: despite all the appeal of the "sun sets" analogy, a function may want to copy a file then start doing some time-consuming task - most extreme example: a copy atop `main()` before entering a daemon/server mode.  Still - how/when to handle that is obviously going to be well understood by the person posting the question.
Comment: Don't forget to `#include `
Comment: @AlecJacobson C++17 has [`std::filesystem::permissions`](http://en.cppreference.com/w/cpp/experimental/fs/permissions).
Comment: @yusufX019 `if (dst << src.rdbuf()){std::cout << "Worked\n";}`
Comment: Seems that Loki is right. The function copyfile() seems to be an extension for *BSD and Mac OS.
Comment: @PeterWeber: I would not say Mac OS. Mac OS is a BSD implementation.
Comment: I'm just careful. I know some people want not call Mac OS a UNIX.
Comment: Is the operator '<<' ok for binary files ?
Comment: Copying a file correctly on Windows is ridiculously difficult to get right, unless you delegate the whole thing to Windows by saying `CopyFile`.
Comment: Beware that Boost copy_file does not work correctly in v 1.40.0
Comment: @LokiAstari: yes, if they go out of scope.
Comment: Is there an equivalently simple way of copying permissions, too?
Comment: @mangledorf: Not at the language level. The language does not have a concept of "File Systems" let alone permission. You will need to use OS or "File system" specific API to achieve that.
Comment: @Loki, do you know of a more C++ way of dealing with POSIX permissions than fchown/fstat (e.g. http://stackoverflow.com/a/5486922/148668)
Comment: Not only is `copyfile` not portable and macOS-specific, but it's also sub-optimal in that you cannot set the block size. **MacOS itself doesn't even use it,** which you can demonstrate yourself by doing a drag&drop of a bunch of photo/video/audio files in Finder and then trying the same operation with `copyfile`. You'll find it's significantly slower. We found this out at our company and now need to roll our own version of it to meet the performance of drag&drop.
Comment: @Anachronist `copyfile()` has nothing to do with the mac. It's a BSD extension (as we noted 10 years ago in the comments above). If you are writing drag/drop; an OS level feature; you should be working with OS level features to do the copy (this question is nothing to do with kind of functionality). Look at your OS file system features to do the copy in this type of situation.
Comment: @Anachronist Look at: [filesystem/copy](https://en.cppreference.com/w/cpp/filesystem/copy) is now part of the standard (so should be portable). Note there is a difference between copying files at the file system level (which copies blocks) and reading and writing a file which requires the content to be streamed through the application. I actually put this as part of the answer ten years ago: `better to fall back on OS calls to the file system`
Comment: @MartinYork -- google for a copyfile man page and all you find is macOS information. Yes, it's a BSD extension, but it seems to be most prevalent (or now exclusive to) macOS. I have no argument with your other points (and thanks for the link to filesystem/copy) but my original points still stand: macOS doesn't appear to use copyfile for data movement, it and it's significantly slower than whatever macOS does.
Comment: @Anachronist `copyfile()` calls need the `COPYFILE_CLONE` flag to be as fast as Finder.
Comment: With the first method you mentioned. How can I check that "dst << src.rdbuf();" operation was successfull ? Can you also suggest any other methods of making sure that files are the same except checking by md5sum or any other algorithm of this kind?
Answer: With C++17 the standard way to copy a file will be including the <filesystem> header and using:
bool copy_file( const std::filesystem::path& from,
                const std::filesystem::path& to);

bool copy_file( const std::filesystem::path& from,
                const std::filesystem::path& to,
                std::filesystem::copy_options options);

The first form is equivalent to the second one with copy_options::none used as options (see also copy_file).
The filesystem library was originally developed as boost.filesystem and finally merged to ISO C++ as of C++17.
Comment: Why there's not a single function with a default argument, like `bool copy_file( const std::filesystem::path& from,
                const std::filesystem::path& to,
                std::filesystem::copy_options options = std::filesystem::copy_options::none);`?
Comment: @Jepessen I'm not sure about this. Maybe it [doesn't really matter](https://stackoverflow.com/q/5031856/3235496).
Comment: @Jepessen in the standard library, clean code is paramount. Having overloads (as opposed to one function with default parameters) makes the programmer's intention more clear.
Comment: @Peter This should now probably be the accepted answer given that C++17 is available.
Answer: Too many!
The "ANSI C" way buffer is redundant, since a FILE is already buffered. (The size of this internal buffer is what BUFSIZ actually defines.)
The "OWN-BUFFER-C++-WAY" will be slow as it goes through fstream, which does a lot of virtual dispatching, and again maintains internal buffers or each stream object. (The "COPY-ALGORITHM-C++-WAY" does not suffer this, as the streambuf_iterator class bypasses the stream layer.)
I prefer the "COPY-ALGORITHM-C++-WAY", but without constructing an fstream, just create bare std::filebuf instances when no actual formatting is needed.
For raw performance, you can't beat POSIX file descriptors. It's ugly but portable and fast on any platform.
The Linux way appears to be incredibly fast — perhaps the OS let the function return before I/O was finished? In any case, that's not portable enough for many applications.
EDIT: Ah, "native Linux" may be improving performance by interleaving reads and writes with asynchronous I/O. Letting commands pile up can help the disk driver decide when is best to seek. You might try Boost Asio or pthreads for comparison. As for "can't beat POSIX file descriptors"… well that's true if you're doing anything with the data, not just blindly copying.
Comment: "`sendfile()` copies data between one file descriptor and another.  Because this copying is done within the kernel, `sendfile()` is more efficient than the combination of `read(2)` and `write(2)`, which would require transferring data to and from user space.":  http://www.kernel.org/doc/man-pages/online/pages/man2/sendfile.2.html
Comment: I have not a in-depth understanding of this, so I should be careful with assumptions and opinions. Linux-Way runs in Kernelspace afaik. This should avoid slow Context-Switching between Kernelspace and Userspace? Tomorrow I will take again a look at the manpage of sendfile. A while ago Linus Torvalds said he doesn't like Userspace-Filesystems for heavy jobs. Maybe sendfile is a positive example for his view?
Comment: Could you post an example of using raw `filebuf` objects?
Comment: ANSI C: But I have to give the function fread/fwrite a size? http://pubs.opengroup.org/onlinepubs/9699919799/toc.htm
Comment: @PeterWeber Well, yes, it's true that BUFSIZ is as good a value as any, and will probably speed things up relative to one or "just a few" characters at a time. Anyway, the performance measurement bears out that it's not the best method in any case.
Answer: I want to make the very important note that the LINUX method using sendfile() has a major problem in that it can not copy files more than 2GB in size! I had implemented it following this question and was hitting problems because I was using it to copy HDF5 files that were many GB in size.
http://man7.org/linux/man-pages/man2/sendfile.2.html

sendfile() will transfer at most 0x7ffff000 (2,147,479,552) bytes,
  returning the number of bytes actually transferred.  (This is true on
  both 32-bit and 64-bit systems.)
Comment: @Paladin It seems that sendfile64 was developed to get around this limitation. From the man page:

"""The original Linux sendfile() system call was not designed to handle large file offsets. Consequently, Linux 2.4 added sendfile64(), with a wider type for the offset argument. The glibc sendfile() wrapper function transparently deals with the kernel differences."""
Comment: does sendfile64() have same problem?
Comment: [sendfile64 has the same issue](https://stackoverflow.com/questions/22373528/sendfile64-only-copy-about-2gb) it seems. However the use of the offset type `off64_t` allows one to use a loop to copy large files as shown [in an answer](https://stackoverflow.com/a/22374134/1543768) to the linked question.
Comment: this is wirtten in man : 'Note that a successful call to sendfile() may write fewer bytes than requested; the caller should be prepared to retry the call if there were unsent bytes.' sendfile or sendfile64 might require to be called within a loop until full copy is done.
Answer: Qt has a method for copying files:
#include <QFile>
QFile::copy("originalFile.example","copiedFile.example");

Note that to use this you have to install Qt (instructions here) and include it in your project (if you're using Windows and you're not an administrator, you can download Qt here instead). Also see this answer.
Comment: `QFile::copy` is ridiculously slow due to it's [4k buffering](https://stackoverflow.com/questions/39485537/qt-qfile-copy-operation-extremely-slow).
Comment: The slowness has been fixed in newer versions of `Qt`. I am using `5.9.2` and the speed is on par with the native implementation. Btw. taking a look at the source code, Qt seems to actually call the native implementation.
Answer: For those who like boost:
boost::filesystem::path mySourcePath("foo.bar");
boost::filesystem::path myTargetPath("bar.foo");

// Variant 1: Overwrite existing
boost::filesystem::copy_file(mySourcePath, myTargetPath, boost::filesystem::copy_option::overwrite_if_exists);

// Variant 2: Fail if exists
boost::filesystem::copy_file(mySourcePath, myTargetPath, boost::filesystem::copy_option::fail_if_exists);

Note that boost::filesystem::path is also available as wpath for Unicode. And that you could also use
using namespace boost::filesystem

if you do not like those long type names
Comment: Boost's filesystem library is one of the exceptions that requires it to be compiled. Just FYI!
Answer: I'm not quite sure what a "good way" of copying a file is, but assuming "good" means "fast", I could broaden the subject a little.
Current operating systems have long been optimized to deal with run of the mill file copy. No clever bit of code will beat that. It is possible that some variant of your copy techniques will prove faster in some test scenario, but they most likely would fare worse in other cases.
Typically, the sendfile function probably returns before the write has been committed, thus giving the impression of being faster than the rest. I haven't read the code, but it is most certainly because it allocates its own dedicated buffer, trading memory for time. And the reason why it won't work for files bigger than 2Gb.
As long as you're dealing with a small number of files, everything occurs inside various buffers (the C++ runtime's first if you use iostream, the OS internal ones, apparently a file-sized extra buffer in the case of sendfile). Actual storage media is only accessed once enough data has been moved around to be worth the trouble of spinning a hard disk.
I suppose you could slightly improve performances in specific cases. Off the top of my head:

If you're copying a huge file on the same disk, using a buffer bigger than the OS's might improve things a bit (but we're probably talking about gigabytes here).
If you want to copy the same file on two different physical destinations you will probably be faster opening the three files at once than calling two copy_file sequentially (though you'll hardly notice the difference as long as the file fits in the OS cache)
If you're dealing with lots of tiny files on an HDD you might want to read them in batches to minimize seeking time (though the OS already caches directory entries to avoid seeking like crazy and tiny files will likely reduce disk bandwidth dramatically anyway).

But all that is outside the scope of a general purpose file copy function.
So in my arguably seasoned programmer's opinion, a C++ file copy should just use the C++17 file_copy dedicated function, unless more is known about the context where the file copy occurs and some clever strategies can be devised to outsmart the OS.
Answer: The simplest way in C++17 and later is:
Use the #include <filesystem> and copy() method. There are 4 overloads for the copy method. You can check that in this link
void copy( const std::filesystem::path& from,

           const std::filesystem::path& to );
void copy( const std::filesystem::path& from,
           const std::filesystem::path& to,
           std::error_code& ec );

void copy( const std::filesystem::path& from,

           const std::filesystem::path& to,
           std::filesystem::copy_options options );

void copy( const std::filesystem::path& from,
           const std::filesystem::path& to,
           std::filesystem::copy_options options,
           std::error_code& ec );

With copy() method can copy files and directories with some options like recursive, non-recursive, copy only directories or overwrite or skip existing files, and so on. you can read more about copy options in this link
This is a sample code from here with some edit:
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <filesystem>
namespace fs = std::filesystem;

int main()
{
    // create directories. create all directories if not exist.
    fs::create_directories("sandbox/dir/subdir");

    // create file with content 'a'
    std::ofstream("sandbox/file1.txt").put('a');

    // copy file
    fs::copy("sandbox/file1.txt", "sandbox/file2.txt");

    // copy directory (non-recursive)
    fs::copy("sandbox/dir", "sandbox/dir2");

    // copy directory (recursive)
    const auto copyOptions = fs::copy_options::update_existing
                           | fs::copy_options::recursive
                           ;
    fs::copy("sandbox", "sandbox_copy", copyOptions);

    // remove sanbox directory and all sub directories and sub files.
    fs::remove_all("sandbox");
}

Answer: Update
The most convenient and efficient way to copy files on Unix platforms is to use the sendfile system call, which internally uses a memory map to copy the file entirely in kernel mode. Note that sendfile can only copy 2GB at a time, so we should use it in a loop.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/sendfile.h>
#include <sys/stat.h>

int main(int argc, char **argv) {
    if (argc != 3) {
        fprintf(stderr, "usage: %s <source> <target>\n", argv[0]);
        return EXIT_FAILURE;
    }
    int source_fd = open(argv[1], O_RDONLY, 0);
    if (source_fd < 0) {
        perror("open source");
        return EXIT_FAILURE;
    }
    int target_fd = open(argv[2], O_RDWR | O_CREAT | O_TRUNC, 0666);
    if (target_fd < 0) {
        perror("open target");
        return EXIT_FAILURE;
    }
    struct stat stat;
    int r = fstat(source_fd, &stat);
    if (r < 0) {
        perror("fstat");
        return EXIT_FAILURE;
    }
    off_t offset = 0;
    ssize_t bytes_sent = 0;
    ssize_t total_bytes_sent = 0;
    while (offset < stat.st_size) {
        bytes_sent = sendfile(target_fd, source_fd, &offset, stat.st_size - offset);
        total_bytes_sent += bytes_sent;
        if (bytes_sent < 0) {
            perror("sendfile");
            return EXIT_FAILURE;
        }
    }
    if (total_bytes_sent != stat.st_size) {
        fprintf(stderr, "sendfile: copied file truncated to %zd bytes\n", bytes_sent);
        return EXIT_FAILURE;
    } else {
        printf("sendfile: %zd bytes copied\n", total_bytes_sent);
    }
    close(source_fd);
    close(target_fd);
    return EXIT_SUCCESS;
}

Copying a roughly 3.2GB file, the time usage is:
real    0m1.894s
user    0m0.000s
sys     0m1.880s

Here is a Python version:
import sys
import os

if len(sys.argv) != 3:
    print(f'Usage: {sys.argv[0]} <source> <destination>')
    sys.exit(1)

with open(sys.argv[1], 'rb') as src, open(sys.argv[2], 'wb') as dst:
    total_bytes_sent = 0
    while total_bytes_sent < os.path.getsize(sys.argv[1]):
        bytes_sent = os.sendfile(dst.fileno(), src.fileno(), offset=None, count=2**31-1)
        total_bytes_sent += bytes_sent
    print(f"{total_bytes_sent} bytes written")

Copying a roughly 3.2GB file, the time usage is:
real    0m2.015s
user    0m0.010s
sys     0m1.973s

The most convenient and efficient way to copy files on Windows is to use the CopyFile API. The real time and the sys time are incredibly low. Maybe it is optimized by calling low-level driver functions performing async DMA because the result is constant when the source and destination drives have different file systems, and when I copy the file from a slow USB 2.0 HDD, the sys time is not fully recorded.
#include <stdio.h>
#include <windows.h>

void PrintLastError(const char *name) {
    char *msg;
    FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
        NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (char *) &msg, 0, NULL);
    fprintf(stderr, "%s failed: %s", name, msg);
    LocalFree(msg);
    exit(EXIT_FAILURE);
}

int main(int argc, char *argv[]) {
    if (argc != 3) {
        printf("Usage: %s <source> <destination>\n", argv[0]);
        return 1;
    }
    if (!CopyFileA(argv[1], argv[2], TRUE)) {
        PrintLastError("CopyFile");
    }
    return EXIT_SUCCESS;
}

Copying a roughly 3.2GB file at a local SSD, the time usage measured by my timing tool is:
real    0.894460s
user    0.000000s
sys     0.734375s

Copying a roughly 3.2GB file from a slow USB 2.0 HDD, the time usage measured by my timing tool is:
real    90.149947s
user    0.015625s
sys     1.328125s

In theory, the most efficient way to copy files is to use a memory map, so the copying process can be done entirely in kernel mode.
If the file is smaller than 2GB, you can use the following code on Unix platforms:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>

int main(int argc, char **argv) {
    if (argc != 3) {
        fprintf(stderr, "usage: %s <source> <target>\n", argv[0]);
        return EXIT_FAILURE;
    }
    int source_fd = open(argv[1], O_RDONLY, 0);
    if (source_fd < 0) {
        perror("open source");
        return EXIT_FAILURE;
    }
    int target_fd = open(argv[2], O_RDWR | O_CREAT | O_TRUNC, 0666);
    if (target_fd < 0) {
        perror("open target");
        return EXIT_FAILURE;
    }
    struct stat stat;
    int r = fstat(source_fd, &stat);
    if (r < 0) {
        perror("fstat");
        return EXIT_FAILURE;
    }
    char *buf = mmap(NULL, stat.st_size, PROT_READ, MAP_PRIVATE, source_fd, 0);
    if (buf == MAP_FAILED) {
        perror("mmap");
        return EXIT_FAILURE;
    }
    r = write(target_fd, buf, stat.st_size);
    if (r < 0) {
        perror("write");
        return EXIT_FAILURE;
    } else if (r != stat.st_size) {
        fprintf(stderr, "write: copied file truncated to %d bytes\n", r);
        return EXIT_FAILURE;
    } else {
        printf("write: %d bytes copied\n", r);
    }
    munmap(buf, stat.st_size);
    close(source_fd);
    close(target_fd);
    return EXIT_SUCCESS;
}

Copying a roughly 2GB file, the time usage is:
real    0m1.457s
user    0m0.000s
sys     0m1.451s

But if the file size is larger than 2GB, write() will truncate the file to 2GB, so it cannot be used. We must map the destination file and use memcpy to copy the file. Since memcpy is used, we can see there is time spent in user mode.
Here is a universal version:
import sys
import mmap

if len(sys.argv) != 3:
    print(f'Usage: {sys.argv[0]} <source> <destination>')
    sys.exit(1)

with open(sys.argv[1], 'rb') as src, open(sys.argv[2], 'wb') as dst:
    mmapped_src = mmap.mmap(src.fileno(), 0, access=mmap.ACCESS_READ)
    print(f"{dst.write(mmapped_src)} bytes written")
    mmapped_src.close()

Copying a roughly 3.2GB file, the time usage on Linux is:
real    0m2.050s
user    0m0.010s
sys     0m2.012s

Copying a roughly 3.2GB file, the time usage measured by my timing tool on Windows is:
real    3.520454s
user    0.031250s
sys     2.046875s

Here is a Unix version:
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/stat.h>

int main(int argc, char *argv[]) {
    int src_fd, dst_fd;
    void *src_map, *dst_map;
    struct stat src_stat;

    if (argc != 3) {
        printf("Usage: %s <source> <destination>\n", argv[0]);
        return 1;
    }

    src_fd = open(argv[1], O_RDONLY);
    if (src_fd == -1) {
        perror("open source");
        return 1;
    }

    if (fstat(src_fd, &src_stat) == -1) {
        perror("fstat");
        return 1;
    }

    src_map = mmap(NULL, src_stat.st_size, PROT_READ, MAP_PRIVATE, src_fd, 0);
    if (src_map == MAP_FAILED) {
        perror("mmap source");
        return 1;
    }

    dst_fd = open(argv[2], O_RDWR | O_CREAT | O_TRUNC, src_stat.st_mode);
    if (dst_fd == -1) {
        perror("open destination");
        return 1;
    }

    if (ftruncate(dst_fd, src_stat.st_size) == -1) {
        perror("ftruncate");
        return 1;
    }

    dst_map = mmap(NULL, src_stat.st_size, PROT_READ | PROT_WRITE, MAP_SHARED, dst_fd, 0);
    if (dst_map == MAP_FAILED) {
        perror("mmap destination");
        return 1;
    }

    memcpy(dst_map, src_map, src_stat.st_size);
    printf("Copied %ld bytes from %s to %s\n", src_stat.st_size, argv[1], argv[2]);

    munmap(src_map, src_stat.st_size);
    munmap(dst_map, src_stat.st_size);

    close(src_fd);
    close(dst_fd);

    return 0;
}

Copying a roughly 3.2GB file, the time usage is:
real    0m2.978s
user    0m0.639s
sys     0m2.325s

Here is a Windows version:
#include <stdio.h>
#include <windows.h>

void PrintLastError(const char *name) {
    char *msg;
    FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
        NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (char *) &msg, 0, NULL);
    fprintf(stderr, "%s failed: %s", name, msg);
    LocalFree(msg);
    exit(EXIT_FAILURE);
}

int main(int argc, char *argv[]) {
    HANDLE hSrc, hDst;
    HANDLE hSrcMap, hDstMap;
    LPVOID lpSrcMap, lpDstMap;
    DWORD dwSrcSize, dwDstSize;

    if (argc != 3) {
        printf("Usage: %s <source> <destination>\n", argv[0]);
        return 1;
    }

    hSrc = CreateFileA(argv[1], GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
    if (hSrc == INVALID_HANDLE_VALUE) {
        PrintLastError("CreateFile");
        return 1;
    }

    dwSrcSize = GetFileSize(hSrc, NULL);
    if (dwSrcSize == INVALID_FILE_SIZE) {
        PrintLastError("GetFileSize");
        goto SRC_MAP_FAIL;
    }

    hSrcMap = CreateFileMappingA(hSrc, NULL, PAGE_READONLY, 0, 0, NULL);
    if (hSrcMap == NULL) {
        PrintLastError("CreateFileMapping");
        goto SRC_MAP_FAIL;
    }

    lpSrcMap = MapViewOfFile(hSrcMap, FILE_MAP_READ, 0, 0, 0);
    if (lpSrcMap == NULL) {
        PrintLastError("MapViewOfFile");
        goto SRC_VIEW_FAIL;
    }

    hDst = CreateFileA(argv[2], GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
    if (hDst == INVALID_HANDLE_VALUE) {
        PrintLastError("CreateFile");
        goto DEST_OPEN_FAIL;
    }

    dwDstSize = dwSrcSize;
    hDstMap = CreateFileMappingA(hDst, NULL, PAGE_READWRITE, 0, dwDstSize, NULL);
    if (hDstMap == NULL) {
        PrintLastError("CreateFileMapping");
        goto DEST_MAP_FAIL;
    }

    lpDstMap = MapViewOfFile(hDstMap, FILE_MAP_WRITE, 0, 0, 0);
    if (lpDstMap == NULL) {
        PrintLastError("MapViewOfFile");
        goto DEST_VIEW_FAIL;
    }

    memcpy(lpDstMap, lpSrcMap, dwSrcSize);
    printf("Copied %lu bytes from %s to %s", dwSrcSize, argv[1], argv[2]);

    UnmapViewOfFile(lpDstMap);
DEST_VIEW_FAIL:
    CloseHandle(hDstMap);
DEST_MAP_FAIL:
    CloseHandle(hDst);
DEST_OPEN_FAIL:
    UnmapViewOfFile(lpSrcMap);
SRC_VIEW_FAIL:
    CloseHandle(hSrcMap);
SRC_MAP_FAIL:
    CloseHandle(hSrc);

    return 0;
}

Copying a roughly 3.2GB file, the time usage measured by my timing tool is:
real    3.223017s
user    0.906250s
sys     2.312500s

Comment: Could you explain why `write` does not work with file > 2 GiB (assuming `size_t` is large enough)? Also, why not just `mmap` the source file in small chunks (by specifying a a suitable offset) to circumvent this, rather than using `memcpy`? (Of course that version runs into race conditions if the file is modified during the copying process but I believe this is true for *all* versions: `mmap`ing the file does not lock it, does it? — Doing this would probably generally be a good idea)
Comment: Maybe `write` (and `sendfile`) internally uses a 32-bit signed `int`, so the maximum number it can represent is 2GB.


Why does this fibonacci sequence work? Can someone help me?

Question: Python beginner problem
(I am a beginner programmer)
So I was making a simple Fibonacci sequence generator and I made a working version, but I'm confused about how it works. In the code (lines 8-9), the first number (0) is being made the new value of the second value (1). But then that should make all the other numbers 0 as well, but it seems like the defining process is backward. Generally, the new value is on the left of the equal sign and the old value is on the right. But then that means everything should turn to 0. But actually, every number turns to 0 if I try to re-define the variables in the regular way (b = a; c = b). Why is this? I've attached my code at the bottom.
def seq_loop():
    a = 0
    b = 1

    for i in range(15):
        print(a)
        c = a + b
        a = b
        b = c

print(seq_loop())

Comment: What have you tried to check what this code does? If you set `b = 1`, why do you expect that it sets this variable to 0?
Comment: _"Generally, the new value is on the left of the equal sign and the old value is on the right."_ Seems like you have a major misunderstanding/incorrect assumption about how the `=` operator works, and that's the cause of your confusion.
Answer: Have a good look at your code.  Walk through it, and write down a,b and c in each iteration (or if you know how to use a debugger, set a break point in the loop te verify your variable's values).  You'll see that your thinking is not right:  in your first iteration: a = b is equivalent to a = 1 and b = c is equivalent to b = 1 + 1.
I am not sure that your interpretation of assignments is correct: An assignment goes right to left.  The value (of the variable) on the right side of = is assigned to the variable on the left side of =
Answer: I don't really understand what you are asking, but a good way to understand code is to simply execute it by hand with pen&paper and keep a list of all the variables in scope and their current values. So, let's do that now.
In the first line, we define and initialize the variable a to the value 0. Our variables in scope and their values are { a = 0 }.
In the second line, we define and initialize the variable b to the value 1. Our variables in scope and their values are { a = 0; b = 1 }.
In the first line of the loop, we print the current value of the variable a, which we can look up in our variable list is 0. We haven't assigned any variables, so our variables in scope are still unchanged: { a = 0; b = 1 }. And the console looks like this:
0

In the second line of the loop, we define and initialize the variable c to the result of evaluating the expression a + b. We have to dereference the two variables, i.e. look up their values in our list, and their values are 0 and 1. 0 + 1 is 1, which means we initialize c to 1. Our variables in scope and their values are { a = 0; b = 1; c = 1 }.
In the third line of the loop, we assign the variable a. The value we assign to the variable a is the current value of the variable b. So, we look at our variable list, and we see that the current value of b is 1, which means we assign 1 to a. Our variables in scope and their values are { a = 1; b = 1; c = 1 }.
In the fourth line of the loop, we assign the variable b. The value we assign to the variable b is the current value of the variable c. So, we look at our variable list, and we see that the current value of c is 1, which means we assign 1 to b. Our variables in scope and their values are { a = 1; b = 1; c = 1 }.
After the fourth line of the loop, the variable c goes out of scope. Our variables in scope and their values are now { a = 1; b = 1 }.
As you can see, we started the first iteration of the loop with { a = 1; b = 0 } but after the first iteration of the loop, we have { a = 1; b = 1 }, which is what we start the second iteration of the loop with. It is important that something has changed here, otherwise each iteration of the loop would do the same thing, and we would always get the same result.
So, let's look at the second iteration of the loop.
In the first line of the loop, we print the current value of the variable a, which we can look up in our variable list is 1. We haven't assigned any variables, so our variables in scope are still unchanged: { a = 1; b = 1 }. And the console looks like this:
0
1

In the second line of the loop, we define and initialize the variable c to the result of evaluating the expression a + b. We look up their values in our list, and their values are 1 and 1. 1 + 1 is 2, which means we initialize c to 2. Our variables in scope and their values are { a = 1; b = 1; c = 2 }.
In the third line of the loop, we assign the variable a. The value we assign to the variable a is the current value of the variable b. So, we look at our variable list, and we see that the current value of b is 1, which means we assign 1 to a. Our variables in scope and their values are { a = 1; b = 1; c = 2 }.
In the fourth line of the loop, we assign the variable b. The value we assign to the variable b is the current value of the variable c. So, we look at our variable list, and we see that the current value of c is 2, which means we assign 2 to b. Our variables in scope and their values are { a = 1; b = 2; c = 2 }.
After the fourth line of the loop, the variable c goes out of scope. Our variables in scope and their values are now { a = 1; b = 2 }.
Now for the third iteration.
In the first line of the loop, we print the current value of the variable a, which we can look up in our variable list is 1. We haven't assigned any variables, so our variables in scope are still unchanged: { a = 1; b = 2 }. And the console looks like this:
0
1
1

In the second line of the loop, we define and initialize the variable c to the result of evaluating the expression a + b. We look up their values in our list, and their values are 1 and 2. 1 + 2 is 3, which means we initialize c to 3. Our variables in scope and their values are { a = 1; b = 2; c = 3 }.
In the third line of the loop, we assign the variable a. The value we assign to the variable a is the current value of the variable b. So, we look at our variable list, and we see that the current value of b is 2, which means we assign 2 to a. Our variables in scope and their values are { a = 2; b = 2; c = 3 }.
In the fourth line of the loop, we assign the variable b. The value we assign to the variable b is the current value of the variable c. So, we look at our variable list, and we see that the current value of c is 3, which means we assign 3 to b. Our variables in scope and their values are { a = 2; b = 3; c = 3 }.
After the fourth line of the loop, the variable c goes out of scope. Our variables in scope and their values are now { a = 2; b = 3 }.
And this is the fourth iteration of the loop.
In the first line of the loop, we print the current value of the variable a, which we can look up in our variable list is 2. We haven't assigned any variables, so our variables in scope are still unchanged: { a = 2; b = 3 }. And the console looks like this:
0
1
1
2

In the second line of the loop, we define and initialize the variable c to the result of evaluating the expression a + b. We look up their values in our list, and their values are 2 and 3. 2 + 3 is 5, which means we initialize c to 5. Our variables in scope and their values are { a = 2; b = 3; c = 5 }.
In the third line of the loop, we assign the variable a. The value we assign to the variable a is the current value of the variable b. So, we look at our variable list, and we see that the current value of b is 3, which means we assign 3 to a. Our variables in scope and their values are { a = 3; b = 3; c = 5 }.
In the fourth line of the loop, we assign the variable b. The value we assign to the variable b is the current value of the variable c. So, we look at our variable list, and we see that the current value of c is 5, which means we assign 5 to b. Our variables in scope and their values are { a = 3; b = 5; c = 5 }.
After the fourth line of the loop, the variable c goes out of scope. Our variables in scope and their values are now { a = 3; b = 5 }.
Let's do one last iteration of the loop.
In the first line of the loop, we print the current value of the variable a, which we can look up in our variable list is 3. We haven't assigned any variables, so our variables in scope are still unchanged: { a = 3; b = 5 }. And the console looks like this:
0
1
1
2
3

In the second line of the loop, we define and initialize the variable c to the result of evaluating the expression a + b. We look up their values in our list, and their values are 3 and 5. 3 + 5 is 8, which means we initialize c to 8. Our variables in scope and their values are { a = 3; b = 5; c = 8 }.
In the third line of the loop, we assign the variable a. The value we assign to the variable a is the current value of the variable b. So, we look at our variable list, and we see that the current value of b is 5, which means we assign 5 to a. Our variables in scope and their values are { a = 5; b = 5; c = 8 }.
In the fourth line of the loop, we assign the variable b. The value we assign to the variable b is the current value of the variable c. So, we look at our variable list, and we see that the current value of c is 8, which means we assign 8 to b. Our variables in scope and their values are { a = 5; b = 8; c = 8 }.
After the fourth line of the loop, the variable c goes out of scope. Our variables in scope and their values are now { a = 5; b = 8 }.
I hope it is somewhat clearer now.
One thing that is very important in programming is naming. Good names should be intention-revealing. In this case, none of the names are very good: what does the name a tell you about what the intent of the programmer is? The same goes for b, c, and i. seq_loop is also not very intention-revealing, i.e. what does this function actually do? It prints the Fibonacci sequence. How can I tell from the name that it prints the Fibonacci sequence? Well, I simply can't!
So, here is the code with some better names, which should clear up some confusion:
def print_fibonacci_sequence():
    previous = 0
    current  = 1

    for _ in range(15):
        print(previous)

        after    = previous + current
        previous = current
        current  = after

print(print_fibonacci_sequence())

You might ask yourself "How is _ a more intention-revealing name than i?" The reason is that _ has a well-known meaning in the Python community: it is used as the name for a variable that is being ignored. Which is exactly what we are doing in this case.
Also, why after and not next? next is already defined in Python and it is considered bad style to shadow or even worse redefine Python builtins.
There are a couple of other oddities in the code. For example, the function prints the elements of the Fibonacci sequence and it doesn't return anything. And then you call the function and print the result of the call … but there is no result because the function doesn't return anything! Renaming the function to have print in its name so that it is clear that it doesn't return anything but prints it, makes that mistake more obvious:
print(print_fibonacci_sequence())

You can immediately see that you print something which prints something, which makes no sense. It should just be
print_fibonacci_sequence()

Another oddity is that the function always prints the first 15 terms of the Fibonacci sequence. Usually, you would want to let the caller decide how many terms to print. Maybe the caller only needs 3? Maybe 20? So, let's do that:
def print_fibonacci_sequence(number_of_elements):
    previous = 0
    current  = 1

    for _ in range(number_of_elements):
        print(previous)

        after    = previous + current
        previous = current
        current  = after

print_fibonacci_sequence(15)

Speaking of letting the caller decide what to do, what if the caller doesn't want to print the Fibonacci sequence? What if the caller wants to format it as HTML or insert it into an Excel table?
You should always separate computation from input/output. So, in this case, instead of printing the Fibonacci sequence, we will return the Fibonacci sequence, and then the caller can print it if they want to:
def fibonacci_sequence(number_of_elements):
    fibonacci_sequence = []

    previous = 0
    current  = 1

    for _ in range(number_of_elements):
        fibonacci_sequence.append(previous)

        after    = previous + current
        previous = current
        current  = after

    return fibonacci_sequence

print(fibonacci_sequence(15))

Actually, if you think about it, having the caller pass the number of terms as an argument is still somewhat restrictive. What if the caller doesn't want the first n terms, but the first terms smaller than n? In that case, they would have to compute the Fibonacci sequence first to see how many terms there are smaller than n and then ask for that number of terms of the Fibonacci sequence, which obviously defeats the purpose of having the function in the first place.
The best solution for the caller would be to produce an infinite number of terms and let the caller decide which condition to use to decide how many terms to take:
def fibonacci_sequence():
    previous = 0
    current  = 1

    while True:
        yield previous

        after    = previous + current
        previous = current
        current  = after

Now you can use it like this:
from itertools import islice, takewhile

first_15_terms = islice(fibonacci_sequence(), 15)
terms_less_than_100 = takewhile(lambda term: term < 100, fibonacci_sequence())

And you can decide what to do with the result. For example print it:
for term in first_15_terms:
    print(term)

for term in terms_less_than_100:
    print(term)

Or you can turn it into a list:
list_of_first_15_terms = list(first_15_terms)
list_of_terms_less_than_100 = list(terms_less_than_100)

And many other things.
This is a general principle in programming, software engineering, and API design: not only separate input/output from computation, but also break up the computation into separate parts for producing values, consuming values, transforming values, filtering values, representing values as strings (to be output later), parsing string representations into values (coming in from the outside), and so on.
In one sentence, we could say: separate the things that change.


Solution of the ordinary differential equation $y'(t)=-y^3+y^2+2y$

Question: Consider the solution of the ordinary differential equation $y'(t)=-y^3+y^2+2y$ subject to $y(0)=y_0 \in (0,2). $ then $\lim \limits_{t \to \infty}y(t)$ belongs to

{-1,0}
{-1,2}
{0,2}
{0, $+\infty $}

My Attempt:  $y'(t)=-y^3+y^2+2y \\ \Rightarrow y'(t)=-y(y^2-y-2) \\ \Rightarrow y'(t)=-y(y-2)(y+1) \\ \Rightarrow \frac{dy}{dt}=-y(y-2)(y+1) \\ \Rightarrow \frac{dy}{y(y-2)(y+1)}=-dt \\ \Rightarrow \int\frac{dy}{y(y-2)(y+1)}=\int-dt \\by \;\;partial \;fraction \; we \; get \\ \int [\frac{-1}{2y}+\frac{1}{6(y-2)}+\frac{1}{3(y+1)}]dy =-\int dt \\ \Rightarrow -\frac{1}{2} log|y| +\frac{1}{6} log|y-2| + \frac{1}{3} log|y+1|=-t + logc_1 \\ \Rightarrow \frac{-3log|y|+log|y-2|+2log|y+1|}{6}=-t + logc_1 \\ \Rightarrow log\frac{(y-2)(y+1)^2}{y^3}=-6t+6logc_1 \\ \Rightarrow log\frac{(y-2)(y+1)^2}{y^3}-logc_1^6=-6t \\ \Rightarrow log\frac{(y-2)(y+1)^2}{cy^3}=-6t \;\; where \;c_1^6=c \\ \Rightarrow \frac{(y-2)(y+1)^2}{cy^3}=e^{-6t}..........(1) \\ when \;\;t=0 \;\; \frac{(y_0-2)(y_0+1)^2}{y_0^3}=c \\ (1) \Rightarrow \frac{(y-2)(y+1)^2}{y^3}=\frac{(y_0-2)(y_0+1)^2}{y_0^3} e^{-6t}$
Now I am not getting how to apply the limit for this and how to find $\lim \limits_{t \to \infty} y(t)$
Comment: No need to compute the exact solution, just sketch the phase portrait directly from the equation $\dot y = -y (y-2)(y+1)$.
Comment: I think it will simply be $0$. By the way, the options provided are sets with discrete elements or intervals?
Comment: @AniruddhaDeshmukh when using $\{$ and $\}$ is is always set of discrete elements and not an interval
Comment: @Holo Then, three of the options will be the answer
Comment: @Hans Lundmark how do I find the limit if I consider only $\dot y=-y(y-2)(y+1)
Comment: @Aniruddha Deshmukh please will you explain how do I get option 3. Because in the key answer it is given that option 2 and 3 are correct
Comment: @AniruddhaDeshmukh no, you will have the Lim of $\frac{(y(t)-2)(y(t)+1)^2}{y(t)^3}=0$, not the Lim of $y(t)=0$
Comment: @Holo Yes! Got it!
Comment: The answer below is correct.
Comment: @Holo But in the key answer it is given that option 2 and 3 are correct then how do we get limit of y(t) =0
Answer: Given that $$y'(t)=-y^3+y^2+2y=-y\left(y^2-y-2\right)=-y(y-2)(y+1)$$
Clearly at $~y=-1,~0,~2~$ we have $~y'=0~.$
So the direction field will be something like:

When $~y<-1~,$ slope of $~y~$ is increasing.
When $~-1<y<0~,$ slope of $~y~$ is decreasing.
When $~0<y<2~,$ slope of $~y~$ is increasing.
When $~y>2~,$ slope of $~y~$ is decreasing.
Given that $~y(0)=y_0\in(0,~2)~,$ which implies that $~\lim_{t\to\infty}y(t)=2~.$
Hence option $\bf{(2)}$ and option $\bf{(3)}$ are the only correct options.
Note:  I know that there is an accepted answer of this old question. But One can check that this is an totally new idea.  So I don't think the community should have any objection about it. Thank you.
Comment: Weak suggestion: Can you change the plot so that the constant solutions are asymptotes of the other solutions, that is, make them more sigmoid? As it is it looks like solutions will cross or at least branch.
Answer: you got $\frac{(y-2)(y+1)^2}{y^3}=\frac{(y_0-2)(y_0+1)^2}{y_0^3} e^{-6t}$ take the limit and you get $$\lim\limits_{t\to\infty}\frac{(y-2)(y+1)^2}{y^3}=0\implies \lim\limits_{t\to\infty}(y-2)(y+1)^2=0 \implies \lim\limits_{t\to\infty}y(t)=\begin{cases}2\\-1\end{cases}$$ hence option (2) is true
Comment: @Priyanka to be clear about the limit, (1) you have to remember that taking the limit means we are taking the variable $t$ and putting in it a "big number", so as long as you don't do anything like $\lim y(t)=y(\lim t)$ without the necessary knowledge you can always take the limit. And if you have $\lim (f(t)=g(t))$ you can do $\lim f(t)=\lim g(t)$ to get to something nicer. About why they gave you also (3) as an answer... I am not sure, I have a little space so I will add another comment about my thought about this
Comment: Thank you. I thought that y(t) is dependent on t so I can't apply the limit directly to the expression $(y-2)(y+1)^2 $. also in the key answer it is given that option 2 and 3 are correct. how do we get option 3?
Comment: If both (2) and (3) correct then $(2)\cup(3)$ correct, but $(1)\subset(2)\cup(3)$ so also (1) should be correct. I don't know if they are wrong or I may missing something here
Comment: Since $y_0\in(0,2)$ then $y(t)\in(0,2)$. So $\lim \limits_{t \to- \infty}y(t)=0$ and $\lim \limits_{t \to+ \infty}y(t)=2$.


how to make async requests from client to server?

Question: want to make few async requests from client to server.
i setting up local server with http module , and export this function to main app file. at the client file i write function that makes http request and i call this function number of times.
<code>//server
const http = require('http');
const ms = 2000;
const init = () => {
    http.createServer((req,res) => {
        sleep(ms);
        console.log(req.method);
        console.log("After sleeping 2 seconds,hello from server");
        res.end();
    }).listen(5000, () => {
        console.log("server running");
    });
}
function sleep(ms) {
    Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,ms);
    console.log("Sleep 2 seconds.");
}

module.exports.init = init;

//client
const url = "http://127.0.0.1:5000";
const http = require('http');

 const  getData = async url => {
  await http.get(url, res => {
    res.on('data', chunk => {
      console.log("chunk : "+chunk);
    });
    res.on('end', () => {
      console.log("response ended.");
    });
  }).on("error", (error) => {
    console.log("Error: " + error.message);
  });
};
const makeRequests = () => {
  for (let i = 0; i < 3; i++) {
    getData(url);
  }
}
module.exports.makeRequests = makeRequests;

//app
const server1 = require('./server1');
const client = require('./client');

server1.init();
client.makeRequests();
</code>
how do i use the async await proprely ? and why its now printing the "chunk" ?
Answer:
want to make few async requests from client to server.

Well, your code is actually async.

how do i use the async await proprely ?

How to use async/await correctly. There are examples how to use.

and why its now printing the "chunk" ?

<code>http.get(url, res => {
    res.on('data', chunk => {
      console.log("chunk : "+chunk);
    });
    res.on('end', () => {
      console.log("response ended.");
    });
</code>
http.get(url, callback) ... response.on("data") gets fired if a new chunk is received. So it will read until the response stream gets an EOF ( End Of File ). If you wanna save & read the whole data at once you can write your chunks into a variable by append and read at "end".
Comment: Thank you. The output using async await and without using it is exactly the same. Are the requests asynchronous anyway?
Comment: Your requests are asynchronous, yep