Javascript call function inside html

Question: My database is giving me week days as "0", "1", "3", "4", "5", "6". And I wanted to translate it to their actual name.
So I'm doing:
HMTL

JS

I'm getting "traduzir is not defined" error. Can someone help? Thanks!
Comment: Make sure that the function `traduzir` is defined in the html before it is called.
Comment: This really calls for a switch statement. See here http://www.w3schools.com/js/js_switch.asp
Comment: Approaching your problem from a different point of view, can you do the translation server side in PHP before it's even rendered in the page?
Comment: Also, you have a typo where you use the vars woord and word
Answer: First you need to make sure the script that defines the traduzir method is placed before the script that calls it.
Then you need to also change your script so that it actually does something with the returned value.
Comment: How do I use the returned value?
Comment: @Ana do you want to print it at the position you call the script ?
Answer: If the section marked JS is in a separate JavaScript file, then remove the HTML ().
In either case, move the second script so the HTML document loads it before the first script. You can't use a function until you have defined it, and it won't be hoisted from a later script in time to use it immediately in an earlier one.

Javascript call function inside html


Interpreting autocorrelation in time series residuals

Question: I am trying to fit an ARIMA model to the following data minus the last 12 datapoints: http://users.stat.umn.edu/~kb/classes/5932/data/beer.txt
The first thing I did was take the log-difference to get a stationary process:
beer_ts <- bshort %>%pull(Amount) %>%ts(.,frequency=1)
beer_log <- log(beer_ts)
beer_adj <- diff(beer_log, differences=1)

.
.
Both the ADF & KPSS tests indicates that beer_adj is indeed stationary, which matches my visual inspection:

.
.
Fitting a model yields the following:
beer_arima <- auto.arima(beer_adj, seasonal=FALSE, stepwise=FALSE, approximation=FALSE)
summary(beer_arima)

Series: beer_adj
ARIMA(4,0,1) with non-zero mean

Coefficients:
         ar1     ar2     ar3      ar4      ma1    mean
      0.4655  0.0537  0.0512  -0.3486  -0.9360  0.0017
s.e.  0.0470  0.0517  0.0516   0.0469   0.0126  0.0005

sigma^2 estimated as 0.01282:  log likelihood=312.39
AIC=-610.77   AICc=-610.5   BIC=-582.68

Training set error measures:
                        ME      RMSE        MAE      MPE     MAPE     MASE        ACF1
Training set -0.0004487926 0.1124111 0.08945575 134.5103 234.3433 0.529803 -0.06818126

.
.
When inspecting the residuals, however, they seem to be serially autocorrelated at lag 12:

I am unsure how I am supposed to interpret this last plot - at this stage I would have expected white noise residuals. I am new to time series analysis, but it seems to me that I am missing some fundamental step in my modelling here. Any pointers would be greatly appreciated!
Comment: You might want to consider looking at the PACF too.
Answer: You are looking at data for monthly beer production. It has seasonality that you must account for and it is this seasonality that you are noticing in your ACF plot. Note that you have 2 strands of seasonality - every 12 months (in the plot note the ACF being particularly high at 12 months and 24 months) and every 6 months (in the plot note the ACF being high at 6 months and 18 months).
As the next steps:
- (1) Try adding lag12 into your model to account for the seasonality every 12 months, the strongest one you observe in the ACF plot
- (2) If after step (1), you still have serial correlation, add both lag12 and lag6 into you model; this should take care of it
Comment: There are two remedies for "seasonal dependency"  1) autoregressive and 2)seasonal pulses . Try adding three seasonal pulses ...one for january , a second for june and a third for october  .
Comment: Every 6*k months seasonality where k is odd actually is 12-month seasonality, just with a phase shift from the original 12-month seasonality.
Comment: The seasonal pulse for jan(1) starts at period 73 ... the seasonal pulse for oct (10) starts at period 31 and the seasonal pulse for june(6) starts at period 78. Values before these periods would be 0 for three variables/series. It is very important especially in a classroomlearning context to teach what is right and what should be done .. even if it "complicates" as teaching insufficient methodology is never a good strategy.
Comment: Good point, Richard. As is, I believe my answer is inconsistent because lag6 accounts for 6 month seasonality, while 6*k (where k is odd), refers, as you said, to a 12-month seasonality. After we've removed the seasonality at 12 months by introducing lag12 in the equation, we're still left with seasonality at 6 months, but, as I understand it, more so at those 6*k (where k is odd) months because lag12 would have already accounted for some of the seasonality at 6*k (where k is even). I think replacing "every 6*k (where k is odd)" with "every 6 months" should fix it. Let me know your thoughts.
Comment: Thank you, IrishStat. Makes sense. I guess you'd call my proposed remedy "autoregressive". By "seasonal pulses ... one for january, a second for june and a third for october" are you referring to dummy variables, one for jan, another for june, and one for oct? I understand you arrived at the idea of adding seasonal pulses for january and october based on analysis supplementary to that provided in the question. The ACF plot provided in the question, as I read it, doesn't indicate anything about January and not much evidence about October (assuming jan start of data - autocorrelation at 10, 22).
Comment: yes add three series ... all 0/1  . The ACF is a portmanteau (global) statistic and doesn't speak to the effect of individual months . Yes ARIMA is both autoregressive and purely endogenous. Adding user specified variables/series adds exogenous structure irrespective of whether they were known a priori or discovered. via Intervention Detection. Note well that your series (error series) also has many pulses unusual one-time values and if left untreated you will get a bloated error variance leading to a downwards bias on all coefficients. I will add another comment.
Answer: If I am not mistaken, the observations in this beer time series were collected 12 times a year for each year represented in the data, so the frequency of the time series is 12.
As explained at https://www.statmethods.net/advstats/timeseries.html, for instance, frequency is the number of observations per unit time. This means that frequency = 1 for data collected once a year,  frequency = 4 for data collected 4 times a year (i.e., quarterly data) and frequency = 12 for data collected 12 times a year (i.e.,  monthly data). Not sure why you would use frequency = 1 instead of frequency = 12 for this time series?
For time series data where frequency = 4 or 12, you should be concerned about the possibility of seasonality (see https://anomaly.io/seasonal-trend-decomposition-in-r/).
If seasonality is present, you should incorporate this into your time series modelling and forecasting, in which case you would use seasonal = TRUE in your auto.arima() function call.
Before you construct the ACF and PACF plots, you can diagnose the presence of seasonality of a quarterly or monthly time series using functions such as ggseasonplot() and ggsubseriesplot() in the forecast package in R, as seen here: https://otexts.org/fpp2/seasonal-plots.html.
Comment: Interesting. My code is `beer_ts <- ts(read.table("http://users.stat.umn.edu/~kb/classes/5932/data/beer.txt")$V3,
 frequency=12,start=c(1956,1))`, followed by `auto.arima(beer_ts)`. Are you maybe reading a local copy that is slightly different? Or using a different version of the `forecast` package (mine is 8.4)?
Comment: This is the only correct answer. Specifying `frequency=12` in the `ts()` call yields a seasonal time series, and `auto.arima()` then fits a nice seasonal model, ARIMA(4,1,2)(0,1,2)[12]. There are still a few "significant" peaks in the (P)ACF plots for the residuals, which I personally would put down to a long series and not worry unduly about.
Comment: Thank you both for your answers, that makes complete sense. With that said, @StephanKolassa, simply setting `frequency=12` does not then give me the same auto.arima model you are getting. What I get is ARIMA(1,0,3)(1,0,0)[12] for the log-differenced series. This is with: `auto.arima(beer_adj, seasonal=TRUE, stepwise=FALSE, approximation=FALSE)`.

I can model it manually at this stage but I was curious to know if you had to modify anything else for the auto.arima to yield the desired result. Thanks!
Comment: @Student_514: It sounds like Stephan is applying auto.arima() to the original beer_ts series while you are applying it to beer_adj (i.e., the log-differenced series). The auto.arima() function is 'smart enough' to know what Box-Cox transformation and differencing to apply to the original series, so it's sufficient to supply the original series to auto.arima().
Comment: Thank you so much, Stephan!  The asker of the question can examine model diagnostics for the model suggested by auto.arima() and also perform time series cross validation to assess the accuracy of forecasts at each specific forecast horizon considered. I agree with you that there is no need to get overly complicated when modelling this time series, especially in a learning context.
Answer: You say "log-difference to get a stationary process" . One doesn't take logs to make the series stationary When (and why) should you take the log of a distribution (of numbers)? , one takes logs when the expected value of a model is proportional to the error variance. Note that this is not the variance of the original series ..although some textbooks and statisticians make this mistake.
It is true that there appears to be "larger variablilty" at higher levels BUT it is more true that the error variance of a useful model changes deterministically at two points in time . Following http://docplayer.net/12080848-Outliers-level-shifts-and-variance-changes-in-time-series.html we find that
The final useful model accounting for a needed difference and a needed Weighted Estimation (via the identified break points in error ) and ARMA structure and adjustments made for anomalous data points is here .
Also note that while seasonal arima structure can be useful (as in this case ) possibilities exist for certain months of the year to have assignable cause i.e. fixed effects. This is true in this case as months (1,6 and 10) have significant deterministic impacts ... Jan & June are higher while October is significantly lower.
The residual acf suggests sufficiency ( note that with 422 values the standard deviation of the acf roughly is 1/sqrt(422) yielding many false positives  . The plot of the residuals suggest sufficiency  . The forecast graph for the next 12 values is here


Time series with multiple periods and non negative values

Question: When I read time series in a ts object and put a period:

tr <- ts(data[,4],frequency=). This works for two different periods and decomposes perfectly to show (downward) trend, seasonality and error. How do I know which is the correct period.
When I use a ETS or STLF function in the forecast package on the above ts object, the summary shows: Model Information: ETS(A,N,N) Why is that? We do have a seasonal+trend component here?
What can we do to deal with negative values when the training set is non-negative and negative values make no sense.
Comment: Has this question been answered sufficiently?  If so, can you mark it answered, please.
Answer:
What the correct period is depends on the data generating process.  For instance, if you are looking at monthly data driven by consumer habits, then, if we presume that consumer behavior fluctuates based on changing circumstances throughout the year, since the data is monthly, 12 is likely a good frequency to select.  It is important to keep in mind that periodicity is multiplicative.  If, for instance, 12 and 24 work, I'd go with 12.  If you have quarterly data, maybe 4 is a good frequency to select. Alternatively, if you are looking at some physical process, like the temperature in an engine, and you have millisecond data, maybe the appropriate period is the number of milliseconds per revolution.
The last two N's mean "none."  I am unable to tell why you think there is a seasonal component and ets does not.  From the help file:

Usually a three-character string identifying method using the
  framework terminology of Hyndman et al. (2002) and Hyndman et al.
  (2008). The first letter denotes the error type ("A", "M" or "Z"); the
  second letter denotes the trend type ("N","A","M" or "Z"); and the
  third letter denotes the season type ("N","A","M" or "Z"). In all
  cases, "N"=none, "A"=additive, "M"=multiplicative and
  "Z"=automatically selected. So, for example, "ANN" is simple
  exponential smoothing with additive errors, "MAM" is multiplicative
  Holt-Winters' method with multiplicative errors, and so on.
It is also possible for the model to be of class "ets", and equal to
  the output from a previous call to ets. In this case, the same model
  is fitted to y without re-estimating any smoothing parameters. See
  also the use.initial.values argument.

What you do with negatives depends on the data generating process.  If, once the forecasted variable reaches zero, the process stops (i.e. you have an absorbing state), then maybe you can just set those foretasted values to zero.  If, however, you believe that downward movements become smaller and smaller, then you may have to change your model to reflect this.  Setting lambda=0 would be a good start, which is equivalent to taking logarithms.  This would make the model multiplicative.  But, in general, if your forecasts are becoming negative and you know that is impossible, your model of the data generating process is probably wrong.
Comment: Thanks Prof for the detailed response.
1) I think there is a daily as well as weekly periodicity in my data. I came across your paper on multiple periods and will make use of it.
2) I used STLF. Is it not by default meant for seasonal data for periods more than 13? Is it possible I saw ANN because I had accounted for periodicity in the TS object
Comment: Defining the period in your TS object does not mean it will be ignored.  If, however, you inaccurately defined it, then maybe the state space model will not include a seasonal term.
Comment: As regards point 2), I feel there is a seasonality because I have added a frequency when I read the time series object. Also when I decompose the time series, I do get components. Please help
Comment: Also when I plot the series, I do see a seasonality. The data does show peaks and troughs on certain days of the year. BTW, I am using STLF function for the forecasting.


