How should I refer to any arbitrary class attributes starting with a fixed string and differing by their ending numbers?

Question: I am writing a Python program which uses ConfigParser to read a configuration file intended to control various aspects of the program's configuration, execution and orientation to its environment and landscape.  I am using Python 2.6.6 on RHEL 6.4.
One aspect of its configuration is how many rsyslog daemons it needs to interact with, and details about each of those instances.  I have chosen the format instance<#>_ to enable the user to specify any arbitrary number of instances with a consistent set of attributes to configure.  An excerpt from the config file appears here:
[rsyslog]
rules_dir:                      /etc/rsyslog.d

instance1_enable:               no
instance1_name:                 rsyslog-Group01
instance1_startupscript:        /etc/init.d/%(instance1_name)s
instance1_conf:                 /etc/%(instance1_name)s
instance1_rules:                %(rules_dir)s/rules-%(instance1_name)s
instance1_restart:              no

instance2_enable:               no
instance2_name:                 rsyslog-Group02
instance2_startupscript:        /etc/init.d/%(instance2_name)s
instance2_conf:                 /etc/%(instance2_name)s
instance2_rules:                %(rules_dir)s/rules-%(instance2_name)s
instance2_restart:              no

I build an object called 'rsyslog' such that its attributes look like this:
rsyslog.instance2_enable="no"
rsyslog.instance2_name="rsyslog-Group02"
...etc

My problem comes when I pass the rsyslog object and an instance number to a function to have that function do operations on the instance#_rules.  I call the function, for example, in this way:
list_of_rules=read_files(rsyslog,2)

The function should return a list of rules which it parses out of the rules file for instance2
/etc/rsyslog.d/rules-rsyslog-Group02

Parsing the rules is no problem when I hard code the instance:
for line in fileinput.input(rsyslog_object.instance7_rules, mode='r'):
    ruleline=re_ruleline.search(line)

But how do I allow for something like the following where '' represents the instance number I passed to the function:
for line in fileinput.input(rsyslog_object.instance<instancenumber>_rules, mode='r'):

I have used the locals() and globals() functions to do variable indirection in other contexts but I am not sure how I would apply them here.
Alternately, if you can see a better, more elegant or Pythonic way to solve the problem of allowing for any arbitrary number of consecutively numbered instances which can be referred to by number in iterations easily and more Pythonicly; please explain how and also why it is a better or more Pythonic way of accomplishing the task.
I am not married to using instance if there is another way to do it.  ConfigParser did not allow '.' in the configuration
Answer: I'm not sure that I completely understand the question, but isn't getattr what you want:
for line in fileinput.input(
   getattr(rsyslog_object, 'instance%d_rules' % instancenumber),
   mode='r'):
    ...

Comment: Thanks mgilson!  I remember reading about String Formatting, and now I see this is not limited to simply printing - we can use this anywhere a string can be used.  Found in the reference here: http://docs.python.org/2.7/library/stdtypes.html#string-formatting
Comment: @JustinHaynes -- Yep.  You could also use `.format` if you prefer (many people do these days):  `'instance{}_rules'.format(instancenumber)`.  `.format` is definitely more powerful, and easier to read when you start doing crazy stuff, but it causes longer lines for simple stuff, so I prefer `%` for simple stuff and `.format` for more complex stuff.  I suppose some people would yell at me for not being consistent, but ...


Tangent map $T_{f,x}:T_{X,x}\to T_{Y,y}\otimes_{\mathcal{O}_{X,x}}k(x)$ is $k(x)$-linear

Question: In Qing Liu 4.2 (page 126) is write that the tangent map $T_{f,x}:T_{X,x}\to T_{Y,y}\otimes_{\mathcal{O}_{X,x}}k(x)$ is $k(x)$-linear. I don't see why.
I see that by definition $T_{X,x}\to T_{Y,y}$ obtain by duality from $\mathfrak{m}_{Y,y}/\mathfrak{m}_{Y,y}^2\to \mathfrak{m}_{X,x}/\mathfrak{m}_{X,x}^2$ is $k(y)$-linear (for the structur obtain by restriction of scalar of $\mathfrak{m}_{X,x}/\mathfrak{m}_{X,x}^2$) but I don't see why it's induce the conclusion: with the notation $\varphi:k(y)\to k(x)$ and $F:T_{X,x}\to T_{Y,y}$, I have for all $u\in T_{X,x}$ and $\alpha\in k(y)$, $T(\varphi(\alpha)u)=\alpha T(u)$, so $T_{f,x}(\varphi(\alpha)u)=T(\varphi(\alpha)u)\otimes1=\alpha T(u)\otimes1=\alpha(T(u)\otimes1)=T(u)\otimes\varphi(\alpha)$. So if we have $\beta=\varphi(\alpha)\in k(x)$, $T_{f,x}(\beta u)=T(u)\otimes\beta=\beta(T_{f,x}(u))$ and I obtain the linearity. But I don't see the reason for why $k(y)\to k(x)$ should be surjective ie why $\beta=\varphi(\alpha)$.
I have seen the errata that require $T_{Y,y}$ has finite dimension over $k(y)$ (e.g. $Y$ is locally Noetherian) or $f$ is locally of finite type but I don't see link with my problem.
I have seen the question Map between Zariski tangent spaces(?) but it seems to be a problem with the isomorphism $\mbox{Hom}_{k(y)}({\frak{m}}_y/{\frak{m}}_y^2,k(x))\simeq\mbox{Hom}_{k(y)}({\frak{m}}_y/{\frak{m}}_y^2,k(y))\otimes k(x)$ wich is not clear to me.
Answer: If $\mathfrak{m}_y / \mathfrak{m}_y^2$ is finite-dimensional over $k(y)$ (for example when $Y$ is locally noetherian), then (by linear algebra) the canonical homomorphism $$\hom_{k(y)}(\mathfrak{m}_y / \mathfrak{m}_y^2,k(y)) \otimes_{k(y)} k(x) \to \hom_{k(y)}(\mathfrak{m}_y / \mathfrak{m}_y^2,k(x))$$
is an isomorphism. This also holds when $k(x)$ is finite-dimensional over $k(y)$, for example when $f$ is locally of finite type.
Now, the $k(y)$-linear map $\mathfrak{m}_y / \mathfrak{m}_y^2 \to \mathfrak{m}_x / \mathfrak{m}_x^2 $ induces a $k(x)$-linear map $\mathfrak{m}_y / \mathfrak{m}_y^2 \otimes_{k(y)} k(x) \to \mathfrak{m}_x / \mathfrak{m}_x^2$, hence by dualizing a $k(x)$-linear map from $T_x$ to
$$\hom_{k(x)}(\mathfrak{m}_y / \mathfrak{m}_y^2 \otimes_{k(y)} k(x),k(x)) \cong \hom_{k(y)}(\mathfrak{m}_y / \mathfrak{m}_y^2,k(x)) \cong \hom_{k(y)}(\mathfrak{m}_y / \mathfrak{m}_y^2,k(y)) \otimes_{k(y)} k(x),$$
that is $T_y \otimes_{k(y)} k(x)$.
Comment: Well it is elementary when you generalize it so that the essential emerges, and the unimportant waste disappears. If $S$ is a $R$-algebra and $M,N$ are $R$-modules, you can look at $\hom_R(M,N) \otimes_R S \to \hom_S(M \otimes_R S, N \otimes_R S)$. The class of $M$ for which this is an isomorphism is closed unter direct sums and contains $R$, hence it contains all finitely generated free modules. This suffices here. Moreover, it is closed unter direct summands, hence contains all f.g. projective modules. If $S/R$ is flat, it is closed under cokernels, hence contains finitely presented modules.
Comment: You can identify the map with $\hom_R(M,N) \otimes_R S \to \hom_R(M,N \otimes_R S)$, and this map even makes sense when $S$ is just some $R$-module. Now play the same game, the class of "good" $S$ is closed under direct sums and contains $R$, hence it contains f.g. free $S$. These "elementary" isomorphisms can be found in Bourbaki's *Algèbre*, but I think usually they are proven using diagrams and exact sequences. In my opinion the proofs using closure properties are easier.
Comment: Thanks, all is clear now. But please don't say "elmentary" ;-)


Angular 6: Selected não funciona com [(ngModel)] e (ngSubmit)="onSubmit()

Question: Recebo a classe Cliente no meu formulário
import { NgSelectOption } from '@angular/forms';

export class Cliente {
    nome: string = '';
    carros: any [] = [
      { id: 1, modelo: 'Gol',selected:false },
      { id: 2, modelo: 'Saveiro',selected:true },

    ];

  }

 ngOnInit() {

    this.cliente = new Cliente();
  }

Quero deixar a opção pré selecionada quando o valor selected for true.
<select [(ngModel)]="cliente.carros" name="cliente.carros" >
  <option *ngFor="let c of cliente.carros"  [selected]="c.selected" [value]="c.id">
    {{c.modelo}}
  </option>
</select>

Mas quando faço isso sem a propriedade name="" o valor não é passado ao da submit no meu form
Segue abaixo a imagem como esta agora.

Segue o link do projeto https://stackblitz.com/github/CristovaoTorres/AngularCrudTest
Comment: Tá meio estranho, você está tentando jogar o valor de volta em `cliente.carros`, tenta apontar o `[(ngModel)]=` para outra variável, por exemplo `carrosSelecionados`
Answer: criei uma função para selecionar o item selected(talvez não seja o mais correto)
  SelecionarCarroSelect(){
this.cliente.carros.forEach((item, index) => {
  if(item.selected)
  this.carro = item.modelo;
});

}
e o html
   <select [(ngModel)]="carro" name="cliente.carros" >
  <option *ngFor="let c of cliente.carros"  >
     {{c.modelo}}
   </option>
 </select>

Answer: Experimenta apenas colocar
[selected]="c.selected"

Comment: Infelizmente não funcionou, e não da nenhum erro.
Answer: <form (ngSubmit)="onSubmit()">

    Nome

    Tipo
    <select>
      <ng-container *ngFor="let carro of cliente.carros">
         {{carro.nome}}
      <ng-container *ngIf="carro.selected">
         <option [value]="carro.id" [selected] >
           {{carro.modelo}}
        </option>
      </ng-container>
      <ng-container *ngIf="!carro.selected">
         <option [value]="carro.id">
           {{carro.modelo}}
        </option>
      </ng-container>
      </ng-container>
    </select>

  <input type="submit" class="btn btn-primary mt-4" value="Salvar">
  Cancelar

</form>

