Aparecer as DIVS de apenas categoria selecionada

Question: Olá,
Estou tendo um problema e não consigo achar a solução, pelo fato de ser algo comum na internet, acredito que não esteja procurando da forma correta.
Gostaria de selecionar as divs que iram ficar a mostra.
Ex:
Tenho vários produtos (cada um em uma div), quando carrego a página, mostra todos, porém, logo em cima tem uns filtros, exemplo:
TUDO - TIPO1 - TIPO2 - TIPO3
Ao clicar em uma das opções, mostraria apenas os produtos (divs) dessa categoria.
Por exemplo, clico no TIPO1, some todas as divs e fica apenas os produtos da categoria TIPO1.
Espero que tenha consigo explicar corretamente.
Answer: Se entendi Bem, Acredito  o Codigo a baixo irá ajudar

  Tipo1

  Tipo1

  Tipo2

  Tipo3

  Tipo3

  Reset

Comment: Obrigado pela ajuda, seria isso mesmo, porém queria que mostrasse através do click em um menu, ou seja, ao invés de clicar na própria div, clicar em um menu e as divs se "organizarem"
Comment: Voce pode utilizar a mesma logica do Click na Div, para um Click em um Menu. o Menu é um Button, link, ou div?
Comment: Então, tentei desenhar para explicar, com as palavras não estou sendo muito bom kk
![imagem de exemplo](http://rdcreative.com.br/Exemplo.jpg)
Answer: Oi! Sabendo aplicar, creio que esta seja uma excelente solução: O Isotope Menu faz exatamente isso de uma forma fluida e responsiva. Creio que para apresentar produtos, seria uma boa escolha.
Abaixo está exemplificado como no Codepen.

// external js: isotope.pkgd.js

// init Isotope
var $grid = $('.grid').isotope({
  itemSelector: '.element-item',
  layoutMode: 'fitRows',
  getSortData: {
    name: '.name',
    symbol: '.symbol',
    number: '.number parseInt',
    category: '[data-category]',
    weight: function(itemElem) {
      var weight = $(itemElem).find('.weight').text();
      return parseFloat(weight.replace(/[\(\)]/g, ''));
    }
  }
});

// filter functions
var filterFns = {
  // show if number is greater than 50
  numberGreaterThan50: function() {
    var number = $(this).find('.number').text();
    return parseInt(number, 10) > 50;
  },
  // show if name ends with -ium
  ium: function() {
    var name = $(this).find('.name').text();
    return name.match(/ium$/);
  }
};

// bind filter button click
$('#filters').on('click', 'button', function() {
  var filterValue = $(this).attr('data-filter');
  // use filterFn if matches value
  filterValue = filterFns[filterValue] || filterValue;
  $grid.isotope({
    filter: filterValue
  });
});

// bind sort button click
$('#sorts').on('click', 'button', function() {
  var sortByValue = $(this).attr('data-sort-by');
  $grid.isotope({
    sortBy: sortByValue
  });
});

// change is-checked class on buttons
$('.button-group').each(function(i, buttonGroup) {
  var $buttonGroup = $(buttonGroup);
  $buttonGroup.on('click', 'button', function() {
    $buttonGroup.find('.is-checked').removeClass('is-checked');
    $(this).addClass('is-checked');
  });
});
* {
  box-sizing: border-box;
}

body {
  font-family: sans-serif;
}

/* ---- button ---- */

.button {
  display: inline-block;
  padding: 0.5em 1.0em;
  background: #EEE;
  border: none;
  border-radius: 7px;
  background-image: linear-gradient( to bottom, hsla(0, 0%, 0%, 0), hsla(0, 0%, 0%, 0.2));
  color: #222;
  font-family: sans-serif;
  font-size: 16px;
  text-shadow: 0 1px white;
  cursor: pointer;
}

.button:hover {
  background-color: #8CF;
  text-shadow: 0 1px hsla(0, 0%, 100%, 0.5);
  color: #222;
}

.button:active,
.button.is-checked {
  background-color: #28F;
}

.button.is-checked {
  color: white;
  text-shadow: 0 -1px hsla(0, 0%, 0%, 0.8);
}

.button:active {
  box-shadow: inset 0 1px 10px hsla(0, 0%, 0%, 0.8);
}

/* ---- button-group ---- */

.button-group {
  margin-bottom: 20px;
}

.button-group:after {
  content: '';
  display: block;
  clear: both;
}

.button-group .button {
  float: left;
  border-radius: 0;
  margin-left: 0;
  margin-right: 1px;
}

.button-group .button:first-child {
  border-radius: 0.5em 0 0 0.5em;
}

.button-group .button:last-child {
  border-radius: 0 0.5em 0.5em 0;
}

/* ---- isotope ---- */

.grid {
  border: 1px solid #333;
}

/* clear fix */

.grid:after {
  content: '';
  display: block;
  clear: both;
}

/* ---- .element-item ---- */

.element-item {
  position: relative;
  float: left;
  width: 100px;
  height: 100px;
  margin: 5px;
  padding: 10px;
  background: #888;
  color: #262524;
}

.element-item>* {
  margin: 0;
  padding: 0;
}

.element-item .name {
  position: absolute;
  left: 10px;
  top: 60px;
  text-transform: none;
  letter-spacing: 0;
  font-size: 12px;
  font-weight: normal;
}

.element-item .symbol {
  position: absolute;
  left: 10px;
  top: 0px;
  font-size: 42px;
  font-weight: bold;
  color: white;
}

.element-item .number {
  position: absolute;
  right: 8px;
  top: 5px;
}

.element-item .weight {
  position: absolute;
  left: 10px;
  top: 76px;
  font-size: 12px;
}

.element-item.alkali {
  background: #F00;
  background: hsl( 0, 100%, 50%);
}

.element-item.alkaline-earth {
  background: #F80;
  background: hsl( 36, 100%, 50%);
}

.element-item.lanthanoid {
  background: #FF0;
  background: hsl( 72, 100%, 50%);
}

.element-item.actinoid {
  background: #0F0;
  background: hsl( 108, 100%, 50%);
}

.element-item.transition {
  background: #0F8;
  background: hsl( 144, 100%, 50%);
}

.element-item.post-transition {
  background: #0FF;
  background: hsl( 180, 100%, 50%);
}

.element-item.metalloid {
  background: #08F;
  background: hsl( 216, 100%, 50%);
}

.element-item.diatomic {
  background: #00F;
  background: hsl( 252, 100%, 50%);
}

.element-item.halogen {
  background: #F0F;
  background: hsl( 288, 100%, 50%);
}

.element-item.noble-gas {
  background: #F08;
  background: hsl( 324, 100%, 50%);
}

Isotope - filtering & sorting

Filter

 <button class="button is-checked" data-filter="*">show all</button>
  <button class="button" data-filter=".metal">metal</button>
  <button class="button" data-filter=".transition">transition</button>
  <button class="button" data-filter=".alkali, .alkaline-earth">alkali and alkaline-earth</button>
  <button class="button" data-filter=":not(.transition)">not transition</button>
  <button class="button" data-filter=".metal:not(.transition)">metal but not transition</button>
  <button class="button" data-filter="numberGreaterThan50">number > 50</button>
  <button class="button" data-filter="ium">name ends with –ium</button>

Sort

 <button class="button is-checked" data-sort-by="original-order">original order</button>
  <button class="button" data-sort-by="name">name</button>
  <button class="button" data-sort-by="symbol">symbol</button>
  <button class="button" data-sort-by="number">number</button>
  <button class="button" data-sort-by="weight">weight</button>
  <button class="button" data-sort-by="category">category</button>

Mercury

Hg

80

200.59

Tellurium

Te

52

127.6

Bismuth

Bi

83

208.980

Lead

Pb

82

207.2

Gold

Au

79

196.967

Potassium

K

19

39.0983

Sodium

Na

11

22.99

Cadmium

Cd

48

112.411

Calcium

Ca

20

40.078

Rhenium

Re

75

186.207

Thallium

Tl

81

204.383

Antimony

Sb

51

121.76

Cobalt

Co

27

58.933

Ytterbium

Yb

70

173.054

Argon

Ar

18

39.948

Nitrogen

N

7

14.007

Uranium

U

92

238.029

Plutonium

Pu

94

(244)

Comment: Obrigado pela resposta! Olhei o site e o código que você sugeriu, é exatamente o que eu quero, porém, achei um pouco complicado o código, queria algo mais simples. Só que vi o código rapidamente, irei analisar e verificar assim que chegar em casa e ter mais tempo.
Comment: @RafaelDantas De nada! Mas se você analisar com cuidado o que eu botei aqui, você vai acabar percebendo que não é nenhum bicho de sete cabeças. O CSS é ignorável nesse caso. A parte mais complicada é aprender a conectar o JS e o HTML, mas você pode ver que tudo é uma questão com os `data-filters` e classes. Boa sorte aí!
Comment: Cheguei em casa agora, vou tentar ver se consigo fazer com ele.
Comment: Dei uma olhada em todo o código, consegui editar e resolver meu problema com ele. Muito obrigado pela atenção!
Comment: @RafaelDantas Nada! Que bom que funcionou! :)


If two polynomials are equal as functions, are they necessarily equal as polynomials?

Question: Say you have a finite field $F$ of order $p^k$. Suppose that $f,g\in F[X_1,\dots,X_m]$, such that the degree of each $X_i$ is strictly less than $p^k$ in both $f$ and $g$. I'm putting this condition to avoid things like $f=X_1X_2X_3^{p^k}$ and $g=X_1X_2X_3$ which technically define the same polynomial function over $F$ since $X_i^{p^k}-X_i$ is in the kernel of the evaluation homomorphism, but are not equal in the polynomial ring.
Under this condition, if $f$ and $g$ define the same polynomial function over $F$, are they equal as polynomials? By equality of polynomial functions, I mean they are equal as sets of ordered pairs. I feel like restricting the degree of each indeterminate should force this to be so, but how can it actually be proven?
Comment: How many scalar numbers define a polynomial with your degree conditions? How many scalar numbers define a function, polynomial or not, on $F^m$? Ergo? (Is this (homework)?)
Comment: @did Thanks, so writing $p^k=q$, both sets have cardinality $q^{(q^m)}$, so every function in $m$ variables over $F$ is a polynomial function. So am I correct in thinking there is a 1-1 correspondence between polynomials of degree$<q$, and thus if $f$ and $q$ define the same polynomial function, then they must in fact be the same polynomial? By the way, this is not homework.
Comment: If $R$ is an infinite integral domain then $R[X]$ is isomorphic as ring to the ring of polynomial functions.
Answer: Formalizing Jacob's answer (+1) and generalizing it to $m$ variables as in did's comment.
Let $F=GF(q)$ be the field of $q$ elements, and let $P=(a_1,a_2,\ldots,a_m)\in F^m$ be an arbitrary point. Let us fix an index $j$, $1\le j\le m$. The polynomial
$$
f_j(x)=\prod_{a\in F, a\neq a_j}(x-a)=\frac{x^q-x}{x-a_j}
$$
has the properties that $f_j(a_j)\neq0$, and $f_j(a)=0$ for all $a\in F, a\neq a_j.$ Therefore the product
$$
f_P(x_1,x_2,\ldots,x_m):=f_1(x_1)f_2(x_2)\cdots f_m(x_m)=\prod_{j=1}^m f_j(x_j)
$$
vanishes at all other points of $F^m$ except at $P$. Furthermore, the polynomial $f_P$
is of degree $\le q-1$ with respect to all the variables $x_j,j=1,2,\ldots,m.$
Let $V_m$ be the space of polynomials in $m$ variables over $F$ such that no variable
appears with degree $\ge q$. Let $V_m'$ be the space of $F$-valued functions on $F^m$.
There is a natural evaluation mapping $ev:V_m\rightarrow V_m'$. Our earlier calculations show that the functions $ev(f_P)$, with $P$ ranging over the points of $F^m$, form a basis
of $V_m'$. Therefore $ev$ is surjective. Because $V_m$ and $V_m'$ both have dimension $q^m$ as vector spaces over $F$, the mapping $ev$ must also be injective (rank-nullity).
This answers your question in the affirmative.
Comment: +1. (Quibble: The degree of $f_P$ in each variable seems to be exactly $q-1$, or am I mistaken?)
Comment: Correct, @did. Inequality would suffice, but it **is** an equality.
Answer: I think the result you want to prove is the following. Let $\mathbb F$ be a finite field of order $q$ then the ring of functions from $\mathbb F$ to $\mathbb F$ is isomorphic to
$$\frac{\mathbb F[x]}{(x^q-x)}.$$
This is usually proved by taking the map from $\mathbb F[x]$ to the ring of functions and demonstrating that it's surjective with kernel $(x^q-x)$. Which is fairly straightforward.


Split dataframe to sub dataframes and fill content according to the relevant dataframe?

Question: I have the following toy dataframe:
x  value      id
A  5           1
B  DE          1
C  False       1
D  yes         1
E  -0.9442     1
A  66          2
D  yes         2
E  -0.9442     2
F  Kuku        2
Z  1           2

