Sum of squared eigenvalues of $A$ equals $\operatorname{tr}(A^2)$?

Question: Is the following always true:
$$\sum_i \lambda_i^2 = \operatorname{tr}(A^2)$$
where $\lambda_i$ are the eigenvalues of $A$. If it's not true in general, then under what conditions is it true? Is it always true if $A$ is square and positive semidefinite?
Please provide a proof or reference. Thanks!
Comment: Write $A$ is Jordan form $A=P^{-1}(D+N)P$. Then $A^2=P^{-1}(D^2+2DN+N^2)P$ Therefore, $tr(A^2)=tr(D^2)$.
Comment: Thanks, time to read up on Jordan form.
Comment: Well, it can be proven without it, but if you can use it, it is effortlessly.
Answer: Yes, this always holds when $A$ is square (which it must be to have eigenvalues). One can use Jordan Normal Form or a density argument, the key idea in both proofs being that
$$ \operatorname{tr}(M) = \operatorname{tr}(UMU^{-1}) $$
for any invertible matrix $U$.

JNF proof: Actually, all we need is that any square matrix $A$ is similar to an upper-triangular matrix $B$, $A=UBU^{-1}$. The multiset of eigenvalues is preserved under similarity and the eigenvalues of an upper triangular matrix are the diagonal elements, so the diagonal elements of $B$ are the eigenvalues of $A$, repeated according to multiplicity. The square of an upper-triangular matrix is again upper-triangular, and direct calculation shows that the diagonal elements of the square are the squares of the diagonal elements, so
$$ \operatorname{tr}(A^2) = \operatorname{tr}(UBU^{-1}UBU^{-1}) = \operatorname{tr}(B^2) = \sum_i \lambda_i^2 $$
as required.
Density proof: The function $f:A \mapsto \operatorname{tr}(A^2)$ is continuous on the vector space of matrices (this space is finite-dimensional, so any norm induces the same topology) so if we can prove something about $f$ on a dense subset of the set of matrices, we can extend it to the whole space by continuity. Matrices with distinct eigenvalues are dense (not a proof, but this is plausible since matrices with two eigenvalues the same have fewer parameters to play with, so one might expect them to form a submanifold of lower dimension), and diagonalisable, and for such matrices $A=UDU^{-1}$, $D$ diagonal, one obviously has
$$ \operatorname{tr}(A^2) = \operatorname{tr}(UDU^{-1}UDU^{-1}) = \operatorname{tr}(D^2) = \sum_i \lambda_i^2. $$
Comment: If $p$ is a polynomial, then the same argument shows that $\sum_k p(\lambda_k) = \operatorname{tr}(p(A))$.
Comment: +1 for addressing OP's original question about the general claim
Comment: Wow I never knew that.  Now I know it twice.
Answer: Suppose that $A \in \mathbb{C}^{n \times n}$ and is diagonalizable.
$$ A = V \Lambda V^{*}$$
the characteristic polynomial is given by
$$ p(t) = det(A -tI) = (-1)^{n}(t^{n}-(trA)t^{n-1}+ \cdots + (-1)^{n} det(A))  $$
also, we have
$$p(t) = (-1)^{n} (t-\lambda_{1})\cdots (t - \lambda_{n}) $$
where $ \lambda_{j}$ are the eigenvalues of $A$ then
$$tr(A) = \lambda_{1} + \cdots + \lambda_{n} = \sum_{i=1}^{n} \lambda_{i} $$
now from above
$$A = V \Lambda V^{*}  $$
$$A^{k} = V \Lambda^{k} V^{*} \implies tr(A^{k}) = \sum_{i=1}^{n} \lambda_{i}^{k} $$
Answer: tr $A^2 $ = tr $AA$ = tr $UDU^{-1}UDU^{-1} $ = tr $UD^2 U^{-1}$ = tr $U^{-1}UD^2 =$ tr $ D^2$ = $\sum \lambda_i^2$
Answer: $A$ is Hermitian, hence diagonalizable, so write $A = UDU^{-1}$, where $U$ is unitary, and where $D$ is the diagonal matrix consisting of the eigenvalue of $A$.  The claim follows.
Comment: See [here](https://math.stackexchange.com/questions/241875/sum-of-the-eigenvalues-of-adjacency-matrix) for a similar question I asked a while ago.
Answer: If $\lambda $ is an eigenvalue of $n\times n$ matrix $A$, then  $\lambda^2 $ is an eigenvalue of $A^2$
On the other hand trace of $A^2$  is the sum of its eigenvalues.
Thus $$\sum_i \lambda_i^2 = \text{tr}(A^2)$$  is true for every square matrix.
Comment: You need to ensure that multiplicities are the same to claim the equality with the sum.
Comment: Saying is not the same as ensuring.
Comment: @spiralstotheleft A and A^2 have the same number of eigenvalues counting  multiplicities.


High performance Solr Tag Cloud

Question: I am looking at how to implement a high performance tag cloud in Solr.
I have a Solr database with 15 million records and more added every day.  I have a field in which several copy statements copy data into.  It can have anywhere between 1 and 6 values.  These values are usually a sentence or two (string data).  I've attempted to create a custom field type to optimize & tokenize the field for quick faceting but I'm getting lackluster performance.
Here is the custom field that I've created.
<code>    <fieldType name="KeywordCloud" class="solr.TextField" positionIncrementGap="100" autoGeneratePhraseQueries="true">
  <analyzer type="index">
    <tokenizer class="solr.WhitespaceTokenizerFactory"/>
    <filter class="solr.StopFilterFactory"
            ignoreCase="true"
            words="stopwords.txt"
            enablePositionIncrements="true"
            />
    <filter class="solr.LowerCaseFilterFactory"/>
  </analyzer>
  <analyzer type="query">
    <tokenizer class="solr.WhitespaceTokenizerFactory"/>
    <filter class="solr.StopFilterFactory"
            ignoreCase="true"
            words="stopwords.txt"
            enablePositionIncrements="true"
            />
    <filter class="solr.LowerCaseFilterFactory"/>
  </analyzer>
</fieldType>
</code>
Any suggestions on how I can achieve at least reasonable performance when faceting this field?  Or is there a totally different approach that I can take?
This approach works great when I only have an index of a million documents or so, but 15 million and higher is giving me issues.
Thanks in advance!
Answer: Have you play with the solr cache? As the number of unique terms for a field gets bigger, you need to grow the cache accordingly. See this link for details. Pay attention on the filter cache and on the field cache.
Comment: Thanks for this!  Is there any defined recommendations that I can follow?  Would be great if there was some math I could apply to figure out the optimal configuration.
Comment: Not really math, but you can monitor the cache statistics while you are doing requests on your index (look for the "Statistics" > "Cache" link from the Solr Admin console). If you see many evictions, your cache size are probably too low. But don't go too high as this could hurt your system too.

High performance Solr Tag Cloud


Private key is not along with my developer certificate

Question: I had the issue "Valid signing identity not found" when i download Provisioning profile from provisioning portal.
I tried couple of times to create the certificate from the fresh, but still facing the same "Valid signing identity not found" issue.
Looks like "Private key is not along with my developer certificate" when i see in the key chain. How could i solve this?
Comment: try this link http://stackoverflow.com/questions/13153227/import-provisioning-profile-to-other-mac-from-apple-site/13153501#13153501
Comment: I tried by revoking and creating the developer certificate. Still i don't find the Private key along with Developer Certificate.
Comment: http://stackoverflow.com/questions/5989368/add-private-key-to-certificate-or-vice-versa   check in the Link may be helpfull for you.
Answer: Its worked, if i tried with another mac book. I am not sure, this one is mac book environment issue.
Steps followed
1. Revoked my current certificate from provisioning portal
2. Created new CSR from new Mac Book
3. Created Developer Certificate by submitting the new CSR.
This developer certificate works successful new Mac.
I tried the same certificate by exporting from new mac to my old mac. It's also successful.


Support of "export ... from" by the TypeScript compiler

Question: Is the following export supported by the tsc compiler?
export {PromiseWrapper, Promise, PromiseCompleter}
              from 'angular2/src/facade/promise';

Thanks for your help!
Answer: It is. You can have a look at the corresponding section in the TypeScript specification:
https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md#11343-export-list-declarations
Comment: Thanks for your answer! Pleased to hear that ;-) There is something I missed. Importing elements exported like gives me undefined. I think that I need to have a deeper look at the Angular2 build script...


How does one reduce the Maximum Likelihood rule to a pairwise comparison of the probability densities?

Question: I am studying an article, where the authors have discussed something about "the ML decision rule reducing to a pairwise comparison of the conditional PDFs" because the means and variances are in ascending order.
To remove confusion, I am attaching a screengrab. As you can see, they use condition (11) to invoke the pairwise comparison of the PDFs in (12). I have checked the reference that they cited, that is, [31], but I did not find anything related to that discussion.
Why are the PDFs equal?
Could anyone explain how this works?
I'm not sure if I'm asking the right questions here, feel free to direct me towards the right questions.
Answer: The distributions in (12) are equal because the decision thresholds $\eta_1, \dots, \eta_{M-1}$ are chosen to make them equal.
Consider a simple case, where you have two distributions and you want to assign an observation to one of them.  If your decision rule is, essentially, "assign the observation to whichever distribution is most likely to have generated it", clearly you will choose the one with the highest probability density at the observed value.   The decision threshold will be the value at which the two probability densities are equal; observations that fall below the threshold will be assigned to one distribution, and those that fall above the threshold will be assigned to the other.

In this case, the two distributions are equal at the value $-0.0636$, which becomes the decision threshold.  Equation (12) is simply a mathematical expression of this relationship between the decision thresholds and the distribution values at those thresholds, extended to more than two distributions.  To the left of the threshold, the observation is more likely to have come from the black distribution, so we would assign it to that one, and similarly for an observation to the right of the threshold.  At the threshold, the likelihood that an observation comes from the black distribution is equal to the likelihood that it comes from the blue distribution, so it doesn't matter - mathematically - which one we assign it to.
Comment: Have updated my answer, hopefully addressing your questions.
Comment: Thank you very much. That is very helpful! I have a few follow-up questions :). 1) What is the significance of making the PDFs equal? 2) Does the threshold, $-0.1$ in this case, have to be at the intersection at which the two PDFs meet? 3) Also, would this rule/information also apply to PDFs with different sizes: say one is narrow and tall while the other is wider and shorter? Basically, the former has a smaller variance and the latter has a larger variance.
Comment: Once again, thank you very much for taking the time to answer my queries!


Output asp.net masterpage webform to html email

Question: Hi I'm having a bit of a nightmare here!
I'mv trying output a webform to html using page.rendercontrol and htmltextwriter but it is resulting in a blank email.
Code:
   StringBuilder sb = new StringBuilder();
   StringWriter sw = new StringWriter(sb);
   HtmlTextWriter htmlTW = new HtmlTextWriter(sw);

   page.RenderControl(htmlTW);

   String content = sb.ToString();

   MailMessage mail = new MailMessage();

   mail.From = new MailAddress("firstname.lastname@example.com");
   mail.To.Add("email@example.com");
   mail.IsBodyHtml = true;

   mail.Subject = "Test";
   mail.Body = content;

    SmtpClient smtp = new SmtpClient("1111");
    smtp.Send(mail);

    Response.Write("Message Sent");

I also tried it by rendering a single textbox and got and error saying It needed to be within form tags (which are on the masterpage).
I tried this fix: http://forums.asp.net/p/1016960/1368933.aspx#1368933  and added:
public override void

VerifyRenderingInServerForm(Control control)
{
   return;
}
But now the errror I get is:
VerifyRenderingInServerForm(Control)': no suitable method found to override
Does anyone have a fix for this?  I'm tearing my hair out!!
Thanks,
Steve
Comment: What part of the page life-cycle are you calling that code in? I assume that the lower case `page` is a typo as the `Page` property should have an uppercase "P", and debugging through a page with that in Page_Load fills the string builder with the full HTML, but then the page throws an error about having multiple form elements as I'm not doing anything with the output.
Answer: This is what I do, in vb:
Dim sw as New StringWriter()
Dim writer as New HtmlTextWriter(sw)
System.Web.HttpContext.Current.Server.Execute("YourPage.aspx", writer)
Dim message as String = sw.ToString()

