How to add values of specific variables in a map

Question: I am building a flutter application that takes some values from a user and stores them in a map. I use a pageviewbuilder to present the Items the user should enter like so:
                    RadioListTile(
                      title: Text('${outcomeScore[index].sectionOne}'),
                      value: 1,
                      groupValue: selectedScore,
                      activeColor: Colors.blue,
                      onChanged: (val){
                        setSelectedScore(val);
                        setState(() {
                          scoreText = outcomeScore[index].sectionOne;
                        });
                        print(val);
                        print(scoreText);
                      },
                      secondary:  Text("One"),
                    ),

                    RadioListTile(
                      title: Text('${outcomeScore[index].sectionTwo}'),
                      value: 2,
                      groupValue: selectedScore,
                      activeColor: Colors.blue,
                      onChanged: (val){
                        setSelectedScore(val);
                        setState(() {
                          scoreText = outcomeScore[index].sectionTwo;
                        });
                        print(val);
                        print(scoreText);
                      },
                      secondary:  Text("One"),
                    )

On the PageView, I use a next button to move to the next page. the next button adds the selected value to the map like so:
  Map<String, String> myMap= {
    'createdOn' : '$currentTime',
  };

myMap[outcomeScore[index].itemTitle] = scoreText;
myMap[outcomeScore[index].itemTitle + " Score"] = selectedScore.toString();

When all of this is done, I end up with a map that has values like:
createdOn: 2020-08-17 10:55:22.983934, TestOne: VFR, TestOne Score: 3, TestTwo: TSA, TestTwo Score: 4, TestThree: RTA, TestThree Score: 3,

This is what the map would look like on Json
{

"TestOne" : "VFR",
"TestOne Score" : "3",
"TestTwo" : "TSA",
"TestTwo Score" : "4",
"TestThree" : "RTA",
"TestThree Score" "3"

}
on the last pageview, I have a submit button instead of the next and on this, I would like to sum up all the values of the variables with "Score" at the end of it. Any ideas on how to do this? I will really appreciate the help.
Thanks.
Comment: can you show me how your map looks like in json format?
Answer: use foreach loop to traverse through the map
var sum = 0;
map.forEach((key, value) {
    if(key.contains('Score')){
      //caution, throws if fails to parse
      sum += int.parse(value);
    }
  });


How do I optimize a rotation of the roots of unity?

Question: Any rotation of the $m$th roots of unity is a finite normalized tight frame (FNTF) of $\mathbb{R}^2$. According to Benedetto and Fickus, every  minimizer $\{x_i\}_{i=1}^{m}$  of the "frame potential" $$FP(\{x_i\}_{i=1}^{m}) = \sum_{i,j=1}^m |\langle x_i, x_j \rangle|^2$$
is a FNTF of $\mathbb{R}^d$.
Given a random initial set $\{x^{(0)}_i\}_{i=1}^{m}$, I would like to produce some rotation of the roots of unity by minimizing $FP$ via gradient descent in the case of $d=2$.
However, when I numerically minimize the (hopefully transparent) function
def FP(phases):
phase_diffs = phases - phases.transpose(1,0)
return (torch.abs(torch.cos(phase_diffs))**2).sum()

where phases are the angles of $\{x_i\}_{i=1}^{3}$ measured counter-clockwise from the x-axis, I see

which are evidently not roots of unity.
Have I misunderstood the frame potential or is this an optimization problem or both? I can provide more details about the solver if necessary.
Thanks in advance!
Comment: If you plug in the m-th roots of unity into your FP function, what do you get? To make sure there are no errors in the programming vs the math.
Comment: The m-th roots definitely minimize the FP function, but the example I posted _also_ achieves the minimal value of the frame potential for m=3, d=2 (4.5). So perhaps FP is coded incorrectly?
Answer: $$
FP (\{ x_i \}_{i=1}^m) = \sum_{i,j=1}^m \mid \langle x_i , x_j \rangle \mid^2\\
$$
Let $\alpha_i$ be $\pm 1$ chosen independently.
$$
FP (\{ \alpha_i x_i \}_{i=1}^m) = \sum_{i,j=1}^m \mid \langle \alpha_i x_i , \alpha_j x_j \rangle \mid^2\\
= \sum_{i,j=1}^m \mid \alpha_i \alpha_j \langle x_i , x_j \rangle \mid^2\\
= \sum_{i,j=1}^m \mid \langle x_i , x_j \rangle \mid^2\\
= FP (\{ x_i \}_{i=1}^m)
$$
So you see that the solution you got starts with the third roots of unity, but then messes with the signs by $\alpha_1=-1$ and $\alpha_2=\alpha_3=+1$.
When you minimize FP, you don't know a priori what these signs are.
Comment: Ah, yes. You can see this from the plot I posted. Thank  you for pointing this out!

By the way, a more reliable potential is hinted at in this paper, if you are interested:

https://www.jstor.org/stable/pdf/2308976.pdf?refreqid=excelsior%3Aa738ebf0d4e9ec5d40878d7d54406f23


How can I report bandwidth usage over x days, broken down by port and protocol?

Question: I need to generate reports showing bandwidth usage broken down by port and protocol, based on all data sent/received over the last x days, in a fairly simple and secure way.
Storing full traffic dumps for later analysis is not an option here for privacy and resource reasons.
Being able to record these statistics in a simple way is important, because eventually I need to be able to combine these stats across all of the servers.
The target machines are running Debian, and minimal solutions would be better as many have below average specs. I have looked at nettop and it seemed like overkill, and I wasn't able to find the breakdown by port and protocol I needed.
Any advice would be greatly appreciated!
Answer: ntop is useful, simple to setup overall accounting. It is based on libpcap to watch traffic but does not store the raw dumps. The traffic data is then available in RRD format if you want to poke around further than the information ntop provides. The web interface does let you drill down into a lot of information.
http://localhost:3000/sortDataIP.html will report per IP - total and protocols
http://localhost:3000/dump.html will let you export a "Hosts/Long" report in text, json, perl, php, python or xml that includes all those counters. Probably best to save that off at a specific time each day and calculate the difference from the saved copies.
Comment: I'm not sure where to begin trying to get this information about of ntop , this is what I meant I'd tried in the OP (not nettop).
Comment: Ah.. using 5.0.1? I just had a look at version 5 and it appears they've moved from simple /etc/services protocols and a -p option that let you define protocols to something called nDPI based on OpenDPI that doesn't detect any protocols for me via libpcap. Nice. I'll add the of where it should come from to the answer anyway
Answer: If you only need this to and from the Internet (or other WAN link), you'd do better to use something like NetFlow on the router (you'll need a collector), rather than run stats on each machine. That will show you port, protocol, and endpoint statistics quite nicely.
Now, if you do need to measure LAN traffic as well, that won't work for you.


Como pegar dados de dois txt diferentes, Java

