Chamar método de outra classe

Question: sou iniciante em java, e estou criando um CRUD básico de uma biblioteca, como tenho muitas operações, achei melhor fazer uma classe especializada pra cada operação, que vai chamar os métodos da classe biblioteca.
Estou fazendo a classe da operação cadastrar, onde ela terá irá chamar os métodos cadastrarAutor, cadastrarLivro, cadastrarAutora da classe biblioteca.
porém não sei como chamar os métodos, pois eles estão em uma classe diferente.
segue o código:
Classe biblioteca
public void cadastarAutor(Autor autor) {
    this.autores.add(autor);

}

public void cadastrarEditora(Editora editora) {
    this.editora.add(editora);

}

public void cadastrarLivro(Livro livro) {
    this.livro.add(livro);
}

Classe Cadastrar
import RepositorioLivros.Biblioteca;

  public class Cadastrar {

    Biblioteca biblioteca= new Biblioteca();

    biblioteca.

}
como eu vou chamar os métodos da classe biblioteca para usar na classe Cadastrar?, instanciei uma biblioteca na classe cadastrar e já tentei fazer deste modo: biblioteca. e chamar os métodos, mas quando eu tento chamar ñ funciona, o Eclipse nem sequer mostra as opçoes após o .(ponto)
O correto seria quando eu tentasse chamar, aparecer as opções dos métodos que estão na classe biblioteca, mas Ñ aparece, após eu digitar biblioteca. , ele da um erro:
Comment: Cadastrar  é para ser um classe ou um método?
Comment: O que ocorre quando tenta chamar?
Comment: editei e coloquei a imagem do erro  na minha pergunta, atualiza e reveja
Comment: `import RepositorioLivros.Biblioteca;`: tem um pacote chamado `RepositorioLivros`?
Comment: sim Igor Venturelli tem sim
Comment: Qual pacote a classe `Cadastrar` está?
Comment: Edita a pergunta incluindo o código completo das duas classes, por favor. Desde a primeira linha do arquivo até a última
Comment: Como eu disse, eu fiz uma classe separadamente pra cada operação, a classe operação vai tratar só das operações da cadastrar, porém as operações estão na classe Biblioteca, e quero chamar elas pra classe Cadastrar....                                                                                A classe Cadastrar está em um pacote chamado Operacoes
Answer: O corpo da classe pode conter somente declarações de membros da classe, como

campos
interfaces
métodos
inicializadores de instâncias
inicializadores estáticos
declarações de construtores para a classe

Para chamar algum método da classe Biblioteca, defina um método dentro da classe Cadastrar e utilize a instância de Biblioteca juntamente com a notação em ponto.
public class Cadastrar {
    // ...
    public void meuMetodo() {
        biblioteca.cadastrarAutor(...);
    }
}

Leia mais sobre o corpo da classe em Java aqui.
Comment: Obrigado amigo era exatamente isso

Chamar método de outra classe


What does the notation of $2^{\mathbb{N}}$ mean?