Comment: Thanks for your help.  I tried this method but couldn't get it to work.  It would just get in a loop and output the same text over and over again.  I don't think I implemented it correctly though
Comment: This isn't called from the page I'm trying to render, but from somewhere else in the code, usually in a business layer.
Comment: I need to set 2 fields on the page before it gets rendered, is there a way to do it like this?
Comment: I haven't tried it but I'd assume you can add them as parameters and use a query string to pass them in.
Comment: in C# `var sw = new StringWriter();
var writer = new HtmlTextWriter(sw);
System.Web.HttpContext.Current.Server.Execute("YourPage.aspx", writer);
string message = sw.ToString();`
Answer: If you don't need to redirect the page, after you render the contents of the page (from your code sample, it doesn't look like you need to), then you may want to use a Response.Filter.
Off the top of my head, it would look something like:
protected void Page_Load(object sender, System.EventArgs e)
{
   Response.Filter = new SmtpFilter(Response.Filter);
}

The SmtpFilter class, is just a class that inherits from the Stream object.
The main method will be the Write method. Here is some code off the top of my head to Override the Write(...) method, send the Smtp mail, and continue on processing.
    public override void Write(byte[] buffer, int offset, int count) {
    // get the html
    string content= System.Text.Encoding.UTF8.GetString(buffer, offset, count);

   MailMessage mail = new MailMessage();

   mail.From = new MailAddress("firstname.lastname@example.com");
   mail.To.Add("firstname.lastname@example.com");
   mail.IsBodyHtml = true;

   mail.Subject = "Test";
   mail.Body = content;

    SmtpClient smtp = new SmtpClient("1111");
    smtp.Send(mail);

    buffer = System.Text.Encoding.UTF8.GetBytes(HTML);
    this.Base.Write(buffer, 0, buffer.Length);
    }

If you need more help on Response.Filters, you may want to google it. The first article I found was in VB.NET, but still helpful:
http://aspnetlibrary.com/articledetails.aspx?article=Use-Response.Filter-to-intercept-your-HTML
Comment: Hi, thanks a lot for this answer.  It looks like what I need.  Will it output the values entered by the user filling in the form?

I'll try this out on Monday and let you know how I get on.
Comment: If the form has been posted back, then yes. This is one of the lasts steps in the Response pipeline, so you will get what is being sent to the browser (javascript and all -- so, you will need to be sure to remove any script from your email).
Comment: Ok, I've tried this and get a error stating that the smtpfilter doesn't exist.

Also that there is no definition for 'Base'  Any ideas?
Comment: You have to create your own SmtpFilter class. Check out the article I linked too. They called their class "ReplaceHTML". It inherits from the Stream class.
Answer: So I was struggling with this and FINALLY found the answer...
I was trying to extract the rendered HTML of a GridView and place it in an email.  Everything worked perfectly when that action was happening on a Page, but when I moved the functionality into a User Control, the VerifyRenderingInServerForm method no longer works because it is a Page method, not a Control method.
To fix this, you have to override the Render method and call up to the Page to insure that control is rendered in a form with a runat=server tag.  Here is the fix...
protected override void Render(HtmlTextWriter writer)
{
    if (Page != null)
    {
        Page.VerifyRenderingInServerForm(this);
    }
    base.Render(writer);
}

Thats HOURS of wasted time right there, but finally!
Comment: Okay, I spoke too soon.  My session got dumped and the issue was actually still occurring.  But I have now ACTUALLY fixed it.  I just placed the VerifyRenderingInServerForm method in the page that my control was placed in.  Kill the method perminantly; don't know why I didn't think of that earlier.
Answer: This is the method I use to cram my webforms into an email:
private string HtmlPageInToString()
{
WebRequest myRequest;
myRequest = WebRequest.Create(@"http://yoururlhere/");

myRequest.UseDefaultCredentials = true;

WebResponse myResponse = myRequest.GetResponse();

Stream ReceiveStream = myResponse.GetResponseStream();
Encoding encode = System.Text.Encoding.GetEncoding("utf-8");

StreamReader readStream = new StreamReader(ReceiveStream, encode);

return readStream.ReadToEnd();
}

This will stuff your webform into a string for use how ever you would like.  The great thing is that it pulls in the whole page so you won't have to worry about the tags from your masterpage not being included also.
Comment: I tried this but the values entered into the text boxes are lost.
Comment: And you are not storing the input from the text boxes anywhere?
Answer: To me this sounds like you could do this with a user control, and then render the user control  output into a string using the following code:
public class ViewManager {
    public static string RenderView(string path, object data) {
            Page pageHolder = new Page();
            UserControl viewControl = (UserControl) pageHolder.LoadControl(path);

            if (data != null) {
                    Type viewControlType = viewControl.GetType();
                    FieldInfo field = viewControlType.GetField("Data");
                    if (field != null) {
                            field.SetValue(viewControl, data);
                    }
                    else {
                            throw new Exception("ViewFile: " + path + "has no data property");
                    }
            }

            pageHolder.Controls.Add(viewControl);
            StringWriter result = new StringWriter();
            HttpContext.Current.Server.Execute(pageHolder, result, false);
            return result.ToString();
}

This code fires all the normal events in the control, and you can load the posted form data into the via a Data property in the control.
This code was lifted from Scott Guthries blog post here.
Regards
Jesper Hauge


SSRS Report expands table width on page 4 only on PDF

Question: My report is doing this:

This only happens when I export the report to PDF.  HTML view looks just fine...
I am not sure where to even start.  The first 3 pages are perfect.  It is just page 4 that gets messed up.
Any guesses of where I should look to fix this are welcome.
Comment: Do pages 1-3 have text in the expected result column?  From what you've posted that's the only difference I can see.
Comment: @lazyDBA - Yes they do, though my image does not show it.  They have more or less what you see in the 4th page.
Comment: The parameter and values rows are all hidden on the 4th page.  So the format got messed up.  If one of those rows is shown then the formatting works....  This is smelling like a bug in SSRS.
Answer: I've seen this same thing in SSRS 2008 and it was extremely frustrating; it was definitely a weird bug of some kind and not just a page-overlap kind of thing (I turned on borders, and made sure none of the cells weren't meant to expand).
From memory, recreating the tablix from scratch made it go away. Although, around the same time I was updating to 2008 SP2 so you might want to check what revision of service pack you're on, too.


Performing logarithmic multiple regression with Excel?

Question: Is it possible to perform logarithmic regression on multiple variables with Excel? If I just have a single independent variable than it's very easy to do this using the best-fit line option (it lets me switch from linear to logarithmic). But this feature does not work for multiple variable regression and the regression feature under the Data Analysis plugin only seems to support linear multiple regression.
However, I have a table that has 3 columns containing 3 independent variables and 1 column with the corresponding dependent variable (outcome). I'm pretty sure there's a logarithmic relationship, but I'm not sure how to use Excel to get the coefficients. Thanks!
Comment: Honestly, I suggest using a dedicated statistics software, because it is too easy to make mistakes and not be able to recognize that there is a mistake. With a line-based statical software like R, at least you get warned that something is not working, and get a hint, were the mistake might be. Excel will just as likely as not produce some result anyway.
Answer: If by logarithmic regression you mean the model log(y) = m1.x1 + m2.x2 + ... + b + (Error), you can use LOGEST and GROWTH with multiple independent variables. Note that if you want the estimated coefficients m1, m2, ..., b from LOGEST, you'll have to enter the formula into multiple cells as an array. See Excel's online help for the steps required.
Alternatively, you can log-transform your dependent variable and use LINEST/TREND which does the same thing under the hood.
ObWarning: Excel isn't the best regression package in the world. See, for example, McCullough & Heiser (2008), On the accuracy of statistical procedures in Microsoft Excel 2007, Comp Stats & Data Analysis 52(10) pp.4570-4578.
Comment: +1 Good thorough answer: it provides options and useful comments.


Area of a subregion of a trapezium determined by a diagonal and an auxiliary line

Question:
ED=15, AC=24 and the height of the trapezium is 12. If point B splits AC in half, the area of quadrilateral OBCD is what?
This question was part of an exam I recieved. Can someone help me. I can't answer it.
Comment: Welcome to MSE. Please tell us what concept specifically you are finding difficult and show at least some form of attempt at a solution. :)
Comment: What is the area of triangle ABE?
Answer: The area of $OBCD$ is area of $ADC$ (which is $144$) minus that
of $OAB$. The area of $OAB$ is $6h$ where $h$ is the height of
$O$ above $AB$.
The triangles $OAB$ and $ODE$ are similar. As $|AB|=\frac45|DE|$
then $h=\frac45(12-h)$ giving $9 h=48$, that is $h=\frac{16}3$.
So $OAB$ has area $32$ and the area you seek is $112$.


What does the l equals to?

Question: I have got this limit and I have no clue how to resolve it:
$$l=\lim_{x\to 0}\frac{ \sqrt[2018]{1+x}-\sqrt[2019]{1-x}}x $$
Can  you give me any tips or even resolve it please?
Comment: I have to say, it's very disappointing the way the community has responded to this post. You reprimand the typesetting, but offer no link to the [MathJax tutorial](https://goo.gl/OWv9nr); you downvote, but don't offer a reason why. And even at that, you post multiple answers out of greed for, what, +15 rep? The OP isn't merely posting a problem and expecting us to solve it; he's **merely asking for tips**, and it's not like this is a simple limit. I shall upvote to cancel out existing downvotes.
Comment: @ncmathsadist: Probably not, or he wouldn't have posted it that way. (But I'm reasonably sure _you_ can).
Comment: can you fix the LaTeX?
Comment: could I fix the LaTeX?
Comment: Ouch... x in the denominator....it suggests...limits value is infinity..unless there is a catch...
Comment: Yes please, fix the LaTeX!
Comment: @Hagen von Eitzen After computing that should I sum them up?
Comment: There was something I could not resolve looking at the LaTeX, and I am reluctant to change the meaning of the OP's question.  That's why I put the question.  And I did not downvote what seemed to be a legit post.
Answer: Hint:
Compute $$\lim_{x\to 0}\frac{\sqrt[2018]{1+x}-\sqrt[2018]{1+0}}{x}$$
and
$$\lim_{x\to 0}\frac{\sqrt[2019]{1-x}-\sqrt[2019]{1-0}}{x}$$
Answer: Hint: If you rewrite your expression to
$$ \frac{\sqrt[2018]{1+x}-1}x - \frac{\sqrt[2019]{1-x}-1}x $$
the limit decomposes into the difference of two derivatives
Answer: If you know how to compute the derivative of $\sqrt[2018]{1+x}$ then de L'hôpital's rule gives you a straightforward answer.
Answer: use L'H,
$\;\;\;\;\lim_{x \to 0} \frac{\sqrt[2018]{1+x}-\sqrt[2018]{1-x}}{x}$
$=\lim_{x \to 0} \frac{\frac{1}{2018(1+x)^{\frac{2017}{2018}}}+\frac{1}{2018(1-x)^{\frac{2017}{2018}}}}{1}$
$=\frac{1}{2018}+\frac{1}{2018}$
$=\color{blue}{\frac{1}{1009}}$
Answer: $n:=2018$, then $n+1=2019$.
$f(x) =\dfrac{(1+x)^{1/n}-1}{x} -$
$\dfrac{(1-x)^{1/(n+1)} -1}{x}$.
1) $\lim_{x \rightarrow \infty} \dfrac{(1+x)^{1/n} -1}{x}=(1/n)$
2) $\lim_{x \rightarrow \infty} \dfrac{(1-x)^{1/(n+1)}-1}{x}=$
$-1/(n+1).$
Note : The limits are the derivatives of the resp. functions at $x=0$.
Combining:
$ \lim_{x \rightarrow 0} f(x)= 1/n+1/(n+1)$.

What does the l equals to?


Example of regular space for which exist two distinct points that can not separate by continuous function

Question: In the book "General topology" by Engelking, where is exercise to build regular topological space, for which there exist two distinct points, $a$ and $b$, for which is correct sentence: for every real valued continuous function $f(a)=f(b)$ (exercise 2.7.17. page 119).
There is also hint, that such space may build from adjoin the point for the space, which is build by A. MYSIOR, which is regular and not completely regular space. But, I still can`t prove that exercise. please. help me if you can.
Comment: Which nomenclature does Engelking use? Is a regular space a fortiori Hausdorff?
Comment: Yes, suppose regularity means that it is Hausdorff too. Same is Written in that article by Mysior: https://www.ams.org/journals/proc/1981-081-04/S0002-9939-1981-0601748-4/S0002-9939-1981-0601748-4.pdf
In first page there is built the regular (and hausdorff also) space that is not completely regular and in second page, is the remark, that if we adjoin one point (with its neighborhoodsto the space from first page, the result space will be also regular, but there will be two points, a and b, that cant separate by continuous function, which means that the result space isn`t completely Hausedorff.
Comment: But, I cant prove that :(
Answer: Take Y as in the remark of the article by A.Mysior you have linked. I will follow its notations.
As it is said in the article, Y is regular.
Now take any real valued continuous function $f$ on Y.
For $\epsilon >0$, $\exists N \in \mathbb{N} $ such that $U_N(b) \subset f^{-1}([f(b)- \epsilon , f(b) + \epsilon])$ (because since f is continuous, $f^{-1}([f(b)- \epsilon , f(b) + \epsilon])$ is a neighborhood of $b$) .
Set $J_n = f^{-1}([f(b)- \epsilon , f(b) + \epsilon]) \cap \{(x,0) \ | \ n-1\leq x \leq n \}$, since $J_{-N-1}$ is infinite, you can apply the same inductive reasoning as in the article (where it is done for $K_n$), hence $J_n$ is infinite $\forall n \in \mathbb{Z}$.
By continuity, we get $a \in f^{-1}([f(b)- \epsilon , f(b) + \epsilon])$.
Thus $f(a)=f(b)$.
I hope this can help.
Comment: Yes, exactly, we get $f(a)=f(b)$ since $\epsilon$ is arbitrary.
Comment: Thank a lot. Your last step, when you write that f(a)=f(b), is the reason of that efsilion is arbitrary, yes?


Alterar mensagem de campo obrigatório

Question: Como alterar a mensagem abaixo e permanecer com a simplicidade e coerência que preciso?

Tenho o seguinte código:

$(function() {
  var requiredCheckboxes = $('.periodicidade :checkbox[required]');
  requiredCheckboxes.change(function() {
   if (requiredCheckboxes.is(':checked')) {
    requiredCheckboxes.removeAttr('required');
   }
   else {
    requiredCheckboxes.attr('required', 'required');
   }
  });
});

<input type="checkbox" required value=1>Segunda-feira
<input type="checkbox" required value=2>Terça-feira
<input type="checkbox" required value=3>Quarta-feira
<input type="checkbox" required value=4>Quinta-feira
<input type="checkbox" required value=5>Sexta-feira
<input type="checkbox" required value=6>Sábado
<input type="checkbox" required value=7>Domingo

Observações:

Obrigatório a marcação de no mínimo 1 (um) checkbox
Utilizar setCustomValidity para a alteração da mensagem
Answer: Boa tarde senhores,

[RESOLVIDO] Segue abaixo a solução disponibilizada em outro fórum:

var requiredCheckboxes = $('.periodicidade :checkbox[required]');

requiredCheckboxes.get(0).setCustomValidity('Mark at least one checkbox');

requiredCheckboxes.change(function() {
  if (requiredCheckboxes.is(':checked')) {
  requiredCheckboxes.get(0).setCustomValidity('');
    requiredCheckboxes.removeAttr('required');
  } else {
  requiredCheckboxes.get(0).setCustomValidity('Mark at least one checkbox');
    requiredCheckboxes.attr('required', 'required');
  }
});

Alterar mensagem de campo obrigatório


Change component template name angular 2

Question: How to change the component name, depend upon the click list i need to change component template <FAQ-omni></FAQ-omni> to some other template its possible ?

        <FAQ-omni></FAQ-omni>

Locator

Offer

Contact

Holiday

FAQ

Answer: You shouldn't change the template selector as they are defined on the page, you should build a more generic template and use @Input() to pass the content in and interpolate in on the page or pass in your predefined number.

        <FAQ [faqData]="faqData"></FAQ>

Locator

Offer

Contact

Holiday

FAQ

code-behind.ts
export class CodeBehind {

    public faqData: SomeObject = {//define default};

    public Show(faqToShow: number) {

        switch(faqToShow) {

        case 1:
             this.faqData = Locator
        case 2:
        //and so on...

        }
    }
}

faq.component.ts
export class FAQ {

    @Input() public faqData: SomeObject;
}

If you do it the way above you would define the object in the parent component, however passing a number in means you could define the content within FAQ separating it from the parent, but that's up to you.
Answer: Component names are static, what you can do is pass he information to that component with something like
In your component, declare a variable
public selected: number;

In your show method, set the selected as
public show(num: number)
{
    this.selected = num;
}

and then use this selected property in your template to pass information like
<FAQ-omni selected="selected"></FAQ-omni>

In your FAQ-omni component, you can receive this variable as an input like
@Component({
    selector: 'FAQ-omni',
    templateUrl: '/template/path.html',
    inputs: ['selected']
})
export class LoginComponent
{
    public selected: number;
}

and use this selected in your template to render/hide any information you want.
You can even use this variable to display some other component based on your condition using *ngIf directive.
<FAQ-omni *ngIf="selected == 1"></FAQ-omni>
<SomeOther-Component *ngIf="selected == 2"></SomeOther-Component>


Migrating files from multiple paths with the migrate module

Question: I am trying to take a bunch of files and turn them into nodes that link to those files in my system. Now when I say a bunch I am talking about thousands, if not tens of thousands of files. So I need a way to do this which includes using multiple directories as the source. Mainly one directory with multiple sub-directories to recurse through.
So I decided to go with the migrate module. In my module setup that creates the migration script I have a schema declared for an intermediary table. This table will hold all of the path information for each file I want to import.
I then (in the install function hook) loop through the image directory recursively and gather a list of file names and paths. Then I stick the information into the intermediary table. This table is what I then import from.
The only problem is that when mapping the file fields I am unable to figure out how to get it to get the source path from each entry. It seems to want me to specify a flat path where all the files will reside and that won't work.
Is there a way to get it to get the full source path from the intermediary table?
This is using Drupal 7 and Migrate 2.2.
Here is the mapping information I am trying. The jpg_uri field is where that source path should be coming from (I just can't seem to figure out how to make that happen).
$jpg_arguments = MigrateFileFieldHandler::arguments('',
  'file_fast', FILE_EXISTS_RENAME, NULL, array('source_field' => 'jpg_name'),
  array('source_field' => 'jpg_filename'), array('source_field' => 'jpg_filename'));

$this->addFieldMapping('field_image', 'jpg_uri')
     ->arguments($jpg_arguments);

Answer: I believe you need to pass NULL as the first argument to arguments() instead of ''.
$jpg_arguments = MigrateFileFieldHandler::arguments(NULL, 'file_fast', ... etc);

Comment: I tried that and it didn't work.
Comment: It turns out that this problem was more complex than I thought. But if I put the full path in the intermediary table and used this NULL option then it works.


how to prove this density result?

Question: Assume that $b\in \mathbb{C}$ such that $0<\vert b \vert <1$. We consider the familly $f_{p}=\{1,b^{p},b^{2p},b^{3p},b^{4p},...,b^{np},...)$. How can one prove that $\operatorname{Span}(f_{p}, \ p\in \mathbb{N}^{*})$ is dense in $l^{2}(\mathbb{C})$? Thanks.
Comment: Have you tried anything?
Comment: I already tried to look at the orthogonal of the closure of Span and prove that it is null but I do not know exactly how to write it...
Answer: Assume that $x$ is orthogonal to each $f_p$. The function
$$h(z):=\sum_{k=0}^\infty x_kz^k$$
is holomorphic on the unit disk and vanishes on the non-discrete set $\{b^p,p\geqslant 1\}$. We conclude that $h$ vanishes identically hence $x=0$.

how to prove this density result?


Print  date for the monday of the current week (in bash)

Question: I want to get a date in the format 'YYYYMMdd'  (for example, today would be 20110627) format for the monday of the current week. From tomorrow through to Sunday I'd like to still print out Mondays (today's) date.  Then Next week, repeat the process
Comment: Some unixen allow `--iso-8601`, which gives you "%Y-%m-%d", which I find easier to scan manually for dates.
Comment: Thinking you'd have to do some math using Week Number of the year and $(date) formatting...
Comment: rereading this, are you asking for a range like monday-nextsunday?
Comment: Yep, basically `date +"%F"` does this nice (adding to Metthew Schinckel's comment). So, applying this to the question, if you have current date as `day=$(date +"%F")` then `date -d "$day -$(date -d $day +%u) days + 1 day" +"%F"` should always give you the Monday date (or replace `%F` with `%Y%m%d` to have the format requested).
Answer: #monday
date -dmonday +%Y%m%d

#last monday
date -dlast-monday +%Y%m%d

#next monday
date -dnext-monday +%Y%m%d

#two mondays from now
date -d'monday+14 days' +%Y%m%d

#two mondays ago
date -d'monday-14 days' +%Y%m%d

#although, if you fancy yourself an Abraham Lincolin
date -d'monday-fortnight ago' +%Y%m%d #2 weeks ago
date -d'monday+fortnight' +%Y%m%d #2 weeks from now

#Monday Next Year
date -d'52+monday' +%Y%m%d

#However, Monday Last Year
date -d'52-monday' +%Y%m%d  #DOES NOT  WORK

#you can try a day other than monday
#and format this differently.

if a range is what your after you may need to do a few things
#Tuesday to Sunday
#since today is monday, I'll use Tuesday
echo `date -dtuesday +%Y%m%d-``date -dnext-sunday +%Y%m%d`

which would output:

20110628-20110703

More on Dates
note this only works on GNU date
I have read that:

Solaris version of date, which unable
  to support -d can be resolve with
  replacing sunfreeware.com version of
  date
Comment: None of these is giving exactly what the original question asked, "monday" is the date of the nearest monday _in the future_ (if today is not monday), so that would not give the monday of the current week. This week's monday can be given by the slightly roundabout `date -d"next-monday - 1week"`
Comment: Yeah, I've found that this solution doesn't work but went with `date -d"last-sunday + 1 day"` instead.
Comment: `date -d"monday-fortnight"` gives me the same result as +.
Comment: so it does...good catch. I probably only tried one at a time. So much for my attempt to be witty. the correct solution would be `date -d'monday-fortnight ago' +%Y%m%d`
Comment: This doesn't answer the question.  Why is it accepted?
Comment: @PandaTGAttwood For a Monday this might work, but adapting this for a Sunday might fail.
Comment: Great answer! How to have the monday date, starting from year (in example 2021) and a week number (in example 22)?
Answer: For those of us without GNU dates (like us OS Xers), we may have the "-v" parameter
You can then do this:
# Most recent Monday
date -v -Mon

# Output as of this writing
Mon Jun 24 12:35:48 EDT 2013

date -v -Mon "+%Y%m%d"

# Outputs
20130624

This also seems to not be a problem if today is Monday, in my current case Thursday
# Today's date
date

# Outputs
Thu Jun 27 12:41:39 EDT 2013

# Most recent Thursday
date -v -Thu

# Outputs
Thu Jun 27 12:41:46 EDT 2013

Comment: On Max, GNU date is available from homebrew with `brew install coreutils`. After that, you can use it as 'gdate'.
Comment: Frustrating, that GNU date doesn't have -v, so this solution also can't be used only both Mac and Linux.
Comment: If you used some other logic to pass in the number of days you could use +/- days also, that might help though make more complex
`date -v'+2d' "+%Y-%m-%d"`
Or last Tues to next Sunday
`echo `date -v -Tue "+%Y-%m-%d - "``date -v +Sun "+%Y-%m-%d"``
Answer: Try this to get the current Monday's date.
wd=`date +%u`;
let wd=wd-1;
mon=`date --date="-$wd day" +%Y%m%d`;

Comment: as a one-liner: `mon=$(date -d "$(( $(date +%u) - 1 )) days ago" +%Y%m%d)`
Comment: I like. Never tried baking it that way: always thought lightning would strike me down for trying to compress all that into one line :)
Answer: I think this actually answers what was requested:
date -d "next monday - 7 days"

Answer: If you want the monday previous to a given date, like a start of week function, there's a little more to it. That's what I was looking for when I searched up this question, so I'll add my answer here.
I tried to take a "reusable tool" approach.
My monday script:
#!/bin/bash
date=${1:-now}
shift
dow=`date +%u -d "$date"`
dow0=$[ $dow - 1 ]
date -d "$date -$dow0 days" "$@"

How it works:

get date -d argument from first command line argument, e.g. "2020-01-01 -2 weeks"
additional args are passed on to the final date command, e.g. to format with +%F
get the day of week with %u (1..7); 1 is Monday
subtract 1 as we want the range 0 to 6.
show the date for the given date, minus the "day of the week" offset

A similar sunday script, which turns out to be a little simpler:
#!/bin/bash
date=${1:-now}
shift
dow=`date +%w -d "$date"`
date -d "$date -$dow days" "$@"

Usage:
# monday
Mon Aug 29 02:28:45 PM AEST 2022
# sunday now +%F
2022-08-28
# monday '2022-12-01' +%F
2022-11-28


how to modify /etc/hosts from shell scripts?

Question: I need to change some hosts entries - for example, there's a desire to update hosts to have active.vm host match the IP of currently booted VM (with some testing appliance). Guest software within VM reports machine's address back to host, and I need to update /etc/hosts based on that information - there's always some time for writing another daemon/cronjob, but wanted to use something existing for fixing hosts entries with a dumb syntax of hostname current_ip.
Someone had recommended me the bind-tools package, but - its nsupdate|host don't suit the task at all. ..
Upd: still looking for something from bind suite, but at least dynamic regeneration seems to be the best solution, and augtool is nice too.
Upd: due to my laziness, dynamic regeneration is not planned to use right now, so started using augtool at the cronjob, that reads webserver's access logs for latest IP - at the VMs which run Windows, whole monitoring solution is just a webbrowser which loads specific url from host machine and has a small reload interval
Answer: I'd rather not touch /etc/hosts in terms of parsing and such. I'd simply create a directory called /etc/hosts.d/ and make up some script that takes:

ip
name
aliases

creates one (1) file with one (1) line. The filename will be <ip>.host and then cat /etc/hosts.d/*host > /tmp/hosts.new && mv /tmp/hosts.new /etc/hosts. Maybe add an incron event that watches the /etc/hosts.d/ directory and regenerates /etc/hosts whenever something happens, that way you'll get rid of old entries too.
Comment: it's a very nice idea, with complete regeneration, sir - at least it saves from having empty hosts file
Answer: Take a look at augeas. It has a ready-made parser/serializer for the hosts file (that's even in their quick tour guide) and comes with a simple tool to make changes (augtool).
Comment: hm, it's in Gentoo portage tree, so will try it.. but somehow I feel that syntax of `augtool> set /files/etc/hosts/*[alias[1] = 'active.vm']/ipaddr 188.8.131.52` will not be tolerated by it. Will test..
Comment: it actually worked, but had to use `alias =` instead of addressing `alias[1]` or `alias[2]`.. it didn't supported them, so editing the entry by other than first name was impossible (not a problem, but will ask for a correct syntax on a list)
Comment: When you use `alias` in this expression, it matches *any* `alias` subnode, not just the firs the first one.
Comment: there's even a `brew` for it.


Convert $(-\sqrt{2},1,0)$ in to cyclidrical and spherical coordinates

Question: So for my answers I'm following the formulas given but I get stuck at finding $\theta$ because it equals $\pi + tan^{-1}(-\frac{1}{\sqrt{2}})$. Does that sound right?
Answer: Cylindrical coordinates map $(x,y)$ to $(r,\theta)$ and leave $z$ as-is.
Calculate $r$ as the length of the $x,y$ projection:  $r=\sqrt{(-\sqrt{2})^2 + 1^2} = \sqrt{3}.$  Calculate $\theta$ as $\theta = \tan^{-1}\frac{y}{x} = \tan^{-1}\frac{1}{-\sqrt{2}}.$  Since your $x$ is negative and your $y$ is positive, it will be in the second quadrant: $\theta \approx 144.7^{\circ}.$
Spherical coordinates are straightforward for this one.  Since $z=0$, $\theta=0$.  Your value of $r$ is the same, and your value of $\phi$ is the value of $\theta$ you found for the cylindrical coordinates.


Setting z-index of `$.mobile.loading`

Question: I am using jQuery's $.mobile.loading function in the following function:
 function showLoading(msg) {
    setTimeout(function(){
        $.mobile.loading( 'show', {
    text: msg,
    textVisible: true,
    theme: 'b',
    html: ""
        });
}, 1);

Sometimes the loader is in the background because a div is on top of it. How can I set the z-index to really high, or do something else to make sure it's always on top of everything?
Comment: Why not just `z-index: 9999` or something?
Comment: @Itay How can I set the `z-index` of this element. That's what I'm having trouble doing.
Answer: What about using the .ui-loader class?
Put this on your CSS file:
.ui-loader {
    z-index: 9999;
}

Answer: you can just use the .css function to change it, for example :
$("#foo").css('z-index','2000');

Reference

Setting z-index of `$.mobile.loading`


BouncyCastle with JBoss in OpenShift

Question: Is is possible to use BouncyCastle with JBoss running in OpenShift?  I have unsuccessfully tried a couple of things.
The error that I am receiving is "java.lang.SecurityException: JCE cannot authenticate the provider BC".
If BouncyCastle isn't able to be used is there another encryption provider available?
Answer: Try Security.addProvider(new BouncyCastleProvider());
Comment: same error.  I previously had Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

BouncyCastle with JBoss in OpenShift


maven can't find path specified

Question: I have some problems building my project with maven on my windows machine and I discovered that even "mvn version"  not completes correctly. It ends with "the system cannot find the path specified"
D:\my_project\nl.esi.poosl.maven>mvn -v
Apache Maven 3.2.3 (33f8c3e1027c3ddde99d3cdebad2656a31e8fdf4; 2014-08-11T22:58:10+02:00)
Maven home: C:\apache-maven-3.2.3
Java version: 1.8.0_20, vendor: Oracle Corporation
Java home: C:\Java\jdk1.8.0_20\jre
Default locale: en_US, platform encoding: Cp1252
OS name: "windows 7", version: "6.1", arch: "amd64", family: "dos"
The system cannot find the path specified.
D:\my_project\nl.esi.poosl.maven>

environment variables:
PATH:                   %JAVA_HOME%\bin;%M2%;C:\Windows\Microsoft.NET\Framework\v4.0.30319;D:\sytemapps\Python27;%M2%;%JAVA_HOME%/bin;C:\Developer\Android\sdk\platform-tools\;%GRADLE_HOME%\bin;%DEVKIT_HOME%\bin;%DEVKIT_HOME%\mingw\bin
JAVA_HOME:
C:\Java\jdk1.8.0_20
M2:
%M2_HOME%\bin
M2_HOME:
C:\apache-maven-3.2.3
I can't find the reason why "The system cannot find the path specified." is printed out because it probably is the reason why my project won't build.
Comment: Some command is executed AFTER Maven. `mvn -v` should end with the OS name. Please run `set MAVEN_BATCH_ECHO=on` followed by `mvn -v` and analyze the output.
Answer: Your %JAVA_HOME% is pointing to a JRE. A JRE usually doesn't have javac. Could this be the source of the issue?
Other than that, my environment is the same as yours and it runs fine.
What does your pom.xml look like?
Comment: Do have the samve java and java version? What is you result? for comparison. My java_home points to the jdk but mvn goes to jre
Comment: I bet its not a problem with your current setup. All of the things you listed are fine. I would check to see if the user that you are logged in as can read all of the directories. It could be an OS permissions issue.
Comment: It's not. `JAVA_HOME: C:\Java\jdk1.8.0_20`. You are confusing "Java home" with "JAVA_HOME".
Answer: %JAVA_HOME%\bin;%M2%;C:\Windows\Microsoft.NET\Framework\v4.0.30319;D:\sytemapps\Python27;%M2%;%JAVA_HOME%/bin;C:\Developer\Android\sdk\platform-tools\;%GRADLE_HOME%\bin;%DEVKIT_HOME%\bin;%DEVKIT_HOME%\mingw\bin
change to
%JAVA_HOME%\bin;%M2_HOME%;C:\Windows\Microsoft.NET\Framework\v4.0.30319;D:\sytemapps\Python27;%M2_HOME%;%JAVA_HOME%/bin;C:\Developer\Android\sdk\platform-tools\;%GRADLE_HOME%\bin;%DEVKIT_HOME%\bin;%DEVKIT_HOME%\mingw\bin
Issue might be becuase of environment variable path name. For maven environment varibale name should be M2_HOME or MAVEN_HOME(for older version)
Comment: changing it to M2_HOME would and does fail because mvn is present in the \bin folder. I tried %M2_HOME%\bin just to be sure. but same error. Current PATH: %M2_HOME%\bin;C:\Windows\Microsoft.NET\Framework\v4.0.30319;%JAVA_HOME%\bin
Answer: Details for the bounty:
Here is the output to mvn -v:
Comment: Update: This is likely a problem with windows. When I create a new local user and run `mvn -v` it works fine. Anybody already had this issue with Windows ?
Comment: I fixed the issue with this: https://superuser.com/a/727323
Answer: In my case,the problem was not with maven nor java.
I fixed it by editing values in regex by following this answer: https://superuser.com/a/727323
Quoted from the answer: "

Open the Registry Editor (press +R, type regedit and hit Enter) .
Navigate to HKEY_CURRENT_USER\Software\Microsoft\Command Processor\AutoRun and clear the values.
Also check HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\AutoRun.

"
Answer: There is a pre and post script mechanism in the mvn.bat.
The %HOME%\mavenrc_pre.bat and the %HOME%\mavenrc_post.bat files. They are executed before and after the maven executable.
It is possible that the mavenrc_post.bat file is exists in your path and it contains something what can not be found during the mvn -v.
This usually happens on corporate machines when the administrators sets something up there.
You can validate it by two ways:

Set the MAVEN_BATCH_ECHO as it was commented by Robert Scholte (set MAVEN_BATCH_ECHO=on). This will echo the batch commands so you can figure out which command causes the error message.
You can disable the pre and post rc execution by setting the MAVEN_SKIP_RC to anything (set MAVEN_SKIP_RC=true).

Note: The mvn.bat is tricky about the location of the %HOME% as it allows overrides but by default that is the %HOMEDRIVE%%HOMEPATH% value.
Comment: Hi, thank you for your answer. I fixed my issue with this: https://stackoverflow.com/a/65145769/3971619. I'll give you the bounty reputations since you don't have a lot of reputation
Comment: Thanks! I hope my answer will help someone.
Answer: As a workaround (and step forward) try with Maven Wrapper:
https://github.com/takari/maven-wrapper
mvnw.cmd clean install

Answer: If you are developing an JavaFX application using Maven, you don't have to download the JavaFX SDK. You can just specify the modules and the versions you want in the pom.xml.
<plugins>
    <plugin>
        <groupId>org.openjfx</groupId>
        <artifactId>javafx-maven-plugin</artifactId>
        <version>0.0.5</version>
        <configuration>
            <mainClass>HelloFX</mainClass>
        </configuration>
    </plugin>
</plugins>

add above plugin and the dependency into the pom file
<dependencies>
    <dependency>
        <groupId>org.openjfx</groupId>
        <artifactId>javafx-controls</artifactId>
        <version>15.0.1</version>
    </dependency>
</dependencies>

No SDK, No path setting. It works for me.
You may find further help in this open jfx documentation

maven can't find path specified


removeClass nao funciona

Question: Preciso validar dois campos em meu form para entao habilitar o botao de Submit para o usuario final, porem o removeClass('disabled') nao esta funcionando.
    $('#main-form').on(function () {
        simCode = $('#main-form [name=code]').val().length;
        carrierId = $('#main-form [name=carrierId]').val();

        if (simCode == 20 || carrierId != "null") {
           $('#save').removeClass('disabled');
        }
    });

Lembrando que simCode recebe os valores de um input type text e carrierId recebe o valor de um select option
Comment: Não seria `.removeProp`?
Comment: Ele pode ter uma classe `.disabled`.
Answer: O disabled não é uma classe, é uma propriedade.
Use:
$('#save').prop('disabled', true);

Exemplo:

function desabilita(){
  $('#save').prop('disabled', true);
}

Clique aqui para desabilitar o botão abaixo

<button type="button" id="save">Botão</button>
Answer: Você não incluiu o seu html, mas ao que tudo indica o disabled que se refere não é uma classe de estilo e sim um atributo do elemento.
$('#main-form').on(function () {
    simCode = $('#main-form [name=code]').val().length;
    carrierId = $('#main-form [name=carrierId]').val();

    if (simCode == 20 || carrierId != "null") {
       $('#save').attr('disabled', false);
    }
});

removeClass nao funciona


how to print value of a taxonomy field to headline with node.html.twig?

Question: field_test1 is a taxonomy field like fields_tags.
{{ content.field_test1 }} prints the title and the value (not in teaser - why not?).
I only want the value and want to print it in the header of the node before {{ label }}.
{{ content.field_test1.value }} or {{ node.field_test1.value }} don't work.
{{ node.field_example.value }} seems to work only for "usual" fields, but not for taxonomy fields.
How to do that?
(I've read the book of Chaz Chumley, but found no solution. I've got an answer of 4k4 in another thread, but I didn't understand. Therefore I've clarified my question here.)
Answer: That's because a taxonomy field has no values. It contains entities, which are the referenced terms. You get the first term with .entity and then you can get the values inside of the term, for example if the term would have a field_test2:
{{ node.field_test1.entity.field_test2.value }}

Or simply the term label (no .value needed for this):
{{ node.field_test1.entity.label }}

If you need translation use the |translation filter of the module Twig Tweak.
Comment: is there a possibility to do it different on front page ("yes, show it") or in a special view for that entity (no, don't show it)?
Comment: Put it in the `{% if not page %}` condition, it's already there for the node title.
Comment: Yes, I've done it:
`{% if not page %}

{{ node.field_kategorie.entity.label }}: {{ label }}

    {% endif %}`
Now the label 'll printed at front page AND also at page view too.
If I don't want it at page view, what should I do?


Como fazer uma imagem ficar "solta" dentro de uma div

Question: Preciso deixar uma imagem "solta" dentro de uma div no meu site mobile. A div tem dimensões fixas mas a imagem é muito maior, por isso, teria que ser algo semelhante ao iframe, porém, sem scroll e o usuário poderá mover a imagem livremente com os dedos.
Na verdade, é uma lista de imagens, cada uma usando a mesma class.
Exemplo:

Exemplo do efeito: (clique para ver o GIF animado)

Uma observação que pode ser importante: tive que desabilitar o "zoom" do site, por motivos de forças maiores.. nisso, o "pinch" com os dedos acredito que não funcionará, ficando somente com a movimentação básica dos dedos.
Comment: É pra ficar igual o último quadrinho? http://xkcd.com/1110/ (espero que  vocês estejam com tempo)
Comment: Por favor, publique a imagem aqui, se o tinypic sumir, a pergunta perde um pouco bastante do sentido...
Comment: @RodrigoBorth, acabo de consertar isso :)
Comment: Tem razão.. pergunta editada.
Comment: da pra fazer essa imagem para de se mexer? fiquei meio tonto lendo essa pergunta kkk
Comment: @Bacco sim, como o último quadrinho.
Answer: O que precisa é de uma funcionalidade tipo drag.
Deixo em baixo um exemplo que fiz agora para drag em touch e mouse.
Acerca da posição do touchmove:
O evento que é passado no eventhandler é diferente para eventos de mouse e de touch. Nos eventos de mouse a posição do ponteiro é obtida pelo evento.clientX e evento.clientY. No entanto no touch esse evento encontra-se em evento.touches[0].clientX e resp. evento.touches[0].clientY. Por causa disto tive de acrescentar uma função para normalizar o evento detectando se se trata de um touch ou de um mouse. Podia ter feito via e.type mas optei asssim.
(Estou a usar e.originalEvent porque o jQuery não disponibiliza a propriedade touch no evento. Disponibiliza somente na propriedade originalEvent onde ele passa uma referência ao evento original).
Portanto a função para normalizar a posição:
function normalizarEvento(e) {
    if (e.originalEvent.touches && e.originalEvent.touches.length) return e.originalEvent.touches[0];
    return e;
}

Para isso precisa de escutar alguns eventos:
Para inicar o drag:
$('img').on('mousedown touchstart', toggleDrag);

Para parar oo drag:
$('img').on('mouseup touchend mouseout', toggleDrag);

A função toggleDrag verifica se o tipo de evento é o de iniciar e dá um valor true à flag que guarda a informação se o drag está a acontecer.
Esta função guarda ainda a posição do evento em relação à posição da imagem, para poder ter essa informação na outra função quando fôr mover a imagem. Juntei uma função extra para isto tendo em conta a posiçõ relativa na página:
function buscarPosicaoRelativa(el) {
    var bodyRect = document.body.getBoundingClientRect();
    var elemRect = el.getBoundingClientRect();
    return {
        x: elemRect.left - bodyRect.left,
        y: elemRect.top - bodyRect.top
    }
}

A função drag muda a margin esquerda e topo conforme a posição do mouse.
Seria ainda possivel medir a velocidade do touch para poder mover rápidamente e com efeito de aceleração. Mas isso enquadra-se bem noutra pergunta. E parte dela já respondi aqui: Como saber a direção do scroll da roda do mouse
Exemplo: http://jsfiddle.net/3t6q1hme/
var ondrag = {};
$('.dragme').on('mouseup touchend mouseout', toggleDrag);
$('.dragme').on('mousedown touchstart', toggleDrag);
$('.dragme').on('mousemove touchmove', drag);

function normalizarEvento(e) {
    if (e.originalEvent.touches && e.originalEvent.touches.length) return e.originalEvent.touches[0];
    return e;
}

function buscarPosicaoRelativa(el) {
    var bodyRect = document.body.getBoundingClientRect();
    var elemRect = el.getBoundingClientRect();
    return {
        x: elemRect.left - bodyRect.left,
        y: elemRect.top - bodyRect.top
    }
}

function toggleDrag(evt) {
    evt.preventDefault();
    var moveTouch = normalizarEvento(evt);
    ondrag.on = evt.type == 'mousedown' || evt.type == 'touchstart';
    if (ondrag.on) ondrag.start = {
        x: moveTouch.clientX - this.getBoundingClientRect().left,
        y: moveTouch.clientY - this.getBoundingClientRect().top
    };
}

function toggleDrag(evt) {
    evt.preventDefault();
    var moveTouch = normalizarEvento(evt);
    var posicaoElemento = buscarPosicaoRelativa(this);
    ondrag.on = evt.type == 'mousedown' || evt.type == 'touchstart';
    if (ondrag.on) ondrag.start = {
        x: moveTouch.clientX - posicaoElemento.x + this.parentNode.getBoundingClientRect().left,
        y: moveTouch.clientY - posicaoElemento.y + this.parentNode.getBoundingClientRect().top
    };
}

function drag(evt) {
    evt.preventDefault();
    var moveTouch = normalizarEvento(evt);
    if (!ondrag.on) return;
    var x = moveTouch.clientX;
    var y = moveTouch.clientY;
    this.style.marginLeft = x - ondrag.start.x + 'px';
    this.style.marginTop = y - ondrag.start.y + 'px';
}

Comment: proponho `onDragon` ou `onDragão` :) Acabo de testar uma variável com acento (`ondragão`) e o fiddle aceitou (¡?)
Comment: @Ricardo juntei mais detalhes à resposta e mudei o jsFiddle para a nova versão.
Comment: @Ricardo testei no iPhone e tablet samsung e o jsFiddle funciona bem. Que plataforma estás a usar?
Comment: @Ricardo aha, sorry. Não devia fazer diferênça pois re-declarar uma função faz com que a outra seja sobrescrita, mas sim deve ser assim: http://jsfiddle.net/3t6q1hme/4/
Comment: Substitui `$('img')` por uma classe específica, e essa classe tem `position:relative`. O efeito não funcionou, tem alguma relação com esse `position`?
Comment: @brasofilo peguei um site que as classes e funções tinham acentos... é engraçado pegar trabalhos assim
Comment: Acredito que não deve ser pelo posicionamento. Não estou conseguindo fazer funcionar. Talvez por que é uma lista de imagens? Todas com uma mesma classe e quando vai "mover" uma delas, dá conflito com as demais?
Comment: @Ricardo pode editar o meu jsFiddle e colocar aqui o código com problemas?
Comment: @Sergio sim, http://jsfiddle.net/z53te9u4/9/ - Nota-se que somente a primeira que você mexe funciona, as demais "buga".
Comment: @brasofilo Sim, em JS quase tudo é válido como identificador.
Comment: @Sergio legal, agora está mais parecido com o que preciso. O único problema é que quando clico primeiro na última, ou na antepenúltima, elas somem!
Comment: @Sergio Testei agora no meu mobile e de fato as imagens estão sumindo ao serem tocadas. Algumas não somem completamente, apenas deslocam para baixo.
Comment: @Ricardo testaste com a versão que está no post? (esta: http://jsfiddle.net/3t6q1hme/) No meu iPdad funciona, posso testar iPhone mais logo.
Comment: @Sergio sério? Bem, pelos testes feitos no Chroms Desktop, dá esse bug. Uso iPhone 5C. Logo farei mais testes e retorno. Obrigado :D
Comment: @Sergio notei que tem dois `function toggleDrag(evt)` e estava dando conflito. Tirei um e funcionou! Obrigado!!


A View pode conversar diretamente com o Model?

Question: Em MVC a View serve para lidar com toda a interface do usuário, o Model serve para conter as classes que representam o sistema e suas regras de negócio e o Controller realiza a comunicação entre a View e o Model (algo como controlar o fluxo de dados), seguindo esta linha de raciocínio eu posso concluir que tanto como a View e o Model não conversam entre si.
Segue um pequeno exemplo em Java para contextualizar:
Classe ViewPessoaCadastro:
public class ViewPessoaCadastro extends JFrame {
    public ViewPessoaCadastro() {
        initComponents();
    }

    private void Salvar(ActionEvent evt) {//Clique
        //Salvar os dados.
    }

    private void Listar(ActionEvent evt) {//Clique
        //Obtem todas as pessoas cadastradas e exibi para o usuario.
    }
}

Classe ControllerPessoa:
public class ControllerPessoa {
    Pessoa pessoa;

    public ControllerPessoa(Pessoa pessoa) {
        this.pessoa = pessoa;
    }

    public void salvar() {
        pessoa.salvar();
    }

    public void alterar() {
        pessoa.alterar();
    }

    public List<Pessoa> listarTodas() {
        List<Pessoa> pessoas = pessoa.listarTodas();
        return pessoas;
    }

    public List<String> obterErrosValidacao() {
        List<String> errosValidacao = pessoa.validar();
        return errosValidacao;
    }
}

Classe Pessoa:
public class Pessoa {
    private String nome;
    private int idade;

    public Pessoa() { }

    public Pessoa(String nome, int idade) {
        this.nome = nome;
        this.idade = idade;
    }

    public void salvar() {
        //Rotina para salvar no banco de dados.
    }

    public void alterar() {
        //Rotina para registrar a alteração dos dados no banco de dados.
    }
    public List<Pessoa> listarTodas() {
        //Rotina para listar todas as pessoas salvar no banco de dados.
        ...
    }

    public List<String> validar() {
        //Rotina para validar a classe pessoa (Regras de negocio).
        ...
    }

    /*Getters e Setters*/
    public String getNome() { return nome; }

    public void setNome(String nome) { this.nome = nome; }

    public int getIdade() { return idade; }

    public void setIdade(int idade) { this.idade = idade; }
}

