Why the reverse DNS lookup of SPN during initial phase of Kerberos authentication?

Question: At its base, Kerberos isn't an overly complicated protocol. I have also already successfully configured a server to accept Kerberos authentications via SPNEGO HTTP headers. I'm new in this area though, so maybe I have just overlooked something...
The confusing part of Kerberos and their implementations is the optional reverse DNS lookup of server's hostname made by clients before they send the resulting SPN to KDC in order to obtain a ticket for the server / application identified by that SPN. As a result, clients may either use the originally requested hostname (this may be an alias - CNAME), OR the reverse-looked up name of the IP-address-owning server in the resulting SPN. This complicates Kerberos setups greatly.
The Kerberos specification (RFC 4120) seems to prefer avoiding the reverse lookup (also referred to as "canonicalization"):

1.3.  Choosing a Principal with Which to Communicate
...
Implementation note: Many current implementations do some degree of
canonicalization of the provided service name, often using DNS even
though it creates security problems.  However, there is no
consistency among implementations as to whether the service name is
case folded to lowercase or whether reverse resolution is used.  To
maximize interoperability and security, applications SHOULD provide
security mechanisms with names that result from folding the user-
entered name to lowercase without performing any other modifications
or canonicalization.

For example, the widespread MIT Kerberos implementation gives an option to disable the reverse lookup and there are even several scenarios suggesting when the reverse lookup should be disabled, in their documentation. On the other side, in Windows the reverse lookup seems to be pretty much hard-coded (see a related question Globally disable reverse DNS lookup for Kerberos on Windows?).
The problem is that the reverse lookups not only break the usage of server aliases (CNAMES), but their optional-ity can cause really unexpected and unstable behavior when different programs on the same machine decide to handle it differently. Like for example when Fiddler makes Kerberos authentication work. And from my tests, the current Firefox, unlike Chrome or IE, even rejects to send Keberos token to a server if requested hostname and hostname looked up by a used Kerberos client library don't match.
So here comes the question: Why is there this mostly problematic default behavior of Kerberos clients? Is there any real benefit nowadays from doing the reverse lookups, other than to maybe get FQDN of a server when FQDN isn't supplied, or to be "backwards-compatible"? Isn't the identity of the called server somewhat confirmed by the widespread usage of SSL anyway?
A bonus question: No new standard coping with this Kerberos "quirk" on the way?
Comment: Ah, sorry, the burden of having to create/support multiple SPNs.  I agree, a service should ideally have a single address, but web farm etc proxies don't always help us in this area, and I suspect it all fell into the too-hard basket and not canonicalising became the easier path.
Comment: There's a good article somewhere (not MS) about using canonicalisation to ensure single host address / SPN, to avoid the burden of having to support the all calling parties' arbitrary aliases.  That concept is the closest thing I've seen to a purpose for the canonicalisation, but it doesn't address why it's optional or even not preferred.
Comment: @Chalky, thanks for your feedback. It seems like no one, maybe from the authors (MS?) themselves, really understand the purpose. I wonder what it means "to avoid the burden of having to support the all calling parties' arbitrary aliases" - I can't see any burden myself here. Maybe you could try to explain?
Comment: Note that from what I've seen, there is usually just one hostname (possibly CNAME alias) used for a target application running on a server that needs to be registered in Kerberos (AD). That's why I can't see the problem in here.
Answer: I've always assumed it's to break CNAMES.
Comment: To be honest, from my experience with MIT Kerberos (non-AD), it always seemed to _help_ with using CNAMEs more than break them. It meant the host only ever needed a single SPN for a particular service even if it was known under multiple names.
Comment: I have just edited my question, so that it is more clear for newcomers. I can confirm that the reverse lookups "break CNAMES". But the question is about why they even exist...
Comment: If the host is serving multiple services then it totally breaks things.
Given that most web servers are virtual hosts/proxys/loadblancers it really makes life hard.  It would be much easier to register a few different CNAMEs than give every different service principal it's own A record, and possibly even a different host IP and reverse Ptr record.
Answer: I guess this is probably the reason why my keberoized application works well out of Windows box (with only a SPN of the CNAME), however need another SPN of the hostname for the application to run out of Unix.


Can a sidebar span two zones in omega 3 theme?

Question: I'm a bit of a newbee with Omega 3. I am having trouble arranging a grid which has a vertical sidebar span two zones. See the attached  diagram to understand the design requirements. I need to have a left sidebar and content block both appear under the header, and a right sidebar that spans both the the header and the content.
I would like to know if it is possible to create such a grid within the standard Omega UI, or if not how can this be accomplished.
Thanks!
Answer: No, with the way the HTML is built, it goes

zone-wrapper div (if used)

zone dov

region div

In your case, I would leave the Header zone empty (make sure the checkbox for forced rendering is off), and then move all of your regions to the Content zone.  In the grand scheme of things, there is nothing special about the Header zone.  I am looking at one of my sites now, and I left Header empty.
With the default templates, the Content zone also contains the Breadcrumb and Messages, so you may need to tweak this a bit to output the regions specifically to get these in the proper place.
Comment: Thanks for your answer. Question is if I put the header in the content zone, how can I have the left sidebar as a separate block under the header? Can I somehow add a view block within the content zone?
Comment: @DoviG. You would keep the left sidebar as a region and just assign the proper gird classes.  Omega just handles the regions.  You add blocks to the regions with the normal methods from the block management page.
Comment: Thanks again and sorry for my repeated questions, as I am pretty new to this. I am afraid I did not explain myself properly. If I understand correctly you suggest adding the header and main content into a single region in the content zone and have them aligned vertically in the region. How do I have the left sidebar block appear under the header next to the content like in the diagram above? Is this doable?


Windows Services in Delphi with database connection

Question: I would just like a tip about a situation.
I created a Windows service that does the task management of my application.
The service connect to the database (Firebird) and call a component that does the task management.
The process works fine, however, in Windows 10 the service does not start automatically after the computer is restarted. In other versions of Windows everything works perfectly. In testing, I have identified that if I comment on the method that calls the execution of the tasks, the service usually starts on Windows 10.
Procedure TDmTaskService.ServiceExecute(Sender: TService);
Begin
  Inherited;

  While Not Terminated Do
  Begin
    //Process;
    Sleep(3000);
    ServiceThread.ProcessRequests(False);
  End;

End;

The problem is that nothing exception is generated in component or service.
By analyzing the Windows Event Monitor, I have identified that the error that occurred with my service is Timeout, in which case the service was unable to connect to the service manager within the time limit. No more exceptions are generated.
Would anyone have any about Windows Services made in Delphi that connect to database?
Example of my source code:
**Base class:**

unit UnTaskServiceDmBase;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, SvcMgr, Dialogs;

type
  TDmTaskServicosBase = class(TService)
  private
    { Private declarations }
  public
    function GetServiceController: TServiceController; override;
    { Public declarations }
  end;

var
  DmTaskServiceBase: TDmTaskServicosBase;

implementation

{$R *.DFM}

procedure ServiceController(CtrlCode: DWord); stdcall;
begin
  DmJBServicosBase.Controller(CtrlCode);
end;

function TDmTaskServicosBase.GetServiceController: TServiceController;
begin
  Result := ServiceController;
end;

end.

**Service Class:**

Unit UnTaskServiceDm;

    Interface

    Uses
      Windows, Messages, SysUtils, Classes, Graphics, Controls, SvcMgr, Dialogs,

      UnJBTask,
      UnJBReturnTypes,
      UnJBUtilsFilesLog,
      UnTaskServiceDmConfig,
      UnTaskServiceDmConnection,
      ExtCtrls,
      IniFiles;

    Type
      TDmTaskService = Class(TDmTaskServicosBase)
        Procedure ServiceExecute(Sender: TService);
        Procedure ServiceCreate(Sender: TObject);
        Procedure ServiceStop(Sender: TService; Var Stopped: Boolean);
      Private
        FTaskServiceConfig: TDmTaskServiceConfig;
        FStatus: TResultStatus;
        FDmConnection: TDmTaskServiceConnection;
        FJBTask: TJBTask;
        FLog: TJBUtilsFilesLog;

        Procedure ExecuteTasksSchedule;
        Procedure UpdateServiceInformation;
        Procedure Process;
        Procedure UpdateConnection;
      Public
        Function GetServiceController: TServiceController; Override;
      End;

    Implementation

    {$R *.DFM}

    Procedure ServiceController(CtrlCode: DWord); Stdcall;
    Begin
      DmTaskService.Controller(CtrlCode);
    End;

    Procedure TDmTaskService.UpdateConnection;
    Begin

      Try
        FDmConnection.SqcCon.Connected := False;
        FDmConnection.SqcCon.Connected := True;

        FLog.Adicionar('Conexão com banco restabelecida.');
        FLog.FinalizarLog;
      Except

        On E: Exception Do
        Begin
          FLog.Adicionar('Erro ao restabelecer conexão com o banco de dados.' +
            sLineBreak + sLineBreak + E.Message);
          FLog.FinalizarLog;
        End;

      End;

    End;

    Procedure TDmTaskService.UpdateServiceInformation;
    Begin
      Inherited;

      Try

        Try
          FTaskServiceConfig.Load;

          FLog.Adicionar('Dados registro serviço.');
          FLog.Adicionar('Nome: ' + FTaskServiceConfig.ServiceName);
          FLog.Adicionar('Descrição: ' + FTaskServiceConfig.ServiceDescription);

          If (FTaskServiceConfig.ServiceName <> EmptyStr) And
            (FTaskServiceConfig.ServiceDescription <> EmptyStr) Then
          Begin
            Name := FTaskServiceConfig.ServiceName ;
            DisplayName := FTaskServiceConfig.ServiceDescription;
          End;

          FTaskServiceConfig.Close;

        Except

          On E: Exception Do
          Begin
            FLog.Adicionar('Erro adicionar dados registro serviço.');
            FLog.Adicionar('Erro ocorrido: ' + sLineBreak + sLineBreak + E.Message);
          End;

        End;

      Finally
        FLog.Adicionar('Name: ' + Name);
        FLog.Adicionar('DisplayName: ' + DisplayName);
        FLog.FinalizarLog;
      End;

    End;

    Procedure TDmTaskService.Process;
    Begin

      Try

        If FDmConnection.SqcCon.Connected Then
        Begin

            ExecuteTasksSchedule;

        End
        Else
          UpdateConnection;

      Except

        On E: Exception Do
        Begin

          FLog.Adicionar('Ocorreu um erro ao checar as tarefas.' + sLineBreak +
            'Erro ocorrido: ' + sLineBreak + E.Message);
          FLog.FinalizarLog;

          UpdateConnection;

        End;

      End;

    End;

    Procedure TDmTaskService.ExecutarTarefasAgendadas;
    Begin

      If FJBTask.ExistTaskDelayed Then
      Begin

        Try
          FJBTask.ExecuteTasks;
        Except

          On E: Exception Do
          Begin
            FLog.Adicionar('Ocorreu um erro ao executar as tarefas agendadas.' +
              sLineBreak + 'Erro ocorrido: ' + sLineBreak + E.Message);
            FLog.FinalizarLog;

            UpdateConnection;
          End;

        End;

      End;

    End;

    Function TDmTaskService.GetServiceController: TServiceController;
    Begin
      Result := ServiceController;
    End;

    Procedure TDmTaskService.ServiceCreate(Sender: TObject);
    Begin
      Inherited;

      Try
        FLog := TJBUtilsFilesLog.Create;
        FLog.ArquivoLog := IncludeTrailingPathDelimiter(FLog.LogFolder) + 'TaksService.log';

        FDmConnection := TDmTaskServiceConexao.Create(Self);
        FDmConnection.Log := FLog;

        FJBTask := TJBTarefa.Create(Self);
        FJBTask.SQLConnection := FDmConnection.SqcConexao;

        FTaskServiceConfig := TDmTaskServiceConfig.Create(Self);
        FTaskServiceConfig.SQLConnection := FDmConnection.SqcConexao;

        FStatus := FDmConnection.ConfigurouConexao;

        If FStatus.ResultValue Then
        Begin
          UpdateServiceInformation;
        End
        Else
        Begin
          FLog.Adicionar(FStatus.MessageOut);
          FLog.FinalizarLog;
        End;

      Except

        On E: Exception Do
        Begin
          FLog.Adicionar('Não foi possível iniciar o serviço.' + sLineBreak +
            'Erro ocorrido: ' + sLineBreak + sLineBreak + E.Message);
          FLog.FinalizarLog;
          Abort;
        End;

      End;

    End;

    Procedure TDmTaskService.ServiceExecute(Sender: TService);
    Begin
      Inherited;

      While Not Terminated Do
      Begin
        Process;
        Sleep(3000);
        ServiceThread.ProcessRequests(False);
      End;

    End;

    Procedure TDmTaskService.ServiceStop(Sender: TService; Var Stopped: Boolean);
    Begin
      Inherited;

      If Assigned(FDmConnection) Then
      Begin

        FLog.Adicionar('Finalizando serviço.');
        FLog.Adicionar('Fechando conexão.');
        Try
          FDmConnection.SqcConexao.Close;
        Finally
          FLog.FinalizarLog;
        End;

      End;

    End;

    End.