Comment: Obrigado pela resposta, infelizmente não funcionou, inseri uma img na pergunta
Comment: ao clicar na setinha, aparece as opções corretamente?
Comment: Se possivel inspecione o elemento referente ao `` e mande uma imagem
Comment: Alterei a pergunta com a img
Comment: editei, veja se agora funciona
Comment: Não funcionou, subi meu projeto no Git https://stackblitz.com/github/CristovaoTorres/AngularCrudTest
Comment: Vamos [continuar esta discussão no chat](https://chat.stackexchange.com/rooms/93359/discussion-between-junior-torres-and-matheus-ribeiro).
Answer: Eu uso o [checked] dentro da tag pra deixar pré-selecionado (isso serve para radio button). Exemplo:
Funcionalidades & Permissões

                  <input class="form-check-input" type="hidden">{{ pp.nome_funcionalidade }}

                    Sim<input class="form-check-inline ml-2 perm" type="radio" name="optPermissao_{{pp.id_perfil_permissao}}" value="1" id="checkinfo_{{pp.id_perfil_permissao}}_1" [checked]="pp.permissao == 1">
                    Não<input class="form-check-inline ml-2 perm" type="radio" name="optPermissao_{{pp.id_perfil_permissao}}" value="0" id="checkinfo_{{pp.id_perfil_permissao}}_0" [checked]="pp.permissao == 0">

Qualquer dúvida, coloco o resto do código aqui para maior compreensão.
Answer: No exemplo que vou deixar, veja a tag que tem o [attr.disabled], ela vai ter o valor pré fixado para um select, só que o valor vem do component.ts.

      Componente
      <select name="componente" id="componente" class="form-control componente" formControlName="id_componente" [attr.disabled]="true">
        <option value="{{ c.id_componente }}" *ngFor="let c of componentes" >{{c.nome_componente }}</option>
      </select>

Faço a busca no DB e insiro no formBuilder, então fica pré selecionado dentro do select.
ngOnInit() {
    this.setCurrentAction();

    this.funcionalidadesForm = this.formBuilder.group({
      id_funcionalidade: [null],
      nome_funcionalidade: [null, Validators.required],
      descricao: [null, Validators.required],
      id_componente: [null, Validators.required]
    });

    this.getListFormularios();
    this.loadPage();
  }
private loadPage() {
    if(this.currentAction == 'edit') {
      this.route.paramMap.pipe(
        switchMap(params => this.funcionalidadesService.getId(+params.get("id")))
      ).subscribe(
        (funcionalidade) => {
          this.updateForm(funcionalidade);
        }
      );
    }
  }

  private updateForm(item) {
    this.funcionalidadesForm.patchValue({
      id_funcionalidade: item[0].id_funcionalidade,
      nome_funcionalidade: item[0].nome_funcionalidade,
      descricao: item[0].descricao,
      id_componente: item[0].id_componente
    });
  }

Answer: Basta tirar o  [(ngModel)]="cliente.carros" do select e ele automaticamente coloca o preselecionado. Testei no stackblitz e funcionou.


ML classifications

Question: I have a doubt in below ML families.
If we are predicting: Yes,  then we have classification and regression
If No, then we have clustering
In clustering, we have K-means algo
In classification we predict discrete values, so we have logistic regression, KNN, and NN
In Regression we predict continuous values, so we have Simple Linear and Multiple Linear regression, also called as causal models
Then we have TimeSeries, with Single, Double and Triple exponential models. And ARIMA, SARIMA models
ARIMA combines Regression and Simple means(Moving Average). Now my question is, does TimeSeries come under classification or Regression?
Comment: You present what looks to me to be a false dichotomy. I think part of the difficulty may be arising from the tendency of machine learning to treat all problems as one of clustering, classification or prediction. The scope of statistical analyses is considerably broader than those applications. An analysis of *time series data* may be for neither classification nor prediction (let alone actually be regression). A variety of time-series models are akin to regression models (though the ones that are are not necessarily being used for prediction). However some time series models would ...ctd
Comment: ctd... considerably stretch the notion of regression. Why seek to pound a somewhat roundish peg into an unneccesarily square hole?
Answer: Strictly speaking, time series methods don't correspond to a specific family of ML models like classification or regression etc...
They are more of a domain of application, similar to natural language processing, image processing, etc...
Models from the Exponential Smoothing family are similar in spirit to regression models, however they are different from regression top problems in the sense that they are sequential and take a variable (possibly infinite number of inputs). You can see this by expanding the expression of an exponential smoothing model.
ARIMA models are an interesting case: If they have only an AR component (meaning ARIMA(p,d,q) with q=0) then they are regression models (AR stands for Auto-Regression after all) - however if the have an MA component, then they fall in the same category as Exponential Smoothing models.
See this post for what ES are not considered regression models and this post for why the MA component of ARIMA models makes them different from regression models.

ML classifications


Can I show the series convergence by this relabeling method?

Question: The series is
$$\sum_2^{\infty}\frac {1}{(\log(n))^{\log(n)}}$$
Can I simply relabel the $\log(n)$ with the variable $y$ and use the ratio test on $\frac{1}{y^y}$?  I'd get 0 in the ratio test limit and I conclude that the series converges.
Is this method valid?
Or should I really stick with the integral test instead?  I tried the integral test too, but the integral is hard to evaluate.
Also, the Cauchy Condensation Test is usually helpful for series of logarithms but it doesn't seem useful in this example.
Any hints or solutions are welcome.
Thanks,
Comment: The condensation test works. Using the change of base for logarithms and powers ($a^{\log b} = b^{?}$) works too and is perhaps a bit simpler.
Comment: LaTeX hint: if you prefix 'log' or 'ln' with a backslash it will get appropriate upright font: `\log` renders as $\log$.
Comment: Marco's answer is the change of base, $a^{\log b} = b^{\log a}$, with $a = \log n,\, b = n$. It's perfectly valid. For the condensation test, you need to see that for large enough $n$, you have $(n\log 2)^{\log 2} > 3$ (or any constant $> 2$), then you have a majorisation by a convergent geometric series (which of course amounts to the root test).
Comment: Hi @DanielFischer, using the Cauchy condensation test, I am stuck with this summand:  $\large \frac {2^n}{n^{nlog(2)}(log(2))^{nlog(2)}}$.  Where can I go from here?  Also, there is a very cool answer offered below by Marco Cantarini, but I'm afraid it may not be valid, since following that move would mean something like $ e^{(log(log(2))}$ evaluates to $\large 2^{log}$, which I believe doesn't make sense.  I'll also review how to change bases of logarithms now too.  Please feel free to comment further.  Thanks so much,
Comment: Hi @DanielFischer, I solved it with the root test, applied to the condensed summand that I wasn't able to simplify.  Wish I had noticed it myself, though - I got it with a hint from another MSE contributor.  I completely overlooked the root test.  Thanks so much for your time :-)
Comment: Ok, got it.  Thanks so much @DanielFischer :-)
Answer: Note that $$\sum_{n\geq2}\frac{1}{\left(\log\left(n\right)\right)^{\log\left(n\right)}}=\sum_{n\geq2}\frac{1}{\exp\left(\log\left(\left(\log\left(n\right)\right)^{\log\left(n\right)}\right)\right)}=\sum_{n\geq2}\frac{1}{n^{\log\left(\log\left(n\right)\right)}}
 $$ and so, for example, for a sufficient large $N
 $ we have $\forall n\geq N
 $ that $n^{\log\left(\log\left(n\right)\right)}>n^{2}
 $ hence $$\sum_{n\geq N}\frac{1}{n^{\log\left(\log\left(n\right)\right)}}\leq\sum_{n\geq N}\frac{1}{n^{2}}<\infty.
 $$
Comment: Hi! What I did is using the identity $y=\exp(\log(y))$ with $y=(\log(n))^{\log(n)}$ and then the property $\log(a^{b})=b\log(a).$If it's not clear, I can add some passages if you want ;)
Comment: @LebronJames You're welcome ;)
Comment: Hi @MarcoCantarini, I'm concerned that your move is not valid:  you inverted the log which plays the role of the argument of the first log.  But if we look at for example $e^{(log(log2))}$ and do the same thing you did, I arrive at $\large 2^{log}$ ... which is nonsensical.  What do you think?  Thanks,
Comment: Oh, gosh - this is awesome, @MarcoCantarini.  You're absolutely right.  And the exact value of N would just be  $\large N = e^e$ - requiring log(log(n)) to be greater than 1, for p-series convergence.  Thanks so much for following up on this answer :-)
Answer: You can use asymptotic analysis:
Compare the series with the Bertrand's series: $\;\displaystyle\sum\frac1{n\log^2n}$, which converges.
$$\log\biggl(\frac{n\log^2n}{\log n^{\log n}}\biggr)=\log n+2\log\log n-\log n\log\log n$$
Now $\;\log n\;$ and $\;\log\log n\;$ are $\;o(\log n\log\log n)$, hence
$$\log\biggl(\frac{n\log^2n}{\log n^{\log n}}\biggr)\sim_\infty-\log n\log\log n\to -\infty. $$
This proves $\;\dfrac{n\log^2n}{\log n^{\log n}}$ tends to $0$ as $n$ tends to $\infty$, which means $\;\dfrac1{\log n^{\log n}}=o\biggl(\dfrac1{n\log^2n}\biggr)$, hence the series converges.
Comment: Thanks as usual, @Bernard :-)


Does jQuery's replaceWith() also remove event handlers?

Question: I've looked through the jQuery Documentation for the answer to this simple question:

Does replaceWith() call remove() or detach() under the hood?

I've had no luck with the official documentation; it is ambiguously defined as removing the node. But tests show a memory leak.
Answer: Looking at the source code of jQuery (2.1.1), you're asking two different questions.

Does jQuery's replaceWith() remove event handlers?
Yes. jQuery calls cleanData(), which is an internal method which removes all data on an element. Since jQuery event handlers are stored in the elements data, they will also get cleaned up.
cleanData() also removes the event handler attached to the element which triggers the execution of all event handlers stored  in the elements data, by calling jQuery.removeEvent() (another internal method).
Does replaceWith() call remove() or detach() under the hood?
The only time it calls remove() is if no arguments were provided to replaceWith(); jQuery treats it as if you were calling remove() instead of replaceWith();

TL;DR: jQuery will clean everything up for you, so there shouldn't be a risk of memory leaks.
Answer: FYW if you don't want that behavior take a look a this poorly discussed thread over jQuery tickets
http://bugs.jquery.com/ticket/13400
and for those who wont ready expect code, here's an implementation of the replaceWith that uses detach instead of remove
with remove()
old.replaceWith( new );
with detach()
old.before( new ).detach();
Answer: 1) with A.ReplaceWith(B); it will remove the A element and all events attached. All events for B have to be declared
2) with A.before( B ).detach(); it will remove the A element but keep event for later (and will apply only to A again). All events for B have to be declared
This problem can be solved by using event propagation or event bubbling as in the code below
<!DOCTYPE html>

This is a heading

with ReplaceWith <button class="rp">1</button>

with before / detach <button class="detach">2</button>

with ReplaceWith correct event bubbling <button class="detach2">3</button>

with before / detach and correct event bubbling <button class="detach3">4</button>

Hope that might helps someone...


Como receber nome de usuario do facebook? Graph API

