UITableView's selectRowAtIndexPath:animated:scrollPosition: not working after reloadData in iOS 8

Question: I have the following code in tableView:didSelectRowAtIndexPath:
[tableView reloadData];
[tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
[tableView deselectRowAtIndexPath:indexPath animated:YES];

It deselects a table view cell tapped by the user (with animation) after the table view is reloaded. It has worked fine in iOS 7 and earlier, but in iOS 8 the animation isn't shown.
What changes were made in iOS 8 to cause this? And what's the best way to achieve the same effect in iOS 8?
Comment: What effect are you looking for? Do you really need to reload or just update the cell?
Comment: 1. why are you reloading the data when a row is selected?
Comment: I call `reloadData` to update the table (either adding or removing rows, depending on the selection) and show a checkmark next to the selected row. I'm not sure if it's the best way to do what I need (still relatively new at this), but the code worked fine in iOS 7 and earlier.
Answer: What is the surrounding code that's causing you to call [tableView reloadData]?
Depending on how much processing you are doing in cellForRowAtIndexPath and the surrounding methods, this can be an expensive operation.
You can run:
[tableView beginUpdates];
// Update code here
[tableView endUpdates];

without having to reload the entire tableView datasource.
When didSelectRowAtIndexPath is called, the cell is already selected. So there shouldn't be any need to call the tableView's selectRowAtIndexPath method. Simply calling deselectRowAtIndexPath should do the trick after updating your cells
Comment: I call `reloadData` to update the table (either adding or removing rows, depending on the selection) and show a checkmark next to the selected row. I guess it is pretty expensive and I should be doing it differently (I'm still relatively new at this). However, the code worked fine in iOS 7 and earlier.


Getting the wrong sign on a coefficient in logistic regression?

Question: I'm trying to make a logistic regression model explaining whether a law passed last year has affected my dependent variable. My most important variable (an indicator variable for whether the law was in effect for a given observation with 1=law and 0=no law) has the wrong sign. Before the law came into effect, the dependent variable event happened 40% of the time (n=250), and after the law came into effect the event happened 56% of the time (n=40). However, the coefficient for the Law variable is negative and odds ratio below 1.
I am also using Date (or number of days after the first observation, as I coded it) as a variable. This is because frequency of the event was on an increasing trend over time, and I want to see if the increase in events after the law is due to the law itself or simply a continuation of the trend over time.
There are other control variables, but the sign on Law is only wrong when Date is included in the model. When I interact these two, the coefficient on Law is -50, the coefficient on the interaction term is 35, and the coefficient on Date is near 0. The law is significant with and without interaction, but not when Date is not included in the model.
Am I getting the wrong sign because these two variables (Law and Date) are collinear? If so, how would I go about figuring out what I want to know– whether the increase in events after the law was passed is due to the law or due to a continuation of the already-existing increasing trend?
Also- standardizing/normalizing Date has no or little effect.
Thank you so much for any advice or help, this has been a very confusing endeavor when I thought it was going to be quite simple.
Answer: One way to look at this is that your probability of "success" (occurrence of your dependent variable) is a function of time. When you introduce the dummy at a fixed time point, you introduce a discontinuity into the time trend.  In your model, this appears to be estimated as a drop at that time point, which I gather is not what you were hoping for.
On the other hand, one does not expect things to happen instantaneously, as your  discontinuity model would suggest. It is somewhat encouraging from your perspective that your interaction is positive, because that suggests a steeper trend after than before.
Some caveats. First, time trends are not linear. They can be tricky to estimate because they generally do not follow nice function forms.  Some kind of non- or semi-parametric smoothing trick might be preferred to estimate the time function.  Second, you have one time function before the law, and another after the law.  How to string those together will be tricky.  A dummy variable introduces an instantaneous jump that seems inappropriate given that things take time to have an effect.  Third, it seems that you really don't have enough data to do estimate everything as well as you would like to. Fourth, causality will be hard to claim in this context.
Comment: You might google "Nonparametric logistic regression."  It's more flexible than Time^2, which is still too restrictive, but it's in the general direction. As far the coefficients being wild, that may be a function of sample size, and maybe it is also because you use "Year" as in the values 1999, 2000, 2001, ... rather than 1,2, 3, ... .  You should graph the fitted probabilities as a function of time, along with the 0's and 1's, to understand the model better.  The population "argument" really does not make sense here.
Comment: Sounds pretty interesting. Use the linear model then, with and without interaction, and draw the graph of the predicted probabilities as a function of year, including the effect of dummy in each model (two graphs). There will be a discontinuity at the point of time of the passage. It won't be in the direction you want, but it least it will give  you a better idea what your data are telling you.  It seems to me that your only hope is in the interaction model, but you probably do not have enough data to say too much.
Comment: Thanks so much! Do you have any more suggestions or resources about adding a non-parametric smoothing trick when using R? Does this mean something like adding Time^2? Also, you're correct about the steeper trend after the law, but should I be worried about how crazy the coefficients are with the interaction? I'm looking at the population, not a sample, so maybe since it's an explanatory model these coefficients don't matter?
Comment: Ah thank you, I was using years as a decimal (as in a certain observation could be 2.7234 years after the first  observation), but your point about sample size makes sense. Unfortunately it's all the data there is. I'll see what I can do with non-parametric logistic regression.
Comment: So I tried nonparametric regression and am still getting a negative coefficient. After graphing the smoothed effect of time on the dependent variable it still looks mostly linear, and I ran an anova comparing the parametric and nonparametric models which showed there's no/weak evidence for non-linearity for the time variable. Again, the sign is only wrong when I include the time variable, which is significant. Am I out of options?


ldapjs - write after end error

Question: I have created an authentication service using the following code in Node.js and ldapjs.
<code>var when = require ('when');
var AuthenticationError = require('../errors/AuthenticationError');
var SessionManagerService = require('./SessionManagerService');

var ldap = require('ldapjs');

var client = ldap.createClient({
    url: 'ldaps://ad.mycompany.com:636',
    tlsOptions: {'rejectUnauthorized': false}
});

module.exports = {

    signIn: function (email, password) {
        return this.ldapBind(email, password).then(
            function () {
                return SessionManagerService.createSessionHash({email: email});
            }
        );
    },

    ldapBind: function (email, password) {
        var deferred = when.defer();
        client.bind(email, password, function(err) {
            if (err) {
                deferred.reject (new AuthenticationError('Invalid username and/or password!', 'Authentication.signIn.error'));
            } else {
                client.unbind();
                deferred.resolve(true);
            }
        });
        return deferred.promise;
    },

};
</code>
When I authenticate my user for the first time, it works perfectly but it fails starting from the second attempt.
The error message is: 'write after end'.
When I restart the node server it works again for the first attempt.
It looks like something is hanging but I don't know what. Any idea?
Answer: I solved this problem a few days ago for creating ldap-client every time in ldapBind function (in your case).

ldapjs - write after end error


PHP executar comando sudo com shell_exec()

Question: Estou com o seguinte problema, Estou a tempo tentando rodar um aquivo sh com o php usando shell_exec por exemplo:
echo shell_exec("./example etc etc");

O meu problema é que ele não executa, será algum problema de permissão?
detalhe que quando digito: php x.php ele retorna certinho (só testei com o usuário root)
Comment: Sem você colocar o que aparece no log de erros, fica difícil saber. Seria bom [edit] e acrescentar esta informação relevante.
Comment: Alguns comandos são desabilitados por padrão.  Se você atualizar a pergunta usando o comando real, e não um exemplo, vai ser mais fácil pra obter ajuda.
Answer: Se você quiser executar o comando através da url do arquivo, exemplo http://exemplo.com/teste.php e nesse teste.php tem seu shell_exec, você precisa certificar-se que o Apache tem permissão para executar esse comando.
Para dar a permissão ao Apache basta saber o usuário, isso vai depender da distribuição do Linux que esteja utilizando. Se você estiver utilizando CentOS será Apache mesmo, caso esteja utilizando Ubuntu será www-data.
Após saber disso verifique qual o caminho do arquivo onde estão os arquivos que você quer executar a permissão sudo pelo Apache, ai você edita o sudoers
vim /etc/sudoers

e adicione a seguinte linha.
apache          ALL=(root)  NOPASSWD: /caminho/da/sua/pasta

ou
www-data        ALL=(root)  NOPASSWD: /caminho/da/sua/pasta

Basicamente você estará dizendo ao servidor que seu Apache tem permissão para executar os arquivos dessa pasta como root.
Comment: Obrigado Cara, Funcionou perfeitamente!


O que seria a "identidade" de um objeto?

Question: Lendo mais sobre objetos, tentando me "desprender" do conceito de que objeto seria apenas provido de uma "classe", nesta resposta, vi a seguinte frase:

"Objetos possuem identidade. Uma variável não."

O que seria a identidade de um objeto? Por que variáveis não possuem uma?
Answer: TL; DR
É a forma de determinar o que é o objeto e em alguns casos distinguir um objeto do outro. Onde mais é usado é determinar se é o mesmo objeto ou outro. É como você sabe quem é o João e quem é o José, ou é o João da Silva, ou é o João da Silva com a filiação tal (por isso que certas características sozinhas não podem ser usadas para criar identidade única).
Introdução
Esse é um termo controverso. Não vou dizer que boa parte das pessoas usam o termo de forma errada, como o fiz em outra questão (lá eu consegui fundamentar a diferença melhor, por isso lá falo que está errado, aqui não).
Há uma definição do que é identidade de objeto no contexto de orientação a objeto. Não gosto dela, porque ela se apropria do termo que pode ser aplicado de outra forma universalmente e diferentemente e dá outro significado. Não é segredo que eu considero OOP algo bem mal definido e conceitualmente tem menos valor que outras disciplinas, até porque o que dá certo quase sempre já vem de outras disciplinas.
Eu pegarei a definição que considero mais universal e ela vem da wiki raiz onde tem bons profissionais tentando criar conhecimento de qualidade sobre computação, e costumam conseguir, e não vou pegar da wiki nutella onde algumas pessoas ajudam criar algum conhecimento geral, e nem sempre dá certo.
Então aconselho ler ambos para entender cada contexto. Todo conhecimento é bem vindo, até quando causa confusão :) Aprenda discernir o joio do trigo.
Se quer ater-se apenas à definição de OOP pode não gostar da resposta, mas eu acho que a pergunta não era sobre isso, a origem dela foi em pergunta sobre a definição universal de objeto, não a usada em OOP. Se for identidade em DDD então, aí piorou :)
Identidade única X equivalente
Uma das coisas que que eu não concordo muito é o próprio termo identidade. Porque ele é usado querendo dizer que é uma identidade única, e por isso o termo deveria ser esse, composto. Se usar só o termo "identidade" eu acho que pode ser outra coisa. Mas tem definição que diz que identidade é única. Isso parece confuso, vou dar minha versão. Não afirmo que ela está correta, faça seu julgamento. Se discorda então fique só com a identidade única.
Existe a identidade única e a identidade equivalente. Pra mim todo objeto tem uma identidade, seja a primeira ou a segunda, não faz sentido não ter, não sei nem como chamar um objeto sem identidade.
A identidade única, que as pessoas chamam só de identidade, é fácil entender. Você tem alguma identificação no objeto que o torna único. Se você tiver objetos com essa característica igual (idêntica) no fundo eles são o mesmo objeto (ou entidade em certo contexto). Pode ser um endereço de memória que determina isso (a tal da referência), pode ser um id garantidamente único (UUID por exemplo, mas pode ser algo sequencial), pode até ser um nome, desde que único em toda solução, ou um conjunto de características que juntas se tornam única, pode ser até mesmo todo o objeto, e é mais comum do que se imagina, principalmente em objetos imutáveis.
A identidade equivalente é quando o objeto possui uma identidade não distinta, ou seja, você pode ter dois objetos completamente diferentes e você não consegue dizer quem é quem. O melhor exemplo é um número 1 em um objeto numérico. Você pode ter dois objetos com esse valor que nada tem a ver um com o outro, é só uma coincidência que eles são o mesmo valor, e não tem informação adicional alguma que os distingua. Pra mim eles possuem identidade (é o número 1) e ela é equivalente nos dois objetos. Para outras pessoas eles não possuem identidade (onde eu não concordo).
Por isso objetos por referência possuem uma identidade natural se nenhuma outra forma existir para distinguir os objetos (em vários casos outras existem e são melhores). Se você tem a mesma referência em dois lugares diferentes certamente elas estão apontando para o mesmo objeto.
Na segunda definição da C2 wiki (tirando a introdução) o autor entende que só importa a identidade equivalente, mas pode ser o contexto que ele usou.
Se continuar lendo lá tem outras formas de definir o que é a identidade. Eu acho isso bom, ainda que cause confusão. Não temos uma definição definitiva clara (a não ser que alguém me mostre uma).
Identidade interna X externa
A identidade interna ou lógica independe do contexto onde o objeto está sendo usado, e ele depende dos seus valores. É comum só algumas partes do objeto serem consideradas para dar uma identidade única. Exemplos: um id de uma pessoa, o CNPJ de uma empresa (isso pode ser um pouco polêmico, veja Valores que podem ser inseridos como chave primária).
Já a identidade externa ou física depende do contexto e de onde o objeto está. É o caso da referência dita acima, então se duplicar esse objeto passa ter dois objetos diferentes, ou seja, pode ter dois "joãos" idênticos (tudo mesmo, ser a mesma pessoa), o que em geral é problemático (algumas metodologias "modernas" pregam isso e tem causado vários problemas), é algo que deve ser evitado, pra isso existe a normalização.
Então tem que tomar cuidado com identidades externas porque entre uma execução e outra pode mudar, e ser a mesma entidade. Para a maioria dos efeitos a identidade interna é que importa pra gente.
A identidade interna acaba permitindo até que dois objetos diferentes sejam a mesma entidade. Eu não gosto disso, cria problemas, mas muita gente faz. Por exemplo pode ter um cliente e um fornecedor que são objetos distintos mas eles são a mesma entidade, são a mesma empresa, tem uma informação única que está presente nos dois objetos, um id por exemplo, ou o CNPJ, se quiser arriscar. Pra mim sistema que faz isso quer confusão, e falo disso em várias respostas aqui no site.
Mutabilidade
Objetos mutáveis podem ter várias características que podem ser mudadas e a identidade do objeto não muda, por exemplo a idade, ou mesmo o nome. Outras características não podem mudar. Mudar uma característica específica mudará a identidade, e algumas pessoas não percebem quais são elas. Por exemplo a pessoa pode achar que se mudar o CPF muda a identidade, mas não muda, é possível trocar de CPF por várias razões e ser a mesma pessoa, portanto deve ser o mesmo objeto.
Objetos imutáveis não podem mudar característica alguma sem mudar a identidade, ainda que a nova identidade seja equivalente à antiga. Então pra mim quando você faz
x = 1
x = 1

