How can you prove $\binom {2n}{2} = 2\binom{n}{2} + n^2$?

Question: Is there a way one can prove that this is true: ${2n \choose 2} = 2{n\choose 2} + n^2$ ?
I am thinking it may involve binomial theorem.
Comment: What do you mean by 2(n, 2)?
Comment: One can use the fact that $\binom{k}{2}=\frac{k(k-1)}{2}$. Or else one can use a combinatorial argument. There are other ways. I assume you meant $2C(n,2)$.
Comment: "I am thinking it may involve binomial theorem." If you mean that this "may involve" the **definition** of the binomial coefficients, indeed it does. What is the definition of ${k\choose 2}$, already?
Answer: We have
$$\begin{align}
\binom{2n}{2}&=\frac{(2n)!}{2!(2n-2)!}\\\\
&=n(2n-1) \tag 1
\end{align}$$
and
$$\begin{align}
2\binom{n}{2}+n^2&=2\frac{n!}{2!(n-2)!}\\\\
&=n(n-1)+n^2\\\\
&=n(2n-1) \tag 2
\end{align}$$
Upon comparing the right-hand sides of $(1)$ and $(2)$ we obtain the result!
Answer: Combinatorial method: consider the following diagram.

The number of lattice points in the big square, such that the first coordinate is strictly less than the second, is equal to those in the top-left little square, plus the two little triangles.
Answer: Suppose we wish to select two people from a group of $n$ men and $n$ women.  Then $\binom{2n}{2}$ is the number of ways we can select two people from the group.  Alternatively, we can select two men in $\binom{n}{2}$ ways, two women in $\binom{n}{2}$ ways, and one man and one woman in $n \cdot n = n^2$ ways.  Hence, $$\binom{2n}{2} = \binom{n}{2} + \binom{n}{2} + n \cdot n = 2\binom{n}{2} + n^2$$
Answer: Induction is fine, too. We have: $$\binom{a}{2}=\binom{a-1}{2}+\binom{a-1}{1},$$ hence we just need to check that the given identity holds for $n=1$ and that $n^2-(n-1)^2=2n-1$.
Answer: You have collection of $n$ red and $n$ black balls. In how many ways we can choose 2 balls form this set?
First solution: ${2n}\choose{2}$.
Second solution: we can choose two red or two black balls in $2 {{n}\choose{2}}$ ways and a pair of one red and one black ball in $n \cdot n = n^2$ ways.
Hence ${{2n}\choose{2}} = 2 {{n}\choose {2}} + n^2$.
Comment: This is essentially N. F. Taussig's answer
Comment: … which is itself essentially mine cast into words :)
Comment: I wrote my answer slower... I think


React/Flux: strange error while rendering

Question: I am getting this error while dynamically rendering a component in react

findComponentRoot(..., .0.1.1.0.18.104.22.168.1:4): Unable to find element.
  This probably means the DOM was unexpectedly mutated (e.g., by the
  browser), usually due to forgetting a  when using tables,
  nesting tags like <form>,
, or , or using non-SVG elements in an
  <svg> parent. Try inspecting the child nodes of the element with React
  ID

I have checked out the markup and it seems fine. Sometimes the error changes on element, I mean, sometimes it appears to affect a certain element sometimes it appears on other elements.
Here is my render object:
render: function(){

    var _slots = function(id, h, handleClick){

        //react way to do this
        var daysforSlot = this.props.workingDays.map(function(day, i){

            var spanActive = this.state.appointments.map(function(appointment){
                            var _activeClass = null;
                            var _s = null;

                            if(h.hour+day === appointment.hour+appointment.day){
                                _activeClass = 'active'
                            }

                            if(_activeClass){
                                _s = {appointment.patient.name}
                            }

                            return (  {_s}  )
            });

            return (

                    {spanActive}

            )
    }.bind(this));

    return(

                {h.text}
                {daysforSlot}

        )

    }.bind(this);

    //creates the working hours for the days and bind the click
    //handler to the hour slots
    var _schedule = this.props.workingHours.map(function(h, i){

        return (

                  {_slots(i, h, this.handleClick)}

            )
    }.bind(this));

    return(

            {_schedule}

    )
}

Thanks in advance for any comments.
Comment: It means more or less what it says on the tin. When you create a table via HTML (or React) the browser will insert `thead` and `tbody` tags in the DOM/Virtual DOM even if you do not. When you mutate your state or properties this causes there to be a mismatch between parent/child mappings tracked by React and causes this error. Be sure to output `tbody` (and `thead` when relevant)
Answer: The html you're outputting is invalid. You have a td directly inside of a div - they must be the direct child of tr. Also you have a span as the child of tr, which is not valid.
Comment: This answer was hugely helpful to me when I was conditionally returning an empty `div` inside a table in my `render` method in my component, which screwed up the markup.


How can i find this universal cover?

Question: I have $X = \{(x,y,z) | x^2 + y^2 = 1, z = 0\}$ and $Y = \{(x,y,z)| (x-1)^2 + y^2 + z^2 = 1\}$.
What is the universal cover of $X \cup Y$?
Comment: The universal cover of a diamond ring is a string of Christmas lights. :)
Comment: It may help to visualize what the space looks like first. $X$ is a circle of radius 1 in the $xy$-plane, centered at the origin. $Y$ is a sphere of radius 1 centered at $(1,0,0)$
Answer: @Wvk is correct in his answer, the universal cover looks exactly like the universal cover of the wedge of two circles pictured below,

except that every node of this graph has to be replaced by a sphere like so:
Answer: $X \cup Y$ is sphere union two (kind of) diameters. So I think the universal cover is like:

How can i find this universal cover?


Why is the default cost function choice of a neuron quadratic loss?

Question: I'm studying neural networks, and I'm trying to decide why the default choice of cost function for a single neuron seems to be quadratic loss:
$$\sum_i(y_i-f_i)^2,$$
instead of:
$$-\prod_ip_i^{y_i}(1-p_i)^{1-y_i},$$
as per logistic regression.  Where both $f_i$ and $p_i$ are the sigmoid (activation) function.
I understand that the neuron does not classify per say but instead modulates/dampens the output based on its activation function, so that when many neurons are connected together to form the network, classification only needs to be done on the output node using some cut-off value.
Nevertheless, if classification is our goal, it seems like the right choice of cost function should be that which relates the strength of the firing directly to the probability that it would fire if it were only firing at total strength or not at all.  And doing this in such a way that if we ran the neuron many times using this probability as the probability that it would fire, then the expected value of the neuron firing would equal the strength with which it fires every time upon minimizing our cost function.  (sorry I may have worded that poorly)
Is there a reason then that the logistic regression cost function is not the default choice?
Comment: From what I heard, the use of the quadratic loss is more due to historical reasons than from practical ones. Interesting question! :)
Comment: Sounds like your reference is either outdated, or specifically assuming regression. All kinds of different losses (square, log, hinge, ranking, etc) get used with ANNs and any decent modern treatment is going to discuss what loss functions are appropriate for a given problem.
Comment: This depends on the problem, but we can roughly generalise by using negative log-likelihood in all problems. In regression, the NLL is the quadratic error (different by some constants). In binary and multi-class clf, the NLL is the cross-entropy. See chapter 5 of Pattern Recognition and ML by Bishop for a summary and details.
Answer: The cost function derived in logistic regression is quite similar to the cross-entropy cost function in NN terminology. The difference is that in cross-entropy they took a log and divided it by the number of samples.
The reason for the log is for the ease of getting the gradient, and dividing by a constant does not affect the learning in terms of gradient decent(Except for Plain gradient descent).
It is used quite often. The default-introduction of the quadratic loss in text books may be due to historical reasons.
Comment: Aha! I feel vindicated by your cross-entropy link.


Definition by degree and intersection number are equivalent (linking number). [repost]