Question: I've learned over the course of the last years that some mapping $\lambda$ denoted :
$$ \lambda : \mathbb{N} \rightarrow 2^{\mathbb{N}}.$$
essentially means that for every natural number, you assign (or map) some set of natural numbers to it. At multiple times, I've wondered if there's some meaning behind this notation (more precisely the $2^{\mathbb{N}}$ part) that I'm not understanding, as it does not seem as straightforward as say :
$$ f : n \rightarrow 2n$$
(also just noted as $f(n) = 2n$), where you clearly map any $n$ to $2n$. Is this $2^{\mathbb{N}}$ just some notation that one has to get used to, or does it make sense somehow to note it this way? If it does make sense, why the choice of exponentiation, and why the $2$?
Comment: In your examples, the $2^\mathbb{N}$ and $2n$ are not used in the same way.  One is the *codomain* that $\lambda$ maps to, and one is the specific *value* that $f$ maps its argument to.  As Dave explains in their answer, the specification of $\lambda$ is strange, because although it uses $2^\mathbb{N}$ as its codomain, it does not give a domain; it gives a specific value $n$.
Comment: Compare:https://math.stackexchange.com/q/901735/87023 https://math.stackexchange.com/q/1442509/87023 https://math.stackexchange.com/q/104522/87023 https://math.stackexchange.com/q/2569341/87023
Comment: @ChrisCulter nice ! You can note this question as a duplicate I suppose, I'll also add these in my accepted answer.
Comment: This one, too: https://math.stackexchange.com/questions/104522/
Comment: And this one: https://math.stackexchange.com/q/901735/468350
Answer: $2^{\mathbb N}$ denotes the power set of $\mathbb N$, i.e. the set of all subsets of $\mathbb N$. This notation is used because, for a finite set $A$, the size of the power set $2^A$ of $A$ is $2^{|A|}$.
However, $\lambda:n\to 2^{\mathbb N}$ still seems like weird notation to me: the $n$ is an element of $\mathbb N$ (presumably) but $2^{\mathbb N}$ is a set. Should it maybe be $\lambda:\mathbb N\to 2^{\mathbb N}$?
Comment: $\lambda:E\to 2^{\mathbb N}$ is fine; it doesn't have to be $\mathbb N$ as the domain, it just needs to be some (nonempty) set.
Comment: Yes, so the original equation was $\lambda : E \rightarrow 2^{\mathbb{N}}$, where $E$ denotes the edge set of a graph. I tried to generalize my question by putting just some $n$ instead, but I forgot (as you and Brian Tung noted) that it should be a set still, instead of a specific value (I'll edit this back in with $\mathbb{N}$).
Comment: As much as it is uncomfortable, $\lambda\colon n \to 2^{\Bbb N}$ still compiles, if one thinks that one set-theoretic of $n$ is $\{0,1,\ldots, n-1\}$.


URLhashListener pegando o item errado (Owl Carousel)

Question: Estou usando Owl Carousel numa landing page. adicionei algumas miniaturas, e usei o URLhashListener para associar as miniaturas á respectiva imagem, mas o link tá abrindo a imagem errada. Parece que o script está calculando o valor errado, as imagens ficam 2 atrasadas.
está em homologação aqui: http://aresdapraca.itlean.com.br/
Comment: Você testou tirar o Loop ?
Comment: funcionou sem loop!
Será que só tem esse jeito?
Answer: Descobri o problema. É um bug do próprio Owl Carousel.
Pode voltar o loop.
loop: true.
Pode tirar aquelas outras opções:
URLhashListener:true,
startPosition: 'URLHash'

Esses dois de cima é só para alterar a URL, o Hash:
#one #two.
Agora o que você tem que fazer é importar esse arquivo de script abaixo no seu código, abaixo do owl.carousel.min.js ou owl.carousel.js.
https://rawgit.com/OwlFonk/OwlCarousel2/develop/src/js/owl.hash.js
Aí está o LINK, mas você pode salvar a página como arquivo JS pra você ter o arquivo, porquê se o LINK quebrar você fica sem.


Clearprompt command: Element-list generation

Question: In view of my previous question Script for recursive add-to-source control: How to ignore specific files and folders, an issue that arose in regard to the command clearprompt (whereby to generate a list of elements for source control) is that it has restrictions on the number of elements it can process. So my question is: Is there a way to allow for a larger number of elements?
Comment: What operating system do you use?
Answer: clearprompt has some limitation, in term of size, number of character per lines, and as you see, number of elements.
Those aren't fixed, on Windows or Unix, as far as I know.
So it is best to split your list, and to display several clearprompt dialogs, with a header specifying the number of said dialog over the total of number of windows expected (1/6, 2/6, 3/6, ...)
The only other solution would be to rely on another library to dispolay that dialog, but the advantage of using ccperl is that it is installed with the ClearCase client, which means it is available on all client workstation.
Answer: I believe I encounter a similar issue where because of this limit, the clearprompt dialog was empty. I debugged the script and the error seems to be because of the system limit of the max command line which was passed to echo in the following statement
`echo $listelement > $list_add`

I just changed this line to the following
open(LIST_ADD,">".$list_add);
print LIST_ADD $listelement;
close(LIST_ADD);

or basically, instead of relying on the shell to copy the content, I am doing the same through perl and that resolved the issue.


Modal Bottom Sheet and Bloc

Question: I get the following error when I run code similar to the below code: BlocProvider.of() called with a context that does not contain a Bloc.
To replicate
BlocProvider(
          create: (context) => getIt<TheBloc>()
          child: BlocBuilder<TheBloc, TheState>(
          build: (context, state) =>
          MaterialButton(
            onPressed: () => _showModal(context),
            child: const Text('SHOW BLOC MODAL'),
),

...
void _showModal(BuildContext context) {
  showModalBottomSheet<void>(
    context: context,
    builder: (_) {
          return MaterialButton(
               onPressed() {
                       context.bloc<TheBloc>().add(
                         TheEvent.someEvent(),
                       );
               }
              child: Text('Press button to add event to bloc')
          );
    },
  );
}

Comment: @SergeySalnikov the issue was this code, I fixed it by wrapping the builder of the modal in a BlocProvider.value as per the bloc api reference. I've added the answer to the question. Thanks
Comment: I reviewed you snippets - this example should work. I guess reason somewhere in you real code
Answer: You need to wrap the builder of showModalBottomSheet with a BlocProvider.value as follows:
As the context is new.
return BlocProvider.value(
     value: BlocProvider.of<TheBloc>(context),
     child: MaterialButton( ...
     ...

Comment: It will more clear if you pass bloc to `_showModal(TheBloc bloc)` and skip unnessesssary lookup in context =)
Comment: can u please explain it little bit more
Answer: Actually if you need this bloc only in bottom sheet and nowhere else, the better and cleaner solution is create the StatefullWidget for bottom sheet content, create the Bloc inside this widget in initState() work with bloc in build() method and free resources in dispose() method.
  showModalBottomSheet<void>(
    context: context,
    builder: (_) {
          return MyBottomSheet(); // your stateful widget
        );
    },
  );

Using bloc like above guarantee that state of your bloc will be the same on each showModalBottomSheet call
Note. If you need to preserve state of bloc, you can try to use AutomaticKeepAliveClientMixin (did not tested)

Modal Bottom Sheet and Bloc


Reconnoiter - Anyone using it?

Question: Reconnoiter is a new tool in the world of monitoring. It is not only a trending tool but also an alerting/fault detection one. IMHO, I reckon that it's in the trending capacities that Reconnoiter has a very huge potential.
One of the premises Recoinnoter is built upon is that RRDTool large installations are very inneficient regarding I/O usage and I think this is RRDTool major problem.
One of the things that can difficult the change from the traditional RRDTool frontends to Reconnoiter is, obviously, the cost of change and the learning curve.
So, any of you has experience with Reconnoiter? How's the learning curve? Was it difficult to move from RRDTool frontend applications (Cacti, Munin, Ganglia) to Reconnoiter? I'm looking forward to read your opinions.
Comment: Don't know Reconnoiter but if you already use Cacti you might be interested by http://docs.cacti.net/plugin:thold for alerting/fault
Comment: @radius: already use thold plugin for some scenarios :)
Answer: The really neat thing about Reconnoiter is that graphs are effectively pointers to the metrics they contain.  There's no archaic concept of rrd database files for each graph, just a JSON object describing the graph.
There is a learning curve with installation and setup of Reconnoiter, which may be a drawback.  Alternatively, you should check out Circonus (http://circonus.com/), which is a hosted service built on Reconnoiter, adding in fault detection and notifications.  They have videos up on the site.

Reconnoiter - Anyone using it?


Concatenating mysql_query in C

Question: I am getting user input from my C program and I want to use the user input in my SELECT statement. However the mysql_query() only has accepts two parameters. I was thinking of coding it like this... mysql_query(con, "SELECT discontinued FROM products WHERE productid = '$products'", products_product_id) however I know that I will get error messages. What would be the best way to tackle this?
int products_product_id;

printf("-----------------\n");
printf("ADDING AN ORDER\n");
printf("-----------------\n");

scanf("%d", &products_product_id);
while(products_product_id <= 0 || products_product_id >= 78)
{
        printf("ProductID not found. Try again.\n");
        scanf("%d", &products_product_id);
}

printf("Searching for: %s\n",products_product_id);

if (mysql_query(con, "SELECT discontinued FROM products WHERE productid = '%products_product_id'", products_product_id)
{
        dberror(con);
}

Answer: mysql_query takes two arguments while you pass in 3.  Use mysql_bind_param to bind variables to your query.

Concatenating mysql_query in C


Equation of circle in 3d Plane?

Question: Suppose I have a sphere centered at origin. $$ x^2+y^2+z^2=5 $$
and a plane $$ \vec{r}.(\hat{i}+\hat{j}+\hat{k})=3\sqrt{3} $$
And this plane cuts the sphere at a circular region. How do I write the equation of this circle in a 3d Plane. I know its center $center=(\sqrt{3},\sqrt{3},\sqrt{3})$ and its radius $r=4$.
Thanks
Comment: Joint equation of sphere and plane.
Comment: Can you please tell a little in detail
Answer: You can represent the 3d circle in parametric form:
1) form a local coordinate system X'Y'Z' on the plane with origin at the circle's center and Z' axis in the same direction as plane's normal.
2) This 3d circle can be represented as
$(x'(t), y'(t), z'(t)) = (rcos(t), rsin(t), 0)$ where r=radius
3) Perform coordinate transformation between coordinate systems X'Y'Z' and XYZ.
I will leave the details about how to find the local coordinate system and how to perform coordinate transformation to yourself.

Equation of circle in 3d Plane?


Aplicativo Android e servidor windows - salvar arquivo no servidor

Question: Montei um programa de vendas e analise de vendas, executado no windows, para uso no pc/servidor, e os outros PCs/Notes já montei a rede por acesso VPN, e todos rodam e salvam o arquivo dentro do servidor. Esses são arquivos são dois arquivos de Excel que servem como banco de dados, de cadastro de clientes e faturamento.
Gostaria de saber, se é possível, ter esse tipo de acesso a modificar o arquivo excel no servidor, ao criar o mesmo programa porém para utilização no Android e se essa informação tenho que colocar no código (se for possível vou atrás de descobrir como).
<code>#Parte do código que salva/atualiza o arquivo Excel:
while True:
    window, eventos, valores = sg.read_all_windows()
    book = openpyxl.load_workbook('faturamento.xlsx')
    dados = book['dados_gerais']
    book2 = openpyxl.load_workbook('cadastro.xlsx')
    dados2 = book2['dados_gerais']
    df = pd.read_excel('faturamento.xlsx')
    df2 = pd.read_excel('cadastro.xlsx', dtype=str)
    df3 = list(df2['cnpj_cpf'])
...
    elif window == janela3 and eventos == 'CONFIRMAR':
        dados.append([ordem_de_venda, data, nome, m3, valor_unt, fat_total, cod_cliente, cod, None, ven])
        book.save('faturamento.xlsx')
        sg.Popup('VENDA FINALIZADA', no_titlebar=True,background_color='#171717')
        janela1 = janela_cadastro()
        janela3.hide()

Obrigada
</code>
Answer: Nesse caso você precisa de um backend para fazer isso. Existem diversas alternativas para isso. Como seu código é Python, um Django ou Flask resolveriam isso. O Django possui já autenticação e um baita controle de usuários integrado.
Algumas questões devem ser consideradas nesse backend (ou web service por assim dizer), como:

Segurança entre o aplicativo android e esse web service. Mesmo estando dentro de uma VPN, eu colocaria alguma autenticação, como "basic authentication" por exemplo;
Concorrência: como um arquivo excel (ainda mais xlsx pois possui compactação) está sendo editado por mais de uma fonte, você precisaria de algum tipo de trava para que não fosse editado por mais de uma fonte. Creio que um banco de dados seria o ideal, a primeira vista;
Histórico: editando um Arquivo excel diretamente, não há uma fonte de histórico confiável indicando quem fez o que no aplicativo.

Para banco de dados eu creio que um MySQL ou até um SQLite resolveriam, que também possuem drivers nativos para Django;
Comment: Muito obrigada!
Comecei a aprender programação a pouco tempo, e precisei desenvolver rápido esse programa para um comercio simples de venda de 1 item apenas, que irá abrir em breve.
Vou pesquisar sobre o MySQL para melhorar o sistema e sobre o Django.
Agradeço a atenção


Gostaria de deixar minha URL amigável em .htaccess

Question: Olá, estou tentando de várias formas tentando deixar a minha URL mais amigável porém não estou conseguindo deixar, ela esta assim:
http://meusite.com/single-product.php?aff_ext=1000&categoria=77&produto=548829
Gostaria de deixar ela assim:
http://meusite.com/single-product.php/sansung-galaxy-s6-4g
Com o exemplo acima eu gostaria de tirar todos aqueles GETs e trocar pelo nome do produto, porém para pegar a página de descrição do produto eu preciso dos GETs. Preciso de algo que camuflasse a URL apenas no navegador do usuário
Comment: Mas no caso terei varias categorias e varios produtos se eu for fazer 1 pra cada um não teria como
Answer: para o que você deseja as configurações de apache no seu <code>.htaccess</code> são as menores dificuldades que você terá, em recomendo o desenvolvimento de um pequeno sistema de MVC.
Para isto recomendo o seguinte link:
Criando um mini-framework PHP 5 com MVC
Créditos para nosso colega Matheus Moura, que nesta série de vídeos ensina muito bem, espero ter ajudado.
Comment: Obrigado Leandro foi muito útil, Deus abençoe vc!!!


How does Google Analytics calculate "Probability of Outperforming Original"?

Question: Here's an example content experiment in Google Analytics. Can anyone explain how to calculate that there's a 98.7% "Probability of Outperforming the Original"?
Comment: Like @Affine said, have you already read the [official documentation](https://support.google.com/analytics/answer/2844870?hl=en)?
Comment: Going to need more than that. They probably should have a description somewhere.
Comment: Though I will say it's not from a standard chi-square test of equal proportions. And the wording suggests they are using a Bayesian approach.
Answer: The percentage is calculated using Monte Carlo simulation, so reproducing the calculation here would not be easy. See https://support.google.com/analytics/answer/2844870?hl=en
Answer: It is not any basic or easy calculation to put here some equitation. Calculation of Google Experiments is based on the "problem" of Multi-armed Bandit.
This is a concept that describes any situation in which you want to conduct an experiment in such a way that you maximize your reward
Full description is available on Google Documentation.
Experiments based on multi-armed bandits are typically much more efficient than "classical" A-B experiments based on statistical-hypothesis testing. They're just as statistically valid, and in many circumstances they can produce answers far more quickly.
They're more efficient because they move traffic towards winning variations gradually, instead of forcing you to wait for a "final answer" at the end of an experiment.
They're faster because samples that would have gone to obviously inferior variations can be assigned to potential winners. The extra data collected on the high-performing variations can help separate the "good" arms from the "best" ones more quickly.
Calculation example is here.
I hope it helps you to understand a bit more how Google is calculating the winner.


Find cointegrating vectors and loadings from a trivariate VAR(1) equation

Question: I have the following process:
$\begin{bmatrix}
X_t \\
Y_t \\
Z_t \\
\end{bmatrix}
= \begin{bmatrix}
1 \\
0 \\
1 \\
\end{bmatrix}
+ \begin{bmatrix}
0.5 & 0.5 & 0 \\
0 & 1 & 0 \\
0 & 0 & 0.8 \\
\end{bmatrix}
\begin{bmatrix}
X_{t-1} \\
Y_{t-1} \\
Z_{t-1} \\
\end{bmatrix}
+ \begin{bmatrix}
\epsilon_{1t} \\
\epsilon_{2t} \\
\epsilon_{3t} \\
\end{bmatrix}
$
When calculating the error correction from I get the following impact matrix:
$\begin{bmatrix}
-0.5 &  0.5  & 0\\
0  &  0 & 0 \\
0  &   0 & -0.2 \\
\end{bmatrix}
$
Then, I know that the cointegrating rank is 2, and there are two linearly independent cointegrating vectors.
I should be able to decompose the above matrix into two $3 \times 2$ matrices $\alpha \beta^{T}$ where $\beta$ contains the cointegrating vectors as its columns. However, I cannot figure out how to do this. And I do not know how to find the cointegrating vectors. Any help would be much appreciated.
Comment: My apologies, accepted!
Answer: Checking out equation by equation
$$ \begin{aligned}
X_t &= 1 + 0.5 X_{t-1} + 0.5 &Y_{t-1}    &           &+ \epsilon_{1,t} \\
Y_t &=                       &Y_{t-1}    &           &+ \epsilon_{2,t} \\
Z_t &= 1   &                  &        + 0.8 Z_{t-1} &+ \epsilon_{3,t} \\
\end{aligned} $$
you quickly notice that $Z$ is affected only by its own history and is not affecting $X$ or $Y$. Hence, $Z$ is not cointegrated with the other two. Moreover, it is not even integrated as its autoregressive coefficient is smaller in magnitude than 1. So when it comes to cointegration, we can just remove $Z$ from the system.
$Y$ is driving itself as it depends only on its own history.
$X$ is being driven by $Y$ and own history.

By staring at the equations for $X$ and $Y$ long enough, one can make a guess that $X-Y$ will be integrated of order zero, I(0). Let us see if that works:
$$ (X_t-Y_t) = 1 + 0.5 (X_{t-1} - Y_{t-1}) + (\epsilon_{1,t} - \epsilon_{2,t}). $$
Let us denote $W:=X-Y$ and $u:=\epsilon_1-\epsilon_2$, then
$$ W_t = 1 + 0.5 W_{t-1} + u_t $$
which is I(0) because

the autoregressive coefficient is below 1 in magnitude;
the error term is I(0) since it is a sum of two I(0) terms.

So the cointegration vector $\beta=\begin{bmatrix} 1 \\ -1 \\ \end{bmatrix}$ for $(X,Y)$ (or $\tilde\beta=\begin{bmatrix} 1 \\ -1 \\ 0 \\ \end{bmatrix}$ for $(X,Y,Z)$) seems to work.

Now you have to find a vector $\alpha$ to premultiply to $(1,-1)$ to get the matrix $\begin{bmatrix} 0.5 & 0.5 \\ 0 & 1 \\ \end{bmatrix}$. That seems to be $\alpha=\begin{bmatrix} -0.5 \\ 0 \end{bmatrix}$.


Can I assign 2 different types to typescript interfaces?

Question: I have following interface structure to store travelers.
interface Person: {
    age: number,
    name: string
}

interface TravelersDirectory {
    [country: string]: Person[]
}
example:
    travelersDirectory = {
        'India': [
            {
                age: 30,
                name 'X'
            },
            {
                age: 35,
                name 'Y'
            },
        ]
    }

With the new change I am going to decouple persons from the travelers directory
to Persons and references will be stored in Travelers directory. The new interface will be :
interface Persons extends Array<Person>

But due to the business requirement travelersDirectory can keep either index (to Persons) or Person object
example:
    const persons = [
            {
                age: 30,
                name 'X'
            },
            {
                age: 35,
                name 'Y'
            },
        ];

    const travelersDirectory = [
        'India': [
            0,
            {
                age: 35,
                name 'Y'
            },
        ]
    ]

Is this possible? can both types(index and Person object) coexist? I tried to work out by making changes to travelersDirectory interface but it didnt work.
    Attempt 1:
    interface TravelersDirectory {
        [country: string]: Person[] | number[]
    }

Attempt2 :
    interface Persons extends Array<Person | number>

    interface TravelersDirectory {
        [country: string]: Persons
    }

How can I do it?
Note: The data structure used is symbolic and I can't redesign it. Only can workaround by playing with the interfaces
Check this link for exact problem https://stackblitz.com/edit/typescript-ypc59j
Comment: Attemp 2 should work
Comment: Attempt 2 works https://stackblitz.com/edit/typescript-tlexc7
Comment: when i use attempt2, I get error "property age does not exist on type number | Person"
Answer: The second attempt in the question is a correct way to type this, but it can be simplified to this:
interface TravelersDirectory {
  [country: string]: Array<Person | number>;
}

After some back-and-forth with OP, I found out the issue was somewhere else, ie this code:
function getName(travelersDirectory: TravelersDirectory, country: string, index: number) {
  return travelersDirectory[country][index].name;
}

This is because travelersDictionary[country][index] can be either a Person or a number, so the property name is not guaranteed to exist. To fix this, we need to guard against this and define what should happen if the result of travelersDictionary[country][index] is a number. We can do this by saving the result into a variable, and using typeof to check if the result is a number before we tell it what will happen if it's a Person.
function getName(travelersDirectory: TravelersDirectory, country: string, index: number) {
    const person = travelersDirectory[country][index];
    if (typeof person === "number") {
      // getName was called referencing a number instead of a Person.
      // Throw Error? Do nothing? Up to you
      throw Error("Can't get name of a number");
    } else {
      // Typescript is smart enough to understand that the variable `person` can't be a number
      // (because we guarded against it in the previous if-expression)
      // so now we can do person.name
      return person.name;
    }
}

Here's a Stackblitz demonstrating this
Answer: Based on your requirements the simplest solution is just to refer to the possible values in the TravelersDirectory itself:
interface TravelersDirectory {
    [country: string]: Array<Person | number>;
}

If you want it to be easier to read you could also use type aliases:
type PersonID = number;
type Persons = Array<Person | PersonID>;

interface TravelersDirectory {
    [country: string]: Persons
}

I personally think it's most readable just to use the type alias for the ID and declare the directory as follows:
type PersonID = number;

interface TravelersDirectory {
    [country: string]: Array<Person | PersonID>;
}

This also allows you to later change the person Id to something else like an object or string instead of a number if needed.
Comment: @atul You should specify that you're using the `TravelersDirectory` interface when assigning the variable. This works https://stackblitz.com/edit/typescript-tlexc7
Comment: @atul If `travelersDirectory[country][index]` is going to be either an object or a number, it means it can be a number. That's why `travelersDirectory[country][index].name` gives an error: it won't work if `travelersDirectory[country][index]` is a number. You need to guard against that case before you can assume it is an object of type Person. See my forked example https://stackblitz.com/edit/typescript-jhi5e9
Comment: @ritaj I'm using type aliases here instead of an interface that extends the types as in his examples. This makes the code more readable. Hardly deserves a downvote!
Comment: when I use  Array. I get error "type number is not assignable to type Person"
Comment: @atul Where you're declaring the TravelersDirectory, it should be const TravelersDirectory = { "india": [] } - you've currently declared it as const TravelersDirectory = [ "india": [] ]
Comment: I am trying on business project (different from the example). As soon as I made the change, the existing code gives so many errors which i mentioned earlier
Comment: @ShamPooSham travelersDirectory isn't a problem. I fixed it the question!
Comment: Thanks @ShamPooSham I edited your example. see the problem. https://stackblitz.com/edit/typescript-ypc59j
Comment: @atul in your latest example your code containing the error assumes that this.travelersDictionary[country][index] is a Person and will have a name property, but your change means it could just be a number, and numbers don't have a name property. What should your code do in this case?
Comment: exactly that was my original question. I want the person info either as object or a number(it will a reference to other directory). is it possible? The real use case is I get person data from external api I process it and add it to another directory. when I send back the same data I do merge from references.
Comment: Thank@ShamPooSham!  I was looking exactly for this! I would appreciate if you add this comment as new answer. It will be useful for everyone.
Comment: @atul I added an answer


How to change OCR from PyTesseract to AzureFormRecognizer

Question: I am currently experimenting with a code I found on GitHub to extract highlighted text from scanned text using OCR. I wanted to try changing the OCRs used. Currently, the code uses PyTesseract. I wanted to try to use AzureFormRecognizer. I am a beginner with OCR softwares and this is my first time using AzureFormRecognizer. I have tried to change PyTesseract to AzureFormRecognizer straight up, but it hasn't worked at all. Please help me with this problem.
Sorry for the very long code. And thank you for your time and consideration.
Code:
import pprint
import pytesseract
from pytesseract import Output
import cv2
import numpy as np
from collections import namedtuple
import re
from matplotlib import pyplot as plt

pytesseract.pytesseract.tesseract_cmd = r'PATH/TO/PYTESSERACT'

Rectangle = namedtuple('Rectangle', ['xmin', 'ymin', 'xmax', 'ymax'])
# It represents information about a word recognized by an OCR
# Word = namedtuple('Word', ['level', 'page_num',
#                   'block_num', 'par_num', 'line_num', 'word_num', 'top', 'left', 'width', 'height', 'conf', 'text'])

# https://stackoverflow.com/questions/27152904/calculate-overlapped-area-between-two-rectangles

class Levels:
    PAGE = 1
    BLOCK = 2
    PARAGRAPH = 3
    LINE = 4
    WORD = 5

def intersect_area(a, b):
    """Calcluate intersection area between two rectangles. Each rectangle has xmin, xmax, ymin, ymax fields."""
    dx = min(a.xmax, b.xmax) - max(a.xmin, b.xmin)
    dy = min(a.ymax, b.ymax) - max(a.ymin, b.ymin)

    return float(dx*dy) if (dx >= 0) and (dy >= 0) else 0.

def normalize_images(images):
    """Convert all images into 3-dimensional images via cv2.COLOR_GRAY2BGR."""
    return [cv2.cvtColor(image, cv2.COLOR_GRAY2BGR)
            if image.ndim == 2 else image for image in images]

def threshold_image(img_src):
    """Grayscale image and apply Otsu's threshold"""
    # Grayscale
    img_gray = cv2.cvtColor(img_src, cv2.COLOR_BGR2GRAY)
    # Binarisation and Otsu's threshold
    _, img_thresh = cv2.threshold(
        img_gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)

    return img_thresh, img_gray

def mask_image(img_src, lower, upper):
    """Convert image from RGB to HSV and create a mask for given lower and upper boundaries."""
    # RGB to HSV color space conversion
    img_hsv = cv2.cvtColor(img_src, cv2.COLOR_BGR2HSV)
    hsv_lower = np.array(lower, np.uint8)  # Lower HSV value
    hsv_upper = np.array(upper, np.uint8)  # Upper HSV value

    # Color segmentation with lower and upper threshold ranges to obtain a binary image
    img_mask = cv2.inRange(img_hsv, hsv_lower, hsv_upper)

    return img_mask, img_hsv

def apply_mask(img_src, img_mask):
    """Apply bitwise conjunction of source image and image mask."""

    img_result = cv2.bitwise_and(img_src, img_src, mask=img_mask)

    return img_result

def denoise_image(img_src):
    """Denoise image with a morphological transformation."""

    # Morphological transformations to remove small noise
    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5,5))
    img_denoise = cv2.morphologyEx(
        img_src, cv2.MORPH_OPEN, kernel, iterations=1)

    # img_contour = img_denoise.copy()

    #This will remove all the highlights and replace it with white, i.e., unhighlighted text
    # # Find highligted contour and fill them with white color
    # contours, hierarchy, = cv2.findContours(
    #     img_denoise, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    # # contours, hierarchy, = cv2.findContours(
    # #     img_mask, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)
    # for idx, c in enumerate(contours):
    #     # if(hierarchy[0][idx][3] != -1):  # Discard contours that are holes
    #     #     continue
    #     cv2.drawContours(img_contour, contours, idx,
    #                      (255, 255, 255), cv2.FILLED, 8, hierarchy)

    return img_denoise #, contours, hierarchy, img_contour

def draw_word_boundings(img_src, data_ocr, highlighted_words=False):
    """Draw word bounding boxes"""

    # Convert source image to RGB if it's grayscaled
    img_result = cv2.cvtColor(img_src, cv2.COLOR_GRAY2BGR) if img_src.ndim == 2 else img_src.copy()

    # Iterate through all words
    for i in range(len(data_ocr['text'])):
        # Skip for all non-word elements
        if data_ocr['level'][i] != Levels.WORD:
            continue
        if highlighted_words and not data_ocr['highlighted'][i]:
            continue
        # Get bounding box position and size of word
        (x, y, w, h) = (data_ocr['left'][i], data_ocr['top']
                        [i], data_ocr['width'][i], data_ocr['height'][i])
        # Draw bounding box in red
        cv2.rectangle(img_result, (x, y), (x + w, y + h), (0, 0, 255), 2)

    return img_result

def draw_contour_boundings(img_src, img_mask, threshold_area=400):
    """Draw contour bounding and contour bounding box"""
    # Contour detection
    contours, hierarchy, = cv2.findContours(
        img_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    # Create two copies of source image
    img_contour = img_src.copy()
    img_box = img_src.copy()

    for idx, c in enumerate(contours):
        # Skip small contours because its probably noise
        if  cv2.contourArea(c) < threshold_area:
            continue

        # Draw contour in red
        cv2.drawContours(img_contour, contours, idx, (0, 0, 255), 2, cv2.LINE_4, hierarchy)

        # Get bounding box position and size of contour
        x, y, w, h = cv2.boundingRect(c)
        # Draw bounding box in blue
        cv2.rectangle(img_box, (x, y), (x + w, y + h), (255, 0, 0), 2, cv2.LINE_AA, 0)

    return img_contour, img_box

def draw_contour_rectangles(img_contour, img_result, rect_width=10, rect_height=10, threshold_percentage=25):
    """Draw small rectangles within the contour if the respective rectangle area exceeds the defined threshold percentage."""

    # threshold for rectangle area
    threshold = (rect_width * rect_height * threshold_percentage) / 100
    contours, hierarchy, = cv2.findContours(
        img_contour, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    for idx, c in enumerate(contours):
        xmin, ymin, w, h = cv2.boundingRect(c)
        xmax = xmin + w
        ymax = ymin + h

        # Scan the image with in bounding boxes
        for x in range(xmin, xmax, rect_width):
            for y in range(ymin, ymax, rect_height):
                rect_roi = Rectangle(x, y, x+rect_width, y+rect_height)
                img_roi = img_contour[y:y+rect_height, x:x+rect_width]

                # count white pixels within region of interest
                count = cv2.countNonZero(img_roi)

                if count > threshold:
                    cv2.rectangle(img_result, (rect_roi.xmin, rect_roi.ymin),
                                  (rect_roi.xmax, rect_roi.ymax),
                                  (255, 0, 0), 1, cv2.LINE_AA, 0)

    return img_result

def find_highlighted_words(img_mask, data_ocr, threshold_percentage=25):
    """Find highlighted words by calculating how much of the words area contains white pixels compared to balack pixels."""

    # Initiliaze new column for highlight indicator
    data_ocr['highlighted'] = [False] * len(data_ocr['text'])

    for i in range(len(data_ocr['text'])):
        # Get bounding box position and size of word
        (x, y, w, h) = (data_ocr['left'][i], data_ocr['top']
                        [i], data_ocr['width'][i], data_ocr['height'][i])
        # Calculate threshold number of pixels for the area of the bounding box
        rect_threshold = (w * h * threshold_percentage) / 100
        # Select region of interest from image mask
        img_roi = img_mask[y:y+h, x:x+w]
        # Count white pixels in ROI
        count = cv2.countNonZero(img_roi)
        # Set word as highlighted if its white pixels exceeds the threshold value
        if count > rect_threshold:
            data_ocr['highlighted'][i] = True

    return data_ocr

def mark_highlighted_words(img_result, data_ocr):
    # draw rectangles for words
    for i in range(len(data_ocr['text'])):
        if data_ocr['level'][i] != Levels.WORD:
            continue
        if not data_ocr['highlighted'][i]:
            continue

        (x, y, w, h) = (data_ocr['left'][i], data_ocr['top']
                        [i], data_ocr['width'][i], data_ocr['height'][i])
        rect_roi = Rectangle(x, y, x+w, y+h)

        cv2.rectangle(img_result, (rect_roi.xmin, rect_roi.ymin),
                      (rect_roi.xmax, rect_roi.ymax), (0, 255, 0), 2)

    return img_result

def draw_text(
    img,
    *,
    text,
    uv_top_left,
    color=(255, 255, 255),
    fontScale=0.5,
    thickness=1,
    fontFace=cv2.FONT_HERSHEY_COMPLEX,
    outline_color=(0, 0, 0),
    line_spacing=1.5,
):
    """
    Draws multiline with an outline.
    https://gist.github.com/EricCousineau-TRI/596f04c83da9b82d0389d3ea1d782592
    """
    assert isinstance(text, str)

    uv_top_left = np.array(uv_top_left, dtype=float)
    assert uv_top_left.shape == (2,)

    for line in text.splitlines():
        (w, h), _ = cv2.getTextSize(
            text=line,
            fontFace=fontFace,
            fontScale=fontScale,
            thickness=thickness,
        )
        uv_bottom_left_i = uv_top_left + [0, h]
        org = tuple(uv_bottom_left_i.astype(int))

        if outline_color is not None:
            cv2.putText(
                img,
                text=line,
                org=org,
                fontFace=fontFace,
                fontScale=fontScale,
                color=outline_color,
                thickness=thickness * 3,
                lineType=cv2.LINE_AA,
            )
        cv2.putText(
            img,
            text=line,
            org=org,
            fontFace=fontFace,
            fontScale=fontScale,
            color=color,
            thickness=thickness,
            lineType=cv2.LINE_AA,
        )

        uv_top_left += [0, h * line_spacing]

def draw_separation_lines(img_src, images=1):
    height, width = img_src.shape[:2]
    img_result = img_src.copy()

    for i in range(1, images):
        x = int((width / images) * i)
        img_result = cv2.line(img_result, (x, 0), (x, height), (255, 255, 255), thickness=2)

    return img_result

def words_to_string(data_ocr):
    word_list = []
    line_breaks = (Levels.PAGE, Levels.BLOCK, Levels.PARAGRAPH, Levels.LINE)

    for i in range(len(data_ocr['text'])):

        #This is all the information for each word that has been read by OCR
        # print("Level: {}; Page: {}; Block: {}; Paragraph: {}; Line: {}; Word: {}; Highlighted: {} Text: {}".format(
        #     data_ocr['level'][i],
        #     data_ocr['page_num'][i],
        #     data_ocr['block_num'][i],
        #     data_ocr['par_num'][i],
        #     data_ocr['line_num'][i],
        #     data_ocr['word_num'][i],
        #     data_ocr['highlighted'][i],
        #     data_ocr['text'][i]))

        if data_ocr['level'][i] in line_breaks:
            word_list.append("\n")
            continue

        text = data_ocr['text'][i].strip()

        if text and data_ocr['highlighted'][i]:
            word_list.append(text + " ")

    # concat all words into one string
    word_string = "".join(word_list)
    # repalce multiple consecutive newlines with one single newline
    word_string = re.sub(r'\n+', '\n', word_string).strip()

    return word_string

def image_to_data(img_src):
    return pytesseract.image_to_data(
        img_src, lang='eng', config='--psm 6', output_type=Output.DICT)

def image_to_string(img_src):
    return pytesseract.image_to_string(
        img_src, lang='eng', config='--psm 6')

def main(args):
    img_input = str(args.img_input)

    # Load image
    img_orig = cv2.imread(img_input)

    # Grayscale and apply Otsu's threshold
    img_thresh, img_gray = threshold_image(img_orig)

    # get ocr data
    data_ocr = image_to_data(img_thresh)

    # yellow highlight colour range
    hsv_lower = [22, 30, 30]
    hsv_upper = [45, 255, 255]

    # Color segmentation
    img_mask, img_hsv = mask_image(
        img_orig, hsv_lower, hsv_upper)

    # Noise reduction
    img_mask_denoised = denoise_image(
        img_mask)

    # Apply mask on original image
    img_orig_masked = apply_mask(img_orig, img_mask=img_mask_denoised)

    # Apply mask on thresholded image
    img_thresh_masked = apply_mask(img_thresh, img_mask=img_mask_denoised)

    data_ocr = find_highlighted_words(
        img_mask_denoised, data_ocr, threshold_percentage=25)

    # Draw contour boundings and bounding boxes
    img_orig_bounding_contour, img_orig_bounding_box = draw_contour_boundings(img_orig, img_mask=img_mask_denoised)

    # Draw word boundings for highlighted words
    img_thresh_word_boundings = draw_word_boundings(img_thresh, data_ocr, highlighted_words=True)
    img_mask_word_boundings = draw_word_boundings(img_mask_denoised, data_ocr, highlighted_words=True)
    img_orig_word_boundings = draw_word_boundings(img_orig, data_ocr, highlighted_words=True)

    # draw all ocr rect
    img_orig_all_ocr = draw_word_boundings(img_orig.copy(), data_ocr)
    img_thresh_all_ocr = draw_word_boundings(img_thresh.copy(), data_ocr)

    img_orig_rects = draw_contour_rectangles(
        img_mask, img_orig.copy())

    img_orig_ocr = mark_highlighted_words(
        img_orig.copy(), data_ocr)

    string_ocr = pytesseract.image_to_string(
        img_thresh, lang='eng', config='--psm 6')

    #print("\n\n")
    #print(string_ocr)
    #print("\n\n")

    str_highlight = words_to_string(data_ocr)
    print("\n\n")
    print(str_highlight)
    print("\n\n")

    height, width = img_orig.shape[:2]
    img_orig_all_text = np.zeros([height,width,3],dtype=np.uint8)
    img_orig_all_text.fill(255)
    string_ocr = string_ocr.replace("'", "'")
    string_ocr = string_ocr.replace("'", "'")
    draw_text(img_orig_all_text, text=string_ocr, color=(0,0,0), outline_color=None, uv_top_left=(100,100), fontScale=1.5,thickness=2)

    img_orig_highlighted_text = np.zeros([height,width,3],dtype=np.uint8)
    img_orig_highlighted_text.fill(255)
    # string_ocr = string_ocr.replace("'", "'")
    # string_ocr = string_ocr.replace("'", "'")
    draw_text(img_orig_highlighted_text, text=str_highlight, color=(0,0,0), outline_color=None, uv_top_left=(100,500), fontScale=1.5,thickness=2)

    img_thresholding = np.concatenate(normalize_images(
        (
            img_orig,
            img_gray,
            img_thresh,
        )), axis=1)

    # draw white line between images
    img_thresholding = draw_separation_lines(img_thresholding, images=3)
    cv2.imshow('thresholding', img_thresholding)
    cv2.imwrite("output/thresholding.png", img_thresholding)
    cv2.waitKey(0)

    img_extract_all = np.concatenate(normalize_images(
        (
            img_orig_all_ocr,
            img_orig_all_text,
        )), axis=1)

    img_extract_all = draw_separation_lines(img_extract_all, images=2)
    cv2.imshow('extract_all', img_extract_all)
    cv2.imwrite("output/extract_all.png", img_extract_all)
    cv2.waitKey(0)

    img_color_segmentation = np.concatenate(normalize_images(
        (
            img_orig,
            img_hsv,
            img_mask,

        )), axis=1)

    img_color_segmentation = draw_separation_lines(img_color_segmentation, images=3)
    cv2.imshow('img_color_segmentation', img_color_segmentation)
    cv2.imwrite("output/img_color_segmentation.png", img_color_segmentation)
    cv2.waitKey(0)

    img_noise_reduction = np.concatenate(normalize_images(
    (
        img_mask,
        img_mask_denoised

    )), axis=1)

    img_noise_reduction = draw_separation_lines(img_noise_reduction, images=2)
    cv2.imshow('img_noise_reduction', img_noise_reduction)
    cv2.imwrite("output/img_noise_reduction.png", img_noise_reduction)
    cv2.waitKey(0)

    img_orig_and_mask = np.concatenate(normalize_images(
    (
        img_orig_masked,
        img_thresh_masked

    )), axis=1)

    img_orig_and_mask = draw_separation_lines(img_orig_and_mask, images=2)
    cv2.imshow('img_orig_and_mask', img_orig_and_mask)
    cv2.imwrite("output/img_orig_and_mask.png", img_orig_and_mask)
    cv2.waitKey(0)

    img_contour_and_bounding = np.concatenate(normalize_images(
    (
        img_orig_bounding_contour,
        img_orig_bounding_box,

    )), axis=1)

    img_contour_and_bounding = draw_separation_lines(img_contour_and_bounding, images=2)
    cv2.imshow('img_contour_and_bounding', img_contour_and_bounding)
    cv2.imwrite("output/img_contour_and_bounding.png", img_contour_and_bounding)
    cv2.waitKey(0)

    img_final = np.concatenate(normalize_images(
    (
        img_mask_word_boundings,
        img_orig_word_boundings,
        img_orig_highlighted_text

    )), axis=1)

    img_final = draw_separation_lines(img_final, images=3)
    cv2.imshow('img_final', img_final)
    cv2.imwrite("output/img_final.png", img_final)
    cv2.waitKey(0)

    img_title = np.concatenate(normalize_images(
    (
        img_orig,
        img_orig_all_ocr,
        img_orig_bounding_contour,
        img_orig_word_boundings

    )), axis=1)

    img_title = draw_separation_lines(img_title, images=4)
    cv2.imshow('img_title', img_title)
    cv2.imwrite("output/img_title.png", img_title)
    cv2.waitKey(0)

if __name__ == "__main__":

    from argparse import ArgumentParser
    from pathlib import Path

    parser = ArgumentParser(description=__doc__)
    parser.add_argument('img_input', type=Path, help="Input image")
    args = parser.parse_args()
    main(args)

Thank you
Answer: Since Form Recognizer API returns a different data structure than PyTesseract, so you'll need to modify the additional code to work with the new data structure.
Below is sample code snippet that can be used to extract text and bounding box.
from azure.core.credentials import AzureKeyCredential
from azure.ai.formrecognizer import FormRecognizerClient

# Replace with your Form Recognizer endpoint and key
endpoint = "https://<Name>.cognitiveservices.azure.com/"
key = "<KEY>"

form_recognizer_client = FormRecognizerClient(endpoint, AzureKeyCredential(key))

def azure_form_recognizer_ocr(image):
    with open(image, "rb") as image_stream:
        poller = form_recognizer_client.begin_recognize_content(image_stream)
        result = poller.result()

    words = []
    for page in result:
        for line in page.lines:
            for word in line.words:
                words.append({
                    'text': word.text,
                    'bounding_box': word.bounding_box
                })

    return words

Also below is sample code snippet to update the image with bounding box and extracted text:
import cv2
def save_image_with_bounding_boxes(image_path, words, output_path):
    image = cv2.imread(image_path)

    for word in words:
        bounding_box = word['bounding_box']
        text = word['text']

        # Draw bounding box
        pts = np.array(bounding_box, np.int32)
        pts = pts.reshape((-1, 1, 2))
        cv2.polylines(image, [pts], True, (0, 255, 0), 2)

        # Display text
        x, y = int(bounding_box[0][0]), int(bounding_box[0][1])
        cv2.putText(image, text, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 1)

    cv2.imwrite(output_path, image)

With above code snippet I was able to get required results.
image_path =  "sample_invoice.jpg"
words = azure_form_recognizer_ocr(image_path)
save_image_with_bounding_boxes(image_path, words, "sample_invoicev-updated.jpg")

For more details you can check this documentation.
Comment: I tried using bounding boxes but contour bounding have been working alot better. For example if the highlighted text is from `bounding boxes` to `highlighted text` in this comment. The contour bounding will encapsulate only that much but the bounding box will cover alot of unnecessary words so as to "complete" the rectangle. I hope you understand what I'm trying to say.


Restricting Video upload to mp4 format alone - in media module

Question: I have been struggling put restriction for uploading video to upload only mp4 videos in media module, other media content like image etc. can be uploaded, but I need to put restriction for video type alone.
I am newbie in Drupal, can some one help me in this, what are the places I need to change in media module.

I would really appreciate any help on this. I did found sites\all\modules\media\includes\media.pages.inc file which had a function media_add_upload_validate($form, &$form_state) also then I found sites\all\modules\media\includes\media.variables.inc which had function media_variable_default and media_variable_get. Then I got lost. I am not sure if these are the correct files where I need to make the changes. Also I was wondering if I have to make change in Drupal core module to do the video upload restriction to mp4 perfectly.
Thanks
Comment: Thanks for whoever has up-voted this question to encourage me :)
Comment: @Ajit Thanks for editing, really sorry for errors in asking question.
Comment: No need to apologize. We all make mistakes ;-)
Answer: Go to admin/config/media/browser to change settings.
Comment: WOW :D ur awesome @Anil Sagar !!!! just one quick question will this modification be reflect in all the places or do i have to some other place as well, to make sure upload and error messages are changed correctly
Comment: What do you mean by all places ?
Comment: by all places i mean all the error messages which are displayed when i tried to upload other files like flv or mpeg??

Just wanted to make sure making change in this place is enough. Thank you so much for quick reply
Comment: Yes, It's taken care by the module... The error messages that you see are rendered from a template..
Comment: It is working great but it is taking time to show error, It is waiting for file to get uploaded and only after that it shows the error is there any way to show the error before file gets uploaded.


Sharing variables between files in node.js

Question: I want to make "variable sharing" in node.js but I cannot find a working way to do that.
My aim is to be able to change variables from an another file. For example, I have a in my main file but after doing something in another file (test.js), a should change its value in the main file. Is it possible to accomplish and how?
I have tried this code but it does not seem to work.
main.js
let a = 10;
module.exports.test = a;
console.log(a);
require('./test.js');
console.log(a);

test.js
let b = require('./main.js').test;
b = 15;

Answer: Other answers given here suggest using globals, but you should avoid use of globals for a whole host of reasons which I won't go into here, but are well documented.
The modular and safe way to share data is to put it in an object (as properties of an object) and then export that object from one module and import it into any others that want access to it. Since the exported object is truly shared, any update to any property on that object will be immediately available to all others who have a reference to the same object.
shared-data.js
module.exports = {a: 10};

test.js
let obj = require('./shared-data.js');
++obj.a;

main.js
let obj = require('./shared-data.js');
console.log("main1: ", obj.a);
++obj.a;
console.log("main2: ", obj.a);

require('./test.js');
console.log("main3: ", obj.a);

This will output:
main1: 10
main2: 11
main3: 12

Because test.js is operating on the shared data that shared-data.js exports
Answer: You can just use global variables. See more here
main.js
global.a = 10;
console.log(global.a); // 10
require('./test.js');
console.log(global.a); // 15

test.js
console.log(global.a) // 10
global.a = 15

Comment: Globals are not recommended in nodejs as it wrecks various goals of modules (like the ability to test a module independently), particularly when data can be shared in a modular way just fine that doesn't have the drawbacks of globals.
Answer: The bad idea here is think when you call ./test, magically variable a will be updated.
Here you can use global variables (example)
Something like:
main.js
global.a = 10
//call test
console.log(global.a)) // 15