Question: Fala pessoal, to com um problema aqui, eu tenho dois .txt e quero criar um novo txt unindo alguns dados desses dois .txt, segue abaixo de como eu pego os dados do .txt, alguém pode me dar um caminho de como fazer isso? Tava pensando se dá pra jogar em um array os dados.
<code>        scanner = new Scanner(new FileReader("caminho"))
        .useDelimiter(",|\n");

        while (scanner.hasNext()) {
            String nome = scanner.next();
            String rg = scanner.next();
            String cpf = scanner.next();
</code>
Comment: qual é seu problema exatamente? ta com dificuldade de ler um arquivo? de escrever o arquivo? poderia ser mais claro?
Comment: Que tipo de união deve ser feita? Qual é o critério que determina quais entradas te um texto devem combinar com o outro? Número da linha? Ou algum outro valor de controle que está escrito nas linhas, como um índice ou um número de documento? Isso pode ser bem simples ou bem complicado de fazer, agente só vai descobrir se você esclarecer o problema.
Comment: eu quero combinar conteúdo de dois .txt, eu consigo ler utilizando o Scanner e escrever usando FileWriter, é mais ou menos igual essa dúvida porém não entendi a explicação http://stackoverflow.com/questions/10411382/combine-some-elements-from-2-txt-files-into-a-third-file
Comment: Você quer simplesmente colar um texto no final do outro?
Comment: Eu tenho um .txt com 1,Nome,RG e outro com Estado,Cidade,Pais , quero criar um terceiro .txt com apenas o 1,Nome,Cidade
Comment: E qual é o fator comum entre o primeiro e o segundo texto? Tem alguma coisa dizendo qual nome mora em qual cidade?
Comment: Não tem nenhum fator necessário entre os dois, eu queria escolher um nome de um txt e uma cidade do outro gerando um txt final com a uniao dos dois
Comment: É pra ser aleatório então?
Comment: Na verdade eu precisava poder selecionar cada "campo" para montar o último
Answer: Uma maneira bacana é você usar os métodos FileWriter para criar/editar o arquivo e o FileReader para ler.
<code>    public void gravar() {
            FileWriter fileWriter;
            BufferedWriter bufferedWriter;
            try {
                fileWriter = new FileWriter("configuracoes\\config.txt");
                bufferedWriter = new BufferedWriter(fileWriter);
                bufferedWriter.write("localhost");
                bufferedWriter.close();
                fileWriter.close();
            } catch (IOException ex) {
                JOptionPane.showMessageDialog(null, "Ocorreu um erro:\n" + ex.getMessage());
            }
        }
</code>

<code>public final void lerArquivo() {

        try {
            FileReader fileReader = new FileReader("configuracoes\\config.txt");
            BufferedReader br = new BufferedReader(fileReader);
            try {
                setIP(br.readLine());
                br.close();
                setUrlPorIP(getIP());

            } catch (IOException ex) {
                BancoDeDados.database.tratamentoDeErro(ex, "");
            }

        } catch (FileNotFoundException ex) {
            new File("configuracoes").mkdir();
            File f = new File("configuracoes\\config.txt");
            try {
                f.createNewFile();
                gravarLinhaDeIP();
                lerArquivoConfig();
            } catch (IOException ex1) {
                //JOptionPane.showMessageDialog(null, "O arquivo 'config.txt' não existe.\n"
                //      + "Foi tentado cria-lo mas algo saiu errado.\n"
                //    + "Tente criar o arquivo Manualmente");
            }

        }

    }
</code>
Documentação Oficial:
http://docs.oracle.com/javase/7/docs/api/java/io/FileWriter.html
http://docs.oracle.com/javase/7/docs/api/java/io/FileReader.html


fiz um contador de clicks e ao armazena-lo no database via ajax, o valor sempre vai para o mesmo item na tabela

Question: Preciso que ao salvar esse item no banco de dados ele seja salvo no seu respectivo produto com o id, mas não sei o que estou fazendo de errado.
route
$route['product_out_click/(:any)']         = 'panel_admin_inventory/product_out_click/$1';

controller
public function product_out_click($id)
    {
        $this->load->model("inventory/Products_Outside_Model");
        $data['clicks'] = $this->input->post('clicks');
        if ($this->Products_Outside_Model->countClicks($id, $data)) {
            $this->session->set_flashdata('success', "Produto editado com sucesso!");
        }
        else {
            $this->session->set_flashdata('danger', "Produto não editado!");
        }
    }

model
public function countClicks($id, $data) {
        $query =  $this->db->get_where("products_outside", array('id' => $id));

        foreach ($query->result() as $row)
        {
            $clicks = $row->clicks;
        }

        $qtd = $clicks;

        $qtd = $qtd+1;

        $data['clicks'] = $qtd;

        $query = $this->db->update("products_outside", $data, array('id' => $id));
        return $query;

    }

view

 <button class="btn btn-xs btn-soft-primary font-size-1 text-uppercase" type="button" data-toggle="tooltip" data-placement="bottom" title="Compre agora">Comprar</button>

<input type="number" class="form-control d-none" name="clicks" id="<?php echo $product_out_search['id']; ?>">

javascript
function onClick() {
        clicks += 1;
        var input_id = $("[name='clicks']").attr("id");
        getElementById(input_id).value = clicks;
      }

      $('.product_out_count').on('click',function(){
        var input_id = $("[name='clicks']").attr("id");
        $.ajax({
            url:"<?php echo base_url(); ?>product_out_click/"+ input_id,
            method:"POST",
            data:{},
            success:function(response){
                // on success do something
            }
        });

      });

Comment: Por favor, esclareça seu problema ou forneça detalhes adicionais a fim de destacar exatamente o que você precisa. Da forma como está escrito atualmente é difícil dizer com exatidão o que você está perguntando.
Answer: Bom depois de muito pesquisar acabei encontrando a resposta.
route
$route['product_out_click/(:any)']         = 'panel_admin_inventory/product_out_click/$1';

controller
public function product_out_click()
    {
        $id = $this->input->get('id');

        $this->load->model("inventory/Products_Outside_Model");
        echo $id;
        if ($this->Products_Outside_Model->countClicks($id)) {
        }
        else {
        }
    }

model
public function countClicks($id) {
        $query =  $this->db->get_where("products_outside", array('id' => $id));

        $clicks = $query->result()[0]->clicks;

        $qtd = $clicks;

        $qtd = $qtd+1;

        $data['clicks'] = $qtd;

        $query = $this->db->update("products_outside", $data, array('id' => $id));
        return $query;

    }

view
<a target="_blank" href="<?php echo $product_out_search['store_link']; ?>"  class="product_out_count" >
 <button class="btn btn-xs btn-soft-primary font-size-1 text-uppercase" type="button" data-toggle="tooltip" data-placement="bottom" title="Compre agora" onClick=onTheClick(<?=$product_out_search["id"];?>)>Comprar</button>

javascript
function onTheClick(theId){
      var clicks = 0;
      clicks += 1;
      $.ajax({
        url:"<?php echo base_url(); ?>panel_admin_inventory/product_out_click?id="+ theId,
        method:"POST",
        data:{},
        success:function(response){
            // on success do something
        }
      });
    }


How to get a user string input on Telepot?

Question: I'm new in Python and in Telegram bot, I hope you can help me understand this with a simple example.
What I need is to define a method that returns me a string to complete a url.
In Python what I need is:
user = input("Insert a username to see the graph:")
graphUrl = "https://www.graphsss123.com/ser/graph/" + user + "-123.jpg"
print(graphUrl)

how could I get the same result using Telepot?
Thank you
Answer: There is no exclusive function for receiving messages in telepot(I guess!!),so you will have to maintain the states (here i have done that using step).The snippet below is an example for adding 2 numbers given by user through telegram
ref:https://github.com/nickoala/telepot/issues/209
global step, no1
        if step == 1:
            if msg['text'] == 'add':
                bot.sendMessage(chat_id, "input no1")
                step = 2
            else:
                bot.sendMessage(chat_id, "please provide no")
        elif step == 2:
            no1 = msg['text']
            bot.sendMessage(chat_id, "input no2")

            step = 3
        elif step == 3:
            no2 = msg['text']
            no3=no1+no2
            bot.sendMessage(chat_id,no3)
            step = 1


Clarification on separability in Rudin

Question: On pg 45 of Baby Rudin we have:

22. A metric space is called separable if it contains a countable dense subset.
24. Let $X$ be a metric space in which every infinite subset has a limit point. Prove that $X$ is separable.
25. Prove that every compact metric space $K$ ... is separable.

Since "countable" is defined in Rudin to exclusively mean "infinite and countable", then clearly the results don't hold for finite metric spaces, since that would imply an infinite set is a subset of a finite one.
What am I misunderstanding?
Comment: He should have included finite as OK too.
Comment: Clearly, "countable" in 22 means "finite or infinite countable"...
Answer: Indeed, Walter Rudin, in the Principles of Mathematical Analysis, p.25, defines as countable set one which is equinumerous to $\mathbb N$. In the same page, he defines what is an at most countable set.
So, in 22 the term countable should be replaced by at most countable to be consistent with itself.

Clarification on separability in Rudin


Como fazer timer em JavaScript

Question: Preciso de ajuda para fazer um timer para uma página, e tem de ser diferente para cada dificuldade de um jogo, por exemplo, para o modo fácil tem 1 minuto, para o intermédio tem 4 minutos, e para o difícil 8 minutos.
Answer: Podes fazer um objeto Timer e depois criares instâncias novas cada vez que precises. Por exemplo:

var button = document.querySelector('button');
var mostrador = document.querySelector('#mostrador');

button.addEventListener('click', function() {
    new Timer(1, mostrador, function() {
        alert('O tempo acabou!');
    }).start();
});

function Timer(mins, target, cb) {
    this.counter = mins * 60;
    this.target = target;
    this.callback = cb;
}
Timer.prototype.pad = function(s) {
    return (s < 10) ? '0' + s : s;
}
Timer.prototype.start = function(s) {
    this.count();
}
Timer.prototype.stop = function(s) {
    this.count();
}
Timer.prototype.done = function(s) {
    if (this.callback) this.callback();
}
Timer.prototype.display = function(s) {
    this.target.innerHTML = this.pad(s);
}
Timer.prototype.count = function(s) {
    var self = this;
    self.display.call(self, self.counter);
    self.counter--;
    var clock = setInterval(function() {
        self.display(self.counter);
        self.counter--;
        if (self.counter < 0) {
            clearInterval(clock);
            self.done.call(self);
        }
    }, 1000);
}

<button>1 minuto</button>

jsFiddle: https://jsfiddle.net/34t7bcrb/
Comment: @py_9 é isto que procuras? https://jsfiddle.net/34t7bcrb/1/
Comment: eu queria um timer que ao carregar no botão jogar do jogo começasse a fazer a contagem decrescente apartir dos 8 minutos por exemplo.
E que aparecesse na página esse mesmo timer como se fosse um cronómetro
Comment: @py_9 é isso que eu te ofereci :) Sabes adaptar o resto ou precisas de ajuda nos detalhes?
Comment: precisava de ajuda nos detalhes se pudesses
Answer: Você pode usar a função setInterval
  setInterval(function(){
    alert("Olá");
  }, 2000);

Entre as chaves coloque a ação que você deseja executar (um alert no exemplo). e depois da chave de fechamento especifique o tempo em milisegundos e a cada vez que essa contagem é completa (2 segundos no exemplo) ele chama a ação desejada.
FiddleJS com exemplo.
Comment: Obrigada, e como é que faço para mostrar o timer na página para realmente se ver o timer a fazer o countdown @pmargreff
Comment: Ele está fazendo a contagem, o que você pode fazer caso queira exibir na tela é atualizar outra variável de segundo em segundo usando a mesma função e a exibir. Pode até mesmo fazer uma outra variável que atualiza de segundo em segundo e colocar um contador dentro da sua função para atualizar somente até o segundo desejado. Acho que essa solução é melhor pois o ajudaria com o objetivo da pergunta e também como esse do comentário.
Comment: eu queria um timer que ao carregar no botão jogar do jogo começasse a fazer a contagem decrescente apartir dos 8 minutos por exemplo. E que aparecesse na página esse mesmo timer como se fosse um cronómetro
Answer: Duas opções simples (2000 ms):
requestAnimationFrame

[requestAnimationFrame] tells the browser that you wish to perform an animation and requests that the browser call a specified function to update an animation before the next repaint.

window.requestAnimationFrame(loop);
var timer_RAF = performance.now();
function loop (){
  passed = performance.now() - timer_RAF;
  if(passed >= 2000){
    console.log('requestAnimationFrame', passed);
    timer_RAF= performance.now();
    // seu codigo a ser executado a cada 2000ms
  }
  window.requestAnimationFrame(loop);
}

setInterval
var timer_interval = performance.now();
setInterval(function(){
    console.log('setInterval', performance.now() - timer_interval);
    timer_interval = performance.now();
    // seu codigo a ser executado a cada 2000ms
 }, 2000);

Como fazer timer em JavaScript


JSF - Session Bean restart on logout and login

Question: I have a web application with a backing bean which has the context of the current logged in user. It is implemented on JSF.
When the user logs out he is forwarded to a login screen (in another JSP page). I would like the current session to be erased when that happens and a new one to be created the next time the user logs in and enters the application.
My question is - how do you delete a session? (I guess the new session will be created automatically the next time the user enters the link)
This is kinda newb i guess, but I couldn't find a solution for this.
Thanks for the Help!
Comment: HttpSession#invalidate() invalidates current session
Answer: <code>((HttpSession) FacesContext.getCurrentInstance()
   .getExternalContext().getSession(false)).invalidate();
</code>
Comment: And the next time I login the session will be created again?
Answer: FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
Comment: 7 years later... :)


How to prove that every point has an infinite number of neighborhoods?

Question: My attempt: Suppose that a point $p$ has finite number of neighborhoods. This implies that the set which contains $p$ is non-empty and is finite. But a non-empty finite set cannot be a nbd of any of its points. Thus, there are infinite number of neighborhoods.
Is this correct? Thanks in advance!
Comment: Every point where exactly?
Comment: This depends on the topology
Comment: It is asked just the same in textbook.
Answer: You need to specify what topological space we're in to have a concrete answer. But assuming we're talking about the standard topology on $\mathbb{R}$, no, the proof doesn't work. For example, suppose there are indeed a finite number of neighbourhoods. This is not the same as saying that each such neighbourhood is finite; for example just take $\mathbb{R}$.
Another way to prove this is simply to construct an infinite set of neighbourhoods: Define $S = \{(p-n, p+n: n)\in \mathbb{N}\}$. Clearly $\forall x \in S$, $x$ is a neighbourhood of $p$. $S$ is also infinite (obviously!). Hence there are an infinite number of neighbourhoods of $p$.
Mind you the caveat here is pointed out in the comments, we need to know what space we're working in, and I just assumed $(\mathbb{R}, \tau_{standard})$. Also not sure if it's relevant to the question in your textbook, but the proof I outlined only shows there are a countably infinite number of neighbourhoods.
Comment: The countability restriction is easily removed: just define $S=\{(p-x,p+x):x\in\Bbb R_{>0}\}$.
Comment: Ok thank you so much!!
Comment: @NatashaJ No problem, hope it helped!
Comment: @TonyK Ah yes, not sure why I used $\mathbb{N}$ in the first place actually...


Understanding the definition of the sign of a permutation , $\operatorname{sgn}(\pi) = (-1)^k$ .