Question: I will here restate a question I asked earlier. It did not have much succes (probably by an incomplete introduction of the problem on my part).
I am reading a paper by Ricca ( http://www.maths.ed.ac.uk/~aar/papers/ricca.pdf p.1338 on the bottom) on the linking number. I would like to see that its definition as the degree of the map $\Psi$ is equal to that by intersection number.
A link $L$ has two component knots $\gamma_1$ and $\gamma_2$, these denote embeddings of $S^1$ in $\mathbb{R}^3$.
Consider
$$\Psi: \mathbb{T} \,\,(= C_1\times C_2)\to S^2: (s,t)\mapsto \textbf{n}(s,t) = \frac{\gamma_1(s) - \gamma_2(t)}{\bigl|\gamma_1(s) - \gamma_2(t)\bigr|}
$$
Then $\text{deg} \Psi$ is one definition of the linking number. Taking a Seifert Surface $M$ of $\gamma_1$  (i.e. an orientable surface with boundary $\gamma_1$) then its intersection number with $\gamma_2$ will also give the linking number.
Now I would like to prove that these are equivalent. Therefore consider the orientable manifold
$$N = (M\times\gamma_2) \,\, \bigm\backslash \,\bigcup_{m\in M\cap \gamma_2} \mathcal{B}(m,\epsilon)
$$
with boundary
$$\partial N = (\gamma_1\times\gamma_2) \cup \bigl(\bigcup_{m\in M\cap\gamma_2}\mathcal{S}(m,\epsilon)\bigr)
$$
Also consider $\overline{\Psi}:N\to S^2: (x,y)\mapsto \frac{y-x}{|y-x|}$. Its restriction to $\gamma_1\times\gamma_2$ is now $\Psi$.
The degree of $\overline{\Psi}$ restricted to $\partial N$ is now zero. So we get
$$\text{deg}\biggl(\overline{\Psi}\biggm| {\gamma_1\times \gamma_2}\biggr) + \text{deg}\biggl(\overline{\Psi}\biggm|{\bigcup_{m\in M\cap \gamma_2}  \mathcal{S}(m,\epsilon)}    \biggr) =0 \text{.}
$$
The first term gives the linking number defined by degree. How do I see that the second term gives the intersection number?
I know this has to do with the orientations, but I don't have enough feeling for this yet, to write this down rigorously. I really hope that someone could explain how this works or at least give me hint. Thanks in advance.
Comment: I've done some edits to make this more readable. But having done so I can now see that your formulas for $N$ and $\partial N$ are flawed. For instance, the set you are removing from $M \times \gamma_2$ is not a subset of $M \times \gamma_2$, instead it is a subset of $M$.
Comment: @LeeMosher: Agreed. Confusingly, this is also the definition given in the paper referenced. Here's what I suspect is going on: View $N$ as $M\times S^1$. Given $m\in M \cap \gamma_2$, let $t_m$ be the point satisfying $\gamma_2(t_m)=m$. The points of the form $(m,t_m) \in  N$ are the points where $\overline{\Psi}$ is undefined, so we remove a 3-ball around each such point. A well-chosen orientation convention for each $S^2$ in the boundary will make it so that the degree of $\overline{\Psi}$ is the negative of the sign of the corresponding intersection between $\gamma_2$ and the surface $M$.
Comment: I should add that it is relatively straightforward, with the right picture, to see that the degree of the map on each $S^2$ is $\pm1$. If I can see why the, say, outward orientation makes the whole computation work, I'll post a full answer.
Comment: @LeeMosher: Indeed this might be a bit confusing, however squirrel added what also I think is meant by the author. I suppose we can see $M\times \gamma_2$ as some kind of torus that is filled up. As such we can then take away these three-dimensional balls around the problematic points. Btw: thanks for the edits
Comment: @squirrel: thank you for your efforts. I am looking forward to that full answer.
Answer: Here's the idea in a more general setting. If you have two oriented submanifolds $X$ and $Y$ intersecting transversally at a point in $\mathbb{R}^n$ (or in an arbitrary oriented manifold but viewed locally as living in $\mathbb{R}^n$ so that you can use vector operations), then the map $\psi: (X \times Y )\setminus (X \cap Y) \to S^{n-1} \subset \mathbb{R}^n$ given by
$$(x,y) \mapsto \frac{y-x}{\|y- x\|}$$
encodes the sign of intersections between $X$ and $Y$. It suffices to consider a local model with oriented copies of $\mathbb{R}^k$ and $\mathbb{R}^\ell$ inside $\mathbb{R}^{k+\ell}$. The above map is defined on $(\mathbb{R}^k \times \mathbb{R}^\ell)\setminus \{(0,0)\}$. For convenience, let $\bar S^{n-1}$ and $S^{n-1}$ denote the unit spheres in $\mathbb{R}^k \times \mathbb{R}^\ell$ and $\mathbb{R}^{k+\ell}$, respectively, each oriented as the boundary of the unit ball. Note that the obvious map $\mathbb{R}^k \times \mathbb{R}^\ell \to \mathbb{R}^{k+\ell}$ is orientation-preserving if and only if the intersection $\mathbb{R}^k\cap \mathbb{R}^\ell$ is positive. It follows that the restriction $\bar S^{n-1} \to S^{n-1}$ of this map has degree positive (resp. negative) one when $\mathbb{R}^k$ and $\mathbb{R}^\ell$ intersect positively (resp. negatively).  The restriction of $\psi$ to $\bar S^{n-1}$ is simply $(x,y)\mapsto y-x$, and we note that it factors as a composition $\bar S^{n-1} \to \bar S^{n-1} \to S^{n-1}$, where the first map is $(x,y)\mapsto (-x,y)$ and the second map is $(x,y)\mapsto x+y$. The first map has degree $(-1)^k$ and the second map has degree positive (resp. negative) one when the intersection is positive (resp. negative).
Now in our setting we have nearly the same setup, but we'll have to make one minor change that ultimately flips the degree. For each intersection point $(m_\alpha,t_\alpha) \in M \cap \gamma_2$ we remove a neighboring 3-ball from $M \times S^1$, obtaining a new manifold $N$. Note that each spherical boundary component $S^2_\alpha$ is oriented as the boundary of $N$, not the boundary of the (removed) 3-ball, so the orientation of $S^2_\alpha$ is the reverse of the sphere $\bar S^{n-1}$ in the above discussion. Thus, at a positive intersection point, the degree of $\overline{\Psi}$ is $-(1)(-1)^{k=2}=-1$. Simiarly, its degree is $-(-1)(-1)^{k=2}=1$ at negative intersection points.
Comment: There was a pair of errors in my original answer.  Each reversed the degree of (the same) map, so the answer appeared correct at the end.  This approach may appear less geometric, so you should check out the previous (flawed) version to get the visual intuition.
Comment: Thank you, this helps a lot. I think I am beginning to get some intuition with these orientations. Am I right to say that the first version would be correct if: 1) We notice that the orientation of the unit ball and and the chosen orientation do not coincide and 2)  we take another orientation of these vectors (in the drawing).
Comment: @TomBecker:  No problem. And you're exactly right, those are the two errors I needed to remedy.


preprocess views view field find view block name

Question: I need the to find the block view name so I can add it to the if statement in hook_preprocess_views_view_field in Drupal 8. How would I do this? When I use kint($variables['field']) to find the variables Drupal explodes so I don't even know if the variables exists
<code>/**
 * Implements hook_preprocess_views_view_field()
 *
 */
function mytheme_preprocess_views_view_field(&$variables) {
    //-- I need the to find the view name
    //-- so I can add it to the if statement
    if ($variables['field']->field == 'nid') {
    }
}
</code>
Answer: Try the following
<code>//gives you views current display - "block_1" or "page_1"
$variables['view']->current_display;

//gives you views id - "recent"
$variables['view']->id();
</code>


T-test in the presence of autocorrelation

Question: I have a time series data and I would like to check if the sample mean is statistically significantly different from zero. I was going to do the t-test, but the t-test assumes independent data, while my data are heavily autocorrelated (about 40% lag-1 autocorrelation), so my t-stats are also extremely bloated.
I know I can subsample my data, so that the autocorrelation is minimized. But is there anyway to correct for the autocorrelation of the time series while still using the full data, so that the t-stats and p-value correctly indicates the probability of observing similar mean at random from a zero-mean data? I guess there are some corrections to the sample size, so we can have some "effective sample size" that is smaller than actual sample size.
Answer: With model variations like this, it is usually possible to adjust the standard pivotal quantity for the T-test, and perform a test analogous to a standard T-test, by calculating the standard error of your point estimator for the mean, and adjusting your test accordingly.  This may require quite a bit of algebra, but it is usually possible to do with a bit of work.  In this answer we will derive the variance of the sample mean and use this to find the standard error of the sample mean, expressed in its usual fashion but with an adjustment for the effective sample size.  We will then form a quasi-pivotal quantity based on the sample mean that can be used for hypothesis testing.

Variance of the sample mean in an AR(1) model: For an AR$(1)$ model with auto-regression parameter $-1<\phi<1$ you have (using some algebra shown in
Appendix at bottom of post):
$$\begin{equation} \begin{aligned}
\mathbb{V}(\bar{X}_n) = \mathbb{V} \Big( \frac{1}{n} \sum_{t=1}^n X_t \Big)
&= \frac{1}{n^2} \sum_{t=1}^n \sum_{r=1}^n \mathbb{C}(X_t,X_r) \\[6pt]
&= \frac{\sigma^2}{n^2} \sum_{t=1}^n \sum_{r=1}^n \frac{\phi^{|t-r|}}{1-\phi^2} \\[6pt]
&= \frac{1}{1-\phi^2} \cdot \frac{\sigma^2}{n^2} \sum_{t=1}^n \sum_{r=1}^n \phi^{|t-r|} \\[6pt]
&= \frac{1}{1-\phi^2} \cdot \frac{\sigma^2}{n^2} \Bigg[ n + 2 \sum_{k=1}^{n-1} (n-k) \phi^k \Bigg] \\[6pt]
&= \frac{n - 2\phi - n\phi^2 + 2\phi^{n+1}}{(1-\phi^2)(1-\phi)^2} \cdot \frac{\sigma^2}{n^2} \\[6pt]
&= \frac{1}{n} \cdot \frac{n - 2\phi - n\phi^2 + 2\phi^{n+1}}{n(1-\phi)^2} \cdot \frac{\sigma^2}{1-\phi^2} \\[6pt]
&= \frac{1}{n_\text{eff}(\phi)} \cdot \frac{\sigma^2}{1-\phi^2}, \\[6pt]
\end{aligned} \end{equation}$$
where the "effective sample size" is defined by:
$$n_\text{eff}(\phi) \equiv \frac{n^2(1-\phi)^2}{n - 2\phi - n\phi^2 + 2\phi^{n+1}}.$$
When $n=1$ we have $n_\text{eff}(\phi) = 1$ and as $n \rightarrow \infty$ we have $n_\text{eff}(\phi) \rightarrow n (1-\phi)/(1+\phi)$.  The ratio $n_\text{eff}/n$ is decreasing with respect to $n$ if $\phi > 0$ and is increasing with respect to $n$ if $\phi < 0$.

Standard error and quasi-pivotal quantity: Now that we have the variance of the sample mean, we have standard error:
$$\text{se}(\bar{X}_n) = \frac{1}{\sqrt{n_\text{eff}(\phi)}} \cdot \frac{\sigma}{\sqrt{1-\phi^2}}.$$
The value $\text{se}(X_t) = \sigma / \sqrt{1-\phi^2}$ is the standard error for a single observation in the model.  As we increase $n$ we adjust the standard error by dividing through by the effective sample size.  If you are willing to incorporate the variability of this function from your estimator of $\phi$ as one lost degree-of-freedom, and otherwise ignore its variability, then you can form the quasi-pivotal quantity with approximate distribution:
$$\frac{\bar{X}_n - \mu}{\hat{\text{se}}(X_t) / \sqrt{n_\text{eff}(\phi)}} \sim \text{T}(df = n-2).$$
This allows you to test the hypothesis of zero mean using a standard T-test, with an adjustment for the estimated auto-correlation between the values.  Note that this is a fairly crude adjustment which does not take account of the variability in the estimator for $\phi$.