test.js
global.a = 15

And, following you idea, calling another class and using these values, you can also do something like this:
main.js
var a = 10
a = require('./test').a //Note that here you are overwriting your 'a' variable
console.log(a) //15

test.js
var b = 15
module.exports.a = b

So, into main.js you assign a value that is from module.exports.a, i.e. you assing a = 15.
Comment: Globals are not recommended in nodejs as it wrecks various goals of modules (like the ability to test a module independently), particularly when data can be shared in a modular way just fine that doesn't have the drawbacks of globals.


SSH agent forwarding when Host and Hostname different

Question: On my client I have an SSH agent setup and the following example config
Host gitserver
  Hostname gitserver.example.com
  ForwardAgent yes
  User git
  IdentityFile C:\Users\user\.ssh\id_rsa.pub
  IdentitiesOnly yes

On the first hop server that I wish to forward my agent through, how do I properly utilize forwarding without brute force checking all the identities that my SSH agent has without getting a too many authentication failures error?
I can get it to work if I limit the SSH agent to contain 5 or less keys as that's within the allowable amount of authentication attempts.
If I try to use the gitserver Host alias on the server, it doesn't know that it means what it does on the clients SSH config.
Do I need to have a proper SSH config setup on the server for this host?
There must be a more portable option than having to configure every server I wish to use agent forwarding with.
I don't think this is a Windows specific problem as I the IdentitiesOnly yes works perfectly fine with larger key stores in the SSH agent. It seems to be an issue with forwarding the correct information to the first hop server.
I hope my question is clear enough to comprehend my problem.
Comment: Why do you have more than one identity file in the agent? If you change the order of the keys, and add the identity that you need first on top, do you still have the issue?
Comment: Because I can? Is this really an unusual use case? I don't have this problem when connecting directly to a server with multiple identity files for hosts in the agent when directly connecting to the end server, only when forwarding the agent through an intermediate server. I want to know if it's possible to make this easy when I am using forwarding.
Answer: Firstly, I apologize if it sounds as if I am making assumptions, as it is not my intention to insult anyone's intellegence.
I'm also not completely positive that I fully understand your issue, but since there are no other answers, as of yet, I thought I'd give it a go.
Unfortunately, without having more information, regarding your Nwtwork & DNS configuration, it's difficult to determine exactly where the problem lies.
Therefore, I'm simply going to list off, some suggestions and resources, for you to utilize, if they are relevant, of course.
Firstly, if the Machines in question, are not currently on a Domain, I would consider replacing the FQDN in the "Hostname" Setting with the Machine's IP Address (like the example, below).
Host Hostname
      Hostname 192.168.0.250
      ForwardAgent yes
      User username
      IdentityFile C:\Users\username\.ssh\id_rsa

