why does ignoring spatial autocorrelation lead to spurious significance

Question: In spatial statistics one often hears the statements like the following:

unaccounted for spatial autocorrelation may lead to spurious significance
  / understimated uncertainty / too narrow confidence intervals

and so on.  The general idea being that ignoring spatial autocorrelation that is unexplained by your covariates is a big no-no.  I'm talking here about models in which there are parameters of fixed effects (such as known spatial covariates) on which we seek to make inference.
I am looking for a mathematical description of this principle
I have heard this principle explained by analogy to pseudo-replicates.  By ignoring pseudo-replicates we artificially increase our sample size and so our uncertainty is underestimated.  Spatial autocorrelation is like the 'continuous' version of this principle.
Obviously I'm unsatisfied with leaving it at this analogy but haven't been able to find a mathematical description of this issue anywhere.
Answer: Okay, let's zoom back from spatial, and think about time-series (1D spatial).
Suppose you are looking at the sum of a statistic over a region:
$s = \sum_{i=1}^N x_i$
Generally:
$\text{var}_{true}(s) = \sum_{i=1}^N \text{var}(x_i) + 2\sum_{i<j}\text{cov}(x_i,x_j)$
If you pretend that the $x_i$ are independent, i.e. ignore the spatial dependency, then you'll mistakenly think that:
$\text{var}_{iid}(s) = \sum_{i=1}^N \text{var}(x_i)$
Which, if the $\{x_i\}$ are postively correlated (not guaranteed, but this the most common scenario in reality) we will have:
$\text{var}_{iid}(s) \le \text{var}_{true}(s)$
Then, because you believe the variance of your statistic to be lower than it should be, you find it 'easier' to achieve significance. But, of course, such results are not accurate.
Comment: Thanks, I understand this point.  I'm probably being stupid here but struggling to relate it to understanding $\text{var}(\beta_i)$ where $\beta_i$ is a fixed effect parameter.  Say I model a gaussian response $y(t) = \beta_0 + \beta_1 x(t)$ but the 'true' model is $y(t) = \beta_0 + \beta_1 x(t) + f(t)$ where f is some smooth thing (e.g. b-spline GAM).  How does missing out $f$ affect my estimated variance for $\beta_1$ ?


remote access on slave computer

Question: We have a bunch of Linux boxes with an embedded Linux on them. The boxes are connected to the internet at client sites and the connections are usually behind a firewall or at least a NAT.
What we need is the ability to connect to the boxes via SSH or other remote terminal in order to do maintenance. But as we can not configure the networks, there is no way to reach the boxes directly from the outside internet.
The ideal solution would be to have a server where the boxes would register and an admin could pick up a connexion when needed and open a tunnel into the box.
Does such a solution exist?
Comment: Maybe I'm paranoid but this sounds pretty fishy to me. If these slave machines are there for legit reasons, the companies should be willing to adjust their network config to help you.
Comment: A botnet is just a tool, good or evil is in the hands of the tool user.
Comment: Google for reverse ssh tunnels.   See http://www.vdomck.org/2009/11/ssh-all-time.html for an example script.  On the security front, I recommend the tunnel be a highly restricted user that you then use sudo/su to escalate access.
Answer: You can port forward the SSH connection from the remote machines to the central server. You would need to assign unique ports for each remote client, and either have a permanent tunnel opened or a web service at the central server that listens to the client pings and asks to enable the port forwarding whenever an admin needs to connect to the remote box.
Answer: There is Pagekite, which is open-source software you can setup on your clients and a server to do this. They also offer a service if you do not want to run your own server.
Answer: You should take a look at saltstack. http://docs.saltstack.com/
the dependencies (python and a few libs) might be too heavy for your embedded systems though.

remote access on slave computer


Is the zero element and zero vector the same thing in the context of Linear Independence?

Question: Say..
A finite set of elements from a linear space are linearly independent if:

Their trivial linear combination is equal to the zero element
Their trivial linear combination is equal to the zero vector

I am not sure if statements 1 and 2 say the same thing.
I know that the zero element has the properties; for elements x and y of a linear space :
x + zero element = x
x + y = zero element
And I believe a zero vector would be an n tuple with only zero elements: (0,0,...,0)
Right now I believe they are the same thing in terms of properties that they have when talking about linear spaces and I think it is just different terminology.
But I also know from an example of a field with 2 elements (even and odd) that, even is the zero element in the field and it is not an n tuple with only zero elements.
As even + even = even and even + odd = odd
Comment: Other objects besides tuples of numbers can be vectors, and even if you're working with tuples of numbers, depending on the vector addition and scalar multiplication in use, the all-zero tuple might not be the "zero vector."
Comment: even * odd = odd ?
Comment: @glockm15 -- I hope you know that $x+y=0$ is not true in general! What is true is that, for all $x$, there exists some $y$ such that $x+y=0$ . In other words, opposites exist.
Comment: My point is that "for elements $x$ and $y$" is not quite correct.
Answer: Both your definitions are wrong. It should be, if the set is $\{v_1,\ldots,v_k\}$,

$$\sum_{i=1}^k \lambda_iv_k=0 \;\Rightarrow\;\text{all $\lambda_i=0$.}$$

You are correct that the zero vector in $\mathbb{R}^n$ has exactly $n$ entries that are equal to the real number $0$.
Finally, the terms zero element and zero vector are often used interchangeably in this context.
Comment: Thanks @max_zorn ,So would it be correct in this context to say that 0 is the zero element/zero vector
Answer: The most conscise definition of vector space is:

an abelian group on which a field acts

The zero vector of such a vector space is nothing else but the zero (or neutral) element of said abelian group.
Specifically, in the vector space $F^n$ of $n$-tuples of elements of the field $F$, the zero vector is also the tuple with all entries zero, $(0,0,\ldots,0)$.
Noe however, that we always also have the ground field in the context of vector spaces. The additive group of that filed of course also has a zero element, which (unless we consider the field as vector space over itself) is not referred to as zero vector.


Error when I am calling webservice with json parameter

Question: I have a web service that save ssrs report. In the parameters of the web service I got json.
The web service code:
<code>    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
     [System.Web.Script.Services.ScriptService]

    public class Save_Report : System.Web.Services.WebService
    {

        [WebMethod]
        public string HelloWorld(NameValue[] Param)
        {

            CreateEventLog();

            EventLog.WriteEntry("UWQ_ReportService", Param.ToString());

            ReportingService2010 service = new ReportingService2010();

            ReportExecutionService rs = new ReportExecutionService();

            rs.Url = "http://rshrept16/reportserver/reportexecution2005.asmx?wsdl";
            rs.Credentials = System.Net.CredentialCache.DefaultCredentials;

            string Report_Path = "/Tutorial/{0}";
            string Destination_Path = "//rshfsc3/users3/NonMekorot/o-tsoudry/Tehila/{0}.{1}";

            string New_File_Name = "myReport1";
            string File_Name = "Sales Orders";
            string Suffix_File = "PDF";
            string historyID = null;
            string[] streamIds;
            string mimeType = string.Empty;
            string encoding = string.Empty;
            string extension = string.Empty;

            reportexecution2005.Warning[] warnings;
            ExecutionHeader execHeader = new ExecutionHeader();
            ExecutionInfo execInfo = new ExecutionInfo();

            reportexecution2005.ParameterValue[] parameters = new reportexecution2005.ParameterValue[7];

            //EventLog.WriteEntry("UWQ_ReportService", string.Format("The Name parameter = {0}, the ID_l_Zones parameter = {1}", Name, ID_l_Zones));

            parameters[0] = new reportexecution2005.ParameterValue();
            parameters[0].Name = "ID_l_Date_From";
            parameters[0].Value = "01/01/2016 00:00:00";

            parameters[1] = new reportexecution2005.ParameterValue();
            parameters[1].Name = "ID_l_Date_To";
            parameters[1].Value = "01/03/2016 00:00:00";

            parameters[2] = new reportexecution2005.ParameterValue();
            parameters[2].Name = "ID_l_Zones";
            parameters[2].Value =  "82,83,84,85,86,87,88";

            parameters[3] = new reportexecution2005.ParameterValue();
            parameters[3].Name = "ID_l_Water_Source_Types";
            parameters[3].Value = null;

            parameters[4] = new reportexecution2005.ParameterValue();
            parameters[4].Name = "ID_l_Water_Types";
            parameters[4].Value = null;

            parameters[5] = new reportexecution2005.ParameterValue();
            parameters[5].Name = "ID_l_Water_Sources_Group_ID";
            parameters[5].Value = null;

            parameters[6] = new reportexecution2005.ParameterValue();
            parameters[6].Name = "ID_l_Parameters_Group_ID";
            parameters[6].Value = null;

            rs.ExecutionHeaderValue = execHeader;

            execInfo = rs.LoadReport(string.Format(Report_Path, File_Name), historyID);

            rs.SetExecutionParameters(parameters, "en-us");

            string SessionId = rs.ExecutionHeaderValue.ExecutionID;
           // Console.WriteLine("SessionID: {0}", rs.ExecutionHeaderValue.ExecutionID)

            byte[] bytes = rs.Render("PDF", null, out mimeType, out encoding, out extension, out warnings, out streamIds);

            try
            {
                System.IO.File.WriteAllBytes(string.Format(Destination_Path, New_File_Name, Suffix_File), bytes);
            }
            catch (Exception ex)
            {
                EventLog.WriteEntry("UWQ_ReportService", "Error occur in save report" + ex.Message);
            }

            return string.Format(Report_Path, File_Name);
        }

        void CreateEventLog()
        {
            try
            {
                if (!EventLog.SourceExists("UWQ_ReportService"))
                {
                    EventLog.CreateEventSource("UWQ_ReportService", "UWQ_ReportService");
                }
            }
            catch (Exception exc)
            {
                using (EventLog eventLog = new EventLog("Application"))
                {
                    eventLog.Source = "Application";
                    eventLog.WriteEntry("Can't Create source log massage:" + exc.Message, EventLogEntryType.Information, 101, 1);
                }
            }

        }
    }

    public class NameValue
    {
        public string name { get; set; }
        public string value { get; set; }
    }
}
</code>
The jquery code that call the call the web service is:
<code>$('button').click(function(){
      var data = {"Param":
                  [
                    {"name": "ID_l_Date_From"               ,"value" : "01/01/2016 00:00:00" },
                    {"name": "ID_l_Date_To"                 ,"value" : "01/03/2016 00:00:00" },
                    {"name": "ID_l_Zones"                   ,"value" : "82,83,84,85,86,87,88"},
                    {"name": "ID_l_Water_Source_Types"      ,"value" : null                  },
                    {"name": "ID_l_Water_Types"             ,"value" : null                  },
                    {"name": "ID_l_Water_Sources_Group_ID"  ,"value" : null                  },
                    {"name": "ID_l_Parameters_Group_ID"     ,"value" : null                  }
                  ]
                };

      $.ajax({
          url: "http://mekuwqtest01/Report_Service/Save_Report.asmx/HelloWorld",
          type:"POST",
          data:JSON.stringify(data),
          dataType: "json",
          ContentType  : "application/json; charset=utf-8",
          ProcessData : true,
          success: function(result){
              console.log(result)
          },
          error: function(error){
              console.log("Error ${error}")
          }
      })
  })
