Prove that $g(x)=\frac{\sin(x)}{\sqrt x}$ has maximum and minimum on $(0,\pi]$

Question: Assume that $g(x)=\frac{\sin(x)}{\sqrt x}$ is given.
Prove that $g(x)$ has maximum and minimum on $(0,\pi]$ .
We've learned a theorem in class which i think is related :
Assume that $f:[a,b]\to\mathbb R$ is continuous.  There exists $c,d \in [a,b]$ such that $\forall x \in [a,b] : f(c) \le f(x) \le f(d)$
Is is enough to prove that $g(x)$ is continous? ( $\sin(x)$ is continous on $(0,\pi]$ . $\sqrt x$ is not zero on that interval ... so, $g(x)$ is continuous too ... Is this correct? )
Answer: No, because for example the function $1/x$ is continuous on $(0,1]$ but it attains no maximum value in that interval.
However, you may consider the continuous extension of $g$ to the the bounded closed interval $[0,\pi]$. What is the limit $\lim_{x\to 0^+} g(x)$?
Moreover note that $g(x)\geq 0$ in $(0,\pi]$ and $g(\pi)=0$.
Answer: Observe that
$$f(x)=\begin{cases}f(x),&x\in(0,\pi]\\{}\\0,&x=0\end{cases}$$
is defined in $\;[0,\pi]\;$ and continuous there.


Elasticsearch best_compression is not working

Question: I am parsing Apache access log from Logstash and indexing it into a Elasticsearch index. I have also indexed geoip and agent fields.. While indexing I observed elasticsearch index size is 6.7x bigger than the actual file size (space on disk). So I just want to understand this is the correct behavior or I am doing something wrong here? I am using Elasticsearch 5.0, Logstash 5.0 and Kibana 5.0 version. I also tried best_compression but it's taking same disk size. Here is the complete observation with configuration file I tried so far.
My Observations:
Use Case 1:

Logstash Conf
Template File

Apache Log file Size : 211 MB
Total number of lines: 1,000,000
Index Size: 1.5 GB
Observation: Index is 6.7x bigger than the file size.
Use Case 2:

Logstash Conf
Template File