You may also want to run the "ssh-add -L" Command, to confirm that your SSH Agent is Running and is holding your Key(s).
Additional Info/Details, regarding the aforementioned Command, can be obtained by following the Link below.
https://superuser.com/a/1141035
As for running OpenSSH Agent Forwarding, in Windows, you may want to review the following articles, as their are some important steps, that are specific to Windows 10/11.
https://richardballard.co.uk/ssh-keys-on-windows-10/
http://blog.zencoffee.org/2022/11/openssh-on-windows-11/
Lastly, it should be noted that SSH Agent Forwarding wasn't really supported on Windows 10, until relatively recently.
That being said, you may want to verify that your Windows and OpenSSH Versions are compatible, in regard to the SSH Agent Forwarding Function.
I hope that this is, at least, somewhat helpful.
Comment: Agent forwarding works, but I don't know how to make the end server request the proper identity to authenticate against without trying every single agent identity before the end server errors out from too many attempts.
Comment: Ok, makes sense. I think you're on the right path, in regard to the "IdentitiesOnly=Yes" Option.

https://superuser.com/questions/268776/how-do-i-configure-ssh-so-it-doesnt-try-all-the-identity-files-automatically
Answer: To answer your question, however, if you read through the Pros & Cons, it seems to suggest that Automation may not be possible.
Cons of SSH Agent Forwarding:

Users must SSH in to deploy; automated deploy processes can't be used.
SSH agent forwarding can be troublesome to run for Windows users.

https://docs.github.com/en/authentication/connecting-to-github-with-ssh/managing-deploy-keys.
Comment: My use case doesn't require automation where private key storage on an automation server is required, but thanks for pointing that out.


Does Strongarm need to be enabled on Production site using Features?

Question: I'm using Features in order to make my site content configuration exportable for purposes of staging my server. I'll be using Strongarm to make some of the site variables exposed for management in a feature.
Does the Strongarm module need to be enabled on my live production site in order for the active features to be able to present and set the variables which I have encapsulated within them?
Or, does Strongarm only need to be enabled on my dev server where and when I am creating my features components?
Answer: Yes, you need the strongarm module on production site as the module implements hook_features_revert and hook_features_rebuild which is needed to do any reverts to the variables you have featurized or to apply new variables that u have introduced in your feature.
Comment: The features created that uses strongarm will actually be created with a dependency to the strongarm module


if $f'(x)\rightarrow L$ as $ x \rightarrow \infty$, $-\infty \leq L \leq \infty $ then $ f(x)/x \rightarrow L $ as $x \rightarrow \infty$

Question: If $f$ is differentiable on $(a,\infty)$, Show that if $f'(x)\rightarrow L$ as $ x \rightarrow \infty$, $-\infty \leq L \leq \infty $  then  $ f(x)/x \rightarrow L $ as $x \rightarrow \infty$.
Deduce further that if $f(x) \rightarrow M$ as $ x\rightarrow \infty$ , and $ f'(x)\rightarrow L $ as $ x \rightarrow\infty $ then $ L = 0$
For the first part I tried converting $f(x)$ to $F(\frac{1}{x})$ and $x \rightarrow 0$ and then using L'Hospital's rule but I am getting stuck. How do I proceed with this problem ?
Answer: For all $\epsilon > 0$, there exists $K > 0$ such that for all $x > K$
$$|f'(x) -L| < \frac{\epsilon}{2},$$
and, if $L \neq 0$,
$$|f'(x)| < \frac{3|L|}{2}$$
By the MVT, there exists $\xi > K$ such that ,
$$f(x)=  f(K) + f'(\xi)(x-K),$$
and
$$\frac{f(x)}{x} = \frac{f(K)}{x} + f'(\xi)(1-K/x).$$
Hence,
$$\left|\frac{f(x)}{x}-L\right| \leq \left|\frac{f(K)}{x}\right| + \left|f'(\xi)\frac{K}{x}\right| + |f'(\xi) - L|\\<\left|\frac{f(K)}{x}\right| + \frac{3|L|}{2}\left|\frac{K}{x}\right| + \frac{\epsilon}{2}.$$
Then for $x$ sufficiently large,
$$\frac1{|x|} \left( |f(K)| + \frac{3}{2}|L||K| \right) < \frac{\epsilon}{2},$$
and
$$\left|\frac{f(x)}{x}-L\right| < \epsilon.$$
Therefore,
$$\lim_{x \rightarrow \infty}\frac{f(x)}{x}=L.$$
A similar argument can be used if $L = 0$.
For the second part, apply L'Hospitals rule:
$$M= \lim_{x \rightarrow \infty}f(x) = \lim_{x \rightarrow \infty}\frac{e^xf(x)}{e^x}\\=\lim_{x \rightarrow \infty}[f(x) + f'(x)] = M + L, $$
and conclude that $L = 0$.
Comment: No need to use L'Hospital for second part. Just note that $f(x+1)-f(x)=f'(c)$ by MVT and taking limit as $x\to\infty$ we get $M-M=L$ or $L=0$. +1
Comment: @ParamanandSingh: Thanks.  Good idea.


Bootstrap-Table Extension - Dropdown in Row Pops Under Table Container

Question: I am using a bootstrap dropdown in each row of a table that uses the bootstrap-table extension written by wenzhixin. The dropdown itself works fine, however, when I open a dropdown near the bottom of the table it shows the vertical scrollbar and the options pop under the containing div for the table. I've been playing with the CSS for a while with no joy.
Has anyone ran into this issue and found a solution?
Answer: Works well if you use the bootstrap-table-contextmenu extension
https://github.com/prograhammer/bootstrap-table-contextmenu
This to create the button That toggle the dropdown

Edit

Reset

</ul

In you table you add :

Javascript :
$(function() {
    $("#userstable").bootstrapTable({
        pagination: true,
        pageSize: 10,
        pageList: [10, 25, 50, 'All'],
        search: "true",
        showRefresh:"true",
        url: "api/users/{{user.userId}}/{{user.role}}",
        contextMenu: '#userstable-context-menu',
        contextMenuButton: '.userstable-button'
    });
})

$('#userstable').on('contextmenu-item.bs.table', function (e, row, $el) {
        if($el.data("item")== "edit"){
            var x = "do something";
        }
}

function editFormatter(value, row, index) {
        return [
            '
',
            '<button type="button" class="btn btn-default dropdown-toggle userstable-button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">',
            '',
            'Toggle Dropdown',
            '</button>
'
            ].join('');
    }

Answer: This may be slightly "hackish" but it's straightforward and simple. The extension creates the table with a fixed-table-body class. Once that's removed it renders without constraining bootstrap dropdowns.
$('#table').bootstrapTable({
    onPostBody: function(data) {
        $('#table')
            .find('.fixed-table-body')
            .removeClass('fixed-table-body');
    }
});


End a task if the windows form is also terminated through task manager

Question: I have a login windows form that pops up when I open MS Access. If the user decides to leave, I have a cancel button that closes the application and MS Access:
private void button2_Click(object sender, EventArgs e)
{
    Application.Exit();
}

But I also want to add that if the user terminates the windows form, it will also terminate MS Access.
ie., if windowForm terminated, then Application.Exit
Comment: Did you try the Form.Closing event? https://msdn.microsoft.com/en-us/library/system.windows.forms.form.closing.aspx
Comment: I think Closing event is not gonna fire if the user uses End Process. Looks like mission impossible to me
Comment: Look at `OnClosing` Event.
Comment: Try to catch WM_CLOSE or similar WndProc messages. We tried but was not successful. If its an end process from task manager it is not logical to handle it :)
Answer: Add a function to the FormClosing event in the Event Properties of your Form or manually:
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Form1_FormClosing);