</code>
The web service installed on the IIS.
when I am trying to run the jquery I'm getting this error:
<code> System.IndexOutOfRangeException: Index was outside the bounds of the array.
   at System.Web.Services.Protocols.HttpServerType..ctor(Type type)
   at System.Web.Services.Protocols.HttpServerProtocol.Initialize()
   at System.Web.Services.Protocols.ServerProtocolFactory.Create(Type type, HttpContext context, HttpRequest request, HttpResponse response, Boolean& abortProcessing)
</code>
Does any one can help me with that please??
Answer: Your problem is in jquery you are creating single elemen array not multiple element array and then you are accessing in c# code as multiple element array but the way you have did in jquery it can't go further more then 0 index in c#. Because at zero index you have fetched your whole element. You need to do it like.
<code>var data = {"Param":
                  [
                    [{"name": "ID_l_Date_From"               ,"value" : "01/01/2016 00:00:00" }],
                    [{"name": "ID_l_Date_To"                 ,"value" : "01/03/2016 00:00:00" }],
                    [{"name": "ID_l_Zones"                   ,"value" : "82,83,84,85,86,87,88"}],
                    [{"name": "ID_l_Water_Source_Types"      ,"value" : null                  }],
                    [{"name": "ID_l_Water_Types"             ,"value" : null                  }],
                    [{"name": "ID_l_Water_Sources_Group_ID"  ,"value" : null                  }],
                    [{"name": "ID_l_Parameters_Group_ID"     ,"value" : null                  }]
                  ]
                };
</code>


Wilson's Theorem Question

Question: Show that $(p-1)!\equiv 2p-p^2$ with Wilson's Theorem.
Wilson's theorem states that $(p-1)!\equiv -1\pmod p$.
I tried working off of that to get $(p-1)!\equiv -1\pmod p$
$\Rightarrow (p-1)!\equiv -1+p\pmod p$
$\Rightarrow (p)!\equiv -p+p^2\pmod p$
$\Rightarrow -(p)!\equiv p-p^2\pmod p$
$\Rightarrow -(p)!\equiv 2p-p^2\pmod p$
I don't know how to get my right side back to its original state though.
Comment: In your first line, what mod are we working? It's not true that $(p-1)! \equiv 2p - p^2 \pmod p$, for instance. Secondly, to get from your second to your third line in your work, you multiply by $p$, which is the same as multiplying by $0$ here. This is why all the work below is equivalent to $0 = 0$.
Comment: The first line doesn't make sense, modulo what? The second and third equation are exactly equal, I don't understand what you are doing. Can you clarify your question?
Comment: Dont worry, you can post the original question and answer yourself. It is way better than leaving a post like this.
Answer: We assume that the condition is verified, ie, $\left(p-1\right) !\; =\; 2p-{p}^{2}$ is true.
Then, if $p>1$ is prime, we have $(p-1)! \equiv -1\bmod (p)$ for Wilson's theorem. Let there is some $k \in \mathbb{Z}$ such that
$$2p-{p}^{2} \equiv -1\bmod (p) $$
$$2p-{p}^{2}+1=kp\qquad$$
$$\frac{2p-{p}^{2}+1}{p}=k$$
$$2-p+\frac{1}{p}=k$$
but $\frac{1}{p}\, \notin \mathbb{Z}$, it's a contradic, because, the first term must be integer

Wilson's Theorem Question


Trying to use hierarchical select in exposed view filter - dont get the option

Question: I have activated the Hierarchical select taxonomy views module, but when I add an exposed filter on my taxonomy term, I dont get an option to use the hierarchical select as a widget as the documentation says I should.
Answer: Use Simple Hierachical Select module instead which works

Simple hierarchical select defines a new form widget for taxonomy
  fields to select a term by "browsing" through the vocabularies
  hierarchy.


Reply ACK DHCP issue when requesting type 81 reply