I have found a few solutions to compress elasticsearch index, then I tried it as well.
- Disable `_all` fields
- Remove unwanted fields that has been created by `geoip` and `agent` parsing.
- Enable `best_compression` [ index.codec": "best_compression"]

Apache Log file Size : 211 MB
Total number of lines: 1,000,000
Index Size: 1.3 GB
Observation: Index is 6.16x bigger than the file size
Log File Format:
127.0.0.1 - - [24/Nov/2016:02:03:08 -0800] "GET /wp-admin HTTP/1.0" 200 4916 "http://trujillo-carpenter.com/" "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 5.01; Trident/5.1)"

I found Logstash + Elasticsearch Storage Experients they are saying they have reduced index size from 6.23x to 1.57x. But that is pretty old solutions and these solution are no more working in Elasticsearch 5.0.
Some more reference I have already tried:
- Part 2.0: The true story behind Elasticsearch storage requirements
- https://github.com/elastic/elk-index-size-tests
Is there any better way to optimize the Elasticseach index size when your purpose is only show the visualization on Kibana?
Answer: I was facing this issue due to index settings were not applied to the index. My index name and template name were different. After using the same template name and index name compression is applied properly.
In the below example I was using index name apache_access_logs and template name elk_workshop.
Sharing corrected template and logstash configuration.
Logstash.conf
output {
  elasticsearch {
    hosts => ["localhost:9200"]
    index => "apache_access_logs"
    template => "apache_sizing_2.json"
    template_name => "apache_access_logs" /* it was elk_workshop */
    template_overwrite => true
  }
}

Template:
{

    "template": "apache_access_logs", /* it was elk_workshop */
    "settings": {
        "index.refresh_interval": "5s",
        "index.refresh_interval": "30s",
        "number_of_shards": 5,
        "number_of_replicas": 0
    },
    ..
}

Reference: https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-templates.html#indices-templates


Como excluir a última linha de um arquivo texto na linguagem C

Question: Galera, estou com uma dúvida de como deveria excluir a ultima linha de um arquivo usando a linguagem C. Alguém poderia me ajudar por favor.
Abaixo, segue meu código.
int quantidadeDeUsuarios = 0;
Usuario *_usuario;

void sair() {
    free(_usuario);
}

void removerUltimoNumero() {

    FILE *arquivo;

    char *linha = (char *) malloc(256 * sizeof(char));
    char *buffer = (char *) malloc(1000 * sizeof(char));
    char *ponteiro;

    memset(buffer, 0, 1000 * sizeof(char));
    ponteiro = buffer;

    arquivo = fopen("usuarios", "r");

    if(arquivo == NULL) {
        cout << "Erro na abertura do arquivo" << endl;
        return;
    }

    while(!feof(arquivo)) {

        fgets(linha, 256, arquivo);

        if(sizeof(linha) == true) {
            strcpy(ponteiro, linha);
            ponteiro += strlen(linha);
        }
    }

    fclose(arquivo);
    rescreveArquivo(arquivo, buffer);
    free(linha);
    free(buffer);
}

void rescreveArquivo(FILE *arquivo, const char *buffer) {
    arquivo = fopen("usuarios", "w");
    fprintf(arquivo, "%s", buffer);
    fclose(arquivo);
}

void numeroDeUsuariosCadastrados() {
    cout << "Número de usuários cadastrados: " << contadorDeLinhasDeUmArquivo() << endl;
}

int contadorDeLinhasDeUmArquivo() {

    FILE *arquivo;
    int numeroDeLinhas = 0;

    arquivo = fopen("usuarios", "r");

    if(arquivo == NULL) {
        cout << "Erro na abertura do arquivo" << endl;
        return 0;
    }

    while(EOF != (scanf("%*[^\n]") && scanf("%*c"))) {
        ++numeroDeLinhas;
    }

    return numeroDeLinhas;
}

void listarUsuarios() {

    char *saida = (char *) malloc(256 * sizeof(char));
    char espaco = ' ';

    FILE *arquivo = fopen("usuarios", "r");

    if(arquivo == NULL) {
        cout << "Erro na Abertura do arquivo" << endl;
        return;
    }

    cout << "=========================================================================================================================================================" << endl;
    printf("| Nome %-25c | RG %-27c | CPF %-26c | Endereço %-41c |\n", espaco, espaco, espaco, espaco);
    cout << "=========================================================================================================================================================" << endl;

    for (int i = 1; fgets(saida, sizeof(saida), arquivo) != NULL; ++i) {
        printf("%s", saida);
    }

    cout << endl << endl;

    fclose(arquivo);

}

void cadastrarUsuario() {

    Usuario *usuario;

    usuario = _usuario;

    if(quantidadeDeUsuarios > 0) usuario = (Usuario *) realloc(usuario, quantidadeDeUsuarios * sizeof(Usuario));
    else usuario = (Usuario *) malloc(sizeof(Usuario));

    if(!usuario) {
        cout << "Exaustão de memória!" << endl;
        exit(1);
    }

    __fpurge(stdin);
    cin.clear();
    cout << "Digite seu nome: ";
    cin.getline(usuario[quantidadeDeUsuarios].nome, 100);

    __fpurge(stdin);
    cin.clear();
    cout << "Digite seu RG: ";
    cin.getline(usuario[quantidadeDeUsuarios].rg, 9);

    __fpurge(stdin);
    cin.clear();
    cout << "Digite seu CPF: ";
    cin.getline(usuario[quantidadeDeUsuarios].cpf, 11);

    __fpurge(stdin);
    cin.clear();
    cout << "Digite seu Endereço: ";
    cin.getline(usuario[quantidadeDeUsuarios].endereco, 100);

    _usuario = usuario;

    insereUsuario(_usuario);

    quantidadeDeUsuarios++;

}

void insereUsuario(Usuario *pUsuario) {

    FILE * arquivo;

    if((arquivo = fopen("usuarios", "a+")) == NULL) {
        cout << "Erro ao criar o arquivo";
    }

    fprintf(arquivo, "| %-30s | %-30s | %-30s | %-50s |\n",
            pUsuario->nome,
            pUsuario->rg,
            pUsuario->cpf,
            pUsuario->endereco
    );

    fclose(arquivo);

}

Comment: Tem tanta coisa errada ou ruim nesse código que eu não sei por onde começar (nem olhei além do que está na janela). Se vai decidir se vai fazer em C ou C++? Consegue garantir que a linha tem 256 caracteres? Acho que não, né? Se colocar o código todo talvez eu consiga fazer alguma coisa, mas não prometo porque não tenho compilador C aqui pra testar.
Comment: https://github.com/codenome/Lista0-EstruturaDeDados/tree/master/Exericicio%207%20(FALTA%20FUN%C3%87%C3%83O%20DE%20EXCLUIR)/usuariosArquivos
Este é o link do projeto!

https://github.com/codenome/Lista0-EstruturaDeDados/blob/master/Exericicio%207%20(FALTA%20FUN%C3%87%C3%83O%20DE%20EXCLUIR)/usuariosArquivos/usuario.cpp
Este acima é a do código!
Comment: Outra coisa... estou fazendo em C mesmo... maisa frente o professor vai usar C++.
Answer: Consegui resolver o problema levando os dados de um arquivo texto para uma alocação dinâmica. Em seguida, tratei o ponteiro da locação escrevendo os dados no mesmo arquivo.
void removerUltimoUsuario() {

FILE *arquivo = fopen("usuarios.csv", "r");

if(arquivo == NULL) {
    cout << "Erro ao criar o arquivo" << endl;
}

Usuario *usuarios = (Usuario *) malloc(numeroDeUsuarios() * sizeof(Usuario));

char linha[500];
int i = 0;
for(; fgets(linha, 500, arquivo); i++) {
    linha[strlen(linha) - 1] = '\0';
    sscanf(linha, "%[^;];%[^;];%[^;];%[^;];",
           usuarios[i].nome,
           usuarios[i].rg,
           usuarios[i].cpf,
           usuarios[i].endereco
    );
}
cout << "N: " << i << endl;
fclose(arquivo);
insereUsuarios(usuarios, i);
free(usuarios);

cout << "Usuário removido com sucesso!" << endl;
}

void insereUsuarios(Usuario *pUsuario, int numUsuarios) {

FILE * arquivo;

if((arquivo = fopen("usuarios.csv", "w")) == NULL) {
    cout << "Erro ao criar o arquivo";
}

cout << "N: " << numUsuarios << endl;

for(int i = 0; i < (numUsuarios-1); i++) {
    fprintf(arquivo, "%s;%s;%s;%s\n",
            pUsuario[i].nome,
            pUsuario[i].rg,
            pUsuario[i].cpf,
            pUsuario[i].endereco
    );
}

fclose(arquivo);
}

Answer: Tem uma forma bem simples utilizando a sua função que já conta a quantidade de linhas do arquivo. Mas antes, quero deixar claro que não revisei e nem testei seu código. Apenas vou deixar uma solução teórica que cabe a você implementar. Vamos lá.

Primeiramente crie um arquivo de saída.
Agora tendo em mãos o arquivo de saída criado e a quantidade de linhas do arquivo original, copie linha por linha do arquivo original para o de saída.
Ao chegar na última linha(que você quer excluir) é só ignorar, ou seja, não copie ela para o arquivo de saída.
Você tem agora 2 arquivos, o original e o de saída. Renomeie ou exclua o arquivo original e mantenha o arquivo de saída como sendo o "novo original".

Creio que esta solução não seja a mais recomendada. Mas até onde li o teu código, esta é a melhor forma de causar menos impacto na sua implementação.
OBS: Não se esqueça de tratar todos os erros durante este processo. Isso vai garantir que o seu arquivo de saída esteja íntegro da forma como você esperava.
Comment: Obrigado Carlos Givisiez!
Vou executar este procedimento!
Comment: Por nada @ThiagoCunha , comente quando você tiver testado! Aguardo.
Comment: Consegui resolver o problema! Vou deixar nos comentários abaixo.


How to use onKeypress event in a textbox

Question: I'm currently working with a node-red demo for conversation service,the question is submitted by hitting a send button, I created a function to do the same when the user press "enter" but it does not work... can someone help me to see what is going wrong this is the current code:

      <form>
        Ask your question here:
        <input type="text" name="chattext" id="id_chattext" onkeypress="javascript:onkeypress()">

      </form>
      <button onclick="javascript:onChatClick()">Send</button>

  function onChatClick() {
    var txt = $('#id_chattext').val();
    chat('You', txt);
    invokeAjax(txt);
  }

  function onkeypress(){
    if (e.keyCode == 13) {
    var txt = $('#id_chattext').val();
    chat('You', txt);
    invokeAjax(txt);
  }
  }

Thanks in advance for all the support.
Comment: There is no 'event' argument in onKeyPress function.
Comment: if (e.keyCode == 13) , where is the 'e' coming from ?
Answer: You have some syntactical mistake and try to use addEventListener for event binding as:
  document.getElementById("id_chattext").addEventListener('keypress', function(e){
 if (e.keyCode == 13) {
    var txt = $('#id_chattext').val();
   e.preventDefault();
   alert(txt);
 }
});

jsfiddle: https://jsfiddle.net/s9y6qpmv/5/
Comment: Thanks a lot... the event fixed and I also change the function to onkeydown


Can overtones be heard if the fundamental is below hearing range?

Question: I hope I'm using the term correctly... I think the overtone series is what one hears based on a fundamental.  For example, if a C3 is played as the fundamental, the first overtone would be the octave above that, followed by the fifth above that, etc.
My question is, is it possible for humans to hear overtones from a fundamental that is below human hearing?  If the lowest tone a human can hear is at about 12Hz under ideal conditions, can a fundamental tone vibrate, for example, at 8Hz (which, in theory, we cannot hear) and produce overtones at 16Hz, 24Hz, 32Hz, etcetera that would be audible to the human ear?  (Then, if that is possible, I wonder how much of what we hear falls into that category.)
Not sure why but I've been curious about this for a while and have not been able to find a good answer.
Comment: Not only is this possible, it's the basis of a certain trick speakers use to recreate low frequencies - look up "missing fundamental effect"!
Comment: @Tom This effect has been deliberately used for speakers, see [this source.](https://books.google.com/books?id=cAIAAAAAMBAJ&pg=PA78&lpg=PA78&dq=%22missing+fundamental%22#v=onepage&q=%22missing%20fundamental%22&f=false)  Though of course, faking low frequencies using psychological tricks is still not recreating low frequencies, and audio engineers would definitely hear the difference.  I have used [the software equivalent of this](https://www.waves.com/1lib/pdf/plugins/maxxbass.pdf) by accident and it was clearly inferior to true bass reproduction.
Comment: @Edward yes, but what I do not get is how are they using this effect actually. Missing fundamental phenomenon will occur as long as you have enough harmonics. If the speaker can reproduce can reproduce these harmonics, nothing more to do! Could be a real phenomenon always occurring sometimes used by manufacturers to justify their lack of bandwidth…
Comment: @user45266 do they really need to implement it? I mean, if the bandwidth of a speaker won't reproduce the fundamental, it may still reproduce the overtones if they are in the range of frequencies they can reproduce, thus recreating the bass by the MFE… So you just need to go low enough to reproduce the harmonics of the lowest bass sound you want to achieve, but there is nothing more to do. Or am I missing something?
Comment: @Tom The MaxxBass software manual I linked says that it generates harmonics.  [Here's a better source for the MaxxBass speaker-](https://www.manualslib.com/manual/188609/Waves-Maxxbass-102.html?page=7#manual) "MaxxBass process generates higher harmonics from the low fundamental frequencies below the (set) MaxxBass Frequency, and adds them back into the signal"
Comment: I don't know exactly which speakers use it when, but I know that the concept has applications in speaker technology somewhere. I'm wondering some of the same things you are, OP.
Comment: @Edward Alright, so it basically makes low frequency signal (below the bandwidth) less clean to generate harmonics so that these frequencies can be heard using MFE ;)
Comment: The question is talking about outside of the human range, not speaker range. Unless that's what you you mean.
Comment: It's worth noting the fundamental doesn't have to be below the audible range to be inaudible. Certain instruments such as some tuned percussion (timpani, tubular bells) exploit this [missing fundamental](https://en.wikipedia.org/wiki/Missing_fundamental).
Answer: If the infrasound has overtones in the audible range, then yes you can hear them. The overtones could be completely separate waves independent from the fundamental - the ear can't tell, even though it tries to figure out which waves come from the same source by grouping together waves that appear to move as a tightly correlated single entity. (Which is the reason why you should avoid having parallel fifths or octaves in N part harmony. Once the voices start moving together by the same steps, the ear puts all of the unison-locked partials/overtones in the same bin, and doesn't distinguish the voices as separate anymore, so your four-part harmony becomes three-part harmony all of a sudden.)
Answer: Yes, this is possible, but this accounts for a minority of musical sounds that we use.  One example in practice is the electric bass guitar, when tuned very low.  Here's an extreme example of a bass tuned to C#0, or 17.32Hz.  You can clearly hear the bass, although its pitch might be hard to discern.  More commonly, you might hear a bass tuned to B0 (30.87Hz, within the human hearing range) but played through speakers that cannot reproduce that low of a note, so you will only hear the harmonics.
Some organs can reach this low as well.  Here's an example of an organ playing very low notes down to about 16Hz.
Also, tubas can reach very low, and the very low notes are called "pedal tones".  This goes down to about 14.57Hz.  This goes down to about 21.83Hz.
Answer: https://en.wikipedia.org/wiki/Missing_fundamental
When the missing fundamental is in the hearing range, most people will "hear" it. Human brain is pretty good at filling in usual things when they are missing. It does require training, but most of us get this training at early age without knowing it.
When the fundamental is lower, however, a lot of people will not have a previous experience to relate the overtones to.
On the other hand, a person used to matching a wide range of vibrations to sounds (like,  say, operators of different rotary machines and engines) could pretty much "feel" the base frequency.
Answer: It's going to be quite dependent on what the original sound source is. Each instrument has its own individual timbre, which will contain different overtones along with the original note, in differing strengths. That's why each instrument sound unique to us, even when each plays exactly the same pitch.
So, yes, providing those overtones are within human hearing range, they will be heard. Which ones will be audible, though, will depend on, as stated previously, what the instrument is that it's played on.
That may sound strange - why would anyone make or play an instrument that could produce sounds, the fundamentals of which would be inaudible?! That's hypothetical, somewhat like the question!
Answer: Yes. As long as the frequency produced by the overtone is within the audible range, it will be heard.
Answer: Many answers so far have answered an opposite question - can we reproduce just the harmonics of a low note and 'hear' the fundamental.  That's an easy 'yes', and it's the practical basis of e.g. an 'acoustic bass' stop on an organ where multiple ranks of pipes tuned to the harmonics of a low note  give the illusion of that low note being played.
The actual question - hearing the harmonics of an ultra-low note that IS actually produced - occurs less frequently in the musical world.  Instruments that play such notes would be large (and therefore expensive).  Why would we bother to make one?  So we need to look at non-musical and natural sources of infrasound.
There certainly seem to be examples of infrasound that DON'T produce audible harmonics - the whole point of low-frequency sound as a weapon is that it isn't audible (or, apparently, particularly practically effective).
And examples of ones that do - e.g. wind turbines.
"The noise has a discrete frequency character, consisting of the blade passing frequency, and a number of harmonics." Infrasound Emission from Wind Turbines, Jørgen Jakobsen, Danish Environmental Protection Agency
But, to return to the question, yes, an infrasound source can have overtones in the audible range, and if they're at more than negligible amplitude, we'll hear them.
Answer: As far as I understand overtone singers produce higher pitches by closely alternating lower frequency tones. So there is a whole area of application in human voice for your theoretical question.
I would like to point out that even the opposite is also possible and has been used, e.g. in Alfred Hitchcock's classic movie "Birds". It is the so called "Trautonium" built and played by Oscar Sala which produces undertones along the same principle.
Answer: I have a special guitar that plays zero octave. Its overtones into distortion push the audible portion of the sound into the midrange.
You can do sane thing with synth that has lot harmonics its zero octave tones are audible in the range of hearing .
Thete so much cool stuff you can do with this , for example tweaking ypur kick drums to be audible on laptop speakers when recording your albums


Given the size of $\mathscr{U}, A, B$, how many possible combinations of $A$ and $B$ such that $A\cap B \neq \varnothing$?

Question: Given the $\mathscr{U} = n, |A| = c_1$, how many possible set $B$ with size $|B| = c_2$ are there, such that $A \cap B \neq \varnothing$.
Answer: Hint
Look at the complementary problem: given the $\mathscr{U} = n, |A| = c_1$, how many possible set $B$ with size $|B| = c_2$ are there, such that $A \cap B = \emptyset$.


How do you calculate the total number of donuts sold?

Question: Let's say you're trying to calculate the total number of donuts sold in NYC in any given month, how would you go about doing this?
What would be the most efficient way? This is an open-ended question I got in an interview, meaning you could make assumptions if you want.
I froze up and couldn't think of any good way to do this, what do you think?
Comment: It all depends on the data you have available.
Comment: For what purpose, applying what criteria of accuracy? How is "efficiency" supposed to be conceived of or measured?  Is this intended to be a thought experiment or perhaps a design for a serious study?  During interviews you need to make sure you're communicating, so *asking questions* to achieve clarification is the very first response to consider.
Answer: Actually something I have experience with!
For legitimate business' selling donuts, look for issued licenses according to the NYC Department of Consumer Affairs based on your criteria.
After establishing a list, I would recommend a random sample of the donut shops within the defined area of which you like to conduct your study, is it just limited to manhattan, or all of the boroughs?
Depending on the business population size, determine your sample size.
If you want first-hand data, you can literally go to each shop and count the number of donuts sold. But beware, this might be seen negatively.
If you want something easier, you can ask for their help via a survey. But don't expect a high response rate.
Extrapolate and estimate given different variables, weather, season, city events, price of inputs (like wheat and water cost), water quality, residential density, access to mass-transit (people like fast food), access to commercial stores (people get hungry when shopping). etc.
For off-the-street donut sales, I guess you can just start to canvass neighborhoods and conduct some fieldwork to determine the above.


How to determine if the sequence $a_n= (30+12\arctan(n!))/6^n$ is divergent or convergent

Question: $$a_n= \frac{30+12\arctan(n!)}{6^n}$$
Not sure where to start, I know at infinity arctangent tends towards $\frac{\pi}{2}$. I also know I'm supposed to find the limit but not sure how to start, the factorial and the arctangent are throwing me off. limit= 0.
Answer: HINT:
$$
0<a_n<\frac{50}{6^n}.
$$
(Why?)
Answer: The factorial is not an issue. Since, $n!\to\infty$ as $n\to\infty$, $\arctan n!\to\frac{\pi}{2}$. On the other hand, $6^n\to\infty$, so $\lim_{n\to\infty}\frac{30+12\arctan n!}{6^n}=0$.
Answer: Convergence of the sequence
$$a_n= \frac{30+12\arctan(n!)}{6^n}\Rightarrow \mbox{converges}$$
Because the limit as $n\to\infty$ exists and is finite as shown below
$$ \lim\limits_{n\to\infty}\frac{30+12\arctan(n!)}{6^n}= \frac{30+12\left(\frac{\pi}{2}\right)}{\infty} $$
$$ = \frac{30+6\pi}{\infty}=0 $$
Convergence of the series
Assuming that $a_n$ is the $n^{th}$ term of a series, we have
$$\sum\limits_{k=0}^n \frac{30+12\arctan(k!)}{6^k}$$
The divergence test is inconclusive because
 $$\lim_{n\to\infty}\frac{30+12\arctan n!}{6^n}=0$$
So now let's check for absolute convergence. Note that
$$ \left|\arctan\left(n!\right)\right|\lt \frac{\pi}{2} $$
$$ 12\left|\arctan\left(n!\right)\right|\lt 12\left(\frac{\pi}{2}\right) $$
$$ 30+12\left|\arctan\left(n!\right)\right|\lt 30+6\pi $$
$$ \frac{30+12\left|\arctan\left(n!\right)\right|}{|6^n|}\lt \frac{30+6\pi}{|6^n|} $$
$$ \left|\frac{30+12\arctan\left(n!\right)}{6^n}\right|\lt (30+6\pi)\left|\frac{1}{6}\right|^n $$
Since $ \left|\frac{1}{6}\right|\lt 1 $, by the geometric series test we have
$$ (30+6\pi)\sum\limits_{k=0}^n\left(\frac{1}{6}\right)^k\Rightarrow \mbox{absolutely convergent} $$
Therefore by the direct comparison test
$$ \sum\limits_{k=0}^n \frac{30+12\arctan\left(k!\right)}{6^k} \Rightarrow \mbox{absolutely convergent} $$
Comment: Good work. Answered the question well.
Comment: Wasn't the question about the sequence itself, not the series?
Comment: @ChristopherCreutzig, I've edited my post to include the convergence of the sequence.
Answer: Hint: Since you know $\arctan$ is bounded you're halfway there. Do you see a way to use the squeeze theorem?
Comment: By binding it between -pi/2 and pi/2
Comment: Another hint: for $x\geq 0$, $\arctan x \geq 0$.
Comment: Im really drawing a blank
Answer: To help erasing blanks drawn:
$$0\xleftarrow[\infty\leftarrow n]{}\frac{30-12\frac\pi2}{6^n}\le\color{red}{\frac{30+12\arctan n!}{6^n}}\le\frac{30+12\frac\pi2}{6^n}\xrightarrow[n\to\infty]{}0$$


how to compress azure queue message (json string) to push and pull from azure storage queue

Question: Azure storage queues have a maximum message size of 64Kb My messages can exceed this size and I am looking for an option to compress
My code looks like below
var json = JsonConvert.SerializeObject(item);
            CloudQueueMessage message = new CloudQueueMessage(json);

            queue.AddMessageAsync(message);

At the receiving end
 public static void ProcessQueueMessage([QueueTrigger("abc")] AbcItem abcItem, TextWriter logger)
    {
        if (abcItem != null)
        {
            //processing
        }
    }

My question is can this sort of compression work on azure queue and Is it possible to compress this string before pushing on the queue and uncompress at the other end when we are pulling it from the queue before processing?
Answer: Yes, you can store all information in queues, so compressed information will work as well.
However, even a compressed file could exceed 64Kb, check out this related question and answer: Azure Queue Storage: Send files in messages for storing the data in Blob storage and only a reference in the queue


Subset of a ring

Question: Can I assume the following:

Let $R$ be a commutative ring, and $S \subset R $ closed under multiplication. If $x \notin S$ then $\langle x \rangle\cap S =\emptyset $ ?
Comment: why do you think so... could you write a small outline/guess what ever you feel comfortable..
Comment: I've got a counter example by someone here.
I guess my way to proof a question I've been given is wrong.
I'll write the question in a new post.
Thanks.
Answer: A counter-example: $R=\mathbb{Z}, S=\mathbb{N},x=-1$.
Comment: Or just $S=\{1\}$ and $R$ any ring of characteristic not $2$.
Comment: @lhf: Yes, of course.

Subset of a ring


Alternativa String.replace()

Question: Estou com uma pulga atrás da orelha.
Tenho um método que remove / altera alguns caracteres da string, é algo desse tipo :
public static String replaceCharSet(String texto) {
    texto = texto.replace("&", "E");
    texto = texto.replace("$", "S");
    texto = texto.replace("á", "a");
    ................
    return texto;
}

Bom isso se repete por varias e varias linhas e além de causar uma perca no desempenho estou desconfiado de memory leak.
Existe alguma forma mais elegante / funcional de fazer isso ?
Segue a lista de todos os caracteres que preciso editar/modificar :
"&", "E"
"$", "S"
"ç", "c"
"Ç", "C"
"á", "a"
"Á", "A"
"à", "a"
"À", "A"
"ã", "a"
"Ã", "A"
"â", "a"
"Â", "A"
"ä", "a"
"Ä", "A"
"é", "e"
"É", "E"
"è", "e"
"È", "E"
"ê", "e"
"Ê", "E"
"ë", "e"
"Ë", "E"
"í", "i"
"Í", "I"
"ì", "i"
"Ì", "I"
"î", "i"
"Î", "I"
"ï", "i"
"Ï", "I"
"ó", "o"
"Ó", "O"
"ò", "o"
"Ò", "O"
"õ", "o"
"Õ", "O"
"ô", "o"
"Ô", "O"
"ö", "o"
"Ö", "O"
"ú", "u"
"Ú", "U"
"ù", "u"
"Ù", "U"
"û", "u"
"Û", "U"
"ü", "u"
"Ü", "U"
"º", "o"
"ª", "a"
"-", " "
".", " "

Utilizo JAVA 8, impossibilitado de migrar no momento para outras versões. É um código antigo aqui da empresa que pretendo melhorar.
Comment: Já tentou fazer uma regex? Quais outros itens você precisa substituir alem dos 3 citados?
Comment: Não tentei/pensei ainda nessa possibilidade. Preciso remover/alterar diversos outros caracteres "especiais" exemplo : ö > o , ª > a , nunca faço algo do tipo á > vazio , pois preciso da string completa só que com eles modificados.
Answer: Basicamente precisa trocar caracteres acentuados por não acentuados a classe Normalizer parece uma boa opção ela faz decomposição dos caracteres baseado no código UTF-8 e esse comportamento varia de acordo com a forma escolhida.
Como existem quatro exceções fiz um replace para cada já que $ não será convertido para S, nem & para E. Pode organizar elas como um enum na sua classe.
import java.text.Normalizer;

public class t {

    String entrada = "olá mundo? é ª º 123 ? $ & * ., x";

    entrada = entrada.replace('$', 'S')
                     .replace('&', 'E')
                     .replace('-', ' ')
                     .replace('.', ' ');

    String saida = Normalizer.normalize(entrada, Normalizer.Form.NFKD);
    System.out.println(saida.replaceAll("\\p{InCombiningDiacriticalMarks}+", ""));
}

Saída:
ola mundo? e a o 123 ? S E *  , x

Baseado em:
Easy way to remove UTF-8 accents from a string?
Unicode Normalization Forms
Unicode Normalization
Comment: Encontrei um probleminha, alguns caracteres permanecem por fazer parte do UTF-8 exemplo : $ - & e preciso remove-los
Comment: @MateusVeloso `, .` também precisam ser removidos?
Comment: Apenas o  "  .  " por " " , ao menos é o que temos em código aqui, ai preciso algo que me traga o mesmo retorno porque é usado em todo sistema
Comment: @MateusVeloso alterei a resposta.

Alternativa String.replace()


Are CNAME "imap..." and "smtp..." subdomains needed?

Question: I'm running my Postfix email server. I have only 1 A dns record for it: mail.my_domain.com I'm able to connect to it, receive and send email through it using only this url. Namely, I don't have "smtp...." and "imap.my_domain.com".
Will there be a necessity, advantage for me to create CNAME "smtp.my_domain.com" and "imap.my_domain.com" pointing to "mail.my_domain.com"?
Answer: Unless you plan on growing to the point you need to split your services onto different servers, these are unnecessary.  When you do grow to that point, just add new A record for smtp, or even smtp1 and smtp2 if your volume is that high.
Most clients will discover your server for both IMAP and SMTP with doing the initial configuration.  Even if you grow to the point of having different SMTP server for incoming an outgoing mail, you may want to continue accepting mail from authenticated users on the submission port (587) the mail domain.
If your use base grows to the point you need to have multiple IMAP servers, consider adding and imap domain posibly with multple addresses for multiple IMAP proxy servers.
Answer: No. These subdomains are completely optional.
Some mail clients will probe for these subdomains while setting up a new account, but they will typically fall back to mail, and/or allow you to enter a server name manually.
Answer: They are not necessary.  I would describe them as medium suggestion/recommendation.
Per service DNS A/CNAME records smtp.example.com (outgoing authenticated email via smtp) and imap.example.com (incoming mail via imap) ease eventual future reconfiguration.
Such records allow to change servers (in DNS) without any need to reconfigure email clients.
Quite a few bigger domains use separate server for smtp-out, smtp-mx/smtp-in, imap/pop3.


Questions about epimorphisms.

Question: Let $P, M, N$ be $A$-modules over a field $K$. If we know that $h:P\to M$ is surjective, $g:N\to P$ is a A-homomorphism such that $hg$ is surjective, can we have $\operatorname{im} g + \ker h = P$? I think that maybe there is some $x \in P$, such that $h(x)\neq 0$ and $x \not\in \operatorname{im} g$. Thank you very much.
Comment: I'm not sure what you mean by an $A$-module over a field $K$. But regardless, of $h\circ g$ is surjective, then you know that $g$ needs to map $N$ to submodule of $P$ isomorphic to $M$, i.e. $P/\ker h$. Hopefully that answers your question well enough?
Answer: It is true that there can be an $x \in P$ such that $x \notin \ker h$ and also $x \notin \operatorname{im}g$.  For example consider the canonical split sequence $M \to M \oplus M \to M$ where $h(m, n) = n$ and $g(m) = (m, 0)$.  Then any $m \neq 0$ gives an element $(0, m)$ which is not in the kernel of $h$ or the image of $g$.
But it is true that $P = \ker h + \operatorname{im}g$.  If $p \in P$ then $h(p) \in M$.  As $hg$ is surjective take $n \in N$ such that $hg(n) = h(p)$.  Then $p - g(n) \in \ker h$, $g(m) \in \operatorname{im}g$, and $(p - g(n)) + g(n) = p$.

Questions about epimorphisms.


Pegar ID do URL no lugar da INDEX

Question: Olá, gostaria de saber como que faz para pegar o ID da URL como se a index fosse a ID, tipo assim
Usando GET:
http://domain.com/api.php?id=1999&output=json
$id = $_GET['id'];

Ok, até ai tudo bem, mais eu gostaria de saber como que faz para pegar o id assim:
http://domain.com/1999/api.php?output=json

Gostaria de saber como que pega este ID que no caso seria 1999.

Quero que minha index detecte desde modo, um ótimo exemplo é a API do PagSeguro, aquele link ou a do Mercado Pago:
http[s]://api.mercadopago.com/collections/notifications/{id here}?access_token={token here}

Exemplo:
http[s]://api.mercadopago.com/collections/notifications/1799030657?access_token=APP_USR-46....

A output ficaria mais ou menos assim:
Comment: Você alterou a url com o .htaccess, certo?
Comment: Depende do que você está falando amigo, eu alterei mais creio que não seja o que você esteja citando, poderia me dar um exemplo amigo?
Answer: Deve alterar isso no htaccess, por exemplo:
Alterações:
HTACCESS:

/public_html/.htaccess

RewriteEngine On
RewriteRule ^([0-9]+)/api.php?$ api.php?id=$1$2 [QSA]

PHP:

/public_html/api.php

<?php
$id = $_GET['id'];
$output = $_GET['output'];
?>

Explicação:
O RewriteRule irá "ler a url" mas irá apontar para outro lugar, acredito que assim ficará fácil de entender.
Digitando o URL:
http://domain.com/1999/api.php?output=json

Irá chamar o aquivo:
api.php?id=1999&output=json

Isso NÃO IRÁ REDIRECIONAR O USUÁRIO, mas é possível fazer também redirecionando.
Construção:
Caso não entenda o RewriteEngine, aqui está um breve passo-a-passo, para saber como isso foi feito, ao menos por mim:
RewriteEngine On
# Liga esta função

RewriteRule ^([0-9]+)/api.php?$ api.php?id=$1$2 [QSA]
#
# Primeira parte:
# ([0-9]+) será o 1999 (http://domain.com/1999)
# /api.php será para restringir (http://domain.com/1999/api.php)
#
# Segunda parte:
# api.php será o arquivo chamado
# ?id=$1 será o resultado do ([0-9]+) (?id=1999)
# $2 [QSA] será o resto do query/parametros

Comment: Muito Obrigado amigo.
Answer: Você pode usar explode('/', $url):
$url = 'http://domain.com/1999/api.php?output=json';
$r = explode('/', $url);
$id = $r[3];
echo $id;

http://php.net/manual/en/function.explode.php

Pegar ID do URL no lugar da INDEX


php mysql foearch with the same value from email to users

Question: i have this on my mysql database
email have 5 value
user have 15 value

how can i loop the email with something like this
email          user
email@example.com  user1
email@example.com  user2
email@example.com  user3
firstname.lastname@example.com  user4
firstname.lastname@example.com  user5
firstname.lastname@example.com  user6
email@example.com  user7
email@example.com  user8
--------------------
and so on....

using the php foreach...
something like when the users loop the email value will loop also and when it reach the end of the value of the email the email will start again to the first email@example.com
is it possible to work on this on foreach or do it as a while?
Comment: 2 users have the same email? Odd.. shouldn't it be the other way around?
Comment: Are you trying to produce every permutation of user and email here? What you're trying to do doesn't make any sense!
Comment: im sorry email and user was just example.... sorry if i did not make it clear... let me say i have 5 fruits which are `orange,apple,grapes,banana,kiwii` then i have `users` in the database record 15, it will loop to every users... `post of MR. NomikOS` below Answers is a perfect sample thank you mr. NomikOS...
Answer: $data = array();
$i=0;
foreach($users as $user){
if(isset($email[$i])){
$data[$email[$i]] = $user;
}
else{
$i=0;
$data[$email[$i]] = $user;

}
$i++;
}
print_r($data);

Answer: Something like this:
$j=0;
for ($i=0;$i<count($users);$i++){
    if (count($email)<$j+1)
        $j=0;
    else
        $j++;
echo $users[$i].' has email: '.$email[$j];
}

Answer: $e = array('email1', 'email2' /* , more email */);
$u = array('user1', 'user2', 'user3' /* , more users */);

$total_e = count($e);
$total_u = count($u);
$total   = $total_e * $total_u;

$counting_e  = 0;
$counting_u  = 0;

for ($i = 0; $i < $total; $i ++ )
{
    echo nl2br($e[$counting_e ++] . " => " . $u[$counting_u ++] . "\n");

    if ($counting_e == $total_e)
        $counting_e = 0;
    if ($counting_u == $total_u)
        $counting_u = 0;
}

Test: http://codepad.org/R5PpAKQW


Magento runs too slow and almost dead

Question: pasted below is the results of running iostat -x 10 10 (a command to look at disk performance):
<code>avg-cpu:  %user   %nice %system %iowait  %steal   %idle
          0.32    0.00    0.17   29.31    0.00   70.19

Device:         rrqm/s   wrqm/s   r/s   w/s   rsec/s   wsec/s avgrq-sz avgqu-sz   await  svctm  %util
sda               4.30    74.03  6.49 387.31   131.87  3678.72     9.68   152.44  385.31   2.54  99.92
sda1              0.00     0.00  0.00  0.00     0.00     0.00     0.00     0.00    0.00   0.00   0.00
sda2              4.30    74.03  6.49 387.31   131.87  3678.72     9.68   152.44  385.31   2.54  99.92
dm-0              0.00     0.00 10.49 458.94   125.47  3671.53     8.09   185.92  394.49   2.13  99.92
dm-1              0.00     0.00  1.30  0.00    10.39     0.00     8.00     0.96  537.85 325.38  42.26
</code>
How can i find the reason of such disk I/O usage on a server where i install magento. This was running fine before but last few days site almost goes down. But canot find the reason. Please help
Comment: You haven't provided any server specifications, store information, traffic levels or noted any changes that you have recently made. Without this it would be impossible to diagnose the fault or assist you.
Answer: with this info it's hard to say if your server is dying because of swapping or mysql hammering the io subsystem. as first two things:

try looking if swap is used / how much
try running "show processlist;" in mysql to see if there are long running queries.

in the long run install something like munin or cacti to gather statistics about the system load.
Comment: Thank you for your quick response. The ram of the server is 16GB and only a magento website is running. Output of top command shows around 4GB of swap is using. I tried with SHOW FULL PROCESSLIST but could not figure how to interpret this.
Comment: take a look at the query duration - if it's more than a second - there's something wrong. your server might be still [ab]using swap despite the fact that you have 16GB of ram... run vmstat 1 for few minutes and see if something is read/written from/to swap; i assume that nothing should be.

Magento runs too slow and almost dead


How to theme only top level menu?

Question: I have the following menus
about us
    company
    menu 2
our work
    menu 1
    menu 2
news
contact
jobs

I like to insert an extra li between each top level menus (about us, our work, news, contact, jobs) to make them look like "about us   |   our work   |   news   | contact   |   jobs "
I looked at template.php and I have themename_menu_link, but I don't know how to compare the variable to check if it is a top level menu or not.
Comment: Why don't you try `css pseudo codes` ?
Comment: @NikhilM // enlighten me please. How do I put | using css?
Answer: The only way I can think of is as follows:
template.php
<?php

function YOURTHEME_menu_tree__YOURMENUNAME(&$variables) {
    global $cur_level;
    $cur_level++;
    return '
' . $variables['tree'] . '
';
}

?>

page.tpl.php
<?php print render(menu_tree('YOURMENUNAME')) ?>

This will give each level an unique class for it's level. Though, there is one big problem with this approach, and that is that menu_tree is working from the bottom up. So you will end up in the following level classes:
ul .level-3
li
li
    ul .level-2
    li
    li
        ul .level-1
        li
    li
li

So, you can never actually be sure about which classname the top level will have, only if you know for sure that there will always be an X count of levels.
Edit
So, just to be clear about my solution here above, this is the only way I can think of doing this programatically at theme level. If you could use a module like Nice Menu's (like suggested above) you should really be using that, since this is more a kind of workaround than a real solution to Drupal's sturdy menu system...
Comment: This has to be done in li level since li has to have '|'. I don't see how I do that with ul class.
Comment: You could use the $cur_level at [theme_menu_link](http://api.drupal.org/api/drupal/includes%21menu.inc/function/theme_menu_link/7) to use the level at **li** level. Something like this:

    function YOURTHEME_menu_link(&$variables) {
      global $cur_level;
      // Then implement, see the API for default code for this block...
Answer: The above solutions only works if the number and structure of the menu links remain the same. The problem is whenever you'd add a link the level number of the top most ul changes. Whenever the top most ul number changes, your css that targets a ul class with that number breaks:
Here is a solution that fixes this problem:
In the first function we output the UL class when the UL is created.
    function YOURTHEME_menu_tree__menu_secondary_menu($variables) {
      global $cur_level_menu_secondary_menu;

      $class = ($cur_level_menu_secondary_menu == 1) ? 'secondary-menu' : 'secondary-menu--submenu';
      $output = '
' . $variables['tree'] . '
';
      $cur_level_menu_secondary_menu--;

      return $output;
     }

In the second function we save the current depth in a global variable $cur_level_menu_secondary_menu.
  function YOURTHEME_menu_link__menu_secondary_menu(array $variables) {
    $element = $variables['element'];

     global $cur_level_menu_secondary_menu;
     $cur_level_menu_secondary_menu = $element['#original_link']['depth'];

     $sub_menu = $element['#below'] ? drupal_render($element['#below']) : '';
     $output = l($element['#title'], $element['#href'], $element['#localized_options']);

     return '
' . $output . $sub_menu . '
';
   }

Thus the top most UL will always have the number 1.

Menu Link

Menu Link

Menu Link

Menu Link

Menu Link

Menu Link

Answer: Rather then doing it with jquery you should try with modules, there are already lots of modules for this requirement, try with "Nice Menu".
Answer: Looks like there's a 'depth' key for each links.
function yourthemename_menu_link(array $vars)
{
    $depth = $vars['element']['#original_link']['depth'];
}

you can check depth to see if it is the first level.

How to theme only top level menu?


Can we approximate a sigma-algebra by an increasing sequence of finite sigma-algebras?

Question: $\newcommand{\N}{\mathbb N}$
$\newcommand{\mc}{\mathcal}$
$\newcommand{\set}[1]{\{#1\}}$
Definition.
We say that a measure space $(X, \mc F, \mu)$ has a countable basis if there is a collection $\set{E_n}_{n\in \N}$ of measurable subsets of $X$ such that for all $\varepsilon>0$ and for all $E\in \mc F$, there is $n$ such that $\mu(E_n\Delta E)< \varepsilon$.

Question. With notation as in the above definition, is it true that if $\mc G$ denotes the $\sigma$-algebra generated by $\set{E_n}_{n\in \N}$, then for all $F\in \mc F$, there is $G\in \mc G$ such that $\mu(F\Delta G)=0$?
Answer: Let $\mu (E_{n_{k}} \Delta E)<\frac 1 {2^{k}}$ for each $k$. Then $\sum_k \mu (E_{n_{k}} \Delta E)<\infty $ so $\mu ( \lim \sup_k (E_{n_{k}} \Delta E))=0$. This implies $\mu (F\Delta E)=0$ where $F=\lim \sup E_{n_{k}}$.
Answer: Another way to see the result is the following:
Let $E\in \mathcal F$ be fixed.
By hypothesis, we can find a sequence $n_1<n_2< n_3<\cdots$ such that $\chi_{E_{n_k}}\to \chi_E$ in $L^1$ as $k\to \infty$.
As is well-known, we may pass to a subsequence and assume that the convergence occurs pointwise a.e.
But then we have $\lim_{k\to \infty} \chi_{E_{n_k}} = \limsup_{k\to \infty}\chi_{E_{n_k}}\pmod{\mu}$. The latter is in $\mathcal G$ and we are done.


Cannot start service app: oci runtime error - executable file not found in $PATH

Question: I get the following error when I run docker-compose:
Cannot start service app: oci runtime error: container_linux.go:247: starting container process caused "exec: \"script.sh\": executable file not found in $PATH"
ERROR: Encountered errors while bringing up the project.

My docker-compose.yml
version: '2.0'

services:
  app:
    build: app
    volumes:
      - C:\Users\svirl\Documents\workspace\bgs-web:/var/www/html/:rw

and in app folder I have
Dockerfile
FROM php:5.6-apache
WORKDIR /var/www/html/

ADD script.sh /var/www/html
RUN chmod +x /var/www/html/script.sh
RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer
ENTRYPOINT ["script.sh"]

and in same folder script.sh
#!/bin/bash
composer install

Is there something I missing?
Answer: The exec syntax of the entrypoint (with the json) needs the full path to the binary, or /var/www/html would need to be added to the path. Update your Dockerfile to the following:
FROM php:5.6-apache
WORKDIR /var/www/html/

ADD script.sh /var/www/html
RUN chmod +x /var/www/html/script.sh
RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer
ENTRYPOINT ["/var/www/html/script.sh"]

Comment: I am sorry but now I get `ERROR: for app  Cannot start service app: oci runtime error: container_linux.go:247: starting container process caused "exec: \"/var/www/html/script.sh\": stat /var/www/html/script.sh: no such file or directory"` but the file is there is I `RUN ls -la` on docker-compose.
Comment: Include your docker-compose.yml. Most likely you are trying to mount a volume somewhere in the /var/www/html path.
Comment: You'll need to include your script.sh on your host and set the execute bits in a way that map into the container. It may be easier to move the script.sh somewhere else inside your image that doesn't get replaced by your volume mount.
Comment: It was Windows Endings. Thank you.
Comment: I choose the second way, the error is gone at build but when I start the container I get: `standard_init_linux.go:178: exec user process caused "no such file or directory"` . `FROM php:5.6-apache
WORKDIR /var/www/html/

ADD script.sh /var/www
RUN chmod +x /var/www/script.sh
RUN ls -la /var/www
RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer

ENTRYPOINT ["/var/www/script.sh"]`
Comment: Make sure you have /bin/bash inside your container, you may need /bin/sh instead. Also make sure you don't have windows linefeeds in your script, running dos2unix on the script can fix that.


Different Feeds Tamper per destination in mapping

Question: I have a csv feeds importer I'm trying to build where I would like the last 2 digits of a code to be mapped to the task code field, but the full 4 or 5 digit number be mapped to the GUID.
From the interface I can only see a way to run the tamper on the source field for all destinations.  Is there some way I can tamp in different ways for different destination fields?  (or tamp for one destination, and use the raw value for another)
Answer: First thing this morning, I realized what Map to multiple fields using 'Blank source' in the documentation means.  I was able to have Task Code as my source for GUID, then Blank Source 1 as my source for Task Code.
In the tamper for Blank Source 1 I use Copy Source Value before doing my other transform:
Answer: Aram Boyajyan wrote a nice article on how to create a custom tamper plugin.
<code>function YOUR_MODULE_tamper_language_callback($result, $item_key, $element_key, &$field, $settings, $source) {
</code>
perhaps one of these callback params holds the destination? something for you investigate.
If yes, then you would just do an if statement.
Comment: @UltraBob cool, it has been a while since I've used feeds. `First thing this morning, I realized` that happens to me too, sometimes sleep fixes everything.


Como armazenar conteúdo de Memo em variável string no Delphi?

Question: Preciso armazenar o conteúdo do Memo1 numa variável string, mas assim não funcionou:
sHTML := Memo1.Lines;

Answer: sHTML := Memo1.Text;

Assim irá funcionar, agora se você precisa de alguma coisa a mais, especifique na pergunta.
Answer: Normalmente utilizo Memo1.Lines.Text
Answer: Pode ser feito feito das seguintes 3 formas, pode criar dois memos e um botão no evento onClick do botão passa o seguinte código para ele:
procedure TForm1.Button1Click(Sender: TObject);
var i: Integer;
    AText: String;
begin
  Memo2.Lines.Add('Option 1');
  for i := 0 to Memo1.Lines.Count -1 do AText := AText + Memo1.Lines[i];
  Memo2.Text := Memo2.Text + AText;
  Memo2.Lines.Add('--------------------------------------------');

  Memo2.Lines.Add('Option 2');
  AText := Memo1.Lines.Text;
  Memo2.Text := AText;
  Memo2.Lines.Add('--------------------------------------------');

  Memo2.Lines.Add('Option 3');
  AText := Memo1.Text;
  Memo2.Text := Memo2.Text + AText;
  Memo2.Lines.Add('--------------------------------------------');
end;

A segunda e terceira opção são praticamente iguais, no entanto a primeira vai pegar apenas o texto de cada linha o que pode ser interessante em certas ocasiões, agora vai tudo depender das suas necessidades.
Answer: Se for variável -> sHTML := Memo1.Text;
Se for campo -> sHTML.AsString := Memo1.Text;


Reference to another database as a prefix

Question: I have a problem referencing another database as a prefix in my settings.php file.I have a master-site[mysite.local] and a slave [sub.local].Both of them are having separate database.I need to check the users table of the master-site as well as the users table of the slave site ,when a user tries to authenticate to the slave which is sub.local.I tried adding the following in the settings.php file of the slave
$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'sub_drupal', //Database for the slave site
      'username' => 'root',
      'password' => '',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => array(
                'default'   => 'sub_drupal.',
                'users'     => 'study.', //parent database
                'sessions'  => 'study.',
                'role'      => 'study.',
                'authmap'   => 'study.',
                'users_roles'   => 'study.',
            ),
    ),
  ),
);

But now it authenticates users only on the parent database.Is it not possible to authenticate users present in the slave database sub_drupal and also in the parent database study.Hope someone could help me with this.Thanks
Comment: Prefixes are for situations when you have shared database. Of course you will have problem using them to access another DB, as this is simply not what they are for, and thus it's impossible. That's pretty much all to it.
Answer: You have the format wrong for two databases you need something like this:
$databases = array(
  'default' => array(
    'default' => array(
      'database' => 'd7',
      'username' => 'root',
      'password' => 'root',
      'host' => '127.0.0.1',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
  'db2' => array(
    'default' => array(
      'database' => 'd7_parent',
      'username' => 'root',
      'password' => 'root',
      'host' => '127.0.0.1',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

You can then use db_set_active('db2'); to change the connection and begin querying the second database.


Granting sudo access for specific command and any flags set (RedHat)

Question: How can you grant sudo access for a specific command with flags.
Ex. I requested sudo access for this command below:
sudo /usr/bin/su - wassa /usr/was7/profiles/dmgr/bin/wsadmin.sh
I can run the above command but cannot run any of the below commands (it will prompt for password then say I do not have the required access):
sudo /usr/bin/su - wassa /usr/was7/profiles/dmgr/bin/wsadmin.sh -lang jython -c "AdminApplication.stopApplicationOnCluster('app', '$APP_CLUSTER')"
sudo /usr/bin/su - wassa /usr/was7/profiles/dmgr/bin/wsadmin.sh -lang jython -c "AdminApplication.stopApplicationOnCluster('app', '$APP_CLUSTER')"
I know I could easily request each command separately (which I may have to anyway because of the companies policy), but I want to avoid it in case I need to make any script changes, I won't want to have to submit another ticket and wait.
Answer: sudo allows shell-style wildcards (aka meta or glob characters) to be used in host names, path names and command line arguments in the sudoers file.
* Matches any set of zero or more characters.
?
Matches any single character.
[...]
Matches any character in the specified range.
[!...]
Matches any character not in the specified range.
\x
For any character 'x', evaluates to 'x'. This is used to escape special characters such as: '*', '?', '[', and ']'.
So you could define something along the lines of this to allow both the command with or without arguments:
leeman24 ALL=(wassa) /usr/was7/profiles/dmgr/bin/wsadmin.sh, /usr/was7/profiles/dmgr/bin/wsadmin.sh -*


Creating a "fake" open relay to capture non-relayable outgoing mail with postfix

Question: We occasionally have customer-provided servers in our technical support and engineering departments.  They're isolated on their own VLAN, with strict firewall rules in place to minimize possible bad behavior.
We've found ourselves needing to capture (instead of block) outgoing mail by these machines.  Redirecting ports and feeding machines fake MX records is easy.  Creating a fake open relay doesn't seem to be.  My goal is:

Mail to firstname.lastname@example.com gets relayed upstream (relay_domain = $mydomain and relayhost = $mydomain)
Mail to email@example.com gets captured and forwarded to an email address @ourdomain.com

Things that probably won't work, as answered in other similar questions:

BCC maps: I don't want the original mail delivered to the original recipients at all.
virtual_alias_maps: The outgoing mails could be to any domain, not just one or two domains.
canonical rewriting /^.*$/: Modifies all mail, which isn't what I want.  I only want non-relayable mail to be forwarded.

If this isn't possible in postfix, can other MTAs handle the task?  It looks like my other obvious choices are sendmail and exim.
Comment: This is inside of a lab / technical support environment.  We're trying to prevent mails from (possibly malicious) systems from reaching the internet, while still being able to inspect the content of those mails and know that they're trying to be sent.  Meanwhile, we still need the ability to send "real" mail from those machines to ourselves at our normal addresses.
Comment: It is not difficult do implement that. But why would you? This violates some RFCs. This is nothing I'm going to help you out. Better block mails not intended to be relayed.
Answer: Set up smtp-sink -- it is included in Postfix source distribution, but may not be present in binary package.
Comment: Interesting.  I could tie the message logging in with a quick script that watches the directory and re-mails selectively...
Answer: Use spamhole:
https://sourceforge.net/projects/spamhole/
From the website:
spamhole is a fake sopen SMTP relay, intended to stop (some) spam by convincing spammers that it is delivering spam messages for them, when in fact it is not.


C# Multiply textboxes answer always 1

Question: I have a problem with the following code.
bool TextBox2INT = true;
bool TextBox1INT = true;

int outputValue = 0;
int ButtonFind;

int TextBox1INT2 = Convert.ToInt32(TextBox1INT);
int TextBox2INT2 = Convert.ToInt32(TextBox2INT);

TextBox2INT = int.TryParse(textBox2.Text, out outputValue);
TextBox1INT = int.TryParse(textBox1.Text, out outputValue);

ButtonFind = (int)Math.Round((double)(TextBoxt1INT2 * 0.0333m * TextBox2INT2) + (double)(TextBox1INT2));
textBoxFind.Text = ButtonFind.ToString();

The problem is that the code works perfectly fine but when im debugging the answer in textBoxFind.Text is always 1.
Comment: Have you tried actually debugging your code? For example, looking at the values of the subexpressions?
Comment: The initialization of `outputValue` to zero isn't necessary since it's used as an out parameter (in the `TryParse` calls).
Answer: You're calling Convert.ToInt32(bool) which will only ever give 0 or 1.
I think you meant:
int TextBox1INT2, TextBox2Int2;

bool textBox1Valid = int.TryParse(textBox2.Text, out TextBox1INT2);
bool textBox2Valid = int.TryParse(textBox1.Text, out TextBox2INT2);

You should also take action if int.TryParse returns false - for example, telling the user to enter a valid number, instead of performing the calculation anyway. I'd also change your variable names, so you'd have something like:
int parsedTextBox1, parsedTextBox2;

bool textBox1Valid = int.TryParse(textBox2.Text, out parsedTextBox1);
bool textBox2Valid = int.TryParse(textBox1.Text, out parsedTextBox2);

if (!textBox1Valid || !textBox2Valid)
{
    // Do something to warn the user here, e.g. a message box
    return;
}

double result = (parsedTextBox1 * 0.0333m * parsedTextBox2) + parsedTextBox1;
textBoxFind.Text = ((int) Math.Round(result)).ToString();

Comment: Picking up rep like shooting fish in a barrel there Jon! But you did go the extra mile with lots of helpful info, so +1 from me ;-)
Comment: @Dommer: Not unless the answer's accepted, to be honest. Getting *votes* is easy - getting *rep* isn't always :)

C# Multiply textboxes answer always 1


Can't maximize The Form When I Used The Rounded Borders in Windows Form C#

Question: I have a form with rounded borders by codes below:
<code>[DllImport("Gdi32.dll", EntryPoint = "CreateRoundRectRgn")]
private static extern IntPtr CreateRoundRectRgn
(
    int nLeftRect,     // x-coordinate of upper-left corner
    int nTopRect,      // y-coordinate of upper-left corner
    int nRightRect,    // x-coordinate of lower-right corner
    int nBottomRect,   // y-coordinate of lower-right corner
    int nWidthEllipse, // height of ellipse
    int nHeightEllipse // width of ellipse
);

public Form1()
{
    InitializeComponent();
    Region = System.Drawing.Region.FromHrgn(CreateRoundRectRgn(0, 0, Width, Height, 30, 30));
}
</code>
But the problem is:When I Maximize the form, It doesn't maximize correctly.
It Maximizes like this:Image
Please Help Me...
Comment: And what happens if you try to resize the form? Hint: you may need to do something when form size is changed.
Comment: More likely you are doing custom drawing, then [Paint event/override](https://stackoverflow.com/a/5445286/1997232) might be appropriate.
Comment: You are not repainting the form on size changed you should look into overriding the `onPaint` method like @Sinatr said.
Comment: It is easy to see from the code snippet, note how you use the Width and Height properties.  They change, so you need the Resize event to do this correctly.  No need for rounded borders when the WindowState isn't Normal.
Comment: I know that i have to do something by maximizing but i don't know the codes @Sintar
Comment: Can you explain more?@HansPassant
Comment: I don't want rounded borders when the WindowsState isn't Normal too. I want to remove the rounds and just maximize to take all the screen. Can you help me in codes? @HansPassant
Comment: I can't imagine what code you need.  Maybe you don't know how to get the normal border back, set the Region property to null.
Answer: I Found The Answer ...
I should clear the all borders that I set before like this:
<code>private void btnMaximize_Click(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Maximized)
            {
                this.WindowState = FormWindowState.Normal;
                btnMaximize.Image = Properties.Resources.maximize_Black;
                Region = System.Drawing.Region.FromHrgn(CreateRoundRectRgn(0, 0, Width, Height, 30, 30));
            }
            else
            {
                this.WindowState = FormWindowState.Maximized;;
                btnMaximize.Image = Properties.Resources.maximize_Black_copy;
                Region = System.Drawing.Region.FromHrgn(CreateRoundRectRgn(0, 0, Width, Height, 0, 0));
            }
        }
</code>
Thanks For All Friends Wanted To Help Me.


Solving 2D Recurrences

Question: Problem
For a n x n grid, how many different ways are there to get from the southeast corner to the northwest corner if I can move one cell west, north, or northwest at any given time?
Recurrence
The number of possible paths starting at cell $(i, j)$ is the sum of the number of paths starting at all of its neighbors:
$$T(i, j) = T(i - 1, j) + T(i - 1, j - 1) + T(i, j - 1)$$
The cell at the northwest corner has only one path (not moving at all) and serves as the base case.
$$T(0, 0) = 1$$
If we're at the west edge, we can only move up.  Likewise, if we're at the north edge, we can only move left.  There is only one path from these cells.
$$T(i, 0) = 1$$
$$T(0, j) = 1$$
If each cell is assigned a number $m = T(i, j)$. this produces a grid that is symmetric about the diagonal - in other words:
$$T(i, j) = T(j, i)$$
If we just follow along the diagonal, then the symmetry can be used to somewhat simplify the recurrence:
$$T(n, n) = T(n - 1, n - 1) + 2T(n - 1, n) = T(n - 1, n - 1) + 2T(n, n - 1)$$
Is there a closed form T(n) for this recurrence relation?  I know it grows exponentially with increasing n, but the exact equation is hard to pin down.
Answer: These are the Delannoy numbers. So far as I know, they have no nice closed form, though they do satisfy
$$T(m,n)=\sum_k\binom{m+n-k}m\binom{m}k=\sum_k2^k\binom{m}k\binom{n}k\;.$$
They are OEIS A008288, and Wolfram has more information. All three links have more information and references.

Solving 2D Recurrences


Agenda js job executes immediately

Question: I'm using Agenda to run schedules events on my server.
I'm scheduling a job using this code:
var job = global.agenda.create('send happy hour notification', {});
job.repeatEvery('0 21 * * *');
job.unique({});
job.save();

So the job should run everyday at 21:00.
But every time my server starts it runs this job..
Am I doing something wrong?
Answer: By default any repeating job will execute on the repeating interval you schedule it to AND immediately. The last part is key: by default a repeating agenda will run immediately after you define it. To change this default behavior you pass skipImmediate: true to "options". Something like this:
job.repeatEvery('3 minutes', {
  skipImmediate: true
});
await job.save();

The above will only run when 3 minutes comes around and every 3 minutes after, as opposed to NOW and in 3 minutes and every 3 minutes after.
Answer: I faced the same issue and so I did some digging and found out that it happens because while saving it fails to calculate nextRunAt correctly, so just run   "job.computeNextRunAt();" before saving your job, and it should be working fine.
Comment: thanks this worked for me, but for some reason it only works if I use the cron job syntax and not if I use a time string.

Agenda js job executes immediately


What is the meaning of detailed balance in Markov Chains?

Question: I know what it means formally to say that a stochastic matrix and a measure are in detailed balance. ($ \lambda_iP_{ij} = \lambda_jP_{ji} \; \forall (i,j)$) but I'm not really sure how to interpret it intuitively, can anyone helpe me?
Answer: Imagine that a heap of sand is placed at each site, with a quantity $\lambda_i$ of sand at site $i$. A bell rings. Then each grain of sand at $i$ decides to migrate to $j$ with probability $P_{ij}$, independently of all the others (that is, each individual grain of sand performs a trajectory of the Markov chain and the trajectories are independent). Detailed balance means that as much sand traveled along the edge $(ij)$ from $i$ to $j$ as from $j$ to $i$. Detailed balance implies stationarity, that is, the fact that, once every grain of sand has settled at its new location, each site $i$ has again a quantity $\lambda_i$ of sand. But detailed balance is stronger than stationarity since it means that a film of the movements of the sand looks exactly the same when viewed forwards or backwards.


Jqgrid is not able to add, edit or delete into my instance of SQL server and I don't think it is even hitting the add, edit or delete function

Question: I am having issues with Free Jqgrid where I can not get it to post to my developer version of Microsoft SQL server. I am using Microsoft visual studios. I am using entity framework 6 for the database connections. When I use break points it doesn't seem to hit my createbid, editbid, or delete bid. I also don't get any errors in console.
I have looked through and done many of the tutorials for editing updating and adding lines. I had the same problem. I cant find an answer that works on stack overflow through my research.
I published it to IIS to see if maybe it was something with visual studios and to see if anything changes but i did get some errors this time. It is not finding the /Home/GetBidValues, Home/EditBid, /Home/CreateBid, /Home/DeleteBid. this is weird because with visual studios it was at least getting data into the grid and showing it. So I will look into this further and see if  there is something wrong with my ajax and also with my C# code.
Here is my Jquery file
$(function () {
    $("#grid").jqGrid
        ({
            url: "/Home/GetBidValues",
            datatype: 'json',
            mtype: 'Get',
            colNames: ['Client Cost', 'ElementId', 'Note', 'Area', 'Element', 'Item', 'Qty', 'Description'], //Othr Misc
            //colModel takes the data from controller and binds to grid
            colModel: [
               {
                    key: true,
                    hidden: true,
                    name: 'ElementId',
                    index: 'ElementId',
                    frozen: true,
                    editable: false
                }, {
                    key: false,
                    name: 'Note',
                    index: 'Note',
                    frozen: true,
                    editable: true,
                    width: 70,
                    align: 'center'
                }, {
                    key: false,
                    name: 'Area',
                    index: 'Area',
                    frozen: true,
                    editable: true,
                    width: 70,
                    align: 'center'
                }, {
                    key: false,
                    name: 'Element',
                    index: 'Element',
                    frozen: true,
                    editable: true,
                    width: 70,
                    align: 'center'
                }, {
                    name: 'Item',
                    index: 'Item',
                    frozen: true,
                    editable: true,
                    width: 70,
                    align: 'center'
                }, {
                    key: false,
                    name: 'QTY',
                    index: 'QTY',
                    frozen: true,
                    editable: true,
                    width: 70,
                    align: 'center'
                }, {
                    key: false,
                    name: 'Description',
                    index: 'Description',
                    frozen: true,
                    editable: true,
                    width: 70,
                    align: 'center'
                }],

            pager: '#pager',
            gridview: true,
            ignoreCase: true,
            rowNumbers: false,
            shrinkToFit: false,
            height: '100%',
            width: 1000,
            viewrecords: true,
            footerrow: true,
            emptyrecords: 'No records to display',
            jsonReader:
            {
                root: "rows",
                page: "page",
                total: "total",
                records: "records",
                repeatitems: false,
                Id: "0"
            }

        });
        $('#grid').jqGrid( 'inlineNav','#pager', {
            edit: true,
            add: true,
            del: true,
            cancel: true,
            search: true,
            refresh: true,
            editparams: {
                keys:true
            }
        }, {
            // edit options
            zIndex: 100,
                url: '/Home/EditBid',
                //datatype: 'json',
                //mtype: 'Post',
            closeOnEscape: true,
            closeAfterEdit: true,
            recreateForm: true,
            reloadaftersubmit: true,
            afterComplete: function (response) {
                if (response.responseText) {
                    alert(response.responseText);
                }
            }
        },{//add
            zIndex: 100,
                url: "/Home/CreateBid",
            closeOnEscape: true,
                closeAfterAdd: true,
                reloadaftersubmit: true,
            afterComplete: function (response) {
                if (response.responseText) {
                    alert(response.responseText);
                }
            }
        }, {
            // delete options
            zIndex: 100,
                url: "/Home/DeleteBid",
            closeOnEscape: true,
            closeAfterDelete: true,
                recreateForm: true,
                reloadaftersubmit: true,
            msg: "Are you sure you want to delete this task?",
            afterComplete: function (response) {
                if (response.responseText) {
                    alert(response.responseText);
                }
            }
        });
});

Here is my C# file
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using ERPWebAppTest.Models;
using Microsoft.AspNet.Identity;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Owin;

namespace ERPWebAppTest.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        Test1Entities db = new Test1Entities();

        [HttpGet]
        public JsonResult GetBidValues(string sidx, string sord, int page, int rows)
        {
            //old code
            int pageIndex = Convert.ToInt32(page) - 1;
            int pageSize = rows;
            var Results = db.BidDetails.Select(
                a => new
                {
                    a.ElementID,
                    a.Note ,
                    a.Area ,
                    a.Element ,
                    a.Item ,
                    a.QTY ,
                    a.Descr ,
    });
            int totalRecords = Results.Count();
            var totalPages = (int)Math.Ceiling((float)totalRecords / (float)rows);
            if (sord.ToUpper() == "DESC")
            {
                Results = Results.OrderByDescending(s => s.ElementID);
                Results = Results.Skip(pageIndex * pageSize).Take(pageSize);
            }
            else
            {
                Results = Results.OrderBy(s => s.ElementID);
                Results = Results.Skip(pageIndex * pageSize).Take(pageSize);
            }
            var jsonData = new
            {
                total = totalPages,
                page,
                records = totalRecords,
                rows = Results
            };

            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public string CreateBid([Bind(Exclude = "ElementID")] BidDetail obj)
        {

            Test1Entities db = new Test1Entities();
            string msg;
            try
            {
                if (ModelState.IsValid)
                {
                    db.BidDetails.Add(obj);
                    db.SaveChanges();
                    msg = "Saved Successfully";
                }
                else
                {
                    msg = "Validation data not successfully";
                }
            }
            catch (Exception ex)
            {
                msg = "Error occured:" + ex.Message;
            }

            return msg;

        }
        [HttpPost]
        public string EditBid(BidDetail obj)
        {
            Test1Entities db = new Test1Entities();
            string msg;

            try
            {
                if (ModelState.IsValid)
                {
                    db.Entry(obj).State = EntityState.Modified;
                    db.SaveChanges();
                    msg = "Saved Successfully";
                }
                else
                {
                    msg = "Validation data not successfull";
                }
            }
            catch (Exception ex)
            {
                msg = "Error occured:" + ex.Message;
            }

            return msg;
        }

        [HttpPost]
        public string DeleteBid(int ElementID)
        {
            Test1Entities db = new Test1Entities();
            BidDetail list = db.BidDetails.Find(ElementID);
            db.BidDetails.Remove(list);
            db.SaveChanges();

            return "Deleted successfully";
        }
    }
}

Answer: I see many small small issues into your jqgrid code, which can be one of the reason of your current problem. You can change them in order to make the above code workable.

colModel items numbers are not exactly same as colNames items. You wrote Client Cost at first in colNames but in colModel you haven't used that.
You also haven't pasted your html code which is required to point jqgrid to load on table element.
for example:

I am also assuming that you have already added free-jqgrid scripts and jquery-ui css files.
Also, in your c# code you can remove redundancy by using a global db initialization.

I have created a demo jqgrid which you can alter according your requirement:

@section Scripts{

}


Creation of a hashmap with struct in Rust

Question: I am trying to set up a hashmap of objects / structs in rust... But I don't understand this concrete problem  (a lifetime error).
#[derive(Hash, Eq, PartialEq)]
#[derive(Serialize, Deserialize, Debug)]
pub struct Node<'a> {
    identifier: &'a str,
    sha_id: Vec<u8>,
    successor_id: Option<Vec<u8>>,
    predecessor_id: Option<Vec<u8>>,
}

impl<'a> Node<'a> {
    ...
    ..
    .
}

pub struct Application<'a> {
    hash_map: HashMap<&'a str, Node>,
}

impl<'a> Application<'a> {
    fn join(&self, node: &Node) {
        self.hash_map.insert(node.identifier, node);
    }
}

The error is a missing lifetime specifier in  the hash_map: HashMap<&'a str, Node> that I tried to solve changing Node to Node<'a> but It throws a "mismatched type" error when I try to insert...
I don't exactly why I have this problem missing the lifetime and I don't find solutions..
UPDATE:
#[derive(Hash, Eq, PartialEq)]
#[derive(Serialize, Deserialize, Debug)]
pub struct Node<'a> {
    identifier: &'a str,
    sha_id: Vec<u8>,
    successor_id: Option<Vec<u8>>,
    predecessor_id: Option<Vec<u8>>,
}

impl<'a> Node<'a> {
    ...
    ..
    .
}

pub struct Application<'a> {
    hash_map: HashMap<&'a str, Node<'a>>,
}

impl<'a> Application<'a> {
    fn join(&self, node: &Node) {
        self.hash_map.insert(node.identifier, *node);
    }
}

And the output is:
"explicit lifetime required in the type of `node`"

UPDATE2:
pub struct Application<'a> {
    hash_map: HashMap<&'a str, Node<'a>>,
}

impl<'a> Application<'a> {
    fn join(&mut self, node: &'a Node<'a>) {
        self.hash_map.insert(node.identifier, *node);
    }

}

And the output is:
self.hash_map.insert(node.identifier, *node); cannot move out of borrowed content

COMPLETE SOLUTION
#[derive(Clone, Hash, Eq, PartialEq)]
#[derive(Serialize, Deserialize, Debug)]
pub struct Node<'a> {
    identifier: &'a str,
    sha_id: Vec<u8>,
    successor_id: Option<Vec<u8>>,
    predecessor_id: Option<Vec<u8>>,
}