Comment: On a side note, `Sleep(3000);` is begging for trouble - it's a huge no-no in services, and threads in general. At least do it in a loop which continuously checks if it's terminated, at bare minimum.
Comment: I have a bad feeling you haven't provided all the code. Since everything has `Inherited;` in it, this tells me that your entire service data module is inherited from another one, which could have more code. Your problem is probably in that ancestor code. But, it's not inherited, it has `TService` directly on there, so why you have `Inherited;` all over, I don't know.
Comment: On Windows startup, assume your service starts *before* the database service has started, thus making your service fail to connect. When that happens, it raises an exception. If that exception isn't handled, the service will halt. *EDIT* I just looked closer and there is some exception handling which should catch this occasion.
Comment: What is the question?
Comment: @JerryDodge: "*Since everything has `Inherited;` in it, this tells me that your entire service data module is inherited from another one, which could have more code*" - it is not unusual for newbies who don't know any better to put `inherited` in event handlers, not knowing that doing so is basically a no-op.
Comment: @JerryDodge. You're right, my service inherits from another class. But this base class has no code that could interfere with the situation. I just modified the class to best exemplify for you.
Comment: @RemyLebeau, sure, but it's not my case, I'll use the inherited statement. It was just an example that I wanted to display in a simpler way.
Answer:
By analyzing the Windows Event Monitor, I have identified that the error that occurred with my service is Timeout, in which case the service was unable to connect to the service manager within the time limit. No more exceptions are generated.

Do not connect to your database, or do any other lengthy operations, in the TService.OnCreate event.  Such logic belongs in the TService.OnStart event instead.  Or better, create a worker thread for it, and then start that thread in the TService.OnStart event and terminate it in the TService.On(Stop|Shutdown) events.
When the SCM starts your service process, it waits for only a short period of time for the new process to call StartServiceCtrlDispatcher(), which connects the process to the SCM so it can start receiving service requests.  StartServiceCtrlDispatcher() is called by TServiceApplication.Run() after all TService objects have been fully constructed first.  Since the OnCreate event is called while your process is trying to initialize itself, before StartServiceCtrlDispatcher() is called, any delay in service construction can cause the SCM to timeout and kill the process.
Also, you should get rid of your TService.OnExecute event handler completely.  You shouldn't even be using that event at all, and what you currently have in it is no better than what TService already does internally when OnExecute is not assigned any handler.
Comment: Indeed, proper service design should never do work in the main service thread. In fact I always write every service in a thread within a test app first, then migrate it over to the service. I have a template I use which allows me to simply start/stop the thread in the start/stop of the service. It would be nice if Borland had never made the `OnExecute` event available in the first place :-)
Comment: @Fero: the alternative is to do what I already explained - create a thread to do your work, and start it in the `OnStart` event and stop it in the `On(Stop|Shutdown)` event. The `OnExecute` event should not be used because it is very easy to mess up. Too many newbies get it wrong and then wonder why their services don't work. `TService` handles SCM requests just fine without `OnExecute` assigned, so let it.
Comment: @Fero, to expand on Remy's answer, [here](https://stackoverflow.com/a/10538102/800214) you can find how to correclty implement a service in Delphi
Comment: If you say OnExecute should not be used at all, whats the alternative?  and whats wrong with OnExecute?
Comment: @RemyLebeau, Remy, thanks for the tips, always very important. I used the OnCreate event to connect because my service can have multiple instances, that is, I can have the same service, connected to different databases. So I need to give it a different name before I start it. This name is in the database. Before showing you I had tried several possibilities arriving at the service I have now, which works without problems, but does not start automatically in Windows 10. I will reformulate the process based on your tips and examples and confirm the return here.
Comment: @Delphiman do not store the service name in a database. It doesn't belong there. Delay all database activity to the `OnStart` event or later. The best place to store the service name is in the service's registered Registry key as an added command line parameter to the executable path so it gets passed to the service process when the SCM is starting it. There are plenty of examples of how to do this for `TService`.
Comment: @RemyLebeau, perfect, thanks for your tip.I'll arrange for the change.
Answer: In your service code :
- you can try to add Dependencies on your Firebird Service
- you can increase WaitHint
if it still not work : you can start as automatic but "Delayed"
Comment: The other answer is the correct fix. This is just a work-around, which isn't even guaranteed to work.
Comment: @HuguesVanLandeghem, In my case, I added Firebird as a dependent service, but still, it still did not work. The detail is that the service only does not start automatically in Windows 10. In the rest of Windows it works without problems. I'll test with your WaitHint tip and confirm whether it worked or not. I can not use the start delayed option because it does not work on Windows 2000, 2003 and XP versions. Which in that case is part of our customers.
Comment: @HuguesVanLandeghem, Just incrementing WaitHint did not work. Just to give you a comeback. The solution was the answer I just posted.
Comment: @Delphiman I think the word you mean to use is "feedback". "comeback" is a negative thing, usually a form of retaliation.
Comment: @JerryDodge, you are right. Sorry, my English is. I meant feedback.
Answer: I found it otherwise to solve, however, I thank everyone for the tips, because in a timely manner you will make improvements to my service.
The solution was to extend the service startup timeout through the Windows ServicesPipeTimeout registry key.
For my case it worked perfectly.
I increased the value of ServicesPipeTimeout to 120000 (2 minutes).
By default the value is 30000 (30 seconds) or less.
To manual Edit:
1) Open the Windows Regedit App;
 2) Locate and then click the following registry subkey:
    - HKEY_LOCAL_MACHINE \ SYSTEM \ CurrentControlSet \ Control
    In the panel values, locate the ServicesPipeTimeout entry.
** Note **:
If the ServicesPipeTimeout entry does not exist, you must create it. To do
this, follow these steps:

 - On the Edit menu, point to New, and then click DWORD Value.
    - Type ServicesPipeTimeout, and then press ENTER.
  3) Right-click ServicesPipeTimeout, and then click Modify.
  4) Click Decimal, type 120000, and then click OK.
     ** 120000 miliseconds = 2 minutes
  5) Restart the computer.
In Delphi (Sample registry value):
Procedure TForm3.JBButton3Click(Sender: TObject);
Const
  CKeyConfigTimeout = 'SYSTEM\CurrentControlSet\Control';
  CValueConfigTimeout = 'ServicesPipeTimeout';

Var
  LReg: TRegistry;

Begin

  LReg := TRegistry.Create;
  Try
    LReg.RootKey := HKEY_LOCAL_MACHINE;
    LReg.OpenKey(CKeyConfigTimeout, False);
    LReg.WriteInteger(CValueConfigTimeout, 120000);
  Finally
    LReg.CloseKey;
    FreeAndNil(LReg);
  End;

End;

Note: The delphi application with the registry update code needs to run in administrator mode for Windows Vista / Server or Superior versions;
Comment: This is just another workaround that is not guaranteed to work. The proper fix is to redesign the service to stop doing anything at startup that can delay the service from connecting to the SCM so it wont timeout in the first place.
Comment: @RemyLebeau, I agree with you. This change in timeout (ServicesPipeTimeout) will allow me to gain time to refactor the process. It will be a temporary solution. Thank you very much for the valuable tips.


Search objects for a given string

Question: I have these objects
const data = [
  {
    id: 1,
    recipient: "001",
    assessment: "Apta",
    score: "2",
    ovarian: "E1",
  },
  {
    id: 2,
    recipient: "ABC2",
    assessment: "Apta",
    score: "2,5",
    ovarian: "E1",
  },
  {
    id: 3,
    recipient: "003",
    assessment: "Refugo",
    score: "3",
    ovarian: "E1",
  },
  {
    id: 4,
    recipient: "004",
    assessment: "Apta",
    score: "4",
    ovarian: "E2",
  },
];

And this is my code, which when it finds the correct string it returns me:
const searchAnimal = value => {
  setInput(value);

  JSON.parse(records).filter(item => {
    if (item.recipient === value) {
      setSearch([item]);
    }
  });
};

What would the logic be to return all object.recipients that start with 00?  Would a regex maybe do it?
Comment: I'm voting to close this question because it needs to be in English.
Answer: I think changing a little bit the logic would help:
let search = function (data, searchString) {
  return data.filter((item) => {
    return item.recipient.includes(searchString);
  });
};

By doing so will give you the object you're searching for.
Answer: You can filter for the objects with a recipient that starts with 00 by using:
const array00Animals = data.filter((animal) => animal.recipient.substr(0, 2) === '00');

This will return the array of objects but only id's 1, 3 and 4 from your sample data.

Search objects for a given string


Calculating the probability of an event being early or late by a certain amount