Dúvidas
Considerando o exemplo acima em Java me surgiu a seguinte dúvida:
Onde eu preencho os atributos da classe Pessoa, faço isso na view criando um objeto de tipo Pessoa e depois passo ele no construtor da classe ControllerPessoa ou eu crio um método na classe ControllerPessoa que contenha todos os parâmetros que representam os atributos da classe Pessoa? Considerando a questão acima existe alguma possibilidade da View conversar diretamente com o Model?
PS:Podem dar exemplos em outras linguagens também, mas de preferência poderia ser Java mesmo.
Comment: normalmente é função dos `helpers` fazer essa comunicação da view com model.
Comment: @DanielOmine os helpers são uma quarta camada?
Comment: De que tecnologia estamos falando? Sei que é em Java, mas qual o *framework* MVC?
Comment: Dener, sim, é um "presentation layer". Não confundir com "service layer".
Comment: @CiganoMorrisonMendez nenhuma tecnologia, se quiser pode citar algum framework MVC :)
Comment: @DanielOmine não sabia que havia outras camadas além das três principais.
Comment: MVC é algo mais genérico. Há diversas variações como MVVM, PM, MVP, etc. Para iniciantes, não precisa ir tão a fundo pois só vai complicar o entendimento. Você vai saber qual padrão adotar quando surgir as necessidades.
Comment: @DanielOmine o MVC pode ser usado sem esses outros padrões? Se sim, é como eu posso coletar informações da view e mandar para o model para que as informações seja persistida em algum banco de dados?
Comment: Por enquanto, esqueça esses outros padrões do comentário anterior.  Sobre a view pegar algo do banco de dados, tavez uso do GoF (padrão observer). Vide resposta do Andrew
Answer: Na definição do Gof (Gang of Four), a única comunicação permitida entre Model e View é utilizando o Design Pattern Observer.
Não há problema algum uma view "conversar" com um model desde que essa "conversa" seja em formato do padrão Observer, ou seja, a view pode apenas observar as mudanças de model para refletir isso para o usuário. Neste e somente neste caso, o controller não se envolve e o model e view podem se comunicar. Caso contrário, o controller deve ser invocado para comunicação entre view e model.
O que é comum de se utilizar para auxiliar nessa comunicação é o padrão ViewHelper que se localiza entre o controller e a view. Este padrão tem como objetivo pegar os dados da view e convertê-los em um objeto pré-formatado para ser enviado para o controller. O controller por sua vez, pode ter uma associação com model e é ele quem realiza a ação de recuperar os dados da view e persistir os dados em model.
Resumindo, não é adequado a view ter qualquer associação com model, exceto em um único caso que é quando a view observa alterações em model para refletir isso para o usuário. Para isso se utiliza o padrão Observer. Por fim, para ajudar o controller a realizar essa comunicação, utiliza-se comumente o padrão ViewHelper.
Update
Você pode interpretar essa definição e aplicar de acordo com seu entendimento. O importante é seguir os principíos do MVC Design Pattern.
Vou dar um exemplo: Imagine que você está desenvolvendo em um ambiente web, onde pode-se considerar um formulário HTML como a camada View, a Servlet que intercepta as requisições como a camada Controller e as classes de domínio como a camada Model.
Um código muito simples seria mais ou menos assim:
VIEW
<form method="post" action="cadastrar">
<input type="text" name="nome" placeholder="Nome da pessoa"/>
<input type="text" name="idade" placeholder="Idade da pessoa"/>
<input type="text" name="frase" placeholder="Frase predileta"/>
<button type="submit">Enviar</button>
</form>

