Dificuldade em passar um parâmetro para um rdlc que tenho(Oracle)

Question: Não estou conseguindo passar uma parâmetro para o meu relatório. Tenho um campo chamado de Regulamentado, referente ao campo Ind_Regulamentado. veja o código abaixo e como eu faço esse filtro?
public static void Emitir()
        {
            //Relatório com DataSource = ORACLE
            dsPlanoMedico.PLANO_MEDICODataTable dtPlanoMedico = new dsPlanoMedico.PLANO_MEDICODataTable();
            dsPlanoMedicoTableAdapters.PLANO_MEDICOTableAdapter adapt = new dsPlanoMedicoTableAdapters.PLANO_MEDICOTableAdapter();

            adapt.Fill(dtPlanoMedico);
            dtPlanoMedico.Where(i => i.IND_REGULAMENTADO == "S");//aqui não funciona

            ReportDataSource rds = new ReportDataSource("dsDados", dtPlanoMedico.DefaultView);
            ReportViewer viewer = new ReportViewer();

            viewer.ProcessingMode = ProcessingMode.Local;
            viewer.LocalReport.ReportPath = "ReportBD.rdlc";
            //viewer.LocalReport.SetParameters(new ReportParameter("Regulamentado", "S"));
            viewer.LocalReport.DataSources.Add(rds);

            Warning[] warnings;
            string[] streamIds;
            string mimeType = string.Empty;
            string encoding = string.Empty;
            string extension = string.Empty;

            byte[] bytesPDF = viewer.LocalReport.Render("PDF", null, out mimeType, out encoding, out extension, out streamIds, out warnings);
            FileStream fsPDF = new FileStream("c:\\temp\\report.pdf", FileMode.Create);
            fsPDF.Write(bytesPDF, 0, bytesPDF.Length);
            fsPDF.Close();
            fsPDF.Dispose();

            byte[] bytesExcel = viewer.LocalReport.Render("Excel", null, out mimeType, out encoding, out extension, out streamIds, out warnings);
            FileStream fsExcel = new FileStream("c:\\temp\\report.xls", FileMode.Create);
            fsExcel.Write(bytesExcel, 0, bytesExcel.Length);
            fsExcel.Close();
            fsExcel.Dispose();

            byte[] bytesWord = viewer.LocalReport.Render("Word", null, out mimeType, out encoding, out extension, out streamIds, out warnings);
            FileStream fsWord = new FileStream("c:\\temp\\report.doc", FileMode.Create);
            fsWord.Write(bytesWord, 0, bytesWord.Length);
            fsWord.Close();
            fsWord.Dispose();

        }

Fui fazer umas alterações e começou a me dar um erro:
essas foram as alterações:
var dv = new System.Data.DataView(dtPlanoMedico);
            dv.RowFilter = "IND_REGULAMENTADO LIKE 'S'";

            ReportDataSource rds = new ReportDataSource("dsDados", dv);

E esse o erro:

The Value expression for the text box 'COD_PLANO' refers to the field
  'COD_PLANO'.   Report item expressions can only refer to fields within
  the current dataset scope or,  if inside an aggregate, the specified
  dataset scope. Letters in the names of fields must use the correct
  case.  C:\Projetos\Servicos\ReportBD.rdlc Servicos

O que pode ser isso?
Fiz esse filtro e filtrou: dv.RowFilter = "IND_REGULAMENTADO LIKE 'N'";, porem se eu faço dessa forma:
dv.RowFilter = "IND_REGULAMENTADO LIKE 'N'";
dv.RowFilter = "TIPO_REGISTRO_ANS LIKE 'D'";

aí só filtra pelo último e não ambos. Como eu resolvo isso?
Answer: Resolvi assim:
public static void Emitir()
        {
            //Relatório com DataSource = ORACLE
            dsPlanoMedico.PLANO_MEDICODataTable dtPlanoMedico = new dsPlanoMedico.PLANO_MEDICODataTable();
            dsPlanoMedicoTableAdapters.PLANO_MEDICOTableAdapter adapt = new dsPlanoMedicoTableAdapters.PLANO_MEDICOTableAdapter();

            adapt.Fill(dtPlanoMedico);
            //dtPlanoMedico.Where(i => i.IND_REGULAMENTADO == "S");

            var dv = new System.Data.DataView(dtPlanoMedico);//aqui
            dv.RowFilter = "IND_REGULAMENTADO LIKE 'N' and TIPO_REGISTRO_ANS LIKE 'D'";//aqui

            ReportDataSource rds = new ReportDataSource("dsDados", dv);//aqui
            ReportViewer viewer = new ReportViewer();

            viewer.ProcessingMode = ProcessingMode.Local;
            viewer.LocalReport.ReportPath = "ReportBD.rdlc";
            //viewer.LocalReport.SetParameters(new ReportParameter("Regulamentado", "S"));
            viewer.LocalReport.DataSources.Add(rds);

            Warning[] warnings;
            string[] streamIds;
            string mimeType = string.Empty;
            string encoding = string.Empty;
            string extension = string.Empty;

            byte[] bytesPDF = viewer.LocalReport.Render("PDF", null, out mimeType, out encoding, out extension, out streamIds, out warnings);
            FileStream fsPDF = new FileStream("c:\\temp\\report.pdf", FileMode.Create);
            fsPDF.Write(bytesPDF, 0, bytesPDF.Length);
            fsPDF.Close();
            fsPDF.Dispose();

            byte[] bytesExcel = viewer.LocalReport.Render("Excel", null, out mimeType, out encoding, out extension, out streamIds, out warnings);
            FileStream fsExcel = new FileStream("c:\\temp\\report.xls", FileMode.Create);
            fsExcel.Write(bytesExcel, 0, bytesExcel.Length);
            fsExcel.Close();
            fsExcel.Dispose();

            byte[] bytesWord = viewer.LocalReport.Render("Word", null, out mimeType, out encoding, out extension, out streamIds, out warnings);
            FileStream fsWord = new FileStream("c:\\temp\\report.doc", FileMode.Create);
            fsWord.Write(bytesWord, 0, bytesWord.Length);
            fsWord.Close();
            fsWord.Dispose();

        }


Some Counterexamples on Connectedness

Question: There are abundant counterexamples in literature of the $2$ statements -

$X$ is Path Connected $\implies$ $X$ is Locally Path Connected
$X$ is Arc Connected $\implies$ $X$ is Locally Arc Connected

In all of the counterexamples I've found, they hold as the space is Path/Arc Connected, but is not Locally Connected (for example, the Extended Topologist's Sine Curve and the Closed Infinite Broom).
So, I wish to ask - are there counterexamples of the above $2$ statements, if we also assume that $X$ is Locally Connected? How about Locally Path Connected for Statement $2$?
Comment: Note that a space that is both locally path-connected and connected space is path-connected. So we don't have an example for the "mixed" case.
Answer: Let $Y=[0,1]\times[0,1]$ with the lexicographic order topology. For each $x\in[0,1]$ let $I_x$ and $I^x$ be copies of $[0,1]$ with its usual topology, and for each $t\in[0,1]$ let $t_x$ and $t^x$ be the copies of $t$ in $I_x$ and $I^x$, respectively. For $x\in[0,1]$ identify $\langle x,0\rangle\in Y$ with $0_x\in I_x$ and $\langle x,1\rangle\in Y$ with $0^x\in I^x$. Then identify all of the points $1_x$ and $1^x$ to a single point $p$ to get the space $X$.
Informally, we attach a 'sticker' in the form of a copy of the closed unit interval to each point on the bottom and top edges of the lexicographically ordered square, and we identify the free ends of the stickers.
Then $X$ is path connected and locally connected, but it is not locally path connected at any of the points $\langle x,0\rangle\sim 0^x$ or $\langle x,1\rangle\sim 0^x$.
Comment: @IshanDeo: Argh! It was **supposed** to be $\langle x,0\rangle\sim 0^x$, the point of $X$ that results from the identification of $\langle x,0\rangle\in Y$ and $0^x\in I^x$. I don't know whether it was a typo or a mental hiccup, but I'm fixing it as soon as I post this comment!
Comment: What exactly do you mean by $\langle x,0\rangle\sim 1^x$?
Comment: So, correct me if I'm wrong, but - you added the lines $I_x$ and $I^x$ for the sole purpose of creating a path between any $2$ points of $X$, which did not originally exist in the ordered square.

Also, $X$ is not locally path connected for the same reason the ordered square is not.
Comment: @IshanDeo: That's right, on both counts.

Some Counterexamples on Connectedness


Encontrar ultima célula preenchida em um range

Question: É possível encontrar a última célula preenchida em um range e colar um valor na próxima linha vazia abaixo?
Preciso de um código que faça a busca no range ("B5:B35"). Usei o seguinte código, mas após a célula 35 eu tenho outras informações então os dados são colados em local errado
If Not Application.Intersect(Target, Range("B4:B8,B11:B15")) Is
Nothing Then Range(Cells(Selection.Row, 2), Cells(Selection.Row,
4)).Select Selection.Copy

Worksheets("Cálculos").Cells(Rows.Count, 2).End(xlUp).Offset(1,
0).PasteSpecial xlPasteValues

Answer: Última Célula de um intervalo
    Dim Calc As Worksheet
    Dim intervalo As Range
    Dim matriz As Variant
    Dim i As Long, j As Long
    Set Calc = ThisWorkbook.Worksheets("Cálculos")
    Set intervalo = Calc.Range("A20:C30")
    matriz = intervalo

    For j = intervalo.Columns.Count To 1 Step -1
        For i = intervalo.Rows.Count To 1 Step -1
            If matriz(i, j) <> "" Then
                MsgBox intervalo(i, j).Address
                GoTo sairLoop
            End If
        Next i
    Next j
sairLoop:

Última Linha de um intervalo numa Coluna
Por exemplo do intervalo de A10 até A30 se estiver preenchido somente até A26, retornará 26:
Dim Calc As Worksheet
Dim UltimaLinha As Long
Set Calc = ThisWorkbook.Worksheets("Cálculos")

With Calc.Range("A10:A30").CurrentRegion
     UltimaLinha = .Rows(.Rows.Count).Row
End With

Última Linha de uma Coluna
Para encontrar a última linha, há várias formas, mas a que EU mais utilizo é:
UltimaLinha= Worksheets("Cálculos").Cells(Worksheets("Cálculos").Rows.Count, "B").End(xlUp).Row
ou
Dim Calc As Worksheet
Set Calc = ThisWorkbook.Worksheets("Cálculos")

With Calc
    UltimaLinha= .Cells(.Rows.Count, "B").End(xlUp).Row
End With

ou
Dim Calc As Worksheet
Set Calc = ThisWorkbook.Worksheets("Cálculos")
UltimaLinha= Calc.Cells(Calc.Rows.Count, "B").End(xlUp).Row

Última Linha da Planilha
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("Planilha1")
lngLstRow = ws.UsedRange.Rows.Count

Resultado:
Então a linha do seu código mudaria para:
Worksheets("Cálculos").Cells(UltimaLinha, 2).Offset(1, 0).PasteSpecial xlPasteValues
ou
Worksheets("Cálculos").Cells(UltimaLinha + 1, 2).PasteSpecial xlPasteValues

Observação: Declarar a UltimaLinha como Long (Dim UltimaLinha As Long), pois muitos tutoriais antigos utilizam o Integer, que possui 2 bytes e
  o intervalo de     –32 768 a 32 767. Portanto, se a versão do Excel for
  maior do que 2007, o programa irá parar após a linha 32767. Já o Long
  possui 4 bytes e intervalo de -2 147 483 648 a 2 147 486 647. Em que o
  Excel possui um limite de 1 048 576 linhas.


Corollary 5 in Royden-Fitzpatrick's Real Analysis: Convergence in Measure