Question: On a multiple Vlan network I have two Vlans that are in my domain group.  One is funcitoning fine while the other is not.  If I place any client in the group that is not to accept BOOTP lease it works fine it is something to do with the request and reply for the WINS or NetBIOS type81 request on devices that reside on my secondary network or VLAN.  One note the WINS and DNS servers that are given as reply to the clients are on the primary vlan and not on this non working secondary.
For a client that worked the packet sequence seen on its switch port was:
Client  ->  Broadcast   DHCP Discover (I want 141.211.###.###)
12.92   ->  141.211.###.### DHCP Offer (You can have 141.211.###.###)
Client  ->  Broadcast   DHCP Request (I accept 12.92's offer)
14.27   ->  141.211.###.### DHCP Offer (You can have 141.211.###.###)
12.92   ->  141.211.###.### DHCP ACK (You've got 141.211.###.###)
Note that the client sent its Request before the second offer from 14.27 arrives.
For a client that didn't work:
Client  ->  Broadcast   DHCP Discover (I'll take anything)
12.92   ->  141.213.###.### DHCP Offer (You can have 141.213.###.###)
14.27   ->  141.213.###.### DHCP Offer (You can have 141.213.###.###)
Client  ->  Broadcast   DHCP Request (I accept 12.92's offer)
Client  ->  Broadcast   DHCP Request (I accept 12.92's offer)
Client  ->  Broadcast   DHCP Request (I accept 12.92's offer)
Client  ->  Broadcast   DHCP Request (I accept 12.92's offer)
But it never gets an ACK from 12.92.
Answer:
Do you have routes from the DNS and
WINS servers to the non-working VLAN
(VLAN2)?
Do you have your DNS server listed as authoritative for VLAN2 IP network?  I.e. is the IP range for VLAN2 listed in your Reverse Lookup Zones?
What are you using to pass the DHCP broadcasts from VLAN to the other?  Do you have a router between networks that could be interfering?
What do the logs on your client say?
What do the logs on the DHCP server say?

These are all questions that come to mind.  One should show you the answer...
Comment: Yes, routing using an external vlan with internal trunk ports on a e6509 10g interface to combine the five internal vlans to that external vlan.
Yes, and Yes
Cisco ASA5580-40 doing DHSCP relay. I think this problem may be caused by the DHCP relay on this box so I am now trying a DHCP relay server inside the network so it functions inside the interfaces ranther than outside.
Sends request gets IP then reply is lost in translation it seems the second reply to WINS drops because it is not broadcast but UDP to the IP.
DHCP server sees the ip address hand of then no reply to the WINs request.


Chi-squared or Kruskal-Wallis?

Question: If I collect data for both a control and an experiment group, what tests would I use to detect a significant difference between groups in:
1) numbers with wound healed at week 4, week 8 and week 12
2) % reduction in wound size week 4, 8 and 12
3) change in score (0-100)
4) distance can walk in 6 mins (meters)
I have said
1) anova
2) kruskal-wallis
3 and 4) repeated measures two way ANOVA, are these correct? I wont know if data is parametric or not until I collect I assume?
ANY ADVICE would be much appreciated,
very stressed final year PT student writing research proposal
Comment: Is this a question from a course or textbook? If so, please add the `[self-study]`
tag & read its [wiki](http://stats.stackexchange.com/tags/self-study/info).
Comment: no I'm proposing a clinical trial and I've very little statistics knowledge, I'm just not sure if the test I have suggested are appropriate.
Answer: It is not perfectly clear what you need, but this is what I would recommend:
1) Fisher exact test (or better log-rank test using event yes/no and time);
2) repeated measure ANOVA (plug in also wound size at baseline);
3) repeated measure ANOVA (plug in also baseline score);
4) t test or Mann-Whitney U test (if you only have this at follow-up, otherwise repeated measure ANOVA.

Chi-squared or Kruskal-Wallis?


Can a song be in both a major and minor key at the same time?

Question: I was wondering if a song's key can be declared as just being ambiguous, where you just don't know if it's in major or minor? I think this concept applies only to relative keys as parallel keys have different notes.
I was listening to a podcast in relation to this where they said it is the musical version of an ambiguous image that is open to two interpretations.
I first saw the concept in an article Tonal Pairing and the Relative-Key Paradox in the Music of Elliott Smith. Where the author describes tonal pairing as based "not on one stable sonority, but on the tension between two tonal centers" that is discussed in this article. An example they give in this article is the opening four measures of Johannes Brahms's Intermezzo, op. 119, no. 1 that cycles between the relative keys of Bm/DMaj.
Comment: To say that "a song is in a key" is a shorthand way of saying that we can *think* about it sensibly from the perspective of that key. The key isn't really a *part* of song itself.
Comment: If I understand the detail of the question, this isn't two keys _at the same time_ it's _alternating_ keys.
Comment: Isn't this the case with all songs that use a power chord structure?
Comment: I regularly compose music without a key listed - technically setting everything to C major so GarageBand doesn't adjust the frequency of any notes automatically.
Comment: The first few measures of Schubert's G major quartet alternate between G major and g minor.  I'm not sure you really can tell the key until after the opening.
Answer: A 'key' is a generalisation of the notes used in any piece. It's a guide to what will appear mostly. If a piece has two sharps in its key signature, they will most likely be F♯ and C♯. We then acknowledge that it is in the key of D major and/or B minor. Perhaps a guide for musicians.
Occasionally, that is taken further, and it could just be that it's in E Dorian, F♯ Phrygian or A Mixolydian, for example.
There are many times when the key of a particular piece changes - modulates - to its parallel key or the key of its dominant, or even subdominant. That's when the word key gets messed about. What we can't say is that a piece with those two sharps is suddenly in key Em for three or four bars in the middle somewhere.
My students are given the impression that home is a key. All journeys start from there (bit like real life!) and only when returned there more or less permanently is the journey over. We may have visited other places on the way, and stayed there temporarily (a holiday?) but generally speaking, we return to the static residence - home. Occasionally, we may decide somewhere else is a better place to be permanently, so we move house and that becomes the new home - thus a new key.
Moving to and from relative keys is commonplace - there's often a Bm section in those pieces which start in key D. Moving to parallel keys is rarer, but will still happen, quite easily as the same root note is familiar to the listener. Much was made of that a couple of centuries ago with the Tierce de Picardie - although one wouldn't call that a key change!
Thing is, the harmonies for both - relatively speaking - are the same, basically. Triads in said D (Bm) key are D maj, G maj. and A maj., and Bm, Em , F♯m. Not forgetting C♯o. All of which get used in both D major and Bm. Inextricably linked,.
The question reminds me of - 'Can you be a father and a son at the same time?'
Comment: Your reference to 'Can you be a father and a son at the same time?' reminds me of the riddle that generally goes something like this: "2 fathers & 2 sons fish up 3 fish and split them evenly between themselves without cutting any fish apart. How does that happen?" The answer is that there's a grandfather, his son, and his son's son, and this takes advantage of people generally assuming that a father and a son won't be the same person.
Comment: @Dekkadeci - that's where it came from. OP seems to be of the opinion that music can't be major and minor in the same piece, I believe.
Comment: I always used the comparison from starting at home and leaving away and coming back home. Only much later I found out that this feeling of coming home is very common spread.
Answer: What does it mean to be "in a key"?  That's really at the heart of this question.
The first question I'd ask in response is, "Why do you care?  What are you trying to determine by saying piece X is in key Y?"
Some people are looking for a simple answer, often determined by the key signature and what local key/chord progression a piece ends on.  They will just declare that to be the key and be done with it.
Other people are interested in something more nuanced.  One might ask what local key a piece is in at a particular point in time.  Some of those people might look at the local context, including accidentals, cadences, etc. and again just declare on the basis of the score that "In measure X, the piece is in key Y."  If there are some conflicting factors, they will weigh various parameters and make a determination based on a global view of the score, as if they were solving a puzzle.  This is the type of "analysis" frequently done in an introductory music theory course, where it seems like the goal is often to label a particular place with a Roman numeral in a particular key.
Of course, sometimes the ambiguity gets stronger.  Some pieces aren't even tonal at all.  But assuming you're working within the general framework of tonal harmony, we might ask as a listener, "How do I know what key I'm in at point X?"
And that's a much harder question.  It depends partly on your priorities in analysis.  Some people may just look at the local scale and declare an answer based on that.  Certainly if you're trying to determine whether you're in D major or B minor in a classical piece, the use of A-sharp as leading tone will often determine the key (i.e., B minor if A-sharp is frequently present and used as leading tone; D major if not).  Local cadences, points of rest, and emphasized harmonies might also give clues.
But that may still not be enough.  To go to the Brahms example in the question, the beginnings of pieces of music in particular may often be quite ambiguous.  Suppose you place a single pitch D, maybe in multiple octaves.  What key are you in?  D major?  B minor?  What about G major, if D is the dominant?  Or what if the notes that coalesce around D are actually B-flat and then F and A-flat, and suddenly you resolve to E-flat, which is your key?  Retrospectively, you realize that D you started on was the leading tone.
But you can't know any of these things with a single pitch D sounded.  In that sense, you might spend a few notes (or a few bars or even longer) at the beginning of a piece not actually knowing as a listener what key you're going to end up in.  Many composers actually seem to enjoy creating sort of "fake-outs" at the beginning of pieces, and this became more common in the 19th century.
In that sense, it's very easy to say that a piece can be in an ambiguous key for a while.  If you have a score-based perspective on analysis, you may look ahead and say, "Oh, obviously that D is a leading tone, which you can see four bars later."  But as a listener you don't yet have that information.
I'd compare the beginning of a piece of music to the creation of a "world."  The composer can give you clues about the rules of that world -- what it looks like, what places you can go, what places you are unlikely to go, what the rules are about how this world operates (is there gravity? which way does it pull?), etc.  These are all expectations set up not only by key, but also by instrumentation, texture, dynamics, articulations, etc.  To use an analogy, it can be like being dropped down by a video game into a new world with a slow graphics card.  In some simple cases, everything appears at once, and it's very clear what the world looks like.  In other cases, you drop in with a field of white around you -- and then gradually out there you see a splotch of green, and then there's a tree.  Later you hear a trickle of something, and a stream appears.  As the field of view fills in, you get a sense of what the landscape is.  And the you can begin (as Tim says) your journey in this musical world.
To be "in a key" as a listener in an emerging world usually means that there are signposts or pointers that designate a particular note as having greater importance or "home."  A stereotypical gesture is a leading tone resolution or a V-I cadence: if you have one of those, it's like a bright red flashing arrow pointing at a note in your world and saying, "There!  That's home!"
But then you look at a piece like the opening of the Brahms Intermezzo.  The first note is F-sharp.  (The splotch of green.)  Are we in F-sharp?  No, a few notes later we've outlined a descending B minor triad.  (A tree appears.)  Are we in B minor?  Well, the next notes might be an E minor triad, which could be iv.  But in the next bar we get an A7-D implication.  (The stream has emerged.)  We might make  a new guess: perhaps the piece opened on vi, and we just heard a circle-of-fifths sequence (vi-ii-V-I in D) that points us to D major.  But rather than a bright red arrow cadence pointing us to D major, we don't get that strong chordal bass motion of a 5-1 leap, just a hint at V7-I in D major.
And the next bar starts doing some weird stuff: F-sharp minor?  In D major, that's an unusual iii chord.  In B minor, that would be an even more unusual minor v chord (for classical harmony).  What the heck is that?  It's like our world opened with some trees and a babbling brook, and suddenly a giant jellyfish dropped out of the sky and landed with a plop in this forest landscape.  What's going on?
The only way to know is to "stay tuned" and try to make sense of the developing tonal landscape.  At this point, as a listener, if you asked me what key I'm in, I'd say, "I don't know.  Could be B minor.  Could be D major.  Definitely not clear."  In essence, ambiguous.  Key choices need not only be ambiguous between relative major and minor.  As noted above, a limited set of notes may not make clear what key you are in for a while.  The opening B minor triad by itself could be a i in B minor or a vi in D major or a ii in A minor or a iv in F-sharp minor or even something more exotic.  Only further context can determine that.  And sometimes the context can be ambiguous for quite some time, or even for an entire piece.  Brahms continues the play with listener expectations for quite some time in this particular piece, introducing various chromatic bits in the subsequent measures that twist and turn and hint at unseen destinations within the dark forest.
Some people resist this idea of ambiguity, generally because some early experience with music theory has taught them that there's supposed to be "one right answer" for an analysis.  Introductory exercises in theory often are chosen specifically because they lack ambiguity and are easy to understand (and easy to grade).  Thus, students get a false sense that a piece must be in a particular key, and a particular chord must have a particular function in a particular key.  Some people might therefore insist that this Brahms opening is NOT "ambiguous," but rather oscillating between keys or something.  Maybe.  That's one interpretation.  But if you believe in the concept of tonicization (i.e., a temporary move toward a non-tonic note, without changing key) or even just an idea of applied/secondary dominants, then one could easily analyze a lot of this piece in at least two different keys.  Which one is the "true" governing tonic?  Does one have to oscillate or move between keys?  The real listening experience of music, particularly for a piece like this Brahms Intermezzo is not always that determined.  The ground in the landscape may never seem firm and always be shifting under your feet.
So yes, in my opinion, it's very possible for segments of a piece and even an entire piece to have an ambiguous sense of key.  For other analysts who want a "one true answer" and a label to put under every chord to "solve the crossword puzzle" (as I generally think of Roman numeral "analysis"), they might want to weigh the various options and argue for a particular tonic at any given moment.  If you forced me to, I could make arguments for what Roman numeral to put under every chord in this piece and what local key you're in.  But personally, I'm often happier just to live in the shifting tonal landscapes as the stream babbles on and leaves blow, wafting wistful strains in various directions accompanying me on a journey that may or may not ultimately take me to a "home"....
Answer: Any song may begin in a major key or a minor key or in a mode such as the Dorian mode. If song starts in a major key it can modulate to a minor key.A pivot chord can also be used to change from a major key to a minor key. Some keys do not have a leading note one semi-tone below the tonic note , they have a sub-tonic note a full step below the tonic and may sound more ambiguous. The natural minor keys;for example F minor (natural form ) has a sub-tonic chord E flat = VII , not vii° triad. Many of J.S. Bach's pieces modulate through closely related keys, but they usually end with an Authentic Cadence in the Home key (where it began ). Example is Menuet in E major by J.S. Bach (from French Suite No.6 in E Major , BWV 817.)
Answer: It is possible for a song or portion thereof to be in an ambiguous key.  Consider the chorus to the song "Hotel California" by the Eagles.  The verse is rather clearly in B minor, with the chord sequence Bm F# A E G D Em F# (i V VII IV VI III iv V).  Most non-tonic chords are major, but that's actually fairly common when using minor keys, and nothing in the melody would suggest a change of key.  Once the chorus arises, however, things become ambiguous.
The first two chords of the chorus are G and D, which would work equally well in B minor (VI III) and D major (IV I), and the melody sounds like it shifts to D major.  Indeed, all but the last two notes of the chorus melody would work just fine in D major.  The third and fourth chords are a V-i cadence in Bm which establish that the song never really left that key, but if they were changed to A D they would instead establish that the song had modulated to D major.  If the ending of the chorus were then left as it was, it would be clear that the chorus had shifted from D major to B minor, but it wouldn't be clear where that would have happened.
Comment: The one that gets me is' Unforgettable'.From memory, starts in key C but ends in key G. And I can't find *where* the modulation occurs. And it all sounds right - as if it's really in key C at the start, and really in key G at the end.
Comment: @Tim: El Shaddai sounds like it starts in E minor, but somehow ends up in D major, and the Theme from Arthur has basically the same chord sequence, but ends up elsewhere.
Comment: 'Fly me to the Moon' - Am (1st chord) **or** C maj. (last chord)? And does anyone really care..?
Answer: I'd say yes, but beware: the idea of a key center is a very human element of music. In real life, there's often no empirical way to say "yep, that song's definitely in C♯ minor, not E major". While in some cases it can be black-and-white, the key of a piece can also be highly subjective and up for interpretation.
Interestingly, one consequence of this observation is that the composer and the audience may have different interpretations of the key of a piece, just as they may differ in their other interpretations of elements of the music. Personally, when I look back at some of my pieces I wrote before I had a very solid grasp on the idea of what a key actually means, I find that I now hear the music as being in an entirely different key than what my hastily-chosen key signature would tell me.
But ultimately, the key or tonal center of a piece is just a construct. It represents a state of stability or common return, and this can be interpreted many ways. Many pieces are not content to stay in one clear set of seven notes, and when they depart from diatonicism, it can be useful to conceptualise a piece as having multiple or fluid tonal centers.
This is apparent from the very idea of a modulation itself. When you change from one key to another over time, it makes sense for the listener to redefine their idea of the tonal center in their mind. If I start a pop song in C major, then pull a truck-driver-style modulation up to D♭ major, no listener will hear the second half of the song as being all relative to the previous tonal center of C. We musicians use the idea of a key center as a way to orient ourselves in an otherwise potentially confusing harmonic landscape, and the best of us can easily redefine this coordinate system on the fly.

The whole genre of the blues is often cited as an excellent example of fluid tonality in music: Elements of major and minor run parallel to each other in the blues - take a look at the common 12-bar blues format. The IV7 chord is a dominant seventh chord, but its seventh is directly contradicted by the V7 chord's third a half-step away. Now, personally, I like to think of blues as its own tonality, but it can be very useful to recognise the elements of major and minor represented in this harmonic landscape.
A lot of pop music is written in such a way as to spark debate on its key. We all know the I-V-vi-IV chord progression, but some songs seem to use the same chords but base themselves around the vi chord. Should we then redefine our coordinate system to emphasize minor? Sometimes it makes sense to do so sometimes it doesn't, but a large amount of pop music exists somewhere between those two extremes. "Viva la Vida" by Coldplay is often quoted as being in A♭ major, but also as in F minor. There have been some interesting academic arguments on this dual sense of the key center in popular music: all-around musical smart guy Adam Neely (I reference his videos a lot, actually, and he's great with theory) has a video essay on this in his discussion of "Sweet Home Alabama" and its potentially disorienting tonality where he gets into a lot of what I've already discussed.
And of course, since we're talking about keys, everyone's probably been waiting for someone to mention "Giant Steps" and "4:33". Think about what the idea of a key center is in the context of those two extreme examples. What's amazing to me is that skilled composers can use chromaticism (in this case, any departures from diatonicism) to set up a continual oscillation between two or more key centers often so subtly as to escape detection by a casual listener.
Answer: I remember that this question araised several times in the last months around a song e.g. Am F C G ... or a similar progression: Is this iv - VI - I - V? or is it i IV iii bVII???
This shows the ambiguity of the function and you can here both Do or La as tonal center. That's why they are called related keys and related chords. In German we use the term "Parallel Key" and "Parallel chord" *)  ... this also demonstrates the parallelism of the two kind of harmonic centers and its ambiguity.
*) I know the parallel key in English is what we call the Variante in German: Cm and C, Am and A etc.
A la Turca  or für Elise are just 2 other examples of famous pieces that are modulating in both "modes" (minor and major). Also many Sonatas and Symphonies begin in minor and the secondary theme (subject group) is in major (or in contrary: primary theme  major and secondary  theme minor - if it is  not modulating to  the dominant) like e.g. the 5th Symphony by Beethoven.
The point is: we define the key from the opening **) bars and the final chord - and also from the dominating passage with the longer durance in a certain key.
**) while there is to say that many songs even don't begin on the 1st degree - as Tim says in his comment Fly me to the moon: vi ii V I) there are other examples that begin with ii-V7-I (and this is like an "up beat" bars motif, but then in the first bars the melody is "cadencing" to the tonic.
Answer: Best example I can think of is Benjamin Britten's Fanfare for St Edmundsbury for three trumpets. It's not a "song" but it demonstrates the point in your question.
Each of the three trumpet parts is in a different key and time signature. Each trumpet plays a section on its own at the start, and then all three play together, still in three different keys. Such is Britten's genius that he makes this work. Clever stuff.


