How much Hanon?

Question: So of course, I have been doing the Hanon exercises. I find that I feel as though I'm doing too many (over 30) before I actually do my practice. I play them all twice, once loud and once quiet with proper technique and at exactly the same speed.
I find that doing this takes so, so, so much time and I can barely get onto my pieces during my morning practice.
Can someone tell me how many Hanon excersises I should be doing, and for roughly how long I should be doing the exercises before starting my pieces?
Answer: "Can someone tell me how many Hanon exercises I should be doing, and for roughly how long I should be doing the exercises before starting my pieces?"
One possible answer to this question is: NONE!
It is perfectly possible to make great progress with piano without spending any time at all on Hanon. They are very un-musical, and you might make better progress spending almost all your time playing REAL music; after all, there is a huge amount of real music which will benefit both your technique and your musical understanding.
My advice would be to try a new routine, where you spend a few minutes each day on warm-up exercises, scales and arpeggios, and then skip Hanon completely, and go straight onto musical pieces (both old and new). Try this for a month, and if you feel you are making progress as rapidly as before, then ditch Hanon completely!
Comment: +1. Hanon was a 19th-century marketing genius, not a piano teacher. Playing Hanon for hours every day won't teach you anything worth knowing about piano technique.
Comment: Agreed. I like to compare Hanon exercises to the idea that you can become a great orator by repeatedly practicing pronouncing all possible 3 letters words as loudly and rapidly as possible.
Comment: @OldJohn Yet it is most important that you pronounce all single letter words (that is, practice scales) as louldy and rapidly as possible for a few minutes each day.
Answer: "I find that doing this takes so, so, so much time and I can barely get onto my pieces during my morning practice." You have the answer there. Exercises should only take up a small part of your practice.
In music practice you should be working on