impl<'a> Node<'a> {
...
..
.
}

pub struct Application<'a> {
    hash_map: HashMap<&'a str, Node<'a>>,
}

impl<'a> Application<'a> {
    fn join(&mut self, node: Node<'a>) {
        self.hash_map.insert(node.identifier, node);
    }

}

Comment: Then they need to clone the data, or have the hashmap store references. A `HashMap` always owns the data stored inside of it.
Comment: I can understand this. Directly, it is a bad design... I can try to refactor all the code to   clone data if you think it is the problem...
Comment: `insert` takes first the key and then the value...
Comment: sorry, I didn't paste correctly the code.. I edit the post, but the error is the same...
Comment: As far as I understand, `HashMap<&'a str, Node>` should provide a lifetime specifier to `Node` because it requires one by definition. So, it should be `HashMap<&'a str, Node<'a>>`.
Comment: Yes, but when I do this, I get a mismatched type error...  I don't exactly why...
Comment: You have 3 or 4 errors, but if you follow the compiler's advices, you should address all of them.
Comment: I understand that It can be tedious, but in fact, I have only one error, but when I fix one, It throws another one...
Comment: It should be telling you which line requires an explicit lifetime in the error message - my hunch is that the `&Node` on `join` needs to be `&Node<'a>`, or possibly even `&'a Node<'a>`.
Comment: @JoeClay, if you do this, though, Rust will refuse to move out of borrowed content with the last version of the code because, apparently, `insert` attempts to move the second argument.
Answer: This simplified example seems to work:
use std::collections::HashMap;