Appendix - Some mathematical working: Here is the mathematical working for the last step of the above result.  Using the results for sums of geometric sequences we have:
$$\begin{equation} \begin{aligned}
\sum_{k=1}^{n-1} (n-k) \phi^k
&= n \sum_{k=1}^{n-1} \phi^k - \sum_{k=1}^{n-1} k \phi^k \\[6pt]
&= n  \sum_{k=1}^{n-1} \phi^k - \phi \frac{d}{d\phi} \sum_{k=1}^{n-1} \phi^k \\[6pt]
&= n \cdot \frac{\phi-\phi^n}{1-\phi} - \phi \cdot \frac{d}{d\phi} \frac{\phi-\phi^n}{1-\phi} \\[6pt]
&= n \phi \cdot \frac{(1-\phi)(1-\phi^{n-1})}{(1-\phi)^2} - \phi \cdot \frac{(1-\phi)(1-n\phi^{n-1}) + (\phi-\phi^n)}{(1-\phi)^2} \\[6pt]
&= n \phi \cdot \frac{1-\phi-\phi^{n-1} + \phi^n}{(1-\phi)^2} - \phi \cdot \frac{1 -\phi -n\phi^{n-1} +n\phi^n +\phi -\phi^n}{(1-\phi)^2} \\[6pt]
&= \frac{\phi}{(1-\phi)^2} \Big[ n (1-\phi-\phi^{n-1} + \phi^n) - (1 -n\phi^{n-1} +n\phi^n -\phi^n) \Big] \\[6pt]
&= \frac{\phi}{(1-\phi)^2} \Big[ n - n\phi - n\phi^{n-1} + n\phi^n - 1 + n\phi^{n-1} - n\phi^n + \phi^n \Big] \\[6pt]
&= \frac{\phi}{(1-\phi)^2} \Big[ (n-1) - n\phi +\phi^n \Big]. \\[6pt]
\end{aligned} \end{equation}$$
We then have:
$$\begin{equation} \begin{aligned}
n + 2\sum_{k=1}^{n-1} (n-k) \phi^k
&= n + \frac{\phi}{(1-\phi)^2} \Big[ 2(n-1) - 2n\phi + 2\phi^n \Big] \\[6pt]
&= \frac{1}{(1-\phi)^2} \Big[ n (1-\phi)^2 + 2(n-1)\phi - 2n\phi^2 + 2\phi^{n+1} \Big] \\[6pt]
&= \frac{1}{(1-\phi)^2} \Big[ n -2n\phi +n\phi^2 + 2n\phi - 2\phi - 2n\phi^2 + 2\phi^{n+1} \Big] \\[6pt]
&= \frac{1}{(1-\phi)^2} \Big[ n - 2\phi - n\phi^2 + 2\phi^{n+1} \Big] \\[6pt]
&= \frac{n - 2\phi - n\phi^2 + 2\phi^{n+1}}{(1-\phi)^2}. \\[6pt]
\end{aligned} \end{equation}$$
Comment: Thanks for the detailed explanation! Just one note: "The value $se(X_t)=σ/\sqrt{1−ϕ^2}$", is the symbol $se(X_t)$ a typo and should be $\hat{se}(X_t)$ instead?
Comment: It would only have the hat over it if you substitute the estimate $\hat{\phi}$ instead of the true parameter $\phi$.  One is the true standard error and the other is the estimated standard error.
Comment: Thanks for the great answer. Would it make sense to base the degrees of freedom for the T distribution on the effective sample size $n_{eff}$ (perhaps $n_{eff}-1$ ?) rather than $n-2$? This makes more sense to me intuitively, but I'm not sure if it's correct.
Comment: I think that answering that would require some actual research into the performance of the relevant estimators.  The degrees-of-freedom parameter in the T-distribution affects both its variance and kurtosis, so you could consider setting this parameter by matching one of these using the method of moments, but it would still require research to see which would perform better as an overall estimator.


Implementation of the Google Identity Toolkit (openid like)

Question: I´m trying to weite a module that implements the folliwing google api
http://code.google.com/apis/identitytoolkit/index.html
it´s kind of like the openid, uses external accounts from the api to allow users to login without having to register the anoying long register form and pass through all verification
I´m new to D7 and openid conpcepts, what i´ve tested was the openid module that comes with D7 and got very disapointed...
first of all I had to have an openid url then I had to create the user and aprove my validation link from my email in order to get logged in to my drupal
that´s useless... because I went through basicaly the same process
What I want is something similar as this StackExchange experience, I used my gmail account and got logged in, I only had to login to google and that was it...
Any ideeas from where to begin with the implementation ?
I want to be able to sync automaticaly the users that will use the Google Id kit with Drupal, without asking too many questions.. because after all what I´m interested is them be able to leave a trail on my site but do encourage them to register easily...
update:
found on google documentation this page
http://code.google.com/apis/identitytoolkit/v1/drupalsample.html
Comment: I suggest you add that as an answer and accept it to mark the question as closed ;)
Answer: If you want to implement it in specific open source platform, please use Google Identity Toolkit Plugins. There is a plugin for opencart 1.4.x: http://www.opencart.com/index.php?route=extension/extension/info&extension_id=3302
It only asks you for 3 installation steps without any coding work to make your dream become true! =)
Drupal plugin for it will be alive soon.
Comment: I've actually made the plugin..don't know how can I make it available for the whole drupal comunity...


looping date with statement from database table in codeigniter

Question: i'm newbie Programmer Codeigniter
i want to show all days from 1 month and give statement from the table of holiday date (i have 46 holiday). i want if holiday, the date show is red.
my controller like this
function attendance()
{
    $data = $this->page();
    $data['this_month'] = date('m');
    $data['this_year']  = date('Y');
    $data['this_day']   = date('d');
    $this_month = date('m');
    $month = $this->m_date->month($this_month)->row_array();
    $data['day_total'] = $month['day_total'];
    $data['holiday'] = $this->m_date->holiday()->result_array();
    $data['attendance']= $this->m_module->attendance()->result_array();
    $data['employee']= $this->m_module->employee()->result_array();
    $this->template->display($data['link'],$data);
}

this is my view
<?php for($m=1; $m <= $day_total; $m++){ ?>
                <?php foreach ($holiday AS $date){ ?>
                    <?php if ($date['tgl'] === date('Y-m-d', strtotime($this_year.'-'.$this_month.'-'.$m))){
                        echo ''.$m.'	';
                    }else{
                        echo ''.$m.'	';
                    } ?>
                <?php } ?>
            <?php } ?>

but when i run in the browser, show like this
error looping image
please help me for this problem.
Thank you.
Answer: I updated the code
in your holiday-loop you echo the date in every iteration, try something like this:
<?php
 for($m=1; $m <= $day_total; $m++){
     $color ="";
     foreach ($holiday AS $date){
           if ($date['tgl'] === date('Y-m-d', strtotime($this_year.'-'.$this_month.'-'.$m))){
               $color="red";
           }
      }
     echo ''.$m.'	';
  }
?>

Comment: thank you for your answer, but a little problem, the date double with holiday. like this 1 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 15 16 17. date 1 and 15 is double.


Problema em inserir dados em arquivo CSV

Question: Estou inserindo os dados no arquivo corretamente, mas quando eu abro o arquivo no Excel, os dados estão todos na mesmo campo na tabela.
Segue o código:
import csv

dados = open('DATA.csv','w')

try:
    writer = csv.writer(dados)
    writer.writerow(('Pais','Região','Status'))
    writer.writerow(('Brail','America do Sul','Emergente'))
    writer.writerow(('Argentina','Amerida do Sul','Subdesenvolvido'))
finally:
    dados.close()

print(open("DATA.csv","rt").read())

Logo após inserir esses dados, eu queria abrir no Excel, e aparecer uma linha com três campos contendo País,Região e Status, onde no caso seria meu cabeçalho da tabela, assim abaixo teria os valores. Alguém pode me indicar o problema ?
Answer: Você queria apenas apresentar os dados na tela? Ou quer que após a execução do código ele abra o arquivo com os dados?
Se for a primeira opção, pode fazer as seguintes alterações no seu código:
Use o with open para abrir o csv e um laço for para printar os dados:
with open('\\DATA.csv', 'rt') as f:
try:
    csv.reader(f)
    for row in f:
        print(row)
except Exception as erro:
        print('erro: ', erro)

Sempre procure tratar possíveis exceções, pois facilita na hora de eventuais erros.
Comment: Eu quero que após a execução do código, eu abro o arquivo CSV no Excel e em cada campos esteja os valor que inseri com write.
Answer: Você precisa setar o delimitador para ponto e vírgula:
writer = csv.writer(dados, delimiter=';')

Uma dica: se você quer abrir o arquivo no excel, porque não gerar um arquivo .xlsx direto? Dê uma olhada nas bibliotecas openpyxl e XlsxWriter.


Eigen: Slow access to columns of Matrix 4

Question: I am using Eigen for operations similar to Cholesky update, implying a lot of AXPY (sum plus multiplication by a scalar) on the columns of a fixed size matrix, typically a Matrix4d. In brief, it is 3 times more expensive to access to the columns of a Matrix 4 than to a Vector 4.
Typically, the code below:
for(int i=0;i<4;++i )  L.col(0) += x*y[i];

is 3 times less efficient than the code below:
for(int i=0;i<4;++i )  l4 += x*y[i];

where L is typically a matrix of size 4, x, y and l4 are vectors of size 4.
Moreover, the time spent in the first line of code is not depending on the matrix storage organization (either RowMajor of ColMajor).
On a Intel i7 (2.5GHz), it takes about 0.007us for vector operations, and 0.02us for matrix operations (timings are done by repeating 100000 times the same operation). My application would need thousands of such operation in timings hopefully far below the millisecond.
Question: I am doing something improperly when accessing columns of my 4x4 matrix? Is there something to do to make the first line of code more efficient?
Full code used for timings is below:
#include <iostream>
#include <Eigen/Core>
#include <vector>
#include <sys/time.h>

typedef Eigen::Matrix<double,4,1,Eigen::ColMajor> Vector4;
//typedef Eigen::Matrix<double,4,4,Eigen::RowMajor,4,4> Matrix4;
typedef Eigen::Matrix<double,4,4,Eigen::ColMajor,4,4> Matrix4;

inline double operator- (  const struct timeval & t1,const struct timeval & t0)
{
  /* TODO: double check the double conversion from long (on 64x). */
  return double(t1.tv_sec - t0.tv_sec)+1e-6*double(t1.tv_usec - t0.tv_usec);
}

void sumCols( Matrix4 & L,
              Vector4 & x4,
              Vector4 & y)
{
  for(int i=0;i<4;++i )
    {
      L.col(0) += x4*y[i];
    }
}

void sumVec( Vector4 & L,
             Vector4 & x4,
             Vector4 & y)
{
  for(int i=0;i<4;++i )
    {
      //L.tail(4-i)  += x4.tail(4-i)*y[i];
      L            += x4          *y[i];
    }
}

int main()
{
  using namespace Eigen;

  const int NBT = 1000000;

  struct timeval t0,t1;

  std::vector<     Vector4> x4s(NBT);
  std::vector<     Vector4> y4s(NBT);
  std::vector<     Vector4> z4s(NBT);
  std::vector<     Matrix4> L4s(NBT);

  for(int i=0;i<NBT;++i)
  {
    x4s[i] = Vector4::Random();
    y4s[i] = Vector4::Random();
    L4s[i] = Matrix4::Random();
  }

  int    sample = int(z4s[55][2]/10*NBT);
  std::cout << "*** SAMPLE = " << sample << std::endl;

  gettimeofday(&t0,NULL);
  for(int i=0;i<NBT;++i)
    {
      sumCols(L4s[i], x4s[i], y4s[i]);
    }
  gettimeofday(&t1,NULL);
  std::cout << (t1-t0) << std::endl;
  std::cout << "\t\t\t\t\t\t\tForce check" <<  L4s[sample](1,0) << std::endl;

  gettimeofday(&t0,NULL);
  for(int i=0;i<NBT;++i)
    {
      sumVec(z4s[i], x4s[i], y4s[i]);
    }
  gettimeofday(&t1,NULL);
  std::cout << (t1-t0) << std::endl;
  std::cout << "\t\t\t\t\t\t\tForce check" <<  z4s[sample][2] << std::endl;

  return -1;
}

