Pesquisar apenas se clicar no botão

Question: Estou fazendo um campo de pesquisa parecido com o CTRL+F, mas ao abrir o site em um celular Android mais antigo, o celular trava, queria estar colocando para pesquisar a palavra/letra apenas quando o usuário clicar no botão, pois de momento está pesquisando de forma automática(somente precisa digitar que a palavra já é marcada, preciso que a palavra seja procurada apenas após o usuário clicar no botão). Poderiam me ajudar por favor, pois não estou conseguindo.
Html

  Search:
  <input type="search" placeholder="Lorem">
  <button data-search="next">↓</button>
  <button data-search="prev">↑</button>
  <button data-search="clear">✖</button>

    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis eu ullamcorper orci, eget porttitor justo. Aliquam id sollicitudin elit. Nulla in sodales ipsum. Donec vulputate venenatis magna. Vestibulum sit amet leo lacinia, cursus lectus in, gravida
    metus. In ultricies sed tortor non pellentesque. Mauris quis tempor neque. Donec nec sagittis magna. Integer fringilla posuere metus eu mollis. Ut ac porta metus. Duis sed lacinia metus. Nunc malesuada iaculis risus vitae bibendum.

    Vivamus posuere condimentum leo eu hendrerit. Pellentesque placerat iaculis ante a rhoncus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum eu ipsum ac magna congue congue sed maximus tortor. Vivamus id odio elementum, vehicula nunc
    ut, efficitur felis. Nullam hendrerit velit libero, gravida porttitor tortor ullamcorper eu. Ut ut lectus non enim sagittis aliquam quis in orci. Donec a arcu eu eros cursus cursus. Donec dictum dignissim tellus, dictum egestas purus pellentesque
    sed.

    Vestibulum eu ornare urna, nec aliquam lectus. Phasellus eu odio sapien. Vestibulum eu turpis at lorem sagittis posuere. Quisque tellus nunc, facilisis id lacus nec, ornare rhoncus elit. Vivamus vehicula eros a condimentum venenatis. Sed orci massa, pulvinar
    sed erat nec, pellentesque suscipit leo. Mauris lobortis tincidunt nunc, sed tempus ex congue vitae. Curabitur lobortis mauris in ex malesuada, quis vehicula neque lobortis. Curabitur aliquam porttitor tellus eget tempus. Donec maximus tempus tristique.
    Aliquam tincidunt odio dictum, scelerisque ipsum ut, facilisis quam. Ut nec malesuada neque.

    Proin felis eros, tincidunt vitae scelerisque sit amet, dictum nec ante. Praesent tincidunt ac lacus nec elementum. Vivamus sed gravida purus, sed efficitur tortor. Nulla non molestie arcu. Sed tincidunt consectetur ligula sed lobortis. In non sapien
    ac urna lacinia placerat sed nec lacus. Aenean lobortis tincidunt sapien a hendrerit. Quisque eu turpis accumsan nisl blandit efficitur.

    Nam sit amet pellentesque est. Sed ligula turpis, ultricies sit amet mattis elementum, tristique non risus. Phasellus at congue ex. Proin nisi leo, vestibulum vitae accumsan in, imperdiet id dolor. Quisque at blandit nisl. Class aptent taciti sociosqu
    ad litora torquent per conubia nostra, per inceptos himenaeos. Nunc eget metus augue. Morbi faucibus venenatis sapien, fermentum porttitor felis pharetra a. Nam interdum nibh tortor, quis maximus turpis blandit eget. Praesent in feugiat neque, sed
    vulputate quam. Curabitur erat quam, efficitur et congue quis, iaculis euismod libero. Quisque odio sapien, efficitur non mauris ac, tincidunt condimentum turpis.

    Maecenas dapibus aliquam vehicula. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Praesent convallis viverra leo quis porta. Sed sit amet porttitor quam. Fusce nec risus non augue consectetur ultricies. Aliquam
    elit lorem, tincidunt ac dolor vel, vulputate consectetur ex. In hac habitasse platea dictumst. Sed eget nisl aliquam, cursus odio nec, commodo lorem. Nulla mollis tortor eu odio rutrum vulputate. Donec condimentum molestie mauris, nec sodales nisi
    volutpat aliquam. Nulla mollis libero sed nibh volutpat, ac mollis elit tincidunt. Vestibulum cursus velit vitae felis aliquam ultricies. Donec vehicula dictum feugiat. Vestibulum volutpat sollicitudin sagittis.

    Aliquam consequat, diam eu ullamcorper porta, diam eros rhoncus turpis, in rutrum sem diam a risus. Duis lacinia velit sed ante feugiat venenatis. Aenean orci leo, dictum non finibus nec, dignissim quis eros. Nullam sit amet orci ac purus blandit commodo
    sit amet eget neque. Sed pellentesque dictum tortor. Ut dui erat, tempus in odio in, aliquet convallis mi. Morbi efficitur justo ante, quis ultricies turpis suscipit ac. Sed sit amet nisl rutrum, laoreet mauris id, ullamcorper orci. In facilisis nisi
    eget fringilla imperdiet. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Morbi ut ultricies dui. Pellentesque elit urna, imperdiet sed congue eget, hendrerit sed urna.

    Proin vel hendrerit nulla. Vivamus vehicula nibh nec lorem blandit, quis aliquam ipsum suscipit. Nulla at vestibulum felis. Aenean ac nibh eget enim molestie pulvinar. Duis nulla justo, tristique id nulla nec, faucibus imperdiet arcu. In vel pretium dui,
    at lobortis sapien. Phasellus ullamcorper id enim eget dictum. Ut imperdiet rutrum est a rutrum. Curabitur eget dignissim tellus. Fusce tempus leo nisl, vitae auctor diam feugiat sit amet. Vestibulum accumsan justo eget odio imperdiet, consectetur
    efficitur ex dapibus.

    Sed pharetra odio a nibh pharetra rutrum. Suspendisse ut ullamcorper lectus. Donec ipsum mauris, congue et lobortis sit amet, ultricies ac tellus. Sed nisi risus, condimentum at varius quis, condimentum ac velit. In condimentum, magna sed ornare eleifend,
    dolor nulla mollis felis, quis feugiat elit turpis non ipsum. Etiam aliquam est imperdiet dolor rutrum, at varius leo sodales. Morbi quis iaculis metus.

    Maecenas auctor nec ligula ac luctus. Nam sit amet euismod mauris. Donec et diam sit amet eros efficitur tempor. Mauris non erat sit amet nunc interdum pulvinar. Sed luctus hendrerit justo eget pulvinar. Cras non arcu sed ligula faucibus pulvinar. Sed
    egestas risus nisl. Duis quis arcu tempus, cursus erat ac, gravida enim. Cras et condimentum ante. Nullam eleifend egestas velit, quis semper est imperdiet non. Donec quis purus varius, placerat mi et, dictum lorem. Sed quis finibus nisi, vitae molestie
    metus. Donec lobortis eros quis vestibulum vulputate.

JavaScript
$(function() {

  var $input = $("input[type='search']"),
    $clearBtn = $("button[data-search='clear']"),
    $prevBtn = $("button[data-search='prev']"),
    $nextBtn = $("button[data-search='next']"),
    $content = $(".content"),
    $results,
    currentClass = "current",
    offsetTop = 50,
    currentIndex = 0;

  /**
   * Saltar para o elemento correspondente ao currentIndex
   */
  function jumpTo() {
    if ($results.length) {
      var position,
        $current = $results.eq(currentIndex);
      $results.removeClass(currentClass);
      if ($current.length) {
        $current.addClass(currentClass);
        position = $current.offset().top - offsetTop;
        window.scrollTo(0, position);
      }
    }
  }

  /**
   * Procurar a palavra-chave inserida no
   * contexto especificado na entrada
   */
  $input.on("input", function() {
    var searchVal = this.value;
    $content.unmark({
      done: function() {
        $content.mark(searchVal, {
          separateWordSearch: true,
          done: function() {
            $results = $content.find("mark");
            currentIndex = 0;
            jumpTo();
          }
        });
      }
    });
  });

  /**
   * Limpar a pesquisa
   */
  $clearBtn.on("click", function() {
    $content.unmark();
    $input.val("").focus();
  });

  /**
   * Salto para a pesquisa seguinte e anterior
   */
  $nextBtn.add($prevBtn).on("click", function() {
    if ($results.length) {
      currentIndex += $(this).is($prevBtn) ? -1 : 1;
      if (currentIndex < 0) {
        currentIndex = $results.length - 1;
      }
      if (currentIndex > $results.length - 1) {
        currentIndex = 0;
      }
      jumpTo();
    }
  });
});

Peguei esse código no site: https://jsfiddle.net/julmot/973gdh8g/
Answer: O mais importante ao copiar o código de algum lugar é entender o que ele realmente está fazendo. Neste caso, o método "on" do jQuery é usado para adicionar um event handler ao "$input", que é o campo de pesquisa.
Para alterar o comportamento conforme vc deseja, é preciso adicionar outro botão e substituir o handler do evento "input" do campo original por um "click" no botão novo. Algo como o código abaixo.
Note que o código original foi copiado e as adições e alterações marcadas com "adicionado" e "alterado", respectivamente.

$(function() {

  // the input field
  var $input = $("input[type='search']"),
    // clear button
    $searchBtn = $("button[data-search='search']"), // adicionado
    // clear button
    $clearBtn = $("button[data-search='clear']"),
    // prev button
    $prevBtn = $("button[data-search='prev']"),
    // next button
    $nextBtn = $("button[data-search='next']"),
    // the context where to search
    $content = $(".content"),
    // jQuery object to save  elements
    $results,
    // the class that will be appended to the current
    // focused element
    currentClass = "current",
    // top offset for the jump (the search bar)
    offsetTop = 50,
    // the current index of the focused element
    currentIndex = 0;

  /**
   * Jumps to the element matching the currentIndex
   */
  function jumpTo() {
    if ($results.length) {
      var position,
        $current = $results.eq(currentIndex);
      $results.removeClass(currentClass);
      if ($current.length) {
        $current.addClass(currentClass);
        position = $current.offset().top - offsetTop;
        window.scrollTo(0, position);
      }
    }
  }

  /**
   * Searches for the entered keyword in the
   * specified context on input
   */
  $searchBtn.on("click", function() { // alterado
    var searchVal = $input.val(); // alterado
    $content.unmark({
      done: function() {
        $content.mark(searchVal, {
          separateWordSearch: true,
          done: function() {
            $results = $content.find("mark");
            currentIndex = 0;
            jumpTo();
          }
        });
      }
    });
  });

  /**
   * Clears the search
   */
  $clearBtn.on("click", function() {
    $content.unmark();
    $input.val("").focus();
  });

  /**
   * Next and previous search jump to
   */
  $nextBtn.add($prevBtn).on("click", function() {
    if ($results.length) {
      currentIndex += $(this).is($prevBtn) ? -1 : 1;
      if (currentIndex < 0) {
        currentIndex = $results.length - 1;
      }
      if (currentIndex > $results.length - 1) {
        currentIndex = 0;
      }
      jumpTo();
    }
  });
});
mark {
  background: yellow;
}

mark.current {
  background: orange;
}

.header {
  padding: 10px;
  width: 100%;
  background: #eee;
  position: fixed;
  top: 0;
  left: 0;
}

