Survival Analysis results are counter intuitive, where am I going wrong?

Question: I am using Survival Analysis to analyse a data set, but i'm having a bit of trouble.
The data consists of everyone who has/has not been terminated from employment within a 4 year period. The aim of the analysis is to uncover the median time to termination.
The data includes 400 people who has experienced the event and 2275 people who have not.
Looking at the raw data, 150 people have remained employed between 30-48 years.
The remaining 2525 people have been employed for less than 30 years.
The average time spent working in the organisation is 4 years.
However, the median time to survival using survival analysis is 40 years.
I'm very familiar with the organisation and this median time to leaving is counter intuitive. Am I missing something?
My code is below
You will see, I start by calculating the length of time from when they began working in the organisation and when they leave (variable name is 'yrs'). If they have not been terminated, today's date is used as they are still employed in the organisation (perhaps this is where i'm going wrong?).
Then I create a survival curve using 'yrs' and 'termid', where termid is an indicator variable, indicating if the observation has been terminated or not.
The median survival time of 40 years is then returned
Is there an issue with my code? Or is it expected that so few observations could carry this much weight in a Survival Analysis.
#find survival time #calculating the number of days between last follow up date and date of starting in the organisation
leaversanalysis = leaversanalysis %>%
  mutate(
    yrs =
      as.numeric(
        difftime(Term.Date,
                 Date.Joined.Organisation,
                 units = "days")) / 365.25
  )

#Indicator variable for termination is 'termid'
#Kaplan Meier estimator for any termination (termination =1, no termination =0)
a <- Surv(leaversanalysis$yrs, leaversanalysis$termid)

#Create survival curve
surv_curvleave <- survfit(Surv(yrs, termid) ~ 1 , data = leaversanalysis)
surv_curvleave

Answer: Median survival here is the time at which 50% of your participants would still be non-terminated.
The lower the risk (hazard) of an event (in your case being "terminated"), the longer it will take to get to the point where 50% of participants have had that event.
An example:
simulate data similar to yours:
set.seed(129)
yrs1 <- round(rbeta(n=2225, shape1 = 1.3, shape2 = 8)*48,1)
yrs2 <- runif(450, min=0, max=48)
yrs <- c(yrs1,yrs2)
termid <- sample(x = c(rep(1, each = 400), rep(0,each=2275)), size = 2675)
data <- data.frame(yrs,termid)
sum(yrs>30) # 167 people employed over 30 yrs
hist(yrs, breaks = 20)

Your code is fine. The survival plot below should reveal why the "median survival" is what it is.
fit <- survfit(Surv(yrs,termid) ~1, data = data)
plot(fit, xlab = "years", ylab = "probability of not being terminated")
abline(h=0.5); abline(v=43.3)
fit

Call: survfit(formula = Surv(yrs, termid) ~ 1, data = data)

      n  events  median 0.95LCL 0.95UCL
 2675.0   400.0    43.3    40.1    46.2