Comment: How are you compiling?
Comment: g++ -O3 -I/usr/include/eigen3 . I am on a Linux 14.04 , with a 3.2.0 Eigen and 4.8.4 gcc. I also obtain similar results on the same computer with clang.
Comment: I cannot reproduce. The generated ASM is exactly the same for each version. You can check by yourself with `g++ -O3 -DNDEBUG -s` and search for `sumCols` and `sumVec` in the generated asm file.
Comment: Sorry, there is a typo, the command is: `g++ -O3 -DNDEBUG -S`
Answer: As I said in a comment, the generated assembly is exactly the same for both functions.
The problem is that your benchmark is biased in the sense that L4s is 4 times bigger than z4s, and you thus get more cache misses in the matrix case than in the vector case.
Comment: Indeed. I now changed the bench to avoid the cache of matrix L (i.e. having only one L, and NBT vector y all applied on the unique L). The difference disappear. Thanks for taking the time to look at it and sorry it was a false problem.


Illegal Memory Reference

Question: I'm a beginner in the Assembly Language
trying to Implement STRCPY
My Assembler "TASM" returns an " Illegal Memory Reference" Error.. and tried to read about the error but couldn't find anything.
Here's ma Code.
include inout.asm
.Model Small,c
.486
.STACK 200h
.DATA
    Arr1 DB "ABCD$"
    Arr2 DB "EFGHIJ$"
.CODE
StART: MOV AX, @DATA
       MOV DS, AX

      LEA Si,Arr1
      LEA Di,Arr2

again:  cmp Byte PTR [Si], "$"
        JNE Ite ; Iterate
        JMP Done
         Ite: MOV Byte PTR[ Di ],[Si] ; Error Here
         Inc Si ; One Byte though
         Inc Di ; One Byte though
         JMP again
Done: MOV Byte PTR [Di], "$"
      call puts, offset Arr2
      Call puts, offset Arr1
 MOV AH,04CH
 MOV AL,0
 INT 21h
 END START

and here's what the Assembler says..
C:\TASM\BIN>tasm /zi /z third
Turbo Assembler  Version 3.1  Copyright (c) 1988, 1992 Borland International

Assembling file:   third.ASM
                 Ite: MOV Byte PTR[ Di ],[Si] ; Error Here
**Error** third.ASM(18) Illegal memory reference
Error messages:    1
Warning messages:  None
Passes:            1
Remaining memory:  415k

btw I tried
MOV Byte PTR[DI],BYTE PT[SI] but didn't work
Answer: As icepack points out, what you have there is not a valid instruction.
Check out the movs instruction, though, which will move the byte from [si] to [di] and also increment both index counters.
Answer: Such operation isn't allowed in asm x86. You can't move data directly from one memory cell to another. In order to do that you need to go through a register, e.g.:
mov al, byte ptr[di]
mov byte ptr[si], al

Comment: Ouch.. Forgot that [Si] and [Di] are memory locations.. :s Thank You :)

Illegal Memory Reference


Interfacing Data back and forth: JSapp <--> Drupal

Question: I want to create custom products for every single one of my customers, and to add a thumbnail and custom order data from a JSAPP.

Seen on #2 My JS application must get the unique id from the user.
regardless if they are logged in or not (i dont know how which is the exact data or variable in the db i should send, and how do i send it?)
in #3 i must recieve custom information generated on the jsapp, i can send this as a  Json , XML or URLstring from the jsapp to drupal commerce; im unsure how could i somehow, inject this information or update a variation of my product.
or maybe there's a more easy way to do this.
Does anyone have some pointers on how to address this communication problem?
Answer:
Once your step one runs, you've actually created a unique order with a unique line item that references a product.
The ID in #2 should probably just be your line-item id.

I would consider creating a rule on the event "After adding a product to cart" and a custom action (this is an answer where I provided the code to make a custom action) that takes a line item id (something the rule will easily have access to) and sends that to the three.js app.

You really just want to add the custom data to the line item (which is unique to each line item on the order). In fact, using Customizable Products you can easily create a bundle specifically for adding as many fields as you would need to track your data (and display/hide it in views or display modes).

To do this, I would create a menu item that somehow recieves the full json object. Perhaps this blog article will help? Regardless, once you have your data, you will want to update the line item with your data and the best way to do this is with entity meta data wrappers if you are using fields to store the data.
<code><?php

$line_item_id = 1;
$line_item = commerce_line_item_load($line_item_id);
$line_item_wrapper = entity_metadata("commerce_line_item",$line_item);
dpm($line_item_wrapper->getPropertyInfo());

// ... mess with fields

$line_item_wrapper->save();

?>
</code>

If you are using the fields on a line item to store your data, the cart will already be up-to-date because it simply references all the line items.
Comment: im going to try tonight!


Can I do a repeated measures logistic regression for 16 students who answered different questions on a test?

Question: I had 15 students take a vocabulary test with 100 items at the end of a course and were scored "1" (correct) or "0" (incorrect) for each item. I would like to predict the likelihood of them getting a specific word correct based on how frequently they encountered the word during the course (input frequency) and how often they used the word in their assignments (productive use). Here is an example of what my data looks like:
<code>student   word    input.freq  productive.use  score
1         影響     4           1               1
1         含まれる 10           0               1
1         燃える   4            0               0
2         影響     4           1               1
2         含まれる 10           0               0
2         燃える   4           2               1
</code>
Obviously I don't have a large sample size, so I was wondering if I could use repeated measures in order to do a logistical regression? However, I worry it may be problematic because they are being given different vocabulary words. If logistic regression cannot be used, are there any other suggestions?
Answer: In a nutshell, there is a specialization of this approach you should use. Item Response Theory (IRT) is the preferred approach to evaluating the operating characteristics of a test. The "2PL" approach uses a logistic probability curve for the likelihood of correct response and random slopes and intercepts for each question. It is essentially a latent variable modeling approach. The latent variable estimates assess the difficulty and discriminability (intercept and slope respectively) for each question, additionally, the "ability" of each student can be assessed by translating the score a latent probability. The overall reliability of the test can be assessed. And the empirical model can be tested against a null model where the slopes and intercepts are identical for each question: that is it assesses the adequacy of the total score for evaluating performance..
Comment: Yes, I am not interested in measuring student ability, item discriminability, or test reliability. I would like to see if I can predict the probability of a student getting an answer correct based on their prior interaction with the word (input frequency and productive use). However, I'm not sure if it is okay to do repeated measures with different vocabulary words.
Comment: This is true, but perhaps you should extend your answer a bit. The OP asked if s/he could predict the probability of getting an answer correct depending on exposure to the word (i.e. input freq in the table). That would be an *explanatory* IRT model with exposure as a continuous predictor. A straight up IRT model would only get you the person's latent ability (verbal fluency, most likely). Naturally, you could then take this ability and run a regular regression, but it would probably under-estimate the uncertainty in verbal fluency - recall that in IRT you predict each person's mean *and SE*.


Dotnet core Console Application slack bot logger

Question: I have a .netCore logger console application. I would like to add a slackLogger class library to my project and therefore use a slackLog function in the driver to log to slack.
I found this code online:
using System;
using SlackBotMessages;

namespace SlackLogger
{
    public static class SlackLogger
    {
        var WebHookUrl = "https://hooks.slack.com/services/Your/WebHook/Url";

        var client = new SbmClient(WebHookUrl);

        var message = new Message("New member registered.").SetUserWithEmoji("Website", Emoji.Loudspeaker);
        message.AddAttachment(new Attachment()
        .AddField("Name", "jane doe", true)
        .AddField("Website", "codeshare.co.uk", true)
        .AddField("Job Title", "Developer", true)
        .AddField("Company", "comp", true)
        .AddField("Bio","something about me)
        .SetThumbUrl("https://codeshare.co.uk/media/1508/paul-seal-profile-2019.jpg?width=500&height=500&mode=crop&anchor=top")
        .SetColor("#f96332")
    );

    client.Send(message);
    }
}

I added th SlackBotMessages package to the dependencies. However, noone of the identifiers is recognized by the program.
I don 't see what I am doing wrong here.
Comment: A lot of syntax errors!
Answer: I corrected the syntax errors, does it work now?
using System;
using SlackBotMessages;

namespace SlackLogger
{

    public static class SlackLogger
    {
        static string WebHookUrl = "https://hooks.slack.com/services/Your/WebHook/Url";

        static SbmClient client = new SbmClient(WebHookUrl);

        static Message message = new Message("New member registered.").SetUserWithEmoji("Website", Emoji.Loudspeaker);
        message.AddAttachment(new Attachment()
            .AddField("Name", "jane doe", true)
            .AddField("Website", "codeshare.co.uk", true)
            .AddField("Job Title", "Developer", true)
            .AddField("Company", "comp", true)
            .AddField("Bio","something about me")
            .SetThumbUrl("https://codeshare.co.uk/media/1508/paul-seal-profile-2019.jpg?width=500&height=500&mode=crop&anchor=top")
            .SetColor("#f96332")
            );