Coloquei no GitHub para referência futura.
a segunda linha, conceitualmente, está criando um novo objeto com sua identidade, e está atribuindo para uma variável que já tinha um objeto com uma identidade, e nesse caso as identidades dos objetos são equivalentes.
A variável não importa nada disso de identidade, ela não tem. O máximo que poderíamos dizer é que ela é identificada pelo seu nome, mas isso é outra coisa completamente diferente, há uma identificação, mas não é o mesmo conceito.
Entenda mais em O que "imutável" realmente significa?.
Variáveis X objetos
Minha intenção naquela resposta foi diferenciar uma coisa da outra. Como variável é um local de armazenamento não tem porque ela ter identidade, o conteúdo dela muda, e se muda a identidade muda, então a variável não pode ter identidade própria, o que está nela é que tem, é só isso.
Outro nível de abstração
Correndo o risco de causar mais confusão, podemos até dizer que a variável tem identidade, ma em outro nível de abstração. Considere isso uma explicação completamente isolada do resto da resposta.
Entenda aqui que o código não deixa de ser uma base de dados. São textos que relacionados tem algum significado. O código nesse contexto é algo que existe por si só e não se confunde com a aplicação que você está criando, nada a ver com o executável que rodará sua aplicação.
Se considerar que variável é um objeto do código (não confundir com objeto da aplicação) então ele tem identidade, porque todo objeto tem identidade. Essa identidade é dada por atributos (já linkei pergunta sobre o assunto logo no começo). Ela tem nome, ela costuma ter tipo (em linguagens de tipagem estática), escopo, pelo menos área de armazenamento, e talvez outras características. Depende da linguagem e contexto, mas mudando apenas uma delas já é outra variável.
Então não é que estou dizendo que variável tem identidade, mas que nesse nível de abstração que estamos olhando a variável é um objeto e todo objeto tem identidade.
Se não consegue entender a diferença do que é sua aplicação e o que é sua base de código, esqueça essa parte por um tempo.
Extra
Pesquisando sobre, achei uma pergunta aqui que mostra como muita gente não entende bem o que é a identidade do objeto, e não estou falando de ninguém ali na página, estou falando do criador da API do Java. Ele acha que um hashcode pode demonstrar a identidade de um objeto. Hashcodes podem se repetir, podem se confundir com outras coisas. Se pelo menos fosse o tipo mais o hashcode ajudaria um pouco, mas ainda pode se repetir.
Answer: Então, vou ser bem breve e resumir.
Tanto Objeto quanto Variável tem identidades.

O que é um identificador ?

Cada variável possui um identificador, que é um nome dado a ela e assim, toda vez que precisarmos usá-la, basta declarar o seu identificador.

O que seria a identidade de um objeto?

Um objeto é a representação de um conceito/entidade do mundo real, que pode ser física (bola, carro, árvore, etc.) ou conceitual (viagem, estoque, compra, etc) e possui um significado bem definido para um determinado software. Para esse conceito/entidade, deve ser definida inicialmente uma classe a partir da qual posteriormente serão instanciados objetos distintos.

Por que variáveis não possuem uma?

As variáveis são elementos básicos na programação, pois são aquelas que armazenam os dados que precisamos no nosso algoritmo. Cada dado pode ser de um tipo diferente e, por isso precisamos mostrar ao nosso algoritmo logo no início o que esperar armazenar.
Imagine, por exemplo, que precisamos separar roupas do vestuário de acordo com o seu tipo dentro de um armário. Esse é quem arruma a bagunça, por isso o consideramos nosso algoritmo, como vemos na Figura 1.

Figura 1. Como guardamos dados
Entendemos com a Figura 1 que cada gaveta corresponde a uma variável, que é um espaço dentro da memória do computador, ou seja, do nosso armário.
Na Gaveta 1 guardamos roupas do tipo camisa, na Gaveta 2 guardamos roupas do tipo calças e na Gaveta 3 do tipo bermuda. Na Gaveta 2 sabemos que não vamos encontrar camisas, pois esse é o tipo de roupa da Gaveta 1.


Proof that $\lim_{(x,y)\to (0,1)} e^{xy} = 1$

Question: Here is my proof:
Let $\epsilon > 0$ be given. There exists $\delta >0$ such that $$|e^{xy}-1| < \epsilon$$ whenever $0<|x|<\delta$ and  $0<|y-1|<\delta$.
Using exponential series, we write $$|e^{xy}-1|=|(1+xy+\frac{x^2y^2}{2!}+...)-1|$$ $$=|xy+\frac{x^2y^2}{2!}+\frac{x^3y^3}{3!}+...|$$ $$\le|xy|+|\frac{x^2y^2}{2!}|+|\frac{x^3y^3}{3!}|+...$$ $$\le|xy|+|x^2y^2|+|x^3y^3|+...$$
$$\lt\delta|y|+\delta^2|y|^2+\delta^3|y|^3+...$$
Let $\delta\le\frac12\implies\frac12\lt y\lt\frac32$ $$\therefore|e^{xy}-1|\lt\frac32\delta+(\frac32\delta)^2+(\frac32\delta)^3+...$$ $$= \frac{3\delta}{2-3\delta}$$
So, we choose $$\delta = min\{\frac12,\frac{2\epsilon}{3(\epsilon+1)}\}$$
$$\implies|e^{xy}-1|\lt\epsilon$$whenever$$0<|x|<\delta $$ and $$0<|y-1|<\delta$$
Q.E.D.
I would also like to know if there are any other ways to prove this.
Comment: Do you have to use $\epsilon$-$\delta$? Otherwise, just note that $xy \mapsto e^{xy}$ is continuous.
Comment: No. Other methods are also fine. Just wanted to use $\epsilon-\delta$ for the mental exercise :)
Comment: @ConnorHarris That approach uses $\epsilon$-$\delta$ too. Twice, actually. It's just usually hidden behind "We already know this general result".
Comment: @DonThousand I'm not sure I follow. Isn't epsilon-delta the way to show that a limit exists? Or is there a catch to it? Can you please provide references?
Comment: @DonThousand I see. Would taking the circular neighbourhood of the point (0,1) work then? If it would, I took the square neighbourhood because it follows from the circular neighbourhood. If we observe that $0<|x|\le\sqrt{x^2+(y-1)^2}<\delta$ and similarly for $|y-1|$. If I'm wrong, what is right way to prove that the limit exists?
Comment: @DonThousand There is nothing wrong with assuming $\delta$ is the same for $x$ and $y$. You're just looking at all points in a square centered around $(0,1)$ rather than a rectangle. We are not looking at just the corners of the squares (in which case rectangles would indeed be necessary).
Answer: Yes, you use the composition theorem
$$
f:(x,y)\to xy,\ g:z\to e^z
$$
with
$$
f: \mathbb{R}^2\to \mathbb{R},\ g:\mathbb{R}\to \mathbb{R}
$$
For the mental exercise, it is very rewarding and I can understand it. Then I advise you to decompose this composition (i.e. general result but with $\epsilon,\delta$).
For example, first for a given $\epsilon$, find the $\delta$ corresponding to the continuity of $g$, then the $\delta_1,\delta_2$ corresponding to the continuity of $f$.
About your proof It seems clever (I only overlooked it, I must go into details), but can be made more generic by decomposing

 For every given $\epsilon>0$, find $\delta>0$ such that $|z|<\delta\Longrightarrow |e^z-1|<\epsilon$ (you can reuse your argument proving that $|e^z-1|\leq e^{|z|}-1$)
 For every given $\delta>0$ find $\delta_i>0,\ i=1,2$ such that
$$
|x|<\delta_1\mbox{ and } |y-1|<\delta_2\Longrightarrow |xy|<\delta
$$