Um formulário simples que irá enviar nome, idade e uma frase predileta de uma Pessoa para um mapeamento "cadastrar".
VIEWHELPER
public class PessoaViewHelper implements IViewHelper{
   public Entidade getView(HttpServletRequest request) {
      Pessoa p = new Pessoa();
      p.setNome(request.getParameter("nome");
      p.setIdade(request.getParameter("idade");
      p.setFrasePredileta(request.getParameter("frase");
      return p;
   }
}

Neste caso, classe Pessoa herda Entidade. Logo, seu ViewHelper está extraindo os dados da request vinda do browser e transformando em um objeto que seja reconhecível pelo controller.
CONTROLLER
public class MyServlet extends HttpServlet {
   IViewHelper viewHelper;
   @Override
   protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        viewHelper = new PessoaViewHelper();
        Pessoa pessoa = viewHelper.getView(req);

        //Nesse momento, seu objeto pessoa contém os dados da view extraídas pelo view helper
       //Aqui você executa sua lógica para fazer o que quiser com o model pessoa.
       //...
       resp.getWriter().write("Pessoa cadastrada...bla bla bla");
    }
}

Controller não precisa executar lógica de extração da view nem executar validações, justamente por que agora ele tem um auxiliar, que é o viewhelper.
Esse foi um exemplo muito simplificado de como funcionaria a lógica de extração de dados utilizando o viewhelper.
Espero ter ajudado.
Comment: O ViewHelper e uma quarta camada?
Comment: Você pode considerar que sim. Mas na verdade ela é uma camada auxiliar que fica situada entre a view própriamente dita e o controller. É o viewhelper que extrai os dados da view e passa para o controller formatado de uma forma que o controller possa entender e manipular o model correto.
Comment: Você pode mostrar em um pequeno exemplo como o ViewHelper extrai os dados da View e passa para o Controller?
Comment: Sim, vou fazer o exemplo aqui e editar a resposta. Só um momento.


No navigation links on 404 pages

Question: When I visit a page that does not exist, I expect to still see the primary and secondary links as on any other page, but what I get is no navigation links in the 404 page. See also No navigation links on 404 pages.
I have found a solution, but I am happy if something else can fix this (possibly without using extra modules).
Answer: You can do it by defining a page in a custom module.
Create a page for the category "Page not found" using hook_menu().
function MODULE_menu() {
  $items['page-not-found'] = array(
    'title' => '',
    'page callback' => 'MODULE_page_not_found',
    'access callback' => TRUE,
  );
  return $items;
}

function MODULE_page_not_found() {
  drupal_set_title('Page not found');
  $cust_err = "";
  $cust_err = $cust_err . "The requested page " . current_path() . " could not be found";
  return $cust_err;
}

The page callback uses current_path() to return the path of the page causing the 404 error.
Go to Admin > Config > System > Site-information, and enter page-not-found (same name as defined in hook_menu) under Default 404 (not found) page.

Now the error page appears like in the following screenshot.

It is clear that it contains all the navigation links, and also the page URL producing the error (very similar to the original page not found). And the module mentioned in the answer above by @Nikhil will output "The requested page could not be found." but does not contain the URL of the page causing the error.
Comment: @NikhilM I've tested this and and the screenshots are real ;-)
Comment: Are you sure i will get the navigation links in the page ?
Comment: I've test it right now. I customize the text shown in page not found page. but apparently it shows the default text from somewhere else! what is going on in drupal?
Comment: I was struggling with this yesterday at work, very nice solution.
Answer: There is a module to make this work 404 Navigation

On 404 Not Found error pages, Drupal will skip rendering of all the
  navigation links of your website for performance reasons*. Some of
  these include:
The "Primary links" block and any other menu links block. The Primary
  links and Secondary links of your theme.
  * Unless you have configured a "Default 404 (not found) page" on admin/config/system/site-information.

Also there is a Patch to fix this in D7.
In D8 See THIS Also THIS
Answer: There are also good module alternatives:

Search 404

Instead of showing a standard "404 Page not found", this module performs a search on the keywords in the URL, e.g. if a user goes to http://example.com/does/not/exist, this module will do a search for "does not exist" and shows the result of the search instead of the 404 page. This should help retain visitors coming in from old URLs linked from other sites or from search indices.
Fast 404

Drupal has expensive 404 errors. On an 'average' site with an 'average' module load, you can be looking at 60-100MB of memory being consumed on your server to deliver a 404. Consider a page with a bad .gif link and a missing .css file. That page will generate 2 404s along with the actual load of the page. You are most likely looking at 180MB of memory to server that page rather than the 60MB it should take.
Answer: You can do it by defining a page in a custom module.
Create a page for the category "Page not found" using hook_menu().
 function MODULE_menu() {
   $items['page-not-found'] = array(
     'title' => '',
     'page callback' => 'MODULE_page_not_found',
     'access callback' => TRUE,
   );
   return $items;
 }

 function MODULE_page_not_found() {
   drupal_set_title('Page not found');
   $cust_err = "";
   $cust_err = $cust_err . "The requested page " . current_path() . " ould not be found";
   return $cust_err;
 }

It's almost good. But this code returns:

"The requested page page-not-found could not be found"

need change current_path() to request_uri() and will return:

"The requested page /request_uri could not be found"
Comment: I changed the error message to `t('The requested page "@path" could not be found.', array('@path' => request_uri()));`. This way the default Drupal translation is used when your site is multilangual.
Comment: You are right, it's good practice =)

No navigation links on 404 pages


Calling a method based on value of variable

Question: I have 1000 methods called method0001, method0002 , ... ,method1000.
I have a variable that takes values between 1 and 1000.
If the value of the variable is x, I'd like to call methodx. For instance, if the value of the variable is 34, I'd like to call method0034. How can I code this in C# please?
Many people are asking what is need for Methodwxyz. Every method is a different type of math question.
i've done this, following the helpful comments but am getting errors (edited the question from earlier)
<code>  using System.Collections.Generic;
 using UnityEngine;
  public class TextControl : MonoBehaviour
{
public static TextControl instance;

void Start()
{
   instance = this;
}
// Update is called once per frame
void Update()
{

        this.GetType().GetMethod("Template00" + "1").Invoke(this, null);

}
public static string Templates001()
{
    // doing something here
}
 }
</code>
thanks
Comment: Use a switch statement, or a dictionary with a delegate type. However this seems a little suspicious, the first question i would ask, is why do you have 1000 methods called methodN
Comment: Yeah seems like the design for the application needs a lot of refactoring.  I think reflection would be best given this case.
Comment: Your solution to whatever problem you have seems likely to be wrong if you have 1000 methods called Method0001, MethodXXXX, Method1000. I imagine there is a much better way to achieve whatever you are trying to do. Without seeing your code or knowing what these methods do, it's difficult to advise.
Comment: Many people are asking what is need for Methodwxyz. Every method is a different type of math question that takes different types of random variables to generate these questions
Comment: As folks have mentioned, you really have two choices, a big switch statement (I'd use something like Excel to write the code and then copy/paste it into VS) or Reflection. Reflection will be slower. But, it will be faster if you create a `Dictionary`. The int will be your method number, and the MethodInfo will refer to the method you want to call. Reflect over all the methods, building the dictionary, at startup. Then, at run time, use the dictionary to pick out the right MethodInfo to `Invoke`
Comment: Looks like you misplaced your method name in the string: Templates not Template.  Also the comment from @Flydog57 is correct.  This does it at runtime which will be slower over multiple interactions.  Since Update is called once per frame in unity, you may want to create a Dictionary to search.   The performance impacts of this will be noticeable.
Comment: Another alternative would be to initialize a `Dictionary>`, again using Excel as a code generator. Probably similar in speed to a big switch statement, but perhaps a little cleaner code (since it would look as if it's table driven) _(I believe, but I'm not sure, that once a switch gets big enough, it gets compiled as if it were a dictionary)_
Answer: You could do this through reflection.  Edit for a quick sample (forgot invoke parameters).  Some tips about reflection:

If you get a nullexception that means it can't find the method
The method you are invoking needs to be public
If you use obfuscation you may not have the same names for the method

Code
<code>public class Program
{
    public static void Main(string[] args)
    {
        Check method1 = new Check(1);
        Check method2 = new Check(2);
    }
}

public class Check
{
    public Check(int x)
    {
        this.GetType().GetMethod("Method" + x).Invoke(this, null);
    }

    public void Method1()
    {
        Console.WriteLine("Method 1");
    }

    public void Method2()
    {
        Console.WriteLine("Method 2");
    }
}
</code>
Comment: ty but i get the error: "NullReferenceException: Object reference not set to an instance of an object"      can you advise? ty
Comment: This means the method you are looking to find doesn't exist.  I would post additional code showing how you are trying to call the method from what point.  More than likely, you are searching for a method in the wrong location.
Comment: added the code in the question.


Squid Proxy - Doing the exact opposite of what I want - reverse Allow/Deny

Question: I have setup this Squid config file and it seems to be doing the exact opposite of what I want. It is blocking traffic from 184.108.40.206 and 22.214.171.124. And allowing all other clients to connect on 80. Is that normal? My first time working with Squid. Note: real IPs have been slightly altered.
acl manager proto cache_object
acl localhost src 127.0.0.1/32 ::1
acl to_localhost dst 127.0.0.0/8 0.0.0.0/32 ::1

# Example rule allowing access from your local networks.
# Adapt to list your (internal) IP networks from where browsing
# should be allowed
#acl localnet src 10.0.0.0/8            # RFC1918 possible internal network
#acl localnet src 172.16.0.0/12         # RFC1918 possible internal network
#acl localnet src 192.168.0.0/16        # RFC1918 possible internal network
acl localhet src 220.127.116.11/24        # My Organization
acl localnet src 220.127.116.11/24        # My Organization
acl localnet src 22.214.171.124/24        # My Organization
acl localnet src 184.108.40.206/24        # My Organization
#acl localnet src fc00::/7               # RFC 4193 local private network range
#acl localnet src fe80::/10              # RFC 4291 link-local (directly plugged) machines

acl safe_ports port 80                  # http

acl CONNECT method CONNECT
acl allow dstdomain  .somecompany.com .anothercompany.com
acl all_others dst all
acl myclients src 188.8.131.52 22.214.171.124

# Recommended minimum Access Permission configuration:
# Only allow cachemgr access from localhost
http_access allow manager localhost
http_access deny manager

# Deny requests to certain unsafe ports
#http_access deny !safe_ports

# We strongly recommend the following be uncommented to protect innocent
# web applications running on the proxy server who think the only
# one who can access services on "localhost" is a local user
http_access deny to_localhost

# INSERT YOUR OWN RULE(S) HERE TO ALLOW ACCESS FROM YOUR CLIENTS

# Disable Caching
cache deny all
#pass accelerated domains to the peer
# Example rule allowing access from your local networks.
# Adapt localnet in the ACL section to list your (internal) IP networks
# from where browsing should be allowed
http_access allow localnet
http_access allow localhost
# And finally deny all other access to this proxy
http_access allowed
http_access deny all_others
#http_access allow whitelist
http_access allow myclients
# Squid normally listens to port 3128
http_port 80
# We recommend you to use at least the following line.
hierarchy_stoplist cgi-bin ?
# Leave coredumps in the first cache dir
coredump_dir /var/spool/squid
# Add any of your own refresh_pattern entries above these.
refresh_pattern ^ftp:           1440    20%     10080
refresh_pattern ^gopher:        1440    0%      1440
refresh_pattern -i (/cgi-bin/|\?) 0     0%      0
refresh_pattern .               0       20%     4320

Answer: The order of the http_access lines in the squid.conf matters.  You have the deny all_others applied before your allow myclients which is the ACL for 188.8.131.52.  The http_access settings are processed in order.  As soon as an ACL matches, the request will be allowed or denied, and rule processing will stop.  The myclients ACL will never be do anything useful since everything is already denied.  So you should move any ACLs you create above the comment # And finally deny....
# from where browsing should be allowed
http_access allow localnet
http_access allow localhost
#http_access allow whitelist
http_access allow myclients
# And finally deny all other access to this proxy
#http_access allowed
http_access deny all_others

Comment: Awesome. Thanks. Any thoughts on getting standard SSL to work? I want SSL to also work over 443.
Comment: Sorry, but I don't what is your problem?  Are you trying to connect to the squid box over SSL, or are you trying to access SSL web site t hrough the proxy, or what?  Anyway, if you have another question, then you should ask another question.
Comment: ok will do. It was to access those same 2 DNS name patterns over SSL on 443. But still only connect to the proxy via 80.
Comment: Ah, in that case, then your issue is related to the `safe_ports` ACL.  Right now it only allows port 80.  If you want to allow connecting to other ports, then you'll want to include them as additional entries.
Comment: If you allow port 443 does Squid know that this means https? or do you have to add another line to say that it is SSL traffic? +1
Answer: Those http_access lines are confused.
You're allowing access by localnet. then denying access to everybody, and then allowing individual clients again.
See this link on how to troubleshoot ACLs: http://wiki.squid-cache.org/SquidFaq/SquidAcl#I_set_up_my_access_controls.2C_but_they_don.27t_work.21__why.3F
Comment: also must be missing something else too - even with the fix I can get to other sites other than *.somecompany.com and *.anothercompany.com


Why do we prefer unbiased estimators instead of minimizing MSE?

Question: I was thinking about why, usually, $\hat{\sigma}^2=\hat{p}(1-\hat{p})$ is used to estimate the variance in a Bernoulli population instead of $s^2=\hat{p}(1-\hat{p})\frac{n}{n-1}$.
$s^2$ is unbiased, but in some cases would lead to strange situations.
Suppose you find $\hat{p}=0.5$. $s^2$ would be grater than $0.25$, which is obviously wrong (since $0<=\sigma^2<=0.25$).
In this situation, it would be fair to cap $s^2$ at $0.25$ to avoid results that don't make sense at all. This would also reduce the $MSE$ but would make the estimator biased again. Instead, it makes more sense to just use $\hat{\sigma}^2$.
This made me think about why unbiased estimators are usually preferred, even if they have a higher MSE.
I have 3 questions:

Is this the reason why biased $\hat{\sigma}^2$ is usually used instead of udjusted $s^2$ for Bernoulli populations? Are there any other reasons?
Why would you want to choose an esimator which is further away from the truth on average, just to make it unbiased?
Why is udjusted $s^2$ preferred over $\hat{\sigma}^2$ for other distributions, even if its $MSE$ is higher? (The estimator that minimizes MSE divides the sum of the squared residuals by $n+1$, but I've never seen it used, why?)

Moreover, $s^2$ is unbiased, but $\sqrt{s^2}$ is biased for estimating the standard deviation, so it isn't that obvious why we should be choosing it (why isn't a different adjusted estimator used
just for the standard deviation?).
I'm editing the question based on the comments I've received:
It seems like the second question is too general because in the majority of cases an unbiased estimator doesn't exists, also there isn't usually a single estimator that minimizes MSE. So, please, consider the second point I've asked only for situations where there is an unbiased estimator which isn't the best one in terms of MSE.
Comment: Answering your last question about why we don't use an unbiased estimator of standard deviation, there is no such universal estimator. $s^2$ is unbiased for variance for any distribution that has a variance. There is no such unbiased estimator for standard deviation.
Comment: ML people regularly use biased estimators (regularisation) for prediction.  IMO biased estimators are a problem for significance testing..
Comment: As @Dave pointed out, [there exist very few transforms of the parameter that allow for the existence of an unbiased estimator.](https://projecteuclid.org/journals/annals-of-mathematical-statistics/volume-40/issue-5/Unbiased-Estimation-in-Convex-Families/10.1214/aoms/1177697370.full) Thus, in many situations, there is no option but using biased estimators (such as Bayes estimators, which are almost always biased). Similarly, there are few situations where there exists a single best MSE estimator.
Comment: Why should mse be preferred? Why not mae? These questions are impossible to answer. Also, the claim that usually preferred unbiased needs support itself. I don't prefer them
Comment: In schools mse is a common measure because it's convenient mathematically for white board derivations of equations.
Comment: Thanks to all. @Aksakal that's a fair point, I was using MSE just because it's more common (I think), but we could use the same argument and ask why we use variance instead of some absolute deviation. About my claim that people prefer unbiased estimators, that's coming from my perspective of a second year student at uni so probably I don't know enough and my opinion is biased itself
Comment: @seanv507 thanks for the comment, can I ask why would you say they are a problem for testing?
Comment: From my course notes I have a quote from Sr. David Cox, "The provision of unbiased estimators is rarely interesting in its own right." but alas I can't find the source. Restricting to unbiased estimators is only useful insofar as minimizing variance proves a solution with some unique and analytic answers, they're much more complicated if we relax the unbiasedness requirement.
Answer: We do often seek the unbiased estimator with the smallest variability. But sometimes convenience (or habit) leads to use of estimators
that are not "optimal" according to some criterion.
In the case of estimating the mean $\mu$ of a normal population
where $\sigma$ is known, sample average $A= \bar X$ is used instead of the sample median $H.$ Both are unbiased: $E(A) = E(H) = \mu.$ But $Var(A) < Var(H),$ so $A$ is more widely used.
Suppose we have a sample of size $n=9$ from $\mathsf{Norm}(\mu=10,\sigma=1).$ An easy formula gives $Var(A) = 1/n = 1/9.$ There is no such easy formula for $Var(H),$ but one can show that $Var(H) > Var(A).$ One way to get a rough estimate is by
simulation:
set.seed(2021)
h = replicate(10^5, median(rnorm(9,10,1)))
mean(h);  var(h)
[1] 10.00027    # aprx E(H) = 10
[1] 0.1668142   # aprx Var(H) > 1/9

set.seed(2021)
a = replicate(10^5, mean(rnorm(9,10,1)))
mean(a);  var(a)
[1] 10.0009     # aprx E(A) = 10
[1] 0.1118979   # aprx Var(A) = 1/9

By contrast, the sample variance $S^2 = V_{n-1} =
\frac{1}{n-1}\sum_{i=1}^n (X_i - \bar X)^2$ is unbiased
with $E(S^2) = \sigma^2.$ However, even though the estimate
$V_n = \frac{1}{n}\sum_{i=1}^n (X_i - \bar X)^2$ is biased,
some still argue that it is better because its mean squared error
$MSE(V_n) = E[(V_n-\sigma^2)^2]$ is smaller than for $V_{n-1}.$
set.seed(2021)
v.8 = replicate(10^5, var(rnorm(9,10,1)))
mean(v.8);  var(v.8);  mean((v.8-1)^2)
[1] 1.001419    # aprx E(V.8) = 1
[1] 0.2528645   # aprx Var(V.8)
[1] 0.252864    # aprx MSE(V.8) = Var(V.8)

set.seed(2021)
v.9 = replicate(10^5, (8/9)*var(rnorm(9,10,1)))
mean(v.9);  var(v.9);  mean((v.9-1)^2)
[1] 0.8901506  # aprx E(V.9) < 1: too small
[1] 0.1997942
[1] 0.2118591  # aprx MSE(V.9) < MSE(V.8)

Perhaps more remarkable is that the estimator $V_{n+1} =
\frac{1}{n+1}\sum_{i=1}^n (X_i-\bar X)^2.$ has even smaller MSE.
set.seed(2021)
v.10 = replicate(10^5, (8/10)*var(rnorm(9,10,1)))
mean(v.10);  var(v.10);  mean((v.10-1)^2)
[1] 0.8011355  # more serious downward bias
[1] 0.1618333
[1] 0.2013788  # aprx MSE(V.10) < MSE(V.9) < MSE(V.8)

In practice, $V_{n+1}$ is not much used. Some statisticians feel MSE puts too much emphasis on far deviations. And many
would object to such large underestimates of $\sigma^2.$
The basic lesson is that there are frequently trade-offs to
be made in choosing an 'ideal' estimator, and it is not always
clear whether unbiasedness or small MSE is more important.
Answer: I think one historical reason $s^2$ with an $n-1$ denominator is used is the analogy to regression settings where the denominator is $n-p$, and especially to the Neyman-Scott problem.  The difference between $n$ and $n-1$ doesn't matter much but the difference between $n$ and $n-p$ may.
The Neyman-Scott problem is the extreme case of $n$ pairs of Normal observations: $Y_{ij}=\mu_i+\epsilon_{ij}$, where $\epsilon_{ij}\sim N(0,\sigma^2)$.  In this model, the MLE of $\mu_i$ is the pairwise mean $\bar Y_i$ and of $\sigma^2$ is
$$\hat\sigma^2_\textrm{MLE}=\frac{\sum_i\sum_j (Y_{ij}-\bar Y_{i})^2}{2n}$$
The MLE has expectation $\sigma^2/2$, which is Not Good.
A 'degrees of freedom' correction gives
$$\hat\sigma^2_\textrm{df}=\frac{\sum_i\sum_j (Y_{ij}-\bar Y_{i})^2}{2n-n}$$
which is unbiased, but in this case is clearly better than the MLE.
So, the actual advantage of the df-corrected estimator in various structured experimental designs lends some weight to also using the df-corrected estimator where it doesn't matter.
Comment: I would argue that the $n-1$ denominator estimator is exactly the $n-p$ estimator in a regression with just an intercept…in which case, why do we care that the $n-p$ estimator is unbiased for the variance of the error term?
Comment: Because when $p$ is of the same order as $n$, the denominator of $n$ is really bad -- it's not even a consistent estimator under some reasonable asymptotics. So it's not that the $n-p$ estimator is exactly unbiased, it's that it isn't horribly far from the truth and the $n$ estimator is.


[kubeadm]error updating cni config

Question: I am getting error message in /var/log/messages when tried to setup the cluster with the command "kubeadm init":
e4dad33)": pods "kube-scheduler-master" already exists
Jan  3 21:28:45 master kubelet: I0103 21:28:45.777830    8726 kubelet_node_status.go:204] Setting node annotation to enable volume controller attach/detach
Jan  3 21:28:46 master kubelet: I0103 21:28:46.829714    8726 kubelet_node_status.go:204] Setting node annotation to enable volume controller attach/detach
Jan  3 21:28:47 master kubelet: I0103 21:28:47.015478    8726 kubelet_node_status.go:74] Attempting to register node master
Jan  3 21:28:47 master kubelet: I0103 21:28:47.027349    8726 kubelet_node_status.go:77] Successfully registered node master
Jan  3 21:28:52 master kubelet: E0103 21:28:52.761903    8726 cni.go:163] error updating cni config: No networks found in /etc/cni/net.d
Jan  3 21:29:02 master kubelet: E0103 21:29:02.762461    8726 cni.go:163] error updating cni config: No networks found in /etc/cni/net.d