Erro ao solicitar a request PUT

Question: Galera, estou com um problema aqui!!!
Estou segmentando os verbos http aqui no thunder client, quando eu envio uma request de GET e de POST, funciona perfeitamente, mas quando é uma request de PUT dá o seguinte erro:
TypeError: Assignment to constant variable.
A questão é que minha variavel não é uma constante, mas uma let:
let users = [
{id: 1, nome: 'paula', idade: 23},
{id: 2, nome: 'fabio', idade: 40}
];
export {users};

users está em um outro arquivo, então eu estou usando o import e export
//arquivo principal:
import { users } from "./users.js";

Quando eu dou a request PUT ele dá o erro que mencionei, mas curiosamente se users estiver no arquivo principal, e não separado, a request PUT funciona perfeitamente.
Não sei mais o que fazer, me ajudem!!!!!!!!!!!
Comment: acho que seu erro não na parte do código acima, provavelmente é aonde está usando o put.. pode postar o trecho completo??
Answer: Os imports são read-only. Se quiseres modificar um valor de um import tens de usar uma função.
let users = [
{id: 1, nome: 'paula', idade: 23},
{id: 2, nome: 'fabio', idade: 40}
];

function setUsers(u) {
    users = u;
}

export {users, setUsers};

Erro ao solicitar a request PUT


O que é a sintaxe de objetos literais em JavaScript?

Question: Alguém pode me ajudar com esta estrutura? Não sei o que é e nem como funciona.
var variavel = {
    teste1: '1',
    teste2: '2',
    teste3: '3'
};

Comment: O que você deseja fazer? Precisa nos dar alguma parâmetro pra responder. Aparentemente está tudo ok num trecho tão curto.
Comment: Entendi, muito obrigado pela sua explicação.
Comment: Alguma das respostas resolveu o seu problema? Acha que pode aceitar uma delas? Se ainda não o fez, veja o [tour] como proceder. Você ajudaria a comunidade identificando a melhor solução para você. Pode aceitar apenas uma delas, mas pode votar em qualquer pergunta ou resposta que achar útil no site todo (se tiver pontuação suficiente).
Answer: Esta é forma de definir um objeto. Os membros do objeto está do lado esquerdo do :, os valores dos membros estão do lado direito.

var variavel = {
    'teste1':'1',
    'teste2':'2',
    'teste3':'3'
};
console.log(variavel.teste1); //acessando o membro
console.log(variavel['teste2']); //sintaxes diferentes, mas mesmo resultado
var variavel2 = { //é mais comum fazer desta forma, ainda que funcione igual
    teste1:'1',
    teste2:'2',
    teste3:'3'
};
console.log(variavel2.teste1); //sintaxes diferentes, mas mesmo resultado
console.log(variavel2['teste2']);

Note que as chaves servem para definir objetos, ou seja, pares de chaves (lado esquerdo) e valores (lado direito). Se usar colchetes, aí está definindo uma sequência de dados.

var variavel3 = ['1', '2', '3'];
console.log(variavel3[0]);

Coloquei no GitHub para referência futura.
Dependendo do uso só pode fazer com aspas duplas, é o caso do JSON, ainda que alguns interpretadores aceitem com a simples.
Comment: Entendi, muito obrigado pela sua explicação.
Answer: Isso é a criação de um objeto com as propriedades teste1, teste2 e teste3. O que tem do lado esquerdo é o identificador da propriedade, do lado direito é o valor.
É a mesma coisa que fazer o código abaixo.

var variavel = {
    teste1: '1',
    teste2: '2',
    teste3: '3'
};

console.log(variavel.teste1);
Answer: Isso é um objeto. A estrutura segue o padrão atributo e seu valor. Esse valor pode ser uma String, boolean, int, function(), outro objeto.
Segue um exemplo:
var objeto = {
    atributoUm: 'String',
    atributoDois: 10, // inteiro
    atributoTrês: true, //boolean,
    atributoQuatro: [], //array
    atributoCinco: {}, // outro objeto
    atributoSeis: function () {} //function,
    atributoSete: funcao.metodo() //método
}

para acessar qualquer atributo, basta chamar o seu objeto ponto atributo.
Exemplo:
objeto.atributoUm // acessa esse específico atributo deste objeto


Batch program - using variable as end in for loop

Question: I am trying to create a simple batch program that will execute the same application X number of times based on a for loop.
Here is what I currently have:
@echo off
set "processCount=4"
FOR %%G in (0, 1, %processCount%) DO START "VSSampleToInvokeCOM.exe" "VSSampleToInvokeCOM.exe"

This nearly works but I only ever get 3 instances of the application. I've tried multiple iterations of this same for loop without any change in the results.
Any assistance is appreciated.
Answer: FOR /L %%G in (0, 1, %processCount%) DO START "VSSampleToInvokeCOM.exe" "VSSampleToInvokeCOM.exe"

You need the /L switch to loop from start to end. Without it, FOR just sees a list of - 3 items...


Como fazer para selecionar tudo menos o top X no MYSQL

Question: Estou programando um projeto pessoal de agendamento e não sei o como implementar um SELECT em todos os tasks que não sejam o top 5 do dia.
Como faço para implementar isso no mysql?
Por exemplo, tenho um SELECT * FROM schedules aqui :

Quero selecionar todos depois do 5, mas sem depender do Schedule_id porque ele pode variar muito no uso real do programa.
Comment: Seria interessante você informar a estrutura das tabelas que você usa para chegar no top 5
Comment: Obrigado pela dica, vou editar agora para incluir ele
Answer: Achei uma pergunta similar em inglês.
Resolvi da seguinte forma seguindo o que estava escrito.
<code>SELECT * FROM Schedules WHERE Schedule_id NOT IN (
    SELECT Schedule_id FROM (
        SELECT Schedule_id FROM Schedules ORDER BY Schedule_id Limit 5
    ) AS x
)
</code>
Comment: Você pode aceitar sua própria resposta se quiser também! Mas é melhor esperar alguma outra resposta melhor antes.


Nginx proxy one port to multiple ports

Question: I have only one port opened in firewall and multiple services running. I want to redirect a request based on URI to different application. For example if I am accessing http:example.com:8443/test1 to be redirected to one application running on port 8440 and if am accessing http:example.com:8443/test1 to be redirected to the master nginx process running on port 80
My configuration file looks like this:
server {
    listen      127.0.0.1:8443;
    location  /test1{
        proxy_pass  http://127.0.0.1:8230;
    }
}
server {
    listen      127.0.0.1:8443;
    client_max_body_size 100m;
    location  /test2{
        proxy_pass  http://127.0.0.1:80; #Nginx master webserver port
    }
}

But when I am accessing localhost:8443/test2 I am receiving a 403 Forbidden but if I am the redirect port for test1 to 80 like this
server {
    listen      127.0.0.1:8443;
    location  /test1{
        proxy_pass  http://127.0.0.1:80;
    }
}

it's working.
Answer: You should only have 1 server since they are both listening on 127.0.0.1:8443. You would then have two location blocks inside that server, for example:
server {
    listen      127.0.0.1:8443;
    client_max_body_size 100m;

    location  /test1 {
        proxy_pass  http://127.0.0.1:8230;
    }

    location  /test2 {
        proxy_pass  http://127.0.0.1:80; #Nginx master webserver port
    }
}

Also, just be aware that you're proxying the traffic, rather than redirecting it.  You will probably need a lot more configuration depending on how your applications are set up, since the /test2 will most likely be passed directly into your server on port 80 too.
Update: for PHP support, you'll need to make sure that php-fpm is installed, and will need a location block in your master nginx server, similar to:
location ~ \.php$ {
    proxy_pass http://your_ip_address:8080;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
}

Comment: Thanks. The issue was generated by the fact that I am trying to configure nginx master web server as a file server and I have created a php page which was added as argument to the upload_pass  directive `upload_pass /example.php;` and the nginx server doesn't know how to handle php. Maybe I need to import a new module in nginx.
Comment: There's a helpful guide here: https://www.digitalocean.com/community/tutorials/how-to-configure-nginx-as-a-web-server-and-reverse-proxy-for-apache-on-one-ubuntu-16-04-server, I've also updated my answer with a quick example.