Comment: 1. We can write $e^{|z|}-1 well this is debatable (just tradition, simplicity and genericity). For the first $\delta$, I would rather choose any $\delta$ within $]0,ln(\epsilon+1)[$.


How to calculate new standard deviation based on formula given only the mean and set standard deviations

Question: I currently have the mean and standard deviation, I need to calculate the new standard deviation given a formula:
<code>µX = 9.5 and µY = 6.8
σX = 0.4 and σY = 0.1

with the equation X-Y
</code>
What steps do I go though to calculate the new mean and standard deviation?
Thanks in advance!
Comment: @JessePFrancis, I will look over these, thanks!
Comment: If $X$ and $Y$ are **independent**, then the **variance** of $aX+bY$ is $a^2$ times the variance of $X$ plus $b^2$ times the variance of $Y$. Here $a=1$ and $b=-1$.  But the post does not say $X$ and $Y$ are independent. With just the information given, we cannot compute the variance of $X-Y$.
Comment: For some basic information about writing math at this site see e.g.
[here](//meta.math.stackexchange.com/q/5020),
[here](//meta.stackexchange.com/a/70559),
[here](//meta.math.stackexchange.com/q/1773) and
[here](/help/notation).
Comment: That makes sense, however, I know that the answer to the mean is -2.7 and the standard deviation should be 0.412, however, with these variables, I cannot seem to figure out the standard deviation after the equation.
Comment: For **independent** $X$ and $Y$, the formula I mentioned gives that the standard deviation of $X-Y$ is $\sqrt{(0.4)^2+(0.1)^2}$.
Comment: Thank you so much, that makes much more sense, I appreciate your help!
Answer: Variance($V$) of $(X-Y)=V(X)+V(Y)-2Cov(X,Y)$ where $Cov(X,Y)$ is the covariance between $X$ and $Y$.
Mean($\mu$) of $(X-Y)=\mu(X)-\mu(Y)$
So you need information regarding the covariance to calculate the answers properly if $X$ and $Y$ are not independent.
EDIT:
$$Cov(X,Y)=\sum_{i=1}^{n}\frac{(x_i-\bar x)(y_i-\bar y)}{\sigma_x\sigma_y}$$
Comment: Unfortunately, that is all of the data that I was given by my professor and from what I have seen it is possible to calculate this number, however, I still cannot seem to calculate the standard deviation.
Comment: What is the standard deviation according to answer?


Formatador de datas não esta funcionado

Question: Tenho um código que supostamente passa para o formato dd-mm-yyyy ou por exemplo 02-10-2017 mas o meu problema é que este código em vez de passar para 02-10-2017 esta a passar para 2-10-2017.
Código :
dt = 2 + "-" + 10 + "-" + 2017;
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
try {
    sdf.parse(dt);
    date_text.setText(dt);
    Log.d(tag,""+dt);
} catch (ParseException e) {
    e.printStackTrace();
}

No log tenho este resultado :
07-13 20:42:25.914 12020-12020/com.pedrogouveia.averagemaker D/tag: 2-10-2017

Código atualizado :
        @Override
        public void onDateSet(DatePicker datePicker, int year, int month, int day) {
            month = month + 1;
            date_button.setVisibility(View.GONE);
            date_text = (TextView) rootView.findViewById(R.id.date_text);
            date_text.setVisibility(View.VISIBLE);
            dt = day + "-" + month + "-" + year;
            SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
            dataInterpetrada = sdf.format(dt);     <---------Esta linha  esta vermelha e esta dizendo incompatible types java.util.dates and java.lang.string
            dt = sdf.format(dataInterpetrada);
            date_text.setText(dt);

        }
    };

Mais em baixo adiciono dt á minha database como string
Comment: Estranho, você escreveu `dt = 2 + "-" + 10 + "-" + 2017;`, mas o log diz `D/tag: 14-7-2017`, será que você não fez alguma confusão?
Comment: Não era so um exemplo o 2-10-2017 o meu tem um dataPicker
Answer: O parse do SimpleDateFormat devolve a data que foi interpretada.
Logo é suposto ser algo como:
Date dataInterpretada = sdf.parse(dt);

E se a quiser escrever no Log com o formato anterior é necessário usar o format do mesmo objeto do formato:
Log.d(tag,""+ sdf.format(dataInterpretada ));

Pequeno teste em java para confirmar.
Completando o código apresentado:
dt = 2 + "-" + 10 + "-" + 2017;
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
try {
    Date dataInterpretada = sdf.parse(dt); //agora guarda a data interpretada
    date_text.setText(sdf.format(dataInterpretada )); //agora com format
    Log.d(tag,""+sdf.format(dataInterpretada )); //e aqui com format também
} catch (ParseException e) {
    e.printStackTrace();
}

Edit:
O SimpleDateFormat devolve uma data do tipo java.util.date e não java.sql.date.
Para resolver este problema ou troca o import ou pode trocar apenas na criação da data fazendo:
java.util.Date dataInterpretada = sdf.parse(dt);

Comment: @PedroGouveia me parece que é exatamente isto que o codigo do Isac faz, transforma em string. Entendeu? O parse converte para um objeto, o correto é usar .format.
Comment: Não eu queria mesmo transformar esta data numa string , so que numa string no formato 02-10-2017 , como faço ?
Comment: Quando uso .format em vez de .parse , tenho este erro : java.lang.IllegalArgumentException: Bad class: class java.lang.String
Comment: Qual a linha de código onde está a ser utilizado o `format`
Comment: Como voce esta dizendo nao da porque diz que é preciso ser uma string para receber.
Comment: o sdf.parse(dt)
Comment: O `format` devolve a data em formato `String`, logo pode ser utilizada em qualquer lugar que se espera uma `String`. E tem que ter as duas partes. Quando for para interpretar a data usa só `parse`, e quando for para mostrar no `Log` ou noutro sitio usa só `format`
Comment: Eu vou editar com o código que atualizado depois diga me alguma coisa
Comment: Ja editei pode dizer sua opinião por favor ?
Comment: O problema está no `import` o parse devolve um `java.util.date` e não um `java.sql.date`. Ou troca o `import` ou quando recebe a data tem que é indicar que é do tipo `java.util.Date`. Vou editar a resposta para contemplar isso também
Comment: Pai voce me salvou , se pudesse ate te dava 10 certos fodasse, voce para que ? Tu es tuga! é bem ! obrigado

Formatador de datas não esta funcionado


Redis script for memory flush

Question: Is it possible to create a script for Redis that flush its memory when it is above a certain value?
In my specific case, I want a flush when the memory is above 90%.
What is the best way, via bash script or Lua script?
Comment: Does this answer your question? [Abuse cURL to communicate with Redis](https://stackoverflow.com/questions/33243121/abuse-curl-to-communicate-with-redis)
Comment: this doesn't answer me. Maybe for more information, I'm using GCP Memorystore
Comment: If I use `(printf "MEMORY STATS\r\n";) | nc REDIS_IP 6379` I obtain all the values. Is there a way to see only a field? I'm looking for something like a `grep`
Comment: Maybe this command is more useful `redis-cli -h REDIS_IP -p 6379 memory stats` than the first one
Answer: I would use a Lua script as it will perform faster, atomically, and it would be easy to use both from redis-cli and any application code.
Here a Lua script to get memory used and maxmemory, the percent, and an action placeholder. It uses both MEMORY STATS and INFO memory to illustrate.
MEMORY STATS brings structured information, but doesn't include maxmemory or total_system_memory, as INFO memory does. CONFIG GET is not allowed from Lua scripts.
local stats = redis.call('MEMORY', 'STATS')
local memused = 0
for i = 1,table.getn(stats),2 do
    if stats[i] == 'total.allocated' then
        memused = stats[i+1]
        break
    end
end
local meminfo = redis.call('INFO', 'memory')
local maxmemory = 0
for s in meminfo:gmatch('[^\\r\\n]+') do
    if string.sub(s,1,10) == 'maxmemory:' then
        maxmemory = tonumber(string.sub(s,11))
    end
end
local mempercent = memused/maxmemory
local action = 'No action'
if mempercent > tonumber(ARGV[1]) then
    action = 'Flush here'
end
return {memused, maxmemory, tostring(mempercent), action}

Use as:
> EVAL "local stats = redis.call('MEMORY', 'STATS') \n local memused = 0 \n for i = 1,table.getn(stats),2 do \n     if stats[i] == 'total.allocated' then \n     memused = stats[i+1] \n break \n end \n end \n local meminfo = redis.call('INFO', 'memory') \n local maxmemory = 0 \n for s in meminfo:gmatch('[^\\r\\n]+') do \n     if string.sub(s,1,10) == 'maxmemory:' then \n     maxmemory = tonumber(string.sub(s,11)) \n end \n end \n local mempercent = memused/maxmemory \n local action = 'No action' \n if mempercent > tonumber(ARGV[1]) then \n     action = 'Flush here' \n end \n return {memused, maxmemory, tostring(mempercent), action}" 0 0.9
1) (integer) 860264
2) (integer) 100000000
3) "0.00860264"
4) "No action"

Answer: That's the way to obtain the allocated memory redis-cli -h 22.214.171.124 -p 6379 memory stats | sed -n 4p. Now it's easy to create a bash script

Redis script for memory flush


How to set multiple entity references as default values using the hook_form_alter()

Question: I have a node which when renders an adds an entityform to the page.
The node has a entity ref field which references multiple other nodes. (eg: Products A, Product B, Product C, etc)
What I need is a rating from each user for each product who views the node.
Eg :
Node 1 | User 1
Product A : rating1
Product B : rating2
Product C : rating3
Node 1 | User 2
Product A : rating4
Product B : rating5
Product C : rating6
How could i establish such a thing?
Answer: You can use Fivestar and Voting API for rating the product
The Fivestar voting module adds a clean, attractive voting widget to nodes and comments and any entity


Publish the web Api in different server

Question: I am new to WEB API,which i want to publish in Hostgator server and need the URL so i can access through my app,Is there any procedure, so i need to do before  publishing web api 2 in different windows server.
Answer: If you want to debug your application that use Web API 2 and your API is separate project you can open second Visual Studio instance and build project there. You'll get localhost URL.
Another option is to use Local IIS and setup your own domain. In this case you must configure Local IIS and hosts.
Last option (if you have one Visual Studio solution with Web API and App projects) is to debug every project as separate instance. Right click on VS project name > Debug > Start new instance.
Comment: i have hostgator windows server ,i want to host my web api in my server is it possible,i have hosted it but, i am not getting proper url need help
Comment: I do not understand what you want to achieve. What do you mean "I am not getting proper url"? If you have own dedicated windows server, you must configure web server (IIS, services, .NET Framework, firewall)... Your server has public IP address and you need to buy domain name and set your DNS records to point this IP address. I suppose if you bought a server, you know how to set it up. Do not hesistate to write me what exactly you need to achieve.
Comment: thanks,i have hostgator windows server with firstname.lastname@example.com,inside hostgator windows server,i have created the folder  with name webapi,and i have add files which consist of web api publish from my VS2015,now i need to get the url to access it from my app lik (mydomain/controller/action)
Comment: As I wrote above, you must configure your web server first. I do not know hostgator provides pre-configured server. Your application code should by placed in c:\inetpub\wwwroot by default. If you place your application code to another folder, you must set up the website in IIS.
Comment: its a pre-configured server please suggest me how i can place my file in there path

Publish the web Api in different server


fetch data from twitter when login

