Feature selection in a traditional regression model to an experiment data

Question: I have an experiment data (total of 96) with 10 predictor and 2 response variables. I want to build a traditional multiple linear regression model to them in R. My aim is to build clearly interpretable (coefficients) and explanatory models for a journal article. Not all variables being significant, I have been trying to reduce the number of variables by checking their t and f table p values as well as the VIF scores to reduce multicollinearity among them. However, rather than this manual selection, I want to use a straightforward and commonly accepted automated feature selection.
I have been doing stepwise regression and I stopped after reading all the statistical doubts about it in the forum. I have read many people suggest Lasso models or some more machine learning related sophisticated approach for this. But, I want to keep this process as simple as possible such that the people in my area (engineering) can easily understand it.
Does anyone have any other suggestion rather than stepwise regression for this automated process?
Note: I have realized some interaction variables play important role in my dataset, so I want to include them as well into this trial (even though the multicollinearity coming with it).
Comment: Why select features at all?  Linear regression is already interpretable, what do you gain by selecting features via a data first approach and not using your domain expertise?
Comment: Because I want the simplest model (principle of parsimony). Some variables are not significantly affecting the model and there are multicollinearity within the variables such that I want to carefully remove some of them by not only my domain expertise but also an accepted automation algorithm.
Comment: There is no "accepted automation algorithm" because data are just numbers without context (that is to say, your domain knowledge).  Coefficients failing to reject the null and multicollinearity are not as problematic as one thinks.

What is your experiment on? What is the goal of this experiment?  Let's start there and maybe we can find a suitable solution.
Answer: See Frank Harrell's Regression Modeling Strategies for extensive discussion about how to cut down on the number of predictors responsibly. Any method that uses the outcomes to select or combine predictors will lead to the same problems as stepwise regression. You certainly can, however, work with the predictors themselves to combine your domain expertise with methods that reduce their effective numbers.
If you have collinear continuous predictors, I suspect that your audience of engineers would be able to understand and accept an approach based on principal components (PCs), combining several predictors that are correlated and only keeping the first 1 or 2 PCs. You can choose some illustrative name for those PCs based on your domain knowledge. Section 4.7 goes into further "data reduction" approaches, based for example on redundancy analysis or predictor clustering. Chapter 8 illustrates the principles in a case study.
Those might not be the "automated" approaches that you seem to want, but these approaches avoid the major pitfall of automated approaches that use the outcomes to pick the predictors.


Non-negative determinant of a block matrix

Question: Here's the problem I've been stuck on for some time now.

Let $A,B \in M_n(\mathbb{R})$. Let $C=
        \begin{bmatrix}
        A & B \\
        -B & A \\
        \end{bmatrix}
$ be a real $2n \times 2n$ matrix. Prove $\det(C) \geq 0$.

What I've tried so far are:

First I tried to write determinant of $C$ as the sum of $2^{2n}$ matrix determinants by expanding all rows of $C$ such that for each binary sequence of length $2n$ like $a = (a_1, a_2, ..., a_{2n})$, if $a_i = 0$ then the first $n$ entries of $i$-th row are zero and if $a_i = 1$ then the second $n$ entries of $i$-th row are zero. But couldn't come close to any answer.
Second we know that determinant is the product of eigenvalues. The characteristic polynomial of $C$ has real coefficients hence its complex roots come in conjugate pairs and have positive product. What remains is to prove that each negative eigenvalue has even multiplicity which I couldn't prove.

Any sort of hints and/or ideas are appreciated.
Answer: Hint. Start with $$\det{\begin{bmatrix}A & B \\-B & A\end{bmatrix}}=\det{\begin{bmatrix}A-iB& B+iA \\-B & A\end{bmatrix}}.$$
Comment: $B+iA=i(A-iB)$.
Comment: Can you plz explain more?
Answer: Let $\left( \begin{matrix} x \\ y \end{matrix} \right) \in \mathbb{R}^{2n}$ be an eigenvector with eigenvalue $\lambda$.
Then $\left( \begin{matrix} -y \\x \end{matrix} \right)$ is also an eigenvector with eigenvalue $\lambda$, so all eigenvalues have an even number of linear independent eigenvectors.
Comment: I don't see how you can conclude without accounting for Jordan blocks.
Comment: @FedericoPoloni A generalized eigenvector of rank $2$ has an associated eigenvector of rank $1$, and you can switch $x$ and $y$ in both eigenvectors, to obtain a generalized an associated eigenvector of the same eigenvalue, thus still keeping an even number of eigenvalues. And the same for eigenvectors of higher rank.


customize error message for required field with  in liferay

Question: I'm trying to validate a required Select option with aui.
for input fields the code below works without any issue :
<aui:input name="name" value="${name}" label="name">
     <aui:validator name="required" errorMessage="your-message-here"></aui:validator>
</aui:input>

But with Select option field, I cannot customise the required error message :
for example :
<aui:select required="true" label="field.label" id="id" name="name" useNamespace="false">
    <aui:option value="" label="first.option" selected="option1"/>
    <aui:option value="" label="second.option" selected="option2"/>
    <aui:option value="" label="third.option" selected="option3"/>

</aui:select>

My Question is : How can I customize the error message for required field in <aui:Select>
Thanks .
Answer: You can validate an aui:select with custom message as following (Tested Code):
HTML
<aui:form method="post" name="fm">
    <aui:select name="sampleDropdown" label="">
        <aui:option selected="true" value="">Select an Option</aui:option>
        <aui:option value="1">Option 1</aui:option>
        <aui:option value="2">Option 2</aui:option>
        <aui:option value="3">Option 3</aui:option>
    </aui:select>

    <aui:button value="Save" type="submit"></aui:button>
<aui:form>

Script:
AUI().ready('alloy-node', 'aui-form-validator', function(A) {
    var formValidator = new A.FormValidator({
        boundingBox: document.<portlet:namespace />fm,
        rules: {
            <portlet:namespace />sampleDropdown: {
                required: true
            }
        },
        fieldStrings: {
            <portlet:namespace />sampleDropdown: {
                required: 'Hey, can\'t leave this unselected.'
            }
        },
        on: {
            validateField: function(event) {},
            validField: function(event) {},
            errorField: function(event) {},
            submitError: function(event) {
                var errors = event.validator.errors;
                event.preventDefault();
            },
            submit: function(event) {
                return false;
            }
        }
    });
});

CSS:

success style

.aui .control-group.success input,
.aui .control-group.success select,
.aui .control-group.success textarea {
  border-color: #488f06;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.075) inset;
}

.aui .control-group.success .checkbox,
.aui .control-group.success .radio,
.aui .control-group.success input,
.aui .control-group.success select,
.aui .control-group.success textarea {
  color: #488f06;
}

error style

.aui .control-group.error input,
.aui .control-group.error select,
.aui .control-group.error textarea {
  border-color: #b50303;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.075) inset;
}

.aui .control-group.error .checkbox,
.aui .control-group.error .radio,
.aui .control-group.error input,
.aui .control-group.error select,
.aui .control-group.error textarea {
  color: #b50303;
}

.aui .control-group.error .control-label,
.aui .control-group.error .help-block,
.aui .control-group.error .help-inline {
  color: #b50303;
}

.aui .help-inline {
  display: inline-block;
  padding-left: 5px;
  vertical-align: middle;
}

Comment: I have exactly the same problem. Can you suggest any other solution? My problem with this is that I have a dynamic form, with unknown number of drop-down lists and with id-s and required messages all coming from the server side. Also, I cannot use an  inside an , Liferay throws a NullPointerException if I do so. Any idea? Thanks in advance.
Comment: Welcome to SO. If the answer above doesn't satisfy your requirement, you can ask new question using http://stackoverflow.com/questions/ask.
Comment: Please ignore my previous comment, I could use your solution, thank you. But I have on question: if I use this instead of an ``, the success (green) and error (red) css styles are only applied to the field when I click the submit button, not when I click away from the field. With ``, they are applied in both cases. Do you know why?
Comment: Its because the custom validator is called on submission of form.
Comment: Acually it's also called when the user clicks away from the drop-down, since it shows the custom error message if they left it empty. It's just the red/green error/succes css styles that don't get applied. They only do when the submit button is clicked.
Comment: Red / Green CSS is applied properly for respective validation, you might have styles related issue. Check for .aui .control-group.error select and .control-group.error .help-inline in aui.css and updated color scheme as per your requirement.


how to delete a record of a collection after a specific amount of time