My Linux version is:
[root@master ~]# cat /etc/redhat-release
CentOS Linux release 7.3.1611 (Core)

Docker version is:
[root@master ~]# docker -v
Docker version 1.12.5, build 7392c3b

Kubernetes version:
[root@master ~]# kubeadm version
kubeadm version: version.Info{Major:"1", Minor:"6+", GitVersion:"v1.6.0-alpha.0.2074+a092d8e0f95f52", GitCommit:"a092d8e0f95f5200f7ae2cba45c75ab42da36537", GitTreeState:"clean", BuildDate:"2016-12-13T17:03:18Z", GoVersion:"go1.7.4", Compiler:"gc", Platform:"linux/amd64"}

The docker containers:
[root@master ~]# docker ps
CONTAINER ID        IMAGE                                                           COMMAND                  CREATED             STATUS              PORTS               NAMES
f9d197b32eeb        gcr.io/google_containers/kube-controller-manager-amd64:v1.5.1   "kube-controller-mana"   8 minutes ago       Up 8 minutes                            k8s_kube-controller-manager.c989015b_kube-controller-manager-master_kube-system_403e1523940e3f352d70e32c97d29be5_812fd5f5
cc196346d2fa        gcr.io/google_containers/kube-scheduler-amd64:v1.5.1            "kube-scheduler --add"   8 minutes ago       Up 8 minutes                            k8s_kube-scheduler.acb91962_kube-scheduler-master_kube-system_3bfbd36dfb8c8f71984a0d812e4dad33_7b6cc90e
5340aebc6aa4        gcr.io/google_containers/kube-apiserver-amd64:v1.5.1            "kube-apiserver --ins"   8 minutes ago       Up 8 minutes                            k8s_kube-apiserver.7fe53ba_kube-apiserver-master_kube-system_d74382f649787a7b1081e1a2b36071dd_a8b18f5f
6b56cda441d6        gcr.io/google_containers/etcd-amd64:3.0.14-kubeadm              "etcd --listen-client"   8 minutes ago       Up 8 minutes                            k8s_etcd.c323986f_etcd-master_kube-system_3a26566bb004c61cd05382212e3f978f_80669ce9
6fe1004d404d        gcr.io/google_containers/pause-amd64:3.0                        "/pause"                 8 minutes ago       Up 8 minutes                            k8s_POD.d8dbe16c_kube-controller-manager-master_kube-system_403e1523940e3f352d70e32c97d29be5_a65251b2
434d49024d1f        gcr.io/google_containers/pause-amd64:3.0                        "/pause"                 8 minutes ago       Up 8 minutes                            k8s_POD.d8dbe16c_kube-scheduler-master_kube-system_3bfbd36dfb8c8f71984a0d812e4dad33_f8d4ad55
e5da18222b52        gcr.io/google_containers/pause-amd64:3.0                        "/pause"                 8 minutes ago       Up 8 minutes                            k8s_POD.d8dbe16c_kube-apiserver-master_kube-system_d74382f649787a7b1081e1a2b36071dd_187a58df
66de3a3ad7e9        gcr.io/google_containers/pause-amd64:3.0                        "/pause"                 8 minutes ago       Up 8 minutes                            k8s_POD.d8dbe16c_etcd-master_kube-system_3a26566bb004c61cd05382212e3f978f_d58fa3b8