The reported median survival here is 43.3 years.
You have said "this median time to leaving is counter intuitive". What you are studying is the median time to being terminated. If people are leaving for other reasons, then using these methods, they are censored, and so do not affect the position of the survival curve.
Answer: The name of the statistic "median survival time" can be a bit misleading - the median survival time of a population is not simply the median of survival times. That is, you can't simply take all the tenure lengths, find the median one, and be done. This is because many people leave for other reasons than being fired, so they drop out of the population (they are censored). If a person leaves voluntarily after 1 year, you know they would have survived at least 1 year without termination, but you can't use that 1 year as a data point for time-to-termination itself. In a population where no one is fired, you never reach median survival, but you will always be able to find a median of tenure times (which isn't nearly as useful).
Rather, the median survival time is the time at which 50% of the uncensored population remains. You note that in your data, you have 400 people who were terminated, and 2275 who were not - only 15% of the population is ever terminated, so it makes sense that you either never see a time when 50% of your workforce has been fired, or see it only very late (when the remaining population is small). It would be possible to see this earlier on, as you could have 1875 people quit over the years, leaving 800 people, 400 of which are later fired. But that would require a very unusual skewing of voluntary quitting in the beginning, followed by a rash of firings at the end. In a population where the overall event rate is well below 50%, you typically won't hit median survival, barring unusual patterns in early censors and late events. Your median survival time is very long, which suggests there are only a handful of people who remain after a 40-year tenure, and half of them get fired.


Design Refactoring

Question: I am designing a System where the following scanario arise.
I have a method f1() for which behavior varies across implementation.
I have a method f2() for which behavior is same for all implementations.
I have designed as following:
interface I1
{
        //Behaviour will vary across implementations
        void f1();
        //Same behaviour for all implementations
        void f2();

 }

    abstract class C
    {
        //Implemented in the Base class
        void f2()
        {

        }
    }

    public class C1:C,I1
    {
        //Implemented interface method
        public f1()
        {

        }

    }
    public class C2:C,I1
    {
        //Implemented  interface method
        public f1()
        {

        }

    }

Is the design is correct? Can anybody suggest any appropriate design in this sceanario ?
Comment: Looks just swell. Of course we can't tell without context, but this would work for the descriptions in the comment...
Comment: http://blogs.msdn.com/b/mhop/archive/2006/12/12/implicit-and-explicit-interface-implementations.aspx   Check this link out. I think it will help you.
Comment: If the classes have to inherit from `C` to get `f2()`, why have the interface? Have you also considered implementing `f2()` as an extension method, as opposed to declaring it on the interface?
Answer: You should create just one abstract class with methods f1() and f2() as follows:
abstract class A
{
    public abstract f1();
    protected void f2()
    {
    }
}

class B : A
{
    public override void f1()
    {
    }
}

Now whenever you create an class based upon A, they can specify their own behavior for method f1().
Answer: An alternative is to use a strategy pattern:
public interface IF1Strategy
{
   void f1();
}

public sealed class C : I1
{
    private readonly IF1Strategy _f1Strategy;

    //strategy injected
    public C(IF1Strategy strategy)
    {
       _f1Strategy = strategy;
    }

    void f2()
    {
    }

    void f1()
    {
       //delegated to strategy
       _f1Strategy.f1();
    }
}

NB: Only suitable if your f1 strategy implementors do not need to call f2.
Advantages:

You can inject the appropriate strategy.
You can unit test strategies on their own.
Class C can change independant of the others i.e. that saves you maintaining a class heirachy. Note how I have sealed it.

In short, I am choosing Composition over inheritance
Answer: I am following OOPs design principle along with strategy pattern to provide a good solution for your problem.
these are the principle i follow:
1. Favor composition over inheritance.
2. Program to interface not implementation,
  public interface I1VariedBehavior
{
    void f1(); // Varies for the implementation.
}
public abstract class I1SameBehavior
{

    public void f2()
    {
        Console.WriteLine("f2 same behavior");
    }
}
public class F1Impl1 : I1VariedBehavior
{
    public void f1() // f1 is own implementation
    {
        Console.WriteLine("F1 own implementation 1");
    }
}
public class F1Impl2 : I1VariedBehavior
{
    public void f1() // f1 is own implementation
    {
        Console.WriteLine("F1 own implementation 2");
    }
}
public class C1 : I1SameBehavior
{
    I1VariedBehavior strategy;
    public C1(I1VariedBehavior strategy)
    {
        this.strategy = strategy;
    }
    public void f1()
    {
        strategy.f1();
    }
}

public class Client
{
    public static void Main(String[] args)
    {
        C1 c1 = new C1(new F1Impl1());
        c1.f1();
        c1.f2();

        C1 c2 = new C1(new F1Impl2());
        c2.f1();
        c2.f2();
        Console.Read();
    }
}

output:
F1 own implementation 1
f2 same behavior
F1 own implementation 2
f2 same behavior

hope that helps.

Design Refactoring


Restore back-up from pre-encrypted drive into newly encrypted drive

Question: It sounds like I am going to be reinstalling CentOS 7 on a server this weekend.
The original installation didn't have the drive encrypted and it needs to be done. My understanding is that this will require a reformat so was going to back-up with rsync to a USB drive and restore after the fresh install and the drive being encrypted.
Is this permitted? Just wasn't sure if CentOS will allow a complete back-up from a un-encrypted file system to restored to an encrypted one.
Answer: CentOS doesn't care what the source media you are reading your backups from is as long as it can read it.


Contest Math Question: simplifying logarithm expression further

Question: I am working on AoPS Vol. 2 exercises in Chapter 1 and attempting to solve the below problem:

Given that $\log_{4n} 40\sqrt{3} = \log_{3n} 45$, find $n^3$ (MA$\Theta$ 1991).

My approach is to isolate $n$ and then cube it. Observe:
\begin{align*}
\frac{\log 40\sqrt{3}}{\log 4n} = \frac{\log 45}{\log 3n} \\
\log 40\sqrt{3}\log 3n = \log 45\log 4n\\
\log 40\sqrt{3} \cdot (\log 3 + \log n) = \log 45 \cdot (\log 4 + \log n)\\
\log n \cdot (\log 40\sqrt{3} - \log 45) =  \log 45\log 4 - \log 40\sqrt{3}\log 3
\end{align*}
Dividing through and putting the coefficients as powers, we have:
\begin{align*}
\log n &= \frac{\log 45^{\log 4} - \log \left[(40\sqrt{3})^{\log 3}\right]}{\log\left(\frac{40\sqrt{3}}{45}\right)}
=\frac{\log \left(\frac{45^{\log 4}}{(40\sqrt{3})^{\log 3}}\right) }{\log\left(\frac{40\sqrt{3}}{45}\right)} \\
&=\log \left(\frac{45^{\log 4}}{(40\sqrt{3})^{\log 3}}\right)^{\log\left(\frac{40\sqrt{3}}{45}\right)^{-1}}
\end{align*}
which shows that
\begin{align*}
n^3 = \left(\frac{45^{\log 4}}{(40\sqrt{3})^{\log 3}}\right)^{3\cdot\log\left(\frac{40\sqrt{3}}{45}\right)^{-1}}
\end{align*}
Somehow it feels like this answer may be simplified further. Are the steps shown so far correct and can the answer be expressed in a better way?
Comment: At the stage where you've written $\log n\cdot\text{this}=\text{that}$, re-write $\text{this}$ and $\text{that}$ in terms of logs of primes.
Answer: I would go the following way.
You have :
$$\begin{align}&\log_{4n} 40\sqrt{3} = \log_{3n} 45\\
\implies &\log_{4n} \left(3\cdot 40^2\right) = \log_{3n} 45^2=k
\end{align}$$
This leads to :
$$\begin{align}&\begin{cases}(4n)^k=3\cdot 40^2\\
(3n)^k=45^2 \end{cases}\\
\implies &\left(\frac 43\right)^k=\frac {3\cdot 40^2}{45^2}=\left(\frac {4}{3}\right)^3\\
\implies &k=3\\
\implies &n^3=\frac {45^2}{3^3}=75\thinspace.\end{align}$$
Answer: $\displaystyle\frac{\ln(40\sqrt{3})}{\ln(4n)} = \frac{\ln(45)}{\ln(3n)}$
$\displaystyle \frac{\ln(3n)}{\ln(4n)}
= \frac{\ln(45)}{\ln(40\sqrt{3})} × \frac{k}{k}
= \frac{\ln(45^k)}{\ln[(40\sqrt{3})^k]}$
Find k, such that ratio inside ln/ln matched
$\displaystyle \frac{3n}{4n} = \left(\frac{45}{40\sqrt{3}}\right)^k = \left(\frac{3}{4}\right)^{3k/2}$
$→ k = \frac{2}{3}$
$3\,n = 45^{2/3}$
$27\,n^3 = 45^2$
$n^3 = 75$
Comment: If ln(3n)/ln(4n) = ln(3m)/ln(4m), it implied n=m.  Unless you meant arithmetic: 45/(40√3) = (3√3)/8 = (3/4)^(3/2)
Comment: It is not ratio ln(a)/ln(b), it is ratio a/b
Answer: Alternative approach:
Let $~r~$ denote $\displaystyle \log_{4n} 40\sqrt{3}.$
Then
$$(4n)^r = 40\sqrt{3}, ~~(3n)^r = 45 \implies $$
$$\left[\frac{4}{3}\right]^r = \left[\frac{4n}{3n}\right]^r = \frac{40\sqrt{3}}{45} = \frac{8\sqrt{3}}{9} \implies $$
$$9 \times 4^r = 8\sqrt{3} \times 3^r \implies $$
$$\frac{2^{2r}}{8} = \frac{\sqrt{3} \times 3^r}{9} \implies $$
$$2^{2r - 3} = 3^{r - (3/2)} = \sqrt{3}^{2r-3}. \tag1 $$
The only way that this is possible is if $(2r - 3) = 0 \implies r = (3/2).$
Checking this candidate value for $r$ gives
$$4^{3/2} \times n^{3/2} = 40\sqrt{3} \implies n^{3/2} = 5\sqrt{3}.$$
Checking this further,
$$3^{3/2} \times 5\sqrt{3}$$
does in fact equal $45$.
So, the sole candidate value for $r$, works.
Therefore,
$$n^{3/2} = 5\sqrt{3} \implies n^3 = \left[5\sqrt{3}\right]^2 = 75.$$
Answer: We could also take a "factorization" approach.  Since
$$ \log_{4n} 40\sqrt{3} \ \ =  \ \ \log_{3n} 45 \ \ = \ \ \alpha \ \ , $$
we can write
$$ (4n)^\alpha \ \ = \ \ 2^3·3^{1/2}·5 \ \ \ , \ \ \ (3n)^\alpha \ \ = \ \ 3^2·5 $$ $$  \Rightarrow \ \ n^\alpha \ \ = \ \ 2^{3 \ - \ 2·\alpha}·3^{1/2}·5 \ \ = \ \ (2^0)·3^{2 \ - \ \alpha}·5 \ \ .  $$
The "primes-raised-to-powers" in each of these factorizations need to "match", so we have
$$ 3 \ - \ 2·\alpha \ \ = \ \ 0 \ \ \ , \ \ \ \frac12 \ \ = \ \ 2 \ - \ \alpha \ \ , $$
both of which tell us that $ \ \alpha \ = \ \frac32 \ \ . $
Thus, we have $$ n^3 \ \ = \ \ (n^\alpha)^2 \ \ = \ \ (2^{3 \ - \ 2·\alpha}·3^{1/2}·5)^2 $$ $$ = \ \ 2^{6 \ - \ 4·\alpha}·3·25 \ \ = \ \ 2^{6 \ - \ 4·[3/2]}·3·25 \ \ = \ \ 2^0·75 $$
or
$$ n^3 \ \ = \ \   3^{4 \ - \ 2·\alpha}·5^2 \ \ = \ \ 3^{4 \ - \ 2·[3/2]}·25 \ \ = \ \ 3·25 \ \ . $$
[Since this problem has so few "moving parts", the posted answers end up being variations on the same concept.]
Answer: In this answer, we provide another method that uses the definition and basic properties of logarithm.
The original equation states :
$$
\begin{align}&\log_{4n}{40}\sqrt{3}=\log_{3n}{45}\\
\implies &{40}\sqrt 3=\left(4n\right)^{\log_{3n}45}\\
&\thinspace\thinspace\thinspace\thinspace \thinspace\thinspace\thinspace \thinspace\thinspace\thinspace \thinspace\thinspace\thinspace \thinspace=\left(3n\cdot \frac 43\right)^{\log_{3n}{45}}\\
&\thinspace\thinspace\thinspace\thinspace \thinspace\thinspace\thinspace \thinspace\thinspace\thinspace \thinspace\thinspace\thinspace \thinspace=45\cdot \left(\frac 43\right)^{\log_{3n}{45}}\end{align}
$$
This leads to the following :
$$
\begin{align}\left(\frac {2}{\sqrt 3}\right)^{2\log_{3n}{45}}&=\frac {40\sqrt 3}{45}=\left(\frac {2}{\sqrt 3}\right)^3\end{align}
$$
Finally, again using the definition of logarithm, we get the desired result:
$$
\begin{align}&\log_{3n}{45^2}=3\\
\implies &n^3=\frac {45^2}{3^3}=75\thinspace .\end{align}
$$
Comment: For the readers : We assume that, the downvote is *not* about mathematical content.


Almost sure convergence of $\sqrt n$-truncated variables

Question: Let $X_i$ be i.i.d. nonnegative random variables such that $E[X_1]<\infty$.
Is is true that
$$m_n:=\frac 1n \sum_{i=1}^n X_i1_{\{X_i \geq \sqrt n\}}$$
converges almost surely to $0$ ?
Since $$E\left[X_i1_{\{X_i \geq \sqrt n\}}\right] = E\left[X_11_{\{X_1 \geq \sqrt n\}}\right] \overset{n\to\infty}{\longrightarrow} 0$$ it is immediate that $m_n$ converges in $L^1$ to $0$, hence in probability as well.
Since $X_i$ has finite first moment, I know that $P(X_i \geq \sqrt n) = o(1/\sqrt n)$.
Answer: Let $R$ be a fixed integer; for each $n\geqslant R$,
$$
0\leqslant m_n\leqslant\frac 1n\sum_{i=1}^nX_i\mathbf{1}_{\left\{X_i\geqslant \sqrt R\right\}}
$$
hence by the strong law of large numbers, the following inequality takes place almost surely:
$$0\leqslant
\limsup_{n\to\infty}m_n\leqslant\mathbb E\left[X_1
\mathbf{1}_{\left\{X_1\geqslant \sqrt R\right\}}\right].
$$
Since $R$ is arbitrary, we can conclude.
Note that it would also work if we replace $m_n$ by $m'_n$ defined by
$$
m'_n=\frac 1n\sum_{i=1}^nX_i\mathbf{1}_{\left\{X_i\geqslant R_n\right\}}
$$
where $\left(R_n\right)_{n\geqslant 1}$ is a sequence of positive numbers such that $R_n\to\infty$, that is, $m'_n\to 0$ almost surely.
Comment: For fixed $R$, the convergence $\frac 1n\sum_{i=1}^nX_i\mathbf{1}_{\left\{X_i\geqslant \sqrt R\right\}}$ to the mean happens on a set $\Omega_R$ of probability $1$ and the inequality $$0\leqslant
\limsup_{n\to\infty}m_n\leqslant\mathbb E\left[X_1
\mathbf{1}_{\left\{X_1\geqslant \sqrt R\right\}}\right]$$ holds only $\Omega_R$. One should consider $\bigcap_{R\geq 1} \Omega_R$, which still has probability $1$. On this smaller set we have $$\forall R\geq 1, \quad 0\leqslant
\limsup_{n\to\infty}m_n\leqslant\mathbb E\left[X_1
\mathbf{1}_{\left\{X_1\geqslant \sqrt R\right\}}\right].$$


No authorization header was received in any of the requests made to fullfilment URL

Question: I have successfully linked my home automation platform with Google Assistant through OAuth2. The user signs into our platform via Google Home App and completes OAuth flow. After completing account linking, the Google Assistant makes a request to my fulfillment URL to sync devices with 'action.devices.SYNC' intent.
But there is no authorization token received in any of the requests to my platform from Google Assistant. How can I identify the requesting user? Where can I find the auth token?
Answer: Sorry for answering my own question. After few web search, I found that Apache is blocking Authorization header by default. I enabled it by placing WSGIPassAuthorization On in my config file.


How to concatenate short and char array using strcat in C

Question: I have a short type variable X which I wanna concatenate with char[] type of variable Y. I tried itoa function but I guess that function is not available to me.So is there any other simple option like strcat(Y,X)?
[Additional Info]
I know I can use sprintf() but I need to pass the final output to some Oracle in-built function and I don't know if sprintf() can give me string or char[] as an output.
Comment: @Jim: A short is not necessarily 2 bytes long.
Comment: If X is a short, you can use a union to pull out the two chars.
Comment: char[] is a string, or do you mean string as an oracle built-in type. Anyway, the result obtained from sprintf is char[]
Comment: Name a common system where it isn't.
Answer: You can use sprintf:
sprintf(Z, "%s%d", Y, X);

Comment: or without `Z`: `sprintf(Y+strlen(Y), "%d", X);`


Can a player protest injured reserve status?

Question: ESPN is stating that the Jets may put Mark Sanchez on injured reserve instead of cutting him if they decide to replace him. He has a large guaranteed contract and cutting him is a large salary cap hit.
Sanchez clearly does not have a season ending injury. My understanding is that the player has to clear waivers before he can be put on injured reserve, but that isn't a lot of protection, no team has cap space left at the start of the season.
So can a team arbitrarily decide to put you on injured reserve no matter what?
Comment: I'd actually first ask whether the CBA permits placing an uninjured player on IR at all.
Comment: that is a good question, but there is also 'how injured'. If you can reasonably come back in a few weeks,but the team doesn't want to reserve the roster spot, it looks like the team can decide to put you on IR. I also think some players who are going to be cut get played on 'season ending IR' at the end of training camp. This is probably with their ok, since they still get paid, but I don't know for sure.
Answer: A player is consulted with before designated to I.R.  They could have a long fingernail and be put on I.R. as long as both sides agree.
A player can file a grievance if they feel they are not injured.  From there the player would have to pass a physical by league.  The team would have to reinstate player, move player to practice squad or cut player.
If the player gets moved to practice squad every team has the ability to pick them up if they will move the player to their starting roster.  Some teams put players on I.R. vs cutting player simply to make sure no one else can use him.
Now if a team cuts a player, they might have salary cap or contract issues to face.  If the player has guaranteed money it will all go to next year's cap.  The player might also have guarantees on annual compensation.  So then you would be cutting someone you will pay fully anyways.  You might want the player around to see how he looks during rehab.  Last thing you want is to have a need at his position and wonder what he was doing the past 8 months.
Also a few other things to consider.  When a team cuts a player, they may lose overall good will in the league.  No one (agents too) wants to sign a contract with a small bonus knowing that this team likes to cut players.  So the move could potentially cost the team.
Another factor is that if a player was hurt, no matter how small, and they are cut then there are usually some legal issues.  Basically the two sides have to come together for an injury settlement.  This happens a few times a year at least but pushes bad will out on both sides.  The team looks like they are casting off the injured and the player looks bad for collecting money for no play.
The truth is IR is a bit of a joke.  The new rule allowing for a couple of short term IR exceptions helped but IR still is a joke.  Some rosters are loaded.  So teams that want to keep a players rights throw them on IR - player agrees so he doesn't get cut.  It is kind of like a redshirt year.  Also on really bad teams you might have little to no depth at a position.  Well you can only have so many inactives...  well now a guy out for 4-5 weeks is gone all year.
The rules were put in place - short inactive list, 53 man roster, IR rules - so that teams couldn't hoard borderline players and so that talent was better dispersed.   To a point the rules might help a little but IR is used more for circumvention.


Is it possible to abandon/abort a RadAjaxRequest that is still processing when a new request is made?

Question: I've got a C# web application that presents the user with reports, occasionaly the reports take in the neighbourhood of several minutes to generate (instead of a few seconds).
I have a RadTreeView of "ReportType" links, when clicked executes a RadAjaxRequest using the RadAjaxManager from the client-side.
function RadTreeviewNodeClicked(sender, eventArgs) {
            try {
                console.log("fired again: " + eventArgs.get_node().get_text());
                var radAjaxManager = $find("<%= RadAjaxManager.GetCurrent(Page).ClientID %>");
                radAjaxManager.ajaxRequest("NodeClicked");
            } catch (error) {
                console.log("error on nodeclicked");
            }
        }

 //from my pageload
 radAjaxManager1 = RadAjaxManager.GetCurrent(Page);
 radAjaxManager1.AjaxRequest += RadAjaxManager1_AjaxRequest;
 radAjaxManager1.ResponseScripts.Add("AttachJQueryUIDateTimePickers();");
 radAjaxManager1.AjaxSettings.AddAjaxSetting(radAjaxManager1,pnlRightContent,RadAjaxLoadingPanel1);
 radAjaxManager1.ClientEvents.OnResponseEnd = "ResponseEnd";

The ajaxRequest handler on the server loads up the appropriate report for the link that was clicked and displays it on the right hand side in an asp:panel.   The menu and panel are both wrapped in a RadAjaxPanel.
If the report data is still loading (the stored procedure is executing) and a user clicks another link:

the client event is triggered
the server finishes the first event
the respondeEnd event is fired
the server starts processing the 2nd event

I would like to abandon/abort the first event when a subsequent event is clicked.  Is this possible?
Answer: I figured out it's possible with Telerik, by setting the Queue Size of the rad Ajax Manager to 0:
        radAjaxManager1.RequestQueueSize = 0;

Comment: My page had RadAjaxManagerProxy, didn't see the property there.  I found it on RadAjaxPanel I was using, but setting it to 0 didn't cancel the ajax request for me.  It still seems to still wait for it to come back before it processes my redirect


What's your angle?

Question:
One needs to get it right.
What I have tried: can do it (see my comment below), would like a simpler solution.   Will post a complete solution after a while.
Any constructive feedback would be appreciated!

$\bf{Added:}$ My attempt, using trigonometry.
The projections of the top and bottom vertices on the horizontal diagonal  divide it in ratios $\frac{\tan 10^{\circ}}{\tan 20^{\circ}}$, and $\frac{\tan 30^{\circ}}{\tan 50^{\circ}}$. So let's show that these ratios are equal, equivalently
$$\tan 10^{\circ} = \tan 20^{\circ} \tan 30^{\circ} \tan 40^{\circ}$$
The equation $\tan x = \tan 2x \tan 3x \tan 4x$ appears in some high school math journal in the 60's.
Write $\tan x = \frac{e^{i x} - e^{-i x}}{i(e^{i x} + e^{ix})} = \frac{z^2-1}{i(z^2+1)}$, so, with $f(z) = \frac{z^2-1}{z^2+1}$ we need to solve
$$f(z)+ f(z^2) f(z^3) f(z^4)=0$$
The LHS factors as
$$\frac{2 (z-1)(z+1) (z^{12}-z^6+1)}{(z^2+1) (z^4-z^2+1) (z^8+1)}$$
and now notice that $z=e^{\frac{2\pi i}{36}}$ is a root of the cyclotomic polynomial $\Phi_{36}(z) = z^{12}-z^6+1$.
Conclusion: the ratios are equal, the top and bottom vertices project onto the same point of the diagonal, and therefore, the diagonals are perpendicular.

A geometric proof would be nice to have.
$\bf{Added:}$
@timon92: brought  this post to my attention. @Andrew Hwang had an intepretation almost identical to this question; should undelete his answer.

Disclosure:  discovered this cute question by accident/luck, while playing with Geogebra some 15 years ago.  Now the question itself  has to do with  adventitious quadrilaterals, specifically those with orthogonal diagonals, a classic subject.  Yes, there are some other ones.
Comment: @peterwhy: right angle $\iff \frac{\tan 10^{\circ}}{{\tan 20^{\circ}}}=\frac{\tan 30^{\circ}}{{\tan 50^{\circ}}}$, and Bob's your uncle
Comment: What is one allowed to do?  Either it is or it is not a right angle and there's nothing you can do to make it or prevent it from being so.  As a question, .... it isn't a question.
Comment: see here: https://math.stackexchange.com/questions/1624651/what-is-the-geometry-behind-frac-tan-10-circ-tan-20-circ-frac-tan-30
Comment: What's the question?
Comment: @Brian Tung: the question is about geometry. Got a proof using trig, would like an alternate proof, preferably with geometry.
Comment: @orangeskid: Thanks for the context! I'll give it some thought; I like the problem. I might recommend that you put some of this clarification in the title and/or further up in the post. The title is not informative, and the first few paragraphs do not make it clear (to me, at least) what you desire.
Comment: @Misha Lavrov: the problem is, one needs to get a right angle
Comment: @fleablood: by any means
Comment: If you want to find the values of the "outside" angles so that the 4 "inner" angles are right, then use the [property](https://m.youtube.com/watch?v=WrssQ8q3pTU) of right triangles having complementary angles
Comment: @timon92: Interesting! Andy Hwang had a very similar interpretation, should have not deleted his answer.  The equality itself is older than most of us here. So is your proof purely geometric then? If I get to reopen maybe you can re-adapt it for this.
Comment: Are you just looking for a proof of $\frac{\tan 10^{\circ}}{{\tan 20^{\circ}}}=\frac{\tan 30^{\circ}}{{\tan 50^{\circ}}}$? If not, can you please clarify? This is rather unclear.
Comment: Note that Andrew Huang's answer in the linked question is not a proof; it is just a pictorial depiction of the equality (which is all that question asked for).
Answer:
Consider two equilateral triangles ( in red) with a common vertex, one rotation of the other by $40^{\circ}$.  There are formed two isosceles triangles with base angles $40^{\circ}$ (equal sides in blue). Now draw the perpendicular bisector of one of the equilateral triangle ( in yellow). We get another isosceles triangle with base angle $40^{\circ}$. Now conclude that we have an isosceles triangle with base angle $70^{\circ}$.  The purple quadrilateral has the required shape.

What's your angle?


How to recalculate uploaded files' sizes in KB and update the values in the database?

Question: I use a shell command to look for all uploaded JPEG files above 500 K.B. (originals) and do JPEG compression on them. They get smaller in size, but Drupal still shows the originally uploaded file size. How to force a recalculation and update the database accordingly after JPEG optimization?
Answer: In Drupal 7 managed files have their filesize property updated upon saving in the file_save() function. So you can just load/save each resized files to have it updated in the DB accordingly.
//@TODO: Get list of $fids corresponding to resized-files
foreach ($fids as $fid) {
  $file = file_load($fid);
  // $file->filesize reflects old size
  file_save($file);
  // $file->filesize now reflects new size
}


Checking for duplicate strings in JavaScript array

Question: I have JS array with strings, for example:
var strArray = [ "q", "w", "w", "e", "i", "u", "r"];

I need to compare for duplicate strings inside array, and if duplicate string exists, there should be alert box pointing to that string.
I was trying to compare it with for loop, but I don't know how to write code so that array checks its own strings for duplicates, without already pre-determined string to compare.
Comment: Consecutive duplicates, or duplicates of any sort? If you threw another 'q' in there at the end, should that count as a duplicate or not?
Comment: Duplicates of any sort. It can be in in the middle of the array, or at the end of the array, or any other combination.
Comment: In my tests, the **fastest** method is [**this one**](https://stackoverflow.com/a/56094764/8112776).
Comment: @ashleedawg in what tests? The array [2,3,4,1,1, ...] where the dots are an array of many elements, should run significantly slower than the hash map as it needs to pass through the full array 4 times in the example above, while a map of values and using `in` would only go through the array once
Answer: The findDuplicates function (below) compares index of all items in array with index of first occurrence of same item. If indexes are not same returns it as duplicate.

let strArray = [ "q", "w", "w", "w", "e", "i", "i", "u", "r"];
let findDuplicates = arr => arr.filter((item, index) => arr.indexOf(item) !== index)

console.log(findDuplicates(strArray)) // All duplicates
console.log([...new Set(findDuplicates(strArray))]) // Unique duplicates
Comment: Note the [time complexity](https://www.bigocheatsheet.com/) here. Looping inside of a loop: O(n^2). Doesn't really matter unless the array is MASSIVE or you're doing this MANY times on a server. But when it matters, it really matters. [`kshetline's` answer](https://stackoverflow.com/a/49215482/99717) performs better at O(n). BUT, that answer trades time for space (the object map), so watch out for that too :)
Comment: This reminds of those old competitions to write the most obfuscated C code possible.
Answer: Using ES6 features

Because each value in the Set has to be unique, the value equality will be checked.

function checkIfDuplicateExists(arr) {
    return new Set(arr).size !== arr.length
}

var arr = ["a", "a", "b", "c"];
var arr1 = ["a", "b", "c"];

console.log(checkIfDuplicateExists(arr)); // true
console.log(checkIfDuplicateExists(arr1)); // false
Answer:

    var strArray = [ "q", "w", "w", "e", "i", "u", "r", "q"];
    var alreadySeen = {};

    strArray.forEach(function(str) {
      if (alreadySeen[str])
        console.log(str);
      else
        alreadySeen[str] = true;
    });

I added another duplicate in there from your original just to show it would find a non-consecutive duplicate.
Updated version with arrow function:

const strArray = [ "q", "w", "w", "e", "i", "u", "r", "q"];
const alreadySeen = {};

strArray.forEach(str => alreadySeen[str] ? console.log(str) : alreadySeen[str] = true);
Comment: @BenClarke, no, because a push word add `str` as an element of the array, whereas `alreadySeen[str] = true` adds `str` as an index of the array, using the array as a hash table. A `Set` object could be used here instead, perhaps with greater clarity.
Comment: This solution works great, too! Thanks.
Shame I can't accept (green checkmark) your answer also.
Comment: Nice one. This particular logic easily allows for "Any" behavior (that is, I can short-circuit the loop when I find that there is any duplicate).
Comment: Can I clarify something please? Does the above expression `alreadySeen[str] = true` just add that `str` item to the `alreadySeen` array? Is it the same as `alreadySeen.push(str)`?
Comment: @kshetline Ok thank you for clarifying. That's a bit too advanced for me though :) Is that method called anything in particular? I'd like to learn more about it
Comment: It is considered bad practice to use arrays to store key-value pairs in Javascript (See https://stackoverflow.com/a/874237/5263954). Better to use `alreadySeen = {}` instead.
Comment: @René K, good point.
Answer: You could take a Set and filter to the values that have already been seen.

var array = ["q", "w", "w", "e", "i", "u", "r"],
    seen = array.filter((s => v => s.has(v) || !s.add(v))(new Set));

console.log(seen);
Answer: Using some function on arrays:
If any item in the array has an index number from the beginning is not equals to index number from the end, then this item exists in the array more than once.
// vanilla js
function hasDuplicates(arr) {
    return arr.some( function(item) {
        return arr.indexOf(item) !== arr.lastIndexOf(item);
    });
}

Comment: Hi, your function is what I need (return only a boolean) but I don't know ES6, can you write it in "simple" javascript please ?
Answer:

function hasDuplicates(arr) {
    var counts = [];

    for (var i = 0; i <= arr.length; i++) {
        if (counts[arr[i]] === undefined) {
            counts[arr[i]] = 1;
        } else {
            return true;
        }
    }
    return false;
}

// [...]

var arr = [1, 1, 2, 3, 4];

if (hasDuplicates(arr)) {
  alert('Error: you have duplicates values !')
}

Simple Javascript (if you don't know ES6)
function hasDuplicates(arr) {
    var counts = [];

    for (var i = 0; i <= arr.length; i++) {
        if (counts[arr[i]] === undefined) {
            counts[arr[i]] = 1;
        } else {
            return true;
        }
    }
    return false;
}

// [...]

var arr = [1, 1, 2, 3, 4];

if (hasDuplicates(arr)) {
  alert('Error: you have duplicates values !')
}

Answer: function hasDuplicateString(strings: string[]): boolean {
    const table: { [key: string]: boolean} = {}
    for (let string of strings) {
        if (string in table) return true;
        table[string] = true;
    }
    return false
}

Here the in operator is generally considered to be an 0(1) time lookup, since it's a hash table lookup.
Comment: Yeap this should be the most performant answer
Answer:    var elems = ['f', 'a','b','f', 'c','d','e','f','c'];

    elems.sort();

    elems.forEach(function (value, index, arr){

        let first_index = arr.indexOf(value);
        let last_index = arr.lastIndexOf(value);

         if(first_index !== last_index){

         console.log('Duplicate item in array ' + value);

         }else{

         console.log('unique items in array ' + value);

         }

    });

Answer: You have to create an empty array then check each element of the given array if the new array already has the element it will alert you.
Something like this.
  var strArray = [ "q", "w", "w", "e", "i", "u", "r"];
  let newArray =[];
  function check(arr){
  for(let elements of arr){
  if(newArray.includes(elements)){
  alert(elements)
  }
 else{
 newArray.push(elements);
 }
 }
 return newArray.sort();
  }
check(strArray);

Answer: Use object keys for good performance when you work with a big array (in that case, loop for each element and loop again to check duplicate will be very slowly).
var strArray = ["q", "w", "w", "e", "i", "u", "r"];

var counting = {};
strArray.forEach(function (str) {
    counting[str] = (counting[str] || 0) + 1;
});

if (Object.keys(counting).length !== strArray.length) {
    console.log("Has duplicates");

    var str;
    for (str in counting) {
        if (counting.hasOwnProperty(str)) {
            if (counting[str] > 1) {
                console.log(str + " appears " + counting[str] + " times");
            }
        }
    }
}

Answer: This is the simplest solution I guess :
function diffArray(arr1, arr2) {
  return arr1
    .concat(arr2)
    .filter(item => !arr1.includes(item) || !arr2.includes(item));
}

Answer:  const isDuplicate = (str) =>{
   return new Set(str.split("")).size === str.length;
}

Comment: Can you explain *why* this works? Since this question is rather old, it's a good idea to clearly articulate why it is useful.
Comment: The above method is a predicate method which means is only returning boolean value. Since set take only unique value, I split the string to array of character then I parse the array of  character to the set constructor for removing any duplicate character. Which mean if duplicate exist in the character array, the set will contain on the unique ones, after that I compare the length of the original string against the set size. If the length are the same it means no duplicate else it  means there is.
Answer: You could use reduce:
const arr = ["q", "w", "w", "e", "i", "u", "r"]
arr.reduce((acc, cur) => {
  if(acc[cur]) {
    acc.duplicates.push(cur)
  } else {
    acc[cur] = true //anything could go here
  }
}, { duplicates: [] })

Result would look like this:
{ ...Non Duplicate Values, duplicates: ["w"] }

That way you can do whatever you want with the duplicate values!


How to respond to "NOTICE: Not enabling PHP 7.4 FPM by default." from system upgrade

Question: I did a standard OS update on Ubuntu LTS (20.04) and the messages end with:
Processing triggers for php7.4-fpm (7.4.3-4ubuntu2.6) ...
NOTICE: Not enabling PHP 7.4 FPM by default.
NOTICE: To enable PHP 7.4 FPM in Apache2 do:
NOTICE: a2enmod proxy_fcgi setenvif
NOTICE: a2enconf php7.4-fpm
NOTICE: You are seeing this message because you have apache2 package installed.

Yes, I am using Apache2. How do I decide whether I want to run those commands to enable PHP 7.4?
Answer: If you want to use PHP-fpm you run
a2enmod proxy_fcgi setenvif and
a2enconf php7.4-fpm
If you are asking why you should install it, it is better to install it if you want to have less overload on your system, have extra security, and want to configure every aspect of PHP. I use it on my website and it works very well!
I would suggest installing it.


Analogy between MPNNs and GCNs?

Question: I'm currently trying to understand graph neural networks and got stuck with comparing MPNN and GCN. In my understanding, MPNN is more of a "general framework", while GCN is a specific "instantiation" of that framework. Accordingly, a GCN can be seen as a type of MPNN.
Now, a MPNN always consists of a message function, an aggregation function and an update function.

The message function is a function from the feature vectors x_i and x_j, as well as the connecting edge e_ij to a new, potentially differently shaped feature vector m_i.
The aggregation function is a function from an arbitrary-sized set of such (latent) feature vectors to a single one (call it u_i).
The update function is a function from a node's own feature vector x_i and the aggregated "upstream" features u_i to the node's new state h_i.

Is that correct so far?
If yes, what would be each of these three functions specifically in the case of a GCN?
In addition, I've read that a GCN cannot handle variable graph structures, i.e. graphs with different number of nodes / edges. I assume this is because the GCN's propagation rule formula has the adjacency matrix in it, which is fixed-size? And then, why / how can a MPNN, instead, deal with different input graphs?
I would be super thankful if somebody could help me sort out these questions!
Answer: Yeah I think the problem is that the MPNN paper, introduce both the general framework as well as their own MPNN, which is a little bit cofusing. Generally speaking tho, you only have message function and a vertex update function. Lastly, you have a readout function that aggregates the information on the whole graph using the information on individual nodes.
In the paper the message function and update function of the GCN is rewritten as:

Lastly, I am not sure what you mean by variable graph structure. But a GCN can handle graphs of different sizes. You can easily see, by looking at the Matrixmulitplications, that the dimensions of adjacency matrix is not important for the multiplication to "work". The only important part, is that you use a good aggregation function in the Readout phase.
Comment: Thanks a lot! Only a few follow-up questions in addtion:

(1) The aggregation, in the case of GCNs, is a simple sum, correct?

(2) What potential limitations / disadvantages does a GCN have over an MPNN?

(3) How would you go about incorporating edge-level features as well, in addition to node features? How would the equations for message- and update functions and the matrices' dimensions change accordingly?
Comment: One more question in addition: in that excerpt you posted above, the update function does not take into account a node's own features, does it? So after one step of message passing, a node's own feature vector is "overwritten" entirely by the aggregated states of its neighbors?
Answer: Yeah you can find the derivation with the self-loops in the Message-Passing Paper as well. Here the A is including self-loops. So adding just the Identity matrix to the Adjacency.

I am note sure, which "aggregation" you are referring to. However, in the GCN the message function computes a weighted mean across all neighbouring nodes. In the original publication the mean is used as a read out function. Generally, speaking the mean is not considered to be a good aggregation function, both on node level as well as the graph level. The choice of aggregation determines which substructures can be differentiated by:
In the paper on Principal Neighborhood aggregation this graphic displays it very well.

Analogy between MPNNs and GCNs?


Error when install Wordpress with mariadb "Your PHP installation appears to be missing the MySQL extension which is required by WordPress."

Question: rpm -e --nodeps mysql-libs
yum install MariaDB-server

The above command helped me to install mariadb, also installed Wordpress.  This was a great help. My problem now is when I reboot the server or restart apache here is the error:
"Your PHP installation appears to be missing the MySQL extension which is required by WordPress."

How can I solve this problem?
Answer: You need to install php-mysql so that PHP could connect to a MySQL/MariaDB instance. Do this by
yum install php-mysql

Comment: I install mariadb without erasing php_mysql and mysql libs. actually I already installed wordpress and create a site but when I restart the httpd the  error occurs
Comment: is this a bug for combining php, mariadb, apache and wordpress. here is my situation: I have a server running with php and mysql, for me to install the mariadb you need to remove mysql-server.

yum remove mysql-server

after removing mysql-server I run this

rpm -e --nodeps mysql-libs

To prevent php_mysql and mysql libs from deletion/conflicts during installation of mariadb

after  that I successfully insyall mariadb and able to install wordpress but if I restart the appache the error occured

"Your PHP installation appears to be missing the MySQL extension which is required by WordPress."
Answer: My solution was to reinstall php and php related packages.
yum remove php*
yum install epel-release

You must find the packages for your specific php version. In this example it's PHP 5.6
yum install php56w php56w-common

You may want as well to reinstall other packages depending on your requirements; listing a few here:
yum install php56w-mysqlnd php56w-pdo php56w-opcache php56w-mbstring php56w-gd php56w-dom php56w-pear php56w-soap

For example you can find a list of packages for PHP 5.6 here https://webtatic.com/packages/php56/#sapis
; or list available packages using yum list available 'php56w-*'
Restart your server: systemctl restart httpd.service


Pointers on how to perform a Monte Carlo Analysis

Question: Im looking for some pointers on how to perform a Monte Carlo simulation. Say im conducting a survey of how late flights are for a certain airline. I amass 1000 records, and plot a cumulative sum of these values. I want to determine how likely it is to have several flights grouped together that a decrease in the cumulative sum would exceed X%. Would i
1) calculate the mean and standard deviation of this sample, use these to generate multiple samples, and record the probability of such a decrease?
2) take the original sample, shuffle it, and then select values from it (without replacement), and record the probability of such a decrease?
Comment: By cumulative sum do you mean rolling some with a period of k (eg the sum of the last 20 flights late times)?  Otherwise I don't see how it can decrease unless some flights come in early ie have negative "late" times - which way is it?
Comment: Yeah there can be positive and negative times. Cumulative in the sense that the values would be 1,4,7,-3,2,-3,... and the cumulative sum values would be 1,5,12,9,11,8,...
Answer: Both approaches need some modification.  If you do the first, in order to generate multiple samples from the mean and standard deviation you need to make assumptions about the distribution eg that it is Normal.  The approach will work (if your distributional assumption is sound), but adds little or nothing to traditional methods.  Only use it if you are satisfied you can characterise the distribution of times well - and this is highly unlikely to be a Normal distribution (Gamma is more likely) so you need the techiques to fit a non-normal distribution.
The second approach makes better use of the information contained in the empirical distribution of your sample, but it won't work unless your selection of values is done with replacement (rather than without replacement).  If you select without replacement you will just end up with your original sample of n once you have selected all n values from it.
The second approach is a form of the bootstrap, and I would encourage you to read some of the voluminous material available.
In both cases you need to assume that there is no information in the ordering of the times - for example, that one flight being late doesn't make the next flight late too.  If this isn't the case, you will need an alternative approach.
Comment: If each resample is the same size as the original it will give you a sense of the distribution that can be expected to apply to the original, so usually it's best to have the same size or possibly one less.
Comment: 1000 is plenty in most straightforward situations, but it depends on the complexity of the test statistic/s you create (particularly if you want to observe how often a rare coincidence of events takes place).  You don't want the answer to depend on how many replications you do.  10,000 should be stacks...
Comment: It sounds as though bootstrapping (second approach) is probably what im looking for. I originally thought it might be possible to use the binomial distribution but im assuming that would only be applicable for a sequence of X late planes in a sample rather than the decrease in the sum of the values.
Comment: How large should each sample be (ie how many times do i select values from the original sample)? How many time should i repeat this process? just lookin for a rule of thumb. Thanks for taking the time to answer my question, i really appreciate it.
Comment: How many times would u resample? 10 or 20k? Thanks for ur help.


JavaScript: Instantiating a class from a JSON array

Question: I have a TestComplete (UI testing) project which uses JavaScript, and I'm trying to store class references in JSON. It seems that my code isn't working, so I might have a conceptual misunderstanding of how JavaScript handles class references in JSON. Here's code which demonstrates my line of thinking:
class MyClass {
  constructor() {
    this.name = "ClassName";
  }
}

function print_name(str_name) {
  console.log(str_name);
}

let my_json = {
    "keyOne": [
        MyClass
    ]
};

let class_ref = my_json["keyOne"][0];
print_name(class_ref.name);

Is there a reason why the print_name function would fail to print the "name" property of the MyClass object?
Comment: No, an actual instance: `"keyOne": [ new MyClass() ]`
Comment: Where are you actually using JSON? You're just using a JavaScript object. JSON can't hold functions.
Comment: You have to create an instance of the class...
Comment: let class_ref = my_json["keyOne"][0];
Answer: Short Answer : Yes there is a reason for that
and the correct code should like this
let my_json = {
"keyOne": [
    new MyClass()
    ]
};

why ?
because you should store an instance of the class not the class itself
and to do that in Javascript we use the new key word followed by the constructor function
BTW if you check this code
typeof MyClass

in the console you will get  function
but its a new syntax comes with the ES2015 a new version of Javascript that make working with a lot of things easier
and your code is the same as
function MyClass(){
this.name = "ClassName";
}

so this acts as a blueprint and to create an object you should use the new key word followed by the constructor
like this
let mySimpleClass = new MyClass();

now if you console
mySimpleClass.name
you will git ClassName
note:- if you want to convert your my_json variable to actual Json
use this
JSON.stringify(my_json);

learn more :
Working with Javascript Objects
JSON.stringify()


Entity vs taxonomy vs content type?

Question: I am setting a website up that will house multiple language schools, so I am mainly dealing with:
Individual language schools
Language courses
I set up a content type called 'Schools' and have fields on this that are unique to a specific school, example:

School Name
School Location
Tel no and contact details
Description of school

I then used entities for these things that are also unique to a school but there are quite a few of them, so I thought I'd be better with entities, then use inline reference entity fields on the school nodes (is this correct?):

Types of accommodation
Activities
Facilities
Image Gallery

Now I have come onto adding courses, there is generally a theme for these at the top level such as: 'Intensive English' then each school has various classes, so you mght have 'Intensive English' MORNING or 'Intensive English' EVENING. Now I don't want to create taxonomies for this classes as I'll have URLs that don't have anything on them, I'd have a table with the various classes in it. But the whole website needs to be searchable.
My question is, what do I need to do for courses? I used entities but now can't create a view that shows the nodes referencing the schools nodes and place it on the taxonomy parent: General English, Intensive English etc. Anyone got an pointers on what I should do and if I have set this up correctly?
I am struggling to create a view that shows a course page and then the schools that offer it, despite creating a reference to it, as in the image. Tried everything with contextual and relationships.
Comment: Hello,  are we talking about Drupal 7 or Drupal 8 ?
Comment: You can disable access to taxonomy paths with a module like Rabbit Hole. https://www.drupal.org/project/rabbit_hole
Comment: @OlegVidenov - this is Drupal 7, sorry for not saying.
Answer: You're right, something that is a 'descriptor' or category is best left as Taxonomy (i.e. Time > Morning/Afternoon/Evening) where they are used to enrich the meaning of data.

Now I don't want to create taxonomies for this classes as I'll have URLs that don't have anything on them

If access to taxonomy paths is a concern, you can install the Rabbit Hole module to disable access to it while preserving the functionality of taxonomy behind the scenes.
You can also use other modules like Taxonomy Views Integrator to 'change' the way taxonomy paths behave. In this modules case, you can display a View on these paths instead of the default page callback for taxonomy. The View can be anything you'd like.
Otherwise, if you attempt to create a custom table to store this data, you will need to use the appropriate hooks in the Views API to describe the table and it's data, and how it relates - which can be a lot of work. In the end, it sounds like you'd wind up duplicating taxonomy current functionality.
Comment: Thanks for the info. If I stick with what I have now: School as content type node, courses as entities, I can't seem to create a view which shows the course page, with the schools that provide this course. I added a entity reference field to my entity that references the school node, as you can see, but I can't work out how to do a view as mentioned.
Comment: Rabbit Hole simply doesn't work, whichever setting I put it onto, if I go use an incognito browser, the page simply shows up. Strange.
Comment: Works for me. Are you sure it is a term page and not already controlled by a view?
Comment: I used it on a content type. Tried each setting, it still shows.

Entity vs taxonomy vs content type?


Equivalence Relation - $\forall f,g \in W : fLg \iff \lim_{x \to {\infty}}f(x) = \lim_{x \to {\infty}}g(x)$

Question: There is $W=\left\{ f:(0,\infty) \to \mathbb R | \lim_{x \to \infty} exists\right\}$
Equivalence relation L :
$\forall f,g \in W : fLg \iff \lim_{x \to {\infty}}f(x) = \lim_{x \to {\infty}}g(x)$
$1.$ Prove every relation class has the same cardinality and what it is.
$2.$ Find cardinality $W/L$
My solution:
$1.$ I know that for every real number a there exists a sequence $r_n$ of rational numbers such that $r_n$ approaches a.
I dont know how to deal with it from here.
$2.$ There are $\mathfrak{c}$ real numbers so $|W/L|=\mathfrak{c}$
I'd be grateful for your help!
Comment: are the functions continuous?
Comment: ok two hints: first every equivalence class must have the same cardinality since if $(x_n)\rightarrow a$ then $(x_n+a)\rightarrow b+a$ (this will help you find a bijection between equivalence classes) then notice the correspondece between an equivalence class an the limit
Comment: Its not specified.
Answer: First, note that $|\{f : (0, \infty) \to \mathbb{R}\}| = |\mathbb{R}|^{|(0, \infty)|} = (2^{\aleph_0})^{2^{\aleph_0}} = 2^{\aleph_0 \times 2^{\aleph_0}} = 2^{\max(\aleph_0, 2^{\aleph_0})} = 2^{2^{\aleph_0}} = \beth_2$. This provides an upper bound on the cardinality of an equivalence class.
Secondly, consider the equivalence class which converges to a fixed number $c$ - call this class $C$. Consider the following function $g : \{f : (0, 1) \to \mathbb{R}\} \to C$ defined by
$$g(f)(x) = \begin{cases}
  f(x) & x \in (0, 1) \\
  c    & otherwise
\end{cases}$$
Clearly, $g$ is injective. Thus, $|C| \geq |\{f : (0, 1) \to \mathbb{R}\}| = \beth_2$.
Thus, $|C| = \beth_2 = 2^{\frak c}$, where ${\frak c} = 2^{\aleph_0} = |\mathbb{R}|$.
Your solution for part 2 is correct.
Comment: Thank you ! but$ |C| \geq |\{f : (0, 1) \to \mathbb{R}\}| \geq \frak c^2 = \frak c$ , no ?
Comment: @erez I mean, it is technically true that $|C| \geq {\frak c}^2$. It's just not relevant. $|\{f : (0, 1) \to \mathbb{R}\}| = |\{f : (0, \infty \to \mathbb{R}\}| = \beth_2$.


Delete rest and reflow rest of score in MuseScore

Question: I have a large MuseScore document from the internet that has a lot of time changes. About six hundred measures in (halfway through), there is a minor error: an extra beat of rest. This throws off the alignment of the rest of the piece — every single subsequent bar is off. I need to delete the extra rest and move the entire rest of the score one beat backward.
Is this possible, or am I up a creek?
Answer: To move everything back one beat: select from the first note after the extra beat rest to the end.   Ctrl-X.    Ctrl-C one beat earlier.
To delete the extra beat from the time-flow: select the extra beat rest, Ctrl-Delete.
Comment: Thanks! There were a lot of messed-up tuplets that made this fail at first, but once I fixed those it worked perfectly.


Limit $\lim_{n→∞}\frac1n\sum_{j=c_n}^n\frac1{2n-2j+1}\sum_{k=1}^jk\prod_{i=k}^{j-1}\frac{2n-2i}{2n-2i+1}. $

Question: If $c_n/n\to c>0$ as $n\to\infty$ (At the beginning of this question, I though the assumption is $c_n\to c$. With the help of metamorphy, the question will be ill-posed. So, the assumption has changed to the current one.), I would like to find$$\lim_{n→∞}\frac1n\sum_{j=c_n}^n\frac1{2n-2j+1}\sum_{k=1}^jk\prod_{i=k}^{j-1}\frac{2n-2i}{2n-2i+1}.
$$
Let $A_n=\sum_{j=c_n}^n\frac1{2n-2j+1}\sum_{k=1}^jk\prod_{i=k}^{j-1}\frac{2n-2i}{2n-2i+1}$. Noting that
$$
\prod_{i=k}^{j-1}\frac{2n-2i}{2n-2i+1}=\frac{2n-2j+1}{2n-2k+1}\frac{(-1)^{n-j}{-1/2\choose n-j}}{(-1)^{n-k}{-1/2\choose n-k}},
$$
we have
\begin{align*}
&A_n\\
=&\sum_{j=c_n}^{n}\sum_{k=1}^{j}\frac{k(-1)^{n-j}{-1/2\choose n-j}}{(2n-2k+1)(-1)^{n-k}{-1/2\choose n-k}}\\
=&\sum_{k=1}^{c_n-1}\sum_{j=c_n}^{n}\frac{k(-1)^{n-j}{-1/2\choose n-j}}{(2n-2k+1)(-1)^{n-k}{-1/2\choose n-k}}+\sum_{k=c_n}^{n}\sum_{j=k}^{n}\frac{k(-1)^{n-j}{-1/2\choose n-j}}{(2n-2k+1)(-1)^{n-k}{-1/2\choose n-k}}\\
=&\sum_{k=1}^{c_n-1}\frac{k}{(2n-2k+1)(-1)^{n-k}{-1/2\choose n-k}}\sum_{j=c_n}^{n}(-1)^{n-j}{-1/2\choose n-j}+\sum_{k=c_n}^{n}\frac{k}{(2n-2k+1)(-1)^{n-k}{-1/2\choose n-k}}\sum_{j=k}^{n}(-1)^{n-j}{-1/2\choose n-j}\\
=&\sum_{k=n-c_n+1}^{n-1}\frac{n-k}{(2k+1)(-1)^{k}{-1/2\choose k}}\sum_{j=0}^{n-c_n}(-1)^{j}{-1/2\choose j}+\sum_{k=0}^{n-c_n}\frac{n-k}{(2k+1)(-1)^{k}{-1/2\choose k}}\sum_{j=0}^{k}(-1)^{j}{-1/2\choose j}\\
=&\sum_{k=n-c_n+1}^{n-1}\frac{n-k}{(2k+1)(-1)^{k}{-1/2\choose k}}(2n-2c_n+1)(-1)^{n-c_n}{-1/2\choose n-c_n}+\sum_{k=0}^{n-c_n}\frac{n-k}{(2k+1)(-1)^{k}{-1/2\choose k}}(2k+1)(-1)^{k}{-1/2\choose k}\\
=&(-1)^{n-c_n}(2n-2c_n+1){-1/2\choose n-c_n}\sum_{k=n-c_n+1}^{n-1}\frac{n-k}{(2k+1)(-1)^{k}{-1/2\choose k}}+\frac{n(n+1)-c_n(c_n-1)}{2},
\end{align*}
where the third-to-last equality follows since $\sum_{u=0}^{a}(-1)^{u}{-1/2\choose u}=(-1)^{a}(2a+1){-1/2\choose a}$.
Is it possible to give a further closed form of $A_n$? And find the limit of $A_n/n$ (expresses it in terms of $c$)? Please give me some help. Thanks you very much.
Comment: Could you please give me some hints?
Comment: I don't know how to deal with the product term. I really need your proof, please. Thank you very much.
Comment: By some simple algebra, I found that $\prod_{i=k}^{j-1}\frac{2n-2i}{2n-2i+1}=\frac{2n-2j+1}{2n-2k+1}2^{2(j-k)}\frac{{2n-2j\choose n-j}}{{2n-2k\choose n-k}}$. But, I still cannot obtain (n+1)/2 as you got.
Comment: Ready. See my answer.
Comment: Many thanks. You are very good at dealing with these things.
Comment: The new version must have $\frac{1}{n^2}$ in place of $\frac{1}{n}$ for the limit to exist. I'm still analysing it...
Comment: I very much appreciate your help. This is just one term in my problem. I have tried to investigate the problem in a different approach and may cause a different task to tackle, hopefully.
Answer: [outdated, should be unaccepted and deleted]
Comment: I have added a few sentences to thank your help.
Comment: I haven't learned double factorial before. You are really good at this technique!!! I learned from you. Thanks.
Comment: I made a mistake that the assumption should be $c_n/n\to c$ as $n\to\infty$. In this case, $A_n$ seems not to have a closed form.
Answer: Now we assume that $c_n\to c$ as $n\to\infty$. I am not familiar with double factorial, but I tried to follow your approach (using the identify ${{2k\choose k}}/2^{2k}=(-1)^{k}{{-1/2\choose k}}$ implying that
\begin{align*}
\prod_{i=k}^{j-1}\frac{2n-2i}{2n-2i+1}&=\frac{2n-2j+1}{2n-2k+1}2^{2(j-k)}\frac{{2n-2j\choose n-j}}{{2n-2k\choose n-k}}\\
&=\frac{2n-2j+1}{2n-2k+1}\frac{(-1)^{n-j}{{-1/2\choose n-j}}}{(-1)^{n-k}{{-1/2\choose n-k}}}
\end{align*}
)
and I obtained that (by switching the summations and changing the variables)
$A_n=\alpha_n+\beta_n$ where
$$
\alpha_n=\frac{(-1)^{n-c_n}(2n-2c_n+1){{-1/2\choose n-c_n}}}{n}\sum_{k=n-c_n+1}^{n-1}\frac{n-k}{(2k+1)(-1)^{k}{{-1/2\choose k}}}
$$
and
$$
\beta_n=\frac{n(n+1)-c_n(c_n-1)}{2n}.
$$
Is it possible to simplify $A_n$ further so as to find the limit?
Comment: I suggest you to *amend* the question (rather than post it as an "answer"). And, of course, I'll look at that (since I called the original formulation "ill-posed", I expected some adjustments to appear).


Call to a member function bundle() on null in Drupal\Core\Entity\Plugin\Condition\EntityBundle->evaluate()

Question: I have a dev site built on Drupal 9.1.9 and now I'm trying to use the site in 9.3.9. Everything is fully functional on 9.1.9 but when I try to run the same site on 9.3.9 I get. I believe the error is being generated from the context module somehow and I tried disabling each context rule and am still facing the error.
The website encountered an unexpected error. Please try again later.
Error: Call to a member function bundle() on null in Drupal\Core\Entity\Plugin\Condition\EntityBundle->evaluate() (line 93 of core/lib/Drupal/Core/Entity/Plugin/Condition/EntityBundle.php).

Drupal\Core\Entity\Plugin\Condition\EntityBundle->evaluate() (Line: 77)
Drupal\Core\Condition\ConditionManager->execute(Object) (Line: 84)
Drupal\Core\Condition\ConditionPluginBase->execute() (Line: 26)
Drupal\context\ContextManager->resolveConditions(Object, 'or') (Line: 352)
Drupal\context\ContextManager->evaluateContextConditions(Object) (Line: 254)
Drupal\context\ContextManager->evaluateContexts() (Line: 242)
Drupal\context\ContextManager->getActiveContexts() (Line: 274)
Drupal\context\ContextManager->getActiveReactions() (Line: 44)
Drupal\context\EventSubscriber\BlockPageDisplayVariantSubscriber->onSelectPageDisplayVariant(Object, 'render.page_display_variant.select', Object)
call_user_func(Array, Object, 'render.page_display_variant.select', Object) (Line: 142)
Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher->dispatch(Object, 'render.page_display_variant.select') (Line: 224)
Drupal\Core\Render\MainContent\HtmlRenderer->prepare(Array, Object, Object) (Line: 132)
Drupal\Core\Render\MainContent\HtmlRenderer->renderResponse(Array, Object, Object) (Line: 90)
Drupal\Core\EventSubscriber\MainContentViewSubscriber->onViewRenderArray(Object, 'kernel.view', Object)
call_user_func(Array, Object, 'kernel.view', Object) (Line: 142)
Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher->dispatch(Object, 'kernel.view') (Line: 163)
Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1) (Line: 80)
Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1) (Line: 58)
Drupal\Core\StackMiddleware\Session->handle(Object, 1, 1) (Line: 48)
Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object, 1, 1) (Line: 106)
Drupal\page_cache\StackMiddleware\PageCache->pass(Object, 1, 1) (Line: 85)
Drupal\page_cache\StackMiddleware\PageCache->handle(Object, 1, 1) (Line: 50)
Drupal\ban\BanMiddleware->handle(Object, 1, 1) (Line: 48)
Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1, 1) (Line: 51)
Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1, 1) (Line: 23)
Stack\StackedHttpKernel->handle(Object, 1, 1) (Line: 708)
Drupal\Core\DrupalKernel->handle(Object) (Line: 19)

