Student's t-test on "high" magnitude numbers

Question: I am trying to calculate whether the difference between the two benchmarks is statically different or not.
The input is req/sec of a HTTP Server and I'm using scipy.stats.ttest_ind to calculate the p-value.
A1 = [
  4670, 4646, 4612, 4618, 4646,
  4609, 4623, 4629, 4566, 4628,
  4582, 4636, 4621, 4574, 4624,
  4563, 4651, 4642, 4586, 4621,
  4606, 4628, 4575, 4631, 4646,
  4600, 4594, 4661, 4568, 4611
]

B1 = [
  4630, 4655, 4652, 4633, 4637,
  4661, 4625, 4680, 4647, 4639,
  4633, 4661, 4638, 4621, 4630,
  4682, 4703, 4665, 4652, 4648,
  4673, 4651, 4669, 4646, 4612,
  4654, 4651, 4619, 4637, 4620
]
st.ttest_ind(A1, B1)
# Ttest_indResult(statistic=-4.855056212284194, pvalue=9.47100493260572e-06)

Why the value is 9.47100493260572e-06? I was expecting to see a value bigger than 0.05 because the input is pretty similar and the means are relatively close, too: 4615 vs 4647
Am I missing something?
Comment: Change the origin of your units to 4600 and look again at the data.  Plotting the distributions of the two groups would be a good idea.
Comment: The question omits details about the domain and the problem at hand, so it's hard to consider whether a t-test is a great choice. It might be interesting to read about equivalence testing.
Answer: The t-test does not care about the magnitudes of your values. The t-test concerns itself with their variance. You are correct that your numbers look to be roughly aligned. However, the distributions appear to be rather tightly clustered, meaning low enough variance for the difference in means to be statistically significant.
What you're allowed to do is ignore the statistical significance and decide that the means are close enough together, based on your knowledge of the process under study, that you accept this difference. This gets into practical significance, as opposed to statistical significance.
Comment: @RafaelGonzaga Then why are you hypothesis testing the means? You might consider posting a new question where you explain your data and goals in more detail, as the specifics of those really are not pertinent to the question asked here.
Comment: My point was that the test doesn't care about raw magnitudes, just how spread out the groups are from their means. I'll think about how to edit in an improved phrasing, bearing in mind that the OP found the original post to be helpful.
Comment: Thanks, that was enlightening. However, trusting the mean between results, specifically on HTTP Benchmarks, is not reliable considering the fact of outliers.

I am trying to use the student t-test approach to compare performance optimizations between two branches. Is there a better approach to use? Thanks in advance
Comment: You right. Thanks!
Comment: It is really correct to say that "the t-test concerns itself with (...) variance"?
Comment: @dipetkov How do you figure it doesn't concern itself with variance?
Comment: I just think it's poor phrasing. The way I understand it is that the objective of t-test is actually the location and the scale is a nuisance parameter.
Comment: Yes, of course you are right that the t-statistics is normalized for the standard deviation, or an estimate of it at least.
Comment: @Rafael Outliers will normally affect the power of a t-test more than the level, meaning that if you get significance despite the outliers, chances are you will also get significance if you do something to deal with the outliers (like for example testing equality of medians). Ultimately a significance test (no matter which) may not be what you need here, for the reasons given in Dave's answer.
Answer: This is more of a comment or extension to the answer by @Dave.  You should always plot your data, and could have included such a plot in your question. Below is plots that help to show the difference between the groups. I use R for the plots, at the end I give the code used.

This is simply a boxplot with the individual points overplotted.  Alternatively, we can show histograms:

The R code used is:
A1 <- c(
  4670, 4646, 4612, 4618, 4646,
  4609, 4623, 4629, 4566, 4628,
  4582, 4636, 4621, 4574, 4624,
  4563, 4651, 4642, 4586, 4621,
  4606, 4628, 4575, 4631, 4646,
  4600, 4594, 4661, 4568, 4611
)

B1 <- c(
  4630, 4655, 4652, 4633, 4637,
  4661, 4625, 4680, 4647, 4639,
  4633, 4661, 4638, 4621, 4630,
  4682, 4703, 4665, 4652, 4648,
  4673, 4651, 4669, 4646, 4612,
  4654, 4651, 4619, 4637, 4620
)
library(ggplot2)
library(hrbrthemes)

df <- data.frame( req = c(A1, B1),
                  benchmark=c(rep("A", length(A1)), rep("B", length(B1)))
)

ggplot(df, aes(benchmark, req, color=benchmark)) + geom_boxplot() +
  geom_point()

### Side-by-side histograms

ggplot(df,aes(req, ..density.., fill=benchmark)) +
  geom_histogram(color="#e9ecef",alpha=0.4, bins=10, position="identity") +
  theme_ipsum() + scale_fill_manual(values=c("#69b3a2", "#404080"))