Question: i want to create an OTP (one time password) for my node js application using mongodb as database
after generating otp and sending that for client with email i want to store the otp as hashedOTP in database and delete (or expire) that after a specific amount of time like 2 minutes
but iam having some problem with that and i dont know how to do it
i have read some articles and mongodb documentations about TTL but i didn't understand that how its working at all and i guess its just about date type records
so i did it with js setTimeout method and in small scales its working fine but because iam not experienced i dont know that it work fine with biger scales or not
here is my schema that i made and i tried expires and expiresAfterSeconds for hashedOTP but it didnt worked
const adminSchema = new mongoose.Schema({
firstName : {
    type : 'string'
},
lastName : {
    type : 'string'
},
email : {
    type : 'string'
},
password : {
    type : 'string'
},
phoneNumber : {
    type : 'string'
},
role : {
    type : 'string'
},
confirmationToken : {
    type : 'string'
},
hasConfirmedEmail : {
    type : Boolean,
    default : false
},
hashedOTP : {
    type : 'string',
}

})
now the first question is saving OTP in database is correct way?
here is my code for handling with setTimeout
    try {
    const hashedotp = await bcrypt.hash(otp,10)
    verifiedAdmin.hashedOTP = hashedotp
    await verifiedAdmin.save()
    setTimeout(async () => {
        console.log('set time out gonna work now ')
        verifiedAdmin.hashedOTP = ''
        await verifiedAdmin.save()
    }, 120000);

i know that it is not necessary to hash the otp but i just did it and the verifiedAdmi is the user that i want to send otp for it and its made by above schema
i just feel that this setTimeout is not going to work fine cause it has many interactions with database
Answer: If you want to delete the hashedOTP after a fixedTime (ie 120000 second) , You could run a cron job and update the collection by checking against the createdAt time
1 - Run Cron Job
2 - if( time of checking is greater than createdAt + 120000 sec) then delete
the hashotp
const CronJob = require('cron').CronJob;

 new CronJob({
    cronTime: "00 */5 * * * *", //every five minutes
    onTick: function() {
       helperFunctionToUpdateData()
    },
}),

i prefer using moment.js to check time difference
Comment: setTimout is queuing those code to be run later , so in case your server gets restarted due  to any reasons , the setTimout will be disappeared and the token won't be removed from the database which is not ideal when thinking from the security part. Its best to implement something like cronJob
Comment: thanks for your answer but the main problem is that i want to have less interaction with database but i forgot to mention that in this way yet we have much interactions with database
Comment: that's the main issue, when the server restarted you loose the action in the setTimeout
Answer: Instead of deleting you do do the below:
Create a different model let say , OtpVerification with fields userId (indexed, because lot of searching will be done), otp (the random number) and expiresAt (current time + 10 minutes can be done easily using moment js).
Then while verifying find in OTPVerification if any document with that userId present if present check otp and
if (expiresAt > currentTime) {
   // allow
} else {
   // otp expired
}


Percorrendo um arquivo e dividindo seu conteúdo em outros arquivos separados usando Python

Question: from scapy.all import *

pkts = rdpcap("lalalao2.pcap")

#time slice de t em segundos : 10 minutos

t = 600
somaMin = pkts[0].time + t

valores=[]
for p in pkts:

    if p<=somaMin:

        valores.append(p)

    else:

        primslice =valores

        f=open("time1.txt",'w')
        f.writelines(primslice)

        valores=[]

        valores.append(p)

        somaMin=p.time + t

O código acima abre um arquivo de dump de rede (PCAP) e cria vetores contendo time slices de t segundos. Gostaria que cada time slice fosse gravado em um arquivo texto diferente: time1, time2, ...
O problema é que não sei quantos slices terei, pois depende da captura. É possível?
Answer: Sim, basta fazer com que o nome do arquivo seja variável. Algo como open('time{}.txt'.format(i), 'w') onde i é um contador.
from scapy.all import *

pkts = rdpcap("lalalao2.pcap")

i = 1
# ^--- Inicia o contador

#time slice de t em segundos : 10 minutos

t = 600
somaMin = pkts[0].time + t

valores=[]
for p in pkts:

    if p<=somaMin:

        valores.append(p)

    else:

        primslice =valores

        f=open("time{}.txt".format(i),'w')
        #           ^--- Deixa o nome do arquivo variável

        f.writelines(primslice)

        i += 1
        # ^--- Incrementa o valor de i indefinidamente enquanto necessário

        valores=[]

        valores.append(p)

        somaMin=p.time + t

Este código gerará os arquivos time1.txt, time2.txt, time3.txt, etc.

Nota: Na sua lógica, se o número de slices não for exatamente um múltiplo do tempo, você perderá o último slice (não será gravado em arquivo). Imagine que em cada slice serão gravados 100 registros, mas no final, no último slice, não sobrem os exatos 100, mas apenas 90. Quando fizer o loop, todos os registros entrarão no if p<=somaMin, mas nenhum entrará no else, onde é escrito o arquivo. Então recomendo que transforme a escrita em arquivo em uma função, chame-a dentro do else, se ainda desejar, mas depois do for, verifique se há elementos em valores e se sim, chame a função novamente.
Comment: sobre a nota é Só colocar o que sobrou fora do loop e gravar em outro arquivo
Comment: Que é exatamente o que eu falei, não é?
Comment: @Anderson Carlos Woss, obrigado. Vou estudar o código aqui!


What variable type to choose for a Poisson distributed variable if software package only allows for nominal, ordinal or continuous

Question: In the area of cluster analysis I want to calculate the dissimilarity for my data (actual use case is to feed in the dissimilarities into a plotting function to calculate so called silhouette plots).
Now, one of my variables follows a Poisson distribution and I'm actually unsure what would be the best/closest variable type for this kind of data, or if necessary what steps I'd need to take to potentially convert from Poisson to sth. else?
Background:
For my purpose I'm using function daisy from R package cluster which requires my columns to be of the following variable types:

Columns of mode numeric (i.e. all columns when x is a matrix) will be
recognized as interval scaled variables, columns of class factor will
be recognized as nominal variables, and columns of class ordered will
be recognized as ordinal variables. Other variable types should be
specified with the type argument. Missing values (NAs) are allowed.

Further:

The list may contain the following components: "ordratio" (ratio
scaled variables to be treated as ordinal variables), "logratio"
(ratio scaled variables that must be logarithmically transformed),
"asymm" (asymmetric binary) and "symm" (symmetric binary variables).
Each component's value is a vector, containing the names or the
numbers of the corresponding columns of x. Variables not mentioned in
the type list are interpreted as usual (see argument x).
Comment: I changed the title and the structure of my question a bit. However, I don't see how this question is solely about software works. I provided some background re cluster analysis and the limitations of the tool I'm using, however, the question is clearly phrased more generally. Hope this makes sense.
Comment: Questions solely about how software works are
[off-topic](https://stats.stackexchange.com/help/on-topic)
here, but you may have a real statistical question buried
here. You may want to edit your question to clarify the
underlying statistical issue. You may find that when you
understand the statistical concepts involved, the
software-specific elements are self-evident or at least
easy to get from the documentation.
Answer: Poisson-distributed data are numeric count data. So a strictly nominal coding, which would treat each count value as a separate unordered level of a multi-level categorical variable, would seem to be inappropriate.
Beyond that, it's essentially your choice of what (dis)similarity measure makes the most sense in the context of your study. Do you want the distance from 1 count to 10 counts to be considered the same as the distance from 101 counts to 110 counts? Then you want interval-scaled, numeric coding.
Do you care about the differences in rank-order among the count values but not necessarily the exact count values? Then an ordinal treatment (or ordratio, which I think would be the same here) would be more appropriate.
The "ratio-scaled" nomenclature comes from Stevens's typology and represents numeric data for which ratios can meaningfully be interpreted: "In contrast to interval scales, ratios can be compared using division. Very informally, many ratio scales can be described as specifying 'how much' of something (i.e. an amount or magnitude)," as the above Wikipedia link puts it.
You thus might choose to consider your data to be ratio-scaled, if that makes sense in the context of your study. For example, if you think that the ratio of counts best captures the distances between instances (e.g, the distance from 1 to 10 counts should be equivalent to the distance from 10 to 100 counts), then the logratio choice would make sense.


Imports parciais trazem vantagens para a aplicação?

Question: Algumas linguagens trazem como recurso a importação de partes da biblioteca utilizada.
Utilizando Dart como exemplo temos dois tipos de imports parcial showe hide .
import 'package:google_maps/google_maps.dart' show LatLng;
Importa somente a classe LatLng da biblioteca.
import 'package:google_maps/google_maps.dart' hide LatLng;
Importa todas as classe da biblioteca menos a LatLng.
Nesse contexto, importar somente as classe que serão utilizadas de uma biblioteca traz alguma vantagem para aplicação?
Answer: Para a aplicação em si não traz vantagens, especialmente de desempenho, mas para a legibilidade do seu código depende, você pode considerar que tem vantagem sim, ou não.
Quando importa só que vai usar o namespace fica mais limpo e não corre o risco de algo conflitar com outra cosia que estaria em outro lugar. Ao mesmo tempo um IDE não mostrará algumas coisas que poderia usar se tivesse importado tudo e te ajudar usar alguma coisa que não tinha pensado.
Obviamente esconder só um tipo ajuda menos, mas pode ser só o que deseja mesmo, pode ser que saiba que só aquilo entraria em conflito.
E se tiver que importar muitos tipos pode ficar mais confuso ainda, então a maior vantagem é quando tem que importar apenas um tipo daquela biblioteca.
É possível que em algumas situações tenha algum ganho mínimo no tempo de compilação, mas nada que importe, é muito mínimo mesmo, só para constar, não é que grandes porções de código deixarão de ser compiladas. O ganho de tempo de compilação que eu falo é porque é mais fácil administrar os símbolos quando há menos deles, por isso é mínimo.
O tree-shaking ajuda a aplicação Dart ter vantagens porque haverá bem menos carga e pelo menos em algum aspecto haverá ganho de performance, mas não por causa do import. A técnica de tree-shaking nada tem a ver com a técnica de importação falada aqui, inclusive o link inicial da outra resposta fala sobre isso, basta ler com atenção. O tree-shaking fará algo não ser compilado desde que aquilo não seja usado pelo código, mas o fato de não importar algo não significa que não há uso na aplicação.
Answer: Olhando do ponto de vista de performance, utilizar o show/hidenão implica necessariamente em uma melhoria.
Isto é, apesar de você dizer ao compilador que seu código usará apenas uma classe específica, pode ser que essa classe importada faça uso internamente de outras partes da biblioteca. No final, tudo será compilado.
Consequentemente, em linguagens que façam uso de tree-shaking, que é o caso de Dart usado como exemplo em sua pergunta, isso não acarreta diferença no tempo de compilação ou no tamanho do aplicativo gerado.
Uma das ajudas que tais palavras reservadas trazem é a redução de conflitos de nome: Se você importa apenas X, e não Y e Z, pode nomear suas classes de Y e Z sem nenhum problema. Pelo mesmo motivo, sua IDE não irá sugerir ou tentar auto-completar coisas que não dizem respeito ao seu interesse.
Outro exemplo de ajuda para o programador é para deixar claras suas intenções ao fazer um import. Quem ler aquele import depois vai saber que aquele código utiliza apenas tal classe, e já vai poder ter um entendimento melhor de seu uso.


Do all remote apps in angular micro front end need to be in the same angular workspace?

Question: I know you can have multiple angular apps within a single angular workspace as remotes loaded into a shell angular app, but can you have multiple angular apps that are not in the same workspace? We have apps in different repositories, so they are not in the same workspace.
--- HOST APP webpack.config.js ---
const { shareAll, withModuleFederationPlugin } = require('@angular-architects/module-federation/webpack');

module.exports = withModuleFederationPlugin({

  remotes: {
    "appOne": "http://localhost:4201/remoteEntry.js",
    "appTwo": "http://localhost:4202/remoteEntry.js",
  },

  shared: {
    ...shareAll({ singleton: true, strictVersion: true, requiredVersion: 'auto' }),
  },

});

--- HOST APP main.ts ---
import { loadRemoteEntry } from '@angular-architects/module-federation';

import('./bootstrap')
    .catch(err => console.error(err));

    Promise.all([
        loadRemoteEntry('http://localhost:4201', 'appOne'),
        loadRemoteEntry('http://localhost:4202', 'appTwo'),
    ])
        .catch((err) => console.error('Error loading remote entries', err))
        .then(() => import('./bootstrap'))
        .catch((err) => console.error(err));

--- HOST APP app-routing.module.ts (routes only) ---
export const APP_ROUTES: Routes = [
  {
    path: '',
    component: HomeComponent,
    pathMatch: 'full'
  },
  {
    path: 'app-one',
    loadChildren: () => loadRemoteModule({
                            remoteName: 'appOne',
                            exposedModule: './appOne',
                        }).then((m) => m.AppOneModule)
  },
  {
    path: 'app-two',
    loadChildren: () => loadRemoteModule({
                            remoteName: 'appTwo',
                            exposedModule: './appTwo',
                        }).then((m) => m.AppTwoModule)
  }
];

--- REMOTE APP ONE webpack.config.js ---
const { shareAll, withModuleFederationPlugin } = require('@angular-architects/module-federation/webpack');

module.exports = withModuleFederationPlugin({

  name: 'appOne',

  exposes: {
    './appOne': './projects/app-one/src/app/app-one/app-one.module.ts',
  },

  shared: {
    ...shareAll({ singleton: true, strictVersion: true, requiredVersion: 'auto' }),
  },

});

--- REMOTE APP ONE app-one.module.ts ---
import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';

import { AppOneComponent } from './app-one.component';
import { AppOneRoutingModule } from './app-one-routing-module';

@NgModule({
    declarations: [AppOneComponent],
    imports: [CommonModule, AppOneRoutingModule]
})
export class AppOneModule {}

--- REMOTE APP ONE app-one-routing-module.ts ---
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { AppOneComponent } from './app-one.component';

const routes: Routes = [{ path: '', component: AppOneComponent }];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule],
})
export class AppOneRoutingModule {}

Comment: Yes, I meant you don't need to have the remotes app in the same workspace. Please let me know if you need more info on the configuration
Comment: **Of course no**. The idea behind micro front end is to have a separate url for your remotes applications. Once you have deployed your remote app you just use the url in the shell app. All this is done in webpack configuration with module federation plugin
Comment: It seems like you are saying as long as you have a url to a deployed app, it can be added to a micro-front end via webpack configuration, meaning the multiple remote apps do not need to be in the same workspace. If this is the case then I was by your "no" :-)
Comment: I'm new to using webpack for module federation, so any configuration hints you could provide would be greatly appreciated!
Answer: Activate module federation in all the angular projects (shell and remotes)
To do that you can use the schematic @angular-architects/module-federation with the command :
ng add @angular-architects/module-federation

This would generate the necessary configuration in the differents files :
- src/bootstrap.ts (bootstrap of AppModule)
- src/main.ts (import bootstrap)
- webpack.config.js (skeleton to use module federation)
- webpack.prod.config.js (skeleton to use module federation)