Question: I am trying to understand the definition of the sign of a permutation $\pi$.
My textbook only mentions that $\operatorname{sgn}(\pi) = (-1)^k$ , where $k$ is the number of transpositions .
But I have also found online that $\operatorname{sgn}(\pi) = (-1)^{\operatorname{inv}(\pi)}$, where $\operatorname{inv}(\pi)$ is the number of inversions on a permutation.
Does this mean $ k = \operatorname{inv} (\pi)$ in general ?
I am trying to show if $\pi$ is a product of $k$ transpositions , then $k \equiv \operatorname{inv}(\pi)\pmod2$
In general, the $\operatorname{sgn}(\pi) = 1$ if $\pi$ is a product of even number of transpositions.
And $\operatorname{sgn}(\pi) = -1$ if $\pi$ is a product of odd number of transpositions.
So I was thinking that if $k$ is even, then $\operatorname{inv}(\pi)$ is even  and so $2\mid\operatorname{inv}(\pi) - k $ and similarly if $k $ is odd, then $\operatorname{inv}(\pi)$ is odd, so $2\mid\operatorname{inv}(\pi) - k$ . So  $k \equiv \operatorname{inv}(\pi) \pmod 2$)
Can someone please verify this? Any better approach or feedback would help!  Would I have to prove this part of the definition?
Thank you !
Comment: @Mahidevran: Yes, mod 2 they are equal.
Comment: I edited for proper use of \operatorname{sgn}, \operatorname{inv}, \pmod, and \mid . $\qquad$
Comment: $k$ does not equal $\operatorname{inv}(\pi)$ in general. For instance, the permutation $(1,4)(2)(3)$ has one transposition but five inversions: $(1,2),(1,3),(1,4),(2,4),(3,4)$.
Comment: in mod 2 they are both equal? How could I relate both the inversion and sign together? I am not sure then, how to approach my problem
Comment: I am confuse about how to prove $k \equiv inv(\pi)$mod$2$ , because my book does not mention any definition about inversion. It only mentions it's a permutation such that the pair of indices $i < j$ and $\pi(i) > \pi(j)$.\
Answer: To see why they are both the same, first prove the following lemma:
Lemma 1
$$\mbox{sgn}(\sigma) =\prod_{1 \leq i < j \leq n} \frac{\sigma(j)-\sigma(i)}{ j-i}$$
To prove it, first note the the RHS must have absolute value 1, as every pair $(k,l)$ appears once at the bottom and once at the top. Therefore the RHS is $\pm 1$, and all you need to do is track the sign. Finally for the RHS you get a minus for each inversion.
Next, use this to get:
Lemma 2
$$\mbox{sgn}(\sigma \circ \tau) =\mbox{sgn}(\sigma)\mbox{sgn}( \tau)$$
Idea of proof: By Lemma 1:
$$
\mbox{sgn}(\sigma \circ \tau)=\prod_{1 \leq i < j \leq n} \frac{\sigma \circ \tau (j)-\sigma \circ \tau(i)}{ j-i} \\
=\prod_{1 \leq i < j \leq n} \frac{\sigma \circ \tau (j)-\sigma \circ \tau(i)}{ \tau (j)- \tau(i)} \cdot \prod_{1 \leq i < j \leq n} \frac{ \tau (j)- \tau(i)}{ j-i}=\mbox{sgn}(\sigma)\mbox{sgn}( \tau)
$$
by a similar computation to Lemma 1.
Lemma 3 If $\tau$ is a transposition $(i,j)$ then
$$\mbox{sgn}(\tau)=-1$$
Proof Just count the inversions.
Combining Lemma 3 and Lemma 2, you finally get:
Theorem Let $\sigma=\tau_1 \cdot ...\cdot \tau_k$ where $\tau_j$ are all transposition. Then
$$\mbox{sgn}(\sigma)=(-1)^k$$
Comment: Very nice.${}{}$
Comment: Does lemma 3 imply sgn is well defined, and independent of the particular decomposition of $\pi$ into transpositions?
Comment: @Mahidevran  Lemma 2 and Lemma 3 together imply that.
Comment: Just to understand , $$\mbox{sgn}(\sigma \circ \tau)$$ is a composition of a transposition $\tau$?
Comment: @Mahidevran Yes. Composition (or product) or permutations.
Answer: Let's assume we have an arbitrary order of n numbers and we want to swap the elements at the "i"th and "j"th position ($a_i$ and $a_j$). When they are swapped, their order regarding to elements from $a_1$ to $a_{i-1}$ and from $a_{j+1}$ to $a_n$ does not change. Therefore, we should concentrate on the elements between them ($a_{i+1}$ to $a_{j-1}$). If there are $m$ elements between $a_i$ and $a_j$, by moving $a_i$ to $a_j$'s place, either we add an inversion or we delete an inversion (consider the elements between them one at a time). Let's assume we add $x_1$ inversions and delete $y_1$ inversions. Note that $x_1 + y_1 = m$. Same is true when we move $a_j$ to $a_i$'s place (it adds $x_2$ and deletes $y_2$ inversions and $x_2 + y_2 = m$). After considering $a_i$ and $a_j$ themselves, which either adds or deletes an inversion, we have added a total of $x_1+x_2-y_1-y_2\pm1$ inversions. As $m=x_1+y_1$ has the same parity as $x_1-y_1$, the total parity is definitely an odd number. So, each operation of swapping adds or removes an odd number of inversions. Just like transpositions.
Comment: Does  $x_1+x_2-y_1-y_2\pm1$ , mean  $x_1+x_2-y_1-y_2 + 1 $ or  $x_1+x_2-y_1-y_2 - 1 $?
Comment: it can be any of them, depending on the relative order of ai and aj
Comment: Fantastic, thank you!
Answer: Here is a geometric definition. Perhaps it might appeal to you.
An $n$-simplex is an $n$-dimensional generalization of a triangle. In small dimensions, we have:
A $0$-simplex is a point.
A $1$-simplex is a line segment.
A $2$-simplex is a triangle.
A $3$-simplex is a tetrahedron.
In general, an n-simplex consists of points $(x_1, x_2, x_3, ..., x_{n+1})$ in $\mathbb{R}^{n+1}$ such that $x_i \ge 0$ for each $x_i$ and such that $\sum_i x_i = 1$.
(Try graphing this definition for $n=1$ and see that it does, in fact, produce the line segment from $(1, 0)$ to $(0, 1)$ on the plane).
Simplices are the bread and butter of algebraic topology. Many times we like to triangulate a space by approximating it with $n$-simplices.
Anyway, back to permutations.
The symmetric group of order $n$ forms the group of isometries of the $n$-simplex. Visualizing this in the case of the triangle or tetrahedron, we see that we can generate any element of the symmetric group by a series of rotations of the triangle/tetrahedron or reflections.
The sign of a permutation is really, then, an indicator telling you if a given transformation can be obtained using only rotations. Put another way, when $\text{sgn}(\pi) = 1$, the tetrahedron will merely be rotated, but when $\text{sgn}(\pi) = -1$, the simplex will be turned inside-out.
This question of whether a simplex will be turned inside out leads to the notion of orientation.


How can I wake a sleeping thread only with certain condition in java?