Question: i want to make app that login with twitter so i want to fetch some data from twitter account such as id,username, and email.
i have an api that take the 3 parameters and return success so i want to get the 3 parameters.
i have a custom button and i want when i tap this button i want to get twitter page and after i write username and password i want to fetch data
i configure twitter and fabric account.
i only want a function to fetch this data for me.
thanks in advance
func application(_ application: UIApplication,
                 didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    Fabric.with([TWTRTwitter.self])

    // twitter configration

    TWTRTwitter.sharedInstance().start(withConsumerKey:"----------", consumerSecret:"-------")

    return true
}

Answer: You can fetch data from twitter by using following method:
Twitter.sharedInstance().logIn { (session, error) in

            if (session != nil) {
                let credential = TwitterAuthProvider.credential(withToken: (session?.authToken)!, secret: (session?.authTokenSecret)!)

                let username = session?.userName
                let userId = session?.userID

                print("Username: \(username ?? "")")
                print("UserId: \(userId ?? "")")

                let client = TWTRAPIClient.withCurrentUser()
                client.requestEmail(forCurrentUser: { (email, error) in
                    if error == nil{
                        if email != nil{
                            let email = email
                            print("Email: \(email ?? "")")
                        }
                    }else{
                        print("error: \(error?.localizedDescription ?? "")")
                    }
                })

            }else{
                print("error: \(error?.localizedDescription ?? "")")
            }
}

Hope this will help you.
Comment: why you write credential also you do not use it ?
Comment: and why i get this error ?   objc[5534]: Class TWTRAppAuthProvider is implemented in both /Users/mohamedeldewaik/Library/Developer/CoreSimulator/Devices/39D130B2-2965-41AA-838A-0DC6A608328B/data/Containers/Bundle/Application/1B22A364-6ABA-442F-990F-A2673C9AC12F/Garage.app/Frameworks/TwitterKit.framework/TwitterKit (0x1073da548) and /Users/mohamedeldewaik/Library/Developer/CoreSimulator/Devices/39D130B2-2965-41AA-838A-0A2673C9AC12F/Garage.app/Frameworks/TwitterCore.framework/TwitterCore (0x107252370). One of the two will be used. Which one is undefined.
Comment: Only use TwitterKit framework rather than both and then check. May be you will not get this error.
Comment: I have write credential to show you that you use this as further for other purpose.
Answer: Declare variable:
var twiterUserdata: [String:Any] = [:]

function for get user Info:
 func twitterUserInfo(){
        TWTRTwitter.sharedInstance().logIn(completion: { (session, error) in
            let client = TWTRAPIClient.withCurrentUser()
            client.requestEmail { emailId, error in
                if (emailId != nil) {
                    let name = session?.userName
                    let email = emailId
                    self.twiterUserdata["name"] = name
                    self.twiterUserdata["email"] = email
                    TWTRTwitter.sharedInstance().sessionStore.session()
                    print(self.arrTwiterUserdata)
                } else {
                    print("error: \(String(describing: error?.localizedDescription))");
                }
            }
        })
    }

Hope It's helps to you.!!

fetch data from twitter when login


Trying to push or add a custom json on a json

Question: Basically, am working with json objects however my skills are not that much because I am still a newbie in javascript and json or object literals. Am trying to achieve where I would like to push or insert a custom json object at the last element of the other xml/json file. Is there any on way how to do this? I've been trying to do it for quite some time now but could not make it work. Any idea how to make it work? because honestly, I don't have any left :-)
I use getJSON to request a JSON from my website. It works great, but I need to somehow insert another custom object literals at the end of the json is it possible?
By the way here is my code.
$(function() {
        $.getJSON('https://some_link_from_a_server_that_produces_xml_file_or_json',

            function(data) {
                //var dataLength = data.length;

                fillData();

                function fillData() {

                    var jsonData = [{
                        "LastModification": "04:27:48",
                        "Symbol": "EURUSD",
                        "Bid": '1.20568',
                        "Ask": "1.21238",
                        "High": '1.21789',
                        "Low": '1.19253',
                        "Direction": "-1",
                        "InserTime": "\/Date(1358760600163)\/",
                        "volume": "0"
                    }];

                    for (var i = 0; i < jsonData.length; i++) {
                        data.push([
                            parseFloat(jsonData[i].Bid),
                            parseFloat(jsonData[i].High),
                            parseFloat(jsonData[i].Low),
                            parseFloat(jsonData[i].Ask),
                            parseInt(jsonData[i].InserTime.substr(6)),
                            parseInt(jsonData[i].volume)
                        ]);
                    }
                    CreateChart();
                }  // end of function fillData()

                function CreateChart() {
                    var chart = new Highcharts.stockChart('container2',
                            {
                                title: {
                                    text: 'EUR/USD',
                                    floating: true,
                                    align: 'left',
                                    x: 0,
                                    y: 55
                                },
                                subtitle: {
                                    text: 'highest: 1.23223 / lowest: 1.21774',
                                    floating: true,
                                    align: 'left',
                                    x: 0,
                                    y: 70
                                },
                                xAxis: {
                                    gridLineWidth: 1
                                },
                                yAxis: {
                                    gridLineWidth: 1
                                },
                                rangeSelector: {
                                    buttons: [
                                        {
                                            type: 'hour',
                                            count: 1,
                                            text: '1h'
                                        }, {
                                            type: 'day',
                                            count: 1,
                                            text: '1D'
                                        }, {
                                            type: 'all',
                                            count: 1,
                                            text: 'All'
                                        }
                                    ],
                                    selected: 1,
                                    inputEnabled: true
                                },

                                series: [
                                    {
                                        name: 'EURUSD',
                                        type: 'candlestick',
                                        data: data,
                                        tooltip: {
                                            valueDecimals: 5
                                        }
                                    }
                                ]
                            }); // end of highcharts.stockchart
                }
            });
    });

Comment: Can you provide what is the body of you JSON looks like when you receive it?
Comment: See, you may not want to add any property to the end of JSON object as order is irrelevant for object's properties. Where as you may push some elements at the end of JSON arrays.
Comment: Thank you for the reply. here is what it looks like @Harish Soni

https://imgur.com/a/KaTfHYW

basically it's a historical data.
Comment: @Satish kumar. Yes basically I am looking for a way to use .push() method. I think I used it already, but no success. I guess I am missing something.
Answer: I think you are making a array of JSON which looks like [{...}, {...}]
However, in your code you are making an array of array which looks like [[...], [...]].
Try :

let data = [];

const func = function(data) {
 fillData();

 function fillData() {

  var jsonData = [{
   "LastModification": "04:27:48",
   "Symbol": "EURUSD",
   "Bid": '1.20568',
   "Ask": "1.21238",
   "High": '1.21789',
   "Low": '1.19253',
   "Direction": "-1",
   "InserTime": "\/Date(1358760600163)\/",
   "volume": "0"
  }];

  for (var i = 0; i < jsonData.length; i++) {
   data.push({
    Bid :parseFloat(jsonData[i].Bid),
    High : parseFloat(jsonData[i].High),
    Low : parseFloat(jsonData[i].Low),
    Ask : parseFloat(jsonData[i].Ask),
    InserTime : parseInt(jsonData[i].InserTime.substr(6)),
    Volume :parseInt(jsonData[i].volume)
   });
  }
  console.log(data);
 }  // end of function fillData()
}
func(data);
Comment: Thanks for the reply @Sam Ho, I will try to restructure my code and use your code snippet.


Image Url In C#

Question: I am Using A Hard coded Image In My Web App When I Uploaded My Web App The Default Image Url IS

http://localhost:61111/Images/blank_profile_female.jpg

But I want My Default Url As
..../Images/blank_profile_female.jpg

I did Something Like This
imgbx.ImageUrl = "http://localhost61111/Images/facebook-default-no-profile-pic.jpg";

Is It Possible?
Comment: yes, it is possible.
Comment: What have you tried so far, and what results did you get?
Comment: @Daniel I did Something Like This

`imgbx.ImageUrl = "http://localhost61111/Images/facebook-default-no-profile-pic.jpg";`
Comment: Just use `/Images/blank_profile_female.jpg`. As in `` This will be relative to your root. That said your question is unclear. What do you mean by default URL, etc?
Comment: Yes It Is Unclear I Should Not Use Default, Its Just The Url Of The Image
Answer: For MVC application
Url.Content("~/Images/blank_profile_female.jpg")

For Web Application
Server.MapPath("~/Images/blank_profile_female.jpg");

Comment: I am Doing This Code In Back End
Comment: Is it a mvc application or simple web application?
Comment: Web Application

Image Url In C#


Background com Parallax não aparece

Question: https://codepen.io/carcleo/pen/JjbYQWa
No código abaixo (e também no codepen acima) eu tenho 2 div's onde estou fazendo um efeito parallax.
Mas eu preciso fazer o efeito acontecer com fundo opaco. uns 30% de opacidade e isso não consigo diretamente na div sem atingir também o conteúdo.
Logo, estou fazendo no ::before da div. Mas o background não aparece de jeito nenhum.
Poderiam me ajudar por favor a entender?

$('.prlx::before').each(function() {

    var obj = $(this);

    obj.css('background-position', '50% 0');
    obj.css('background-attachment', 'fixed');

    $(window).scroll(function() {

        var offset = obj.offset();
        var yPos = -($(window).scrollTop() - offset.top) / 10;
        var bgpos = obj.css('background-position-x') + ' ' + yPos + 'px';
        obj.css('background-position', bgpos);

    });

});
#detalhes {
    position: relative;
    width: 100vw;
    height: 600px;
}
#contato {
    position: relative;
    width: 100vw;
    height: 800px;
}
#detalhes::before {
    content:'';
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    opacity: .2;
    background-image: url("https://i.stack.imgur.com/vxxg4.jpg") ;
    background-size: cover;
}
#contato::before {
    content:'';
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    opacity: .2;
    background-image: url("https://i.stack.imgur.com/D0Mls.jpg") ;
    background-size: cover;
}

Comment: Acho que não é possível selecionar esse tipo de elemento `:before`, `:after` seu selector => `'.prlx::before'` , você vai ter que manipular de outra forma
Comment: Link relacionado no stackoverflow en - [Selecting and manipulating CSS pseudo-elements such as ::before and ::after using javascript \(or jQuery\)](https://stackoverflow.com/a/21709814/2456894)
Answer: Pelo que entendi você quer deixar o fundo "opaco" sem afetar a opacidade do conteúdo, se for isso você pode usar manipular a cor do fundo em códico rgba
e usar a lógica em javascript para mudar a cor de fundo em determinada situação exemplo:

 Text added.

Parece que a cor de fundo é cinza, mais é preto com 30% da cor "desbotado", você pode manipular para dar a cor de fundo na opacidade que você quer
Deixei a cor da tag p branco pra mostrar que não afeta o comportamento :)
Edit: Encontrei uma resposta não muito antiga para exatamente o mesmo problema está é a seguinte:

Não há nada chamado opacidade de fundo. A opacidade é aplicada ao elemento, seu conteúdo e todos os seus elementos filho. E esse comportamento não pode ser alterado apenas substituindo a opacidade nos elementos filhos.
A opacidade dos filhos e dos pais tem sido um problema antigo e a correção mais comum é usar rgba(r,g,b,alpha)cores de fundo. Mas neste caso, por se tratar de uma imagem de fundo, essa solução não funcionará. Uma solução seria gerar a imagem como PNG com a opacidade necessária na própria imagem. Outra solução seria tirar o div filho e torná-lo absolutamente posicionado.

Porém de outras respostas ... encontrei um operador do css chamado background-blend-mode um exemplo deste:

Only one div needed

No CSS:
div#content {
 background-image: url(my_image.png);
 background-color: rgba(255,255,255,0.6);
 background-blend-mode: lighten;
 /* Você pode adicionar largura de fundo etc*/
}

Ele irá mesclar a cor de fundo ( com a opacidade 0,6) na imagem de fundo.
Porem tem vários operadores para se usar o background-blend-mode não é só o lighten que foi usado no exemplo.
Comment: Não -e cor de fundo, se fosse, usaria rgba() mas é imagem de fundo. Essa está sendo a minha dificuldade.
Comment: Editado :) esqueci de avisar kkk
Comment: Não entendi muito bem. Você está usando a imagem e uma cor de fundo juntas . O background-blend-mode: lighten; vai afetar a imagem de fundo ou a cor de fundo? Precisa necessariamente ser a imagem e não tem necessidade de uma cor de fundo. Salvo se o objetivo seja aguardar o carregamento da imagem,
Comment: Sim, usei a cor de fundo, porque o `background-blend-mode` não funciona sem o `background-color` mas é no background-color que você ajusta o quanto você quer de opacidade, nesse caso a opacidade é de 0,6 se quiser uma menor pode trocar o 6 pelo 3 aí vai ficar com 0,3 de opacidade.
Comment: Desculpe, não deu certo. Veja: https://codepen.io/carcleo/pen/BaQjYyV
Comment: no caso da opacidade onde diz "nao há nada ..." o ::before resolve esse problema pois é um bloco dentro e no inicio da div. No caso, a opacidade está send aplicado ao bloco e não a imagem de fundo
Comment: Todo aquele texto onde diz "Não há nada ..." foi uma resposta de 2012 que encontrei sobre este problema, e a última resposta com o exemplo acima foi uma de 2016 que encontrei sobre isto. Não entendi o que quis dizer quando diz que a opacidade está sendo aplicada ao bloco, pois a opacidade da imagem muda, agora a opacidade do conteúdo não mudou junto. Olha como testei https://codepen.io/Maria_eduarda/pen/OJbMqVY
Comment: obrigado. entendi Deu certo: https://codepen.io/carcleo/pen/JjbYQWa

Background com Parallax não aparece


How can I recursively create a UL/LI's from JSON data - multiple layers deep

Question: I am trying to use use the following JSON data to create the following similar structure in a recursive inner function with not much luck, really need some help and so if anyone can assist please do. Thank you in advance.

                         ....etc

the JSON data I am using is as follows:
    var JSON = {
    menu: [
        {id: '0',sub: [
            {name: 'lorem ipsum 0-0',link: '0-0', sub: null},
            {name: 'lorem ipsum 0-1',link: '0-1', sub: null},
            {name: 'lorem ipsum 0-2',link: '0-2', sub: null}
            ]
        },
        {id: '1',sub: null},
        {id: '2',sub: [
            {name: 'lorem ipsum 2-0',link: '2-0', sub: null},
            {name: 'lorem ipsum 2-1',link: '2-1', sub: null},
            {name: 'lorem ipsum 2-2',link: '2-2', sub: [
                {name: 'lorem ipsum 2-2-0',link: '2-2-0', sub: null},
                {name: 'lorem ipsum 2-2-1',link: '2-2-1', sub: null},
                {name: 'lorem ipsum 2-2-2',link: '2-2-2', sub: null},
                {name: 'lorem ipsum 2-2-3',link: '2-2-3', sub: null},
                {name: 'lorem ipsum 2-2-4',link: '2-2-4', sub: null},
                {name: 'lorem ipsum 2-2-5',link: '2-2-5', sub: null},
                {name: 'lorem ipsum 2-2-6',link: '2-2-6', sub: null}
            ]},
            {name: 'lorem ipsum 2-3',link: '2-3', sub: null},
            {name: 'lorem ipsum 2-4',link: '2-4', sub: null},
            {name: 'lorem ipsum 2-5',link: '2-5', sub: null}
            ]
        },
        {id: '3',sub: null}
    ]
}