Question: I'm very new to this so I assume there's a better way to ask this that I just don't know about.  Please point me in the right direction.
Suppose I'm running a library and books are due 30 days after they're borrowed.  And there's a library member named Joe, and I want to figure out how likely it is that he'll return his books on time, and early or late by certain amounts.  Joe has returned his books on the following intervals after borrowing them: [10, 24, 27, 27, 28. 29, 29, 29, 30, 30, 30, 31, 31, 32, 34].  This is just an example and I'd probably be looking at more
How can I figure out the probability that Joe will have returned his books on-or-before each day 25-35.  My naive attempt would be to sum up the number of returns by preceding intervals like this:

25: 02/15
26: 02/15
27: 04/15
28: 05/15
29: 08/15
30: 11/15
31: 13/15
32: 14/15
33: 14/15
34: 15/15
35: 15/15

Is the a "smarter" way to do this, and possibly one that would work with less-discrete numbers than whole days?  Ideally I think I'd like to end up with some kind of continuous function so that I could track the returns down to the second and it would be able to tell me the probability of Joe returning his books at 33.1 days and the probability at 33.9 days, and 33.9 days would have a higher probability.
In particular if there's a good way to do this with a readily-available python package that would be a huge help.
Answer: There are several approaches you may use, depending on what assumptions are you willing to make and how much data do you have at hand. I present three possible methods with explantion and code. Note that I calculated only the "probability of returning book on day 25" and "the probability of returning book after noon on day 25", but you can choose arbitrary limits (even a second).
Non Parametric Estimation

In general, the function you wrote as example is the empirical distribution function $$ \hat{F}_n\left( x \right) = \frac{1}{n}\sum_{i=1}^{n} 1_{\left\lbrace X_i <x \right \rbrace} $$ Where $1_A = \begin{cases}1 & A \text{ holds} \\ 0 & \text{otherwise}\end{cases}$.  It convergence to the real distribution with rate of convergence of $O\left( \sqrt{n} \right)$, meaning that for large enough $n$, the errors $ \left| \hat{F}_n\left( x \right) - F\left( x \right) \right| $ have standard deviation of $ O\left(\frac{1}{\sqrt{n}}\right) $. More suprisingly, the convergence is uniform (holds for all values of $x$ together). However, this is all asymptotics. I'm not sure how it works on a small sample. In any case, it really easy to calculate this function:
def F(data, x)
    return np.mean(data < x)

# Probability of returning book on day 25
F(data, 25) - F(data, 24)

# Probability of returning book after noon on day 25
F(data, 25) - F(data, 24.5)

Note however that $ \hat{F}_n\left( x \right) $ is still quite discrete, and it is possible to estimate the probabilities to a finer resolution using kernel density estimation. This approach approximates the derivative of $ \hat{F}_n\left( x \right) $ and is quite similar to producing histograms. In essense, you calculate $$ \hat{f}_h \left(x\right) = \frac{1}{n}\sum_{i=1}^{n} \frac{1_{\left\lbrace \left|x_i - x\right| < h \right\rbrace}}{2h}$$ This makes sense as soon as you note that $ 1_{\left\lbrace \left|x_i - x\right| < h \right\rbrace} = \hat{F}_n\left( x + h \right) - \hat{F}_n\left( x  - h\right)$. You have to choose the parameter $h$ which sort of acts as resolution. In practice, you can replace $1_{\left\lbrace \left|x_i - x\right| < h \right\rbrace}$ with other functions, all called kernel, which affect the smoothness of the resulting function. This method is more complex, and required more data to achieve the same performance as $ \hat{F}_n $. The actual rate actually depends on the underline distribution.
Although more complex, this estimator has an implementation in sklearn:
from sklearn.neighbors import KernelDensity
from scipy import integrate

clf = KernelDensity(bandwidth=0.5, kernel="tophat")
clf.fit(data)

# clf.score returns the log density
density = lambda x: np.exp(clf.score(x))

# Probability of returning book on day 25
probability, error = integrate.quad(density, 24, 25)

# Probability of returning book after noon on day 25
probability, error = integrate.quad(density, 24.5, 25)

Note that you might want to play around with the parameters, and that score returns the log of the probability.

Parametric Estimation

Now we are ready to assume a model. It's a stronger assumption, but works better for smaller amounts of data (assuming you choose your model wisely). Two possibilities for such simple model are exponential distribution and gamma distribution. Both distribution are modeling continuous waiting times with small differences (exponential models the time until the first event, gamma until the $\alpha$'s th event). Our goal is to find the rate in which the event happens, i.e., how long until the costumer returned the book. (There might be better models, so don't get stuck on this one if it fails to predict properly).
Exponential distribution has density $$ f\left(x ; \lambda \right) = \lambda e^{-\lambda x}$$ where $x$ is non-negative. Note that given data points that were generated independently, $$ f\left(x_1,\ldots, x_n ; \lambda \right) = \prod_{i=1}^{n} \lambda e^{-\lambda x} =  \lambda^n e^{-\lambda \sum_{i=1}^{n} x}$$ A common estimator for $ \lambda $ using the data is the maximum likelihood estimator (MLE), that is, the paramter $\lambda$ that maximizes the probability density for the given data. In our case, $$ \hat{\lambda} = \frac{n}{\sum_{i=1}^{n} x_i }$$ After estimating the rate, we can calculate the required probability using the density function. scipy actually provides it for us:
from scipy.stats import expon

# Note that expon uses scale = 1 / lambda
scale = mean(data)

# Probability of returning book on day 25
expon.cdf(25) - expon.cdf(24)

# Probability of returning book after noon on day 25
expon.cdf(25) - expon.cdf(24.5)

Final Remark
There is no one size fit all. After estimating, you should test to see if the estimation makes sense. A few advised steps:

Plot the histogram to know what to expect
Plot the estimated density vs. the density of exponential with the estimated parameter
Check the average error between points and their estimation. Preferably, do it on dataset that wasn't used for the estimation task (test set)
If high resolutions are important, it might be advisable to convert the data to seconds.


Simple question about the asymptotics of estimators

Question: Consider any arbitrary estimator called $\hat{M}$ (e.g., regression coefficient estimator or specific type of correlation estimator, etc) that satisfies the following asymptotic property:
$$\boxed{\sqrt{N}(\hat{M}-M) \overset{d}{\to}\mathcal{N}(0,\sigma^2)}\,\,\,\,\,\,\,\,\,\,\,\,(1)$$
which implies that our $\hat{M}$ is consistent. We also have a consistent estimator $\hat{\sigma}$, which gives rise to the asymptotic property:
$$\displaystyle \ \ \boxed{\frac{\sqrt{N}(\hat{M}-M)}{\hat{\sigma}} \overset{d}{\to}\mathcal{N}(0,1)}\,\,\,\,\,\,\,\,\,\,\,\,(2)$$
I'm wondering if I can use the $z$- or $t$-test just like normal for any such $\hat{M}$ that satisfies the above? Let $Q$ be defined as the test statistic:
$$\displaystyle \ \ \boxed{Q_\hat{M} = \frac{\hat{M}-M_{H_0}}{\sqrt{\frac{1}{N}\hat{\sigma}^2}}}\,\,\,\,\,\,\,\,\,\,\,\,(3)$$
My goal is to do the following hypothesis test:
$H_0: M = 0$
$H_a: M \not= 0$
yet the only information I have access to is $(1)$ and $(2)$, whence my question.

$$\underline{\text{Update}}$$
The current answers suggest that I can't always robustly $z$- or $t$-test for any such $\hat{M}$. I am reading the relevant sections of All of Statistics (Wasserman), as well as Statistical Inference (Casella & Berger). Both state that, if:
$$\displaystyle \ \ \frac{\sqrt{N}(\hat{M}-M)}{\hat{\sigma}} \overset{d}{\to} \mathcal{N}(0,1)$$

then "an approximate test can be based on the wald statistic $Q$ and would reject $H_0$ if.f. $Q < -z_{\alpha/2}$ or $Q > z_{\alpha/2}$" (in Casella & Berger, page 492, "10.3.2 Other Large-Sample Tests")
or, in (Wasserman, page 158, Theorem 10.13) "Let $Q = (\hat{M}-M_{H_0})/\hat{se}$ denote the observed value of the Wald statistic $Q$ $\big($where $\hat{se}$ is obviously equal to my $\sqrt{\frac{1}{N}\hat{\sigma}^2}$$\big)$. The p-value is given by:

$$p = 2\Phi(-|Q|)$$
This contradicts the existing advice since they do not state any other necessary assumptions to be able to do this legitimately (to the best of my ability to comprehend). Either;

I have failed to understand existing answers.
I have failed to express my original question clearly.
I have failed to read these chapters properly.
They are excluding thoroughness for pedagogical purposes.

I would appreciate some assistance on which option is correct. Thanks. $\big($Please go easy I am new to stats :)$\big)$.