.content {
  margin-top: 50px;
}

  Search:
  <input type="search" placeholder="Lorem">
  <button data-search="search">Search</button>
  <button data-search="next">↓</button>
  <button data-search="prev">↑</button>
  <button data-search="clear">✖</button>

    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis eu ullamcorper orci, eget porttitor justo. Aliquam id sollicitudin elit. Nulla in sodales ipsum. Donec vulputate venenatis magna. Vestibulum sit amet leo lacinia, cursus lectus in, gravida
    metus. In ultricies sed tortor non pellentesque. Mauris quis tempor neque. Donec nec sagittis magna. Integer fringilla posuere metus eu mollis. Ut ac porta metus. Duis sed lacinia metus. Nunc malesuada iaculis risus vitae bibendum.

    Vivamus posuere condimentum leo eu hendrerit. Pellentesque placerat iaculis ante a rhoncus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum eu ipsum ac magna congue congue sed maximus tortor. Vivamus id odio elementum, vehicula nunc
    ut, efficitur felis. Nullam hendrerit velit libero, gravida porttitor tortor ullamcorper eu. Ut ut lectus non enim sagittis aliquam quis in orci. Donec a arcu eu eros cursus cursus. Donec dictum dignissim tellus, dictum egestas purus pellentesque
    sed.

    Vestibulum eu ornare urna, nec aliquam lectus. Phasellus eu odio sapien. Vestibulum eu turpis at lorem sagittis posuere. Quisque tellus nunc, facilisis id lacus nec, ornare rhoncus elit. Vivamus vehicula eros a condimentum venenatis. Sed orci massa, pulvinar
    sed erat nec, pellentesque suscipit leo. Mauris lobortis tincidunt nunc, sed tempus ex congue vitae. Curabitur lobortis mauris in ex malesuada, quis vehicula neque lobortis. Curabitur aliquam porttitor tellus eget tempus. Donec maximus tempus tristique.
    Aliquam tincidunt odio dictum, scelerisque ipsum ut, facilisis quam. Ut nec malesuada neque.

    Proin felis eros, tincidunt vitae scelerisque sit amet, dictum nec ante. Praesent tincidunt ac lacus nec elementum. Vivamus sed gravida purus, sed efficitur tortor. Nulla non molestie arcu. Sed tincidunt consectetur ligula sed lobortis. In non sapien
    ac urna lacinia placerat sed nec lacus. Aenean lobortis tincidunt sapien a hendrerit. Quisque eu turpis accumsan nisl blandit efficitur.

    Nam sit amet pellentesque est. Sed ligula turpis, ultricies sit amet mattis elementum, tristique non risus. Phasellus at congue ex. Proin nisi leo, vestibulum vitae accumsan in, imperdiet id dolor. Quisque at blandit nisl. Class aptent taciti sociosqu
    ad litora torquent per conubia nostra, per inceptos himenaeos. Nunc eget metus augue. Morbi faucibus venenatis sapien, fermentum porttitor felis pharetra a. Nam interdum nibh tortor, quis maximus turpis blandit eget. Praesent in feugiat neque, sed
    vulputate quam. Curabitur erat quam, efficitur et congue quis, iaculis euismod libero. Quisque odio sapien, efficitur non mauris ac, tincidunt condimentum turpis.

    Maecenas dapibus aliquam vehicula. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Praesent convallis viverra leo quis porta. Sed sit amet porttitor quam. Fusce nec risus non augue consectetur ultricies. Aliquam
    elit lorem, tincidunt ac dolor vel, vulputate consectetur ex. In hac habitasse platea dictumst. Sed eget nisl aliquam, cursus odio nec, commodo lorem. Nulla mollis tortor eu odio rutrum vulputate. Donec condimentum molestie mauris, nec sodales nisi
    volutpat aliquam. Nulla mollis libero sed nibh volutpat, ac mollis elit tincidunt. Vestibulum cursus velit vitae felis aliquam ultricies. Donec vehicula dictum feugiat. Vestibulum volutpat sollicitudin sagittis.

    Aliquam consequat, diam eu ullamcorper porta, diam eros rhoncus turpis, in rutrum sem diam a risus. Duis lacinia velit sed ante feugiat venenatis. Aenean orci leo, dictum non finibus nec, dignissim quis eros. Nullam sit amet orci ac purus blandit commodo
    sit amet eget neque. Sed pellentesque dictum tortor. Ut dui erat, tempus in odio in, aliquet convallis mi. Morbi efficitur justo ante, quis ultricies turpis suscipit ac. Sed sit amet nisl rutrum, laoreet mauris id, ullamcorper orci. In facilisis nisi
    eget fringilla imperdiet. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Morbi ut ultricies dui. Pellentesque elit urna, imperdiet sed congue eget, hendrerit sed urna.

    Proin vel hendrerit nulla. Vivamus vehicula nibh nec lorem blandit, quis aliquam ipsum suscipit. Nulla at vestibulum felis. Aenean ac nibh eget enim molestie pulvinar. Duis nulla justo, tristique id nulla nec, faucibus imperdiet arcu. In vel pretium dui,
    at lobortis sapien. Phasellus ullamcorper id enim eget dictum. Ut imperdiet rutrum est a rutrum. Curabitur eget dignissim tellus. Fusce tempus leo nisl, vitae auctor diam feugiat sit amet. Vestibulum accumsan justo eget odio imperdiet, consectetur
    efficitur ex dapibus.

    Sed pharetra odio a nibh pharetra rutrum. Suspendisse ut ullamcorper lectus. Donec ipsum mauris, congue et lobortis sit amet, ultricies ac tellus. Sed nisi risus, condimentum at varius quis, condimentum ac velit. In condimentum, magna sed ornare eleifend,
    dolor nulla mollis felis, quis feugiat elit turpis non ipsum. Etiam aliquam est imperdiet dolor rutrum, at varius leo sodales. Morbi quis iaculis metus.

    Maecenas auctor nec ligula ac luctus. Nam sit amet euismod mauris. Donec et diam sit amet eros efficitur tempor. Mauris non erat sit amet nunc interdum pulvinar. Sed luctus hendrerit justo eget pulvinar. Cras non arcu sed ligula faucibus pulvinar. Sed
    egestas risus nisl. Duis quis arcu tempus, cursus erat ac, gravida enim. Cras et condimentum ante. Nullam eleifend egestas velit, quis semper est imperdiet non. Donec quis purus varius, placerat mi et, dictum lorem. Sed quis finibus nisi, vitae molestie
    metus. Donec lobortis eros quis vestibulum vulputate.

Pesquisar apenas se clicar no botão


Windows phone 7 grouped list

Question: I am new to silverlight and windows phone 7 development and am having some trouble working out the best way to do a "grouped list".
Essentially what I would like to do is group a list of event details by date into something like this:

Monday 5/6/10
 event 1
 event 2
Tuesday 6/6/10
 event 3

I tried using nested listboxes which work to certain extent but killed the scrolling. Is that the best way to do grouping (assuming I can fix the scrolling issue) or is there some other method?
Answer: What about using nested ItemsControls and templates?
Answer: You may find the scrolling issue with nested listboxes is due to your nested listboxes being of a variable height. Try making them a fixed height or containing them in a wrapping element with a fixed height for now. This is a known issue with the current ctp effecting listboxes with contents of variable height.
Answer: I would recommend the LongListSelector control from this toolkit
http://silverlight.codeplex.com/releases/view/75888
That's what I used in the past. You can set a template for the header and one for an item. You can also set a template for when you tap a group

Windows phone 7 grouped list


Return undefined value in jQuery ajax call with promise

Question: I have tried many times with jQuery ajax call but it return value before updating it. i have googled it and tried lots of solutions no one work for me, i always get undefined value because function return value before ajax call complete. any help would be appreciate,
here is my code
$(document).ready(function() {
  console.log(secondvalidation());
});

function onemorevalid() {
  console.log("working");
  //this ajax call return 1
  return jQuery.ajax({
    url: 'handler/email.php',
    method: 'POST',
  });

}

function secondvalidation() {
  onemorevalid1 = new onemorevalid();
  onemorevalid1.done(function(data) {
    console.log("data " + data);
    return data;
  });
}

output on console is
working
undefined
data 1

Answer: You're making an object out of a method. Which is wrong fundamentally. Also if you need to pass the value of an ajax call to code called afterwards, you can add async:false to you query so that the code will wait for the ajax response.
Just make sure that you call the other_function() after the ajax method gets called in document ready function.
So I think what you need is this:
$(document).ready(function(){
var requested_data;

        var request = $.ajax({
      url:'handler/email.php',
          method:'POST',
          async:false,
          dataType: 'text'
    });

    request.done(function(data) {
       console.log("data " + data);
 requested_data = data
    });

 function other_function(){
console.log("toing_toing: " + requested_data);
}
other_function();
   });

here's a working example fiddle of this code.
Please note that there are other ways to achieve this as per this answer. async:false may cause your script to freeze till the request is complete, and thus if the request took a long time that would give a bad UI experience.
Comment: How i can use this returned data in another function
Comment: Thanks @toing_toing,  your answer useful but as you are using "async:false"; it is deprecated, can we do something like your answer  without using "async:false";
Comment: @Ganesh you should have a look at the linked answer. There are many other ways mentioned in that.


Understanding the definition of the direct sum of subspaces of a vector space

Question: I have a question regarding the definition of direct sum of a vector space in relation to subspaces.

Definition: A vector space $V$ is called the direct sum of $W_1$ and $W_2$ if $W_1$ and $W_2$ are subspaces of $V$ such that $W_1\cap W_2 = \{0\}$ and $W_1 + W_2 = V$. We denote that $V$ is the direct sum of $W_1$ and $W_2$ by writing $V = W_1\oplus W_2$.

Is this definition saying that any vector in $V$ can be written as a linear combination of the vectors in the set $W_1 + W_2$?
Thanks!
Answer: The definition is saying that any vector $v \in V$ can be written as $v = w_1 + w_2$ where $w_1 \in W_1$ and $w_2 \in W_2$ (this is the condition $W_1 + W_2 = V$), and this decomposition is unique (this follows from the condition $W_1\cap W_2 = \{0\}$). You don't need to take linear combinations.
Comment: Right, the key word missing from the OPs statement is "unique".  Of course what the OP says is true, it does mean any vector can be written as a combination like that.  But it's not equivalent to that without specifying "unique".
Answer:
$W_1\cap W_2=\{0\}$ if and only if
\begin{align}
\phi\colon W_1\times W_2&\to V\\
(v,w)&\mapsto v+w
\end{align}
is injective and
$V=W_1+W_2$ if and only if $\phi$ is surjective.

In summary:
\begin{equation}
V=W_1\oplus W_2\Leftrightarrow \phi\text{ is a vector space isomorphism.}
\end{equation}
In other words: $V=W_1\oplus W_2$ if and only if for all $v\in V$, there is exactly one $(w_1,w_2)\in W_1\times W_2$ such that $v=w_1+w_2$.
Proof of 1.:
(Reminder: If $W_1$ and $W_2$ are vector subspaces of $V$, $W_1\cap W_2$ is also a vector subspace of $V$.)

If $v\in W_1\cap W_2$, $\phi(v,0)=v+0=v=0+v=\phi(0,v)$. $\Rightarrow v=0$ if $\phi$ is injective.
Conversely, if $W_1\cap W_2=\{0\}$ and $(v,w),(v',w')\in W_1\times W_2$, then
\begin{equation}
\phi(v,w)=\phi(v',w')\Leftrightarrow v+w=v'+w'\Leftrightarrow v-v'=w'-w=:u.
\end{equation}
Since $v-v'\in W_1$ and $w'-w\in W_2$, $u\in W_1\cap W_2=\{0\}$. Thus, $v=v'$ and $w=w'$.


Characterizing non-constant entire functions with modulus $1$ on the unit circle

Question:
Is there a characterization of the nonconstant entire functions $f$ that satisfy $|f(z)|=1$ for all $|z|=1$?