Question:
Corollary 5: Let $\{f_n\}$ be a sequence of nonnegative integrable functions on $E$. Then
$$\lim_{n \to \infty} \int_E f_n = 0 ~~~~~~(5)$$
if and only if
$$f_n \to 0 \mbox{ in measure on } E \mbox{ and } \{f_n\} \mbox{ is uniformly integrable and tight over } E ~~~~~(6)$$

Here's the part of the proof giving me trouble:

First assume (5). Corollary 2 tells us that $\{f_n\}$ is uniformly integrable and tight over $E$...

Here is corollary 2:

Let $\{h_n\}$ be a sequence of nonnegative integrable functions on $E$. Suppose that $h_n(x) \to 0$ for all most all $x \in E$. Then $$\int_E h_n \to 0 \mbox{ iff } \{h_n\} \mbox{ uniformly integrable and tight over } E$$

How can we invoke corollary 2 if $f_n$ isn't assumed to converge pointwise a.e. to $0$ on $E$?
EDIT:
Okay. I encountered some more difficulties in the second half of the proof:

To prove the converse, we argue by contradiction. Assume that (6) holds but (5) fails to hold. Then there is some $\epsilon_0 > 0$ and a subsequence $\{f_{n_k}\}$ for which $$\int_E f_{n_k} \ge \epsilon_0 \mbox{ for all } k$$ However, by theorem 4, a subsequence $\{f_{n_k}\}$ converges to $f \equiv 0$ pointwise almost everywhere on $E$ and this subsequence is uniformly integrable and tight so that, by the Vitali Convergence Theorem, we arrive at a contradiction to the existence of the above $\epsilon_0$. This completes the proof.