        client.Send(message);
    }
}


Multiple subdirectories for controllers in annotations.yaml

Question: I'm am trying to organize my controllers a bit more in a Symfony 5.3 application. They are in a couple of subdirectories and use annotations for their routing. Here are some samples:

../src/StuffA/Controller/ControllerA.php
../src/StuffB/Controller/ControllerB.php

I now want to specify both inside my annotations.yaml. I tried several approaches, but could not find anything that works:
Wildcards - Does not work
controllers:
    resource: '../../src/*/Controller'
    type: annotation

Multiple Paths - Does not work
controllers:
    resource: '../../src/{StuffA,StuffB}/Controller'
    type: annotation

Single Paths - Works but only for one Controller
controllers:
    resource: '../../src/StuffA/Controller'
    type: annotation

Any hint on what I'm doing wrong?
Answer: Just create multiple resource keys.
E.g.:
# annotations.yaml
controllersFoo:
    resource: ../../src/Foo/Controller/
    type: annotation

controllersBar:
    resource: ../../src/Bar/Controller/
    type: annotation

I don't think you can use wildcards or glob patterns with the annotation loader.
Comment: Having 10 keys does not seem to be a big issue, IMO. I don't use annotations/attributes, so my configuration for everything is organized the way I want, separated from the code.
Comment: Just to sort of butt in here, I second the notion of using a routing file instead of annotations when you decide to move controllers elsewhere.  I use single action controllers and place those files wherever it makes most sense to me. No controller directories.  I once pitched the idea of using autoconfigure to load routes from controller files but it went nowhere.
Comment: I will probably end up having up to 10 such folders. Any other ideas on how to make it work without specifying each folder individually?
Comment: Ok, I'll use multiple paths in annotations for now. Might switch over to routing.yml. I just likes to specify routing inside the controllers to have everything at the same place. I'll keep a look out for nice solutions inside routing.yml however.


How to retrieve instance attribute names for which the value is true?

Question: I am using Ruby on Rails 3.2.9 and Ruby 1.9.3. I have an array of symbols and a model class  (ActiveModel) having those symbols (more others) as boolean attributes. Given a class instance I would like to retrieve all its attribute names for which the value is true. That is:
# Given an array of symbols
[:attr_1, :attr_2, :attr_3]

# Given a class instance
<#Model attr_1: true, attr_2: false, attr_3: false, attr_4: true, ... attr_N: true>

# Then I would like to return
[:attr_1, :attr_4, ..., :attr_N]

How can I make that?
Comment: all attributes return booleans?
Comment: @tokland - Not all attributes related to the given model class return booleans but attributes present in the given array "mapped" to those of the given class return booleans.
Answer: attrs = [:attr_1, :attr_2, :attr_3]

class Model
  def are_true?(attr_names)
    eval(attr_names.map {|a| "send(:#{a})"}.join(" && "))
  end
  def which_true?(attr_names)
    attr_names.map {|a| a if send(a) == true}.compact
  end
end

m = <#Model attr_1: true, attr_2: false, attr_3: false, attr_4: true, ... attr_N: true>

m.are_true?(attrs)  # evals if all given attr_names are true
m.which_true?(attrs) # returns array of attr_names which are true

Answer: If you have the list of symbols you can iterate through them and select the ones that are true
symbols = [:attr_1, :attr_2, :attr_3]
symbols.select {|sym| object.send(sym) == true }

If you don't have the list of symbols you want you can simply iterate through all the attributes of the model
symbols = object.attributes
symbols.select {|sym| object.send(sym) == true }

Comment: you can safely drop `== true`
Comment: Not really, that'd return anything that is not `nil` or `false`, the question explicitly says: "I would like to retrieve all its attribute names for which the value is `true`"
Comment: indeed, but looking at the example we can assume that all values are booleans (probably `something?` methods of ActiveModel). If not, it's a poor example.
Comment: Agreed, but that's not an assumption we should be making without further knowledge of the data model, and since the question asks for only `true` values, I believe it does make sense to include it.
Comment: @tokland - The model class is a `ActiveModel`.
Comment: @Pablo Fernandez heelhook - Is the `send` method less performant?
Comment: Not at all. Its standard ruby and what ActiveRecord uses as well. Its part of the `Object` class of Ruby: http://ruby-doc.org/core-1.9.3/Object.html#method-i-send
Comment: @Pablo Fernandez heelhook - What implementing the same but by using the RoR' [`attributes`](http://apidock.com/rails/ActiveRecord/AttributeMethods/attributes) method?
Comment: See the second example. Uses that to retrieve the attributes of the object.


Foco sempre no JFrame

Question: Eu preciso que quando eu clicar em algum botão da minha aplicação o foco retorne para o JFrame. Existe algum método para isso?
Eu poderia chamar o método MeuFrame.requestFocus() em cada ActionPerformed, mas isso demoraria muito.
Answer: Existe sim, tente:
Você diz pro seu jButton transferir o foco e pede pro seu jFrame solicitar esse foco.
 jButton.transferFocus();
 jFrame.requestFocus();

Você ainda pode obter o foco forçando através do:
jFrame.grabFocus();

Esse método obtém o foco independente de quem o tiver (força a transferência do foco pra si), inclusive trás o foco para a janela caso ela não esteja ativa.
Eu lhe recomendaria utilizar da primeira forma, porque o efeito do segundo pode ser indesejado ao usuário.
Comment: existem muitos botões na minha aplicação... Demoraria muito...
Comment: não tem outro jeito não?
Comment: cada botão seu deve dizer que deve transferir
Comment: @Dongabi seus botões não têm uma ação? É só colocar no fim da ação.

Foco sempre no JFrame


Find the density function of $2T_1+T_2$

Question: A device containing two key components fails when, and only when, both components fail. The lifetimes, $T_1$ and $T_2$, of these components are independent with common density function $f(t) = e^{-t}$, $t > 0$ . The cost, $X$, of operating the device until failure is $2T_1 + T_2$.

And here's the solution:
The joint density of $T_1$ and $T_2$ is given by
$$
f(t_1,t_2)=e^{-t_1}e^{-t_2},t_1>0,t_2>0
$$
Therefore,
$Pr(X\leq x)=Pr(2T_1+T_2\leq x) ......step$ $one$
$=\int_{0}^{x}\int_{0}^{\frac{1}{2}(x-t_2)}e^{-t_1}e^{-t_2}dt_1dt_2......step$ $two$
......

What I didn't understand is how you can go from step one to step two.
Answer: We look the easier case first, $P(a_1 \leq Y_1 \leq a_2,b_1\leq Y_2 \leq b_2) = \int_{b_1}^{b_2} \int_{a_1}^{a_2}f(y_1,y_2)dy_1dy_2$. You need to compute the integral over the rectangle region $[a_1,a_2]\times[b_1,b_2]$.
Back to your question, $P(2T_1+T_2 < x)$, and $t_1,t_2>0$, so what you need to do is to find the integral region on $(t_1,t_2)$-plane. The region of $t_1$ goes from the line $t_1=0$ to $t_1=\frac{1}{2}(t_2-x)$, and when $t_1$ is given, the region of $t_2$ is from $0$ to $x$.

Find the density function of $2T_1+T_2$


how to setup dnsmasq for DNS for private and public hostnames via different DNS servers

Question: lets say i have this private hostname dev.private.example.com that is only accessible in a private network over VPN connection and i have prod.example.com that is accessible to the internet. I have DNS servers to resolve the private hostname and then i can use the public DNS servers(google, cloudflare etc) for the public hostnames.
i will like setup dnsmasq(let me know if there is another tool) so that it will query DNS server for the private hostnames and if it is another hostname then it will resolve via the public DNS servers
How do i go about doing this?
Comment: This is a better question and a better answer than the steaming pile that is linked as being the original Q&A. Even the question title on the other linked question is wrong.
Comment: we try to shy away from duplicate questions and duplicate answers.
Comment: thank you @Justin
some of the admins on this site got attitudes and i just dont worry myself much..i told them this question is not same but the guy couldn't take no for an answer and still went ahead to mark as duplicate...thanks for cosigning on this
Comment: answer is below..thanks
Answer: this is what worked for me
edit /etc/dnsmasq.conf and have this in the file
conf-dir=/etc/dnsmasq.d/,*.conf

and then create a file in the conf directory /etc/dnsmasq.d/private.example.com.conf
and add the following in the content of the file

#dont use hosts nameservers
no-resolv
#use following default nameservers
server=126.96.36.199
server=126.96.36.199
strict-order
#serve all *.private.example.com queries using a specific nameserver
server=/private.example.com/184.108.40.206
server=/private.example.com/18.104.22.168

where the following are the nameservers 22.214.171.124 and 220.127.116.11 resolving the private hostname
then restart dnsmasq
service restart dnsmasq
now any private hostnames *.private.example.com will use those nameservers to resolve!!!
and boom!!!


Prove that the language $L = \{a^nb^kc^{n+k} : n \geq 0, k \geq 0\}$ is not regular

Question:
Problem   Prove that the language $L = \{a^nb^kc^{n + k} : n \geq 0, k \geq 0\}$ is not regular by Pummping Lemma.
Pumping Lemma   Let $L$ be an infinite regular language. Then
  there exists some positive integer $m$ such that any $w \in L$ with
  $|w| \geq m$ can be decomposed as: $w = xyz$, with $|xy| \leq m$, and
  $|y| \geq 1$ such that $w_i = xy^iz,$ is also in $L$ for all $i = 0,1,2 \ldots$

Note:$|w|$ means the length of string $w$.
My attempt to this problem is as follows,
Let $m$ be any positive integer, we definie $w$, $w = a^mb^mc^{m+ m}$. Since $m > 0$ which implies $n \geq 0$ and $k \geq 0$ are true. Hence, $w \in L$.
Now consider $|xy|$, by Pumping Lemma we know that $|xy| \leq m$ which implies that $xy$ must consists of entirely $a's$. Furthermore, $|y| \geq 1$, hence $y = a^k$ for some positive integer $k$.
Assuming $k = 1$ to consider $w_0 = xy^0z = a^{m-1}b^{m}c^{2m}$, this string is obviously not in $L$ because $m - 1 + m \neq 2m$. Similarly for $k > 1$, we can always  use $y^0$ to extract some a's from $a^m$ which contradicts the constraints $n + k$. Therefore $L$ is not regular $\square$.
Any suggestion or comment would be greatly appreciated. Thank you.
Comment: It's generally fine, but $m$ cannot be any positive integer, it should be the $m$ of the pumping lemma. The proof should start: suppose $L$ were regular. By the pumping lemma, there exists an $m$ such that ...
Comment: Also, I don't think that there is any need to prove $w \in L$, it's immediate.
Comment: @Yuval Filmus: Thanks a lot. In fact, I wrote $m$ be a positive integer before. Shame on me. As for the proof of $w \in L$, I stated it clearly so I remember that I have to pick a $w \in L$, otherwise my proof is invalid. Lastly, a nice catch on "Suppose $L$ is regular". Would you mind changing your comment to answer so that I can accept it. Thanks in advance.
Comment: If $L$ was regular, then its intersection with $b^{\ast} c^{\ast}$ would be regular. The intersection is $\{b^k c^k \colon k \geq 0\}$, which is a bit simpler, also nonregular language.
Comment: Note that you can use the contraposition of Pumping Lemma for a direct proof over all natural $m$.
Comment: @sdcvvc, Raphael: Many thanks for the suggestion.
Answer: It's generally fine, but for one thing: $m$ cannot be any positive integer, it should be the $m$ given by the pumping lemma. The proof should start: Suppose $L$  were regular. By the pumping lemma, there exists an $m$ such that ... and so on.
Also, the proof of $w \in L$ is rather verbose.


Media queries ou múltiplas folhas de estilos?

Question: Em questão de deixar o site rápido e responsivo, o que é melhor?
1-Usar o Media Queries e definir as resoluções em apenas uma folha de estilo.
2-Usar varias folhas de estilo que serão chamadas no HTML de acordo com a resolução.
Comment: Não estou certo quanto ao desempenho, mas você pode testar o carregamento das duas formas e ver se dá alguma diferença. Na minha opinião sem dúvida usar Media Queries, além de ser mais elegante a manutenção pode ficar mais simples, pois em um arquivo ficam os estilos, ao invés de ter vários arquivos.
Comment: Pode desenvolver em arquivos separados e utilizar uma ferramenta de automação para incluir tudo em um único arquivo.
Comment: Atualmente, é muito raro encontrar sites com media queries em arquivos separados. Geralmente todo o código encontra-se em somente um arquivo CSS.
Answer: Recomenda-se usar somente um arquivo de folha de estilos (.css). Segue abaixo uma relação de prós e contras. Lembrando que são só recomendações e observações... qualquer um dos métodos é efetivo.
Prós de um arquivo .css:

1 requisição HTTP;
Mais fácil você não esquecer de atualizar alguma Media Querie específica.

Contras de um arquivo .css:

Tamanho do arquivo é maior;
Quanto maior o projeto, mais difícil a manutenção;
Necessário soluções JavaScript para funcionar no IE8 para baixo.

Prós de usar vários arquivos:

Arquivo padrão é menor;
Facilita a manutenção e a organização.

Contra de usar vários arquivos:

Várias requisições HTTP;
Piora a manutenção em relação a esquecer de atualizar um item em determinado arquivo.


Is a map from a smooth curve, bijective away from the singularities, already a normalization?

Question: Over $\mathbb{C}$, I am considering a map between projective curves $f: C \rightarrow C'$, where $C$ is smooth.
Suppose that $f$ is surjective as well as bijective away from the singularities of $C'$. Does it already follow that $C$ is a resolution of singularities?
The converse is clear, but I'm not sure how to formally prove this direction (if it is true at all).
Answer: We use the following fact: if $X$, $Y$ are integral schemes of finite type over $\mathbb{C}$ and $f: X \to Y$ is bijective and $Y$ is normal, then $f$ is birational.
See Akhil Matthew's post in https://mathoverflow.net/questions/73321/isomorphism-between-varieties-of-char-0 for the proof of this fact.
Now it's easy: look at $$f : C  \backslash f^{-1}(\text{ Sing }(C')) \to C' \backslash \text{ Sing }(C')$$ and it satisfies the above criterion. Hence, $f$ is birational.
It's well-known that if two smooth curves are birational, they are isomorphic. Hence $C$ must be isomorphic to the normalization of $C'$.
Comment: Thank you, that was very concise and clear. It didn't occur to me to conclude birationality of $f$ first, but in retrospect it makes total sense.