core/lib/Drupal/Core/Entity/Plugin/Condition/EntityBundle.php
Once, I made changes to evaluate function by providing if condition on the $entity, then it works as expected. I'm not confident that this approach is the correct way to fix the issue here.

public function evaluate() {
    // Returns true if no bundles are selected and negate option is disabled.
    if (empty($this->configuration['bundles']) && !$this->isNegated()) {
      return TRUE;
    }
    /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
    $entity = $this->getContextValue($this->getDerivativeId());
    //var_dump($entity); die();
    if($entity){
      return !empty($this->configuration['bundles'][$entity->bundle()]);
    }
  }

Should I be looking for the patches here or is there any way I can debug what's causing this error? Any advice would be highly appreciated.
Comment: First, check that your modules are up-to-date, that you have run all database updates, and that you have rebuilt the caches.  Then, if you are still having trouble, try switching to the dev branch of Context.  Don't start looking for patches or hacking the code until you are absolutely sure you have updated things properly.
Answer: The generic entity bundle condition was introduced in Drupal 9.3. See the change record https://www.drupal.org/node/2983299
This error is usually caused by a context mapping in config. This can also happen in the standard block layout without the context module.
What is the entity type if you var_dump $this->getDerivativeId()? This could lead to a context rule like in this issue https://www.drupal.org/project/context/issues/3260611
Comment: `var_dump($this->getDerivativeId(), $entity); ` provides `string(13) "taxonomy_term" NULL ` output. Now, I'm just looking a  way to find out which entity doesn't have taxonomy term. Is there any way to pinpoint the cause
Comment: Export the configuration (via UI or drush cex) and look for a context rule containing the condition `entity_bundle:taxonomy_term`. Then add the context mapping according to the linked issue and import the config again.