and the code I have created (incomplete, this is the brain teaser I need help on) is:
$(function(){

    $.fn.dropdown = function(settings){
        var that = this;
        var settings = $.extend({}, $.fn.dropdown.defaults, settings);
        var methods = {
            isArray: function(o){
                return Object.prototype.toString.call(o) === '[object Array]';
            },
            createDropdownCode: function(arr){
                var menu = arr.menu;
                var html = null;
                var menusort = function(menu){
                    html = that;

                    that.find("li").each(function(idx){

                        var menuList = menu[idx].sub;
                        var baseContainer = $(this);
                        var count = -1;

                        var subsort = (function(){

                            count += 1;

                            return function(submenu, pb){

                                var subblock;
                                subblock = $("
").append('
');

                                if(methods.isArray(submenu)){

                                    for(var i=0;i<submenu.length;i++){

                                        var l = $("
").append(""+ submenu[i].name +"");

                                        subblock.find('ul').append(l);

                                        if(pb !== undefined && i == submenu.length-1){
                                            pb.append(subblock)
                                        }

                                        if(methods.isArray(submenu[i].sub)){
                                            subsort(submenu[i].sub, subblock.find('ul li').eq(i));
                                        }

                                    }
                                }
                            }
                        })()
                        subsort(menuList)
                    })
                }
                menusort(menu);
                return null; //html !== null ? html.html() : null;
            },
            init: function(){

                // filter through json
                // create the div=>ul=>li
                if(settings.jsonData === undefined || settings.jsonData === null){
                    console.warn('No JSON Data passed')
                    return;
                }else{
                    if(!methods.isArray(settings.jsonData.menu)){
                        console.warn('No JSON Data passed')
                        return; // error, no data!
                    }
                }

                //var html = methods.createBlock(settings.jsonData.menu[0].sub);
                var html = methods.createDropdownCode(settings.jsonData);
                //console.log(html)
            }
        }

        methods.init();

        return that;

    }

    $.fn.dropdown.defaults = {
        jsonData: null
    }

})

$('#menu').dropdown({
    jsonData: JSON
});

integrated code used, thanks to the individual that gave a close enough answer - Although will study the others.
$.fn.dropdown = function(settings){

    var that = this;
    var settings = $.extend({}, $.fn.dropdown.defaults, settings);

    var methods = {
        createDropDownCode: function(arr){

            // loop through li's of primary menu
            that.find("li").each(function(idx){

                $(this).append( menusort(arr.menu[idx].sub) );

                function menusort(data){
                    if(data !== null)
                        var html = "

";

                    for(item in data){
                        html += "
";
                        if(typeof(data[item].sub) === 'object'){
                            html += "" + data[item].name + "";
                            if($.isArray(data[item].sub))
                                html += menusort(data[item].sub);
                        }
                        html += "
"
                    }
                    if(data !== null)
                        html += "

";
                    return html;
                }
            })
        },
        init: function(){
            var html = methods.createDropDownCode(settings.jsonData);

        }
    }

    methods.init();

}

Comment: To note I know there is an isArray method in JQuery.
Answer: You can try this recursive function I've just coded:
function buildList(data, isSub){
    var html = (isSub)?'
':''; // Wrap with div if true
    html += '
';
    for(item in data){
        html += '
';
        if(typeof(data[item].sub) === 'object'){ // An array will return 'object'
            if(isSub){
                html += '' + data[item].name + '';
            } else {
                html += data[item].id; // Submenu found, but top level list item.
            }
            html += buildList(data[item].sub, true); // Submenu found. Calling recursively same method (and wrapping it in a div)
        } else {
            html += data[item].id // No submenu
        }
        html += '
';
    }
    html += '
';
    html += (isSub)?'
':'';
    return html;
}

It returns the html for the menu, so use it like that: var html = buildList(JSON.menu, false);
I believe it is faster because it's in pure JavaScript, and it doesn't create text nodes or DOM elements for every iteration. Just call .innerHTML or $('...').html() at the end when you're done instead of adding HTML immediately for every menu.
JSFiddled: http://jsfiddle.net/remibreton/csQL8/
Comment: is concatination of a string faster than using jQuery to create the dom elements?
Comment: just checked it out, great - looks like I can use this for my needs or at least mold it to what I am trying to accomplish. thanks! btw, are there recursion patterns that I can use?
Comment: Yes, concatenation is faster than creating DOM elements. I'm glad it helps.
Comment: I'm not sure what you mean by recursion patterns?
Comment: I just inspected the html that is coming out from this method, and it looks to be very buggy - chrome is very forgiving, any thoughts? seems to be allot of empty '' tags.
Comment: I made a fe alterations, I have added the code (wrapped in a plugin) to this thread for others (and your self) to see.
Comment: ahh to patterns I am just wondering if there are particular programming patterns that have been used for recursion and are designed for such a method?
Comment: Okay, yeah I just realized it produces 'undefined' values. I'm JSFiddling it if you want: http://jsfiddle.net/remibreton/csQL8/
Comment: i can't see jsfiddle, please update, really need this @RémiBreton
Comment: Thanks @RémiBreton. Your answer is very helpful for my work. Many Thanks!
Comment: This code that you have posted helped me to make the recursive function I was trying to build. Thank you!
Comment: yeah, using the recursive function!
Answer: Make two functions makeUL and makeLI.  makeUL calls makeLI on each element, and makeLI calls makeUL if there's sub elements:
function makeUL(lst) {
    ...
    $(lst).each(function() { html.push(makeLI(this)) });
    ...
    return html.join("\n");
}

function makeLI(elem) {
    ...
    if (elem.sub)
        html.push('
' + makeUL(elem.sub) + '
');
    ...
    return html.join("\n");
}

http://jsfiddle.net/BvDW3/
Needs to be adapted to your needs, but you got the idea.
Answer: Pure ES6
var foo=(arg)=>
`

${arg.map(elem=>
    elem.sub?
        `<li>${foo(elem.sub)}</li>`
        :`<li>${elem.name}</li>`
    ).join('')}

`

JSON example
   var bar = [
  {
    name: 'Home'
  }, {
    name: 'About'
  }, {
    name: 'Portfolio'
  }, {
    name: 'Blog'
  }, {
    name: 'Contacts'
  }, {
    name: 'Features',
    sub: [
      {
        name: 'Multipage'
      }, {
        name: 'Options',
        sub: [
          {
            name: 'General'
          }, {
            name: 'Sidebars'
          }, {
            name: 'Fonts'
          }, {
            name: 'Socials'
          }
        ]
      }, {
        name: 'Page'
      }, {
        name: 'FAQ'
      }
    ]
  }
]
var result=foo(bar)

Your 'result' will be valid HTML
Answer: This solution uses a single recursive function. I simplified logic by using Array's map() prototype function.

$(function () {
    $("body").html(makeUnorderedList(getData().menu));
});

function makeUnorderedList(data, li) {
    return $('
').append(data.map(function (el) {
        var li = li || $('
');
        if (el.id || el.link) li.append($('', {
            text : el.id || el.link,
            href : '#' + (el.id || el.link),
            name : el.name
        }));
        if (el.sub) li.append(makeUnorderedList(el.sub, li));
        return li;
    }));
}

function getData() {
    return {
        menu: [{
            id: '0',
            sub: [{
                name: 'lorem ipsum 0-0',
                link: '0-0',
                sub: null
            }, {
                name: 'lorem ipsum 0-1',
                link: '0-1',
                sub: null
            }, {
                name: 'lorem ipsum 0-2',
                link: '0-2',
                sub: null
            }]
        }, {
            id: '1',
            sub: null
        }, {
            id: '2',
            sub: [{
                name: 'lorem ipsum 2-0',
                link: '2-0',
                sub: null
            }, {
                name: 'lorem ipsum 2-1',
                link: '2-1',
                sub: null
            }, {
                name: 'lorem ipsum 2-2',
                link: '2-2',
                sub: [{
                    name: 'lorem ipsum 2-2-0',
                    link: '2-2-0',
                    sub: null
                }, {
                    name: 'lorem ipsum 2-2-1',
                    link: '2-2-1',
                    sub: null
                }, {
                    name: 'lorem ipsum 2-2-2',
                    link: '2-2-2',
                    sub: null
                }, {
                    name: 'lorem ipsum 2-2-3',
                    link: '2-2-3',
                    sub: null
                }, {
                    name: 'lorem ipsum 2-2-4',
                    link: '2-2-4',
                    sub: null
                }, {
                    name: 'lorem ipsum 2-2-5',
                    link: '2-2-5',
                    sub: null
                }, {
                    name: 'lorem ipsum 2-2-6',
                    link: '2-2-6',
                    sub: null
                }]
            }, {
                name: 'lorem ipsum 2-3',
                link: '2-3',
                sub: null
            }, {
                name: 'lorem ipsum 2-4',
                link: '2-4',
                sub: null
            }, {
                name: 'lorem ipsum 2-5',
                link: '2-5',
                sub: null
            }]
        }, {
            id: '3',
            sub: null
        }]
    };
}

Extension
Here is a more dynamic approach. You get to choose how your list items are rendered and what the child property is. The mapFunc paramater is a callback that gives you access to the current child node and its parent.
The scope of the mapFunc is the item. So you could use item as well as this to refer to said item.
$(function () {
    $("body").html(makeUnorderedList(getData().menu, function(item, index, parent) {
      // `item` and `this` are the same.
      return $('', {
            text : (item.id || item.link),
            href : '#' + (item.id || item.link),
            name : item.name,
            'data-index' : index
        });
    }, 'sub'));
});

function makeUnorderedList(data, mapFunc, childProp, li, parent) {
    return $('
').append(data.map(function (el, index) {
        var li = li || $('
');
        li.append(mapFunc.call(el, el, index, parent));
        if (el[childProp]) {
            li.append(makeUnorderedList(el[childProp], mapFunc, childProp, li, data));
        }
        return li;
    }));
}

Comment: Thanks, it was very helpful! Apprecidated
Answer:
Fiddle

Code:
JS
var jsonstring = [{
  "id": '1',
  "children": [{
    "id": '2'
  }, {
    "id": '3',
    "children": [{
      "id": '4'
    }]
  }]
}, {
  "id": '5'
}];

 var htmlStr= recurse( jsonstring );
$('#test').append(htmlStr);

function recurse( data ) {
  var htmlRetStr = "
";
  for (var key in data) {
        if (typeof(data[key])== 'object' && data[key] != null) {
        var x=key*1;
        if(isNaN(x)){
            htmlRetStr += "
" + key + ":
";
            }
            htmlRetStr += recurse( data[key] );
            htmlRetStr += '

';
        } else {
            htmlRetStr += ("
" + key + ': "' + data[key] + '"
' );
        }
  };
  htmlRetStr += '
';
  return( htmlRetStr );
}

HtML

CSS
li ul ul li {
    padding-left: 10px;
}

li ul ul ul {
    padding: 0px;
}

Answer: I was searching for general parent child element function and I saw these answers,
 and I took some pieces of code from here and there and made this function.
I decided to share my code as an answer,
 in case someone like me will find this post  when he is searching for a general parent child html element draw function:
function drawRecElements(arr, html, elements) {
    if (typeof (html) === 'undefined') {
        var html = '';
    }
    if (typeof (elements) === 'undefined') {
        var elements = {child: '
', childClose: '
', parent: '
', parentClose: '
'};
    }
    if (typeof (arr) === 'string') {
        return elements.child + arr + elements.childClose;
    } else if (typeof (arr) === 'object') {
        for (i in arr) {
            if (typeof (arr[i]) === 'string') {
                html += elements.parent + elements.child + i + elements.childClose + elements.child + arr[i] + elements.childClose + elements.parentClose;
            } else if(typeof (i) === 'string' && (isNaN(i))){
                html += elements.parent + elements.child + i + elements.childClose + elements.child + drawRecElements(arr[i],'',elements) + elements.childClose + elements.parentClose;
            } else if (typeof (arr[i]) === 'object') {
               html = drawRecElements(arr[i], html,elements);
            }
        }
    }
    return html;
}

https://jsfiddle.net/kxn442z5/1/
Answer: This is like a complete solution for generating UL/LI recursively from  JSON config, which has customizable classes for each node and support of expand and collapse events for each node. This provides just a basic working model, from which you ll be able to expand and customize to your needs.
I found this answer from https://techmeals.com/fe/questions/javascript/6/How-can-I-create-a-dynamic-tree-of-UL-and-LI-from-JSON-config
Example JSON config file:
var config = {
    "Menu-1-Level-1": {
        "label": "Menu-1-Level-1",
        "type": "treeView",
        "class": "Menu-1-Level-1",
        "children": [
            {
                label: "Menu-1-Level-2",
                type: "treeView",
                "class": "Menu-1-Level-2",
                children: [
                    {
                        label: "Menu-1-Level-3",
                        class: "Menu-1-Level-3"
                    }
                ]
            },
            {
                label : "Menu-2-Level-2",
                class: "Menu-2-Level-2"
            }
        ]
    },
    "Menu-2-Level-1": {
        "label": "Menu-2-Level-1",
        "type": "treeView",
        "class": "Menu-2-Level-1",
        "children": [
            {
                label: "Menu-1-Level-2",
                class: "Menu-1-Level-2",
                type: "treeView",
                children: [
                    {
                        label: "Menu-1-Level-3",
                        class: "Menu-1-Level-3"
                    }
                ]
            },
            {
                label : "Menu-2-Level-2",
                class : "Menu-2-Level-2"
            }
        ]
    }
};

HTML Code:
<!DOCTYPE html>

    <title>Tree Menu</title>

    <link href="tree.css" rel="stylesheet">

Tree.js
var tree;

tree = function (treeNodeParent, dataObj) {
    this.dataObj = dataObj;
    this.treeNodeParent = treeNodeParent;
    this.treeNode = $(document.createElement("ul")).addClass("treeNode");
};

tree.prototype.expandCollapse = function (e) {
    var target = $(e.currentTarget), parentLabel = target.parent();

    if (parentLabel.hasClass("collapsed")) {
        parentLabel.removeClass("collapsed").addClass("expanded");
    } else {
        parentLabel.addClass("collapsed").removeClass("expanded");
    }
};

tree.prototype.attachEvents = function () {
    var me = this;
    me.treeNodeParent.delegate(".collapsed label, .expanded label", "click", me.expandCollapse);
};

tree.prototype.attachMarkUp = function () {
    var me = this;
    me.treeNodeParent.append(me.treeNode);
};

tree.prototype.getEachNodeMarkup = function (nodeObj, rootNode, selector) {
    var selectedNode, i, me = this;

    if (nodeObj.children) {

        if (!selector) {
            selectedNode = rootNode;
        } else {
            selectedNode = rootNode.find(selector);
        }

        nodeObj.class = nodeObj.class ? nodeObj.class : "";
        selectedNode.append($.parseHTML("
" + "" + nodeObj.label + "" + "

"));
        selector = selector + " li[name=" + nodeObj.label + "] > ul";

        for (i = 0; i < nodeObj.children.length; i = i + 1) {
            me.getEachNodeMarkup(nodeObj.children[i], rootNode, selector);
        }

    } else {
        nodeObj.class = nodeObj.class ? nodeObj.class : "";
        rootNode.find(selector).append($.parseHTML("
" + "" + nodeObj.label + "" + "
"));
    }
};

tree.prototype.getTree = function () {
    var component, me = this;

    for (component in me.dataObj) {
        if (me.dataObj.hasOwnProperty(component)) {
            me.getEachNodeMarkup(me.dataObj[component], me.treeNode, "");
        }
    }
    me.attachMarkUp();
    me.attachEvents();
    return me.treeNode;
};

Tree.css
.treeNode .collapsed > ul, .collapsed > li {
    display: none;
}

.treeNode .expanded > ul, .expanded > li {
    display: block;
}

testPage.js
// the variable "config" is nothing but the config JSON defined initially.
treeNode = new tree($('.treeContainer .tree'), config);
treeNodeObj = treeNode.getTree();

Look at the example provided at https://jsfiddle.net/3s3k3zLL/
Answer: An edit to an old answer brought this question back up, and I think in modern JS this becomes easier than many answers above.
Here is one solution, using template strings and parameter destructuring:

const buildMenu = (nodes) =>
  `
${nodes.map(
    ({id, name, link, sub}) => sub
      ? `<li>${name ? `${name}` : id}<div>${buildMenu(sub)}</div></li>`
      : `<li>${id || `${name}`}</li>`
  ).join('')}
`

var JSON = {menu: [{id: '0',sub: [{name: 'lorem ipsum 0-0',link: '0-0', sub: null}, {name: 'lorem ipsum 0-1',link: '0-1', sub: null}, {name: 'lorem ipsum 0-2',link: '0-2', sub: null}]}, {id: '1',sub: null}, {id: '2',sub: [{name: 'lorem ipsum 2-0',link: '2-0', sub: null}, {name: 'lorem ipsum 2-1',link: '2-1', sub: null}, {name: 'lorem ipsum 2-2',link: '2-2', sub: [{name: 'lorem ipsum 2-2-0',link: '2-2-0', sub: null}, {name: 'lorem ipsum 2-2-1',link: '2-2-1', sub: null}, {name: 'lorem ipsum 2-2-2',link: '2-2-2', sub: null}, {name: 'lorem ipsum 2-2-3',link: '2-2-3', sub: null}, {name: 'lorem ipsum 2-2-4',link: '2-2-4', sub: null}, {name: 'lorem ipsum 2-2-5',link: '2-2-5', sub: null}, {name: 'lorem ipsum 2-2-6',link: '2-2-6', sub: null}]}, {name: 'lorem ipsum 2-3',link: '2-3', sub: null}, {name: 'lorem ipsum 2-4',link: '2-4', sub: null}, {name: 'lorem ipsum 2-5',link: '2-5', sub: null}]}, {id: '3',sub: null}]}

const tree = buildMenu(JSON.menu);

document.getElementById('output').innerHTML = tree

Most of the complexity here is simply in handling different formats for nodes that have sub-arrays and those that don't and for those with name/link properties and those with just an id property.  If the input was a little more consistent, this would be simpler still.  Nonetheless, this is not a horrible version.  If you like to work with string-based DOM solutions, it's fairly clean.
Note that while modern features make the solution cleaner, we could do the same thing in ES5:
const buildMenu = (nodes) =>
  '
' + nodes.map (
    (node) => node.sub
      ? '
' + (node.name ? '' + node.name + '' : node.id) + '
' + buildMenu(node.sub) + '

'
      : '
' + (node.id || '' + node.name + '') + '
'
  ) .join ('') + '
'

Comment: Oh wait, that last version is not ES5, as it still has arrow functions.  I'll leave removing them as an exercise for the reader.  :D


On a Drupal user application form, is it possible for the user to lookup existing users?

Question: I'm looking to add a user lookup form to my Drupal site's application form. One question would ask the applicant/registrant to look up an already existing user on the site. What's the best way to go about something like this in Drupal?
Comment: The question is a bit vague. What do you mean by "look up" in this context? A search system? A list?
Comment: @cilefen I have a group of existing users who are displayed as a view (to the public). Users are on that View if they have a user role checked. So I want the 'look up' autocomplete a user (first name, last name) from that list.

It's a way of the registration giving the applicant the ability to say who (of the users on the site) referred them to the site.
Answer: Yes it is possible but would require some custom code.
Assuming you already have a form element where your autocomplete search would take place, in a hook_form_alter() or hook_form_FORM_ID_alter() you could use something like:
  // Add ajax autocomplete.
  $form['name_of_your_text_element']['#attached']['js'][] = 'misc/autocomplete.js';
  $form['name_of_your_text_element']['#autocomplete_path'] = 'ctools/autocomplete/user';

Note that you will probably need to adjust some permissions in order to allow anonymous users to see your users' information. Check /admin/people/permissions if you need to fine-tune something there.
You also need to have the ctools module enabled in order to use this functionality.


Improper integral $\int _{-\infty}^1 \arctan(e^x)\,\mathrm dx$

Question: How can I calculate this integral? $${\int _{-\infty}^{1}\textrm{arctan}(e^x)\,\mathrm dx}$$
It converges. Can I associate some constant to its value?
Comment: Have you seen [this](http://tutorial.math.lamar.edu/Classes/CalcII/ImproperIntegrals.aspx)?
Answer: $$I={\int _{-\infty}^{1}\textrm{arctan}(e^x)\,\mathrm dx}=I_1+I_2\qquad \begin{cases}
I_1=\int _{-\infty}^{0}\textrm{arctan}(e^x)\,\mathrm dx \\
I_2=\int _{0}^{1}\textrm{arctan}(e^x)\,\mathrm dx
\end{cases}$$
$$I_1=\int _{0}^{\infty}\textrm{arctan}(e^{-x})\,\mathrm dx = \int _{0}^{\infty}\sum_{n=0}^\infty \frac{ (-1)^n (e^{-x})^{2n+1} }{2n+1} dx $$
$$I_1=\sum_{n=0}^\infty\int _{0}^{\infty} \frac{ (-1)^n (e^{-x})^{2n+1} }{2n+1} dx =\sum_{n=0}^\infty \frac{ (-1)^n }{(2n+1)^2} = C \qquad \text{Catalan constant}$$
$$I_2=\int _{0}^{1}\left(\frac{\pi}{2}-\textrm{arccot}(e^x)\right)\,\mathrm dx = \frac{\pi}{2}-\int _{0}^{1}\textrm{arctan}(e^{-x})\,\mathrm dx $$
$$I_2= \frac{\pi}{2}-\int _{0}^{1}\sum_{n=0}^\infty \frac{ (-1)^n (e^{-x})^{2n+1} }{2n+1}dx =\frac{\pi}{2}-\sum_{n=0}^\infty \int _{0}^{1}\frac{ (-1)^n (e^{-x})^{2n+1} }{2n+1}dx $$
$$I_2=\frac{\pi}{2}+\sum_{n=0}^\infty \frac{ (-1)^n (e^{-(2n+1)}-1) }{(2n+1)^2} = \frac{\pi}{2}+\sum_{n=0}^\infty \frac{ (-1)^n e^{-(2n+1)} }{(2n+1)^2}-C$$
The Catalan constant is eliminated in the sum $I_1+I_2$.
$$I={\int _{-\infty}^{1}\textrm{arctan}(e^x)\,\mathrm dx}=I_1+I_2=\frac{\pi}{2}+\sum_{n=0}^\infty \frac{ (-1)^n e^{-(2n+1)} }{(2n+1)^2}$$
$${\int _{-\infty}^{1}\textrm{arctan}(e^x)\,\mathrm dx}=\frac{\pi}{2}+\frac{1}{e}-\frac{1}{9e^3} +\frac{1}{25e^5}-\frac{1}{49e^7} +...$$
The series is quickly convergent. This allows to easily compute good approximates :
$${\int _{-\infty}^{1}\textrm{arctan}(e^x)\,\mathrm dx} \simeq 1.933396177216636$$
In addition :
Thanks to the comment from Claude Leibovici, a closed form can be derived :
$${\int _{-\infty}^{1}\textrm{arctan}(e^x)\,\mathrm dx}=\frac{\pi}{2}+\frac{1}{16e}\Phi(e^{-4}\:,\:2\:,\:1/4)-\frac{1}{16e^3}\Phi(e^{-4}\:,\:2\:,\:3/4)$$
$\Phi$ is the Lerch function. http://mathworld.wolfram.com/LerchTranscendent.html
Comment: Hi Jean ! Long time no speak ! Nice manipulations, indeed ! Just for your curiosity $$\sum_{n=0}^\infty \frac{ (-1)^n e^{-(2n+1)} }{(2n+1)^2}=\frac 1e \,
   _3F_2\left(\frac{1}{2},\frac{1}{2},1;\frac{3}{2},\frac{3}{2};-\frac{1}{e^2}\right)$$
Comment: Hi Claude ! Glad to meet you again. Beautiful formula. In fact, I didn't look for a special function. Your comment draw me to search a bit further. A special function of lower level can do the job :  $$\sum_{n=0}^\infty \frac{ (-1)^n x^{2n+1}}{(2n+1)^2} = \frac{x}{16}\Phi(x^4\:,\:2\:,\:1/4)-\frac{x^3}{16}\Phi(x^4\:,\:2\:,\:3/4)$$ with $x=e^{-1}$ ; and $\Phi$ is the Lerch function.
Comment: Still nicer ! Lerch function is one of the most liked for me.
Answer: It's about $1.93$.
We get this by using the following methods:
First, we rewrite the $\arctan$ function using logarithms:
$$\int \arctan(e^x) \,dx=\int-\frac{i(\ln(ie^x+1)-\ln(1-ie^x))} 2$$
Then, by applying linearity we obtain:
$$\frac i 2 \int \ln(1-ie^x)\,dx - \frac{i}{2} \int\ln(ie^x+1) \, dx$$
By substituting $u=-ie^x$, we obtain:
$$\int \ln(ie^x+1) \,dx = \int -\frac{\ln(1-u)} u \,du=-\operatorname{Li}_2(u)=-\operatorname{Li}_2(-ie^x)$$
We do the same to $\int\ln(1-ie^x)\,dx$ with the same $u$-substitution:
$$\int ln(1-ie^x) \,dx = -\operatorname{Li}_2(ie^x)$$
Then, we back-substitute:
$$\frac i 2 \int\ln(1-ie^x)\,dx -\frac i 2 \int \ln(ie^x+1)\,dx = \frac{i\operatorname{Li}_2(-ie^x)}2 - \frac{i\operatorname{Li}_2(ie^x)} 2 + C$$
We can rewrite this in a neat way:
$$-\frac{\pi\ln(e^{2x}+1)}{4}-\frac{i\operatorname{Li}_2(ie^x-+)}2 + \frac{i\operatorname{Li}_2(1-ie^x)} 2 + x\arctan(e^x)+C$$
We evaluate at the given bounds, obtaining $\approx1.9334$


Can I programmatically add a row to a WPF datagrid?

Question: I just want to add a new row, I have my datasource in objects in which I need to do some processing.  i need something like below for wpf datagrid...
DataRow row = dataTable.NewRow();
foreach (NavItem item in record.Items)
{
    row[item.FieldNo.ToString()] = item.RecordValue;
}
dataTable.Rows.Add(row);

Comment: Why don't you bind your datasource to the wpf datagrid's itemssource and then when your datasource is updated (as in new row is added) it will be added in the wpf datagird as well.
Comment: I tried to bind the datatable to the itemssource, it works, but the header, the visiblity and other mapping with the wpf datagrid are not correct.  I tried a dictionary list, in which I wanted the key to be the column and the value the row value, which does not work. I am running out of ideas, all resources on the web, are with static columns..
Comment: My datasource is in objects which require processing before displaying, I cannot bind it directly.
Comment: I can't just bind it to an object I created, with dynamic columns??
Comment: http://stackoverflow.com/questions/704724/programatically-add-column-rows-to-wpf-datagrid
Answer: You should be using an ObservableCollection<NavItem> as the datagrid source. Then simply adding a new element to your collection will add it to the datagrid.
See this MSDN article.
Answer: I do not know if it is the right solution, but I came up to something like this, in desperation:
foreach (NavField field in this.Fields)
 {
      DataGridTextColumn column = new DataGridTextColumn();
      column.Header = field.FieldNo.ToString();

      //Some other logic
      // Hide non active and hidden fields
      if (!field.Active || !field.Show)
           column.Visibility = System.Windows.Visibility.Collapsed;

       grid.Columns.Add(column);
  }

Then I add the datatable as itemssource:
  this.dataGridLines.ItemsSource = dataTable.DefaultView;

If I set the datatable directly, it does not care about the columns from the datatable and autogenerate its own columns, don't know why..
Comment: You also need to set: AutoGenerateColumns to false;
Comment: So each time your item source changes in order that field.Show changes you would need to re-run the loop for adding the columns?
Comment: If you know what all columns you can have then you add those in XAML and bind visibility of those columns so that if in the datasource it later changed then it can be reflected. Or you can have your column collection and bind that to a DP of the view that can re-generate columns.
Comment: In fact for my situation, I have to repopulate the whole grid each time and I do not know the columns which are dynamic.


Failed to find Evans' further comments on the weak solutions to the Poisson equation

Question: Let $(M,g)$ be a compact Riemannian manifold with nontrivial boundary and let $W_0^{1,2}(M)$ be the closure of $C_c^\infty(M)$ in the Sobolev space $W^{1,2}(M)$. Suppose $f\in C^\infty(M)$. Given $u\in W_0^{1,2}$ that solves the Poisson equation $\Delta u=f$ weakly, I was trying to make $u$ become a strong (classical) solution, and all I have is the PDE book written by Evans. I knew my question is something related to the theory of regularity, and after consulting Evans' book, I was able to presume that $u$ is actually smooth and vanishing on the boundary ($C_0^\infty$), but the question remains: is smoothness enough to guarantee that $u$ solves the Poisson equation in the classical sense?
After going through Evans' book thoroughly, I found nothing more. Or maybe I was foolish enough to not tell the implications. So I came here for a piece of advice. It would be great if someone could indicate precisely where to find relevant discussions in Evans' book. Thank you.
Answer: Ill just  do it for the case where $U \subset \mathbb{R}^n$ is an open subset.
You have for any $\phi \in C_c^{\infty}(U)$
$$
\int_U \nabla u \cdot \nabla\phi \; \mathrm{d}vol=\int_U f \phi \; \mathrm{d}vol.
$$
Then, you can proceed to integrate by parts (note we can do that, since $u$  is smooth!) to arrive at
$$
\int_U(\Delta u - f)\phi \; \mathrm{d}vol
$$
for any $\phi \in C_c^{\infty}(U)$. By the fundamental lemma of the calculus of variations, we have $\Delta u=f$ almost everywhere and by continuity, it holds everywhere.
I should also mention, that in the case of smoothness the weak/distributional gradient and classical gradient agree.
Depending on your definition of the Laplacian, you can adapt this to Riemannian manifold via charts and the definition of Sobolev spaces/Laplacian via charts. Since being a classical solution is a local property, charts will work out just fine.


Problema com conexão banco firebird hibernate

Question: Tenho uma aplicação em java que disponibiliza serviços rest com servlets e hibernate, que em primeiro momento funciona perfeitamente. Posso fazer milhares de requisições a diversos serviços que recuperam informações na base firebird que ela responde muito bem...
Mas algumas vezes o firebird trava ou simplesmente é reiniciado, e então minha aplicação ficava travava com problemas de comunicação mesmo quando o banco firebird voltava a funcionar. Então era necessário reiniciar minha aplicação para voltar ao normal.
Resolvi este problema de ré-conexão, adicionando os comandas abaixo no arquivo hibernate.cfg.xml:
<property name="hibernate.c3p0.acquire_increment">5</property>
<property name="hibernate.c3p0.idle_test_period">120</property>
<property name="hibernate.c3p0.min_size">5</property>
<property name="hibernate.c3p0.max_size">20</property>
<property name="hibernate.c3p0.max_statements">50</property>
<property name="hibernate.c3p0.timeout">600</property>
<property name="hibernate.c3p0.preferredTestQuery">select 1</property>

Depois de 120 segundos que o bando parado voltava a funcionar, a aplicação também reiniciava a conexão, e permitia fazer novas requisições...
Então me deparei com um outro problema.
Depois de a aplicação voltar a funcionar, a mesma fica instável. Ela passa a retornar erros de conexão sincronizado de acordo com as quantidade de requisições: hora a cada três requisições com sucesso uma é retornada o erro (Sempre nessa ordem); e se fizer um novo teste, reiniciando a aplicação, este cronograma pode mudar, como a cada 5 requisição uma falha...
Esse erro sincronizado me parece um sintoma de um erro que me desarmou...
Todo meu código de configuração do hibernate.cfg.xml
<property name="hibernate.dialect">org.hibernate.dialect.FirebirdDialect</property>
<property name="hibernate.connection.driver_class">org.firebirdsql.jdbc.FBDriver</property>
<property name="hibernate.connection.url">jdbc:firebirdsql://localhost:3050/D:/automacao/projetos/DB/DB.FDB</property>
<property name="hibernate.connection.username">USER</property>
<property name="hibernate.connection.password">*******</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.connection.isolation">1</property>

<property name="current_session_context_class">thread</property>
<property name="connection.relaxAutoCommit">true</property>
<property name="connection.autoReconnect">true</property>
<property name="hibernate.connection.autocommit">false</property>
<property name="hibernate.connection.release_mode">on_close</property>

<property name="hibernate.c3p0.acquire_increment">5</property>
<property name="hibernate.c3p0.idle_test_period">120</property>
<property name="hibernate.c3p0.min_size">5</property>
<property name="hibernate.c3p0.max_size">20</property>
<property name="hibernate.c3p0.max_statements">50</property>
<property name="hibernate.c3p0.timeout">600</property>
<property name="hibernate.c3p0.preferredTestQuery">select 1</property>

Peço a ajuda de alguém para tentar resolver este problema.
Infelizmente não consegui uma solução, acredito que possa ser um erro no driver de conexão do firebird.
Mas consegui contornar criando um serviço do Windows que testa a aplicação de tempos em tempos e reinicia o apache tomcat se houver algum erro.
Answer: Segundo a documentação do Hibernate é altamente desencorajador utilizar a propriedade abaixo, a qual era utilizada em até a versão 2.x. Eu tiraria ela para fazer uns testes.
<property name="hibernate.connection.release_mode">on_close</property>

Outra propriedade que me parece não se adequada é a hibernate.connection.isolation. É melhor deixar o padrão usado pelo banco de dados. Se adiciona-la tem que saber exatamente que o valor passado significa o que você realmente quer alterar. No seu caso, está usando TRANSACTION_READ_UNCOMMITTED, é isso mesmo que quer?
<property name="hibernate.connection.isolation">1</property>

Uma observação:
A seguinte propriedade é false por padrão, não precisa adiciona-la a não ser que queira passar o valor para true:
<property name="hibernate.connection.autocommit">false</property>

Comment: Que chato, não sei mais o que poderia ser. Por acaso você tentou testar com outro banco de dados, tipo MySQL ou qualquer outro? As vezes pode ser um bug do banco ou do driver de conexão.
Comment: obrigado pela ajuda @ramarcio. O isolamento é este mesmo que preciso... pois é uma aplicação para controle de estoque online, então preciso saber as alterações de uma terceira transação antes mesmo da mesma ser comitada...vou fazer o teste tirando o release_mode.
Comment: @ramarcio, ainda continuou com o problema depois das alterações, erro que só acontece depois de parar e depois iniciar a base de dados.
Comment: Vou testar sim...e já imaginei isso tbm... muito obrigado pela força.


Text goes over image in Chrome/Safari, not FF or IE, using Sandbags

Question: I am using the sandbag method to have 2 lines of text appear above an image.  Here is an image showing the effect working in FF but not in Chrome (same problem in Safari):

Does anyone know what causes this?
Edit:
My apology for not posting the link: http://antigua-guide.info/ The issue can be seen halfway down the right-center column.
Here is the html and the css.
Comment: Can we have a look at it somewhere online. Or can you post the code in stead of the images
Comment: Firefox (Gecko) and Safari/Chrome (Webkit) render fonts slightly differently, which seems to be influencing your [sandbag text-wrapping technique](http://www.alistapart.com/articles/sandbags/). It's difficult for anyone to help you unless you can post a more complete or editable HTML/CSS example.
Answer: This seems like a webkit/chrome bug.  You can report it on http://code.google.com/p/chromium/issues/list . Meanwhile you can use a dirty chrome/safari hack to add some fixes to your css:
<code>@media screen and (-webkit-min-device-pixel-ratio:0) {
   .hpm2_content img, .modulebody img {
        margin-top:18px;
    }
}
</code>
Comment: Awesome.  I adapted this solution to the various sandbags (0-5 lines above the image).  Thank you very much!
Comment: +1, This bug gave me 2 hours of blood and tear ... Gonna report it right away and will test your fix. Regards


Java: Given a List of file names, make sure the corresponding XML only contains information about these filess

Question: I have a List of files (20,000 to 50,000 files), and a large xml file. I want the file XML to only contains information about the file in the List.
For example, let say we have only file XYZ on our list, and  XML files look as below.
<?xml version="1.0" encoding="ISO-8859-1"?>
<index>
<document>
    <entry number="1">
        <commentfield>
            <name>FileName</name>
            <value>XYZ</value>
        </commentfield>
    </entry>
    <entry number="2">
        <commentfield>
            <name>Note</name>
            <value>03-000</value>
        </commentfield>
    </entry>
</document>
<document>
    <entry number="1">
        <commentfield>
            <name>FileName</name>
            <value>ABC</value>
        </commentfield>
    </entry>
</document>
...
</index>

The XML contains information of two files, XYZ and ABC. Therefore, I do not want the final XML to contains the last <document> ... ABC ... </document> because this document ABC is not on our List. I have requirements successfully work in KSH script, but it runs too slow (over 4 hours for 22000 files. Well it also does something else). But I decide to port over to Java for better performance. What I have done is read line by line into a String, and when i hit </document>, then I parse out the name of the file, check if this files exist on our list, if so then write this whole <document> ... </document> to another xml file, then read again the next <document>. Is there a better way?
Already able to write code to accomplish this using DOM parser. The code are long, so if you need it, please pm me. tyvm for your help
Comment: Never ever try processing XML files with non-XML tools: that is, the idea of reading XML line by line is a very bad one. Don't do that. So at least switch to using an XML parser -- JDK 1.6 comes equipped with at least two, usable through 3 APIs (DOM, Stax, SAX) and XPath access.
Comment: @StaxMan. The problem is not with parsing the XML, but either rewrite the XML to a new XML with truncated data, or truncate data directly on the original data. Any idea?
Comment: define what *"large XML file"* means to you?
Comment: @Jarrod: Sorry, the xml file is not that big. 40MB maybe. Look at the xml sample above. There are two records above. I have seen 56,000 records so far.
Comment: Trying to truncate in place won't work well; just read in (use Stax), choose things to retain, write out. Stax easier than SAX since you have full control over reading events/tokens -- javax.xml.stream.XMLInputFactory that'll create XMLStreamReaders for reading, XMLStreamWriters for writing.
Answer: 'Parsing' an XML input yourself using regex or whatever is a brittle solution that will place unnecessary restrictions on the format of the input text (around whitespace and such). There's no need for it when the Java library comes with several XML parsers.
Using DOM might be the easiest way to go, if you can guarantee that your input XML won't grow too large to slurp into memory at once. You can:

Read the XML into a DOM structure
Traverse the DOM and modify it, removing the unwanted nodes
Write the modified DOM to a new file using a Transformer. Example here.

A more efficient option might be StAX, which doesn't require the entire input to be read in at once. I haven't used it, but it has the ability to read as well as write documents. You could read a <document> element at a time, and write it back to an output file if it's in the list. A bit of a tutorial here.
Answer: There are multiple ways to approach this:
XSLT would make this very simple if you have a fixed input list you can write a transform that only selects valid elements and outputs them. This way you don't have to actually write any code and can use something like xsltproc that is very fast!
This is what I would try first because it specifically created for transforming XML into other XML, it is less code and less code is less maintenance.
Here is an idea of how to get started, this outputs all the <document/> elements where the <value/> elements is not equal to ABC.
<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <xsl:output method="xml"/>

    <xsl:template match="node()|@*">
      <xsl:copy>
         <xsl:apply-templates select="node()|@*"/>
      </xsl:copy>
    </xsl:template>

    <xsl:template match="document[entry[commentfield[value[(text()='ABC')]]]]"/>

</xsl:stylesheet>

There are plenty of resources and good books on XSLT all you need to do is provide a whitelist of supported <value/> elements and reverse the logic in my example.
If you have an .xsd or you can create one, your input file doesn't look very complicated, you can use JAXB to automatically generate a Object hierarchy to parse the input file and then you can walk the resulting Object graph and remove anything that doesn't meet your criteria and Marshall it back to a file.
JAXB isn't very viable if the file size is larger than what will fit into memory.
Comment: I cant do JAXB, since I dont have the `.xsd` (JAXB would be nice actually). Can `XSLT` do what I want? I look at XSLT a bit, but I am not sure, can you provide a bit of sample code?
Answer: Ignoring, for the moment, details of the best way to parse and re-write the XML, the basic strategy of reading once through the XML file and looking for each file name in the list seems sound.
However, you might be able to improve they way you check for presence in the list of filenames (you don't specify how you're doing that). A couple of possibilities:

Put the filenames in a Set, and check for presence in the set, which will be an O(1) or O(log N) operation
Sort the list of filenames and perform a binary search, which will be an O(log N) operation.

Either way would be an improvement over a simple linear search through an unsorted list.
Comment: I was using HashMap for that. So is there no better way for this?
Comment: Yep, HashMap or HashSet is what I'd probably use.
Comment: Ahh, right. I'd second what another commenter said: use proper XML parsers to deal with XML; writing your own line-by-line parser is bound to be brittle. I'll add another answer below.
Answer: You can use Xpath to get the elements, if you know of the structure of the xml you can then remove those elements.  Depending how you are processing your xml you can either use DOM (probably not a good idea for large XMLs)