Add a span/class to a field

Question: I've found a way to add a style to a region. The link is /admin/structure/ds/styles.
I've found a way to specify a style for my Title. We can choose the "class" attribute of  title property.
Howe can I add a specific class/span to my "publish date" field?
How can I do that with Display Suite?
Comment: DS Extra module do the trick. Choose "expert" mode for field, and play with it.
Comment: I think "admin/structure/ds/extras" can help me, but I don't know how to use it. Link/tutorials/Help is welcome :)
Comment: Play with it?.....Isn't there a propper tutorial for this, "playing wiith it" is a waste of a lot of time...!
Answer:
Enable the module display suite extras
Define a display suite layout. Once the layout is specified you get the 'custom classes tab'.
Enable Field Templates in the display suite configuration screen admin > structure > Display Suite. Then select "Field Templates". Check "Enable Field Templates. URL is admin/structure/ds/list/extras
Define some classes. Using the "CSS classes" tab in the display suite settings define some "CSS classes for fields". URL is admin/structure/ds/classes
Ensure that the view mode that you are using is managed by display suite. Under "Manage display" accessed either via the node editing screen or admin > structure > content types check the box next to the view mode being used. In the format column the 'Field template' text should now be shown.
Using the cog icon on the right, edit the field template setting. Select the CSS style chosen in #4

With images the process is
1. enable display suite extras
2. Define a display suite layout

Enable field templates

Define classes

Manage the view mode

Select the classes

Add a span/class to a field


Codeigniter:Update Image and Display Current image if I don't want to update old image

Question: I'm stuck on a problem with updating image. I've created image upload which works fine but I also want it to be updated. When I add a need image it updates correctly but I if don't want to change the image and leave it as it is, then my current image can't be retrieve.
Please help me
Here is my code:
my model update
 function updateDatasale($id){

          $data=array(

              'mayor_permit_attachment'=>$this->mayors_attachment()

          );
          $this->db->where('id',$id);
          $this->db->update('tickets',$data);
      }

function mayors_attachment(){

            $pic=array(
                'upload_path'=>'./uploads/',
                'allowed_types'=>'gif|jpg|png',
                'max_size'=>4000,
                'max_width'=>10024,
                'max_height'=>10024,
            );
            $this->load->library("upload",$pic);

            if($this->upload->do_upload('mayors_attachment')){
                $fb=$this->upload->data();
                $fd=$fb['file_name'];
                return $fd;
            }
            else{
                $data = "null";
                return $data;
            }

 }

controller
public function updatesales($id){
    $this->TicketReply_model->updateDatasale($id);
    redirect("accepttask");
}

views

           Mayors Permit:
             <input type="file" name="mayors_attachment" >

Comment: have your problem is solved or not??
Comment: not yet. Additional for my problem is every time I do update, the image return null in database if I did not select any image
Comment: please check my answer please.
Comment: I tried your answer but still nothing happen .. I do make a variable to store may old image but still after updating the old image cant retrieve  ..
Answer: First You have to store hidden image from database with input type file option.
and then check in controller function with if else{} image is available or not?
views
<form method="POST" action="<?php echo base_url().'ControllerName/updateImageData/'.$id;?>" enctype="multipart/form-data">

           Mayors Permit:

           //store hidden image from database.

           <input type="hidden" name="mayors_attachment_oldimage"  value="<?php echo $mayors_attachment;?>">

           <input type="file" name="mayors_attachment">

<button class="btn btn-primary form-control" type="submit">Update Details</button>

</form>

Controller Code :
 public function updateImageData($aid)
    {
         if($_FILES['mayors_attachment']['name']!=""){

             $config['upload_path'] = "./assets/uploads/mayors_attachment/";
            $config['allowed_types'] = 'gif|jpeg|png|jpg';
            $this->load->library('upload',$config);
            $this->path = './assets/uploads/mayors_attachment/';

           $this->upload->initialize($config);

            if (!$this->upload->do_upload('mayors_attachment'))
            {
              $error = array('error'=>$this->upload->display_errors());
           }else{
           $imageUpload = $this->upload->data();
           $mayors_attachment_image_name=$imageUpload['file_name'];
            }
        }
         else{
                $mayors_attachment_image_name=$this->input->post('mayors_attachment_oldimage');

            }

         $insertdata = array(
              'mayors_attachment'=>$mayors_attachment_image_name);

        $insertQuery = $this->db->where('id',$aid)->update('tickets',$insertdata);
    }

Comment: if your problem is solved then please marked as accepted answer by green tick for future readers also.
Comment: what happens ??
Answer: One way that I've used to solve this kind of problem was to store the file name (or the full path) in a session or cookie. After storing, you can easily retrieve this detail and use it wherever you want.
In your upload file check block:
if($this->upload->do_upload('mayors_attachment')){
// other code here
$attachment_session_data = array('attachment_file' => $fb['full_path']); // or the file_name if your prefer
$this->session->set_userdata($attachment_session_data); // add to session
// return normally
}

Then in your view file, using a value attribute for a file input doesn't count and it is not being submitted to the form. So, a workaround will be to echo an img tag, to show the image, then while processing the form, you would check if a new value is entered in the input file and also if a session already exists the previously entered image.
Something like so:
VIEW FILE

           Mayors Permit:
             <input type="file" name="mayors_attachment" >
             <img src="<?php echo $this->session->attachment_file; ?>">

Ideally, $this->session->attachment_file should be in your controller and saved as part of the $data array that will be sent to the view, then you can just call or echo the variable in the view file. (I hope you get the point).
Then in your CONTROLLER or MODEL:
// Check if session exists and input file is empty
if ( $this->session->attachment_file && empty($_FILES) )
{
    // No file was entered, no need to upload
}
else
{
    // New file was entered, do upload.
}

Comment: Glad to help. If this answer solved your problem, please mark as accepted.


Como funciona a integração de aplicativos em redes sociais?

Question: Ultimamente tem se tornado cada vez mais comum a integração de aplicativos dos mais diversos tipos em redes sociais, como por exemplo Facebook, Twitter e até mesmo o Github. Queria entender como funciona essa integração. O Gitter por exemplo permite interação via chat em repositórios do Github... No Facebook, qualquer pessoa pode ir na seção de desenvolvedores e criar um aplicativo para interagir com páginas e pessoas. Até mesmo o Google Hangouts tem aplicativos para serem usados a gosto do usuário na hora das conferências. Estou muito curioso à respeito do funcionamento disso.
Como eu poderia reproduzir algo desse tipo em uma aplicação? Essas plataformas simplesmente fornecem uma API para que essas apps adicionais possam ser integradas? Ou tem algo além disso? Referências para leitura são muito bem vindas... :D
Answer: O protocolo utilizado para integrações de aplicações é o O-Auth. Nunca implementei ele do lado da minha aplicação, apenas ja testei o uso da integração com aplicações como as citadas na sua questão.
Também até a pouco não sabia que se tratava de um padrão para autenticação de clientes externos a aplicações. O site que tem toda a documentação é:
http://oauth.net/2/
Espera ter ajudado!


This representation of the precision matrix (Inverse of the covariance matrix) confuses me