Clearly, $f(z)=z^n$ works for all $n$. Also, it's not difficult to show that if $f$ is such an entire function, then $f$ must vanish somewhere inside the unit disk. What else can be said about those functions?
Thank you.
Answer: The only such functions are $f(z)=az^n$ with $|a|=1$.
Let $f$ be such a function and define
$$g(z)=\overline{f(\overline{z}^{-1})}^{-1}.$$
Due to the two complex conjugations, $g$ is meromorphic
on $\mathbb{C}-\{0\}$. Also $g(z)=f(z)$ when $|z|=1$.
By analytic continuation, $f(z)=g(z)$ for all nonzero $z$.
Now $g$ has a pole of order $k$ at $\infty$ where $k$
is the order of $f$ at zero. Hence $f$ is a polynomial of degree $k$.
As $k$ is also the order at $0$ then $f(z)=az^k$; clearly
$|a|=1$.
Comment: This must be from the Book.
Comment: Pierre-Yves, $f$ is entire, since that is the hypothesis!
Comment: I think You implicitly assumed that $f(z) = 0\iff z = 0$ ($g$ has a pole in $\bar{a}^{-1}$ if $f(a) = 0$), but in this case the claim follows almost immediately from maximum modulus principle.
Comment: Pierre-Yves, an entire function with a pole (i.e., not an
essential singularity) at $\infty$ s a polynomial.
Comment: I deleted my previous question by mistake. It was: why is f a polynomial? Thanks for your answer, but now I don't understand why f is entire. (The function g is meremorphic, not holomorphic.)
Comment: Pierre-Yves, $f=g$.
Comment: Sorry to insist. You wrote: "g is meromorphic on $\mathbb{C}-\{0\}$". (I agree that f and g define together a function which is meromorphic on the Riemann sphere.)
Comment: You're right! I didn't read the question carefully enough... I can only apologize for the trouble, and thank you for your patience and kindness.
Answer: If a function $f$ is holomorphic in a neighborhood of the closed disk and has modulus 1 on the circle, then $f$ is a finite Blaschke product.  You can prove this by taking all of the zeros inside the disk counted according to multiplicity, dividing by corresponding holomorphic automorphisms of the disk that have those zeros, and showing that the result is constant.  (This quotient and its reciprocal are analytic and bounded by 1 on the disk...)  Thus, your $f$ is a finite Blaschke product, but it also has no poles in the plane.  The only such functions are constant multiples of power functions, as ifk already said.
Comment: Nice answer. In fact, my proof was (again) flawed, but one can modify it to give alternative proof of this formula with finite Blaschke product.
Comment: Nice, the solution is easy once you use Blaschke products!
Answer: Partial answer.
If $|f(z)|=1$ for all $|z|=1$ and $f$ is entire function, then $f:\mathbb D \to \mathbb D$, by the Maximum Modulus Theorem.
Using Schwarz-Lemma we can characterize, at least, the conformal ones.
( See Functions of one Complex Variable, Conway 2ed pag. 131 )
Answer: Edit: How frustrating, this is still not correct. It is not hard to make this proof work by generalizing to the functions holomorphic on unit disc and continuous on its closure, but such approach will be nothing else than proving the theorem cited by Jonas Meyer (see his answer).
Second attempt:

Note that $f$ has finitely many zeros in $\mathbb{D}$ (identity principle + compactness).
Observe that if $F\in \mathcal{O}(\mathbb{D})\cap \mathcal{C}(\bar{\mathbb{D}}),$ the only zero of $F$ is in zero, and $|F|$ is constant on unit circle, then $F(z) = e^{it}z^{k}$ where $k = ord_{0}F$.
(apply the maximum principle for $F(z)/z^{k}$ and $z^{k}/F(z)$)
Let $z_{1},\ldots, z_{n}$ be all pairwise distinct zeros of $f$ in $\mathbb{D}$. By induction on $n$ we will show that $n = 1$ and  $z_{1} = 0$.