And the CNI was already installed:
[root@master ~]# yum list |grep kubernetes-cni.x86_64
kubernetes-cni.x86_64                      0.3.0.1-0.07a8a2            @kubernetes

Any guys face the similiar issue?
Answer: You just have to install a (3rd party) Pod Network of some kind, like stated in the guide.
Personally, I'm using Weave or Flannel. You can for example install Weave this way:
kubectl apply -f https://git.io/weave-kube

That said, there are many other Pod Network providers as well, see http://kubernetes.io/docs/admin/addons/.
Kubernetes focus is not networking per se, instead it exposes an interface for third party solutions, like Weave and Flannel.

[kubeadm]error updating cni config


mysql Erorr when use select ?

Question: i have a problem , each time i try to do select and fetch this error show
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'add' at line 1

  <?php
      mysql_connect("localhost", "root", "123") or die() ;
 mysql_select_db("boom") or die() ;
 //Retrieves data from MySQL
 $select= "select * from add" ;
 $data = mysql_query($select) or die();
 //Puts it into an array
 while($info = mysql_fetch_array( $data ))
 {

 echo "";
 }
 //Outputs the image and other data
 ?>

what is the problem here ?
Comment: http://stackoverflow.com/questions/4656487/sql-syntax-error-near-add
Answer: add is a reserved word:
http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html
Rewrite the query like so:
$select= "select * from `add`" ;