etc.
for each id, we have some set of attributes.
I want to "slice" them by attributes for each id (for example id 1 has A,B,C,D and E attributes and id 2 has A,D,E,F and Z attributes.
How can I create such sub dataframes containing only A,B,C,D and E attributes, A,D,E,F and Z attributes and so on - like boxes of same attributes where I will store the request id's with the appropriate attributes?
What I am trying to do is to split the whole dataframe by id's and then extract the attributes of each. Is there any method to do this in a simpler manner?
Answer: You can create a dict of .groupby() objects of x grouped by id, as follows:
x_df_dict = {a: b for a, b in df.groupby('id')['x']}

Then, you can access the sub-dataframes (more accurately sub-Series) of x by id, as follows:
print(x_df_dict[1])

0    A
1    B
2    C
3    D
4    E
Name: x, dtype: object

print(x_df_dict[2])

5    A
6    D
7    E
8    F
9    Z
Name: x, dtype: object


JQuery toggle images CSS

Question: I am using Jquery to change the css of some images.
It works and changes the image css size when clicked.
The only issue is that when I click on the next image, the previous image stays
with the new css toggle.
Is there a way that when I click on the next image, the previous image goes back to
the original css.
I have included a jsfiddle example here:
http://jsfiddle.net/webdott/hSFpp/
Here is the jquery code:
$('img').click(function() {
    $(this).toggleClass('thumb fullview')
});

You can see that each image you click stays large.
Thanks
Comment: this is close, but not does not toggle the larger image. http://jsfiddle.net/Resey/
Comment: ok. this works. http://jsfiddle.net/webdott/rqkDR/1/
Comment: why did you take away my best answer award?
Answer: You need to remove the fullview class from all other img elements, before adding it to the one which was clicked. Try this:
$('img').click(function() {
    $('img').removeClass('fullview'); // remove class from all
    $(this).addClass('fullview'); // add class to clicked img
});

Updated fiddle
Answer: Try removing the class on img "fullview" and adding it to $(this) after.
$('img').click(function() {
    $('img').removeClass('fullview');
    $(this).addClass('fullview');
});

Fiddle
UPDATE:
I realized that though we both solved the problem, clicking the large image didn't toggle it. I added a function for that in the following code:
if ( $('img').hasClass('fullview') ) {
    $(this).click(function() {
        $(this).removeClass('fullview');
});
}

UPDATED FIDDLE
Comment: Your update has an issue - click the same image twice and it no longer works.
Comment: Yea i realized that right away...I've been working on a solution
Comment: @samrap - thanks, but as Rory pointed out, it only works once. See the updated answer. I just need the toggleClass.
Answer: check this fiddle. I solved your issue. please check this fiddle http://jsfiddle.net/Resey/1/
$('img').click(function() {
    $(this).toggleClass('fullview').siblings().removeClass('fullview');
});

Comment: @AliCarikcioglu probably because you posted nearly 30 minutes after I had posted and answer, and the OP himself had already sorted it.

JQuery toggle images CSS


Preciso fechar a conexão em cada consulta?

Question: Atualmente eu tenho uma aplicação web que faz consulta com múltiplos bancos de dados em um mesmo controller. Para cada banco eu gero uma conexão na inicialização do servidor e mantenho elas numa classe estática onde as respectivas DAOs à utilizaram e fecho no context destroy da aplicação.
A minha duvida é, eu realmente preciso abrir e fechar a conexão a cada chamada do controller? Do modo que utilizo hoje não ira me trazer problemas de performance?
Comment: Tenho a mesma dúvida, porém além da performance ainda perguntaria sobre a segurança de manter uma conexão aberta durante todo clico de vida da aplicação.
Comment: Não precisa, desde que use o [try-with-resources](https://pt.stackoverflow.com/q/172909/28595), pois ele fecha para você. Agora se quer reaproveitar, o interessante é trabalhar com pool de conexões.
Comment: não estaria, pois o pool de conexões diz para a aplicação que fechou a conexão mas a mantém dentro do pool para ser reutilizada. Esta é a mágica do pool de conexões a reutilização delas para melhor aproveitamento e performance.
Comment: @diegofm, mesmo assim ainda não estaria abrindo e fechando a conexão?
Comment: Sim, no caso, a pool seria mesmo a melhor solução. Obrigado :)
Answer:
A minha duvida é, eu realmente preciso abrir e fechar a conexão a cada chamada do controller?

Conexões com bancos de dados costumam ser stateless. Ou seja, abre, faz o que tem que fazer e fecha.
Eu, particularmente, não vejo motivos para segurar uma conexão aberta com o banco, até mesmo porque existem configurações de datasources que justamente verificam se existem conexões ociosas e as fecham.
Quando digo "faz o que tem que fazer" não significa executar uma única consulta. Você pode executar N consultas, N transações e etc.
Se você tiver uma lista de clientes para cadastrar no banco, por exemplo, você não precisa abrir e fechar uma conexão para cada item dessa lista. Você pode muito bem abrir uma conexão, iterar a lista inserindo todos os clientes no banco através dessa conexão e depois fechá-la. O importante é não segurar a conexão aberta "pra sempre".

Do modo que utilizo hoje não ira me trazer problemas de performance?

Se você usar Pool de Conexões não. O pool foi concebido exatamente com o propósito de facilitar/deixar menos custoso resgatar uma conexão com o banco.
Comment: Muito obrigado, eu já tinha pensado em utilizar Pool Connections. Parece que não terei como fugir.


Inserir tabulação ao imprimir

Question: Tenho um código para imprimir cada variável de uma List. Estou tentando inserir uma tabulação nessas variáveis. Deem uma olhada no meu código que consta no evento printPage:
int charactersOnPage = 0;
int linesPerPage = 0;

var Fonte = new Font("Arial", 12);

Cliente cliente = Clientes[listaClientes.SelectedIndex];

StringBuilder sb = new StringBuilder();
foreach (var cli in cliente.Produtos)
{
    sb.AppendFormat("\n\n{0} R${1} Data: {2}", cli.NomeProduto, cli.ValorProduto, cli.DataCompra);
}

e.Graphics.MeasureString(sb.ToString(), Fonte, e.MarginBounds.Size, StringFormat.GenericTypographic, out charactersOnPage, out linesPerPage);

e.Graphics.DrawString(sb.ToString(), Fonte, Brushes.Black, e.MarginBounds, StringFormat.GenericTypographic);

e.HasMorePages = false;

Com este código meu output é algo como: Carro R$20000 Data: 08/11/2014. Eu quero inserir uma tabulação entre esses valores e ter como saída isto:

Andei tentando com coisas do tipo:
RectangleF tabulacao = new RectangleF(30, 10, 100, 122);
e.Graphics.DrawString(System.Convert.ToString(sb), Fonte, Brushes.Blue, tabulacao);
e.Graphics.DrawRectangle(Pens.Black, Rectangle.Round(tabulacao));

Não estou sabendo como organizar cada uma dessas variáveis dentro de retângulos para fazer a tabulação. Qualquer ajuda é bem-vinda!
Comment: É um relatório, que será impresso?
Comment: Sim, serão impressos todos os produtos comprados pelo cliente que estiver selecionado. O meu código está pronto e a saída como eu quero. A única coisa que necessito é inserir uma tabulação como no exemplo para ficar mais organizado.
Comment: A tabulação usando os RectangleF: você precisa ter pelo menos uma variável para controlar o deslocamento do RectangleF no eixo X
Comment: Você já considerou usar alguma ferramenta de Reporting, ou até mesmo HTML Tables para gerar seu relatório?
Comment: Nunca associei C# com HTML. Me parece ser uma boa ideia.
Answer: Acho que o mais certo é você usar alguma ferramenta de geração de relatório.
Mas se quiser tentar gerar via HTML, para relatórios simples, de até uma página vai bem:
Coloca um WebBrowser na janela, e este código:
var HTML = "

OK
";
webBrowser.NavigateToString(HTML);

Inserir tabulação ao imprimir


How can one compute the "average" of a dataset of histograms that minimizes the mean Earth Mover's Distance between all data points and average?

Question: It is my understanding that when the distance metric is euclidean distance, the mean of a dataset minimizes the average distance between all data points and the computed "mean".
In the case of Earth Movers Distance for discrete distributions, how would one compute a "mean" such that the average EMD distance between this "mean" and all of the histograms in the dataset is minimized? How would such an average distance minimizing formula be derived in general for a given distance function?
The application is for a K-means clustering task. Existing approaches only use averaging as an update rule for the new centroid even when using an unusual distance function for which a straightforward mean will not minimize average distance to the centroid. Our group believes using this approach for updating cluster centroids will improve the quality of our cluster generation.
Comment: Not my field, but I beleive earth mover distance is related to transport problems in OR. If you don't get help here maybe ask at https://or.stackexchange.com/
Answer: I think what you discribed is the Wasserstein Barycenter.
There is plenty of literature about the Wasserstein barycenter, including fast ways to compute it, (you could specify it's the Wasserstein-1 distance you're interested in, since it's easier to compute than the general Wasserstein distance) and about its use for clustering.


SMTP module cannot connect to smtp.gmail.com

Question: The SMTP module stopped working about a week ago. It is no longer able to connect to smtp.gmail.com.  I have tried commonly recommended remedies:

Allow "Less secure apps" in Google settings.
Visit http://www.google.com/accounts/DisplayUnlockCaptcha and click the button.
Switch to port 587 and TLS.
Turn the SMTP module off and then back on.

I am still not able to send emails.  This seems to have happened without any changes to the site.  The debug output:
<code>SMTP.module is active.
The configuration options have been saved.
SMTP -> get_lines(): $data was ""
SMTP -> get_lines(): $str is "220 smtp.gmail.com ESMTP f19-20020ac859d3000000b002de4d014733sm11933677qtf.13 - gsmtp "
SMTP -> get_lines(): $data was "220 smtp.gmail.com ESMTP f19-20020ac859d3000000b002de4d014733sm11933677qtf.13 - gsmtp "
SMTP -> FROM SERVER: 220 smtp.gmail.com ESMTP f19-20020ac859d3000000b002de4d014733sm11933677qtf.13 - gsmtp
SMTP -> get_lines(): $data was ""
SMTP -> get_lines(): $str is "250-smtp.gmail.com at your service, [18.104.22.168] "
SMTP -> get_lines(): $data was "250-smtp.gmail.com at your service, [220.127.116.11] "
SMTP -> get_lines(): $data was "250-smtp.gmail.com at your service, [18.104.22.168] "
SMTP -> get_lines(): $str is "250-SIZE 35882577 "
SMTP -> get_lines(): $data was "250-smtp.gmail.com at your service, [22.214.171.124] 250-SIZE 35882577 "
SMTP -> get_lines(): $data was "250-smtp.gmail.com at your service, [22.214.171.124] 250-SIZE 35882577 "
SMTP -> get_lines(): $str is "250-8BITMIME "
SMTP -> get_lines(): $data was "250-smtp.gmail.com at your service, [220.127.116.11] 250-SIZE 35882577 250-8BITMIME "
SMTP -> get_lines(): $data was "250-smtp.gmail.com at your service, [22.214.171.124] 250-SIZE 35882577 250-8BITMIME "
SMTP -> get_lines(): $str is "250-AUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH "
SMTP -> get_lines(): $data was "250-smtp.gmail.com at your service, [220.127.116.11] 250-SIZE 35882577 250-8BITMIME 250-AUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH "
SMTP -> get_lines(): $data was "250-smtp.gmail.com at your service, [220.127.116.11] 250-SIZE 35882577 250-8BITMIME 250-AUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH "
SMTP -> get_lines(): $str is "250-ENHANCEDSTATUSCODES "
SMTP -> get_lines(): $data was "250-smtp.gmail.com at your service, [126.96.36.199] 250-SIZE 35882577 250-8BITMIME 250-AUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH 250-ENHANCEDSTATUSCODES "
SMTP -> get_lines(): $data was "250-smtp.gmail.com at your service, [220.127.116.11] 250-SIZE 35882577 250-8BITMIME 250-AUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH 250-ENHANCEDSTATUSCODES "
SMTP -> get_lines(): $str is "250-PIPELINING "
SMTP -> get_lines(): $data was "250-smtp.gmail.com at your service, [126.96.36.199] 250-SIZE 35882577 250-8BITMIME 250-AUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH 250-ENHANCEDSTATUSCODES 250-PIPELINING "
SMTP -> get_lines(): $data was "250-smtp.gmail.com at your service, [18.104.22.168] 250-SIZE 35882577 250-8BITMIME 250-AUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH 250-ENHANCEDSTATUSCODES 250-PIPELINING "
SMTP -> get_lines(): $str is "250-CHUNKING "
SMTP -> get_lines(): $data was "250-smtp.gmail.com at your service, [22.214.171.124] 250-SIZE 35882577 250-8BITMIME 250-AUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH 250-ENHANCEDSTATUSCODES 250-PIPELINING 250-CHUNKING "
SMTP -> get_lines(): $data was "250-smtp.gmail.com at your service, [126.96.36.199] 250-SIZE 35882577 250-8BITMIME 250-AUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH 250-ENHANCEDSTATUSCODES 250-PIPELINING 250-CHUNKING "
SMTP -> get_lines(): $str is "250 SMTPUTF8 "
SMTP -> get_lines(): $data was "250-smtp.gmail.com at your service, [22.214.171.124] 250-SIZE 35882577 250-8BITMIME 250-AUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH 250-ENHANCEDSTATUSCODES 250-PIPELINING 250-CHUNKING 250 SMTPUTF8 "
SMTP -> FROM SERVER: 250-smtp.gmail.com at your service, [220.127.116.11] 250-SIZE 35882577 250-8BITMIME 250-AUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH 250-ENHANCEDSTATUSCODES 250-PIPELINING 250-CHUNKING 250 SMTPUTF8
SMTP -> get_lines(): $data was ""
SMTP -> get_lines(): $str is "334 VXNlcm5hbWU6 "
SMTP -> get_lines(): $data was "334 VXNlcm5hbWU6 "
SMTP -> get_lines(): $data was ""
SMTP -> get_lines(): $str is "334 UGFzc3dvcmQ6 "
SMTP -> get_lines(): $data was "334 UGFzc3dvcmQ6 "
SMTP -> get_lines(): $data was ""
SMTP -> get_lines(): $str is "534-5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbs "
SMTP -> get_lines(): $data was "534-5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbs "
SMTP -> get_lines(): $data was "534-5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbs "
SMTP -> get_lines(): $str is "534-5.7.14 ayHmWfTW3uH_Y0l9QBdB8thX_D2gyq0cU5Ltn0zJWruuXlc4Bvxyeag-Md22UG22XWJJX "
SMTP -> get_lines(): $data was "534-5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbs 534-5.7.14 ayHmWfTW3uH_Y0l9QBdB8thX_D2gyq0cU5Ltn0zJWruuXlc4Bvxyeag-Md22UG22XWJJX "
SMTP -> get_lines(): $data was "534-5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbs 534-5.7.14 ayHmWfTW3uH_Y0l9QBdB8thX_D2gyq0cU5Ltn0zJWruuXlc4Bvxyeag-Md22UG22XWJJX "
SMTP -> get_lines(): $str is "534-5.7.14 kFJOLwtOF7Agw6KdzAL_P3IQZlAY-bSuSgKpM_aD8Rzd7AAIdpfRWkwd9bXW-wWw> "
SMTP -> get_lines(): $data was "534-5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbs 534-5.7.14 ayHmWfTW3uH_Y0l9QBdB8thX_D2gyq0cU5Ltn0zJWruuXlc4Bvxyeag-Md22UG22XWJJX 534-5.7.14 kFJOLwtOF7Agw6KdzAL_P3IQZlAY-bSuSgKpM_aD8Rzd7AAIdpfRWkwd9bXW-wWw> "
SMTP -> get_lines(): $data was "534-5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbs 534-5.7.14 ayHmWfTW3uH_Y0l9QBdB8thX_D2gyq0cU5Ltn0zJWruuXlc4Bvxyeag-Md22UG22XWJJX 534-5.7.14 kFJOLwtOF7Agw6KdzAL_P3IQZlAY-bSuSgKpM_aD8Rzd7AAIdpfRWkwd9bXW-wWw> "
SMTP -> get_lines(): $str is "534-5.7.14 Please log in via your web browser and then try again. "
SMTP -> get_lines(): $data was "534-5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbs 534-5.7.14 ayHmWfTW3uH_Y0l9QBdB8thX_D2gyq0cU5Ltn0zJWruuXlc4Bvxyeag-Md22UG22XWJJX 534-5.7.14 kFJOLwtOF7Agw6KdzAL_P3IQZlAY-bSuSgKpM_aD8Rzd7AAIdpfRWkwd9bXW-wWw> 534-5.7.14 Please log in via your web browser and then try again. "
SMTP -> get_lines(): $data was "534-5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbs 534-5.7.14 ayHmWfTW3uH_Y0l9QBdB8thX_D2gyq0cU5Ltn0zJWruuXlc4Bvxyeag-Md22UG22XWJJX 534-5.7.14 kFJOLwtOF7Agw6KdzAL_P3IQZlAY-bSuSgKpM_aD8Rzd7AAIdpfRWkwd9bXW-wWw> 534-5.7.14 Please log in via your web browser and then try again. "
SMTP -> get_lines(): $str is "534-5.7.14 Learn more at "
SMTP -> get_lines(): $data was "534-5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbs 534-5.7.14 ayHmWfTW3uH_Y0l9QBdB8thX_D2gyq0cU5Ltn0zJWruuXlc4Bvxyeag-Md22UG22XWJJX 534-5.7.14 kFJOLwtOF7Agw6KdzAL_P3IQZlAY-bSuSgKpM_aD8Rzd7AAIdpfRWkwd9bXW-wWw> 534-5.7.14 Please log in via your web browser and then try again. 534-5.7.14 Learn more at "
SMTP -> get_lines(): $data was "534-5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbs 534-5.7.14 ayHmWfTW3uH_Y0l9QBdB8thX_D2gyq0cU5Ltn0zJWruuXlc4Bvxyeag-Md22UG22XWJJX 534-5.7.14 kFJOLwtOF7Agw6KdzAL_P3IQZlAY-bSuSgKpM_aD8Rzd7AAIdpfRWkwd9bXW-wWw> 534-5.7.14 Please log in via your web browser and then try again. 534-5.7.14 Learn more at "
SMTP -> get_lines(): $str is "534 5.7.14 https://support.google.com/mail/answer/78754 f19-20020ac859d3000000b002de4d014733sm11933677qtf.13 - gsmtp "
SMTP -> get_lines(): $data was "534-5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbs 534-5.7.14 ayHmWfTW3uH_Y0l9QBdB8thX_D2gyq0cU5Ltn0zJWruuXlc4Bvxyeag-Md22UG22XWJJX 534-5.7.14 kFJOLwtOF7Agw6KdzAL_P3IQZlAY-bSuSgKpM_aD8Rzd7AAIdpfRWkwd9bXW-wWw> 534-5.7.14 Please log in via your web browser and then try again. 534-5.7.14 Learn more at 534 5.7.14 https://support.google.com/mail/answer/78754 f19-20020ac859d3000000b002de4d014733sm11933677qtf.13 - gsmtp "
SMTP -> ERROR: Password not accepted from server: 534-5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbs 534-5.7.14 ayHmWfTW3uH_Y0l9QBdB8thX_D2gyq0cU5Ltn0zJWruuXlc4Bvxyeag-Md22UG22XWJJX 534-5.7.14 kFJOLwtOF7Agw6KdzAL_P3IQZlAY-bSuSgKpM_aD8Rzd7AAIdpfRWkwd9bXW-wWw> 534-5.7.14 Please log in via your web browser and then try again. 534-5.7.14 Learn more at 534 5.7.14 https://support.google.com/mail/answer/78754 f19-20020ac859d3000000b002de4d014733sm11933677qtf.13 - gsmtp
SMTP -> get_lines(): $data was ""
SMTP -> get_lines(): $str is "221 2.0.0 closing connection f19-20020ac859d3000000b002de4d014733sm11933677qtf.13 - gsmtp "
SMTP -> get_lines(): $data was "221 2.0.0 closing connection f19-20020ac859d3000000b002de4d014733sm11933677qtf.13 - gsmtp "
SMTP -> FROM SERVER: @byemsg
SMTP -> ERROR: Failed to connect to server: php_network_getaddresses: getaddrinfo failed: Name or service not known (0)
</code>
Answer: I needed to use an app password. This is done at https://myaccount.google.com/security
Before creating an app password, you have to turn on 2-factor authentication for the account.


Check if counts are Poisson distributed

Question: I want to check if counts of bird territories in different cells are Poisson distributed. Due to the very small p-value produced by the below code, I have concluded they are not Poisson distributed.
Is this conclusion correct? Are the expected values and degrees of freedom in the chi-squared test correct?
(p.s. I know just by looking at a plot that they are not a Poisson distribution and I also realise the sample size might be too small to genuinely test if they are Poisson distributed. The point of this is to understand how to use the chi-squared test to check if it is Poisson distributed.)
library(dplyr);library(tidyr);library(ggplot2)

tibble(territories = c(15L, 5L, 18L, 16L, 2L, 18L, 19L, 19L, 17L, 11L, 8L, 19L, 18L, 15L, 9L, 17L, 7L, 17L, 13L, 13L, 23L, 18L, 19L, 11L, 20L, 12L, 20L, 7L, 14L, 9L, 13L, 9L, 9L, 11L, 9L, 15L, 10L)) -> df

df %>%
  dplyr::count(territories, sort = FALSE, name = "observed") ->
  df

# add zeros to data
expand.grid(territories = 2:23) %>%
  left_join(df, by = "territories") %>%
  mutate(observed = case_when(is.na(.$observed) ~ 0L, TRUE ~ .$observed)) ->
  df

df %>%
  mutate(expected = sum(df$observed) * dpois(2:23, 14)) ->
  df

stats::chisq.test(df$observed, p = df$expected, rescale.p = TRUE)

pchisq(q = 273, df= 20,lower.tail=FALSE) # manually correct degrees of freedom

df %>%
  pivot_longer(cols = observed:expected, names_to = "observed", values_to = "count") %>%
  ggplot +
  geom_col(aes(territories, count, fill = observed), position = position_dodge())

Comment: dplyr code is not always easy to read and the description is not very clear. What sort of counts are we looking at? What does 'territories' on the x-axis mean?
Comment: Is territory a count variable or a label?
Answer: The Poisson goodness-of-fit test is applied as follows. I use R as an example just as you do.
First, get the frequency table
df <- data.frame(territories = c(15L, 5L, 18L, 16L, 2L, 18L, 19L, 19L, 17L, 11L, 8L, 19L, 18L, 15L, 9L, 17L, 7L, 17L, 13L, 13L, 23L, 18L, 19L, 11L, 20L, 12L, 20L, 7L, 14L, 9L, 13L, 9L, 9L, 11L, 9L, 15L, 10L))

table(df)
territories
 2  5  7  8  9 10 11 12 13 14 15 16 17 18 19 20 23
 1  1  2  1  5  1  3  1  3  1  3  1  3  4  4  2  1

You see thus you have territories 2 repeated once, 5, repeated once, 7 repeated twice and so on, but there are holes in the territory values.
Fit the Poisson distribution to your data, i.e. compute the sample average:
hat_lambda <- mean(df$territories)

Now, for each territory, compute the expected counts. Each is just the probability under the estimated Poisson to observe the specified territory multiplied by the sample size. Before this, in the above table, we have to supply the other territory values that have not been observed but are probable under the estimated Poisson. There is a bit of arbitrariness in how you supply these additional values. You could bin the values in classes in order to avoid having too many classes with low frequencies.
One option could be <2, 3, 4, 6, 21, 22 and >23, which all have frequency zero and we bin the values less than 2 and those $>23$.
# sample size
N <- length(df$territories) + 7 # seven further categories
x <- sort(unique(df$territories)) # categories with positive counts
exp_counts = N*dpois(x, lambda = mean(df$territories))

Now compute the chi-squared statistic and the associated p-value
(chisq_obs <- sum((x-exp_counts)^2/exp_counts) + 7)
# p-value
1-pchisq(chisq_obs, df=length(x)+7-1)

As rightly guessed, the counts are far from being Poisson distributed, i.e. the p-value is extremely small.
Note 1. The number of degrees of freedom is equal to the number of unique observations, e.g. here the length of x, minus the number of estimated parameters, e.g. here equal to one.
Note 2. Since the extra categories provided have zero observed counts, each of them contributes to the chi-square statistic by 1. Thus a consequence of using too many categories is that you will inflate the chi-square statistic as well as the degrees of freedom of its limiting distribution.
Note 3. Since the $\chi_k^2$ is only a limiting distribution valid for large sample sizes, some writers caution the user of this approximation to be certain that the sample size is large enough s.t. each expected count is at least 5. As you can check in this example, such a rule fails. So if you want to follow this rule, you have to consider another (arbitrary) binning of the territory values in classes s.t. each class has expected value $\geq 5$.
Comment: This is a careful account of the procedure, but from a scientific as well as statistical view there is much else to be said. First, Poisson may be a poor fit, but it seems unlikely that any brand-name distribution would work better for mildly irregular data such as these. Second, beyond stating that the data are not well fitted well by a  Poisson the implications of that depend on what else is in mind.  For example, if there are covariates, Poisson regression might still be a good idea for modelling, or at least not worse than alternatives.
Comment: Are zeros not needed for frequencies that are zero. For example, frequencies of 3, 4, 6 etc are missing from `table(df)` - are zeros not needed?
Comment: There has been much advice over several decades about minimum acceptable expected counts but experts don't agree. All expected counts at least 5 is at the hyper-cautious end of the advice.
Comment: @NickCox, Your comments are thoughtful as usual. I'll expand my answer by adding these extra thoughts, although I'm not sure how much relevant they are to the OP's question.
Comment: yes, you are right, we cannot have holes under the Poisson :-) I'll update my answer.

Check if counts are Poisson distributed


Sequence approaching infimum

Question: Given the fact that for a non-empty subset $K ⊂ V$ and $J : V → \mathbb R$ the number $\inf_{v \in K} J(v)$ exists, why does a minimizing sequence always exist?  So I read somewhere this: A minimizing sequence of a function $J$ on the set $K$ is a sequence $(u_n)_{n∈ \mathbb N}$ such that $u_n \in K$ for all $n$ and $\lim_{n\to\infty}J(u_n) = \inf_{v∈K} J(v)$. By definition of the infimum value of $J$ on $K$ there always exist minimizing sequences! It seems like a logical consequence but I don't get it...
Comment: Welcome to math.SE: since you are new, I wanted to let you know a few things about the site. In order to get the best possible answers, it is helpful if you say in what context you encountered the problem, and what your thoughts on it are; this will prevent people from telling you things you already know, and help them give their answers at the right level. Also, on this site we use MathJaX to format our maths. [Here](http://meta.math.stackexchange.com/q/5020/145141) you can find a basic tutorial.
Comment: You nee to add some more context.
Comment: so I read somewhere this : A minimizing sequence of a function J on the set K is a sequence(un) n∈IN such that
un ∈ K ∀n and lim n→+∞J(un)=inf v∈K J(v).
By definition of the infimum value of J on K there always exist minimizing sequences!  It seems like a logical consequence but I don't get it...
Comment: Use "$" around your math and \ to perform commands.
Comment: Right click on math and show them as TeX commands for a feel of how this site works.
Answer: Part of the reason you might be having trouble "getting" this result is that it's impossible to visualize! (At least, it is impossible to visualize unless you have more information about $V$ and $K$ than you've given us.) The result tells you that the sequence exists, but it doesn't give you any way of knowing what the points of the sequence actually are, nor any particular means of choosing them.
It turns out that the quoted result (as written) is equivalent to the

Axiom of Countable Partial Choice: Given a sequence of non-empty sets $(A_n)_{n\in\Bbb N},$ there is an infinite subset $I$ of $\Bbb N$ and a function $f:I\to\bigcup_{n\in\Bbb N}A_n$ such that $f(n)\in A_n$ for all $n\in I.$

Note that the above result tells us little about the sets $A_n,$ the set $I,$ and the function $f.$ So, while we might be able to grasp this result conceptually, we wouldn't necessarily be able to take a given sequence of sets $A_n$ and determine what $I$ and $f$ satisfy the desired properties. Let's prove the equivalence!
On the one hand, suppose the minimizing sequence result holds, and that we have a sequence $(A_n)_{n\in\Bbb N}$ of non-empty sets. Let $$V=K=\bigcup_{n\in\Bbb N}A_n\times\{n\}.$$ Note that the elements of $K$ have the form $\langle a,n\rangle,$ where $a\in A_n\subseteq A$ and $n\in\Bbb N.$ Define $J:V\to\Bbb R$ by $J(a,n)=\frac1{n+1}.$ Since the sets $A_n$ are non-empty, then so are the sets $A_n\times\{n\}.$ Hence, for each $n\in\Bbb N,$ there is some $\langle a,n\rangle\in A_n\times\{n\},$ meaning that $J(a,n)=\frac1{n+1}.$ Thus, the range of $J$ is $\left\{\frac1{n+1}:n\in\Bbb N\right\}.$ Readily, the infimum of this set is $0.$ By the desired result, there is a minimizing sequence--that is, a sequence $\bigl(\langle a_k,n_k\rangle\bigr)_{k\in\Bbb N}$ of points of $K$ such that $\lim_{k\to\infty}J(a_k,n_k)=0.$ In other words, $\lim_{k\to\infty}\frac1{n_k+1}=0.$ Now, if the sequence $(n_k)_{k\in\Bbb N}$ took on only finitely-many values, then we couldn't have $\lim_{k\to\infty}\frac1{n_k+1}=0.$ Hence, $(n_k)_{k\in\Bbb N}$ takes on infinitely-many values. Letting $I=\{n\in\Bbb N:n=n_k\text{ for some }k\in\Bbb N\},$ we therefore have that $I$ is an infinite subset of $\Bbb N.$ Given any $n\in I,$ there is some least $k\in\Bbb N$ such that $n=n_k;$ and given that least $k,$ we define $f(n)=a_k.$ Readily, then, we can show that $f:I\to \bigcup_{n\in\Bbb N}A_n,$ and $f(n)\in A_n$ for all $n\in I,$ so ACPC holds.
On the other hand, suppose ACPC holds, and suppose that $K$ is a nonempty subset of $V$ and $J:V\to\Bbb R$ a function such that $\inf_{v\in K}J(v)$ exists. Let $x=\inf_{v\in K}J(v),$ and for each $n\in\Bbb N,$ let $$A_n:=\left\{v\in K:J(v)<x+\frac1{n+1}\right\}.$$ By definition of $x,$ we can readily show that each $A_n$ is non-empty. Hence, there is an infinite subset $I$ of $\Bbb N$ and a function $f:I\to\bigcup_{n\in\Bbb N}A_n$ such that $f(n)\in A_n$ for all $n\in I.$ Since $I$ is an infinite subset of $\Bbb N,$ then there is a function $h:\Bbb N\to I$ sending the least element of $\Bbb N$ to the least element of $I$, the second-least element of $\Bbb N$ to the second-least element of $I$, and so on. Finally, letting $v_n=f\bigl(h(n)\bigr)$ for all $n\in\Bbb N,$ we find that $(v_n)_{n\in\Bbb N}$ is a sequence of points of $K,$ and we can prove by construction that $\lim_{n\to\infty}J(v_n)=x=\inf_{v\in K}J(v),$ as desired.
Answer: Hint:

Gap Lemma: Let $\varnothing \neq A \subseteq \mathbb R$ and $x = \inf A$. Given any $\varepsilon > 0$, there is an $a \in A$ such that $a - x < \varepsilon$.

Then, we can use the gap lemma with $\varepsilon_n = \frac{1}{n}$ to get a sequence $(a_n)_{n \in \mathbb N}$ such that $\lim_{n\to\infty} a_n = x$.
Comment: I see that... it was quite easy.. thank you very much for your time!!

Sequence approaching infimum


jqGrid with inlineNav: is there a way to force the Add button to re-enable?

Question: I'm using jqGrid 4.3.2 with the inlineNav option.  All editing on the grid is done locally using loadonce: true and clientArray.  When the user finishes editing, they click a save button on the form and the entire grid is posted to the server.  This works great, for the most part, but I've run into an oddity.  If the user adds a new row and then clicks the save button before hitting enter to confirm the edit or deselecting the newly added row, the add button on the inline navigator remains disabled even after calling saveRow before posting and reloading.  I've tried resetSelection and restoreRow after the saveRow call, but neither of these work.  My save code:
$("#submitButton").click(function () {
    $("#theGrid").jqGrid('saveRow', $("#selectedRowId").val(), false, 'clientArray');
    if (!ValidateGridData())
        return false;
    var rowData = $("#theGrid").jqGrid('getRowData');
    var dataToSend = JSON.stringify(rowData);
    $.ajax({
        url: '@Url.Action("UpdateGridData")',
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        data: dataToSend,
        dataType: 'json',
        async: false,
        success: function (data, textStatus, jqXHR) {
            $("#theGrid").jqGrid('setGridParam', { datatype: 'json' });
            $("#theGrid").trigger('reloadGrid');
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert('Error saving data: ' + textStatus + " " + errorThrown);
        }
    });
    return true;
});

Is there a way I can convince the inline navigator that the new row is saved and the user can add more rows?
Answer: The buttons added in the navigator by the inlineNav method has ids which constructed from the grid id and the corresponding suffix:

Add: gridId + "_iladd" (for example "list_iladd")
Edit: gridId + "_iledit" (for example "list_iledit")
Save: gridId + "_ilsave" (for example "list_ilsave")
Cancel: gridId + "_ilcancel" (for example "list_ilcancel")

To enable the button you should remove 'ui-state-disabled' CSS class:
var gridId = "list";
$("#" + gridId + "list_iladd").removeClass('ui-state-disabled');

To disable the button one can use .addClass('ui-state-disabled') instead.
Additionally I don't recommend you to use any inline editing methods like saveRow directly. In the case you will probably not have the problem which you try to solve. Look at the code from the answer. It defines editingRowId and myEditParam as
var $grid = jQuery("#list"),
    editingRowId,
    myEditParam = {
        keys: true,
        oneditfunc: function (id) { editingRowId = id; },
        afterrestorefunc: function (id) { editingRowId = undefined; }
    };

and then use inlineNav with myEditParam parameter:
$grid.jqGrid('inlineNav', '#pager',
    { edit: true, add: true, editParams: myEditParam,
        addParams: {addRowParams: myEditParam } });

In the case you can be sure that editingRowId get you the id of the current editing row or undefined if no row are editing. So you can use $(gridIdSelector + "_iledit").click(); instead of editRow to edit the current selected row. In the same you can use setSelection if needed and simulate click on any other inline editing navigator buttons.
UPDATED: If you need you can still combine calls of saveRow inside of onSelectRow, but you can first use the variable editingRowId and seconds use myEditParam which will be common for all editing ways which you use:
onSelectRow: function (id) {
    var $this = $(this);
    if (editingRowId !== id) {
        if (editingRowId) {
            // save or restore currently editing row
            $this.jqGrid("saveRow", editingRowId, myEditParam);
            // or $this.jqGrid("restoreRow", editingRowId, myEditParam);
        }
        $this.jqGrid("editRow", editingRowId, myEditParam);
    }
}

If you need some other options of inline editing methods you can include there in the myEditParam. You will see that editingRowId is much better to use as lastSel variable which you find in the most inline editing examples.
Comment: I was just heading down that path, except was using a sloppy `replace` on the `attr('class')` instead of `.removeClass`.  Works perfectly.  Thanks!
Comment: Oleg, I've been going over your additional comments about not using saveRow directly.  I was using `onSelectRow` to call `saveRow` on the previously selected row, similar to code from http://stackoverflow.com/q/2359011/27457".  Do you not recommend using this approach?
Comment: @AJ.: I understand what you mean. I think in the case you can still good *combine* inline editing with other inline editing methods and you will have no problems if you follows some additional rules: see "**UPDATED**" part of my answer.


Dúvida com layouts dinâmicos

Question: Costumo montar as views's das aplicações php que utilizo com operadores condicionais.
Por exemplo, usuário não logado, seto uma variável inicial na sessão:
$logado = FALSE;

Caso o usuário esteja logado, atribuo TRUE e dentro das view's, torno algumas coisas dinâmicas, por exemplo, o botão de login.
if (!$logado) {
    //exibe formulário de login
} else {
    //Exibe mensagem: bem vindo user xxxx, clique aqui para efetuar logoff.
}

E utilizo isto em outras coisas também, por exemplo, usuário logado, pode salvar uma nova informação em um form, usuário não logado, apenas visualiza o resultado do select de informações já salvas.
A minha dúvida é: Isto é uma boa prática?
Utilizar if no contexto de estruturar o html e torná-lo adaptável de acordo com variáveis setadas em sessão?
Answer: Gerar views dinâmicas, de acordo com determinados parâmetros, é um desafio em qualquer linguagem.
Há basicamente três abordagens principais para lidar com isso:
Scripts
A abordagem de misturar scripts com HTML é a mais eficiente, porém pode facilmente levar a código difícil de entender, dar manutenção e propenso a erros.
Template Engines
Usar um mecanismo de templates ajuda a separar lógica da apresentação. O efeito colateral é o desempenho, já que os templates precisam ser interpretados para gerar a saída.
Alguns mecanismos permitem a "compilação" dos templates para resolver o problema do desempenho, mas isso exigirá um cuidado a mais na implementação.
Particularmente eu gosto da abordagem baseada em templates.
Componentes
Alguns frameworks geram as views através de componentes, que na verdade são uma coleção de objetos que encapsulam o HTML gerado.
Em PHP isso não é tão comum quanto em Java, por exemplo, mas se me lembro bem o Yii funciona dessa maneira.
A vantagem é que há um algo grau de reaproveitamento de código, mas devido à grande abstração e complexidade você pode facilmente perder o controle do que está fazendo, além de tornar tarefas que outrora seriam triviais em algo que depende de um conhecimento relativamente profundo do framework.
Considerações
Não há nenhum problema em usar alguns ifs ou laços no código, desde que você consiga fazer a separação disso com a lógica do sistema.
Um exemplo bem simples de como usar a própria linguagem PHP como um tipo de template engine, evitando assim a grande quantidade de classes incluídas ao se usar frameworks, pode ser visto em alguns templates do Wordpress. Exemplo:
<?php if (have_posts()) : ?>
    <?php while (have_posts()) : the_post(); ?>

    <?php endwhile; ?>
<?php endif; ?>

Dúvida com layouts dinâmicos


Does the category of finite sets and injective functions (i.e., monomorphisms) have all coproducts?

Question: My impression is that it does not have all coproducts because:
If $f:A \rightarrow C$ and $g:B \rightarrow C$ are injective functions with $f(a)=g(b) \in C$ for some $a \in A$ and some $b \in B$, then the unique function $(f,g):A+B \rightarrow C$ is not injective. As injectivity is violated, some coproducts cannot be computed in such a category.
Is this correct?
Comment: Hi - welcome to MSE! I don't really understand Thomas Andrews' comment - it seems to me that your argument doesn't work in $\mathbf{Set}$, because not all morphisms in $\mathbf{Set}$ are monic. I think your idea is good, and it's possible to get a proof from that idea. Can you argue that if $\{1, 2\}$ has a coproduct with itself, then $(\mathrm{id}, \mathrm{id}): \{1, 2\} + \{1, 2\} \to \{1, 2\}$ cannot be monic in this category? (think about the definition of coproduct.. and be careful to argue things are distinct)
Comment: You have only shown that the subcategory is not closed under coproducts of sets. This is not enough. Consider, say, the category of torsion abelian groups. It has products, namely the torsion subgroup of the product of abelian groups. It is not closed under (infinite) products of abelian groups, though. Dualize, you get an example for coproducts.
Comment: That same reasoning would work in the category of all sets, so it seems like there is something wrong with your reasoning. What do you think $A+B$ means?
Answer: Your argument, as written, appears to me to assume that the coproduct, if it existed, is just the ordinary disjoint union. But it could be the case that the coproduct exists but is something else; in that case the argument would need to be modified, although I do think it can be salvaged.
Here is an alternative argument which is just based on counting. Let $A, B$ be two finite sets. If the coproduct $A \sqcup B$ existed then by definition it would have to satisfy
$$\text{Hom}(A \sqcup B, X) \cong \text{Hom}(A, X) \times \text{Hom}(B, X)$$
for all finite sets $X$. Write $a = |A|, b = |B|, x = |X|$ for the sizes of these sets. The number of injections between two finite sets is the falling factorial
$$|\text{Hom}(A, X)| = (x)_a = x(x-1) \dots (x-a+1).$$
It follows that
$$|\text{Hom}(A, X)| \times |\text{Hom}(B, X)| = (x)_a (x)_b$$
which is a polynomial of degree $a + b$ in $x$; this means that $A \sqcup B$ must have size $a + b$, but this would imply $(x)_a (x)_b = (x)_{a+b}$ which is false by an inspection of the roots for any $a, b \ge 1$.
In other words, although the definition of the coproduct asks for a natural bijection between $\text{Hom}(A \sqcup B, X)$ and $\text{Hom}(A, X) \times \text{Hom}(B, X)$, a counting argument shows that if $A, B$ are non-empty then there is not even a bijection (for all $X$), natural or otherwise.
Comment: Awesome proof !
Answer: The category in question fails to have coproducts. I will show that in particular $\{1\} + \{1\}$ fails to exist.
Take the finite set $\{1\}$ and consider the identity map $\mathrm{id}: \{1\} \rightarrow \{1\}$. This is a monomorphism (in fact an isomorphism),  so by the universal property of the coproduct, we can deduce that if the coproduct $\{1\} + \{1\}$ exists, then we have a monomorphism $f: (\{1\} + \{1\}) \hookrightarrow \{1\}$.
This means that $\{1\} + \{1\}$ has at most one element: if we have elements $x,y : \{1\} \rightarrow (\{1\} + \{1\})$, then $f \circ x = f \circ y$, and since $f$ is a monomorphism, we get $x = y$.
Now consider the two elements (constant maps) $c_1,c_2:\{1\} \hookrightarrow\{1,2\}$. We know that $c_1 \neq c_2$. But by the universal property of the coproduct, if it were to exist, we would have a unique monomorphism $g: (\{1\} + \{1\}) \hookrightarrow \{1,2\}$ so that $c_1,c_2$ factor as $g \circ \iota_1 = c_1$ and $g \circ \iota_2 = c_2$ for respective $\iota_1,\iota_2: \{1\} \rightarrow (\{1\} + \{1\})$. Since $\iota_1$ and $\iota_2$ are elements of $\{1\} + \{1\}$, we'd then have $\iota_1 = \iota_2$ by the previous observation, and consequently $c_1 = g \circ \iota_1 = g \circ \iota_2 = c_2$, a contradiction.
Therefore, the category of finite sets and monomorphisms fails to have coproducts. The failure of existence of coproducts in categories such as $\mathrm{Set}_{mono}$ and $\mathrm{Grph}_{mono}$ is one possible motivation for introducing "proxy" constructions, such as the proxy pushouts Bumpus and I used in our categorial treatment of treewidth, and the lens proxy pullbacks of (Rosebrugh and) Di Meglio.
Answer: No two nonempty finite sets have a coproduct in the category of finite sets and injections.
Suppose that $A$ and $B$ are two nonempty finite sets and $C$ is their coproduct with injections $i:A \to C$ and $j:B \to C$.
Then, one needs to find a finite set $D$ with two injections $f:A \to D$ and $g:B \to D$ such that there is no injection $h:C \to D$ for which $h \circ i=f$ and $h \circ j=g$, which would contradict $C$ being a coproduct.
Without loss of generality, assume that $|A| \le |B|$. Then, there is an injection $A \to B$, and of course, the identity is an injection $B \to B$. If there were an injection $C \to B$, then it would follow that $|C|=|B|$ and hence $j$ is a bijection (as any injection between two finite sets of the same size is a bijection). From this and the fact that $C$ is a coproduct, it would follow that any finite set that has an injection from $B$ would have exactly one injection from $A$. This could only happen if $A$ is empty, but it was assumed to be nonempty, which is a contradiction.
So, there is no injection $C \to B$, which means that the coproduct could not exist.
The above proof works regardless of whether $C$ is the disjoint union (the coproduct in the category of finite sets and all functions, not just injective ones) or not.
Comment: @QiaochuYuan Because $j$ is an injection between two finite sets of the same size.
Comment: I don't quite follow this argument. Why can you conclude that $j$ is a bijection?
Comment: I think this proof is not correct. It also assumes that A+B is the coproduct in the category of sets. It is the same mistake the OP did.
Comment: @MartinBrandenburg To avoid confusion with the disjoint union, I have denoted the coproduct in the category of finite sets and injections as $C$ instead of $A+B$.
Comment: Ah the proof is much better now. +1
Answer: The proof by the OP only shows that the subcategory is not closed under coproducts of sets. This is not enough. A subcategory can have products which are different from the ambient category.
Actually, in our case, we can show that this behaviour doesn't appear.
Let $A,B$ be two finite sets.  Assume that $A,B$ have a coproduct $C$ in the category of finite sets with injections, let $\eta_A : A \to C$, $\eta_B : B \to C$ be the inclusions. We will show that $C$ is the disjoint union of the sets $\mathrm{im}(\eta_A)$ and $\mathrm{im}(\eta_B)$.
Let $A+B$ be the coproduct in the category of all sets and maps (just the disjoint union) with the inclusions $\iota_A : A \to A + B$ and $\iota_B : B \to A + B$. Notice that they are injective. So by the universal property of $C$ there is a morphism $f : C \to A$ with $f \circ \eta_A = \iota_A$ and $f \circ \eta_B = \iota_B$. It follows easily that $\mathrm{im}(\eta_A),\mathrm{im}(\eta_B) \subseteq C$ are disjoint since this is the case for the sets $\mathrm{im}(\iota_A),\mathrm{im}(\iota_B) \subseteq A+B$.
Consider $C' := \mathrm{im}(\eta_A) \cup \mathrm{im}(\eta_B)$. We can corestrict $\eta_A,\eta_B$ to get $\eta'_A : A \to C'$, $\eta'_B : B \to C'$, which are still injective. By the universal property of $C$ there is a morphism $f : C \to C'$ with $f \circ \eta_A = \eta'_A$ and $f \circ \eta_B = \eta'_B$. Let $j : C' \to C$ be the inclusion. Then $j \circ f : C \to C$ is an injective map with $j \circ f \circ \eta_A = j \circ \eta'_A = \eta_A$, likewise for $B$. Hence, the (uniqueness of the) universal property of $(C,\eta_A,\eta_B)$ implies $j \circ f = \mathrm{id}_C$. Therefore, $j$ is surjective, i.e. $C' = C$.
This shows that $(C,\eta_A,\eta_B)$ actually is isomorphic to $(A+B,\iota_A,\iota_B)$. Again: this is not the case for all subcategories!
And now we can finish the proof by showing that $(A+B,\iota_A,\iota_B)$ is not a coproduct (when $A,B$ are non-empty), like the OP did.


Draw lines between regions based on factor in ggplot

Question: I am using geom_tile and facet_grid to plot some data which is factored on its ptype column. A MWE follows:
library(ggplot2)

data<-"T So Sigma Gamma Rtot Sof Sff ptype
8078 10 3 0 0.6 3 3 3 factor1
8089 10 3 0.1 0.6 3 3 3 factor1
8100 10 3 0.2 0.6 3 3 3 factor1
8111 10 3 0.3 0.6 3 3 3 factor1
8122 10 3 0.4 0.6 3 3 3 factor1
8133 10 3 0.5 0.6 3 3 3 factor1
8144 10 3 0.6 0.6 3 3 3 factor1
8155 10 3 0.7 0.6 3 3 3 factor1
8166 10 3 0.8 0.6 3 3 3 factor1
8177 10 3 0.9 0.6 3 3 3 factor1
8188 10 3 1 0.6 3 3 3 factor1
49304 20 3 0 0.6 3 3 3 factor1
49315 20 3 0.1 0.6 3 3 3 factor1
49326 20 3 0.2 0.6 3 3 3 factor1
49337 20 3 0.3 0.6 3 3 3 factor1
49348 20 3 0.4 0.6 3 3 3 factor1
49359 20 3 0.5 0.6 3 3 3 factor1
49370 20 3 0.6 0.6 3 3 3 factor1
49381 20 3 0.7 0.6 3 3 3 factor1
49392 20 3 0.8 0.6 3 3 3 factor1
49403 20 3 0.9 0.6 3 3 3 factor1
49414 20 3 1 0.6 3 3 3 factor1
76198 30 3 0 0.6 3.76171 3 3.76171 factor2
76209 30 3 0.1 0.6 3.76171 3 3.76171 factor2
76220 30 3 0.2 0.6 3.76171 3 3.76171 factor2
76231 30 3 0.3 0.6 3.76171 3 3.76171 factor2
76242 30 3 0.4 0.6 3.76171 3 3.76171 factor2
76253 30 3 0.5 0.6 3.76171 3 3.76171 factor2
76264 30 3 0.6 0.6 3.76171 3 3.76171 factor2
76275 30 3 0.7 0.6 3.76171 3 3.76171 factor2
76286 30 3 0.8 0.6 3.76171 3 3.76171 factor2
76297 30 3 0.9 0.6 3.84754 0.1 0.16195 factor3
76309 30 3 1 0.6 3.84754 0.1 0.16195 factor3
127588 40 3 0 0.6 5.35608 3 5.35608 factor2
127599 40 3 0.1 0.6 5.35608 3 5.35608 factor2
127610 40 3 0.2 0.6 5.35608 3 5.35608 factor2
127623 40 3 0.3 0.6 5.35608 3 5.35608 factor2
127634 40 3 0.4 0.6 5.35825 0 0 factor3
127645 40 3 0.5 0.6 5.35825 0 0 factor3
127656 40 3 0.6 0.6 5.47198 0.2 0.51703 factor3
127669 40 3 0.7 0.6 5.56348 0.2 0.51703 factor3
127680 40 3 0.8 0.6 5.73882 0.8 1.85069 factor3
127691 40 3 0.9 0.6 6.03841 0.9 2.05019 factor3
127702 40 3 1 0.6 6.37118 1.6 3.30385 factor3
162297 50 3 0 0.6 7.36898 3 7.36898 factor2
162309 50 3 0.1 0.6 7.36898 3 7.36898 factor2
162321 50 3 0.2 0.6 7.36898 3 7.36898 factor2
162333 50 3 0.3 0.6 7.49796 0.1 0.42697 factor3
162344 50 3 0.4 0.6 7.64096 0.1 0.42697 factor3
162357 50 3 0.5 0.6 7.78737 0.4 1.54882 factor3
162371 50 3 0.6 0.6 8.358 0.8 2.78492 factor3
162389 50 3 0.7 0.6 8.92932 1.1 3.59043 factor3
162404 50 3 0.8 0.6 9.58623 1.7 4.97184 factor3
162416 50 3 0.9 0.6 10.2468 2.1 5.77926 factor3
162448 50 3 1 0.6 10.8984 2.9 7.20516 factor3
195012 80 3 0 0.6 15.9047 3 15.9047 factor2
195028 80 3 0.1 0.6 17.0201 0.1 1.68242 factor3
195058 80 3 0.2 0.6 18.8161 0.4 5.00423 factor3
195086 80 3 0.3 0.6 21.2521 0.8 7.83781 factor3
195128 80 3 0.4 0.6 23.3847 1.4 10.8074 factor3
195175 80 3 0.5 0.6 25.4261 2 13.0496 factor3
195304 80 3 0.6 0.6 27.1939 2.6 14.8517 factor3
195342 80 3 0.7 0.6 28.8538 3.4 16.8773 factor3
195373 80 3 0.8 0.6 30.3827 3.8 17.7612 factor3
195418 80 3 0.9 0.6 31.8626 4.8 19.7527 factor3
195513 80 3 1 0.6 33.201 5.7 21.341 factor3
231307 60 3 0 0.6 9.80308 3 9.80308 factor2
231319 60 3 0.1 0.6 9.80308 3 9.80308 factor2
231330 60 3 0.2 0.6 10.0912 0.1 0.68484 factor3
231343 60 3 0.3 0.6 10.4219 0.3 1.85263 factor3
231354 60 3 0.4 0.6 11.1548 0.6 3.2646 factor3
231367 60 3 0.5 0.6 12.1336 1.1 5.1274 factor3
231378 60 3 0.6 0.6 13.1552 1.6 6.62604 factor3
231389 60 3 0.7 0.6 14.1498 1.8 7.15294 factor3
231401 60 3 0.8 0.6 15.1461 2.6 9.00079 factor3
231412 60 3 0.9 0.6 16.1305 3.2 10.1851 factor3
231423 60 3 1 0.6 17.0404 4 11.5972 factor3
263033 90 3 0 0.6 19.5131 3 19.5131 factor2
263050 90 3 0.1 0.6 22.1254 0.2 4.33427 factor3
263066 90 3 0.2 0.6 25.5275 0.6 8.83941 factor3
263079 90 3 0.3 0.6 28.7836 1.1 12.233 factor3
263094 90 3 0.4 0.6 31.494 1.7 15.1418 factor3
263109 90 3 0.5 0.6 33.8865 2.3 17.3951 factor3
263122 90 3 0.6 0.6 35.9751 3.1 19.785 factor3
263140 90 3 0.7 0.6 37.8814 4.1 22.2404 factor3
263156 90 3 0.8 0.6 39.6486 4.6 23.3014 factor3
263171 90 3 0.9 0.6 41.2937 5.5 25.0511 factor3
263187 90 3 1 0.6 42.8274 6.4 26.6386 factor3
278614 70 3 0 0.6 12.6641 3 12.6641 factor2
278634 70 3 0.1 0.6 12.8453 0.1 1.08362 factor3
278649 70 3 0.2 0.6 13.6719 0.2 1.99456 factor3
278682 70 3 0.3 0.6 14.9937 0.5 4.13083 factor3
278741 70 3 0.4 0.6 16.5076 1 6.65247 factor3
278768 70 3 0.5 0.6 18.0436 1.6 8.91378 factor3
278798 70 3 0.6 0.6 19.522 2.1 10.426 factor3
278842 70 3 0.7 0.6 20.8664 2.5 11.4774 factor3
278881 70 3 0.8 0.6 22.1743 3.5 13.7218 factor3
278931 70 3 0.9 0.6 23.3991 4.1 14.8892 factor3
279090 70 3 1 0.6 24.6061 4.9 16.2968 factor3
370330 100 3 0 0.6 23.4521 3 23.4521 factor2
370344 100 3 0.1 0.6 28.6985 0.3 7.83825 factor3
370365 100 3 0.2 0.6 33.7053 0.8 13.3056 factor3
370386 100 3 0.3 0.6 37.4726 1.2 16.0314 factor3
370406 100 3 0.4 0.6 40.6543 1.9 19.5437 factor3
370427 100 3 0.5 0.6 43.3269 2.6 22.1924 factor3
370463 100 3 0.6 0.6 45.7282 3.3 24.3216 factor3
370492 100 3 0.7 0.6 47.8327 4.4 27.0937 factor3
370520 100 3 0.8 0.6 49.7812 5 28.3945 factor3
370557 100 3 0.9 0.6 51.6038 5.7 29.7796 factor3
370602 100 3 1 0.6 53.3879 7.2 32.4554 factor3
412193 110 3 0 0.6 27.6951 3 27.6951 factor2
412204 110 3 0.1 0.6 36.5918 0.4 12.0252 factor3
412215 110 3 0.2 0.6 42.7655 0.9 17.4787 factor3
412226 110 3 0.3 0.6 47.1396 1.6 21.9812 factor3
412237 110 3 0.4 0.6 50.7359 2.2 24.7757 factor3
412248 110 3 0.5 0.6 53.6021 2.9 27.3664 factor3
412259 110 3 0.6 0.6 56.2749 3.7 29.762 factor3
412270 110 3 0.7 0.6 58.5612 4.8 32.4988 factor3
412281 110 3 0.8 0.6 60.7087 5.5 34.0162 factor3
412292 110 3 0.9 0.6 62.673 6.7 36.3154 factor3
412303 110 3 1 0.6 64.5379 7.8 38.2264 factor3
430210 120 3 0 0.6 32.1833 3 32.1833 factor2
430221 120 3 0.1 0.6 45.6131 0.4 15.1777 factor3
430232 120 3 0.2 0.6 52.7576 1 22.0867 factor3
430243 120 3 0.3 0.6 57.6179 1.6 26.0984 factor3
430254 120 3 0.4 0.6 61.516 2.3 29.5158 factor3
430265 120 3 0.5 0.6 64.6629 3.2 32.8588 factor3
430276 120 3 0.6 0.6 67.5344 3.8 34.6713 factor3
430288 120 3 0.7 0.6 69.994 4.5 36.5286 factor3
430299 120 3 0.8 0.6 72.2754 5.8 39.5058 factor3
430310 120 3 0.9 0.6 74.3846 6.6 41.0843 factor3
430321 120 3 1 0.6 76.3764 8.3 44.0881 factor3
466534 130 3 0 0.6 36.9146 3 36.9146 factor2
466545 130 3 0.1 0.6 55.7089 0.5 20.4219 factor3
466556 130 3 0.2 0.6 63.5321 1.1 27.0676 factor3
466567 130 3 0.3 0.6 68.8209 1.9 32.1692 factor3
466578 130 3 0.4 0.6 72.9612 2.6 35.3899 factor3
466589 130 3 0.5 0.6 76.4129 3.4 38.296 factor3
466600 130 3 0.6 0.6 79.3824 4 40.1256 factor3
466611 130 3 0.7 0.6 82.0293 4.9 42.4973 factor3
466622 130 3 0.8 0.6 84.461 6.4 45.847 factor3
466633 130 3 0.9 0.6 86.6854 6.9 46.8273 factor3
466644 130 3 1 0.6 88.7074 8.7 50.0145 factor3
475416 140 3 0 0.6 41.8711 3 41.8711 factor2
475427 140 3 0.1 0.6 66.4409 0.5 24.4193 factor3
475438 140 3 0.2 0.6 75.0445 1.1 31.5349 factor3
475449 140 3 0.3 0.6 80.6704 1.9 36.9064 factor3
475460 140 3 0.4 0.6 85.0171 2.6 40.2685 factor3
475471 140 3 0.5 0.6 88.651 3.5 43.6432 factor3
475482 140 3 0.6 0.6 91.813 4.3 46.0965 factor3
475493 140 3 0.7 0.6 94.6003 5.5 49.1544 factor3
475504 140 3 0.8 0.6 97.1285 6.4 51.1477 factor3
475515 140 3 0.9 0.6 99.521 7.4 53.1594 factor3
475526 140 3 1 0.6 101.678 9 55.9788 factor3"

dsub<-read.table(text=data)
dsub<-data.frame(dsub)
dsub$ptype<-factor(dsub$ptype,levels=c("factor1","factor2","factor3"))

p<- ggplot(dsub, aes(x=T, y=Sigma,fill=cut(Rtot, c(0,10,20,30,40,50,60,70,Inf))))
p<- p + geom_tile() + scale_fill_brewer(type="seq",palette = "YlGn")+facet_grid(~ptype)
p<- p + scale_x_continuous(expand=c(0,0)) + scale_y_continuous(expand=c(0,0))
p

Plotting it appears as follows:

Notice that the three different sections fit together like puzzle pieces! The factor indicates where the boundary is.
I'd like to combine these sections together in the same graph, with some thicker black lines separating each region. Is there a way to do this?
Comment: [A dataset to work on would be nice.](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example)
Comment: @maj: edited to include data and a MWE with that data. Thanks for the suggestion.
Comment: related: [Overlay ggplot grouped tiles with polygon border depending on extra factor](http://stackoverflow.com/questions/25704567/overlay-ggplot-grouped-tiles-with-polygon-border-depending-on-extra-factor)
Answer: I tried to replicate the answer from the question with your values - I had to change dsub slightly though to make it work (T/10, (Sigma*10)+1)...
#### I changed the values here ####
dsub$T<-dsub$T/10
dsub$Sigma<-(dsub$Sigma*10) +1
###################################

ymax <- max(dsub$Sigma)
xmax <- max(dsub$T)

m <- matrix(0, nrow=ymax, ncol=xmax)
m[as.matrix(dsub[,c(3,1)])] <- dsub[,8]

has.breaks<-function(x) ncol(x)==2 & nrow(x)>0

hw<-do.call(rbind.data.frame, Filter(has.breaks, Map(function(i,x)
  cbind(y=i,x=which(diff(c(0,x,0))!=0)), 1:nrow(m), split(m, 1:nrow(m)))))
vw<-do.call(rbind.data.frame, Filter(has.breaks, Map(function(i,x)
  cbind(x=i,y=which(diff(c(0,x,0))!=0)), 1:ncol(m), as.data.frame(m))))

ggplot(data=dsub, aes(x=T,y=Sigma))+
  geom_tile(aes(fill=cut(Rtot, c(0,10,20,30,40,50,60,70,Inf))))+
  scale_fill_brewer(type="seq",palette = "YlGn")+
  geom_segment(data=hw, aes(x=x-.5, xend=x-.5, y=y-.5, yend=y+.5))+
  geom_segment(data=vw, aes(x=x-.5, xend=x+.5, y=y-.5, yend=y-.5))+
  scale_x_continuous(expand=c(0,0))+
  scale_y_continuous(expand=c(0,0))+
  theme(axis.line = element_line(colour = "white"),
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        panel.border = element_blank(),
        panel.background = element_blank())


Android Collection for First In All Out

Question: I have a problem where I need to use a type of collection in my android application. The collection should insert items at the top and will remove from the top too but also clear all the bottom most items from it.
For example, if I have following in the collection.
1 | 2 | 3 | 4 | 5

I insert "6".
1 | 2 | 3 | 4 | 5 | 6

I remove "6"
Empty

I insert "7"
7

And I insert "8"
7 | 8

Comment: If you are always removing from the top then why not just clear the structure every time? Maybe some clarification is in order here. Is order maintained as your sample seems to indicate?
Comment: This is one way to do that but how to make it thread safe as 2 different threads are responsible for inserting and removing.
Comment: Ahh maybe you should clarify your original question with all of your requirements. You also did not mention if maintaining order is required. As Peter mentioned a LinkedList can do this for you as well.
Answer: LinkedList has all needed methods enabling you to add item to front or end of list. You can remove all with clear().

Android Collection for First In All Out


What's this vertical dash called and what does it mean?

Question: I found this vertical dash on some sheet music and I can't figure out what it is or what does it mean. I've tried looking through Wikipedia's list of symbols, but  I couldn't find it there and me searching for a vertical line on the staff only yealded results about barlines

The image is a snippet from Lutheran church music for the organ, specifically, it's Bach's Jesu, wahres Brot des Lebens or a similar piece by Johan Crüger/Johan Frank deck thyself my soul with gladness. I don't have the sheet music at hand at the moment so I can't be sure which
Edit2:
Did some looking around and found a picture of the full piece on my harddrive.
Comment: Closely related if not a duplicate: https://music.stackexchange.com/questions/70009/what-is-the-meaning-of-this-small-vertical-line
Comment: Also either closely related or an outright duplicate: https://music.stackexchange.com/questions/73894/whats-the-meaning-of-the-separator
Comment: What it looks like to me is that it was originally written with the D on the same beat as the C# and the slash is the rest of the stem.  You'll notice the stem on the D is a little shorter than normal too.
Comment: @Dekkadeci That one seems limited to Adams
Comment: Knowing that it's a Bach organ work, I'm going to double down on the possibility that it marks an instance of a theme. Also, sometimes in hymnals we see markings like this showing places that the organist might choose to use as an introduction (more often an angle bracket, but sometimes I've seen other marks for secondary-choice spots). At any rate, it ought to be explained in the edition. When you get a chance, please share a larger screenshot with more context.
Comment: Related: [Odd symbol in Béla Bartók's Mikrokosmos Book 1](https://music.stackexchange.com/questions/17243/odd-symbol-in-béla-bartóks-mikrokosmos-book-1)
Answer: It's a "breath" mark. In vocal or wind instrument parts, its meaning is literal: take a quick breath. In piano music it's like a phrase mark and means to leave a little space (I.e. a "breath") between the two notes on either side. It's not common in piano music, but not unusual.
Comment: Is it, though? Typographically, it looks to me more like things i've seen to mark the theme in a fugue, or metric meanings like situations in which there's a reason to demarcate a half bar, like for phrasing purposes
Comment: Does it differ from a comma breath mark or from a caesura?
Comment: @ArnasŠniokaitis If both are in the same piece, then the comma represents a more significant break, as at the end of a phrase, while the tic is a quick breath. If they're in different pieces, then the likely mean the same thing, which you'd confirm by looking at the context.
Comment: I thought a breath mark was a comma, and as a mark on a piano score, there's probably only one well-known player who'd use it... or were there several..?
Comment: @ArnasŠniokaitis It's the same as a comma. Not a full break, but a quick breath.
Comment: @Tim Commas are more common, but tics are also used.
Comment: @AndyBonner Yes, it could be either of those things, especially now that we know it's Bach, but interpretively it still amounts to much the same thing. It seems likely it's marking a fugal theme, given the composer, but there's not enough information to be sure.
Comment: is there a difference between it and a comma denoted breath mark? Because in my choir I found both used and I don't know what makes them distinct?


How to proceed for the following problem in uniform continuity

Question:
I am trying to solve this problem. Please give one hint to proceed for the problem. I think there may be counterexample
Answer: Yes, this is true. I'm not sure how to give a hint that does not spoil it. I suggest reading sentence by sentence and going for your self once you think you can.
Since $f$ is uniformly continuous, by definition: $\forall \varepsilon > 0 \exists \delta > 0$ s.t. $$\forall x,y \in (0, \infty): \vert x - y \vert < \delta \Rightarrow \vert f(x) - f(y) \vert < \varepsilon$$. Hence in particular this is true for $y := x + \frac{1}{x}$. Hence for any given $\varepsilon > 0$ there exists $\delta > 0$ with
$$\vert \frac{1}{x}\vert = \vert x - x - \frac{1}{x} \vert < \delta \Rightarrow \vert f(x) - f(x + \frac{1}{x}) \vert < \varepsilon$$ Hence for $x \rightarrow \infty$ we have $\vert f(x) - f(x + \frac{1}{x}) \vert \rightarrow 0$ and thus
$$\lim_{x \rightarrow \infty} \frac{f(x+\frac{1}{x})}{f(x)} = \lim_{x \rightarrow \infty} \frac{f(x) +( f(x+\frac{1}{x})-f(x))}{f(x)} = 1 + \lim_{x \rightarrow \infty} f(x+\frac{1}{x})-f(x)) = 1$$


Show that $\int_0^\infty e^{-x^2/2}\cos(ax)\,dx=\frac 1 2 \sqrt{2 \pi} e^{-a^2/2}$ for $a\in \mathbb{R}$.

Question: In my course of complex analysis I am asked to solve the following exercise:
Show that $\displaystyle \int_0^\infty e^{-x^2/2}\cos(ax) \, dx = \frac 1 2 \sqrt{2 \pi} e^{-a^2/2}$ for $a\in \mathbb{R} $.
I have tried using the integration methods by means of integration contours but I make many errors and I can not get the result.
Answer: You can also use Feynman's trick, if you let:
$$I(a)=\int_0^{\infty} e^{-\frac{x^2}{2}} \cos(ax)dx.$$  Then we have that, $$I'(a)=-\int_0^{\infty} xe^{-\frac{x^2}{2}} \sin(ax)dx. $$  Now using parts with $dv=xe^{\frac{-x^2}{2}}dx$ so $v=-e^{-\frac{x^2}{2}}$ and $u=\sin(ax)$ so $du=a\cos(ax)dx$ we have $$-(-\sin(ax)e^{\frac{-x^2}{2}} |_0^{\infty}+a\int_0^{\infty}\cos(ax)e^{\frac{-x^2}{2}}dx)=-aI(a).$$  Now we have the following differential equation: $$I'(a)=-aI(a).$$  To get a initial condition note that, $I(0)$ is the usual gaussian, $I(0)=\sqrt{\frac{\pi}{2}}.$ So solving gives: $$ln|I(a)|=-\frac{a^2}{2}+C$$ or $$I(a)=Ce^{\frac{-a^2}{2}}.$$  Plugging in the initial condition gives the desired result:$$I(a)=\sqrt{\frac{\pi}{2}}e^{\frac{-a^2}{2}}.$$
Answer: HINT:
Write
$$\begin{align}
e^{-x^2/2}\cos(ax)&=\text{Re}\left(e^{-x^2/2+iax}\right)\\\\
&=e^{-a^2/2}\text{Re}\left(e^{-\frac12(x-ia)^2}\right)\tag 1
\end{align}$$
Exploit the evenness of the integrand, use $(1)$, translate the argument by enforcing the substitution $x-ia \to x$, deform the contour back to the real line exploiting Cauchy's Integral Theorem, evaluate the resulting Gaussian integral, and take the real part.
SPOILER ALERT:  Scroll over the highlighted area to reveal the solution

Therefore, $$\begin{align}\int_0^\infty e^{-x^2/2}\cos(ax)\,dx&=\frac12 e^{-a^2/2} \int_{-\infty}^\infty \text{Re}\left(e^{-\frac12(x-ia)^2}\right)\,dx\\\\&=\frac12 e^{-a^2/2} \text{Re}\left(\int_{-\infty}^\infty e^{-\frac12(x-ia)^2}\,dx\right)\\\\&=\frac12 e^{-a^2/2} \text{Re}\left(\int_{-\infty-ia}^{\infty-ia} e^{-\frac12 x^2}\,dx\right)\\\\&=\frac12 e^{-a^2/2} \text{Re}\left(\int_{-\infty}^{\infty} e^{-\frac12 x^2}\,dx\right)\\\\&=\frac12 \sqrt{2\pi }e^{-a^2/2}\end{align}$$as was to be shown!


Synchronizing a webform to populate MailChimp lits

Question: I'm synchronizing a webform to populate MailChimp lits via the MailChimp module. As well as capturing the first and last name I also want to capture the City and Province.
However when I submit I only seem to capture the email address in MailChimp.
I configured my form for each field as the following.
Email Field (This works.)

Title: Email
Key: email
Type: Email

First Name (This doesn't transfer to MailChimp.)

Title: First Name
Key: fname
Type: Text field

Last Name (This doesn't transfer to MailChimp.)

Title: Last Name
Key: lname
Type: Text field

In MailChimp I set up in the List fields and |MERGE| tags the following.

First Name |FNAME|
Last Name |LNAME|

Has anyone else had issues with merging fields from Drupal 8 into MailChimp via the MailChimp module?
Answer: I've recently built a subscriber module with a small piece of custom code. I prefer working with webform handlers instead of the Mailchimp module.
In a custom module add a folder src/Plugin/WebformHandler and create a file newsletterSubscription.php. Add the following code:
<?php
namespace Drupal\<mycustommodule>\Plugin\WebformHandler;

use Drupal\Core\Form\FormStateInterface;
use Drupal\webform\Plugin\WebformHandlerBase;
use Drupal\webform\webformSubmissionInterface;

/**
 * Form submission handler.
 *
 * @WebformHandler(
 *   id = "newslettersubscription",
 *   label = @Translation("Newsletter subscription"),
 *   category = @Translation("Form Handler"),
 *   description = @Translation("Administers subscriptions in Mailchimp"),
 *   cardinality = \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_SINGLE,
 *   results = \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_PROCESSED,
 * )
 */

class newsletterSubscription extends WebformHandlerBase {

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [];
  }

  const MAILCHIMP_API_KEY = 'x'; // see https://mailchimp.com/help/about-api-keys
  const LIST_ID = 'x'; // see https://3by400.com/get-support/3by400-knowledgebase?view=kb&kbartid=6

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {

    $values = $webform_submission->getData();
    $email = strtolower($values['e_mail']);
    $first_name = $values['first_name'];
    $last_name = $values['last_name'];

    // The data to send to the API
    $postData = array(
      "email_address" => "$email",
      "status" => "subscribed",
      "merge_fields" => array(
        "FNAME" => "$first_name",
        "LNAME" => "$last_name"
      )
    );

    // Setup cURL
    // To get the correct dataserver, see the url of your mailchimp back-end, mine is https://us20.admin.mailchimp.com/account/api/
    $ch = curl_init('https://us20.api.mailchimp.com/3.0/lists/'.self::LIST_ID.'/members/');
    curl_setopt_array($ch, array(
      CURLOPT_POST => TRUE,
      CURLOPT_RETURNTRANSFER => TRUE,
      CURLOPT_HTTPHEADER => array(
        'Authorization: apikey '.self::MAILCHIMP_API_KEY,
        'Content-Type: application/json'
      ),
      CURLOPT_POSTFIELDS => json_encode($postData)
    ));

    // Send the request
    $response = curl_exec($ch);
    $readable_response = json_decode($response);
    if($readable_response->status == 403) {
      \Drupal::logger('Mailchimp_subscriber')->error($readable_response->title.': '.$readable_response->detail .'. Raw values:'.print_r($values));
      \Drupal::messenger()->addError('Something went wrong. Please contact your webmaster.');
    }
    if($readable_response->status == 'subscribed') {
      \Drupal::messenger()->addStatus('You are now successfully subscribed.');
    }
    if($readable_response->status == 400) {
      if($readable_response->title == 'Member Exists') {
        \Drupal::messenger()->addWarning('You are already subscribed to this mailing list.');
      }
    }

    return true;
  }
}

Read more on how to enable and use the handler here: How to create a mailchimp subscription with drupal 8 webform and custom handlers (Video)
Answer:
Go to the settings of your webform
Add handler on the Emails/Handlers tab
Select your List and Email field you wish to use
In the merge vars section you can link your webform fields with fields from your Mailchimp webform. For example:
FNAME: [webform_submission:values:name]
LNAME: [webform_submission:values:surname]

Answer: For me to get this to work, I needed to quote the tokens:
FNAME: '[webform_submission:values:name]'
LNAME: '[webform_submission:values:surname]'


Finding $a \pmod c$ if $a \pmod b$ is known

Question: Suppose that:
$Y \pmod B = 0$
$Y \pmod C = X$
I know $B$ and $C$. $Y$ is unknown, it might be an extremely large number, and it does not interest me.
The question is: Is it possible to find $X$, and if so, how?
Answer: In the case where $b$ aand $c$ are relatively prime, knowing $y\bmod b$ gives absolutely no information about $y\bmod c$. It could be any of $0,1,2, \dots,c-1$.
In the general case where $b$ and $c$ are not necessarily prime, let $d=\gcd(b,c)$. Knowing $y\bmod b$ tells us what $y\bmod d$ is. But $y\bmod c$ can take on any value compatible with the known value of $y\bmod d$. That is, if $y\bmod d=y_1$, then $y\bmod c$ can take on any of the values $y_1,y_1+d, y_1+2d, \dots,y_1+kd$, where $k=\frac{c}{d}-1$.
Answer: No; more information is needed. To see this, suppose that $B=2$ and $C=5$ and suppose that we know that $Y \bmod 2 = 0$ and we want to figure out $X = Y \bmod 5$. The possibilities for $X$ are not unique and depend on $Y$:

Since $2$ is a factor of $10$, we could have $Y=10$, which yields $X=0$.
Since $2$ is a factor of $12$, we could have $Y=12$, which yields $X=2$.
Since $2$ is a factor of $14$, we could have $Y=14$, which yields $X=4$.
Since $2$ is a factor of $16$, we could have $Y=16$, which yields $X=1$.
Since $2$ is a factor of $18$, we could have $Y=18$, which yields $X=3$.
Answer: $\bigg\lbrace\begin{eqnarray}y\equiv 0\pmod b\\ y\equiv x\pmod c\end{eqnarray}\bigg\rbrace $ $\!\iff\! \bigg\lbrace\begin{eqnarray} y &=& j b,\ \ &{\rm  some}\ \ j\in \Bbb Z\\ y &=& x\! +\! k c,\ \ &{\rm some}\ \ k\in \Bbb Z\end{eqnarray}\bigg\rbrace\!\iff\! x = jb\!-\!kc,\ \ {\rm some}\ \ j,k\in\Bbb Z$
Thus, by Bezout, the possible values of $\,x\,$ are precisely the multiples of $\,\gcd(b,c).$
Comment: This is a very good observation. Thank you. I almost thought that it might be a key to solving my problem, but recently I discovered that my number C is a prime. Looks like I'm out of luck.
Comment: @Highstaker If $\,c\,$ is prime then $\,\gcd(b,c) = 1\ $ or $\,c,\,$ so the possible values of $\,x\,$ are all values, or all multiplies of $\,c,\,$ resp.
Comment: Yes, that's what I meant. X can be anything up to C. I guess I'll have to take a different approach.
Comment: @Highstaker What was your intended application?


Is it true that the order of the group is a power of $2$ if every element has order $2$?

Question: I read in this old question that

If $G$ consists only of elements of order 2, then $|G|=2^m$ for some
   $m$.

But it's not clear to me. I tested the base case $G=\{a,b,ab,e\}$ but induction does not seem appropriate.

Assuming the statement is true, how does one go about proving this?
Comment: For finite groups, this is a consequence of Cauchy's result that if a group has finite order $n$ and $p\mid n$ is a prime, then this group contains an element of order $p$. Conversely, if $G$ contains an element of order $p$, then $p\mid |G|$. For infinite groups the claim is false.
Comment: The same result still holds for (infinite) profinite groups by the same argument, interpreting the order of the group in the usual way.
Answer: For finite groups it's definitely true.  Suppose $|G|$ was divisible by an odd prime $p$.  By Cauchy's Theorem, $G$ contains an element of order $p$
I should add, clearly this does not hold when $G$ is an infinite group, since every non-identity element of $\mathbb{Z}_2^{\infty}$ has order $2$.
Comment: I'd avoid the contradiction by removing the word "odd" and concluding that $p=2$.
Comment: Yeah I agree, we should avoid proofs by contradiction when unnecessary.
Comment: Hi. Would you mind including what the group $\mathbb{Z}_2^{\infty}$ is called?
Comment: @WhiteLake There are two common notions for what $\mathbb Z_2^{\infty}$ could mean.  The first is $$\bigoplus_{i=1}^{\infty}\mathbb Z_2$$and the second is $$\prod_{i=1}^{\infty}\mathbb Z_2.$$The former is isomorphic to $\mathbb Z_2[x]$ and the latter is isomorphic to all modulo 2 sequences of $0$ and $1$.
Answer: No group consists only of elements of order $2$, because the identity always has order $1$ :-)
Leaving this nitpick aside, it's well-known that a group of exponent $2$ is abelian because
$$
a(ba)b = (ab)^2 = e = a^2 b^2 = a(ab)b
$$
(followed by canceling $a$ from the left and $b$ from the right), so if the group is finite it's isomorphic with $({\bf Z/2\bf Z})^m$ for some $m$.
JasonM's argument is still preferable because it generalizes to arbitrary primes: a finite group of exponent $p$ has order $p^m$ for some $m$, else some other prime $q$ divides the group order, and then Cauchy's theorem produces an element of order $q$.
Comment: Yes, that's why I wrote "so if the group is finite it's isomorphic with
$({\bf Z/2\bf Z})^m$ for some $m$" without spelling out the argument.
(One way to say it is that a group of exponent $2$ is a vector space over
the field $\bf Z/2\bf Z$, so if $G$ is finite then it has finite dimension $m$
and then $|G| = 2^m$.)
Comment: [That comment was a reply to a question " . . . once you know it's Abelian,
isn't it easy to see directly from first principles that $|G|=2^{|X|}$ . . . ?"
later deleted by the asker.]
Answer: I would like to propose a more direct answer without using Cauchy's theorem. First note that any group $G$ with only order 2 elements apart form the identity is abelian. Consider the minimum number of generators required to generate the group, say there are $n$ of these. Then every element of the group must be a product of these $n$ generators. Since the group is abelian, the order of the generators within a product is inconsequential and there are at most $\sum_{i=1}^n \binom{n}{i}$ of such products. Adding the identity element itself, this makes at most $2^n$ elements, so $|G|\leq 2^n$. But in fact all of the products must be distinct (and different from the identity) since otherwise we can always rearrange (multiplying by inverse generators and so forth) such that one supposedly independent generator is in fact a product of other generators. Thus $|G|=2^n$, where $n$ is the minimum number of generators of $G$.
Answer: Here's a counter-example where the order is infinite: an infinite product of copies of $\mathbb Z/2\mathbb Z$
Answer: Cauchy's theorem states that if a prime $p$ divides the order of a group $G$, then $G$ has an element of order $p$. In particular, if the order $|G|$ is a composite number which is not a power of $2$, because $|G|$ is divisible by a prime $p > 2$,  $G$ has an element whose order is not equal to $2$.  The proof of Cauchy's theorem would then prove your claim that if every non-identity element of a finite group $G$ has order 2, then the only prime dividing $|G|$ is $2$.
Note that the order of the identity group element is $1$.  So your assertion refers only to the non-identity group elements.


Flatten list of dynamic objects in c#

Question: I have a list of dynamics:
var list = new List<dynamic> { Json.Decode(@"{""no"":""001"",""photos"":[""01.jpg"",""02.jpg""]}"), Json.Decode(@"{""no"":""002"",""photos"":[""01.jpg""]}") };

How can i use selectMany to fatten the photos property into:
{"no": "001", "photo": "01.jpg"}
{"no": "001", "photo": "02.jpg"}
{"no": "002", "photo": "01.jpg"}

Answer: Believe you want to get flatten list of photos
var photos = list.SelectMany(x=>(DynamicJsonArray)x.photos).Cast<string>();

Output

Flatten list of dynamic objects in c#


Actionbarsherlock Spinner background image stretched

Question: I am trying to change the color of the little triangle on the Actionbar spinner (sherlock).  I have done so using the following code:
<code><style name="MyTheme" parent="Theme.Sherlock.Light">
    <item name="windowActionBarOverlay">true</item>
    <item name="homeAsUpIndicator">@drawable/ic_drawer</item>
    <item name="actionDropDownStyle">@style/MyActionBarSpinnerStyle</item>

</style>

<style name="MyActionBarSpinnerStyle" parent="@style/Widget.Sherlock.Light.Spinner.DropDown.ActionBar">
    <item name="background">@drawable/actionbar_spinner_background</item>
</style>
</code>
The icon triangle is changed but it seems to stretch the image to the whole size of the spinner.
image http://dodsonsolutions.com/screens/screen1.png
I am using the patch-9 drawable file that everyone says to use:
spinner http://dodsonsolutions.com/screens/spinner_background_disabled.png
If this is not the correct dimensions of the file then does anyone know what it should be?
Or how do I get it not to stretch and just sit in the bottom right hand corner.
Thank you.
Answer: are you using the image that has correct extension?
check the extension of the png file you are using. if it is not ".9.png", change it into .9.png
or if it is .9.png?
there must be a build error of your project. try to rebuild & run. that must be solved.
Comment: This Did it!  Thank you.  I was unaware that I needed to keep the .9 in the name.
Answer: 1.try to define pixel in the area that you want to re-size not all around the image and check pixel more than 3 mostly declaring 1 pixel not working
2.check your xml file to make sure layout_width and layout_height is wrap_content
3.To use 9patch :the image file extension should be png and while you declare area extension become .9.png


Rationalizing radical expressions

Question:
$\sqrt [ 3 ]{\frac{3}{4}  }$  is the expression.
  What i did was change it to an equivalent fraction $({\sqrt [ 3 ]{\frac{6}{8}  }=\frac{\sqrt [ 3 ]{  6}}{2} } )$. But i think it isn't right.
  Please help me.
Comment: As LaTeX'ed, looks perfectly good. Right strategy, right result.
Comment: So what did you do exactly?
Comment: i chaged it to 3/4 to 6/8 to get a perfect cube, my answer is cube root of 6/2. is it right?
Comment: You phrased it wrong but I think you are correct. It's the cube root of 6 and that quantity divided by 2
Answer: If you did this,
you were correct
(writing out every possible step):
$$\sqrt[3]{\frac{3}{4}}
=\sqrt[3]{\frac{2\times 3}{2\times 4}}
=\sqrt[3]{\frac{6}{8}}
=\frac{\sqrt[3]{6}}{\sqrt[3]{8}}
=\frac{\sqrt[3]{6}}{2}
$$

Rationalizing radical expressions


Integral with gamma function

Question: Inspired by the limit
$$
\lim_{n\to \infty}\frac{\sqrt[n]{n!}}{n} = e^{-1}
$$
and using desmos.com, I plotted the function
$$
f(x)=\frac{\sqrt[x]{\Gamma(x+1)}}{x}-\frac{1}{e}
$$
and obtained the result bellow.

Don't know why, but I had the feeling that the integral
$$
\int_{0}^{\infty}\left(\frac{\sqrt[x]{\Gamma(x+1)}}{x}-\frac{1}{e}\right)dx
$$
would converge. Then I used Wolfram to test it. Here's it's solution:

Using desmos.com, I started to test some values for the fraction $\frac{\sqrt[n]{n!}}{n}$ and for values greater than $n=169$, the computer can't solve, but I know that that the value will converge to $e^{-1}$, so large values of $n$ shouldn't be a problem. So the problem is the computer, which makes me think that Wolfram suffer the same type of issue.
So, is there an analytic way to prove that the integral converges? Does the integral have a closed form? If it does not converge, how can I prove it?
Thank you in advance.
Comment: The problem isn't the asymptotic behaviour when $x\rightarrow\infty$ but the divergence of the integrand at $x=0$.
Comment: Hi Abezhiko. Thank you for the quick answer. I've tested the same integral (using Wolfram) but with the lower bound equal to 1. Same result (divergence).
Comment: The substitution $x=1/t$ implies
$$
\int_a^\infty\left(\frac{\Gamma(x+1)^{1/x}}{x}-\frac{1}{e}\right)\mathrm{d}x = \int_0^{1/a}\left(\frac{\Gamma\left(1+\frac{1}{t}\right)^t}{t}-\frac{1}{et^2}\right)\mathrm{d}t
$$
with $a>0$. In this form, the integrand is singular at $t=0$; so I guess that the tail of the original integrand doesn't decrease fast enough for convergence.
Comment: So basically, you are asking wheter the integral converges or diverges as $x \to \infty$ regardless of what the lower bound is, correct?
Comment: Thank you Abezhiko and Accelerator. Originally, I want to know if the total integral converges (with the interval $[0, \infty]$. And if it doesn't, the integral with the limit $[a, \infty]$ converges for all $a > 0$? And if so, is there a closed form?
Comment: There is in your own comprehension, as Abezhiko, Accelerator remarked already,  defined limit value does not imply convergent convergent integral measure along certain region. The answer to closed form is "Probably not",   without any formal implication of "probably"-adverb here.
Answer: As $x\to\infty$, the integrand behaves like (using Sterling's formula) $$\frac{\left(\sqrt{2\pi x} (x/e)^x \right)^{1/x} }{x} -\frac 1e  \\ = \frac{(2\pi x)^{\frac{1}{2x}} -1}{e} \\ = \frac{e^{\frac{\ln (2\pi x)}{2x}} -1}{e} \\ \approx  \frac{\ln (2\pi x)}{2ex}
 $$
Evidently $\int_1^{\infty} \frac{\ln (2\pi x)}{2ex} dx$ diverges, so also the original integral.
Comment: Thank you, @Vishu. I'm wondering, maybe we can use  https://math.stackexchange.com/questions/1038957/pretty-lower-bound-on-the-gamma-function to prove the divergence.
Comment: @otreblig We sure can.
Answer: There is also a problem around $x=0$ since
$$\log (\Gamma (x+1))=\sum_{n=0}^\infty \frac{\psi ^{(n-1)}(1)}{n!} \,x^n=-\gamma  x+\frac{\pi ^2 x^2}{12}+\frac{x^3 \psi
   ^{(2)}(1)}{6}+O\left(x^4\right)$$
$$f(x)=\frac{\sqrt[x]{\Gamma(x+1)}}{x}-\frac{1}{e}$$
$$f(x)=\color{red}{\frac{e^{-\gamma }}{x}}+\left(\frac{e^{-\gamma }}{12}  \pi
   ^2-\frac{1}{e}\right)+\frac{e^{-\gamma }}{2}
   \left(\frac{\pi ^4}{144}+\frac{\psi
   ^{(2)}(1)}{3}\right)x+O\left(x^2\right)$$ which is a quite good approximation.
Consider
$$I_k=\int_{10^{-k}}^1 f(x)\,dx$$
$$\left(
\begin{array}{ccc}
k & \text{approximation}& \text{solution}\\
 1 & 1.35996 & 1.36433 \\
 2 & 2.66105 & 2.66542 \\
 3 & 3.95470 & 3.95907 \\
 4 & 5.24759 & 5.25197 \\
 5 & 6.54041 & 6.54478 \\
 6 & 7.83322 & 7.83759 \\
 7 & 9.12603 & 9.13040 \\
 8 & 10.4188 & 10.4232 \\
 9 & 11.7116 & 11.7160 \\
 10 & 13.0045 & 13.0088 \\
\end{array}
\right)$$
Nice but diverging.

Integral with gamma function


how to print a value in array with json

Question: <code>$qr=mysql_query("SELECT `setting-name`,`setting-explain` FROM `fndn_Setting`");
    $row=mysql_fetch_assoc($qr);
    for($i=1;$row=mysql_fetch_assoc($qr);$i++){
        $arr[$i]=$row;
    }

    echo json_encode($arr);
</code>
Hi
the json print this value:
<code>{"1":{"setting-name":"sms_num","setting-explain":"201300"},"2":{"setting-name":"sms_txt","setting-explain":"40"}}
</code>
But I want to print this value:
<code>{"1":{"sms_num","201300"},"2":{"sms_txt","40"}}
</code>
How can I correct this?
Comment: Why you don't reformat the array to your wishes that you echo instead of returning the query result?
Comment: `$arr[$i]=array($row['setting-name'] => $row['setting-explain']);`
Comment: Please dont use mysql_* it has been deprecated. it will get your question multiple down votes. other than that your way of retrieving data is wrong
Answer: Change one line to take only values
<code>    $arr[$i]=array_values($row);
</code>

how to print a value in array with json


Como montar uma RegEx para identificar o estado das interfaces

Question: Usando o comando ip link show no terminal eu obtenho o seguintes texto:
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN mode DEFAULT group default qlen 1000link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP mode DEFAULT group default qlen 1000
    link/ether b8:27:eb:01:1e:5b brd ff:ff:ff:ff:ff:ff
3: wlan0: <BROADCAST,MULTICAST> mtu 1500 qdisc noop state DOWN mode DORMANT group default qlen 1000
    link/ether b8:27:eb:54:4b:0e brd ff:ff:ff:ff:ff:ff

Com essa regex: (?<=eth0:)(.*) eu já consigo pegar toda a linha do eth0 e ignora-lo, mas eu não consegui fazer com que ele pare na palavra "state", e fazer ignorar tudo entre "eth0:" e "state" e pegar somente o estado UP/DOWN/UNKNOWN.
Answer:
Precisa ser com regex? Você pode usar awk para pegar somente o campo correspondente ao status, e passar o nome da interface como parâmetro do comando  ip:
ip link show eth0 | awk '{print $9 }'

Primeiro, ip link show eth0 mostra somente a interface de rede que você quer:
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP mode DEFAULT group default qlen 1000
    link/ether b8:27:eb:01:1e:5b brd ff:ff:ff:ff:ff:ff

Em seguida o pipe (o caractere |) pega esta saída e passa para o comando seguinte,  que no caso é o awk.
O awk separa o conteúdo de cada linha em campos, por padrão separados por espaços. Sendo assim, o nono campo ($9) é o que contém a informação que você quer. Por isso print $9 mostra:

UP

Só que o comando acima também mostra uma linha em branco abaixo do UP, já que a segunda linha não tem 9 campos (se separarmos por espaços, são somente quatro), e por isso o print $9 não imprime nada (mas o print por padrão coloca uma quebra de linha no final, então o resultado é uma linha em branco).
Uma alternativa para evitar esta linha em branco é usar grep para pegar somente as linhas que possuem eth0 e depois fazer o awk com esta linha:
ip link show eth0 | grep eth0 | awk '{print $9 }'

Com isso ele só imprime UP, e não imprime a segunda linha em branco.
Outra alternativa é usar head com a opção -n 1 para trazer somente a primeira linha (a que tem eth0), assim não preciso do grep:
ip link show eth0 | head -n 1 | awk '{print $9 }'

Se quer mesmo usar regex, você pode usar grep com a opção -P (que habilita a sintaxe Perl Compatible - já que por padrão o bash não suporta lookbehind):
ip link show eth0 | head -n 1 | grep -o -P "(?<=state )\w+"

Isso também imprime UP.
Ou, se você tiver o Perl instalado:
ip link show eth0 | head -n 1 | perl -ne 'print $1 if /eth0.*?state (\w+)/'

No caso, usei os parênteses para formar um grupo de captura em torno do que eu quero: o \w+ logo depois de "state". Assim, este grupo estará disponível na variável especial $1 (já que é o primeiro grupo de captura). Esse código também imprime UP, mas sem a quebra de linha no final. Se quiser a quebra de linha, basta trocar por:
ip link show eth0 | head -n 1 | perl -ne 'print "$1\n" if /eth0.*?state (\w+)/'

Mas ainda acho a solução com awk mais simples.
Comment: Não, não precisa ser regex. Eu acabei de testa este código, retornou UP como disse, mas o que é "awk"?
Comment: @MatheusLeite Atualizei a resposta com uma explicação
Comment: Entendi perfeitamente, obrigado!


Proving or disproving a limit of a complex-valued function

Question: Prove or Disprove $\lim_{z \rightarrow 0} z \sin \left( \frac{1}{z} \right) = 0$.
My Approach: Since this result is true for real variable $z=x$, and since the real line contains the accumulation points of $\mathbb{C}$, by the Identity Principle  the assertion holds for $z \in \mathbb{C}$ as well.
I want to see without using the "Identity Principle", how to establish the limit. Any appropriate suggestions are much appreciated.
Answer: False:
Let $z=ia$ ($a$ real) then $sin({\frac{1}{z})=\frac{e^{1/a}-e^{-1/a}}{2i}}$ So $ae^{1/a}\to \infty$ for $a\to 0+$ while $ae^{-1/a}\to \infty$ for $a\to 0-$
Comment: I am not familiar with the "Identity Principle", so I can't comment on it.  However as you see the assertion is false.  From what I gathered (Wikipedia) the function has to be analytic, which is obviously not at $z=0$.
Comment: So why isn't this follow from the "Identity Principle" ?