Question: Oi, pessoal. Como obter o id de um usuario do facebook, e seu nome usando Graph api?
Eu apenas consigo pegar o id das mensagens, usando sender = event.sender.id;
function fbGetProfile(id) {
   request({
      method: 'GET',
      uri: 'https://graph.facebook.com/v2.6/${id}',
      qs: {
        fields: 'first_name',
        access_token:PAGE_ACCESS_TOKEN
      },
      json: true
    }, function(error, response, body) {
    if (error) {
      console.log('Error sending message: ', error);
    } else if (response.body.error) {
      console.log('Error: ', response.body.error);
    }
  });

Answer: O Graph API já não permite procurar pelo username. Também acabo de conferir a documentação e não tem nada lá à respeito.
Vi que o HTML do Facebook contém duas meta tags com o User_ID:

<meta property="al:android:url" content="fb://profile/4" />
<meta property="al:ios:url" content="fb://profile/4" />


Rock,Paper&Scissors game problem in JavaScript

Question:
Whenever I run the code , computer-Point has score 1 before the game
started . Second issue that I couldn't figure out is that how to set a
play round for 5 set.  these are the JavaScript code

describe the values
set computer choices
set check-winner Function
set Player choices
set game function

````
var playerPoint = 0;
var computerPoint = 0;
const userScore_p = document.querySelector(".human > p");
const computerScore_p = document.querySelector(".machine > p");
const result_p = document.querySelector('.result > p');
const rock = document.getElementById('rock')
const paper = document.getElementById('paper');
const scissors = document.getElementById('scissors');
const playerSelection = [rock, paper, scissors]

const weapons = ["rock", "paper", "scissors"];
// set the computer random choice
function getComputerChoice(){
    const choice = weapons[Math.floor(Math.random() * weapons.length)];
    return choice;
}

function checkWinner(playerSelection) {
       const computerSelection = getComputerChoice();
       if (playerSelection == computerSelection) {
        result_p.textContent = "Tie";

    }
     else if ((playerSelection == "rock" && computerSelection == "scissors") ||
              (playerSelection == "scissors" && computerSelection == "paper") ||
              (playerSelection == "paper" && computerSelection == "rock")) {
                 result_p.textContent = "player Winnnn";
                 playerPoint++;
                 userScore_p.innerHTML = playerPoint;
    } else {
                result_p.textContent = "Player lost!!!!";
                computerPoint++;
                computerScore_p.innerHTML = computerPoint;
    }
    console.log(computerSelection)
    console.log(playerSelection);
}

function getPlayerChoice() {
    rock.addEventListener("click", function () {
     checkWinner("rock");
    });
    paper.addEventListener("click", function() {
         checkWinner("paper");
    });
    scissors.addEventListener("click", function() {
        checkWinner("scissors")
    });

}

function game() {
    const computerSelection = getComputerChoice();

    for (let i = 0; i < 5; i++) {
        if (playerPoint > computerPoint) {
        result_p.innerHTML = "you won the game"
      } else if (playerPoint < computerPoint) {
        result_p.innerHTML = "you lose the game"
      } else {
        result_p.innerHTML = "Drawwww"
      }
   }
}

game()
checkWinner();
getPlayerChoice();
    ````

Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Answer: The problem here is, player is not going to choose a weapon until they click on 1 of the 3 buttons, so when you call the function getPlayerChoice() it actually doesn't mean the player clicked on one of those buttons.
You should process the logics inside the checkWinner() function, which is called whenever the user clicks on a button.

let playerPoint = 0;
let computerPoint = 0;

const userScore_p = document.querySelector(".human > p");
const computerScore_p = document.querySelector(".machine > p");
const result_p = document.querySelector('.result > p');
const rock = document.getElementById('rock')
const paper = document.getElementById('paper');
const scissors = document.getElementById('scissors');
const playerSelection = [rock, paper, scissors]

rock.addEventListener("click", function() {
  checkWinner("rock");
});

paper.addEventListener("click", function() {
  checkWinner("paper");
});

scissors.addEventListener("click", function() {
  checkWinner("scissors")
});

const weapons = ["rock", "paper", "scissors"];

// set the computer random choice
function getComputerChoice() {
  const choice = weapons[Math.floor(Math.random() * weapons.length)];
  return choice;
}

function checkWinner(playerSelection) {

  const computerSelection = getComputerChoice();

  if (playerSelection == computerSelection) {
    result_p.textContent = "Tie";

  } else if ((playerSelection == "rock" && computerSelection == "scissors") ||
    (playerSelection == "scissors" && computerSelection == "paper") ||
    (playerSelection == "paper" && computerSelection == "rock")) {
    result_p.textContent = "player Winnnn";
    playerPoint++;
    userScore_p.innerHTML = playerPoint;
  } else {
    result_p.textContent = "Player lost!!!!";
    computerPoint++;
    computerScore_p.innerHTML = computerPoint;
  }
  console.log(computerSelection)
  console.log(playerSelection);
}
<button id="rock">rock</button>
<button id="paper">paper</button>
<button id="scissors">scissors</button>

  HUMAN

0

  MACHINE

0

  RESULT

Comment: I corrected my code but with the your guide and it's work. I still couldn't figure out how to set five round game. I try many ways and I can't find any answer and it's none stop game.


How does core triggers cleanup of expired sessions in database?

Question: core/lib/Drupal/Core/Session/SessionHandler.php defines a method (gc()) to clear expired sessions from the database (sessions table)
when is that triggered ? is there a way to trigger it from the interface ?
i know i can just truncate sessions manually or with a cron or a custom drush command..., but i wonder how does core uses it and what triggers it by default
Thanks
Comment: I can't say 100% without looking into it fully but my likely guess is part of a cron run, probably by system_cron function in the system.module
Comment: looked at system_cron() but it doesn't seem to do so. at least not directly.
Answer:
Configuring Garbage Collection
When a session opens, PHP will call the gc handler randomly
  according to the probability set by session.gc_probability /
  session.gc_divisor. For example if these were set to 5/100
  respectively, it would mean a probability of 5%. Similarly, 3/4 would
  mean a 3 in 4 chance of being called, i.e. 75%.
If the garbage collection handler is invoked, PHP will pass the value
  stored in the php.ini directive session.gc_maxlifetime. The
  meaning in this context is that any stored session that was saved more
  than gc_maxlifetime ago should be deleted. This allows one to expire
  records based on idle time.
However, some operating systems (e.g. Debian) do their own session
  handling and set the session.gc_probability variable to 0 to stop
  PHP doing garbage collection. That's why Symfony now overwrites this
  value to 1.
If you wish to use the original value set in your php.ini, add the
  following configuration:
# config/packages/framework.yaml
framework:
    session:
        gc_probability: null

Source: Symphony's official docs on Configuring Sessions and Save Handlers

In Drupal this is seen in /sites/default/default.settings.php
/**
 * Some distributions of Linux (most notably Debian) ship their PHP
 * installations with garbage collection (gc) disabled. Since Drupal depends on
 * PHP's garbage collection for clearing sessions, ensure that garbage
 * collection occurs by using the most common settings.
 */
ini_set('session.gc_probability', 1);
ini_set('session.gc_divisor', 100);

Since the above "most common settings" is set to 1/100, Garbage Collection would run 1% of the time.
Now, as per the code comment, I presume this does not get put into settings.php when it gets auto-generated if your distribution has one already set one in one of its files as I don't see this in my settings.php
You can also set this in services.yml as seen in this answer.

In Conclusion
Note that while Drupal is built on top of Symphony, it does not rely on Symphony for this. I just quoted their nice explanation from their documentation.
We learned that PHP automatically calls this gc() method every session.gc_probability/session.gc_divisor % of the time and if you look at PHP docs on SessionHandler.

SessionHandler is a special class that can be used to expose the
  current internal PHP session save handler by inheritance. There are
  seven methods which wrap the seven internal session save handler
  callbacks (open, close, read, write, destroy, gc and create_sid).
Source: http://php.net/manual/en/class.sessionhandler.php

core/lib/Drupal/Core/Session/SessionHandler.php
/**
 * Default session handler.
 */

class SessionHandler extends AbstractProxy implements \SessionHandlerInterface { ...

 /**
   * {@inheritdoc}
   */
  public function gc($lifetime) {
    // Be sure to adjust 'php_value session.gc_maxlifetime' to a large enough
    // value. For example, if you want user sessions to stay in your database
    // for three weeks before deleting them, you need to set gc_maxlifetime
    // to '1814400'. At that value, only after a user doesn't log in after
    // three weeks (1814400 seconds) will his/her session be removed.
    $this->connection->delete('sessions')
      ->condition('timestamp', REQUEST_TIME - $lifetime, '<')
      ->execute();
    return TRUE;
  }

Comment: `Now, as per the code comment, I presume this does not get put into settings.php when it gets auto-generated if your distribution has one already set >one in one of its files as I don't see this in my settings.php`
Actually this is in default.services.yml file in the site folder.
Comment: i configured gc_probability and gc_divisor to 100 (both). i also configured gc_maxlifetime to 20  in default.services.yml and in php.ini (just to be sure)
I still have very old sessions in sessions table meaning that the ->gc() method wasn't fired event after login/logout.
i still don't know how this can be executed by Drupal core . is the execution order missed between php and symfony or between symfony and Drupal or something else i still ignore
Comment: First of all, if you want to put it in the yml file, copy default.services.yml and rename it services.yml; otherwise, when you update core you will lose your changes.
Comment: Second, most importantly, I am sure your `gc` method is running at some point. If you look carefully what Drupal's `gc()` method does (which is exactly why I included it in my answer) and if you read the `gc` code comments, it checks against if `php_value session.gc_maxlifetime` have passed since the last time the user has logged in. If your `php_value
 session.gc_maxlifetime` is set to 3 weeks or a year, the old sessions will not be getting deleted any time soon no matter how many times `gc` runs
Comment: Take a look at [this answer](https://drupal.stackexchange.com/a/215632/27710) which sets the max life time.


Reasons to prefer low bias with higher variance over the alternative (and vice versa)

Question: I am trying to understand the bias-variance tradeoff in practice. I have read several related questions and answers, but still have a few questions:

Assume we are estimating a structural equation model (SEM) and we are able to choose between two estimators: one with high bias but low variability, and one with low bias but high variability. In what settings would a researcher prefer the first vs. the latter?

Related to the first question: with lowest MSE values representing the optimal tradeoff between variance and bias, would it ever make sense to choose an estimator with higher MSE values over one with lower MSE values? If so, when?

If we'd pick the less biased version, would meta-analyses be useful to attenuate the high variance issue?
Answer: a) Neither bias nor imprecision are desirable, and I don't recall anyone arguing that one is (in principle) worse than the other.  The issue is that they are both reasons why your sample statistic differs from the population parameter it estimates.  Bias and imprecision could be relatively worse in a particular condition or using a particular estimator, which is what the trade-off is all about (see next point).
b) No, you would never prefer an estimator with higher (R)MSE. (Root-)mean-squared error sums the (squared) bias and sampling variance, so it is a composite summary of "how incorrect you can expect your estimate to be, on average," taking both bias and imprecision into account.  Thus, (R)MSE provides a reasonable way to compare one estimator that is biased but precise vs. another that is imprecise but unbiased.
c) Yes, if the meta-analysis aggregates a sufficient amount of data, then it could overcome the lack of precision of unbiased estimation. But finding unbiased results is a huge practical problem for meta-analysis (e.g., publication bias).
Comment: +1, this is a good answer, but re #2, note that a standard recommendation (eg, in ESL) is to use the lambda associated w/ the simplest model that is w/i 1 SE of the minimum.  That means you are preferring a higher RMSE.


Local web app not resolving localhost

Question: I have a local web site called http://localhost.example.com but now when I try to open it in a web browser it redirects me to http://www.example.com. This used to work before. What I changed in the system was the configuration of AWS CLI and the Bitbucket local configuration in order to use two different accounts. Nothing more. I believe that changes are irrelevant. Aren't they?
All the information and files I provide are from local workstation. I'm using OS X 10.12 (beta 2).
The relevant part of /etc/hosts is this:
127.0.0.1   localhost
255.255.255.255 broadcasthost
::1 localhost

127.0.0.1   localhost.example.com
127.0.0.1   babydiapi.example.com
127.0.0.1   localhost.mi.example.com
127.0.0.1   localhost.qr.example.com
127.0.0.1   localhost.pay.example.com
127.0.0.1   playground.com
127.0.0.1   payments.com
127.0.0.1   localhost.comunidad.example.com
126.96.36.199  web1.example.com
18.104.22.168  web2.example.com
188.8.131.52 web3.example.com

But I make ping localhost.example.com I get this:
PING localhost.example.com (22.214.171.124): 56 data bytes
64 bytes from 18.104.22.168: icmp_seq=0 ttl=49 time=166.894 ms

I tried to do ping http://localhost.example.com but it didn't worked:
ping: cannot resolve http://localhost.example.com: Unknown host

I suppose this is a normal behavior.
Which is the staging server for my application. Clearly not localhost.
I read somewhere that I should use host localhost.example.com, but I still get this:
localhost.example.com has address 18.104.22.168

I use Nginx as my local web server, the configuration looks like this:
server {
    listen   127.0.0.1:80;
    listen   127.0.0.1:443 ssl;
    server_name localhost.example.com;
    server_name_in_redirect off;
    error_page 404 /www/error/404.html;
    error_page 503 /www/error/404.html;

    ssl_certificate /usr/local/etc/nginx/ssl/localhost.crt;
    ssl_certificate_key /usr/local/etc/nginx/ssl/localhost.key;

    access_log /usr/local/etc/nginx/logs/www.example.com.access.log;
    error_log /usr/local/etc/nginx/logs/www.example.com.error.log;

    location ~ ^/(.*)/$ {
         rewrite ^/(.*)/$    /$1 permanent;
    }

    location ~* ^.+(\.jpg|\.jpeg|\.gif|\.png|\.js|\.ico|\.woff|\.ttf|\.eot|\.css)$ {
        root /www/www.example.com/webroot;
        access_log        off;
        expires          365d;
    }
    location / {
        root   /var/www/www.example.com/webroot/;
        index  index.php index.html index.htm;
        if (-f $request_filename) {
            break;
        }
        if (-d $request_filename) {
            break;
        }

        if (-f $request_filename) {
            break;
        }

        # Trigger 503 response on maintenance
        set $mantenimiento 0;
        if (-f /var/www/www.example.com/.mantenimiento) {
            set $mantenimiento 1;
        }
        if ($remote_addr = 127.0.0.1) {
            set $mantenimiento 0;
        }
        if ($mantenimiento) {
            return 503;
        }

        if (!-f $request_filename) {
            rewrite ^/(.+)$ /index.php?url=$1 last;
            break;
        }

    }
    location ~ .*\.php[345]?$ {
        set  $script     $uri;
        set  $path_info  "";

        if ($uri ~ "^(.+\.php)(/.+)") {
          set  $script     $1;
          set  $path_info  $2;
        }
        include fastcgi_params;
        fastcgi_pass    127.0.0.1:9000;
        fastcgi_index   index.php;
        fastcgi_param SCRIPT_FILENAME /var/www/www.example.com$fastcgi_script_name;
        fastcgi_param  SCRIPT_NAME      $script;
        fastcgi_param  PATH_INFO        $path_info;
        fastcgi_buffer_size 128k;
        fastcgi_buffers 4 256k;
        fastcgi_busy_buffers_size 256k;
        fastcgi_read_timeout 300;
    }

    location @error_web {
        root /var/www/error;
        index 404.html;
    }
 }

Do you have any ideas or hints? I have been looked over the internet for about a week and found nothing helpful.
Comment: Could you please execute: cat /etc/nsswitch.conf and send us the result?
Comment: Is that host file on your server or your workstation? Are you doing the testing from the server or your workstation? What OS are you using? Suggest you clarify the question.
Comment: Thanks, I have just updated the question. It's my local workstation I'm testing from. I use OS X 10.12 beta 2.
Comment: You're using OS-X for your workstation and server? You've said all configuration files are for your location workstation, but you have a ping time of 160ms, which suggests Nginx is running on a server which probably has a different OS. You should also include relevant logs.
Comment: No, Nginx is running on my local machine, but when I ping it it shows the IP of the staging server (which is located in Linode running Debian) and not 127.0.0.1. Which logs should be relevant?
Comment: `cat: /etc/nsswitch.conf: No such file or directory` I believe this file doesn't exist in OSX/macOS
Answer: I'm curious as to whether your /etc/hosts is no-longer the same as /private/etc/hosts. From my 10.11.5 machine, I see that they should be a hard link (same inode number as seen in the first field in the ls -li output below:
Camerons-MacBook-Air:~ cameron$ ls -li /private/etc/hosts /etc/hosts
12484749 -rw-r--r--  1 root  wheel  247 15 Jul 21:01 /etc/hosts
12484749 -rw-r--r--  1 root  wheel  247 15 Jul 21:01 /private/etc/hosts

Is this still the case for you? Do /etc/hosts and /private/etc/hosts refer to the same file on disk?
On a Linux host, I would have also wondered about /etc/nsswitch.conf, but I see OS X doesn't seem to have that; I'm not sure what it would use instead though. This file controls the lookup-method order for resolving names such as user-names or host-names.
Cheers,
Cameron
Comment: Thanks, this was a starting point for finding the problem. However, the solution was provided by the other answer. I appreciate your help.
Answer: I'd love to test this for you but I don't have OSX.
There is some discussion out there about this problem. People are saying formatting issues (missing/lack of/incorrect hidden characters) in the hosts file can lead to it being ignored. See the following question and scroll down to the answers and comments.
https://apple.stackexchange.com/questions/158117/os-x-10-10-1-etc-hosts-private-etc-hosts-file-is-being-ignored-and-not-resol
You can look into this craziness also. Again to do with formatting of the hosts file.
https://github.com/devopsgroup-io/vagrant-hostmanager/issues/60
What editor are you using? Can you rewrite the whole file carefully using vi, nano or some other Unix editor?
Don't use host or nslookup, dig, etc... they will bypass the hosts file and query DNS servers. Keep on trying with ping localhost.domain.com until you get 127.0.0.1.
Comment: Thanks, I cannot believe I didn't try this out first. The las time I edited the file I was using Sublime , and in the bash history that was on the top last commands so I always used this. I tried now with vim and there it's clearly about line endings, so I want back to Sublime and changed the line ending configuration to Unix. Thanks a lot.
Comment: @VladimirNul You're welcome. Can I have the bounty?
Comment: Of course, it says I have to wait 14 hours, but I will as soon as I can.
Comment: It should be OK now
Comment: sometimes its just the local DNS cache and could be cleared by `dscacheutil -flushcache && sudo killall -HUP mDNSResponder`

Local web app not resolving localhost


Missing step in this proof of $\operatorname*{rank}(A+B) \leq \operatorname*{rank}A + \operatorname*{rank}B$

Question: I know how to prove this inequality using bases for the row space, however, my professor presented a proof of
\begin{align*}
  \operatorname*{rank}(A+B) \leq \operatorname*{rank}A + \operatorname*{rank}B
\end{align*}
using rank-nullity theorem. He fell sick so he just sent the notes, which I don't understand, can someone please help me.
\begin{align*}
  n - \operatorname*{null}(A+B) &\leq 2n - \operatorname*{null}A -\operatorname*{null}B \\
  \operatorname*{null}(A+B) &\geq -n + \operatorname*{null}A + \operatorname*{null}B \\
  \operatorname*{null}A + \operatorname*{null}B &\leq n + \operatorname*{null}(A+B)
\end{align*}
Then it suffices to prove this inequality.
\begin{align*}
  N(A) \cap N(B) \subseteq N(A+B)
\end{align*}
I understand why this is true, but I don't understand the next line
\begin{align*}
  \operatorname*{null}A + \operatorname*{null}B \setminus (N(A) \cap N(B)) \leq n
\end{align*}
Not only does this not make sense from the sense of 'where does $n$ come from', it also, if I understand correctly, makes no sense from the mathematical standpoint. He probably meant $\dim(N(A) \cap N(B))$
Hence,
\begin{align*}
  \operatorname*{null}A + \operatorname*{null}B \leq n + \dim(N(A) \cap N(B)) \leq n + {\rm null}(A+B)
\end{align*}
This last statement makes sense from the fact above that $N(A) \cap N(B) \subseteq N(A+B)$
If anyone knows how to prove this using rank-nullity theorem or understands what happened here, please let me know.
Comment: @JoséCarlosSantos None of the answers in the "duplicate" answers the OP's question (see my previous comment).
Comment: @AnneBauval Right. It's open once again.
Comment: @IrvingRabin It doesn't. The OP's question is not "how to prove this inequality" but "Please explain one step in the following proof".
Comment: There is now a new close vote for "needs details or clarity". I really wonder why. I found this post really clear and well detailed. (+1)
Answer: Assuming $A,B$ are linear maps defined on a vector space $E$ of dimension $n$ (this answers your 'where does $n$ come from', which you should have asked earlier in your post), your professor first used the rank-nullity theorem, to reduce the task to proving
$$\operatorname*{null}A + \operatorname*{null}B\le n + \operatorname*{null}(A+B).$$
Then, he implicitely applied Grassmann's formula: for any two subspaces $F,G$ of $E,$
$$\dim(F)+\dim(G)-\dim(F\cap G)=\dim(F+G)\le n$$
to $F=N(A)$ and $G=N(B).$ This is why he (nearly) wrote
$$\operatorname{null}(A)+\operatorname{null}(B)-\dim(N(A)\cap N(B))\le n.$$
So you rightly guessed his "$\setminus(N(A)\cap N(B))$" was a typo and meant "$-\dim(N(A)\cap N(B))$".
Since the rest was clear, you are done.
Answer: For any two subspaces $A$ and $B$,
$$\dim(A)+\dim(B)-\dim(A\cap B)=\dim(A+B)$$
Indeed, let $A∩B$ have basis $\{u_i\}$, A have basis $\{u_i\}∪\{a_i\}$, and B have basis $\{u_i\}∪\{b_i\}$. Suppose there is a nontrivial linear combination of these basis vectors with a nonzero coefficient for some $a_i$. Then there exists a vector $x$ in $B$ that can be expressed as a linear combination of $a_i$'s. However, $x$ is also contained in $A∩B$ and can thus be expressed as a linear combination of $u_i$'s, which contradicts the fact that $\{u_i\}∪\{a_i\}$ is a basis of $A$. Therefore,$ \{u_i\}∪\{a_i\}∪\{b_i\}$ is a basis of $A+B$ and the formula is proven.
Comment: Duplicate: https://math.stackexchange.com/questions/317294
Answer: Presumably $A,B$ are defined on a linear space $V$ of dimension $n$.
There seems to be a typo en the solution given to the OP or a transliteration. In any case here is a short proof of
\begin{align*}
  \operatorname*{null}A + \operatorname*{null}B \leq n + \dim(N(A) \cap N(B)) \leq n + {\rm null}(A+B)
\end{align*}
where $\operatorname{null}(A):=\dim(N(A))$, $N(A):=\{x\in V: Ax=0\}$.

Let $A'$ be the restriction of $A$ to $N(B)$. Then
$N(A')=N(A)\cap N(B)$ and so
$$\dim(N(B))=\dim(N(A)\cap N(B))+\operatorname{rank}(A')$$
Hence
\begin{align}
\dim(N(A))+\big(\dim(N(B))-\dim(N(A)\cap N(B))\big)&=\dim(N(A))+\operatorname{rank}(A')\\
&\leq \dim(N(A))+\operatorname{rank}(A)=n
\end{align}


create instances and store them in array

Question: I have a student class and every student instance created needs to be stored in an array.attributes can be given in program or read from user input.how do I extend my main() method to store it? i am stuck .
Here is my student class code:
public class student {

    int   studentID;
    String studentName,gender,course;
 /** set the student name
  * @param studentName
 */
 public  void        setName(String studentName){
this.studentName = studentName;
 }
  /**
  * set student ID number
  * @param studentID
   */
   public  void        setNewId(int studentID){
   this.studentID = studentID;
  }
   /**
   * Set student gender
   * @param gender
   */
   public void setGender(String gender){
  this.gender = gender;
 }
 /**
  * set the course
  * @param course
  */
   public  void        setCourse(String course){
   this.course = course;
 }
 /**
  *Gets the Student's ID Number.
  *@return IdNumber Student ID Number.
  */
  public  int      getIdNumber(){
return studentID;
 }

  /**
  *Gets the Student's Name.
  *@return studentName Student Name.
  */
 public  String      getName(){
return studentName;
 }
 /**
  * Get student gender
  * @return
   */
 public String getGender(){
  return gender;
 }
 /**
  *Gets the Student's Course.
  *@return course Student Course.
  */

  public  String     getCourse(){
return course;
  }
  /**
  *Prints Student Informations.
  *@return Student ID Number, name, gender and course.
    */

  public void printStudent(){
 System.out.print(studentID+""+studentName+""+gender+""+course);
}
}

And here is my main class with main() method that needs the array:
public class SMSMain {
    /**
     *
     * @param args
     */
    public static void main(String[] args) {
    // Create an instance of student object

    student a = new student();
    a.studentName = "Maria";
    a.studentID = 1236;
    System.out.println("Student Name:" + a.studentName);
    System.out.println("Student ID:" + a.studentID);
}
}

Comment: First declare and initialize an array of Student[] in the main method (note that the first letter of a class should be capitalized). Then fill it with Student instances. You should show us your attempt to do this so we can better understand just what you need help with.
Comment: Kindly remove all code from your post that is not *directly* relevant to the question (that would be most of your code btw).
Answer: You need to initiate the array and create objects within loop.
   Student[] students;
    System.out.println("Enter number of students :");

    DataInputStream in = new DataInputStream(System.in);
    int n = in.readInt();
    students = new Student[n];
    for(int i=0; i<n ;i++) {
        students[i] = new Student();
        System.out.println("Name:");
        students[i].setName(in.readLine());
        System.out.println("Id:");
        students[i].setNewId(in.readInt());
     }

Comment: Thanks tsatiz, it is not home work, just book exercise i am doing because i am self learning java.
Comment: You should not post answers in Homework questions. Although we know the user didn't said it's homework, it's somewhat clear that he's learning, and instead of telling him the answer, we should help him to get to the answer with his own legs.


forcefully / manually remove content type

Question: Is it possible to manually remove a content type?
I've packaged it in a feature and now the content type is no longer needed; it's been deprecated. I'm unable to delete the content type after disabling the feature in the features panel and in the modules page.
Answer: If you have devel install then go to sitename/devel/php and execute the following code.
<code>node_type_delete('content_type_machine_name');
</code>
else you can run the same code inside hook_init() of your custom module.
Hope it helps.


"Sharp" Inequalities

Question: When we say that an inequality is sharp, does it mean that it is "the best" inequality we can get between the two quantities involved?
For example, I read that we would say that the inequality
$$
\frac{a^2+b^2}{2}\geq ab
$$
is sharp, but wouldn't $\frac{a^2+b^2}{2}$ on the RHS be sharper than $ab$?
Do we just mean that we can't multiply the RHS of $\cdot\geq\cdot$ by a constant $>1$ (or equivalently that we can't multiply the LHS by a constant in $[0,1)$)? So that would be a "best" inequality in this sense?
Comment: Your last paragraph is correct: Notice that if $a=b$ we have equality, so we can't make the LHS larger or the LHS smaller without the inequality being violated.
Comment: so there is no difference between sharp and tight, right?
Answer: Here is another definition of sharpness that demonstrates that the inequality is optimal (i.e., best-possible).
If $f,h:\mathbb{R}^n \longrightarrow \mathbb{R}$ and
\begin{equation}
f(x) \geq h(x),~\forall x \in S \subseteq\mathbb{R}^n, \tag{1} \label{ineq}
\end{equation}
then \eqref{ineq} is called sharp if $\exists s \in S$ such that $f(s) = h(s)$.
Why is this inequality the best possible inequality? Suppose that \eqref{ineq} is sharp as defined above. For contradiction, if $g:\mathbb{R}^n \longrightarrow \mathbb{R}$ is a function such that
\begin{equation}
f(x) > g(x) \ge h(x),~\forall x \in S
\end{equation}
then $f(s) > h(s)$, a contradiction. Thus, the inequality is the best-possible.
Comment: So basically, if an inequality can be changed to a strict one, then it isn't sharp?
Comment: @AlexanderJ93: Indeed; for instance, the inequality $|x| \geq -1$, which is valid for every real number $x$, is not sharp since $|x| > -1$ is also valid for all $x$.
Comment: @AlexanderJ93: Notice also that $|x| > |x| - 1 \geq -1$ and the inequality $|x| - 1 \geq -1$ is (obviously) sharp.
Comment: @PietroPaparella What about the specific case where $s$ is such that $f(s)=0$ and hence any multiplicative constant $C$ preserves sharpness? I have asked this [follow-up question](https://math.stackexchange.com/q/4767415/342439).
Comment: @MorrisFletcher: nothing changes: suppose that $f(x) \ge g(x), \forall x \in S \subseteq \mathbb{R}^n$ and $\exists s \in S$ such that $f(s) = g(s) = 0$. If $\exists h: \mathbb{R}^n \longrightarrow \mathbb{R}$ such that $f(x) \ge h(x) > g(x), \forall x \in S$, then $0 = f(s) \ge h(s) > g(s) = 0$, a contradiction.
Answer: As was said, many times bounds are not as strong as they theoretically could be. In math, this comes because a specific quality is hard to compute. A basic example is computing world population-- you could say "The population of the world is greater than 3 billion." but this inequality might not be very good.
So by saying an inequality is sharp, it means that a theoretical maximum has been reached and there's no room for improvement for that particular inequality. However, there could of course be other inequalities with the same LHS or RHS.

"Sharp" Inequalities


Como importar um arquivo .xls no R mantendo os nomes com acentos nas variáveis categóricas?

Question: Fiz a importação de um arquivo em .xls que contém colunas com nomes de drogas e sua classe. Alguns nomes têm acento como "Antipsicótico", "Benzodiazepínico" e "Antidepressivo Tricíclico". Usei o read.xlsx conforme abaixo:
require(xlsx)
AskStack <- read.xlsx("file.xlsx",sheetIndex = 1)

E quando chequei o data.frame vi que os nomes estavam com modificações de encoding conforme verão adiante:
> dput(AskStack)
structure(list(Medic.1 = structure(c(24L, 13L, 15L, 3L, 32L,
9L, 2L, 17L, 15L, 21L, 25L, 32L, 17L, 21L, 9L, 9L, 15L, 15L,
26L, 31L, 31L, 31L, 20L, 31L, 21L, 24L, 21L, 31L, 24L, 17L, 2L,
32L, 31L, 23L, 26L, 25L, 31L, 11L, 31L, 12L), .Label = c("alprazolam",
"Alprazolam", "Amitriptilina", "Bupropiona", "citalopram", "clomipramina",
"clonazepam", "Clonazepam", "Desvenlafaxina", "Diazepam", "Donarem",
"Donaren", "Duloxetina", "escitalopram", "Escitalopram", "fluoxetina",
"Fluoxetina", "fluvoxamina", "imipramina", "Imipramina", "Olanzapina",
"paroxetina", "Pondera", "Quetiapina", "Quetros", "Risperidona",
"Rivotril", "Sem uso informado", "sertralina", "Trazodona", "Venlafaxina",
"Venlaxin"), class = "factor"), classe = structure(c(2L, 4L,
4L, 1L, 5L, 5L, 3L, 4L, 4L, 2L, 2L, 5L, 4L, 2L, 5L, 5L, 4L, 4L,
2L, 5L, 5L, 5L, 1L, 5L, 2L, 2L, 2L, 5L, 2L, 4L, 3L, 5L, 5L, 4L,
2L, 2L, 5L, 4L, 5L, 4L), .Label = c("Antidepressivo Tricíclico",
"Antipsicótico", "Benzodiazepínico", "ISRS", "ISRSN", "não se aplica"
), class = "factor")), row.names = c(NA, 40L), class = "data.frame")

Como faço para importar sem a necessidade de alterar manualmente depois da importação?
Comment: Tente especificar o `enconding` na função `encoding = "UTF-8"`. Que o problema deve estar por aí.
Answer: Você pode usar o pacote readxl, que resolve o problema automaticamente:
> library(readxl)
> read_xlsx("Drogas.xlsx")
# A tibble: 3 x 1
  Drogas
  <chr>
1 Antipsicótico
2 Benzodiazepínico
3 Antidepressivo Tricíclico

Eu particularmente prefiro o readxl para ler arquivos do excel em R.


keep getting syntax error in python

Question: I'm doing the MIT open courseware class 6.00 Introduction to Computer Science and Programming and I'm stucked in the problem 2 of the 8th assignment where I'm supposed to create a greedy algorithm to give students the best subjects possible depending on a value, work relationship.
this is the part of my code where i get a syntax error and can't seem to figure out what's wrong:
subjects={'6.00':   (16,   8),'1.00':   (7,    7),'6.01':   (5,    3), '15.01':  (9,    6)}

def greedyAdvisor(subjects, maxWork, comparator):
    """
    Returns a dictionary mapping subject name to (value, work) which includes
    subjects selected by the algorithm, such that the total work of subjects in
    the dictionary is not greater than maxWork.  The subjects are chosen using
    a greedy algorithm.  The subjects dictionary should not be mutated.

    subjects: dictionary mapping subject name to (value, work)
    maxWork: int >= 0
    comparator: function taking two tuples and returning a bool
    returns: dictionary mapping subject name to (value, work)
    """

    bestSubjects={}
    currentWork=0
    NA=['0']
    while currentWork<maxWork:
        candidate=find_best_sub(subjects,comparator)
        candidate_work= find_work(candidate)
        if candidate_work+currentWork<=15:
          d2={candidate:subjects[candidate]
          NA.append(candidate)
          bestSubjects.update(d2)
          currentWork+=candidate_work
        elif candidate_work+currentWork>15:
              continue
      return bestSubjects

def find_best_sub(subjects,comparator, NA):
    """returns the best subject according to a comparator, the subject must be available so if it's in the NA list it wont be considered"""
  subs= subjects.keys()
  subs=list(subs)
  best_subject='1.00'
  for subject in subs:
    if subject not in NA:
        if comparator(subjects[subject],subjects[best_subject])== True:
          best_subject= subject
        elif comparator(subjects[subject],subjects[best_subject])== False:
          continue
  return best_subject

def find_work(subjects,sub):
  work=sub[WORK]
  return work

Comment: "this is the part of my code where i get a syntax error" - that looks a lot like *all* your code. What did you try to narrow down the problem?
Comment: Also, just saying "I get a syntax error" makes your code very hard to debug. Paste the actual error, with traceback. Even if that looks like gobbledegook to you, it's incredibly useful to the people trying to help you.
Comment: @afkfurion: Don't edit the syntax error out of a question about a syntax error.
Answer: As can often happen, the erroring line is one above the one being reported:
      d2={candidate:subjects[candidate]
      NA.append(candidate)

In this case you aren't closing the brace in d2 declaration
      d2={candidate:subjects[candidate]} #<--- here
      NA.append(candidate)

Answer:           d2={candidate:subjects[candidate]
          NA.append(candidate)

You dropped a brace.
Next time, look at the error message:
    NA.append(candidate)
     ^
SyntaxError: invalid syntax

then look at the line it's pointing to and the line above it.

keep getting syntax error in python


Guitar for child

Question: My 6-year old has shown interest in playing guitar when I am playing mine. My guitar is way too big for her small hands. Are half-sized guitars useful for learning? Or should I think about something like a ukelele instead?
This would not be for formal lessons, just for playing with dad.
Comment: I'd say the small guitars (three quarters, half, etc.) are designed for this sort of thing, so go for it. I vaguely remember a resource or two where scale lengths for different sizes were mentioned, but I can't find it right now. Also, I would buy from a shop so I could check out the neck size in person, before buying it.
Answer: I think it is wonderful that your child is showing an interest in playing an instrument and making music.  You should certainly encourage that desire in any way possible.
There are many very good quality smaller size guitars that might be a good fit for a six year old.  In order to increase the chances that your child will actually find the experience rewarding enough to stick with it as she gets older, you should get her the best quality smaller size guitar you can afford.  Avoid the ones that are sold in the toy department at Walmart.
Name Brand Guitar makers such as  Yamaya, Taylor and Martin - all make guitars that are smaller scale.  Sometimes they call them travel guitars and they can certainly be used that way.  I personally love the Baby Martins because they sound awesome for such a small guitar.  Taylor makes the Baby Taylor and Martin makes several versions of their Little Martin such as the LX1.  Yamaha makes the Yamaha Junior.
To make the smaller guitar even easier on tender fingers you might consider restringing it with a custom finger friendly string set like the one described here.  Custom Finger Friendly String Set for Beginning Guitarist
Of course a ukulele is easier to play and easier to learn.  But it is not a guitar.  I own a ukulele but rarely play it because I personally prefer the way my guitars sound.  My uke is a solid mahogany baritone uke but still sounds thin compared to even my Taylor GS Mini Travel Guitar.
But since ukuleles can be very inexpensive, and even the lower priced ones are relatively easy to play, you could get both a pair of ukes and a good quality short scale guitar.  If your child gives up on the guitar, you will have a travel guitar to take on vacation.
Enjoy your time making music together with your child.
Answer: I would go ukulele first, personally. A friend of mine who is a music teacher of primary school children (same age as your daughter) has bought ukuleles for her whole class and swears by them; they all absolutely love them - it's a fun, not too serious instrument that they actively enjoy learning.

They are easy to pick up and put down. You can easily take them anywhere.
The neck is far easier to play for child sized hands than even the small-bodied guitars, and the strings much more forgiving.
Fewer fingers to organise - I got my two and a half year-old (briefly) playing a C chord successfully because it's just one finger :)
Psychologically for the child, I think they seem closer to toys, so they are less intimidating to grab and mess around on.
Psychologically for the parent, they are cheaper and feel more robust than guitars, so if you are a bit of a worrier you'll be able to just let her do what she wants with it rather than trying to make sure it's all put away carefully etc. I think the more ownership she feels, the more she'll play it - my own pet theory only, nothing to back that up :)
You could chat to her close friends' parents and see if you can find one who might like to also get one, then they can take them round to each other's houses and swap tips. Or you could get one for your four year old as well, but I suspect this would cause more arguments than playing with a similar-aged friend!

One final point, as you are intending this to just be playing along with daddy rather than formal lessons - you could treat it as a transposing instrument and teach her the guitar names for the chord shapes - so instead of calling it a C, call it a G etc. Then if she does want to move on to the guitar, she'll know a good few chords already.
(As an anecdotal example of the last point, I did this the other way round when helping my wife, who had learned the guitar years ago, to play the ukulele - we started using the actual chord names, but as soon as we switched to the guitar ones she picked it up instantly as the old memories kicked in.)
Answer: Buy 2 ukeleles, one for you and one for daughter. Then you can have fun together.  A few years ago I had to learn to play ukelele to teach a girl, with learning dificulties, having trouble with guitar.I now play it regularly and 2 of my friends now play them as well as guitar. It is great for holidays as you can put it in your luggage.
Having taught children of various ages I think even a half size guitar is to big for an average 6 year old.
Comment: Maybe I should get one for my 4 year old, too. I'm sure Mom will appreciate the cacophony. :) Seriously, though, I hadn't considered getting a pair of them, though I was leaning towards a ukelele so I could play it myself.

Guitar for child


Limitação de Session para guardar dados

Question: Tenho um query lenta no Oracle para listar todos os acessos de um usuário, então pensei em gravar o resultado em uma Session, a media de registros retornados é 600, é muito para uma Session?
Teria alguma outra forma melhor de se guardar esses dados?
Answer:
A média de registros retornados é 600, é muito para uma Session?

Não. Sessions em teoria não possuem limite de armazenamento.

Teria alguma outra forma melhor de se guardar esses dados?

Sim, em um servidor de presistência chave-valor, como o Redis. Sessions te limitam a apenas um servidor, enquanto que o Redis pode atendê-lo em um contexto distribuído.
Answer: Não tem uma questão de ser muito para a sessão, pode ser muito para a memória que você tem disponível. Se você tiver 600 registros na sessão, é pouco. Se se você tiver 1000 sessões simultâneas, 600 mil pode ser muito, pode não ser.
Eu respondi algo sobre isto, ali falo que a melhor solução é um sistema de cache. Ele é mais adequado na maioria das situações porque pode ser liberado se necessário e dura além das sessões, que em muitos cenários pode ser um ganho interessante. Lá eu falo para não exagerar na carga da session. Mas falo de exagerar mesmo. E o tamanho do exagero depende da memória disponível.
Lembre-se que o banco de dados tem um cache também (veja como implementar na resposta do OnoSendai). Pode ser que ele seja suficiente também. Mediu para ver se realmente precisa manter algo em memória? Tem ganho razoável? Sem medir não dá para afirmar nada. Mesmo que seja intuitivo, às vezes, na prática, pode ocorrer algo diferente do esperado.
Se perceber que precisa de um outro nível de cache, procure uma solução em memória no mesmo servidor. Isto deve resolver 99,99% dos casos. Se você tem um caso raro na mão e precisa escalar horizontalmente, procure um software que ajude nisto, tipo um Memcached, Redis, etc.
Há um framework que ajuda nisto e possui diversas opções. Na página deles confirma que o cache mais simples é o mais rápido e que bancos de dados servem mais quando há necessidade de distribuição entre processos (onde a performance é absurdamente inferior, ao ponto de ser pouco útil como cache em alguns cenários). O uso de dicionário também é o que ocupa menos memória, o que é útil para dar espaço para mais conteúdo útil.
Answer: Como Cigano e Maniero disseram, não, não há limites.
Porém se seu problema é performance em uma base de dados Oracle, eu tenho uma sugestão: Materialized Views.
Uma Materialized View é basicamente um snapshot de uma query cacheada no banco de dados, que pode ser indexada.
Este é um exemplo de criação de Materialized View:
CREATE MATERIALIZED VIEW MV_LOGINS_USUARIO_52
NOLOGGING
CACHE
BUILD IMMEDIATE
REFRESH FAST ON COMMIT
AS
[Sua query aqui]

Uma vez criada, a view conterá o resultado da última consulta até que seja destruída ou refrescada. Como você não está executando a query de novo, mas apenas acessando dados cacheados, o tempo de resposta é muito superior.
A vantagem deste método é que você não consome recursos do servidor web.
Comment: @Rod eu prefiro Redis para outras coisas. Se não há necessidade de cache distribuído, a adição de um serviço apenas para guardar cache de consulta é desnecessária.
Comment: Gostei da solução =D, mas ainda prefiro redis
Comment: bem pelo contrário, usar o redis para deixar dados de db, dependendo da disponibilidade, é ótimo, já pensou se for uma tabela que há pouca ou nenhuma mudança(valores fixos) e sendo bem acessada por um grande número de usuários? ficaria muito de boa =D. Por curiosidade, em quais casos você utiliza o redis? Se não para armazenar dados..rsrs
Comment: @Rod como mencionei, uso Redis para cache distribuído. Se não há necessidade de coordenar o cache entre vários servidores - ou, como no caso do OP, o conteúdo a ser cacheado por ser centralizado no banco de dados mesmo - então a adição de um serviço extra não é justificável; existem várias camadas disponíveis nativamente (System.Web.Caching, System.Runtime.Caching, MemoryCache, etc.) Uma boa arquitetura possui o mínimo de partes móveis necessário.
Comment: Gostaria de ver mais perguntas/respostas sobre o assunto, parece algo muito interessante e útil. +1

Limitação de Session para guardar dados


Empty file when Request.Files

Question: I'm working with C# and MVC3 and I'm trying to upload a text file that I know is not empty, but when I access the file (when debugging) via Request.Files["Cv"].ContentLength is 0.
How come this happens? I know the file is not empty, as it has some text strings there but I need to check that there..
Thanks a lot everybody in advance.
Best,
Manuel
Comment: Have you verified that the file is actually being sent to the server?  I would recommend checking this first, typically I inspect the HTTP traffic between my browser and web app using fiddler.
Comment: Are you sure that Request.Files["CV"] exists? Also could you show the code around this.
Comment: @msarchet yes, I can see the name of the file that I'm trying to upload, the `ContentType` and the rest of attributes.
Comment: Please show your code. View and controller action.
Comment: I'm using two controllers for two parts of my web app that are using the same code for the uploading; I'm uploading the same file and it's working on one controller, but not in the other :)
Comment: @noloman, I didn't ask if it is working or not. I asked to see your code please. I asked an example that will allow me to reproduce your problem. Because I can point you to an answer illustrating that this works without any issue: http://stackoverflow.com/questions/5193842/file-upload-asp-net-mvc3-0/5193851#5193851. So apparently the problem is with your code. And without seeing your code I don't see how I can help you.
Comment: Please post header from Fiddler.
Answer: I figured the problem out by myself: it was a matter of initializing the model in the right place.. thanks everybody for your help!
Comment: Could you please show the code for your solution, as this is a question and answer site.
Comment: This answer adds no knowledge whatsoever.

Empty file when Request.Files


Barplot (gráfico de barras) de variável numérica versus categórica no R

Question: Como plotar um gráfico de barras no R em que no eixo x tenho uma variável categórica (com 4 categorias: frequente, as vezes, raro, nunca) e no eixo y a média de uma variável numérica (Y=0:13)? Como faço para inserir a legenda acima das barras?
Abaixo um exemplo da tabela de cruzamento da variável categórica com a numérica. Nas colunas "frequente", "as vezes", "raro" e "nunca" estão o número de indivíduos que responderam uma dessas quatro opções e a pontuação de Y (0:13).
  Y        Frequente  As vezes   Raro    Nunca
  0          86        70        111       69
  1         227       181        246      149
  2         341       254        417      197
  3         418       298        501      275
  4         396       316        541      257
  5         458       310        564      307
  6         387       273        562      246
  7         352       212        518      228
  8         247       167        401      207
  9         173       118        278      131
  10         88        54        140       61
  11         35        19         74       27
  12          9         7         31        8
  13          2         0          3        0

A informação que deve ter no gráfico de barras é: qual é a média de Y para os indivíduos que responderam: frequente, raro, as vezes e nunca.
Agradeço a ajuda!
Answer: Eu faria assim:
library(tidyr)
library(dplyr)
library(ggplot2)

dados %>%
  gather(intensidade, qtd, -Y) %>%
  group_by(intensidade) %>%
  summarise(media = weighted.mean(Y, qtd)) %>%
  ggplot(aes(x = intensidade, y = media)) + geom_col()

Considerando que dados é um data.frame da mesma forma que você postou.
Não esqueça de instalar os pacotes antes de usar. Da pra instalar todos juntos usando install.packages('tidyverse').
O gráfico gerado é assim:
Comment: Não consegui rodar - Erro: Invalid column specification - Você poderia detalhar o que atribuiu a "intensidade" e "qtd", por favor?
Comment: intensidade e quantidade são apenas nomes para as colunas que são criadas... poste o resultado de dput(dados) para que a gente possa olhar exatamente como está a sua base. Meu chute que não existe nenhuma coluna chamada Y...
Comment: consegui!! Valeu!


Recuperar Data do tipo Date - php + mysql

Question: Olá, eu to buscando do banco uma informação de data num grid com várias informações, estou fazendo assim:
 $data = $tbdeliberacoes->getData();
 date("d/m/Y", strtotime($data));

e este é o meu retorno na tela:
 31/12/1969

para todos os campos ele mostra essa data. Mas as datas gravadas no banco estão normais.
O campo que quero buscar é do tipo Date.
Comment: Quando vc imprime `$data` ela vem em qual formato?
Comment: a variavel $data é impressa d/m/Y
Comment: Se `$data = $tbdeliberacoes->getData();` já retorna em `d/m/Y` não precisa do date nem do strtotime.
Comment: Não entendi bem a questão. Está retornando todos os dados corretos, apenas as datas aparecem repetidas? Se sim, não é falta de incrementar a iteração com os resultados, como por exemplo com o uso do foreach ?
Comment: Sim, o campo no banco é do tipo DATE, eu busco a data em um arquivo "json" do symfony. Neste eu coloco date('d/m/Y', strtotime($tbdeliberacoes->getData())), no action eu coloco:

list($dia, $mes, $ano) = explode("/", $request->getParameter($field));
                        $data = date("Y-m-d", strtotime($ano."-".$mes."-".$dia)); $arrQuery[] = 'upper(data) LIKE \'%'. strtoupper($data) . '%\'';

Se eu habilitar o modo de debug eu recebo este erro: Warning: strtotime() expects parameter 1 to be string
Se eu desabilitar o modo debug todas as datas aparecem como: 31/12/1969
Answer: strtotime só vai converter a data em timestamp se ela estiver no formato YYYY-MM-DD.
Se $data já está no formato d/m/Y, então a chamada a date é desnecessária.
Para entender melhor sobre conversão entre formatos de datas, veja este artigo: http://rberaldo.com.br/php-conversao-de-datas-formato-brasileiro-e-formato-iso/
Comment: E aí Beraldo ? Vazou do iMasters ?
Comment: Não. Apenas dou uma passada aqui de vez em quando.


Android (Java/Kotlin) - Http error 400 - Bad Request and the request have only header without body

Question: everyone!
I've been building and app that consumes an API from the company where I work. When I perform a request (GET) with URL connection (through HttpURlConnection) with header (encoding, authorization and etc.) AND a body (as a JSON, using Content-Type = "application/json") the response code is 200 and the connection works pretty good, but and I use the same header in another request BUT WITHOUT a content, I get a Bad Request.
I already tried setting the doOutout = false, but It doesn't work.
I think that everything is OK with the URL and the header because I performed the request by Postman and I got the response.
Here is the way I'm creating the connection and connecting:
<code>val uri = Uri.parse("Base URL").buildUpon().appendPath(path).build() val url = URL(uri.toString()) val connection = url.openConnection() as HttpURLConnection connection.apply {
            addRequestProperty("Charset", Charsets.UTF_8.displayName())
            addRequestProperty("Authorization", "Basic $token")
            addRequestProperty("X-Serial", 5036.toString())
            requestMethod = "GET"
            connectTimeout = 0
            readTimeout = 0
            doOutput = false
            if (responseCode != HTTP_OK) throws Exception("Erro")
        }
</code>
Comment: Is it possible to see the JSON structure of the failing request and response?
Comment: @EamonScullion, in this, this request there's no JSON. As response, the JSON'd look like this:

[
    {
        "Id": "1",
        "Nome": "Name"
    },
    {
        "Id": "2",
        "Nome": "Name"
    }
]

This is the exception:
     Caused by: br.com.company.app.api.resource.ResponseException: Erro da conexão com a API!

    Causa: 400: Bad Request
        at br.com.company.app.api.resource.BaseClient.verifyResponseError(BaseClient.kt:32)
        at br.com.company.app.api.resource.BandeirasClient.listarBandeiras(BandeirasClient.kt:39)
Comment: I don't know if the request property X-Serial is valid for a HttpUrlConnection.
This API is working in as App made in C# for windows.
Answer: Bad Request suggest that it's an issue with the way your request is formed.
It is likely a problem with one of the request headers that you are setting. Have a look at the accepted request headers here.
Charset should potentially be named Accept-Charset, and I haven't seen any examples of X-Serial being used.
Here is an example of setting up a GET request using HttpUrlConnection. You could try removing all headers apart from Authorization and setting the request method to GET, like in this example.
Answer: I found out what was the problem: Me!
The $token value was generate with the flag DEFAULT. After I realized that, I putted the flag NO_WRAP and my request worked.
My bad! But thanks for all support!


Get undefined when reading $scope variable

Question: I'm trying to read the variable accessCode in my form in a Angular (1.6.8) function but I only get undefined.
The HTML
<form ng-submit="redeem()" ng-controller="SubscriptionCtrl as subscription">
   <input class="text-uppercase" type="number" ng-maxlength="6" placeholder="Indtast kode" ng-model="accessCode" />
   <input type="submit" class="btn btn-dark-green" value="Indløs" />
</form>

The Angular JS
app.controller('SubscriptionCtrl', ['$scope', '$http', '$templateCache',
    function ($scope, $http, $templateCache) {

$scope.redeem = function () {
    console.log($scope.accessCode);
};
}]);

Any ideas why I can't read $scope.accessCode?
Comment: You did something like this:     angular.module('myApp.controllers', []).
controller('SubscriptionCtrl ', ['$scope', function ($scope) {
  // ...
});    ????
Comment: can you make a jsFiddle or codepen?
Comment: ng-model="subscription.accessCode";
Answer: You don't have to revert your code back to using $scope since using controller as syntax is better (See advantages). You have to bind not only your ng-model but also your ng-submit to your controller instance subscription.

var app = angular.module('myApp', [])
app.controller('SubscriptionCtrl',
    function() {
        var subscription = this;
        subscription.redeem = function() {
            console.log(subscription.accessCode)
        }
    })

        <form ng-submit="subscription.redeem()">
            <input class="text-uppercase" type="number" ng-maxlength="6" placeholder="Indtast kode" ng-model="subscription.accessCode" />
            <input type="submit" class="btn btn-dark-green" value="Indløs" />
        </form>

Answer:
I think you forget to add the controller as section with ng-model,
  because you used:

ng-controller="SubscriptionCtrl as subscription"

So, in your ng-model, you have to use:

ng-model="subscription.accessCode"

Also change ng-submit="redeem()" to
  ng-submit="subscription.redeem()"
So, the HTML section will be as follows:

    <form ng-submit="subscription.redeem()" ng-controller="SubscriptionCtrl as subscription">
       <input class="text-uppercase" type="number" ng-maxlength="6" placeholder="Indtast kode" ng-model="subscription.accessCode" />
       <input type="submit" class="btn btn-dark-green" value="Indløs" />
    </form>

In controller side implement as follows:

//creating a module
var app = angular.module("app",[]);

//registering the above controller to the module
app.controller("SubscriptionCtrl",['$scope',function ($scope){
  $scope.accessCode = "";
    $scope.redeem = function () {
    console.log($scope.accessCode);
  };
}]);

Comment: And how do I access it in my function? $scope.accessCode?
Comment: Access code is ok. $scope.redeem = function (collectionId) {
    console.log($scope.accessCode);
    ...
};
Comment: Have to defined controller like angular.module('myApp.controllers', []). controller('SubscriptionCtrl ', ['$scope', function ($scope) { // ... }); ?
Comment: I have defined the controller but left it out for simplicity. Sorry :-)
Answer: Try this ..
Might have missed module name in html.
In app.js :
    var app = angular.module('myApp', []);
    app.controller('SubscriptionCtrl', function($scope) {
       console.log($scope.accessCode);
              .....
    });

Instead of using as .
Directly inject the $scope into the controller.
In HTML:

    <form ng-submit="redeem(collection.Id)" ng-controller="SubscriptionCtrl">
       <input class="text-uppercase" type="number" ng-maxlength="6" placeholder="Indtast kode" ng-model="accessCode" />
       <input type="submit" class="btn btn-dark-green" value="Indløs" />
    </form>

Follow ng-controller
Hope it helps..!


Add values of select to a href

Question: I've 2 select boxes. I want that the output of those fields, change the href attibute of the link.
<select class="option1">
    <option>Selecteer onderwijssoort</option>
    <option value="basisonderwijs">Basisonderwijs</option>
    <option value="voortgezetonderwijs">Voortgezet onderwijs</option>
    <option value="nt2">NT2</option>
</select>

<select class="option2">
    <option>Selecteer niveau</option>
    <option value="vmbot">VMBO T</option>
    <option value="havo">HAVO</option>
    <option value="vwo">VWO</option>
</select>

Start vergelijking

Comment: Show us what you've tried. Also, take a look at the following: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/change_event
Comment: Welcome to Stack Overflow! Please read through the [help center](https://stackoverflow.com/help), in particular [How do I ask a good question?](/help/how-to-ask) Your best bet here is to do your research, [search](/help/searching) for related topics on SO, and give it a go. If you get stuck and can't get unstuck after doing more research and searching, post a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) of your attempt and say specifically where you're stuck. People will be glad to help.
Comment: Does this answer your question? [Get selected value in dropdown list using JavaScript](https://stackoverflow.com/questions/1085801/get-selected-value-in-dropdown-list-using-javascript) Additionally https://stackoverflow.com/questions/5416767/get-selected-value-text-from-select-on-change/47495878
Answer: Here is a solution using jQuery:

var selectedOption1, selectedOption2 = "";

$(".option1").change(function(){
  selectedOption1 = $(this).val();
  $("#methodelink").attr("href","/filter/#1="+selectedOption1+"&2="+selectedOption2);
});

$(".option2").change(function(){
  selectedOption2 = $(this).val();
  $("#methodelink").attr("href","/filter/#1="+selectedOption1+"&2="+selectedOption2);
});

<select class="option1">
    <option>Selecteer onderwijssoort</option>
    <option value="basisonderwijs">Basisonderwijs</option>
    <option value="voortgezetonderwijs">Voortgezet onderwijs</option>
    <option value="nt2">NT2</option>
</select>

<select class="option2">
    <option>Selecteer niveau</option>
    <option value="vmbot">VMBO T</option>
    <option value="havo">HAVO</option>
    <option value="vwo">VWO</option>
</select>

Start vergelijking
Answer: You can do this with vanilla JS.
Take a look at following:

let opt1, opt2;

function updateOpt(){
  opt1 = document.getElementsByClassName('option1')[0].value;
  opt2 = document.getElementsByClassName('option2')[0].value;
  let href ="/filter/#1="+opt1+"&2="+opt2;
  let a = document.getElementById("methodelink");
  a.setAttribute("href", href);
  let p= document.getElementsByTagName("p")[0];
  p.innerHTML = a;
}
<select class="option1" onchange="updateOpt()">
    <option>Selecteer onderwijssoort</option>
    <option value="basisonderwijs">Basisonderwijs</option>
    <option value="voortgezetonderwijs">Voortgezet onderwijs</option>
    <option value="nt2">NT2</option>
</select>

<select class="option2" onchange="updateOpt()">
    <option>Selecteer niveau</option>
    <option value="vmbot">VMBO T</option>
    <option value="havo">HAVO</option>
    <option value="vwo">VWO</option>
</select>

Start vergelijking

Add values of select to a href


Sum of autoregressive processes?

Question: I am working on a research topic where I need to add together two AR processes and I was wondering if the distribution of these processes is of a recognizable form/structure.  More formally, if $x_t$ is a AR(p) process with characteristic polynomial $\Phi_x(u)$ and $y_t$ is a AR(q) process with characteristic polynomial $\Phi_y(u)$, then what is the structure of $z_t=x_t+y_t$?
Answer: This was studied by Granger and Morris (1976) who showed that
AR($p$) + AR($q$) = ARMA($p+q,\max(p,q)$).
Comment: I am reading through the paper but am stuck, do you think you can elaborate on these calculations?
Comment: Or rather is it obvious why this result holds?
Comment: Does this only hold for Gaussian noise? As far as I can tell, the innovations in the combined process when, say, $p=q=1$, are given by $e_z(t) = e_x(t) + e_y(t)$ and $e_z(t-1) = -\psi_{y,1} e_x(t-1) - \psi_{x,1}e_y(t-1)$ and I don't think we can write the second term as $\theta_{z,1} e_z(t-1)$ unless the innovations are Gaussian.
Comment: Actually, I don't think it is possible even for Gaussian distribution to express the innovations as an $MA(1)$ process. We can, probably, create the same covariance structure, but it doesn't look to me that we can simply multiply $t-1$ innovation with a scalar to get the $MA(1)$ component.
Answer: Rob Hyndman's answer isn't technically correct - Granger and Morris (1976) didn't show exactly that. In fact, for $AR(p)$ process $X_t$ and $AR(q)$ process $Y_t$,
\begin{align}
\phi_X(B)X_t &= \epsilon_t\\
\phi_Y(B)Y_t &= \eta_t\\
\end{align}
where $B$ is the backshift operator, we have
\begin{align}
Z_t &= X_t + Y_t\\
&= \phi_X^{-1}(B)\epsilon_t + \phi_Y^{-1}(B)\eta_t\\
\phi_X(B)\phi_Y(B)Z_t &= \phi_Y(B)\epsilon_t + \phi_X(B)\eta_t
\end{align}
The left hand side polynomial is of order $p+q$ and the right hand side has autocovariance zero at lags above $\max(p,q)$, thus in general $Z_t \sim ARMA(p+q,\max(p,q))$ - however as Granger and Morris (1976) point out this is not necessarily the case. In fact, strictly speaking we have
\begin{align}
  AR(p)+AR(q) = ARMA(x,y),\text{ }\text{ }\text{ }x\leq p+q, y\leq\max(p,q)
\end{align}
For example (p. 249), in the case of repeated AR polynomial roots,
\begin{align}
  (1-\alpha_1B)X_t &= \epsilon_t,\text{ }\text{ }\text{ }\text{i.e., }X_t\sim AR(1)\\
  (1-\alpha_1B)(1-\alpha_2B)Y_t &= \eta_t,\text{ }\text{ }\text{ }\text{i.e., }Y_t\sim AR(2)
\end{align}
We have
\begin{align}
  Z_t &= X_t + Y_t\\
  (1-\alpha_1B)(1-\alpha_2B)Z_t &= (1-\alpha_2B)\epsilon_t + \eta_t
\end{align}
Then $Z_t\sim ARMA(2,1)$, i.e., $x<p+q$ and $y<\max(p,q)$.
Likewise (p. 249), on the MA side, for
\begin{align}
  (1-\alpha B)X_t &= \epsilon_t,\text{ }\text{ }\text{ }\text{i.e., }X_t\sim AR(1)\\
  (1+\alpha B)Y_t &= \eta_t,\text{ }\text{ }\text{ }\text{i.e., }Y_t\sim AR(1)
\end{align}
We have
\begin{align}
  Z_t &= X_t + Y_t\\
  (1-\alpha B)(1+\alpha B)Z_t &= (1+\alpha B)\epsilon_t + (1-\alpha B)\eta_t
\end{align}
Denote the right hand side
\begin{align}
  \zeta_t = \epsilon_t + \alpha \epsilon_{t-1} + \eta_t -\alpha \eta_{t-1}
\end{align}
If $\text{var}(\epsilon)=\text{var}(\eta)$, we have
\begin{align}
  E[\zeta_t \zeta_{t-k}]=0,\text{ }\text{ }\text{ }\forall k>0
\end{align}
Then $Z_t \sim ARMA(2,0)$, i.e., $y<\max(p,q)$.
However as Granger and Morris (1976, p. 250) highlight, '[i]t would be highly coincidental if the "true" series [i.e., $X_t$] and observational error series [i.e., $Y_t$] obeyed models having common roots, apart possibly from the root unity, or that the paramaters of these models should be such that the cancelling out of terms produces a value of $y$ less than the maximum possible.'
Answer: As far as I can tell, the assertion that the sum of two $AR$ processes is an $ARMA$ process is based on the assumption that it belongs to $ARMA$ family and then the auto-covariance structure is matched.
Given two $AR(1)$ processes
$$(1 - a_xL)x(t) = e_x(t)$$
$$(1 - a_yL)y(t) = e_y(t)$$
their sum (assuming invertibility) is
$$ z(t) = x(t) + y(t) = \frac{e_x(t)}{1 - a_xL} + \frac{e_y(t)}{1 - a_yL}$$
Multiplying by the $AR(1)$ polynomials, we get
$$ (1 - a_xL)(1 - a_yL)z(t) = (1 - a_yL)e_x(t) + (1 - a_xL)e_y(t)$$
which is
$$ (1 - (a_x + a_y)L + a_xa_yL^2)z(t) = e_x(t) + e_y(t) - \left(a_y e_x(t-1) + a_x e_y(t-1)\right)$$
So, the left-hand side is an $AR(2)$ process, but I don't see how we can express the right-hand side as an $MA(1)$ process, because if we define
$$ e_z(t) = e_x(t) + e_y(t)$$
then there is no way we can express the $t-1$ term on the right-hand side as a scalar multiple of $e_z(t-1)$, i.e.
$$a_y e_x(t-1) + a_x e_y(t-1) \neq be_z(t-1) = b\left(e_x(t-1) + e_y(t-1)\right)$$
for a scalar value $b$ (unless, of course, $a_x = a_y$).
We can construct an $ARMA(2,1)$ process which will have the same auto-covariance signature as the sum of two $AR(1)$ processes, but it won't be identical to the sum of the two processes.
Comment: Nicely shown. The auto-covariances of an ARIMA series do uniquely identify the process upto a scale factor ( there's a proof of this somewhere ), so yes, you can't obtain the same exact process as the sum of 2 AR(1)'s but you can in terms of identification of the process. I think that's what the mean by two processes being "equal".
Comment: This is not correct. Loc cit shows, in fact as one of the first steps in the proof, that the sum of two MA process is again a MA. Your guess that the errors should be the sum of the two individual errors is just not correct.
Comment: @user2520938  Hi.  Not sure that I fully understood your comment, but the discussion here is about the sum of ARMA processes, not MA.
Comment: @Confounded You're writing that it is not clear how right hand side of one of your equations is again a MA process. I'm saying that it is in fact an MA process.
Comment: @user2520938  Can you then please show how it can be expressed in the form $z_t + a_1z_{t-1}$?, which is what I would call an MA(1)?  Thank you
Comment: @Confounded I suggest you read the article mentioned above, where on one of the first pages they show that this is in fact an MA. The proof is not constructive though.

Sum of autoregressive processes?


Something seems wrong about this induction proof but I can't pinpoint what?

Question: I'm a TA marking some assignments and I came across theses two induction proofs which seem like they work on a surface level. However, they also feel vaguely circular but I can't describe exactly why. I don't want to take marks off if I can't describe why this is wrong, so can anyone help me out?
First:

Second:
Comment: 2nd.  Use of a = k + 1 is hocuspocus claiming the conclusion of the induction step.  The use of p seems loose for not being propertly quantified but for some reason modern teaching encourages sloopy and ambiguous quantifications.
Comment: 1st.  The useless k(m) makes the proof clumbersome beyond consideration.  The induction needs to be on m and begin at 0.
Comment: Thanks, that makes sense :)
Comment: @WilliamElliot: +1 for the word 'clumbersome'.
Answer: The first solution is simply incorrect. At no point is $10^{2b+3}$ proved to be divisible by 11, all that is done is to comment on the nature of $2b+3$.
Comment: Thanks! That's a much better way for me to phrase it to the student then "this feels wrong" :P


Residual vs. Predicted Plot- Thick linear trend. How do I interpret this for assumptions?

Question:
Trying to interpret these graphs in order to understand if this model meets the assumptions for multiple linear regression.
Any thoughts?
Comment: It would help to tell us what your predictors are like. I assume you have either many categorical ones or a mixture with continuous ones with a smallish number of values. It would also help to know what your outcome is like. Again I assume it is bounded above and below with many values at the extremes. You could tell u all these things rather than let us guess and then someone might be able to give you helpful advice.
Comment: If the axis labels are to be trusted, this model does not satisfy the assumptions. (Obviously.) What goes wrong and what can be done about it is impossible to tell without further information: What does the model look like that you fit? What kind of data do you have? What do you want to research? etc.
Comment: I agree with @mdewey. The standardization here obscures a little what is happening. Consider the definition residual $=$ observed response $-$ fitted response. So in the original units the distinct values of the observed lie on lines with the same intercept and slope $-1$. You have clear diagonal bounds which may be as simple as corresponding to observed $= 0, 1$. In other words, it appears that you have fitted a hyperplane to a bounded response. That raises the question of whether any predicted values are outside those bounds. Better to use a flavour of regression that respects the bounds.
Comment: Dependent variable: Attributed Charisma Independent variable: Narcissism Moderator variable: Value congruence interaction term. control variables: age, sex, party affiliation. does this graph appear to meet linearity assumptions? Just not normality and possible heteroscadicity? Thank you!
Comment: charisma and narcissism and value congruence used a likert scale. Sex and party dummy variables
Comment: If you are concerned about independence of errors as you suggest in a comment then you need to think about the science of what you are doing. A plot is not going to reveal whether the observations are independent or not as far as I can see.
Answer: The lines in the figure arise because your dependent variable has a hard minimum and a hard maximum (although, because everything is standardized, I can't tell what the actual values of the extrema are). You wouldn't usually see these lines in a residual plot of data that was really generated by a linear regression model, because such a model postulates that the error is normally distributed, and a normal distribution has no extrema.
Of course, real data is rarely if ever generated by a neat statistical model, so the answer to the question "Does my data meet the assumptions of such-and-such a model?" is almost always "no".
Comment: There is a pretty strong consensus here. A bounded response (dependent variable in your terminology) which you explain as on a Likert scale could be modelled by some sort of ordered logit or probit, for example. If you insist on linear regression, you should not be surprised by the sharp bounds on the plot, which have been explained as inevitable side-effects of the bounded scale.
Comment: Still bit confused at the consensus here?
Comment: Also which plot would test independence of errors?
Comment: Now I think it's a pretty good answer, so not only is my objection gone, I've upvoted accordingly. You should feel free to remove any of your responses to me as you wish.


Repair Windows 2008 boot

Question: I have been caught in a loop where I can't boot up Windows Server 2008.
When the OS starts to boot I am presented two options:

Launch Startup Repair (recommended)
Start Windows Normally

No matter what option is chosen I end up with a black screen stating "Windows is loading files..." which takes approx 15 minutes until "System Recovery" is started. I try to run the "Startup Repair" but it reports the following error:

Problem Event Name: StartupRepairOffline
Problem Signature 01: 0.0.0.0
Problem Signature 02: 0.0.0.0
Problem Signature 03: unknown
OS Version: 6.1.7600.2.0.0.256.1
Locale ID: 1033

Actually no matter what other options I would try in the System Recovery they would also report some kind of error.
Some other logging I have been able to extract:

Diagnosis and repair details:

Number of repair attempts: 1
Session details
System Disk =
Windows directory =
AutoChk Run = 0
Number of root causes = 1

Test Performed:
Name: System disk test
Result: Completed successfully. Error code = 0x0

Root cause found:
A hard disk could not be found. If a hard disk is installed, it is not responding.

So it is actually stating that Harddisk could not be found... which to me seems to be a bit contradictious since the System Recovery just loaded all files from the hard disk it now states it cannot find.
Any ideas on what other options I have?
Comment: What happened leading up to this state? Is this a new install, or was it working and suddenly stopped when you rebooted it?
Comment: It has been running without any problems for almost 2 years. A windows update was installed last night and since then I could only ping the machine, but vpn, file resources etc. stopped working. Not responding to keyboard/mouse. I did a hard reset and it booted as normal... but within 30 minutes it stopped responding again, hard reset... and now it wont even bot anymore.
Comment: New findings: It seems to be related to the file system. It runs extremely slow and for some reason I can't boot up another Windows system when the RAID/Harddrive is present. At a few occasion I am however able to browse files on the harddrive with the command prompt.
Answer: You may need to load a driver for the storage controller.  If Windows is unable to load a driver, the hard drive(s) will not be available to the install. What is the controller in the computer?
Comment: RocketRaid 2640X4. I have tried to provide the drivers but this is how the System Recovery reacts: 1. Adding drivers... (approx 10 minutes) 2. Searching for Windows Installations... (freezes here after some while).
Answer: It sounds like you have a failed or failing RAID controller. I'd contact the vendor and see if they have any more advanced troubleshooting techniques for the controller itself.
Answer: Turned out it was a faulty disk that caused the problem. The disk was still identified by the system as operational thus creating all the above problems. Once unplugged everything worked flawless (replaced it, and raid array was rebuilt).

Repair Windows 2008 boot