Shell
The shell app will use the router to lazy load the remotes modules(remote1, remote2)
export const APP_ROUTES: Routes = [
 {
   path: '',
   component: HomeComponent,
   pathMatch: 'full'
 },
 {
   path: 'remote1',
   loadChildren: () => loadRemoteModule({
                           remoteName: 'remote1App',
                           exposeModule: './Remote1',
                       }).then((m) => Remote1Module)
 },
];

So this Remote1Module module is not part of the shell project.
Your main.ts file will look like :
Promise.all([
    loadRemoteEntry('https://url_remote1', 'remote1App'),
    loadRemoteEntry('https://url_remote2', 'remote2App'),
])
    .catch((err) => console.error('Error loading remote entries', err))
    .then(() => import('./bootstrap'))
    .catch((err) => console.error(err));

So here you are trying to load the remote app with his url and name. The name must be the reference of the name you are going to use in routes(remoteName: 'remote1App').
Microfrontend project(Aka remote)
So let say we are in the remote1 project which have a module named Remote1Module This module contains the functionality we would like to expose in the Shell app.
In order to make this work we need to expose Remote1Module in the remote1 project webpack.
module.export = {
    ...
    plugins: [
        new ModuleFederationPlugin({
            name: 'remote1',
            filename: 'remoteEntry.js',
            exposes: {
                './remote1App': './src/app/remote1.module.ts'
            }
        }),
        shared: share({
            ...
        })
    ]
}

This configuration exposes the Remote1Module under the public name remote1App. You can also share some packages with the Shell app by using the shared section.
Trying out
You can run first your remote app and then after your shell but this order is not necessary. I'm suggesting just to avoid the error

Error loading remote entries ...

ng serve remote1App
ng serve shell

All credits to Manfred Steyer (https://www.angulararchitects.io/en/aktuelles/the-microfrontend-revolution-part-2-module-federation-with-angular/)
Comment: I've added code for what I have so far but I'm getting errors when I view the host app in Chrome:

Uncaught SyntaxError: Cannot use 'import.meta' outside a module

and

Unhandled Promise rejection: Cannot read properties of undefined (reading 'init') ; Zone:  ; Task: Promise.then ; Value: TypeError: Cannot read properties of undefined (reading 'init')
Answer: You need to setup module federation in all your angular project if you are not using mono repo approach
Comment: Yes, I've done that but no luck. Module federation in Angular seems fragile at best, and if the apps are not in the same workspace, even more so.
Comment: Can you please push your changes to github and give the url here. I have used Module Federation in a non mono repo approach. Everything works fine for me.
Comment: Is it dynamic or static? We have it working statically, but not dynamically, in which you specify remotes either in a manifest or config file.
Comment: @GregLafrance I have an approach to make remotes work dynamically. We can specific the remote url from shell application


How to run jar files

Question: I have a Win XP machine which has java installed on it. The problem that I cannot open jar files. It seems that association is broken. How can I launch jar files by using console. Or maybe there is a way to set a proper association.
Answer: You may have to add java to your path.  I'm not actually sure how to do that - I'm more of a linux user.  If what freedom_is_chaos suggested doesn't work then java isn't in your path and you need to add it.  If you just want to run it and don't want to worry about whether or not it's in your path then you'll need to do: C:\full\path\to\jre\bin\java -jar yourJar.jar
Comment: To add stuff to path, right click on My Computer, Properties, Advanced, Environment Variables, find Path and click edit. Add the full path to your java.exe to the end of what's there (look first and see if it ends with a semicolon, I forget). You also might have to enclose the path in " " if something in the path contains spaces.
Comment: :P stealer. But you're correct, I probably should have included the full path and all that stuff too. Recent Java installs should add it to your path though.
Answer: from the cmd line. run:
java -jar java.app

How to run jar files


How to get a count of how many users each user has referred

Question: I have a table called User_Accounts, In that table I have a column named Referred_By.
When a new record is added to this table the column id auto increments, In my case this is the userid. So if a user has referred another user. say Gary1992 referred James. James would have gary1992's id in the referred column.
So my question.
I am wondering how I can get a count of how many users each user has referred and put this into a view?
Please let me know if you need more information, I have tried my best to explain and really can't get my head around this.
Answer: <code>SELECT Referred_By, COUNT(*) counter
FROM User_Accounts
GROUP BY Referred_By
</code>
Comment: Perfect, I didnt even know about the GROUP BY :)


React useEffect() infinite re-render for getting all despite dependencies

Question: I'm relatively new to React, but I have been using useEffect to get all of my news and events from the database on load of a page. I recently tried to implement a loading spinner, and now I seem to be hitting an infinite loop, but I cannot understand why. I have the news and events in the dependency array, because if they change, then we need to update what is displayed to the user. The only potential issue I can see is that I am building up the news and events arrays in my action in my state store, but I haven't seemed to encounter this issue until trying to implement this functionality. Its probably something stupid, but can anyone help me?
Front end code:

export default observer(function NewsAndEvents() {
    const { generalStore } = useStore();
    const { getNewsAndEvents, events, news, loading } = generalStore

    useEffect(() => {
        getNewsAndEvents();
    }, [news, events]);

    return (

News

                { loading ? <LoadingSpinner /> : news.map((news, index) => {
                   return <News key={`news_${index}`} title={news.title} content={news.content} />
                })}

Get action:

export default class GeneralStore {
  isAuthenticated: boolean = false;

  selectedEvent: Event | undefined = undefined;
  events: Event[] = [];

  selectedNews: News | undefined = undefined;
  news: News[] = [];

  loading: boolean = false;

  constructor() {
    makeAutoObservable(this);
  }

  getNewsAndEvents = async () => {
    this.loading = true;
    try {
      let response: any = await agent.newsAndEvents.list();
      if (response !== null) {
        runInAction(() => {
            this.events = [];
            this.news = [];
          response.events.forEach((item: any) => {
            let newEvent: Event = {
              id: item._id,
              date_time: item.date_time,
              name: item.name,
              description: item.description,
              price: item.price,
              type: ContentType.event,
            };
            this.events.push(newEvent);
          });
          response.news.forEach((item: any) => {
            let newNews: News = {
              id: item._id,
              title: item.title,
              content: item.content,
              type: ContentType.news,
            };
            this.news.push(newNews);
          });
          this.setLoading(false);
        });
      }
    } catch (ex) {
      console.log(ex);
      this.setLoading(false);
    }
  };
}

I am using TS and MobX.
Comment: Why exactly you want to update `news` when `news` changes? What is the use case for that?
Answer: if your getNewsAndEvents() function is updating news or events, your useEffect will run infinitely. You need to create a flag to prevent this.
const [flag, setFlag] = useState(true);

useEffect(() => {
  if (flag) {
    getNewsAndEvents();
    setFlag(false);
  }
}, [flag]);

Ideally flag should be a global state too but I used useState here cuz I'm not familiar with mobx.
Then every time you want getNewsAndEvents() to run, you can set the flag to true.
Answer: I think the problem is when the loading ends, its value (true) stays the same because loading is not a component state, so the component will not be rerendered if the loading ends, so to solve that, I suggest you put the loading value in a state using useState hook like that:
const [loading, setLoading] = useState(generalStore.loading);

then you will add a useEffect with a [generalStore.loading] dependency so it will update the state after the loading value changes, and that will make the component rerender:
useEffect(() => {
    setLoading(generalStore.loading);
}, [generalStore.loading]);

I'm not sure this solution will work for you, but I think it deserves a try.


Calculating the withdrawal amount from a fund as an annuity-immediate incorrectly

Question: I have the following problem.

Consider an investment of $5,000 at 6% convertible semiannually. How much can be withdrawn each
half-year to use up the fund exactly at the end of 20 years?

I can tell that this problem is an annuity-immediate. Since the interest compounding period and the withdrawal period are equal the interest rate used would stay at 6% and there would be 40 compounding periods over the 20 years. I tried to use the following formula.

P = 5000/(a 40|.06), => (a 40|.06) = (1-(1.06^-40))/.06

The answer that I get when I do all of my calculations is $332 however this is way off from the listed answer in the back of the book. But from my best understanding, I'm doing everything correctly. Would somebody be able to enlighten me as to what I'm doing wrong?
Comment: I get $\$216.31$. I think this is more realistic.
Comment: That is the correct answer. What did you do differently?
Answer: $\require{enclose}$
The rate is a nominal $i^{(2)} = 0.06$ convertible semiannually, which means that the effective semiannual rate is $j = \frac{i^{(2)}}{2} = 0.03$.  Hence the equation of value is
$$5000 = X a_{\enclose{actuarial}{40}j} = X \frac{1 - v^{40}}{j} = \frac{1 - (1.03)^{-40}}{0.03} X \approx 23.1148 X,$$
from which it follows that $X \approx 216.312$.  This assumes that withdrawals from the investment occur at the end of each $6$-month period.
Comment: I have a question. Since the nominal rate of interest was the same as the withdrawal period I thought I didn't have to convert the interest.  But when I plug that value in I get the right answer.
Comment: @j.jerrod.taylor There cannot be any other interpretation.  A (nominal) interest rate $i^{(m)}$ convertible $m$ times per year means that, by definition, $$\left( 1 + \frac{i^{(m)}}{m} \right)^m = 1 + i,$$ where $i$ is the effective annual rate of interest.  Hence the quantity $i^{(m)}/m$ is the effective rate per compounding period; e.g., if I say a fund has a nominal rate of $i^{(12)} = 0.03$ convertible monthly, the effective monthly rate of interest is $i^{(12)}/12 = 0.0025$, and the effective annual rate is $i = (1.0025)^{12} - 1 \approx 0.030416.$


Why the two alerts are showing different values here? What's happening?

Question: Consider the below JavaScript code:

var x = 3;
var foo = {
  x: 2,
  baz: {
    x: 1,
    bar: function() {
      return this.x;
    }
  }
}
var go = foo.baz.bar;
alert(go());
alert(foo.baz.bar());

The two alerts here show different values. First one gives "3" and second one "1". But aren't both actually referring the same thing? I think its somehow related to the scope, but I am not getting it how the code is executing here.
Comment: what this means in js depends on context of the caller.
Comment: var go = foo.baz.bar it stores then function in the variable and as a you have declare X globally as 3 and locally as 3 value in your snippet. So, when you run alert((go()) it access global value of x and that is why it shows x = 3 in first alert. You may access foo.baz object's bar method and baz have property x also defined with value 1 so in that function this.x refers local object baz's property x.
Comment: @JonasW Nice duplicate find!
Comment: @bergi wasnt me, someone with low rep commented here, i just hit the close button ;)
Answer: Context (basically this) is not defined by where a function is (in contrast to scope) but rather how it is called. Namingly when you do:
object.method()

method is called in objects context. When you do
method()

method is called in no context at all ( or in non strict mode it is window for some reason). However you can change that by binding the context:
var method = object.method.bind(object);
method();

Comment: Seems inconsistent to answer *and* close a question. By closing it, and thereby preventing people from answering, you're implying that it shouldn't be answered. By answering, you're giving it legitimacy, so why prevent others from doing the same?
Comment: You really should post your answer on the exact duplicate question, if you feel a new answer is necessitated at all.
Comment: @skinny pete well actually i answered and found the dupe later on. However i get your point. If you think i should delete this answer, let me know and i do so. However i think no one really profits from it when i delete it, its just waste of my time :)


For what values of $m$ and $n$ is $\int_{0}^{1} x^{m-1}(1-x)^{n-1}\log x\ dx$ convergent?

Question: I cannot really understand how to prove this I know that $\int_{0}^{1} x^{m-1} (1-x)^{n-1}\ dx$ is $\beta$ function.
Comment: @Dr.SonnhardGraubner Don't forget that $\log x\to0$ as $x\to 1$.
Comment: i think it must be $$\Re(n)>0$$ and $$\Re(m)>0$$
Comment: In the additional information I said I know $\int_{0}^{1} x^{m-1} (1-x)^{n-1}$  is beta function however, I don't know how to prove its convergence, the title consists the full question. @MrYouMath
Comment: @Dr.SonnhardGraubner I'd like to know the proof as I am unable to do so. If you can help?
Answer: Near zero, the integrand is $\sim x^{m-1}\log x$. As $|\log x|=O(x^{-\epsilon})$ for small positive $x$, the integral converges near zero iff $\text{Re}(m)>0$, as for the beta integral.
Near one, the integrand is $\sim -(1-x)^n$. This converges
near one iff $\text{Re}(n)>-1$.
Comment: what about the $\log x $ present in the second case? Won't $\log x$ will be 0 then?
Comment: @ItiShree I took that into account: $\log x\sim -(1-x)$ near $x=1$.
Comment: Okay, thanks I got it now.
Comment: The result of the integration is quite beautiful (at least to me !).
Answer: The integral
$$ B(m,n)=\int_{0}^{1}x^{m-1}(1-x)^{n-1}\,dx = \frac{\Gamma(m)\,\Gamma(n)}{\Gamma(m+n)} $$
is convergent as soon as $\color{red}{\text{Re}(m),\text{Re}(n)>0}$, granting the integrability of $x^{m-1}(1-x)^{n-1}$ over $(0,1)$. Under these assumptions it is a differentiable function, also because $B(\cdot,n)$ and $B(m,\cdot)$ are moments, hence log-convex functions by the Cauchy-Schwarz inequality. It follows that
$$ \int_{0}^{1} x^{m-1}(1-x)^{n-1}\log(x)\,dx =\frac{\partial}{\partial m}B(m,n)$$
and by logarithmic differentiation we get:
$$\begin{eqnarray*} \int_{0}^{1} x^{m-1}(1-x)^{n-1}\log(x)\,dx &=& \frac{\Gamma(m)\,\Gamma(n)}{\Gamma(m+n)}\left[\psi(m)-\psi(m+n)\right]\\&=&-\frac{\Gamma(m)\,\Gamma(n+1)}{\Gamma(m+n)}\sum_{s\geq 0}\frac{1}{(s+m)(s+m+n)}\end{eqnarray*}$$
where $\psi(x)=\frac{d}{dx}\log\Gamma(x)$ is the digamma function.


Picturefill.js: Need help converting  to the  srcset/sizes method

Question: This is what I have...
<picture>
    <source srcset="assets/images/home/desktop-hero.jpg" media="(min-width: 768px)" />
    <source srcset="assets/images/home/mobile-hero.jpg" media="(max-width: 767px)" />

</picture>

Comment: Why was this downed? The title clearly states what I need help with.
Answer: Assuming that the "mobile" image is a scaled-down version of the "desktop" image, and the widths of the images are 384 and 768 respectively, and you want the image to be 100vw wide up to 768px...

If your "mobile" image is a cropped version of the "desktop" image (art direction), then you should be using <picture>. (You can drop the second <source> though, the  is picked up as a candidate.)


Do not show searchResultsTableView before search button clicked

Question: I'm trying to solve this problem with no luck. I have a search bar and search a display controller inside table view controller.
Everything works fine - I make the server call to search the endpoint when user clicks the "Search" button and display the results. But the problem is I do not want to show No results in the table view before user clicks Search.

Instead of that I prefer to show default dark overlay.
Answer: You could return 1 in numberOfRowsInSection while the query is in progress and leave the dummy cell empty or set its hidden property to YES so it is not visible. So you have do not have "No Results" showing up.
Also for making it a dark overlay try something like this:
- (void)searchDisplayController:(UISearchDisplayController *)controller didLoadSearchResultsTableView:(UITableView *)tableView{
    tableView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"default.png"]];
}