Another dimension is that my intended application is $n = 3000$, so perhaps the finite sample problems are less relevant?
Comment: You are empirically using the proof of the robustness of the t-test ([see](http://stats.stackexchange.com/q/44262/10525)). A good estimator of $\sigma$ typically requires a moderate or large sample size. This in turn implies that the distribution of the T statistic is a Student-$t$ with large degrees of freedom, which is approximately normal.
Comment: @StasK already answered, I will only note that it is not a good idea mathematically to have $N$ dependent quantities on both sides of $\to$.
Comment: @Jase My answer is "*They are similar when the sample size is moderate or large but there is not much gain on doing such approximation*". The quality and validity of the approximation is still restricted to some conditions on the sampling distribution, as discussed in the link posted in my previous comment. On the other hand, I think this question reflects a good intuition.
Comment: @Jase The normal approximation that you are proposing depends on two underlying approximations. The first one is the speed of convergence to the normal distribution in your first equation (*speed* as a function of the sample size). The second one is the speed of convergence of the estimator of $\sigma$. If at least one of these is slow (in the sense that it requires a large sample size to produce an accurate estimation), then the approximation may not be that appealing.
Comment: @Jase The $t$-test is a bit more conservative than the normal test you are considering. The proposed normal test can be seen as an approximation of the t-test, which is already an approximation (this is explained in StasK's answer). If your estimators $\hat{M}$ and $s$ are as good as you mention, then they will likely provide similar answers. My point is that the normal test can be used (only) in nice scenarios; it will work well but this test is not robust.
Comment: @Jase I said "normal test" because you are using a normal approximation to the T statistic. The $t-$test is more conservative in the sense that the denominator is treated as a random variable, not just a number. This is why the resulting distribution (Student-$t$) has heavier tails than the normal ones.
Comment: @Jase How are you estimating $\sigma$? Is it the sample variance? If the answer is yes, then the statistic $t_{\hat{M}}$ is approximately distributed as a Student-$t$ with [certain degrees of freedom](http://en.wikipedia.org/wiki/Student%27s_t-test). If not, then you have to obtain the distribution of $\hat{\sigma}$ and after that, obtain the distribution of the ratio $t_{\hat{M}}$. If the variability of $\hat{\sigma}$ is small, then the normal test will work. If the variability is high, then you need the distribution of your statistic which may be complicated but you can employ  bootstrap.
Comment: @Jase Yes, that is always the case because the estimator is consistent. But the variability of the estimator, this is, the variance of the distribution of the estimator may be still big. What you try do is: simulate $N$ samples of size $n$ (the sample size of interest) from the sampling model and calculate $N$ statistics $t_{\hat{M}}$. Plot the histogram of the sample of statistics and check if they look normal. You can go one step further and test for normallity, *e.g.* using `shapiro.test()`.
Comment: @Jase As I said "You can go one step further and test for normallity, e.g. using `shapiro.test()`". Another option consists of resampling in order to obtain a bootstrap sample of your test statistic and to use this sample to conduct the hypothesis test.
Comment: I do not see any contradiction between the answers here and Wasserman's Theorem 9.18. Wasserman states that the result is asymptotic and applies to the MLE not any estimator. Therefore: (1) you may need a large sample to get an accurate approximation and (2) the result applies to the MLE *under appropriate regularity conditions*, which does not contradicts the answers below.
Comment: Do you mean, "any *such* $\hat M$"?
Comment: Right! I really should have mentioned that.
Comment: @Procrastinator So the answer is *"Yes, you can $t$-test like normal for any such $\hat{M}$"*?
Comment: @Procrastinator What problems can come up if I do a $t$-test like normal?
Comment: @Procrastinator Thanks. If $s \to \sigma$ (i.e. estimated std. error $\to$ asymptotic std. error) and $\hat{M} \to M$ very quickly in a simulation study, then is it safe to use the $t$-test as I described?
Comment: Many thanks @Procrastinator for this interesting link. Really.
Comment: Well, finally I am a bit disappointed by the answer. Anyway, thanks.
Comment: @Elvis Do you mean the answer in the link I posted? You can also go to the wikipedia link I posted there, which contains the basic idea of the proof, I think.
Comment: @Procrastinator Okay, so to summarize your contribution: $\text{(i)}$ Standard, everyday $t$-testing is fine for any such $\hat{M}$ in order to test $H_0: M = 0$ versus $H_a: M \not= 0$, and $\text{(ii)}$ $z$-testing is fine only in nice, idealized scenarios.
Comment: Yes, I read all that. In fact as far as I understand the consequence of Slutky lemma is just that the statistic is asymptotically normal.
Comment: @Procrastinator Also, I'm not sure what you mean by "The $t$-test is a bit more conservative than the normal test you are considering". I am not considering any "normal test". I am considering only the $t$-test.
Comment: @Procrastinator Can you tell me what test statistic I should be using for this $\hat{M}$? What would the test statistic look like if I want to work with the Student-$t$ distribution?
Comment: @Procrastinator Well $\hat{\sigma}^2$ is simply the estimator for the asymptotic variance, $\sigma^2$. A simulation study is done and found that the error decreases monotonically as $n$ is increased.
Comment: @Procrastinator How do I tell the difference between whether it's Student-$t$ distributed (hence I use normal $t$-test) or normally distributed (hence I use $z$-test)? They look the same to the eyeball.
Answer: That's exactly how asymptotic results are being used in practice, e.g., in logistic regression. I would probably factor it differently as
$$\sqrt{N}\frac{\hat{M}-M}\sigma \overset{d}{\to}\mathcal{N}(0,1)$$
which shows the desired result more immediately, IMO (as mptikas mentioned in the comments, it is not kosher to have $N$ on the RHS of the asymptotic expression). The practical problem with this of course is that $\sigma$ is usually unknown, and needs to be estimated. The result, and the application, would still hold if a $\sqrt{N}$-consistent estimator is plugged in place of $\sigma$. In some applications, getting such an estimator is a non-trivial task, as is the case with say dependent data (time-series, cluster sampling, spatial data).
Update: since the asymptotic distribution is the normal rather than Student, a $z$-test is more appropriate. In practice, $t$-tests are often used instead, but coming up with the degrees of freedom is often a challenge. Besides, for most sample statistics, the finite sample asymmetry and bias are greater concerns than heavy tails, and these obviously cannot be corrected by referring the test statistic to the $t$-distribution instead of the standard normal.
Comment: But should he do a $t$-test or a $z$-test?
Comment: I updated my answer a little bit to address this question, see above.
Comment: It is still unclear to me whether I can do the $t$-test or whether I can't do it (or whether my ability to do it robustly is contingent upon some conditions).
Answer: Taking the question at its face value, the answer is no.  I offer a counterexample where $\hat{M}$ approaches its estimand in distribution while its variance diverges: in such a case, the $t$ statistic must approach zero almost surely, proving it can have neither an asymptotic Normal or t distribution.

Consider the usual Normal setting where $\hat{M}$ is an unbiased estimator of the mean based on $N \ge 2$ iid observations of a Normal$(\mu, \sigma^2)$ variable, $(X_1, X_2, \ldots, X_N)$.  Let $\beta$ be a function of $N$ to be determined later and, writing  $\bar{X}$ for the sample mean, consider the estimator
$$\hat{M}(X_1,\ldots,X_N) = \beta(N)\bar{X}\ \text{ if }\ X_1\ge\max(X_1,\ldots,X_N)\ \text{ else }\  \frac{N-\beta(N)}{N-1}\bar{X}.$$
Because the first alternative in the definition of $\hat{M}$ happens with probability $1/N$ and the second with probability $(N-1)/N$, we can compute that
$$\mathbb{E}(\hat{M}) = \mathbb{E}\left(\frac{1}{N}\beta(N)\bar{X}\ + \frac{N-1}{N}\frac{N-\beta(N)}{N-1}\bar{X}\right)  = \mathbb{E}(\bar{X}) = \mu,$$
showing that $\hat{M}$ is an unbiased estimator of $\mu$, and (by computing the expectation of $\hat{M}^2$ and subtracting the square of the expectation of $\hat{M}$),
$$\text{Var}(\hat{M}) = \frac{\sigma^2/N + \mu^2}{N(N-1)^2}\left((N-1)^2\beta(N)^2 + (N-1)\left(N-\beta(N)\right)^2\right) - \mu^2.$$
If we choose $\beta(N) = O(N^b)$ for $\frac{1}{2} \lt b \lt 1$, the right hand side (which is $O(N^{2b-1})$) will diverge but $\hat{M}$ will approach $\mu$ in distribution (because most of the time $\hat{M}$ will equal $ \frac{N-\beta(N)}{N-1}\bar{X}$ which is becoming arbitrarily close to $\bar{X}$).

In a comment, StasK has noted that this estimator $\hat{M}$ is not exchangeable in the arguments ($X_1$ plays a favored role) and asks whether that might be part of the cause of the "bad" asymptotic behavior.  I do not believe so.  For instance, let $s$ be the sample standard deviation and $\bar{X_{\widehat{i}}}$ be the mean of the variables with $X_i$ excluded.  The distribution of $(Y_i) = (X_i - \bar{X_{\widehat{i}}})/s)$ depends only on $N$ (not on $\mu$ or $\sigma$)--it is a multivariate distribution with scaled Student t distributions as marginals--so for each $N$ we there exists a number $t_N$ for which there is a $1/N$ chance that $\max(Y_i)\ge t_N$.  In the definition of $\hat{M}$, replace the condition $X_1 \ge \max(X_i)$ by $\max{Y_i}\ge t_N$.  Everything works out exactly as before, but this $\hat{M}$ is invariant under permutations of the data.
Comment: I don't have a copy of either of those texts in front of me, Jase, but I suspect that they have assumed the estimates are Maximum Likelihood estimates (which is the setting for a Wald statistic), whereas your question asks about an "arbitrary" estimator.
Comment: Bill, you probably meant $X_1 \ge \max(\cdots)$ in the first formula. This (counter)example is of course artificial, but still useful to have at hand, as most counterexamples are. What would be the additional requirements to impose on $\hat M(X_1, \ldots, X_N)$ to rule out situations like you've described? Interchangeability of the arguments?
Comment: @StasK Thanks--done. Instead of the $X_1 \ge \max\ldots$ test we could use a randomized procedure, so interchangeability doesn't help. I don't know what a sufficient set of conditions would be to rule out this situation. Although the example is artificial, it models estimators that might once in a while be a little "wild." We might speculate that such estimators are also likely to be inadmissible (as in the case of unbiased estimators for lognormal distributions), so that could be a fruitful direction to look for conditions.
Comment: Please see my updated question.
Comment: I trust that your answer was absolutely fantastic, but since I do not have the capability to understand it I will award the correct answer to stask.
Comment: I'll be sure in the future not to provide incomprehensible answers to your questions.
Comment: I think it is good to get a broad range of complexity in the answers if the goal is to make CV into a database of authoritative answers catering to a wide audience.


Como verificar se um checkbox esta checado com jquery?

Question: Ola, estou tentando fazer uma operação em JS caso um checkbox esteja checado, porem não estou obtendo sucesso. Segue o código:
  $('#btn-proximo').click(function(e){
            if($('#in_acesso').is('checked')){

            $('#div_valida :input').each(function(){
              if(this.value == "" || this.value == " "){
                e.preventDefault();
                 this.focus();

            }
          if($('#password').val() != $('#password_confirmation').val()){
            $('#dados_gerais').preventDefault();
            $('#erroSenha').show('fade');
            setTimeout(function(){
              $('#erroSenha').hide('fade');
            },6000);
            $('#password').focus();

          }

        })
        }
        })

Comment: Coloque o `:` antes do checked, assim `.is(':checked')`
Comment: mude a linha if($('#in_acesso').is('checked')){ para if($('#in_acesso').is(':checked')){
Faltou só o ":" antes do "checked"
Answer: JQUERY – VERIFICANDO UM CHECKBOX COM IS(':CHECKED')
A primeira forma de se fazer esta verificação é usando a função is() do jQuery. Ela verifica se o argumento, ou conjunto de argumentos que você declarou satisfazem a condição determinada. Caso positivo, ela retorna "verdadeiro". Caso negativo, retorna "falso".
Para usar o is(), primeiro precisamos escolher o elemento e depois fazer a verificação usando o seletor :checked , que funciona com checkboxes, entre outros.
Você usou simplesmente checked sem : (dois pontos)
Veja

$('#btn-proximo').click(function(e){
     if($('#in_acesso').is('checked')){
          console.log("primeiro codigo");
     }

     if($('#in_acesso').is(':checked')){
          console.log("segundo codigo");
     }
})

<button id="btn-proximo">proximo</button>

<input type="checkbox" id="in_acesso">
Answer: O Jquery possui o seletor :checked, e com a ajuda do length você consegue obter o valor 1 quando o objeto for selecionado. Desta forma, você consegue "checkar" um ou mais checkbox. Enquanto o checkbox não for selecionado, ele possui valor 0, logo você pode desenvolver sua lógica a partir desta funcionalidade. Espero que ajude. Segue o código de exemplo:

$('#check').on('click', function(){
 var checkbox = $('#check:checked').length;
  console.log(checkbox);

  if(checkbox === 1)
  {
    alert('Parabéns! \o/');
  }
});

    <input type="checkbox" id="check">


Carregar uma tag scrip apos outra tag script ter carregado por completo

Question: Quero carregar uma tag script somente quando a outra estiver COMPLETAMENTE carregada.
Exemplo:

quero que o scriptDois carregue apenas depois o scriptUm tenha carregado COMPLETAMENTE.
Já tentei algumas maneiras porem todas estavam relacionadas ao carregamento da pagina, gostaria de uma maneira que esteja relacionada ao carregamento de outro script.
Comment: Da maneira como você colocou, elas já são carregadas em sequência.
Comment: O segundo executa quando terminar a execução do primeiro. A não ser que você esteja disparando operações assíncronas (timers, ajax) e queira carregar o segundo ao final dessas operações. Nesse caso o carregamento vai depender de como é o código do primeiro script. Talvez isto te ajude: https://pt.stackoverflow.com/q/14544
Comment: Talvez essa pergunta te ajude https://pt.stackoverflow.com/questions/138892/%C3%89-poss%C3%ADvel-incluir-um-arquivo-javascript-dentro-de-outro-arquivo-javascript
Comment: @bfavaretto Me corrija se eu estiver errado, eles de fato são executados em sequencia, contudo não o scriptDois executa independente de o scriptUm ter terminado sua execução por completo.
Answer: usa o script1 como chave para iniciar o script2
function script1() {
    //codigos que quer que seja executado primeiro
    return script1(true);
}

function script2(keyRun) {
    if(keyRun){
        //o que quiser que execute
    }
}

Dessa forma o script2 só vai executar quando o script1 terrminar de ser executado.
Caso você esteja usando funções assíncronas no script1, você terá que tratá-lo com Promise, mais ou menos dessa forma:
async function script1() {
    myCode = (resolve, reject) => {
        //vou usar o fetch como exemplo de função assincrona
        fetch(url)
            .then((html) => {resolve(script2(true))})
            .catch((error) => reject(console.error(error)));
    }
    return await new Promise(myCode);
}

function script2(keyRun) {
    if(keyRun){
        //o que quiser que execute
    }
}

Nesse caso, se der algum erro o script2 não será executado, mas isso pode ser facilmente resolvido com o devido tratamento dos erros
Answer: Você pode utilizar o atributo defer da tag script.

Desse modo o carregamento do script passa do padrão (fetch seguido da execução), que pausa o carregamento do HTML, para o fetch assíncrono e execução em sequência após o carregamento do HTML de acordo com a ordem de chamada dos arquivos.


Automatically changed Profile pic and decreased points

Question: Today I just logged to magento.stackexchange.com and shocked to see that my Profile Pic is changed and Reputation point is decreased (-125), saying <code>−xx  User was removed</code>

Can any one say OR explain, what's happened to my profile ?
Answer: All I can tell you is that your -125 points come from the fact that a user that upvoted your questions/answers got deleted. Read more about this here.
I have no idea what happened to your avatar.
I only see in the activity report 2 avatar changes from May 30.
Maybe you changed the avatar on stackoverflow.com and you also clicked to change it on every other site in the stackexchange network.
Comment: I don't make up the rules. [read this question](http://meta.stackexchange.com/q/125740/224252) and the answers. Maybe you will understand why this is needed and why it happens.
Comment: but this is much disruptive to me (results in -125). Can't they use that "special deletion", stated in the link you provided ?
Comment: That's how the delete works. Special deletion applies in special cases. I guess this was not a special case.
Comment: This is ridiculous. If user is removed, why it should affect my points ?


changing style of the active element on a WP PHP Menu

Question: I am creating a menu using this function:
function nav_menu( $theme_location ) {
    if ( ($theme_location) && ($locations = get_nav_menu_locations()) && isset($locations[$theme_location]) ) {
        $menu = get_term( $locations[$theme_location], 'nav_menu' );
        $menu_items = wp_get_nav_menu_items($menu->term_id);
        $menu_list  = '' ."\n";
            $menu_list  .= '
' ."\n";
            foreach( $menu_items as $key => $menu_item ) {
                $menu_list .= '
' ."\n";
                $menu_list .= 'url . '" class="nav-link">' . strtoupper($menu_item->title) . '' ."\n";
                $menu_list .= '
' ."\n";
            }
            $menu_list .= '
' ."\n";
        $menu_list .= '' ."\n";
    } else {
        $menu_list = '';
    }
    echo $menu_list;
}

the problem is I want to highlight the current page I am on the menu but it seems not possible due when I apply a pseudoclass it applies to all the menu elements, maybe with a JS function or similar will be able to achieve that?
Comment: What version of WordPress are you using? I don't believe WordPress stores menu item data using individual nav_menu_item WP Post entries anymore.
Comment: thanks for your reply @kofeigen, I'll have a look. I'm afraid that means there is no way to achieve it then?
Answer: just adding a JS to add a class and it works:
document.querySelectorAll(".nav-link").forEach((link) => {
    if (link.href === window.location.href) {
        link.classList.add("active");
        link.setAttribute("aria-current", "page");
    }
});

then add the class "active" in the css
Comment: Interesting solution. Just keep in mind it might break if you upgrade WordPress to a newer version. Please mark your own answer as **accepted** if it works. It will be helpful to those who find your question in search results to know a correct answer is available. Thanks.


Confidence interval of quantile / percentile of the normal distribution

Question: What is the formula (if it exists) for the sample variance / confidence interval of a quantile / percentile of the normal distribution?
For example, the 5th percentile for a standard normal population distribution is -1.64, but what is the 95% one-sided confidence interval if I have a sample of n=1,000? I.e. on average the 5th percentile of a standard normal sample will be -1.64 and 95% of the time the sample 5th percentile of a sample of n=1,000 will be below -1.54 (approximate from simulations).
There seems to be some kind of formula as it's an option in SAS (CIQUANTNORMAL) and I think it may be related to the Probit but haven't found an explanation.
Answer: When you are trying to estimate a quantile from data then you can turn the problem into a binomial problem.  For 1,000 data points you want to know what value will have 5% of values below it (population values, the sample is just the estimate) and 95% above it.  So you can test each possible value using the binomial (how many of your 1,000 values are below the value you are testing).  All the values that would not be rejected given your data constitute the confidence interval.
There is some more detail on Wikipedia or by Googling "quantile confidence interval".
Answer: Suppose that $X\sim N(\mu,\sigma)$, where $\mu$ and $\sigma$ are unknown.   Since $\bar{x}$ and $s$ are independent, it is pretty easy to calculate confidence bounds for any linear combination of $\mu$ and $\sigma$.
Now, all you need to remember is that the 5th percentile of $X$ is, as you note, $\mu-1.64\sigma$.


@forelse dentro de @forlese

Question: Olá, estou precisando fazer um @forlese dentro de um @forlese em Laravel:

Contas cadastradas

                Fornecedor
                Data de Emissão
                Data de Vencimento
                Sequência
                Valor
                Tipo
                Conta Resultado
                Mais opções

            @forelse($FinContaspagar as $contas)
                @forelse($FinContaspagarDetalhe as $detalhe)

                    {{ $contas->getTerceiro() }}
                    {{ $contas->getDtemissao()->format("d-m-Y") }}
                    {{ $contas->getDtvencimento()->format("d-m-Y") }}
                    {{ $detalhe->getSequencia() }}
                    R$ {{ $detalhe->getValor() }}
                    {{ $detalhe->getTipo() }}
                    {{ $detalhe->getContaResultado() }}

                        getCodigo()) }}">Editar
                        |
                        getCodigo()) }}">Apagar

            @empty

                    Não há ações neste momento!

                @endforelse
            @endforelse