Question: Currently I am accessing server from my client android device after every 10 second using Thread.sleep function and check if any new content have been updated to server and do the same update to client device after sleep. so every thing works well in one while loop. But now I even want to check if something has been updated to server even in that sleep mode. In case if some new update available to the  server,  then I have to break that sleep and do update to client device from the server, otherwise let it sleep for the duration of time. Main reason is I want to increase sleep time, but at the same time check the status of server for update and do update. Need to reduce server treffic by increasing sleep time ,but need to update even in between the sleep new update arise.
public void run() {

        while( m_KeepRunning ) {

            // 10s sleep to give the app time to start
            try {
                for( int i = 0; i < 10 && m_KeepRunning; i++) {
                    Thread.sleep( 1000 );
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        Log.d("SERVER", "--- Start update from Server ");

        servercallfunction();// suppose to call server and check for new update :if do then  update to client machine

}
}

Comment: For that only we have wait and notify, right?
Comment: You can interrupt a sleeping thread and it will start going again from the catch clause.
Comment: Sockets might be the way to go
Comment: A different approach is to use push notifications.
Answer: Since you are making server in sleep for some limited time , it wont be able to find server status in that period of time, so no question of getting server status in that period of time as its in sleep mode. In order to get server status , thread has to come out of sleep. So if you need to reduce server traffic by going to sleep , you have to sacrifice the offline from server during those period as well.


Find sum of real roots of the equation $\sqrt{8-x}=x-2$

Question:
Solve the equation $\sqrt{8-x}=x-2.$

I got the answer to the question as $x= -1$ or $x= 4$. However, the answer key says the actual answer to the question is $4$ only. What am I missing here?
Comment: You are missing that $\sqrt{9}\neq -3$.
Comment: I get that the question is quite basic but does that warrant downvotes? Genuine question.
Answer: Using the fact that $\sqrt{x^2}=|x|$ where | . | refers to the absolute value, we can apply this to your specific problem to see that:

$\sqrt{9}=\sqrt{3^2}=|3|=3$

or

$\sqrt{9}=\sqrt{(-3)^2}=|-3|=3$

Therefore, since $\sqrt{9}\neq-3$, we conclude that $x=-1$ cannot be a valid solution, and so the correct answer is only $x=4$, as stated in your answer.
Answer:
While it is commonplace to solve an equation such as $ \ \sqrt{8 - x} \ = \ x - 2 \ $ by first "squaring" both sides, it should be understood that this has the effect of altering the properties of the functions represented on each side of the equation.  The curve for the function $ \ y \ = \ x - 2 \ $ (blue curve in graph at left) is a straight line which does not enter the second quadrant, so there is no negative value of $ \ x \ $ that can produce a positive value for $ \ y \ \ . $  The curve (in red) for $ \ y \ = \ \sqrt{8 - x} \ \ , $  on the other hand, can only produce positive values of $ \ y \ $ for $ \ x \ < \ 8 \ \ , $ as square-roots of positive real numbers are only defined to be positive.  So the properties of these functions tell us that there can be no intersection of their curves for $ \ x \ < \ 0 \ \ . $
The act of "squaring" the functions (which enables the solution $ \ (x - 2)^2 \ = \ x^2 - 4x + 4 \ = \ 8 - x $ $ \Rightarrow \ x^2 - 3x - 4 \ = \ (x - 4)·(x + 1) \ = \ 0 \ ) \ $ alters ("transforms") the straight line function into an "upward-opening" parabola with its vertex at $ \ (2 \ , \ 0 ) \ $ and its $ \ y-$intercept at $ \ (0 \ , \ 4) \ \ , $ so that its function curve (green in the graph at right) now extends into the second quadrant, permitting it to intersect with the straight line (orange) for $ \ (\sqrt{8 - x})^2 \ \ . $  This intersection at $ \ (-1 \ , \ 9) \ $ is then an artifact ("spurious solution") of the "squaring" transformation: any negative-value solution for $ \ x \ $ is already "rejected" for the original functions.
Answer: To solve you need to square the given equation.
When you square the right side you get same result for x -2 and 2 - x , therefore you get solutions for both cases. This is why you need to avoid squaring of equations when you are solving. But if there is no other option you can square but you have to check validity of your solutions by substituting those to the original equation.


How to find $g(x)$ if $f(g(x))$ and$ f(x)$ are given?

Question: I'm attempting a question where $f(x)$ and $f(g(x))$ are given and the question is to find $g(x)$
How do I approach this problem?
What fundamentals should I keep in mind while encountering such questions?
Comment: Apply the inverse function $f^{-1}$, it it exists.
Answer: If $y=f(x)$, try to write $x$ as a function of $y$.
For example, if $y=2x+3$, then $x=(y-3)/2$.  So $f^{-1}(x)=(x-3)/2$.
Apply this function to $f(g(x))$.  If $f(g(x))=x^2$, then $g(x)=f^{-1}(f(g(x))) = (x^2-3)/2$.
Answer: You may try solving such questions using the chain rule of differentiation that is $dz/dx=dz/dy.dy/dx$
Suppose that we have to differentiate the following function - $$f(x)=sin(2x)$$
We define the inside and outside function to be- $$f(x)=sin(x)$$ and $$g(x)=2x$$
Then, the derivative of the composition will be as follows:
$$F'(x)=f'(g(x))g'(x)$$$$=cos2x*2$$$$F'(x)=2cos(2x)$$
Or else you can use this example to solve your question-
Given $F(x) = 3x - 1$ and $F(G(x)) = x² - 5x$, find $G(x)$.
$sol^n-$$$F(x)=3x-1$$
Then,$$ F(G(x))=3[G(x)]-1=x² - 5x $$
$$=>3[G(x)]=x² - 5x+1$$
$$=>G(x)=\frac13(x² - 5x+1)$$
I hope this example woulld help you.
Comment: I was able to solve by using the method given by @Michael
I'm trying to solve it by chain rule of differentiation as well, but I'm unable to, can you please give an example?
Answer: For $g(x)$ when given $(f \circ g)(x) = f(g(x))$ and $f(x)$:
$$g(x)=f^{-1}(f \circ g(x))$$
For $g(x)$ when given $(g \circ f)(x) = g(f(x))$ and $f(x)$:
$$g(x)=(f \circ g)(f^1(f \circ g)(x))$$
Thank me later even though I'm 2 years late..
 Your savior..
Comment: Lol about being 2 years late. This does only work when $f$ is invertible.
Comment: Unfortunately your  second formula doesn't work.


What do square brackets above the bottom staff mean?

Question:
From Leonard Ornstein's Tarantelle (1963)
Unlike pedal markings, these are above the bottom staff. I feel like it could be phrasing, but that's normally indicated by the beaming of the notes. What do these groupings mean?
Comment: @AndrewLi That would make sense if this was 9/8.
Answer: It is phrasing.  It's a kind of regrouping of the beats in the left hand, from 4 beats in the bar to 3.  It's much more visual using the brackets than just using phrase marks.
Comment: Wouldn't this normally be notated using note beaming? I think that would be equally as visual.
Comment: @Okoyos it occurs to me also that, since this is a piano piece, beaming the LH part but not the RH part would make it visually tough to identify synchronized notes.
Comment: @Okoyos Yeah, if this were written by Bartók I think it would definitely be shown with a beaming pattern. But not everyone likes that notation method because it can be hard to read. It looks to me that this composer is trying to find a compromise that preserves the readability of proper 12/8 beam patterns but still shows the anti-metric grouping. It also might be someone dealing with a notation program that can't do the other beaming easily—note the strangely uncentered 12/8, this doesn't look like a high quality program.
Comment: @Okoyos  note beaming is usually broken at the start of each beat. I have seen beaming,e.g., of groups of 6 16th notes in 4/4 time, but that's a bit easier to interpret than beaming eighth notes in  6/8 or 12/8 time.
Comment: @PatMuchmore Also included in Tarantelle are some double beaming in the left hand. I would think that also signifies phrasing, so it seems odd that they would have two different ways of expressing phrasing. Why do you think that is?


Asp.net mvc4 jqueryGrid not show up

Question: I'm triying to implement jquerygrid plugin into my asp.net mvc4 application. But im in stuck. Need your help. Wrote all code and i got only white page with json data. I dont know why.
My view is shown below:
@model Fancy.Management.Model.User.IndexModel
@{
ViewBag.Title = "Index";
}

And my action method is shown below:
  public ActionResult Index(string sidx, string sord, int? page, int? rows)
    {
        var jsonData = new
        {
            total = 1,
            page = 1,
            records = 3,
            rows = new[]{
     new{Id=1,cell=new[] {"1","-7","Is this good question?"}},
     new{Id=2,cell=new[] {"2","15","Is this really?"}},
     new{Id=3,cell=new[] {"3","23","Why is the sky blue?"}}
     }
        };
        return Json(jsonData, JsonRequestBehavior.AllowGet);
    }

Exception that i got is shown below:
Answer: Your Index action isn't returning a View, so the View you've created never gets used.  The action is only returning JSON data:
return Json(jsonData, JsonRequestBehavior.AllowGet);

Which is why you're seeing JSON data in the browser when you request the Index action.
Instead, you need to return a view (with an instance of IndexModel, which you don't seem to have in the code):
return View(someInstanceOfIndexModel);

The jqGrid is then going to need to use a different action to get its JSON data, since the AJAX request is a different request than the one which initially loads the page.  Something like this:
url:'@Html.Action("IndexData","User")',

The action method you currently have for Index would then be renamed to something like IndexData (using the sample above) to handle the AJAX request.
Ultimately, the order of operations here would be:

Browser requests Index.
Index returns a View (populated by any necessary view model).
Since the view in question contains JavaScript code, that code will be executed by the browser.
The JavaScript code makes a second request to another action (I called it IndexData, but you can call it whatever you want).
That other action returns Json with the data needed by the grid.
The client-side JavaScript code receives the data and populates the grid.

Asp.net mvc4 jqueryGrid not show up


Sql Round, when on .5, rounds to the greater number ie 1.235 result 1.24

Question: When doing invoices, i want to round say 1.235 to 1.23
Select Round(TestData,2) From TestTableRound

why do i get the result 1.24, considering its midway? i want this rounded to 1.23.
This can lead to discrepancies when billing, sometimes the invoice doesnt match the bill.
Just curious, any help would be great, thanks
Comment: It's the default behavior
Comment: DBMS defined. Which one are you using?
Comment: Thanks Minh, but is there anyway around it?
Comment: Using Microsoft SQL Sever Management
Comment: Are you trying to match an existing system that has implemented rounding in that manner? And what is the rule? Is it round ties to an odd digit, to zero, something else? Rounding 5s up is the way I was taught in elementary school (as I imagine most others in Canada and the US were). It wasn't until I started to learn spreadsheets and programming that I learned about rounding bias (and then in engineering at uni, but I started using spreadsheets long before then).
Answer: Maybe you can decrease the amount a litle bit before rounding, like this
Select Round(TestData-.001,2) From TestTableRound

Another trick (for your case) is to multiply by 100, take the integer part, then divide by 100
Select
 CASE WHEN FLOOR(TestData * 1000)-FLOOR(TestData * 100)*10 <= 5 THEN
          FLOOR(TestData * 100)/100
      ELSE ROUND(TestData , 2)
 END
 From TestTableRound

Comment: Probably a good alternative +1
Answer: The Wikipedia article on rounding should be helpful: http://en.wikipedia.org/wiki/Rounding
You may be looking for Banker's Rounding. See this article on Microsoft's implementations: http://support.microsoft.com/en-us/kb/196652
Without more details about what you are trying to achieve, we really can't provide much more help than that.


How to focus on blog portlet in liferay

Question: is there a way to refocus on the blog portlet after clicking next/prev. when i click those buttons it goes to the top of the page.
We are using liferay 7, with freemarker. We are kind of new with liferay
Comment: http://meta.stackexchange.com/questions/141823/why-is-cross-posting-wrong-on-an-external-site
Answer: I suppose you mean to scroll to the blog portlet when you say "focus on".
In this case the mechanism it is pretty simple:

IF in the DOM there is an element with a specific id attribute AND the url ends with #the-same-id-attribute then when the page is loaded it will scroll to that element.

The blog portlet has a unique attribute by default, you should append it to your next/prev buttons URLs.
Ref:
Fragment Identifier

How to focus on blog portlet in liferay


Best Approach to filter out data from array

Question: I want to filter out data from an array based on certain condition.
Check if both 'isChecked' & 'isPrimaryKey' is true and if 'rename' is not empty then in the output array need to show rename otherwise show name.
The below code working perfectly for me. I want to know is there any better approach.
Also want to know is there any fault in this approach (using map for iterating over limited number of object)
let columnList = [
  { id:1, name: "Id", rename: "", isChecked: true, isPrimaryKey: true },
  { id:2, name: "Name", isChecked: false, isPrimaryKey: true },
  { id:3, name: "age",  rename: "Age", isChecked: true, isPrimaryKey: true },
  { id:4, name: "Designation", isChecked: true, isPrimaryKey: false },
  { id:5, name: "Salary", isChecked: false, isPrimaryKey: true },
  { id:6, name: "Department", isChecked: true, isPrimaryKey: false },
  { id:7, name: "Project", isChecked: false, isPrimaryKey: false }
];

let data = columnList.map(d => {
  if(d.isChecked && d.isPrimaryKey) {
    return (d.rename && d.rename !== '') ? d.rename : d.name;
  }
});

data = data.filter(item => item);
console.log(data);

Output: ["Id", "Age"]
Answer: You should use array.reduce instead of array.map + array.filter.

Array.map - This function will return an array of n element with returned value. It can return partial/processed value.
Array.filter - This function is used to filter items in array. This will return n elements that match the case but will not change/process them.
Array.reduce - This function is meant to reduce the number of items in array. In doing this, you can manipulate items and return a custom value.

Also for the case where you need to check if rename is available then return it else return name, you can achieve it using .push(d.rename || d.name)

let columnList = [
  { id:1, name: "Id", rename: "", isChecked: true, isPrimaryKey: true },
  { id:2, name: "Name", isChecked: false, isPrimaryKey: true },
  { id:3, name: "age",  rename: "Age", isChecked: true, isPrimaryKey: true },
  { id:4, name: "Designation", isChecked: true, isPrimaryKey: false },
  { id:5, name: "Salary", isChecked: false, isPrimaryKey: true },
  { id:6, name: "Department", isChecked: true, isPrimaryKey: false },
  { id:7, name: "Project", isChecked: false, isPrimaryKey: false }
];

let data = columnList.reduce((p, d) => {
  if(d.isChecked && d.isPrimaryKey) {
    p.push(d.rename || d.name);
  }
  return p;
}, []);
console.log(data)

But if you still wish to go for Array.map + array.filter, you can try something like this:

let columnList = [
  { id:1, name: "Id", rename: "", isChecked: true, isPrimaryKey: true },
  { id:2, name: "Name", isChecked: false, isPrimaryKey: true },
  { id:3, name: "age",  rename: "Age", isChecked: true, isPrimaryKey: true },
  { id:4, name: "Designation", isChecked: true, isPrimaryKey: false },
  { id:5, name: "Salary", isChecked: false, isPrimaryKey: true },
  { id:6, name: "Department", isChecked: true, isPrimaryKey: false },
  { id:7, name: "Project", isChecked: false, isPrimaryKey: false }
];

let data = columnList
  .filter(d => d.isChecked && d.isPrimaryKey)
  .map(d => d.rename || d.name);

console.log(data)

The difference is in reading. When you read it, you read it as,

You are filtering list by isChecked and isPrimaryKey and the from the filtered, you are returning either rename or name

These functions are part of functional programming and their beauty comes when they improve readability of code. In your code, reader will have to read the logic to understand what you are trying to achieve, which beats the purpose.
Comment: Adding to @marinbgd point, the difference would be somewhere around 100ms if you have an array of around 100,000 or 1M entries. But if you are using a bundler like `webpack` etc, these functions are replaces with optimized code. So yes, you should go for readability, unless you have a trader blotter system than needs to be updated every second
Comment: If you have like 100-1000 items in an array, it just does not matter (performance wise), go for the readability. You can measure this and see for yourself.
Comment: Thank you. From your opinion performance wise which one is good Array.map + array.filter or Array.reduce or any another approach like ramda?
Comment: `Array.reduce` will take `O(n)` and `Array.map + Array.filter` will take `O(n + m)` where `m` represents the filtered list. So you are adding `m` iterations extra. But if you are looking for performance, nothing beats `for`. These functions improve readability at the cost of performance. But usually there is standard optimizations applied by bundler. So you should not bother much about it
Comment: Good, Thank you very much
Answer: A follow-up to Rajesh's answer: if you want the clean code of filter-then-map, but don't want to add extra iterations, Ramda offers support for transducers in many of its list-handling functions, including map and filter.  The following version will iterate the list once, checking on each step if the item matches the filter, and if it does choosing the correct property via the function passed to map.
But the code is still nicely factored into the filtering step and then the mapping step.

let columnList = [
  { id:1, name: "Id", rename: "", isChecked: true, isPrimaryKey: true },
  { id:2, name: "Name", isChecked: false, isPrimaryKey: true },
  { id:3, name: "age",  rename: "Age", isChecked: true, isPrimaryKey: true },
  { id:4, name: "Designation", isChecked: true, isPrimaryKey: false },
  { id:5, name: "Salary", isChecked: false, isPrimaryKey: true },
  { id:6, name: "Department", isChecked: true, isPrimaryKey: false },
  { id:7, name: "Project", isChecked: false, isPrimaryKey: false }
];

const getCols = R.into([], R.compose(
  R.filter(d => d.isChecked && d.isPrimaryKey),
  R.map(d => d.rename || d.name)
))

const cols = getCols(columnList)

console.log(cols)

You also asked if there was an issue with your approach.  There might be.  As well as the extra iterations already discussed, there are two more concerns: First, using filter with item => item will disallow not just the null/undefined values but also any false-y value, most notably 0.  So if you were trying to extract a list in which 0 might be a reasonable value, this will exclude it.  Second, in functional programming, it's generally considered a bad habit to reassign variables.  So data = data.filter(...) is much frowned-upon.


JavaPNS alternatives?

Question: The company I work for has an issue with using LGPL software, are there any viable alternatives to JavaPNS or is it the clear leader for Java and APN?
Thanks.
Answer: Maintaining the JavAPNS library take time and effort. If you or your company isn't willing to help support/improve it, yet expects many man-hours to have been spent in making it stable then feel free to go elsewhere.
Have you looked at:
https://github.com/notnoop/java-apns
It says: Licensed under the New 3-Clause BSD License.
Comment: I up-voted this because it does provide an answer that was valuable to me.  However, it is unnecessarily preachy.  No need to say "feel free to go elsewhere" when his question was, "where else can I go?"

JavaPNS alternatives?


ASP MVC Creating Form Rows Dynamically

Question: I haven't even attempted this yet and am creating this question for advice really.
I have a strongly typed page which receives a form model composed of several components. It is to create a mitigating circumstance (MC) for a student at a university for my final year project. A MC can be composed of the initial problem, assessment extensions, and I use a multi select box to allow the user to select staff retrieved from the database which are able to view the MC once created.
The thing is I feel that a student could be granted many assignment extensions for one problem. I am wander if it is possible to include a button/image on the form which when clicked will create a new assessment extension object, and duplicate the form components to set the values for the object? This would all need to occur without any page refreshes.
Any advice, or links to good tutorials would be appreciated. I have so far been unable to find any suitable examples.
Thanks,
Jon
Comment: I don't this can't be answered your basically asking for an entire application here from db to UI layer.
Answer: There are a number of ways to do this, but the fastest is to create a javascript handler which creates the form controls without any sort of server request, all you need to do is keep track of how many items are in your list so you can name the form controls correctly.
Start by making a button that when you click on it creates form controls.  Once you get that, work on the naming.

ASP MVC Creating Form Rows Dynamically


(search) form without redirect or submit handler

Question: Use case:
Search field e.g. in the header, that leads to a url with GET query string.
The usual flow of forms built with Drupal 7 form API is like this:

User visits a page with the form.
User submits, $_POST or $_GET
Validate + submit handlers are called
Redirect to a new page.

What i would like instead:

User visits page with the form, that was built with form API.
User submits, resulting in a $_GET request, e.g. example.com/search?query=foo+bar.
The page example.com/search?query=foo+bar is served, without thinking about form API.

So, I want to use form API to build the form HTML (cause it's convenient), but not any submit magic.
Ideas?
Maybe I could find an example in existing modules, but I am looking for a "big picture" or documentation.
Comment: Why not make a submit button that just does a `drupal_goto`, with your query ?
Comment: sure this is an option. But it is a wasted http request with Drupal bootstrap.
Comment: You mean the destination URL is always the form URL ?
Comment: destination url is the form action attribute.
Answer: Not sure what you're exactly asking but everything should be well documented on Form API
I've recently done a form like this so I can give you an example of a GET method form:
/**
 * Form function for iwm_collections_search_form block
 */
function mymodule_search_form($form, &$form_state) {
  $form['#action'] = url(MYMODULE_SEARCH_PATH);
  $form['#method'] = 'get';
  $form['#attributes'] = array('class' => array('form-main'));
  $form['#after_build'][] = 'mymodule_search_form_after_build';
  $form['query'] = array(
    '#type' => 'textfield',
    '#title' => t('Keywords'),
    '#default_value' => '',
    '#size' => 30,
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#name' => '',
    '#value' => '',
    '#attributes' => array(
      'class' => array(
        'submit',
      ),
    ),
  );

  return $form;
}

You need an #after_build function to remove the unnecessary hidden fields so that it doesn't clutter the address bar:
/**
 * After build callback for mymodule_search_form
 */
function mymodule_search_form_after_build($form) {
  unset($form['form_token']);
  unset($form['form_build_id']);
  unset($form['form_id']);
  return $form;
}

No javascript, no submit handlers, easy.
Comment: Interesting. I suppose the form still goes into the $_SESSION, does it? Not a big problem, but it feels wrong.. (not saying this is your fault, maybe this is the only way)
Comment: You drink the water... you follow the rules :) If you want to use Form API then you gotta accept the rules
Comment: Ok so this means there is no API in Drupal that is "designed" for this kind of thing.
Comment: I think it's designed this way to keep it secure from various injections and tampering with the form. Not 100% sure on that.
Answer: If you don't want to build a submit function that simply does a drupal_goto, you can set a dummy submit button and with Javascript, preventDefault its action, and then do whatever you want as a query.
Comment: This sounds more like a workaround, and requires javascript. Not a bad answer, but there might be better ways.


How to add an image to ListView column header?

Question: It should be easy, right?
Have a listview, add an imagelist, add images to the imagelist, assign image index to the column you want.
But, it doesn't work.
Microsoft article states that it is a known problem in .NET 1.1.
But has it been fixed since?
Answer: You still have to use Interop. I suggest you to use the example given in the article.
Comment: Yeah, that's what I do. One would think this issues could have been solved already.
Comment: Alas, one can barely do anything advanced with Window Forms without resorting to WinAPI…
Answer: I did like this
1)made imagelist1
2)set the listviewlarge=imagelist1 & samallImagelist = imagelist1
3)write to form initilaize area
this.Columname0.ImageIndex = 0;
this.Columname1.ImageIndex = 1;
its work.