Warm up
Technique
Old material
New material
Theory
etc etc
Answer: Short answer: As much and for as long as you need in order to do what you wish to do in your music. Every practice session should be a balance of technique and music, and your teacher should prescribe that balance. Also the length of the time spent on anything is far less important than the quality of time spent. For technical work, it's possible that 15 minutes of focused, quality work will do more good than an hour of undisciplined work doing the exact same exercises. For your morning sessions when time is limited, I would probably limit Hanon to no more than a few minutes (5-10), and then move on to other things.
The long answer is that it depends on what you're trying to achieve in your piano playing. If you just want to have fun, and play casually, then just play anything and have fun. There are no rules or definitive guidance in this case, except to simply enjoy what you're doing.
(The below is mostly in response to others suggesting that you shouldn't do any Hanon or that Hanon is a waste of time.)
However, if your goals are more long-term, and wish to advance to the level of playing standard repertoire to the best of your abilities, then the answers are very different. In order to fully express yourself in your playing, you have to have the tools to do so. Things like scales, arpeggios, Hanon, Pischna, Czerny, etc., all serve to give you the tools you need to fully express the pieces you wish to play. These exercises isolate the technical elements found in all music, and learning how to solve these problems will dramatically improve your playing of the actual music. Imagine wishing to paint a vivid and accurate portrait, but being limited to just three colors and one brush. How accurate and life-like will that painting be? Now imagine you had 50 colors at your disposal, and you could mix as many as you want to create just the perfect hue, and you had five brushes of different sizes and material to control each stroke to a granular level? Scales, Hanon, and all of the other technical exercises are your tools, and the more and better tools you have, the better your music will be. If you skip this tools-building phase, then your enjoyment of the music will be far diminished.

How much Hanon?


How to display a views slideshow placeholder?

Question: I have a site where the user can add images to the content types page and (custom) project. These images are displayed in a views slideshow based on contextual filter on each page/project in a block. The slideshows are header slideshows, so there must be a placeholder slideshow, if no images are added. How can i accomplish this ? I need a solution where no further maintenance by the user is needed.
Do i have to put some if/else in the page.tpl.php or is there some more elegant way ?
Answer: Your slideshow is a View. So:

Go to edit page of your view
Expand "Advanced" field set
Add new item into "NO RESULTS BEHAVIOR"
Choose "Global: Text area"
Add your placeholder html there. E.g.
NO-IMAGES

Save View
Answer: The Answer of milkovsky pointed me in the right direction:

Go to edit page of your view
Expand "Advanced" field set
Add new item into "NO RESULTS BEHAVIOR"
"Choose "Global: View area"
View to insert -> choose the placeholder view to display instead
Add another contextual filter "GLobal Null"
WHEN THE FILTER VALUE IS NOT AVAILABLE -> Display contents of "No Result found"
Save view


Watermark location is different in word and PDF document in MS interop C#

Question: In my program, there is a function with which users can add watermark to docx or PDF files.
Application wordApp = new Application();
wordApp.Visible = false;
wordApp.ScreenUpdating = false;
Microsoft.Office.Interop.Word.Document wordDoc = null;
wordDoc = wordApp.Documents.Open(file.path, o, o, o, o, o, o, o, o, o, o, o, o, o, o, o);
wordDoc.Activate();

if (file.watermark == true)
{
    Microsoft.Office.Interop.Word.Shape wordShape = null;
    foreach (Microsoft.Office.Interop.Word.Section section in wordDoc.Sections)
    {
        wordShape = section.Headers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Shapes.AddTextEffect(
                         Microsoft.Office.Core.MsoPresetTextEffect.msoTextEffect1,
                         "What a lovely day", "Arial", (float)30,
                         Microsoft.Office.Core.MsoTriState.msoTrue,
                         Microsoft.Office.Core.MsoTriState.msoFalse,
                         150, 150, ref o);
        wordShape.Fill.Visible = Microsoft.Office.Core.MsoTriState.msoTrue;
        wordShape.Fill.Solid();
        wordShape.Fill.ForeColor.RGB = (Int32)Microsoft.Office.Interop.Word.WdColor.wdColorGray15;
        wordShape.Line.Visible = Microsoft.Office.Core.MsoTriState.msoFalse;
        wordShape.RelativeHorizontalPosition = Microsoft.Office.Interop.Word.WdRelativeHorizontalPosition.wdRelativeHorizontalPositionMargin;
        wordShape.RelativeVerticalPosition = Microsoft.Office.Interop.Word.WdRelativeVerticalPosition.wdRelativeVerticalPositionMargin;
        wordShape.Left = (float)Microsoft.Office.Interop.Word.WdShapePosition.wdShapeCenter; // here I set the location to center
        wordShape.Top = (float)Microsoft.Office.Interop.Word.WdShapePosition.wdShapeCenter;
        wordShape.Rotation = -45;
    }
}

if (file.PDFGenerate == true)
{
    object wordFileFormat = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatPDF;
    wordDoc.SaveAs2(file.newPath + ".pdf", ref wordFileFormat, o, o, o, o, o, o, o, o, o, o, o, o, o, o, o);
    wordDoc.Close(oFalse, o, o);
    wordApp.Quit(o, o, o);

}
if (file.PDFGenerate != true)
{

    wordDoc.SaveAs2(file.newPath +".docx", ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o);
    wordDoc.Close();
    wordApp.Quit();
}

The problem is that the location of the added watermark is not identical as you can see in the uploaded pictures.

In PDF files, watermarks are correctly placed in the center of the document, while in docx files, they aren't. I'd like to fix this problem, keeping the structure, algorithm of my code. I appreciate any help. Thanks a lot in advance.
Comment: Found another problem... added watermarks are shown in a completly different position when it's executed on anther PC. Why is that?
Comment: @EugeneAstafiev No, when watermark is added on Word, it seems correct.
Comment: Have you tried doing that manually on Word? Do you get the same results?
Answer: foreach (Microsoft.Office.Interop.Word.Section section in wordDoc.Sections)
            {
                Microsoft.Office.Interop.Word.Shape wordShape = section.Headers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Shapes.AddTextEffect
                (Microsoft.Office.Core.MsoPresetTextEffect.msoTextEffect1, "What a lovely day", "Arial", (float)30, Microsoft.Office.Core.MsoTriState.msoTrue,
                Microsoft.Office.Core.MsoTriState.msoFalse, 0, 0, o);

                wordShape.Fill.Visible = Microsoft.Office.Core.MsoTriState.msoTrue;
                wordShape.Fill.Solid();
                wordShape.Fill.ForeColor.RGB = (Int32)Microsoft.Office.Interop.Word.WdColor.wdColorGray15;
                wordShape.Line.Visible = Microsoft.Office.Core.MsoTriState.msoFalse;
                wordShape.WrapFormat.Type = Microsoft.Office.Interop.Word.WdWrapType.wdWrapBehind;
                wordShape.Rotation = -45;
                wordShape.Left = (float)Microsoft.Office.Interop.Word.WdShapePosition.wdShapeCenter;
                wordShape.Top = (float)Microsoft.Office.Interop.Word.WdShapePosition.wdShapeCenter;
                wordShape.RelativeHorizontalPosition = Microsoft.Office.Interop.Word.WdRelativeHorizontalPosition.wdRelativeHorizontalPositionPage;
                wordShape.RelativeVerticalPosition = Microsoft.Office.Interop.Word.WdRelativeVerticalPosition.wdRelativeVerticalPositionPage;
            }


Are there any Combinatoric proofs of Bertrand's postulate?

Question: I feel like there must exist a combinatoric proof of a theorem like: There is a prime between $n$ and $2n$, or $p$ and $p^2$ or anything similar to this stronger than there is a prime between $p$ and $(\prod_p p) + 1$ (Euclid's theorem).
I was trying to prove one by the Sieve on this grid
<code>    1     2     3     4 ... p
  p+1   p+2   p+3   p+4 ... 2p
 2p+1  2p+2  2p+3  2p+4 ... 3p
...........................
...........................
........................... p^2
p^2+1 p^2+2 p^2+3 p^2+4 ...
</code>
but it did not work.
Do any good arguments like this exist? I don't expect anything as strong as Prime Number Theorem or even Bertrand, but surely a direct combination proof can prove that there are lots of primes?
Comment: I'm not sure exactly what counts as a combinatorial argument, but it's certainly a phrase I associate with the work of Erdos.  So I will note that Erdos, at a very young age, gave a new proof of Bertrand's Postulate.  You might want to check that out and see if it is "combinatorial enough" for your purposes or tastes.
Comment: Chebyshev said/And I say it again/There's always a prime/Between $n$ and $2n$.
Comment: To add a reference to @Pete's comment: An extremely nice exposition of Erdős's argument can be found in Aigner and Ziegler's book *Proofs from THE BOOK* (which I heartily recommend to anyone liking beautiful and outstandingly clever mathematics, which is in addition written and exposed with great care for details). The title refers to a phrase of PE about which you can find out on his [Wikipedia page](http://en.wikipedia.org/wiki/Paul_Erdős) in case you're interested.
Answer: Here is an elementary argument which shows that there are "lots" of primes. Consider the number of numbers in the interval $[1, n]$. On the one hand, this is $n$. On the other hand, by unique factorization every such number can be uniquely written in the form $\prod_{i=1}^{\pi(n)} p_i^{e_i}$. It follows that $n$ is equal to the number of non-negative integer solutions to
$$e_1 \log p_1 + ... + e_{\pi(n)} \log p_{\pi(n)} \le \log n.$$
This is easily seen to be at most $\left( \log_2 n \right)^{\pi(n)}$, hence
$$n \le (\log_2 n)^{\pi(n)}$$
from which it follows that
$$\pi(n) \ge \frac{\log n}{\log \log_2 n}.$$
It might be possible to extract a weak form of Bertrand's postulate from this argument.
Comment: Well, there are!
Comment: It tells us there are at least 4 primes below 100000? edit: this is better than Euclids proof which gives $\pi(n) \ge \log(\log(n))$.
Answer: Interesting idea to use a grid.  I doubt it will work for this question, since writing things in that grid format in a sense splits into arithmetic progressions modulo $p$, and usually saying things about the primes in a progression is harder.
However, I cannot help but mention that using a grid like that was applied brilliantly by Maier to prove a counter-intuitive result, (using the Prime Number Theorem for Arithmetic Progessions) and the idea is now called the Maier Matrix Method.
(A small digression, but it is interesting!)
The Maier Matrix Method
There are questions regarding primes in short intervals, and we can ask ourselves what does $$\pi(x+y)-\pi(x)$$ look like?  To say anything meaningful, $y$ cannot be too small, but here lets suppose $y=\log^B(x)$ for some $B>2$.  Selberg proved that under the Riemann Hypothesis, we have $$\pi(x+y)-\pi(x)\sim \frac{y}{\log x}$$ as $x\rightarrow \infty$ for almost all $x$. (A set with density $\rightarrow 1$)  It was then conjectured that this asymptotic must hold for all $x$ which are sufficiently large.  (This conjecture was made for several reasons, one of which is that it is true under Cramer's probabilistic model)
In a surprising turn of events, Maier showed it was false, and that there exists $\delta>0$ and arbitrarily large values of $x_1$ and $x_2$ such that both $$\pi(x_1 +\log^B (x_1))-\pi (x_1)> (1+\delta)\log^{B-1}(x_1)$$and $$\pi(x_2 +\log^B (x_2))-\pi (x_2)< (1-\delta)\log^{B-1}(x_2)$$hold, despite the fact that the asymptotic holds for a set of density $1$.
He proved this using a method which is now called the "Maier Matrix Method."  Essentially, it is just drawing a grid which is similar to the one above, and then applying a clever combinatorial argument.  The columns are arithmetic progressions, and by PNT4AP, we can easily say things about them to understand the number of primes in the grid.  There is a little trick with oscillation of the Dickman Function, but then basically by the pigeon hole principle the question is solved.
I definitely think you might find this expository article by Dr.Andrew Granville to be interesting.  (It is quite readable, and gives an a more in depth, and very clear explanation)
Answer:
Edited: Here is a very relevant link on Robin Chapman's page.  It is the combinatorial proof which Erdos originally used to prove Bertrands postulate.  (Mentioned in Pete L. Clark's comment)
The PDF is very similar to the proofs I mentioned here, (and here)  and is based entirely on the primes dividing the central binomial coefficient.
I will leave in the proof regarding a lower bound for $\pi(x)$, since it is still relevant.

What follows is a proof Chebyshev's Theorem based on the primes dividing the central binomial coefficient.  First, two well known facts:
Fact 1: Let $r(n,p)$ denote the highest power of a prime $p$ that divides $n!$. Then $$r(n,p)=\left\lfloor\frac{N}{p}\right\rfloor+\left\lfloor\frac{N}{p^{2}}\right\rfloor+\left\lfloor\frac{N}{p^{3}}\right\rfloor+\cdots$$
Fact 2: For every integer $N\geq1$ we have that $$\frac{4^{N}}{2N}\leq\binom{2N}{N}.$$
Theorem: We have that $$\pi(x)\geq\ln(2)\frac{x}{\ln x}-2.$$
Proof. Consider $\binom{2N}{N}.$ For each prime $p$, let $v_{p}$ denote the number of times it divides $\binom{2N}{N}$. Hence $$\binom{2N}{N}=\prod_{p\leq2N}p^{v_{p}}.$$ Let $t=\log_{p}(2N)$ so that $\left\lfloor\frac{2N}{p^{j}}\right\rfloor=0$ when $j\geq t.$ By the lemma, we have $$v_{p}=\left(\left\lfloor\frac{2N}{p}\right\rfloor+\left\lfloor\frac{2N}{p^{2}}\right\rfloor+\cdots\right)-2\left(\left\lfloor\frac{N}{p}\right\rfloor+\left\lfloor\frac{N}{p^{2}}\right\rfloor+\cdots\right)=\sum_{i=1}^{t}\left\lfloor\frac{2N}{p^{i}}\right\rfloor-2\left\lfloor\frac{N}{p^{i}}\right\rfloor.$$ Since $\left\lfloor\frac{2N}{p^{i}}\right\rfloor-2\left\lfloor\frac{N}{p^{i}}\right\rfloor=0$ or $\left\lfloor\frac{2N}{p^{i}}\right\rfloor-2\left\lfloor\frac{N}{p^{i}}\right\rfloor=1$ for each $i$ we see that $v_{p}\leq t.$ Hence if $p^{r}$ divides $\binom{2N}{N}$ we must have $p^{r}\leq2N.$  Consequently $$\binom{2N}{N}=\prod_{p\leq2N}p^{v_{p}}\leq\prod_{p\leq2N}(2N)=(2N)^{\pi(2N)}.$$Applying the other lemma we get $\frac{4^{N}}{2N}\leq(2N)^{\pi(2N)}$and upon taking logarithms we find$$N\ln4-\ln(2N)\leq\pi(2N)\ln(2N)$$and hence $$\frac{2N\ln2}{\ln2N}\leq\pi(2N)+1.$$Since this holds for every even integer, and there is at most one prime between even integers we get
$$\frac{x\ln2}{\ln x}-2\leq\pi(x)\ \text{for all } \ x\geq2,$$ as desired.
Comment: A very similar proof can be used to give a similar upper bound; it can be found, for example, in Apostol's _Introduction to Analytic Number Theory_ (the section is titled something like "elementary results").
Comment: See also: http://math.stackexchange.com/questions/95766/chebyshev-proof-prod-limits-p-leq-2k-p-2k/95783#95783


A simple question in regards to a academic article

Question: Introduction:
I am currently doing some reading on psycological research and in this context I have some questions which may seem very simple. Nevertheless, it is not very transparent from the articles how the calculations are made so please feel free to answer as broad or as specific as you feel.
Question:
What confuses me is a statement like this:
b= -.09, t(82) = -2.14, p<.05
or this:
b= .34, t(68.87) = 2.03, p<.05
Should I consider this as the General Linear Model?
Any input is appreciated. Thanks!
See this example
Comment: There is no way to know, without context. If the context doesn't tell you, then that is a serious flaw in the article.
Comment: What article(s) do you refer to? What is the model corresponding to the results you quote?
Comment: Normally, within psychology you would assume that such coefficients refer to linear regression like you say, but yes, the authors should specify at some point.
Comment: [See this example](http://cmapspublic2.ihmc.us/rid=1LQRS9WDF-1618CKG-1L54/pdf%20(2).pdf)
Answer: In the example you've linked to, the analysis is actually a mixed model, with random intercepts, which is a little more complicated than the General Linear Model, but it really could have been made more clear.

A main effects model with a random intercept was tested
  initially (Kenny et al., 2006). The following equation was
  tested for each emotion [...]

Observed Emotion =  Actor's AAI + Actor's CAI + Partner's AAI + Partner's CAI + Actor's Sex +
 Actor's Depression + Partner's Depression.
Answer: The paper you linked to tells you what general class of models were used (as will any paper worth reading):
From the abstract: "Hierarchical linear models demonstrated that ..."
p897: "we tested a series
of hierarchical linear models using Mixed SPSS 12."
And then the paper mentions specific models:
p897 "A main effects model with a random intercept was tested
initially (Kenny et al., 2006)"
...
This part of the paper worries me though:
p897 "Interaction effects were tested next and nonsignificant in-
teraction terms were removed to reduce the number of
predictor variables in the model."
Comment: "Hierarchical linear models demonstrated that" is not a description of the model, it is a description of a (broad) category of regression methods. But the way the OP present the stats from the paper already made that clear: these are regression model outputs. Eoin's answer provides an example of the model.
Comment: The general class of models used are hierarchical linear models, which is what I claimed. If Eoin's answer is better, you really should upvote it.


How to use linear regression for heavily skewed purchase data?

Question: I am trying to use multiple linear regression to predict the amount that a particular user will spend in a particular time frame on a particular site.  Part of the problem is that there are very few purchasers relative to non purchasers.  The other problem is my lack of great features.
You can see below my predictions vs. actual customer spend.  Even though the model does not look good, it still has some value as is.
I am wondering if there are any recommended techniques for working with linear regression with this type of data?
Comment: Have you considered quantile regression?
Comment: Also, have you considered simple log transformation?
Comment: Or some glm (generalized linear model) for positive responses?
Comment: I have also used logistic regression.  Logistic works slightly better than linear for classification (predicting positive or negative based on a manually chosen threshold), but I want to be able to better predict amount users will spend.   Have not tried quantile regression (not familiar with the approach).
Answer: I echo the recommendation for quantile regression. I'll flesh that out a little.
First, software: SAS has PROC QUANTREG and R has the quantreg package. There are probably ways to do this in most other statistical software, as well.
Second, the general idea of quantile regression is to model the quantiles rather than the mean.
Third, it has at least three advantages over OLS regression in this particular context:

It allows you to model whichever quantile you like. If you want to model the big spenders, you can do that.
It makes no assumptions about the distribution of the residuals.
If you model a quantile that is higher than the proportion of zero spenders, those zero spenders won't affect the results for those quantiles.

Here  is a blog post I wrote on Medium.
Answer: Have you considered a generalized linear model (GLM) as an alternative to the linear model you describe?
If your response variable follows some non-Normal distribution (as your data appear to, with much more values between 0 - 1000 than from 1000 to the maximum around 4000).
Give this page on GLMs in R a look:  http://www.statmethods.net/advstats/glm.html
or explore the glm function.


How to save HTML (Jsoup) to a File in Android

Question: I download HTML file from Web and now I want to save it to internal storage. I know how to save an XML file, because there I use InputStream. But here, I have a Document.
CODE SNIPPET from DownloadHTML.java:
           try {
                Log.d("URL" , URL);
                Document doc = Jsoup.connect(URL).get();

                temperature = doc.select("tbody").select("tr").select("td.t");
                date = doc.select("tbody").select("tr").select("td.meteoSI-th");
            } catch (IOException e1) {
                e1.printStackTrace();
            }

How can I save Document doc to a File in internal storage of my Android Device?
I have tried reading this tutorial from official Android page but it did not help me in my case. I think there is similar solution as to saving XML file, but can't get my head around.
Answer: You can get the document contents as a String by using doc.toString()
Then write the string to a file.
Probably the easiest thing to do once you have created the file as shown in the tutorial that you linked to is to use a PrintWriter, something like:
PrintWriter printWriter = new PrintWriter(file);
printWriter.print(doc.toString());


Appended html element inside angular directive is getting removed from DOM on changing view

Question: I am developing a support chat system. Whenever a support staff clicks on support icon, support screen (staff-room.html) opens which has list of client waiting for request to be attended. Following is an extract of code from the above file
<md-list-item ng-repeat="client in clientChannelList | filter: searchText">

{{ client.senderName}}

          {{ client.siteName}}

    <button chat-popup-box>Attend</button>
</md-list-item>

   <md-toolbar class="background-transparent">

   </md-toolbar>
   <md-divider></md-divider>

   <md-divider></md-divider>

I have an attribute directive chat-popup-box (present in button element) which initialises on clicking of a button. Inside this directive I am creating an html element which creates chat pop up window and appending it with element having id chat-popup in the parent (staff-room.html).
var htmlelement = `<div class="popup-box chat-popup">Some stuff</div>`
var compiledElement = $compile(htmlelement)($scope);
var pageElement = angular.element(document.getElementById("chat-popup"));
pageElement.append(compiledElement);

Now the problem is whenever I am changing the state(navigating to any other module) and coming back,  I am loosing the HTML which I have appended in

 from DOM.  Hence I am loosing chat window pop up.
So Before changing state view DOM was something like this

Some stuff

But after changing state and coming back to same state DOM is like this

While debugging I found out that directive is not being destroyed as even after changing state, flow was going inside the chat-popup-box directive but HTML which I have appended is getting removed from DOM. Is there a way to prevent that?
Answer: A good start might be to code your page in a more AngularJS-y way. The idea is that values are stored and manipulated in the various scope objects and component controllers. I'm not sure which part of the html is replaced, in your case, when you change to another module, but if you stay within the same app, your html will be re-rendered, including your button and functionality, but the popup will not appear until you press the button (again). If you want the popup to be open the next time you arrive on this page, you will have to store this fact in code somewhere. In AngularJS, services are typically used for this purpose.
You could do something like this:
<md-list-item ng-repeat="client in clientChannelList | filter: searchText">
    (...)
    <button ng-click="controller.changeActiveClient()">Attend</button>
</md-list-item>

    (...)

Some stuff

    <md-divider></md-divider>

(better yet, create a component to hold your popup box)
Then, in your controller have something like this:
this.activeClient = staffRoomService.getActiveClient();
this.setActiveClient = staffRoomService.setActiveClient;

Or something; then, create the staffRoomService to store your active client. Anyway, do read up on scopes, components, and "the AngularJS way". It will make your life better and more fun. https://docs.angularjs.org/guide/concepts


Comparativo de Array() PHP

Question: Tenho as seguintes arrays:
$arrTag = "Array ( [0] => stdClass Object ( [id] => 1 [id_pacote] => 7 [id_fornecedor] => [nome] => Salgados - 100 Un [valor_compra] => 100 [valor_venda] => 150 [descricao] => Pacote de Salgados com 100 unidades [created_at] => 2016-11-03 18:00:55 [updated_at] => ) [1] => stdClass Object ( [id] => 2 [id_pacote] => 7 [id_fornecedor] => [nome] => Doces - 100 Un [valor_compra] => 50 [valor_venda] => 114 [descricao] => Pacote com 100 unidades de doces [created_at] => 2016-11-03 18:01:31 [updated_at] => ) [2] => stdClass Object ( [id] => 3 [id_pacote] => 7 [id_fornecedor] => [nome] => Refrigerante - 10 un [valor_compra] => 50 [valor_venda] => 85 [descricao] => Pacote com 10 unidades de refrigerantes [created_at] => 2016-11-03 18:02:04 [updated_at] => ) )";
$arrBanco = "Array ( [0] => stdClass Object ( [valor_venda] => 150 [id] => 1 ) [1] => stdClass Object ( [valor_venda] => 85 [id] => 3 ) )";

Preciso comparar se o id dentro da arrTag, é igual ao id dentro da arrBanco e colocar echo "checked";
Se resume em uma lista do banco de dados, onde eu tenho uma lista de itens (pacotes_itens) e virá marcado os itens que já foram comprados (pacotes_itens_comprados).
HTML QUE SERÁ INSERIDO O CHECKED.
Dentro do input type="checkbox"

        #
        Item do Pacote
        Valor

    <?php
    if(count($dados->detalhes_pacote)>0){
        foreach($dados->detalhes_pacote as $valor_pacote){
    ?>

            <?php echo $valor_pacote->id; ?>
            <?php echo $valor_pacote->nome; ?>
            R$ <?php echo number_format($valor_pacote->valor_venda, "2", ",", "."); ?>
            <input type="checkbox" name="itens[]" id="itens[]" class="checados" data-id="<?php echo $valor_pacote->id; ?>" value="<?php echo number_format($valor_pacote->valor_venda, "2", ",", "."); ?>|<?php echo $valor_pacote->id; ?>">

    <?php
        }
    } else {
    ?>

            Nenhum item foi adicionado a este pacote.

    <?php } ?>

Comment: O que você pretende com esse array representando dentro de uma `string`? Tá pensando em usar o `eval`?
Comment: onde estão as referidas variáveis? arrtag, arrbanco...
Comment: Estão na questão acima... só não sei como verificar dentro das arrays, se o id de uma é igual ao id da outra
Comment: dentro do codigo maior, onde que fica ambas as variáveis?
Comment: Ponha o código que tem os _arrays_ na pergunta. Com aquelas duas strings não dá pra saber o que você quer. Precisa por as arrays de verdade, e não a representação visual delas..
Answer: foreach ($arrBanco as $objBanco) {
  foreach ($arrTag as &$objtag) {

    if($objTag->id == $objBanco->id){
      // encontrei o $objTag, pode altera-lo diretamente aqui...
      $objTag->jaComprado = true;
    }

  }
}

Tive dificuldade para entender a relação entre "$dados->detalhes_pacote" e  "$arrTag $arrBanco"...

Comparativo de Array() PHP


Remover um valor de uma lista

Question: Quero remover dois valores de uma lista. Do tipo tenho um vetor:
vet[0]*3

for i in range(3):
    vet[i]=input('Digite um valor: ')

Quero remover o máximo e o mínimo. Como faço?
Já tentei fazer vet.remove(max(vet)), mas não dá.
Answer: Em python vc define uma lista assim:
vet = []

Para adicionar elementos na lista atraves de inputs vc pode fazer
for i in range(3):
   vet.append(int(input('Digite um valor: ')))

Digamos que o usuario tenha digitado 10, 20, 30, se voce quisesse ver o conteúdo de vet, poderia fazer:
print(vet)

E teria a saída:
[10, 20, 30]

Para excluir os elementos cujos valores sejam o máximo e o minimo:
# Excluindo o valor máximo:
vet.pop(vet.index(max(vet)))

# Excluindo o valor mínimo
vet.pop(vet.index(min(vet)))

# Imprimindo a lista resultante:
print(vet)

Saída:
[20]

Remover um valor de uma lista


Can 2 conditionals be combined like this?

Question: I want to 1)display an alert if ("#one") is checked and ("#two") isn't checked. Then display a different alert if both are checked. What I have does the first part right, then displays both alerts on the second part.
$("#one").click(function() {
    if($(this).is(":checked") && $("#two").is(":not(:checked)")) {
    alert("foo");
    } else {
        if($(this).is(":checked") && $("#two").is(":checked")) {
            alert("foo foo");
        }
    }
});

Answer: You're overcomplicating it, I think.
$("#one").click(function() {
    var thisIsChecked = this.checked,
        twoisChecked = $('#two').get(0).checked;

    if(thisIsChecked) {
         if (twoisChecked) {
            alert('foo foo');    //  <----
         }                       //      |  note the switch
         else {                  //      |
            alert('foo');        //  <----
         }
    }
});

See also: When to use Vanilla JavaScript vs. jQuery?
Comment: can you explain the comma separated variable? and the .get(0) what does that do?
Comment: @Dirty: the comma separated is more-or-less equivalent to separate `var` statements. Some people, like [Douglas Crockford](http://www.jslint.com/lint.html), advocate using a single `var` statement per function. See [this question](http://stackoverflow.com/questions/810313/). The [`.get()`](http://api.jquery.com/get) call returns the underlying DOM element (not a jQuery element) so that you can access the `.checked` attribute rather than making a more-expensive `.attr()` call when it's just not necessary.
Comment: very good, thanks. I'll try and incorporate this. I really appreciate it man.
Answer: $("#one").click(function() {
    if(this.checked) {
       var $two = $("#two");
       if (!$two.is(":checked")) {
            alert("foo");
       } else {
            alert("foo foo");
       }
    }
});

Answer: It looks fine to me. Example of this in action here: http://jsfiddle.net/andypaxo/9vJGL/
Is this the behaviour that you want?
Comment: @Dirty: you're still making things more complicated (and much less efficient!) than needed, amigo.
Comment: had a selector wrong, i guess it was ok to begin with. thx @andypaxo!
Comment: @Matt - I know, man I'm trying. which method is best? I'm familiar with ternary operators, but instead of vanilla alert's I'm using jAlert dialog boxes so those are out.
Comment: @Dirty: ternary operators? Where did [the conditional operator](https://developer.mozilla.org/en/JavaScript/Reference/Operators/Special/Conditional_Operator) come into this?
Comment: in Jordan's example. I'm a little more familiar with those, from PHP and had tried it, but couldn't use my jAlert boxes.
Answer: JSfiddle with solution
HTML:
<form>
   <input id="one" type="checkbox" />
   <input id="two" type="checkbox" />
</form>

JS:
var one = $("#one");
var two = $("#two");

one.click(function() {
    if (one.is(":checked"))  {
        if (two.is(":checked")) {
           alert("foo foo");
        } else {
           alert("foo");
        }
    }
});

Comment: trying it out, but I need variables to be local as there will be a lot of these
Comment: You could write it like this, I only make them variables to cache the lookups: `$("#one").click(function() {
    if ($(this).is(":checked"))  {
        if ($("#two").is(":checked")) {
           alert("foo foo");
        } else {
           alert("foo");
        }
    }
});`
Answer: I'd refactor a bit to get rid of the nested ifs and dry things up a bit:
$("#one").click(function() {
    if(!this.checked) { return }
    var message = $("#two").is(':checked') ? 'foo foo' : 'foo';
    alert(message)
});


Can input variable be leaking data?

Question: I am currently working on a binary classification problem using imbalanced data. The algorithm that I am using is random forest. The problem is about predicting whether each sales project will meet its target or not.
For example, a sales manager could have multiple sales project running under him. We need ML to predict what is the likelihood that each project will meet its target agreed during start of the project. Each projects runs for 3 to 5 year cycle. So, every year there is a specific target to be met.
Based on the year currently the project is in, we would like to know whether project will meet its target upto that specific year. If the project is in 3rd year, we need to find the likelihood for the project to meet its 1st 3 years target (1st, 2nd and 3rd year).
So, now my question is on including two columns/feature which contains the value of how much target achieved/units purchased till this time point (3rd year) as well as "target set at the start of the project". Is it okay to include the feature of "total target achieved/units purchased as on date" and "target set at the start of the project"?
or it is data leakage or considered biasing the model?
we have that target achieved/units purchased as on date info for every project which is updated frequently based on the purchase made.
Every project that we are trying to predict the likelihood, will either have achieved 0 % of the target or 10% of the target or 20% of the target or exceeded the target up to that time point etc. So, we have this info for all records.
And the output_label column is marked as 1 if they exceed the target and marked as 0 if they have not met the target. So, we feed the model the target set (ex:1000 units should be bought) for a project and also how much they have achieved as of now (ex: 200 units bought already) along with other variables.
So, do you think this is a data leakage or considered biasing the model? can I use these two features or not?
As I have the data for these two features at the start of my analysis itself. Meaning, if I am extracting data/building model today, I can find out what is the latest value for "target achieved as on date" yesterday and "target set at the start of the project" (using which labels are derived)
But what if ML model easily captures the relationship (if target achieved >= target set - high likelihood to meet the target else low likelihood to meet the target).
So, in this case do we need ML at all in the first place? Am confused. Of course, along with these features, am trying to few more input variables as well based on historical data. Can you guide me on whether incorporating these two features - target set and target achieved as of date is okay? But yes, including these features results in better performance of the model.
while these two features majorly drive the prediction to 87% of f1 in test data, if I include my additional features, they take upto 93% for f1 in test data. If I exclude these two features, f1 is about 55-60% for minority class.
But one thing, I found out was that these two columns are not heavily correlated within themselves and also with the target. So, am not sure how is prediction performance being increased so heavily after these two features
Also, important point to note is that my output variable is computed using a formula/rule that involves these two features.
However, when I validated the performance on the test data, I don't see any signs of overfitting or drop in performance. But yes, these two features drive the prediction all alone contributing to around 87% of f1 score where as other 3-4 predictors add another 5 points.
So, am I good to use these features in model building despite they being used to create rule-based label? I don't let the model know the exact formula/rule. So, what do you think?
Comment: Is this different from your [recent question](https://datascience.stackexchange.com/q/121538/73930) on Data Science?
Comment: No, it is the same. As there was no response, I posted here.
Comment: In order to determine whether there is data leakage, we need to know what the flow of data is. What data are you using for training the model and what data are you using to test the performance of the model? This is not explained very well.
Comment: When are you doing the predicting? If you're trying to predict a project's likelihood of success before even launching it, you of course should not try to predict that using data from the project as it happens. Is this a retrospective measure of success or a prospective prediction of it?
Comment: No, am trying to predict the project only after it is officially signed/started.. so, when they sign, they will set the target to achieve for the project (which runs for multiple years). Of course, during initial days target achieved will be 0% and as time progresses, target achieved will start accumulating values. So, prediction is done only after project start and is in progress.. So, my understanding is projects during the initial stages should show low likelihood (because they may not have achieved anything significant). So, do you think it makes sense to use ML for this problem
Comment: @TheGreat Hard to say if ML is really needed, as there are probably some simple rules that could get you pretty far, like "projects that have exceeded milestones are likely to continue to succeed". Computational approaches shine when the relationship between input features and what you're trying to predict is complex or non-obvious. Tough to get the full scope here, but if you have relatively few input features and good understanding of how they relate to outcome already, a domain expert might be able to make decent predictions on their own with no ML model.
Comment: If I don't use ML, how do I rank the likelihood of the projects to meet the target..Sales users may not have time to focus on all the projects. So, we need some mechanism to bring their attention to high likelihood to succeed projects and discard dead projects and not spend their resources, phone calls, follow up, customer visits etc...Instead of we manually coming up with rules and assigning weightages, using a simple model like Random Forest is not encouraged? I am asking only to understand when and when not to use ML.
Answer: If I understand this correctly, there is no data leakage. You are just using information that at the point at which you want to predict the outcome is available, and therefore can be used.
The concept of information leakage comes into play when using resampling, data set splitting, cross-validation and the like. These technques use some part of the data in order to predict some other part of the data that in fact you already have, but in order to assess the prediction quality on unseen data properly, you pretend that you don't have it (as you are emulating a real situation in which you wouldn't have that information at the point where you use the other part for prediction). Information leakage means that for some reason you set up things in such a way that at some stage you use information that you shouldn't use, because in a real situation you wouldn't have it. As far as I understand your situation, this is not the case here.

But what if ML model easily captures the relationship (if target achieved >= target set - high likelihood to meet the target else low likelihood to meet the target). So, in this case do we need ML at all in the first place?

Why would the fact that ML does a job successfully (and rather easily) be a reason that we don't need it at all in the first place? If your prediction problem indeed is to predict achievement of the target in a situation in which you already have strong information that indicates with large probability what will happen, so be it! (The only thing one could worry about is whether a simpler approach will do the trick already, but as long as it's not a big problem to set up your random forest, you may well use it.)
Comment: @TheGreat "ML" is a rather imprecise term (if it means what I think it means; using abbreviations without explanation is never a good idea), so I'm not really sure where you'd put the border between "ML" and "non-ML", and I don't think there is a generally agreed definition for this. Generally, there are truck loads of classification methods, so I can't give you a list here. Random Forest is often pretty good, I'm not worried about your choice there, but I can't say what's good in general without knowing the actual data.
Comment: Wow. Nice. Good to know. If I include additional features (other than these two features), I do see some bump in performance. So, guess things like this can be used to justify the use of ML.
Comment: A quick question. When you meant simpler approach, did you feel that this problem could have been solved without ML ? I ask because the reason for me to choose ML was to see whether there are any other factors that can influence this relationship and also to rank the project based on likelihood(to meet the target). So, do you think it makes sense to use ML for this? If simpler approaches, can let me know what options do we have?
Comment: Is there anyway to rank the projects based on their likelihood to succeed without using machine learning algos? We wanted to rank the project for our sales users. So, felt machine learning us the only way and it helps with additional insight. Can we do this without Machine learning almost as well?
Comment: I ask mainly because,  am learning as a data scientist and don't wish to force fit AI or ML in situations where it is not required. So, your inputs would help me gain some clarity
Comment: @TheGreat As I told you, there is no agreed definition for where Machine Learning ends. Some machine learners would claim all classification methods as their own, so whatever you could use could be seen as ML by definition, however some people wouldn't agree... ultimately it has little impact on your problem whether something is called ML or not.
Comment: One follow up question. Due to paucity of human resources to label our dataset, we got some business rules from the domain experts involving these two variables to label our dataset. Now, can I use the same variables (along with other variables) that were used in the output label formula for building models? I ran a validation and found out that using these two features doesn't overfit but yes, they come up as the majority predictor (along with few other predictors) confirming business users expertise..
Comment: @TheGreat Don't normally use comments for further questions as others normally won't read them.  In any case, my understanding was that you use information at a certain time point to predict performance at a future time point. Now it looks like the performance at an earlier time point is used to label what you finally want to predict? That sounds strange to me, and potentially problematic.
Comment: Sorry, I thought it was related. Anyway, I created a new post here - https://stats.stackexchange.com/questions/616031/can-variables-used-for-rule-based-labeling-be-treated-as-input-features

Can input variable be leaking data?


How to add class in title div for specific block?

Question: I have created a block using Views module in website using drupal 7.
My block title's HTML structure is as bellow:

BLOCK_TITLE

I want to add a class in
.
Should I create a module for this or any other way?
Please guide me how can I do this?
Thank you in advance
Comment: You should first search in Google then post somewhere.
Comment: Yes I had and found a way by using module. But it doesn't worked for me.
Answer: function themename_preprocess_block(&$variables) {
if($variables['block']->bid == 'views-front-block') {

     $variables['classes_array'][] = 'container';
 }

}
add this function in your template.php file of your theme.
Answer: I think the Block Class module will allow you to add classes in blocks. Here is a quote about it (from the module's project page):

... allows users to add classes to any block through the block's configuration interface. By adding a very short snippet of PHP to a theme's block.tpl.php file, classes can be added to the parent
 element of a block. Hooray for more powerful block theming!
Comment: It just add class in  of block. I want to add class in  for title of the block.
Comment: You can use sibling selector in CSS to do so( http://css-tricks.com/child-and-sibling-selectors/)
Comment: I want to add bootstrap.css class in this  so it will not work.
Answer: Your view -> Edit -> Expand Advanced Fieldset -> Theme: Information. Copy the template suggestion from Style output (Display output? I can't really remember) container and create that file (Do not forget to clean the cache). Then copy the default code and modify it. For ex.:
<?php print $wrapper_prefix; ?>
  <?php if (!empty($title)) : ?>

<?php print $title; ?>

  <?php endif; ?>
  <?php print $list_type_prefix; ?>
    <?php foreach ($rows as $id => $row): ?>
      <li class="<?php print $classes_array[$id]; ?>"><?php print $row; ?>

    <?php endforeach; ?>
  <?php print $list_type_suffix; ?>
<?php print $wrapper_suffix; ?>


Need help in generating scripts in java language in Selenium IDE

Question: i am trying to record actions performed in the Firefox browser using Selenium IDE. I observed that for recorded scripts, the default language in source tab is HTML. As i wanted to have scripts in java, i got into Options->format in menu bar but i do not see Java listed in there. I could only see HTML, Ruby, python and C#. Could you please help me in generating/converting scripts in java?
Answer: It seems you do not have (or have but deactivated) Selenium Java plugin installed for your IDE.

If you're using Selenium 1.x version, then go to Selenium IDE->Options->Options and check Enable experimental features
Alternatively, try installing the latest stable version from here

You can also check what's installed from Selenium IDE->Options->Options->Plugins tab

EDIT:
For recording options in Java, please see the below settings in the screenshot
Comment: Thank you. It worked, i have selected java formatters in the java plugins page, now i am able to export recorded test cases in java language. But still i see that recorded script are in HTML format.
Comment: I am using Selenium IDE 2.4.0 *. I tried changing in clipboard format as java but still the script is in HTLM. Could you please help me solve this one too.
Comment: @Srekk I have added the screenshot for that too, basically I just get formats option within Options menu and if I select Java, it throws and initial warning of being an experimental feature and then carries on with the recording
Comment: Thanks PopoFibo. I did that.


Alterar a cor Background da ListView quando o valor chave for encontrado

Question: Na minha app tenho uma ListView que é prenchida através de BaseAdapter.
Então no BaseAdapter eu tenho uma intrução IF para alterar o Background da lista quando do valor de uma variavel foi igual ao valor de uma outra variavel global.
O problema é o BaseAdapter altera a cor quando os valores das duas variaveis são iguais (isto só acontece uma única vez) e também altera a cor em outros locais errados!!!??? Aqui vai o código do método getView para ver se alguém me consegue ajudar:
@Override
public View getView(int position, View convertView, ViewGroup parent) {

    View view = convertView;
    ViewHolder viewholder;

    if(convertView == null){

        LayoutInflater inflater = (LayoutInflater) contexto.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = inflater.inflate(R.layout.textview_personalizado_dialog, null);

        viewholder = new ViewHolder();

        viewholder.estacao = (TextView) view.findViewById(R.id.textView1);
        viewholder.horas = (TextView) view.findViewById(R.id.textView2);

        view.setTag(viewholder);

    } else {

        viewholder = (ViewHolder) convertView.getTag();

    }

    String estacaoHora = lista.get(position);
    String[] tokens = estacaoHora.split("/");

    String valor1 = tokens[0];// Estação
    String valor2 = tokens[1];// Hora
    String valor3 = tokens[2];// Minutos

    // Quando o valor da variavel "valor1" for igual ao valor da variavel "estacaoPesquisa" altera a cor de Background:
    if (valor1.equals(estacaoPesquisa)){

        // Altera a cor de fundo da lista:
        viewholder.estacao.setBackgroundColor(contexto.getResources().getColor(R.color.verde_5));
        viewholder.horas.setBackgroundColor(contexto.getResources().getColor(R.color.verde_5));

        viewholder.estacao.setText("  " + valor1);
        viewholder.horas.setText(valor2 + ":" + valor3);

    } else {

        viewholder.estacao.setText("  " + valor1);
        viewholder.horas.setText(valor2 + ":" + valor3);

    }

    return view;
}

// Classe interna:
static class ViewHolder {

    TextView estacao;
    TextView horas;

}

Comment: Veja esta [resposta](http://pt.stackoverflow.com/a/61057/2541) talvez ajude.
Comment: Olá ramaral! O post que indicou é meu. Aqui o meu pedido de ajuda é diferente, ou seja, eu não necessito de fazer uma lista zebrada, eu quero antes fazer uma lista normal mas quando o valor String de uma dada lista for igual ao valor de uma variavel quero alterar a cor de Background dessa lista (que vai ser unica na ListView)...
Comment: Não tinha reparado que o poste era seu. O problema aqui surge pela mesma razão. Vejo que não percebeu o problema. Vou postar uma resposta.
Comment: Obrigado ramaral. Fico aguardar...
Answer: O problema aqui surge pela mesma razão da sua outra pergunta.
O Android, para que não seja necessário estar sempre a fazer o inflate da view de cada uma das linhas da ListView, tem um mecanismo que permite reaproveitar views já não utilizadas.
Quando existe um view que pode ser reaproveitada ela é passada no parâmetro convertView do método getView(). Repara que o seu código so faz o inflate quando a convertView é nula:
if(convertView == null){

    LayoutInflater inflater = (LayoutInflater) contexto.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    view = inflater.inflate(R.layout.textview_personalizado_dialog, null);

    viewholder = new ViewHolder();

    viewholder.estacao = (TextView) view.findViewById(R.id.textView1);
    viewholder.horas = (TextView) view.findViewById(R.id.textView2);

    view.setTag(viewholder);

} else {

    viewholder = (ViewHolder) ViewHolder.getTag();
}

Adicionalmente, para não ter de estar sempre a obter as referencias aos elementos da view, através de findViewById, é utilizada uma classe, a ViewHolder, para guardar essas referências. A ViewHolder é guardada na propriedade Tag da View.
Quando a convertView não é nula recuperam-se a ViewHolder recorrendo-se ao método getTag:
.....
.....
} else {

    viewholder = (ViewHolder) ViewHolder.getTag();
}

Quando a view é reaproveitada ela vem com as sua propriedades setadas com os valores usados anteriormente.
Assim como você atribui os valores correspondentes à linha actual,
viewholder.estacao.setText("  " + valor1);
viewholder.horas.setText(valor2 + ":" + valor3);

tem também de repor qualquer atributo que tenha sido alterado.
Neste caso você altera a cor do background:
viewholder.estacao.setBackgroundColor(contexto.getResources().getColor(R.color.verde_5));
viewholder.horas.setBackgroundColor(contexto.getResources().getColor(R.color.verde_5));

O código terá de ser alterado para que, quando a estacaoPesquisa não for a pretendida, seja atribuída a cor "original" do background.
if (valor1.equals(estacaoPesquisa)){

    // Altera a cor de fundo da lista:
    viewholder.estacao.setBackgroundColor(contexto.getResources().getColor(R.color.verde_5));
    viewholder.horas.setBackgroundColor(contexto.getResources().getColor(R.color.verde_5));

    viewholder.estacao.setText("  " + valor1);
    viewholder.horas.setText(valor2 + ":" + valor3);

} else {

    viewholder.estacao.setBackgroundColor(contexto.getResources().getColor(R.color.????));
    viewholder.horas.setBackgroundColor(contexto.getResources().getColor(R.color.????));

    viewholder.estacao.setText("  " + valor1);
    viewholder.horas.setText(valor2 + ":" + valor3);

}

Nota: Substitua R.color.???? pela cor "original"
Comment: Era esse o problema!! Efetivamente eu não tinha intendido bem a lógica do funcionamento do método getView. Foi excelente a sua explicação. Muito obrigado. Abraço.


How to view Linux memory map info in C?

Question: I'm dynamically loading some Linux libraries in C.
I can get the start addresses of the libraries using the

dlinfo

(see 1).
I can't find any information to get the size of a library, however.
The only thing that I've found is that one must read the

/proc/[pid]/maps

file and parse it for the relevant information (see 2).
Is there a more elegant method?
Comment: As i know, parsing a `maps` is the easiest method. Why it is not elegant in your opinion?
Comment: Compared to simply doing the following, it's not very pretty to have to mess with string parsing.

`struct link_map *map;
dlinfo(hLibrary, RTLD_DI_LINKMAP, ↦);
void* base = map->l_addr;`
Comment: There is an `map->l_name` and you can do a `stat` based on path to library. Or you can try to dig into link_map deeper and find segments/sections of the ELF file loaded.
Answer: (This answer is LINUX/GLIBC specific)
According to http://s.eresi-project.org/inc/articles/elf-rtld.txt
there are link_map *map; map->l_map_start & map->l_map_end
    /*
        ** Start and finish of memory map for this object.
    ** l_map_start need not be the same as l_addr.
    */
    ElfW(Addr) l_map_start, l_map_end;

It is a bit not exact, as said here http://www.cygwin.com/ml/libc-hacker/2007-06/msg00014.html
=  some libraries are not continous in memory; the letter linked has some examples... e.g. this is the very internal (to rtld) function to detect is the given address inside lib's address space or not, based on link_map and direct working with ELF segments:
/* Return non-zero if ADDR lies within one of L's segments.  */
int
internal_function
_dl_addr_inside_object (struct link_map *l, const ElfW(Addr) addr)
{
  int n = l->l_phnum;
  const ElfW(Addr) reladdr = addr - l->l_addr;

  while (--n >= 0)
    if (l->l_phdr[n].p_type == PT_LOAD
    && reladdr - l->l_phdr[n].p_vaddr >= 0
    && reladdr - l->l_phdr[n].p_vaddr < l->l_phdr[n].p_memsz)
      return 1;
  return 0;
}

And this function is the Other alternative, which is to find program headers/ or section headers of ELF loaded (there are some links to such information in link_map)
And the easiest is to use some stat syscall with map->l_name - to read file size from the disk (inexact in detecting huge bss section).
Answer: Parsing /proc/self/maps (or perhaps popen-ing a pmap command) seems still the easiest thing to me. And there is also the dladdr function (provided you have some adress to start with).

How to view Linux memory map info in C?


ARM Assembly Time System Call Unexpected Values

Question: So I'm trying to get the time using ARM assembly and am having trouble doing so. This is the code that I have:
<code>.data
    .balign 4
    time:
    .word 0

.text
    .global _start

_start:
    ldr r0, =time
    mov r7, #0xd
    svc #0

    mov r7, #1
    svc #0
</code>
However, when using GDB, the value at the address of the variable time is always 0. The return value in r0 after the first system call is always 0xffffffda. It never changes and I can assume that it isn't the time since epoch.
The information that I gathered this from is:
https://w3challs.com/syscalls/?arch=arm_strong
I am trying to call the system call "time."
Note that I am programming on a Raspberry Pi 2 model B. The link links to arm_strong architecture and the architecture I am working with is an ARMv7. But essentially replacing the 9 with a 0 in the r7 requirement gets me the system call I want. So for "time" I use 0xd instead of 0x90000d.
What am I doing wrong that neither the return value nor the pointer I pass into the system call is getting me the value I expect? Eventually what I want to do is take the value and print it to the console.
Comment: [-38 is `-ENOSYS`](http://lxr.free-electrons.com/source/include/uapi/asm-generic/errno.h#L17), which suggests it might be worth looking up the _actual_ appropriate syscall number for the kernel version you're running, rather than guessing from a wildly out-of-date reference.
Comment: I've tried to look for information about that, but I have had no luck. How do you suggest I should go about looking for the actual appropriate syscall number?
Comment: Here is a more accurate representation that I found: https://w3challs.com/syscalls/?arch=arm_thumb
Comment: The zeroes for `time` are because of runtime linking. Dynamic linker will populate them when your program is executed.
Comment: Everything looks correct to me.  I suggest you just set 'R0' to NULL (0) and don't have Linux write to user space memory for you.  The `time_t` fits in R0 and you can use it directly.  Can you do that and see if the error code changes? Or you are successful.  You could use the Linux 'asm/unistd.h' and get the 0xd constant from there as `__NR_time` (and `__NR_exit` too).  The issue may have to do with the constant pool and data references.  You might want to set an exit code.  I guess the executable runs with out SEGV?
Comment: See: [Linux static compile](http://stackoverflow.com/questions/24616226/how-can-i-select-a-static-library-to-be-linked-while-arm-cross-compiling) and [_start with thumb](http://stackoverflow.com/questions/20369440/can-start-be-the-thumb-function/20379933#20379933) as they might be helpful?
Answer: This is an alternative solution.
As indicated by @artless noise, it appears that your code is correct; I am getting the same result as you.
Notwithstanding, an alternate solution may be to use the gettimeofday syscall; which does return Epoch; provided that this is your goal. Some comments within the Internet suggest that time and gettimeofday may be using different sources; so gettimeofday may not be as accurate.
I have tried using time() with a null and not null pointer and all results return  0xffffffda in r0, respectively.
<code>  1 /*
  2         David @InfinitelyManic
  3         http://stackoverflow.com/questions/39820523/arm-assembly-time-system-call-unexpected-values
  4
  5         $ uname -a
  6         Linux raspberrypi 4.4.21-v7+ #911 SMP Thu Sep 15 14:22:38 BST 2016 armv7l GNU/Linux
  7
  8         $ cat /etc/os-release
  9         PRETTY_NAME="Raspbian GNU/Linux 8 (jessie)"
 10
 11         $ less /usr/share/gdb/syscalls/arm-linux.xml
 12         <syscall name="time" number="13"/>
 13
 14         arm/EABI   swi 0x0              r7          r0
 15
 16         gcc -g stuff.s -o stuff
 17 */
 18
 19 .bss
 20 .data
 21         fmt:    .asciz  "%lu\n"
 22         t:      .zero 8
 23 .text
 24         .global main
 25         .include "mymac.s"
 26
 27 main:
 28         nop
 29         ldr r9,=t
 30
 31         bl _time0
 32         mov r1, r0
 33         bl write
 34
 35         bl _time1
 36         ldr r1, [r9]
 37         bl write
 38
 39 exit:
 40         mov r7, #1
 41         svc 0
 42
 43 write:
 44         push {r1-r3,lr}
 45         ldr r0,=fmt
 46         bl printf
 47         pop {r1-r3,pc}
 48
 49 _time0:
 50         push {r1-r3,lr}
 51         mov r7, #13             // time
 52         eor r0, r0
 53         svc 0
 54         pop {r1-r3,pc}
 55
 56 _time1:
 57         push {r1-r3,lr}
 58         mov r7, #78             // gettimeofday
 59         ldr r0,=t
 60         eor r1, r1
 61         svc 0
 62         pop {r1-r3,pc}
</code>
OUTPUT:
<code>$ ./stuff
4294967258
1475617987
</code>


Second derivative test failure?

Question: $f(x,y)=12x^2+12y^2+(x+y)^3$
Find all local maxima, minima and saddle points.
I found $2$ critical points $(0,0)$ and $(-2,-2)$ but the second derivative test came out weird for the set of points $(-2,-2)$. I got $f_{xx}=0$ and the discriminant bigger than $0$. That doesn't imply anything (not maxima, not minima, not saddle point and test isn't even inconclusive). What do I do at this point?
Answer: I would say the test is conclusive: the discriminant is negative (-24^2) so it is a saddle.
Comment: Forgot that $f_{xy}$ was squared. Thank you!
Answer: I would say it's a saddle point as well. Here's a quick plot of the function at the point in question

Second derivative test failure?


Using drush on drupal 8?

Question: Dursh works very well with my Drupal 7, but when I try running Drush on Drupal-8 directory it throws some error message,
$drush pm-list

Command pm-list needs a higher bootstrap level to run - you will need invoke drush from a more functional Drupal environment to run[error]
this command.
The drush command 'pm-list' could not be executed.                                                                                [error]
A Drupal installation directory could not be found

could anyone tell me the solution for this problem?
any help is appreciated. Thank you.
Answer: Which version of drush? https://github.com/drush-ops/drush#drush-versions has a nice table, but in short you need the master branch from github if you want to work with Drupal 8.
Comment: so it was version compatibility issue, my version was 4.5, i didn't really noticed that. Thank you sir.
Comment: Drush 7 works with Drupal 8. See also http://drupal.stackexchange.com/questions/85281/im-on-drush-version-6-cant-do-a-drush-status-on-my-drupal8-site-whats-the-s
Comment: Yes and `master` contains Drush 7 at this moment.
Answer: I have not used drush with drupal 8, but these errors are sometimes experienced with D7 if you run drush from outside a site directory (eg sites/mysite.com) if the 'default' site is invalid or not defined.
Is it possible this might be the case here?

Using drush on drupal 8?


What is Z_ENT column in SQLite database that gets created by Core Data?

Question: When you use Core Data with SQLite database as underlying data store, core data will autogenerate some columns...
One of them is "Z_ENT"  and another is "Z_OPT"
I believe "Z_OPT" is for how many times the record has been altered.  Can anyone tell me what Z_ENT is for?
Thanks!
Comment: Why would they track Z_OPT? Who is using that data?
Answer: "Z_PK is the unique id for each, Z_ENT is their entity id (same as what's listed in the Z_PRIMARYKEY table"
From here
Comment: Very valuable (even now) :)
Comment: As a SQLite layperson with dated MySQL knowledge pointedly poking around, this answer didn't really tell me what the purpose of z_ent was. However, according to another site I found, it says z_ent is a table ID, which makes much more sense to me. Found here: https://www.theiphonewiki.com/wiki//Applications/MobileNotes.app


Proof of linear independence of dummy encoding

Question: I understand one-hot encoding is linearly dependent and if I drop one column, it would become linear independent, but I don't know how to prove it, can someone give me a mathematical proof.
Answer: Start with the definition:

A sequence of vectors $\mathbf{v}_1, \mathbf{v}_2, \dots,
 \mathbf{v}_k$ from a vector space $V$ is said to be linearly
dependent, if there exist scalars $a_1, a_2, \dots, a_k$, not all
zero, such that
$$a_1\mathbf{v}_1 + a_2\mathbf{v}_2 + \cdots + a_k\mathbf{v}_k =
 \mathbf{0},$$
where $\mathbf{0}$ denotes the zero vector.

One-hot encoded matrix looks like
$$
\begin{bmatrix}
1 & 0 & 0 \\
0 & 1 & 0 \\
0 & 0 & 1 \\
\end{bmatrix}
$$
now add an intercept to the matrix:
$$
\begin{bmatrix}
1 & 1 & 0 & 0 \\
1 & 0 & 1 & 0 \\
1 & 0 & 0 & 1 \\
\end{bmatrix}
$$
You should not have problems finding non-zero vectors such that after multiplying the new matrix by them you would get zero vectors (e.g. $(-\pi, \pi, \pi, \pi)$). This shows that the columns are linearly dependent, so multicollinear. That is why we drop one of the columns per each feature.
Comment: Dropping a column in (3) will not create linearly independent columns.
Comment: Thanks, but that still doesn't fix the example!  The rank of the matrix in $(3)$ is $3,$ implying you would have to drop at least three columns before the remaining ones are linearly independent.


SMTP-SASL authentification doesn't work

Question: I created another thread previously, where I reported about the problem that I wasn't able to get saslauthd starting up at all:
SMTP authentification: saslauthd won't start
I now re-installed a completely new Ubuntu 16.04 system on my VPS in order to set up postfix with SMTP-SASL authentification from the scratch. At least now "ps ax" shows that saslauthd is running, but it still doesn't work, as a telnet test seems to suggest:

root@servername:~# telnet localhost 25
  Trying ::1...
  Connected to localhost.
  Escape character is '^]'.
  220 servername.com ESMTP Postfix (Ubuntu)
  EHLO test
  250-servername.de
  250-PIPELINING
  250-SIZE 10240000
  250-VRFY
  250-ETRN
  250-STARTTLS
  250-ENHANCEDSTATUSCODES
  250-8BITMIME
  250-DSN
  250 SMTPUTF8

(It should show "250-AUTH LOGIN PLAIN" if it would be working properly).
I've configured smtpd to run in a chroot environment and changed the configuration files accordingly, but also when not running it via chroot (with modified configuration) the result is the same.
The "postfix" user belongs to the "sasl" group and there's no error output in /var/log/mail.log. Also /var/log/auth.log seems to suggest that saslauthd starts without any problems.
I collected all relevant configuration files and output here:
postfix and sasl configuration / output
If there's anything else that might be relevant I'll post this as well of course.
I'd be really thankful for any ideas, suggestions or advice, since I've already spent many hours on configuring this, but still can't get the SMTP-SASL authentification running (besides this issue my mail server is running fine).
Kind regards
Comment: Check your logs.
Comment: I checked all relevant logs, none of them contains any hint on what the reason could be.
Comment: If authentication actually failed, _something_ would be logged when you made the attempt. Try again and look carefully.
Answer: First of all: This is not exactly an "answer to my original question", and since I understand the sense of the rules in this regard, I apologize for making use of this function - The only reason why I do so is that I think it would be totally confusing to anyone if I'd instead use the comment function due to its quite strict restrictions (I'd have to split this up into many separate comments without being able to format my text properly). However, since I want to obey the rules of this site, I will delete my answer or accept it of course, if a moderator should decide to do so - I post this as an 'answer' only for pragmatic reasons.
Second: Thank a lot to Michael - He gave me the crucial hint that instead of reconfiguring/checking all kind of configurations after seeing that the telnet test failed it would be a much better approach to try sending an authenticated SMTP mail and then check the logs (something I could have figured out by myself as well - since the telnet test might show whether SASL is working, but of course it's of no use to find out why it's not working).
So I must admit that a lot of stuff had been messed up (not referring to the non-authentificated SMTP server, which worked without any problems). Basiclly I followed this tutorial for setting up my mail server, having adjusted the configuration to my system and added some extra functionality (automatic Bcc forwarding for incoming and outcoming mail in particular):
Email with Postfix, Dovecot, and MySQL
Actually I think that this tutorial is a really good one, but I now believe that this configuration might be the reason why SASL authentication didn't work so far.
First of all I had to add this to my /etc/dovecot/dovecot.conf, otherwise it wouldn't start:

namespace inbox {
  inbox = yes
  }

Then I had to add to add/modify the line "smtpd_sasl_path = private/auth" in /etc/postfix/main.cf
I found this information when I searched for the entry "Oct 25 01:30:31 servername postfix/smtpd[2983]: warning: SASL: Connect to smtpd failed: No such file or directory" which showed up in my /var/log/mail.log and after having changed it the error message disappeared.
SMTP-SASL authentication still doesn't work, but I think that's because I changed the authentication from "sasldb" to "shadow" in /etc/default/saslauthd but didn't configure it so far.
Probably "shadow" would be a more recommendable approach when working with virtual users, right?
I can send mails using my SMTP server, but my server doesn't request a proper authentication.
By the way, my /var/log/auth.log is completely filled with SMTP connection attempts, but even though there's no authentication none of those attempts to send mails via my mail server had been successful (but nonetheless one should secure it obviously).
So this is my current /etc/postfix/main.cf:
/etc/postfix/main.cf
I'd really appreciate it, if someone could give me a link to a tutorial which describes how to set up mail server running postfix with virtual users and SASL-SMTP authentication.
Kind regards and all the best
Comment: As I already wrote, I also changed various things in my dovecot configuration files, so I created a pastebin including all relevant dovecot configuration files: http://pastebin.com/DVhJ50vL My question: Should I go on with this 'patchwork' approach (maybe there wouldn't bee too much I'd have to change), or would it be rather recommendable to set it all up from the scratch?

SMTP-SASL authentification doesn't work


Fluent NH Sqlite

Question: is there a way to specify the location of where the Sqlite database is created through Fluent NH configuration?
I have attached the code below that I am using, and I would have thought that ExportTo would have done what I was after, but it only exports the hbm files to the specified location.
string fullPath = string.Format("{0}\DatabaseFiles\", Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory));

config = Fluently.Configure().Database(SQLiteConfiguration.Standard.ConnectionString(connectionString)).ExposeConfiguration(c =>
{
c.SetProperty("current_session_context_class", "thread_static");
if (exportSchema) {
    SchemaExport schema = new SchemaExport(c);
    schema.Drop(false, false);
    schema.Create(false, true);
}

}).Mappings(m => m.AutoMappings.Add(automappings).ExportTo(fullPath));

Answer: You specify the filename through the Data Source parameter of the connection string:
Data Source=C:\folder\file.db

http://sqlite.phxsoftware.com/forums/p/938/4017.aspx

Fluent NH Sqlite


Projection on sum of Banach spaces

Question: If we have projections $P$ and $Q$ on Banach spaces $X$ and $Y$, respectively. It is easy to see that the operator matrix
$$ S=\begin{bmatrix} P & 0 \\ 0 & Q \end{bmatrix} $$ determines a projection on $X\oplus Y$ such that $R(S)= R(P) \oplus R(Q)$ and $N(S)=N(P)\oplus N(Q)$. My question is this. If I have a projection $S$ on $X\oplus Y$, what would be the proper representation of this projection in the form of a $2\times 2$ operator matrix ? Would it be a diagonal operator matrix ?
Comment: What do you mean by 'representation of [the] projection" and what do you mean by "diagonal operator matrix"? If I have $P$ and $Q$ projections on $X$ and $Y$ respectively then some $S$ on $X\oplus Y$ defined as $S(x+y) = Px+Qy$ for all $x\in X$ and $y \in Y$ is a projection as $S^2 = S$. I'm not sure that general Banach space operators always admit matrix representations, so you might have to restrict the hypothesis to Hilbert space operators instead.
Comment: Well, in this case every bounded linear operator $B: X\oplus Y \rightarrow X \oplus Y $ can be represented as $$ B= \begin{bmatrix} B_1 & B_2 \\ B_3 & B_4 \end{bmatrix} : \begin{bmatrix} X \\ Y \end{bmatrix} \rightarrow \begin{bmatrix} X \\ Y \end{bmatrix} $$. So my question is, if we have a projection $S : X \oplus Y \rightarrow X \oplus Y$, must it's matrix representation be diagonal in the sense that $$ S = \begin{bmatrix} S_1 & 0 \\ 0 & S_2 \end{bmatrix} ?$$
Comment: In that case no, since you can always find a basis in which the "matrix" is not diagonal, see gerw's answer.
Answer: No. Let $x \in \mathbb{R}^2$ be a vector of norm $1$, but not aligned with the coordinate axes. Then, $x \, x^\top$ is a projection which is not block-diagonal.
Comment: Thanks for the answer, although a counter example in infitinite dimensional Banach spaces would be more interesting ( since I was already familiar with counterexamples such as this one).
Comment: Then take any infinite dimensional Hilbert space $H$ and consider the projection $\mathbb{R}^2 \times H \ni (y,h) \mapsto (x\,x^\top y , h)$ on the space $\mathbb{R} \times (\mathbb{R} \times H)$.
Comment: Yes, and it can be represented as an operator matrix of the form  $$ \begin{bmatrix} xx^\bot & 0 \\ 0 & I_H \end{bmatrix}: \begin{bmatrix} \mathbb{R}^2 \\ H \end{bmatrix} \rightarrow \begin{bmatrix} \mathbb{R}^2 \\ H \end{bmatrix}.  $$
Comment: Yes, this works if you factor the space like $(\mathbb{R}^2) \times (H)$, but not if you factor it like $\mathbb{R} \times (\mathbb{R} \times H)$, i.e. $X = \mathbb{R}$ and $Y = \mathbb{R} \times H$.
Comment: My question was about spaces was about operators on sums of spaces themselves without different factorisations.

Projection on sum of Banach spaces


Is it possible to hide a menu item using menu blocks in context based on user roles?

Question: I am using the Menu block module to create menu blocks and have them attached to the menu in Drupal 7.  I am also using the Context module to display the menu and items on different pages.
I have a certain menu item that I want only to be visible with certain user roles.  I have created a context for the page (based on "path") that linked to the menu item and have selected the administrator role as a condition and selected require both (path and user role).
Using a non-admin test user I can still see the menu item (It should be hidden).  When I click on it the page content doesn't show but the menu item is still visible to the user.
How do I use Context to hide the menu item as well.
Thanks in advance
Answer: you could hide it programatically
<code>function YOURTEMPLATE_menu_alter(&$items) {

 global $user;

  if (in_array('anonymous user', $user->roles)) {
  unset($items['user/%user/profile']);   // example link
  }

 }
</code>
This will hide that menu item for anonymous users.


How important are the priors in a MH algorithm

Question: I am developing a MH algorithm for estimating some parameters, I have some insights about the prior for some of them but for others I am just guessing. I have simulated some data and I am trying to test if my algorithm works, here is easy because I put the mean for the priors near to my true values, but what happens with my real data? are they going to be strongly influenced by my guessing? How can I proceed for have values in which I can trust?
thanks
Answer: The question is somewhat out of focus as it mixes the issue of inference (to wit, Bayesian inference in this case) and computation (i.e., Metropolis-Hastings approximation to the posterior distribution).
The prior selection influences inference and estimates, as it should. I suggest reading some introductory material to Bayesian statistics to this effect, not in the least suggesting my own books! In case one is incapable of setting a prior, there are reference solutions (e.g., Jeffreys priors), and algorithms that provide an assessment of the choice being made.
To test an algorithm implementation like MH it is completely acceptable to start with a prior distribution that strongly agrees with one's (simulated) data. An easy solution in this regard is to generate a parameter from the prior (provided it is proper) and a dataset conditional on this generated parameter. The posterior distribution (as approximated by MH) should then "cover" the value generated unless the model is ill-defined, e.g., unidentifiable.


Asp.Net 5(Core 1.0) Class Library System.Text.RegularExpression

Question: Como utilizar o namespace System.Text.RegularExpression no Asp.Net 5, estou com um projeto e fui atualizar ele para o asp.net 5, meu problema foi que não consigo utilizar Expressões regulares no mesmo e n consigo referenciar o namespace em questão.
Comment: Não conheço muito sobre o .NET Core ainda, estou procurando algo pra te ajudar.
Comment: Só um adendo: ASP.NET agora se chama ASP.NET Core 1.0
Comment: jbueno, vc sabe como resolver? isso eu já sabia, e que o asp.net core vai morrer tb já sabia, pois vai ser anexado ao .net core q está para sair, se puder ajudar a resolver agradeço...abç!
Answer: Encontrei essa questão nas issues do beta ainda e foi resolvido adicionando a dependência "System.Text.RegularExpressions" no project.json.
Pelo que eu entendi, agora o Regex é uma biblioteca isolada do System.Text
Fonte:
https://github.com/dotnet/coreclr/issues/1454


If $(m-n)^2 = 48$, $m^2 + n = 30$, then what is the value of $mn/3$?

Question: If $(m-n)^2 = 48$, $m^2 + n = 30$, then what is the value of $mn/3$?
Comment: Do you really mean $m^2+n=30$, or is it supposed to be $m^2+n^2=30$? Also, what have you tried? Where did you get stuck?
Comment: Yes, you should show your workings please.
Comment: I *really* doubt your gave the problem correctly.
Answer: $n= 30 - m^2$
So $(m-n)^2 = (m^2 +m -30)^2 = 48$
So $m^2 + m - 30 =\pm 4\sqrt 3$.
So $m^2 + 2\frac 12m + \frac 14 = 30 + \frac 14 \pm 4\sqrt 3$
$(m+\frac 12)^2= 30\frac 14 \pm 4\sqrt 3$
$m + \frac 12 = \pm \sqrt{30\frac 14 \pm 4\sqrt 3}$
$m =-\frac 12\pm \sqrt{30\frac 14 \pm 4\sqrt 3}$
So $\frac {mn}3 = \frac {m(30-m^2)}3 = \frac {(\pm \sqrt{30\frac 14 \pm 4\sqrt 3})(30 -(-\frac 12\mp \sqrt{30\frac 14 \pm 4\sqrt 3})^2)}3$
Answer: Perhaps you meant $(m-n)^{2} = 48$ and $m^{2} + n^{2} = 30$. If this is the case, one may solve it as it follows
\begin{align*}
m^{2} - 2mn + n^{2} = 48 \Longleftrightarrow 30 - 2mn = 48 \Longleftrightarrow mn = -9 \Longleftrightarrow \frac{mn}{3} = -3
\end{align*}


Finding the integral of $\frac{8t^3 +13}{(t+2)(4t^2+1)} dt.$

Question: I was looking for the integral of $\frac{8t^3 +13}{(t+2)(4t^2+1)} dt.$
My work:
Dividing the $\frac{8t^3 +13}{(t+2)(4t^2+1)}$, I get $2 + \frac{-16t^2 -2t + 9}{4t^3 + 8t^2 + t + 2}$ or $2 + \frac{-16t^2 -2t + 9}{(t+2)(4t^2+1)}$
Using the partial fraction decomposition on the expression $\frac{-16t^2 -2t + 9}{(t+2)(4t^2+1)}$, the partial fractions of $\frac{-16t^2 -2t + 9}{(t+2)(4t^2+1)}$ I get
is $\frac{-3}{t+2} + \frac{-4t + 6}{4t^2 +1 }$
So...I conclude that....
$$\frac{8t^3 +13}{(t+2)(4t^2+1)} = 2 + \frac{-3}{t+2} + \frac{-4t + 6}{4t^2 +1 } $$
Getting now the integral of $\frac{8t^3 +13}{(t+2)(4t^2+1)} dt$.
$$\int \frac{8t^3 +13}{(t+2)(4t^2+1)} dt = \int \left( 2  + \frac{-3}{t+2} + \frac{-4t + 6}{4t^2 +1 } \right) dt $$
$$ = \int 2 dt  + \int \frac{-3}{t+2} dt + \int \frac{-4t + 6}{4t^2 +1 } dt $$
$$ = \int 2 dt  + \int \frac{-3}{t+2} dt + \int \frac{-4t}{4t^2 +1 } dt + \int \frac{6}{4t^2 +1 } dt $$
$$  = 2t  - 3ln(t+2)  - \frac{1}{2}ln(4t^2 + 1) + 6\arctan (2t) + C$$
$$   = 2t  - \left( (ln(t+2)^3)  + ln((4t^2 + 1)^{\frac{1}{2}}) \right) + 6\arctan (2t) + C$$
$$   = 2t  - \left( ln((t+2)^3(4t^2 + 1)^{\frac{1}{2}}) \right) + 6\arctan (2t) + C $$
$$   = 2t  - \frac{1}{2}\left( 2\left( ln((t+2)^3(4t^2 + 1)^{\frac{1}{2}}) \right)\right) + 6\arctan (2t) + C $$
$$   = 2t  - \frac{1}{2}ln((t+2)^6(4t^2 + 1))  + 6\arctan (2t) + C $$
But in my book, it says that the integral of $\frac{8t^3 +13}{(t+2)(4t^2+1)} dt$ is $2t  - \frac{1}{2}ln((t+2)^6(4t^2 + 1))  + 3\arctan (2t) + C$
My answer is so close to that of the book, but I couldn't locate my error. Where did I go wrong?
Comment: What is $(\arctan(2t))'$?
Comment: @choco_addicted   $\int \frac{6}{4t^2 +1 } dt = 6\arctan(2t)$. It came from the integral  $\int \frac{du}{u^2 +a^2}  = \frac{1}{a}\arctan(\frac{u}{a})$
Answer: You know that
$$
\int \frac{1}{t^2+1}dt=\arctan t + C.
$$
Thus, let $u=2t$, then
\begin{align}
\int \frac{6}{4t^2+1}dt &= \int \frac{6}{u^2+1}\frac{1}{2}du\\
&=\int \frac{3}{u^2+1}du\\
&=3\arctan u + C\\
&=3\arctan 2t + C.
\end{align}
Thus $\int \frac{6}{4t^2+1}dt = 6\arctan (2t) + c$, you found, is wrong.
Answer: you should properly pose x=2t but then dx/dt=2
$I= \int 2 dt  + \int \frac{-3}{t+2} dt + \int \frac{-4t}{4t^2 +1 } dt + \int \frac{6}{ \color{red}{4t^2 +1 }} dt$
$I= \int 2 dt  + \int \frac{-3}{t+2} dt + \int \frac{-4t}{4t^2 +1 } dt + \int \frac{3}{ \color{red}{x^2 +1 }} dx$
$I= \int 2 dt  + \int \frac{-3}{t+2} dt + \int \frac{-4t}{4t^2 +1 } dt + 3\int \frac{1}{ \color{red}{x^2 +1 }} dx$
$I= \int 2 dt  + \int \frac{-3}{t+2} dt + \int \frac{-4t}{4t^2 +1 } dt + 3\color{red}{\arctan(2t)}$


Is the skew normal distribution log-concave?

Question: Is the skew normal distribution log-concave?
Answer: Yes, this property was proved by Azzalini himself in his paper "A class of distributions which includes the normal ones". You can find it there as Property D, which is used to prove strong unimodality of the skew normal density.