Answer: $select = "select * from `add` ;

Adding the backticks will solve your problem. ADD is a reserved word in MySQL
Answer: Ensure that 'add' is the table name (add is a reserved word), and try escaping your table name with the ` character.
Backticks are good practise to escape the table name for MySQL (Next to the 1 on your keyboard).
SELECT * FROM `add`

Comment: it worked ! , thanks :) where i can found this character on the keyboard ?
Answer: "Add" is a reserved word in MySQL.  You can either change the name of your table, or escape it out.  According to this it looks like you would need to put backticks around the table name, like add.
Comment: Backticks ` **not** single quotes

mysql Erorr when use select ?


Drupal 7 stopped working 500 internal Server error

Question: For some reasons, my site stopped responding today, Error

The www.mysite.com page isn't working
www.mysite.com is currently unable to handle this request. HTTP ERROR
  500

I understand there are many reasons for 500 error and it hard to know what exactly happend, I had a look into server log and notice this error

[Wed May 11 10:31:27 2016] [warn] [client x.y.z] mod_fcgid: stderr:
  PHP Parse error: syntax error, unexpected 'return' (T_RETURN) in
  /var/www/vhosts/mysite.com/httpdocs/pro/includes/common.inc on line
  5106.

Looking into common.inc
<code>function drupal_json_encode($var) {
  // The PHP version cannot change within a request.
  static $php530;

  if (!isset($php530)) {
    $php530 = version_compare(PHP_VERSION, '5.3.0', '>=');
  }

  if ($php530) {
    // Encode <, >, ', &, and " using the json_encode() options parameter.
    return json_encode($var, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT);
  }

  // json_encode() escapes <, >, ', &, and " using its options parameter, but
  // does not support this parameter prior to PHP 5.3.0.  Use a helper instead.
  include_once DRUPAL_ROOT . '/includes/json-encode.inc';
  return drupal_json_encode_helper($var);
}
</code>
Line 5106 =   return json_encode($var, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT);
Comment: What happens if you remove the line above temporarily (the comment)? If this just "happened", without you changing anything, it'll be a change your host has made to the web server config
Comment: try restarting apache
Comment: I think it would be more worrying if that fixed the problem @NoSssweat. If restarting apache fixes a syntax error, something's wrong elsewhere. It's probably a BOM issue in all honesty, these things usually are
Comment: Try restarting your database server
Comment: I commented the line still same problem and same complain :/. I am on shared hosting and i can't restart apache or database.