And then write:
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    Application.Exit();
}

Comment: This line was the key: "this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Form1_FormClosing); "  I was only using Form1_FormClosing but it wasn't exiting out. Thank you!


Combining probabilities from multiple observations

Question: Given a number of probabilities taken from a large number of recorded football games.

A: Chance of WIN given 6 corners: 0.6
B: Chance of WIN given 2 goals: 0.6
C: Chance of LOSS given 2 red cards: 0.7

Is it possible to calculate an estimate for the chance of a WIN given 6 corners, 2 goals and 2 red cards?
Answer: I am afraid it is not because the chance of corners and goals are most likely correlated (3 corners 1 goal, I think is the saying).
If corner and goal are highly correlated, then the information that a team got 2 goals doesn't tell us much more about its win probability after we already know that they have 6 corners. For perfect correlation actually P(6 corners) = P(6 corners and 2 goals) = 0.6.
For the completely uncorrelated case P(6 corners and 2 goals) = $1 - (1-0.6)^2 =0.84$ (basically a Bernoulli trial with two draws).
But as we don't know the correlation between corners and goals, we cannot say which of these two (or any probabilities in between) is true. Thus my answer is that it is not possible.


Ruby inject until sum exceeds a set value and return the index where this occurs

Question: With the following array and value:
v = 50
a = [10, 20, 25, 10, 15]

I want to iterate through the array adding up the values until the sum of these values exceeds the variable v. And then I want to be able to return the index in the array where that occurred. so...
10 + 20 + 25 = 55 (which is the first point which the sum is greater that 'v')
so index = 2
Thanks for your help
Answer: For the sum:
a.inject do |sum,n|
  break sum if sum > v
  sum + n
end

For the index, idea is the same - you use the memo as an array and keep the sum in the first element:
a.inject([0,-1]) do |memo,n|
  break [memo[0], memo[1]] if memo[0] > v
  [memo[0]+n, memo[1]+1]
end

you need to look at the array after that
Comment: thanks, that works now.. didn't realise you could pass 'multiple memos' using an array!
Comment: @wawmsey: that is an important realization! Yes, `inject` reduces an `Enumerable` down to a single value, however, that single value can be as complex as you want it to be … for example, itself an `Enumerable` or an `Array` or a `Hash` or …
Comment: He's looking for the index at the point it passes, not the sum; which is what makes this tricky (inject doesn't pass index).
Comment: thanks, that returns sum that first exceeds v, is it possible to return the index of the array that this occurred at?
Answer: A couple more ways
a.each_with_index.inject 0 do |acc, (n, idx)|
     break idx - 1 if acc > v
     acc + n
end

or
a.to_enum.with_index(-1).inject 0 do |acc, (n, idx)|
     next acc + n if acc < v
     break idx
end

Answer: I think you'd have to inject over the indexes and access the outside array, since inject does not pass along the index; like so:
a.each_index.inject do |memo, i|
  break i if memo > v
  memo + a[i]
end


Why do the courses at Stanford use the lazy initialisation?