#[derive(Clone)] // we'll be cloning it later on
struct Node<'a> {
    data: &'a i32
}

struct Test<'a> {
    hash_map: HashMap<&'a str, Node<'a>>  // the hash map owns the struct
}

impl<'a> Test<'a> {
    fn new() -> Test<'a> {
        Test {hash_map: HashMap::new()}
    }

    fn join(
        &mut self, // must be mutable
        node: Node<'a>) { // do not pass a reference
        self.hash_map.insert("test", node);  // inserting moves `node`
    }
}

fn main() {
    let stuff = Node {data: &12};
    let mut test = Test::new();

    test.join(stuff.clone());  // if we don't clone, `stuff` will get moved

    println!("{}", *test.hash_map["test"].data);  // outputs "12"
}

Since std::collections::HashMap::insert attempts to move its second argument, one can't dereference a pointer to something and pass that to this method because otherwise the pointer will become uninitialized, which isn't permitted. A way so solve this is to pass a moved value and not a pointer to join.
Comment: While your code snippet might answer the question, it would be good if you could add a few sentences what was wrong and how you solved it, at best with some links to documentation or similar problems.
Answer: For poor idiots like myself, who are trying to find out how to put hashmaps in a struct, no need to spend many hours "playing" with lifetimes(the 'a in the above example). They are not required in the slightest, just use String instead of &str in your structure.
Edit: @neo made a slightly clearer version of my below example at rust-lang
struct ComputerConfig {
    hostname: String,
    // displays: Vec<DispConfig>,
}

struct MyConfig {
    pub config_version: u8,
    computers: HashMap<String, ComputerConfig>, // the hash map owns the struct
}

impl MyConfig {
    fn new() -> MyConfig {
        MyConfig {
            computers: HashMap::new(),
            config_version: 1,
        }
    }

    /// Join is used to add a new ComputerConfig into the hashmap
    fn join(
        &mut self, // must be mutable
        key: &str,
        node: ComputerConfig,
    ) {
        // do not pass a reference
        self.computers.insert(key.to_string(), node); // inserting moves `node`
    }
}

fn main() {

  let mut cfg = MyConfig::new()

  cfg.join("test", stuff);

  println!("{:?}", &cfg); // outputs "12"

}

Comment: I guess this answer sort of gives a much cleaner insight into using hashmaps, without the bringing in the complexity of lifetime to it. Ofcourse a little bit more of editing would have been made this perfect.

I have captured the compiling and running version of @matthew here just for others reference:

https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=4c026dce214a85620987b28b07956db6


Is it possible to disallow taking a reference to an object

Question: I want to do the opposite of making instances of a class noncopyable, that is, make sure that instances of a particular class can be passed only as a copy and not as a reference. If any function tries to receive it by reference, I would like it to give a compilation error (ideally) or a run time error.
I dont think making operator & private is going to do it, is there a legitimate way of doing this.
Comment: Fair question but chances are if you want to do this it's indicative of bad design.  This will prohibit you from factoring a large function if this object is used throughout.
Comment: @san - Interestingly enough, C++11 provides a `std::addressof` function that provides the address of an object even if you override or hide the `&` operator.
Comment: For a specific object you can prevent taking the address of a variable by declaring the variable as `register`. I.e. `register int a; &a` is not allowed. But this won't help with what is being asked for here.
Comment: Interesting idea, but this would basically be the same as disallowing a pointer to that kind of object, and that seems pretty unreasonable to me.
Comment: @san - not at all, I often do something like `Type& t = *pointerToType;` to avoid juggling pointer dereferences.  That only subverts the intent if the function it's passed to plans to take ownership which for many many functions will not be the case.
Comment: @DanF disallowing pointers would I think be easier. Making `&` private should do it.
Comment: @djechlin Could you substantiate your claim ? I can think of one use case, auto/scoped pointers. Passing them by reference subverts there intent.
Comment: @djechlin  Correct me if I am wrong, but one of the intended semantics of (a non const) auto_ptr is that if I pass it to some function it is the functions responsibility from then on. Anything that allows a function to deny responsibilty is a subversion of intent (especially when my code calls third party libraries when deployed on the client side). If every function was ideal, careful and well behaved, well, we wouldnt even need auto_ptrs to begin with, is it not ?
Comment: @BoPersson upvoted for the information, thanks
Comment: @amaurea Thanks. I never knew.
Answer: That's impossible. Any named variable can bind to a reference variable of the appropriate type. That's just how the language works.
In particular, you could never have a copy constructor with your restriction, so you couldn't actually pass the object by value!
Answer:
I dont think making operator & private is going to do it, is there a legitimate way of doing this.

No, because the & you use in function signatures for pass-by-reference is not an operator. You're talking either about the address-of operator (unary) or bitwise-and operator (binary). So it has nothing to do with pass-by-reference.
There's no way to disallow pass-by-reference for a type.
I doubt your motivation is strong enough to do this, and you appear to have a bad understanding of the passing mechanism:

If any function tries to receive it by reference, I would like it to give a compilation error (ideally) or a run time error.

A function either passes a parameter by reference, or by value. It's decided by its declaration, and I think your confusion stems from here. For example:
void foo(X x);

takes the parameter x by value. There's no way to pass it by reference. No way. Likewise:
void foo(X& x)

takes it by reference, and it always will.


Qual a diferença entre .prop() e .attr()?

Question: Essas duas funções do jQuery fazem exatamente a mesma coisa? Ou há alguma diferença entre as mesmas.
É informado que a função .prop() veio a partir do jQuery 1.6
Ela veio para substituir .attr() ? Ou as duas estão presentes(e usadas) hoje na biblioteca tendo as mesmas funcionalidades para quem as deseja usar?
Comment: Da uma olhada nessas respostas é em inglês possui vários exemplos http://stackoverflow.com/questions/5874652/prop-vs-attr
Comment: ótimo Gabriel! vou ver
Answer: Ambos perfazem as mesmas funções.
A diferença é que o método .prop() está no DOM e o método .attr() está no HTML.
Um exemplo, mais claro e genérico, é quando tenta acessar um atributo inexistente num elemento, poderá acessar esse atributo no DOM (usando o .prop()), porém, esse atributo está sempre vazio por padrão. Se acessa pelo método .attr(), retorna como undefined.
Exemplo:

v = $("#foo").prop("class");
console.debug("prop retorna vazio: "+v);
v = $("#foo").attr("class");
console.debug("attr retorna indefinido: "+v);

bar

Veja o resultado pelo console no developer tools. No chrome, pressione Ctrl+Shift+I e clique na guia "console".
Resultará nisso:
   prop retorna vazio:
   attr retorna indefinido: undefined

Answer: Depende da situação, na verdade o .prop() trás o valor, literalmente e o .attr() o conteúdo, por exemplo:
 <input type="checkbox" checked="checked"/>

$('input').prop('checked'); //Retorna true
$('input').attr('checked'); //Retorna checked

Na página do jquery isso é explicado com mais detalhes(inglês).
http://api.jquery.com/prop/
Comment: Na verdade não é que faça a mesma coisa, mas o resultado é o mesmo, quando você precisa do "value" de um elemento por exemplo...
Comment: Ótimo exemplo. O .prop() busca pelo DOM, e para o DOM, o checked é um booleano. Por isso retorna true ou false. O .attr() vai pelo HTML e retorna o conteúdo, no caso, retorna "checked" como uma string. Enfim, fazem praticamente as mesmas coisas com pequenas diferenças. A maior diferença que é bem clara é, um atua no DOM e outro no HTML.
Comment: hum... interessante, eu só usava attr(), não sabia o que o prop() fazia...
Você disse que depende da situação, pode haver algum caso em que os dois farão a mesma coisa?
Answer: 1º) ATRIBUTO -  Quando você escreve o HTML, chamamos de atributo do HTML
HTML
<input type="checkbox" />

    type é o atributo      "checkbox" é o conteúdo

    jquery pegando o atributo
        $('input').attr('type'); //retorna 'checkbox'
        $('input').attr('checked'); //retorna 'undefined'(porque você não
                                    //digitou o atributo checked = "checked"  no input,
                                    //então ele não existe lá)