More information: Link!
Comment: "query is in progress" how to check it?
Comment: @Kosmetika Link added to my Answer
Comment: yeah, but your link will remove No results even after search done


Manually fitting a mixture distribution in matlab

Question: I am trying to fit a mixture model containing a gamma and an exponential distribution:
The general form, using the pdfs, is: p * gammapdf + (1-p) * exponentialpdf.
The pdfs for the Gamma and Exponential, respectively are as follows:

In matlab I have coded the mixture of these two as follows:
(p * ((1/(gamma(k) * theta^k)) * (x(i)^(k-1)) * (exp(-x(i)/theta)))) + ((1-p) * (1/lambda) * exp(-x(i)/lambda))

where p is the probability of the gamma and 1-p is the probability of the exponential, gamma is the internal matlab call to the gamma function, k is the shape parameter, theta the scale parameter of the gamma and lambda the rate of the exponential. x is the vector containing all of the data and i indexes x (I'm using a for loop to evaluate each data point with the model, I could vectorize it, but the speed is actually pretty good, all things considered).
However, the predicted data are no where close to what one would expect. My intuition is that there is something wrong with how I coded the gamma portion of the mixture distribution. Upon looking at this, does anyone have any suggestions for how I might improve this?
Additionally, if you have time, a second mixture distribution I am trying to manually fit is a mixture of the exponential and inverse gaussian distributions. Below is the pdf for the inverse gaussian

And the code for this mixture model:
(p * ((lambda/(2*pi*(x(i)^3)))^0.5 * (exp((-lambda*((x(i) - mu)^2))/(2*(mu^2)*x(i)))))) + ((1-p) * (1/lambda_exp) * exp(-x(i)/lambda_exp))

Where p is the same as above, except p corresponds to the inverse gaussian, lambda is the mean of the inverse gaussian, mu the standard deviation, and lambda_exp is the rate of the exponential. And again, x is as above.
I am using maximum likelihood estimate, where I take the natural log of each value and then sum those values to get a log-likelihood (LL) value that is then fed in simulated annealing (SA) minimization function in matlab to find the best parameter values. Note, that since SA minimizes, I put a negative sign in front of the LL value, which effectively causes SA to maximize.
I broke out the individual components of my mixtures and have confirmed that using these process I get the same parameter values when fitting the single distribution as the built in functions in matlab.
I'm now thinking the issue is in how I get the predicted values and then plot them.
My tactic here was to take the same equations from above and feed in the parameter values and the data to get predicted values. This however and obviously, gives me the pdf of the data and not actual predicted values. My question then is, given that I have a mixture of two distribution pdfs, how do I get actual predicted values from them so I can plot them against each other?Thanks.
Comment: It would help a lot if you could post code (either here or in a gist or something) for a reproducible example so we can see what you're doing.
Answer: You are right that it's not meaningful to evaluate the pdf and think of it as predicted values comparable to the data. You could try something like this:
xx = linspace(1,100);                               % grid of values
ksdensity(x,'support','positive')                   % empirical density plot
line(xx,mypdf(xx,p(1),p(2),p(3),p(4)),'color','r')  % fitted density overlay

Here I used ksdensity function from the Statistics Toolbox, but you could use hist if you normalize to unit area. The mypdf function is the pdf that you define. The first input xx is a grid of values spanning the data. The p(1),...,p(4) values are the estimated parameters that you found.
Answer: I don't see any issues with how you coded your mixture model. That said, you could make your life a lot easier (and possibly speed up your code) by using the built-in functions for those pdfs from the statistics toolbox:
f = @(x,lambda,a,b,t) lambda*gampdf(x,a,b) + (1-lambda)*exppdf(x,t);

Now, let's talk about your predictions.

the predicted data are no where close to what one would expect.

How are you generating these predictions? You've shown us how you coded the model, but I have no idea how you fit this model. Having seen your objective function, I'm wondering if your optimization routine isn't the problem. Some considerations:

Are you using a built-in function to fit this, or have you home-brewed your own optimization? If you rolled your own optimization, maybe you should try using a supported tool like mle or fmincon.
If you built your own optimization: what algorithm are you using to fit this? EM? Gradient Descent? Newton-Raphson? If you're not using EM, I'd give that a shot.
Have you tried using different starting parameters? Maybe you're getting stuck at local minima. Try randomly sampling a bunch of starting parameters within what you consider to be reasonable ranges for the problem. Exploring the model space like this might land you on a better (possibly global) minimum.
Are you using a bayesian strategy? Maybe you need to reevaluate your priors.
Comment: I edited my post, with some clarification and answers to your questions.


Jquery ajax in iphone

Question: Can anyone tell me how to use Jquery Ajax in Iphone app. development ?
Sample codes are appreciated .
Thank you.
Comment: You need to learn Javascript.
Comment: Are you talking about making jquery ajax calls in a web page access via an iPhone or a full on iPhone app?
Answer: I would imagine it would be the same as normal AJAX development.
<code>$.ajax({
    url: 'your_url',
    success: function( data )
    {
        console.log( data );
    }
});
</code>

Jquery ajax in iphone


How do I find the reason for the last shutdown in Windows Server 2003?

Question: I have a windows server 2003 system which restarted for no apparent reason. Everything seems to be running fine now, but I want to know why it shutdown. I don't see any obvious signs of problems in the event logs. It is running on a UPS so I don't think it lost power.

How can I find the reason for the last shutdown in Windows Server 2003. I usually type a reason when I restart, and I have seen error codes when I go to the console after an unexpected restart. How can I retrieve that reason now?
Any other ideas about how to find out why the restart happened?
Answer: Open eventvwr → System.
View → Filter... → Event Id: 1074 and 1076. Comment field will contain what you typed in.
If there are no other events around that time to give you any clues, you may want to adjust your auditing settings to catch more items, but Sean Earp's link will probably give better details on that.
Comment: I've just came here for a quick reference for the same issue. However, I could find the shutdown event as ID 1074. I'm running windows server 2003 R2 SP2
Comment: Event ID 1076 was the clue I was looking for, thanks. Of course since this was an unexpected shutdown, it does not give me much useful information. I will check out Sean's link to see if I can capture more  info if this happens again.
Comment: @amyassin, Both works for me. `1074` gives you "Information" type events while `1076` gives you "Warning" type events. @Kara, besides the checkbox "planned / unplanned", what other factors may affect whether an event is `1074` or `1076`?
Answer: Take a look at the Technet information on the Shutdown Event Tracker, which is the OS component that keeps track of expected and unexpected shutdowns in Windows.
Answer: look at your event viewer and if there was a bsod you can check your dump file.
you should enable no restart option on systems or servers if you want to see the error message posted on the bsod. this is under control pane> system> advanced tab> startup recovery options.
you can use utilities from technet to read your dump file and it will usually show you if any drivers or which ones caused the issue. then you can reference the event id as mentioned to find out any solution.s
Answer: To open Event Viewer,

click Start, click Control Panel, double-click Administrative Tools,
  and then double-click Event Viewer

https://technet.microsoft.com/en-us/library/cc737766(v=ws.10).aspx#one


How do we know radioactive decay can be modeled by the half-life equation, dq/dt = -aq?

Question: I understand how to solve it. but why does
$$\frac{d \lambda}{dt} = -k \lambda$$
The equation, in and of itself, means the rate of decay is proportional to the amount at a given time. How do we know its not squared proportion, like universal gravitation? Or a squared/cubed relationship like Kepler's law that states the period squared is equal to the distance cubed.
Comment: Ultimately it's a good model because it accords with experimental evidence. (FYI, $d\lambda/dt$ isn't proportional to time, but the amount of remaining material $\lambda$.) Now you might ask why at a quantum level, it works. I.e., starting with some general physical principle, can you derive this result. That would be good question for Physics SE.
Comment: Okay thank you.  This always appears in applied diff eq models so I thought it would apply here. Also, I did say the rate of decay was proportional to the amount, the amount at a given time lol.  Anyways thanks for the quick response.  I guess it does require a deeper understanding of physics, which I lack (taking physic E&M next semester).
Answer: The underlying assumption is that each atom's decay is treated as an independent event, and that the probability of it decaying in any given second is a constant.  (In other words, a Poisson process.)
So, the more atoms you have around to decay, the more decays per second you'll get.


Delayed Job Delayed::PerformableMethod undefined method "delayed_task" for #