Question: Why does the course at Stanford use the lazy initialization for all getters?
Is this correct? Does it have any real advantage?
One advantage (for me) is that the init method can become much shorter and you need not check if a variable is allocated.
Comment: Maybe not an exact duplicate, but definitely related: http://stackoverflow.com/q/10739726/620197
Answer: The idea is to load resources on demand. This way everything loads faster and when needed. In the cases it's not used, it doesn't allocate additional memory.
Comment: ... which ends up moving the cost of initialization to being a side-effect of primary app operations, leading to oft difficult to optimize performance issues and, less often, initialization ordering dependencies that are total pain to debug.
Comment: @bbum ok.... but when i read this
[link](http://stackoverflow.com/questions/17095452/method-is-not-being-called)
and
[link](http://stackoverflow.com/questions/20522624/override-getter-only-needs-synthesize)
I have come to doubt if use lazy everywhere.
Comment: Everywhere is not an option. Everything is case-specific. As @bbum says go can meet other issues. Experience is what teaches you how to approach each situation.
Comment: @graver yes, but stanford use lazy everywhere.... why? Paul Hegarty use lazy also when the getter is call immediately after application start
Comment: The projects they demonstrate are too simple to generalise. It's probably just to teach the students about the lazy instantiation. Just a thought.
Comment: Exactly;  lazy initialization works -- and appears to be a great convenience -- in the context of the Stanford courses for the exact reason @graver mentions.    In the real world?   As project complexity grows, having indeterminately ordered code execution will lead to nothing but pain.
Comment: In the Apple ecosystem, lazy init is pretty rare. This is likely the instructor bringing some other paradigm over.
Comment: @@Michael I not too sure of this.


Understanding multiple linear regression residuals

Question: I'm a bit confused whether residual vectors in OLS are orthogonal to every vector in X.
The problem I have is: Which of the following are true statements for our multiple linear regression with datapoints as rows of design matrix X, label vector Y, and using the model Ŷ = X̂.
I can understand that the residual vector e = Y - Ŷ is orthogonal to Y. And to me, it would make sense for the residual vector e = Y - Ŷ to also be orthogonal to some cases of vector in X. But what about every?
Any help would be appreciated.
I reference this diagram:
Comment: *"I can understand that the residual vector e = Y - Ŷ is orthogonal to Y"* is not correct: you may have intended *"orthogonal to Ŷ"*.  What is true with ordinary linear regression is that $\sum (Y - \hat Y)\hat Y =0$ i.e. $(\mathbf{Y}-\mathbf{\hat Y})\cdot \mathbf{\hat Y}=0$, equivalent to saying the covariance of $Y - \hat Y$ and $\hat Y$ is $0$; if this was not the case then you could reduce $\sum (Y - \hat Y)^2$ by changing $\hat Y$. Similarly and for the same reason,  $\sum (Y - \hat Y)X_1=0$ and $\sum (Y - \hat Y)X_1=0$ etc. and equivalently with the covariances.
Answer: Its been a long time since I've had to do some linear algebra, so forgive me if I've forgotten some of it.  Let's begin by assuming that $X$ is full rank and $\operatorname{rnk}(X)=p<n$.
Minimizing the loss means
$$ \nabla R = 0 \>.$$
Note that $\nabla R$ in terms of $X$ and $y$ is
$$ \nabla R = -2X^T (y- X\theta) $$
Note that $e = y - X\theta$.  This means that $y-X\theta$ is in the null space of $X^T$, so the residual is orthogonal to the columns of $X$.  Those columns span some subspace of $\mathbb{R}^n$ (the blue plane in your image).  So since the residual is orthogonal to the columns, and the columns are linearly independent, it is orthogonal to all linear combinations of those columns. In particular, it is orthogonal to the prediction (the closest vector in the plane to $y$).
Answer: Under OLS the residual is orthogonal to every column in the design matrix
To understand this issue, it is worth understanding the concept of the column space of the design matrix $\mathbf{x}$.  This is the space spanned by linear combinations of the column vectors in the design matrix, so it represents every possible vector you can form via the linear transformation $\mathbf{x} \boldsymbol{\theta}$.  In your diagram, the column space is the blue region.
When you fit the regression model using OLS estimation, this method is equivalent to forming the predicted response as the projection of $\mathbf{y}$ onto the column space of $\mathbf{x}$.  In fact, the hat matrix $\mathbf{h} = \mathbf{x} (\mathbf{x}^\text{T} \mathbf{x})^{-1} \mathbf{x}^\text{T}$ is the projection matrix that maps the actual response vector onto the predicted response vector.  This orthogonal projection is shown in the diagram in your question.  Since the fitted model is formed by an orthogonal projection, the residual vector is orthogonal to the column space of $\mathbf{x}$ which means it is orthogonal to every column of $\mathbf{x}$ (and therefore also orthonogal to the predicted response vector $\hat{\mathbf{y}}$).
Answer: Assuming $X$ is full rank, you can see it in terms of the hat matrix $H = X(X^\top X)^{-1}X^\top$. This matrix is an orthogonal projection matrix onto the column space of $X$.
The estimate of $y$ is $\hat{y}=X\hat{\theta}=Hy$. The residual is $e = y - \hat{y} = (I-H)y$. The matrix $(I-H)$ is an orthogonal projection matrix onto the orthogonal complement of the column space of $X$, so the residual vector $e$ is orthogonal to every vector in the column space of $X$.


Varnishncsa for Varnish 4 split log by Vhost

Question: In the varnish 3, varnishncsa can support -m option (-m tag:regex only list records where tag matches regex. Multiple -m options are AND-ed together. ). After upgraded to varnish 4, I cannot find the -m option in varnish 4. Is it any easy way to upgrade from 3 to 4. Please advice.
Thanks.
Answer: You can split by different hosts using:
<code>varnishncsa -q "ReqHeader ~ '^Host: .*\.example1.com'"
varnishncsa -q "ReqHeader ~ '^Host: .*\.example2.com'"
</code>


proving idempotent central modulo of matrices

Question: Let $R$ be a ring, let $I$ be an ideal of $R$, and let $u\in R$ be idempotent modulo $I$ (that is, $u^{2}-u\in I$). Then $u$ can be lifted to an idempotent in $R$ in case there is an idempotent $e$ in $R$ with $e-u \in I$.
I want to know that if $R$ is the ring of $n\times n$ upper triangular matrice over a field $\mathbb{Q}$ and if $J$ is the ideal of matrices having zero on the diagonal, then
there are idempotents that are central modulo (in the centre) $J$ that can not be lifted to central idempotents of $R$?
Comment: (not a duplicate) but a [related question](http://math.stackexchange.com/questions/91754/proving-idempotent-characteristics-on-matrices-algebra)
Answer: Let $k$ be a field, let $T$ be the $k$-algebra of $n\times n$ upper triangular matrices, and let $J\subset T$ be the ideal of strictly upper triangular matrices.
Let us assume that $n>1$ to avoid trivialities.
Then $T/J$ is isormorphic to $\underbrace{k\times\cdots\times k}_{n\text{ factors}}$. In particular, $T/J$ has a basis of central idempotents.
On the other hand, $T$ is a connected algebra: it has exactly one non-zero central idempotent, namely its unit. It is clear now that not all central idempotents in $T/J$ can be lifted to $R$.
Comment: could you explain more.
Comment: What exactly don't you understand in what I wrote? If you tell me, it'll be easier for me to help.
Comment: what does basis of central indempotent of $\frac{T}{J}$ looklike? and what is connected algebra?


Question about Differential Equations, why is there no constant for $x$?

Question:
The following equation is in the form$$\frac{dy}{dx}=f(y)$$
  Solve the diffrential equation$$\frac{dy}{dx}=2+3y$$

$$\frac{dy}{dx}=2+3y$$
$$dy=(2+3y)dx$$
$$\frac{dy}{2+3y}=dx$$
then I integrated bothsides..
$$\int\frac{dy}{2+3y}=\int{dx}$$
and this is what I think you should get but the book says otherwise...
$$\frac{1}{3}ln(2+3y)+c = x+c$$
I know I'm wrong about this but why is there no constant when we integrate the RHS? I'm assuming there's a 1 in front of the $dx$ and when you integrate you get $x+c$
If someone could explain why I'd be grateful.
Comment: You can put a constant $C_1$ on the left, and a constant $C_2$ on the right. But these can be combined into a single constant $C$ either on the left or the right. Note that it is not right to do as you did and use the *same* constant symbol on the left and right, for then you get cancellation.
Comment: use $c1 , c2 $ , combine them to make a single $c3$.
Answer: The two sides can take different constants, say $c_1$ and $c_2$. But then you can move both constants to one side and call $c = c_1 - c_2$, which also can take any value.
The lesson here is that $c_1$ and $c_2$ can be same or different, in contrary to what your form says.
Answer: Formally speaking, this solution should be
$$\frac{1}{3}\ln(2+3y)+c_1=x+c_2.$$
But we can also write this
$$\frac{1}{3}\ln(2+3y)=x+c_2-c_1.$$
But we can define a new constant $c=c_2-c_1$, and write this
$$\frac{1}{3}\ln(2+3y)=x+c.$$
Usually, we skip all the middle steps and jump straight to the end.


Calculating $\int_0^{\pi/2} \sqrt[n]{(\tan x)}dx=\int_0^{\infty} \frac{x^n}{1+x^{2n}}$ using contour integration

Question: Let $n$ be a natural number. I want to calculate $$\int_0^{\pi/2} \sqrt[n]{(\tan x)}dx=\int_0^{\infty} \frac{x^n}{1+x^{2n}}dx$$ using contour integration.
I declare $f(z) = \frac{z^n}{1+z^{2n}}$. This function has $2n$ simple poles of the form $exp(i\frac{-\pi}{2n} + i\frac{\pi k}{n})$ for $k = 0,1,2, ... , 2n-1$.
My problem is to find which contour to use. I thought about using the following:
$\gamma_1(t) = t$, $t \in [0,R]$
$\gamma_2(t) = Re^{it}$, $t \in [0,\frac{\pi}{n}]$
$\gamma_3(t) = te^{i\frac{\pi}{n}}$, $t \in [0,R]$
This way I have only one pole in the contour and I can use the residue theorem.
Is this a good approach? I somehow have problem with the calculations here.
Help would be appreciated
Comment: $\gamma_3= t e^{\frac{i \pi}{n}}$.  Yes, I believe this is a straightforward approach (surround one pole with a sector of a circle).
Comment: This has already been solved on this site plenty of times. Please search "Approach0" online and see if you can find it yourself
Answer: As you have defined $\gamma_3$,  that line contour is beginning at $t= R$ and comming back to 0. We are going to need to flip the sign.
$$Res_{z=e^{\frac{\pi i }{2n}}} f(z) = \int_{\gamma_1} f(z) \ dz + \int_{\gamma_2} f(z) \ dz - \int_{\gamma_3} f(z) \ dz$$
We are hoping to solve for $\int_{\gamma_1} f(z) \ dz$
You will need to show that $\lim_\limits{R\to\infty} \int_{\gamma_2} f(z) \ dz= 0.$
I will leave that to you.
$$Res_{z=e^{\frac{\pi i }{2n}}} f(z) = \int_0^\infty f(t) \ dt - \int_0^\infty f(e^\frac{\pi i}{n} t)e^\frac{\pi i}{n} \ dt$$
$$Res_{z=e^{\frac{\pi i }{2n}}} f(z) = (1+e^\frac{\pi i}{n})\int_0^\infty f(t) \ dt\\
2e^{\frac{\pi i}{2n}} \cos \frac{\pi}{2n}\int_0^\infty f(t) \ dt = Res_{z=e^{\frac{\pi i }{2n}}} f(z)\\
\int_0^\infty f(t) \ dt = \frac{1}{2e^{\frac{\pi i}{2n}}\cos \frac{\pi}{2n}} Res_{z=e^{\frac{\pi i }{2n}}} f(z)$$
$$Res_{z=e^{\frac{\pi i }{2n}}} f(z) = 2\pi i \frac{i}{2n e^{\frac{(2n-1)\pi i }{2n}}}  = \frac{\pi e^\frac{\pi i}{2n}}{n}$$
$$\int_0^\infty f(t) \ dt  = \frac{\pi}{2n\cos \frac{\pi}{2n}}.$$
Comment: You've lost a factor $2$ in the third line from the bottom.
Comment: I saw that, thanks.
Comment: Thanks, it helped me to finalise my answer
Answer: Substitute $x^{2n} = z$ to get
$$ \int_0^\infty \frac{x^{n}}{1+x^{2n}}dx = \frac{1}{2n}\int_0^\infty \frac{z^{-\frac12+\frac{1}{2n}}}{1+z} dz$$
Using the keyhole contour, you can find that for $n>1$:
$$\oint_C \frac{z^{-\frac12+\frac{1}{2n}}}{1+z} dz = (1-e^{2\pi i(-\frac12+\frac{1}{2n})}) \int_0^\infty \frac{z^{-\frac12+\frac{1}{2n}}}{1+z} dz = (1+e^{\frac{i\pi }{n}}) \int_0^\infty \frac{z^{-\frac12+\frac{1}{2n}}}{1+z} dz$$
On the other hand
$$\oint_C \frac{z^{-\frac12+\frac{1}{2n}}}{1+z} dz = 2\pi i \,{\rm Res}_{-1}\frac{z^{-\frac12+\frac{1}{2n}}}{1+z} =2\pi i e^{i\pi(-\frac12+\frac{1}{2n})} = 2\pi e^{\frac{i\pi }{2n}}$$
That means that
$$ \int_0^\infty \frac{z^{-\frac12+\frac{1}{2n}}}{1+z} dz = \frac{2\pi e^{\frac{i\pi }{2n}}}{1+e^{\frac{i\pi }{n}}} = \frac{\pi}{\cos\frac{\pi}{2n}}$$
$$ \int_0^\infty \frac{x^{n}}{1+x^{2n}}dx = \frac{\pi}{2n \cos\frac{\pi}{2n}}$$
Your approach is equivalent, but without the initial change of variables.


Extensions of $\mathbb{Z}/(m)$ by $\mathbb{Z}$

Question: I know that $\text{Ext}_{\mathbb{Z}}^1(\mathbb{Z}/(n), \mathbb{Z}) \cong \mathbb{Z}/(n)$.
I am trying to use this to show that the extensions of $\mathbb{Z}/(n)$ by $\mathbb{Z}$ are
$$0 \to \mathbb{Z} \to W_a \to \mathbb{Z}/(n)\to 0$$ where $W_a = (\mathbb{Z} \oplus \mathbb{Z})/(-a,n)\cdot\mathbb{Z}$.
In a homework question I have it is now claimed that if $d = \gcd(a,n)$ then $W_a \cong \mathbb{Z}\oplus\mathbb{Z}/(d)$.
I have tried all sorts of "obvious" maps to get an isomorphism.
One that I tried was taking $(z, k) \in  \mathbb{Z}\oplus\mathbb{Z}/(d)$ to $(z,k) +((-a,n)\cdot\mathbb{Z})$, but this fails to even be well defined from what I can tell.
Does anyone have any hints/directions I could try to show that $W_a \cong \mathbb{Z}\oplus\mathbb{Z}/(d)$? It seems like this should pull out easily, but for some reason I have not been able to come up with an isomorphism.
Answer: Let $a' = \frac{a}{d}, n' = \frac{n}{d}.$ Then gcd$(a', n') = 1 \Rightarrow $ there exist $x, y \in \mathbb{Z}$ such that $a'x + n'y = 1.$ Note that $\{r = (-a', n'), s = (y, x) \}$ forms a $\mathbb{Z}$-basis of $\mathbb{Z} \oplus \mathbb{Z}$ (why?). Define a $\mathbb{Z}$-module homomorphism $\phi: \mathbb{Z}r \oplus \mathbb{Z}s \rightarrow (\mathbb{Z}/d\mathbb{Z}) \oplus \mathbb{Z}$ by $(\alpha r, \beta s) \mapsto (\alpha$ mod $d, \beta).$ Then $\phi$ is surjective and ker$\phi = (-a, n)\mathbb{Z}.$
${\bf Note:}$ This is just an intimidation of the proof of the structure theorem of finitely generated modules over a PID.


Como faço para adicionar a API Firebase ao meu projeto android?

Question: Estava pesquisando sobre e achei bastante interessante, mas não sei o que é necessário e como fazer para usar
Answer: Se for no Android Studio, é necessario no minimo um dispositivo com Android 4.0 (Ice Cream Sandwich) ou versões
mais recente, e o Google Play Services 15.0.0 ou superior. Te indico entrar nesse link da documentação oficial do Firebase
com o tutorial completo
https://firebase.google.com/docs/android/setup


Exclude row while calculation average using AVG in sql server

Question: I have this table (Worker)
ID      NAME                 ST     SALARY       DEP_ID
-----       -------------------- --  ---------  ---------
1       Arun                 MH      55000          22
2       Manish               MP      53000          11
3       Rahul                GJ      45000          22

i want to get average salary and in that average I dont want to include minimum salary.
I wrote this query
select AVG(w.salary)
from Worker w
where w.salary  >(select MIN(w.salary) from Worker w)

can this be done without using subquery?
Comment: yes that will work and it can be done :)
Comment: How it can be done without using subquery?? @SpiderCode
Answer: Well, average is just sum/count, so you can do:
select (SUM(w.salary) - MIN(w.salary)) / (COUNT(w.salary) - 1)
from Worker w

Edit: As per the comment, the above solution does not work if there is more than one minimum and you want to exclude all minima.  To fix that without using a subquery, I can only think of using a cursor (which seems like overkill).  Nonetheless, the following fits the requirement:
DECLARE @min int = NULL
DECLARE @numMin int = 1
DECLARE @sum int = 0
DECLARE @current int
DECLARE @count int = 0

DECLARE db_cursor CURSOR FOR
SELECT salary
FROM Worker

OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @current

WHILE @@FETCH_STATUS = 0
BEGIN
    IF @min IS NULL BEGIN
        SET @min = @current
    END
    ELSE IF @current < @min BEGIN
        SET @min = @current
        SET @numMin= 1
    END
    ELSE IF @current = @min BEGIN
        SET @numMin= @numMin + 1
    END

    SET @sum = @sum + @current
    SET @count = @count + 1

    FETCH NEXT FROM db_cursor INTO @current
END

CLOSE db_cursor
DEALLOCATE db_cursor

SELECT (@sum - @numMin * @min) / (@count - @numMin)

Comment: This doesn't work because more than one row might have the minimum salary.
Comment: Yup, good point.  The only other solution I can think of would require a cursor (and calculating min by hand).
Comment: But instead of doing all these things, according to me the query written by OP will work fine.
Answer: I don't know if this is the best pratics in SQL
Select (SUM(w.salary)-MIN(w.salary))/(COUNT(w.salary)-1) from Worker w

Comment: This doesn't work because more than one row might have the minimum salary.
Answer: I don't think you can really do this accurately without a subquery.  The issue is that multiple records could have the minimum salary.  In fact, all of the salaries could be the minimum and the average may not even be defined.
You can do:
select AVG(w.salary)
from (select w.*, min(w.salary) over () as minsalary
      from Worker w
     ) w
where w.salary > minsalary;

That still has a subquery, but not in the where clause.
Comment: OP wants answer without subquery
Comment: I know. but what about the answer's provided by AFetter and mbroshi ? are their answer give accurate results ? just curious to know.
Comment: @SpiderCode . . . They are incorrect when more than one row has the minimum salary.
Comment: +1 : Saw your comment and marked as 'useful' on each answers. that's true. :)


UWP and SerialSample byte encoding error

Question: I will start off by saying I'm new to UWP. I recently downloaded VS2017 and have begun work on creating an App based off of an older C++/CLI Winform project. The reason for this is to avoid device compatibility issues.
To the problem.
I've followed the SerialUART sample code availbe here https://github.com/ms-iot/samples/tree/develop/SerialUART/
And I have been able to connect and read data successfully from the arduino based device into the UWP App.  The problem I am having is that every so often the App throws a COMException error: "No mapping for the Unicode character exists in the target multi-byte code page"
It appears to be the same character (or set of characters) causing the issue. But when the arduino based device is connected to the arduino serial monitor, the data is printed out exactly as intended. Indeed, it is even saved to the SD card exactly as presented on the serial monitor.
I've used a 'try' and 'catch' block to prevent the app crashing, and printed the error out on the text block I'm using as a terminal window, but the error doesn't seem to clear. Every time new data is received, the error message is reprinted.
I have verified that it's only certain character(s) printed at test startup and test end that are causing the issue as I tried connecting to the arduino device halfway through a test and got test data streamed out no problem.
So, how do I clear this exception error? And why does the UWP app have trouble with certain characters when the aruino serial monitor does not?
Answer: Ok, so i discovered what the problem was here. In my arduino application, I was sending out characters such as

²

and

°

What happens in the arduino serial terminal, is, it prints out the alt-code symbol prior to the squared symbol or degree symbol being printed etc. It looks like a capital "A" with a hat, followed by the symbol being printed.
Im guessing this is a quirk of arduino serial terminal as to get round this, I actually was able to split the character code up (as they are two bytes wide) and print out the latter half of the byte only.
Problems arose in VS2017 UWP because it was only seeing half of the actual character code and throwing a wobbly. Taking out the 'fix' I came up with meant that it could interpret all serial data correctly. And VS is clever enough to know not to print out the alt-code symbol when displaying a squared symbol or degree symbol etc...


Is it possible to get the ID of the div / img when double click on an image using jquery?

Question: Now I have an html page that display image. Notice that the div only contain 1 image file:

What I would like to implement is when user double click on the div , through jquery/ js to get the "div_1" or "img_1" . In better way, get the "1" . Is it possible to implement / any function can help to achieve that?
Thanks
Updated:
The current Html code is like that

It seems my case is not that straight forward, when i use var id = $(this).attr("id"); it return page as result. If my case don't allow me to get the attribute of page,  the id of image, then it means i can not get the actual ID of individual image? thanks
Most Updated ( 1 flaw left only!)
$("div.turn-page").dblclick(function() {
var id = this.id;
num = id.split("_")[1];
alert (num);
});

Currently I am using this to get the id , however for the last result (not turn-able) when i double click it do not response or do anything. But it should be work since the class there is turn-page p7 ?

Comment: Yes, it is very, very possible. What have you tried so far? --->
Comment: I have tried to set the  as a button or something, when onclicked it trigger the function that can get img path?
Comment: updated question . Please take a look
Answer: You can do this in javascript:
document.getElementById("div_1").children[0].id

This will return the id of the first child of the "div_1" div
Comment: I'm not sure how this helps given that the OP already has an id-allocation scheme that gives parallel ids to the images and their containing divs. He or she wants to get the id of a _clicked_ element...
Comment: He wanted the id of either the div or img tag. And it´s easy to modify this code to get the id of the div
Answer: Like this:
$("div").dblclick(function() {
    var id = this.id,
        num = id.split("_")[1],
        imgSrc = $(this).find("img").attr("src");

    // do something with the id, the number, or the image src
});

Demo: http://jsfiddle.net/LGwK7/
This will bind a double-click handler to all div elements, so you might want to add a common class to just the ones you care about and bind to those. (I'm assuming it doesn't make sense to bind by id because you asked how to get the id of the clicked one.)
Note that your html has an error: <div="div_1"..., should be <div id="div_1"...
Comment: @VIDesignz - I often see completely correct answers downvoted for no apparent reason, so I don't worry when it happens to me. I assume in a lot of cases the downvoter _can't_ explain why...
Comment: @user782104 - For your updated html you probably want to use `$("div.turn-page").dblclick(...` as per what I said in my answer about using a class so that you don't bind to _all_ divs.
Comment: Just haters I guess...ughh
Comment: Yeah - where were they earlier when I needed a few downvotes to take my reputation down to 36363? By the way, thanks for the upvote @VIDesignz.
Comment: Your updated code works in isolation: http://jsfiddle.net/MV9xd/ so perhaps you have some other code that breaks it.
Comment: @nnnnnn this is off topic, but I think I am losing my mind... Does $(document).load(); actually work? I swear it did but now it seems it doesn't...
Comment: @VIDesignz - I've never tried `$(document).load()`. If you're trying to attach an event handler try `$(window).load()` instead (assuming `$(document).ready()` doesn't suit your purpose). If you're trying to use the Ajax `.load()` method I'm not sure what happens if you try to use it on the `document` but I wouldn't think it a good plan.
Comment: @VIDesignz I don't think so. This is from the jQuery API docs for the `load` method: "This event can be sent to any element associated with a URL: images, scripts, frames, iframes, and the window object." Nothing about `document`, so I think it wouldn't. Unless you mean the other purpose of `load` to use AJAX...
Comment: @nnnnnn Thank you man...I have seen it around and never second guessed it, it was only when I implemented it that I realized it didn't work.  I thought it was because I upgraded my jquery to 1.8
Answer: You can do something like this
var divId;

$('div').dblclick(function(e){
    e.preventDefault();
    divId = $(this).prop('id');
});

Comment: I was thinking maybe the double click could trigger viewing the image in a browser light box. It may not be needed though :)
Comment: `$(this).prop("id")` is too much jQuery. Just do `this.id`
Comment: Good point @IHateLazy - I'm embarrassed to say I did the same thing in my own answer (now updated) even though I often point out the same thing to others. Oops.
Comment: @IHateLazy I can respect that...jquery has erased my javascript memory! :o
Comment: @nnnnnn: Yeah, it's not the worst  pattern one can adopt. Just needlessly heavy and complex.


Non-overlapping aggregation and autocorrelation

Question: I have a time series that follow an MA(1) process , I do non-overlapping aggregation with aggregation level $m=2,3,\dots$, and then I calculate autocorrelation of basic and aggregated series, for negative value of moving average parameter, aggregated autocorrelation becomes close to zero, means that the aggregated series want to be like white noise, I was wondering if anybody can explain the reasons behind this behavior?
Answer: One way to analyze this is to start with the MA(1) expression $y_t = e_t - \theta e_{t-1}$, then write out the expressions for $(y_1 + y_2)$ and $(y_3 + y_4)$ in terms of the $e_t$.  You get:
$y_1 + y_2 = e_2 + (1-\theta)e_1 - \theta e_0$
$y_3 + y_4 = e_4 + (1-\theta)e_3 - \theta e_2$
Note that the only common term between the two expressions is $e_2$; the first expression has $e_1$ and $e_0$, which don't appear in the second, and the second has $e_4$ and $e_3$, which don't appear in the first.  If you find the correlation explicitly, you get:
$\rho_{12,34} = -\theta / (1 + \theta^2 + (1-\theta)^2)$
For just $y_1$ and $y_2$, we have $y_1 = e_1 - \theta e_0$ and $y_2 = e_2 - \theta e_1$.  Here we have $e_1$ in both, but fewer other terms.  The correlation here is
$\rho_{12} = -\theta / (1+\theta^2)$.
Comparing the denominators of the two expressions for the correlation, you can see the first has the extra (non-negative) term $(1-\theta)^2$ in it.  Since the numerators are the same, for all $\theta \ne 0 \space \text{or}\space 1$, the correlation between $y_t+y_{t+1}$ and $y_{t+2}+y_{t+3}$ will be closer to 0 than the correlation between $y_t$ and $y_{t+1}$.
As you aggregate more and more, this effect will get larger; the only common term is  $e_{t+\tau}$, where you are aggregating $y_t \dots y_{t+\tau}$ and $y_{t+\tau+1} \dots y_{t+2\tau}$, but the variability of the aggregates increases as the number of terms making up the aggregation increases, so the correlation decreases.
Comment: may I ask one more question please? I have applied SES as a forecasting method on both basic and aggregated series, and then I disaggregated forecasts resulted from aggregated series and finally I calculate ratio of MSEbasic/MSEdagg, where MSEbasic=Var(dt-ft) and MSEdagg=Var(dt-(FT/m), dt is basic series, ft is forecast of basic series, FT is aggregated forecast and m is aggregation level. this ratio show that for highly negative value of Theta, basic approach works better and for the rest of Theta parameter aggregated approach works better, I'm trying to find why?


Are private static variable inside non-static class available to the entire application?

Question: I have something like this:
...
public partial class MyPage : System.Web.UI.Page
{

    private static string _code = null;
...

Will the _code variable be shared with everyone on my application who loads MyPage?
This question is not a Duplicate
The possible duplicate does not address static variables inside a non-static class.  I now know it does not matter, however, the "duplicate" does not say this.
Comment: possible duplicate of [How do static properties work in an asp.net enviroment?](http://stackoverflow.com/questions/4026785/how-do-static-properties-work-in-an-asp-net-enviroment)
Comment: i think this is a very useful question and is helping me figure out if i can do that is said in question.
Comment: @finnw I said `_code` variable in my question but was originally going to have it as a property when I was writing the title... SO SORRY! (downvote? really?)
Comment: I did not downvote you (but I did vote to close as duplicate.)
Comment: @asawyer The "duplicate" does not address static variables inside a non-static class. I now know it does not matter, however, you're "duplicate" does not say this.
Comment: @capdragon I'm sorry if you don't agree, and I did not downvote. The question, in my opinion is an duplicate because it addresses static value behavior in asp.net applications. I had asked the same thing before and thought the information I received would be useful to you. The close vote is simply the mechanism provided. There is no reason to get bent out of shape.
Comment: I still think it's a duplicate.  The difference is not significant enough to justify a separate question.
Answer: yes, static members of non static classes are anyway static.
Answer: Yes, it will be shared across the application domain. Since a single app domain is created for each IIS Application within an IIS worker thread, the value of the static variable can be considered shared globally.