What is the difference between Visualization and BI Visualization?

Question: I am currently doing visualization on my project and I need to know whether the visualization I have done is BI visualization or not.
So is there any difference between Visualization and BI Visualization? If yes, then what are the differences?
Comment: A trivial answer is that much visualization is not aimed at business and as such can hardly be said to fall under that heading. A more interesting question is whether there are visualization methods that are distinct to business (data or audience). It is easy to guess that some methods are much more popular when aimed at business, but that doesn't seem a very deep point. All in all, it is hard to think that seeking a distinction serves very much purpose.
Comment: I guess that BI visualization means "Business Intelligence Visualization". Is this correct ? Is this really a fixed term / name (like K-Means) or just a description for "visualization used in Business Intelligence environment" ?
Comment: @steffen yea, it is `Business Intelligence Visualization`. I had heard a lot about `BI Visualization` and need to confirm whether there is any difference between visualization and BI Visualization.
Answer: BI is obsolete term used as marketing umbrella for various companies (like IBM, Oracle or SAP) to create illusion that they are relevant.
Data Visualization (DV) is a more specific and modern term: DV allowing users to see, explore, drilldown and interact with their data. It is a huge variety of DV vendors, but 3 of them are way ahead of others (Spotfire/TIBCO, Tableau, Qlikview/Qliktech) if you do not wish to do much coding and focus on your data and business problems.
However if you willing to do some own development, you can find some excellent SDKs on market (D3 as a leading example), which can enable you to do useful visualizations but it will require more of your time and reduce your overall productivity.
In any case Data Visualization cannot provide a complete solution to your analytical problems and needs to be used together with analytical tools like R.
Comment: highchart is a good tool and your question is very fuzzy. what you will do with answer? how it will help you? can you share your visualization and why you did it?
Answer: A lift chart (and the measurement of uplift in general) is a decent example of a business-centric visualization: they seem to be used mostly for marketing and related applications. I can imagine some non-business situations where a lift chart would be an effective tool, but I don't think I've ever come across one of them in the wild. To confirm this hunch, I took a quick look at the Google Image results for lift chart, and the first page seems business-y (the labels say "marketing campaign" or "customers" etc).
Nick Cox's comment on the question is apt. Some visualizations might not make sense in a business context (state space diagrams?). Others might be over-represented, either due to the subject matter or just by convention (e.g., some of these lift charts look suspiciously like ROC curves in disguise).
If you wondering whether visualization experience in general would qualify you for a BI Visualization job, I'd say yes, but you might want to poke around a bit to make sure you produce "idiomatic" charts that match your customer/client/employers' expectations.