Porém o retorno que eu tenho é:
FatalErrorException in 21634628c350161c40fd94debe415477685a25b0.php line 102:
syntax error, unexpected 'endif' (T_ENDIF)

Devo fechar o @endforelse antes?
Comment: Qual é código da linha 102?
Comment: @VirgilioNovic Essa linha nem sequer existe... o código vai até a linha 92
Comment: Olha é impossível não existir, dá uma verificada no arquivo `21634628c350161c40fd94debe415477685a25b0.php` que fica na pasta `storage\framework\views` ...
Answer: @foreach ($propostas as $proposta)

Dados da proposta

    Solicitante: {{ $proposta->solicitante }}
    Data: {{ $proposta->data }}

Serviços da proposta

        @foreach ($propostas->servicos as $servico)
            Descrição: {{ $servico->descricao }}
            Valor: {{ $servico->valor }}
        @endforeach
    Total: {{ $proposta->total }}
@endforeach

Comment: Tharles, bem vindo ao StackOverflow! Seria interessante se você juntasse, ao código, uma pequena explicação de como ele responde à pergunta.

@forelse dentro de @forlese


How can I change tag separator from "," to "+"?

Question: I want to change tag separator in a Term reference field of my content type (using Autocomplete term widget (tagging)) from "," to "+" or maybe something else (in Drupal 7) because this field needs to be filled in Persian.
What shoud I do ?
thanks.
Comment: @Ashlar, When I don't understand _why_ people are doing what they are doing, I suspect they are going about the actual problem in the wrong way. _Now_ that have some more information, I can tell you that this is a known problem. [Issue here](http://drupal.org/node/582534). While you can manipulate the form itself, as suggested below, the real solution is in pushing that issue. Engage in [office hours](http://drupal.org/node/1242856) and the experienced core maintainers will help you fix the problem for real instead.
Comment: because "," is "،" in persian so users should change their keyboard format, and as long as this field could fill with both English ang Persian words, I need a character which is same in these languages.
Comment: You question lacks context.
Comment: Please refer to the faq option in the top menu to find more about asking questions.  It is unclear where you are trying to apply this change and why, so it is not clear to a responder how to answer.  You can edit and expand upon your question to clarify.
Comment: Is that clear enough now?
Comment: Now I believe I understand the question. However, I prefer not to help people do "wrong" things, and find it hard to imagine the circumstances in which this is a good idea.
Comment: @letharion Can you provide an answer re: why it is wrong?
Comment: @Sheshkovsky Out of curiosity, why can't you use the comma in Persian?
Answer: you can use a hook_form_FORM_ID_alter. I used this validation to make sure users use commas instead of spaces:
function MYMODUDLE_form_FORM_ID_alter(&$form, &$form_state, $form_id) {
 $form['#validate'][] = 'custom_form_validate';
}

function custom_form_validate($form, &$form_state) {
  $tags = $form_state['values']['field_MYNAME_tags']['und'];
  foreach ($tags as $tag) {
    if ((strlen($tag['name']) > 15) || (substr_count($tag['name'], ' ') > 1)) {
      form_set_error('field_MYNAME_tags', 'Please enter tags separated by commas');
    }
  }
}

Answer: Ideal answer of my question according to this issue is: In drupal/include/common.inc file, change the line $regexp = '%(?:^|,\ *)("(?>[^"]*)(?>""[^"]* )*"|(?: [^",]*))%x'; to  $regexp = '%(?:^|,|،|\ *)("(?>[^"]*)(?>""[^"]* )*"|(?: [^",|،|]*))%xu';.
Now both English and Persian comma is available for separator, and I will not worry about changing keyboard language or not!
Answer: Two notes for this regex fixed:
At first you should change common.inc file unicode to utf-8;
Then remember that when you upgrade your drupal core, you sholud redo this change in common.inc file again.
Answer: Your ultimate solution is autocomplete deluxe module. You can get from its project page