First, why does $\int_E f_{n_k} \ge \epsilon_0$ hold for all $k$? If I've properly negated the definition of the convergence of a sequence, we should actually have that there exists an $\epsilon > 0$ such that for every $N \in \Bbb{N}$ there exists an $k \ge N$ such that $\int_E f_{n_k} \ge \epsilon_0$.
Second, assuming that (5) fails certainly does give us a subsequence such that blah blah holds; and theorem 4 gives us a subsequence such that blah blah holds. But what reason is there for thinking that these subsequences are the same?
Comment: As to questions in Edit, I don't see what the problem is with $\int_E f_{n_k} \geq \epsilon_0$. For each $n$, just define $n_k$ to be any $k \geq n$ such that the desired inequality holds. For the second part, the authors don't assume the subsequences are the same. They write, "a subsequence of $\{f_{n_k}\}$ converges...," that subsequence being a subsubsequence of $\{f_n\}$.
Comment: There's nothing wrong with my negation. It's a mere notational variation of what you wrote that makes the relevant relation to subsequences salient. You seem to be confused about some basic definitions. I'm not sure what else I can say to help you with this. You should just review and think carefully about the definitions of subsequences, limits, etc.
Comment: There is an [erratum](http://www2.math.umd.edu/~pmf/docs/Real%20Analysis.pdf) to this Corollary, though I don't immediately see that it resolves your questions.
Comment: @aduh I'm afraid I don't understanding your reasoning. We are _given_  the sequence in virtue of assuming (5) false. So we don't have any control over its form/nature, so how can modify it so that the inequality holds for every $k$?
Comment: The negation of (5) is: $\exists \epsilon_0>0, \forall n, \exists n_k \geq n$ such that $\int_E f_{n_k} \geq \epsilon_0$. So $\{f_{n_k}\}$ is the desired subsequence. I still don't see what the issue is here.
Comment: @aduh Your negation of (5), which isn't entirely correct (it should be "$\exists k \ge n$ such that..."), doesn't say anything about something being true for all $k$. Perhaps that's the problem, however: the $k$'s domain of quantification isn't specified. If the author is asserting that the domain of quantification is $\Bbb{N}$, then I believe this is mistaken.
Answer: I responded to your EDIT in the comments so will confine this answer to the main question. However, if you have further questions about the EDIT, I'd be glad to try to answer them. (Sorry if my last comment seems rude. It was written in a hurry.)
Now, as to your main question, I think Royden's exposition here isn't great, but the result still holds.
Here, I think, is the most charitable way to read the text. Section 5.1 extends the results in the preceding section, 4.6, by proving a Vitali Convergence Theorem for sets with infinite measure. Section 5.2 introduces the concept of convergence in measure and extends some of the results from 4.6 and 5.1. To understand the result you ask about, it's helpful, then, to view it as an analogue of the results that precede it in sections 4.6 and 5.1. In particular, if you inspect the proof of Theorem 26 in Section 4.6, you will see that $\lim_{n \to \infty}\int_E h_n = 0$ implies $\{h_n\}$ is uniformly integrable on $E$; the assumption that $h_n \to 0$ a.e. is not used in this direction of the proof. Corollary 2 in Section 5.1, the proof of which is left as an exercise, is a straightforward extension of Theorem 26.
The part of Corollary 2 that is relevant to your question is: $\lim_{n \to \infty}\int_E h_n = 0$ implies $\{ h_n\}$ is uniformly integrable and tight. To get uniform integrability, the proof of Theorem 26 applies. To get tightness, the same idea works. To wit, with $\epsilon > 0$ given, $\lim_{n \to \infty}\int_E h_n = 0$ implies that $\int_{E_0} h_n < \epsilon$ for all $n >N$ and all $E_0 \subset E$ because the $\{h_n\}$ are non-negative. If $n \leq N$, then the integrability of $h_1,...,h_N$ implies that there is a set $A$ of finite measure such that
$$\int_{E \setminus A} h_j < \epsilon, \ \ 1 \leq j \leq N.$$
This is Proposition 1, Section 5.1, extended to a finite collection of integrable functions. Because $E \setminus A \subset E$, it follows that $\{h_n\}$ is tight.
To sum up, the assumption that $f_n \to 0$ a.e. is not needed in the direction of the proof that you ask about, but I do think that the authors could have made this clearer somehow.
Comment: Ah! Dang it! I worked on corollary 2, but I suppose enough time elapsed between proving corollary 2 and proving corollary 5 that I forgot that one direction of corollary 2 doesn't use pointwise convergence. By the way, I don't you think you were being rude, so no worries. Thanks for the help!
Comment: By the way, if you're interested in receiving another 50 points, I bounty on [this](https://math.stackexchange.com/questions/2720901/vitali-covering-lemma-proof) question


Converting image from data and then data from image increases data

Question: I am getting my image from PHAsset.
I am requesting an image data using requestImageData function of PHAsset.
After getting data from that function, I create an image from that data using scale = 1
Then again converting data from that newly created image, I get increased data, not as the data I got previously
Below is the code that I use to get data from PHAsset
imageManager.requestImageData(for: image.asset, options: nil) { [weak self] (data, str, orientation, info) in
            guard let strongSelf = self else { return }
            if let dt = data {
                //Here I get data.count as 4993397
                if let image = UIImage(data: dt, scale: 1) {
                    strongSelf.image = image
                    print("New data : \(image.jpegData(compressionQuality: 1)?.count)")
                    //The result printed here is 12107879
                }
            }
        }

Why the data gets increased here, I don't have any idea
Thanks!!
Comment: There is [really good comment](https://stackoverflow.com/a/50582203/5928311) about size of image and about compression ratio. This is not the answer to your question, but just FYI
Comment: @VadimNikolaev Thanks for the response, I'll surely look for this
Answer: This line
let image = UIImage(data: dt, scale: 1)
construct image with the highest quality ratio (q=1.0). That's why the image is suddenly so big.
So the moment you get your image as an UIImage from NSData, the decompression/conversion changes the size of the image.
Comment: Thanks for the response, I understood what you are saying but how can I solve this problem because I want to get data from newly created image, should I resize image at that moment when I get the UIImage from Data ? @jawadAli
Comment: There are proper ways to resize an image such as
https://stackoverflow.com/questions/31314412/how-to-resize-image-in-swift
Comment: I have resized my image with this kind of resizing technique. Thanks for the response
Comment: thank you :) have a nice day ... if it resolved please accept answer
Comment: sorry for the delay in accepting the answer @jawadAli


What can be said if $A^2+B^2+2AB=0$ for some real $2\times2$ matrices $A$ and $B$?

Question: Let $A,B\in M_2(\mathbb{R})$ be such that $A^2+B^2+2AB=0$ and $\det A= \det B$. Our goal is to compute $\det(A^2 - B^2)$.  According to the chain of comments on Art of Problem Solving, the following statements are true:

$\det(A^2+B^2)+\det(A^2-B^2)=2(\det A^2+\det B^2)$. (Is this well known?)
(1) $\implies \det(A^2-B^2)=0$.
If $A,B\in M_2(\mathbb{C})$ satisfy $A^2+B^2+2AB=0$, then $AB=BA$.
$(A+B)^2=0 \implies \det(A^2-B^2)=0$.

Can someone help me with justifying these statements?
Edit.
Doug M provided an explanation for (1) in the answers. Here is an explanation for (2):
$A^2+B^2+2AB=O_2 \implies A^2+B^2=-2AB$. So $\det(A^2+B^2)=4\det(AB)$. Now using (1), $\det(A^2-B^2)= 2\left(\det(A^2)-2\det(AB)+\det(B^2)\right) = 2\left((\det(A)^2-\det(B)^2\right) = 0$.
Answer: Of course, the OP did not understand much about the proposed exercise. In particular, in $M_2(\mathbb{C})$, $A^2 +B^2+2AB=0$ implies $\det(A)=\det(B)$.
In fact, the interesting result is
Proposition. Let $A,B\in M_2(\mathbb{C})$ be such that $(1)$ $A^2+B^2+2AB=0$. Then $AB=BA$. (Note that the result works only in dimension $2$.)
Proof. If $H=A+B$, then $H^2=HA-AH$ and $\mathrm{tr}(H^2)=0$. Moreover $H^3=H^2A-HAH=HAH-AH^2$ implies that $\mathrm{tr}(H^3)=0$. We deduce that the eigenvalues of $H$ are $0$, $H$ is nilpotent, $H^2=0$, $AH=HA$, $AB=BA$.  $\square$
Remark. According to Proposition, $(1)$ implies that $(A+B)^2=0$, $\det(A+B)=0$, $\det(A^2-B^2)=0$. Moreover, $AB=BA$ implies that $A,B$ are simultaneously triangularizable. Since $A+B$ is nilpotent, we may assume that $A=\begin{pmatrix}a&c\\0&b\end{pmatrix},B=\begin{pmatrix}-a&d\\0&-b\end{pmatrix}$ and, consequently, $\det(A)=\det(B)$.
Answer: If $A = \pmatrix {a&b\\c&d}, B = \pmatrix {e&f\\g&h}$
$\det (A+B) + \det (A-B)\\(a+e)(c+h) - (b+f)(c+g) + (a-e)(c-h) - (b-f)(c-g)\\ 2ac+2eh - 2bc-2fg\\2(\det A + \det B)$
$\det (A+B) + \det (A-B) = 2(\det A + \det B)$
In which case the initial premise indeed holds.
I am pretty sure this only holds in the $2\times2$ case.


Model.save() is bugged?

Question: I'm trying to pass freecodecamp test which require to submit a name and save it to collection. However, everytime i pressed submit in my form, there is this lengthy warning message in the console :
(node:20679) DeprecationWarning: Mongoose: mpromise (mongoose's default promise library) is deprecated, plug in your own promise library instead: http://mongoosejs.com/docs/promises.html
This is my route code :
app.post('/api/exercise/new-user/', (req, res) => {
  const {username} = req.body;
  if(username===''){
    res.send('Name must not empty');
  }else{
    const aNewTrainee = new PersonExcer({name:username});
    aNewTrainee.save().then(aTrainee => {
            res.status(200).json(aTrainee);
        })
        .catch(err => {
            res.status(400).send('adding new todo failed');
        });
  }
})

And since if i tried to query the document collection after save, there is no result, then that can only mean the save() call did not work :
//This has no result
app.get('/api/exercise/users', (req, res)=>{
  PersonExcer.find(function(err, docs) {
    if (err) {
            console.log(err);
        } else {
            res.json(docs);
        }
  });
  //This has no result
})

Please have a look at the complete code here (edit: link removed).
Comment: I've been try your code and it's working fine. Please update your mongoose to the latests version.
Comment: @TitusSutioFanpula yes, thank you! Please submit your answer, i will upvote.
Answer: I've been try your code and it's working fine, please update/upgrade your mongoose to the latest version.
You can use this command line below to check which packages have newer versions available:
npm outdate

For upgrade your mongoose, you can use this command line:
npm install mongoose@latest --save

For update, you can use this command line:
npm update mongoose

I hope it can help you.
Answer: Maybe call method is wrong, Check  https://mongoosejs.com/docs/promises.html
for answers

Model.save() is bugged?


How to use Commerce Feeds to Import Stock for the Commerce Stock module?

Question: I have the Commerce Stock module enabled for my products in Drupal Commerce.
But I cannot import data to the stock fields: When I set up the correct product processor, I can't see the Stock field which is present in my product variation type.
Answer: Your problem sounds similar to the issue: Not recognizing product variants fields.
The solution is most probably to upgrade the Commerce Feeds module to 7.x-1.x-dev, or if you don't want to use a dev version you could downgrade the Feeds module to 7.x-2.0-alpha9.
Comment: Upgrading commerce feeds didn't work for me, but downgrading feeds to 7.x-2.0-alpha9 did the trick.
Comment: Thank you!  It shows the fields I want to use now.  If something ends up not working like I thought it would, I've still got my local copies of Drupal and my database structure.
Answer: As for me there was only one solution: reinstall. And after reinstalling first you should add importer, set stock mapping and only after that - enable feeds tamper. If I installed tamper before mapping setup there always was same problem with mapping. So, mb it's same thing. Sorry, can't comment.
Comment: I actually had to manually pull out my commerce_feeds 7.x-1.3 because each time I disabled and "uninstalled," commerce_feeds was still there.  But I've got the 7.x-1.x-dev, and the mapping shows the field targets I wanted.


Replacing TTY with a script in CentOS 6

Question: How would I go about replacing a TTY with a custom script in CentOS 6.  CentOS 6 uses upstart instead of the standard SysV init scripts, so I'm having difficulty figuring out how it all works.
Typically (in SysV init scripts), I would edit /etc/inittab and replace one of the mingetty lines with my script, like this:
1:2345:respawn:/root/myscript tty1

However, with Upstart, this file doesn't the relevant lines, so I'm unsure of how to accomplish this.
Comment: Have you looked at the documentation?  The [RedHat documentation](http://docs.redhat.com/docs/en-US/Red_Hat_Enterprise_Linux/6/html/Migration_Planning_Guide/ch04s02.html) has a section on service initialization, and there is of course a website for Upstart as well.
Comment: I did, the documentation wasn't very helpful about replacing an existing tty with something else.
Comment: It looks like you've figured it out anyway.  Congrats!
Answer: I've figured it out.
First I modified /etc/init/start-ttys.conf to have this for the script section:
script
    . /etc/sysconfig/init
    for tty in $(echo $ACTIVE_CONSOLES) ; do
          [ "$RUNLEVEL" = "5" -a "$tty" = "$X_TTY" ] && continue
            if [ "$tty" == "/dev/tty1" ]; then
                    initctl start myjob TTY=$tty
                    continue
            fi
            initctl start tty TTY=$tty
    done
end script

I then created /etc/init/myjob.conf:
stop on runlevel [012456]

respawn
exec /usr/bin/openvt -c 1 -f -e /root/myscript

This ultimately starts /root/myscript on tty1, instead of mingetty.  I'm unsure if this the is simplest way of doing it, but it works quite nicely.

Replacing TTY with a script in CentOS 6


$P(a < X \leq b) = F(b) - F(a)$?

Question: Let X be a random variable with distribution function F, $a,b \in \Re$ with $a \lt b$ and $F(x-)$ is the limit of $F$ in $x$ from the left.
I tried to proof that the equality is correct, but I'm stuck by not comprehending what to do next, so far I had:
$(x,y] = (-\infty,y]-(-\infty,x]$
$\Rightarrow \forall x \in \Re$ we have
$F_X(x)=P(X \leq x) = P(X \in (-\infty,x])$
Then I assume that I need to prove that the continuity property of distribution functions from the right still satisfied, but I don't know how to do it with this elements. Can someone clear my mind a little bit? Thanks
Answer: You have the right idea. Since $(-\infty,a]$ and $(a, b]$ are disjoint, you have
$$P(X \in (-\infty, a]) + P(X \in (a, b]) = P(X \in (-\infty, a] \cup (a, b]) = P(X \in (-\infty, b]).$$

$P(a < X \leq b) = F(b) - F(a)$?


Convert string to the list it describes

Question: Say someone gives me a string like:
"[[A,B],[C,D]]"

and I want to extract the list it describes:
[[A,B],[C,D]]

How do I do this?
P.S.
A, B, C, D are just placeholders, they could be numeric values or strings.
Comment: `[[A,B],[C,D]]` is not valid Python. Can you clarify?
Comment: Are `A`, `B` etc. placeholders occupied by literal values, or are they some existing variable names, or something else?
Comment: Placeholders, it could be anything, numbers, string, etc.
Comment: Note, while this is possible you almost certainly shouldn't be doing this
Answer: To prevent an ValueError: malformed string from being raised when passing the input directly to ast.literal_eval, "s need to be added around the characters in the string:
import ast, re
s = "[[A,B],[C,D]]"
new_s = ast.literal_eval(re.sub('\w+', '{}', s).format(*['"{}"'.format(i) for i in re.findall('\w+', s)]))

Output:
[['A', 'B'], ['C', 'D']]

Comment: That's neat! Never seen that before.
Comment: Actually ast is enough, see my P.S., A,B,C and D are placeholders. Did not know about ast, need to learn, do you have a good link to its use?
Comment: @user See [here](https://stackoverflow.com/questions/15197673/using-pythons-eval-vs-ast-literal-eval) for information specifically regarding `ast.literal_eval` or [here](https://docs.python.org/3/library/ast.html) for more about syntax parsing in Python.
Answer: Based on A, B, C, and D being numbers (int, or float) or strings (str), you can simply use:
l = eval("[[A,B],[C,D]]")

For example:
In [1]: l = eval("[[1,2],[3,4]]")

In [2]: l
Out[2]: [[1, 2], [3, 4]]

In [3]: l = eval("[['Hello', 10],['bye', 100]]")

In [4]: l
Out[4]: [['Hello', 10], ['bye', 100]]

In [5]: l = eval("[[3.14, 1],['bye', 2.72]]")

In [6]: l
Out[6]: [[3.14, 1], ['bye', 2.72]]

Comment: Would you mind commenting on the difference between eval and ast.literal_eval?
Comment: @user, I found this [question](https://stackoverflow.com/questions/15197673/using-pythons-eval-vs-ast-literal-eval) with several answers explaining the difference between `eval` and `ast.literal_eval()`, is it enough for you?

Convert string to the list it describes


How does splitting up the products work?

Question: I have been given the following problem and starting steps but I am stuck on the first step

A measure of goodness of fit to estimate the mean $\mu$ and standard
deviation $\sigma$ of a normally distributed random variable is
maximum likelihood estimation. For sample $y = (y_1,... y_n)$ drawn
from the normally distributed random variables, $Y_i \sim
> N(\mu,\sigma)$, the likelihood is given by
$p(y|\mu,\sigma)=\prod_{i=1}^{n}\big(\frac{1}{2\pi\sigma^2}\big)^{\frac{1}{2}}
 exp \big( - \frac{1}{2\sigma^2}(\mu-y_i)^2 \big) $  Using the fact
that $e^{-a}e^{-b} = e^{-a-b}$ for arbitrary variables a and b, show
the negative log likelihood has the following form:
$L_(y|\mu,\sigma) = -\log  p(y|\mu,\sigma)
 +\frac{1}{2\sigma^2}\sum_{i=1}^n(y_i-\mu)^2$

The steps start with splitting up the products to be
$\prod_{i=1}^n(\frac{1}{2\pi\sigma^2})^{\frac{1}{2}}\prod_{i=1}^n exp\big( - \frac{1}{2\sigma^2}(\mu-y_i)^2 \big)$
I don't see why this can be done because
$(a1 *a2) (b1* b2) \ne (a1* a2) b1 ( a1 *a2) b2$
What am I missing?
Answer: Someone explained that I could think of it this way:
Consider the sum operator
$\sum_{i=1}^n a+y_i = \sum_{i=1}^na+\sum_{i=1}^n y_i $
The product operator can work similarly
$\prod_{i=1}^n a y_i = \prod_{i=1}^na\prod_{i=1}^n y_i $
I guess I am just not used to working with the product operator.


Question about Rudin's Functional Analysis Closed Graph Theorem

Question: In page 51 of Rudin's Functional Analysis, the closed graph theorem is proven, which says that if you have a linear map between two F-spaces whose graph is closed in the product space, then the map is continuous (2.15).
Then in a remark, Rudin says that in applications the closedness of the graph is verified by verifying that the map is sequentially closed. However, why would you even need to use the closed graph theorem if the map is sequentially closed, as for metric spaces (of which F-spaces are one example), sequential continuity anyway implies continuity, and so you wouldn't need to use the closed graph theorem to begin with!
What am I missing?
Comment: A closed graph is proved by assuming $x_n \rightarrow x$ and $Tx_n \rightarrow y$, and showing that $Tx=y$. That's different than proving continuity where you assume $x_n \rightarrow x$ and must show that $Tx_n \rightarrow Tx$.
Comment: The continuity is still being inferred from the graph being closed. The usual way you do this is to show that for any sequence $(x_n)$ converging to some $x$, such that $Ax_n \rightarrow y$ for some $y$, then $y=Ax$ (if the operator is only densely defined, you also need the condition that $x$ is in the domain).  Notice that sequential continuity implies the above is true.
Answer: Let $X$, $Y$ be Banach spaces and $A: X \to Y$ be linear.
Sequential closedness of the graph of $A$ means that if $x_n \to x$ and $Ax_n \to y$, then $Ax =y$. But not any convergent sequence $(x_n)_n$ has to be mapped to a convergent image sequence $(Ax_n)_n$.
Sequential continuity of $A$ means, that if $x_n \to x$, then $Ax_n$ converges as well and $Ax_n \to x$.
For example let
$X = (C^1[a,b], \Vert \cdot \Vert_\infty)$ and $Y= (C^0[a,b], \Vert \cdot \Vert_\infty)$ and $Af = f'$ be the differentiation map. A classical result from analysis tells you that if both $f_n$ and $f_n'$ are uniformly convergent (i.e. convergent in respect to $\Vert \cdot \Vert_\infty$) then $\lim f_n' = (\lim f_n)'$. This means that the graph of $A$ is closed. However $A$ is not continuous as you can see by $f_n (x) = \frac{1}{n} \sin(n^2 x)$: Then $f_n \to 0$ but not $Af_n \to 0$. This is because $Af_n (x) = n \cos(n^2x)$ so $Af_n$ does not converge uniformly at all.
The reason why the closed graph theorem doesn't work here is that $X = (C^1[a,b], \Vert \cdot \Vert_\infty)$ is not complete.
Continuity of $A$ implies closedness of the graph of $A$, but the inverse statement is the closed graph theorem and requires comleteness of $X$ and $Y$.


Skills needed for classical guitar

Question: I've been playing steel-string acoustic for 25+ years, and I'm becoming more interested in classical guitar playing. While I'm fairly good at fingerstyle, I'm aware that making the leap to classical/flamenco playing is not going to be simple or quick. (For example, I was able to learn Mood for a Day well, but it was a long process for me.)
My question is: What basic skills would a good rock/folk guitarist need to learn in order to evaluate this situation? Is it all about posture and learning to play melodies on top of chords, or is there more to it than that? (I strongly suspect there is.)
My ultimate goal is not to become a classically-trained player (years of lessons just isn't an option at the moment) but, rather, to learn enough techniques that I can use them to supplement my existing skills and keep my playing from becoming stale.
Comment: You may not want years and years of lessons,  but how about a couple intro lessons with a classical teacher?  He/she would be able to evaluate your form and current finger-style technique and help you adapt to basic classical.
Comment: I'm more in your boat than theirs, so I'll comment, not answer, but what I see is them doing active basslines with active treble lines, which is like travis picking but harder. The stuff amazes me.
Answer: Much of sounding good when playing classical music is in having the ability to make the correct voice stand out at the proper time. Classical guitar songs generally have at least 2 voices and frequently 3 and sometimes more. You can practice this by picking an easy song with 2 voices. The first time through make the high voice the dominant voice and play a second time through and make the low voice dominant. If you've been fingerpicking rock/folk then you'll probably need to learn the rest stroke in order to make the voices stand out.
Also, as Michael said, and I want to reiterate, fingernails are very important. If they aren't right then it becomes really hard to get the voicing and then the songs sound muttled. I struggle with that all the time because I don't like long fingernails, but it definately makes my playing go from a 2 to a 6 or 7 when my nails are longer and trimmed at the right angles.
Answer: If you're not interested in learning to play "legit" classical guitar I dare say you are on the right track.  Find some music that you like and start learning it.  The first few pieces will feel like a lot of work, but it will get easier every time.
The process of learning the music will expose the areas in your technique that need work.  When you hit a portion of the music that you have trouble with, make an exercise out of it.
Comment: This may be the best answer yet!
Answer: One skill is fingernail management, and understanding its relationship to tone. No joke: classical players focus highly on the combination of nail/finger that plucks the string.
I learned this from a former teacher (I'm not an expert). From what I remember, there are no set "rules" in terms of how much nail to use, but the quest for "tone" was much the same as an electric player will critique amps, pedals, pickups, etc. Then, once the preference is established, there is a lot of work with files etc to maintain that amount of nail.
Answer: A lot of it comes back to basics - when starting to use p i m a and pinkie take it slow. Practice simple sequences first, with a slow metronome (for example strings from low to high and back pimamip) and follow with slightly more complex sequences (pmiampai) and onwards (eg pmipiapmapia) etc
Letting your fingers get used to working independently slowly and then building speed is key to being able to build in classical picking styles.
Comment: The pinky, when used, is denoted "e".
Answer: You should follow some sort of technique manual. I really like the Celedonio Romero book. I've heard good things about Segovia (the way I heard it, he even tells you how to make your own strings out of animal intestines). And the Sor method is fascinating (but very dense).
A good technique book will give you

explanation and photographs of correct positions
a selection of nice pieces in varying difficulty
exercises to develop speed and accuracy
Comment: Downvoter, care to explain? You don't like books?
Answer: There is some great repertoire out there for beginning and novice players. This will help you develop your technique while playing 'real' music. A lot of players started with the book 100 Graded Classical Guitar Studies, edited by Fredrick Noad. It's still in print, and can be had for about $20/ US new.
The pieces are sequenced by difficulty, and even the easiest pieces are by well-known composers and interesting to play. Even if you only tackle a few of the earliest pieces, you'll be developing the skills you would need to tackle more challenging repertoire, and you can then apply these skills to whatever music you like.
I would also suggest that, even if years of lessons aren't in the cards, that you consider taking a few lessons with a good teacher. You'll likely get more out of the process with a little expert guidance.

Skills needed for classical guitar


Outlook 2007 constantly disconnected

Question: I have exchange on my server it has been working fine for over the last year but as of 2 days it is now saying in my outlook 2007 it is displaying disconnected and it doesnt want to connect. Any ideas how to reconnect to my exchange server
Answer: Check your network connection to your Exchange server. Can you ping your Exchange server from your client using the hostname? If you can proceed, if you cannot then you have a network layer issue between your client and Exchange.
Hold down CTRL and right-click the Outlook icon in your system tray and choose "Connection Status". You should see your Exchange server under general and it should say "Disconnected" if you aren't connected. Go ahead and click "Reconnect" to attempt to reconnect.
Comment: i can connect to the server from the workstation. when i right click the outlook in the system tray there is nothing in the connection status it appears to be blank
Comment: Hold down CTRL and right-click the Outlook status icon in the system tray.
Comment: i did that. Anyway i found out the cause there was little space on the disk so it disabled a service and unmounted the First storage mailbox so i just had to mount it and restart the service
Answer: If you can ping your exchange server then

go to regedit and
delete the profilelist without the admin profilelist and
on the cmd prompt execute gpupdate

Reconfigure your outlook. The problem should be resolved then.

Outlook 2007 constantly disconnected


What's the most pain-free way to fit logistic growth curves in R?

Question: This isn't as easy to Google as some other things as, to be clear, I'm not talking about logistic regression in the sense of using regression to predict categorical variables.
I'm talking about fitting a logistic growth curve to given data points. To be specific, $x$ is a given year from 1958 to 2012 and $y$ is the estimated global CO2 ppm (parts per million of carbon dioxide) in November of year $x$.
Right now it's accelerating but it's got to level off at some point. So I want a logistic curve.
I haven't found a relatively straightforward way to do this yet.
Comment: A logistic curve isn't the only curve that 'levels off'. Indeed a multiple of any continuous cdf would satisfy that requirement.
Comment: Use the package grofit Makes use of spline and growth curves.
Comment: I think you are taking me to be @user2581681. I just edited their answer.
Comment: Nick, thank you very much for positng your code, I was just wondering how to write it as an equation? in the code the values C, a and K refer to which parameters?
Answer: See the nls() function. It has a self starting logistic curve model function via SSlogis(). E.g. from the ?nls help page
DNase1 <- subset(DNase, Run == 1)

## using a selfStart model
fm1DNase1 <- nls(density ~ SSlogis(log(conc), Asym, xmid, scal),
                  DNase1)

I suggest you read the help pages for these functions and probably the linked references if possible to find out more.
Answer: I had the same question a little while ago. This is what I found:
Fox and Weisberg wrote a great supplemental article using the nls function (both with and without the self-starting option mentioned by Gavin). It can be found here.
From that article, I ended up writing a function for my class to use when fitting a logistic curve to their data:
### Log fit - be sure to use quotes around the variable names in
### the call
log.fit <- function(dep, ind, yourdata){
#Self-starting ...

y <- yourdata[, dep]
x <- yourdata[, ind]

log.ss <- nls(y ~ SSlogis(x, phi1, phi2, phi3))

#C
C <- summary(log.ss)$coef[1]
#a
A <- exp((summary(log.ss)$coef[2]) * (1/summary(log.ss)$coef[3]))
#k
K <- (1 / summary(log.ss)$coef[3])

plot(y ~ x, main = "Logistic Function", xlab=ind, ylab=dep)
lines(0:max(x), predict(log.ss, data.frame(x=0:max(x))), col="red")

r1 <- sum((x - mean(x))^2)
r2 <- sum(residuals(log.ss)^2)

r_sq <- (r1 - r2) / r1

out <- data.frame(cbind(c(C=C, a=A, k=K, R.value=sqrt(r_sq))))
names(out)[1] <- "Logistic Curve"

return(out)
}


Solving characteristic equation to find eigenvalue.

Question: I came across the following question:
The characteristic polynomial of a $3 \times 3$ matrix $A$ is $|\lambda I -A| = \lambda^3  + 3 \lambda^2+4 \lambda +3$. Find $trace(A)$ and $det(A)$.
I know that I have to find the eigenvalues $x$ from the characteristic equation $x^3  + 3 x^2+4 x +3 =0$, then add them to find $trace(A)$ and multiply them to find $det(A)$. However, I am not able to find roots the cubic equation.
I tried finding its solution by del Ferro's depressed cubic form (explained in Sec-$1.3$ of Complex Analysis by Newman and Bak). I replaced $x$ by $y-1$ in the characteristic equation and got the cubic equation $y^3+y+1=0$. On solving further as per the method, I got
$x=u+v= \sqrt[3]{\frac{-1}2+ \sqrt{\frac 14 + \frac 1{27}}}+\sqrt[3]{\frac{-1}2- \sqrt{\frac 14 + \frac 1{27}}}$.
I cannot solve it any further, hence can't find trace or determinant. Any idea how to it solve further to find the root. Also any idea on how to do it by any other method (like by writing down its companion matrix - I don't know how to do it).
Thank you.
Answer: It is hard to find out the roots, but all we need is the sum and product of all the roots. In a polynomial $x^3+ax^2+bx+c$, the sum of all roots is simply $-a$, which is $trace(A)$, and the product is $(-1)^3c$ which is $det(A)$.
To sum up, $trace(A)=-3$, $det(A)=-3$.
Comment: Why do we always sum up, and never multiply out?
Comment: @Indominus Well, since $c=3$ don't you think $det(A)=(-1)^3c=-3$? ............Anyways, I missed that part completely... Thanks....
Comment: Yes, you are right, thanks! Let $\lambda = 0$, we can get $c=det(-A)$, so $det(A)=(-1)^3c$
Comment: @GerryMyerson, love your comment!!


What is an easy way to commit work half way through a transaction, but then continue to

Question: Background
I am using the github.com/jmoiron/sqlx golang package with a Postgres database.
I have the following wrapper function to run SQL code in a transaction:
func (s *postgresStore) runInTransaction(ctx context.Context, fn func(*sqlx.Tx) error) error {
    tx, err := s.db.Beginx()
    if err != nil {
        return err
    }
    defer func() {
        if err != nil {
            tx.Rollback()
            return
        }
        err = tx.Commit()
    }()
    err = fn(tx)
    return err
}

Given this, consider the following code:
func (s *store) SampleFunc(ctx context.Context) error {
    err := s.runInTransaction(ctx,func(tx *sqlx.Tx) error {

        // Point A: Do some database work

        if err := tx.Commit(); err != nil {
            return err
        }

        // Point B: Do some more database work, which may return an error
    })
}

Desired behavior

If there is an error at Point A, then the transaction should have done zero work
If there is an error at Point B, then the transaction should still have completed the work at Point A.

Problem with current code
The code does not work as intended at the moment, because I am committing the transaction twice (once in runInTransaction, once in SampleFunc).
A Possible Solution
Where I commit the transaction, I could instead run something like tx.Exec("SAVEPOINT my_savepoint"), then defer tx.Exec("ROLLBACK TO SAVEPOINT my_savepoint")
After the code at Point B, I could run: tx.Exec("RELEASE SAVEPOINT my_savepoint")
So, if the code at Point B runs without error, I will fail to ROLLBACK to my savepoint.
Problems with Possible Solution
I'm not sure if using savepoints will mess with the database/sql package's behavior. Also, my solution seems a bit messy -- surely there is a cleaner way to do this!
Comment: how about splitting your function in two and running one after another in separate transactions? if the first one fails do not run the second.
Comment: See [https://github.com/golang/go/issues/7898](https://github.com/golang/go/issues/7898). Sub(nested)-transaction is not yet supported, but you can use `SAVEPOINT` in PostgreSQL.
Comment: Yes, use the proposed method.
Comment: See my comment to your answer.
Comment: @putu, is the solution I proposed the way to go?
Answer: Multiple transactions
You can split your work in two transactions:
func (s *store) SampleFunc(ctx context.Context) error {
    err := s.runInTransaction(ctx,func(tx *sqlx.Tx) error {
        // Point A: Do some database work
    })
    if err != nil {
        return err
    }
    return s.runInTransaction(ctx,func(tx *sqlx.Tx) error {
        // Point B: Do some more database work, which may return an error
    })
}

Comment: In this case your possible solution using safepoints should work (if your database supports safepoints).
Comment: Make that [`savepoint`](https://www.postgresql.org/docs/current/static/sql-savepoint.html) ("v" not "f").
Comment: The reason I'd like to avoid this is that I insert a new row in Point A, and do not want that row to be modified before Point B is complete. If I have two distinct transactions, then someone else could possibly mess around with the row from Point B. Is it possible to use nested transactions?
Answer: I had the problem alike: I had a lots of steps in one transaction.
After starting transaction:

BEGIN
In loop:

SAVEPOINT s1
Some actions ....
If I get an error: ROLLBACK TO SAVEPOINT s1
If OK go to next step

Finally COMMIT

This approach gives me ability to perform all steps one-by-one. If some steps got failed I can throw away only them, keeping others. And finally commit all "good" work.


C# how to move items of listview1 from usercontrol to another listview of usercontrol

Question: Is it possible or is there any way to transfer the ListViewItems from usercontrol(child) to the another usercontrol(Parent) how could i do that without instances to parent? because i want to transfer the data from the listview of the child to pass on its parent. i cant instance parent because the parent is already showed but disabled. when my child usercontrol is closed or disposed, the parent will be enabled again how can i move my items from the child to its parent ?
P.S: Usercontrol1 is the parent of Usercontrol2
Comment: A bit more clarity on the question would be helpful to solve your issue.
Comment: @GeekyCoder check my edited.
Comment: yes it is possible. but you will need references and/or helper function.. disabling the an lv doesn't prevent it from receiving items through code.
Comment: @TaW i did the ref function and it works little bit, it says that listviewitem cannot passed as an out or ref what should i do?
Comment: A function to move a listviewitem can be as simple as this : `public void moveItem(ListView lv1, int oldIndex, ListView lv2, int newIndex)
    {
        oldIndex = Math.Min(oldIndex, lv1.Items.Count-1);
        ListViewItem lvi = lv1.Items[oldIndex];
        lv1.Items.RemoveAt(oldIndex);
        lv2.Items.Insert(Math.Min(newIndex, lv2.Items.Count), lvi);
    }`
Answer: Okay, I think this is right i ended up in using this code:
<code> private void button1_Click(object sender, EventArgs e)
    {
        string[,] name = new string[listView1.Items.Count,2];//
        for(int i = 0; i < listView1.Items.Count; i++)       //
        {                                                    // This will insert the items from the listview to array
            name[i,0] = listView1.Items[i].Text;             //
            name[i, 1] = listView1.Items[i].SubItems[1].Text;//
        }                                                    //
        ucAddBook.pass(ref name);//called the method from parent and set name as reference in parameter
        this.Dispose();//this will trigger the parent to loop the array that i pass then insert in the listview
    }
</code>
this is the code from parent
<code>    public static string[,] mylist { get; set; }// i set the array to static so if the usercontrol is already disposed the array wont get reset to null
    public void pass(ref string[,] name)        // this is where the array designated
    {
        mylist = name;
    }
    private void usercon_AddBook_ControlRemoved(object sender, ControlEventArgs e)
    {
        panel2.Enabled = true;
        for (int i = 0; i <mylist.Length/2; i++)                //
        {                                                       //
            ListViewItem item = new ListViewItem(mylist[i, 0]); // this will insert the items from array to listview
            item.SubItems.Add(mylist[i, 1]);                    //
            listView1.Items.Add(item);                          //
        }                                                       //
    }
</code>
Please let me know if my code needs an improvements; thanks;
NOTE: I updated the for loop i changed it from mylist.Length-1 to mylist.Length/2 because im using 2d array so the lenght would doubleup thats why i divide it into 2,so my array will not going to out of range.
Comment: If this works, fine. If it doesn't hen it isn't an answer and you should move the code to your question.
Comment: @Taw should i remove this and move to my question? sorry for asking im new here.
Comment: Yes, unless it actually __does__ answer the question. If it does, then it is a valid answer and you should leave it! I was unsure because of the comment about it _working only a little_
Comment: @TaW oh, yes this code works.  Sorry i misunderstood your comment. Ill just leave it here


Show that an unrestricted $3$-coloring of a plane triangulation $G$ has an even number of $3$-colored faces

Question: Show that an unrestricted $3$-coloring of a plane triangulation $G$ has an even number of $3$-colored faces.
Here an unrestricted $3$-coloring means that adjacent vertices can receive the same color. And a $3$-colored face is a face where its frontier has distinct colors in each vertex.
Comment: I don't quite understand what you mean by triangulation of the plane.
Is this infinite or not? If infinite, how can we talk about even or odd number of the 3-colored faces? Can you define this concept more precisely?
Answer: I think the idea should be something like this below.
Because I've seen somewhere 25+ years ago a competitive math problem of this kind whose solution impressed me quite a lot back then.
Let $s$ be any segment. Let also
$f(s) = 1$ if the two ends/vertices of the segment are colored differently;
$f(s) = 0$ if the two ends are of the same color.
Now for each triangular face $a$ denote $G(a)$ to be the sum of $f(s_{ai})$ for its three sides $s_{ai}$ where $i=1,2,3$.
Obviously $G$ can take only the values $0, 2, 3$.
You can make a few drawings and convince yourself in this.
Now sum $G(a)$ over all triangular faces $a$ and denote this sum by $S$.
On one side: $$S = n_0 \cdot 0 + n_2 \cdot 2 + n_3 \cdot 3$$
where $n_i$ is the number of triangular faces for which $G$ takes the value $i$.
On the other side each segment takes part in exactly two triangles. So in $S$ we  in fact sum up the $f(s)$ values for all segments, but actually each segment $s$ contributes two times its own $f(s)$ to $S$.
Therefore $S$ is even.
But then $n_3$ has to be even (from the above equation).
And this is what we wanted to prove.
Side note: I don't quite understand what you mean by triangulation of the plane.
Is this infinite? If so, how can we talk about even or odd number of the 3-colored faces?
Also I see in Wikipedia that different types of triangulations can be defined.
Triangulation (geometry)
But I am sure this problem (which you state) has something to do with this idea.
Comment: Hey! Thanks for answering. A [plane triangulation](https://en.wikipedia.org/wiki/Planar_graph#Maximal_planar_graphs) is a maximal plane graph.
Comment: @BigBlinders OK, in that case the argument I provided seems to work fine.


separating records based on a column

Question: I have four columns .Two columns are comma separated. I am trying to get individual records for those comma separated values.
col  col2   col3   col4
------------------------
1     1,2    2,3    4
2     3,4    5      7
4     5      3      5

My result set swill be
col1   col2   col3   col4
--------------------------
1        1      2     4
1        1      3     4
1        2      2     4
1        2      3     4
2        3      5     7
2        4      5     7
4        5      3     5

I have tried many. But couldn't get exact dataset. Thanks in advance
Comment: what's the maximum commas you can have in a column?
Comment: Not so easy as I understand : https://stackoverflow.com/questions/2696884/split-value-from-one-field-to-two
Comment: max of 5 commas
Answer: Here is one method that uses two derived tables of numbers to get the nth element from the list:
select col1,
       substring_index(substring_index(col2, ',', n2.n), ',', -1) as col2,
       substring_index(substring_index(col3, ',', n3.n), ',', -1) as col3,
       col4
from t join
     (select 1 as n union all select 2 union all select 3 union all select 4 union all select 5
     ) n2
     on t.col2 like concat(repeat('%,', n2.n - 1), '%') join
     (select 1 as n union all select 2 union all select 3 union all select 4 union all select 5
     ) n3
     on t.col3 like concat(repeat('%,', n3.n - 1), '%')

separating records based on a column


ios swift Hide UINavigationBar created by NavigationViewController

Question: I have several views in my storyboard.
The flow of the program is a user enters start mileage in my MileageViewController (which is a standard UIViewController) and then clicks a button to select their start location from a separate view. This view is a treeviewcontroller and because of editing I had to embed in a NavigationViewController which introduced a UINavigationBar and I have an edit button. I can edit my list (and I'll eventually add adding to the list).
All is fine... until I segue from a cell in the treeview back to my MileageViewController into which I update the title from the selected cell into startLocation UIText... hope I've painted a picture you understand... :)
My problem is that on getting back to the MileageViewController it now has a header (UINavigationBar) with Back to LocationChoiceTreeViewController.... how do I disable the header in this instance?
Comment: do you want to remove the whole bar so the viewController is "Full screen" or just remove the back button ?
Comment: remove the whole bar please... note it's not there the first time the user sees the MileageViewController... it only appears after they return from the LocationChoiceTreeViewController
Answer: on the viewWillAppear of the controller
<code>if let n = navigationController {
    n.setNavigationBarHidden(true, animated: false)
}
</code>


Ao lidar com delete/update, devo fazer o unsubscribe no modo Async Pipe?

Question: Eu sou novato em Angular.
Um dos principais objetivos do async pipe é automaticamente cuidar de se inscrever (subscribe) e cancelar sua inscrição (unsubscribe).
Tenho duas dúvidas:
Primeira Dúvida
Ao lidar com delete ou update  (ambos são API services), Preciso cancelar a inscrição via ngOnDestroy?
projects$: Observable<Project[]>;

constructor(
    private projectService: ProjectService,
) { }

ngOnInit() {
    this.loadProject();
}

loadProject(){
    this.projects$ = this.projectService.getProjects()
    .pipe(
        map(result => {
            if(result.success){
                return result.data;
            }
        })
    );
}

deleteProject(){
    if(this.projectToDelete){
        const id = this.projectToDelete.id;
        this.projectService.deleteProject(id).subscribe(result => {
            if(result.success){
                this.loadProject();
            }
        });
    }
}

Segunda Dúvida
Existe uma outra maneira de deletar um elemento especifico de um Observable sem chamar a API que carrega o projects$? Algo abaixo, diferente com o código de cima:
    //Neste caso  this.projectsects type não é um observable.
    deleteProject(){
        if(this.projectToDelete){
            const id = this.projectToDelete.id;
            this.projectService.deleteProject(id)
            .subscribe(result => {
                if(result.success){
                    this.projects = this.projects.filter(item => {
                        return item.id != id;
                    });
                    this.projectToDelete = null;
                    this.closeModal();
                }
            });
        }
    }

Answer: Da documentação do Angular:
"The async pipe subscribes to an Observable or Promise and returns the latest value it has emitted. When a new value is emitted, the async pipe marks the component to be checked for changes. When the component gets destroyed, the async pipe unsubscribes automatically to avoid potential memory leaks."
O Async Pipe irá fazer tanto o subscribe como o unsubscribe automaticamente quando o componente é iniciado e destruido
Você deve filtrar o array dentro da função map para alterar o valor de um Observable:
this.projects$ = this.projects$.map(
    project => project.filter(
        item => item.id != id
    )
);


Regex exclude word from matches

Question: Does anyone know what am I doing wrong?
I have this sentence:
hi [user=1234]John Jack[/user] take me home

and I need regex which select only John Jack
My regex:
(\[user=\d\d\d\d](.+?)\[\/user\])(?!(\[user=\d\d\d\d\])|(\[\/user\]))

I want exclude [user=1234] and [/user]
This (\[user=\d\d\d\d](.+?)\[\/user\]) selects [user=1234]John Jack[/user] but I want only John Jack
Full example:

hi [user=1234]John Jack[/user] take me home. [user=12] Jonno Ha
  [\user] where you are [differentTag] hm?  [/differentTag]. Peter Im
  here with [user=1]Danny Di [\user]
Comment: I think you should show us more data here, and also put it in context.  Do you want an answer tailored only for _this_ sentence, or for other sentences as well?
Comment: value.substring(value.firstindexof(']'), value.lastindexof('[')) ???
Comment: @TimBiegeleisen yes  answer tailored only for this sentence will be enough.
Comment: @MichaelShrestha substrings this is not good way because there are another tags in sentences
Comment: @LukStorms I need get name in the user tag
Answer: Alternative to the answer from @matoni with "lookahead" and "lookbehind" syntax, you can use grouping (which are already defined in your pattern) and extract an appropriate group:
    String s = "hi [user=1234]John Jack[/user] take me home ...";
    Pattern p = Pattern.compile("\\[user=\\d+\\](.+)\\[/user\\]");
    Matcher m = p.matcher(s);
    while (m.find()) {
        System.out.println(m.group(1));
    }

Comment: P.S. just do not go wild with groups (as it was in your example) define only those that you need
Answer: (.+?) is group indexed as 2 and it should hold John Jack so you should be able to obtain it via matcher.group(2).
Demo:
String text = "hi [user=1234]John Jack[/user] take me home. [user=12] Jonno Ha [\\user] where you are [differentTag] hm? [/differentTag]. Peter Im here with [user=1]Danny Di [\\user]";
Pattern p = Pattern.compile("(\\[user=\\d\\d\\d\\d](.+?)\\[\\/user\\])(?!(\\[user=\\d\\d\\d\\d\\])|(\\[\\/user\\]))");
Matcher m = p.matcher(text);
if(m.find()){
    System.out.println(m.group(2));
}

Output: John Jack

If you wanted to find more users you need to change if to while and fix your regex because

currently you are searching for users with 4 digit IDs so it will fail to match [user=12] or [user=1]. So instead of \d\d\d\d you can use \d+.
you are using [user=ID]..[/user] but also [user=ID]..[\user] (both / and \].

BTW since Java doesn't use /regex/flags syntax, / is not considered as special character so you don't need to escape it.
Also I am not sure why you need (?!(\\[user=\\d\\d\\d\\d\\])|(\\[\\/user\\])) at the end of your regex, it doesn't really do anything in example you showed so it looks like it can be removed. Also we don't need to surround earlier part with parenthesis because look-ahead doesn't add anything to whole match which is already placed in group 0, so we don't need separate group which will duplicate that match. After removing those those extra parenthesis (.+?) will be indexed as group 1.
Modified and simplified solution can look like:
String text = "hi [user=1234]John Jack[/user] take me home. [user=12] Jonno Ha [\\user] where you are [differentTag] hm? [/differentTag]. Peter Im here with [user=1]Danny Di [\\user]";
Pattern p = Pattern.compile("\\[user=\\d+](.+?)\\[(/|\\\\)user]");
Matcher m = p.matcher(text);
while(m.find()){
    System.out.println(m.group(1).trim());
}

Output:
John Jack
Jonno Ha
Danny Di

Answer: Try this:
String s = "hi [user=1234]John Jack[/user] take me home";
// assuming user id has always 4 decimals
Pattern p = Pattern.compile("(?<=\\[user=\\d{4}\\]).+(?=\\[/user\\])");
Matcher m = p.matcher(s);
m.find();
System.out.println(s.substring(m.start(), m.end()));

Note, you can not use in "lookbehind" pattern of variable length like (?<=.+). So if you know, that user id has at max e.g. 11 places, then you can use:
Pattern.compile("(?<=\\[user=\\d{4,11}\\]).+(?=\\[/user\\])");

For more details about regex see: Pattern javadoc
Answer: Full decoding:
public class RegExpPattern_002 {

   public static void main( String[] args ) {
      final String text =
         "hi [user=1234]John Jack[/user] take me home."
         + " [user=12] Jonno Ha [/user]"
         + " where you are [differentTag] hm? [/differentTag]."
         + " Peter Im here with [user=1]Danny Di [/user]";
      final Pattern p = Pattern.compile(
         "([^\\[]*)\\[(\\w+)(=([^\\]]+))?\\]([^\\[]*)\\[/(\\w+)\\]" );
      final Matcher m = p.matcher( text );
      while( m.find()) {
         final String preText   = m.group( 1 );
         final String attrOpen  = m.group( 2 );
         final String value     = m.group( 4 );
         final String content   = m.group( 5 );
         final String attrClose = m.group( 6 );
         assert attrClose.equals( attrOpen );
         System.err.printf(
            "pre = '%s', attr = '%s', value = '%s', content = '%s'\n",
            preText, attrOpen, value, content );
         System.err.println("-----------------------------");
      }
   }
}

Execution log:
pre = 'hi ', attr = 'user', value = '1234', content = 'John Jack'
-----------------------------
pre = ' take me home. ', attr = 'user', value = '12', content = ' Jonno Ha '
-----------------------------
pre = ' where you are ', attr = 'differentTag', value = 'null', content = ' hm? '
-----------------------------
pre = '. Peter Im here with ', attr = 'user', value = '1', content = 'Danny Di '
-----------------------------

Answer:
I assume you no need any java code, otherwise please comment me to delete the answer

to exclude[user=1234] and [/user] you can use:
[^\]\[a-zA-Z=\d\/]
and for matching other parts:
[a-zA-Z ]*[^\]\[a-zA-Z=\d\/][a-zA-Z]*

and for input:
hi [user=1234]John Jack[/user] take me home. [user=12] Jonno Ha [\user] where you are [differentTag] hm? [/differentTag]. Peter Im here with [user=1]Danny Di [\user]

you can use:
[a-zA-Z ]*[^\]\[a-zA-Z=\d\/\\]+[a-zA-Z ]*

It matches all things except all inside []
[a-zA-Z ]*[^\]\[a-zA-Z=\d\/\\]+[a-zA-Z ]*
It excludes:
[user=1234]
[/user]
[user=12]
[\user]
[differentTag]
[/differentTag]
[user=1]
[\user]

and if you want to match only the user name before [/user] or [\user] you cat try:
[a-zA-Z ]+(?=\[(?:\\|\/)user\])

[a-zA-Z ]+(?=\[(?:\\|\/)user\])
it matches:
John Jack
Jonno Ha
Danny Di

and more efficient than above:
(?<=])[a-zA-Z ]+(?=\[(?:\\|\/))

and still matches:
John Jack
Jonno Ha
Danny Di

Regex exclude word from matches


Can't make my crescendo end were I want it to with Lilypond

Question: I'm trying to reproduce a scanned score with Lilypond. The original (the part of interest, at least), looks like this :

As you can see, there is a crescendo starting at the beginning of the 3rd bar, and ending at the end of the 4th bar.
My Lilypond code is the following (I put the crescendo in the upper staff) :
%%%%%%%%%%
%% VERSION
%%%%%%%%%%

\version "220.127.116.11"

%%%%%%%%%%%
%% PIANO UP
%%%%%%%%%%%

pianoUpper = \relative c' {
    \clef "treble"
    \time 3/4
    \key c \major

    f4-. \p a-. c-. |
    e,-. g-. c-. |
    a( \< b c) |
    2.\fermata \! \bar "||"

    \time 6/8

    <e, g>8.( \p <f a>16 <e g>8 <c e>4.) |
}

%%%%%%%%%%%%
%% PIANO LOW
%%%%%%%%%%%%

pianoLower = \relative c {
    \clef "bass"
    \time 3/4
    \key c \major

    <f a c>2. |
    <g c> |
    <d a' c> |
    <g b>\fermata \bar "||"

    \time 6/8

    <c, e g>4 <c e g>8 <c e g>4. |
}

%%%%%%%%
%% SCORE
%%%%%%%%

\score {
    <<
        \new PianoStaff <<
            \new Staff = "upper" \pianoUpper
            \new Staff = "lower" \pianoLower
        >>
    >>
}

And it produces the following result :

Which is upsetting, because I would very much like the crescendo to finish just after the accord of the 4th bar. I have tried placing the \! at different places, with no satisfying result.
Has someone an idea of how I can have the crescendo ending at the end of bar 4, like on my original scanned score?
Answer: You can input an empty chord with <> and let the hairpin end on it. This way, you don't need to input an \override or scale the duration.
\new Voice {
  \time 3/4
  \relative c' { a'4(\< b c) | 2.\fermata <>\! \bar "||" }
}

The above code should render as:
Comment: I don't remember where I learned this trick and could not find it in the documentation. But it is especially helpful when you deal with multiple voices. I think it works for spanners in general.
Comment: This is actually a better solution. I didn't know that. I'll add it to my repertoire.
Answer: The hairpin that ends on the first beat of a measure stops at the bar line. To change this, override the property to-barline to false.
...

f4-. \p a-. c-. |
e,-. g-. c-. |
\once \override Hairpin.to-barline = ##f
a( \< b c) |
2.\fermata \! \bar "||"

...

See here: http://lsr.di.unimi.it/LSR/Item?id=595
If you want the hairpin to go further than that, use a scaled duration and spacer rests to trick the hairpin to end at an invisible note at the third beat of the measure.
...

f4-. \p a-. c-. |
e,-. g-. c-. |
\once \override Hairpin.to-barline = ##f
a( \< b c) |
2.*1/3 \fermata s4 s \! \bar "||"

...

See here about scaling durations: http://lilypond.org/doc/v2.20/Documentation/notation/writing-rhythms#scaling-durations
Comment: You could also let the hairpin end on a void chord using `<>\!`. This way, you don't have to insert spacer rests.
Comment: @JambonSama I added my comment as new answer. Actually, there is no "best" answer to your approach. I would perhaps not necessarily scale durations because I think this is a quite hacky solution and may have some negative effects on the placement of the notes, but I guess the solution with overriding the hairpin's `to-barline` property is actually one of the intended ways to solve your problem.
Comment: @JasperHabicht how so? I am very new at Lilypond, so I tried finding the corresponding documentation, but no such luck. And between your suggestion and TiagoPC's solution, which one is actually better / more recommended / better practice?


Solving recurrence $T(n) = T(\lfloor{\frac{n}{2}}\rfloor) + T(\lceil{\frac{n}{2}}\rceil) + cn$ is $O(n\text{log}(n))

Question: So I need to prove that T(n) is $O(n\text{log}(n))$, considering $c>0$ is a constant and using substitution method
What I've tried so far:
We need to prove that $T(n) \leq dn\text{log}(n), d\geq0$
Assuming that $T(\frac{n}{2}) \leq dn\text{ln}(\frac{n}{2})$, we have
$T(n) \leq dn\text{ln}(\lfloor{\frac{n}{2}}\rfloor) + dn\text{ln}(\lceil{\frac{n}{2}}\rceil) + 1$
Removing the ceil and the floor, I'm guessing we don't want to equal both of them to $\frac{n}{2}$, so
$T(n) \leq dn\text{ln}(\frac{n}{2}) + dn\text{ln}(\frac{n+1}{2}) + 1$
$T(n) \leq dn\text{ln}(n)-dn\text{ln}(2) + dn\text{ln}(n+1) - dn\text{ln}(2)+1$
$T(n) \leq dn\ln(n) + dn\ln(n+1) -2dn + 1$
And I have no idea how to continue this.
Answer: By strong induction, $T$ is a growing function. Indeed,
$$T(2)=2T(1)+c>T(1)$$ and
$$T(n+1)=T\left(\left\lfloor\dfrac{n+1}2\right\rfloor\right)+T\left(\left\lceil\dfrac{n+1}2\right\rceil\right)+c(n+1)>T(n).$$
Now if we take $n:=2^k$,
$$T(2^k)=2T(2^{k-1})+c\,2^k,$$ which can be written
$$S(k)=2S(k-1)+c\,2^k.$$
Using the theory of linear recurrences, we know that the solution will be of the form
$$S(k)=(ak+b)2^k$$ and by identification,
$$(ak+b)2^k=2(ak-a+b)2^{k-1}+c\,2^k,$$
$a=c$ and $b$ is free. Hence
$$S(k)=(ck+S(0))2^k$$ and
$$T(n)=(c\log_2(n)+T(1))n.$$
As the function is monotonous, this justifies the $O(n)$ bound, and even $\Theta(n)$.

Below, the exact curve of $\dfrac{T(n)}n$ for $c=1,T(1)=0$.

In fact, though you can't see it on this plot, the growth is perfectly linear between two powers of $2$.


How to reconnect chromecast device when restart app in android

Question: Hello  every one i faced one problem regarding chromecast when i connect to chromecast device and remove app from background and after that again open app
but app disconnect  to chromecast device can any idea to auto connect chromecast device to my app please suggest .
Answer: You can follow our documentation on this very subject, if yo want to do it yourself, or you can use Cast Companion Library that does it for you. In short, you need to persist a few pieces of data (such as session id, route id) and use them to perform reconnection.


How to Export MySQL Database From Digital Ocean Managed Database

Question: I have a MySQL database hosted on Digital Ocean Managed Database service. I lost my previous dev machine and did not push the Schema to git along with application files. I am desperate to get back the SQL Schema  in my local machine for further Development but have so far been usuccessfull. I have tried so many commands from different suggestions but they all failed.
I connect to the DB via the MySQL Shell using the command:
mysql -u username -password-h example-test-do-user-7878789-0.b.db.ondigitalocean.com -P 25060 -D example_db
All queries are executed successfully via this shell method. When trying to Dump the Schema to my machine, I use the following command:
mysql -u username -p -h mysql-test-do-user-4915853-0.db.ondigitalocean.com -P 25060 your_database_name \> database_file_name.sql
But I get the error as follows: mysqldump: unknown variable 'set-gtid-purged=OFF'
if I remove that part and try again, I get the error:
mysqldump: Got error: 2003: "Can't connect to MySQL server on 'localhost' (10061 "Unknown error")" when trying to connect
which doesnt make sense to me. So, without further ranting; How to I achieve my intended result.
NOTE: I did try Mysql workbench, but it won't connect all together
Answer: I can appreciate trying to achieve what you want via mysql shell. I stumbled across the same problem and for quite some tie did not find the help i needed, then I tried doing it using mysql workbench. Try it and you will find that its easier than usin the command-line approach. MySQL Workbench has a good GUI  based database miguration capability. You can migrate you Do Managed DB directly into you local mysql server or export a schema dump. If you decide to go wit this approach, just make sure you add your machine's IP as a trusted source, else you will not be able to connect.
Comment: Did you copy this from somewhere? Best to include a source link.
Answer: I noticed this issue too on DigitalOcean and it's because the database hostname contains special characters which confuses mysqldump .. it's better to save the hostname as a variable.
This is the bash function we use in SlickStack:
function ss_mysqldump_user {
    command mysqldump --user="${DB_USER}" --password="${DB_PASSWORD}" --host="${DB_HOST}" --protocol=tcp --port="${DB_PORT}" --no-create-db --no-tablespaces --single-transaction --dump-date --force "$@"
}

Doing this prevents the hostname from being misinterpreted.
More info:
https://slickstack.io/forum/topic/mysqldump-from-managed-remote-database-server


React.JS pass role value from top menu page to sub page

Question: I have the logon user's role infromation in the TopMenu.jxs
  getIsCurrentUserAdmin () {
    return _.some(this.props.currentUser.userRoles, ['roleId', 2]);
  },
  render: function () {
    let isCurrentUserAdmin = this.getIsCurrentUserAdmin();

How can I pass the value of isCurrentUserAdmin to my sub page, say UserDetails.jxs. Here userDetails mean that logon user is administrating other users' detailed information.
Please help me. I am a newbie to React.JS
Answer: If I understand the question correctly you are looking to pass down data to a component using props.
You can do this like so
render: function() {
  const isCurrentUserAdmin = this.getIsCurrentUserAdmin();

  return <MyOtherComponent isAdmin={isCurrentUserAdmin} />;
}

You will also need to add isAdmin to the PropTypes of MyOtherComponent, however using prop types is beyond the scope of this question. See the docs for a starting place about PropTypes
Comment: Thank, Spirift,  I have var UsersDetail = React.createClass({
  propTypes: {
    user: React.PropTypes.object,
    groups: React.PropTypes.object,
    ui: React.PropTypes.object,
    params: React.PropTypes.object,
    router: React.PropTypes.object,
  },
Comment: return
;   was added to TopMeny.jsx  But when I use  (this.props.isAdmin) in UsersDetail, I got erorr: 'isAdmin' is missing in props validation. Do I need to do anything before using it in UsersDetail ?
Comment: You should add every prop to the prop types as well. Add isAdmin to the prop types and the Type that it is and the error will go away. `isAdmin: React.PropTypes.bool` I'm guessing that this prop is a Boolean.


Question about differentation

Question: I can't understand a passage: given $f\in C^2([a,b]\times\mathbb{R}\times\mathbb{R}$), $f=f(x,u,\xi)$, $u \in C^2[a,b]$, we have
$\frac{d}{dx}[f(x,u,u')-u'f_\xi(x,u,u')] = f_x(x,u,u') + u'\Big[f_u(x,u,u')-\dfrac{d}{dx}[f_\xi(x,u,u')]\Big]$
I don't understand why, I thought:
$\frac{d}{dx}[f(x,u,u')-u'f_\xi(x,u,u')] = f_x(x,u,u') -u''f_\xi(x,u,u') - u'\dfrac{d}{dx}[f_\xi(x,u,u')]$
Where am I wrong? Thank you.
Answer: Without the intermediate steps, I don't know why you obtained a different result. In any case, the first equality is correct. Indeed we have that
$$\begin{align}\frac{d}{dx}[f(x,u,u')-u'f_\xi(x,u,u')]&=\dfrac{d}{dx}[f(x,u,u')]-
u''f_\xi(x,u,u')-u'\dfrac{d}{dx}[f_\xi(x,u,u')]\\
&=\left(f_x(x,u,u')+f_u(x,u,u')u'+f_\xi(x,u,u')u''\right)\\
&\qquad-
u''f_\xi(x,u,u')-u'\dfrac{d}{dx}[f_\xi(x,u,u')]\\
&= f_x(x,u,u') + u'\Big[f_u(x,u,u')-\dfrac{d}{dx}[f_\xi(x,u,u')]\Big].
\end{align}$$
Comment: @FrancescoMengoli You are welcome!
Comment: First of all, I would like to thank u for the time you dedicated to answer me. Furthermore, I didn't think about continuing the derivation,  that was my mistake, the first equation was of the book, the second one my attempt to solve. Thank you.

Question about differentation


Reverse proxy with SSL and IP passthrough?

Question: Turns out that the IP of a much-needed new website is blocked from inside our organization's network for reasons that will take weeks to fix.  In the meantime, could we set up a reverse proxy on an Internet-based server which will forward SSL traffic and perhaps client IPs to the external site?  Load will be light. No need to terminate SSL on the proxy.  We may be able to poison DNS so original URL can work.
How do I learn if I need URL rewriting?  Squid/apache/nginx/something else?  Setup would be fastest on Win 2000, but other OSes are OK if that would help.  Simple and quick are good since it's a temporary solution.
Thanks for your thoughts!
Answer: Since you need to do URL rewrite, you can use ARR (Application Request Routing) with IIS 7 (or higher).There is an option to disable "SSL offloading" if you do not wish to terminate SSL on proxy end.
http://www.iis.net/learn/extensions/configuring-application-request-routing-(arr)/http-load-balancing-using-application-request-routing
To ensure that Client IPs are carried over, you can install ARRHelper as per
http://blogs.iis.net/anilr/archive/2009/03/03/client-ip-not-logged-on-content-server-when-using-arr.aspx.
I assume your web site is running IIS.
Alternatively, for something quick and dirty on Windows, use netsh portproxy to proxy all TCP 443 (SSL) traffic over.
<code>netsh interface portproxy add v4tov4 listenport=443 listenaddress=188.8.131.52 connectport=443 connectaddress=10.0.0.2
</code>
See http://technet.microsoft.com/en-us/library/cc731068(v=ws.10).aspx#BKMK_1
Make sure IIS is not installed, and take note that client IP is not carried over.
Answer: Easiest reverse proxy solution for you will probably be IIS 7 with Application Request Routing. It's a very quick install so even if it's not what you're looking for, at least you can give it a shot without spending a whole lot of time.
http://learn.iis.net/page.aspx/489/using-the-application-request-routing-module/
http://www.hanselman.com/blog/NewModulesForIIS7ApplicationRequestRoutingProxyAndLoadBalancingModule.aspx
Comment: Thanks for the tip.  Unless it's changed since http://blogs.iis.net/wonyoo/archive/2008/07/10/ssl-off-loading-in-application-request-routing.aspx ARR can't do the "CONNECT tunneling" that's needed to avoid terminating SSL at the proxy. Is there a workaround?
Answer: I use Squid on Window 2003 from http://squid.acmeconsulting.it/  It works very well for as a normal web proxy.
If you think Squid might work, they also have an SSL binary of Squid 2.7 (stable-8) that is "for reverse proxy only - EXPERIMENTAL"
Answer: Even though your question is already 9 years old there might be other people having the same problem.
You can just use Tor Browser(Wikipedia Article). If it can get through the Great Firewall of China, it can also make any needed site available in a organization's network.
I know this is not an explanation how to set up a proxy server but the question was how to do it simple and quick. And it is:
Download Tor Browser --> Start Tor Browser --> Maybe configure bridges --> Click Connect --> Surf an anonymous web without censorship, tracking and surveillance
You don't even need admin rights!
Tor Browser is secure, anonymous and FLOSS(Free / Libre Open Source Software) licensed under the GPLv3(GNU General Public License, version 3)(Wikipedia) a free, copyleft license by the FSF(Free Software Foundation).
I know this forum is about servers but the question is here and this is also a solution.
Comment: it is not about if it works or not, it is about if your solution is scalable and secure enough to be used organization-wide. implementing Tor organization-wide isn't efficient (i.e. think hundreds of endpoints), filtering it isn't efficient enough (i.e. a lot of NSFW contents), building policies around that is complex enough, and securing your endpoints is difficult enough; that running reverse proxy costing somewhere around USD 60 per year is cheaper and much more efficient than dealing with that.


Production Instance : CLOSE_WAIT Connection Issue

Question: I am using 10EC2 Instances behind 1 ELB. And ELB configured 80 to 8080 and 443 to 8080 port.
And all 10EC2 instances having installed with Apache Tomcat, total request on ELB around 8000 to 10000 in 1 minute.
I am facing problem for CLOSE_WAIT connection on 10 EC2 Instance, having Apache Tomcat.
EC2 Instance Type : m1.xlarge
When we restart the Apache Tomcat, all CLOSE_WAIT connections are lost, but its not proper way to work on Production Instances.
Please help me out.
Comment: Same problem here! But the strange thing is I am running workers that are connected to my local nginx using unix socket. And these workers are stuck  with a connection on load balancer on SSL port. I tried many other solutions and it keeps happening (changed nginx to apache, and uwsgi to gunicorn for python workers). I believe its a ELB problem. And the worst thing is that sometimes it goes crazy an floods my EC2 instances with CLOSE_WAIT connections (more than 100k connections). Amazon support says its not an ELB issue. Any hints?
Answer: Some clients don't properly close the TCP connection when they're done.  That's out of your control.  These generally time out after a bit, and don't create too much of a problem, other than cluttering the listing you get from netstat -an and similar.
So, why you are having a problem with it?
This might be pertinent:  What limits the maximum number of connections on a Linux server?
Answer: This is a variant of the problem described here:
https://unix.stackexchange.com/questions/10106/orphaned-connections-in-close-wait-state
Does your application have many mobile clients? These clients, connecting over unreliable networks, can do crazy things with TCP states.
The simplest way to handle it is to reboot your apache instances in a rolling fashion - say, one server each 30 minutes. If you have enough instances behind your ELB then the net effect on your service should be bearable.
Comment: Earlier, all of the clients on the Internet were connecting over rather unreliable and slow networks and TCP states weren't gone crazy. )
Comment: Does this actually work?  My understanding is that those CLOSE_WAIT states are being maintained by the OS, and restarting apache processes should have no effect.
Answer: Check out cutter.
Cutter is a tool for linux-based firewalls that allows connections passing through them to be forcably [sic] aborted by the firewall administrator.


How to implement custom page transition with animation when navigate from one page to another?

Question: I want to achieve below custom animation when navigation from one page to another i am trying with hero animation but no luck any help will appreciated.
Thanks!
Comment: have you tried Hero Animation,
this is seems like can help https://medium.flutterdevs.com/animating-a-widget-across-screens-in-flutter-229a00a99d19
Comment: Try using SliverAppBar to achieve this kind of UI. It has built-in scroll animations & you can also define custom animations. https://api.flutter.dev/flutter/material/SliverAppBar-class.html
Comment: Can you share your UI code So we can add animations
Answer: I'd take look at this doc https://docs.flutter.dev/cookbook/animation/page-route-animation first.
I'd propose a mix between example shown there of slide-in transition where new page slides from the bottom in your example and mix it with fade-in transition shown here:
import 'package:flutter/material.dart';
import 'list.dart';

import 'main.dart';

class FadeAnimation extends StatelessWidget {
  static const routeName = 'Fade_Animation';
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Fade Animation"),
      ),
      body: ListView.builder(
          itemCount: curveList.length,
          itemBuilder: (context, index) {
            return Card(
              child: ListTile(
                title: Text("${curveList[index]}"),
                leading: CircleAvatar(
                  child: Text("${index + 1}"),
                  backgroundColor: Colors.white,
                ),
                onTap: () {
                  print(curveList.length);
                  Navigator.of(context).push(PageRouteBuilder(
                      pageBuilder: (context, animation, anotherAnimation) {
                        return ReturnPage();
                      },
                      transitionDuration: Duration(milliseconds: 2000),
                      transitionsBuilder:
                          (context, animation, anotherAnimation, child) {
                        animation = CurvedAnimation(
                            curve: curveList[index], parent: animation);
                        return FadeTransition(
                          opacity:animation,
                          child: child,
                        );
                      }));
                },
              ),
            );
          }),
    );
  }
}

The list.dart file:
import 'package:flutter/animation.dart';

List<Curve> curveList = [
  Curves.bounceIn,
  Curves.bounceInOut,
  Curves.bounceOut,
  Curves.decelerate,
  Curves.ease,
  Curves.easeIn,
  Curves.easeInBack,
  Curves.easeInCirc,
  Curves.easeInCubic,
  Curves.easeInExpo,
  Curves.easeInOut,
  Curves.easeInOutBack,
  Curves.easeInOutCirc,
  Curves.easeInOutCubic,
  Curves.easeInOutExpo,
  Curves.easeInOutQuad,
  Curves.easeInOutQuart,
  Curves.easeInOutQuint,
  Curves.easeInOutSine,
  Curves.easeInQuad,
  Curves.easeInQuart,
  Curves.easeInQuint,
  Curves.easeInSine,
  Curves.easeInToLinear,
  Curves.easeOut,
  Curves.easeOutBack,
  Curves.easeOutCubic,
  Curves.easeOutExpo,
  Curves.easeOutQuad,
  Curves.easeOutQuart,
  Curves.easeOutQuint,
  Curves.easeOutSine,
  Curves.elasticIn,
  Curves.elasticInOut,
  Curves.elasticOut,
  Curves.fastLinearToSlowEaseIn,
  Curves.fastOutSlowIn,
  Curves.linear,
  Curves.linearToEaseOut,
  Curves.slowMiddle,
];

Combination of the two should be exactly what you're looking for.
main.dart file:
import 'package:flutter/material.dart';

import 'fadeAnimation.dart';

main() {
  runApp(MaterialApp(
    routes: {
      FadeAnimation.routeName: (context) => FadeAnimation(),
    },
    theme: ThemeData.dark(),
    debugShowCheckedModeBanner: false,
    home: SafeArea(
      child: Scaffold(
        appBar: AppBar(title: Text("Page Tranaction")),
        body: ListView.builder(
          itemBuilder: (context, index) {
            return Padding(
              padding: const EdgeInsets.all(8.0),
              child: Card(
                child: ListTile(
                  onTap: () {
                    Navigator.of(context).pushNamed(animationTypeList[index]);
                  },
                  leading: CircleAvatar(
                    backgroundColor: Colors.white,
                    child: Text("${index + 1}"),
                  ),
                  title: Text(animationTypeList[index].toString()),
                ),
              ),
            );
          },
          itemCount: animationTypeList.length,
        ),
      ),
    ),
  ));
}

class ReturnPage extends StatelessWidget {
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Center(
        child: Text('you're here'),
      ),
    );
  }
}

var animationTypeList = [
  FadeAnimation.routeName,
];

Or instead of combining the 2 during transition wrap widget that contains the next screen with fade-in widget so when it gets created it fades in only once with some internal variable keeping track of that. That way you would have for example: slide-in animation during transition and widget you're transiting to would be opaque at first with gradual fade-in. Or the other way around.
Hope this helps!


C++17 support in iOS/Android SDKs

Question: Can I reuse C++17 source code of a third-party library for development of iOS/Android applications? Thanks.
Comment: Everything depends on whether the compiler, that you use, supports C++17. OS itself, doesn't know anything about syntax rules in any given language.
Answer: You certainly can in iOS.  The clang compiler used by Xcode supports this natively - just select it in the project settings.
I'd be surprised if the same wasn't true of Android.
Comment: Does it also mean all the C++17 features are available as well, e.g. std::filesystem?
Comment: Nope, just checked now on a freshly installed xCode, when including filesystem header, it reports "not found".
Comment: Android r18b comes with prebuilt toolchains based on clang 7.0.2, which has had support for C++17 since version 4.
Comment: Should do, yes.
Comment: Are you sure you selected C++17 in your build settings?
Comment: Strange.  Email Apple?
Comment: Surely older versions of iOS, e.g. 9.0, will not have libc++17 support? Or is libc++ distributed separately in the bundle?
Comment: Android finally supports `std::filesystem` with NDK v22 in Dec 2020. They still have some issues ([perm_options::nofollow](https://github.com/android/ndk/issues/1258), [canonical](https://github.com/android/ndk/issues/1260)) on older devices.

C++17 support in iOS/Android SDKs


Lower and upper bounds for fractional linear transformation

Question: If we have $k(z)=\frac{z}{1-tz}$ which is convex in unit disk, then $k(\bar{z})=\overline{k(z)}$, $k(z)$ maps real axis to real axis where $|z|\leq{r}$, $t\in\mathbb{R}$. What is the upper and lower bounds of $\Re {k(z)}$?
Comment: If $r\ge1/t$ then there can't be any upper bound since $k\to\infty$ as $z\to1/t$
Answer: I would suggest writing the LFT in the following form:
$$
k(z)=\frac{z}{1-tz} = -\frac{1}{t} + \frac{1}{t(1-tz)}
$$
Now test with some points in $\mathbb{C}$ such as $\infty,0,1,\frac{1}{t}$ etc.
For some geometric aid, to see Gerry Myerson's comment try this applet. Also you can find your answer by trying out.
Select circle and enter the variables at the bottom with Enter new values button.


Extracting multiple groups out of a string?

Question: I am trying to extract some information from a string as given below:
[Recently, ,, many, brane, inflation, scenarios, were, proposed, -LRB-, see, ,, e.g., ,, -LSB-, 3, -RSB-, for, a, review, -RRB-, ,, together, with, their, embeddings, into, the, -LRB-, warped, -RRB-, compactified, superstring, models, ,, in, a, good, package, with, the, phenomenological, constraints, coming, from, particle, physics, -LRB-, see, ,, e.g., ,, -LSB-, 4, -RSB-, -RRB-, .]
So what I need to extract is the values appearing between square braces
(e.g. -LSB-, 3, -RSB-, && -LSB-, 4, -RSB-,)
Here is the related snippet of my code:
String pttrn = ".*-LSB-,\\s(\\d),\\s-RSB-,.*";
Pattern pattern = Pattern.compile(pttrn);
m = pattern.matcher(sentence.toString()); rgx = m.find();
int count = 0;
while (rgx) {
    String ref = (m.group(1));
    count++;
    System.out.println("found: " + count + " : " + m.start() + " - " + m.end());
    statement.clearParameters();
    statement.setString(1, rs.getString("ut"));
    statement.setString(2, rs.getString("sec_title"));
    statement.setString(3, ref);
    statement.executeUpdate();

     }

As a result of this code, I always get one value. When I try m.group(2) I get an error saying there is no group 2.. What might I missing?
Answer: You have only one group within your Pattern, so a single match will only provide a single group. You need to apply the search multiple times:
while (m.find()) {
    System.out.println(m.group(1));
}

This means your code should be:
String input = "...";
Matcher matcher = Pattern.compile("-LSB-,\\s(\\d),\\s-RSB-,").matcher(input);

while (matcher.find()) {
    System.out.println(matcher.group(1));
    // the real work should go here
}

For me this prints out:
3
4

Comment: Thanks for your quick response. But now when I use m.find it again returns only one value. I am a bit confused. My pattern catches 2 same groups and by applying while(m.find()) i am anticipating to get them through the loop. OR should I write the same pattern again. If so I have to know how many groups exist in the sentence, before applying regex? Sorry for my poor explanation:(
Comment: Basically a single call to `m.find()` will find the regular expression once. That will then populate the `m.group(1)`. When you *call find again* the `m.group(1)` will be populated with _the next match_. The call `m.find()` returns a boolean indicating if the find was successful, so putting it in a while loop will search for every match. There is no need to know how many matches exist.
Comment: Basically you should replace `while (rgx)` with `while (m.find())` and remove the call to `m.find()` that is outside the while loop.
Comment: Ok so based on this explanation the simple loop :  while (m.find()) {  System.out.println(m.group(1)); } must give two outputs which are 3 and 4 considering the text I gave. But somehow I can only retriev the output 4. I think i am missing some small point.
Comment: Thank you very much. In my pattern I use .* in the beginning and end which hinders to get 3. By removing them as you did I get what i want.
Answer: You have to call find in your while loop:
  while (m.find()) {


How can I arrange a children's song for choir, to make it more interesting?

Question: Our church choir would like to perform some children's songs. (I won't go into the reasons why, right now.) How can I make the songs more interesting?  The kids are so cute when they sing them, that the arrangement doesn't really matter. But with adults singing, I want to add some interest.
I got some ideas from this question What can I do to make cover song to be more interesting?
Any other ideas would be greatly appreciated. We do have a flute, occasionally.
Answer: All the usual arranging techniques are at your disposal.  Straightforward harmonisation, quirky or "juicy" re-harmonisation, melody in parts other than the soprano, descants, polyphonic devices...
Don't get OVER-clever though!