Question: I am currently reading the book titled "Generalized Least Squares" by Takaeki Kariya and Hiroshi Kurata. In one section, a General linear regression model of the form
\begin{equation}
y=X\beta+\varepsilon
\end{equation}
where $y$ is an $n\times 1$ vector, $X$ is an $n\times k$ known matrix of full rank and $\varepsilon$ is an $n\times 1$ random vector with mean $0$ and covariance matrix $\Omega$, such that
\begin{equation}
\mathbb{E}(\varepsilon)=0,\quad Cov(\varepsilon)=\mathbb{E}(\varepsilon\varepsilon')=\Omega\in S(n)
\end{equation}
where $S(n)$ denotes the set of $n\times n$ positive definite matrices.
Moreover, $\Omega$ is unknown and is fomrulated as a function of an unknown but estimable parameter $\theta$
\begin{equation}
\Omega=\Omega(\theta)
\end{equation}
A family of models they consider has the following covariance structure:
\begin{equation}
\Omega=\sigma^2\Sigma(\theta)
\end{equation}
with
\begin{equation}
\Sigma(\theta)^{-1}=I_n+\lambda_n(\theta)C\quad \theta\in\Theta\subset \mathbb{R}
\end{equation}
where $C$ is an $n\times n$ known symmetric matrix, $\lambda=\lambda_n=\lambda_n(\theta)$ is a continuous real valued function on $\Theta$, and the matrix $\Sigma(\theta)$ is positive definite for any $\theta\in\Theta$.
I follow everything clearly up until the presentation of the precision matrix. I would appreciate clarifying this for me, by the means of an example.
Answer: Example: let $\lambda_n(\theta) = \theta^3$ and let $C = \begin{bmatrix}1 & 1 \\ 1 & 1 \end{bmatrix}$. Then
$$\Sigma(\theta) = (I_n + \lambda_n(\theta) C)^{-1} = \left(\begin{bmatrix}1 \\ & 1 \end{bmatrix} + \theta^3 \begin{bmatrix}1 & 1 \\ 1 & 1 \end{bmatrix} \right)^{-1}
= \begin{bmatrix}\theta^3 + 1 & \theta^3 \\ \theta^3 & \theta^3 + 1\end{bmatrix}^{-1}.$$
The class of covariance matrices would be $\sigma^2 \Sigma(\theta)$ for $\theta \in \Theta$ where $\Sigma(\theta)$ has the above form and is positive definite.
For different choices of the function $\lambda_n(\cdot)$ and the fixed matrix $C$, you will get different sets of covariance matrices.


Finding $\lim _{x\to2}\frac{x^{15}-2^{15}}{x-2}$

Question: Please I would it if anyone can breakdown the process of solving
$$\lim _{x\to2}\frac{x^{15}-2^{15}}{x-2}$$
I've tried solving but couldn't get it. Used an online solver and it came up with $245760$, but I would really love to know the process of solving it.
Comment: x-2 is a factor of the numerator, so you should be able to factorise and cancel the denominator
Answer: Hint. One may prove that, for $x,a, \in \mathbb{R}$ and for $n=1,2,\cdots$,
$$
x^n-a^n=(x-a)(x^{n-1}+a\cdot x^{n-2}+\cdots+a^{n-2}\cdot x+a^{n-1}).
$$ Can you apply it?
Answer: Without calculus, Olivier Oloa's answer gives you the way to go by factoring (binomial formula).
If you are allowed to use calculus, this is a limit where l'Hôpital's rule is very efficient:
$$\lim_{x \to 2} \frac{x^{15}-2^{15}}{x-2}= \lim_{x \to 2} \frac{\left(x^{15}-2^{15}\right)'}{\left( x-2 \right)'} = \lim_{x \to 2} \left( 15x^{14} \right) = 15\cdot 2^{14} = 245\,760 $$
If you haven't heard of this rule but you know derivatives, write $\color{blue}{f(x)=x^{15}}$ and compare with:
$$f'(a) = \lim_{x \to a}\frac{f(x)-f(a)}{x-a} \quad\leftrightarrow\quad \color{blue}{\lim_{x \to 2} \frac{x^{15}-2^{15}}{x-2}=f'(2)}$$
to notice that your limit is precisely the definition of the derivative of $f(x)=x^{15}$ at $x=2$ to arrive at $f'(2)=15\cdot 2^{14}= 245\,760$ again.
Comment: thanks..heard of l'hopital's rule but had no idea what it was used for
Comment: To apply LH in this case is absurd.
Answer: It's simple: just use L'Hopital Rule...
$$\lim_{x \to 2}\frac{x^{15}-2^{15}}{x-2}$$
which gives $$\lim_{x \to 2}15x^{14}=15(2)^{14}=245760$$
Comment: You're welcome :)
Comment: To apply LH in this case is absurd.
Answer: Replace the $x$ up top by $x-2 + 2$:
$$((x-2)+2)^{15} - 2^{15}$$
When this is expanded, you get, for some complicated bunch of coefficients $a_k$:
$$\sum_{k=1}^n a_k (x-2)^k + 2^{15} - 2^{15}=\sum_{k=1}^n a_k (x-2)^k$$
When you divide this by $x-2$ and set $x=2$, the only thing left is $a_1$. What is $a_1$? Well, applying the binomial formula, it's $\binom{15}{1}2^{14}=245760$.


AngularJS upgrade 1.2 to 1.5

Question: I am currently upgrading an Angular 1.2.x application to 1.5.5. After upgrading it, the application itself is still working fine. Unfortunately my servicetests are failing with (e.g) the errormessage:

Error: [$injector:unpr] Unknown provider: storeProvider <- store <- secondService