Equivalence of total boundedness and relative compactness in Polish spaces.

Question:
Let $E$ be a Polish space. A set $A\subset E$ is totally bounded if and only if $A$ is relatively compact.

First we suppose $A$ is totally bounded. Since $\overline A$ is closed and $E$ is complete, $\overline A$ is complete. Let $x$ be the limit of a sequence $\{x_n\}$ in $A$ and $\varepsilon>0$. Choose $y_1,\ldots, y_n\in A$ so that $A\subset \bigcup_{i=1}^n B(y_i,\varepsilon/2)$. Choose $N$ such that $d(x_n,x)<\varepsilon/2$ and let $j$ be such that $x_N\in B(y_j,\varepsilon/2)$. Then $$d(x,y_j)<d(x,x_n)+d(x_n,y_j)<\varepsilon,$$ so that $x\in B(x,y_j)$. It follows that $\overline A$ is totally bounded, and thus compact.
I am a bit unsure of this since I did not use the separability of $E$. I also do not see how to show the converse. Any tips would be appreciated.
Answer: Separability is not required. The equivalence is true in any complete metric space. For the converse note that $\overset {-} A$ can be covered by  a finite number of balls of radius $\epsilon$ (because it is compact and it is covered by all balls of radius $\epsilon)$. Hence $\overset {-} A$ is totally bounded. Any subset of a totally bounded set is also totally bounded, so $A$ is totally bounded.
Proof of the fact that if $A \subset B$ and $B$ is totally bounded the $A$ is totally bounded: cover $B$ by balls $B(b_i,\epsilon /2), 1\leq i \leq n$. Without loss of generality assume that each of these balls has non-empty intersection with $A$. Let $a_i \in A\cap B(b_i,\epsilon /2)$. You can now verify that $A$ is covered by the balls $B(a_i,\epsilon)$.


Using spy() in Julia

Question: I am trying to use spy(). But I am not getting the use of it right. I think my error has something to do with this: https://github.com/JuliaLang/julia/issues/2121
I have a 300x300 Array{Float64,2}
using PyPlot
pygui(true)
spy(I) # where I is my 300x300 array

and it gives me this error:
LoadError: PyError (:PyObject_Call) <type 'exceptions.TypeError'>
TypeError("object of type 'PyCall.jlwrap' has no len()",)
  File "/home/ashley/.julia/v0.4/Conda/deps/usr/lib/python2.7/site-packages/matplotlib/pyplot.py", line 3154, in plot
    ret = ax.plot(*args, **kwargs)
  File "/home/ashley/.julia/v0.4/Conda/deps/usr/lib/python2.7/site-packages/mpl_toolkits/mplot3d/axes3d.py", line 1539, in plot
    zs = np.ones(len(xs)) * zs

I have tried specifying spy(I, zs=zeros(size(I)) but then I just get the error:
LoadError: ArgumentError: function spy does not accept keyword arguments
while loading In[260], in expression starting on line 13

Any ideas?
Comment: i tested your code in julia-v0.4 with no error, but spy just drew nothing.
Answer: spy shows the non-zero elements. Apparently it doesn't show anything if there are no non-zero elements.
M = sprand(300, 300, 0.1)  # generate a sparse matrix with density 0.1 of non-zeros
M = full(M)
spy(M)

works for me.
Comment: Thank you - this works for me. But only when I am using the terminal version of julia. When I try run it in a script using an editor (so far sublime and vim) it builds but nothing happens - i.e. nothing shows. I know this is a separate question so pls just say if you would prefer I start another thread - but how do I do this with an editor?
Comment: I guess this has to do with whether the editor "knows" how to interact with the graphics package. I would recommend the Jupyter Notebook for this kind of interactive graphing.
Comment: wasn't using interactive mode with IJulia. Putting `plt[:show]()` at the end did the trick.
Comment: I would like to find an easy way to do Julia without notebook. But I hear you - thanks.

Using spy() in Julia


Hosts names get clear on network/pc restart

Question: I have nginx set up in my cent os and setting up virtual domians apart from localhost:
<code>      test.pluspro.com test2.pluspro.com.
</code>
after adding the domains to the /etc/hosts file in the system they  are working well.but once the network or pc restart the hosts names get cleared and set to its defaults.
Some one has an idea why this happens?
Answer: that has nothing to do what how the hostname is set.. edit the following file
<code>/etc/sysconfig/network
</code>
if you don't see a HOSTNAME=some.host.com add it


Help drawing the function $\frac{100}{1+20e^{-0.23t}}$

Question: Can somebody explain this one to me?
Draw the function
$$p(t)=\frac{100}{1+20e^{-0.23t}}$$
for $t\in[-20,40]$.
Comment: it looks like P is described as a function of time, t is defined wierdly as t is normally time but it can apparently be negative, but beyond that, what ar eyou struggling to understand
Answer: This is not a differential equation problem. The problem asks to draw the function
$$p(t) = \frac{100}{1 + 20e^{-0.23t}}$$
for $t \in [-20,40]$. You can use Wolfram to give you an hint for what you wanna find and use calculus tools. Find the first and second derivatives, find were it is zero, find how this function behaves in that range. Is it crescent? Is it decreasing?
Comment: Which derivative tells you if it is crescent?


jQuery não funciona em App Electron

Question: Estou criando um aplicativo Electron apenas estudo, só que estou encontrando um problema.
Criei uma página html simples, utilizando o framework Bootstrap 4.0, nela coloquei apenas um menu.

index.html

          <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

          </button>

                      Arquivos

                      Configurações

                          wmsouza

Wéllingthon Motta

email@example.com

                                          Atualizar dados

                                              Sair

Adicione nela os scripts necessários.

Feito assim, ao abrir o arquivo index.html no navegador, funciona perfeitamente.

Mais ao executar no aplicativo, o método dropdown não funciona e retorna erro no console falando que o Bootstrap necessita do jQuery.

Uncaught Error: Bootstrap's JavaScript requires jQuery. jQuery must be included before Bootstrap's JavaScript.
      at bootstrap.min.js:6
  (anonymous) @ bootstrap.min.js:6

Porém na aba Network, mostra que o jQuery foi carregado.

O que pode estar acontecendo ?
Comment: Já experimentaste com o jQuery 2? O 3 é uma versão muito reduzida, talve zlhe falte algum método.
Comment: Tentei com a versão 2, também não deu certo.
Answer: Pelo que entendi o Eletron usa o node.js ou seja o jQuery acaba trabalhando como se não estivesse rodando em um "browser", então ao invés do jQuery ficar acessivel no escopo do window. ele acaba ficando só acessível no escopo do global. ou apenas usando require(), isto por causa deste trecho:
if ( typeof module === "object" && typeof module.exports === "object" ) {

    // For CommonJS and CommonJS-like environments where a proper `window`
    // is present, execute the factory and get jQuery.
    // For environments that do not have a `window` with a `document`
    // (such as Node.js), expose a factory as module.exports.
    // This accentuates the need for the creation of a real `window`.
    // e.g. var jQuery = require("jquery")(window);
    // See ticket #14549 for more info.
    module.exports = global.document ?
        factory( global, true ) :
        function( w ) {
            if ( !w.document ) {
                throw new Error( "jQuery requires a window with a document" );
            }
            return factory( w );
        };
} else {
    factory( global );
}

Creio que ao adicionar via

jQuery não funciona em App Electron


Focus on the element to scroll on load of the page

Question: I am trying to focus/activate a container through javascript, so that I can scroll it by using up and down arrow keys. Currently, this is not possible until I click on that container.
Here is the fiddle
HTML

CSS
.main {
    width: 300px;
    height: 400px;
    background-color: green;
    overflow: auto;
}
.child {
    height: 800px;
    width: 30px;
    background-color: red;
}

I tried using Element.focus() method of javascript which didn't work.
Comment: Purpose of jQuery tag???
Comment: @A.Wolff I thought there is a solution using it. Just similar to as I mentioned javascript tag.
Comment: Anything that can be done in jQuery can be done in javascript ;)
Answer: You need to set tabindex attribute in order to get DIV element focusable, e.g:

Then for styling purpose, you could wish to set outline CSS property:
.main {
    outline: 0;
    ...
}

-DEMO-
Comment: @Mr_Green You still need to call `main.focus();` of course, `tabindex` doesn't magically set focus: http://jsfiddle.net/s0tjocwk/4/  ***As a side note*** This should be possible in future to use `autofocus` attribute for not only input elments but AFAIK, none browser currently support it for DIV element
Comment: Thanks for the solution. but this is not working when I apply using javascript. Here is the [Fiddle](http://jsfiddle.net/venkateshwar/s0tjocwk/3/). Sorry, I didn't mention that I have many similar containers on the page and I need to activate a single container.


Parsing XML - string captured is front truncated. Swift

Question: My parsing of xml documents works well, but what I have noticed is that randomly the text in between certain tags ("AbstractText") becomes truncated and I have no idea what.  Again, this appears only here and there and is not always the case for this tag.  My code for the parsing is below and also an example of a truncated text.
<code> var abstractBool = false
 var abstract = ""

 func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) {
      switch elementName {
       case "AbstractText":
             abstractBool = true
      }
}

 func parser(_ parser: XMLParser, foundCharacters string: String) {
       if abstractBool{
          abstract = string
       }
 }

 func parser(_ parser: XMLParser, didEndElement elementName: String,
 namespaceURI: String?, qualifiedName qName: String?) {
      switch elementName {
           case "AbstractText":
           abstractBool = false
      }
 }
</code>
Raw XML from remote server:
<code> <Abstract>
 <AbstractText>
 Protein kinase C (PKC) has been shown to activate the mammalian target of
 rapamycin complex 1 (mTORC1) signaling pathway, a central hub in the
 regulation of cell metabolism, growth and proliferation. However, the
 mechanisms by which PKCs activate mTORC1 are still ambiguous. Our previous
 study revealed that activation of classical PKCs (cPKC) results in the
 perinuclear accumulation of cPKC and phospholipase D2 (PLD2) in recycling
 endosomes in a PLD2-dependent manner. Here, we report that mTORC1 activation
 by phorbol 12,13-myristate acetate (PMA) requires both classic, cPKC, and
 novel PKC (nPKC) isoforms, specifically PKCη, acting through distinct
 pathways. The translocation of mTOR to perinuclear lysosomes was detected
 after treatment of PKC activators, which was not colocalized with PKCα- or
 RAB11-positive endosomes and was not inhibited by PLD inhibitors. We found
 that PKCη inhibition by siRNA or bisindolylmaleimide I effectively decreased
 mTOR accumulation in lysosomes and its activity. Also, we identified that
 PKCη plays a role upstream of the v-ATPase/Ragulator/Rag pathway in response
 to PMA. These data provides a spatial aspect to the regulation of mTORC1 by
 sustained activation of PKC, requiring co-ordinated activation of two
 distinct elements, the perinuclear accumulation of cPKC- and PLD-containing
 endosomes and the nPKC-dependent translation of of mTOR in the perinuclear
 lysosomes. The close proximity of these two distinct compartments shown in
 this study suggests the possibility that transcompartment signaling may be a
 factor in the regulation of mTORC1 activity and also underscores the
 importance of PKCη as a potential therapeutic target of mTORC-related
 disorders.
 </AbstractText>
 </Abstract>