Undefined index: und on .tpl.php for content type

Question: How can i fix the error message?

the error message is Notice: Undefined index: und in include() (line
  9 of /var/www/html/sites/all/modules/custom/theme/icons.tpl.php).

my code is:
<code><?php
global $language ;
global $base_url , $base_path ;
$lang = $language->language;
$count = 0;
foreach ($data as $kay => $node_obj) {
    $node = node_load($node_obj->nid);
if (isset($node->field_description[$lang])) {
    $img_url = $node->field_icon['und'][0]['uri'] ;
$count++;
</code>
?>
Comment: Depending on installed modules, and templates, the array keys can vary. Have you tried something like: ->field_icon['#items']['uri']['value']?
Answer: I fix it by
add
<code>!empty( )
</code>
like this
<code>$img_url = !empty($node->field_icon['und'][0]['uri']) ;
</code>


Gmail and hotmail are tagging my mails as spam?

Question: We have two domains .local and .com. Sending connector uses .com fqdn while receiving connector uses .local fdn. I got an error "no reverse dns set". So i called my isp and get it done. After doing it.Gmail and hotmail started tagging my mails as spam.
While testing on mxtools i got smtp mismatch error.
I have
One send connector
Two receive connector- default and client.
Not able to change fqdn on default.
Server authentication is not letting me do so. We have Microsoft front page security for exchange. We are using firewall in which exchange ip is mapped to public ip.(nat).
Comment: Without more information it is hard to say but it sounds like your MX records may not match your configuration.  Again, we would need more detailed information regarding your issue.
Comment: since setting rdns broke this, i'm going to guess that your new rdns record has a non-matching forward pointer.  There must be matching records; RDNS & A record / fwd pointer or this can happen.
Comment: we have two primary dns:-(1) example.com (2)example.local.  In example.com we have A record as mail ip address is 192.168.1.11 which is our exchange server ip. Than this ip is mapped with external public ip in our firewall.
Answer: your PTR should be the same as your mail server name. (The name it uses when you telnet to your smtp server). Also a valid PTR needs an A record, too.
Bests,
Semir


how to count number of records found from database and display in jsp page using struts2?

Question:         List<CommonDTO> subjectList = new ArrayList<CommonDTO>();
            try {

                pstmt = conn.prepareStatement(SLCMQueryConstant.SEARCH_SUBJECT);
                pstmt.setString(1, commonDTO.getSubjectName());
                pstmt.setString(2, commonDTO.getSubjectCode());

                if(commonDTO.getIsActive()==0){

                    pstmt.setInt(3, commonDTO.IsActive = 1 );

                }
                else{

                    pstmt.setInt(3, commonDTO.IsActive= 0);
                }

                rs = pstmt.executeQuery();
                int count = 0;
                while (rs.next()) {
                    count++;
                    CommonDTO commondto = new CommonDTO();
                    commondto.setSubjectId(rs.getInt("Subject_Id"));
                    commondto.setSubjectCode(rs.getString("Subject_Code"));
                    commondto.setSubjectName(rs.getString("SubjectName"));
                    commondto.setSubjectNameHindi(rs.getString("SubjectName_Hindi"));
                    commondto.setIsActive(rs.getInt("Is_Active"));
                    commondto.setViewcount(count);
                    subjectList.add(commondto);
                }
                System.out.println(count);
            }
        return subjectList;

    public static final String SEARCH_SUBJECT = new StringBuilder("").
    append(" SELECT Subject_Id,Subject_Code,SubjectName,SubjectName_Hindi,Is_Active").
        append(" FROM  M_Subject_Master WHERE   Subject_Id=IFNULL(NULL,Subject_Id) ").
        append(" AND (SubjectName IS NULL OR SubjectName LIKE CONCAT('%',?,'%'))").
        append(" AND (Subject_Code IS NULL OR Subject_Code LIKE CONCAT('%',?,'%'))").
        append(" AND Is_Active = ?  ").
        append(" ORDER BY SubjectName").toString();

JSP Page to show number of records found
 =========================================
<s:iterator value="subjectList" var="quesvar" status="questat">
                    <s:hidden value="%{subjectId}" name="commonDTO.subjectId" id="subjectId"></s:hidden>
                    No.Of Records Found<s:property  value="subjectList[#questat.index].viewcount"/>

                        <s:property value="#questat.count"/>
                            <s:property  value="subjectList[#questat.index].subjectCode"/>
                            <s:property  value="subjectList[#questat.index].subjectName"/>

                            <a href="#" onClick="editSubject(<s:property  value="subjectList[#questat.index].subjectId"/>)" >View/Edit

                    </s:iterator>

How can I count number of records from database and print on jsp page ?
I don't use another prepare statement for count how can i display number of records fetch in jsp from database.
Answer: With this in your JSP file you could print the size
<s:property value ="subjectList.size()"/>

Comment: @pink great, could you validate the answer so another people could use it also in the future? Thanks!
Answer: You can also do it Directly from the database.
Include SQL_CALC_FOUND_ROWS after select like select SQL_CALC_FOUND_ROWS * from users
And then again fire Select FOUND_ROWS()
Note : just fire both query with same instance of database connector.
This will help you when you have lots of rows and you have applied limit. In that case you will have total no of records which may be greater then limit.
For example, in any UI for mysql Like SQLyog or workbench when you first try to open a table they their self append limit of 1000 records but table may contain more then 50000 records in that case getting count from array list may not give you total number of records every time.


Closed and bounded set in $\mathbb{R}^n$ is sequentially compact

Question: I want to prove that any closed and bounded set in $\mathbb{R}^n$ is sequentially compact.
Note that I want to prove this without using the Heine-Borel theorem and the equivalence of sequential compactness and compactness. Ah and I can use that any closed and bounded set in $\mathbb{R}$ is sequentially compact.
The way I did it is as follows: Let $S$ be a closed and bounded subset of $\mathbb{R}^n$. Then $\exists a,b \in \mathbb{R}$ such that $S \subseteq [a,b]\times [a,b] \times ...[a,b]$.
Now I will consider a sequence in $S$.
Let $x_p = (x_p^1, x_p^2,...,x_p^n) \forall p \in  \mathbb{N}$.
Then I will construct $n$ sequences of components of $x_p$.
Let $x^{(i)}=x_1^i,x_2^i...$
Then $x^{(1)}\subset [a,b]$, and $[a,b]$ is sequentially compact. so  $x^{(1)}$ has a convergent subsequence.
Now if we denote the indices of this sequence by $t_1,t_2...$ we know that $x^1_{t_1},x^1_{t_2}, x^1_{t_3}...$ converges to some $x$ in $[a,b]$.
Now if we consider  $x^2_{t_1},x^2_{t_2}, x^2_{t_3}...$ it is a sequence in $[a,b]$ a sequentially compact space. So it has a convergent subsequence. Again we take the indices of this subsequence and we consider them to build a subsequence of $x_3$ which converges.
After we have repeated this procedure $n$ times we are left with $n$ we have found a set of indices $f_1,f_2...$ such that $x^n_{f_1}, x^n_{f_2}...$ converges. But then by construction $x^p_{f_1}, x^p_{f_2}...$ converges $\forall  p \in1..n$ as it is a subsequence of a convergent sequence.
Then $x_{f_1},x_{f_2} ..$ converges (as it is a sequence in  $\mathbb{R}^n$ for which all individual components converge) and as it is included in a closed set, the limit of the sequence is part of the set.
Since we started with an arbitrary sequence, this proves that any closed and bounded set in $\mathbb{R}^n$ is sequentially compact.
Can you please have a look at this and tell me if something is wrong? It seems fine to me, but I really want to get the concept behind sequential compactness. I know that historically it was the first definition of compactness, so I find it important to see how knowledge evolved and how people initially proved it, without using compactness.
Also, please feel free to show me another proof, I am very interested in that as well.
Thank you!
Comment: http://en.wikipedia.org/wiki/Bolzano%E2%80%93Weierstrass_theorem
Answer: Your proof seems fine, and is quite similar to the standard proof that is mentioned in the link Qiaochu commented above. I find this following reasoning more intuitive, but some work needs to be done to make it a proof:
Start as you did, bounding your sequence in some large cube and cut the cube in half to make two rectangular prisms. At least one of these prisms has infinitely many points of the sequence inside of it - cut that one in half again. Now repeat this argument and you can see why you must have an accumulation point.
Answer: Let me give first the definitions:

D A metric space $M$ (or subset of a metric space) is said to be precompact if every sequence in $M$ contains a Cauchy (or fundamental) subsequence.

${}$

D Let $S$ be any subset of $\Bbb R^n$. Given $\epsilon >0$, we say that $N$ is an $\epsilon$-net for $S$ if the set of open balls
$$B_\epsilon(N)=\{B(x,\epsilon):x\in N\}$$
covers $S$. That is, the set of open balls of radius $\epsilon$ centered at the points of $N$ cover $S$.

Now, a theorem by Hausdorff

T Let $P$ be a metric space, $M$ a subset of $P$. Then $P$ is precompact if and only if, given $\epsilon >0$, $P$ contains a finite $\epsilon$-net for $M$.

P Suppose $M$ is precompact. Then given $\epsilon >0$, choose $x_1\in M$. If the point $x_1\in M$ is such that $d(x,x_1)<\epsilon$ for each $x\in M$; $\{x_1\}$ is itself an $\epsilon$-net, and we're done. If there exists points with $d(x,x_1)>\epsilon$, choose as $x_2$ one of these points. If now for every $x\in M$ we have either $d(x,x_1)<\epsilon$ or $d(x,x_1)<\epsilon$ , we're done. Else, continue the process, noting that the distance from each new $x_n$ to the $x_i\; ;1\leq i\leq n-1$ exceeds $\epsilon$. Thus, if the construction fails to terminate after a finite number of steps, we would obtain a sequence $\{x_n\}_{n\in \Bbb N }$ which contains no Cauchy subsequence, contrary to the hypothesis that $M$ is precompact. Thus, the construction must terminate, providing us with a finite $\epsilon$-net, $\{x_1,\dots,x_{\ell}\}$.
Conversely, suppose that for any $\epsilon>0$, $P$ contains a finite $\epsilon$-net for $M$, and let $A$ be any infinite subset of $M$, in particular, a sequence containing infinitely many distinct points of $M$. We can select a Cauchy subsequence as follows. Let $x_0\in A$ be any point, then take $\epsilon =1$ in the condition and cover $A$ with a finite number of balls of radius $1$. One of these balls, say $B_1$, must contain an infinite $A_1$ of $A$. Choose $x_1\in A_1\setminus \{x_0\}$. Choosing $\epsilon = 1/2$; we cover $A_1$ with a finite number of balls of radius $1/2$. One of them, say $B_2$ must contain an infinite subset $A_2$ of $A_1$. Choose $x_2\in A_2\setminus \{x_0,x_1\}$. Continuing this process, we obtain a sequence $A_0\supseteq A_1\supseteq A_2\cdots$, where each $A_n$ is contained in a ball of radius $1/n$ and a sequence of distinct points $x_0,x_1,x_2,\dots$ with $x_n\in A_n$. This sequence is Cauchy, for if $m<n$, $$B_m\supseteq A_m\supseteq A_n$$ which means $$d(x_n,x_m)<\frac 2 m$$Since $2/m\to 0$, we're done. It follows $M$ is precompact.
${}$
Look here for

T Let $S$ be bounded in $\Bbb R^n$. Then $S$ is precompact.

Now, since $\Bbb R^n$ is complete, any Cauchy (sub)sequence will converge. The assumption that the set is closed means the limit $\ell$ will be in such set. Thus, every bounded closed subset of $\Bbb R^n$ contains a convergent subsequence, that is, it is sequentially compact.
NOTE Observe the similarity of the $\implies$ direction of Hausdorff's criterion with the proof of Weiertrass-Bolzano that Ragib suggests.


Create syntactic sugar to define a variable as a class instance

Question: I'm trying to create my own class that acts like a regular type, like this:
class CustomType:
    def __init__(self, content):
        self.content = content
    def __str__(self):
        return self.content

This means I can do something like this:
a = CustomType("hi there")
print(a)  # 'hi there'

But the problem is that I have to use a = CustomType("hi there"). Is there a way I can do something  like a = /hi there\ or a similar solution that lets me create my own syntactic sugar?
Thanks.
Comment: Nope. Not unless you wanna hack the source.
Comment: There would be no way for the parser to know to look for that
Answer: No.  Python does not support creating new syntax.
Answer: Note: I would not suggest doing this.
You can't do that because the parser wouldn't know to look for it, but if you wanted something similar, you could create a custom class that returns a new instance of CustomType when divided by a string:
class CustomSyntax:
    def __truediv__(self, value):
        return CustomType(value)

Then if you had an instance of that class (let's call it c), you could divide it by a string any time you wanted an instance of CustomType:
a = c/'hi there'
b = c/'hello world'

However, that's a little weird, and you'd be best off sticking to your regular constructor.


Python/R Exploratory Data Analysis for Classification

Question: Are there preexisting functions in Python/R that create exploratory data analysis plots like the following:
Answer: In R, the pairs() command can do this (check the Scatterplot Matrices plot ): http://www.statmethods.net/graphs/scatterplot.html
In python, check seaborn for the pairplot() and Pairgrid methods:
http://stanford.edu/~mwaskom/software/seaborn/tutorial/axis_grids.html


Cannot change password for user postgres in postgresql

Question: I have made the following entry in pg_hba.conf

local   all all trust

but still

su postgres

does not accept blank as password. I am not able to run psql nor pg_ctl for same reason as most of the files are owned by postgres.

EDIT1

dhaval@ubuntu:~$ su -c "pg_ctl reload -D template1"
Password:
su: Authentication failure

dhaval@ubuntu:~$ su -c psql
Password:
su: Authentication failure

I am giving the root password above but I guess its expecting "postgres" superuser password. I dont have the same. I need to reset it.

EDIt2

dhaval@ubuntu:~$ sudo -i -u postgres
[sudo] password for dhaval:
postgres@ubuntu:~$ psql
Welcome to psql 8.3.7, the PostgreSQL interactive terminal.

The above has taken me postgreSQL command prompt. But I am still not sure why the "trust" was not working.
Comment: "trust" is working fine -- **Postgres** trusts you, the **OS** does not (you are not root, therefore when you try to `su` to postgres you must enter the **postgres OS user**'s password)  -- There are two different authentication stores, and two separate "users" here (one set for the OS and one for DB).  Also note that you don't need to `su` to postgres (see the `-U` option to psql to specify a database username other than the currently-logged-in OS user)
Answer: Operating System User passwords (the thing you're asked for when you try to su) are not the same as Postgres User Passwords (the thing you don't need when you set auth to trust in pg_hba.conf).
You need to set a valid OS password for the Operating System's postgres user and enter that password in order to su to that user (Or su to that user from  root, where you won't be asked for a password).
Typically the postgres OS user password is locked out after DB initialization since the only thing that needs to run as postgres is pg_ctl, which can be launched with su -c from your init scripts (that run as root and therefore don't need the password).
Comment: Yes, but to enter postgresql I need the postgres superuser password which I dont have.
Answer: Most likely you are trying to do 'su postgres'. Ubuntu does not allow a non-root user to switch to another user. So you may need to assume root and then su postgres.
To become 'root', try:
sudo su -
After that, try:
su postgres
That should get you access as the 'postgres' user as understood by the OS.
Hope this helps.
best
Vishal Belsare


PerfMon "Data Collector" Vs. "Save Settings"/html

Question: Perfmon seems to have two ways to capture / log its findings.  One is to use a "data collector," and the other is to open a context menu and "Save Settings As" which produces an html file.
Could someone explain what scenario(s) inspire the two different means of capturing data?  I mean, I've noticed that data collectors can be stored as CSV, binary, SQL, etc.  That unto itself makes a data collector very useful.  But then why have the html format?
I want to use the tool as expertly as possible, so I'm trying to understand the subtleties of its recording capabilities.
Answer: Just as you've said, data collector actually collects the data from perfmon and stores it. It runs as a separate process.
And as you said, save settings does exactly that.... It saves the monitors that you've setup in the active perfmon view for easy loading later, as, when you close perfmon, the settings return to default.
Data collector settings and information persists through closing and opening of perfmon, but the active view perfmon settings do not.
The clipboard icon easily allows you to load settings from your clipboard for the active view of perfmon. Just open the HTML file you saved, copy it, and click the clipboard button, and the settings will load into the active view.
It is a very clunky way to go about saving and loading settings, but this is how Microsoft has setup perfmon.


using something other than *for* loop

Question: i have this code i'm using for my bot and the point of the code is to give role on reaction but refer to reactionRolesDict for the information,
i have a bit of the code that i want to change but mainly the first for loop for category in reactionRolesDict: to something else because it makes the code execute once for every category in the dict.
this is the code:

reactionRolesDict = {
  gender_roles_id: {
    "emotes": ["♂", "♀"],
    "roles": [male_role, female_role],
    "exclusive": True
  },
  ping_roles_id: {
    "emotes": ["", "", "", "", ""],
    "roles": [announcements_role, giveaway_role, events_role, server_update_role, other_role],
    "exclusive": False
  }
)

@bot.event
async def on_raw_reaction_add(payload):

  for category in reactionRolesDict:

    if payload.message_id == reaction_gender_roles_id:
      print('''this prints as many times as there is categories in *reactionRolesDict*''')

      category = reactionRolesDict[category]

      if payload.emoji.name in category["emotes"]:

        role = category["roles"][category["emotes"].index(payload.emoji.name)]
        member = discord.utils.get(guild.members, id=payload.user_id)

        if category["exclusive"]:

          for has_role in category["roles"]:

            if has_role in member.roles:

              print('member has a role from the same category')

              return

          await member.add_roles(role)

edit: removed unnecessary parts of the code
Comment: You haven't said what you actually _want_.  Okay, you don't want to loop once for every category.  What should the code do instead?
Comment: And do you have any requirements on what the something else should do? Perhaps you can exchange `for` and the first if statement since it is independent of the category.
Comment: ... Just remove the for loop?
Comment: yeah, sorry if i wasn't clear about it. basically i want to change the `for` loop to `if` statment or something that would serve the code better. unfortunately i tried removing the `for` loop but it breaks it
Comment: It's still not clear what this is supposed to do. But maybe you just want to use a variable as the key of `reactionRolesDict`? So do something with `reactionRolesDict[someVariable]`?
Comment: i'm gonna be honest, i didn't write this code and i don't know much about python, all i cared about is that it works; i was looking at your comment for a hot minute and i couldn't understand what you meant
Comment: "because it makes the code execute once for every category in the dict" and *what* do you want it to do instead?
Answer: alot of people didn't understand what you meant, i believe that you want to hard code for every category, if that's the case then i would not recommend you do it that way because the code you have right now serves all categories by it self without the need of repeating.
nevertheless this is the hard coded version of the code (of which i don't recommend)

reactionRolesDict = {
  gender_roles_id: {
    "emotes": ["♂", "♀"],
    "roles": [male_role, female_role],
    "exclusive": True
  },
  ping_roles_id: {
    "emotes": ["", "", "", "", ""],
    "roles": [announcements_role, giveaway_role, events_role, server_update_role, other_role],
    "exclusive": False
  }
)

@bot.event
async def on_raw_reaction_add(payload):

  for category in reactionRolesDict:

    if payload.message_id == gender_roles_id:
      print('''this prints as many times as there is categories in *reactionRolesDict*''')

      category = reactionRolesDict[category]

      if payload.emoji.name in category["emotes"]:

        role = category["roles"][category["emotes"].index(payload.emoji.name)]
        member = discord.utils.get(guild.members, id=payload.user_id)

        if category["exclusive"]:

          for has_role in category["roles"]:

            if has_role in member.roles:

              print('member has a role from the same category')

              return

          await member.add_roles(role)

    if payload.message_id == ping_roles_id:
      print('''this prints as many times as there is categories in *reactionRolesDict*''')

      category = reactionRolesDict[ping_roles_id]

      if payload.emoji.name in category["emotes"]:

        role = category["roles"][category["emotes"].index(payload.emoji.name)]
        member = discord.utils.get(guild.members, id=payload.user_id)

        if category["exclusive"]:

          for has_role in category["roles"]:

            if has_role in member.roles:

              print('member has a role from the same category')

              return

          await member.add_roles(role)

i do not recommend you do this at all but it's there if you want to hard code it

using something other than *for* loop


Dynamically updating time data in chart.js freezes the chart

Question: I am using chart.js via ng2-charts to display a simple line chart that is fed with dynamic data whose X value is a timestamp. Therefore I am using the time cartesian axis of chart.js
When I start pushing data into the chart all is fine but I want to limit the amount of data shown to a max value, so I have implemented a simple mechanism where the oldest element is removed from the array as it gets filled.
This behavior seems to make the chart freeze and as a consequence shows this bug.
The problem is shown in this stackblitz: just wait a few seconds for the array to have three values (the max):
https://stackblitz.com/edit/ng2-charts-line-template-gzhikq
If I remove the "time" configuration from chart.js and feed the labels manually the problem does not show up (but this is not what I want!).
https://stackblitz.com/edit/ng2-charts-line-template-rs6enh
So the problem seems to be related to the usage of the time axis. I have tried the solutions explained in the bug mentioned above but none works (probably because they deal with the symptom not the root cause). Any help is greatly appreciated.
Answer: In your code, you add an element to your data array and remove the oldest one as soon as the limit of three entries is exceeded. The problem with this approach is that Angular doesn't notice changes in your data array because its reference doesn't change and its size remains the same.
The issue can be solved by replacing the data array inside ChartDataSets each time the data changes. Instead of using Array.shift(), you could use Array.slice().
lineChartData: ChartDataSets[] = [{
    data: [],
    label: 'Series A'
}];

...

ngOnInit() {
    this.interval = setInterval(() => {
        const data = this.lineChartData[0].data;
        data.push({ y: Math.random(), x: new Date() });
        this.lineChartData[0].data = data.slice(data.length > 3 ? 1 : 0);
    }, 2000);
    ...
}

Please have a look at the following StackBlitz
Comment: Thanks, I can use this as workaround in the short term but it does not address the root issue. Note shift() does change the size of the array so Angular should notice (it notices indeed in the second stackblitz I have done as an example). The other problem with this reassignment of data is that he graph if fully redrawn therefore the "flow" of time is not perceived (see the difference of your example with my second stackblitz)


What does --with-cflags="-Wno-error=implicit-function-declaration" do?

Question: I was struggling to install thin as a dependency in a Ruby project, when I came across this solution here: https://github.com/macournoyer/thin/issues/365#issuecomment-692063842 (gem install thin -v '1.7.2' -- --with-cflags="-Wno-error=implicit-function-declaration")
It works, but I'm not very familiar with Ruby so have no idea why. What is this flag doing? Why does it make the install work without any issues?

The error I was getting before this fix:
❯ gem install thin -v '1.7.2'
Building native extensions. This could take a while...
ERROR:  Error installing thin:
        ERROR: Failed to build gem native extension.

    current directory: /Users/XXX/.gem/ruby/2.7.1/gems/thin-1.7.2/ext/thin_parser
/Users/XXX/.rubies/ruby-2.7.1/bin/ruby -I /Users/XXX/.rubies/ruby-2.7.1/lib/ruby/2.7.0 -r ./siteconf20210923-79304-z21dcg.rb extconf.rb
checking for main() in -lc... yes
creating Makefile

current directory: /Users/XXX/.gem/ruby/2.7.1/gems/thin-1.7.2/ext/thin_parser
make "DESTDIR=" clean

current directory: /Users/XXX/.gem/ruby/2.7.1/gems/thin-1.7.2/ext/thin_parser
make "DESTDIR="
compiling parser.c
parser.c:31:18: warning: unused variable 'http_parser_en_main' [-Wunused-const-variable]
static const int http_parser_en_main = 1;
                 ^
1 warning generated.
compiling thin.c
thin.c:242:3: error: implicit declaration of function 'thin_http_parser_init' is invalid in C99 [-Werror,-Wimplicit-function-declaration]
  thin_http_parser_init(hp);
  ^
thin.c:242:3: note: did you mean 'http_parser_init'?
./parser.h:41:5: note: 'http_parser_init' declared here
int http_parser_init(http_parser *parser);
    ^
thin.c:260:3: error: implicit declaration of function 'thin_http_parser_init' is invalid in C99 [-Werror,-Wimplicit-function-declaration]
  thin_http_parser_init(http);
  ^
thin.c:277:3: error: implicit declaration of function 'thin_http_parser_init' is invalid in C99 [-Werror,-Wimplicit-function-declaration]
  thin_http_parser_init(http);
  ^
thin.c:294:3: error: implicit declaration of function 'thin_http_parser_finish' is invalid in C99 [-Werror,-Wimplicit-function-declaration]
  thin_http_parser_finish(http);
  ^
thin.c:294:3: note: did you mean 'Thin_HttpParser_finish'?
thin.c:290:7: note: 'Thin_HttpParser_finish' declared here
VALUE Thin_HttpParser_finish(VALUE self)
      ^
thin.c:296:10: error: implicit declaration of function 'thin_http_parser_is_finished' is invalid in C99 [-Werror,-Wimplicit-function-declaration]
  return thin_http_parser_is_finished(http) ? Qtrue : Qfalse;
         ^
thin.c:334:5: error: implicit declaration of function 'thin_http_parser_execute' is invalid in C99 [-Werror,-Wimplicit-function-declaration]
    thin_http_parser_execute(http, dptr, dlen, from);
    ^
thin.c:334:5: note: did you mean 'Thin_HttpParser_execute'?
thin.c:317:7: note: 'Thin_HttpParser_execute' declared here
VALUE Thin_HttpParser_execute(VALUE self, VALUE req_hash, VALUE data, VALUE start)
      ^
thin.c:338:8: error: implicit declaration of function 'thin_http_parser_has_error' is invalid in C99 [-Werror,-Wimplicit-function-declaration]
    if(thin_http_parser_has_error(http)) {
       ^
thin.c:338:8: note: did you mean 'http_parser_has_error'?
./parser.h:44:5: note: 'http_parser_has_error' declared here
int http_parser_has_error(http_parser *parser);
    ^
thin.c:359:10: error: implicit declaration of function 'thin_http_parser_has_error' is invalid in C99 [-Werror,-Wimplicit-function-declaration]
  return thin_http_parser_has_error(http) ? Qtrue : Qfalse;
         ^
thin.c:374:10: error: implicit declaration of function 'thin_http_parser_is_finished' is invalid in C99 [-Werror,-Wimplicit-function-declaration]
  return thin_http_parser_is_finished(http) ? Qtrue : Qfalse;
         ^
9 errors generated.
make: *** [thin.o] Error 1

make failed, exit code 2

Gem files will remain installed in /Users/XXX/.gem/ruby/2.7.1/gems/thin-1.7.2 for inspection.
Results logged to /Users/XXX/.gem/ruby/2.7.1/extensions/x86_64-darwin-19/2.7.0-static/thin-1.7.2/gem_make.out

Answer: I didn't read the stack trace properly...
It looks like this flag is basically telling the compiler to ignore where functions are implicitly declared rather than erroring out when this happens.


Windows Phone GPS Emulator not firing GPS Location Changed event

Question: The title pretty much says it. I have a GPS object with a location changed event registered.
I know that the code works because it logs my position as I move with a real device.
The Windows phone 8 emulator that is in the Visual studio 2012 sdk isn't firing the location changed event though and I don't know why.
I would post code but it's redundant and not the cause. I think the issue is with the emulator. Is there anyone else having this issue?
Answer: Turns out this is a bug
http://social.msdn.microsoft.com/Forums/wpapps/en-US/c2cc57b1-ba1f-48fb-b285-d6cfbb8f393a/windows-phone-8-emulator-returns-microsofts-location-only
Here is a work around that kinda works

Start your app in emulator
Set location
Go to the MAPs app on the emulator
Click find my location (Wait for it to find you)
Go back into your app and see that the new location is updated

You must do this for every move in the emulator you want to make


Apollo GraphQL FetchMore

Question: I'm trying to get Apollo gql to load more posts after clicking a button. So it would load the next 15 results, every time you click - load more.
This is my current code
import Layout from "./Layout";
import Post from "./Post";
import client from "./ApolloClient";
import { useQuery } from "@apollo/react-hooks"
import gql from "graphql-tag";

const POSTS_QUERY = gql`
  query {
    posts(first: 15) {
      nodes {
        title
        slug
        postId
        featuredImage {
          sourceUrl
        }
      }
    }
  }
`;

const Posts = props => {
  let currPage = 0;
  const { posts } = props;
  const { loading, error, data, fetchMore } = useQuery(
    POSTS_QUERY,
    {
      variables: {
        offset: 0,
        limit: 15
      },
      fetchPolicy: "cache-and-network"
    });

  function onLoadMore() {
    fetchMore({
      variables: {
        offset: data.posts.length
      },
      updateQuery: (prev, { fetchMoreResult }) => {
        if (!fetchMoreResult) return prev;
        return Object.assign({}, prev, {
          posts: [...prev.posts, ...fetchMoreResult.posts]
        });
      }
    });
  }

  if (loading) return (

          Loading...

  );
  if (error) return (

          Oops, there was an error :( Please try again later.

  );
  return (

          {data.posts.nodes.length
            ? data.posts.nodes.map(post => <Post key={post.postId} post={post} />)
            : ""}

        <button onClick={() => { onLoadMore() }}>Load More</button>

  );
};

export default Posts;

When you click load more it refreshes the query and console errors
Invalid attempt to spread non-iterable instance
I have been loading for solutions but a lot of the examples are previous or next pages like traditional pagination. Or a cursor based infinite loader which I don't want. I just want more posts added to the list onClick.
Any advise is appreciated, thank you.
Answer: Your current POSTS_QUERY it isn't accepting variables, so first you need change this:
const POSTS_QUERY = gql`
  query postQuery($first: Int!, $offset: Int!) {
    posts(first: $first, offset: $offset) {
      nodes {
        title
        slug
        postId
        featuredImage {
          sourceUrl
        }
      }
    }
  }
`;

Now, it will use the variables listed in your useQuery and fetchMore.
And to finish the error is because updateQuery isn't correct, change it to:
function onLoadMore() {
    fetchMore({
      variables: {
        offset: data.posts.nodes.length
      },
      updateQuery: (prev, { fetchMoreResult }) => {
        if (!fetchMoreResult) return prev;
        return { posts: { nodes: [...prev.posts.nodes, ...fetchMoreResult.posts.nodes] } };
        });
      }
    });
  }

Answer: I would suggest useState hook to manage a variable that stores current offset in the dataset, place a useEffect to watch changes to that offset, the offset value in passed as query variable to load data. Remove fetchmore, useEffect hook will do the job.
When user clicks on load more button, you just need to update offset value, that will trigger the query and update data.
const [offset,setOffset] = React.useState(0)
const [results, setResults] = React.useState([])

const { loading, error, data } = useQuery(
    POSTS_QUERY,
    {
      variables: {
        offset: offset,
        limit: 15
      },
      fetchPolicy: "cache-and-network"
    }
);

React.useEffect(() => {
 const newResults = [...results, ...data]
 setResults(newResults)
}, [data])

function onLoadMore() {
 setOffset(results.data.length)
}

Comment: Does that not require me to query all the posts initially though?
Comment: The query variable 'offset' will be a state variable, whenever it is updated, the query will run and the data returned in set in another state variable. This is cover the functionality if fetchMore function. No need to query everything initially. Only ask for 15 results and update offset(from state) on load more.
Comment: Are you able to help with an example, sorry I can't figure this out :(
Comment: I appreciate the help, unfortunately I get 'Invalid attempt to spread non-iterable instance'
Comment: It seems the data returned from API is not iterable. Dump that in console and inspect, it will help :)

Apollo GraphQL FetchMore


how to solve a pde whose coefficient is the function itself

Question: I am studying differential geometry, Walker metric in three dimension.
I try to find the geodesic equations of a Walker manifold and I need to solve the following PDE. Unfortunately, I didn't take any PDE course and I don't know what kind of PDE it is and how to solve it.
$f\frac{\partial f}{\partial x}-\frac{\partial f}{\partial z}=0,\quad \frac{\partial f}{\partial y}=0$
where $f(x,y,z)$ is a continuous function.
Any suggestion would be greatly appreciated.
Also, can you advise me an elementary PDE book easy to follow and self-study.
Comment: The geodesic equations are second order and quadratic in first derivatives. Are you sure you have the right system?
Comment: the first term cries out to be written as $\tfrac12 \frac{\partial}{\partial x} (f^2)$.
Comment: f is not the geodesic curve, it is the function of the Walker metric. I might be wrong but I got this PDE a few times. There is a system of PDEs and I need to solve this PDE as a part of the solution.
Answer: Take $f(x,y,z)= -\frac{x}{z}$. Then: $\frac{\partial f}{\partial x} = -\frac{1}{z}$, and $\frac{\partial f}{\partial z}= \frac{x}{z^2}$. Then: $f \frac{\partial f}{\partial x} = (-\frac{x}{z})(-\frac{1}{z})= \frac{x}{z^2}= \frac{\partial f}{\partial z}$ and $\frac{\partial f}{\partial y}=0$, as desired.
Comment: Thanks for the solution. I am trying to find a general solution but this will help too. :)


Statistical test for single sample vs empirical distribution?

Question: I have a sort of strange problem, where my sample is difficult to obtain, but the population distribution is easy to obtain.  Specifically, I have obtained a single observation.  I would like to know if it comes from a particular population.  A closed form for the population distribution is not known, but I can resample it ad infinitum and obtain an empirical distribution to any desirable degree of accuracy.  Judging by the pretty-picture method, the distribution is not normal enough to assume normality, but is normal enough for me to wonder if there is something better to use here than Chebyshev's Inequality.
Are there any Nonparametric methods that can be used to test a single observation against an empirical distribution?
Comment: If your null hypothesis is that the sample observation did come from that population then then there is a $5\%$ probability that the sample will be in top tail or bottom tail of the known samples from the population.  So take your  resamples (one less than a multiple of $40$ might work) and look at the ranked position of the observation you are interested in among these
Comment: Do you have any specific (perhaps intractable) alternative distribution(s) in mind?
Comment: @jbowman, not really... I could probably fit e.g. a Gamma to it with some success, since it "looks like" a skewed normal and is guaranteed to be > 0.  OTOH, I have no a priori reason to expect the population to be gamma, so a nonparametric form would really be preferable.
Comment: @jbowman aaaaahhhhhh, I think I take your meaning now.  You mean that if I had some other hypothesis for the population distribution besides the one I can empirically determine, I could employ the [Likelihood Ratio Test](https://en.wikipedia.org/wiki/Likelihood-ratio_test)?
Comment: Something along those lines, yes.   But if you don't, you don't.
Answer: There is no statistical test because you have a sample, not a sampling distribution. You can compute distance metrics (eg, Z-score in case of normal distributions) but this would not be an inferential test
Comment: If it is the former, then I would posit a simpler analogy, wherein I get a single point estimate of "7", and ask the question "what is the likelihood that this is the result of a coin flip?"  Clearly some kind of inference can be made here, although perhaps "statistical inference" is not the correct label.
Comment: "but this would not be an inferential test" Are you making a semantical claim or an existential one?
Comment: An accurate claim. Inferential tests make assumptions that do not accommodate single point estimates.
Comment: You mistake my meaning.  Do you intend to say that nothing can be logically inferred about the likelihood that a point estimate belongs to a particular population with a known distribution, or do you intend merely to say that such an inference is not properly "statistical inference"?
Comment: If I have a null hypothesis that my data is distributed Gaussian $(0,1)$, and I observe a single value of $6$, it seems to me I can certainly apply a test and reject the null; the non-rejection region for $H_0$ might be, e.g., $(-1.96, +1.96)$ or some such, but it's still a test.
Comment: You can call it a test but it is not a inferential test. Meaning, with NHST you are making an inference about an unobserved population based on a sample statistic. A single observation is not a statistic. That said you can calc the p(obs) given h(distribution), yea, but it doesn't allow you to generalize


Turn dictionary of lists into a 1D numpy array

Question: I have a Python 3 dictionary holding very long lists (30 million integers each). I would like to stitch all these lists into a single numpy array. How can I do this efficiently?
The following
np.array(my_dict.values())

doesn't seem to work (I get array(dict_values([[...], [....])) as opposed to a flat 1D numpy array).
Comment: in Python 3 just do `np.array(list(my_dict.values())).flatten()`
Answer: If you're looking for a flat 1d array, you could just use np.concatenate:
>>> d = {'a': [1, 2, 3, 4, 5], 'b': [1, 2, 3, 4, 5], 'c': [1, 2, 3, 4, 5]}
>>> np.concatenate(list(d.values()))
array([1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5])

Answer: try this
list(my_dict.values())

(commentary added)
dict.values() returns view not a list. Refer here
Comment: While this might answer the authors question, it lacks some explaining words and links to documentation. Raw code snippets are not very helpful without some phrases around it. You may also find [how to write a good answer](https://stackoverflow.com/help/how-to-answer) very helpful. Please edit your answer.
Answer: from itertools import chain
import numpy as np
chn = chain.from_iterable(d.values())
np.array(list(chn))

Comment: `list(chn)` makes more sense than `[x for x in chn]`. It's faster, too.
Comment: for me (Python 3) `np.array(list(chain(d.values())))` works
Comment: +1 if he doesn't need any order based on the keys this was the fastest approach
Answer: Allocate numpy arrays ahead of time:
my_dict = {0:[0,3,2,1], 1:[4,2,1,3], 2:[3,4,2,1]}
array = numpy.ndarray((len(my_dict), len(my_dict.values()[0]))

then you can insert them into the array like so:
for index, val in enumerate(my_dict.values()):
    arr[index] = val
>>> arr
array([[ 0.,  3.,  2.,  1.],
       [ 4.,  2.,  1.,  3.],
       [ 3.,  4.,  2.,  1.]])

Comment: This creates a multidimensional array not a 1d array as requested by the OP
Answer: In order to get an ordered concatenation based on the keys:
np.array([d[k] for k in sorted(d.keys())]).flatten()

if you don't need any order based on the keys, @Padraic Cunningham's approach was the fastest based on my timings here...