Comment: @Rafael The focus of the suggest is not *shall I use a t-test?*. Instead, it is a recommendation to visualize the data very early (as a tool complementary to e.g., a t-test) by an affordable plot. This could be: to recognize if a distribution might be normal, or skewed, or tailed, plot a histogram.  For a relationship between dependent and independent variable perhaps linear, or exponential, or different, plot a scatter plot ([Anscombe's quartet](https://en.wikipedia.org/wiki/Anscombe%27s_quartet)). *And then* engage with the computation(s), tests, modelization, plots for the final report.
Comment: Thanks for the explanation of the graphs. I came from a different area, therefore, some foundations are not very clear to me.
It's not very clear to me to understand when should I use the t-test approach, should I create a new question?
Comment: @Rafael Looking at this plot, the mean different between groups is very clear, and outliers are not an issue. So your test result is fine, what's wrong was your expectation what the result should be.
Answer: I strongly support the stance of @kjetil b halvorsen that visualization is the first priority. This would be a comment on his answer except that I have a different graph to show.
The spirit of plotting all the data, plus a summary, is excellent. Kjetil's graph in practice raises two comments on details.

The plot doesn't show means. As it happens, the means are close to the medians, but you are not always so lucky.

A dot plot or strip plot in a single line will not be easy to work with if there is much over=plotting of similar or identical values. Same comment: As it happens, that is not a major problem here, but you are not always so lucky.

This plot follows the spirit of Emanuel Parzen's suggestion that a quantile plot together with a box gives a good picture of the data.
The boxes conventionally show medians and quartiles. The quantile plos show the points in order with a tacit horizontal scale of rank or plotting position. So, outliers, gaps, tied values and other fine structure are all evident if they exist. The longer horizontal lines show the means. (Incidentally, each mean is also the area under the quantile function expressed as a continuous curve and as a function of cumulative probability.)


Chai expect that result equals one of three options

Question: I am using enzyme and chai to test my React application. I want to write an expectation that tests that the result is equal to one of three possible options.
For example (sudo code):
expect(result).to.eq('red').or('green').or('yellow');
or
expect(result).to.beOneOf(['red','green','yellow']);
Is there a way I can do this?
Answer: I found this solution on stackoverflow
Chai expect to be one of array elements
Looks like I can switch my expectation around like this"
expect(['red', 'yellow', 'green']).to.include(result);


Problema ao salvar

Question: Somente um formulário que está me retornando esse erro, a questão que eu não sei oque pode ser ou como faz para arrumar, alguns pedem pra coloca o relacionamento em cascata oque já está.

NHibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing or set cascade action for the property to something that would make it autosave. Type: BlogWeb.Models.Veiculo, Entity: BlogWeb.Models.Veiculo

Linha de retorno de erro:
public void Adiciona(Abastecimento abastecimento)
    {
        ITransaction tx = session.BeginTransaction();
        session.Save(abastecimento);
        tx.Commit();
    }

Veiculo Mapping:
public class VeiculoMapping : ClassMap<Veiculo>
{
    public VeiculoMapping()
    {
    Id(p => p.Id).GeneratedBy.Identity();
    Map(p => p.NCarro);
    Map(p => p.Modelo);
    Map(p => p.Ano);

    }
}

Veiculo Model:
public class Veiculo
{
    public virtual int Id { get; set; }
    [Required]
    public virtual int NCarro { get; set; }
    [Required]
    public virtual string Modelo { get; set; }
    public virtual int Ano { get; set; }
}

Abastecimento Mapping:
public class AbastecimentoMapping : ClassMap <Abastecimento>
    {
        public AbastecimentoMapping()
        {
            Id(a => a.Id).GeneratedBy.Identity();
            Map(a => a.DtAbastecido);
            Map(a => a.Litro);
            Map(a => a.VlrUnit);
            Map(a => a.Km);
            Map(a => a.TotalGasto);
            Map(a => a.Km_Andado);
            References(a => a.NomeProduto, "NomeProdutoId");
            References(a => a.Autor, "AutorId");
            References(a => a.NumCarro, "NumCarroId");
        }
    }

Abastecimento Model:
public class Abastecimento
{
    public virtual int Id { get; set;}
    [Required]
    public virtual int Litro { get; set; }
    public virtual DateTime? DtAbastecido { get; set; }
    public virtual decimal VlrUnit { get; set; }
    public virtual int Km { get; set; }
    public virtual decimal TotalGasto { get; set; }
    public virtual int Km_Andado { get; set; }
    public virtual Usuario Autor { get; set; }
    public virtual Compra NomeProduto { get; set; }
    public virtual Veiculo NumCarro { get; set; }
}

Comment: Se tu formatou o PC, você trouxe o banco de dados além do projeto?
Comment: Sim, trouxe tudo inclusive o banco de dados, tenho três backups do banco que fica no servidores, no storage e no proprio computador
Comment: @EmanuelF O restante dos formulario, salva tranquilamente, somente essa que da problema
Comment: Abastecimento está referenciado o Veículo?
Comment: @EmanuelF Abastecimento pega Id do Veiculo que fica na tabela veiculo
Comment: Só pra descargo de consciência. Esse veículo já está salvo no sistema?
Comment: @EmanuelF Descobri o erro, por causa de um erro de ortografia, quando coloquei para chamar a classe do Veiculo, a variavel é Id e eu tinha colocado pra chamar por id e não Id
Comment: Estava procurando por alguma coisa que não existia, e retornando o erro. Se resolveu, perfeito!
Comment: @EmanuelF Não sabe o ódio que to, fiquei 3 dias com esse problema e descubro que algo idiota, mas obrigado pela atenção e paciência
Answer: Você está salvando uma entidade, que possui relacionamento com alguma entidade que foi alterada mas que não foi salva antes.
Se for este caso, você tem duas opções:

Salva a outra entidade antes de salvar esta;
Mapear o relacionamento como cascade, afim de que nessa situação a outra entidade relacionada seja salva também.

Falando em cascade
Para cada operação básica da sessão NHibernate - incluindo Persist (), Merge (), SaveOrUpdate (), Delete (), Lock (), Refresh (), Evict (), Replicate () - existe um estilo de cascata correspondente. Respectivamente, os estilos em cascata são chamados persistir, mesclar, salvar-atualização, excluir, bloquear, atualizar, expulsar, replicar. O estilo em cascata para Save () e Update () é save-update; para SaveAndUpdateCopy () é mesclar; e para PersistOnFlush () é persistente. E remover é um alias para deletar.
Se você deseja que uma operação seja conectada em cascata ao longo de uma associação, você deve indicar isso no documento de mapeamento. Por exemplo:
<one-to-one name="person" cascade="persist"/>

Estilos em cascata meus combinados:
<one-to-one name="person" cascade="persist,delete,lock"/>

Você pode usar cascade = "all" para especificar que todas as operações devem ser conectadas em cascata ao longo da associação. A cascata padrão = "none" especifica que nenhuma operação deve ser conectada em cascata.
Recomendo ler mais nesse post em Inglês AQUI
Comment: Emanuel obrigado pela explicação, mas onde eu colocaria cascade em uma mapping do nhibernate `public class VeiculoMapping : ClassMap
    {
        public VeiculoMapping()
        {
        Id(p => p.Id).GeneratedBy.Identity();
        Map(p => p.NCarro);
        Map(p => p.Modelo);
        Map(p => p.Ano);
        Map(p => p.Km);

        }
    }`
Comment: @GuilhermePadovam você tem um Vaiculo.hbm.xml ?
Comment: Não tenho, mas tenho a RouteConfig.cs, não sei se é algo que tenha que altera, o problema que outros formulários, que fazem o CRUD perfeitamente, somente esse que não da certo, porém é a classe mais importante
Comment: Como disse na resposta. Esta tentando salvar a Entidade Abastecimento, mas fez alguma alteração na entidade Veículo que não foi salva.
Comment: Estranho, isso que to tentando achar, porque se fosse no banco ele iria adiciona uma coluna pelo mapping, está tudo certo, tanto no model, mapping e viewmodel veiculo esse é o problema, porque ele me retorno o erro na model veiculo
Comment: Edita a resposta e adiciona o mapeamento das duas entidades.
Comment: Adicionei na pergunta tanto o mapping de abastecimento onde tento salva e retorna o erro e o mapping e model de onde ele fala o erro que é o Veiculo Model

Problema ao salvar


Filtering using a str array

Question: I am trying to filter an ASCII list (which contains ASCII and other characters) by using an array that I have created. I am trying to remove any integer string within the list.
import pandas as pd
with open('ASCII.txt') as f:
    data = f.read().replace('\t', ',')
    print(data, file=open('my_file.csv', 'w'))
df = list(data)
test = ['0','1','2','3','4','5','6','7','8','9']

for x in df:
    try:
        df = int(df)
        for i in range(0,9):
            while any(test) in df:
                df.remove('i')
        print(df)
    except:
        continue

print(df)

This is what I currently have however, it does not work and outputs:
['3', '3', ',', '0', '4', '1', ',', '2', '1', ',', '!', ',', '\n', '3', '4', ',', '0', '4', ...]

Comment: What are the contents of `data`? Are there any errors? If so, please [edit] your post and add their [*full text*](https://meta.stackoverflow.com/q/359146). Why are you importing `pandas` and not using it? To figure out what the error(s) is/are, remove the `try`/`except` and just let the code run. `except: continue` is just masking any errors and preventing them from being seen. You can't call `int()` on a list, so that's one error. `while any(test) in df` isn't doing what you think it's doing. `for i in range(0,9): ... df.remove("i")` isn't going to do what you want it to.
Comment: Forgot one: up at the top, you're reading the contents of your text file into a string, replacing tabs with commas along the way. Calling `list()` on a string isn't doing what you probably think it's doing - try it at an interactive prompt.
Comment: Here are some hints: Test each line in an interactive session so it does what you want it to *before* putting it into a larger block of code. Constantly look at the values of your variables so they are what you think they are. Read the documentation for all of the functions you're using, to make sure they do what you want them to do. Actively look for errors, don't hide them.
Comment: Just to note: your entire loop can be replaced with a one-liner: `df = [c for c in data if c not in string.digits]`
Answer: Your if condition for numbers is broken.
any checks if at least one element in the passed iterable is truthy, i.e. not an empty string in your case.
test = ['0','1','2','3','4','5','6','7','8','9']
while any(test) in df:  # Condition always evaluates to False
    df.remove('i')  # Only removes the character 'i' from df

So your condition any(test) evaluates to True. And now you are checking if True is in df which it isn't, so the condition evaluates to False.
The next error is, that you try to remove the letter 'i' from your list with the remove call. This can be fixed by casting the integer to a string
for i in range(9):
    # Cast integer to str
    while str(i) in df:
        # Remove str i from df
        df.remove(str(i))

Using a str list instead of the range function, you can directly iterate over the elements of the test list:
df = list(data)
test = ['0','1','2','3','4','5','6','7','8','9']

for num in test:
    # Loop as long as num appears in df
    while num in df:
        df.remove(num)  # removes all elements with value of num

By doing so you have to run a second loop to remove all appearances of the current num in df, as remove only removes the first occurrence of that value.
Alternatively you can also check each element of df if it is a digit by using the str method isdigit. But as you modify the list in-place you need to iterate over a copy. Otherwise you'll encounter side-effects as you reduce the size of df:
# Use slice to create a copy of df
for el in df[:]:
    if el.isdigit():
        df.remove(el)

As you iterate over each element in df you don't need an inner loop to remove each occurrence of value el.
Comment: Thank you I tried this, and it worked just as I wanted. I'm new to coding and did not know about the isdigit function. cheers buddy

Filtering using a str array


php string to int

Question: $a = '88';
$b = '88 8888';

echo (int)$a;
echo (int)$b;

as expected, both produce 88. Anyone know if there's a string to int function that will work for $b's value and produce 888888? I've googled around a bit with no luck.
Thanks
Comment: What int value are you expecting for $b? 888888?
Comment: PHP does not follow the `ISO standard 31-0` when it casts a string to integer. PHP has it's own specification, outlined here: [String conversion to numbers](http://www.php.net/manual/en/language.types.string.php#language.types.string.conversion).
Answer: You can remove the spaces before casting to int:
(int)str_replace(' ', '', $b);

Also, if you want to strip other commonly used digit delimiters (such as ,), you can give the function an array (beware though -- in some countries, like mine for example, the comma is used for fraction notation):
(int)str_replace(array(' ', ','), '', $b);

Comment: or if you want to remove all non numeric characters (int)preg_replace('#[^0-9]+#', '', $b);
Comment: beware of (int), the maximum supported value is 2147483647, so if you have (int)2222222222 it will return 2147483647
Answer: If you want to leave only numbers - use preg_replace like: (int)preg_replace("/[^\d]+/","",$b).
Answer: What do you even want the result to be? 888888? If so, just remove the spaces with str_replace, then convert.
Answer: Replace the whitespace characters, and then convert it(using the intval function or by regular typecasting)
intval(str_replace(" ", "", $b))

Answer: Use str_replace to remove the spaces first ?
Answer: You can use the str_replace when you declare your variable $b like that :
$b = str_replace(" ", "", '88 8888');
echo (int)$b;

Or the most beautiful solution is to use intval :
$b = intval(str_replace(" ", "", '88 8888');
echo $b;

If your value '88 888' is from an other variable, just replace the '88 888' by the variable who contains your String.

php string to int


Show Media Preview Image on Views

Question: I want to show the Preview Image from Media Youtube videos in Views. But I can't figure out how to display them in views. Is it supported? How?
Comment: barraponto, Were you successful in creating a View of Media Assets?? I am trying to create a grid of YouTube Videos in my Media. I cant figure out how to do it Eric
Answer: Figured it out: visit admin/config/media/file-types and pick the file type you want to edit (Youtube media are Videos). Pick one of the file displays (Small, Big, Original) and enable the Youtube Preview Image display. Finally, pick an image style in the dropdown menu.
Then, visit the Manage Display tab. If you previously chose the Small file display, for example, edit the Display to make sure the File will be shown.
Comment: If you think the UI is way too complicated as it is, please join the Media sprint http://groups.drupal.org/node/173749
Comment: do you have a tutorial on how to have your fields behaving differently on a per views basis ?
Comment: @tostinni you might like the Display Suite module.

Show Media Preview Image on Views


Reconciling the survey adjusted AIC for multiple regression models in the R survey package version 4.1-1

Question: I am unable to reconcile the new survey adjusted AIC calculation (dAIC) used for multiple regression in version 4.1-1 of the survey package on CRAN for modelling data with complex survey weights. I have reached out to the author, Thomas Lumley, but haven't received a response.
The survey design adjusted dAIC is given in the paper of Lumley and Scott (2015)
$$
   d\text{AIC} = -2n \widehat \ell (\widehat{\boldsymbol \theta}) + 2 p \widehat{\overline \delta}
$$
In the most recent version of survey, the dAIC is computed for Multiple regression directly. I have derived the equations from the accompanying paper but cannot determine why there are two extra operations done in the survey package.

Why is the final result divided by $\widehat \sigma^2$ in https://github.com/cran/survey/blob/9addea4be893748c60974732b01ef7a393019217/R/dAIC.R#L121? This affects the estimates of the AIC, $\overline \delta$ and the design adjusted effective df.
Why are the intercept elements removed from the covariance matrices that are used to estimate $\overline \delta$ in lines https://github.com/cran/survey/blob/9addea4be893748c60974732b01ef7a393019217/R/dAIC.R#L100-L103?

Derivation of result for Multiple regression model
Assuming $\boldsymbol\theta = (\beta_0, \beta_1, \ldots,\beta_p, \sigma^2)^T = (\boldsymbol{\beta}^T, \sigma^2)^T$ with the model
$$
    \boldsymbol{y} = \boldsymbol{X} \boldsymbol{\beta} + \boldsymbol\varepsilon \qquad \text{where}\qquad \boldsymbol\varepsilon \sim \mathcal N(\boldsymbol 0, \sigma^2 I)
$$
or for a single observation
$$
   y_i = \boldsymbol x_i^T \boldsymbol \beta + \varepsilon_i
$$
which has likelihood
$$
f_{\boldsymbol\theta} (y|\boldsymbol x) = \frac{1}{\sqrt{2\pi \sigma^2}} \exp \left\{ - \frac{(y - \boldsymbol x^T \boldsymbol\beta)^2}{2\sigma^2} \right\}.
$$
Then the weighted log-likelihood is
$$
\widehat \ell(\boldsymbol \theta) = \frac{1}{N} \sum_{i \in s} w_i \ell_i(\boldsymbol \theta)
$$
where the weights in the paper are scaled so that $N = \sum_{i \in s}w_i$ and the log-likelihood is $\ell_i(\boldsymbol \theta) = \log f_{\boldsymbol\theta} (y_i|\boldsymbol x_i)$. For convenience, define the diagonal matrix $\boldsymbol W = \text{diag}(w_i)$. Then this leads to,
$$
    \sum_{i \in s} w_i \ell_i(\boldsymbol \theta) = - \frac{N}{2} \log(2\pi) - \frac{N}{2} \log(\sigma^2) - \frac{\boldsymbol \varepsilon^T \boldsymbol W \boldsymbol \varepsilon}{2\sigma^2},
$$
with score vector
$$
    \widehat{\boldsymbol U} = \frac{\partial \widehat \ell (\boldsymbol\theta)}{\partial \boldsymbol \theta} = \begin{pmatrix} \frac{1}{\sigma^2} \boldsymbol X^T \boldsymbol W \boldsymbol \varepsilon \\ - \frac{N}{2\sigma^2} + \frac{\boldsymbol \varepsilon^T \boldsymbol W \boldsymbol \varepsilon}{2 (\sigma^2)^2}\end{pmatrix}
$$
Solving $\widehat{\boldsymbol U} = \boldsymbol 0$ gives the expected estimates $\widehat{\boldsymbol \beta} = (\boldsymbol X^T \boldsymbol W \boldsymbol X)^{-1} \boldsymbol X^T \boldsymbol W \boldsymbol Y$ and $\widehat \sigma^2 = \frac{1}{N}(\boldsymbol Y - \boldsymbol X \widehat{\boldsymbol \beta})^T \boldsymbol W (\boldsymbol Y - \boldsymbol X \widehat{\boldsymbol \beta})$
In the survey package the weights are further chosen such that $w_i \mapsto \frac{w_i}{\overline w} \Rightarrow N = n$ which has the consequence that $-2n\widehat \ell(\widehat{\boldsymbol \theta}) =\sum_{i \in s} w_i \ell_i(\boldsymbol \theta)= N + N \log(2\pi) + N \log(\widehat \sigma^2)$ which validates minus2ellhat on https://github.com/cran/survey/blob/9addea4be893748c60974732b01ef7a393019217/R/dAIC.R#L96:w
However, the final line in that function divides minus2ellhat (and the other terms) by sigmahat2. Why?
The design adjusted penalty also has the step of removing the intercept. The penalty term of the dAIC is, $2 p \widehat{\overline \delta}$ where $p$ is the number of parameters in the model and $\widehat{\overline{\delta}}$ denotes the average design affect. The average design effect is defined $\overline \delta = tr(\boldsymbol \Delta)/p$ where $\boldsymbol \Delta = \boldsymbol{\mathcal I}(\boldsymbol \theta) \boldsymbol V(\boldsymbol \theta)$ is known as the design effect, the ratio of covariance matrices with and without sampling weights ($\boldsymbol{\mathcal I}(\boldsymbol \theta)$ is the Fisher information matrix for the unweighted model and $\boldsymbol V(\boldsymbol \theta)$ being the asymptotic covariance matrix of the parameter estimates in the weighted model).
The Fisher information is defined
$$
    \boldsymbol{\mathcal I}(\boldsymbol \theta) = \begin{pmatrix} \frac{1}{\sigma^2} \boldsymbol X^T\boldsymbol X & \boldsymbol 0\\ \boldsymbol 0^T & \frac{n}{2(\sigma^2)^2}\end{pmatrix}
$$
The design effect of the slope parameters are extracted from the two appropriate covariance matrices fitted using svyglm but there is a step where the intercept components are removed https://github.com/cran/survey/blob/9addea4be893748c60974732b01ef7a393019217/R/dAIC.R#L100-L103. If the null model is the intercept model itself, this will cause an error since the matrices in this step will be empty and cannot be inverted.
The other calculations seem correct and the design effect of the $\sigma^2$ component is estimated correctly using the second moment of the score vector assuming the survey weighted probabilities and using the Fisher information above in the unweighted case.
References
[1]
Lumley, T., and A. Scott. "AIC and BIC for Modeling with Complex Survey Data." Journal of Survey Statistics and Methodology 3, no. 1 (2015): 1–18. https://doi.org/10.1093/jssam/smu021.
Comment: Looking at this with fresh eyes. The `V0` matrix defined in the R code is the `naive.cov` element  from the `svyglm` model which itself is the `cov.unscaled` from a standard `glm`. That is, it is $(X^TX)^{-1}$ and missing the $\widehat{\sigma}^2$ factor. So this division by sigma2 is necessary for the regression slope parameter part (including intercept) for the calculation of $dAIC$. It shouldn't be done everywhere as is currently done in `survey` though. Also unable to verify why the intercept elements (first row & col) is removed from both `V` and `V0` in the new survey implementation too.
Answer: The $d$AIC metric for multiple regression was calculated directly in the survey package in version 4.1-1 here.
Note in the implementation in survey the rescaled weights $w_i^*$ are used so that $\sum_{i \in s} w_i^* = N^* = n$. That is, $w_i^* = \frac{w_i}{\overline w}$ where $\overline w = \frac{1}{n}\sum_{i \in s} w_i$ which has the implication that $N = N^* = n$.
Recall that the $d$AIC has two components, the likelihood component and the penalty component.
\begin{equation}
    d\text{AIC} = -2n \widehat{\ell}(\widehat{\boldsymbol{\theta}}) + 2p\widehat{\overline{\delta}}
\end{equation}
There seem to be two issues with the implementation in survey. First, the penalty component is not correctly computed for the $\sigma^2$ contribution. Second, both the likelihood and penalty components are divided by $\widehat{\sigma^2}$ which is not necessary.

The penalty component is computed in the extractAIC_svylm function at this point. However, the sigma component in the code this seems to be the reciprocal of the theory. See \eqref{deltabar} and the equations following it. In particular, reconcile $\mathcal I_{\sigma^2}$ and $V_{\sigma^2}$ in the theory with Isigma2 and Hsigma2 in the code. In addition to this, the penalty component (and likelihood component) is further modified with a division by $\widehat{\sigma^2}$ on the final line.
The likelihood component is correctly computed in survey at this point of the code in the body of the extractAIC_svylm function as it agrees with \eqref{ellhat}. However, the return statement on the last line divides the AIC by $\widehat \sigma^2$.

The theory to justify this is below and a suggested code fix below that.
Weighted likelihood for multiple regression under sampling design
In the complex survey design approach, the observations $\left\{ (y_i, \boldsymbol{x}_i): i \in s\right\}$ are assumed to be derived from a sample $s$ of $n$ units drawn from a finite population of size $N$ using some probability sampling design. The weights associated with the $i^{\mathrm{th}}$ unit from the population are defined to be $w_i$.
The data from the finite population are assumed to be generated from some distribution with joint density, $g(y, \boldsymbol{x})$. The desired modelling approach for the data is assumed to be a parametric model, $\left\{ f_{\boldsymbol{\theta}}(y|\boldsymbol{x}), \boldsymbol{\theta} \in \boldsymbol{\Theta}\right\}$. Generally speaking the parametric family induced by $f_{\boldsymbol{\theta}}(y|x)$ does not need to contain the true distribution in $g(y, x)$ or $g(y|x)$. The parametric model would be considered misspecified in this case. The likelihood approach can nevertheless still be used and the objective function being maximised is the quantity,
\begin{equation}
    \ell(\boldsymbol{\theta}) = \mathbb{E}_g \left( \log f_{\boldsymbol{\theta}}(y|\boldsymbol{x})\right).
\end{equation}
This is motivated by the using the Kullback-Leibler divergence of the candidate parametric model away from the true model,
\begin{equation}
    \mathrm{KL}(f_{\boldsymbol{\theta}}, g) = \mathbb{E}_g \left( \log g(y| \boldsymbol{x})\right) - \ell(\boldsymbol{\theta}).
\end{equation}
The target parameter is $\boldsymbol{\theta}^*$ is the parametric value that is the 'least false' which is the value that minimizes the Kullback-Leibler divergence above (or equivalently, maximizer of $\ell(\boldsymbol{\theta}))$. In terms of the classical likelihood equations, this occurs at the new score equation,
\begin{equation}
    \mathcal U(\boldsymbol{\theta}^*) = \mathbb{E}_g \left( \left.\frac{\partial \log f_{\boldsymbol{\theta}}(y|\boldsymbol{x})}{\partial \boldsymbol{\theta}}\right|_{\boldsymbol{\theta} = \boldsymbol{\theta}^*}\right) = 0.
\end{equation}
The likelihood equation, $\ell(\boldsymbol{\theta})$, being a population mean parameter is estimated using the weighted estimator,
\begin{equation}
    \widehat{\ell}(\boldsymbol{\theta}) = \frac{1}{N} \sum_{i \in s} w_i \ell_i(\boldsymbol{\theta})
\end{equation}
where $\ell_i(\boldsymbol{\theta}) = \log f_{\boldsymbol{\theta}}(y_i|\boldsymbol{x})$ and the weights are assumed to aggregate to the population total, $\sum_{i \in s}w_i = N$. For the multiple regression model, each observation is assumed to follow the log-likelihood,
\begin{equation}
    \ell_i(\boldsymbol{\theta}) = \log f_{\boldsymbol{\theta}}(y_i|\boldsymbol{x}_i) = - \frac{1}{2} \log(2 \pi) - \frac{1}{2}\log(\sigma^2) - \frac{(y_i - \boldsymbol{x}_i^T \boldsymbol{\beta})^2}{2 \sigma^2},
\end{equation}
where the parameter space is defined $\boldsymbol{\theta} = \left( \boldsymbol{\beta}^T, \sigma^2\right) \in \mathbb{R}^{m+1} \cup \left\{\mathbb{R}_+\setminus 0\right\}$ and $\boldsymbol{x}_i$ is a vector of covariates for observation $i$. To estimate the maximizer of $\ell(\boldsymbol{\theta})$, use an estimator that solves the score equation,
\begin{equation}
    \widehat{\mathcal U}(\boldsymbol{\theta}) = \frac{1}{N} \sum_{i \in s} w_i \frac{\partial}{\partial \boldsymbol{\theta}}\ell_i(\boldsymbol{\theta}).
\end{equation}
Then $\boldsymbol{\theta}^*$ is consistently estimated by $\widehat{\boldsymbol{\theta}}$ that satisfies the weighted pseudo-score equations, $\widehat{\mathcal U}(\widehat{\boldsymbol{\theta}}) = 0$. This is shown later using results of Fuller (2009).
Before computing the required terms in this analysis, the link between $\widehat{\boldsymbol{\theta}}$ and the AIC strategy of model assessment is covered. The model that matches the population likelihood the best will minimize the Kullback-Leibler divergence above. The AIC strategy is to estimate this difference by estimating $Q_n = \mathbb{E}_g( \ell(\widehat{\boldsymbol{\theta}}))$ and selecting the model with the largest value.
Theorem 1 of Lumley and Scott (2015) showed the statistical properties of the naive estimator, $\widehat{\ell}(\widehat{\boldsymbol{\theta}})$, with,
\begin{equation}
    \mathbb{E}_g(\widehat{\ell}(\widehat{\boldsymbol{\theta}})) = Q_n + \frac{1}{n} \mathrm{tr} \left\{ \boldsymbol{\Delta} \right\} + o_p(n^{-1})
\end{equation}
where $\boldsymbol{\Delta} = \mathcal I(\boldsymbol{\theta}^*)\boldsymbol{V}(\boldsymbol{\theta}^*)$ and $\mathcal I(\boldsymbol{\theta}) = \mathbb{E}\widehat{\mathcal J}(\boldsymbol{\theta})$ and $\boldsymbol{V}(\boldsymbol{\theta}^*)$ being the asymptotic covariance matrix of $\sqrt{n}\widehat{\boldsymbol{\theta}}$.
In particular, their proof utilizes the regularity conditions and results of Theorem 1.3.9 Fuller (2009) under the typical framework in survey estimation. That is, it is supposed that there are a sequence of finite populations indexed by $\nu$ and a sequence of samples of size $n_\nu$ drawn from the $N_\nu$ units in the $\nu^{\mathrm th}$ population with a well-defined probability scheme. Then asymptotic normality and consistency is established with

$\widehat{\boldsymbol{\theta}}_\nu$ is asymptotically normal with $\sqrt{n} (\widehat{\boldsymbol{\theta}}_{\nu}- \boldsymbol{\theta}^*) \stackrel{d}{\longrightarrow} \mathcal N(\boldsymbol{0}, \boldsymbol{V}(\boldsymbol{\theta}^*))$.
If a sequence $\left\{\boldsymbol{\theta}_\nu \right\}$ are consistent estimators of $\boldsymbol{\theta}^*$, that is, $\boldsymbol{\theta}_\nu \stackrel{p}{\longrightarrow} \boldsymbol{\theta}^*$, then $\widehat{\mathcal J}_\nu(\boldsymbol{\theta}_\nu) \stackrel{p}{\longrightarrow} \mathcal I(\boldsymbol{\theta})$.

Consider now the precise form of the likelihood equations in this weighted sampling design context. For convenience define $\boldsymbol{W} = \mathrm{diag}(w_i)_{i \in s}$ as the diagonal matrix of weights.
The log-likelihood takes the form,
\begin{equation}
\begin{aligned}
    \widehat{\ell}(\boldsymbol{\theta}) &= - \frac{1}{2} \log(2 \pi) - \frac{1}{2} \log \sigma^2 -  \frac{1}{N}\frac{(\boldsymbol{Y} - \boldsymbol{X}\boldsymbol{\beta})^T\boldsymbol{W}(\boldsymbol{Y} - \boldsymbol{X}\boldsymbol{\beta})}{2\sigma^2}\\
        &= - \frac{1}{2} \log(2 \pi) - \frac{1}{2} \log \sigma^2 -  \frac{1}{N}\frac{\boldsymbol{\varepsilon}^T\boldsymbol{W}\boldsymbol{\varepsilon}}{2\sigma^2}
\end{aligned}\tag{1}\label{ellhat}
\end{equation}
Maximising the log likelihood function in a similar manner to the unweighted case gives the weighted score vector $\widehat{\mathcal{U}} = \frac{\partial \widehat{\ell}}{\partial \boldsymbol{\theta}} = \frac{1}{N} \sum_{i \in s} w_i \frac{\partial l_i(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}}$, and corresponding negative Hessian $\widehat{\mathcal J}(\boldsymbol{\theta}) = - \frac{\partial^2 \widehat{\ell}}{\partial \boldsymbol{\theta} \partial \boldsymbol{\theta}^T} = - \frac{1}{N} \sum_{i \in s} w_i \frac{\partial^2\ell_i(\boldsymbol{\theta})}{\partial \boldsymbol{\theta}\partial\boldsymbol{\theta}^T}$. Evaluating these leads to the equations,
\begin{equation}
\widehat{\mathcal{U}}(\boldsymbol{\theta}) = \begin{pmatrix} \boldsymbol{X}^T\boldsymbol{W} \boldsymbol{\varepsilon}/ (N\sigma^2)\\ - \frac{1}{2N\sigma^2} (N  - \boldsymbol{\varepsilon}^T\boldsymbol{W}\boldsymbol{\varepsilon}/(\sigma^2))\end{pmatrix} = \frac{1}{N} \sum_{i \in s} w_i \begin{pmatrix} \boldsymbol{x}_i^T \frac{(y_i - \boldsymbol{x}_i^T\boldsymbol{\beta})}{2\sigma^2}\\ - \frac{1}{2\sigma^2}  + \frac{(y_i - \boldsymbol{x}_i^T \boldsymbol{\beta})^2}{2 (\sigma^2)^2}\end{pmatrix} =: \begin{pmatrix}  U_{\boldsymbol{\beta}}\\ U_{\sigma^2}\end{pmatrix}.
\end{equation}
\begin{equation}
    \widehat{\mathcal J}(\boldsymbol{\theta}) = \begin{pmatrix} \frac{\boldsymbol{X}^T \boldsymbol{W} \boldsymbol{X}}{N\sigma^2} & \frac{\boldsymbol{X}^T \boldsymbol{W} \boldsymbol{\varepsilon}}{N(\sigma^2)^2} \\
                                                 \frac{\boldsymbol{\varepsilon}^T \boldsymbol{W} \boldsymbol{X}}{N(\sigma^2)^2} & -\frac{1}{2(\sigma^2)^2} + \frac{\boldsymbol{\varepsilon}^T \boldsymbol{W}\boldsymbol{\varepsilon}}{N(\sigma^2)^3}
                                 \end{pmatrix}, \qquad  \mathcal J_N(\boldsymbol{\theta}) = \begin{pmatrix} \frac{\boldsymbol{X}^T  \boldsymbol{X}}{N\sigma^2} & \frac{\boldsymbol{X}^T  \boldsymbol{\varepsilon}}{N(\sigma^2)^2} \\
                                                 \frac{\boldsymbol{\varepsilon}^T  \boldsymbol{X}}{N(\sigma^2)^2} & -\frac{1}{2(\sigma^2)^2} + \frac{\boldsymbol{\varepsilon}^T \boldsymbol{\varepsilon}}{N(\sigma^2)^3}
                                 \end{pmatrix};
\end{equation}
where $\mathcal J_N(\boldsymbol{\theta})$ is the negative Hessian without the weights applied which is used in later results.
Solving the pseudo-score equation above yields the pseudo maximum likelihood parameter estimates,
\begin{equation}
    \widehat{\boldsymbol{\beta}} = \left(\boldsymbol{X}^T\boldsymbol{W}\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{W}\boldsymbol{Y}, \qquad       \widehat{\sigma}^2 = \frac{1}{N} \boldsymbol{\varepsilon}^T\boldsymbol{W}\boldsymbol{\varepsilon}.
\end{equation}
From (1.3.78) in Fuller (2009) $\mathcal I(\boldsymbol{\theta}) = \mathbb{E}\widehat{\mathcal J}(\boldsymbol{\theta})$ can be estimated by $\mathcal J(\boldsymbol{\theta})$,
\begin{equation}
    \widehat{\mathcal J}(\boldsymbol{\theta}) = -\frac{1}{N}\sum_{i \in s} w_i \frac{\partial \ell_i(\boldsymbol{\theta})}{\partial \boldsymbol{\theta} \partial \boldsymbol{\theta}^T} = -\frac{1}{N}\sum_{i \in s}  \frac{\partial \ell_i(\boldsymbol{\theta})}{\partial \boldsymbol{\theta} \partial \boldsymbol{\theta}^T}  + O_p(n^{-1/2}) =: \mathcal J_N(\boldsymbol{\theta}) + O_p(n^{-1/2}) \stackrel{a.s.}{\longrightarrow} \mathcal J(\boldsymbol{\theta})
\end{equation}
and $\mathcal J(\boldsymbol{\theta})$ is non-singular.
Estimating the design effect matrix, $\boldsymbol{\boldsymbol{\Delta}}$
Recall the design effect matrix term $\boldsymbol{\boldsymbol{\Delta}} = \mathcal I(\boldsymbol{\theta}^*) \boldsymbol{V}(\boldsymbol{\theta}^*)$ where $\boldsymbol{V}(\boldsymbol{\theta}^*)$ denotes the asymptotic covariance matrix of $\sqrt{n}\widehat{\boldsymbol{\theta}}$. The estimate of $\mathcal I(\boldsymbol{\theta})$ is considered first.
\begin{equation}
    \mathcal I(\boldsymbol{\theta}) = \mathbb{E}\widehat{\boldsymbol{\mathcal J}}(\boldsymbol{\theta}) \Rightarrow \widehat{\mathcal I}(\widehat{\boldsymbol{\theta}}) = \begin{pmatrix} \frac{\boldsymbol{X}^T\boldsymbol{X}}{N\widehat{\sigma}^2} & \boldsymbol{0} \\ \boldsymbol{0}^T &  \frac{1}{2(\widehat{\sigma}^2)^2}\end{pmatrix} =: \begin{pmatrix} \mathcal I_{\boldsymbol{\beta}} & \boldsymbol{0}\\ \boldsymbol{0}^T & \mathcal I_{\sigma^2} \end{pmatrix},
\end{equation}
where $\boldsymbol{0}$ is a column vector of zeros of dimension $m +1$. Note that the regression parameters, $\boldsymbol{\beta}$, and the variance nuisance parameter, $\sigma^2$, are orthogonal. That is, in the sense that the Information matrix is block diagonal.
The design effect adjustment is computed using $\boldsymbol{\boldsymbol{\Delta}}$ with,
\begin{equation}
    \overline{\delta} = \mathrm{trace}(\boldsymbol{\boldsymbol{\Delta}}) / p.
\end{equation}
The blockwise diagonal form of $\mathcal I(\boldsymbol{\theta})$ allows the trace to be computed separately for the regression parameters and the variance nuisance parameter. Indeed, due to the form of the negative Hessian $\widehat{\mathcal J}(\boldsymbol{\theta})$, it follows that $\boldsymbol{V}(\boldsymbol{\theta})$ will be blockwise diagonal with,
\begin{equation}
    \boldsymbol{V}(\boldsymbol{\theta}) = \begin{pmatrix} V_{\boldsymbol{\beta}} & \boldsymbol{0} \\ \boldsymbol{0}^T & V_{\sigma^2} \end{pmatrix} \Rightarrow \mathrm{trace}(\boldsymbol{\boldsymbol{\Delta}}) = \mathrm{trace}(\mathcal I_{\boldsymbol{\beta}}\boldsymbol{V}_{\boldsymbol{\beta}}) + \mathrm{trace}(\mathcal I_{\boldsymbol{\sigma^2}}V_{\sigma^2}) = \mathrm{trace}(\mathcal I_{\boldsymbol{\beta}}\boldsymbol{V}_{\boldsymbol{\beta}}) +\mathcal I_{\boldsymbol{\sigma^2}}V_{\sigma^2}\tag{2}\label{deltabar}
\end{equation}
The trace calculation is split into the two components. One for the regression parameters and one for the variance nuisance parameter. The trace of the regression parameters is estimated routinely using the standard variance covariance matrices of the regression parameters in $\mathcal I_{\boldsymbol{\beta}}$ and $V_{\boldsymbol{\beta}}$. That is, define $\boldsymbol{V}_{\boldsymbol{\beta}, 0}$ to be the variance covariance matrix of $\boldsymbol{\beta}$ under simple random design and the variance covariance matrix under sampling weights to be $\boldsymbol{V}_{\boldsymbol{\beta}}$. Then simply $\mathcal I_{\boldsymbol{\beta}}\boldsymbol{V}_{\boldsymbol{\beta}} = \boldsymbol{V}_{\boldsymbol{\beta}, 0}^{-1}\boldsymbol{V}(\boldsymbol{\beta})$
The $\sigma^2$ component of the calculation involves estimating the scalars $\mathcal I_{\sigma^2}$ and $V_{\sigma^2}$. The $\mathcal I_{\sigma^2}$ component can be estimated directly with $\widehat{\mathcal{I}}_{\sigma^2} = 1 /(2(\widehat{\sigma}^2)^2)$. To estimate $V_{\sigma^2}$, it can be done by estimating the $\sigma^2$ element in the Information matrix under the sampling weights and then taking the reciporical. To estimate the $\sigma^2$ element in the Information matrix, use the standard estimation equation as the variance of the score equation. Since the score equation is zero at the MLE it only requires computing the second moment of the score vector. The contribution of each observation to the $\sigma^2$ element in the score equation is defined,
\begin{equation}
    U_{\sigma^2, i}(\boldsymbol{\theta}) := \frac{\partial l_i(\boldsymbol{\theta})}{\partial \sigma^2} = - \frac{1}{2\sigma^2} + \frac{(y_i - \boldsymbol{x}_i^T \boldsymbol{\beta})^2}{2(\sigma^2)^2}.
\end{equation}
Therefore an estimate of the second moment and consequently variance of this component since the score vector is zero at the MLE is given by,
\begin{equation}
    \widehat{\mathbb{V}\text{ar}}U_{\sigma^2} = \frac{1}{N}\sum_{i \in s} w_i U_{\sigma^2, i}^2(\widehat{\boldsymbol{\theta}}) = \frac{1}{N}\sum_{i \in s} w_i \left( - \frac{1}{2\widehat{\sigma}^2} + \frac{(y_i - \boldsymbol{x}_i^T \widehat{\boldsymbol{\beta}})^2}{2(\widehat{\sigma}^2)^2}\right)^2
\end{equation}
Thus the estimate of the covariance element $V_{\sigma^2}$ can be estimated with,
\begin{equation}
    \widehat V_{\sigma^2} = \left(\widehat{\mathbb{V}\text{ar}} U_{\sigma^2}\right)^{-1}.
\end{equation}
Finally $\widehat{\overline{\delta}} = \widehat{\delta}_{\boldsymbol{\beta}} + \widehat{\delta}_{\sigma^2} = \mathrm{trace}(\widehat{\boldsymbol{V}}_{\boldsymbol{\beta}, 0}^{-1} \widehat{\boldsymbol{V}}_{\boldsymbol{\beta}}) + \widehat{\mathcal{I}}_{\sigma^2}\widehat{V}_{\sigma^2}$.
Answer: Code fix
Below includes a proposal fix using the theory and comparison in the other answer by @JRW.
The following calculations are setup assuming survey version 4.2-1 which
has the first CRAN implementation for the direct dAIC calculation including
the effects for estimating $\sigma^2$ as well as the $\beta$ coefficients in
a survey weighted linear multiple regression model.
set.seed(2023)

Load VGAM to use their TIC calculation
library(survey, warn.conflicts = FALSE, quietly = TRUE)
library(VGAM, warn.conflicts = FALSE, quietly = TRUE)
library(knitr)

To compute old survey output and alternative proposal
require(testthat, warn.conflicts = FALSE, quietly = TRUE)
stopifnot(packageVersion('survey') == "4.2.1")

proposed function
extractSvyLmAIC <- function(fit, k = 2) {
    # Extract weights used in survey
    w <- fit[["prior.weights"]]
    n.hat <- sum(w)
    y <- fit[["y"]]
    mu.hat <- fit[["linear.predictors"]]
    eps <- y - mu.hat
    # Use ML estimate of sigma2
    sigma2.hat <- sum(eps^2 * w) / n.hat
    # Compute the likelihood component of the AIC
    minus.2.ell.hat <- n.hat * (log(sigma2.hat) + 1 + log(2 * pi))
    # Construct the beta contribution to the design effect matrix
    v.beta.zero <- fit[["naive.cov"]] * sigma2.hat
    v.beta <- vcov(fit)
    # Compute the delta matrix for the regression coefficients
    delta.beta.matrix <- solve(v.beta.zero, v.beta)
    # Compute the sigma2 component of the delta matrix
    ## Information matrix for sigma2 in unweighted case
    i.sigma2 <- 1 / (2 * sigma2.hat^2)
    ## Estimate the covariance of sigma2 under sampling weights
    ## Use the score equation estimator
    u.sigma2.i <- -1 / (2 * sigma2.hat) + eps^2 / (2 * sigma2.hat^2)
    var.sigma2 <-  1 / mean(w * u.sigma2.i^2)
    delta.sigma2 <- i.sigma2 * var.sigma2
    # Compute the overall design effects
    delta.beta <- diag(delta.beta.matrix)
    delta.bar <- mean(c(delta.beta, delta.sigma2))
    eff.p <- sum(delta.beta, delta.sigma2)
    # Compute the dAIC = -2LL + k * p * deltabar
    aic <- minus.2.ell.hat + k * eff.p
    c(eff.p = eff.p, AIC = aic, deltabar = delta.bar)
}

Number of decimal places in output
ndp <- 2L

Basic check with unit weights
For a first test of the dAIC code, a simple linear regression model is considered
where the outcome and predictors have no relationship whatsoever and are pure
gaussian noise with correlation matrix and matrix scatterplot shown below.
n <- 100L
dat <- replicate(3L, rnorm(n), simplify = FALSE) |>
    as.data.frame() |>
    setNames(c("y", "x1", "x2"))

Inspect the various AIC, dAIC and TIC calculations by first fitting the appropriate models
Shown below is the various AIC calculations, including the standard AIC generated for
regular lm/glm models, along with the TIC for the vglm models. The $d$AIC
calculations proposed by survey 4.0and 4.2-1 (current as of 11/07/23) are
shown along with the newly proposed correction in extractSvyLmAIC function
included in this document. To generate the email@example.com values, the code uses
the survey 4.2-1 package intercepting the check that the model is a gaussian
multiple regression model forcing it to compute the dAIC via the glm framework
#" as was done in `firstname.lastname@example.com`.
numPredictors <- function(model) {
    if (inherits(model, "vglm"))
        model <- model@misc
    attr(terms(model$formula), "term.labels") |> length()
}
dfOrder <- function(df) {
    desired.order <- c("value", "predictors", "calculation", "df", "delta")
    df <- df[match(colnames(df), desired.order)]
}

Intercept the is.svylm function to force the firstname.lastname@example.com calculation
s40AIC <- function(model) {
    aic <- testthat::with_mock(is.svylm = function(x) FALSE,
                               AIC(model),
                               .env = "survey")
    aic <- data.frame(value = aic[["AIC"]],
                      df = aic[["eff.p"]],
                      delta = aic[["deltabar"]])
    aic[["calculation"]] <- "survey v4.0 (dAIC)"
    aic[["predictors"]] <- numPredictors(model)
    aic
}

Current survey calc
sAIC <- function(model) {
    aic <- AIC(model)
    aic <- data.frame(value = aic[["AIC"]],
                      df = aic[["eff.p"]],
                      delta = aic[["deltabar"]])
    aic[["calculation"]] <- "survey (dAIC)"
    aic[["predictors"]] <- numPredictors(model)
    aic
}

Proposed survey calc
dAIC <- function(model) {
    aic <- extractSvyLmAIC(model)
    aic <- data.frame(value = aic[["AIC"]],
                      df = aic[["eff.p"]],
                      delta = aic[["deltabar"]])
    aic[["calculation"]] <- "proposal (dAIC)"
    aic[["predictors"]] <- numPredictors(model)
    aic
}
calcTIC <- function(model) {
    aic <- data.frame(value = TICvlm(model))
    aic[["df"]] <- NA
    aic[["delta"]] <- NA
    aic[["calculation"]] <- "vglm (TIC)"
    aic[["predictors"]] <- numPredictors(model)
    aic
}
glmAIC <- function(model) {
    aic <- AIC(model)
    n.preds <- numPredictors(model)
    aic <- data.frame(value = aic[[1]], df = n.preds + 2)
    aic[["delta"]] <- NA
    aic[["calculation"]] <- "glm (AIC)"
    aic[["predictors"]] <- n.preds
    aic
}
emptyDF <- function(calculation) {
    data.frame(value = NA, df = NA, delta = NA, calculation = calculation, predictors = NA)
}
aicCalcs <- function(models) {
    output <- lapply(models, function(x) {
        if (inherits(x, "svyglm")) {
            proposeddAIC <- dAIC(x)
            s40 <- tryCatch(s40AIC(x), error = function(e) emptyDF("firstname.lastname@example.com (dAIC)"))
            s41 <- tryCatch(sAIC(x), error = function(e) emptyDF("survey (dAIC)"))
            return(rbind.data.frame(proposeddAIC, s40, s41))
        }
        if (inherits(x, "vglm")) {
            return(calcTIC(x))
        }
        glmAIC(x)
    })
    output <- do.call(rbind, output)
    output <- dfOrder(output)
    output
}
unit.design <- svydesign(ids = ~1, weights = ~1, data = dat)

Fitting survey lm models with unit weights
m0 <- svyglm(y ~ x1, design = unit.design)
summary(m0)
#>
#> Call:
#> svyglm(formula = y ~ x1, design = unit.design)
#>
#> Survey design:
#> svydesign(ids = ~1, weights = ~1, data = dat)
#>
#> Coefficients:
#>             Estimate Std. Error t value Pr(>|t|)
#> (Intercept)  0.07124    0.09692   0.735    0.464
#> x1          -0.01786    0.09958  -0.179    0.858
#>
#> (Dispersion parameter for gaussian family taken to be 0.9857939)
#>
#> Number of Fisher Scoring iterations: 2
m1 = svyglm(y ~ x1 + x2, design = unit.design)
summary(m1)
#>
#> Call:
#> svyglm(formula = y ~ x1 + x2, design = unit.design)
#>
#> Survey design:
#> svydesign(ids = ~1, weights = ~1, data = dat)
#>
#> Coefficients:
#>              Estimate Std. Error t value Pr(>|t|)
#> (Intercept)  0.069979   0.098790   0.708    0.480
#> x1          -0.017611   0.100177  -0.176    0.861
#> x2          -0.007479   0.101843  -0.073    0.942
#>
#> (Dispersion parameter for gaussian family taken to be 0.9857391)
#>
#> Number of Fisher Scoring iterations: 2
## base R regular glm models with `glm`
o0 <- glm(y ~ x1, data = dat)
summary(o0)
#>
#> Call:
#> glm(formula = y ~ x1, data = dat)
#>
#> Coefficients:
#>             Estimate Std. Error t value Pr(>|t|)
#> (Intercept)  0.07124    0.10226   0.697    0.488
#> x1          -0.01786    0.10710  -0.167    0.868
#>
#> (Dispersion parameter for gaussian family taken to be 0.995853)
#>
#>     Null deviance: 97.621  on 99  degrees of freedom
#> Residual deviance: 97.594  on 98  degrees of freedom
#> AIC: 287.35
#>
#> Number of Fisher Scoring iterations: 2
o1 <- glm(y ~ x1 + x2, data = dat)
summary(o1)
#>
#> Call:
#> glm(formula = y ~ x1 + x2, data = dat)
#>
#> Coefficients:
#>              Estimate Std. Error t value Pr(>|t|)
#> (Intercept)  0.069979   0.104201   0.672    0.503
#> x1          -0.017611   0.107701  -0.164    0.870
#> x2          -0.007479   0.101869  -0.073    0.942
#>
#> (Dispersion parameter for gaussian family taken to be 1.006064)
#>
#>     Null deviance: 97.621  on 99  degrees of freedom
#> Residual deviance: 97.588  on 97  degrees of freedom
#> AIC: 289.35
#>
#> Number of Fisher Scoring iterations: 2
## VGAM computations with `vglm` to compute TIC
vm0 <- vglm(y ~ x1, data = dat, family = uninormal)
summary(vm0)
#>
#> Call:
#> vglm(formula = y ~ x1, family = uninormal, data = dat)
#>
#> Coefficients:
#>               Estimate Std. Error z value Pr(>|z|)
#> (Intercept):1  0.07124    0.10124   0.704    0.482
#> (Intercept):2 -0.01218    0.07071  -0.172    0.863
#> x1            -0.01786    0.10603  -0.168    0.866
#>
#> Names of linear predictors: mean, loglink(sd)
#>
#> Log-likelihood: -140.6759 on 197 degrees of freedom
#>
#> Number of Fisher scoring iterations: 3
#>
#> No Hauck-Donner effect found in any of the estimates
vm1 <- vglm(y ~ 1 + x1 + x2, data = dat, family = uninormal)
summary(vm1)
#>
#> Call:
#> vglm(formula = y ~ 1 + x1 + x2, family = uninormal, data = dat)
#>
#> Coefficients:
#>                Estimate Std. Error z value Pr(>|z|)
#> (Intercept):1  0.069979   0.102634   0.682    0.495
#> (Intercept):2 -0.012207   0.070711  -0.173    0.863
#> x1            -0.017611   0.106081  -0.166    0.868
#> x2            -0.007479   0.100337  -0.075    0.941
#>
#> Names of linear predictors: mean, loglink(sd)
#>
#> Log-likelihood: -140.6732 on 196 degrees of freedom
#>
#> Number of Fisher scoring iterations: 3
#>
#> No Hauck-Donner effect found in any of the estimates
models <- list(o0, o1, vm0, vm1, m0, m1)
unit.aics <- aicCalcs(models)

Unit weighted model comparisons.
In the case of unit weights, the dAIC calculations should agree with the TIC
as a special case along with the standard AIC computation
in glm models.
pack.index <- table(unit.aics[["calculation"]])
unit.aics <- unit.aics[order(unit.aics[["calculation"]]), ]
numeric.cols <- vapply(unit.aics, is.numeric, logical(1L))
unit.aics[numeric.cols] <- lapply(unit.aics[numeric.cols], round, ndp)
unit.aics |> kable(row.names = FALSE, format = "pipe")

value
calculation
predictors
delta
df

287.35
glm (AIC)
1
NA
3.00

289.35
glm (AIC)
2
NA
4.00

287.21
proposal (dAIC)
1
0.98
2.93

289.26
proposal (dAIC)
2
0.99
3.96

290.09
survey (dAIC)
1
0.92
1.83

292.15
survey (dAIC)
2
0.95
2.86

99.32
survey v4.0 (dAIC)
1
0.86
0.86

101.32
survey v4.0 (dAIC)
2
0.93
1.87

287.03
vglm (TIC)
1
NA
NA

289.07
vglm (TIC)
2
NA
NA

Scenario 2
Consider now when x2 is significant in explaining y. It should be included
in the model and reflected in the AIC calculations.
n <- 100L
dat <- replicate(3, rnorm(n), simplify = FALSE) |>
     as.data.frame() |>
     setNames(c("y", "x1", "x2"))
dat[["y"]] <- dat[["x2"]] + rnorm(n, sd = 0.5)
unit.design <- svydesign(ids = ~1, weights = ~1, data = dat)
m0 <- svyglm(y ~ x1, design = unit.design)
summary(m0)
#>
#> Call:
#> svyglm(formula = y ~ x1, design = unit.design)
#>
#> Survey design:
#> svydesign(ids = ~1, weights = ~1, data = dat)
#>
#> Coefficients:
#>             Estimate Std. Error t value Pr(>|t|)
#> (Intercept) -0.04666    0.11948  -0.391    0.697
#> x1           0.06003    0.12155   0.494    0.623
#>
#> (Dispersion parameter for gaussian family taken to be 1.401867)
#>
#> Number of Fisher Scoring iterations: 2
m12 <- svyglm(y ~ x1 + x2, design = unit.design)
summary(m12)
#>
#> Call:
#> svyglm(formula = y ~ x1 + x2, design = unit.design)
#>
#> Survey design:
#> svydesign(ids = ~1, weights = ~1, data = dat)
#>
#> Coefficients:
#>             Estimate Std. Error t value Pr(>|t|)
#> (Intercept) -0.03446    0.05347  -0.644    0.521
#> x1           0.06865    0.05903   1.163    0.248
#> x2           1.02685    0.04582  22.413   <2e-16 ***
#> ---
#> Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
#>
#> (Dispersion parameter for gaussian family taken to be 0.2792745)
#>
#> Number of Fisher Scoring iterations: 2

glm versions
o0 <- glm(y ~ x1, data = dat)
summary(o0)
#>
#> Call:
#> glm(formula = y ~ x1, data = dat)
#>
#> Coefficients:
#>             Estimate Std. Error t value Pr(>|t|)
#> (Intercept) -0.04666    0.11969  -0.390    0.697
#> x1           0.06003    0.12639   0.475    0.636
#>
#> (Dispersion parameter for gaussian family taken to be 1.416172)
#>
#>     Null deviance: 139.10  on 99  degrees of freedom
#> Residual deviance: 138.78  on 98  degrees of freedom
#> AIC: 322.56
#>
#> Number of Fisher Scoring iterations: 2
o12 <- glm(y ~ x1 + x2, data = dat)
summary(o12)
#>
#> Call:
#> glm(formula = y ~ x1 + x2, data = dat)
#>
#> Coefficients:
#>             Estimate Std. Error t value Pr(>|t|)
#> (Intercept) -0.03446    0.05370  -0.642    0.523
#> x1           0.06865    0.05670   1.211    0.229
#> x2           1.02685    0.05200  19.746   <2e-16 ***
#> ---
#> Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
#>
#> (Dispersion parameter for gaussian family taken to be 0.2850327)
#>
#>     Null deviance: 139.104  on 99  degrees of freedom
#> Residual deviance:  27.648  on 97  degrees of freedom
#> AIC: 163.23
#>
#> Number of Fisher Scoring iterations: 2

VGAM versions in vglm for TIC
vm0 <- vglm(y ~ x1, data = dat, family = uninormal)
summary(vm0)
#>
#> Call:
#> vglm(formula = y ~ x1, family = uninormal, data = dat)
#>
#> Coefficients:
#>               Estimate Std. Error z value Pr(>|z|)
#> (Intercept):1 -0.04666    0.11849  -0.394   0.6937
#> (Intercept):2  0.16388    0.07071   2.318   0.0205 *
#> x1             0.06003    0.12512   0.480   0.6314
#> ---
#> Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
#>
#> Names of linear predictors: mean, loglink(sd)
#>
#> Log-likelihood: -158.2816 on 197 degrees of freedom
#>
#> Number of Fisher scoring iterations: 3
#>
#> No Hauck-Donner effect found in any of the estimates
vm12 <- vglm(y ~ 1 + x1 + x2, data = dat, family = uninormal)
summary(vm12)
#>
#> Call:
#> vglm(formula = y ~ 1 + x1 + x2, family = uninormal, data = dat)
#>
#> Coefficients:
#>               Estimate Std. Error z value Pr(>|z|)
#> (Intercept):1 -0.03446    0.05289  -0.652    0.515
#> (Intercept):2 -0.64281    0.07071  -9.091   <2e-16 ***
#> x1             0.06865    0.05585   1.229    0.219
#> x2             1.02685    0.05122  20.049   <2e-16 ***
#> ---
#> Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
#>
#> Names of linear predictors: mean, loglink(sd)
#>
#> Log-likelihood: -77.6133 on 196 degrees of freedom
#>
#> Number of Fisher scoring iterations: 7
#>
#> No Hauck-Donner effect found in any of the estimates
sig.models <- list(o0, o12, vm0, vm12, m0, m12)
x2.aics <- aicCalcs(sig.models)

Below are the calculated criterions for this example and the model with x2
should be the clear superior model as it includes the most informative predictor
against y. Again the proposed output agrees with the TIC and standard AIC
calculation. The survey calculations vary wildly, the survey v4.0 has the correct
conclusion but the values are not in agreement with TIC. Also the design effect
adjustment in deltabar shows a very small deltabar for the 2 predictor model.
On the other hand, survey >= 4.1-1 has the completely incorrect conclusion
with an $d$AIC three times larger in the 2 predictor model and the design effect
has blown up to 2 in deltabar. The proposal is stable with design effects near
1 for both models which is consistent with the earlier results.
pack.index <- table(x2.aics[["calculation"]])
x2.aics <- x2.aics[order(x2.aics[["calculation"]]), ]
numeric.cols <- vapply(x2.aics, is.numeric, logical(1L))
x2.aics[numeric.cols] <- lapply(x2.aics[numeric.cols], round, ndp)
x2.aics |> kable(row.names = FALSE, format = "pipe")

value
calculation
predictors
delta
df

322.56
glm (AIC)
1
NA
3.00

163.23
glm (AIC)
2
NA
4.00

322.84
proposal (dAIC)
1
1.05
3.14

163.50
proposal (dAIC)
2
1.03
4.14

229.58
survey (dAIC)
1
0.76
1.52

569.02
survey (dAIC)
2
1.60
4.80

141.40
survey v4.0 (dAIC)
1
1.31
1.31

28.71
survey v4.0 (dAIC)
2
0.27
0.53

322.12
vglm (TIC)
1
NA
NA

162.68
vglm (TIC)
2
NA
NA

Created on 2023-07-11 with reprex v2.0.2
Comment: Interesting, thx for your effort. Wonder if the author will respond. Question: Tried both, original and you proposal; why are all AICs different from the AICs stored in the  `"svyglm"` objects, i.e. `fit$aic`? Using `4.2-1`.


Video from Url in Videoview

Question: I want to play a video from a url in a VideoView:
@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);

    String path1="http://commonsware.com/misc/test2.3gp";
    Uri uri=Uri.parse(path1);

    VideoView video=(VideoView)findViewById(R.id.videoView1);
    video.setVideoURI(uri);
    video.start();
}

But I'm getting a NullPointerException when I try to run the app.
The logcat says that the problem is in: video.setVideoURI(uri);
Can someone help me please?
Thanks.
Answer: I don't see where you are defining a layout... I think you forgot:
setContentView(R.layout.main);

Which would cause any findViewById() to return null.
Comment: Ok, that was the problem :-).
Comment: Is it also possible to play mp4 files? If i try to play such a file i'm getting this message: Could not play video".
Comment: [Android supports mp4](http://developer.android.com/guide/appendix/media-formats.html), but I just tried with a random mp4 and got the same vague pop-up error... Sorry, I don't know the answer to this one off the top of my head.

Video from Url in Videoview


Making nodes from XLS files

Question: I'm trying to add a +2000 video database (stored on youtube) to my website. I have an excel file with on every line the video title, the url and the keywords.
Is there an easy way to automate this process rather then copy pasting +2000 times in to new nodes?
Kind regards!
Comment: http://drupal.stackexchange.com/questions/78144/sync-70-000-records-from-csv-into-drupal
Comment: @kermit Updated my answer with link. hope it helps.
Answer: You can achieve that using the Feeds module

Import or aggregate data as nodes, users, taxonomy terms or simple database records.

One-off imports and periodic aggregation of content
Import or aggregate RSS/Atom feeds
Import or aggregate CSV files
Import or aggregate OPML files
PubSubHubbub support
Create nodes, users, taxonomy terms or simple database records from    import
Extensible to import any other kind of content
Granular mapping of input elements to Drupal content elements
Exportable configurations
Batched import for large files

This article might help you to achieve this.
Answer: You can use view inside node and Feed Import
Answer: Piece of cake!
First of all here is a question I have recently answered on how to import content from .CSV file and create nodes using the feeds module. You can develop a solution with this answer as a helper.
Alternatively you can instruct your FEED module to get the videos from youtube directly rather than having the EXCEL middleman. You need to make use of the Youtube Feeds Parser Module and the modules it REQUIRES.
Once you have enabled the youtube feeds module, you should have access to an extra parser which would allow you to map fields of the content type to specific metadata of youtube videos. You can then hook this Feed Importer into a content types and instruct the CRON to run it automatically in the background - magic.
See the review of Youtube Feeds Parser here
Answer: Another approach (with custom module):
1. install YouTube Field, add new field(YouTube video) to your content type.
2. install PHPExcel module.
3. create simple custom module (.module file with single hook_enable function):
function MYMODULE_enable()
{
  module_load_include('inc', 'phpexcel');
  $path = 'sites/default/files/MYFILE.xls';
  $result = phpexcel_import($path);
  if (is_array($result)) {

    foreach ($result as $key => $value) {
      // here you need to know what's being returned by $value (you can use dpm() function from Devel module to debug the $result array).. I assume it's an object
      $node = new stdClass();
      $node->type = 'MY_TYPE';

      node_object_prepare($node);

      $node->title = $value->title;
      $node->MY_YOUTUBE_VIDEO_FIELD_NAME['und'][0]['value'] = $value->url;

      node_save($node);
    }

  }
  else {
    drupal_set_message(t('Oops ! An error occured !'), 'error');
  }
}

hook_enable is launched only once when you enable your module (I am using it here to prevent launching tnat piece of code unnecessarily).. If you want you can run that snippet at any request (without hook_enable), or from separate file (outside or inside of drupal by drush scr).

Making nodes from XLS files


Variable is not saving after subprogram

Question: I have been given a school project to create an interactive menu that allows a theoretical restaurant employee to input the items that a customer wants and output the table and the cost
(the first number is the table, second and above is the menu items)
But for some reason, in process() the cost is just getting outputted as 0, even though in the debug you can see that it is processing the cost fine.
<code>## -- Setup -- ##
Table = 0 # Used to display what table an order comes from
Menu = ["All day (Large)", "All day (Small)", "Hot Dog", "Burger", "Cheese burger", "Chicken goujons", "Fries", "Salad", "Milkshake",
    "Soft drinks", "Still Water", "Sparkling water"] # Menu Items, if statements will be used for the prices
MenuPrice = ["5.50", "3.50", "3.00", "4.00", "4.25", "3.50", "1.75","2.20", "1.30", "0.90", "0.90"]

## -- Main -- ##
# Order Input
i = input("Enter Table and Order number (Seperate with comma): ") # Order Input

# Order Processing
Order = i.split(",") # Splits the list where there is ","
Orderlen = len(Order)
Table = Order[0] # This is for displaying what table the order will go on
Table = int(Table) # Converting Table from a str to an int

global ii, Food, Cost, CostAdd
ii = 0 # Variable to complete a liner search through the order list
Food = [] # For displaying the food
Cost = 0 # For displaying the cost
CostAdd = 0 # Adds to Cost

def Process(ii, Cost, CostAdd): # Compiles the Order
    ii = ii + 1
    if ii == Orderlen:
        return Cost
        pass
    else:
        Pointer = Order[ii]
        Pointer = int(Pointer)
        Pointer = Pointer - 1 # Syncs input with the Diners Menu
        Food.append(Menu[Pointer])
        CostAdd = MenuPrice[Pointer]
        CostAdd = float(CostAdd)
        Cost = Cost + CostAdd
        print(f"Cost: {Cost}, CostAdd: {CostAdd}")

        Process(ii, Cost, CostAdd)
Process(ii, Cost, CostAdd)

# Order Output
print(f"NEW  Cost: {Cost}, CostAdd: {CostAdd}")
print(f"{Food} for Table: {Table}") # Displays what food is going to what table
print(f"This will cost: {Cost}")

</code>
Any help would be greatly appreciated, thanks in advance!
Comment: Did you intend and forget to *store* the ``Cost`` calculated inside ``Process``, perhaps? ``Cost`` inside ``Process`` is a local variable, independent of the global ``Cost`` variable.
Comment: You need to provide a [mre]. To start, you haven't given any example input.
Comment: BTW UpperCamelCase should be reserved for class names. Variables should be snake_case.
Answer: I believe this gets you the output you were looking for or at least will help you in the right direction:
<code>Table = 0 # Used to display what table an order comes from
Menu = ["All day (Large)", "All day (Small)", "Hot Dog", "Burger", "Cheese burger", "Chicken goujons", "Fries", "Salad", "Milkshake",
    "Soft drinks", "Still Water", "Sparkling water"] # Menu Items, if statements will be used for the prices
MenuPrice = ["5.50", "3.50", "3.00", "4.00", "4.25", "3.50", "1.75","2.20", "1.30", "0.90", "0.90"]

## -- Main -- ##
# Order Input
i = input("Enter Table and Order number (Seperate with comma): ") # Order Input

# Order Processing
Order = i.split(",") # Splits the list where there is ","
Orderlen = len(Order)
Table = Order[0] # This is for displaying what table the order will go on
Table = int(Table) # Converting Table from a str to an int

global ii, Food, Cost, CostAdd
ii = 0 # Variable to complete a liner search through the order list
Food = [] # For displaying the food
Cost = 0 # For displaying the cost
CostAdd = 0 # Adds to Cost

def Process(ii, Cost, CostAdd): # Compiles the Order
    while 1:
        ii = ii + 1
        if ii == Orderlen:
            return Cost,CostAdd
        else:
            Pointer = Order[ii]
            Pointer = int(Pointer)
            Pointer = Pointer - 1 # Syncs input with the Diners Menu
            Food.append(Menu[Pointer])
            CostAdd = MenuPrice[Pointer]
            CostAdd = float(CostAdd)
            Cost = CostAdd
            print(f"Cost: {Cost}, CostAdd: {CostAdd}")

Cost,CostAdd = Process(ii, Cost, CostAdd)

# Order Output
print(f"NEW  Cost: {Cost}, CostAdd: {CostAdd}")
print(f"{Food} for Table: {Table}") # Displays what food is going to what table
print(f"This will cost: {Cost}")
</code>

Variable is not saving after subprogram


Why cloned struct value still equals to the original struct

Question: I created the following interface:
type cloneable interface {
    clone() cloneable
}

And a person struct (implements cloneable):
type person struct {
    firstName string
    lastName  string
    age       int
}

func (p person) clone() person {
    return person{p.firstName, p.lastName, p.age}
}

Now I attempt to clone my person value like so:
p1 := person{"name", "last", 22}
p2 := p1.clone()

fmt.Println(p2 == p1) // PRINTS 'true', why?

The clone method works as intended, but why p2 equals to p1? these are both values, not references, how can they be equal?
Comment: As you said, `p1` and `p2` are both values. Why are you expecting a comparison to check the memory address of the object? You can do that by using `&`.
Comment: There are no references in Go.
Answer: Two structs will be equal if first, all their field types are comparable and all the corresponding field values are equal.
if your struct has at least one function or one uncomparable value, then you can not compare two structs
Answer: From The Go Programming Language Specification:

The equality operators == and != apply to operands that are comparable. ... These terms and the result of the comparisons are defined as follows:

The Go Programming Language Specification: Comparison operators


Interval that the sum of the roots of a quadratic equation can be in.

Question: I am given the equation:
$2x^2-2mx+m^2-2m=0$
Where $m\in \mathbb{R}$; $x_1$ and $x_2$ are the roots of the equation. The question asks for the interval of the sum of the roots, that is $x_1 + x_2$.
This is what I did:
Using Vieta's Formulas
$x_1 + x_2 = -\dfrac{b}{a}=-\dfrac{-2m}{2}=m.$
And since $m\in \mathbb{R}$, I thought that the interval that the sum can be in is $\mathbb{R}$. But that proved to be wrong and I don't know how to solve it, all I now know is that the true answer should be $[0,4]$.
Answer: You are correct that the sum of the two roots can take any value assuming that $x_1,x_2\in\mathbb{C}$. If instead we are limited to $x_1,x_2\in\mathbb{R}$ then we require a non-negative discriminant so
$$b^2-4ac=(-2m)^2-4(2)(m^2-2m)\ge0\implies m\in[0,4]$$
Hence the sum of the roots $x_1+x_2=m\in[0,4]$.
Comment: Shouldn't the discriminat be exclusively greater than 0? Since if we had it equal to 0, we'd only have one root, so we couldn't really talk about 2 x's. I know my reasoning is wrong since your answer is correct, but could you please point me in the right direction?
Comment: @BogdanVlad I suppose you are correct although you could say that it is a quadratic with two repeated roots such that $x_1=x_2$. In which case $x_1+x_2=2x_1=2x_2$.


Framework c# com windows Form Application

Question: Estou querendo desenvolver um ERP em C# com windows Form App, gostaria de saber se existe algum framework para essa parte.
Pois pesquisei e achei o Entity, mas não encontrei se posso utilizar ele no desenvolvimento desktop.
Alguém utilização algum para agilizar o desenvolvimento?
Obrigado
Comment: Se você tá desenvolvendo com .NET, ele próprio é um framework. Entity é um ORM.
Comment: pode trabalhar no desktop
Comment: Certo Obrigado pelos comentários, mas então se uso visual studio já estou usando um framework ?
Comment: Sim amigo, se vc está usando o visual studio, você já está usando a .Net Framework. O VIsual Studio é o nosso ambiente de trabalho, aonde escrevemos nosso código e usamos os componentes e funcionalidades que ele nós oferece, a isto chamamos de IDE. A .Net framework é o "serviço" que pega o que fazemos no VS e converte em linguagem de máquina para o computador interpretar. resumindo a framework tem os recursos e o visual studio é o meio para usarmos estes recursos
Answer: o próprio .Net já é um Framework, mas dentro dele você possui várias bibliotecas e uma delas é a do Entity Framework, que tem o objetivo de resolver o problema de persistência de dados baseado no conceito de ORM. Você poderá utilizar o Entity em sua aplicação seja ela Desktop ou Web, mas para persistência de dados você não é obrigado a usar o Entity, poderá utilizar outro framework ORM como o NHibernate, ou mesmo utilizar instruções SQL para realizar os insert, update, selects, deletes dos registros das tabelas de seu sistema.
Antes de mais nada tenha em mente que essa é uma decisão muito importante para a arquitetura do seu sistema, inclusive depende do banco de dados que irá utilizar.


Form com dois destinos

Question: Tenho o seguinte formulário:
@using (Ajax.BeginForm("minhaAction", "meuController", new AjaxOptions()
    {
        HttpMethod = "POST",
        OnFailure = "alert('Erro!')",
        OnSuccess = "TrabalharResultado"

    }, new { id = "meuForm" } ))
{
...
...
...
<input type="submit" value="Enviar" id="btn-Enviar" />
<input onclick="enviarForm" type="button" value="Enviar Outro Action" id="btn-Enviar2" />
}

Ao clicar no botão btn-Enviar todo o form é enviado minhaAction em meuController.
Meu objetivo é que ao clicar no botão btn-Enviar2, esse mesmo form seja enviado para outraAction em meuController, então lá eu poderia receber a mesma FormCollection.

Como eu poderia fazer a function enviarForm?
Answer: Você poderia setar 2 values com o mesmo name para cada button
<button type="submit"name="minhaaction" value="Action 1">
<button type="submit"name="minhaaction" value="Action 2">

e em sua Action, realizar a verificação para cada um dos casos
public ActionResult MinhaAction(string minhaaction)
{
   if(minhaaction == "Action 1") {
     //realiza action 1
   }else {
    //Realiza action 2
   }
}

Comment: @bigown sobre db? eu publiquei novamente, acabei publicando 2 vezes, então eu deletei uma, desculpe...poderia responder sim, obrigado

Form com dois destinos


How do I check the value of a field if its empty?

Question: Is there a way to check, in a preprocess function, if the value of a field is empty?
I'm getting the following error.

Call to a member function isEmpty()

function iom_preprocess_block__twitterfeed(&$variables) {
  // Get the twitter_username field from node.
  $twitterUsername = \Drupal::routeMatch()
    ->getParameter('node')
    ->get('field_twitter_username')
    ->value;

  if ($twitterUsername->isEmpty()) {
    dump("Empty");
  }
  else {
    dump("Not Empty");
  }
}

Answer: @vinhd proposition is correct, by the way you can also use the isEmpty() method from the field list interface. It can be more adapted for complex field types.
if($node->hasField('field_your_field') && !$node->get('field_your_field')->isEmpty(){

}

Comment: This is the correct answer: after get(..) you can call isEmpty right away.
Answer: None of the other answers is fully correct, each one will only work in some cases. Before calling an object method, you have to check
- if the object exists,
- if the object is of the right type
- and if the object has that specific method/field.
The following code might look like a bit of an overkill, but it is the most bulletproof solution I've found so far. Everything I'm checking in there is based on a real word error I've had in my own projects:
function MYMODULE_preprocess_MYHOOK(&$variables) {

  $route = \Drupal::routeMatch();

  //special case node preview: has no node object, but a node_preview
  if ($route->getRouteName() == 'entity.node.preview') {
    $node = $route->getParameter('node_preview');
  }
  // this is the default case
  else {
    $node = $route->getParameter('node');
  }

  //$node can be either a node object (most of the times)
  //or an integer (on some admin routes)
  if (is_numeric($node)) {
    $node = \Drupal\node\Entity\Node::load($node);
  }

  // this if-statement is the important part that prevents the error messages
  if ($node instanceof \Drupal\node\NodeInterface && $node->hasField('field_MYFIELD')) {
    // no you can savely do whatever you want with field_MYFIELD
    $myVar = $node->get('field_MYFIELD')->value;
    $isEmpty = $node->get('field_MYFIELD')->isEmpty();
  }
}

Answer: You can try code:
check has field:
$node = \Drupal::routeMatch()->getParameter('node');
if($node->hasField('field_twitter_username')){
  //todo code
}

check empty value
$field_value = $node->field_twitter_username->getValue()
if(!empty($field_value)){
  //todo code
}

Comment: Second option seems to caught an error `Error: Call to a member function getValue() on string`
Comment: can you check hasField that field does exist
Comment: @clestcruz it works great


Problom With VBA code throw an "user defined type not defined" error

Question: I cannot figure out why the following code is throwing a compile error with the message "user defined type not defined". It is highlighting Set fso = FileSystemObject
Sub S()
Dim fso As FileSystemObject
    Dim ts As TextStream
    Dim i As Integer
    Dim myCell As Range

    Set fso = FileSystemObject

    For i = 0 To TotalColumnNumber
       ' last argument, True, says to create the text file if it doesnt exist, which is
       ' good for us in this case
       Set ts = fso.OpenTextFile("column_" & i, ForWriting, True)

       ' set mycell to the first cell in the ith column
       Set myCell = SheetName.Cells(1, i)

       ' continue looping down the column until you reach a blank cell
       ' writing each cell value as you go
       Do Until myCell.Value = ""
           ts.writeline myCell.Value
           Set myCell = myCell.Offset(1, 0)
       Loop

       ts.Close
    Next

    Set ts = Nothing
    Set fso = Nothing

    End Sub

thanks
Comment: Move the line ***Sub S()*** to the top of your code.
Comment: @Gary'sStudent now  Sub S() is highlighting :(
Comment: Try `Set fso = New FileSystemObject`
Comment: https://trumpexcel.com/vba-filesystemobject/
Answer: The code has many several problems:

You need to set a Reference

use:  Set fso = New FileSystemObject
establish values for your variables before you use them; this includes TotalColumnNumber, SheetName, etc.
Answer: Are you referencing the correct namespaces in Tools/References?

Problom With VBA code throw an “user defined type not defined” error


Is using jQuery a guarantee for cross browser compatibility?

Question: I noticed that writing cross-browser compatible code in JavaScript could be a little difficult in some cases. Is using jQuery a guarantee that my JavaScript code works in all browsers?
Comment: [http://docs.jquery.com/Browser_compatibility](http://docs.jquery.com/Browser_compatibility)
Comment: Have a look at this page: http://docs.jquery.com/Browser_Compatibility
Comment: It depends entirely on what you intend to do. For example, ajax requests are standardised within jQuery, so you can rest assured ajax will work across all browsers simply by coding it using jQuery. That is only one example.
Answer: jQuery provides good compatibility among modern browsers. There are, however, no guarantees. No one can offer you that.
Answer: As you can read on jQuery's page about browser compatibility, it supports all modern browsers including old but widely used browsers like Internet Explorer 7. If you encounter an issue with a browser using jQuery, you should submit a bug report. The beauty with frameworks such as jQuery is their compatibility.
Good luck!


I want to apply a style request to all sheets in a spreadsheet using google spreadsheet API

Question: the following is a batch updates request, it is styling only the sheet of index 0, I would like to apply this style to all sheets in the spreadsheet, or alternatively style each sheet by name...
I am trying to avoid making a request, getting the sheet ids and names, and styling each one by its id.
<code>   // start sheet formatting for better readability/visuals
           $formatRowColrequests = [
               new \Google\Service\Sheets\Request([
                   'updateSheetProperties' => [
                       'properties' => [
                           'gridProperties' => [
                               'frozenRowCount' => 1
                           ]
                       ],
                       'fields' => 'gridProperties.frozenRowCount'
                   ]
               ]),
               // columns auto width to fit content
               new \Google\Service\Sheets\Request([
                   "autoResizeDimensions" => [
                       "dimensions" => [
                           "dimension" => "COLUMNS",
                           "startIndex" => 0,
                       ]
                   ]
               ]),
               new \Google\Service\Sheets\Request([
                   "repeatCell" => [
                       "range" => [
                           "endRowIndex" => 1,
                       ],
                       "cell" => [
                           "userEnteredFormat" => [
                               "backgroundColor" => [
                                   "red" => 152 / 255,
                                   "green" => 217 / 255,
                                   "blue" => 99 / 255,
                                   "alpha" => 0.8
                               ],
                               "horizontalAlignment" => "LEFT",
                               "textFormat" => [
                                   "fontSize" => 12,
                                   "bold" => true,
                               ]
                           ]
                       ],
                       "fields" => "userEnteredFormat(textFormat,backgroundColor,horizontalAlignment)"
                   ]
               ]),
               new \Google\Service\Sheets\Request([
                   "repeatCell" => [
                       "range" => [
                           "startRowIndex" => 1,
                       ],
                       "cell" => [
                           "userEnteredFormat" => [
                               "horizontalAlignment" => "LEFT",
                               "textFormat" => [
                                   "fontSize" => 10,
                                   "bold" => false
                               ]
                           ]
                       ],
                       "fields" => "userEnteredFormat(textFormat,backgroundColor,horizontalAlignment)"
                   ],
               ]),
           ];
           $batchUpdateCellFormatRequest = new \Google\Service\Sheets\BatchUpdateSpreadsheetRequest([
               'requests' => $formatRowColrequests,
           ]);
           $service->spreadsheets->batchUpdate($target_spreadID, $batchUpdateCellFormatRequest);
           // end sheet formatting
   ```
</code>
Answer: I believe your goal is as follows.

You want to use your request body for all sheets or the specific sheets using the sheet names.
You want to achieve this using googleapis for PHP.
You have already been able to get and put values to the Spreadsheet using Sheets API.

In this case, how about the following modification? In this modification, first, the sheet IDs are retrieved using the sheet names. Using these sheet IDs, your request body is used for the specification sheets.
Modified script:
<code>$target_spreadID = "###"; // please set Spreadsheet ID.

// Retrieve sheet IDs.
$sheetNames = ["Sheet1", "Sheet3"]; // Please set the sheet names you want to use the request body.
$res = $service->spreadsheets->get($target_spreadID, [
  "ranges" => $sheetNames,
  "fields" => "sheets(properties(sheetId))",
]);

// Create request body.
$sheets = $res->getSheets();
$requests = [];
foreach ($sheets as $i => $sheet) {
  $sheetId = $sheet->getProperties()->getSheetId();
  $formatRowColrequests = [
    new \Google\Service\Sheets\Request([
      "updateSheetProperties" => [
        "properties" => [
          "gridProperties" => [
            "frozenRowCount" => 1,
          ],
          "sheetId" => $sheetId,
        ],
        "fields" => "gridProperties.frozenRowCount",
      ],
    ]),
    // columns auto width to fit content
    new \Google\Service\Sheets\Request([
      "autoResizeDimensions" => [
        "dimensions" => [
          "dimension" => "COLUMNS",
          "startIndex" => 0,
          "sheetId" => $sheetId,
        ],
      ],
    ]),
    new \Google\Service\Sheets\Request([
      "repeatCell" => [
        "range" => [
          "endRowIndex" => 1,
          "sheetId" => $sheetId,
        ],
        "cell" => [
          "userEnteredFormat" => [
            "backgroundColor" => [
              "red" => 152 / 255,
              "green" => 217 / 255,
              "blue" => 99 / 255,
              "alpha" => 0.8,
            ],
            "horizontalAlignment" => "LEFT",
            "textFormat" => [
              "fontSize" => 12,
              "bold" => true,
            ],
          ],
        ],
        "fields" =>
          "userEnteredFormat(textFormat,backgroundColor,horizontalAlignment)",
      ],
    ]),
    new \Google\Service\Sheets\Request([
      "repeatCell" => [
        "range" => [
          "startRowIndex" => 1,
          "sheetId" => $sheetId,
        ],
        "cell" => [
          "userEnteredFormat" => [
            "horizontalAlignment" => "LEFT",
            "textFormat" => [
              "fontSize" => 10,
              "bold" => false,
            ],
          ],
        ],
        "fields" =>
          "userEnteredFormat(textFormat,backgroundColor,horizontalAlignment)",
      ],
    ]),
  ];

  $requests = array_merge($requests, $formatRowColrequests);
}
$batchUpdateCellFormatRequest = new \Google\Service\Sheets\BatchUpdateSpreadsheetRequest(["requests" => $requests]);

// Request Sheets API using the created request body.
$service->spreadsheets->batchUpdate($target_spreadID, $batchUpdateCellFormatRequest);
</code>

When this script is run, your request body is used for the specific sheets declared by <code>$sheetNames = ["Sheet1", "Sheet3"];</code>.

If you want to use your request body to all sheets in the Spreadsheet, please modify the above script as follows.

From
<code>  $sheetNames = ["Sheet1", "Sheet3"]; // Please set the sheet names you want to use the request body.
  $res = $service->spreadsheets->get($target_spreadID, [
    "ranges" => $sheetNames,
    "fields" => "sheets(properties(sheetId))",
  ]);
</code>

To
<code>  $res = $service->spreadsheets->get($target_spreadID, [
    "fields" => "sheets(properties(sheetId))",
  ]);
</code>

References:

Method: spreadsheets.get
Method: spreadsheets.batchUpdate
Comment: Thank you for your reply @Tanaike, I was trying to avoid a second request to target specific Ids as the whole spreadsheet is being manipulated by the code. I was hoping there would be a wildcard of some sort to apply a request to all sheets.
Comment: @Hsein Bitar Thank you for replying. About `I was hoping there would be a wildcard of some sort to apply a request to all sheets.`, unfortunately, in order to reflect your request body to all sheets, it is required to use the sheet ID for each sheet. I apologize for this current specification on the Google side. And, I deeply apologize my answer was not useful. This is due to my poor skill. I deeply apologize for this. But, I think that my answer might be useful for other users. So I would like to leave my answer. If you are required to delete my answer, please tell me.
Comment: I did end up using the sheet ID, and your answer is useful definitely @Tanaike.
I will not mark it as accepted yet, maybe someone would find a wildcard, maybe in some updates later.
Comment: @Hsein Bitar Thank you for replying. About `I will not mark it as accepted yet, maybe someone would find a wildcard, maybe in some updates later.`, I understand your intention. I thought that unfortunately, in the current stage, this your goal cannot be achieved. So, as the current solution, I proposed the above sample script. I think that this is due to my very poor skill. I deeply apologize for my very poor skill again. I would like to study more. But, I think that your goal might be achieved in the future update at the Google side.


Loss function for linear regression with calculus of variations

Question: I'm struggling with mathematics behind linear regression. In the following lines I pasted the text from the book Pattern Recognition and Machine Learning (p. 46) where author derives the regression function $\mathbb{E}_{t} [t | \mathbf{x}]$. I want to understand the procedure from the equation (2) to the final result. Could somebody please provide me some useful pointers (and/or links) which concept from the calculus of variations should I study.
The average, expected, loss is given by
$$
\mathbb{E}[L] = \int \int L(t, x (\mathbf{x})) p (\mathbf{x}, t) \, d\mathbf{x} \, dt.
\tag{1}
$$
A common choice of loss function in linear regression is the squared loss given by $L (t, y(\mathbf{x})) = \{ y (\mathbf{x}) - t \}^{2}$. In this case, the expected loss can be written as
$$
\mathbb{E}[L] = \int \int \{ y (\mathbf{x}) - t \}^{2} p (\mathbf{x}, t) \, d\mathbf{x} \, dt.
\tag{2}
$$
Our goal is to choose $y (\mathbf{x})$ so as to minimize $\mathbb{E} [L]$. We can do this using the calculus of variations to give
$$
\dfrac{\delta \mathbb{E} [L]}{\delta y (\mathbf{x})} = 2 \int \{ y (\mathbf{x}) - t \} p (\mathbf{x}, t) \, dt = 0.
\tag{3}
$$
Solving for $y (\mathbf{x})$, and using the sum and product rules of probability, we obtain
$$
y (\mathbf{x}) = \dfrac{\int tp (\mathbf{x}, t) \, dt}{p (\mathbf{x})} = \int t p (t | \mathbf{x}) \, dt = \mathbb{E}_{t} [t | \mathbf{x}]
\tag{4}
$$
Answer: I don't think you need calculus of variations. First, define the loss for every fixed $\bf x$,
$$\mathbb{E}[L | {\bf x}] = \int \{ y (\mathbf{x}) - t \}^{2} p (t | \mathbf{x}) \,  dt.
\tag{2*}$$
and the minimizer of that is $y (\mathbf{x}) = \mathbb{E}_{t} [t | \mathbf{x}]$
and then just
$$\mathbb{E}[L] = \int \mathbb{E}[L|x] f(x)\, dx$$
Comment: Thanks for your reply. But, I still want to use calculus of variations.
Comment: The calculus of variations is just a set of rules to justify formal derivative computations. Expanding $(y(\mathbf{x})-t)^2=y(\mathbf{x})^2+t^2-2y(\mathbf{x})t$, it is absolutely clear that the minimizer is unique and attained at the value $y(\mathbf{x})$ you mentioned. That is all the "calculus of variations" you need.
Answer: I am assuming your difficulty is in the jump between Eq.2 and Eq.3. All you need is an Euler-Lagrange equation, as in their equation (3). In their notation $f(x,y,\dot y)=\int \{y(x)-t\}^2p(x,t)dx$, so that $df/d\dot{y}=0$, for instance.
UPDATE:
answering comments to make a more verbose explanation.
The Eq. (2) can be rewritten as:
$$E[L]=\int f(t,y) dt$$
The stationary (optimal) solution is when in my link to E-L the condition (3) is satisfied, but since our $f(t,y,\dot y)\equiv f(t,y)$ doesn't have $\dot y$ in it, only the first term matters and it becomes:
$$\frac{\partial f}{\partial y}=0$$
This is Eq. (3) in the question. If you have trouble arriving to it, then review the Leibnitz integral rule. However, in this case it's unnecessary, because the integral is over $t$, so you can simply apply differentiation wrt $y$ trivially.
Comment: I have stumbled across the same problem about how it went from Eq.2 to Eq.3.  I still could not understand the solution given by you. It would be great if you can explain a bit more in detail. Thanks!
Comment: To be concrete, I could not understand the derivation of  $δE[L]/δy(x)$ (how did it result into the LHS of Eq.3) and why did $dx$ go away.
Comment: I still couldn't understand the steps between (2) and (3) reading this answer. In case a reader is still interested in the problem, [here](https://math.stackexchange.com/questions/2130282/bishop-ml-and-pattern-recognition-calculus-of-variations-linear-regression-loss)'s a much clearer explanation.


Showing uniform convergence of $f_n(x) = \sin(\frac{x}{n})$ on $[0, 1]$ and $[0, \infty]$.

Question: I understand how to show that the sequence of functions given by $f_n(x) =
\sin(\frac{x}{n})$ converges uniformly on $[0,1]$.
Indeed, suppose $\epsilon > 0$. Choose $N \in \mathbb{N}$ such that $N>\frac{1}{\epsilon}$. Then $\lvert \sin(\frac{x}{n}) \rvert \leq \frac{x}{n} \leq \frac{1}{n} \leq \epsilon$ if $n \geq N$.
I'm stuck on proving it fails to be uniformly convergent on $[0, \infty)$. I believe that to negate the definition of uniform convergence, I need to find an $\epsilon > 0$ such that for all $N
\in \mathbb{N}$ there exists an $x \in [0, \infty)$ so we can find an $n \geq N$ such that $\lvert \sin(\frac{x}{n}) \rvert\geq \epsilon$.
So I guess could take $\epsilon = \frac{1}{10}$ and suppose $N \in
\mathbb{N}$. But I don't know how to choose $x$ and find an $n\geq N$ to satisfy $\lvert \sin(\frac{x}{n}) \rvert\geq \epsilon$.
Answer: The sequence $\left(\sin\left(\frac xn\right)\right)_{n\in\mathbb N}$ doesn't converge uniformly on $[0,+\infty)$ because it converges pointwise to the null function, but, for each $n\in\mathbb N$, $\sin\left(\frac{\pi n}n\right)=-1$. So, if you take $\varepsilon=1$, it is not true that there is a natural $N$ such that$$n\geqslant N\wedge x\in[0,+\infty)\implies\left|\sin\left(\frac xn\right)\right|<\varepsilon.$$
Comment: Many thanks for this! It also helped me understand how to prove it for similar problems! :)


Trying to find a combinatorial design which describes my problem

Question: A group of 8 golfers would like to play in teams, split into two teams of 4, with a different arrangement of teams on each of 5 consecutive days; they would like each pair of players to be on the same team on at least 2 but no more than 3 of the days.
I've established computationally that there are no solutions which fit these criteria; however, I'd like to be able to prove it's not possible by finding the correct combinatorial design and showing that for these values it can't be done; I'd also be interested to know if it would be possible with more golfers, or more days.
I don't know much about design theory, although from what I can see of block designs, many of the examples given allow for setups where each pair occurs in a given number of blocks; the situation where there are two teams isn't covered, since even if I choose blocks of size 4, a pair not being contained in a block isn't the same as both those players being in the other team; it seems I'd need a particular type of block design, possibly a tournament model, but they seem to be more aimed at pairing up competitors rather than teams. Any ideas what I'm looking for?
Answer: This is not a complete solution. I'm working on it.

On each day, there are two teams of four golfers. Each team of four corresponds to six distinct pairs of players who are on the same team that day. This means that, over the five days, the total number of (not necessarily distinct) pairs of players on the same team is exactly $$5\cdot 2 \cdot \binom{4}{2} = 60$$
The total number of distinct pairs is $$\binom{8}{2}=28$$
Each of these distinct pairs is allowed to show up in the overall count of $60$ at least $2$ times and at most $3$ times.
This means that exactly four of the pairs show up $3$ times, and the rest show up only twice. In other words, four distinct pairs of golfers share a team three times, and the other $24$ pairs of golfers are only on the same team twice. These numbers $4$ and $24$ are the solutions $x$ and $y$ to this simple system of equations
\begin{align}
x+y&=28\\
3x+2y&=60
\end{align}
But we also know that every golfer is on a team on each of the five days. This means that each golfer is included in $3$ pairs (of golfers on the same team) each day. We use this first to confirm the total number of pairs (dividing by $2$ to adjust for overcounting) as $$\frac{3 \cdot 5 \cdot 8}{2}=60$$
Now the four pairs that have multiplicity $3$ can be all distinct, or there could be at least one golfer who appears in at least two of these pairs. But the fact that each golfer plays the same number of days implies that all multiplicity-$3$ pairs are distinct. In other words, all $8$ golfers are included in exactly $1$ pair that has multiplicity $3$.
Comment: This is great - I've managed to determine this, and used it in my computational approach. It gives you a very constrained problem, and I'm not surprised there are no solutions. Let me know if you get any further!
Comment: @KatieSteckles I've tried a few things and I can't come up with a nice way to finish the problem - it does narrow down the possibilities a lot though, so maybe brute force for the rest of them (as I assume you did?) is the best approach...


Handling callbacks with RxJava

Question: I am trying to understand what is the best way to handle a particular case, using RxJava.
I need to return an Observable which handles the removal of an account from the Android AccountManager. Unfortunately, this action is asynchronous and it needs a callback to handle the result.
Because of this, I am using the Observable.create method, in this way:
return Observable.create(subscriber -> {
        final Account account = getAccountIfExist();
        if (account == null) {
            subscriber.onError(new NoUserFoundException());
            return;
        }

        accountManager.removeAccount(account, future -> {
            boolean result = false;
            try {
                result = future.getResult();
            } catch (Exception ex) {
                Log.e(TAG, "Remove account not successful : ", ex);
                subscriber.onError(ex);
                return;
            }

            if (result) {
                subscriber.onNext(account.name);
                subscriber.onCompleted();
            } else {
                subscriber.onError(new RuntimeException("Cannot remove the account."));
            }
        }, null);
    });

But, Observable.create has different problems dealing backpressure and cancellation, as stated in this post
So, the question is, how can I use Observable.fromCallable (or an equivalent method) for handling callbacks (in general) and also dealing with backpressure and cancellation?
Answer: You can try to use

Observable.defer

return Observable.defer(() -> {
    final Account account = getAccountIfExist();
        if (account == null) {
            return Observable.error(new NoUserFoundException());
        }
 accountManager.removeAccount(account, future -> {
            boolean result = false;
            try {
                result = future.getResult();
            } catch (Exception ex) {
                 return Observable.error(ex);
            }

            if (result) {
                Observable.just(account.name);
            } else {
                return Observable.error(new NoUserFoundException("Cannot remove the account."))
            }
        }, null);
});

Handling callbacks with RxJava