Nginx proxy one port to multiple ports


Difficulty finding point A using two equations

Question: I have been having difficulty answering the following question:
The figure below shows a distribution between the
origin, O, and the point B. The section from O to A is represented by
the equation
$y = x^2$, whilst the section from point A to point B is
represented by the equation $3y = −20+ 20x −2x^2$. Find the coordinates
of the point A.
Any help in terms of how to apply the correct methodology for this question and how to solve it would be greatly appreciated.
Comment: The point A satisfies both equations.
Answer: Let $ A=(x_0,y_0) $. A is the intersection point between the two curves, which means that $ y_0 = x_0^2 $ and that $ y_0 = \frac{1}{3} \big( -20 + 20x_0 - 2x_0^2 \big) $.
Let $ y_0 = y_0 $, i.e.
$$ x_0^2 = \frac{1}{3} \big( -20 + 20x - 2x^2 \big) $$
$$ 3x_0^2 = -20 + 20x_0 - 2x_0^2 $$
$$ 5x_0^2 - 20x_0 + 20 = 0 $$
$$ 5 (x_0^2 - 4x_0 + 4) = 0 $$
$$ 5(x_0-2)(x_0-2) = 0 $$
$$ x_0 = 2 $$
Plugging this into either of the two equations, you get: $ y_0 = x_0^2 = (2)^2 = 4 $. Therefore, $ A=(x_0,y_0) = (2,4). $
Comment: just check  $x_0$ it should be $2$
Comment: @Karl you're right, thanks! I've updated my answer.
Comment: Thankyou this makes lots of sense, Did not realise it was simple algebraic manipulation, it looked to me like a vectors question
Answer: Plugging $y=x^2$ in the second equation, we get after simplification
$$x^2-4x+4=0$$ which gives the coordinates of the point $A :  x=2$ and
$y=4$.


In given random varaible $ X$ ~ $Geo(p)$ what is E(X=x)?

Question: In given random varaible $ X$ ~ $Geo(p)$  what is E(X=x)?
(I know that E(X)=$\frac{1}{p})$.
Comment: There are tons of questions here asking the same thing. Have you tried searching and more importantly, what have you tried?
Comment: What do you mean by $E(X=x)$?
Comment: And WP is not an option because?
Comment: @StubbornAtom , if X ~ Geo(p) , so what is E(X | X=x) ?
Comment: "if X ~ Geo(p) , so what is E(X | X=x) ?" ?? For **every** X, E(X|X=x)=x. Sorry but it is difficult to understand what is blocking you (apart from, perhaps, having  no idea about what the symbols you are using, actually mean).
Comment: We seem to have a case of homework outsourcing here. Three questions so far, all terrible, with no personal input whatsoever. OP: Please change your modus operandi.
Comment: Answer accepted 1 minute after being posted. Did you understand anything at all from it?
Comment: @Did How can i understand how a random variable split?
Comment: "How can i understand how a random variable split?" What? Are you somewhat obliquely admitting that you understand nothing from the answer below? Why accept it, then?
Answer: If by $X=x$ you mean indicator $\Bbb{1}(X=x)$, then the answer is merely
$$\Bbb{E}(\Bbb{1}(X=x)) = \Bbb{P}(X=x)$$
For natural $x$ the last probability is $p^{x - 1}(1-p)$ or $p^x$ depending on how you define $Geo(p)$ distribution.
Comment: The question you ask in the comment differs from the one you asked in the post. It still unclear what exactly do you mean. The expectation of the indicator is just a probability and I elaborated it above. The conditional expectation you ask about is just $x$ (what is the expected value of X if we know that X equals to x? Obviously, x).
Comment: if X ~ Geo(p) , so what is E(X | X=x) ?


Why does the NCAA limit how much time coaches can spend with players?

Question: I was reading the New York Times article "A Deep U.S. Open Run Becomes a Pitch For College Tennis" which says,

One of the major disadvantages of college tennis is that the N.C.A.A. limits how much time coaches can spend with players.

What are these limits, when were these limits instituted, and what is the rationale for these limits?
Answer: [ This is obviously a somewhat cynical answer ]

what is the rationale for these limits?

Because the NCAA wishes to maintain the farce that college athletes are amateurs. If they spent unlimited time with their coaches, it would be clear that was in fact their primary occupation and it would be much harder for the NCAA to justify not paying them. By ensuring that the "student-athletes" spend more time on what are nominally learning activities than what are nominally sporting activities, the NCAA successfully protects its business model.
For tennis players, this probably wouldn't matter much as they don't bring in any significant income, but if the NCAA allowed unlimited time for tennis players, there would be no justification for not allowing it for football and basketball players as well, and that would cause problems.


How to fix the false beats of piano

Question: I have tuned my old piano several times. Now the only problem I have is that there are few keys that have false beats. I looked for solutions from YouTube. The answer I got was using CA glue on the pin. I tried it but it didn't work very well in the end. Can anyone tell me more effective method to fix this problem with false beats?
Comment: Seems like it's a piano with a wooden frame, where the pins are in wood. There is no solution - get one with an iron frame.
Comment: Aha.  That is indeed interesting and puzzling.  I forgot to say that pianos that _lack_ iron frames are very rare these days, either antiques or copies of antiques.  When was your piano made?  Is it possible that other strings are vibrating sympathetically, a fifth or an octave apart from the one you're tuning?  What is the pitch you're trying to tune, and what is the frequency of the beating you hear?
Comment: @Time Thanks for your answer. I didn't know that there exist pianos with iron frames. Thanks a lot.
Comment: @Tim even if there's an iron frame, the pins are in a wooden block.  Libertarian Monarchist Bot: what do you mean by "false beat"?
Comment: @phoog If I mute the other two strings, there's still "wa~wa~wa" beats sounds while I play a single string.
Comment: @phoog Thanks for your comments. My parents bought me the piano in early 2000. So I guess it was made in late 1990s. What do you mean by other strings vibrating sympathetically? I dont remember the pitch. There were several treble strings that have false beats, but I cannot tell the frequencies because I've never trained in piano tuning. I use my Tunelab, which doesn't tell me the frequence of the beats.
Comment: By frequency of the beats I mean how many beats you hear per second.  As the string goes "wa-wa-wa," how many "wa's" happen in a given period of time?  By sympathetic vibration I mean the vibration that you hear if you, for example, press middle C slowly and silently so the damper is not touching the strings, then strike the C below sharply and release it quickly.  The middle C strings will be left vibrating; this vibration is called "sympathetic."
Comment: If your piano was made in the 1990s, it surely has a metal frame unless it was sold as a "fortepiano."  See http://pianotuninginyork.blogspot.com/2016/10/feeling-tension-1-why-piano-has-high.html for a picture of a cast-iron frame that has been removed from the wooden case.
Comment: @phoog I tried to count the number of beats per second but I found it so difficult to do this job. I am wondering how piano technicians do this. The sound will fade away, so how should I count the number of beats within a second? I still don't know what "sympathetic" means. I don't hear anything after releasing it quickly.
Answer: False beats in a piano string are from stresses or inconsistencies in the steel of the string. You need to replace the string. Call a piano tech and have it done. You can diy but you need a micrometer to figure out what gauge wire to order and you will need to order 1/4 lb.because it's the smallest amount you can order. Then there are some basic tools that would help and you can find out how it's done from YouTube or piano tech literature. Remember: In the context of the music you are playing, you'll never notice it.
Comment: Thanks for your answer. We don't have any piano tech who is capable of doing this work in my city.
Answer: In theory, every piano string should have a false beat, though it is usually much more obvious in the treble.  If you ask 100 piano technicians what is the cause and what is the cure you will likely get 100 answers.  As stated before: "In the context of the music you are playing, you'll never notice it."  In my 50 years of tuning I have only had 2 customers actually notice false beats. My personal opinion: the less one does to bend, kink, mutilate or damage a string the better.  I find new, inexpensive pianos usually have fewer false beats than expensive older instruments that have been "fixed" by many well-meaning technicians.
Comment: Thank you for your information.

How to fix the false beats of piano


how to mock/make available different event class in my test case in gwt mvp app testing?

Question: i'm using gwtp and i'm writing some tests on my view,i have some events like ChangeEvent, clickEvent in my view so how can i obtain these objects i tried by mocking but it is not working.
the code in my view is
`@UiHandler("submit")
    void onClickSubmit(ClickEvent e) {
        doClick();
    }
<code>@UiHandler("change")
public void onChange(ChangeEvent e) {
    doChange();
}
</code>
`
Answer: Try to reverse the MVP pattern. This way you will need to test only the presenter. Remember in  MVP, the view is supposed to be "dumb". The goal is to avoid testing the view.
http://arcbees.wordpress.com/2010/09/03/reversing-the-mvp-pattern-and-using-uihandler/
Comment: yes i come accross this, and we did some presenter tests also. i just want  to know what is the purpose of GWTTestCase, actually we write all presenter testcases with out using GWTTestCase. thanks.


Child component doesn't get changed prop

Question: I have the following structure:
class Parent extends React.Component {

  componentDidMount() {
    document.addEventListener('keydown', () => {
      this.value++;
    })
  }

  this.value = 0;