</code>
What i am able to extract is the following front-end-truncated portion of the string:
<code> scompartment signaling may be a factor in the regulation of mTORC1 activity
 and also underscores the importance of PKCη as a potential therapeutic target
 of mTORC-related disorders.
</code>
Answer: That's the normal behavior. You are given partial strings, and you have to concatenate them and the final result is given by the concatenation of all the strings obtained in the lapse between didStartElement and didEndElement are called. Be sure to save the current element in a variable so in foundCharacters you know where the partial string belongs to.
<code>var abstractBool = false
var abstract = ""

func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) {
      switch elementName {
       case "AbstractText":
             abstractBool = true
             abstract = "" // if you read an XML document with multiple
                           // AbstractText elements, you need to reset
                           // the variable
      }
}

 func parser(_ parser: XMLParser, foundCharacters string: String) {
     if abstractBool{
        abstract.append(string)
     }
 }

 func parser(_ parser: XMLParser, didEndElement elementName: String,
 namespaceURI: String?, qualifiedName qName: String?) {
     switch elementName {
         case "AbstractText":
         abstractBool = false
         // Here the variable 'abstract' contains the full text
     }
 }
</code>
Comment: Your PS doesn't apply to iOS, just macOS.
Comment: Thank you for the comment. Since the question is tagged with "iOS", I removed the PS.


Can Windows RDC admin users be immune from being kicked?

Question: I'm using remote desktop on Windows Server 2008 r2 and I'm trying to find a way to prevent users from kicking off admin users. I understand that according to MS a regular user should not be able to kick off an admin user however if a user attempts to log in while the admin user is on (and all other sessions are in use) the admin user has 30 seconds to click the box telling Windows that they are still using this session or they will be kicked.
The behavior that I am trying to create is for the admin to not be able to be kicked under any circumstances. Is this possible?
Edit: Allow me to clarify. I don't need more than 2 users to be able to log on. I just need for no normal user to be able to kick the admin user regardless of the number of users. If the admin user is on and someone else tries to log in I would like for them to be denied access. Is this possible?
Comment: "I'm using remote desktop on Windows Server 2008 r2" - No you're not. You're using remote desktop for administration, which is limited to two sessions. If you need more than two sessions then you need to install the RDS role, install an RDS License Server, purchase the appropriate type and number of RDS CAL's and set up a proper RDS environment.
Comment: What are those limited users doing on the server in the first place? Regardless of how many sessions you *need* without licensing RDS, you're only allowed to use Remote Desktop for administrative purposes. Having limited users log into these servers to work on things that are not related to the administration of that specific server is a violation of the license agreement.
Comment: I don't need more than two sessions. I just need for the admin users to be immune to being logged off.
Answer: Terminal services. You need it if you have multiple users:
http://technet.microsoft.com/en-us/library/cc754746(v=ws.10).aspx
Comment: If you're wanting to have more than 2 connections to the server you NEED the RDS role. However, if you're wanting to use the remote session for admin purposes, you can pass the /admin switch via RDC as noted here: http://support.microsoft.com/kb/947723
Comment: If you've installed the RDS role and have an activated RDS License server, and have the appropriate number and type of RDS CAL's then how is it that the admin is getting kicked off... unless more than one user is using the admin user account, in which case that's your problem and you ought to stop doing that. Each user should have their own uniquly named user account.
Comment: "In Windows Server 2008 R2, Terminal Services was renamed Remote Desktop Services." I'm already using this. I don't have a problem with multiple users being able to log in. I just don't want the admin to be able to be kicked.
Answer: Without purchasing and installing Remote Desktop Services CALs, you are only entitled to use Remote Desktop for administrative purposes. This is per the Windows Server license terms. If you have two non-administrative users that need to log in to run applications, you still need to purchase RDS CALs. The default two connections are only for administrative purposes. It's not two freebie RDS entitlements per server.
When you properly license your environment, your issue will go away since the proper amount of limited connections will be allowed in addition to two administrative sessions per server.


Inductive proof that every person supports the same team

Question: I can't find what's wrong with this.
Proof:
Every person supports the same team.
We can observe that in a set with only one person, all people within it support the same team. Now suppose that the statement is true for every set with cardinality $≤ n$. Then if there are $n + 1$ persons in a set, we take one of them and, by the hypothesis, all $n$ persons support the same team. Now put this person back to the initial set and remove a different one. Again, all the $n$ persons left support the same team. Therefore all $n + 1$ persons support the same team, and for every $k$ in $\mathbb N$, those $k$ people support the same team.
Comment: I suggest reading the answers to [this question](http://math.stackexchange.com/questions/428151/questions-on-all-horse-are-the-same-color-proof-by-complete-induction?rq=1).
Comment: Notice that in the inductive step it is being assumed n-1 > 0.  You haven't demonstrated in initial step where n -1 > 0.
Answer: Hint: The base case needs to be solved for $n = 1$ AND $n = 2$ in this problem. Do you see why?
Comment: +1. Alternatively, the inductive step implicitly assumes that $n>1$, and hence is not valid.
Comment: @f'': well, nothing goes wrong at that step if you mechanically treat "supports the same team" as a single-valued predicate, like "belongs to a set" or "is red". And therefore read "all n support the same team" as if it meant "each one of them supports the same team and therefore they all support the same team". It's just a question of exactly where you want the proof to be wrong ;-)
Comment: I suspected that the problem was there, but I can't see why it is problematic to solve it only for $n=1$.
Comment: @izzorts Try running the inductive step for $n=1$ and see what goes wrong.
Comment: @izzorts: the problem at $n = 1$ is that of your $n+1$ (i.e. 2) people, first you take a set of one and say that one supports the same team as himself. Then you take another set of one and say that one supports the same team as himself. But because the two sets don't intersect, they might support different teams. The erroneous "proof" skips over the fact that two sets $A$, $B$ need a non-empty intersection in order for us to prove "all of $A$ support the same team and all of $B$ support the same team implies all of $A \cup B$ support the same team".
Comment: ... although to see why that is, you might need a more formal expression of what "supports the same team" actually means. The "proof" uses supposed properties of this phrase without ever formally defining it, in the hope you won't notice that it doesn't really have the properties claimed.
Comment: Sandeep answered best. To be able to find "another" person to remove in the argument above, one has to have at least 3 people. So the induction gets blocked at $n=2.$
Comment: Go through the inductive step slowly.  You have n +1 people.  Remove 1.  n people support the same team (call i) Al.  Removed person unkown.  Remove one person.  One removed person supports A.  One removed person is unknown.  Remaining n-1 people IF THERE ARE ANY support A.  Add the unknown person.  You have n people so they must support the same team.  IF THERE WERE ANY n-1 people supporting A, these n people including the unknown support A.  Bring first person back.  BUT WHAT IF n-1 WAS 0?
Answer:
Now put the person back and remove another.  Again those n people support the same team.

Yes, but the $n$ people might support a different team than the previous $n$ people.
You are assuming:
$ set_1 = \{$ $n$ people supporting team $A$ $\}$
$ set_2 = \{$ $n$ people supporting team $B$ $\}$
$ set_{phantom} = set_1 \cap set_2 = \{$ $n-1$ people who support both team $A$ and team $B$ $\}$
(NEVER mentioned but assumed to exist)
We assume $set_{phantom}$ isn't empty and as people can't support different teams, we conclude $A$ and $B$ are the same team.
Then we have:
$set_{magic} = set_1 \cup set_2 = \{ n + 1$ people supporting either team $A$ or team $B$ but they are the same team $\}$
But notice! Our base case was $n=1$.  For $n=1$ then $set_{pantom}$ with $n-1 = 0$ members IS empty. So team $A$ and team $B$ may be different. And $set_{magic}$ could be $n+1 =2$ people supporting different teams.
So to do this proof right we need to prove it for a case where $set_{phantom}$ will have at least $1$ member. Thus we need to show this for a base case of $n >= 2$.
So we need to show all sets of two people support the same team.
It is impossible for us to show this.


Explicit Representation of the SU(N) Simple Roots in with redundant coefficents?

Question: Commonly the simple roots for $SU(n)$ groups are given as $n$ dimensional vectors, although root-space is $n-1$ dimensional.
The $SU(n)$ Wikipedia article explains:

Here, we use n redundant coordinates instead of n − 1 to emphasize the symmetries of the root system (the n coordinates have to add up to zero). In other words, we are embedding this n − 1 dimensional vector space in an n-dimensional one.

I want to know how can I transform back from these redundant coordinates to the non-redundant ones.
A concrete example:
I need an explicit representation of the simple roots of $SU(5)$ in four dimensions. Unfortunately these are usually given in five-dimensions, because the coefficients are then all integers.
$$\{\text{(1, -1, 0, 0, 0)},\text{(0, 1, -1, 0, 0)},\text{(0, 0, 1, -1, 0)},\text{(0, 0, 0, 1, -1)}\} $$
How can I compute the corresponding coefficents in four-dimension? The result should be sth. like
$$\{1,0,0,0\} , \left\{-\frac{1}{2},\frac{\sqrt{3}}{2},0,0\right\}, \left\{0,0,-\frac{1}{\sqrt{3}},\sqrt{\frac{2}{3}}\right\} \left\{0,0,-\frac{\sqrt{\frac{3}{2}}}{2},\frac{\sqrt{\frac{5}{2}}}{2}\right\}, $$
Answer: You just need to find a set of points in $\mathbb{R}^4$ which have the same inner products with each other as the original points.  This is equivalent to finding an orthogonal transformation of $\mathbb{R}^5$ that sends the original hyperplane $H : x_1 + x_2 + \ldots + x_5 = 0$ to one of the coordinate hyperplanes, say $x_5=0$.
Written as a matrix in the original coordinates, the transformation will have $(1,1,1,1,1)/\sqrt{5}$ in the bottom row (assuming your vectors are column vectors). Then complete to an orthogonal matrix in an arbitrary way: the other rows must be linearly independent unit vectors in $\mathbb{R}^5$ orthogonal to $(1,1,1,1,1)/\sqrt{5}$.  There are lots of ways to do this.  Now when you apply this matrix to your original vectors, the result will always have a 0 in the last coordinate, which you can drop, leaving a point in $\mathbb{R}^4$.
Your question suggests that you are expecting an answer of a particular form, but in fact, the answer isn't unique and there are lots of different answers you could get which are all correct, depending on how you complete the orthogonal matrix.  Maybe there is a particularly "nice" completion that gives you the answer you suggest, but I don't see it right now.
Comment: Thanks a lot! Your answer makes perfect sense but unfortunately I'm not really sure how to perfom the actual computation. A short example for one of the vectors would be much, much appreciated!
Comment: @JakobH Sorry, my original answer was incorrect.  See the new answer.


Error in TAG in Android Studio while using Google Firebase Authentication using Email and Password

Question: Here is the Code
I have also created A separate function for the still it does not work
 mAuth.signInWithEmailAndPassword(email, password)
    .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
        @Override
        public void onComplete(@NonNull Task<AuthResult> task) {
            if (task.isSuccessful()) {
                // Sign in success, update UI with the signed-in user's information
                Log.d(TAG, "signInWithEmail:success");
                FirebaseUser user = mAuth.getCurrentUser();
                updateUI(user);
            } else {
                // If sign in fails, display a message to the user.
                Log.w(TAG, "signInWithEmail:failure", task.getException());
                Toast.makeText(EmailPasswordActivity.this, "Authentication failed.",
                        Toast.LENGTH_SHORT).show();
                updateUI(null);
            }

            // ...
        }
    });