LOOP on files ! PARSE FILES and GROUP them by IDENTIFIER?

Question: I would like to :

Read the list of * .txt files from the directory

For all the .txt files in my folder, I would like to use the information contained in all the rows id=NAME, part of the fifth column in all the *.txt files (e.g., Hox.txt and zinc.txt below)

Determine which family the given file belongs to (e.g cram-2) using a separate lookup table linking id values to a Family value (e.g., Lookup Table below)

Combine/concatenate all the files with the same family (e.g HOX.txt and zinc.txt) into one .txt file.

Save the linked file with the name of the column Family (e.g cram-2.txt).

!! REMINDER !!
!! R WILL HAVE TO WORK ON A LOT AND HEAVY .txt FILES - NEED OF A TEMPORARY DIRECTORY? !!
Example:
The HOX.txt file rows :
ma  reg out fim id=HOX;seq=AGCAGGAAATA;score=12.1915;pval=4.97e-05
se  reg out fim id=HOX;seq=AGCAGGAAATA;score=12.1915;pval=4.97e-05
to  reg out fim id=HOX;seq=AGCAGGAAATA;score=12.1915;pval=4.97e-05
pa  reg out fim id=HOX;seq=AGCAGGAAATA;score=12.1915;pval=4.97e-05

The zinc.txt file rows :
ma  reg out fim id=zinc;seq=AGCAGGAAATA;score=12.1915;pval=4.97e-05
se  reg out fim id=zinc;seq=AGCAGGAAATA;score=12.1915;pval=4.97e-05
to  reg out fim id=zinc;seq=AGCAGGAAATA;score=12.1915;pval=4.97e-05
pa  reg out fim id=zinc;seq=AGCAGGAAATA;score=12.1915;pval=4.97e-05

The lookup table :
Name                        Family
HOX                         cram-2
zinc                        cram-2
fire                        sf.xr
fire                        ra.XS-2
...continues...

The final output I search to obtain :
a) File name = cram-2.txt
b) Concatenate HOX.txt and zinc.txt because both are from Family cram-2!
ma  reg out fim id=HOX;seq=AGCAGGAAATA;score=12.1915;pval=4.97e-05
se  reg out fim id=HOX;seq=AGCAGGAAATA;score=12.1915;pval=4.97e-05
to  reg out fim id=HOX;seq=AGCAGGAAATA;score=12.1915;pval=4.97e-05
pa  reg out fim id=HOX;seq=AGCAGGAAATA;score=12.1915;pval=4.97e-05
ma  reg out fim id=zinc;seq=AGCAGGAAATA;score=12.1915;pval=4.97e-05
se  reg out fim id=zinc;seq=AGCAGGAAATA;score=12.1915;pval=4.97e-05
to  reg out fim id=zinc;seq=AGCAGGAAATA;score=12.1915;pval=4.97e-05
pa  reg out fim id=zinc;seq=AGCAGGAAATA;score=12.1915;pval=4.97e-05