As far as i understand the previous errormessage it is telling me, that within the testscope there is no 'secondService' available. I considered that to be the
Let's say 'firstService' must be mocked. The second service is so simple that it is not needed to mock it.
<code>describe('mainService', function () {
  [...]
  beforeEach(module('app.myApp', function($provide) {
    $provide.value('$state', stateMock);
    $provide.value('firstService', firstServiceMock);
    //following line is needed in Angular 1.3 and greater,
    //if i am running it on angular 1.2 without the line it is working
    $provide.value('secondService', secondServiceMock); }));

beforeEach(inject(function ($injector) {
mainService = $injector.get('mainService');
</code>
How can i inject the original 'secondService' into my unittest, as i do not want to mock every service that this servicetest is depending on.
Please correct me if i am wrong, as i understood it is an issue with scoping https://docs.angularjs.org/guide/migration#migrating-from-1-2-to-1-3. But this more looks like it is related to controllers and not to services.
If it is, then how can i inject it? I also could not figure out a way to use the deprecated mentioned '$controllerProvider.allowGlobals();' in the testcontext.
The Class:
<code>(function () {
'use strict';
angular.module('app.myApp').factory('mainService', mainService);

/* ngInject */
function mainService($state, firstService, secondService,){...}
</code>
Answer: The real issue is found in here. I could not see the whole context, so this question should be ignored.
Bower dependency found in unit test Angular 1.2, but cannot be found Angular 1.5

AngularJS upgrade 1.2 to 1.5


Erro com código PHP

Question: Boa noite, estou desenvolvendo um sistema de login, porém o sistema de mensagem ao digitar email ou senha incorretos está dando erro. Foram feitas algumas alterações na minha postagem anterior, porém o problema não foi resolvido. Os erros exibidos na páginas são:
 Notice: Undefined index: cdg in C:\xampp\htdocs\tcc\index.php on line 69

 Notice: Undefined variable: msg in C:\xampp\htdocs\tcc\index.php on line 86

Segue abaixo o código HTML E PHP com as linhas sinalizadas conforme o erro apresentado:
HTML:
Cadastre-se

Entre

            <button type="button" class="close" data-dismiss="modal" aria-label="Fechar">
            ×
          </button>

                    <?php
  //LINHA 69          $cdg = $_GET['cdg'];
                    if ($cdg == 1) {
                        $msg = "Login ou senha incorreto!";
                    }
                ?>

                    <form method="post" action="valida.php">

                                <input type="email" class="form-control" name="email" id="email" placeholder="Email:">
                                <input type="password" class="form-control" id="senha" name="senha" placeholder="Senha:">

                        <input type="submit" name="btnLogin" value="Entrar" class="btn btn-outline-warning">

                            <?php
          //LINHA 86   echo $msg;
                            ?>

Caso não possuir conta,
                            cadastre-se

                    </form>

PHP:
<?php
include("conexao.php");

$email = $_POST['email'];
$senha = $_POST['senha'];
/* Verifica se existe usuario, o segredo ta aqui quando ele procupa uma
linha q contenha o login e a senha digitada */
$sql_logar = "SELECT * FROM aluno WHERE email = '$email' && senha = '$senha'";
$exe_logar = mysqli_query($conection, $sql_logar) or die (mysqli_error());
$fet_logar = mysqli_fetch_assoc($exe_logar);
$num_logar = mysqli_num_rows($exe_logar);

//Verifica se n existe uma linha com o login e a senha digitado
if ($num_logar == 0){
    header("Location: index.php#login?cod=1");
}
else{
   //Cria a sessão e manda pra pagina principal.php
   session_start();
   $_SESSION['email'] = $email;
   $_SESSION['senha'] = $senha;
   header("Location:aluno.php");
}
?>

Comment: `$_GET['cdg']` e `$msg` não existe e o seu código primeiro deve verificar se existe pra depois mostrar ou recuperar
Comment: Opa Virgilio, gostaria de pegar esse 'cdg' do php direto, como tentativa de login, como se fosse o num_logar, mas não deu certo
Comment: Então precisa pegar aquilo que existe! o `cdg` você está passando na `url`?
Comment: Não estou, como posso fazer de maneira prática?
Comment: Eu não sei como está fazendo e o que precisa mas, é na url tipo `http://www/logar.php?cdg=1` então no seu código PHP funciona. mas, mesmo assim tem que verificar a existencia com `isset()`
Comment: Consegui tirar o primeiro erro usando um isset, porém o segundo não consegui, quando eu coloco o isset da um erro no código que não abre nem a página.. Preciso colocar um SESSION no php para que quando de errado o login demonstre a mensagem:     $_SESSION['msg'] = "Login ou senha incorreto!";
Como posso fazer?
Comment: Isso que falei acima é refente ao echo $msg no html
Answer: De acordo com o erro, resolvi o primeiro e o segundo, porém a mensagem não é exibida ao usuário final. Segue o código atualizado da parte do html, problema resolvido!:
HTML:
<?php
                        if(isset($_GET['cdg'])) {
                        $cdg = $_GET['cdg'];
                        if ($cdg == 1) {
                            $msg = "
Login ou senha incorreto!
";
                        }
                      }
                    ?>

                        <form method="post" action="valida.php">

                                    <input type="email" class="form-control" name="email" id="email" placeholder="Email:">
                                    <input type="password" class="form-control" id="senha" name="senha" placeholder="Senha:">

                            <input type="submit" name="btnLogin" value="Entrar" class="btn btn-outline-warning">

                                <?php
                                $msg = (isset($_GET['msg'])) ? $_GET['msg'] : null;
                                echo $msg;
                                ?>

Caso não possuir conta,
                                cadastre-se

Erro com código PHP


how to set new date() in a @requestParam?

Question: I would like to know if is possible to set a new date() in a @requestParam?
@RequestMapping("/resa")
public String reservation(Model model,@RequestParam(name = "page", defaultValue = ?????? )int p
) throws ParseException

Thank you in advance
Comment: No. Annotation values must be compile-time constants. And a Date can't be the default value for an int anyway.
Answer: Annotations in Java are limited to compile-time constants, so you can't instantiate any new Objects there. There may be a way by using Spring's Expression Language, but I find that hacky.
I guess after Java 8, the correct way to do this would be to have a parameter of type Optional<LocalDateTime>> (Date is a bad old API, don't use it):
@RequestMapping("/resa")
public String reservation(Model model,
       @RequestParam("date") Optional<LocalDateTime>> optionalDate){

    LocalDateTime date = optionalDate.orElseGet(()-> LocalDateTime.now());
}

The Spring docs explicitly mention that Optionals are supported as arguments.
Comment: They say you shouldn't use `Optional` for parameters, it⁄s (mostly) for return values. See for example [Java 8 Optional: How to Use it](https://dzone.com/articles/java-8-optional-how-use-it), the section *How should Optional NOT be used?* near the bottom: "it won't buy us anything … in input parameters of methods". (But I agree in using `java.time`, of course.)
Answer: You can't, but you can make it unrequired, and then just check whether it's null and then assign it with new Date()


Azure pipeline build name (Last commit)

Question: Hi everyone I was wondering if is there any chance to modify in the build name the last commit message, for instance as it's shown in the below image, we always see the buildname followed by the last commit from the repo.
enter image description here
this pipelines is using the multirepo feature, so when the pipeline is triggered by azure build policy it shows the last commit of the pull request and when it triggered manually it shows the last commit from the hosted repo, so in that case we would like to change that message for other generic message.
I have seen in the microsoft docs that we are able to change the name of the build, but I didnt see anything related with the last commit message.
Comment: Check if this helps- https://stackoverflow.com/questions/179123/how-to-modify-existing-unpushed-commit-messag
Answer: The commit message is the value of Build.SourceVersionMessage that corresponds to the message on Build.SourceVersion commit.
There is no method to change the displayed commit message. In fact, it is not part of the build name (Build.BuildNumber). It just displays together with build name in the title line as part of the summary. Changing the value of build name will not affect the displayed commit message.

In addition, For YAML pipelines, Azure DevOps has provided a built-in feature to hide the commit message and only display the build name in the title line of a pipeline run. For more details, see "Disable showing the last commit message for a pipeline run".
If you prefer this, you can try it.
For example:
# Set the format of build name.
name: $(Date:yyyyMMdd).$(Rev:rr)

# Set the triggers.
trigger:
  . . .

# Disable showing the last commit message.
appendCommitMessageToRunName: false

stages:
- stage: A
  displayName: 'Stage A'
  . . .

Comment: Thank you for your answer this really helps me.

Azure pipeline build name (Last commit)


Issue with switching navbars

Question: Okay so currently I have 2 navbars one for desktop/large tablet and one for mobile view. I do not know how to make it switch when I get to the certain size. Here is my attempt, but it is not working.

body, html {
    margin: 0;
    font-family: sans-serif, arial;
}

.content {
    padding: 30px;
}

.nav-main-mobile {
    display: none;
}

.nav-main {
  width: 100%;
    background-color: #222;
    height: 70px;
    color: #fff;
}

.nav-main .logo {
    float: left;
    height: 40px;
    padding: 15px 30px;
    font-size: 1.4em;
    line-height: 40px;
}

.nav-main > ul {
    margin: 0;
    padding: 0;
    float: left;
    list-style-type: none;
}

.nav-main > ul > li {
    float: left;
}

.nav-item {
    display: inline-block;
    padding: 15px 20px;
    height: 40px;
    line-height: 40px;
    color: white;
    text-decoration: none;
}

.nav-item:hover {
    background-color: #444;
}

.nav-content {
    position: absolute;
    top: 70px;
    overflow: hidden;
    background-color: #222;
    max-height: 0;
}

.nav-content a {
    color: #fff;
    text-decoration: none;
}

.nav-content a:hover {
    text-decoration: underline;
}

.nav-sub {
    padding: 20px;
}

.nav-sub ul {
    padding: 0px;
    margin 0px;
    list-style: none;
}

.nav-sub ul li a {
    display: inline-block;
    padding: 5px 0px;
}

.nav-item:focus {
    background-color: #444;
}

.nav-item:focus ~ .nav-content {
    max-height: 400px;
    -webkit-transition: max-height 0.4s ease-in;
    -moz-transition: max-height 0.4s ease-in;
    transition: max-height 0.4s ease-in;
}

@media screen and (max-width: 580px) {
    .nav-main {
        display: none;
    }

    .nav-main-mobile {
        display: all;
    }
}
<!DOCTPYE html>

    <meta charset="utf-8" />
  <title>Learn HTML and CSS</title>
  <link rel="stylesheet" href="app.css" />

                    Home

                    Materials

Text-Editors

Web Browsers

                    Getting Started

Setting It Up

HTML

CSS

                    Other

Sign Up

Sign In

Sources

Home

stuff

stuff

stuff

stuff

stuff

stuff

stuff

stuff

        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio.      Praesent libero. Sed cursus ante dapibus diam. Sed nisi. Nulla quis sem at nibh elementum imperdiet. Duis sagittis ipsum. Praesent mauris. Fusce nec tellus sed augue semper porta. Mauris massa. Vestibulum lacinia arcu eget nulla.

Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Curabitur sodales ligula in libero. Sed dignissim lacinia nunc. Curabitur tortor. Pellentesque nibh. Aenean quam. In scelerisque sem at dolor. Maecenas mattis. Sed convallis tristique sem. Proin ut ligula vel nunc egestas porttitor. Morbi lectus risus, iaculis vel, suscipit quis, luctus non, massa. Fusce ac turpis quis ligula lacinia aliquet.

Mauris ipsum. Nulla metus metus, ullamcorper vel, tincidunt sed, euismod in, nibh. Quisque volutpat condimentum velit. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nam nec ante. Sed lacinia, urna non tincidunt mattis, tortor neque adipiscing diam, a cursus ipsum ante quis turpis. Nulla facilisi. Ut fringilla. Suspendisse potenti. Nunc feugiat mi a tellus consequat imperdiet. Vestibulum sapien.

Proin quam. Etiam ultrices. Suspendisse in justo eu magna luctus suscipit. Sed lectus. Integer euismod lacus luctus magna. Quisque cursus, metus vitae pharetra auctor, sem massa mattis sem, at interdum magna augue eget diam. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Morbi lacinia molestie dui. Praesent blandit dolor. Sed non quam. In vel mi sit amet augue congue elementum. Morbi in ipsum sit amet pede facilisis laoreet. Donec lacus nunc, viverra nec, blandit vel, egestas et, augue. Vestibulum tincidunt malesuada tellus. Ut ultrices ultrices enim.

Thank You in advance.
Comment: `display:all` is wrong. `display:block` is what you need. Close-voted as typo.
Answer: it's display: block, not display: all
Comment: Correct, but for your reference "typo" questions like this should be closed, not answered. I know you don't have your close-vote hammer just yet, but keep it in mind for when you do ^^
Comment: hmm - a typo in my understanding is when somebody hits a wrong key on the keyboard and for example writes "nlock" instead of "block"
Answer: You have to use media queries in order to tell the browser what CSS rules you want it to apply for each specific instance.
Here is a very simple fiddle with a media query for device with a max-width of 500px, in which I override the nav background color from the original black to red.
/* original class */
nav{
  height:50px;
  width:100%;
  background:#000;
}

/* when the window size is max 500px apply this rules */
@media (max-width:500px){
  nav{
    background:red;
  }
}

http://jsfiddle.net/vxyoz78x/
Hope that helps.

Issue with switching navbars


Meta-analysis (Metafor) using Cohens D, what is the variance?

Question: I am using the package Metafor in R to do a meta-analysis, my models are derived from lmer (lme4). I am using the package -> EMAtools -> lme.dscore to retrieve the Cohen's d values which will be used in the meta-analysis.
What I am really stuck on is the variance for Cohen's d.
Last time we did this, we did the standard error to the power to 2 (SE^2) and that was sufficient to be considered the variance, however I am finding it difficult to find a citation as to how this would be considered correct.
Answer: The standard approach to meta-analysis is called the inverse-variance weighted method. The practical effect is that you are giving greater weight to the more precise effect sizes. The standard error is a direct measure of a statistics precision and the standard error is a type of standard deviation. Hence, if you square a standard error it becomes a variance. The metafor package is asking as inputs the vector of effect sizes and associated variances. For Cohen's $d$, the variance is:
$$ v_d = \frac{n_1 + n_2}{n_1 n_2} + \frac{d^2}{2(n_1+n_2)} $$
where $n_1$ and $n_2$ are the sample sizes for the two groups and $d$ is the calculated Cohen's $d$. The standard error for Cohen's $d$ is simply the square-root of the above. Any text on how to do meta-analysis will have this information.
Comment: Thanks for the clean explanation, makes sense.


Binary Serializer - changing location of serializable class with serialized files

Question: I have a class that represents search criteria used to build queries against a datastore. This class is serializable, allowing class instances to be saved to disk and reloaded, providing the business-level feature of saving searches to re-use them.
Here's the problem; I recently changed the location of the class that can be serialized. I didn't change the structure of said class, I only moved it from one project (which no longer exists by its original name) to another. In doing so I realized that I just broke the deserialization of files based on the class as it existed in its prior location.
If possible, I need to be able to "convert" these files. Though the files are in binary format, much of the file is readable as plain text, including the now-invalid namespace. However, just changing the text of said file that I can see will corrupt it, so obviously I'm missing something.
Is there a way to either update the file as some sort of batch process, or point the serializer at the new class location, so the files can be deserialized?
Answer: You can create a small program having two copies of the serializable class in each namespace. Then you can read the data from the files using the class in the old namespace and for each instance create an instance of the class in the new namespace where you copy all the fields. You can then serialize the new classes back to files.
Comment: This is what I'm thinking I'll have to do as well. I was hoping it wouldn't come to this, but oh well. If I end up going this route I think I'll take Marc's advice and switch to a text-based serialization method like DataContract. As he said, it won't matter where the object is as long as its form (as seen by the serializer) matches the serialized file.
Comment: I ended up doing this, but serializing the files to XML; those files could then be deserialized by the same object in its new location.
Answer: You can fix this by using TypeForwardedToAttribute, so that when the system looks in the old assembly, it fails to find the type, but it finds the attribute and looks again in the new assembly. See MSDN for usage, but this works with BinaryFormatter fine.
However, I strongly suggest moving to a contract-based serializer, such as protobuf-net. This will not care of you relocate, rename, etc the types or members. BinaryFormatter is ... Prickly.
Comment: Unfortunately, as I mentioned, the old library doesn't even exist in the solution anymore, so I can't put a "forwarding address" in the old location. I was hoping there was a way to configure the serializer directly so it would do the forwarding without even looking in the old place. I'm thinking of just converting to XML serialization, so if this changes again I'm more likely to be able to update the files directly with any necessary changes.
Comment: @KeithS to do that you might be able to use a custom Binder, but ... Hard stuff. If you can use the old dll to deserialize it would be easier.