2º) PROPRIEDADE - Quando você chama o objeto input, encontram-se as propriedades
HTML
<input type="checkbox" />

    type é o atributo      "checkbox" é o conteúdo

    a) Mostrando o objeto input com jquery

        console.log($("input"));
            quando você fizer este console verá que muitas propriedades aparecerão,
            porem vou mostrar somente duas no exemplo abaixo

            OBJETO
                input
                   type   : "checkbox", (type    é a propriedade - "checkbox" é o valor)
                   checked: false       (checked é a propriedade - false      é o valor)

    b) Jquery pegando a propriedade
        $('input').prop('type');    //retorna o valor 'checkbox'
        $('input').prop('checked'); //retorna o valor 'false'

RESUMO
        ATRIBUTO    .attr() você pega da escrita HTML <input type="checkbox" />
        PROPRIEDADE .prop() você pega do OBJETO input


How to solve for $x$ in $x^3+8^x-9=0$

Question: How to find real numbers $x$ that are solutions to
$$x^3+8^x-9=0$$
Please help me.
Comment: Another hint to go along with BMS's answer, look at a plot of the function, for example, using [*WA*](http://www.wolframalpha.com/input/?i=Plot%5Bx%5E3%2B8%5Ex+-+9%2C+%7Bx%2C-2%2C2%7D%5D). Regards
Comment: One more suggestion: many problems of this type (not all, of course) can be solved for $x$ using Lambert-W function (see Wiki entry on examples), but this is not a 'closed-form' solution
Answer: HINT: Try a few small whole numbers, and you'll quickly find a solution. Note also that $x^3+8^x$ is an increasing function of $x$, so there can be at most one solution.
Comment: @FashfeeshFood: I'd be surprised if there were one. I'd be **very** much surprised if there were a straightforward one.
Comment: yes i found  x=1 but i want  Algebraic solution
Answer: $$(x^3 -1)=(8-8^x) $$
$$(x-1)\color{Violet}{(x^2 +x+1)}= (8-8^x )$$
$$But\color{Violet} {(x^2+x+1)>0}$$
$$Eithr\color{blue}{  (x-1)\geq0} \space\space and\space \color{red}{8-8^x\geq0}$$
$$\color{blue}{x\geq1}\space and \space \color{red}{x\leq1} \Rightarrow\space \color{green} {x=1}$$
$$OR\color{blue}{  (x-1)\leq0} \space\space and\space \color{red}{8-8^x\leq0}$$
$$\color{blue}{x\leq1}\space and \space \color{red}{x\geq1} \Rightarrow\space \color{green} {x=1}$$
Comment: Very nice solution!
Comment: Nice solution +1
Answer: Note that
\begin{align}
x^3+8^x-9=0\iff
&
\begin{cases}
x^3-1=2^3-(2^{x})^3\\
x^3-8=1^3-(2^{x})^3\\
\end{cases}
\\
\iff
&
\begin{cases}
(x-1)(x^2+x+1)=[2-(2^{x})][2^2+2(2^{x}) + (2^{x})^2] \\
(x-2)(x^2+2x+4)=[1-(2^{x})][1+(2^{x})+(2^{x})^2] \\
\end{cases}
\\
\end{align}
Then is easy to see that $x=1 \implies x^3+8^x-9=0 $.
We have that $f(x)=x^3+8^x-9\implies f^\prime(x)=3x^2+e^x\cdot\log_e(8)>0$ and then $f(x)$ have only one root. That is, $f(x)=0\implies x=1$.
Then $x=1$ the unique root.

How to solve for $x$ in $x^3+8^x-9=0$