Code working on few  files.bed only.
I tried using tempfile() and tempdir() but still didn't worked.
dfNameFamily = tibble(
  Name = as.character(df$Name),
  Family = as.character(df$Family)

dir = "~/textfiles"

TxtFile = function(dir) dir_ls(dir, regexp = "\\.txt$")

readTxt = function(FileName){
  lines = character()
  if(file_exists(FileName)){
    con = file(FileName, open = "r")
    lines = readLines(con)
    close(con)
  }
  lines
}

GetName = function(l) str_match(l, ";id=(.+);seq")[1,2]

SaveFile = function(l, name, dir){
  con = file(paste0(dir, "/" , name))
  writeLines(unlist(l$lines), con)
  close(con)
}

tibble(FileName = TxtFile(dir)) %>%
  mutate(
    lines = map(FileName, readTxt),
    Name = map_chr(lines, GetName)) %>%
  left_join(dfNameFamily, by="Name") %>%
  group_by(Family) %>%
  group_walk(SaveFile, dir)

Comment: Stackoverflow is not a site for hiring someone to write code for you. You need to show what you have done so far and people will be glad to find answers and solve exact problems met by you. You can read here about how to provide [MCVE](https://stackoverflow.com/help/minimal-reproducible-example)
Answer: Try this code.
Gather the files to be processed in the bedDir directory. Create a directory bedOut for the output files. It's best to keep this in one RStudio project where you create these directories.
Extend the Names and Families vectors accordingly according to your needs.
library(data.table)
library(tidyverse)
library(fs)
library(utils)

Names = c("HOX", "zinc", "fire", "fire2")
Families = c("cram-2", "cram-2", "sf.xr", "ra.XS-2")
GetName = function(l) str_match(l, "id=(.+);seq")[1,2]
GetFamily = function(l) Families[which(Names==GetName(l))]

BedFile = function(dir) dir_ls(dir, regexp = "\\.bed$")

info = function(txt, start_time, end_time){
  tdif = end_time - start_time
  tunit = " ms"
  if(tdif>=1000){
    tdif = tdif/1000
    tunit = " s"
  }
  cat(paste0("Read ", txt," (", round(tdif,2),tunit,")\n"))
}

time_ms = function() as.numeric(as.numeric(Sys.time())*1000, digits=15)

pbTitle = function(path, files, i){
  paste("[", round(i/length(files)*100, 0),"%]",
        "files have been read from the", path, "directory.",
        "The file being read:", files[i])}

bedDir = "bedDir"
bedOut = "bedOut"
files = BedFile(bedDir)
if(length(files)>0){
  start_time = time_ms()
  pb = winProgressBar(max = length(files), width = 500)
  on.exit(close(pb), add = TRUE)

  for(i in 1:length(files)){
    setWinProgressBar(pb, i-1, pbTitle(bedDir, files, i-1))
    lines = fread(text = files[i], sep = "|", header=FALSE)
    Name = GetName(lines[1])
    Family = GetFamily(lines[1])
    fileName = paste0(bedOut, "/", Family, ".bad")
    fwrite(lines, fileName, append = file_exists(fileName))
  }

  close(pb)
  info(paste(length(files), "files"), start_time, time_ms())
}

P.S.
I recommend that you note that I used the fastest known functions for reading and writing fread and fwrite text files from the data.table package here.
Let me know if that's it and how fast it works.
Comment: The most important thing is to know the problem well. As you already know him, you can look for the optimal solution for him. Your original description of the problem was somewhat confusing and incomplete. While writing the first version of program, I was rather guessing what you expect. Knowing your problem fully, I was able to optimize it. Hope you learned something by the way (for sure how `txtProgressBar` works). Finally, check out my other answers. Perhaps one of them will be equally informative for you and you will want to click "This answer is useful". I'll be glad.
Comment: Worked on 137 Gbts in less than 10 minutes. This is astonishingly thank you so much! @MarekFiolka
Comment: Yes it was useful, took a bit to understand each part of the code though. Sure, I ll go through your other inputs and informative answers. Best, and thank you again! @MarekFiolka


What is the probability of randomly selecting $ n $ natural numbers, all pairwise coprime?

Question: It's known that the probability of selecting $ n $ natural numbers randomly and ending up with a greatest common divisor equal to one is $ \prod (1-p^{-n}) = 1/\zeta(n) $. However, a total GCD of 1 does not rule out any of the pairs among the set of $ n $ numbers sharing a common factor. What's the probability none of them share a common factor? (Since there's a possibility of "random selection" being ambiguous, let's take it to mean chosen with uniform probability from {$ 1,2,3,\dots, N$} as $N \to \infty $.)
Comment: A quick and dirty approach gives $\prod (1-1/p)^{n-1}(1+(n-1)/p)$. I don't know how to write this number in a "closed form". The (certainly not rigorous) idea is: for every prime $p$, the probability that $p$ divides a random number is $1/p$, and we can admit that it divides either none of the $n$ numbers (prob. $(1-1/p)^n$) or one of them ($(1-1/p)^{n-1}n/p$), and suppose that the probabilities for different $p$'s are independent.
Answer: This answer is on a heuristical level; I don't purport to rigorously prove the result.
The probability $\prod (1-p^{-n})$ can be derived from the fact that for sufficiently large $N$ the probability of each number being divisible by a given prime $p$ is $p^{-1}$, so the probability of all $n$ numbers being thus divisible (which would lead to the gcd not being $1$) is $p^{-n}$. Applying this reasoning to your case, we have that the probability for not more than one of the $n$ numbers being divisible by $p$ is the sum of the probabilities of zero or one of them being divisible by $p$, which is
$$\binom n0\left(\frac{p-1}{p}\right)^n+\binom n1\left(\frac{p-1}{p}\right)^{n-1}\frac1p=\left(1-\frac1p\right)^{n-1}\left(1+\frac{n-1}p\right)\;.$$
So we could expect the probability you're looking for to be given by
$$p_n=\prod_p\left(1-\frac1p\right)^{n-1}\left(1+\frac{n-1}p\right)\;.$$
I don't know whether it's possible to evaluate this Euler product explicitly. Numerically (both evaluating the Euler product and generating large pseudo-random numbers), I get
$$
\begin{array}{|c|c|}
n&p_n\\
\hline
1&1\\
2&0.6079\\
3&0.2867\\
4&0.1149\\
5&0.0409\\
\end{array}
$$
Of course $p_2=1/\zeta(2)$, since in that case the two conditions coincide.
P.S.: The Euler product can be evaluated more efficiently numerically if we rewrite it as
$$p_{n+1}=\prod_p\left(1-\frac1p\right)^n\left(1+\frac np\right)=\prod_p\left(1-\frac1{p^2}\right)^n\frac{1+\frac np}{\left(1+\frac 1p\right)^n}=\zeta(2)^{-n} \prod_p\frac{1+\frac np}{\left(1+\frac 1p\right)^n}\;,$$
since the remaining product converges more quickly. (Also it looks more like something that might have a closed form.)
Comment: $p_3$ is the "Strongly carefree constant" $\prod_p \left(1 - \frac{3}{p^2} + \frac{2}{p^3}\right)$.  See http://mathworld.wolfram.com/CarefreeCouple.html and references there.
Comment: That looks sound. (Minor correction: not more than one of the $ n $ numbers.) Thanks for the response.
Comment: @anon: Thanks, corrected.


Multi-group SEM - constraints and regression paths

Question: This is a question seeking to follow up on this post.
I have a multigroup SEM with a mix of observed and latent variables.
In the measurement model to inspect latent variables, metric invariance holds (loadings), but scalar invariance (intercepts) does not hold.
The regression is one manifest variable (Std_LC) and one latent variable predicting a latent outcome.
I wish to determine if the regression coefficients significantly different across three groups. If I hold "loadings" and "regressions" invariant, there are no sig. differences across groups. But if intercepts are not also constrained to test for differences, aren't the regressions coefficients representing different values?
Basically, I understand configural, metric, and scalar invariance, but I don't understand if "intercepts" being constrained here refers to intercepts of indicators loading onto latent factors, or also intercepts of variables modelled in the regression.
Many thanks in advance for any advice you could offer!
<code>modelx <- '

FluentWR =~ Std_WI +Std_ORF + Raw_RANN
RC =~ Std_PC + Std_WC
RC ~ FluentWR + Std_LC
FluentWR ~~ Std_LC '
```
</code>
Answer: The regression slope coefficients in your structural (latent variable) model only involve the covariance structure (latent variances and covariances). Therefore, loading (metric/weak) invariance is sufficient to meaningfully test whether the regression slope coefficients in the structural model are equal across groups.
The intercepts in the structural regression model involve the mean structure of the latent variables. To meaningfully compare structural intercepts, you need to have at least strong/scalar invariance in your measurement model (i.e., equal factor loadings and equal indicator intercepts). Otherwise, the mean structure of the latent variables is not comparable across groups.
Comment: Thank you Christian! This is very helpful. I should have mentioned that I expect the regression model coefficients to vary across groups, especially for the single manifest variable. I guess I am wondering ... my model is maybe more like a path analysis with latent variables, and less like a proper SEM since I am not using item-level indicators, but sum scores. Is a measurement model even necessary? Is it enough to hold "intercepts" and "regression" constrained like this post describes? https://jslefche.github.io/sem_book/multigroup-analysis.html
Comment: Or perhaps I am going about it backwards and need to first see if a measurement model can be developed that indeed meets scalar invariance, so I can test the regression model coefficients. I will try both, but I am not sure how they are nested. Thanks again for the  response!
Answer: Yes, probably the most appropriate way to approach this would be to test an item-level multigroup CFA (measurement model) first to see what level of measurement equivalence holds across the groups. Depending on the level of measurement equivalence, you can then test the equivalence of the structural regression coefficients across groups using multigroup SEM or path analysis.
Comment: Thank you so much!


Qual é a diferença entre __CLASS__ e get_called_class?

Question: No PHP, conheço dois métodos de exibir o nome da classe atual que está sendo chamada: através da constante mágica __CLASS__ e da função get_called_class().
Aparentemente, as duas fazem a mesma coisa.
class A
{
     public static function className()
     {
          echo get_called_class();
     }
}

class B
{
     public static function className()
     {
          echo __CLASS__;
     }
}

B::className(); // 'B'
A::className(); // 'A'

Existe diferença de performance entre elas?
Existe alguma diferença na hora de chamá-las?
Answer: Fazendo os testes após ver esta resposta no SOen, elas tem efeitos diferentes em situações quando estendemos uma classe:

get_called_class retorna o nome da classe atual e não da onde foi declarado:
<?php
class Foo
{
    static public function digaMeuNome()
    {
        var_dump(get_called_class());
    }
}

class Bar extends Foo
{
}

Foo::digaMeuNome(); // Retorna Foo
Bar::digaMeuNome(); // Retorna Bar

__CLASS__ retorna o nome da classe aonde o método foi declarado, ou seja o método digaMeuNome foi declarado em Foo:
<?php
class Foo
{
    static public function digaMeuNome()
    {
        var_dump(__CLASS__);
    }
}

class Bar extends Foo
{
}

Foo::digaMeuNome(); // Retorna Foo
Bar::digaMeuNome(); // Retorna Foo

Comment: A resposta ficou um pouco simples, mas vou tentar complementar mais a tarde.
Comment: Mas era isso mesmo que eu estava esperando :)


SQL, buscar apenas um elemento por categoria

Question: Estou a tentar fazer uma query SQL que selecione apenas um elemento por cat_id, do genero de um ciclo For onde verifica se já existe um cat_id=1 e se já tiver passa para a frente até correr a tabela toda.

estou a utilizar esta função para ir buscar todos os ficheiros
public function get_products()
    {
        $sql  = "SELECT * FROM products";
        $query = $this->db->query($sql);
        return $query->result_array();
    }

e quero apenas ir buscar 1 por cat_id
Answer: Se eu entendi corretamente, você quer retornar suas categorias e apenas 1 registro de cada. Isso você pode conseguir fazendo uma query base que retorne o último ID registrado para uma categoria
SELECT MAX(id) FROM products GROUP BY cat_id

Caso a sua necessidade seja retornar o primeiro produto por categoria, basta alterar o MAX por MIN.
Com base nesta query, você pode retornar as informações desta forma:
SELECT * FROM products WHERE id in (SELECT MAX(id) FROM products GROUP BY cat_id)

Comment: obrigado, era exatamente isso


Inheritance of property characteristic by sub-properties

Question: In OWL, is a sub-property of an irreflexive property also irreflexive? Likewise is a sub-property of an asymmetric property also asymmetric?
Logically, they should be, but I can't find anything in the OWL documentation that specifies that this is the case.
Consider the following example:
:parent-of a owl:IrreflexiveProperty .

:father-of a owl:ObjectProperty ;
    owl:subPropertyOf :parent-of .

Based on this ontology, the following would not be allowed because parent-of is irreflexive:
_:max :parent-of _:max .

But is father-of implicitly irreflexive as well? In other words, would this also be prohibited:
_max :father-of _:max .

If you think of a property as a set of arrows which connect pairs of points, then irreflexive just means that there are no arrows which both start and end at the same point. A sub-property is simply a subset of those arrows, and so the sub-property of an irreflexive property is necessarily also irreflexive. Likewise with asymmetric properties. But again, I don't know if OWL spells this out explicitly or if OWL reasoners are supposed to make this "assumption".
Answer:
In OWL, is a sub-property of an irreflexive property also irreflexive?
  Likewise is a sub-property of an asymmetric property also asymmetric?

Yes. The logical formulation is in OWL 2 Web Ontology Language Direct Semantics (Second Edition):

2.3.2 Object Property Expression Axioms
Satisfaction of OWL 2 object property expression axioms in I is
  defined as shown in Table 6.
…

Axiom: IrreflexiveObjectProperty( OPE )
Condition: ∀ x : x ∈ ΔI implies ( x , x ) ∉ (OPE)OP

Your reasoning shows that any subproperty of an irreflexive property satisfies the condtition.  Therefore, the subproperty is also irreflexive.

But again, I don't know if OWL spells this out explicitly or if OWL
  reasoners are supposed to make this "assumption".

OWL reasoners are based on these definitions, and so should be able to infer that the subproperty is irreflexive.


Error When Trying to Use Windows Server 2016 Native VPN Client to Connect to Fortigate VPN

Question: Good day all.
I am stuck trying to troubleshoot an error on windows server 2016 using the native vpn client to connect to a fortigate VPN that I had setup.
Initially I was having errors to due with error 789 for which I re-enabled and set to automatic start both the IKE/IPSEC Keying service and the IPSEC policy agent.
After this I tried to connect again to the VPN server, but this time it is giving me a different error:
<code>Can't connect to <VPN Name>. The modem or other connecting device has reported an error.
</code>
I know that an obvious fix would be to use forticlient for windows, however due to restrictions on this production server, it has not allowed to be installed.
I have tried updating the drivers for the WAN Miniport associated with the VPN connection but still I getting the same error.
This specific server is also running on ESXI 6.0 with a single virtual NIC.
Please let me know of any tips or methods of getting this machine to connect to the VPN.
Thank you!
Comment: Questions seeking installation, configuration or diagnostic help must include the desired end state, the specific problem or error, sufficient information about the configuration and environment to reproduce it, and attempted solutions. Questions without a clear problem statement are not useful to other readers and are unlikely to get good answers.
Answer: A lot of thing can go wrong here; look at your Fortnet logs for (some) more details (enable Debug-Logs for verbose output).
In my (last) case it was NAT-T. Windows Server 2016+ does not enable NAT traversal by default.
You can enable NAT-T on Windows through the registry:
<code>[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\PolicyAgent]
"AssumeUDPEncapsulationContextOnSendRule"=dword:00000002
</code>
Reboot your maschine after changing this setting.
Comment: your initial solution was part of the fix...turns out the pool of addresses that I had assigned on the fortigate were already in use by one of my colleagues. I corrected that and was still having issues. But once I added that fix to the registry all was well. Thank you very much, would have never thought of that!
Comment: hey @bjoster I checked the VPN logs on the fortigate device and the error coming up when I try to connect the windows server is

```
no ip addresses left to assign in virtual domain:root
```
I edited the registry with the fix you suggested but still no luck even after a reboot...thank you though because I believe you have pointed me in the right direction for troubleshooting
Comment: `no ip addresses left to assign` smells bit like there is a IP conflict or no lease left on the fortigate side.


How to find the line begins with digit and move digit to previous line in Notepad++

Question: For example:
Rahul
1423502012
Manage

Should be converted to:
Rahul 1423502012
Manage

I have thousands of lines, please help me to move the number (eg.1423502012) at the end of previous line.
Answer:
Ctrl+H
Find what: \R(?=\d)
Replace with:    (a space)
check Wrap around
check Regular expression
Replace all

Explanation:
\R          : any kind of linebreak
(?=\d)      : lookahead, make sure we have a digit after current position

Result for given example:
Rahul 1423502012
Manage

Answer: In Notepad++, do a regex Find-and-Replace:
Find what:
^(.*)\s+^(\d+)

Replace with:
$1 $2

Make sure to uncheck the box next to ". matches newline".


Number Theory: Describe all $x\in \mathbb{Z}$ so that $x^m \equiv 0\pmod{n}$

Question: I've been working on this homework problem but I'm not sure how to come up with the answer:
Let the prime factorization of $n\in \mathbb{N}$ with $n>1$ be $n=p_1^{a(1)}p_2^{a(2)}\cdots p_k^{a(k)}$. Describe all $x\in \mathbb{Z}$ so that for some $m>0$, $x^m\equiv 0\pmod{n}$.
What I've come up with so far is:
$x^m\equiv 0\pmod{n}\implies n\mid x^m\implies p_1^{a(1)}p_2^{a(2)}\cdots p_k^{a(k)}\mid x^m$,
But I'm unsure where to go from here.
Thanks!
Answer: If there exists an $m$ such that $p_1^{a(1)}p_2^{a(2)}\cdots p_k^{a(k)}\mid x^m$, then that means that $p_1p_2\cdots p_k\mid x$. The reason is this: If $p_i^{a(i)}\mid x^m$, then $p_i \mid x^m$, which in turn implies $p_i \mid x$, by Euclid's lemma. Since this is true for all the primes $p_i$, we have that $\operatorname{lcm}(p_1, p_2,\ldots, p_k)$ divides $x$, and we're done.
Comment: Thank you so much! I figured it out now.


How Residuals of Instrumental Variables Estimation are calculated and why you can have a negative R-squared?

Question: I would like to understand, precisely, why you can have a negative $R^2$ with a 2SLS estimation, such as you have in commands like ivreg2 in Stata. There is reference for such an occurrence for ivregress here: http://tinyurl.com/qbb9o9s. It states the residuals are calculated with the endogenous variables of the structural model, but it also states that the estimation does not have a nested constant-only version of the model -- this last detail is probably what makes possible the $R^2$ to be negative, I guess. I know that an estimation without the constant can produce a negative R-squared (I understand this), but I cannot say for sure if not having a nested constant-only version of the model is in any way similar. Could someone help me understand how the residuals are calculated?
Answer: First of all, ask yourself whether your instruments are actually strong enough to warrant the usage of TSLS. As you perhaps know from Bound et al. (1995), your estimates can be badly biased and inconsistent with 2SLS, see for example here. Moreover, you should do an F test for the first stage and check whether it's about ten.
Even better, use robust test statistics. Ivreg2 and condivreg have some available but only for one endogenous regressor under conditional homoskedasticity. The R square value is usually useless for inference. Check whether your coefficients are statistically significant, first using a t-test and then Anderson-Rubin confidence intervals as given by condivreg.
These intervals may be infinitely large which will then correspond to your instrument strength.
Comment: I told you this several times in the other thread that you use the original endogenous variable and not the fitted values for the calculation of the standard errors ;-)
Comment: I understand that R-squared as stated in `ivreg2` and `ivregress` is a bit useless. But it still a mystery to me how those residuals are calculated from the structural equation with the endogenous variables. That is what I want to understand.
Comment: If it's just about the residuals then see this excellent answer by Dimitriy here http://stats.stackexchange.com/questions/126313/standard-errors-of-a-two-stage-least-squares-regression-stata/126317#126317
Comment: Thank you, Andy. So in the version of Stata you estimate the residuals with the $\beta_{IV}$ and the original $X$ with the endogenous variables? Now I think I see more clearly how the residuals are calculated.


Transfer physical Windows Server 2008R2 licence to Hyper-V server

Question: I have a plan to upgrade my 2008R2 Standard Edition to 2012R2 Standard Edition, and then virtualize them with Hyper-V 2012R2. Is it possible to upgrade from Windows Server 2008R2 Standard Edition to Windows Server 2012R2 Standard edition if I have SA (software insurance)?
What would be my next steps for legal OS licensing for this environment? Can I use these licenses for virualizing environment (Hyper-V server)?
I have seen that with SA you can migrate from 2008R2 Standard to 2012R2 standard, but I couldn't figure out can I transfer these licenses to new server?
I read a lot about licensing rights, but I couldn't find the exact situation that would be of use for me.
Answer: Software assurance give you the right to upgrade during software assurance life .
You don't have to transfer license but request new one. Its in your microsoft vlsc account.
http://www.microsoft.com/licensing/software-assurance/
be carefull with virtual licensing . microsoft say : 2012 r2 is 2 vitual + 1 physical
references : http://www.aidanfinn.com/?p=15477
Comment: Be careful with blanket answers to general questions. Microsoft Software-Assurance comes in many different forms and packages. For example, step-up licensing (mentioned in the question above) is not a guaranteed right with all versions of SA. As for the second point, I'm not entirely sure I follow, are you saying he should be careful because he has more licenses than he thinks (for the same price)?
Comment: We don't answer licensing questions here and you may be giving the OP licensing advice that isn't legally or technically correct, which is why we don't answer licensing questions here. The OP should contact Microsoft directly or contact a Microsoft licensing specialist.
Comment: Yep its why i link to the software assurance website . When you talk about virtualize and windows standard you don't have to forget the rule about ms licensing because virtual is not physical licensing. And its why i post the link . But i don't have 20 year to explain my answer so i resume idea so he can read understand and request answer on dark point .


checked radio pelo name e value javascript

Question: Preciso marcar um dos inputs radio com checked via javascript, de preferência usando name e/ou value para isto.

<!DOCTYPE html>

<input type="radio" name="generoi1" value="female">Feminino

<input type="radio" name="generoi1" value="male">Masculino

<button onclick="myFunction()">Try it</button>

Comment: Como assim **checar** um input radio?
Comment: deixa o radio com checked = true;
Answer: Isso é erro de digitação, não existe getElementByName, falta um S, o correto é getElementsByName:

<!DOCTYPE html>

<input type="radio" name="generoi1" value="female">Feminino

<input type="radio" name="generoi1" value="male">Masculino

<button onclick="myFunction()">Try it</button>

O lis[0] vai pegar o primeiro elemento que encontrar e lis[1] vai pegar o segundo e assim por diante, pois o indice começa do zero.
Você pode optar por usar querySelector que é semelhante aos seletores CSS (se já souber usar), que deve ficar assim:

<!DOCTYPE html>

<input type="radio" name="generoi1" value="female">Feminino

<input type="radio" name="generoi1" value="male">Masculino

<button onclick="myFunction('female')">Feminino</button>
<button onclick="myFunction('male')">Masculino</button>

Comment: @lucaspereira editei a resposta com uma sugestão mais simples, se resolveu por favor marque a resposta como correta, se não souber como veja esse pequeno turotial de como usar o site: https://pt.meta.stackoverflow.com/q/1078/3635 - Obrigado!
Comment: Nossa... nem tinha visto
Comment: Muito obrigado.


A linear motion of $\mathbb{R}^2$ is a bijective mapping of the form $T_A:\mathbb{R}^2\longrightarrow \mathbb{R}^2$ given by $T_A(x)=A\underline{x}$

Question: I was reading about group theory. There was a problem given in a book as follows:

A linear motion of $\mathbb{R}^2$ is a bijective mapping of the form $T_A:\mathbb{R}^2\longrightarrow \mathbb{R}^2$ given by $T_A(x)=A\underline{x}$ for $x\in\mathbb{R}^2$ and $A\in GL(2,\mathbb{R})$ where $A\underline{x}$   is given by the left multiplicaton of the matrix $A$ with the column matrix $\underline {x}$. Show that the set of linear motions is a group under composition of mapping.

However, I am not getting what do they mean by $\underline {x}\in \mathbb {R}^2$? Does they mean ordered pairs $(a,b)$, where $a,b\in\mathbb{R}$ and then $\underline {x}=\begin{bmatrix}
a\\
b
\end{bmatrix}$, i.e a column matrix? Also,  what do they mean by "composition of mapping"? I am not quite getting it...
Comment: you have the correct interpretation of $\underline{x}$ denoting a $2\times 1$ matrix and $x$ denoting an ordered pair in $\mathbb{R}^2$.
Comment: by "under composition of mapping" the author means that the composition law on the set of linear motions is meant to be function composition
Comment: @CSquared Can you please explain what do u mean by "group composition law"?...
Comment: For example, the integers with addition $(\mathbb{Z},+)$ is a group whose composition law (or group operation) is addition. The symmetric group $(S_n,\circ)$ is a group whose composition law (or group operation) is function composition.
Comment: Which book are you referring to?
Comment: @CSquared So is the value of  $(T_A\circ T_B)(x)$ be equal to $AB\underline {x}$ ? Is the identity element $I\underline {x}$(, where $I$ is an identity matrix) ? Also, inverse exists for  each matrix $A$ if $det(A)\neq 0$ but  we are concerned about the inverse function here ....so What will it be? I am not quite getting it...
Answer: Yes, here you should think of $x \in \mathbf{R}^2$ as a $2\times 1$ vector. The set you want to show is a group is $\{T_A : A \in \mathsf{GL}_2(\mathbf{R})\}$ and the binary operation is composition of functions. What is $(T_A \circ T_B)(x)$? What is the identity element?
Comment: Well, $(T_A\circ T_B)(x)$ is equal to  $AB\underline {x}$, right? Also , associativity is satisfied here in the group. And if $T_A(x)=I\underline {x}$ (where $I$ is a $2×2$ identity matrix) then  $T_A$ is the identity element , right? Also, what about the inverse of each element?...
Comment: I think that your confusion might be about $\mathsf{GL}_2(\mathbf{R})$. This is the set (group) of $2\times 2$ invertible matrices with coefficients in the real numbers. So since every matrix $A$ has an inverse, this gives you the inverse transformation.
Comment: Well,I do know about $GL_2(\mathbb{R})$ but is the value of $(T_A\circ T_B)(x)$ be equal to $AB\underline {x}$ ? Is the identity element $I\underline {x}$(, where $I$ is an identity matrix) ? Also, inverse exists for  each matrix $A$ if $det(A)\neq 0$ but  we are concerned about the inverse function here ....so What will it be? I am not quite getting it...


Escaping Rendering Liquid Template in Jekyll Markdown

Question: Is there a way to escape liquid template rendering in Jekyll markdown pages?
I have the following fenced code block in a markdown file:
```html
<!DOCTYPE html>
<html lang="en">

  <head>
    <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Example Title</title>
</head>

<body>
  <div id="app">
    {% raw %}
    {{ content }}
    {% endraw %}
  </div>
</body>

</html>
```

which renders to:
<!DOCTYPE html>

    <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Example Title</title>

I'm not sure why, but Jekyll is processing the content between the {% raw %} tags. I would like to retain the {{ content }} block as-is, without being rendered.
I've also tried the approach of using a { as a page variable and accessing it via the following:
{{ page.lcb }}{ content }}

Comment: Possible duplicate of [How to escape liquid template tags?](https://stackoverflow.com/questions/3426182/how-to-escape-liquid-template-tags)
Answer: Turns out my issue was further complicated by a template issue with Vue.js, which also uses the mustache syntax for templates. I was able to resolve this with the following:
{% raw %}{{ "{{ content "  }}}}{% endraw %}

It doesn't look great, but it works.
Answer: I encountered the same problem. I use CloudCannon for Jekyll. I had several places where I used {{}}, so I ended up putting it into the the component file, where probably template should reside anyway to comply with Vue's structure, e.g.:

var app = new Vue({
    el: "#app",
    data: {...} ,
    filters: {...} ,
    methods: {...},
    template: `

            {{service.name}} {{service.price | currency}}

          Total: {{total() | currency}}

    `
});


Can a fielder use the wicketkeeper's glove if the wicketkeeper has discarded it during play?

Question: If a wicketkeeper throws one of their gloves on the ground to pick up the ball and throw it more easily, then chases after the ball and picks it up and throws it to the stumps, can another fielder put on the glove at the stumps to receive the wicketkeeper's throw?
Answer: No.
The Laws are extremely clear on this.
Law 27.1 on protective equipment says that

[t]he wicket-keeper is the only fielder permitted to wear gloves and external leg guards.

Law 28.1 on protective equipment repeats this exact statement, and further says

[i]n addition, protection for the hand or fingers may be worn only with the consent of the umpires.


PHP Remove " In GET

Question: I simply need a GET Variable that doesn't have any " marks. ' marks are okay, but " aren't. What do I need to do to fix that? And no, changing the " marks to ' do not work. I must do this because the GET is a URL link, so the URL link must be within two " quotes. If a " mark is within those lines, it will cause the link to stop short.
' . $_GET["test"] . '

My Code
<?php
$user = str_replace($_GET["user"], "\"", "'");
$user = "" . $user . "";
?>

Comment: There is nothing here that needs fixing. Can you be more specific?
Comment: You already wrote that. Try another way. *What* is it can't have *quotes*? *Why*?
Comment: Then look here: http://stackoverflow.com/questions/129677/whats-the-best-method-for-sanitizing-user-input-with-php.
Comment: Yes, it can't have the " mark...
Comment: Because it is in a URL link, so the URL link must be within two " quotes. If a " mark is within those lines, it will cause the link to stop short.
Comment: Although I've answered your question, you've not worded it very descriptively. Please consider adding more detail in the future.
Comment: @ChristianStewart: You have answered his question, but your answer is still not 100% correct. Exactly because there was not enough information to determine the correct answer.
Comment: Quite right, I have still answered the question "How do I remove " marks from a GET variable"
Comment: You reposted the question under a different username and said that we did not answer it... This is NOT acceptable behavior under SO rules and etiquette.. Needless to say I have expanded my answer to be a full solution.
Answer: You can simply fetch the $_GET[''] variable and use a find and replace to replace all the "
Example:
$myVar = str_replace($_GET["myVar"], "\"", "'");
$myStringWithVar = "" . $myVar . "";

Full example:
<iframe src="https://domain.tld/?user=<?php echo
str_replace($_GET["myVar"], "\"", "'");  ?>&password=' .
$_GET['password'] . '&version=99" height="30" width="500">

Please do not ask the same question again later on under a different username (as you have done)
Comment: And how exactly do I do that?
Comment: $user = str_replace($_GET["user"], "\"", "'");
$user = "" . $user . "";
Comment: Yes, you would use that... You asked how to fix the variable in that little itty bit of code you gave us, and this is my interpretation of what you were asking.
Comment: And this to display it? ' . $user . '
Comment: To display it you will want to type echo $myVar.
Comment: Still not working. I have  What am I doing wrong?
Comment: $user is not a variable... Please post more code, I can't see what you're doing.
Comment: I added the code involving the GET Variable.
Comment: Christian, tutoring is not a good use of time for that user. (Lots of deleted questions, banned accounts, more trivial inquiries to come the more you feed a [help vampire](http://meta.stackexchange.com/questions/19665/the-help-vampire-problem).)
Comment: Is there a better place for blood? Im hungry.
Comment: I like to help @mario Also you can't reference PHp things from html

PHP Remove " In GET


css: How display right of some li tags

Question: I'm creating a content slider with ul and li like:

content

content

content

content

content

content

content show

....ect

Now I want to show 3 contents on the left and 3 on the right and slider between of both.
I make to show all li id=(left and right) on the left and slider on the right but I cannot set li id="right" on the right listed.
How can display id="right" on the right of slider?
Like:
text               text
text CONTENTSLIDER text
text               text

Comment: What css do you already have? Also you should use ids only once per page, for `left` and `right` you should use css classes.
Comment: Please create a [jsFiddle test case](http://jsfiddle.net/) of your code.
Comment: You can only use an ID once in HTML. Use classes instead.
Answer: you have to use style's or css file, and give the div tabs width, abd each li use float style
try to use class="left" and class="right"
#tabs { width:600px;} //example
.left { float:left;}
.right { float:right;}

Comment: I use style. I set float:left for left id and float:right for right id, this is not the same?
Comment: this is similar, try to use classes
Answer: I'm not sure I get what you really want but maybe you can use the float:right attribute for all the li you want to go to the right!

css: How display right of some li tags


How do I convert the result fro views_get_view_result() to an array?

Question: I am getting an object from views_get_view_result().
Array
(
 [0] => Drupal\views\ResultRow Object
    (
        [_entity] => Drupal\node\Entity\Node Object
            (
                [in_preview] =>
                [values:protected] => Array
                    (
                        [vid] => Array
                            (
                                [x-default] => 9
                            )

                        [langcode] => Array
                            (
                                [x-default] => en
                            )

                        [revision_uid] => Array
                            (
                                [x-default] => 1
                            )

                        [revision_timestamp] => Array
                            (
                                [x-default] => 1508904645
                            )

                        [revision_log] => Array
                            (
                                [x-default] =>
                            )

How do I convert it to an array? My objective is to get the content types fields values. In an entity object there is toArray() to achieve this, but it doesn't work for what views_get_view_result() returns.
Answer: This is the entity you are looking for:
$node = $row->_entity;

And the field values:
$values = $node->toArray();

These are all of the values from the node, however if you want the results from the fields configured in the Views UI, see Get result view with formatter programmattically
Comment: It doesn't work. There isn't such thing as toArray()
Comment: It's hard to debug your code without knowing it, but suppose you have the rows in `$rows`, then loop over them with `foreach ($rows as $row)` and then you should be able to find the entity of each row in `$row`.
Comment: It works. Is there any way to do this without looping the object array?
Comment: Yes, you can use array functions, but this is more a php question.


Calculate $\sin{55}-\sin{19}+\sin{53}-\sin{17}$ without calculator

Question: So here is a trigonometric series.

$$\sin{55^\mathrm{o}}-\sin{19^\mathrm{o}}+\sin{53^\mathrm{o}}-\sin{17^\mathrm{o}}$$

Strange isn't it,  and I have to calculate the total result of the series (without calculator). I don't think Maclaurin series will help me any way. Further I tried almost all trigonometric identities (as per my knowledge) but so far I had no clue. Probably I am missing some kind of identity. Anyone can help me in this?

Note: It's not a homework question.
Comment: HINT: Use [Prosthaphaeresis Formulas](http://mathworld.wolfram.com/ProsthaphaeresisFormulas.html)
Comment: Hopefully arguments are degrees not radians.
Comment: @Jihad Yes. It's  in degrees.
Answer: Hint:
The key observation here is that $55+17=53+19$.
$$\sin{55}^\circ-\sin{19}^\circ+\sin{53}^\circ-\sin{17}^\circ=\color{#C00}{\sin55^\circ-\sin17^\circ}+\color{green}{\sin53^\circ-\sin19^\circ}.$$
Now use the identity
$$\sin a-\sin b=2\sin(\tfrac{a-b}2)\cos({\tfrac{a+b}2}).$$
Comment: Thank you. This was the identity which I was missing. Silly me.
Comment: Glad I could help!
Answer: You can use the following product-sum trig identity:
$$\sin (a+b) - \sin (a-b) = 2 \cos a \sin b$$
$$\sin (a+b) + \sin (a-b) = 2 \sin a \cos b$$
So, $$(\sin 55^\circ - \sin 17^\circ) + (\sin 53^\circ - \sin 19^\circ)$$
$$(2 \cos 36^\circ \sin 19^\circ) + (2 \cos 36^\circ \sin 17^\circ)$$
$$2 \cos 36^\circ (\sin 19^\circ + \sin 17^\circ)$$
$$4 \cos 36^\circ \sin 18^\circ \cos 1^\circ$$

We can find $\sin 18^\circ$ using the following method, and use $\cos 2x = 1 - 2 \sin^2 x$ to find $\cos 36^\circ$.
$\sin 72^\circ = 2 \sin 36^\circ \cos 36^\circ$
$\cos 18^\circ = 4 \sin 18^\circ \cos 18^\circ (1 - 2 \sin^2 18^\circ)$
$1 = 4x(1 - 2x^2)$ where $x = \sin 18^\circ$
$8x^3 - 4x + 1 = 0$
We can factor using a few methods, I think the easiest is to observe that $x = 1/2$ is a root and do polynomial long division of $(2x-1)$:
$(2x - 1)(4x^2 + 2x - 1) = 0$ We can't have $x = \frac{1}{2}$ because that's $\sin 30^\circ$, not $\sin 18^\circ$.
Quadratic formula: $x = \frac{-2 \pm \sqrt{20}}{8} = \frac{1}{4} (-1 \pm \sqrt{5})$
The root is positive, so it's $\frac{1}{4} (-1 + \sqrt{5})$. From this follows $\cos 36^\circ = \frac{1}{4}(1 + \sqrt{5})$

So, the above answer reduces to just $\cos 1^\circ$. This doesn't have a nice formula, but it is algebraic!
Comment: That's a neat way to find the exact values of sin(x) and cos(x) for not-so-nice values of x. I've never seen it before. Are there limitations to when this method can be used?
Comment: @Dasherman Yeah, there certainly are limitations. This case pretty much just happens to work out nicely.
Answer: HINTS: The sum and difference of trig sines is to be used.See how 20 degree difference can be used as a common factor.  4 (Cos[36. Degree]   Sin[18. Degree]) = 1 , must know the $ (\sqrt 5 \pm 1)/2 $ results.
Answer comes out as:  $ \cos( 1^0)$
Comment: I think you mean $(\sqrt{5} \pm 1)/4$ results
Comment: Yes, I mean generally one should know this Golden Ratio, sine, cos of multiples of 18 degrees etc., nice set of results.
Answer: You need $\sin54^{\circ}-\sin18^{\circ}=1/2$.
If you know complex numbers, the following formula will be obvious:
$$1+\cos72^{\circ}+\cos144^{\circ}+\cos216^{\circ}+\cos288^{\circ}=0$$
from which my first line follows.


The closure of neighborhoods are also interior in what kind of metric spaces?

Question: The definition of an open set $O$ is that any $x \in O$ has an open neighborhood with $N \subset O$. I am wondering in what kind of metric space is it true that there is a closure of such a neighborhood with $\overline{N} \subset O$.
I think the answer is that the metric space is complete (intuitively meaning that it has no "holes", so the closure is just including the boundary of the neighborhood) but I'm not sure about it, nor do I know how to prove it.
Answer: This is possible in any metric space. To see this, note that we may take $N$ to be a ball of radius $r$ for some $r$. Then every point in the complement of $O$ is a distance of at least $r$ from the center of $N$. If we let $B$ be the open ball with the same center but radius $r/2$, then the closure of $B$ consists of points that are at most $r/2$ away from the center and hence all such points are contained in $O$.
Comment: Oh, right. I just had a conceptual misunderstanding of a neighborhood in my head. Anyhow, is there a particular reason then that we choose neighborhoods to be open rather than closed?
Comment: @Soke for one, in my language neighborhoods are always open. Second, in topological spaces that are not metrizable we may not be able to find a neighborhood whose closure is contained in the open set.
Answer: If I'm understanding the question correctly, there is such an $N$ for every metric space.
Let $x_0\in O$ ($O$ is open in some metric space $A$). Then there is a ball $B(x_0,r_0)\subseteq O$.
Now if the metric is $d$, and $\iota:A\to A\times A$ is the function defined by $\iota (a)=(x_0,a)$, then $d\circ \iota :A\to \mathbb{R}$ is continuous (because both maps are continuous).
Set $M\subseteq A\times A$ where $M=(d\circ \iota)^{-1}([0,r_0/2])$. Then this set (which is really $\{x\in A|d(x_0,x)\leq r_0/2)\}$) is the preimage of a closed set under a continuous function, so it is closed. Also, $M\subseteq B(x_0,r_0)$
Define $N=B(x_0, r_0/2)$
Now notice that $N \subseteq M$, so $\overline{N}\subseteq M \subset B(x_0,r_0)$.


MySQL Views: polymorphic associations and child tables

Question: How to create views (producer_view and retailer_view) showing the total amount of each transaction SUM( unit_price * quantity ) when they are supplier and client ?
producer_view
+------+-------------------+-----------------+
| name | as_supplier_total | as_client_total |
+------+-------------------+-----------------+
| foo  |               144 |               9 |
| bar  |                 9 |             264 |
+------+-------------------+-----------------+

retailer_view
+------+-------------------+-----------------+
| name | as_supplier_total | as_client_total |
+------+-------------------+-----------------+
| baz  |                16 |             125 |
| qux  |               245 |              16 |
+------+-------------------+-----------------+

My two difficulties are that:

The supplier_id and the client_id for each transaction is stored in two polymorphic associations where supplier_type and client_type can be either App\Producer or App\Retailer.
The unit_price and quantity for each transaction are stored in a child table.

The two parent tables are:
Producer
+----+------+
| id | name |
+----+------+
|  1 | foo  |
|  2 | bar  |
+----+------+

Retailer
+----+------+
| id | name |
+----+------+
|  1 | baz  |
|  2 | qux  |
+----+------+

In a transaction, both producer and retailer can be either supplier or client.
Transaction
+----+---------+-------------+---------------+-----------+--------------+
| id | product | supplier_id | supplier_type | client_id |  client_type |
+----+---------+-------------+---------------+-----------+--------------+
|  1 | a       |           1 |  App\Producer |         1 | App\Retailer |
|  2 | b       |           2 |  App\Retailer |         1 | App\Retailer |
|  3 | c       |           1 |  App\Producer |         2 | App\Producer |
|  4 | d       |           2 |  App\Retailer |         2 | App\Producer |
+----+---------+-------------+---------------+-----------+--------------+

Details of each transaction is recorded in an item table:
Item
+----+----------------+------------+----------+
| id | transaction_id | unit_price | quantity |
+----+----------------+------------+----------+
|  1 |              1 |         10 |        1 |
|  2 |              1 |         20 |        1 |
|  3 |              2 |         30 |        1 |
|  4 |              2 |         40 |        1 |
|  5 |              3 |         50 |        1 |
|  6 |              3 |         60 |        1 |
|  7 |              4 |         70 |        1 |
|  8 |              4 |         80 |        1 |
|  9 |              5 |          2 |        2 |
| 10 |              6 |          3 |        3 |
| 11 |              7 |          4 |        4 |
| 12 |              8 |          5 |        5 |
+----+----------------+------------+----------+

SQLFiddle from the validated answer below:

producer_view
retailer_view
Answer: Try these queries:
For producer:
SELECT
  p.name,
  SUM(i.quantity * i.unit_price) AS as_supplier_total,
  cagg.as_client_total
FROM producer p
LEFT JOIN transaction t on t.supplier_id = p.id AND t.supplier_type = 'App\\Producer'
LEFT JOIN item i ON t.id = i.transaction_id
LEFT JOIN (
  SELECT
    p.id,
    SUM(i.quantity * i.unit_price) AS as_client_total
  FROM producer p
  LEFT JOIN transaction t on t.client_id = p.id AND t.client_type = 'App\\Producer'
  LEFT JOIN item i ON t.id = i.transaction_id
  GROUP BY p.id
) AS cagg ON cagg.id = p.id
GROUP BY p.id

For retailer:
SELECT
  r.name,
  SUM(i.quantity * i.unit_price) AS as_supplier_total,
  cagg.as_client_total
FROM retailer r
LEFT JOIN transaction t on t.supplier_id = r.id AND t.supplier_type = 'App\\Retailer'
LEFT JOIN item i ON t.id = i.transaction_id
LEFT JOIN (
  SELECT
    r.id,
    SUM(i.quantity * i.unit_price) AS as_client_total
  FROM retailer r
  LEFT JOIN transaction t on t.client_id = r.id AND t.client_type = 'App\\Retailer'
  LEFT JOIN item i ON t.id = i.transaction_id
  GROUP BY r.id
) AS cagg ON cagg.id = r.id
GROUP BY r.id

Comment: What does what does `cagg` stand for ?
Comment: Just a random alias (short for "client aggregation")


Calculating the area of a triangle defined in $\mathbb{R}^3$

Question:
In $\mathbb{R}^3:$
$$A = (2,0,-1)\\ B = (3,1,-1)\\ C = (4,-2,0)$$
Calculate the area of the triangle defined by $ABC$.

In $\mathbb{R}^2$, I usually perform an orthogonal projection to calculate the height of the triangle, and then
$$\frac{b\cdot h}{2}$$
It is not entirely clear to me how to do the same for $\mathbb{R}^3$. Well, let's do it either way:
Cast an orthogonal projection of $\vec{AC}$ over $\vec{AB}$:
$$Proj_{\vec{AB}}\vec{AC} = \frac{\vec{AC} \cdot \vec{AB}}{\vec{AB} \cdot \vec{AB}}\cdot \vec{AB}$$
$$\frac{(2,-2,1)\cdot (1,1,0)}{(1,1,0) \cdot (1,1,0)}\cdot(1,1,0)$$
$$\frac{0}{2}\cdot(1,1,0)$$
$$(0,0,0)$$
Huh, a null projection... Maybe I can't do it this way after all?
Comment: What you've done is prove that $AC\perp AB$. You were on the right track, you just didn't work your solution through (I presume you were trying to brute-force the $\frac{1}{2}bh$ area formula). The general formula that you were looking for was: $$\frac{1}{2}||AC-\text{proj}_{AB}{AC}||||AB||$$
Answer: Your work makes no sense. The area is zero if $\vec{AC}\perp \vec{AB}$?? Also, dot returns a scalar and you are taking dot of a scalar with a vector.
The best way is $\frac 1 2|\vec {AB} \times \vec {AC}| $
Answer: Awesome's answer is pretty economical.  If you're in the mood, a much more masochistic way would be to use the Pythagorean theorem to find the side lengths of the triangle, then apply Heron's formula.
Comment: Or take components of your area vector. Compute area of three projections separately and then take their resultant. $3$ times masochistic.
Comment: One might also calculate $\vec{AB} \times \vec{AC}$, normalize it as well as $\vec{AB}$, and multiply them to get an orthogonal base which puts the triangle into the $XY$ plane of a new coordinate system. Decompose vectors and *voila*, the problem is reduced to $\mathbb R^2$, which has a known solution.  ;)
Comment: Or manually count every pixel inside the triangle!


Prove completely regular space has the initial topology of all continuous functions into the unit interval

Question: From the definition, for a completely regular spaces $X$, a nonempty open set $U\subset X$, and a point $x\in U$, there exists a cts $f: X\to[0,1]$ s.t. $f(X-U)=0$ and $f(x)=1$. Then $x\in f^{-1}((1/2,1])\subset U$. Does this qualify as a proof of the statement in the title?
But aren't we supposed to show there are finitely many cts funcitons $f_i: X\to [0,1]$ such that $x\in \cap_1^nf_i^{-1}(V_i)\subset U$? I can't seem to find a proof in a textbook. That is, open preimages should only be a subbase, not a base, right? Thanks.
Update
It seems, in this particular case, preimages of open sets in $[0,1]$ do indeed form a base, not just a subbase, due to the following fact:

For $V_1, \cdots, V_n$ open sets of $[0,1]$, and $f_1,\cdots, f_n$ cts functions from $X$ to $[0,1]$, the intersection $U':=\cap_1^n f_i^{-1}(V_i)$ is open in $\tau$, and so, for every $x\in U'$, by definition of completely regularity, there exists a cts $f:X\to [0,1]$ s.t. $f(X-U')=0$ and $f(x)=1$. So $U'':=f^{-1}((1/2,1])\subset U'$.

That is, we don't need finite intersections of open preimages to from a base, the open preimages themselves do form a base!! Based on @Chad_K's answer.
Answer: Let $\tau$ be the topology on $X$ and $\tau_w$ be the initial topology from all continuous functions to $[0,1]$.  Your argument shows that members of $\tau_w$ are a base for $\tau$.  So every member of $\tau$ is a union of members of $\tau_w$, so every member of $\tau$ is a member of $\tau_w$.  So $\tau\subseteq \tau_w$.
For the other direction, let $x\in S\in\tau_w$.  By definition there are sets $V_1,\ldots,V_n\subseteq [0,1]$ such that $V_i$ are open in $[0,1]$ and continuous functions $f_1,\ldots,f_n$ such that $x\in\bigcap_{i=1}^n f_i^{-1}(V_i)\subseteq S$.  But each $f_i^{-1}(V_i)$ is $\tau$-open because the $f_i$ are continuous.  So $\bigcap_{i=1}^n f_i^{-1}(V_i)$ is $\tau$-open.  This shows that members of $\tau$ are a base for $\tau_w$.  So by similar argument to above, $\tau_w\subseteq \tau$.
Comment: It seems to me $\tau_w\subset \tau$ is an automatic fact, and requires no proof at all. My question really is about, shouldn't preimages of open sets only form a subbase, not a base?
Comment: @user760:  If $V\subseteq[0,1]$ is open and $f\colon X\to[0,1]$ continuous, sets of the form $f^{-1}(V)$ are a *subbase* for $\tau_w$.  They also turn out to be a base for $\tau$.  That's not a problem.  It just means that a space being 'completely regular' is more demanding that saying $\tau=\tau_w$.
Comment: Thanks! So in this case, open preimages form a subbase that is also a base! I didn't realize that.


In how many bases the last digit of $2013$ will remain $3$?

Question: In $10$ base number system, the last digit of $(2013)$ is $3$
But When it is written in base $9$ then $(2676)_9$, So, the last digit is 6
Then, in how many bases the last digit of $2013$ will remain $3$?
Comment: @costrom That doesn't matter. The question boils down to: for what $n$ is $2013= 3 \pmod n$.
Comment: how do you want digits represented in bases above 10?
Comment: @costrom Yes, the base can go above 10.
Comment: @RezwanArefin If you still don't see this think about this: if $2013-3=2010$ is divisible by some number $n$ ($n >3$) this means that $2010$ can be written in some base $n$ without remainder , or ,in other words,the last digit in that base is $0$ so when you add $3$ you can substitute it as last digit ($2010= ab...c3_n$ where the subscript $n$ indicates the base in which the number is written).
Answer: The last digit always represents the digit for $b^0=1$. You can generally say that it will be the represented number modulo the base. So you're asking for how many numbers $n$ does $2013\equiv3\mod n$ hold. For $n>3$ this is equivalent to asking for the factors of $2010$. Factorizing $2010$ can be easily done by hand and will yield the answer to your question. Also, we need to subtract $3$ from the number of factors of $2010$ since the factors $1,2,3$ will not leave $3$ as the remainder.


What is a good guitar solo to learn in the minor scale?

Question: I am starting to play and improvise in the minor scale, and I would like to learn some guitar solos that are good examples of this scale so that I see how other people use it. What are some famous solos in contemporary or classic rock that make use of the minor scale? Which flavor of the minor scale are they using (natural, melodic, harmonic)?
Update:
I asked the question in this form because I thought it was more generically useful, but some of the answers aren't quite getting at the question because they're assuming I'm a beginner.  I'm a teacher, not a beginner, and I find that my students learn scales, theory, and improvisation much better if they learn it in the context of a song they know. I was looking for some new examples to change up my teaching a little.
Answer: I believe an excellent song for soloing in the full minor key is Black Magic Woman by Santana.  It has solo parts that you can learn, but is also a generally welcoming song to improvise on top of.
I'd also consider Dream On by Aerosmith.  With some simple fills and more tricky short solos, it has something for guitarists of many skill levels.
While not entirely in a minor key, there are some excellent minor-key soloing licks to be found in Hotel California by The Eagles.
A lesser-known song that has some great minor solos in it is the studio release of Hey Baby (New Rising Sun) by Jimi Hendrix (look for it on the recently released First Rays of the New Rising Sun album, also on Voodoo Child - The Jimi Hendrix Experience).
All of these tunes use the natural minor key; while I am not a music theory expert, it sounds to me like Hotel California employs all three minor flavors... it's in Bm but features a sharp 6th and 7th in its progression.
Good luck!
Answer: Seriously? Most songs either use major or minor and they are effectively the same scale. Just about any blues will be based on the minor pentatonic which is a subset of the aeolian mode. Most classical pieces in minor will be based on the harmonic minor and baroque pieces tend to be based on the melodic minor.
Most rock songs are based on blues and hence use the minor pentatonic but also incorporate the major pentatonic(blues does to in a sense as it does add it's own notes).
Stairway to heaven has a nice solo in A minor that isn't too difficult and almost comes strange from the pattern.
Learn your scales if you want to practice them. Simply learn to solo with them by making up your own(that way you are using more of your ear than your memory). Of course learn your favorite solo's too(at least some parts).
I think it would serve you better to ask what you are trying to learn and what you want to accomplish(short term). There are millions of songs and almost all are based around 12 notes... can't be too complex can it? ;)
Comment: C major and A minor contain the same notes, but they are certainly not the same scales.  for starters C starts on C, and A starts on A :O  But a less condescending answer is to say that the relationship between the tonic and the intervals around it make the C major and A minor scales very different beasts.  If you're playing A minor over a C major chord progression you're going to have some troubles.
Comment: Right. I'm not talking about how to fret the scale though, I'm talking about songs that are in the key of A minor (or any other key). Whether or not they think about a scale as strictly A minor or the relative minor of C major doesn't change the fact that a piece is in A minor and not C major. Which is why I said they're different. While the major and minor key are related and some major keys use the same notes as a minor key, C Major is different from C Minor and I'm looking for songs with a minor sound. And that's not getting in to harmonic or melodic minor.
Comment: Yes, seriously. Minor and Major are not effectively the same scale. While there is a relative minor with the same notes, C major and C minor do not sound the same at all. Also, see the update to my question. I'm actually a teacher and was looking for some suggestions for students. I phrased it the way I did because I thought it would be more generally useful for the site. Probably not the best idea in hindsight.
Comment: C major and A minor ARE THE SAME SCALES(effectively, in minor we actually modify the scale to make it more like major and end up with the melodic minor scale). If you are teaching the parallel concept... e.g., C major vs C minor, then it is good in some regards but bad in others. The reason is that it can be too difficult for some to learn to play in those scales. They learn there patterns for major and minor when in fact they can learn half the information by realizing that C minor is the same scale as Eb major.
Comment: It also helps with improvising because they don't have twice as much information to wade through.  If you teach someone(and show them) that A minor and C major have the same notes... and in reality all the modes are just the same notes from a set of notes, then they can start playing immediately regardless if they understand it or not.  I can force someone to play in dorian regardless if they know it or not as long as they know how to play in some mode of dorian(e.g., C ionian). Of course they may be emphasizing all the wrong notes(such as E and G rather than D and F).
Comment: Of course the bad thing is that they may end up actually believing that it's the same notes and never truly learn to express the mode(for example as a solo line). In any case C major and A minor are effectively the same scale. They are relative's of each other. If you know how to play in C major your 90% of the way of playing in Aminor(and hence Cminor and every other minor if it's on guitar since the patterns are movable). (
Comment: Minor pentatonic is a subset of both the Aeolian and Dorian modes. For newbies: one can think of pent minor as an abstract essence of minor, with Aeolian and Dorian adding unique colours to the tonal palette.
Comment: Also think of Pat Martinos concept of converting-to-minor how useful minor can be applied
Answer: I'm not sure how "modern" he is, but Robin Trower used a Minor Pentatonic scale for a majority of his early recordings: "Caledonia"
Deep Purple: "Highway Star" both guitar and keyboard solos
Albert Collins: He used a Minor Key tuning so learning his solos will give you great insight into using Minor Pentatonic in a Blues setting
Jeff Beck: Cause We Ended As Lovers - which is dedicated to Roy (Buchanan), who was also a master soloist in Minor Keys
I know that these are old school: Enjoy!!
Answer:
Guns N Roses "Sweet Child O' Mine" guitar solo is in E harmonic minor.
Van Morrison's "Moondance" is in A Dorian.
Carlos Santana uses A minor and A harmonic minor in the song "Smooth".
Answer: "Mood For A Day" is an acoustic solo guitar piece by Steve Howe on the Yes album Fragile. It is in B (harmonic) minor. It requires finger-style picking. This piece was my segue to Segovia; it is what I auditioned for my classical guitar teacher, although my performance was not as fluid as the original.
Answer: Here are three Led Zeppelin's songs written in the Aeolian minor mode based on the natural minor scale: Since I've Been Loving You, Stairway To Heaven, Dazed and Confused.
for my taste, there are outstanding guitar riffs and solos there. harmonic analysis of these songs here


General questions regarding text-classification

Question: I'm new to Topic Models, Classification, etc… now I'm already a while doing a project and read a lot of research papers. My dataset consists out of short messages that are human-labeled. This is what I have come up with so far:

Since my data is short, I read about Latent Dirichlet Allocation (and all it's variants) that is useful to detect latent words in a document.
Based on this I found a Java implementation of JGibbLDA but since my data is labeled, there is an improvement of this called JGibbLabeledLDA
In most of the research papers, I read good reviews about Weka so I messed around with this on my dataset
However, again, my dataset is labeled and therefore I found an extension of Weka called Meka that had implementations for Multi-labeled data
Reading about multi-labeled data, I know most used approaches such as one-vs-all and chain classifiers...

Now the reason me being here is because I hope to have an answer to following questions:

Is LDA a good approach for my problem?
Should LDA be used together with a classifier (NB, SVM, Binary Relevance, Logistic Regression, …) or is LDA 'enough' to function as a classifier/estimator for new, unseen data?
How do I need to interpret the output coming from JGibbLDA / JGibbLabeledLDA. How do I get from these files to something which tells me what words/labels are assigned to the WHOLE message (not just to each word)
How can I use Weka/Meka do get to what I want in previous question (in case LDA is not what I'm looking for)

I hope someone, or more than one person, can help me figure out how I need to do this. The general idea of all is not the issue here, I just don't know how to go from literature to practice. Most of the papers don't give enough description of how they perform their experiments OR are too technical for my background about the topics.
Answer: If you are new to classification or machine learning in general, reading books, research papers and etc. is hard, because it requires some background (probability, calculus and linear algebra).
If you have some background in probability you will understand the folowing:

LDA is a generative model.
Generative model - It specifies a joint probability distribution over observation and label sequences

In this paper Latent Dirichlet Allocation is described in details how to use LDA and in which cases.
Comment: I have some background in calculus and linear algebra and I understand the essence of probability and distributions over words etc… The hardest part is to really understand how I can use this in practice with the tools mentioned (JGibbLDA, WEKA/MEKA, etc…)
Comment: Well for the programming part i can't help you (since i have never used the frameworks). But if you are using a framework for data mining there must be some code examples on the net.


drill down taxonomy node count using views

Question: I don't know if I'm the only one having this issue but my problem seems to be common. I just could not find the solution here and Google.

My site have the taxonomy menu:
Classifieds
  Electronics
  Autos
Jobs
  Accounting
  Information Technology
I just want to show a summary for every term that has children on it. E.g., When you click on Classifieds it should show like this:
Electronics(160)
Autos(310)
And when you click on Autos(310) it should show for example:
Aston Martin(200)
Toyota(110)
And then drill down to the last child item with node count. (e.g. DB9 Coupe (xx) etc..)
When I use the views default summary display and you clicked on 'classifieds' it will show:
Free Stuffs(xx)
DB9 Coupe(xx) <-- this should should first as 'Autos' and not show the last child in the hierarchy!
Basically, it's just a page with summary counts of terms being used in nodes and count them by level in the taxonomy hierarchy. So, from clicking a parent term, the first child terms will only show with node counts, then when clicking on one child only the children of this child will show with node counts etc..
Thank you in advance!
Answer: FYI. For those who have the same issue above. I managed to do this in Drupal 7 and it's called facet search primarily using Apache Solr or without Apache Solr here
Comment: Hi,I have the same issue,how did you manage it?Could you tell the configuration of facets?thanks


how can i display a result from a server javascript function to a html page using angular

Question: This is a form that will go to the javascript page and will upload the photo to the server

                   <form id        =  "uploadForm"
                      enctype   =  "multipart/form-data"
                      action    =  "/api/photo"
                      method    =  "post">

                      <input type="file" name="userPhoto" />
                      <input type="submit" value="Upload Image" name="submit">
                   </form>

This is the JavaScript function
 function confirmUploaded() {
  res.end("File was successfully uploaded -- " + outText);

}

How would i call this function from the JavaScript file to the HTML page
Comment: I'm not sure what you're asking. Do you want to call the function when the user's hits submit?
Answer: res.end is not a client side, It is a server side code and need to be send from the server end(NodeJS).
Make use of $http.success in angular and then on success attach the result to a particular div or header tags and use css for formatting.


CDI : @Specializes bean can replace only one bean?

Question: Env:
    Wildfly 9.0.1
    Weld 2.2.14

Going by CDI spec and the way @Specializes works, seems to me that a @Specializes bean can only replace 'a' bean/implementation and not 'some' beans/implementations.
I find this strange given the flexibility that interfaces and qualifiers provide.
Let me give the scenario via example code:
Bean classes:
interface Animal {
  public String getName();
}

@Siamese
public class Cat implements Animal {
  @Override
  public String getName() {
    return "Siamese";
  }
}

@Labrador
public class Dog implements Animal {
  @Override
  public String getName() {
    return "Labrador";
  }
}

Injection points:
@Siamese
@Inject
private Animal cat;

@Labrador
@Inject
private Animal dog;

Given the code, my intention is to provide one @Specializes mock bean that can be injected into both the injection points listed above. Here is the mock bean
@Alternative
@Specializes
public class MockAnimal implements Animal {
  @Override
  public String getName() {
    return "Mock Animal";
  }
}

But this seems impossible as the MockBean must "extend" whichever bean it needs to specialize.
Wanted to check with you guys if there is a work around other than creating MockDog and MockCat.
Thanks in advance,
Rakesh
Comment: I guess you could try to annotate your mock with both qualifiers Siamese and Labrador. In that case the mock bean would be elligible on both injection points.
Answer: Normally, what you would want to use is only @Alternative without @Specializes, and add all qualifiers you want your bean to be injected with. @Specializes is only necessary when you want the new bean completely cover the old bean without copying its qualifiers, and even for injection points that use @Any annotation.
Solution for you example would then be:
@Alternative
@Labrador
@Siamese
public class MockAnimal implements Animal {
  @Override
  public String getName() {
    return "Mock Animal";
  }
}

The only injection point, where this would not cover Cat and Dog beans, would be an injection point with @Any, like this:
@Any
Instace<Animal> allAnimals;

This would list all 3 implementations of Animal, even with the alternative enabled. But it seems that this is not your concern.


What is the meaning and intuition behind Laplace's method for the maximum of a function?

Question: I am reading the book Bandit Algorithms. On page 257, it talks about how to approximate the maximum of a function with Laplace's method. I cannot understand how this method can be used to find the maximum of a function. The book presents Laplace's method as follows:

Assume that $f:[a,b]\rightarrow\mathbb{R}$ is twice differentiable and has a unique maximum at $x_0\in (a,b)$ with $-q=f^{''}(x_0)<0$. Laplace's method for approximating $f(x_0)$ is to compute the integral
$$
I_s=\int_{a}^{b}\exp\left( sf(x) \right)\: dx
$$

I am wondering how we can determine $f(x_0)$ from $I_s$. I would be thankful if someone can give me an example and intuition behind this method. I read Wikipedia page but I don't understand how it can be used to find the maximum of a function.
on Page 258, it presents "Method of Mixtures" as follows:

Lapalce's approximation suggests that $\max_{x} \: M_t(x)\approx \int_{\mathbb{R}^d} M_t(x)\: dh(x)$, where $h$ is some measure on $\mathbb{R}^d$ chosen so that the integral can be calculated in closed form.

I am wondering if $h(x)$ should be always a probability distribution and if $M_t(x)$ can be any arbitrary function.
Answer: The intuition behind Laplace's method is that because the exponential function exaggerates large values, as $s\rightarrow \infty$, the function $x\mapsto e^{sf(x)}$ will eventually be totally dominated by its maximum value, which is $e^{s f(x_0)}$, where $x_0$ maximizes $f$.
It's easier to see this in the discrete case first, so let $f \colon \{1, \dotsc, n\} \rightarrow \mathbf{R}$ and let $x_0 = \mathop{\mathrm{argmax}}_{x} f(x)$ be a unique maximizer.
Now, we have that
\begin{align*}
\sum_{x=1}^n e^{sf(x)}
&= e^{s f(x_0)}\sum_{x=1}^n e^{s(f(x) - f(x_0))} \\
&= e^{s f(x_0)}\Bigl(1 + \sum_{x\neq x_0} e^{s(f(x) - f(x_0))}\Bigr) \\
&= e^{s f(x_0)}(1 + o(1)),
\end{align*}
where we see that the latter sum is $o(1)$ from the fact that $f(x) < f(x_0)$ for each $x \neq x_0$.
Therefore, in this case, we can determine $f(x_0)$ from the resulting limit
$$
\frac{1}{s}\log\Bigl(\sum_{x=1}^n e^{sf(x)}\Bigr)
\rightarrow f(x_0).
$$
The continuous case is more complicated since we have to take into account the curvature of $f$ at $x_0$, but the idea is the same.
I'll omit the technical details, which are presented in the textbook that you linked, but the upshot is that the analogous result is that
\begin{align*}
\int_a^b e^{s f(x)} dx
&= e^{s f(x_0)} \sqrt{\frac{2\pi}{s |f''(x_0)|}}(1 + o(1)),
\end{align*}
from which we similarly get that
$$
\frac{1}{s}\log\Bigl(\int_a^b e^{s f(x)} dx\Bigr)
\rightarrow f(x_0).
$$

As for your second question, the $h$ need not be a probability measure, and that this doesn't matter much due to the very liberal meaning of $\approx$.
In particular, since we're taking $s^{-1}\log I_s$, the $\approx$ can hide even any polynomial factor without affecting the result.
So unless $h$ is really bad (like $dh(x) = e^{|x|} dx$ or something), there's no problem.
We can again see what's going on schematically in the discrete case, so let $h$ be any measure on $\{1, \dotsc, n\}$.
We then have that
\begin{align*}
\int e^{s f(x)} dh(x)
= \sum_{x=1}^n e^{s f(x)} h(x)
= e^{s f(x_0)}(h(x_0) + o(1)),
\end{align*}
from which we have
\begin{align*}
\frac{1}{s}\log \Bigl(\int e^{s f(x)} dh(x)\Bigr)
= f(x_0) + \frac{1}{s}\log(h(x_0) + o(1))
\rightarrow f(x_0).
\end{align*}
Basically, $e^{s f(x)}$ only cares about what's going on in the immediate vicinity of $x_0$, where the value of the measure is approximately constant.
But then any constant contribution gets killed by the $s^{-1} \log I_s$ transformation.
Comment: See the latest edits to my post
Comment: Right, but in the textbook $M_t(x) = \exp\{\langle x, S_t\rangle - \frac{1}{2}\lVert x\rVert_{V_t(\lambda)}^2\}$, which is sort-of of the form $e^{t f(x)}$. Of course, it isn't exactly, but this is why Laplace's method merely "suggets" the approximation rather than showing it
Comment: Thank you so much for the great explanation. Regarding the "Method of Mixtures", I would be thankful if you could help me know what are the requirements for this method.
Comment: Thanks @Damian. Your answer for the second part seems a bit different. I mean you considered $\int e^{sf(x)} dh(x)$ but not $\int f(x)\: dh(x)$.
Comment: Ooo. I missed this point and I thought that it is true for all functions. I really appreciate your help


Simulation data using a dataframe

Question: I want to simulate an existing dataset to get the best model.Considering the following dataset and I want to create 100 or 1000 sample using this data in R. Any help?
x<-data.frame( A=c("A","B","M","N","P"),
B=c("G","N","P","R","I"),
C=c("T","F","L","U","U"),
D=c(9,12,13,13,12),
E=c(14,17,10,19,10),
F=c(10,12,19,17,15),
G=c(7,12,10,14,15),
H=c(18,19,19,12,12),
I=c("K","L","M","F","D"),
J=c("C","V","O","N","F"),
K=c("G","N","P","P","I"))

Comment: it's really not at all clear what you want to do.  The generic recipe for bootstrapping is `boot_data <- x[sample(nrow(x),size=nrow(x),replace=TRUE),]` ...
Comment: @Ben I want  to create say 1000 sample with 1000 rows using the data set provided to find out the best model for my data. This would help to find out the bias
Comment: @@  Ben Bolker , does  the function of set.seed (1) make sens in your codes ( if I want to use)?
Answer: If you want 1000 data sets, try putting them all into list with this.
lapply(1:1000, function(i, x) x[sample(nrow(x), size=1000, replace=TRUE), ], x)

Although I'm not sure what the value of using a simulated data sets of size 1000 from a sample of fewer observations.  I believe Ben Bolker's recommendation of size=nrow(x) is probably the more sound way to approach this.

Simulation data using a dataframe


Quasar QList pagination with QPagination component and laravel paginate() method

Question: I want to paginate a list made with the QList component
With the laravel paginate() method I receive on the client side the following data necessary for pagination:
current_page:
data:[]
first_page_url:
from:
last_page:
last_page_url:
next_page_url:
path:
per_page:
prev_page_url:
to:
total:

I'm getting started with Quasar framework and I want a simple QList pagination solution.
Apparently the QPagination component will be suitable for this purpose.
I would appreciate suggestions on how to implement a working QPagination or other simple solution.
EDITED
Some code to demonstrate what I am trying to achieve
<template>
  <q-page class="fit row wrap justify-center items-start content-start" style="overflow: hidden;">

            <q-list bordered separator v-for="(post, index) in posts" :key="index">
              <q-item clickable v-ripple>
                  <q-item-section>
                        <q-item-label> {{ post.title }} | {{ index }}</q-item-label>
                        <q-item-label caption> {{ post.content }}</q-item-label>
                   </q-item-section>
              </q-item>

            </q-list>

                    <q-pagination
                          v-model="page"
                          :min="currentPage"
                          :max="totalPages"
                          :input="true"
                          input-class="text-orange-10"
                    >
                    </q-pagination>

  </q-page>
</template>

EDITED » To better illustrate the problem to solve:
<template>
  <q-page class="fit row wrap justify-center items-start content-start" style="overflow: hidden;">

            <q-list bordered separator v-for="(post, index) in posts" :key="index">
              <q-item clickable v-ripple>
                  <q-item-section>
                        <q-item-label> {{ post.title }} | {{ index }}</q-item-label>
                        <q-item-label caption> {{ post.content }}</q-item-label>
                   </q-item-section>
              </q-item>

            </q-list>

                    <q-pagination
                          v-model="page"
                          :min="currentPage"
                          :max="totalPages"
                          :input="true"
                          input-class="text-orange-10"
                    >
                    </q-pagination>

            <button v-if="prevPage" class="text-grey-darker text-sm" style="margin-right:10px;" @click="goPrevPage(prevPage)">
                Prev. Page | Pag. {{currentPage}} of {{totalPages}}
            </button>
             <button  v-if="nextPage"  class="text-grey-darker text-sm" @click="goNextPage(nextPage)">
                Next Page | Pag. {{currentPage}} of {{totalPages}}
            </button>

  </q-page>
</template>

EDITED with working solution
<template>
  <q-page class="fit row wrap justify-center items-start content-start" style="overflow: hidden;">

            <q-list bordered separator v-for="(post, index) in posts" :key="index">
              <q-item clickable v-ripple>
                  <q-item-section>
                        <q-item-label> {{ post.title }} | {{ index }}</q-item-label>
                        <q-item-label caption> {{ post.content }}</q-item-label>
                   </q-item-section>
              </q-item>

            </q-list>

                    <q-pagination
                          v-model="page"
                          :min="currentPage"
                          :max="lastPage"
                          input
                          input-class="text-orange-10"
                          @input="goAnotherPage"
                    >
                    </q-pagination>

  </q-page>
</template>

Comment: Thanks hurnhu. Frankly, I've made several attempts to implement the QPagination component, but looking at the template, the script and the component's api, I still can't understand how this component works. It would be helpful if the documentation had some more information about this.
Comment: If you provide code you have tried, we can help fix it. But we cant just provide a full solution. Join their discord, they are really helpful, im sure someone there can help
Answer: Just use the computed property for getting data based on pagination.
getData(){
  return this.posts.slice((this.page-1)*this.totalPages,(this.page-1)*this.totalPages+this.totalPages)
}

<q-list bordered separator v-for="(post, index) in getData" :key="index">
    <q-item clickable v-ripple>
        <q-item-label> {{ post.title }} | {{ index }}</q-item-label>
        <q-item-label caption> {{ post.content }}</q-item-label>
    </q-item>
</q-list>

Working codepen - https://codepen.io/Pratik__007/pen/PowpOeL
Comment: You can use this or use Qtable.
Comment: Thanks Patel works fine for my first example case and was a great help. thanks again. I am studying Quasar's various pagination possibilities. Qpagination is getting complicated for me. I think for a real case with laravel paginate () that only brings a few records in each request, somehow I have to fire methods with the component's navigation arrows (I couldn't figure out from the api how to do it). I built an example case with two buttons (PrevPage and NextPage) to better illustrate what I want to achieve.
Comment: Sorry but I don't have any idea about laravel pagination.
Comment: Thanks Patel. I edited my post with a solution that works well for me.