Comment: What is the error?
Comment: 'TAG' has private access  in 'android.support.v4.app.FragmentActivity'
Answer: Add codes below
for Kotlin:
companion object{
        private const val TAG = "your tag"
    }

to the out of onCreate()
for Java:
under your class (I guess it is "EmailPasswordActivity")
private static final String TAG = "EmailPassword";

That should be enough.
Answer: Change TAG with "yourname". I've tried it and it was successful.


How to exclude files matching two distinct wildcards in a batch file

Question: I have a folder containing file format for example
20140821160438_708_IP_JUL_2014.csv
20140821160438_708_PUD_JUL_2014.csv
20140821160438_708_IP_GP_JUL_2014.csv
20140821160438_708_PUD_GP_JUL_2014.csv

I want to grab file without GP in the file name and grab file of only IP and PUD. For example, I want to grab only IP in the file name, How do I write 2 condition in the following code to exclude PUD and PUD_GP?
FOR /R "C:\Share\PRC Interface" %%G IN (! *PUD_GP*.csv) DO move "%%G" C:\ERP_Interface\PRCERP\IP

Comment: How is this related to WinSCP? How is this related to programming? Please ask on [su].
Comment: the scritp is in the batch file of the winscp thanks.
Comment: WinSCP does not have `FOR`, nor `move` commands (it has `mv` though). WinSCP cannot move local files. So this is not a WinSCP script. It rather looks like a Windows batch command. The only reasonably close task WinSCP can do is to move files matching your rules from a remote directory to a local one or vice versa. Is this what you want to do? Or do you actually want to modify that Windows command to move only matching LOCAL files to another local directory (what has nothing to do with WinSCP)? Please make your question clear. Do not try to suggests tools to use, rather describe the problem.
Comment: the script is in a .bat file, and it will call the winscp.exe, the for script is inside the batch file.
Answer: pushd "C:\Share\PRC Interface"
for /f "delims=" %%a in ('
    dir /a-d /b /s *_IP_*.csv *_PUD_*.csv ^| find /i /v "_GP_"
') do echo move "%%~fa" "C:\ERP_Interface\PRCERP\IP"
popd

Retrieve the list of all the required files and filter to exclude those not wanted
move operation is only echoed to console. If the output is correct, remove the echo command


How to hide dynamics for only one voice channel in Guitar Pro 7?

Question: How to hide dynamics, the mezzo-forte (mf), in my score sheet for specific voice channels in Guitar Pro 7? I know I can hide dynamics for all channels, but that's not what I want.
In my score sheet, I sometimes need to use different voice channels to get the rhythm I want. This will add new dynamics (the mf) in the score sheet when I apply the new voicing in a bar later in the piece.

Voicing channel
image

Voice 1mf first bar

Voice 2mf first bar

Voice 3mf second bar

The only workaround I found was to apply overlapping notes on all the voice channels on the same note in the first bar.
Answer: After searching through the manual, I couldn't find anything about hiding dynamics for a specific channel.


E# in Brothers in Arms by Dire Straits

Question: I have been playing guitar for over ten years, but in about the past five years, I do not think I have improved much. I recently decided I want to change that, starting by trying to understand the music that I play better. My first step in this is learning some music theory and scales.
Currently, I am trying to play and understand 'Brothers in Arms' by Dire Straits. I believe the key of this song is G# minor. The notes in this scale are G#, A#, B, C#, D#, E, F#, and G#. Somewhere in the song (2:28 in the 7:04-version of the song), I hear the following lick;
<code>X:1
L:1/16
M:C
K:G#m
%%score T1
V:T1           clef=treble-8
% 1
[V:T1] z4 (f^e)de a,8
</code>

    E|-------------|
    B|-7p6---6-----|
    G|-----8-------|
    D|---------8---|
    A|-------------|
    E|-------------|

The 6th fret on the B-string is an E# that falls outside of the regular minor scale. This note is also used in a lick closely after. To a novice like myself, just having learned about scales, this feels counterintuitive. I can hear it sounds good here, but when I try and play the note in other places, it usually feels out of place.
Can anyone explain to me why this sounds good here? Or did I make any wrong assumptions, or am I merely overanalyzing now?
Comment: Mark Knopfler can't read music, so if you asked him personally, he'd probably just say "It sounds right to me". You are correct in your key, though - it is in G# minor.
Answer: There is no E# in the G# minor scale, but there is one in the D# minor scale. If you look at the chord that is being played, you'll see it's just a D# minor chord.
So I think the best way of viewing it is that you momentarily get a little glimpse of the key of D# minor (which is quite "near" to the G# minor since they differ only in one tone -- the E/E#) which is quickly ended by putting the VI chord (in G# minor) right next to it. In this case, it's the E major chord, and that makes it obvious that we're still in G# minor and we haven't moved anywhere.
(They could have easily done a modulation (i. e. a key change) to D# minor with this. If they hadn't followed with an E major chord, but with some chord that belongs to D# minor and not to G# minor (a super-simple example would be A#7), they would "hammered it home" and the move to D# minor would be finished. You may try that on your guitar: after playing the lick, just play an A#7 chord. You will see that it fits and it pulls you to the key of D# minor.)
You also mentioned that you couldn't find a good place for that E# (augmented 6th degree) in your playing. However, there is a scale that is called the Dorian mode and it is just a minor key with the 6th degree raised up a semitone. It gives a beautiful, characteristic sound that you have certainly heard before, because it's used a lot in movie or video game soundtracks. Just take your guitar and play these chords: E minor, A major, E minor, A major... I think you will certainly recognize that vibe. Once you connect it with the raised 6th degree, I think you will able to use it yourself in a way that sounds good.
Answer: The answer by Ramillies gives a lot of context about the major 6th and the Dorian mode. However, for a single note, played twice in just one bar, you could simply consider it an altered note. It's OK to play "wrong notes" that are not in the key you're playing in. It happens all the time in music, and it works fine as long as it's played in passing, as it's in this case.
As a side note, if you're stuck in your playing I can recommend what works for me. Set yourself some actionable, achievable goals. If you play the same songs over and over, you won't get any better, but if you say "I want to learn the 5 boxes of the minor pentatonic" or "I want to improve my timing when playing rythm" or "I want to learn how to mute strings when bending", you have goals that you can easily reach in a few weeks. Then you'll look back and you'll realize you've improved your playing. "I want to play like Mark Knopfler" is not a very actionable short-term goal goal ;) Good luck!
Comment: @leftaroundabout: Everything you say is correct: anyone can play any note at any time, and still, every note has an effect.  The reason "wrong notes are okay" keeps coming up is that music theory is often taught as rules, rather than guidelines.  Beginners and those who haven't developed their ears are tempted to always follow "the rules," such as don't ever play notes out of key.  Then their music sounds flat and boring... or at least lacking in personality.  The greats know how to bend/ break the rules (with "wrong" notes) in a way that sounds great, and unique.
Comment: @Casey that's one of the reason why it's actually good that beginners start by _sticking to the rules_: so that when they eventually get to break them, they'll be able to do it deliberately and with a _focused_ effect. Start right away with breaking each and every rule, and the result will just sound totally arbitrary and thus just as bland – perhaps with "personality", but not good. More typical however is for those who don't understand the rules to produce _more limited_ music, because they just discard anything that sounds unfamiliar rather than questioning what's actually going on.
Comment: @leftaroundabout you're absolutely right in your comment. It all depends on what level of learning you're at. I'm at the point where I'm starting to get the sounds I want by breaking out of the scale every so often. I still don't know exactly *what* I get when I break out of it, but it sounds better. Perhaps you're at the point where you can break out of it and say "oh, this was a bit of the Dorian mode there!". Unfortunately, I still cannot hear it. Also, I've heard this song so many times that I no longer hear "a change in character" in the lick... to me, it's the way it's supposed to sound.
Comment: @leftaroundabout at the end of the day I think we're saying the same things. It's OK to break out of the scale... and of course it's going to sound different! It's not the same to add a maj6 or adding a b9, it is going to add a different flavour. Nothing I said contradicts your statement :)
Comment: I have to say it certainly is an actionable long-term goal, because Mark Knopfler had a similar goal to play like JJ Cale, and he achieved it!  (Listen to Cale's playing and then listen to Knopfler, especially the earlier Dire Straits stuff.)  He picked up more country influences from his other idol Chet Atkins too. The key part to achieving it though is to be able to analyse each bit of what they're doing - and then set yourself those as short-term learning goals like you say.  With Mark Knopfler for example, it might be Travis picking, arpeggios, and volume control swells.
Comment: @leftaround I agree with you. We all come at music from a different place. I started with "too much theory" and too little listening (I guess that's what you get when a classically trained trombonist picks up the guitar).  My early compositions were guided by "the rules" more than my goals of the vibe/ emotion/ feel I was after. I'm probably a bit of an outlier (most aspiring guitarists probably don't have a failed symphony composition under their belts), but I found the "break the rules" to be very helpful. Maybe the full advice should be: "learn the rules... then break them, on purpose."
Comment: Thanks for your addition and advice, much appreciated :)
Comment: I don't know why people keep making these "wrong notes are ok" remarks. –Yes, it's "ok" to play any note in music, at any point... in the sense of, _it's art, anything is ok_. You can also play this song but hammer in a distorted G powerchord on the 4 beat of every bar. But that doesn't mean it won't have a certain effect; every note does. And that E♯ there most definitely does change the character of the lick in a significant way, even though it's just a passing note.
Comment: I have aded a "short-term" edit to my answer. Knopfler has been heavily influenced by Cale; however, in "trying to sound like Cale", Knopfler ended up building a very distinct and personal style that's immediately recognizable. In that case, you could say that he "failed" in his long-term goal, to the delight of many of us :)
Answer: The chord behind the lick is in D# minor. If he played an E, however, that would be a b9 over the chord- just a half step above the root. It's a cool sound that is used extensively in jazz and classical but not much in rock. It's pretty high in terms of dissonance.
Instead, he uses the E# -- or F -- the natural 9 of the D# chord, which is much more consonant.
Another way to think about it is as the Dorian mode of G#. It has the natural 6  of the scale as opposed to the b6 in the minor/aeolian mode.

E# in Brothers in Arms by Dire Straits