I downloaded my site into my local server and it seems to be working. There is defiantly some problem with the hosting. I contacted them and waiting for reply.
Answer: For some reason under PHP selector in Plesk dom and gd was disabled. after enabling those two the site return back to normal.


Implicit differentiation: How to calculate the ratio of the minimum size of the population to the maximum population size?

Question: I apologize for the lack of context. I was given the following information that $$\frac{dP}{dt} = kP  \cdot \cos(kt),$$ where $P(t)$ is the size of population at $t$ hours and $k$ is some constant. I would like to determine the ratio of the minimum size of the population to the maximum population size.
Using separation of variables, I eventually got to $$P(t) = Ae^{\sin(kt)},$$ where $A = e^C$ for some constant $C.$
I suppose the minimum value sin can be is $-1,$ and the maximum is $1.$ Then, the ratio is $\frac{Ae^{-1}}{Ae},$ and this is equal to  $\frac{1}{e^2}.$
Is this reasoning/logic correct?
Answer: Ultimately, you are correct, but there is something slightly deeper at play here.
Lemma. Given an everywhere differentiable function $f(x),$ the composition $g(x) = e^{f(x)}$ has a local maximum (resp. minimum) at $x = a$ if and only if $f(x)$ has a local maximum (resp. minimum) at $x = a.$
Proof. By the Chain Rule, we have that $g'(x) = e^{f(x)} f'(x).$ Considering that $e^{f(x)} > 0$ for all $x,$ we have that $g'(x) = 0$ if and only if $f'(x) = 0.$ Consequently, the critical points of $f(x)$ and $g(x)$ are the same. Even more, the sign of $g'(x)$ is the same as the sign of $f'(x),$ hence the claim holds.
Our case is $P(t) = Ae^{\sin(kt)}.$ Considering that $\sin(kt)$ is an everywhere differentiable function, in order to find the local extrema of $P(t),$ it suffices (by the lemma) to find the local extrema of $\sin(kt).$ Of course, these occur periodically when $kt = \frac{(2n + 1) \pi}{2}$ for each integer $n,$ so the maximum (resp. minimum) value of $\sin(kt)$ is $1$ (resp. $-1$). Consequently, by the lemma, the maximum value of $P(t)$ is $Ae,$ and the minimum value of $P(t)$ is $Ae^{-1}.$