  render() {
    return (<ChildComponent value={this.value} />)

ChildComponent simply renders the value:
class ChildComponent extends Component {
  render() {
    return (

            {this.props.value}

    );
  }}

I don't want to rerender Parent component on every KeyDown event, that's why I don't put a value to the state.
I want ChildComponent rerenders on every KeyDown event, but ChildComponent renders only once because it doesn't get changed value and always shows 0 although this.value is changing.
Is it possible to rerender ChildComponent while changing this.value of the ParentComponent or I should place logic into ChildComponent using setState to render correct result?
Comment: Without updating the state, you cannot trigger `render` on Parent. I see `setState` the best approach.
Answer: You should add the value to parent state. This is simply the way React works. Even if you could manually trigger a rerender on the child component, it would still be  0 as still 0 is provided props. When React detects state has changed on Parent component, it will calculate the virtual dom of all child elements, do a diff on the virtual dom vs the real dom, then selectively update the real dom with those values (only the inner text of the Child component div will actually be new). React is incredibly optimised to handle rerendering using the virtual dom, and you should not worry about performance loss of this situation.
Answer: The reason the child component didn't get called when value changes because you are overriding normal variable value but not react component state. So inorder to call child component when value changes you need to manage value property in component state of parent so whenever you modify it's value using setState, component will re render
Change
   class Parent extends React.Component {

     componentDidMount() {
         document.addEventListener('keydown', () => {
            this.value++;
         })
    }

     this.value = 0;

     render() {
          return (<ChildComponent value={this.value} />)
     }
   }

To
  class Parent extends React.Component {
      constructor(props){
           super(props);
           this.state = {
                 value: 0
           }
      }
    componentDidMount() {
        document.addEventListener('keydown', () => {
             this.setState({value: this.state.value++});
        })
    }

     render() {
          return (<ChildComponent value={this.state.value} />)
     }
   }


Context Free Grammar and some details

Question: Why this grammar shows a Context Free and Linear Language, (i.e, not context sensitive or non-context free).
<code>S -> SBA | a
BA -> AB
aA -> aaB
B -> b
</code>
Answer: This grammar itself is of course context-sensitive, so in order to show that the language is nicer than that, you'll have to figure out what the language actually is. Note that the only way to get rid of $S$ is to apply the production $S\to a$, which you can do after applying $S\to SBA$ $n$ times for any $n\ge 0$. At that point you have the string $a(BA)^n$. If $n=0$, this is the terminal string $a$. Suppose that $n>0$, so that you have $aBA(BA)^{n-1}$. If you apply $B\to b$, you will have no way to get rid of the $A$s, so the only production that can be usefully applied is $BA\to AB$; this results in the string $aAB(BA)^{n-1}$. Now you can get rid of one $A$ by applying $aA\to aaB$ to get $aaBB(BA)^{n-1}$.
If $n=1$ this is $aaBB$, and the only possible terminal derivation from here is to $aabb$. If $n>1$, it's $aaBBBA(BA)^{n-2}$, and you can apply the same reasoning as before to see that the only useful derivation is to $aaABBB(BA)^{n-2}$ and thence to $a^3B^4(BA)^{n-2}$.
If you continue the analysis in this vein, you should find that the language has a rather simple description, and once you've discovered that, you can design a linear grammar for the language.
Added: We've seen that the only real freedom in a derivation using this grammar is the number $n$ of times that we apply $S\to SBA$ before applying $S\to a$ to get rid of the initial symbol $S$. After that there is some variation in the order in which we can apply productions, but there's only possible terminal string. If $n=0$, this string is $a$. If $n=1$, it's $aabb$. If $n>1$, we get to $a^3B^4(BA)^{n-2}$; if $n=2$, this is $a^3B^4$, which generates $a^3b^4$. If $n>2$, we pull out one copy of $BA$ to get $a^3B^4BA(BA)^{n-3}$, use $BA\to AB$ repeatedly to run the first $A$ to the left through the $5$ $B$'s that precede it, and get $a^3AB^5(BA)^{n-3}$. We can now get rid of that $A$ by applying $aA\to aaB$ to get $a^4B^6(BA)^{n-3}$. If $n=3$, $5$ applications of $B\to b$ turn it into $a^4b^6$.
In general, if we have $a^kB^\ell(BA)^m$ with $m>0$, the only derivation that can reach a terminal string is
$$a^kB^\ell(BA)^m=a^kB^\ell BA(BA)^{m-1}\Rightarrow^*a^kAB^{\ell+1}(BA)^{m-1}\Rightarrow a^{k+1}B^{\ell+2}(BA)^{m-1}\;.$$
Thus, every time we get rid of one $BA$, we add an $a$ to the block of $a$'s at the beginning of the string, and we add two $B$'s between them and the $BA$'s. If we start with $a(BA)^n$, this will happen $n$ times before we get rid of all of the non-terminal symbols, and we'll end up with $a^{n+1}b^{2n}$. In other words the language generated by this grammar is $L=\{a^{n+1}b^{2n}:n\ge 0\}$.
Now recall that a linear grammar is a context-free grammar that has at most one non-terminal symbol on the righthand side of each of its productions. You should be able to design such a grammar for $L$ without too much trouble: you can do it with just one non-terminal symbol, $S$, and two productions, one of which is $S\to a$.
Comment: you means  am i right, Context Free and Linear Language?
Comment: @Davied: Yes, the language generated by that grammar is a linear language (and therefore context-free by definition), even though the grammar itself is not linear.
Comment: would you please say,  how do u know, "grammar itself is of course context-sensitive" ?
Comment: @Davied: Actually, depending on the definition that you use, it may not be one. It is, however, a [non-contracting grammar](http://en.wikipedia.org/wiki/Noncontracting_grammar), which by a standard algorithm can be converted to a context-sensitive grammar in the strict sense. Some people use the term *context-sensitive grammar* for both.
Comment: i get confused. my question is really about why this grammar is Context Free and Linear Language, but after lot's of study i didnt get it. please help me.
Comment: @Davied: I'm was actually just about to go to bed; I'll try to add a bit to my answer when I get up tomorrow.
Comment: okey, i waiting for your comments. you are very kind to learn me. thanks so much. have a nice night.
Comment: @Davied: I wrote quite a bit more; I did still leave a little bit for you to complete.

Context Free Grammar and some details


Syncronize new / modified files trought SFTP on Linux

Question: I only have a SFTP access on my NAS, on Lacie OS 3.X, (so exit rsync) and i want to backup it from a remote debian server.
The problem is that the NAS is 4TB and it can take a lot of time if i transfert all files everytimes.
Is there a simple way to do that, based on modification time and or file size in a small script or a command line ?
Comment: [`rsync`](http://linux.die.net/man/1/rsync) already does this.
Comment: Yes, but it have to be on both sides isn't it ?
Comment: No, @dawud probably didn't read/understand your whole problem. There is ftpfs, and you can rsync anything for that.
Comment: @dawud Simpe rsync is not enough, he stated very clear, he has only ftp access. And rsync can't ftp.
Comment: Oh, I see, my bad. Take a look at http://serverfault.com/questions/24622/how-to-use-rsync-over-ftp there are some alternatives cited there to use SFTP.
Comment: I saw csync, look fine but dead ? A way to install it on a recent debian ?
Comment: And i'm afraid to rsyncing a ftpfs mount, some files are very fat and i read that it retrieve the whole file to make the checksum.
Comment: I don't know that we can be of much help, you seem somewhat restricted. What type (make/model) NAS is it ?
Comment: It's a Lacie 2 Big NAS, on Lacie OS 3.x. Initial Thread here if you want : http://stackoverflow.com/questions/29346422/backup-a-lacie-2-big-nas-on-a-remote-linux-server
Comment: I succeed to install csync2, but reading the documentation, i'm not sure i can do it with that.
Answer: It seems that your NAS can be configured to perform remote backups (which appears to be what you want). This line is of interest
... It can also be a third-party NAS compatible with rsync.
In your case, the remote debian server should be considered a NAS. I expect you can configure rsyncd on it and then configure the NAS to use it as a target.
Comment: I didn't know that Rsync can be used as a daemon. It work, Thanks a lot !


Why does total differential is sum of partial derivatives?

Question: Everywhere is definition of total differential I see the sum of partial derivatives multiplied by appropriate differentials, but there is nowhere clear explanation why it is.
Comment: If a variable is dependent on a number of other variables, then the *total change* in the former  (given by the differential element of the dependent variable) must be computed by adding up the changes in all of the latter (given by the individual differential elements of the independent variables) *weighted* (by multiplication) by the respective influence of each variable (given by the partial derivatives). That's the intuitive explanation (of course not a formal rigorous one).
Comment: @Deepak worthy of being an answer
Comment: Start by proving the multi-variate chain rule.
Comment: @Deepak "must be computed by adding up the changes in all of the latter" why it must?
Comment: I don't clearly understand, when imagine 3d chart, why sum of changes in x and y axes gives the real change of z axes.
Comment: [This question](http://math.stackexchange.com/q/1876559/265466) seems like it has a lot of relevant information.
Answer: The differential of a function $f:\mathbb R^m\to\mathbb R^n$ is a linear map that is the "best" approximation to the change of $f$ near some point $\mathbf p=(p^1,\dots,p^n)$, i.e., $f(\mathbf p+\mathbf h)=f(\mathbf p)+\operatorname{d}f_{\mathbf p}[\mathbf h]+o(\|\mathbf h\|)$. Restricting ourselves to a scalar-valued function $f:\mathbb R^n\to\mathbb R$, it's fairly straightforward to show that ${\partial f\over\partial x_k}(\mathbf p)=\operatorname{d}f_{\mathbf p}[\mathbf e^k]$, where $\mathbf e^k$ is the basis vector corresponding to the $x^k$ coordinate. Since a linear map is determined by its action on the basis vectors, in this coordinate system we can write $\operatorname{d}f_{\mathbf v}$ as the row vector $\left({\partial f\over\partial x_1}(\mathbf p),\dots,{\partial f\over\partial x_n}(\mathbf p)\right)$ so that $\operatorname{d}f_{\mathbf p}[\mathbf h]$ becomes simple matrix multiplication (or, if you prefer, a dot product).
Now, the differential $dx^i$ of the affine coordinate function $x^i$ is just a function that assigns to a point $\mathbf p$ its $i$th coordinate. Using the above matrix formulation, this means that $dx^1=(1,0,\dots,0)$, $dx^2=(0,1,0,\dots,0)$, and so on. So we can write $\operatorname{d}f_{\mathbf p}$ as $${\partial f\over\partial x_1}(\mathbf p)(1,0,\dots,0)+\cdots+{\partial f\over\partial x_n}(\mathbf p)(0,0,\dots,1)$$ or $${\partial f\over\partial x_1}dx^1+\cdots+{\partial f\over\partial x_n}dx^n$$ (with the partial derivatives evaluated at $\mathbf p$).
It might help to look at this geometrically. For a scalar-valued function $f$, this linear approximation amounts to approximating the $n$-dimensional hypersurface (in $\mathbb R^{n+1}$) $y=f(\mathbf x)$ at the point $\mathbf p$ by its tangent hypersurface at that point. Just as the derivative of $f$ gives the slope of the tangent line to the curve $y=f(x)$ in the one-dimensional case $f:\mathbb R\to\mathbb R$, in the multidimensional case each partial derivative ${\partial f\over\partial x_i}$ gives the slope of the tangent hypersurface in the $x^i$ direction. The equation of the tangent hypersurface at $\mathbf p$ is thus $$y={\partial f\over\partial x_1}(x^1-p^1)+\cdots+{\partial f\over\partial x_n}(x^n-p^n)=\left({\partial f\over\partial x_1},\cdots,{\partial f\over\partial x_n}\right)(\mathbf x-\mathbf p),$$ with the partial derivatives evaluated at $\mathbf p$. Comparing this to the definition of $\operatorname{d}f_{\mathbf p}$ at the top, we again find that it can be represented as a row vector of partial derivatives, and proceed as before.
Comment: > Do you at least understand the connection between the tangent (hyper)plane and partial derivatives described in the last paragraph?

No. Can you explain simpler the answer of my question?
Comment: It is too difficult. I don't understand your answer since  f(p+h)=f(p)+dfp[h]+o(‖h‖)
Comment: @DmitryNalyvaiko Do you at least understand the connection between the tangent (hyper)plane and partial derivatives described in the last paragraph? If you get that and how the tangent hyperplane relates to the differential, the rest is just a matter of definitions and algebra.
Comment: @DmitryNalyvaiko Have a look at [this question](http://math.stackexchange.com/q/1912660/265466) and [this one](http://math.stackexchange.com/q/1876559/265466) that I referenced earlier. Beyond that, I don't think I'm going to be able to help you. It's starting to look like it'll take more space and time than I have to do so.


Message headers in Kafka (.NET)

Question: If I understand correctly, the current version of confluent-kafka-dotnet (Confluent.Kafka package, version 0.11.2) does not support publishing/reading messages with message headers. Is there a way to use message headers in .NET now? Any chances to get this functionality in the near future?
Answer: Message header support will be in the next release of librdkafka (see the related GitHub pull request for librdkafka). With that in, it will be straightforward to add this to Confluent.Kafka. I can't guarantee when this will be done, but I can say it is relatively high priority.
For .NET specifically, see this GitHub issue for confluent-kafka-dotnet.

Message headers in Kafka (.NET)


Visual Studio variable bin directory

Question: I have a few VS 2010 C# projects that are shared between several solutions. I would like these  projects to build to the directory of the solutions they are open in. How do I do this?
I considered setting up different build configurations (Debug_Xsln, debug_Ysln, Release_Xsln...) but wasn't sure if there was a better way.
Comment: It is automatic when you add a reference to the project's output.
Answer: http://msdn.microsoft.com/en-us/library/42x5kfw4(v=VS.100).aspx
You can use a postbuild event with xcopy and the macro $(SolutionName) or $(SolutionDir) to copy the compiled files into the correct folder.
Go into properties for the project, build events tab, and in Post Build event command line enter something like this:
xcopy "$(ProjectDir)bin\$(ConfigurationName)\*.*" "$(SolutionDir)$(ProjectName)\bin\$(ConfigurationName)" /i /d /y

The benefit of this method is you can copy the build output of one project to multiple locations
OR
(as Ziplin discovered)
If you only have one location you want the build output to go, you can use the macros above to set the output path, like this:
$(SolutionDir)$(ProjectName)\bin\$(ConfigurationName)

just go to the project properties on the build tab and set your macroed location as the output path
Comment: Josh, I found what I think is a cleaner way to do it. If you update you're answer, I'll give it to you because you led me the right way. - I can just set the output path to the text you gave -     $(SolutionDir)bin\$(Configuration)
Comment: One approach I have done when a group of libraries is shared among projects is to wrap them in a single solution and use xcopy to deploy them to a shared network location, then in each solution that uses them, it pulls from the shared location.  Then versioning can be controlled with subfolders, or each solution can always be automatically built with the latest version, depending on how you want to manage it.
Comment: Your answer looks much cleaner than my solution, thanks! Not so sure about your comment, however.
Comment: I updated.  I didn't know macros worked in the output path.  Very cool, but the only caveat is that it will work for only one deployment location, where as the post build event is useful if you want to deploy to multiple locations or/while retaining the default output location.
Comment: Very true. I ran into an issue where I had VS register the assembly (A) with COM, and then xcopied as you had prescribed. When I rebuilt again, another assembly that referenced A tried to unregister it, but A had already been rebuilt to Av2, so the unregister step freaked out. Using the output path seemed like a better solution in this niche instance.

Visual Studio variable bin directory


Expected value of hat game

Question: Question: At each round, draw a number 1-100 out of a hat (and replace the number after you draw). You can play as many rounds as you want, and the last number you draw is the number of dollars you win, but each round costs an extra $1. What is a fair value to charge for entering this game?
There is a solution for this here, which makes sense to me (Yuval's): fair value of a hat-drawing game
However, why is my approach wrong:
$$E = \frac12 (75) + \frac12 (E-1) \Rightarrow E = 74 $$
The first term represents the probability that I exit the game; if I get higher than 50, then I should stop playing the game (right?), in which case my EV is 75 - this is the $\frac12 (75)$. The second case is where I get less than 50, and now I will re-draw from the hat, but I lose a dollar - this is the $\frac12 (E-1)$.
Comment: As Yuval's answer points out, you can do a lot better than $50$ for the cutoff value.
Comment: @Lulu Do you know how come in Yuval's answer they outright subtract 1? Shouldn't the subtracting 1 only be conditioned on re-picking a number? (The question implies that you only get charged a dollar starting on the first re-pick)
Comment: I did not study that solution.  There's nothing wrong with your method, save that you just guessed (incorrectly) at the threshold.  Do your calculation for each possible threshold and take the optimal one.
Answer: Your approach results in a different (and sub-optimal) expectation because your choice of stopping rule is not the same as the one in the answer you cited.  For it is not at all obvious that your rule, which is to stop drawing if you obtain a number exceeding $50$, should maximize the expectation.  Why stop there?  You know that the probability to obtain such a number is $1/2$, but maybe you are better off picking a higher threshold to stop, knowing that it only costs one dollar to play again.
For example, suppose we stop when the number drawn $X$ exceeds $55$, not $50$.  Then, there are $45$ numbers that stop the game and the expectation is $$\operatorname{E}[X] = \frac{45}{100}\cdot 78 + \frac{55}{100} \cdot\operatorname{E}[X - 1],$$ which upon solving yields $$\operatorname{E}[X] = \frac{691}{9} \approx 76.77778.$$  That improves upon your expectation, and shows that there is still an additional benefit to trade off more expected draws/plays in exchange for a higher stopping threshold.  The solution you cited seeks to find that threshold by allowing it to vary, then finding when the resulting expectation calculation is maximized.

To make things more interesting and generalize the question in other ways, suppose we change the cost of playing the game.  Instead of $1$ per round, what if it costs $2$ per round?  You can see that this will also affect your choice of cutoff, decreasing it because as it becomes more expensive to play, the more conservative you must be.  I invite the reader to modify the solution cited in the link to generalize it to the case where the numbers are in some arithmetic progression, say $$\{a, a+d, a+2d, \ldots, a+(n-1)d\},$$ and the cost per play is $c$.  What if the numbers are in geometric progression, say $$\{a, ar, ar^2, \ldots, ar^{n-1}\},$$ where $a > 0$ and $r > 1$?
Comment: Thanks for clearing this up.
Comment: I'm going to try to work out the arithmetic and geometric progression ones, and will get back to you!

Expected value of hat game


In how many ways can a committee be formed such that we have at least $5$ from each gender?

Question: female $= 30$
male $= 40$
committee requirement$ = 11$
In how many ways can a committee be formed such that we have at least $5$ from each gender?
my approach:
1. $30C5 \cdot 40C5 \cdot 60C1$
2.(second approach)
  $[30C5 \cdot 40C6] + [30C6 \cdot 40C5]$
Which one is correct?  They give different answers...
Comment: Please read this [tutorial](http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) on how to typeset mathematics on this site.
Answer: The second approach is correct.  If there are at least five persons of each gender on the committee, there are only two possibilities:

five women and six men
six women and five men

There are $\binom{30}{5}\binom{40}{6}$ ways to select five of the thirty women and six of the forty men, and $\binom{30}{6}\binom{40}{5}$ ways to select six of the thirty women and five of the forty men.  Since the cases are disjoint, the total number of committees that can be formed is the sum of these.
What is wrong with the first approach?
You are counting the same committees more than once.  You are counting each committee with six women six times, once for each of the six ways you could count one of the six women as one of the other sixty people.  You are also counting each committee with six men six times for the same reason.  Notice that
$$6\binom{30}{6}\binom{40}{5} + 6\binom{30}{5}\binom{40}{6} = \binom{30}{5}\binom{40}{5}\binom{60}{1}$$


Change variables in a loop PHP

Question: I have a very simple question, my problem is that I don't have much experience with PHP. I have a component where 3 columns are repeated
. Layout wise they are exactly the same, the only thing that changes is the information. Is there any way to iterate over the column 3 times and change the variables $plan_s,$plan_m, and $plan_l?

<?php
extract($args)

?>

      <?php if (!is_front_page()): ?>

        <?= ( $plan_s['plan_info'] ); ?>

      <?php endif ?>

<?= ( $plan_s['plan_name'] ); ?>
(<?= ( $plan_s['plan_description'] ); ?>)

<?= ( $plan_s['gigas'] ); ?>GB

<?php the_field('plans_tagline', 'option'); ?>

€<?= ( $plan_s['price'] ); ?>

<?php the_field('plans_days', 'option'); ?>

          <?= __('Find out more', 'test') ?>

      <?= __('Select', 'test') ?>

      <?php if (!is_front_page()): ?>

        <?= ( $plan_m['plan_info'] ); ?>

      <?php endif ?>

<?= ( $plan_m['plan_name'] ); ?>
(<?= ( $plan_m['plan_description'] ); ?>)

<?= ( $plan_m['gigas'] ); ?>GB

<?php the_field('plans_tagline', 'option'); ?>

€<?= ( $plan_m['price'] ); ?>

<?php the_field('plans_days', 'option'); ?>

      <?= __('Select', 'test') ?>

      <?php if (!is_front_page()): ?>

        <?= ( $plan_l['plan_info'] ); ?>

      <?php endif ?>

<?= ( $plan_l['plan_name'] ); ?>
(<?= ( $plan_l['plan_description'] ); ?>)

<?= ( $plan_l['gigas'] ); ?>GB

<?php the_field('plans_tagline', 'option'); ?>

€<?= ( $plan_l['price'] ); ?>

<?php the_field('plans_days', 'option'); ?>

      <?= __('Select', 'test') ?>

I would need to change this part as well.
 <?= __('Select', 'test') ?>

by
<?= __('Select', 'test') ?>
 <?= __('Select', 'test') ?>

In the second and third iteration, how could I do it?
Answer: Yes, place the 3 arrays into another array and then loop over that array
$all3 = ['plans'=>$plan_s, 'planm'=>$plan_m, 'planl'=>$plan_l];

foreach ( $all3 as $name => $plan) {
?>

        <?php if (!is_front_page()): ?>

                <?= ( $plan['plan_info'] ); ?>

        <?php endif ?>

                    <?= ( $plan['plan_name'] ); ?>
(<?= ( $plan['plan_description'] ); ?>)

                        <?= ( $plan['gigas'] ); ?>GB

                        <?php the_field('plans_tagline', 'option'); ?>

                            €
                            <?= ( $plan['price'] ); ?>

                            <?php the_field('plans_days', 'option'); ?>

                <?= __('Find out more', 'test') ?>

<?php
    $toggle = 'toggleS';
    $model = '#ModalPlan1';

    if ( $name == 'plans' ) {
        $toggle = 'toggleS';
        $model = '#ModalPlan1';
    } else if ( $name == 'planm' ) {
        $toggle = 'toggleM';
        $model = '#ModalPlan2';
    } else {
        $toggle = 'toggleL';
        $model = '#ModalPlan3';
    }
?>
    <a href="#" id="<?= $toggle ?>" class="btn btn--primary normal" data-toggle="modal" data-target="<?= $model ?>"><?= __('Select', 'test') ?>

<?php
}
?>

Comment: Thanks! And if I wanted to change this

by

In the second and third iteration, how could I do it?
Comment: There is one idea

Change variables in a loop PHP


I need to update two table in single query

Question: I need to update two table in single query.
Please find the below query.
Update
m_student_moreinfo
INNER JOIN
  m_student
ON
  m_student_moreinfo.studentID = m_student.id
SET m_student_moreinfo.MIAStartdate=GETDATE(),m_student.status='Clinical MIA'

where
  studentID IN
(
  Select
    smi.studentID
  FROM
    dbo.m_student st
  INNER JOIN
    dbo.m_student_course sc
  on
    sc.studentID=st.id
  INNER JOIN
    dbo.m_student_classClinical  scl
  on
    scl.studentcourseID=sc.id
  INNER JOIN
    dbo.m_student_moreinfo smi
  on
    smi.studentID=st.id
  where
    scl.startDate<=GETDATE() and scl.endDate >=GETDATE()
      and MIAStartdate IS NULL
)

I am getting Incorrect syntax near Inner.
Comment: You can not update two tables in a single query. You will have to do it in two update statements.
Comment: that error is from the inner join next to the update. It is not possible to update 2 tables in one statement.
Answer: You can't update two tables at once, but you can link an update into an insert using OUTPUT INTO, and you can use this output as a join for the second update
please see this and that for more info
So basically  you can wrap this in transaction and commit after all update steps finished.
Answer: Simple answer: You can not.
What you can do is two update queries in a transaction:
BEGIN TRANSACTION;
update query 1
update query 2
COMMIT;

That wil do the job for you
Comment: why not ? what is your constraint ?
Comment: Take a look at this thread: [Update a table using join in SQL Server](http://stackoverflow.com/questions/1604091/update-a-table-using-join-in-sql-server).  It might put some light on your problem of using a JOIN in an update query.


Orphan not removed

Question: In Symfony 2.3, a Member entity is not deleted as expected. The data show that the Member record remains with household_id null. Something obvious eluding me?
Household entity includes
/**
 * @var \Doctrine\Common\Collections\Collection
 *
 * @ORM\OneToMany(targetEntity="Member", mappedBy="household", cascade={"persist", "remove"}, orphanRemoval=true)
 * @ORM\OrderBy({"dob" = "ASC"})
 * @Assert\Valid
 */
protected $members;

/**
 * Remove members
 *
 * @param \Mana\ClientBundle\Entity\Member $members
 */
public function removeMember(Member $member) {
    $this->members->removeElement($member);
    $member->setHousehold(null);
}

Comment: ok I suppose you remove the entity with $em->remove($entity)
try to add fetch="EAGER" to the column definition and check the mapping with octrine:schema:validate command.
And remove $member->setHousehold(null); from removeMember(), you don't need it
Comment: There may be contexts in which the orphanremoval is not locked for example in preupdate event listener, how the entity is removed?
An alternative can be to set the cascade at the database level with onDelete="CASCADE" in joincolumn definition.
Comment: @KernelFolla: Cascading at the db level is not available - the table is MyISAM to enable a FULLTEXT search.  The application has no added event listeners.
Comment: @ KernelFolla: Please provide the above as an answer so I can accept it! It took `fetch="EAGER"` to remove the orphan. `$member->setHousehold(null);` was indeed superfluous.
Comment: @KernelFolla: Resend of comment, this time without the intrusive space. Please provide the above as an answer so I can accept it! It took `fetch="EAGER"` to remove the orphan. `$member->setHousehold(null);` was indeed superfluous.
Answer: It seems like the handler for orphanremoval does not work if the collection is not initialized.
I'm not sure it's an issue of doctrine but you can workaround the problem adding fetch="EAGER" to the column definition.
Comment: Curious, though, since `$this->members = new ArrayCollection();` exists in Household `__construct()`.
Comment: Yes but when doctrine create an entity it is replaced with PersistentCollection and it is not initialized until you take other entity from the collection.

Orphan not removed


rxJs publishLast not flushing out messages

Question: I've just read http://blog.thoughtram.io/angular/2016/06/16/cold-vs-hot-observables.html and I was trying to get the publishLast working with some basic observables and I couldn't, can someone explain why?
        let obs = Observable.create((observer: Observer<number>): void => {
      observer.next(234);
    })
        .publishLast()
        .refCount();

    obs.subscribe((v: number) => console.log("1st subscriber: " + v));
    setTimeout(() => {
      obs.subscribe((v: number) => console.log("2nd subscriber: " + v));
    }, 1100);

Answer: I am assuming that by "flushing out" you mean that you are not receiving any events in your subscribe block.
The problem is that publishLast can only emit when it knows the Observable will not be emitting any more values, and the only way it can do that is if you call complete on the Observer.
So your code needs to look like this:
let obs = Observable.create((observer: Observer<number>): void => {
  observer.next(234);
  observer.complete();
})
.publishLast()
.refCount();

Comment: Thank you so much! My use case is this, I have a behaviorSubject that maps into an http call, and I would like it to return the last result to everyone, but if the behaviorSubject changes it should make a new http call, and notify it's subscribers. Is there any way to make this?
Answer: @user2555964 For your use case, combining switchMap with distinctUntilChanged might provide a solution. Take a look an Angular's documentation where they use these two operators to implement a real-time search box
https://angular.io/tutorial/toh-pt6#herosearchcomponent


Estimating regression coefficients in the presence of stochastic trend

Question: I have a very basic problem. My time series is modeled as:
$$
\begin{align}
Y_t &= a_t + \beta x_t + v_t \\
a_t &= a_{t-1} + w_t
\end{align}
$$
where $ w_t$ ~ $N(0,W) $  with known $W$, and $v$ is white noise.
I don't know if I can use the usual linear regression here, since the values for $a$ are not deterministic and are not stationary. What method should I use to estimate $\beta$, and specifically, get $t$-statistics or $p$-values for it? Implementation wise, I use lm() for estimating my regression in R. I would appreciate it if you could mention how to do it in R.
Comment: If you estimate the model with a kalman filter and maximum likelihood you can get standards errors for $\beta$ and the variances of $v_t$ and $w_t$, so you can compute p-values for those coefficients.  It would not make sense in this context to compute p-values for $a_t$ since, as you said in your post, they are stochastic.
Comment: A similar problem occurs in neuroimaging, where the BOLD signal is modeled as a linear combination of regressors, plus an error term which is modeled as an AR(1) process plus white noise. There the approach is to first naively estimate $\beta$ using least squares, then estimating the properties of AR(1) + white noise from the residuals, and then applying a whitening filter to $Y_t$ and $x_t$ with the idea that the errors of the whitened data and regressors are now approximately white noise. Finally, the regression coefficients are estimated again. This is of course only an approximation.
Comment: Is there an additional error term in the model or is $a_t $ supposed to be the error term.  If $a_t $ is the error term you can use generalized least squares.  If there is an additional error term you can use a Kalman filter
Comment: @ZacharyBlumenfeld Thank you for noticing my error. I have edited the question. If I use Kalman Filter, it seems like I won't be able to compute t-statistics and p-values for the coefficients. Am I right?
Answer: The most obvious approach would be to use Kalman filtering with diffuse or partially diffuse initial conditions (e.g. $\beta$ diffuse) to estimate the coefficients and their variances.
If the sample sizes are not small, the estimate divided by the standard error should be approximately standard normal. [You could get there via CLT and Slutsky, for example, even if $v_t$ were not Gaussian.]


How do you check if an input is a negative number in VB

Question: I am trying to do some validation which checks if the value in a textbox is an integer then checks if the the value is negative. It correctly checks if the value is an integer but I can't get it to check if the value is negative.
Note: The value being entered is the number of competitions attended so comps = competition etc...
Dim comps As Integer
    Dim value As Double
    If Integer.TryParse(txtCompsEntered.Text, integer) Then
        value = txtCompsEntered.Text
        If value < 0 Then
            lblcompsatten.ForeColor = Color.Red
            txtCompsEntered.ForeColor = Color.Red
            lblcompsatten.Text = "No negative numbers"
        Else
            lblcompsatten.ForeColor = Color.Black
            txtCompsEntered.ForeColor = Color.Black
            lblcompsatten.Text = ""
        End If
        lblcompsatten.ForeColor = Color.Black
        txtCompsEntered.ForeColor = Color.Black
        lblcompsatten.Text = ""
    Else
        lblcompsatten.ForeColor = Color.Red
        txtCompsEntered.ForeColor = Color.Red
        lblcompsatten.Text = "Not a number"
    End If

I have already looked at this thread but it didn't seem to work
how-to-check-for-negative-values-in-text-box-in-vb
Comment: If a Jon Skeet answer doesnt work, you almost certainly did something wrong.  you are mixing types Integer and Double and not using TryParse right at all.
Answer: Tryparse will convert the input to an integer if it succeeds - you don't need both the comps and value variables.  Here's an example of how it works:
Dim comps As Integer
Dim input As String = "im not an integer"
Dim input2 As String = "2"

'tryparse fails, doesn't get into comps < 0 comparison
If Integer.TryParse(input, comps) Then
    If comps < 0 Then
        'do something
    End If
Else
   'I'm not an integer!
End If

'tryparse works, goes into comps < 0 comparison
If Integer.TryParse(input2, comps) Then
    If comps < 0 Then
        'do something
    End If
End If

Comment: Thanks. It was that I didnt have the second integer.tryparse.
Comment: You don't need to have both... that was just an example of where it would enter the comps < 0 line based on the input actually being able to be parsed to an integer
Answer: There are a couple of things off with your code but the main issue is using Integer.TryParse incorrectly.
Incorrect:
Dim value As Double
If Integer.TryParse(txtCompsEntered.Text, integer) Then
    value = txtCompsEntered.Text
        If value < 0 Then

Correct:
Dim value As Integer
If Integer.TryParse(txtCompsEntered.Text, value) Then
    If value < 0 Then

The things to note are that Integer.TryParse will return a boolean value (true if the value can be convertan integer, false if not). It will them dump the converted value into the second parameter you pass into it. In your case, you had 'integer', which is incorrect. You should be passing in a variable and then using that variable for your comparison.
Also, be careful with your types. You have 'value' as a double when you seem to be working with integers.
Answer: Maybe try this?
If myinteger.toString.Contains("-") Then
    'it's negative
Else
    'it isn't
End If

Or even simplier
If myinteger < 0 Then
    'it's not negative
Else
    'it is negative
End if