Trabalhar com hora e minuto

Question: Gostaria de fazer um código que pegasse hora e minuto para que eu possa trabalhar com uma programação de horários para a execução de uma ação, exemplo:
var inserirProgramAtual = document.getElementById("CBNestudio");

    if ((new Date().getDay() > 0) && (new Date().getDay() < 6)) {
        if (new Date().getHours() >= 5 && new Date().getHours() <= 9) {
            inserirProgramAtual.innerHTML = `

        Jornal da manhã

    `
        } else if (new Date().getHours() >= 9 && (new Date().getHours() <= 10)) {
            inserirProgramAtual.innerHTML = `

        Programa qualquer

    `

Eu consegui pegar o horário normalmente, que é 9 horas, mas o que eu poderia fazer para pegar 30 minutos? Por exemplo, quero que às 9h10 ou 9h30 execute uma ação.
Comment: Neste caso, concordo com o Wictor que não está claro o que vc quer e como está fazendo. Por favor clique em **[edit]** e explique em mais detalhes o que vc quer fazer e o que quer dizer "não deu certo" (deu algum erro? o código se comportou de maneira inesperada? qual? etc). Em outras palavras, tente fazer um **[mcve]**
Comment: Não é só chamar `getMinutes`? https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Date/getMinutes
Comment: Por favor, explique de forma mais clara a sua dúvida.
Comment: Certo, dai o script iria ser acionado exatamente as 9:30. Quem iria ficar de olho no relógio e com dedo no botão do mouse para rodar o script no exato momento que  o horário marcar 9:30? Mais fácil fazer a condicional se a hora e minuto atual for maior que 9:30hs
Comment: Eu quero que a ação do código seja executado às 9h30, já tentei com getMinutes e não deu certo
Comment: Editei, caso ainda não ajude eu tento ser mais claro, desculpe a pergunta mal formulada.
Comment: Você esta pensando as informações de onde? E o que você quer fazer com esta informação?
Comment: O foco é a linha de código:
if (new Date().getHours() >= 5 && new Date().getHours() <= 9) {...}

Desejaria que o horário fosse 9:30, e não apenas 9:00 como o código já está fazendo.
Answer: Se for para somente não executar após o horário faça a verificação em duas etapas, conforme abaixo:

let dateTime = new Date();

if(dateTime.getHours() >= 5 && dateTime.getHours() <= 9){
 if(dateTime.getHours() === 9 && dateTime.getMinutes() >= 30){
    console.log('vai parar');
   return false
  }

  console.log('Continua...');
}

Agora se precisar disparar o script no horário exato, recomendo ver sobre o uso de cron job.

Trabalhar com hora e minuto


Implicit random variable value

Question: Wikipedia freely uses notation $P(Y|X)$, to usually mean $P(Y=y|X=x)$. Is there any other use of this notation (random variable within a PMF without mention of a particular value)? In other words, can I (mentally) insert the =value any time I see this sort of thing? Additionally, is this notation well accepted?
Answer: My feeling is that the things are exactly as you have described. In some cases people mean random events $A$ and $B$, not random variables, and there is no need to put something like $=...$. And when they mean random variables, I think it is very usuall to replace the strict notation $P(Y=y|X=x)$ with a frivolous $P(Y|X)$, if it does not lead to confusion. Personally I have never seen situations, when writing $P(Y|X)$ somebody assumed a random variable $P$, which is a function of $X$ and $Y$...

Implicit random variable value


using contextual filters to filter with relationship

Question: I have articles and issue nodes, where every article is related to an issue. I am trying to create a Views block which shows related Articles. This block should show on on the Article node page.
What I tried was this:
I created a view of Articles. I set the relationship to Entity Reference: Referenced Entity field_article_issue and created a contextual filter on field_article_issue_number (a field in issues) using that relationship. This didn't work, and the block shows nothing. What am I doing wrong?
Answer: You can't show both. When you choose to show articles,  vieuws will select articles from the database using your conditions. Since an issue is not an article, they will not show.
What you probably can do is embed another view in your views header or footer section and display the related issues in that view.
Comment: I edited my post above, I had written something incorrectly. I want to have a view of only Articles, not article. Does this change your answer?
Comment: Ah now I see, it was a block. A block is not capable of reading conditional filters from the url. Your conditional filter should include one of the default options that do work. For instance the `node id from url` option. Can you do anything with that?


How can I load custom font (ttf) with size more than 60kb

Question: I want to load custom font with size 150kb, but I it gets EXCEEDS_LIMIT error and in the code that below console prints "EXCEEDS_LIMIT", I tried to reduce the ttf size but I failed
Any Idea??
<code>    LabelField helloWorld = new LabelField("Hello World");
    int res = FontManager.getInstance().load("PageD1.TTf", "MyFont",
            FontManager.EXCEEDS_LIMIT);
    if (res == FontManager.SUCCESS) {
        try {
            FontFamily family = FontFamily.forName("MyFont");
            Font myFont = family.getFont(Font.PLAIN, 50);
            helloWorld.setFont(myFont);
        } catch (ClassNotFoundException e) {
            System.out.println(e.getMessage());
        }
    } else if (res == FontManager.EXCEEDS_LIMIT) {
        System.out.println("EXCEEDS_LIMIT");
    }

    add(helloWorld);
</code>
Answer: According to the documentation there is a limit in place of 60kb for OS 5.0. There is no way to work around this.
Under OS 6.0 the limit remains the  same, but under 7.0 it is raised to 6MB
Comment: Yes, I know this documentation, and unfortunately I currently develop for OS 5,6, any idea?
Comment: No, you really don't have any options.  I actually had to go so far as to create a custom bitmap font renderer for my app, allowing me to generate fonts of multiple sizes.  That's not practical for most situations though.


Linear functionals on the space of all square matrices

Question: Suppose $V$ is the vector space consisting of all $n \times n$ square matrices. How can we find the form of a linear functional on $V$ ?
Hofmann's book says (in exercise 8 of section 7 of chapter 3) that every functional on $V$ has the form ${\rm tr}(B^t A)$ for some matrix $B$.
Why? and how?
Answer: Let $E_{i,j}$ denote the matrix whose $(i,j)^{th}$ entry is 1, and all others are zero. Let $f_{i,j}$ denote the dual basis; then it suffices to prove this result for these $f_{i,j}$'s.
Consider $A = \sum a_{i,j} E_{i,j} \in V$, then
$$
f_{k,l}(A) = a_{k,l} = tr(E_{k,l}^t A)
$$
Answer: The vector space of square matrices of order $n$ is isomorphic to $\mathbb R^{n^2}$. This is directly followed by $\text{vec}$ operation which sends a matrix $A$ to a vector $\text{vec}(A)$. According to Riesz representation theorem, there exists a unique vector $v=\text{vec}(B)\in\mathbb R^{n^2}$ such that for any $u=\text{vec}A$, we have $$\left<u,v\right>=\sum_{k=1}^{n^2}u_kv_k=\sum_{i=1}^n\sum_{j=1}^nA_{ij}B_{ji}=\text{tr}B^TA$$
Answer: There's a more general result. Given a $\Bbb K-$vector space ($\Bbb K=\Bbb R$ or $\Bbb C$) $E$ and an inner product $\langle\cdot \mid \cdot \rangle:E\times E \to \Bbb K$, the homomorphism $$\varphi:\begin{matrix}E \to E^*=\mathcal F\left(E,\Bbb K\right)\\ x\mapsto \left(y\mapsto \langle x\mid y\rangle\right)\end{matrix}$$
is injective. In the case where $E$ is finite dimensional, $\dim E^*=\dim \mathcal F\left(E,\Bbb K\right)=\dim E \times \dim \Bbb K=\dim E \times 1 = \dim E$ so since $\varphi $ is injective, it is bijective.
Now in your case, $E=\mathcal M_n\left(\Bbb K\right)$ and $\langle x\mid y\rangle = \operatorname{tr}\left(^tB A\right)$.


Find the value of $\frac{1}{20} + \frac{1}{30} + \frac{1}{42} + \frac{1}{56} + \frac{1}{72} + \frac{1}{90}$

Question: Find the value of $p+q$, where $p$ and $q$ are two positive integers such that $p$ and $q$ have no common factor larger than $1$ and
$$\frac{1}{20} + \frac{1}{30} + \frac{1}{42} + \frac{1}{56} + \frac{1}{72} + \frac{1}{90} = \frac{p}{q}.$$
By using Wolfram Alpha, I obtain the sum is $\frac{3}{20}$. But I have no idea on how to obtain the sum.
Any hint would be appreaciated.
[The question is taken from SMO 2015 Junior section]
Comment: Well the standard way is to put them over a common denominater, add, and if nesc reduce.  Did you have trouble doing that?
Comment: "I obtain the sum is 3/20. But I have no idea on how to obtain the sum."  You don't know how to add 3 and 20?
Comment: @fleablood: I mean I don't know how to obtain the sum $3/20$, not the final answer.
Answer: We can observe that
\begin{align}
20&=4\cdot 5\\
30&=5\cdot6\\
42&=6\cdot7\\
56&=7\cdot8\\
72&=8\cdot9\\
90&=9\cdot10.
\end{align}
Can you use partial fraction?
Comment: Good observation, but I think it easier to see that the difference of two consecutive elements is increased by 2: $10, 12, 14, 16, 18...$, what indeed correspond to $(a)_2-(a-1)_2=2(a-1)$
Answer: We  know that
$$
S_n=\frac{1}{1 \cdot 2}+ \frac{1}{2 \cdot 3}+ \cdots+ \frac{1}{(n-1)n}=1-\frac{1}{n}
$$
Then yours sum is exactly $$S_{10}-S_4=(1-\frac{1}{10})-(1-\frac{1}{4})=\frac{1}{4}-\frac{1}{10}=\frac{5-2}{20}=\frac{3}{20}.$$
Answer: $1/20 + 1/30 + 1/42 + 1/56 + 1/72 + 1/90 = $
$1/4*5 + 1/5*6 + 1/6*7 + 1/7*8 + 1/8*9 + 1/9*10 = $
Note:  $\frac{1}{n(n+1)} + \frac{1}{(n +1)(n +2)} = \frac{n+2 + n}{n(n+1)(n+2} = \frac {2n + 1}{n(n+1)(n+2)} = \frac{2}{n(n+2)}$
And $\frac{k}{n(n+k)} + \frac{1}{(n+k)(n + k + 1)} = \frac{k(n + k + 1) + n}{n(n+k)(n + k + 1)} = \frac{(k + 1)n + (k+1)k}{n(n+k)(n+k + 1)} = \frac{k+1}{n(n+ k + 1)}$.
So...
$1/4*5 + 1/5*6 + 1/6*7 + 1/7*8 + 1/8*9 + 1/9*10 = $
$2/4*6 + 1/6*7 + 1/7*8 + 1/8*9 + 1/9*10 = $
$3/4*7 + 1/7*8 + 1/8*9 + 1/9*10 = $
$4/4*8 + 1/8*9 + 1/9*10 = $
$5/4*9 + 1/9*10 = $
$6/4*10 =  3/20 = p/q$
$p + q = 3 + 20 = 23$.


Apache Ignite and Spring Data - How to delete an entity?

Question: I am using Apache Ignite with Spring Data in Persistent Storage mode (ignite version 2.9.1 with spring data 2.2). Saving and reading Objects through the Spring Data Reposiory works fine. But when I try to delete an entity it get not removed from the storage altough when I try to use the repo.deleteById() method according to the ignite spring data documentation.
Any hints? Thank you
Remark 1: The repo.deleteAll() works fine.
Remark 2: The DELETE FROM Item where Id = x works fine with an SQL client.
Remark 3: I uploaded the example on github https://github.com/egloffmark/ignite-test/tree/master/ignite-test-map
Remark 4: I noticed that it seems to be related to the list which get obtained from the repo find method. It looks like that you can not iterate a second time through the same list? The following seems not to work:
        // query items
        log.info("first iteration, reading items...");
        Iterable<Item> items = itemRepo.findAll();
        // first iteration
        for(Item item : items) {
            log.info(item.toString());
        }

        // second iteration on same result object  <--- NOT WORKING !!!!
        log.info("2nd iteration,...");
        for(Item item : items) {
            log.info(item.toString());
        }

Output (first execution)
Started MyIgniteMapApplication in 4.437 seconds (JVM running for 4.673)
XXXXXXXXXXX  application started... XXXXXXXXXXX
Number of Items: 0
storing items...
1st iteration, reading items...
Item(id=1, name=Advanced Xtra Item, code=AIX-1, attributes={Price=3.9, Color=red})
Item(id=2, name=Advanced Hyper Item, code=AIX-2, attributes={Price=9.9, Color=blue})
Item(id=3, name=Advanced Biggest Item, code=AIX-3, attributes={Price=8.95, Color=pink})
2nd iteration,...
deleting items...
Number of Items: 3
XXXXXXXXXXX  application finished... XXXXXXXXXXX

Classes
Model Class
@Data
public class Item {

    private static final AtomicLong ID_GEN = new AtomicLong();

    @QuerySqlField(index = true)
    private Long id;

    @QuerySqlField
    public String name;

    @QuerySqlField
    public String code;

    public Item(Long id, String code, String name) {
        this.id = id;
        this.code = code;
        this.name = name;
    }

    public Item(String code, String name) {
        this(ID_GEN.incrementAndGet(),code, name);
    }
}

Repository
@RepositoryConfig(cacheName = "ItemCache")
public interface ItemIgniteRepository extends IgniteRepository<Item, Long> {
}

SpringBoot Application
@SpringBootApplication(scanBasePackages = { "com.ontius.ignite.config" })
@Slf4j
public class MyIgniteApplication implements CommandLineRunner {

    public static void main(String[] args) {
        SpringApplication.run(MyIgniteApplication.class, args);
    }

    @Autowired
    private ConfigurableApplicationContext applicationContext;

    @Autowired
    private ItemIgniteRepository itemRepo;

    @Override
    public void run(String... args) throws Exception {
        log.info("XXXXXXXXXXX  application started... XXXXXXXXXXX");

        long itemsCount = itemRepo.count();
        log.info("Number of Items: {}", itemsCount);
        if (itemsCount == 0) {

            // store some items
            Map<Long, Item> items = new TreeMap<Long,Item>();

            Item item = new Item("AIX-1","Advanced Xtra Item");
            items.put(item.getId(),item);

            item = new Item("AIX-2","Advanced Hyper Item");
            items.put(item.getId(),item);

            item = new Item("AIX-3","Advanced Ultra Item");
            items.put(item.getId(),item);
            log.info("storing items...");
            itemRepo.save(items);
        }

        // query items
        log.info("1st iteration, reading items...");
        Iterable<Item> items = itemRepo.findAll();
        // first iteration
        for(Item item : items) {
            log.info(item.toString());
        }

        // second iteration on same result object  <--- NOT WORKING !!!!
        log.info("2nd iteration,...");
        for(Item item : items) {
            log.info(item.toString());
        }

        // delete items <--- NOT WORKING !!!!
        log.info("deleting items...");
        for(Item item : items) {
            itemRepo.deleteById(item.getId());
        };
        itemsCount = itemRepo.count();
        log.info("Number of Items: {}", itemsCount);

        log.info("XXXXXXXXXXX  application finished... XXXXXXXXXXX");
        applicationContext.close();
    }
}

Comment: Can you post a complete runnable reproducer to e.g. github? I have trouble making it run, Spring Boot and all.
Comment: I uploaded the example to github https://github.com/egloffmark/ignite-test/tree/master/ignite-test-map
Comment: The Ignore docs you linked to says delete is not supported? I think you need to call `deleteAll(ids_to_delete)` version.
Comment: No the method ```deleteById()``` is working. The problem was another basic one, see below the answer.
Answer: The problem has nothing to do with the "deletion" or "ignite" itself. Instead that a spring data CrudRepository is returning a Iterable<T> by default which according the specification can only be consumed once.
public interface CrudRepository<T, ID> extends Repository<T, ID> {
 ...
    /**
     * Returns all instances of the type.
     *
     * @return all entities
     */
    Iterable<T> findAll();
}

A common solution forthis problem is to define its own "findAll" method in your Repository interface which return a list type instead e.g.
@RepositoryConfig(cacheName = "ItemCache")
public interface ItemIgniteRepository extends IgniteRepository<Item, Long>, CustomItemIngniteRepository {
   ...

    @Override
    public List<Item> findAll();

}

After that its work as expected. You can iterate a second time over the same result object.
Output
XXXXXXXXXXX  application started... XXXXXXXXXXX
Number of Items: 0
storing items...
1st iteration, reading items...
Item(id=1, name=Advanced Xtra Item, code=AIX-1, attributes={Price=3.9, Color=red})
Item(id=2, name=Advanced Hyper Item, code=AIX-2, attributes={Price=9.9, Color=blue})
Item(id=3, name=Advanced Biggest Item, code=AIX-3, attributes={Price=8.95, Color=pink})
2nd iteration,...
Item(id=1, name=Advanced Xtra Item, code=AIX-1, attributes={Price=3.9, Color=red})
Item(id=2, name=Advanced Hyper Item, code=AIX-2, attributes={Price=9.9, Color=blue})
Item(id=3, name=Advanced Biggest Item, code=AIX-3, attributes={Price=8.95, Color=pink})
deleting items...
item: Item(id=1, name=Advanced Xtra Item, code=AIX-1, attributes={Price=3.9, Color=red})
item: Item(id=2, name=Advanced Hyper Item, code=AIX-2, attributes={Price=9.9, Color=blue})
item: Item(id=3, name=Advanced Biggest Item, code=AIX-3, attributes={Price=8.95, Color=pink})
Number of Items: 0
XXXXXXXXXX  application finished... XXXXXXXXXXX


Color onclick TD red and the tds connected to it grey

Question: When I click on a TD I need to make the background color red, and the 4 td's connected to it need to get the background color grey.
When I click on a other TD the previous td's need to go white again and the new td has to color red and the others connected to it grey.
The right, left, above, and bottom of the RED TD need to get the color grey.
Also the previous clicked TD need to stay but when i click on another td the first one needs to go away.
This is what I already have:
HTML

Jquery
$('document').ready(function (){
    $('td').click(function (){
        var $this = $(this);
        var col = $this.index() + 1;
        var row = $this.closest('tr').index() + 1;

        $(this).css('background-color', 'red')
        $('p').text('Je zit nu in kolom ' + col + ' en in rij ' + row);
    })
});

Answer: So something like this

$('document').ready(function() {
  var $td = $('td').click(function() {
    if ($(this).hasClass('grey')) {
      alert("can't click");
    } else {
      var $this = $(this);
      var col = $this.index() + 1;
      var row = $this.closest('tr').index() + 1;

      $td.removeClass('red grey'); // set all td's color white

      $('tr:nth-child(' + (row - 1) + '),tr:nth-child(' + (row + 1) + ')')
        .find('td:nth-child(' + col + ')') // get the clicked column td's
        .addClass('grey');

      $(this).addClass('red') // set clicked td's color red
        .parent()
        .find('td:nth-child(' + (col - 1) + '),td:nth-child(' + (col + 1) + ')')
        .addClass('grey'); // set color to grey

      $('p').text('Je zit nu in kolom ' + col + ' en in rij ' + row);
    }
  })
});
td {
  width: 20px;
  height: 20px;
}
.grey {
  background-color: grey
}
.red {
  background-color: red
}

Comment: The TD's under, left, right, above the red TD need to get the color grey.
Comment: @KipVerslaafde you didn't make that clear in your question.
Comment: @PranavCBalan thanks, but i only need the first tds connected to it and not the whole rows. So only 4 other TDS need to color grey.
Comment: @PranavCBalan thanks, now i need to get when i click on a TD thats already grey i need to get a alert that i cant click on it
Answer: $('document').ready(function ()
{
    $('td').click(function ()
    {
        var row = $(this).closest('tr');

        $(row).find('td').css('background-color', 'grey');
        $(this).css('background-color', 'red');
    })
});

JSFiddle


Can't find file in .htaccess

Question: In my website I'm trying to implement friendly URLs. I have an index.php file and a .htaccess file in my hosting's public folder. I'm using the following code in the .htaccess file:
DirectoryIndex index.php
RewriteEngine On
RewriteRule ^article/([0-9]+)/$ ../Feed/Article.php?id=$1

Therefore, if anyone enters www.example.com/article/15/, it loads the Article.php passing the 15 value through GET.
But the problem is that the Article.php file is outside the public folder (hence the ../) and Apache doesn't find it.
Can anyone help me?
Note: I don't have access to the httpd.conf file.
Answer: That doesn't rewrite to a filesystem path but a URI. so if Article.php is at http://example.com/Article.php your rewrite rule would look like:
RewriteRule ^article/([0-9]+)/$ http://example.com/Article.php?id=$1

Comment: Probably better off stripping the `http://example.com` out of that rewrite.
Comment: Oh, ok I understand. But that forces me to save all the files inside the public folder, right? Isn't it that *very* insecure?
Comment: You can put it in another subdirectory and forbid access to it. But I don't see why it should be a security issue if users can access the script directly?

Can't find file in .htaccess


What guitar setup to use to record on phone

Question: I have been playing guitar for a while now and I admit that I have been neglecting learning about the hardware. But now I would like to start recording what I play and preferably what I sing as well. I am looking for a setup where I can use my phone as a "Pseudo amp" where I can control the volume, tone, effects etc.
I realize there exist a few questions about this, but they all seem to suggest that you know a lot about mixers and producing. I am not looking for something to produce a professional sound by any means.
I just would like a setup where I can

control stuff on my phone
record what I play
and then have a pair of headphones as an amp or a real amp (if I could switch between these it would be fantastic but headphones are the main priority).

So the solution would probably be something akin to a Line 6 Pod but preferably with the amp part controlled by the phone.
I don't even know if it is technically possible but if the link between the phone and the headphones could be wireless that would be even better.
Hope you guys have some input and if nothing else then at least some input on what I need to read up on to find a good solution.
I know it might be expensive, that is OK it is a prioritized hobby!
Answer: This site discourages asking for and making recommendations of things like gear, books, etc. but you'll be happy to know there are many devices out there that do what you are looking for, some for well under $100. Without knowing your setup and specifically what you want to achieve I suggest searching the web for "smartphone audio interface" or "smartphone guitar interface" to get an idea of what's out there. Then call the customer service folks at Sweetwater.com (or another music store if you prefer). They can help you decide what is best for you based on the type of phone and musical gear you have, what you're wanting to do, and your budget. Best of luck to you!


Inserção da letra "e" em type number

Question: Gostaria de saber como não permitir a inserção da letra "e", que provavelmente representa o número de Euler, no input type="number.
Comment: Resumindo, ao invés de digitar  `10000`, o usuário pode digitar `1e4`, o que simplifica para quem conhece a notação científica - ainda mais quando considerado números ainda maiores. Agora, se você não deseja manter a notação, basta utilizar [`Number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number). Sinceramente, eu não vejo motivos algum para impedir algo que facilita a vida do usuário.
Comment: @AndersonCarlosWoss Depende muito do sistema. Eu vejo muitas formas pela qual permitir notação científica apenas criaria uma bagunça. Isso depende muito de para onde esse dado será enviado e como será processado.
Comment: Como o @AndersonCarlosWoss disse, [pelo que pude ler](https://stackoverflow.com/a/31706796/3956218), a letra "e" nada tem a ver com o número de euler, e sim pela característica do `input type="number"` aceitar números com a notação científica, [arrisque aumentar ou diminuir 1](https://jsfiddle.net/xmdvdbf3/), ele tambem aceita números negativos, ou seja ele aceita os dois caracteres "e" e "-", além dos 10 algarismos do sistema decimal
Comment: Acredito que esse "e" aí representa a notação científica, indicando a potência de 10. Por quê não permitir que ele seja indicado no campo?
Answer: Uma forma de fazer seria assim, no seu HTML:
<input type="number" onkeydown="return FilterInput(event)" onpaste="handlePaste(event)">

E no seu JavaScript:

Answer: Você poderia tentar desta forma, aonde #input seria o id do seu input:
Em Jquery:
$(function() {
    $("#input").keypress(function(event) {
        if (event.which != 8 && event.which != 0 && (event.which < 48 || event.which > 57)) {
            $(".alert").html("Enter only digits!").show().fadeOut(2000);
            return false;
        }
    });
});

Em Javascript puro:
document.querySelector(".your_class").addEventListener("keypress", function (evt) {
    if (evt.which != 8 && evt.which != 0 && evt.which < 48 || evt.which > 57)
    {
        evt.preventDefault();
    }
});

Comment: Poderia ter incluído a fonte na resposta.
Comment: Poderia claro mas ai colocaria todos os locais aonde pesquisei para encontrar, tem uma junção de algumas respostas. E @Henrique caso tenha uma resposta exatamente igual pode marcar a fonte. Ou poderia colocar sua resposta. Ou melhor pedir para cada pessoa adicionar suas fontes, pois todas as respostas daqui vieram de outros lugares né ?
Comment: Na verdade só comentei porque são as mesmas respostas desta pergunta: [How to block +,-,e in input type Number?](https://stackoverflow.com/questions/39291997/how-to-block-e-in-input-type-number)
Comment: Entendi e fato são iguais porém não as encontrei ali. Mas se for assim concordamos que deveria colocar o mesmo comentario em praticamente todas as respostas aqui do SO né.
Answer: Encontrei algo parecido nessa resposta:
var valorNum = document.getElementById("id_input")

valorNum.addEventListener("keydown", function(e) {
  // prevent: "e"
  if ([69].includes(e.keyCode)) {
    e.preventDefault();
  }
})

Um ponto que você precisa ver é que ao chegar no valor máximo do campo e o usuário clicar na setinha (cima ou baixo) ele transforma o número e exibe o "e" (ex: 2.18723978932187987e+35), mas este código previne a letra e caracteres especiais digitados pelo usuário.

Inserção da letra "e" em type number


angularjs only in a particular wordpress post

Question: I build a website with many pages (event, blog, game....). One page display games (posts). User click on a new game button and there is a new post created.
User click on buttons to play, post is updated and reloaded.
I understand we can set wordpress to be a single application page with angularjs.
Is it possible to keep all the website as it is and use angularjs only for the game page, post ?
Answer: Absolutely, Just bootstrap ng-app to a wrapper of the section that has to be angularized or add ng-app to that wrapper. That way all the rest stays exactly the same.
Comment: OK, I try and let you know


The space of all linear maps from $U\to V$ is isomorphic to $\text{Mat}_{l\times k}(K).$

Question: While trying to solve the following problem

Let $K$ be a finite field of $q$ elements. Let $U$, $V$ be vector spaces over $K$ with
  $\dim(U) = k$, $\dim(V) = l$. How many linear maps $U \rightarrow V$ are there?

I came across the following claim here:

The space of all linear maps from $U\to V$ is isomorphic to $\text{Mat}_{l\times k}(K).$

Could someone link me to a proof of this result?
Answer: It's solved here:
Proving isomorphism between linear maps and matrices
And the proof is based on Matrix representation of linear transformations