Let $n = 1$.
We are taking $h \in Aut(\mathbb{D})$ s.t. $h(0) = z_{1}$ and $g:= f\circ h\in \mathcal{O}(\mathbb{D})\cap \mathcal{C}(\bar{\mathbb{D}})$.
Then $|g|$ is constant on unit circle, $0$ is the only zero of $g$ in $\mathbb{D}$. So $g(z) = e^{it}z^{k}$.
Therefore $f(z) = e^{it}\cdot \left(\frac{z - z_{1}}{1 - \bar{z_{1}}z}\right)^{k}$ in $\mathbb{D}$.
From identity principle for meromorphic functions this equality holds in $\mathbb{C}$, and gives contradiction unless $z_{1} = 0$ (otherwise $f$ is not entire).
If $n > 1$, then we're reasoning by contradiction.
W.l.o.g. $z_{n}\neq 0$.
We are taking $h \in Aut(\mathbb{D})$ s.t. $h(0) = z_{n}$ and $g:= f\circ h\in \mathcal{O}(\mathbb{D})\cap \mathcal{C}(\bar{\mathbb{D}})$, and then $h^{-1}(z_{1}),\ldots, h^{-1}(z_{n-1}), 0$ are the all zeros of $g$ in $\mathbb{D}$.
Let $k = ord_{0}g$, and $G(z) = g(z)/z^{k}\in \mathcal{O}(\mathbb{D})\cap \mathcal{C}(\bar{\mathbb{D}})$.
$G$ has $n-1$ zeros on $\mathbb{D}$, $|G(z)| = 1$ on unit circle, thus from inductive assumption $n-1 = 1$ or $G$ is constant (we cannot use inductive assumption since in general $G\not\in \mathcal{O}(\mathbb{C})$!).
If $G$ is non-constant then $n-1 = 1$ and $G(z) = e^{it}z^{l}, \ l > 0$ - a contradiction with $ord_{0}g = k$. Otherwise $n - 1 = 0$ - a contradiction.
Finally 1. and 3. proves that all entire functions with desired property are of the form $f(z) = e^{it}z^{k}$.
The following reasoning is not correct (see the Malik Younsi's answer):
This should be the comment to the Leandro's answer, although I cannot add comments yet.
W.l.o.g. $f$ is non-constant. Then by maximum modulus $f$ has zero inside $\mathbb{D}$.
Denote this zero by $a$.
Composing $f$ with an automorphism $h$ of disc s.t. $h(0) = a$ we obtain that $g = f\circ h$ satisfies $g(0)= 0$ and moreover $|g(z)|\le |z|^{k}$ inside $\mathbb{D}$, where $k$ is the order of zero of $g$ in $0$ (indeed $g(z)/z^{k}$ is entire and we may use the maximum modulus principle).
By Schwarz lemma there exists $\theta\in \mathbb{R}$ satisfying $g(z) = e^{i\theta}z^{k}$.
From classification of automorphisms of the disc, we have $h^{-1}(z) = e^{i\omega}\frac{z-a}{1-\bar{a}z}$ for some $\omega\in \mathbb{R}$, and from this the full classification easily follows.
Answer: For your $f$ we know there are no zeros on the boundary of the circle, and only a finite number of zeros inside. So you can form the Blaschke product $b$ for the non-zero zeros of $f$ inside the circle, and $f(z)/(z^{n}b(z))$ is non-vanishing and holomorphic on an open neighborhood of the closed unit disk for some natural number $n$, and has modulus $1$ on the unit circle. Of course, it may be that $f$ has no non-zero zeros inside the disk, in which case, define $b\equiv 1$.
So $\ln|f(z)/(z^{n}b(z))|$ is harmonic on an open neighborhood of the closed unit disk, and it vanishes on the unit circle. So this harmonic function is identically $0$, which means $|f(z)/(z^{n}b(z))|\equiv 1$ inside the disk. Now, by the maximum modulus principle for holomorphic functions, $f(z)=Cz^{n}b(z)$ for some unimodular constant $C$, and for all $|z| \le 1$. By the identity theorem, this must be true for all $z$ where $b(z)$ is finite, which means that the Blaschke factor $b$ must not be present in the factoring because $f$ is entire. Therefore, $f=Cz^{n}$ for some constant $C$ with $|C|=1$ and for some $n \ge 0$.


Como faço para uma string maior que o fgets dela não passe para o próximo fgets? (C)

Question: Gente, tenho essas duas entradas de string:
printf("Entre com a string: ");
fgets(str, sizeof(str), stdin);

printf("\nEntre com o caracter a ser procurado: ");
fgets(caracter, sizeof(caracter), stdin);

Acontece que se eu colocar uma string maior na primeira entrada, ela acaba sendo armazenada na segunda e meu programa buga. Tem alguma forma deu controlar isso e fazer com que a primeira entrada só armazene a quantidade que estipulei?
Comment: https://pt.stackoverflow.com/a/111702/112052
Answer: Este problema acontece pois o fgets vai ler todos os caracteres que você pedir menos um, pois o último sempre será um \0, então se você pediu para ele coletar apenas 10 caracteres porém digitar:
Input: abcdefghijklmno[enter]
Ele irá pegar para sua string apenas o abcdefghi\0.
Mas o problema acontece com o resto do input e o enter no final dele, pois ele acabou ficando apenas jogado no buffer do teclado (stdin) como um jklmno[enter] solto, então quando o programa achar a próxima entrada de dados que utilize o scanf, esse buffer já vai ser lido instantenamente e por já ter um enter já vai mandar esses dados para esse input
Porém como já apontado no link do hkotsubo nos comentários, uma solução bem simples muito comentada para balancear um problema gerado pela proteção de overflow do fgets, é usar o fflush(stdin); para limpar o buffer do teclado, que resolve esse problema de maneira simples, porém não é o ideal e muito menos o seguro, por isso muitas vezes você verá uma solução maior para resolver o problema de maneira mais segura que é o:
int c;
while ( (c = getchar()) != '\n' && c != EOF ) { }

Esse while basicamente vai consumir o seu buffer até achar o enter e o End Of File.
Ou até mesmo essa solução que não é portável para outros sistemas:
fseek(stdin, 0, SEEK_END);

Todas elas funcionam parcialmente para mitigar os problemas de entrada do teclado, se quiser ver mais para buscar uma solução mais segura, tambem linkado no tópico do comentário.
Comment: Não, no link que eu indiquei diz justamente o oposto: que usar `fflush(stdin)` é errado, por ser um comportamento indefinido.
Comment: Perdão, não deixei tão claro a importância dos outros métodos e o problema do fflush, imagino estar mais coeso agora


Definition of Messaging in MVVM Light

Question: I am trying to learn to use the MVVM Light Toolkit but i did not find a concrete definition of what is

"Messaging"

and the

"Messenger Class"

mvvm light - messaging
Someone asked this question but before reading the articles that are given in the answers can  anyone give a concrete definition of what  Messaging means in MVVM ?
Thank you !
Answer: There are some cases wich is not easy to make a property in the viewmodel and link it to the view. You need a class to bind any property from the code behind the WPF to the viewmodel.
In the following example, every time the user selects several rows from the grid (the view), the number of selected rows is passed to the viewmodel using the Messenger class:
//in the view
public MainWindow(){
    InitializeComponent();
    this.MyGrid.SelectionChanged += MyGrid_SelectionChanged;
}

void MyGrid_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
{
    Messenger.Default.Send<IList>(this.MyGrid.SelectedItems);
}

//in the viewmodel
private IList _numFilasSeleccionadas;

        public IList NumFilasSeleccionadas
        {
            get { return _numFilasSeleccionadas; }
            set
            {
                _numFilasSeleccionadas = value;
                RaisePropertyChanged("NumFilasSeleccionadas");
            }
        }

private void RegisterCommands()
        {
            Messenger.Default.Register<IList>(this, d => this.NumFilasSeleccionadas = d);
        }

Definition of Messaging in MVVM Light


Clustering visited vertex in a graph

Question: I would like to know can anyone introduce me an algorithm to cluster multiple sequence of visited vertices in a graph. For example assume your graph has 6 nodes.
following might be 3 different sequences:
<code>2 3 3 4
1 2 4 5 6
1 3 5 6 6 6
</code>
I am looking for to see how to cluster something like above. So two graph might be similar if they share the same nodes with similar ordering (not necessarily the same) .
Can anyone give an algorithm to do that. Has anything like this implemented in any package in R, Python or Matlab.
Answer: To cluster data samples you need to define a dissimilarity measure.
Depending on your choice which samples should be considered similiar - the dissimilarity measure should be chosen.
(a) If you give importance to the ordering of the nodes visited - then i suggest to look into "time series clustering"
In your case I recommend to use DTW as suggested in the answer to this    question: Suitable distance metric for time-series clustering with respect to location of shapes
(b) If you give importance only to "which nodes have been visited", then i suggest to encode the samples differently. For each sample, you create an array with the length of the number of all nodes in the network. Each position is a boolean (1 - true, 0 - false) which indicates whether or not this node has been visited.
2 3 3 4   - 0 1 1 1 0 0
1 2 4 5 6 - 1 1 0 1 1 1
1 3 5 6 6 6 - 1 0 1 0 1 1
Then finally you can choose an algorithm for clustering - which all have their pros and cons.
Comment: Thanks .I really appreciate it. when you code it a 0 or 1. then what do these sequence represent? are they distances ? because for all these clustering algorithms the rows are observations and the columns are the features. Therefore rows make sense but what about columns what do they represent?
Comment: Each column represents a node. For each observations (row) each has either been visited (1) or not (0). This is just an example for a possible encoding. One of the disadvantages of this specific encoding is that the order is nodes visited is neglected as well as the count of visits per node. (12345 = 51234 = 5511223344 === 1 1 1 1 1)
Comment: Does your DTW work if we revisit some vertices again suppose we have 1 2 2 2 and 1 2 1 1?

Clustering visited vertex in a graph


What's an intuitive way to explain the different types of validity?

Question: Specifically I'm thinking of a simplified division whereby validity is divided into:

Construct validity
1a. Convergent validity
1b. Discriminant validity
Criterion related validity
2a. Predictive validity
2b. Concurrent validity

This division leaves out some common concepts (e.g. face validity, other types of criterion validity), but it's for undergraduates taking their first course in statistics. I'm required to teach using this division.
I'm looking for examples, mnemonics, diagrams, and anything else that might help me explain the division in a memorable and intuitive way.
One thing I'm particularly struggling with is a clear way to explain the difference between concurrent validity and convergent validity, which in my experience are concepts that students often mix up.
Comment: One thing that people often misappreciate, in my own view, is that they think construct validity has no criterion. But any validity must have a criterion. Either external or internal. A construct is an internal criterion, and an item is being checked to correlate with that criterion, the latter must be therefore modeled. If one doesn't formulate the internal criterion as such self-contained entity the checking of correlations within the set of items will be an assessment of interitem homogeneity/interchangeability which is one of facets of reliability, not validity.
Comment: There's not going to be one correct answer that will be memorable and intuitive to you, I'm afraid.  But there are innumerable book chapters, articles, and websites on this topic.  Good luck.
Answer: Both convergent and concurrent validity evaluate the association, or correlation, between test scores and another variable which represents your target construct. Here is the difference:
Concurrent validity tests the ability of your test to predict a given behavior. For instance, verifying whether a physical activity questionnaire predicts the actual frequency with which someone goes to the gym. You could administer the test to people who exercise every day,  some days a week, and never, and check if the scores on the questionnaire differ between groups.
Convergent validity examines the correlation between your test and another validated instrument which is known to assess the construct of interest. In this case, you could verify whether scores on a new physical activity questionnaire correlate to scores on an existing physical activity questionnaire.
Here is an article which looked at both types of validity for a questionnaire, and can be used as an example: https://www.hindawi.com/journals/isrn/2013/529645/ [Godwin, M., Pike, A., Bethune, C., Kirby, A., & Pike, A. (2013). Concurrent and Convergent Validity of the Simple Lifestyle Indicator Questionnaire. ISRN Family Medicine, 2013, 1–6. https://doi.org/10.5402/2013/529645]
A book by Sherman et al. (2011) has a chapter which describes the types of validity you mention - which are also part of the 'tripartite model of validity.'  You may be able to find a copy here https://www.researchgate.net/publication/251169022_Reliability_and_Validity_in_Neuropsychology
The reference for the chapter is
 [Sherman, E. M. S., Brooks, B. L., Iverson, G. L., Slick, D. J., & Strauss, E. (2011). Reliability and Validity in Neuropsychology. In The Little Black Book of Neuropsychology (pp. 873–892). Springer US. https://doi.org/10.1007/978-0-387-76978-3_30]
Comment: please add full references for your links in case they die in the future


Can't move variable outside of function to be used

Question: I am really struggling with this. I have created a form which calculates what the person owes based on how many people in a tent and if they are paying by credit card. The amounts update depending on the selection. When the user submits they should be redirected to PayPal with the total amount on the end of the url, I.e:
PayPal.me/240 for £240 or PayPal.me/600 for £600
The issue is my price variable is outside of my other function which sets the redirect, and the price amount never makes it to the redirect.
This is what I have tried:
HTML:
    <select name='field_0' id='field_0' class='text_select' onchange="pricecalc()"   >
<option value="2 people" >2 people</option>
<option value="3 people" >3 people</option>
<option value="4 people" >4 people</option>
<option value="5 people" >5 people</option>
<option value="6 people" >6 people</option>
</select>

    <select name='field_1' id='field_1' class='text_select' onchange="pricecalc()"   >
<option value="Bank transfer" >Bank transfer</option>
<option value="Debit card" >Debit card</option>
<option value="Credit card + 3.4%" >Credit card + 3.4%</option>
</select>
Total Price
Hello World!
Price Each
Hello World!

Relevant JS:
var myprice;
function pricecalc() {
  var a = document.getElementById("field_0");
  var quantity = a.value.substring(0, 1);
  var b = document.getElementById("field_1");
  var type = b.value;

  if (quantity == '2') {
    var rate = '120';
  } else if (quantity == '3') {
    var rate = '110';
  } else {
    var rate = '100';
  }

  myprice = rate * quantity;
  if (type == 'Credit card + 3.4%') {
    myprice = myprice * 1.034;
  }

  var price_each = (myprice / quantity);
  document.getElementById("cost").innerHTML = myprice;
  document.getElementById("costeach").innerHTML = price_each;
}

function PHPFMG( formID ){
    var redirect = 'https://www.paypal.me/tim/' + myprice;

Comment: How/when is `PHPFMG()` called?
Comment: What is the value you get for var redirect in PHPFMG? Is it 'https://www.paypal.me/tim/undefined'?
Comment: @dsch yes it is undefined but it should be 240/500 etc
Comment: As Xatenev aksed, it best if we can see how and when PHPFMG is called.
Answer: I would recommend doing this instead
function pricecalc() {
  var myprice;
  var a = document.getElementById("field_0");
  var quantity = a.value.substring(0, 1);
  var b = document.getElementById("field_1");
  var type = b.value;

  if (quantity == '2') {
    var rate = '120';
  } else if (quantity == '3') {
    var rate = '110';
  } else {
    var rate = '100';
  }

  myprice = rate * quantity;
  if (type == 'Credit card + 3.4%') {
    myprice = myprice * 1.034;
  }

  var price_each = (myprice / quantity);
  document.getElementById("cost").innerHTML = myprice;
  document.getElementById("costeach").innerHTML = price_each;

  return myprice;
}

Then
function PHPFMG( formID ){
    var myprice = pricecalc();
    var redirect = 'https://www.paypal.me/tim/' + myprice;
}

This way you don't polute the global scope


Adding metrics to existing model in Keras

Question: I have an existing model and would like to add additional metrics to it. The Keras metrics page says the metrics are added at compile time, but I would like to add them after loading (in part because model.load_model() only seems to load the first metric, and because I have new metrics I would like to try on existing model first). Is that possible?
Comment: You can compile a model as many times as you want. That will not change it's weights. So you can load model and then compile model with metrics.
Comment: Thanks, didn't know that! Care to make an answer out of it so I can accept it?
Answer: You can compile a model as many times as you want. That will not change its weights.
So you can load the model and then compile it with metrics.
The only possible problem of recompiling the model is possibly resetting the optimizer state.
Comment: When you say "possibly resetting...", do you mean that you are not sure about it or that it only happens in some circumstances?
Comment: I'm not sure about it.
Answer: Just adding this gist for quick and easy copy/paste answer for your convenience:
from keras.models import load_model

model_path = 'path/to/your/old_model.h5'
new_metrics = [<metrics to add>...]  # for example ['binary_accuracy']

model = load_model(model_path)
model.compile(optimizer=model.optimizer,
                        loss=model.loss,
                        metrics=model.metrics+new_metrics)

Make sure to add needed parameters to the compile function if used any other than the above case.
Comment: This would'nt work in many cases, since metrics have to be in a dictionary to define in Multi-Task output which metric is applied.


How to efficiently remove elements from series of pandas dataframe

Question: I have a pandas dataframe of the following structure:
   Col1   |           Col2      |     Col3
   -------+---------------------+--------------
0   6     |    [a,b,c,d,e,f]    |     ....
1   4     |    [a,g,h,i]        |     ....
2   5     |    [a,b,j,k,l]      |     ....

I have a list of elements that I have to remove from all the lists in Col2 [a,b,h]
Finally I need to translate it to
   Col1   |           Col2  |     Col3
   -------+-----------------+--------------
0   4     |    [c,d,e,f]    |     ....
1   2     |    [g,i]        |     ....
2   3     |    [j,k,l]      |     ....

Where Col1 is the count of elements in Col2
I tried
def modify_data(dataset):
    ds = dataset.copy()
    Col2 = dataset['Col2']
    remove_list = [a,b,h]
    removed_col2 = []
    counts = []
    for i,row in enumerate(Col2):
        cleaned = np.array(list(set(row)-set(remove_list)))
        removed_col2.append(cleaned)
        counts.append(len(cleaned))

    ds.loc[:,'Col1'] = counts
    ds.loc[:,'Col2'] = removed_col2
    return ds

But the performance is too bad.  For example for a dataset with 200,000 rows.
CPU times: user 11min 26s, sys: 24.2 s, total: 11min 50s
Wall time: 11min 48s

Answer: I will try with
df.Col2 = (df.Col2.map(set)-set(['a','b','h'])).map(list)
df.Col1 = df.Col2.str.len()
df
Out[111]:
           Col2  Col1
0  [f, e, c, d]     4
1        [g, i]     2
2     [j, k, l]     3

Comment: @TrentonMcKinney for the timing we should do df.Col2.map(len)
Comment: Which is better `df.Col2.str.len()` or `df.Col2.map(len)`?
Comment: For 3M rows of lists, `df.Col2.map(len)` is faster by 109ms.
Answer: Another solution, using list comprehension :
df = pd.DataFrame(
    {
        "col1": [6, 4, 3],
        "col2": [
            ["a", "b", "c", "d", "e", "f"],
            ["a", "g", "h", "i"],
            ["a", "b", "j", "k", "l"],
        ],
    }
)

df['col2'] = [[value for value in entry
               if value not in ('a','b','h')]
              for entry in df.col2
             ]
df['col1'] = df.col2.str.len()

   col1     col2
0   4   [c, d, e, f]
1   2   [g, i]
2   3   [j, k, l]


Making simultaneous parallel calls to repository methods in ASP.NET API

Question: In my ASP.NET Core API, I need to make 3 separate calls to 3 different repositories in order to collect all the data I need to make decisions.
I want to shave off all the time I can in order to speed things up. Is there any difference in terms of time it will take for all 3 call to complete using the regular or a parallel invoke approach?
The regular way would be:
var customer = await _customersRepository.GetCustomer(customerId);

var balance = await _salesRepository.GetCustomerBalance(customerId);

var product = await _productsRepository.GetProduct(productId);

I haven't used the parallel approach before but I think it goes something like this:
Customer customer;
Balance balance;
Product product;

Parallel.Invoke(
   () =>
   {
      customer = await _customerRepository.GetCustomer(customerId);
   },
   () =>
   {
      balance = await _salesRepository.GetCustomerBalance(customerId);
   },
   () =>
   {
      product = await _productRepository.GetProduct(productid);
   });

Again, my main concern is to complete all three repository/database calls as quickly as I can so that I have all the data I need to make a decision. With that said:

Is there any benefit to running parallel tasks to save time?
Are there any other benefits or concerns to using the parallel invoke approach?
Answer: Depending on the time that the repository actions take it can be beneficial to execute them in parallel. However the DbContext is not thread-safe so be sure to retrieve a separate instance for each execution (assuming they read from a DbContext). Also take a look at this thread for more information regarding parallel execution with EF Core: What is the best practice in EF Core for using parallel async calls with an Injected DbContext?
Answer: It's far better if you can construct a single query to the database retrieving all your data at once.
But if you must do multiple concurrent database calls, you can do so using Task.WhenAll (note: not Parallel). You would have to ensure that your repositories use different database contexts, since EF contexts do not support concurrency:
var customerTask = _customersRepository.GetCustomer(customerId);
var balanceTask = _salesRepository.GetCustomerBalance(customerId);
var productTask = _productsRepository.GetProduct(productId);

await Task.WhenAll(customerTask, balanceTask, productTask);

var customer = await customerTask;
var balance = await balanceTask;
var product = await productTask;

Comment: Thank you! In my case, I'm actually calling different databases i.e. Azure Cosmos DB and Azure Table Storage.


For which values of $p$ does the serie $\sum\limits_{n=2}^\infty\frac{1}{n^p\ln(n)}$ converge?

Question: For which values of $p$ does the serie $\sum\limits_{n=2}^\infty\frac{1}{n^p\ln(p)}$ converge? I'm trying to use the ratio test but I can't get a simple term in which use limit easily enough.
Comment: Do you mean $\ln(n)$? If so, a place to start is to prove that if $\varepsilon > 0$ then $\lim_{n \to \infty} \frac{n^p \ln(n)}{n^{p+\varepsilon}} = 0$. Apply that for $p<1$. Use direct comparison for $p>1$. Then you have to do something else for $p=1$.
Comment: @Ian sure, thanks. Let me try to use that.
Answer: As noted in a comment, you can settle the case for any $p \neq 1$ using comparison tests combined with the fact that the harmonic series diverges, and $\sum 1/n^p$ converges for $p > 1$. For $p = 1$, either use an integral comparison test, or if you note that $\ln n = (\log_2 n) / (\log_2 e)$ then you can work with the series $\sum_n 1/n \log_2 n$ and use the Cauchy condensation test to determine convergence.


Question and Answers setup

Question: Trying to figure how to setup drupal 8 to function like StackExchange.
My goal is to be able to allow users to mark answers helpful so that best answers get moved to the top. Similar to StackExchange.
I can think of two ways to do this but would like some feedback from the experts.
Option 1: Create content Question and add comments to it. Use flag module to flag helpful replies. Create a template for question comments so that each top replies + its replies are groped together.
Option 2: Create Question, Create comment type Answer, Create a new comment type called replies and attach it to comment type Answer.
Or is there another alternative that I am not thinking off?
What would be the best way to create a similar setup such as StackExchange?
Comment: 'Best' is a very vague term. Can you elaborate on what you mean? Performance, themeability, something else? Also option 2 appears to be an extension to option 1. I think you should not choose on what we think is best (question might get closed for being to opininated), you should choose on what your users need. Do you/they need comments on answers or not?
Comment: Users need to comment in the answers. Basically, I am trying to setup similar functionality as StackExchange instead of setting up a forum thread style or a long string of comments.
Comment: @Umair merci for the update. About Quiz module: that's like saying that questions (+ answers) on drupal.SE are quizes also, no? If you're looking for D7 based "inspiration" (the kind of functionality to consider), have a look at the [Answers](https://www.drupal.org/project/answers) module ... all that's needed is a patch to upgrade it to D8 ...
Comment: @Pierre.Vriens and that patch can only be done by a person who knows how to that
Comment: I am also looking for such functionality but there is no module for D8.
Comment: @Umair (bonjour!) why not use D7 instead?
Comment: @Pierre.Vriens Past few months I have been working on D7, but then I found out open social distribution D8. Only 2 things are missing. Hashtags and Q&A functionality. Both are not available for D8. For me hashtags is more important. #word in a textarea will be converted to a linked hashtag to taxonomy. I can create a filter using mentions module, but in order it to work, the tag must be already available in the list of taxonomy terms. This is not the case here. When a user writes #word, he is either creating a new term or using existing one.
Comment: @Pierre.Vriens  Regarding Q&A, I just found version 8 of [Quiz module](https://github.com/mradcliffe/quiz.git). Haven't tested it yet. Not sure if this is what I am looking for
Comment: @Umair that's true, but isn't that the case for about anything in Drupal? To build some list of something in a Drupal site, often it's just a matter of using the [Views](https://www.drupal.org/project/views) module ... ***by a person who knows how to do that*** ...
Answer: Your Option 1 and Option 2 seem to both implement "answers" as comments...
Another option (= Option 3) would be to implement Answers as another content type, combined with an entity reference field (multiple values allowed) added to your Questions content type.
By using a content type for both Questions and Answers, it would probaby simplify anything about voting (either Question or Answers), and you could also use the Flag module (e.g. to mark "an" answer as the "accepted" answer).
At this time it's too early (= not ready for D8 yet) for some typical other modules that could be added to this later on:

the Rules module, to implement whatever logic you'd want (eg: only question authors can flag one, and only one. answer with the fag to mark an answer as accepted.
the Userpoints module, to implement your reputation system.

PS: you probaby have a good reason why it has to be implemented in D8, but if D7 would be "good enough" (at least for now), you could implement something similar to this Option 3 by using what is explained in this answer to "How to implement a reputation based system with badges in Drupal similar to StackExchange sites?".
Comment: Thank you for the suggestion. I was wondering if option three was possible as well. I think that would be the best way to go. If I understand you suggestion correctly. I create a content type Answers. Then add that as a field to Questions content type, add it as Reference Type > Content. Select multiple values. Here is what I am not clear about. Do I need to check allow reference if the entity does not exist? Or is there another way?
Comment: @Progonat it seems that your understanding, as in your comment here is indeed correct. However, I'm not sure what to answer to your "*Do I need to check allow reference if the entity does not exist?*". Maybe you want to try to rephrase that by indicating what the "entity" actually would be (I think you mean "answer", but not sure. Also, why the setup/config of 2 content types (+ reference to multiple answers) you would have implemented a data moduel that I'd recommend. But know that you'll have to think of a UI to allow "new answers" only if linked to its related question (to avoid orphans).
Comment: Since comments are full entities in Drupal 8, there is no benefit of using a content type over a comment type.. You should be able to attach a flag to a comment just as good as you can attach it to a node. By choosing content types you invoke a lot more access checks and risk creating orphans. Besides you need modules like [rabbit hole](https://www.drupal.org/project/rabbit_hole) to prevent users from viewing the individual answers by their dedicated node id's. I would recommend to use comments.
Comment: @Neograph734 DankJeWel (oeps: merci) for your comment. I agree that comments in D8 have a lot of improvements. Though "my" perception is that using another content type for "answers" (instead of comments as you suggested) simplifies things, at least for the [Answers](https://www.drupal.org/project/answers) module. It may seem easy at first, but trust me, things can get pretty complicated.. The "questions" module does use such "comments"-approach for answers though. About the rabbit hole: have a look at what happens if you try to access [this "answer"](http://drupal.placeto.be/node/52) ...
Comment: @Pierre.Vriens, you will not get the demonstrated behavior by just using nodes and references ;-). (And rabbit hole certainly is not the only solution.) But there is no use in fighting over what would be the best solution, I just wanted to leave my thoughts on the matter.
Comment: @Neograph734 I appreciate your thoughts on this! Though I've a problem in makiing sure I correctly interprete your last comment. Maybe you want to retry/clarifiy a bit?
Comment: @Pierre.Vriens That I do not want a trigger a discussion ;) Or did you mean the demonstrated behavior part? You suggested to use references and nodes, but by only using references and nodes you will not be able to redirect the nid of an answer to the question page, as could be seen in your link.
Comment: I have decided to use a custom comment type instead of a new node for the answers. Comments can be customized almost as much as nodes. With very few limitations. Comments are good for what I need it to do and it is very easy and simple to setup.

Question and Answers setup


How can I change which AD account an Exchange mailbox is connected to without deleting the account?

Question: I would like to move an Exchange 2010 mailbox from mydomain\userAccount1 to mydomain\userAccount2 without deleting userAccount1.
I have seen numerous articles online that talk about how to do this after userAccount1 is deleted but none that provide steps to move a mailbox with all its e-mail, active sync relationships, and other metadata over to a different active directory user account.
How can I move a mailbox from mydomain\userAccount1 to mydomain\userAccount2 without deleting userAccount1?
Answer: You may try to performs these steps:

removing Exchange attributes for userAccount1 using the Disable-Mailbox cmdlet
running Clean-MailboxDatabase
reconnecting the mailbox to userAccount2 using the Connect-Mailbox cmdlet

Hope this helps.
Answer: This is the closest i could find.  I am not sure that it will be what you're looking for, but it might be able to help.
http://technet.microsoft.com/en-us/library/dd298174.aspx
Answer: Maxwells answer dated 2012/05/02 @ 14:09 is correct.
Quoted directly from the 'Disable-Mailbox' online link:

The Disable-Mailbox cmdlet removes the mailbox's Exchange attributes from Active Directory. The mailbox isn't deleted and can be reconnected to its user at a later date by using the Connect-Mailbox cmdlet.


Proof of inequalities using binomial theorem

Question:
How do they achieve $$1+1+\frac{1}{2}\left(1-\frac{1}{n}\right)?$$ If I consider the first three terms of the binomial expansion, I get the first two terms, but can't factor the third to match this.
Answer: \begin{align}
& \frac{n(n-1)}{2}\left(\frac1n\right)^2 \\
=& \frac{n(n-1)}{2} \; \frac1{n^2} \\
=& \frac12\;\frac{n-1}{n} \\
=& \frac{1}{2}\left(1-\frac{1}{n}\right)
\end{align}
Answer: $(1+x)^n = 1 + n x + \frac {n(n-1)}{2} x^2 + \cdots$
All the terms in the "$\cdots$" are positive if $x$ is positive.
If $n \ge 2$
$(1+x)^n \ge 1 + n x + \frac {n(n-1)}{2} x^2 $
$(1+\frac {1}{n})^n$ replace $x$ above with $\frac 1n$
$(1+\frac 1n)^n \ge 1 + n \frac 1n + \frac {n(n-1)}{2} (\frac 1n)^2 $
and distribute
$(1+\frac 1n)^n \ge 1 + 1 + \frac {n^2-n}{2n^2} = 2+\frac {n-1}{2n} = 2+\frac 12 - \frac {1}{2n} $


Issues with the Dorian mode

Question: In Dorian mode we have a flat 3rd. and a flat 7th. Does the flattening refer to changing a major to a minor or does it refer to lowering a note by one fret to make it a flat (as in sharp/flat). Peter E
Answer: The basic major scale is the datum point. Changes which make modes and minors are notated from those major notes.
So, saying C Dorian has a ♭3 it says E♭ rather than E♮, and ♭7 of B♭ instead of the 'standard' B.
Both notes, as it happens are majors changed to minors - M3>m3, M7>m7.
Moving any note down one fret on guitar essentially flattens it - although its new name may not reflect that.
Comment: Thank you for your reply, are you saying that E major note, and E major chord are both reduced to a minor, surely they are both different items and sound differently?
Comment: Theere is no such thing as an 'E major note'. There's an 'E natural', which is the 3rd in key C - and is E♮. E major chord (or E minr chord) has nothing to do with all of this.
Answer: "Flattening" a  note refers to lowering that note by a half step; the term isn't key-dependent. For example, E->Eb, F->E, F#->F, and F##->F# (though I can't think of a practical example); when flattening (also Eb->Ebb).
There is a bit of subtlety in this. Flattening or sharpening a note does not change the note name.  (Notational practice doesn't generally assume equal-temperament where Cb=B enharmonically. Lots of music notation practice tends to ignore enharmonic equivalence; B#, C, and Cb are assumed to be three different notes.)
The same thing applies to the term "sharpening";  notes are raised a half step.
Extra comment: some English idiolects prefer to use "flat" or "sharp" as a verb rather than "flatten" or "sharpen" so this may occur in one's reading. (I prefer the "en" form so as to make it clear that I'm using a verb. Sightreading is important in ordinary reading as well as in music.)
Comment: Second para. is confusing!
Answer: Yes, I think you understand it. The "flat" would be lowering a major to a minor interval. A bit more detail follows.
Dorian mode has a minor third and minor seventh above the tonic.
Whether sharps and flats are involved depends on the key signature and which tone is the tonic.
If you were in D dorian with a key signature of no sharps and flats, you would not use any flats to spell the third and seventh tones of the scale.
But, a lot of chord and scale notation uses a major chord or scale as a reference point. If you were in C major with a key signature of no sharps and flats and wanted to change the scale to C dorian, you would put flats on the third and seventh, the E and B.
When speaking generically about dorian mode, it better to use the interval name, like: dorian mode has a minor third above the tonic.
When the tones are spelled out, then use sharps and flats, like: the third above the tonic in C dorian is E flat.
You can also say lowered or raised rather than flat or sharp to avoid awkward thinks like a "sharp 5th" in E flat major (where the raised fifth will actually be spelled B natural!) Those lowerings and raisings are by half step (one fret on guitar.)
The common lingo will use "sharp" and "flat" regardless whether the actual spellings use sharps or flats. It's just a short hand naming, but it's confusing in the beginning. When you learn proper interval names and key signatures and such you will get used to it.

Issues with the Dorian mode


Using parameters in routes

Question: I am using the pathauto module to create url aliases for all user account url, so:
/user/[uid] will become /u/[user:account-name]-[user:uid]
which means:
/user/36 will become /u/john-smith-36
In my custom module, I have created a route to fire a controller when /u/john-smith-36/settoken?token=123456 url is accessed.
The controller will:

Fetch the account of the current logged in user.
Update the text field field_user_push_token with the query parameter value:
123456
Save the account of the current logged in user.
Redirect the user to the page: /thank-you

I am finding a difficulty on how to use parameters in route for the user account url !
save_push_token.routing
save_push_token.SavePushToken:
  path: '/{user}/settoken'
  defaults:
    _controller: '\Drupal\save_push_token\Controller\SavePushTokenController::SavePushToken'
  requirements:
    _permission: 'access content'

SavePushTokenController.php
<?php

namespace Drupal\save_push_token\Controller;

use Symfony\Component\HttpFoundation;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Session\AccountInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;

class SavePushTokenController extends ControllerBase {

  /**
   * Display the markup.
   *
   * @return array
   */
  public function SavePushToken(AccountInterface $user, Request $request) {

// Get token value from url.
    $request = Request::createFromGlobals();
    $userpushtoken = $request->query->get('token');

// Load the (current logged user) account.
// No need to load the user account because of {user}
    // $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());

// Set the (token).
    $user->set('field_user_push_token', $userpushtoken);

// Save the (current logged user) account.
    $user->save();

// Redirect to "/thank-you" page.
    return new RedirectResponse('/thank-you');

  }
}

But simply the controller is not fired when I access for example /u/john-smith-36/settoken?token=123456 url is accessed.
any help on how to properly use parameters in routes ?
Comment: Isn't this because a route can't start with a parameter?
Answer: I see two problems. First your routing file has the path set to:
path: '/{user}/settoken'

To do what you're describing I would expect to see:
path: '/u/{user}/settoken'

Second, are you opposed to using a second parameter in the URL instead of the Get Method variable? If not opposed you can add a second parameter that will handle the 'token' variable.
In your routing file you can set up the pareters like this:
path: '/u/{user}/settoken/{token}'

The url would then be (cleaner I think):
/u/john-smith-36/settoken/123456

Lastly, to access the parmeters in your controller you shouldn't need to access the Globals. The parameters get passed to your function directly. Use this as the function declaration to pick up the variables:
public function SavePushToken($user, $token)

Comment: P.S. The $user variable being passed in via the parameter won't be a user object, it'll just be a string. I see you using the user object, also with a variable named $user, to call a couple methods. Don't confuse the two and name one of them something else.
Comment: thank you for your point and I was doing exactly as your point but what really confused me is this documentation [here](https://www.drupal.org/docs/8/api/routing-system/parameters-in-routes/using-parameters-in-routes) which says: **There is nothing more to provide in the route for the parameter conversion to happen because user is the name of an entity type and it will get automatically converted into a user object. In the controller, define an argument on the controller method with the same name to get this user object passed in**
Comment: the problem was because of using **public function SavePushToken(AccountInterface $user, Request $request)** which i took from [here](https://www.drupal.org/docs/8/api/routing-system/parameters-in-routes/using-parameters-in-routes)... The right function use is to declare the variable within the function in this way: **public function SavePushToken($user, $token)** Thank you and answer accepted... God bless

Using parameters in routes


Multivariable chain rule - notation?

Question: Assume we have four functions $\in C^\infty$ from $\mathbb R^2 $ to $\mathbb R$, written as follows:
$$
x=x(u,v) , \quad u=u(r,s)
$$
$$
y=y(u,v) , \quad v=v(r,s)
$$
then, assuming the composition $x(u(r,s),v(r,s))$ is properly defined,
$$
\frac{\partial x}{\partial r} = \frac{\partial x}{\partial u} \frac{\partial u}{\partial r} + \frac{\partial x}{\partial v} \frac{\partial v}{\partial r}.
$$
But, in the particular case where $(r,s)=(x,y)$, we have that $\frac{\partial x}{\partial x} =1 $, but the right hand side gives us
$$
 \frac{\partial x}{\partial u} \frac{\partial u}{\partial x} + \frac{\partial x}{\partial v} \frac{\partial v}{\partial x}
$$
which equals 2?
What am I getting wrong here?
Does my misunderstanding follows from a notation error?
Thanks
Comment: Hint: try writing an example where your stated conditions hold, and try to see which one of your conclusions is correct (and why).
Answer: $\frac{\partial x}{\partial u} \frac{\partial u}{\partial x} + \frac{\partial x}{\partial v} \frac{\partial v}{\partial x}$ doesn't equal $2$. This is one of those instances where regarding differential notation as cancellable fractions leads you astray.

Multivariable chain rule - notation?


Stabilizer of the orthogonal group of the Minkowski form acting on the upper sheet of hyperboloid space

Question: I was studying this paper and on page 8 the author defines the orthogonal group associated to the Minkowski linear form in the usual way ( $A \in O(1,n) \Longleftrightarrow \langle Ax | Ay \rangle =  \langle x|y \rangle \ \forall x, y \in \mathbb{R}^{1,n}$, where $\mathbb{R}^{1,n}$ is $\mathbb{R}^{n+1}$ with the Minkowski linear form). $\mathbb{H}^n$ is defined as the $x :  \langle x | x \rangle  = -1$ and $x_0 > 0$.
The part that I can't prove is that the stabilizer of $\mathbb{H}^n$ is equal to the subset of $O(1,n)$ such that the first column belongs to $\mathbb{H}^n$. I did prove that if $A \in Stab_{O(1,n)} \ \mathbb{H}^n$ then $A_0$ must belong to $\mathbb{H}^n$, but the reverse is escaping me.
Answer: Intuitively speaking you have this: you know that any $A\in O(1,n)$ will map the point $x_0=(1,0,0,\dots,0)$ to an element of the two-sheeted hyperboloid. It could be the upper sheet or the lower sheet. With the extra condition of $A_{00}>0$ you know it will be mapped to the upper sheet. So one point from the upper sheet goes to a point on the upper sheet. From this you want to conclude that all points on the upper sheet stay on the upper sheet.
You will need some kind of continuity argument here. Something that says that if a point $x$ stays on the upper sheet, then a point $y$ close by will stay there, too. Assume this were not the case. Then you would have a continuous path from $x$ to $y$ made of points on the upper sheet, which gets mapped to something that lies partially on the upper sheet and partially on the lower sheet. This cannot be done without a discontinuity, and linear functions are continuous.
This is just a proof idea. You may need to flesh this out to make it rigorous enough for your formalism, but it should be enough to guide your approach.


Higman embedding theorem

Question: The Higman Embedding theorem says that any finitely generated recursively presented group can be embedded in a finitely presented group.
My question is if one can embed such a group as a normal subgroup into a finitely presented group?
Comment: Moved to MO

http://mathoverflow.net/questions/73076/higman-embedding-theorem
Comment: Mustafa: would you mind posting a short answer indicating that Mark Sapir answered your question on MO, so that this question can be considered closed? There are now two votes to close as "too localized" which I don't think it is.
Answer: This question was answered in Mo by Mark Sapir
https://mathoverflow.net/questions/73076/higman-embedding-theorem

Higman embedding theorem


Why $\frac{p(re^{2\pi is})/p(r)}{|p(re^{2\pi is})/p(r)|}$ defines a loop in the unit circle?

Question: Why can $$\frac{p(re^{2\pi is})/p(r)}{|p(re^{2\pi is})/p(r)|}$$
defines a loop in the unit circle $S^1\subset\mathbb{C}$ based at 1, where $s\in[0,1]$, $p(z)=z^n+a_1z^{n-1}+\ldots+a_n$ is a polynomial for $z\in\mathbb{C}$, $p(z)\neq0$ and $r\in\mathbb{R}$.
I understand the fact that dividing by the magnitude is rescaling it the unit size but what I struggle to grasp is why $p(re^{2\pi is})/p(r)$ is a circle? Is there any way to understand this parametrisation?
I know $re^{2\pi is}$ is parametrisation of a circle with radius $r$, but what does it actually say when we put in the points of the circle into the polynomial $p(z)$?
My other doubt is could $p(re^{2\pi is})/|p(re^{2\pi is})|$ also define a loop in the unit circle? What is the purpose of the $p(r)$ in the original formula?
Thanks for the help.
Answer: Let's call your function $f(s)$.  For it to be a loop, you just need to have $f(0)=f(1)$.  This is true because $e^{2\pi i}=e^{0}=1$, so $f(0)$ and $f(1)$ are both $\frac{p(r)/p(r)}{|p(r)/p(r)|}=1$.
Comment: But does that mean $p(re^{2\pi is})/|p(re^{2\pi is})|$ can also do the job? Why do we still need $p(r)$?
Comment: I would guess that in context you want it to be a loop based at $1$, so $f(0)=f(1)=1$.  If you leave out $p(r)$, you'll get $f(0)=f(1)=p(r)/|p(r)|$.
Comment: So why if we include $p(r)$ we would get a circle?
Comment: What don't you understand about what I wrote in my answer?
Comment: I understand that if I leave out $p(r)$ I'll get $p(r)/|p(r)|$ and it is a loop based at 1. What I don't understand is what makes the difference if we don't leave out $p(r)$? Why can we get a circle if we don't leave out $p(r)$?
Comment: We do still get a loop if we leave out $p(r)$, it just (probably) won't satisfy $f(0)=f(1)=1$.
Comment: Another thing that I still doubt is that if we don't leave out $p(r)$, how can we guarantee that the shape of the loop is a circle?
Comment: What does "the shape of the loop is a circle" mean?  The image will be (contained in) the unit circle, but beyond that there's not any meaningful sense in which it will be a circle in general.


Next js problem with relative react fuse paths

Question: Hello. I use React Fuse in Front End, and Nextjs to run the server. But Next has a problem with relative fuse paths, for example the relative path @history leads to module not found error !. Is there a way to solve this problem?
import history from '@history';

Answer: It is supported since Next.js 9.5.4. Follow the instruction of the nextjs docs:

Since Next.js 9.5.4, importing a CSS file from node_modules is permitted anywhere in your application.
For global stylesheets, like bootstrap or nprogress, you should import
the file inside pages/_app.js. For example:

// pages/_app.js
import 'bootstrap/dist/css/bootstrap.css'

export default function MyApp({ Component, pageProps }) {
  return <Component {...pageProps} />
}

For importing CSS required by a third party component, you can do so
in your component. For example:

// components/ExampleDialog.js
import { useState } from 'react'
import { Dialog } from '@reach/dialog'
import '@reach/dialog/styles.css'

function ExampleDialog(props) {
  const [showDialog, setShowDialog] = useState(false)
  const open = () => setShowDialog(true)
  const close = () => setShowDialog(false)

  return (

      <button onClick={open}>Open Dialog</button>
      <Dialog isOpen={showDialog} onDismiss={close}>
        <button className="close-button" onClick={close}>
          <VisuallyHidden>Close</VisuallyHidden>
          ×
        </button>

Hello there. I am a dialog

      </Dialog>

  )
}


Detect and handle when a database query goes wrong

Question: My problem is I want all my queries must return results after a limited time. AFAIK, postgres has 2 options for this: connect_timeout when open a connection to database, and statement_timeout for a query.
This lead to 2 problems:

I must estimate how much time the query is run. My approach is setup
a worst case scenario: with a preset bandwidth to db server, a query
with a lot record... to determine it, but I think this ain't a smart
way. Are there any better ideas/patterns... to handle this?
The network problem. Assume the network is bad with heavy packets
    loss, high ping as hell... the query from clients, and the result from
    the server are stuck ... Of course we can set a
    timeout from the code, but I think it will be complicated due to
    handle resource and other things, and it's duplicated with the
    database timeout mechanism. Are there anyway to handle this?

Another version of the story: when a query take a long time, I want to distinguish: this query is all good, just has too many records, wait for it, and no, the query is "broken",don't wait for it...
Ps : I found this link, but this is for SQL Server 2005 :(
http://www.mssqltips.com/sqlservertip/1338/finding-a-sql-server-process-percentage-complete-with-dmvs/
Comment: For what purpose do you need the well defined timeout? Why do think it is important for your application?
Comment: I need the info to report to the upper layer. My team-leader want a report, not something run around  for a long time.
Comment: But why does your team-leader think so? Does he want to prevent your application from blocking a long time due to synchronous DB access? Or does he think the queries are not important enough to wait for them?
Comment: Yes, prevent the block and few more things. The queries result varies from just a number to hundreds of thousands records, when it takes time, the user should distinguish: this query is all good, just has too many records, wait for it, _and_ no, the query is "broken",don't wait for it, contact tech-support ASAP...
Comment: Do you really need hundred of thousands of records? If you do then you shouldn't mind waiting a bit. If you don't then why not limit the result or use a cursor?
Comment: Yes, if the user queries data saved a month ago, it will reach about 500,000 records. Users also require to access data with no restriction. And what do you mean a cursor?
Comment: BTW, the network can be unstable and we must handle that.
Comment: You do not explain what the actual operational problem you're trying to solve here is. This sounds more like a candidate for log analysis / pg_stat_statements than for a query timeout.
Comment: Another version of the story: when a query take a long time, I want to distinguish: this query is all good, just has too many records, wait for it, and no, the query is "broken",don't wait for it...
Comment: You will not be able to do what you want. It's a recognised extremely hard problem in computing theory. http://en.wikipedia.org/wiki/Halting_problem
Answer: As you already mentioned, it is hard to predict how long a query runs (due to the query itself and its parameters, due to network, due to server load).
Anyway you should move the SQL queries into QThreads. This allows your application from serving the GUI while the queries run.
Also I would not try to solve this by timeouts. You will get into a lot of trouble because you will fail to choose the right timeouts for each query and each situation. Instead provide a way of cancelling queries by a button or a dialog so the user can decide if it is sensible to continue waiting or not.
Comment: Thank, I do implement QThread to do the interactions with the database. If there isn't any solution, I will follow your advice, let's the user decide the action. So I think I'll need a query indicators or something similars to give info to the user
Comment: Remember accept my answer if you don't get a better one.
Answer: What you want to do:

when a query take a long time, I want to distinguish: this query is all good, just has too many records, wait for it, and no, the query is "broken",don't wait for it.

is just not going to work out. You appear to require a solution to the halting problem, a fundamentally hard problem in computer science.
You must decide how long is acceptable for a query to run, and set a timeout. There is no reliable way to predict how long it should run, except by looking at how long other similar queries took to run before. Nor is there any way to tell the difference between a correct (but slow) query and one that is going to run forever. That's particularly true when things like WITH RECURSIVE or PL/PgSQL functions are involved.
Answer: You can do the queries in a specific class the object of which resides in a separate thread and wait for a timeout for the object to quit :
databaseObject->performQuery();

QThread * th = databaseObject->thread();
th->quit();
th->wait(2000);

if(th->isRunning())
{
    th->terminate();
    return false;
}
else
    return true;

Comment: Thank, but how do you estimate the time out? The query will be varies from a few to hundreds of thousands records.
Comment: @Tiana987642 I doubt there is any simple way to estimate the query time. You can have your own maximum acceptable time for query. The timeout is dependent to your needs.


Python: optimising loops

Question: I wish to optimise some python code consisting of two nested loops.  I am not so familar with numpy, but I understand it should enable me to improve the efficiency for such a task.  Below is a test code I wrote that reflects what happens in the actual code.  Currently using the numpy range and iterator is slower than the usual python one.  What am I doing wrong?  What is the best solution to this problem?
Thanks for your help!
import numpy
import time

# setup a problem analagous to that in the real code
npoints_per_plane = 1000
nplanes = 64
naxis = 1000
npoints3d = naxis + npoints_per_plane * nplanes
npoints = naxis + npoints_per_plane
specres = 1000

# this is where the data is being mapped to
sol = dict()
sol["ems"] = numpy.zeros(npoints3d)
sol["abs"] = numpy.zeros(npoints3d)

# this would normally be non-random input data
data = dict()
data["ems"] = numpy.zeros((npoints,specres))
data["abs"] = numpy.zeros((npoints,specres))
for ip in range(npoints):
    data["ems"][ip,:] = numpy.random.random(specres)[:]
    data["abs"][ip,:] = numpy.random.random(specres)[:]
ems_mod = numpy.random.random(1)[0]
abs_mod = numpy.random.random(1)[0]
ispec = numpy.random.randint(specres)

# this the code I want to optimize

t0 = time.time()

# usual python range and iterator
for ip in range(npoints_per_plane):
    jp = naxis + ip
    for ipl in range(nplanes):
        ip3d = jp + npoints_per_plane * ipl
        sol["ems"][ip3d] = data["ems"][jp,ispec] * ems_mod
        sol["abs"][ip3d] = data["abs"][jp,ispec] * abs_mod

t1 = time.time()

# numpy ranges and iterator
ip_vals = numpy.arange(npoints_per_plane)
ipl_vals = numpy.arange(nplanes)
for ip in numpy.nditer(ip_vals):
    jp = naxis + ip
    for ipl in numpy.nditer(ipl_vals):
        ip3d = jp + npoints_per_plane * ipl
        sol["ems"][ip3d] = data["ems"][jp,ispec] * ems_mod
        sol["abs"][ip3d] = data["abs"][jp,ispec] * abs_mod

t2 = time.time()

print "plain python: %0.3f seconds" % ( t1 - t0 )
print "numpy: %0.3f seconds" % ( t2 - t1 )

edit: put "jp = naxis + ip" in the first for loop only
additional note:
I worked out how to get numpy to quickly do the inner loop, but not the outer loop:
# numpy vectorization
for ip in xrange(npoints_per_plane):
    jp = naxis + ip
    sol["ems"][jp:jp+npoints_per_plane*nplanes:npoints_per_plane] = data["ems"][jp,ispec] * ems_mod
    sol["abs"][jp:jp+npoints_per_plane*nplanes:npoints_per_plane] = data["abs"][jp,ispec] * abs_mod

Joe's solution below shows how to do both together, thanks!
Comment: The key to writing fast numpy code is *avoiding* loops by vectorizing operations (or, rather, pushing the loops down to the fast C level), not that iterating over numpy objects is faster.  IOW, idiomatic numpy code doesn't have many `for` loops, but acts on vectors and arrays as a whole.
Comment: I'm not acquainted with `numpy.range`, but using Python's `range` is the same as creating a list of `n` elements, whereas, `xrange` is a generator of numbers -- avoiding storage of an entire list.
Comment: Thanks. You are right, but when I use xrange instead of range there is no change in the runtime.
Comment: 2 questions. 1) Is the size of the arrays the same as for your true application? 2) How fast do you need the code to run?
Comment: 1) for a small problem, yes.  For the largest problem, it would be more like npoints_per_plane = 50000, nplanes = 64, naxis = 1000, specres = 1000. 2) I want the code to run in a similar order of magnitude to c.  I have just spent a week converting a swig interface to pure python but now it takes twice as long for a small problem, and this is the bottleneck.
Comment: It seems like a simple transform with a constant multiplication for all values. It might be faster to simply write a smart indexer unless you absolutely need the data in a linear array i.e. make 'sol' a class with access operators that access 'data' underneath
Comment: sol is actually a variable in a netcdf file that I am interacting with via netCDF4, so I am currently stuck with a linear array.
Answer: The best way of writing loops in numpy is not writing loops and instead using vectorized operations. For example:
c = 0
for i in range(len(a)):
    c += a[i] + b[i]

becomes
c = np.sum(a + b, axis=0)

For a and b with a shape of (100000, 100) this takes 0.344 seconds in the first variant, and 0.062 seconds in the second.
In the case presented in your question the following does what you want:
sol['ems'][naxis:] = numpy.ravel(
    numpy.repeat(
        data['ems'][naxis:,ispec,numpy.newaxis] * ems_mod,
        nplanes,
        axis=1
    ),
    order='F'
)

This could be further optimized with some tricks, but that would reduce clarity and is probably premature optimization because:

plain python: 0.064 seconds
numpy: 0.002 seconds

The solution works as follows:
Your original version contains jp = naxis + ip which merely skips the first naxis elements [naxis:] selects all but the first naxis elements. Your inner loop repeats the value of data[jp,ispec] for nplanes times and writes it to multiple locations ip3d = jp + npoints_per_plane * ipl which is equivalent to a flattened 2D array offset by naxis. Therefore a second dimension is added via numpy.newaxis to the (previously 1D) data['ems'][naxis:, ispec], the values are repeated nplanes times along this new dimension via numpy.repeat. The resulting 2D array is then flattened again via numpy.ravel (in Fortran order, i.e., with the lowest axis having the smallest stride) and written to the appropriate subarray of sol['ems']. If the target array was actually 2D, the repeat could be skipped by using automatic array broadcasting.
If you run into a situation where you cannot avoid using loops, you could use Cython (which supports efficient buffer views on numpy arrays).
Comment: `c = numpy.sum(a + b[::2])`
Comment: Actually the code does look like a one to one mapping, except that it is [`reshape`d](http://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html). Cython code can be used inline via [`cython.inline`](http://docs.cython.org/src/reference/compilation.html#compiling-with-cython-inline).
Comment: thanks, yeah I am reading http://docs.scipy.org/doc/numpy/reference/arrays.nditer.html to try and work out if I can vectorize my loop.  The problem is it is not a 1:1 mapping so perhaps I need the loop still.  And can I put cython code in a python script?  Not sure how that works...
Comment: how does one vectorize "for i in range(len(a)): c += a[i] + b[2*i]" for example?  this would help me understand what to do.
Comment: okay, I see the syntax now ([i:j:k] where i=start, j=stop, k=increment), but I cannot work out how to apply this my loop. how does one vectorize "for ipl in xrange(nplanes): sol["ems"][jp + npoints_per_plane * ipl] = data["ems"][jp,ispec] * ems_mod" for example?
Comment: thanks joe, your solution is both neat and fast (and correct, determined via assert) - exactly why I want to use python!  now I just need to work out how your solution works!
Comment: @user1334640 added some more explanation, hope it helps
Comment: @user1334640 Is more clarification required? If not it would be appropriate to accepted the answer.

Python: optimising loops


Erro Unity 5 aparentemente codigo

Question: Estava fazendo esse jogo quando apareceu este problema

Assets/SampleAssets/2D/Scripts/Platformer2DUserControl.cs(2,25): error CS0234: The type or namespace name CrossPlatformInput' does not exist in the namespaceUnitySampleAssets'. Are you missing an assembly reference?

O meu código esta da seguinte maneira
using UnityEngine;
using UnitySampleAssets.CrossPlatformInput;

namespace UnitySampleAssets._2D
{

    [RequireComponent(typeof (PlatformerCharacter2D))]
    public class Platformer2DUserControl : MonoBehaviour
    {
        private PlatformerCharacter2D character;
        private bool jump;

        private void Awake()
        {
            character = GetComponent<PlatformerCharacter2D>();
        }

        private void Update()
        {
            if(!jump)
            // Read the jump input in Update so button presses aren't missed.
            jump = CrossPlatformInputManager.GetButtonDown("Jump");
        }

        private void FixedUpdate()
        {
            // Read the inputs.
            bool crouch = Input.GetKey(KeyCode.LeftControl);
            float h = CrossPlatformInputManager.GetAxis("Horizontal");
            // Pass all parameters to the character control script.
            character.Move(h, crouch, jump);
            jump = false;
        }
    }
}

Comment: @mgibsonbr é isso mesmo que você falou, esse código deve ser de algum tutorial ou exemplo antigo, pois esse UnitySampleAssests não existe mais tem uns bons 3 anos. Pegar o eixo já é nativo da ferramenta desde então. Aqui tem um exemplo de como pegar comando de eixos, já está no segundo certo.
https://youtu.be/fotMn6x7aoU?t=34m45s
Comment: Quando "apareceu" esse problema? O código funcionava e depois deixou de funcionar? Ou o erro está aí desde o início? Esse projeto foi feito do zero ou copiado de algum lugar? Não tenho experiência com o Unity, mas [esse post no unity3d.com](http://answers.unity3d.com/questions/755466/the-name-crossplatforminput-does-not-exist-in-the.html) sugere que esse recurso não é nativo do Unity, e sim parte de um projeto ou pacote ("sample assets beta package" eu acho). Seu projeto usa esse pacote? A pasta `CrossPlatformInput` está presente?
Comment: Porque a tag está como `JavaScript` se o código é `C#` ?
Answer: O pacote "UnitySampleAssets" foi disponibilizado no evento Unite em 2014, numa palestra sobre boas práticas para jogos 2D no Unity, você pode baixá-lo aqui.
Nesse arquivo você vai encontrar esse script que está faltando.
Link da palestra (recomendo): https://www.youtube.com/watch?v=HM17mAmLd7k
Answer: Eu não conheço esse pacote UnitySampleAssets. Você chegou a importa-lo? Será que não deletou alguma pasta dele, por acidente?
Para resolver esse problema, você pode reimportar esse pacote ou deixar de usar o CrossPlatformInput. Comentando a linha using UnitySampleAssets.CrossPlatformInput; e trocando todos os CrossPlatformInputManager por Input.

Erro Unity 5 aparentemente codigo


Sugestão de melhoria de codigo, para abertura de varios arquivos csv em diretorios diferentes

Question: Boa noite amigos, um amigo me passou um código que ele estava desenvolvendo para que eu pudesse estudar, porem eu gostaria de ver uma melhor alternativa para a abertura de vários arquivos .csv, só que estão em diferentes pastas.
O código está imenso, creio que seja possível algo melhor com o loop for.
Tenho conhecimento básico em Python.

Os diretórios estão divididos em 4 pastas, nomes de L1 - L2 - L3 - L4
dentro de cada destas 4 pastas, tem algumas pastas com o formato de data. Ex: 03_02_20
dentro destas pastas com as datas estão os arquivos.csv
cada arquivo possui um código diferente no formato do nome, um numero 500 e alguma coisa. EX: L1_503_03_02_20.csv
L1_505_03_02_20.csv
....
L1_508_03_02_20.csv

Segue o código original abaixo:
# Importação dos CSVs
df = pd.DataFrame()
df1 = pd.DataFrame()
df2 = pd.DataFrame()
df3 = pd.DataFrame()
df4 = pd.DataFrame()
df5 = pd.DataFrame()

for DateCSV in AnalysisDate:
    if Line == 'L4':
        df3 = pd.read_csv(
            DiretorioBase + "\\" + DateCSV + "\\" + Line + "_504_" + DateCSV + ".csv", sep=";")
        df3['workcenter'] = 3
        df1 = pd.read_csv(
            DiretorioBase + "\\" + DateCSV + "\\" + Line + "_502_" + DateCSV + ".csv", sep=";")
        df1['workcenter'] = 1
        df2 = pd.read_csv(
            DiretorioBase + "\\" + DateCSV + "\\" + Line + "_503_" + DateCSV + ".csv", sep=";")
        df2['workcenter'] = 2
        df5 = pd.read_csv(
            DiretorioBase + "\\" + DateCSV + "\\" + Line + "_506_" + DateCSV + ".csv", sep=";")
        df5['workcenter'] = 5
        df4 = pd.read_csv(
            DiretorioBase + "\\" + DateCSV + "\\" + Line + "_505_" + DateCSV + ".csv", sep=";")
        df4['workcenter'] = 4
    else:
        df1 = pd.read_csv(DiretorioBase + "\\" + DateCSV + "\\" + Line + "_505_" + DateCSV + ".csv", sep=";")
        df1['workcenter'] = 1
        df2 = pd.read_csv(DiretorioBase + "\\" + DateCSV + "\\" + Line + "_506_" + DateCSV + ".csv", sep=";")
        df2['workcenter'] = 2
        if not(Line == 'L2' and Mes == 2):
            df3 = pd.read_csv(DiretorioBase + "\\" + DateCSV + "\\" + Line + "_503_" + DateCSV + ".csv", sep=";")
            df3['workcenter'] = 3
        df4 = pd.read_csv(DiretorioBase + "\\" + DateCSV + "\\" + Line + "_507_" + DateCSV + ".csv", sep=";")
        df4['workcenter'] = 4
        df5 = pd.read_csv(DiretorioBase + "\\" + DateCSV + "\\" + Line + "_508_" + DateCSV + ".csv", sep=";")
        df5['workcenter'] = 5
    df = df.append(df1).append(df2).append(df3).append(df4).append(df5)

df['Line'] = Line
df = df.drop_duplicates(keep='first')

Answer: Olá, seja bem vindo ao Stack Overflow.
Não sei se consegui compreender bem seu problema, ainda sim trouxe uma solução:
import os
import pandas as pd

def getListOfFiles(dirName):
    listOfFile = os.listdir(dirName)
    allFiles = list()
    for entry in listOfFile:
        fullPath = os.path.join(dirName, entry)
        if os.path.isdir(fullPath):
            allFiles = allFiles + getListOfFiles(fullPath)
        else:
            allFiles.append(fullPath)

    return allFiles

diretorio = r"C:\seu\diretório\base\nesta\variável"
files = getListOfFiles(diretorio)

df = pd.DataFrame()
for key, file in enumerate(files):
    if file.endswith(".csv"):
        df_x = pd.read(file, sep=";")
        df_x['workcenter'] = key
        df.append(df_x)

O que essa solução faz é:

A função lê todos as pastas e subpastas em um diretório e filtra apenas os arquivos, trazendo-os em uma lista.
Pega cada arquivo da lista retornada e, caso o arquivo termine com a extensão .csv, ele lê e salva em um dataframe temporário df_x.
Ao final, ele simplesmente adiciona esse dataframe temporário à um dataframe final df.

Não sei se ficou claro a solução, nem se atende suas espectativas.
Em caso negativo, comente aqui e vamos avaliando até chegarmos a melhor solução pra você.


Sub-process /usr/bin/dpkg returned an error code (1)

Question: Hey friends i am getting the following error when i am trying to purge shorewall
root@aptosid:/etc# apt-get purge shorewall
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following packages will be REMOVED:
  shorewall*
0 upgraded, 0 newly installed, 1 to remove and 3 not upgraded.
1 not fully installed or removed.
After this operation, 1,843 kB disk space will be freed.
Do you want to continue [Y/n]?
(Reading database ... 212702 files and directories currently installed.)
Removing shorewall ...
: not found/shorewall: 25: /etc/default/shorewall: :q
Stopping "Shorewall firewall": not done (check /var/log/shorewall-init.log).
invoke-rc.d: initscript shorewall, action "stop" failed.
dpkg: error processing shorewall (--purge):
 subprocess installed pre-removal script returned error exit status 1
configured to not write apport reports
                                      Errors were encountered while processing:
 shorewall
E: Sub-process /usr/bin/dpkg returned an error code (1)
root@aptosid:/etc#

please help me out ...........?
Answer: It looks like the install is messed up and some of the configuration files are missing.  You might be able to get it to continue if you do
touch /etc/default/shorewall

but more likely you'll need to reinstall the package to get the missing configuration back, then purge it.  To reinstall it you'll need to do
apt-get install --reinstall shorewall


ansible - tranferring files and changing ownership

Question: I'm new to Ansible. The following is my requirement,

Transfer files(.tar.gz) from one host to many machines (38+ Nodes) under /tmp as user1
Log in to each machines as user2 and switch to root user using sudo su - (With Password)
extract it to another directory (/opt/monitor)
Change a configuration in the file (/opt/monitor/etc/config -> host= )
Start the process under /opt/monitor/init.d

For this, should I use playbooks or ad-hoc commands ?
I'll happy to use ad-hoc mode in ansible as I'm afraid of Playbooks.
Thanks in advance
Answer: You'd have to write several ad hoc commands to accomplish this. I don't see any good reason to not use a playbook here. You will want to learn about playbooks, but it's not much more to learn than the ad hoc commands. The sudo parts are taken care of for you by using the -b option to "become" the using sudo. Ansible takes care of the logging in for you via ssh.
The actions you'll want to make use of are common for this type of setup where you're installing something from source, commands like yum, get_url, unarchive, service. As an example, here's a pretty similar process to what you need, demonstrating installing redis from source on a RedHat-family system:
- name: install yum dependencies for redis
  yum: name=jemalloc-devel ... state=present

- name: get redis from file server
  get_url: url={{s3uri}}/common/{{redis}}.tar.gz dest={{tmp}}

- name: extract redis
  unarchive: copy=no src={{tmp}}/{{redis}}.tar.gz dest={{tmp}} creates={{tmp}}/{{redis}}

- name: build redis
  command: chdir={{tmp}}/{{redis}} creates=/usr/local/bin/redis-server make install

- name: copy custom systemd redis.service
  copy: src=myredis.service dest=/usr/lib/systemd/system/
  # and logrotate, redis.conf, etc

- name: enable myredis service
  service: name=myredis state=started enabled=yes

You could define custom variables like tmp and redis in a global_vars/all.yaml file. You'll also want a site.yaml file to define your hosts and a role(s).
You'd invoke the playbook with something like:
ansible-playbook site.yaml -b --ask-become-pass -v

This can operate on your 38+ nodes as easily as on one.
Comment: Thank you Elliott... The file is not a source and it is a tarball. Will try what Bruce said and let you guys know. Apology for the late reply.
Answer: You'll want a playbook to do this.  At the simplest level, since you mention unpacking, it might look something like this:
- name: copy & unpack the file
  unarchive: src=/path/to/file/on/local/host
             dest=/path/to/target
             copy=yes

- name: copy custom config
  copy: src=/path/to/src/file
        dest=/path/to/target

- name: Enable service
  service: name=foo enabled=yes state=started

Comment: Thank you. Wil try it out and share you the results. Apology for my late reply