Question: I am using delayed jobs and I think I have a problem with serialization. We are using ruby 2.2.2.
In my model I have a callback that fires on save and creates a delayed job for my model. like this:
after_create :update_queue

def update_queue
  self.class.delay(run_at: 1.minutes.from_now, delayed_reference_id: self.id, delayed_reference_type: "Payment", queue: "qbo_payments").delayed_task(self.id)
end

def self.delayed_task
  # Do some stuff
end

However I am getting the error:
undefined method `delayed_task' for #<Class:0x0000000f93f9b8>
~/shared/bundle/ruby/2.2.0/gems/activerecord-4.2.0/lib/active_record/dynamic_matchers.rb:26:in `method_missing'
~/shared/bundle/ruby/2.2.0/gems/attr_encrypted-3.0.3/lib/attr_encrypted.rb:295:in `method_missing'
~/shared/bundle/ruby/2.2.0/gems/attr_encrypted-3.0.3/lib/attr_encrypted/adapters/active_record.rb:129:in `method_missing_with_attr_encrypted'
~/shared/bundle/ruby/2.2.0/gems/delayed_job-4.1.2/lib/delayed/performable_method.rb:26:in `perform'
~/shared/bundle/ruby/2.2.0/gems/delayed_job-4.1.2/lib/delayed/backend/base.rb:84:in `block in invoke_job'
~/shared/bundle/ruby/2.2.0/gems/delayed_job-4.1.2/lib/delayed/lifecycle.rb:61:in `call'
~/shared/bundle/ruby/2.2.0/gems/delayed_job-4.1.2/lib/delayed/lifecycle.rb:61:in `block in initialize'
~/shared/bundle/ruby/2.2.0/gems/delayed_job-4.1.2/lib/delayed/lifecycle.rb:66:in `call'
~/shared/bundle/ruby/2.2.0/gems/delayed_job-4.1.2/lib/delayed/lifecycle.rb:66:in `execute'
~/shared/bundle/ruby/2.2.0/gems/delayed_job-4.1.2/lib/delayed/lifecycle.rb:40:in `run_callbacks'
~/shared/bundle/ruby/2.2.0/gems/delayed_job-4.1.2/lib/delayed/backend/base.rb:81:in `invoke_job'
~/shared/bundle/ruby/2.2.0/gems/newrelic_rpm-126.96.36.1998/lib/new_relic/agent/instrumentation/delayed_job_instrumentation.rb:127:in `block in invoke_job'
~/shared/bundle/ruby/2.2.0/gems/newrelic_rpm-18.104.22.1688/lib/new_relic/agent/instrumentation/controller_instrumentation.rb:363:in `perform_action_with_newrelic_trace'
~/shared/bundle/ruby/2.2.0/gems/newrelic_rpm-220.127.116.118/lib/new_relic/agent/instrumentation/delayed_job_instrumentation.rb:126:in `invoke_job'
~/shared/bundle/ruby/2.2.0/gems/delayed_job-4.1.2/lib/delayed/worker.rb:230:in `block (2 levels) in run'
/usr/local/rvm/rubies/ruby-2.2.2/lib/ruby/2.2.0/timeout.rb:89:in `block in timeout'
/usr/local/rvm/rubies/ruby-2.2.2/lib/ruby/2.2.0/timeout.rb:99:in `call'
/usr/local/rvm/rubies/ruby-2.2.2/lib/ruby/2.2.0/timeout.rb:99:in `timeout'
~/shared/bundle/ruby/2.2.0/gems/delayed_job-4.1.2/lib/delayed/worker.rb:230:in `block in run'
/usr/local/rvm/rubies/ruby-2.2.2/lib/ruby/2.2.0/benchmark.rb:303:in `realtime'
~/shared/bundle/ruby/2.2.0/gems/delayed_job-4.1.2/lib/delayed/worker.rb:229:in `run'
~/shared/bundle/ruby/2.2.0/gems/delayed_job-4.1.2/lib/delayed/worker.rb:306:in `block in reserve_and_run_one_job'
~/shared/bundle/ruby/2.2.0/gems/delayed_job-4.1.2/lib/delayed/lifecycle.rb:61:in `call'
~/shared/bundle/ruby/2.2.0/gems/delayed_job-4.1.2/lib/delayed/lifecycle.rb:61:in `block in initialize'
~/shared/bundle/ruby/2.2.0/gems/delayed_job-4.1.2/lib/delayed/lifecycle.rb:66:in `call'
~/shared/bundle/ruby/2.2.0/gems/delayed_job-4.1.2/lib/delayed/lifecycle.rb:66:in `execute'
~/shared/bundle/ruby/2.2.0/gems/delayed_job-4.1.2/lib/delayed/lifecycle.rb:40:in `run_callbacks'
~/shared/bundle/ruby/2.2.0/gems/delayed_job-4.1.2/lib/delayed/worker.rb:306:in `reserve_and_run_one_job'
~/shared/bundle/ruby/2.2.0/gems/delayed_job-4.1.2/lib/delayed/worker.rb:213:in `block in work_off'
~/shared/bundle/ruby/2.2.0/gems/delayed_job-4.1.2/lib/delayed/worker.rb:212:in `times'
~/shared/bundle/ruby/2.2.0/gems/delayed_job-4.1.2/lib/delayed/worker.rb:212:in `work_off'
~/shared/bundle/ruby/2.2.0/gems/delayed_job-4.1.2/lib/delayed/worker.rb:175:in `block (4 levels) in start'
/usr/local/rvm/rubies/ruby-2.2.2/lib/ruby/2.2.0/benchmark.rb:303:in `realtime'
~/shared/bundle/ruby/2.2.0/gems/delayed_job-4.1.2/lib/delayed/worker.rb:174:in `block (3 levels) in start'
~/shared/bundle/ruby/2.2.0/gems/delayed_job-4.1.2/lib/delayed/lifecycle.rb:61:in `call'
~/shared/bundle/ruby/2.2.0/gems/delayed_job-4.1.2/lib/delayed/lifecycle.rb:61:in `block in initialize'
~/shared/bundle/ruby/2.2.0/gems/delayed_job-4.1.2/lib/delayed/lifecycle.rb:66:in `call'
~/shared/bundle/ruby/2.2.0/gems/delayed_job-4.1.2/lib/delayed/lifecycle.rb:66:in `execute'
~/shared/bundle/ruby/2.2.0/gems/delayed_job-4.1.2/lib/delayed/lifecycle.rb:40:in `run_callbacks'
~/shared/bundle/ruby/2.2.0/gems/delayed_job-4.1.2/lib/delayed/worker.rb:173:in `block (2 levels) in start'
~/shared/bundle/ruby/2.2.0/gems/delayed_job-4.1.2/lib/delayed/worker.rb:172:in `loop'
~/shared/bundle/ruby/2.2.0/gems/delayed_job-4.1.2/lib/delayed/worker.rb:172:in `block in start'
~/shared/bundle/ruby/2.2.0/gems/delayed_job-4.1.2/lib/delayed/plugins/clear_locks.rb:7:in `call'
~/shared/bundle/ruby/2.2.0/gems/delayed_job-4.1.2/lib/delayed/plugins/clear_locks.rb:7:in `block (2 levels) in <class:ClearLocks>'
~/shared/bundle/ruby/2.2.0/gems/delayed_job-4.1.2/lib/delayed/lifecycle.rb:79:in `call'
~/shared/bundle/ruby/2.2.0/gems/delayed_job-4.1.2/lib/delayed/lifecycle.rb:79:in `block (2 levels) in add'
~/shared/bundle/ruby/2.2.0/gems/delayed_job-4.1.2/lib/delayed/lifecycle.rb:61:in `call'
~/shared/bundle/ruby/2.2.0/gems/delayed_job-4.1.2/lib/delayed/lifecycle.rb:61:in `block in initialize'
~/shared/bundle/ruby/2.2.0/gems/delayed_job-4.1.2/lib/delayed/lifecycle.rb:79:in `call'
~/shared/bundle/ruby/2.2.0/gems/delayed_job-4.1.2/lib/delayed/lifecycle.rb:79:in `block in add'
~/shared/bundle/ruby/2.2.0/gems/delayed_job-4.1.2/lib/delayed/lifecycle.rb:66:in `call'
~/shared/bundle/ruby/2.2.0/gems/delayed_job-4.1.2/lib/delayed/lifecycle.rb:66:in `execute'
~/shared/bundle/ruby/2.2.0/gems/delayed_job-4.1.2/lib/delayed/lifecycle.rb:40:in `run_callbacks'
~/shared/bundle/ruby/2.2.0/gems/delayed_job-4.1.2/lib/delayed/worker.rb:171:in `start'
~/shared/bundle/ruby/2.2.0/gems/delayed_job-4.1.2/lib/delayed/command.rb:132:in `run'
~/shared/bundle/ruby/2.2.0/gems/delayed_job-4.1.2/lib/delayed/command.rb:120:in `block in run_process'
~/shared/bundle/ruby/2.2.0/gems/daemons-1.2.3/lib/daemons/application.rb:265:in `call'
~/shared/bundle/ruby/2.2.0/gems/daemons-1.2.3/lib/daemons/application.rb:265:in `block in start_proc'
~/shared/bundle/ruby/2.2.0/gems/daemons-1.2.3/lib/daemons/daemonize.rb:84:in `call'
~/shared/bundle/ruby/2.2.0/gems/daemons-1.2.3/lib/daemons/daemonize.rb:84:in `call_as_daemon'
~/shared/bundle/ruby/2.2.0/gems/daemons-1.2.3/lib/daemons/application.rb:269:in `start_proc'
~/shared/bundle/ruby/2.2.0/gems/daemons-1.2.3/lib/daemons/application.rb:295:in `start'
~/shared/bundle/ruby/2.2.0/gems/daemons-1.2.3/lib/daemons/controller.rb:69:in `run'
~/shared/bundle/ruby/2.2.0/gems/daemons-1.2.3/lib/daemons.rb:193:in `block in run_proc'
~/shared/bundle/ruby/2.2.0/gems/daemons-1.2.3/lib/daemons/cmdline.rb:88:in `call'
~/shared/bundle/ruby/2.2.0/gems/daemons-1.2.3/lib/daemons/cmdline.rb:88:in `catch_exceptions'
~/shared/bundle/ruby/2.2.0/gems/daemons-1.2.3/lib/daemons.rb:192:in `run_proc'
~/shared/bundle/ruby/2.2.0/gems/delayed_job-4.1.2/lib/delayed/command.rb:118:in `run_process'
~/shared/bundle/ruby/2.2.0/gems/delayed_job-4.1.2/lib/delayed/command.rb:99:in `block in daemonize'
~/shared/bundle/ruby/2.2.0/gems/delayed_job-4.1.2/lib/delayed/command.rb:97:in `times'
~/shared/bundle/ruby/2.2.0/gems/delayed_job-4.1.2/lib/delayed/command.rb:97:in `daemonize'
script/delayed_job:5:in `'"

What I have tried
After a bit of google research I found 2 fixes. The first and more widely accepted fix is to add:
require 'yaml'
YAML::ENGINE.yamler = 'syck'
#https://github.com/collectiveidea/delayed_job/issues/199

However, syck is no longer supported for ruby 2.2.2
The second solution, which only seemed to exacerbate the problem, was to add "bundle exec" to my delayed_job startup script like this:
run "cd #{current_path}; bundle exec script/delayed_job start #{rails_env}"

Answer: This will work !
after_create :update_queue

def update_queue
 self.delay(run_at: 1.minutes.from_now, delayed_reference_id: self.id, delayed_reference_type: "Payment", queue: "qbo_payments").delayed_task()
end

def delayed_task
   self.class.delayed_task(self.id)
end

def self.delayed_task
 # Do some stuff
end


How do I deal with $\cos(n\pi /4)$ in this series?

Question: I need to evaluate the limit
$$\lim_{n\to\infty}\,\sum _{k=0}^n\frac{\cos(k\pi/4)}{2^k}$$
I see that this series is convergent because is limited by $1/2^n$ that is a convergent geometric series but I can't define what is this $\cos(n\pi /4)$ so I can't find what its ratio $r$ is. If it were $\cos(n\pi)$, then I should put $(-1)^n$ but what about this?
Comment: Is that supposed to be $2^k$ in the denominator?
Answer: We can evaluate the series in closed form by using Euler's Formula to write $\cos(\pi k/4)=\text{Re}(e^{i\pi k/4})$.
Proceeding, we find that
$$\begin{align}
\lim_{n\to \infty}\sum_{k=0}^n\frac{\cos(\pi k/4)}{2^k}&=\lim_{n\to \infty}\text{Re}\left(\sum_{k=0}^n\left(\frac{e^{i\pi/4}}{2}\right)^k \right)\\\\
&=\lim_{n\to \infty}\text{Re}\left(\frac{1-\frac1{2^{n+1}}e^{i\pi(n+1)/4}}{1-\frac12e^{i\pi/4}}\right)\\\\
&=\frac{4-\sqrt2}{5-2\sqrt2}\\\\
&=\frac1{17}(16+3\sqrt 2)
\end{align}$$
Comment: Very nice. ..+1
Comment: @donantonio Thank you my friend.  I really appreciate it.


Is `std::wstring` a sort of class with reference counting?

Question: A few simple questions:

Is std::wstring a sort of class with reference counting like std::vector? As in, could I have it as a class member without specifying its size?
When I do this: std::wstring string2 = string1; (where string1 is also a wstring and has a value), would it copy the actual data or just the referring class?

I used to know this but I forget.
Comment: Please define "reference class".
Answer:
Is std::wstring a sort of reference class like std::vector? As in, could I have it as a class member without specifying its size?

Yes, it is a "reference class", you can have it as a class member without specifying its size.

When I do this: std::wstring string2 = string1; (where string1 is also a wstring and has a value), would it copy the actual data or just the referring class?

This will copy the data because you're calling the assignment operator defined within the wstring class.
If you want to change the "referring class" consider using a pointer.
Answer:
I'm not quite sure what do you mean by "reference class" but yes you can have it as a class member without specifying the size:
class MyClass
{
private:
    std::wstring _str;
}

It would copy the actual data and you will have 2 different string objects with the same content.

It's worth noting that std::string, std::wstring, std::u16string and std::u32string are just typedefs for std::basic_string<some_exact_type>, so they all work the same way.


Conditional Breakpoint Error - Type does not implement selector max and signature

Question: I am trying to debug a piece of code of mine where (Integer) values in a map sometimes get surprisingly high.
When I do this
Collection<Integer> vals = newState.values();
int max = Collections.max(vals);
return newState; // breakpoint here

I can set a conditional breakpoint at the line of the return statement with a condition involving max, e.g. max > 10. When I leave out the middle line and set the breakpoint condition to Collections.max(vals) > 10, I get a runtime exception in debug mode.
"Reason: Type does not implement selector max and signature (Ljava/util/Collection;)Ljava/lang/Comparable;"
I can get what I want with the code fragment above, but I still wonder what is going on here. Guessing it could be the Collections method failing to realize that Integer is indeed comparable, I tried Collections.<Integer>max(v) and some (bad syntax) variations, without success.
Answer: Collections.max() has an interesting trick in its signature:
public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll)

As you can see, extends Object looks redundant here. The trick is that during type erasure T turns into its first generic bound (i.e. Object), so that the actual erased signature of this method looks like this:
public static Object max(Collection coll)

It's made for retaining binary compatibility with pre-generic version of this method: code compiled against pre-generic version expects return type to be Object, and using this trick new version satisfies its expectation.
However, as you can see, debugger incorrectly assumes that erause of T is Comparable. Perhaps it's a bug in debugger.
Answer: Most of the time It will happen when you call a static method inside same scope with class reference prefix
Example
public final class SomeUtilClass{
    public static boolean utilMethod1() {
     //
    }

    public static boolean utilMethod2() {

        if(SomeUtilClass.utilMethod1()) {
           //
        }
    }
}

in the above example with in the utilMethod2 we have used utilMethod1 with prfixing the class name (ie SomeUtilClass.utilMethod1()) which is unnecessary since both are in the same scope, it is just like a calling a local private method,
In this case the prifix  SomeUtilClass." is not needed, it will cause these kind of problem while debugging if we remove "SomeUtilClass." prfix inside the if condition it will work just fine.. since utilMethod2 does not need any class reference to call utilMethod1


valor do textbox para outro textbo usando Tabcontrol e Tabpages

Question: Estou usando em um form um TabControl, com três páginas.
Na TabPage1 tenho um TextBox (vendedor), preciso levar o valor deste TextBox para outro TextBox que está na  TabPage3.
Como posso fazer isso entre as paginas do TabControl sendo que o form é único?
Segue o Load() do form:
private void frmComissaoPic_Load(object sender, EventArgs e)
{
    SqlCommand carrega = new SqlCommand(@"SELECT SA.A3_NREDUZ FROM SA3010 AS SA WHERE SA.A3_TIPO = 'E'", conexaoDADOADV(true));
    carrega.Connection = conex;
    carrega.CommandType = CommandType.Text;
    try
    {
        SqlDataReader dr = carrega.ExecuteReader();
        DataTable dt = new DataTable();
        dt.Load(dr);

        txt_vendedor.DisplayMember = "A3_NREDUZ";
        txt_vendedor.DataSource = dt;
    }
    catch (Exception)
    {
        MessageBox.Show("Não existem dados a retornar por favor verifique como o Administrador do sistema");
    }

    CloseButtonDisabler.DisableCloseButton(this.Handle.ToInt32());

    txt_vendatab3.Text = txt_vendedor.Text;
    txt_nfe.Text      = "";
    txt_pedido.Text   = "";
    txt_item.Text     = "";
}

Comment: Precisa "levar o valor" quando? Enquanto for digitado? Ao clicar num botão? Ao trocar de página? Aliás, o código postado não é útil para a questão.
Comment: Boa tarde...então preciso levar o valor ao trocar de pagina.
Answer: É só usar o evento Selecting do TabControl
public void tabControl1_Selecting(object sender, TabControlCancelEventArgs e)
{
    txtDois.Text = txt_vendedor.Text;
    // Onde, txtDois é o TextBox que vai receber este dado
}

Você pode inscrever o evento usando o form designer ou então no (ou após) o método InitializeComponents()
public Form1()
{
    InitializeComponents();
    tabControl1.Selecting += tabControl1_Selecting;
}

Comment: Linq só mais uma duvida, eu consigo dentro deste comando fazer um select e executar uma query também ao mudar de pagina sem precisar de um botão
Comment: @JuniorGuerreiro Consegue
Comment: @JuniorGuerreiro Conseguiu resolver o problema da publicação?
Comment: Sim resolvi sim.....obrigado..


Cypress unable to click on custom button

Question: I am automating a test on a page and I need to click the "Add images" button. But it's not reacting
<button class="btn btn-default awe-hidden" id="html5button" onclick="$('#html5files').click();return false;">Add images</button>

I have tried

cy.get('button').contains('Add images').click()
cy.get('button').contains('Add images').invoke('show').click()
cy.get('button').contains('Add images').invoke('show').click({force: true})
cy.get('button').contains('Add images').trigger('mouseover').dblclick()
Also tried trigger 'mousedown', short wait then 'mouseup'
Also tried cy.contains('Add images').click()

Any ideas?
Comment: It may be because the onclick contains jquery code. Try using [cypress-real-events](https://github.com/dmtrKovalenko/cypress-real-events) `cy.get('button').realClick()`
Comment: can you please provide the error message/stacktrace of your failing test?
Comment: Thanks @DieGraueEminenz but there is no error message displayed.
Comment: @Sarah thank you that solves it :) If you post it as the answer I will mark it.
Answer: The onclick() event handler contains a jQuery expression, but I suspect Cypress doesn't handle it properly.
You can use cypress-real-events instead
cy.get('button').realClick()


Two Windows server, not in domain, grant permissions to each other's users

Question: We have two Windows Server machines, which are not in domain. Sql Server runs on one of them.
We want to save backups of Sql Server to another server. We created a folder in second server then we gave everyone permission to folder.
When we backup the Sql server, we got an error, Permission denied. I understand the problem but I want to learn giving permission to another server's users for the folder.
Comment: Questions must demonstrate a ***minimal understanding of the problem being solved.*** Try including attempted solutions, why they didn't work, and the expected results. See [How can I ask better questions on Server Fault?](http://meta.serverfault.com/q/3608/) for further guidance.
Answer: You can only grant permissions to local users if not in a domain, not to users of another system. The other computer than has to connect with the credentials of a user local to the target computer to be able to access it.
Comment: Small exception: you can grant it to guest, but you shouldn't.
Comment: and you can fool it if necessary by creating the same username/password combination on the target server that is currently being used as the login on the "client" server for the sql server service.


Contar apenas novos regsitros no banco e apresentar como notificações

Question: Tenho a seguinte questão, preciso retornar em um painel que existem registros que não estão sendo mostrados na tela. Tipo tenho 10 registros sendo exibidos, são cadastrados mais 2 dai preciso mostrar uma notificação parecida com a do Facebook.
Num primeiro momento pensei em cadastrar os novos registro com um status e depois muda-lo quando o registro fosse carregado na tela até funcionou muito bem. O que gostaria de saber é se existe algo feito através do mysql mesmo?
Answer: Não há amigo, o controle tem que ser manual, com uma flag como vc fez ou inserindo esses novos IDs em uma tabela de controle com a mesma finalidade.
Comment: Que pena. Seria tão amigável. Vou ter que manter meu código com está então. Depois que otimizar ele posto aqui para ajudar alguém no futuro.


Why AWS classic ELB with HTTP protocol doesn't work with websockets?

Question: I know that there is an ALB and NLB option that works with websockets. I can't understand why classic ELB with HTTP protocol doesn't work with websocket connections, although at the instance there is Nginx which is configured to add connection and upgrade headers. Once I switch it to TCP protocol it works. Can you explain how exactly this protocol works when there is HTTP proxy in the middle?
It is still using same TCP, as soon as client reached the server and  Nginx added upgrade headers, server response with switch protocol message should reach the client and then they just use TCP of established HTTP connection. What is the reason it drops this connection on an ELB, response buffering, or it just drops all non HTTP traffic?
So Nginx sends to ELB
<code> HTTP/1.1 101 Switching Protocols
Server: nginx/1.13.1
Date: Sat, 21 Mar 2020 07:53:38 GMT
Connection: upgrade
Upgrade: websocket
Sec-WebSocket-Accept: PozdkhgL/Zdkgh3kwu0KkACFCt0=
</code>
But ELB never deliver it back to client, and request get timed out.
Answer: The Classic ELB doesn't support Websockets.  Why it doesn't is not something AWS publishes.  From the chart in the reference below it specifically calls out, as you pointed out, that the ALB and NLB support Websockets.  Why the Classic does not support them is not disclosed.
Bottom line, if you want to use an ELB with Websockets use an ALB or NLB
References
Elastic Load Balancing Features
Answer: I don't know why ELB doesn't support websockets. But if the vendor says they don't support it, you should just stick with that.
Hey, it's their platform.


Decrease one VolumeGroup, increase another

Question: Is it possible to decrease the vg_home and increase vg_root? I am running RHEL. I need to know the steps.
[root@web /]# uname -a
Linux web 2.6.32-131.4.1.el6.x86_64 #1 SMP Fri Jun 10 10:54:26 EDT 2011 x86_64 x86_64 x86_64 GNU/Linux
[root@web /]# cat /etc/redhat-release
Red Hat Enterprise Linux Server release 6.2 (Santiago)

[root@web /]# df -kh
Filesystem            Size  Used Avail Use% Mounted on
/dev/mapper/vg_web-lv_root
                       50G  7.8G   40G  17% /
tmpfs                 7.8G  384K  7.8G   1% /dev/shm
/dev/sda2             485M   79M  381M  18% /boot
/dev/sda1             200M  256K  200M   1% /boot/efi
/dev/mapper/vg_web-lv_home
                      755G  6.2G  711G   1% /home

[root@web /]# cat /etc/fstab

#
# /etc/fstab
# Created by anaconda on Sun Jul 10 14:37:44 2011
#
# Accessible filesystems, by reference, are maintained under '/dev/disk'
# See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info
#
/dev/mapper/vg_web-lv_root /                       ext4    defaults        1 1
UUID=bc2a5e3c-d55a-4980-887a-695cb0e0dbe7 /boot                   ext4    defaults        1 2
UUID=C024-19D6          /boot/efi               vfat    umask=0077,shortname=winnt 0 0
/dev/mapper/vg_web-lv_home /home                   ext4    defaults        1 2
/dev/mapper/vg_web-lv_swap swap                    swap    defaults        0 0
tmpfs                   /dev/shm                tmpfs   defaults        0 0
devpts                  /dev/pts                devpts  gid=5,mode=620  0 0
sysfs                   /sys                    sysfs   defaults        0 0
proc                    /proc                   proc    defaults        0 0

Answer: You mean lv_home and lv_root, presumably, given that vg_home doesn't exist... This is why I loathe the RHEL installer; it does such idiotic things with both naming and space allocation.
What you'll need to do is:

Ensure nothing has any files open in /home, and that nothing will try and access any files in /home during the resizing operation.  This is best achieved by dropping into single user mode (telinit 1, unless RHEL's gone and switched to upstart or something in recent versions), but if you at least turn off the HTTP and SMTP services you're on a good start.
Unmount /home (umount /home)
Fsck the filesystem (fsck /dev/vg_web/lv_home)
Reduce the size of the filesystem on lv_home to something sensible (resize2fs /dev/vg_web/lv_home 45G)
Reduce the size of the LV to something sensible, but a bit larger than the filesystem (because it's easier to make the filesystem a bit bigger later, but chopping off the end of the filesystem by making the LV a bit too small is catastrophic: lvresize -L50G vg_web/lv_home)
Fsck again (fsck /dev/vg_web/lv_home)
Mount the filesystem again (mount /home)
Expand the filesystem back out to the size of the LV (resize2fs /dev/vg_web/lv_home)

And next time, don't trust what anaconda wants to do, and create the LVs yourself to the sizes that are appropriate for your system.
Comment: Yes I did the abbreviation I need to increase vg_web-lv_root and reduce vg_web-lv_home
Comment: Expand the filesystem back out to the size of the LV (resize2fs /dev/vg_web/lv_home)  you mean (/dev/mapper/vg_web-lv_root)
Comment: No, I did not.  Extending the root LV is a separate exercise involving the use of `lvextend` and `resize2fs`, which I've left as an exercise.


Cython: Workaround scipy.optimize.cython_optimize.brentq argument ctype to work with class methods ctype

Question: I'm trying to use the root finder scipy.optimize.cython_optimize.brentq inside a class, but the first argument of this function accepts only the type ctypedef double (*callback_type)(double, void*) and my class method is the type of ctypedef double (*w_func)(test,double, void*).
How could I get this working?
The following code is an exemple of the problem.
%%cython
from scipy.optimize.cython_optimize cimport brentq

ctypedef double (*f_func)(test,double, double)
ctypedef double (*w_func)(test,double, void*)
ctypedef double (*callback_type)(double, void*)

ctypedef struct test_params:
    double y0
    double x1
    f_func f
    w_func w

cdef class test():
    def __init__(self):
        cdef test_params myargs
        myargs.y0 =  1.0
        myargs.x1 = 0.7
        myargs.f = self.sum2
        myargs.w = self.w
        print(self.brentqWrapper(myargs, -10, 10, 1e-3, 1e-3, 10))

    cdef double sum2(self, double x1,double y1):
        return x1+y1

    cdef double w(self, double y1, void *args):
        cdef test_params *myargs = <test_params *> args
        return y1 - myargs.y0 - myargs.f(self,myargs.x1,y1)

    # Cython wrapper function
    cdef double brentqWrapper(self,test_params args, double xa, double xb,
                                       double xtol, double rtol, int mitr):
        return brentq(args.w, xa, xb, <test_params *> &args, xtol, rtol, mitr, NULL)

test()

Answer: ISTM it's easiest and most clean to restructure your code to have a module-level function which receives the class instance in its last argument.
Comment: How could I  pass a class instance as the last argument of the type void* ?


Poisson Arrival time and Gamma distribution

Question: I have a question on poisson arrival times / gamma distribution that I just cannot understand as of now.
Question: The times when goals are scored in a 60 minute match are modeled as a Poisson process. For such a process, assumed that the average time between goals are 15 minutes ($\lambda$= 1/15).
Assume that at least three goals are scored in a game. What is the mean time of the third goal?
Here is the answer given in the book I have (Introduction to Stochastic Processes with R):

I expected something on the form of E[$S_n$] = n / $\lambda$ but got something very different.. can someone explain the answer and why it is correct?
Thanks.
Comment: Not that it helps explain, but the unconditional expected time is $E[S_3]=3\times 15 =45$ as you imagined, while  this final result can be written as $E[S_3\mid S_3 \le 60]= 45-\dfrac{480}{e^4-13}$.  It is lower because you have truncated off the possibility that the third goal happens after the end of the match, so removing the possibility of high $S_3$, and thus having a smaller conditional expectation
Comment: I would say that this task needs to use the Erlangian distribution (a special case of the gamma distribution).

https://en.m.wikipedia.org/wiki/Erlang_distribution
Answer: It is the condition that at least $3$ goals are scored that makes things more complicated. You are asked to find conditional expectation $\mathbb E[S_3|S_3\leq60]$ (not $\mathbb ES_3$).
The solution works like this:
In general we have the rule:$$\mathbb E[X|X\in A]=\frac{\mathbb EX1_{X\in A}}{P(X\in A)}$$and we can apply that here in order to find $\mathbb E[S_3|S_3\leq60]$.
Note that: $$P(S_3\leq60)=P(N(60)\geq3)=1-P(N(60)=0)-P(N(60)=1)-P(N(60)=2)$$where $N(60)$ has Poisson distribution with parameter $60\lambda=4$. This way we can find the denominator.
If $f(t)$ denotes the PDF of $S_3$ then the numerator will be:$$\int_0^{60}tf(t)dt$$
We can find the PDF by taking the derivative of CDF: $$P(S_3\leq t)=P(N(t)\geq3)=1-P(N(t)=0)-P(N(t)=1)-P(N(t)=2)$$where $N(t)$ has Poisson distribution $\lambda t=\frac{t}{15}$.

Edit:
Let me add that in this situation $S_k$ has Erlang distribution with parameters $k$ and $\lambda$ or in other terminology the Gamma distribution with parameters $\alpha=k$ and $\beta=\lambda$. Its PDF is:$$e^{-\lambda}\frac{\lambda^kx^{k-1}}{(k-1)!}$$
A nice way to prove that is (again) taking the derivative of the CDF of $S_k$.
Comment: In R the denominator can be found as `pgamma(60,3,1/15)` or `(1-ppois(2,4))` and the numerator as `3*15*pgamma(60,4,1/15)` or `3*15*(1-ppois(3,4))`
Answer: One can also rely on known properties :

Interarrival times $T_1,T_2,... $ in a Poisson process are independent and exponentially distributed ;
The sum of $n$ independent and exponentially distributed r.v. follows a $\Gamma(n,\lambda)$ distribution (https://en.wikipedia.org/wiki/Relationships_among_probability_distributions) and you can look on Wikipedia at the analytical form of this distribution, which is exactly the one used in the formula reported.

Now if you know that $S_3=T_1+T_2+T_3$ has distribution $f(s)$ than $E[S_3|S_3<a]$ is equal to:
$E[S_3|S_3<a]=\frac{\int_0^a xf(x)dx}{\int_0^a f(x)dx}$,
which is your expression. As @Henry observed, this can be either numerically or analitically evaluated. For the analytical part, I would rely on Mathematica or Wolfram Alpha to make things quicker...


Xib view file is not working in landscape mode

Question: I have added new Xib view file in my project. I assigned to view controller and in the view controller I set:
<code>- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    //return (interfaceOrientation == UIInterfaceOrientationLandscapeRight);
    return YES;
}
</code>
But when the application runs in landscape mode, xib is not in landscape mode. I have set in info.plist file also xib file is also in landscape view. What do I have to do? Any help?
Answer: You need to adjust the alignment of elements on your view in the way, that when it rotates the elements will take their place according to orientation.
for example if you have a button on your left bottom corner, in the alignments pane you should assign it to stick to left and bottom, while maintaining its original size. Also the containing view has to be fully autoresizable.
You can do it from the code like this:
<code>self.view.autoresizingMask = (UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
</code>
Hope this helps
Comment: sir, i have added , i have same issue
Comment: do you need this view show in portrait and in landscape, or only in landscape? If you need it to show in both, you have to change ALL subviews in your view to have proper alignment. If you need your view ONLY in landscape, you can design it in IB in landscape mode. To achieve this, find a small circular arrow on the top right side of the view editor. If you press it, the editor will change to landscape mode and you can edit your view in landscape, so it will show properly in landscape.
Comment: Hi, when I used IB to design in landscape mode, the view does not rotate to landscape, but it is in the landscape "shape" (the wide and short size) displayed in portrait mode. What am I missing? I have edited the plist file, the code you have from above, but it still does not work. (the keyboard is rotated correctly however)...


Excluir última vírgula de uma string

Question: Tenho uma string:
"imagens":["upload/7057c705298193c513f07fbb8fbe2856.jpg", "upload/30c2dbcd5c890e763fab6ccfa63ab24c.jpg", "upload/40f4af351cfa1d01ca2e468965d28626.jpg", ]
E quero excluir a última vírgula dela, deixando ficar assim:
"imagens":["upload/7057c705298193c513f07fbb8fbe2856.jpg", "upload/30c2dbcd5c890e763fab6ccfa63ab24c.jpg", "upload/40f4af351cfa1d01ca2e468965d28626.jpg"]
Como fazer?
Comment: Provavelmente isso é um problema na geração da string, melhor do que tirar a vírgula é nem colocá-la. Mas pra ter certeza mesmo, somente vendo o código que gera a string.
Answer: // Remove os dois últimos caracteres
$str = substr($str, 0, strlen($str)-2);

// Acrescenta de volta o ]
$str .= ']';

Answer: Você pode fazer isso com a função str_replace
$string = '"imagens":["upload/7057c705298193c513f07fbb8fbe2856.jpg", "upload/30c2dbcd5c890e763fab6ccfa63ab24c.jpg", "upload/40f4af351cfa1d01ca2e468965d28626.jpg", ]';

echo str_replace(', ]', ']', $string);

O resultado será:
"imagens":["upload/7057c705298193c513f07fbb8fbe2856.jpg", "upload/30c2dbcd5c890e763fab6ccfa63ab24c.jpg", "upload/40f4af351cfa1d01ca2e468965d28626.jpg"]
Answer: Veja o seguinte Trecho de código que remove a vírgula com ou sem espaço antes do colchete.
<?php
/*A string que vc forneceu*/
$texto = '"imagens":["upload/7057c705298193c513f07fbb8fbe2856.jpg", "upload/30c2dbcd5c890e763fab6ccfa63ab24c.jpg", "upload/40f4af351cfa1d01ca2e468965d28626.jpg", ]';

/*Limpa String*/
echo preg_replace("/,(\s{1,}|)]/", "]", $texto);
?>

Excluir última vírgula de uma string


Usage of unusual characters in sports shirts

Question: Many languages make use of characters outside the standard English A-Z set, and these characters often make it into family names, e.g., Özil, Fàbregas, Čech, Szczęsny, and so forth. Surprisingly (to me), kit manufacturers often produce shirts where the player's name has a special character replaced with the closest approximation within the English A-Z set, e.g.,

At Arsenal, Szczęsny's shirt says Szczesny, and this version of the name is even used in the club's website. Similarly, Čech goes by Cech.
Many Iceland players have names with a þ or a ð in them, and then carry shirts where it is replaced with th. For example, Sigþórsson went around the Euro this summer with a shirt that said Sigthorsson. This is also the version of his name in his Nantes website.

Many such examples can be provided. Effectively, the only special characters that regularly make it into shirts are Germanic umlauts and Spanish/Portuguese accents. This is odd, because the change in spelling often entails a change in pronunciation (e.g., Šmicer's Liverpool shirt used to say Smicer, even though š and s correspond to different sounds; this is like giving Ronaldo a shirt that says Renaldo and then going "eh, close enough, who cares").
So  here there are actually two questions. First, why do clothing companies systematically produce shirts with known misspellings (unlikely to be economic reasons, I think; the cost of procuring additional characters is probably trivial relative to the size of the market)? And second, why do the relevant players systematically tolerate the misspellings?
Comment: It is interesting to note that Szczęsny's and Čech have (or had) names without diacritics on their Arsenal shirts whereas the club [permits the umlaut in Özil's name](http://i.stack.imgur.com/NFqis.jpg). It might that whether diacritics are excluded or not be due to whether the player himself is happy or not with the exclusion: if he is happy, then the diacritics are dispensed with for practical reasons. (This is just a personal opinion, hence I'm posting as a comment rather than answer.)
Comment: It seems that even within a single club, the rules about carons aren't always applied consistently.  Look at [this](http://i.telegraph.co.uk/multimedia/archive/01982/dzeko-nasri_1982794i.jpg) and [this](http://static.goal.com/121600/121632_heroa.jpg).
Answer: The FIFA equipment regulations mandate:

7.6 The letters used for the Player's name must be (...) Latin characters. Phonological diaeresis, such as accents or umlauts, are permitted.

So the answer to both of your questions is: Because the FIFA laws say so.
I can only speculate as to why these laws are there. Most likely, referees and spectators will prefer to have any spelling they can pronounce. For instance, I have no idea how to start pronouncing 郑智, 武磊 or 郜林. Although the spellings Zheng Zhi, Wu Lei, and Gao Lin probably don't match the correct pronunciation, they are sufficiently recognizable and allow any European to approximate the player's name.
Even worse than not being  able to pronounce these names, it may also be hard to distinguish them during a fast-paced match. In effect, names written in unknown character sets do not fulfill the primary function of a name; identifying a person by name would be hard.
I'm not aware of any ruling that forbids writing out the full player's names in press materials such as club websites. My guess would be that it's more important for the name to be consistent than right; if every English fan mispronounces the name the same way, they can still talk about the players.
Incorrect renderings may also result in a better pronunciation. Asking a German how Sigþórsson would be pronounced, the result would be likely be Siɡpʰɔʁsɔn, whereas Sigthorsson's German pronunciation of Siɡtʰɔʁsɔn is much closer to the correct one (in addition to creating an excellent pun).
The players have to follow FIFA laws. Just as some players would like to play with a cool cap, or have sponsor names on their shirts, they have to bow to the laws. Also, some players may themselves prefer their names' pronunciation to be consistent but wrong - or sometimes, as in the case of Sigþórsson, rendered incorrectly but pronounced (more) correctly, because a recognizable/spellable name increases prominence, and increased prominence translates to increased income.
Comment: I'd guess these distinctions might also be based on such boring differences as the ability to write the specific character on a keyboard and availability in the fonts used. E.g. I noticed international athletics competitions sometimes keep acute accents in names, but drop "more exotic" carons: a quickly found example of [Barbora Spotáková without Š but with Á](https://youtu.be/j0q70t3yaNM?t=1m38s).
Comment: I accept the answer, but I dislike it, as it makes little sense from a linguistic/orthographic perspective (a German umlaut, for one, is not a diaeresis). If one wants to say that the *ñ* in *Cañizares* is a licit extension of the basic Latin character set, there is no obvious reason to deny the *š* in *Šmicer* the same status.


Parse Mutual Friends response PHP JSON

Question: I am using facebook graph api to access mutual friend list using PHP
Here's how I am doing it

$url  = "https://graph.facebook.com/me/mutualfriends/123456788?access_token=1457856";

$user = json_decode(file_get_contents($jsonurl));

I am now printing the result via print_r($user->data) and following is the output

Array
(
    [0] => stdClass Object
        (
            [name] => XYZ
            [id] => 123
        )

)
Array
(
    [0] => stdClass Object
        (
            [name] => YZX
            [id] => 235
        )

)

I need to get name and Id of the mutual friends from the above resultset using PHP
What should be the next step for this?
Answer: It would be the same like $user->data:
foreach($user->data as $user) {
   echo "name: ".$user->name."
";
   echo "id: ".$user->id."
";
}

I have tested this on the following data:
stdClass Object
(
    [data] => Array
        (
            [0] => stdClass Object
                (
                    [id] => ID
                    [name] => Name
                )

            [1] => stdClass Object
                (
                    [id] => ID
                    [name] => Name
                )

        )

)

Comment: I am not getting the desired output with this code, here's how I have implemented it
Comment: foreach($user->data as $resultSet)
{
echo $resultSet->name;
}
Comment: FYI: mutual friends API is deprecated for versions v2.0 and higher
(in case anyone tries this in 2017)

Parse Mutual Friends response PHP JSON


Is there any solution except integration by parts for $\int_0^\infty x^2 e^{-x} \sin(\alpha x) dx$?

Question: I want to calculate the Fourier sine integral and the Fourier cosine integral of the function $f(x)=x^2e^{-x}$. So I have to calculate:
$$
\int_0^\infty x^2e^{-x}\sin(\alpha x)dx \qquad , \qquad \int_0^\infty x^2e^{-x}\cos(\alpha x)dx
$$
The integration by parts method is really complex for these two integrals!
Is there any better solution to calculate them?!
Answer: $$\int_{0}^{+\infty}x^2 e^{-(1-i\alpha)x}\,dx=\frac{1}{(1-i\alpha)^3}\int_{0}^{+\infty}x^2 e^{-x}\,dx =\frac{2}{(1-i\alpha)^3}=\frac{2}{(1+\alpha^2)^3}(1+i\alpha)^3 $$
then you may just consider the real or imaginary parts of both sides to get:
$$ \int_{0}^{+\infty}x^2 e^{-x}\cos(\alpha x)\,dx = \frac{2-6\alpha^2}{(1+\alpha^2)^3},\qquad \int_{0}^{+\infty}x^2 e^{-x}\sin(\alpha x)\,dx = \frac{6\alpha-2\alpha^3}{(1+\alpha^2)^3}.$$
Comment: @SimplyBeautifulArt: all right, the change of variable $x\mapsto\frac{x}{1-i\alpha}$ change the upper bound $+\infty$ into $\frac{+infty}{1-i\alpha}$, but by applying the ML Lemma the integral $\int_{M}^{\frac{M}{1-i\alpha}}$ converges to zero so we are allowed to leave $+\infty$ as endpoint of the integration range, after the substitution.
Comment: A small nitpick, as $(1-i\alpha)x\mapsto x$, $+\infty\not\mapsto+\infty$.
Answer: One might consider the following integral:
$$f(\alpha)=\int_0^\infty e^{-x}\sin(\alpha x)~\mathrm dx$$
This can be solved using Euler's formula:
$$\begin{align}f(\alpha)&=\Im\int_0^\infty e^{(i\alpha-1)x}~\mathrm dx\\&=\Im\left[\frac{e^{(i\alpha-1)x}}{i\alpha-1}\right]_0^\infty\\&=\Im\left[\frac1{1-i\alpha}\right]\end{align}$$
Likewise, from the integral representation:
$$f''(\alpha)=-\int_0^\infty x^2e^{-x}\sin(\alpha x)~\mathrm dx$$
And from the closed form:
$$f''(\alpha)=\Im\left[\frac{-2}{(i\alpha-1)^3}\right]=\Im\left[\frac{2(i\alpha+1)^3}{(\alpha^2+1)^3}\right]=\frac{2\alpha^3-6\alpha}{(\alpha^2+1)^3}$$
Likewise,
$$\begin{align}g(\alpha)&=\int_0^\infty e^{-x}\cos(\alpha x)~\mathrm dx\\&=\Re\int_0^\infty e^{(i\alpha-1)x}~\mathrm dx\\&=\Re\left[\frac1{1-i\alpha}\right]\\\implies f''(\alpha)&=\Re\left[\frac{2(i\alpha+1)^3}{(\alpha^2+1)^3}\right]=\frac{2-6\alpha^2}{(\alpha^2+1)^3}\end{align}$$
$$f''(\alpha)=-\int_0^\infty x^2e^{-x}\cos(\alpha x)~\mathrm dx$$
Answer: Laplace transform
$\mathcal{L}\{x^2\sin\alpha x\}(s)=-\dfrac{2 a \left(a^2-3 s^2\right)}{\left(a^2+s^2\right)^3}$
your integral is
$\mathcal{L}\{x^2\sin\alpha x\}(1)=-\dfrac{2 a \left(a^2-3\right)}{\left(a^2+1\right)^3}$
For cosine is
$\mathcal{L}\{x^2\cos\alpha x\}(1)=\dfrac{2 \left(1-3 a^2\right)}{\left(a^2+1\right)^3}$
Comment: Well, (it is just my opinion that) Laplace transform does not address the OP's need, since approaches to get the result also involve integration by part.
Comment: @BAI I just looked on tables :)
Answer: If you don't want to use complex numbers, you'll find $\int_0^\infty e^{-\beta x}\cos\alpha x$ and its sine counterpart are relatively easy by parts. Then just apply $\partial_\beta^2$ and set $\beta=1$.
Answer: In general, for any real numbers $\alpha$ and $\beta>0$
\begin{aligned}
\int_0^{\infty} x^\beta e^{-x} \sin (\alpha x) d x
& =\Im \int_0^{\infty} x^\beta e^{-x} e^{\alpha x i} d x \\
& = \Im \int_0^{\infty} x^\beta e^{-(1-\alpha i) x} d x \\
& = \Im\left[\frac{\Gamma(\beta+1)}{(1-\alpha i)^{\beta+1}}\right] \\
& =\Gamma(\beta+1) \Im \left[ \frac{(1+\alpha i)^{\beta+1}}{\left(1+\alpha^2\right)^{\beta+1}} \right]\\
& =\frac{\Gamma(\beta+1)}{\left(1+\alpha^2\right)^{\beta+1}} \Im\left[(1+\alpha i)^{\beta+1}\right] \\
&
\end{aligned}
As a bonus,
$$\int_0^{\infty} x^\beta e^{-x} \cos (\alpha x) d x= \frac{\Gamma(\beta+1)}{\left(1+\alpha^2\right)^{\beta+1}} \Re\left[(1+\alpha i)^{\beta+1}\right] \tag*{} $$
In particular, $\beta=2$,
$$\int_0^{\infty} x^2 e^{-x} \sin (\alpha x) d x= \frac{\Gamma(3)}{\left(1+\alpha^2\right)^{3}} \Im\left[(1+\alpha i)^{3}\right]= \frac{6 \alpha-2 \alpha^3}{\left(1+\alpha^2\right)^3}
$$
$$\int_0^{\infty} x^2e^{-x} \cos (\alpha x) d x = \frac{2-6 \alpha^2}{\left(1+\alpha^2\right)^3}
$$