How to determine the number of terms in $(x+\frac{1}{x}+1)^n$

Question: I just wanted to know, how can I calculate number of terms in $$\left(x+\frac 1{x}+1\right)^n?$$
My try:
Any term of the expression will be of the form $(x)^i(\frac{1}{x})^j(1^k)$, and if in any term  if $i=j$ then it will become a constant term. I also tried to write the expression as $\frac{x^2+x+1}{x}$ but i don't know what to do know.
Please keep it simple and write how you got there. I just have no idea.
Thank you.
Comment: @ThomasAndrews yeah i wrote that but it was of no help.
Comment: Try $n=2$, how many terms do you get? What are they?
Comment: @SamSharma: As a suggestion, write down the things you've tried in your question to avoid receiving information you already know (such as Thomas' comment).
Comment: @Clayton i have edited it.
Comment: @ThomasAndrews please help.
Comment: Note that $x^i(\frac1x)^j1^k = x^{i-j}$. You're probably supposed to collect all terms with the same power of $x$ into a single one. How many different values of $i-j$ are possible?
Comment: @HenningMakholm how can i determine that?. Sorry i am new to this.
Answer: Hint: Our expression is equal to $\frac{1}{x^n}(x^2+x+1)^n$.
The number of terms is the same as the number of terms in $(x^2+x+1)^n$.
Imagine expanding $(x^2+(x+1))^n$ using the Binomial Theoremm $a=x^2$, $b=x+1$. We will get $x^{2n}$ plus a bunch of lower degree terms.
How many terms? There can't be any more than $2n+1$ terms, because each term will have shape a constant times $x^k$, where $k$ is any of $0, 1, 2,\dots,2n$.
Persuade yourself, and the reader, that there are no "missing" terms, that is, no coefficient of an $x^k$, $k=0$ to $2n$, is equal to $0$. Here we are helped in the argument by the fact that the coefficients of $x^2+x+1$ are positive, so on multiplication nothing can cancel.
Added: Your approach also works well, but some detail has to be filled in. We get a large sum. Before we simplify, they are of shape $x^i\left(\frac{1}{x}\right)^j 1^k$, where $i+j+k=n$. As you pointed out, when we simplify, some of these combine. For example, $x^1(1/x)^1(1)^{n-2}$ will become $1$, as will quite a few others, when $n$ is at all large. And there will be several ways to end up with an $x^1$, also several ways to end up with a $(1/x)$, which I will call $x^{-1}$.
What is the biggest power of $x$ that we get? By choosing $i=n, j=0,k=0$ we get $x^n$. By choosing $i=0,j=n,k=0$ we get $x^{-n}$. That's the smallest (most negative) power that we get. Between $n$ and $-n$, inclusive, we have $2n+1$ numbers (don't forget $0$).
We want to see that we get a term in every one of these powers. By symmetry, it is enough to show that we get stuff in every non-negative power of $x$, from the $n$-th power to the $0$-th power.
For $0\le m\le n$, we get $x^m$ in the expansion, for example by using $i=m,j=0,k=0$, and usually in several other ways. But the point is we do get some stuff that involves $x^m$. So every power of $x$, from $x^n$ down to $x^{-n}$ is represented, a total of $2n+1$.
Comment: I am sorry but i am not able to understand this, can you give another way round.Thank you and +1 for your help.
Comment: I will be away for a while. In the meantime, perhaps you can indicate in a comment which one(s) of the $5$ short paragraphs of the answer give you trouble.
Comment: The second para says: The number of terms is the same as the number of terms in $(x^2+x+1)^n$ but there is also x^n as denominator will it not cancel some terms in numerator and it will become constant.
Comment: Also in the third:how does expanding $(x^2+(x+1))^n$ gives x^2n plus a bunch of lower degree terms and also i am not able to understand third and fourth. I am sorry, but thank you for your effort. If you don't mind can you check what i have tried and where can i go from there. Thanks.
Comment: The point is that the highest term is $x^{2n}$ as you say.  The lowest term is $1=x^0$.  You will have one term for each exponent $0$ through $2n$, making $2n+1$ of them.  There is no need to compute the actual terms to solve this problem.


Stick Control for Speed

Question: I've been working on fine tuning my finger control to increase speed and finesse. Here is the problem. My stick rotates in my left hand. It does not move forward or backwards, just rotates. The problem is it rotates then seems to roll to the tip of my thumb, which causes me to stop and re-grip. Visually, my grip looks identical in both hands. Yes, my left is weaker, but I feel like I'm holding both sticks with equal pressure. How might I stop that rotation and roll?
Thank you!
Doug
Answer: I used to have exactly the same problem. In my case, one of the reasons was that my left hand do tend to slightly rotate inward - almost unnoticeably but enough to affect the stick rebound. Sadly there was no particular exercise to correct this but the obvious: Practice slow and focused, and practice also full strokes without finger control.
Focus on really feeling the rebound on the tip and raising the stick with the wrist movement being guided by the rebound, and not the other way around. Getting a good wrist stroke with a good rebound is key to a smooth transition into finger control, by feeling the rebound and starting to guide the stick back to the hitting surface with your fingers instead of the wrist.
Doing this exersice, slow and controlled, for a couple of hours straight (while you watch a movie) did drastically improve my finger control. After 3-5 movies you'll be pretty confident.

Stick Control for Speed


discontinuity of $f(x) = \sum_{n\geq 1} \sin((n+ \alpha /n)x)/n$

Question: It is well known that the function defined by
$$g(x) = \sum_{n\geq 1 } \sin(nx )/n $$
is a piece-wise linear function $x$, and has jumps at $x = 2 m \pi $. Its picture is

Now let us consider a modified function
$$f(x) = \sum_{n\geq 1 } \sin((n+\alpha /n)x )/n ,$$
where $\alpha $ is some real number. For $\alpha = 0.1$, its picture is

It also has jumps at $x = 2 m \pi $.
I am trying to understand it. It is not a standard Fourier series. How can we prove that it has discontinuities at $x = 2 m \pi$? Apparently, we have
$$ f(2m \pi ) = \frac{1}{2} (f(2 m \pi +0^+ ) + f(2 m\pi +0^- )). $$
This is also an interesting point.
Answer: I think I understand the phenomenon now. It is simple. Just consider the difference of the two series
$$ f- g = \sum_{n\geq 1} \frac{2}{n} \cos((n + \alpha /2n ) x)\sin (\alpha x /2 n ) . $$
This series converges uniformly into a continuous function.


Responsive images with multiple fields

Question: I'm working on a site that has (and must have) three image fields for out three breakpoints. We could call them field_img_mobile, field_img_tablet and field_img_desktop
Is there a way (a module?) that could load the image field corresponding to the breakpoint?
Answer: I think Picture module help you to solve your query.
Please check Responsive Images in Drupal with the Picture Module.
OR you can try these also :

Flickr
Responsive images and styles
Comment: I've already used picture, I remember that it works with a single field and multiple image cache. This is the best solution but unfortunately I've to maintain these three different fields.

Responsive images with multiple fields


Qual o efeito da função bind() em um código cliente?

Question: Estava perambulando pelo Google Imagens atrás de um diagrama de estado para modelo de servidor e cliente e acabei encontrando isso aqui:

Despertei curiosidade em relação a imagem acima devido ao fato de ser citado o uso da função bind() no lado do cliente. Isso me pareceu meio estranho, pois aprendi que a função bind() deve ser apenas usada pelo servidor e não pelo cliente.
Contudo, venho aqui com as seguintes dúvidas:

Que papel a função bind() desempenha em um código cliente?
Por que no diagrama diz que o uso da função bind() é opcional?
Como a função bind() poderia ser aplicada no código abaixo?
client.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <netdb.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

#define SRV_ADDR "127.0.0.1"
#define SRV_PORT "9009"

int make_socket(void){

    int ecode, sockfd;

    struct addrinfo *results=NULL, hints;

    memset(&hints, 0, sizeof(struct addrinfo));

    hints.ai_family=AF_INET;
    hints.ai_socktype=SOCK_STREAM;
    hints.ai_protocol=IPPROTO_TCP;

    if((ecode=getaddrinfo(SRV_ADDR, SRV_PORT, &hints, &results))!=0){

        sockfd=-1;

    }else{

        struct addrinfo *it=NULL;

        for(it=results; it!=NULL; it=it->ai_next){

            if((sockfd=socket(it->ai_family, it->ai_socktype, it->ai_protocol))==-1){

                continue;
            }

            if(connect(sockfd, it->ai_addr, it->ai_addrlen)==0){

                break;
            }

            close(sockfd);
        }

        freeaddrinfo(results);

        if(it==NULL){

            sockfd=-1;
        }
    }

    return sockfd;
}

short get_msg(char *msg, size_t n){

    int rv;

    if(fgets(msg, n, stdin)!=NULL){

        size_t len=strlen(msg);

        msg[len-1]='\0'; //elimina o \n

        rv=0;

    }else{

        rv=-1;
    }

    return rv;
}

int main(void){

    int sockfd=make_socket();

    if(sockfd!=-1){

        short rv;
        char msg[101];

        printf("\n");

        do{

            do{

                printf("Você >");

                if((rv=get_msg(msg, 101))!=0){

                    printf("\n* Falha na leitura!");
                    printf("\n  |.__Escreva a mensagem novamente.\n\n");
                }

                send(sockfd, msg, 101, 0);

            }while(rv!=0);

            if(strcmp(msg, "!exit")!=0){

                recv(sockfd, msg, 101, 0);

                printf("Estranho: %s\n", msg);
            }

        }while(strcmp(msg, "!exit")!=0);

        close(sockfd);
    }

    return 0;
}

Answer: Se não for feito 'bind' no socket utilizado no 'connect' então é feito um bind automático em uma porta disponível, geralmente uma porta chamada de "efêmera". (Isso também acontece quando se faz um 'bind' na porta 0).
Em geral não é feito o 'bind' na porta local em uma conexão client (criada por 'connect') porque não há necessidade, mas eventualmente pode haver casos de uso que isso pode ser feito. Você poderia criar uma aplicação server que só aceitasse conexões vinda de um client que utilize uma porta local específica, por exemplo.


Is weak convergence in $L^2(0,T;H)$ equivalent to weak convergence in $H$?

Question: Let $H$ be a hilbert space and let $u_n\in L^2(0,T;H)$ be a sequence. Then $u_n$ converges weakly to $u\in L^2(0,T;H)$ iff
$$\int_0^T (u_n(t),v(t))_H\,dt \to \int_0^T (u(t),v(t))_H\,dt$$
for every $v\in L^2(0,T;H)$. Does the following hold:
$$u_n \rightharpoondown u\quad \text{in } L^2(0,T;H) \quad\Leftrightarrow\quad u_n \text{ is bounded in } L^2(0,T;H)\text{ and } u_n(t)\rightharpoondown u(t)\quad \text{for almost all } t\in (0,T).$$
$\Leftarrow:$ Let $v\in L^2(0,T;H)$. By assumption, we have
$$(u_n(t),v(t))_H \to (u(t),v(t))_H\quad\text{for almost all } t\in (0,T).$$
Since
$$\lvert(u_n(t),v(t))_H\rvert\leq \lvert\lvert u_n(t)\rvert\rvert_H \lvert\lvert v(t)\rvert\rvert_H,$$
we can use the hölder inequality and the boundedness of $u_n$ to bound the righthandside by an integrable function. Lebesgues dominated convergence then implies
$$\int_0^T (u_n(t),v(t))_H\,dt \to \int_0^T (u(t),v(t))_H\,dt$$
and thus $u_n \rightharpoondown u$ in $L^2(0,T;H)$. Is my reasoning correct?
I am also stuck on the other direction.
Answer: Take $H=\mathbb{R}$ (or any finite-dimensional space), then weak convergence in $H$ is equivalent to strong convergence. But weak convergence in $L^2((0,T),\mathbb{R})$ does not imply pointwise almost everywhere convergence. For example, $u_n(t) = \sin(nt)$ converges weakly to zero in $L^2((0,T),\mathbb{R})$ as $n\to\infty$, but it does not converge a.e. to zero since every $u_n$ is nonzero except at a finite number of points. In fact, you can't even extract an a.e. convergent subsequence. (See Pointwise almost everywhere convergent subsequence of $\{\sin(nx)\}$)


Circle timer background color change

Question: I am using a timer. I want to put a black background at the back of text in the circle shape. right now it is transparent and you can see blue color at the back of text. I want that blue to black in the center part of the circle only.
<code>$("#DateCountdown").TimeCircles();
$("#CountDownTimer").TimeCircles({
    time: {
        Days: {
            show: false
        },
        Hours: {
            show: false
        }
    }
});
$("#PageOpenTimer").TimeCircles();
var updateTime = function () {
    var date = $("#date").val();
    var time = $("#time").val();
    var datetime = date + ' ' + time + ':00';
    j$("#DateCountdown").data('date', datetime).TimeCircles().start();
}
$("#date").change(updateTime).keyup(updateTime);
$("#time").change(updateTime).keyup(updateTime);
$(".startTimer").click(function () {
    $("#CountDownTimer").TimeCircles().start();
});
$(".stopTimer").click(function () {
    $("#CountDownTimer").TimeCircles().stop();
});
$(".fadeIn").click(function () {
    $("#PageOpenTimer").fadeIn();
});
$(".fadeOut").click(function () {
    $("#PageOpenTimer").fadeOut();
});
</code>
Fiddle
Answer: The plugin didn't support it... So what I did was change the plugin.
I added:
<code>    use_inner_background: true,
    circle_inner_bg_color: "#000",
</code>
to the standard settings, you can change these as you will to make it transparent or not. I defaulted it to black.
See the working fiddle, here

Circle timer background color change


Proving absolute convergence for complex sequences

Question: Let $(z_n)_{n\in\mathbb{N}}$ be a complex sequence and $\alpha\in]0,\dfrac{\pi}{2}[$. For all $n\in\mathbb{N}$, the argument of $z_n$ is in $[-\alpha,\alpha]$. If $\sum z_n$ converges, prove that it's absolutely convergent.
Answer: Hint
Let $z_n=x_n+y_n\,i$. Since $|\arg{z_n}|\le\alpha<\pi/2$, $x_n\ge0$ and $|y_n|\le(\tan\alpha)\,x_n$.


How to INSERT date in PHP & Mysqli

Question: i have variable $est_date = "25-02-2015" this is DD-MM-YYYY format
so now i need to insert this value in mysql table, the column type is DATE TIME,
so i tried like this but the date are not storing in the coloumn est_date,
it just showing me 00-00-0000
$mysqli = new mysqli('localhost','root','','smart_marine');
$insertdate = date("d-m-Y", strtotime($est_date));
$insert = $mysqli->prepare("INSERT into repair (
                                            cont_details_id,
                                            depot_details_id,
                                            cont_condition,
                                            est_cost,
                                            currency,
                                            est_date,
                                            location
                                            )
                                VALUES (?,?,?,?,?,?,?)");

        $phpArray = json_decode($serialize_data, true);
        foreach ($phpArray as $key => $value)
        {
            if($value['rate']!=''&& $value['drop']!='')
            {
            $insert->bind_param('sssssss',
                                 $value['id'],
                                 $depot_details_id,
                                 $value['drop'],
                                 $value['rate'],
                                 $currency,
                                 $insertdate,
                                 $location);
            $insert->execute();
            }
        }

please some one help me.
i tried to store like this too
$insert->bind_param('sssssss',
                                     $value['id'],
                                     $depot_details_id,
                                     $value['drop'],
                                     $value['rate'],
                                     $currency,
                                    STR_TO_DATE($est_date , '%d-%m-%Y'),
                                     $location);

but this return error "undefined function STR_TO_DATE"

Comment: But you stated this :- `i need to insert this value in mysql table, the column type is DATE TIME`
Comment: data type of the field is "date"
Answer: You need to change this line:-
$insertdate = date("d-m-Y", strtotime($est_date));

to
$insertdate = date("Y-m-d", strtotime($est_date));

Note:- DATETIME data-type format is Y-m-d H:i:s. thanks.
Answer: A datetime format is YYYY-MM-DD. Reset the date like this:
$date = date("Y-m-d", strtotime($est_date));

Then pass into your query.
Answer: The general format of DATE in mysqli is
 'date_add' => date("Y:m:d H:i:s"),

and if you have a variable just put after your value of variable

How to INSERT date in PHP & Mysqli


Set action on detailDisclosureButton in UITableViewCell

Question: I have set UITableViewCell in my app.
productsCell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;//productCell is of type UITableViewCell

Previously for this accessoryAction property was used. But now its deprecated.
How to do this.
Thanks in advance.
Answer: Implement this method in your delegate:
- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath

indexPath will point on the cell which accessory cell was tapped.
Or try this:
UITableViewCell *cell;
UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(accessoryTapped)];
[cell.accessoryView addGestureRecognizer:recognizer];
[recognizer release];

Comment: I did that. But method is not being called. Make sure, I am using a single cell of UITableViewCell. I am not using UITableView.
Comment: Are you using cell without table?
Comment: Yes. I am using it without cell. In my requirement tableView doesn't fit.
Comment: Then I can only suggest to add `UITapGestureRecognizer` to your `cell.accessoryView`.


How do I force git to think a file is unmerged?

Question: I want to make changes to a file in my repo, then force git to believe the file is unmerged and show up in git status like so:
# Unmerged paths:
#   (use "git reset HEAD <file>..." to unstage)
#   (use "git add <file>..." to mark resolution)
#
#       both modified:      lib/delayed/recipes.rb
#

That's the entirety of my question. Read on for an explanation of why, since I know that's the first thing that will be asked.
The purpose here is a bugfix for Piston which today leaves merge conflicts in the index where they are too easily overlooked.
The way piston update works with a Git repo is:

Clone the remote repo into a new temporary git repo
Checkout that temp repo to the last commit we saw (saved in .piston.yml)
Checkout our local repo (in a new branch) to the last commit where .piston.yml was updated
Copy our local repo's files into the temp repo
Commit all changes in the temp repo (these are our local changes as of the last time we updated this vendored project)
Run git merge master in the temp repo to merge our local changes with the remote repo's changes
IGNORE MERGE CONFLICTS(!) and copy all the files from the temp repo to our local repo
Commit those files (in our new temp branch) to our local repo
Checkout local repo back to our original starting point
Merge temp branch into local repo (adds any further changes we have made)

I expect to fix this problem by allowing the file with merge conflicts to be committed into the temp branch, but at the very end (after it runs git merge --squash) I want to tell git about the files that had a merge conflict in the temp repo.
Comment: See "How to selectively recreate merge state?" thread on Git mailing list: http://thread.gmane.org/gmane.comp.version-control.git/135059
Answer: In Git file that has a merge conflicts has (usually) three versions in index, and a version in working area with diff3 -E / rcsmerge conflict markers.  The versions in the index are stage 1 from common ancestor, stage 2 for "our" version, and stage 3 for "theirs" version.  For unmerged file there is no version in stage 0 (you can use git update-index --unresolve to restore unmerged state by deleting stage 0).
You would need to use git ls-files --stage or git ls-tree <commit> to get sha-1 identifiers of blobs (file versions) you want to put in index, or git hash-object -w <file> if you want to generate version of a file from scratch / from working area version.  Then you use git update-index --index-info to put higher order stages into the index file (and git update-index --unresolve after this, or git update-index --force-remove prior to stuffing higher stages to remove stage 0 from index).  You can re-generate file with merge markers in working area using git checkout --conflict=merge -- <file>.
HTH (Hope That Helps)

See also: "How to selectively recreate merge state?" thread on Git mailing list.
Comment: The two file versions that had the merge conflict are in another repo, and may have had a third version merged in by now. Isn't that a problem? (Though I confess I don't yet understand your response completely.)
Comment: I'm beginning to understand better. I think I would have to set it up to appear as an octopus merge, no? Merging common ancestor plus vendor changes plus local changes. This is way more complex than I anticipated and I don't think I'm up for it anymore. Thanks for the answer, though.
Comment: No octopus: merges are 3-way merges in Git, therefore three versions needed.  I'll try to come up with an example later.


How to flag only one message as "\flagged" with Horde Imap Client library

Question: I'm trying to flag message with the imap flag "\flagged". The problem is that not only the message I intended to mark gets flagged, but also all other messages which were sent from the same email address are also flagged.
For example, in my mailbox I have 10 messages from email@example.com. I want to mark only one of them as "flagged", so I get it's uid and send a request. But it marks all 10 messages. I want only that one with the specific uid.
I'm working with gmail account. When flagging messages in gmail's webmail itself, it marks only one message as intended, so it's not a weird feature from gmail itself.
The code I'm using is below. What's the problem?
$uids = new Horde_Imap_Client_Ids([1521]);//uid of message I want to mark as flagged

$options = [
    'uids' => $uids,
    'add' => ['\flagged'],
];

$Imap_Client_Socket->store('INBOX', $options);

Comment: Also, I think you need to escape the \ with \\ so it become `\\flagged`.
Answer: Change your options to this
$options = [
  'ids' => $uids,
  'add' => [Horde_Imap_Client::FLAG_FLAGGED],
];

Notice how uids changed to ids. Also, I used the flag constant defined in Horde_Imap_Client instead.


RapidApi Testing returns `kutz-log-nil-tenantid`

Question: On RapidAPI I have created a new API and added a simple GET endpoint (/version). Every call (from the Dashboard Test Endpoint feature and from the browser) returns
{"version":"kutz-log-nil-tenantid"}

Anyone experiencing the same? Did I miss some configuration? I cannot see what it is wrong.
Answer: It looks like /version is a reserved word and cannot be used.
After creating a different endpoint (ie /status) it works fine.
RapidAPI documentation lists the reserved words but version in not one of them.
Answer: I think something was wrong from the backend when you were creating this endpoint because /version is not the reserved word.
It should work fine if you try this now.
Remember, you can always write to the RapidAPI support team(firstname.lastname@example.com). They are very active and would love to help you out.
Comment: Thanks Pratham. I contacted Support and they confirmed it is a reserved word but the documentation is not up-to-date. They are working (apparently) to fix this.


Send Query or SP output as HTML mail from Azure data factory

Question: I'm trying to implement Azure data factory pipeline. From there trying to execute one SP and need to send output in HTML format from Azure data factory through Logic App. Facing issue while sending output to Web task in ADF.
Any hint ?
Error details
Error code
2108
Troubleshooting guide
Failure type
User configuration issue
Details
{"error":{"code":"InvalidRequestContent","message":"The request content is not valid and could not be deserialized: 'Unexpected character encountered while parsing value: <. Path '', line 0, position 0.'."}}
Source
Answer: In Body option of the Setting TAB in Web Activity, Instead of adding the JSON in the "Dynamic Content", add JSON as usual in the box.
Refer below screen shot:


O que é um banco de dados embutido (embedded)?

Question: o que é um banco de dados embutido, e que como chamamos os "não embutidos"?
Por exemplo:
Eu estou tentando criar um banco de dados pelo H2 Database Engine, e tem duas opções de banco H2: Embedded ou Server. Poderiam me explicar melhor esses dois tipos, e se tem outros?
Comment: Relacionada: [O que caracteriza um banco de dados?](https://pt.stackoverflow.com/q/191199/28595)
Answer: Geralmente o termo é usado quando o mecanismo de acesso ao banco de dados fica junto com a aplicação, em oposição de ter uma outra aplicação com a qual a sua se comunica para acessar o banco de dados.
O banco de dados embarcado mais conhecido é o SQLite (e também é o mais usado do mundo considerando todos os tipos de DB).
Nesse caso o produto permite funcionar assim ou como servidor. Cada um tem sua vantagem.
Para coisas simples que vão rodar só naquela máquina costuma ser melhor usar ele embarcado na aplicação. Só não sei o quanto o H2 é bom nesse modo, é comum ter algumas limitações, alguns produtos tem limitações demais. Mas tende ser mais rápido e simples de implantar e cuidar. Quase todos os websites do mundo (não falo de aplicações web, muitas podem, mas boa parte não) podem bem ser atendidos por um banco de dados embarcado, até porque a esmagadora maioria deles tem pouco acesso e pouca interação. Rearquitetado "um pouco", provavelmente este site (a versão em inglês mesmo, um dos sites mais acessados do mundo, mas que praticamente é uma aplicação) daria para rodar com SQLite ou algum DB embarcado, com vantagens e desvantagens (não é que seja tão simples e não estou dizendo que compensa).
Se tiver várias instâncias de aplicações querendo acessá-lo ao mesmo tempo, especialmente em máquinas diferentes o servidor passa ser melhor, ou até necessário.
Coloquei no GitHub para referência futura.


Como funciona o recurso "Buscar por imagem semelhantes" do google?

Question: Estou precisando criar um gerenciador para um banco de imagens bem extenso, onde neste gerenciador além da busca por título e descrição, deverá haver um recurso que busque por imagens visualmente semelhantes.
Para este caso estive pensando em "dividir" uma imagem em blocos e salvar as informações predominância de cor de cada bloco, porém acredito que desta forma só seria possível encontrar imagens de cores semelhantes.
Como funciona o recurso do Google de encontrar imagens semelhantes?
Answer: Eu não sei te dizer como funciona exatamente o algoritmo específico do Google, mas posso oferecer uma ajuda em como é o princípio básico da busca de imagens por conteúdo.
Essa área é comumente chamada de CBIR (Content-Based Image Retrieval, ou Recuperação de Imagens Baseada em Conteúdo em português), pois envolve a busca de imagens a partir de seu conteúdo. É uma área de grande interesse mas de difícil solução porque as imagens são de difícil interpretação por computadores (é por isso que se usa amplamente CAPTCHAS para impedir acesso automatizado às páginas na Internet).
Há algumas abordagens tradicionais pra resolver esse problema.
1. Busca Baseada em Anotação
A ideia de anotar as imagens com rótulos descritivos do seu conteúdo é a mais simples. Você apenas cria um banco de dados contendo as imagens e os textos (rótulos) que a descrevem. Imagine, por exemplo, a imagem de um filhote de cachorro. O banco de dados pode conter pra elas as palavras "filhote", "cachorro", "labrador" (se for o caso), e por ai vai. A busca então seria realizada com base nas anotações, sendo as imagens devolvidas aquelas cujas anotações mais bem correspondem ao termo de pesquisa. Eu suponho que esse seja o algoritmo principal utilizado pelo Google, quando você pesquisa por imagens usando expressões de texto.
A grande dificuldade desse método é que é trabalhoso e entediante fazer anotações manuais das imagens. Por isso, existem soluções parcialmente automatizadas. O Google, muito provavelmene, utiliza reforço humano a partir das pesquisas efetuadas. Você digita um texto qualquer ("cachorrinho", no exemplo anterior - uma palavra que ainda não consta como anotação) e ele exibe imagens mais e menos "relevantes" com base nos links existentes entre elas. Se você clica em uma imagem menos relevante (que ainda não tem esse rótulo), isso pode ser considerado um indício de que você, como humano, validou que esse rótulo também é aplicável. Se mais pessoas fazem o mesmo, então o Google pode automaticamente adicionar tal rótulo à imagem, e aumentar a relevância dele conforme essas buscas específicas ocorrem.
Outra ideia é usar fontes de rotulações mantidas por humanos, como o Flickr e/ou o Pinterest. Apesar de ser uma tarefa entendiante, quem gosta de fotografia sente prazer em fazê-lo nesse contexto. Além disso, há um trabalho comunitário na rotulação, que facilita a existência de novos rótulos.
Há ainda a ideia de usar jogos para automatizar a rotulação. A ideia é bem simples, mas muito inteligente: com um jogo de adivinhação, duas pessoas (que não necessariamente se conhecem) jogam pela Internet. O jogo simplesmente apresenta uma foto (de um filhotinho de labrador, por exemplo) para um dos jogadores, e o outro jogador (que não vê a foto) precisa adivinhar com base em perguntas que só podem ser respondidas com sim ou não pelo companheiro de jogo. As perguntas (por exemplo, "É um animal?) que vão sendo respondidas como sim, se tornam rótulos automaticamente, e a relevância decorre do número de ocorrências entre diferentes partidas. Eu infelizmente perdi a referência desse jogo, mas há inúmeros outros como o ESP-Game (que é bem similar) e o Name-It-Game (que faz a anotação por regiões).
2. Busca Baseada em Similaridade
Um dos problemas da abordagem anterior é que mesmo que as imagens sejam muito bem rotuladas ainda podem existir dificuldades semânticas importantes. Um exemplo clássico é a busca pelo termo "porco". Esse termo pode retornar imagens que sejam rotuladas corretamente, mas que são muito distintas e não necessariamente representam o que o usuário desejava no momento da busca. Eis um exemplo clássico (aqui no Brasil, ao menos):

uma imagem da Ilha dos Porcos (uma ilha do litoral Paulista)
uma imagem de uma vara (coletivo) de porcos (o animal)
uma imagem de relacionada ao time de futebol Palmeiras (time Paulista cujo apelido é "Porco")

A ideia dessa segunda abordagem é melhorar a busca evitando o uso de texto, mas fazendo a busca de imagens que sejam similares a uma imagem de referência fornecida pelo usuário (recurso que o Google Images também tem disponível).
A grande dificuldade dessa abordagem é justamente definir similaridade. Há três formas tradicionais (e eu suponho que o Google use uma mistura das duas primeiras): similaridade por cor, similaridade por textura e localização de pontos de referência.
Na similaridade por cor o algoritmo pode realizar uma medição numérica das cores na imagem de referência, e então buscar em um banco de dados em que tal medição já esteja pré-calculada (afinal, fazer esse cálculo a cada pesquisa é computacionalmente inviável). Existem inúmeros algoritmos, mas o mais simples é o seguinte (a fonte original dessa sugestão é esta resposta no SOEN):

Escale as imagens para um tamanho pequeno (64x64, por exemplo, para que os detalhes sejam menos importantes na comparação).
Escale as cores para o mesmo intervalo (para que ambas as imagens tenha a cor mais escura como preto e a mais clara como branco).
Rotacione e inverta as imagens para que os cantos mais claro e mais escuro fiquem em locais padronizados (mais claro no canto superior esquerdo e mais escuro no canto inferior direito, por exemplo, para que ambas estejam na mesma orientação).
Então, tire a diferença entre cada pixel e calcule a diferença média. Quando mais próxima de zero, mais similares serão as imagens.

É comum também combinar a comparação de cores com os locais e/ou o formato em que elas ocorrem. Como a diferença média do algoritmo anterior fornece um único valor para toda a imagem, a comparação vai resultar em algo como você mesmo disse na pergunta: comparar pela predominância geral de cor. Nesse caso, uma alternativa é - ao invés de ter um único valor de diferença média - ter uma quadtree com valores médios para diferentes regiões (e sub regiões) da imagem. Assim, a comparação pela similaridade ainda será por predominância de cores, mas em regiões específicas de forma a gerar resultados potencialmente mais acurados.
Em um passado não muito distante havia um produto comercial da IBM chamado QBIC, que chegou a ser usado em museus para facilitar a busca de quadros: bastava você desenhar mais ou menos o quadro que desejava (céu azul claro, mar azul escuro, areia amarela, por exemplo) e ele achava imagens similares. Infelizmente não achei museus que ainda usem essa tecnologia, mas há esse exemplo de buscador chamado Retrievr que faz exatamente o mesmo, buscando imagens similares ao que você desenha no Flickr. :)
Há também outro algoritmo bastante utilizado para definir similaridade: a comparação do histograma de cores normalizado. Um histograma nada mais é do que uma distribuição de frequências, isto é, do número de ocorrências de algo (cada valor de pixel, por exemplo) em um contexto (na imagem, por exemplo). O histograma de cores não separa as ocorrências por valor de pixel, mas sim por cada cor em uma sequência de cores (que você mesmo define, não precisa ser só RGB). Imagens semelhantes tem essa distribuição muito parecida, e a vantagem é que quando o histograma é normalizado (isto é, transformado em percentual de cada cor, pra não importar o número total de pixels) isso torna a comparação independente de rotação e escala nas imagens. Veja esta outra resposta do SOEN para mais detalhes sobre a implementação (nela há uma referência a slides com ajuda para obter histogramas em OpenCV, por exemplo).
Assim, você pode implementar esse algoritmo da seguinte forma:

Calcule o histograma de cores para ambas as imagens (em cada imagem, conte os pixels e acumule essa contagem em "categorias" de cores que você definir - no exemplo da Wikipedia os pixels são contados para cada combinação RGB, mas com os valores dos pixels escalonados para [0 a 3] pra facilitar - isto é, diminuir o tamanho da tabela). Naturalmente, no caso das imagens no banco de dados esses valores podem (devem!) estar pré-calculados.
Normalize os valores em cada categoria, dividindo o valor pelo número total de pixels. Isso resultará no valor em formato percentual, mais fácil de ser comparado.
Compare os histogramas das duas imagens medindo, por exemplo, a taxa média de erro. Para cada categoria, tire a diferença entre os valores nas duas imagens. Depois, tire a diferença média entre todas as categorias. Quanto mais semelhante a imagem, mais próximo de zero será essa diferença.

Na similaridade por textura procura-se definir o padrão (matemático) da textura da imagem. Você pode imaginar algo como a sequência de "claro-escuro-claro-escuro-..." que ocorre em uma imagem de um piso ladrilhado, por exemplo. Algo muito utilizado nesse caso são os Filtros de Gabor. Esses filtros são muito sensíveis às variações de bordas na imagem (bordas são detalhes importantes) em diferentes orientações (vertical, horizontal, diagonal, etc). Esses filtros são considerados como muito próximos à forma como o olho humano responde aos mesmos estímulos visuais, mas independentemente disso o fato é que eles são muito úteis para descrever a textura de uma imagem.

No blog de Patrick Fuller há um fantástico tutorial (em inglês)
  de 6 partes que vai te explicar muito facilmente (e com exemplos em
  C++) o princípio do processamento de imagens até chegar ao Filtro de
  Gabor. Vale a leitura!

Assim, é possível extrair esse padrão de uma imagem para então utilizá-lo em buscas. É também muito comum utilizar algoritmos de aprendizagem-de-máquina para aprender o padrão de um conjunto de imagens de exemplo e utilizá-los na classificação de novas imagens (como sendo de algo "já conhecido"). Este exemplo em Python demonstra exatamente isso, usando a biblioteca Scikit-Learn. Ele aprende o padrão de imagens de tijolos, grama e parede, e usa-o na função match para comparar as características de textura (features) de duas imagens (usando os mínimos quadrados para definir o "erro" - que quanto mais próximo de zero, mais similares as imagens são).

Por fim, há também a possibilidade de se comparar as imagens diretamente em termos do detalhe de seu conteúdo, de forma a tentar encontrar imagens que sejam semelhantes em termos dessas ocorrências. A ideia é primeiramente encontrar nas imagens as características de borda (features) mais relevantes, e então verificar se as mesmas características ocorrem nas duas imagens (na de referência e na sendo comparada na busca).
Essa abordagem é mais usada para sobrepor imagens parciais (para juntá-las automaticamente e criar um panorama 360º, por exemplo), mas poderiam ser utilizadas também na comparação de conteúdo em uma busca. Existem exemplos prontos em OpenCV, tanto para identificar as características mais relevantes, como para fazer a sua localização entre as imagens (matching):


Change input value on hover CSS

Question: Value of button gives me name of button on site. I want to change this button name on hover but i have no idea how to do it.
echo '<form id="pszycisk" method="POST" >';
           echo "<input id='submit' class='$przycisk' name ='obejrzane' type='submit' value='$przycisk' > ";
         echo '</form>';

Answer: You can use JavaScript to change the name on hover with onmouseover event and it can change back to the previous name with onmouseout event.

var submitBtn = document.getElementById('submit')
var submitBtnOriValue = document.getElementById('submit').value;

submitBtn.onmouseover  = function () {
    submitBtn.value = "hovered"
}
submitBtn.onmouseout  = function() {
    submitBtn.value = submitBtnOriValue;
}
<input id='submit' class='$przycisk' name ='obejrzane' type='submit' value='not hover' >
Answer: If you need a pure css solution you can do something like this. Place two buttons in the same position, one is hidden by default and only shows when the visible one is hovered:

.button-container {
  position: relative;
}
.hover-hide-me,
.hover-show-me {
  position: absolute;
  top:0;
  left:0;
  width: 100px;
}
.hover-show-me {
  display: none;
}
.hover-hide-me:hover + .hover-show-me {
  display: block;
}
.hover-show-me:hover {
  display: block;
}
<!DOCTYPE html>

        <input type="submit" value="NOT HOVER" class="hover-hide-me">
        <input type="submit" value="HOVER" class="hover-show-me">

The best solution is to use javascript, like in the other answer provided. This is just a trick if you want to stick to css.
Regards.

Change input value on hover CSS


Kotlin Multi Platform framwork CodeSig problem on a Mac OS application

Question: I created a module using kotlin multi-platform and is it is working perfectly on Android and iOS, but when I try to do the same for a macOS app I get the following error:
XYZ.app: code object is not signed at all
Command CodeSign failed with a nonzero exit code

I'm generating the framework as follow:
kotlin {
    jvm("android")

    macosX64("mac") {
        binaries {
            framework {
                baseName = "XyzForMac"
            }
        }
    }

    def iosClosure = {
        binaries {
            framework {
                baseName = "XyzForIos"
            }
        }
    }
    if (System.getenv("SDK_NAME")?.startsWith("iphoneos")) {
        iosArm64("ios", iosClosure)
    } else {
        iosX64("ios", iosClosure)
    }

    sourceSets {…}
}

task packForXcode(type: Sync) {
    def targetDir = new File(buildDir, "xcode-frameworks")
    def mode = System.getenv("CONFIGURATION") ?: "DEBUG"

    def frameworkMac = kotlin.targets.getByName("mac").binaries.getFramework(mode)
    inputs.property("mode", mode)
    dependsOn frameworkMac.linkTask
    from frameworkMac.outputDirectory
    into targetDir

    def frameworkIos = kotlin.targets.getByName("ios").binaries.getFramework(mode)
    inputs.property("mode", mode)
    dependsOn frameworkIos.linkTask
    from frameworkIos.outputDirectory
    into targetDir

    doLast {
        def gradlew = new File(targetDir, "gradlew")
        gradlew.text = """\
            |#!/bin/bash
            |export 'JAVA_HOME=${System.getProperty("java.home")}'
            |cd '${rootProject.rootDir}'
            |./gradlew \$@""".stripMargin().stripIndent()
        gradlew.setExecutable(true)
    }
}

tasks.getByName("build").dependsOn(packForXcode)

It looks I'm doing everything correctly, especially because the app is running as expected on Android and iOS. I'm wondering if I missing any mac os specific configuration to make it works…
Answer: I solve the problem changing the approach, instead of using the custom task packForXcode and importing manually the framework, I'm using now the CocoaPods integration, so what I did:

Using cocoapods, deleting the packForXcode task (and the custom steps on Xcode)
I'm moving the targets to a specific block on gradle build:
Because I'm using cocoapods there are no different packed binaries anymore

kotlin {
    targets { // <-- this is new
        jvm("android")

        macosX64("mac") {
            binaries {
                framework("Xyz") // Removed the ForMac
            }
        }

        def iosClosure = {
            binaries {
                framework("Xyz") // Removed the ForIos
            }
        }
        if (System.getenv("SDK_NAME")?.startsWith("iphoneos")) {
            iosArm64("ios", iosClosure)
        } else {
            iosX64("ios", iosClosure)
        }
    }
    cocoapods {…} // cocoa pods block
    sourceSets {…}
}


Why autocovariance is 0?

Question: First of all I am a newbie in stats, trying to study statistics, and somehow I find 'time series' way more difficult than other topics.
I am confused with the "autocovariance". In the book "Time series analysis and its applications", it says:

Before my question I must admit that I did not know what values of  $w_s$ and $w_t$ shall be chosen, and what I understood from my previous question is that you have to specify a lag: logic of autocovariance in time series
ie: lag 1 is to compare each value with the one right before.
But now I have 2 questions:

Why the author never defines the lag he is using? is he calculating the autocovariance for lag 1,2? or what?
I do not see how the covariance would be 0... If I think of the case for lag 1, in my head I picture potential values like: -0.5,  1, -2, 1, 1.

I see that the autocovariance will be negative (one value goes up, the next one goes down...)
Of course I do know my logic is faulty, the author shall not be wrong, but I want to fully understand it before proceeding to other topics... How come it is 0?
Comment: The lag is $s-t.$  By *fiat* the covariance is zero for nonzero lags.
Comment: If $s=t$ the lag is 0, both $s$ and $t$ is time index so when given that $s=t$ then $cov(w_s,w_t) = cov(w_t,w_t) = var(w_t)$. If they are different $s\not=t$ the lag is different from 0 and hence you are looking at different timeperiods, but a white noise process is per definition one where there is no correlation across time that is where $cov(w_s,w_t) = 0 $ follows from $s \not = t$.
Answer: In the example they refer to white noise time-series, so the "random" one, where there is no correlation by definition, since the values are independent of each other.

Why autocovariance is 0?


Consider the following Matrix, are the conditions satisfied?

Question: I am trying to solve the following questions however i am having little lucky. I have searched online and consulted my textbook however neither are proving to be helpful. These types of questions always seem to come up in exams so i would be grateful for any help! I have attached the link to the questions below, many thanks!
Comment: Have a look [here](https://en.wikipedia.org/wiki/Hawkins%E2%80%93Simon_condition).
Comment: Apologies for the edit, so the 3 principal minors have to be greater than 0?
Comment: Yes that´s true. I´ve posted an answer to make it clearer.
Comment: Thank you so much! Much appreciated!
Comment: I restored the original title. Changing it to "Question solved" won't help anyone searching for help on this topic!
Answer: We have
$$\textbf B=\textbf I-\textbf A=\begin{pmatrix}1&0&0 \\ 0&1&0 \\ 0&0&1 \end{pmatrix}-\begin{pmatrix}0.1&0.5&0.2 \\ 0&0.1&0  \\ 0&0.2&0.2  \end{pmatrix}=\begin{pmatrix}0.9&-0.5&-0.2 \\ 0&0.9&0  \\ 0&-0.2&0.8  \end{pmatrix}$$
Calculating the leading principal minors:
$|\textbf B_1| =|0.9|=0.9>0$
$|\textbf B_2|=\left|\begin{matrix}0.9&-0.5 \\ 0&0.9  \end{matrix}\right|=0.9\cdot 0.9-(0\cdot(-0.5))=0.81>0$
$|\textbf B_3|=\left|\begin{matrix}0.9&-0.5&-0.2 \\ 0&0.9&0  \\ 0&-0.2&0.8   \end{matrix}\right|=...$
If $|\textbf B_1|,|\textbf B_2|,|\textbf B_3| >0$, then the Hawkins–Simon condition is fullfilled.


Buscar e copiar arquivo usando o PowerShell ISE

Question: Para copiar os arquivos imagem png de um disco para outro, usamos:
<code>Copy-Item "D:\" -Filter "*.png" -Destination "F:\Files_PNG" -Recurse -Force
</code>
Copia os arquivos e a estrutura de Diretórios.
Quais parâmetros usar para não copiar os Diretórios e Subdiretórios e apenas os arquivos png?
Answer: Encontrei a solução. Atenção: Se existir arquivos com o mesmo nome, o anterior sera sobrescrito.
<code># Copiaremos os arquivos deste disco
$fonte  = "D:\"

# Colocamos a data e hora nesta variável
$agora   = (Get-Date).ToString('MM_dd_yy_HH_mm_ss')

# Concatenamos o disco de destino com a variável acima para abaixo criarmos o diretório.
$dest    = "$("F:\PNG_")$($agora)"

# Cria o diretorio de destino
New-Item -ItemType Directory $dest -Force

# Atenção aqui.......CUIDADO: se existir arquivos com o mesmo nome;
# o anterior sera sobrescrito.
# Copiamos apenas os arquivos, (repetindo)
# porem se existir arquivos com o mesmo nome; o anterior sera sobrescrito.
Get-ChildItem $fonte -Filter "*.png" -Recurse -file | Copy-Item -Destination $dest -Force
</code>


Neural network training: Early stopping vs. reducing the number of neurons/layers

Question: Assuming we have a regression task (1D-output, values between 0.0 and 1.0) with 100 input dimensions and a classical MLP with one hidden layer.
When given 10000 training examples, a network with, for example, 50 neurons in the hidden layer has around 5000 trainable parameters and might overfit.
To avoid this, two (out of many) options are:

apply early stopping (quit training when the validation loss no longer improves)
reduce the model complexity (for example, only use 8 neurons in the hidden layer, thus having only around 800 trainable parameters).

Assuming training duration and model size are irrelevant, is there a consensus about which method of these two is to be preferred?
Does one method usually produce better results than the other?
Comment: Use regularisation instead of early stopping - it is more controllable.  Reducing model complexity is a bit of a blunt instrument as it can only be reduced in discrete steps (and it is quite difficult in practice to decide exactly when to stop).  The regularisation parameter(s) are on the other hand continuous.  Using a large neural network with regularisation is usually quite effective, but there are no guarantees.
Answer: Of course this decision is a difficult one without having a good understanding of the data, difficulty of the problem, and also the network architechture characteristics (e.g., activation functions) that you are considering. But as a rule of thumb (which might be very bad), you can make a decision about this based the following heuristic.
Perform your early stopping and measure:

Your Training set error rate
Your Development set error rate (do not touch your test set! reason).

Consider the following steps in order of appearance:

If your Training error is high, then you stopped too early. Let it continue for a while.

If the Training error stays high after you continued training, you actually have a high bias. Increase the complexity of your network.

If your Training error is okay and now is close to optimal/bayes (compared to Development error which is still relatively high at the current epoch), it means that your network had enough complexity to reach the "optimum" point but it had too much complexity, as your Development set has not reached that "optimal" point yet. This indicates that you need to reduce the complexity of your network (i.e., reduce #nodes).

If the alternative is true (i.e., Training error ~= Development error at the current epoch), then you are doing fine with complexity, so keep training your model with further epochs.

Note that you are making this decision at a certain epoch. Former or later epochs may present you a different story.
Finally, a no-brainer approach (which could be safer in my opinion) is that you can simply re-run the model training and follow each path (i.e., reducing #node vs. increasing #epoch) and then compare the performances. I think Andrew NG. has a pretty good lecture on this.
Answer: EDIT:
A straight-forward answer from Yoshua Bengio

Page 11 in https://arxiv.org/abs/1206.5533
-> So use more neurons in combination with early stopping
I do not think these two things are equal.
Early stopping just stops you from overtraining, that is you train longer than necessary for a given set of hyperparameters,  which results in a decreased validation loss. You can always use early stopping, independelty of the choice of hyperparameters.
However, reducing the number of neurons is an actual change to the architectures.
Early stopping can help you estimate the best possible validation loss for a given choice of architecture. So you can for example compare Model A to Model B. Early stopping helps you to identify the best loss, and hence the best parameters, for each model. And you now can adequately compare Model A to Model B. But in order find a well-performing model you need to change, hyperparameters that change the optimizer and or the architecture.
We can see also that when we train with 10 neurons as shown in OPs answer, we also get degradation of performance
Comment: You state that early stopping is good for model evaluation. But, if the models are not sufficiently trained (due to early-stopping), how can we fairly evaluate model A vs. B (note that if we continue they might reach a better error)?
Comment: In the best case you set the patience of your early stopping component high enough so that it will not stop the training too early. But you make always the argument, lets say you train for 100 epochs maybe after the 101th epoch you will observe a huge decrease in loss
Answer: As an addition to the answers already given, I conducted a small experiment using the MNIST dataset:

train/val split: 60000/10000
input dimensions: 784
hidden layers: 1
output neurons: 10

The number of neurons in the hidden layer is what I used to adjust the model complexity.
import matplotlib.pyplot as plt

import numpy as np
import tensorflow as tf
import tensorflow_datasets as tfds

def normalize_img(image, label):
    """Normalizes images: `uint8` -> `float32`."""
    return tf.cast(image, tf.float32) / 255., label

(ds_train, ds_test), ds_info = tfds.load(
    "mnist",
    split=["train", "test"],
    shuffle_files=True,
    as_supervised=True,
    with_info=True,
)

# 60000
ds_train = ds_train.map(normalize_img, num_parallel_calls=tf.data.AUTOTUNE)
ds_train = ds_train.cache()
ds_train = ds_train.shuffle(ds_info.splits["train"].num_examples)
ds_train = ds_train.batch(128)
ds_train = ds_train.prefetch(tf.data.AUTOTUNE)

# 10000
ds_test = ds_test.map(normalize_img, num_parallel_calls=tf.data.AUTOTUNE)
ds_test = ds_test.batch(128)
ds_test = ds_test.cache()
ds_test = ds_test.prefetch(tf.data.AUTOTUNE)

for hidden_layer in range(2, 21):
    # https://www.tensorflow.org/datasets/keras_example
    model = tf.keras.models.Sequential([
        tf.keras.layers.Flatten(input_shape=(28, 28)),
        tf.keras.layers.Dense(hidden_layer, activation='elu'),
        tf.keras.layers.Dense(10)
    ])
    model.compile(
        optimizer=tf.keras.optimizers.Adam(0.001),
        loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
        metrics=[tf.keras.metrics.SparseCategoricalAccuracy()],
    )
    model.summary()

    history = model.fit(ds_train, epochs=100, validation_data=ds_test)

    layers = [28 * 28, hidden_layer, 10]
    params = model.count_params()
    val_loss = history.history["val_loss"]
    min_val_loss = min(val_loss)
    min_val_loss_min_ep = np.argmin(val_loss)
    min_val_loss_max_ep = len(val_loss) - np.argmin(val_loss[::-1]) - 1

    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)
    ax.plot(history.epoch, history.history["loss"], label="train")
    ax.plot(history.epoch, history.history["val_loss"], label="val")
    ax.set_title(f"{layers=}; {params=}; {min_val_loss=:8.6};\n{min_val_loss_min_ep=}; {min_val_loss_max_ep=}")
    ax.set_ylim([0, 1.2])
    plt.xlabel("epochs")
    plt.ylabel("loss")
    plt.legend(loc="upper center")
    plt.grid()
    fig.savefig(f"{hidden_layer:02d}.png")

Resulting learning curves: https://imgur.com/a/SskHmNC
Example with 10 hidden neurons (does not need early stopping):

Example with 19 hidden neurons (does need early stopping around epoch 20):

Interpretation: From some number of neurons in the hidden layer upward, we need early stopping to get the best validation loss for these models.
While I was somewhat cheering for the fewer-neurons solution to win, in this experiment, the solutions with more neurons (and early stopping!) performed better, i.e., the best validation loss was significantly lower.
Comment: Beautiful experiment. Thanks. I wonder at what "complexity" level the switch happens. Could you please redo the analyses with increasing number of hidden nodes (i.e., one by one) and simply plot the best error in each configuration?
Comment: @Amin.A Thanks. The code does exactly that, i.e., it iterates over the number of neurons in the hidden layer from 2 to 20. The results of each iteration are [here](https://imgur.com/a/SskHmNC). And `min_val_loss` should be the value you're looking for.
Comment: I do not agree with the interpretation.
1. Usually, you use early stopping to end training when the validation loss does not improve rather than when it gets worse. So in the top experiment, early stopping should have kicked in. https://keras.io/api/callbacks/early_stopping/
2. You do not NEED early stopping, you can just decrease the learning rate for the second experiment.
3. You do not know what happens after 100 epochs, it can still increase its validation loss
I get what you want to say, but I would argue if you found hyper parameters (including the number of epochs) that work well,
Comment: then you do not need early stopping anyways, but early stopping can help you identify the best hyperparameters, like for example, the validation loss of experiments 1 and 2 look the same at the end of the 100 hundred epochs, using early stopping for both however would have resulted in you knowing that more neurons actually perform better.
Comment: @Janosch Thanks. In the experiment, I purposely did not actually implement early stopping to get the full graphs. From the graphs, one can deduce where it would have ended with early stopping being enabled. And I agree, instead of early stopping I can of course also just manually reduce the number of epochs to what gives a good validation loss. One could call this method "manual early stopping". ;-) The graphs end at epoch 100 because I wanted them to not be squeezed too much. It's an approximation for an "infinite" number of training epochs. But yeah, I should have shown more epochs.
Comment: Here are the graphs for 500 epochs ([11 n](https://i.imgur.com/VYY2MCf.png), [19 n](https://i.imgur.com/Chrse3w.png)). They show, that 11 Neurons also need to be stopped early, i.e. not being trained infinitely. However, reducing the number of neurons even further at some point leads to [a situation where more training no longer worsens the validation loss](https://i.imgur.com/gfketYL.png). So qualitatively, I think the conclusion holds, i.e. the results, at least in this experiment, of using more neurons (and stopping early) are better compared to using so few neurons with "infinite" epochs.


Angular [Material] - Injetar componentes dinâmicamente em um template

Question: Tenho dois elementos estáticos no projeto, que nunca vão sumir, somente o conteúdo, esses são o menu do topo e uma sidenav, apartir da rota quero inserir componentes dentro do <mat-sidenav-content></mat-sidenav-content> conforme vou navegando, a principío é simples, mas é de outro componente, então seria inserir componentes dentro do template.

<mat-sidenav-container>
  <mat-sidenav mode="side" opened>
    teste
  </mat-sidenav>
  <mat-sidenav-content>

  </mat-sidenav-content>
</mat-sidenav-container>

<mat-toolbar color="primary">

works

</mat-toolbar>

<app-top-menu></app-top-menu>
<app-sidenav></app-sidenav>

index component

No app.component.html só tenho <router-outlet></router-outlet>, então a ideia é que toda vez que um usuário acessar o app, caia no login e depois carregue essa sidenav e qualquer outro component dentro do mat-sidenav-content
Teoricamente eu faria isso em um component, adicionaria os templates e o conteúdo iria no local correto, porem, ele fica abaixo do sidenav:
Segue imagens:

Component index inserido abaixo do template:

Como deveria ser:
Answer: Para que o <mat-sidenav> funcione corretamente é necessário projetar todo o conteúdo do app dentro da tag <mat-sidenav-content>.
Para colocar um componente dentro do outro utilize a tag <ng-content>. Ela funciona como um slot para que você possa inserir tags/conteúdo dentro do seu componente angular.

<mat-sidenav-container>
  <mat-sidenav mode="side" opened>
    teste
  </mat-sidenav>
  <mat-sidenav-content>

    <ng-content></ng-content>
  </mat-sidenav-content>
</mat-sidenav-container>

Com isso, agora é possível colocar o componente <app-top-menu> dentro do componente <app-sidenav>:

<app-top-menu>
  <app-sidenav></app-sidenav>
</app-top-menu>

Referências:

https://material.angular.io/components/sidenav/overview
https://medium.com/claritydesignsystem/ng-content-the-hidden-docs-96a29d70d11b
Comment: Com alguns ajustes, isso é realmente o que eu queria, o que eu mudei é que  fica isolado acima e o ng-content vai dentro do content da sidenav, com isso, o conteúdo eu coloco dentro da tag da sidenav e funciona perfeitamente, obrigado, você me ajudou a finalizar =D


How to fix when echo link url array in php?

Question: I have a code example:
include 'simple_html_dom.php';
    // convert link url
    function foo($uri) {
        $url = parse_url($uri);
        $paths = explode('/', $url['path']);
        return sprintf("%s://%s/%s", $url['scheme'], 'localhost/test/get_image/images', end($paths));
    }
    $str = '
    ';
    $html = new simple_html_dom();
    $html->load($str);
    // remove all image
    $arr_img = array();
    foreach($html->find('img') as $element) {
        $arr_img[] = $element->src;
    $str_rep = str_replace($element->src, foo($element->src), $str);
    }
    echo $str_rep;

OUTPUT:

Error when can't get link "http://www.somedomain.com/somepic.jpg" not convert to "http://localhost/test/get_image/images/somepic.jpg"
How to fix it ?
Answer: You are assigning something to $str_rep in your foreach-loop, but using the variable outside of it: You process only the last match.
Try something like this instead:
foreach($html->find('img') as $element) {
    $arr_img[] = $element->src;
    $str_rep = str_replace($element->src, foo($element->src), $str);
    echo $str_rep;
}

Comment: result is : test


No delete button for a content reference

Question: I have a custom block type in Drupal 8 where I reference an unlimited amount of content nodes. Now that I want to delete a reference, there's no delete button available or label that mentions any kind of operation at all.

If you look at the "image reference field" there's an operation to delete one image reference after another:

Where can I find this delete option for content references? Simply leaving the field blank and pressing save will raise a validation error.
Answer: To delete a value from your "Content Reference" field, simply leave the textfield of the desired row-to-delete blank (the multi-field widget for autocomplete fields doesn't have a delete button, it infers which rows should be maintained/deleted based on the presence of a value).
You've marked that field as required (notice the red asterisk at the top), so it must contain at least one value for the form to pass validation. If that's undesirable, just visit the manage fields page, edit the field, and remove the required constraint.


Excel's EXP function compared to a series expansion

Question: I am comparing the results of a series expansion of $e^x$ to Excel's $\mathop{EXP}(x)$ function.  Should I expect them to be the same?
Excel's gives $\mathop{EXP}(10) = 22026.4657948067$.  However, the series expansion, to 21 terms is $22031.0549667285$
This is using the series expansion below:
$$e^x=1+\frac{x}{1!}+\frac{x^2}{2!}+\cdots$$
Comment: I've edited your post to take advantage of our math formatting.  If you click "edit," you can see the code that I used.
Answer: Excel's value for $EXP(10)$ is correct to the digits quoted.  You seem to have made a mistake in your "series expansion": a truncation of the series, when $x > 0$, should be less than the true value, and yours is greater.  The correct value of
$\sum_{j=0}^{21} 10^j/j!$ (yes, that's really $22$ terms, not $21$) would be $22011.0549667285$.
Answer: Excel is correct, and your sum of the series expansion is not, presumably because of accumulated numerical error.  The sum of the first 21 terms of the series expansion should be
$$
\sum_{n=0}^{20} \frac{10^n}{n!} \;=\; \frac{29687012153221}{1349932311} \;\approx\; 21991.4820256650.
$$
Note that this is quite far off from the actual value of $e^{10}$.  For numbers as large as $10$, the series for $e^x$ really doesn't converge that quickly.  You would need to use at least 44 terms of the series to get ten decimal places of accuracy.
Comment: Thanks folks, you are both correct.  When corrected my series expansion worked correctly and gave exactly Excel's answer 22026.4657948067 at n=44.


Inferring Position Number, String, and Shifts From Sparse Fingering Notation

Question: I'm attempting to (re)learn some violin music using the composer's desired fingering.  However, my background is not in violin but in fiddle, where fingerings and positions/shifts are rarely written (or required; fiddle style traditionally rarely uses (and music rarely requires) anything but 1st position).
I am having trouble because, while some violin fingerings imply positions on particular strings, the notation is fairly sparse.  In many cases, it is underdetermined: a fingering on one string could alternately be the same fingering on the next string down.
I'm looking for feedback on whether I'm doing this correctly, or rules I may not have learned to help make sense of it.

As an extended example of what I'm dealing with, here are the first two lines of a song.  There are no positions or strings notated in the music, just a few fingerings here and there:

My current thought process goes something like:

The first note is an A3 which, neglecting unlikely subharmonics, can only be played on the G-string.
The A4 that begins measure 6 is notated "2".  I guess that means second finger, 4th position on the D-string?  I suppose it could also be 7th position on the G-string, but that seems less-likely since the next note is an open D (I think; since this is not on a note that can't be played on an open string) and also that's pretty high.  I guess also the 2nd-finger harmonic on the G-string from 4th position would also achieve D4.
Continuing on, the F4 also has a "2", which can't be played from 4th position, so we could shift back to 1st position, which makes sense since we need to hit the A3 again on the G-string right afterward.  I guess this puts the shift in the middle of a slurred passage, but putting it two quavers earlier involves either unnecessary string crossing or a fourth-finger reach, which would be bizarre since we were starting in a position where that isn't necessary.
In measure 7, the G4 also has a "2".  So is there supposed to be a shift from 1st position to 2nd position between the F4 and the G4?  I suppose it should actually be at the beginning of the measure since the passage is slurred?  Though, if we're already shifting, we could shift to the G-string and avoid a string crossing mid-passage.
Though, does a shift make sense?  You could already hit the A4 with your 4th finger.  Albeit (if the shift is to 2nd position) this explains how the "4" in measure 8 can be hit (with a 4th-finger reach).

And so on.  As you can see, I'm having to make all kinds of guesses and assumptions, working from very limited information—and I think I'm doing a bad and inaccurate job of it.
I'm not particularly concerned with this particular piece; what I'm looking for is how to solve these sorts of problems in-general.  All these implied shifts on implied strings—isn't there a better way?  Some rules I'm missing?
Answer: Violin playing uses frequent shifts of hand position.
The most common positions used are 1, 3, and 5. The even numbers are not used so much in normal playing, though your example uses the 2nd position several times. (Is it an exercise in shifting positions, I wonder?)
The fingerings on your example show the notes where there is a shift to a new position. For example the first A can only be played in the first position, but the 2 on the second A shows that note is the third position on the D string. The 2 on F near the end of the bar shows a change back to the first position, and so on for the rest of the piece.
You can play open strings in any position, but (unlike fiddle technique) violin technique often avoids open strings because the sound is different and the note can not be played with vibrato. Hence the open strings are often marked. Without the 0 on the third note (D) this would usually have been played with 2 on the G string, not as an open string.
You seem to be confused about how the positions are numbered - you seem to describing them more like guitar fret positions than violin positions. On the G string, the first finger plays A in the first position, B in the second, C in the third, etc - i.e. the position numbers correspond to the notes of a scale, not semitones. (Of course you can always adjust a finger position by a semitone up or down from its standard position depending on the key of the music, the same as you do in the first position).
Answer: I'll go point to point here based on your thought process (still learning violin, but I've been playing for 13 years so far)
You are correct, this A3 can only be played on the G-string
You actually go to 3rd position with the second finger. Meaning that your first finger hits the G4 on the D-string. You need not shift back down over here, because you can play the open D4 without any fingers. Stay in 3rd position here, and lift your 2nd finger on the A4 to get the open D4.
Yes you got it right, except you shift from 3rd position to 1st position, not from 4th.
The 2 on the G4 means a shift up to 2nd position, but I would go to the G-string here, unless you really want to follow every single fingering of the composer, which is understandable. To be honest, yes, the conductor may have wanted the shift to 2nd position for a reason, but it is a lot more understandable and logical to avoid the  nasty F-G-F string crossing, but at the same time, in order to stay in the 3rd position on the G-string, you must shift back down to 1st position on the previous F4 in measure 6, but cross strings over to 4th finger on the G-string.
You can understand the rest of the piece, your thought process is OK and logical, but just remember to use your better judgement of fingerings as you move your hand up the neck for the shifts. For instance, in measures 10 and 12, I'd actually suggest going to second position (1st finger on B3 on the G-string, and staying there, using your 4th finger to reach the G4)
Sorry if I may have sounded blunt or illogical in some aspects, but that's my thought process here. I think you got the rest of the piece down, but good luck and happy playing!
Answer: The assumption that printed fingerings are of the composer, can be misleading.  Unless you are playing etudes, I would consider printed fingerings as mere helping suggestions.  Good fingerings are of subjective nature and you should use fingerings suiting your style and skills unless you are trying to learn from etudes.
The only cases when fingerings could be the composer's wish, are in etudes or where open strings or harmonics are printed or where only the string name is specified.


IP address precise location

Question: Looking for a way to get precise location of an IP address, including those
owned by big corps. For instance, the address 18.104.22.168 is owned by Google and
most Geo-IP tools show Mountain view, but I don't think that is the case - this is the first
IP address that you see after you get out of Spain while accessing a youtube video (I'm running traceroute from Barcelona).
Any ideas?
Comment: Hmmm. I see. Thanks for the replies. My basic problem is to see where is the nearest CDN node that Youtube uses. One can traceroute to the address given in the youtube video link, but that leads to the Mountainview address. Clearly, not right.
Answer: Yeah, give up on unrealistic ideas. YOu dont know because noone knows. And the data can change (dynamic ip addresses asigned tio dial i ncustomers - where do THEY reside?).
Only google knows how their internal network is exactly steructured. What you see is the registered address for the block.
Comment: Additionally, it could be a risk to expose that much detail of the internal network to everyone. Google doesn't gain anything by detailing their network to the public, but could stand to lose privacy/security/etc. Some websites are tagged with the ICBM meta, that's the best you'll get, and there's still no guarantees of accuracy.
Answer: As TomTom says, there are no reliable methods for doing geolocation by IP address, because IP addresses fundamentally don't map to physical locations.
For an individual user/small business at an ISP, the best you can hope for is to get their area by location of the nearest "point of presence" for their ISP, which will probably mean the local exchange for most cable/ADSL customers.
For businesses, the best you can hope for is to get the location of (one of) their gateways to the internet, which might or might not have anything to do with the location of the person sitting tapping away on their keyboard interacting with your site.

IP address precise location


A largura do meu site não está igual, header é menor que o resto. Como resolver?

Question: A largura do meu site não está a mesma como pode-se ver abaixo:

O header (barra de logo, navegação e imagem principal) está menor que o conteiner do site, estou usando Bootstrap. O CSS com as medidas está assim:

    @media (min-width: 1200px) {
    .container{
        max-width: 790px;
    }
}

@media (min-width: 992px) {
    .container{
        max-width: 790px;
    }
}

body {
    margin-top: 10px;
    font-family: Verdana;
    font-size: 12px;
    color: #727E55;
}

.container, .container-fluid {
    background-color: #fff;
}

.row {
    margin-bottom: 3px;
}

[class*="col-"], header, .row-nav, .img-rolante, footer, div[role="main"] {
    margin-top: 0;
    padding-top: 3px;
    padding-bottom: 3px;
    padding-left: 3px;
    padding-right: 3px;
    background-color: #f5f5f5;
    background-color: rgba(86,61,124,.15);
    border: 1px solid #ddd;
    border: 1px solid rgba(86,61,124,.2);
    /*text-align: center;*/
}

div[role="main"], footer {
    background-color: #fff;
    height: auto;
}

HTML

<!DOCTYPE html>

    <title>Lorem Ipsum</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link href="css/bootstrap.min.css" type="text/css" rel="stylesheet">

    <link href="css/contato.css" type="text/css" rel="stylesheet">
    <link href="css/geral.css" type="text/css" rel="stylesheet">

                LoremIpsum.Com

                        CASAS

São Paulo

Rio de Janeiro

Minas Gerais

                        CHÁCARAS

São Paulo

Rio de Janeiro

Minas Gerais

                        SÍTIOS

São Paulo

Rio de Janeiro

Minas Gerais

                        FAZENDAS

São Paulo

Rio de Janeiro

Minas Gerais

                        POUSADAS

São Paulo

Rio de Janeiro

Minas Gerais

                        TERRENOS

São Paulo

Rio de Janeiro

Minas Gerais

CONTATO

            <marquee scrollamount=2
       behavior=alternate direction="right">

            </marquee>

Contato

   TERMOS DE USO Web Design & Development by LoremIpsum.Com © 2003 | All
      rights reserved | CRECI SP XXXXX
      - CRECI MG XXXXX

 Encontre seu Imóvel na LoremIpsum.Com

                CASAS A VENDA |
                CHÁCARAS A VENDA |
                SÍTIOS A VENDA |
                FAZENDAS A VENDA |
                POUSADAS A VENDA |
                TERRENOS A VENDA

CLIQUE AQUI e Cadastre seu Imóvel a Venda conosco

Não sei como arrumar, para que o header tenha a mesma largura que o resto do layout.
PS.: as bordas e background mais escuro é para melhor visualização minha quanto a margin e padding. Estou usando html5, css3 e bootstrap.
Comment: Seria interessante colocar o html para o pessoal visualizar, pois assim fica um pouco complicado de dizer algo.
Comment: tente colocar por percentagens %
Comment: Mande o html que te ajudamos
Comment: Coloquei! @marciano.andrade
Comment: Coloquei @carlinhos-de-sousa-jr
Answer: Para resolver seu problema eu adicionei uma div com a class="row" ao redor do header.
Ficando assim:

Eu fiz isso pois notei que as divs abaixo desta estavam dentro de uma row, mas o header não estava.
Neste link você pode ver como ficou: https://jsfiddle.net/7m447ymn/
Obs: Caso não queira as margens você pode retirar a class row de todas as divs e criar algo seu personalizado.
Comment: Nossa, MUITO obrigada! Estava há dois dias tentando arrumar isso e não conseguia!  Ficou certinho agora.


RandomForestRegressor Example Not Working

Question: I'm trying to work through a RandomForestRegressor example.  I'm using Python, JupyterLab and sklearn.
I've copied code from https://stackabuse.com/random-forest-algorithm-with-python-and-scikit-learn/
Code is:
import pandas as pd

import numpy as np

from sklearn.model_selection import train_test_split

from sklearn.ensemble import RandomForestRegressor

# csv from web site above
dataset = pd.read_csv("d:\maternal_health_risk.csv")

y = dataset['BS']
X = dataset.drop(['BS'], axis=1) # You can either include risk level or drop it here

SEED = 42
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=SEED)
rfr = RandomForestRegressor(n_estimators=20, max_depth=3, random_state=SEED)

X_train, y_train
rfr.fit(X_train, y_train)

I'm getting an error message from the above that states:
raise ValueError("sparse multilabel-indicator for y is not supported.")
I've looked at y_train object.  Its a Series object with type float64 values.
Not sure what error message means or how to fix.  Thanks.
Comment: The full traceback would be useful to include; please [edit] to provide more details.
Answer: Figured out answer to my question.  RandomForestRegressor expects pandas and series inputs to contain only numbers.  I need to drop any columns containing text or replace the text with numbers. In this case the following additional line resolved the issue:
dataset['RiskLevel'] = dataset['RiskLevel'].replace('low risk', 0).replace('mid risk', 1).replace('high risk', 2)


Find the supremum and infimum

Question: I have a set $E = \{x: x^2-x-1 < 0 \}$ for which I need to find the infimum and supremum (and minimum and maximum if exists). I'm not sure how to do it but after some calculation I cam up with $Inf(E) = - \infty \ Sup(E) = \frac{1}{2}$, and there is no minimum nor maximum.
Comment: Hint: What does the graph of $x^2-x-1$ look like?
Comment: If you don't show your thought process, nobody can read your mind to figure out why you got the wrong answer.
Comment: Before worrying about $\sup$ and $\inf$, you should try to figure out exactly what $E$ _is_. What do you think $E$ is, and why do you think that is?
Answer:
$$x^2-x-1 = (x-\frac{1+\sqrt{5}}{2})(x-\frac{1-\sqrt{5}}{2}) < 0$$
=> $$x \in   (\frac{1-\sqrt5}{2},\frac{1+\sqrt5}{2})$$
Therefore E  = $(\frac{1-\sqrt5}{2},\frac{1+\sqrt5}{2})$
It's clear that $ \sup E = \frac{1+\sqrt5}{2}$, $\inf E = \frac{1-\sqrt5}{2}$
EDIT: What may obfuscate you is that the supremum is not the x value where f(x) gets maximum. It is the x value in the set E which gives the set a upper boundary.
Answer: HINT
Solving the inequation $x^2 -x -1 \lt 0$ we get $x \in (\frac {1-\sqrt5}2,\frac {1+\sqrt5}2)$

Find the supremum and infimum


Problemas com threads em C++

Question: Olá, eu estou a usar o mingw, versão 32-bits no windows 7 Ultimate e estou com problemas a utilizar threads.
Eu sei que não funcionam para esta versão do mingw, razão pela qual uso a versão neste link. Mas eu não compila este exemplo, porque diz que

In static member function 'static unsigned int mingw_stdthread::thread::_hardware_concurrency_helper()':
  error: '::GetNativeSystemInfo' has not been declared (in line 266)

Isto no ficheiro thread que fiz download, testei neste site e funcionou este exemplo, alguém me poderia dizer o porquê de isto acontecer?
<code>#include <iostream>         // std::cout
#include <thread>           // std::thread

class test {
public:
    static void foo(){}
    static void bar(int x){}
    test(){
         std::thread first (foo);     // spawn new thread that calls foo()
         std::thread second (bar,0);  // spawn new thread that calls bar(0)
         first.join();                // pauses until first finishes
         second.join();               // pauses until second finishes
    }
};

int main() {
     test TESTE;
     return 0;
}
</code>
Comment: herm.. E qual o problema?
Comment: @Kahler editei o post.
Comment: Quais foram as flags/bandeiras que você passou pro mingw?
Comment: [Problema parecido](https://stackoverflow.com/questions/28036686/use-pthreads-in-mingw-in-win7).
Comment: @MárioFeroldi Eu não passei nenhuma flag e já tentei com a tag -pthread, sem sucesso, e já tinha encontrado esse post quando andei á procura da resposta.
Comment: @Simplecoder eu ajustei o link que você forneceu para conter o seu código exemplo (vai aparecer quando algum editor aprovar).
Answer: Existem muitas distribuições diferentes do Mingw, algumas não suportam threads diretamente e requerem inclusão de código específico da plataforma. A página que você postou contém esses pedaços de código, embora o autor declare que só testou para o MinGW-w64 5.3.0, e avisa que os macros para detecção de plataforma podem ter de ser ajustados manualmente para algumas versões do Windows.
O erro que você postou é relacionado com uma declaração faltante, você incluiu a biblioteca requerida de acordo com as instruções?

This is a header-only library. To use, just include the corresponding mingw.xxx.h file, where xxx would be the name of the standard header that you would normally include.

Talvez você precise declarar, no código em sua plataforma:
<code>#include mingw.thread.h
#include <thread>
</code>
Caso não seja esse o problema, e você esteja disposto e apto a usar outra distribuição para Windows, que já contenha threads embutidos (recomendo), aqui estão algumas opções abertas:

TDM GCC, vem com a versão GCC 5.1.0 (muito fácil de instalar e usar)
Mingw-w64, vem com o GCC 7.3
Comment: Continua a não funcionar, diz _fatal error: mingw.thread.h: No such file or directory_.
Comment: Bem, se você traduzir esse erro para o português: "mingw.thread.h: Arquivo ou diretório inexistente", o que quer dizer que você não adicionou os arquivos durante a sua compilação, ou forneceu caminho errado...

Problemas com threads em C++


What difficulty will I face if I use same elasticsearch instance for dev and prod

Question: I am planning to use same elasticsearch instance for dev/qa and prod env.
Using snapshot and aliasing I can achieve this.

But I am not aware about the side effects of doing this.

Simultaneously I have budget constrain and my elasticsearch is deplyed on AWS.

Also, can anyone suggest any better solution.
Answer: Just a few thoughts:
If you decide to run load testing on your QA index, your clients using the PROD index will suffer.
If you need to venture into configuration tuning (and you will), you'll have to restart your cluster for changes to take effect, that will also disrupt PROD.
Those are the two big NO-NO for having all your environments in the same cluster. If budget is a constraint, you can definitely have dev + QA in the same cluster, but the PROD one should be standalone for obvious reasons.


Bernoulli infinite product measures singular if $p \not = q$.

Question: I am going through Achim Klenke's Probability Theory textbook. In Section 7.4, he discusses what it means for two measures to be singular to one another and gives the following example.
Let $\Omega = \{0, 1\}^\mathbb{N}$ and let $(\mathrm{Ber}_p)^{\otimes \mathbb{N}}$ and $(\mathrm{Ber}_q)^{\otimes \mathbb{N}}$ be the infinite product measures with parameters $p$ and $q$, respectively. For $n \in \mathbb{N}$, let $X_n$ be the $n$-th coordinate map. Then under $(\mathrm{Ber}_r)^{\otimes \mathbb{N}}$, $(X_n)_{n \in \mathbb{N}}$ is independent and Bernoulli distributed with parameter $r$.
Here is the step where I get confused:
Klenke states that one can apply the strong law of large numbers such that for any $r \in \{p, q\}$, there exists a measurable set $A_r \subset \Omega$ with $(\mathrm{Ber}_r)^{\otimes \mathbb{N}}(\Omega \backslash A_r) = 0$ and $\lim_{n \to \infty} n^{-1} \sum_1^n X_i(\omega) = r$ for all $\omega \in A_r$ and therefore in particular $A_p \cap A_q = \emptyset$ if $p \not = q$, and thus $(\mathrm{Ber}_p)^{\otimes \mathbb{N}}$ and $(\mathrm{Ber}_q)^{\otimes \mathbb{N}}$ are singular in that case.
Now I am completely confused by the last paragraph. First off, what guarantees the existence of such a measurable set $A_r$? Then, how does it particular follow that $A_p \cap A_q = \emptyset$ if $p \not = q$? And finally, how does the last imply singularity of the two measures? A nice and clear explanation would be greatly appreciated, thanks!
Answer: Consider the sequence space under the measure $P_r = \text{Ber}(r)^{\otimes \mathbb{N}}$. By the strong law of large numbers, $$P_r(\limsup_{n \to \infty}\frac{X_1 + \dots + X_n}{n} = r) = 1.$$
So $A_r = \{\limsup_{n \to \infty}\frac{X_1 + \dots + X_n}{n} = r\}$ is the set Klenke is talking about. The above shows that $P_r$ assigns mass $1$ to $A_r$. Clearly if $p \neq q$ then $A_p \cap A_q = \emptyset$ because $\limsup_{n \to \infty}\frac{X_1 + \dots + X_n}{n}$ cannot simultaneously equal $p$ and $q$.
Answer: I'm also not sure what the problem is, so I'll argue why there is no problem.
Consider $\{0,1\}^{\mathbb N}$ equipped with the Borel algebra induced by the discrete topology (which is the power set of $\{0,1\}^{\mathbb N}$, cf. this discussion to see why it doesn't matter which product algebra we take, be it induced by projections or rectangles).
For an integer $n>0$ let $a_{n}:\{0,1\}^{\mathbb N}\rightarrow\mathbb R$, $x\mapsto n^{-1}\sum_{m=1}^{n}x_m$, where $\mathbb R$ is equipped with the canonical Borel algebra. Notice that $a_{n}$ is measurable since it is continuous (which is trivial for the discrete topology).
So, for $\bar a\in\mathbb R$ and an integer $k>0$ the set
$$E_{n,k}(\bar a)=\{x\in\{0,1\}^{\mathbb N}:|a_{n}(x)-\bar a|\le 1/k\}\subseteq\{0,1\}^{\mathbb N}$$
is measurable, since this is the preimage of the measurable set $[\bar a-1/k,\bar a+1/k]$ under a measurable function. But then the set $E(\bar a)=\cap_{k>0}\cup_{n_0>0}\cap_{n\ge n_0}E_{n,k}(\bar a)$ is measurable, and we have
$$E(\bar a)=\{x:\forall k\exists n_0\forall n\ge n_0\,|a_{n}(x)-\bar a|\le 1/k\}=\{x:\lim_{n\rightarrow\infty}a_{n}(x)=\bar a\}.$$
Now, the strong law of large numbers (is well-defined and) yields $\mathbb P_r(E(r))=1$, where $\mathbb P_r=\mathrm{Ber}_r^{\otimes\mathbb N}$. And since the limit is unique (by definition of the limit) if it exists, we have $\bigcup_{s\in\mathbb R\setminus\{r\}}E(s)\subseteq \{0,1\}^{\mathbb N}\setminus E(r)$. In particular, we have $\mathbb P_p(E(p))=1\neq 0=\mathbb P_q(E(p))$, so $\mathbb P_p$ and $\mathbb P_q$ are singular (notice that the definition on Wikipedia can be reduced to the existence of an event $A$ such that $\mu(A)=1$, $\nu(A)=0$ since we consider non-negative normalized measures).
I'm fairly confident that this discussion is reasonable. Thus, the underlying $\sigma$-algebra in Klenke's book was overly restrictive (I doubt that), or the wording was intended to be suggestive (e.g. to point towards a definition, result or the likes), but if so, I still didn't get the message.


javax.net.ssl.SSLHandshakeException apenas no Glassfis 4

Question: Fiz uma rotina para pagamentos online na Cielo, JSF , os testes que fiz com Tomcat 9, com Windows 10 rodaram 100%, porem quando coloquei em produção no Glassfish 4, o sistema ao redirecionar para a pagina da Cielo vem com esse erro.
javax.net.ssl.SSLHandshakeException:
  sun.security.validator.ValidatorException:
    PKIX path building failed:
      sun.security.provider.certpath.SunCertPathBuilderException:
        unable to find valid certification path to requested target.

Acredito que não seja o código e sim alguma configuração de certificado do SO(Open Suse) ou Glassfish.
Comment: você colocou o certificado ssl no servidor?
Comment: Não, o sistema não tem certificado SSl. Ou você fala do SSl do site que vou acessar?
Comment: Esse erro que você está recebendo, é que essa sua biblioteca não encontrou o certificação no seu servidor. muito provavelmente o diretório que está na sua maquina de desenvolvimento é diferente do servidor, ou senão nem existe o arquivo no ser servidor ainda.
Answer: Bom, eu coloquei a aplicação para ignorar o SSL, chamando essa função antes do POST.
Uteis.ignorarSSL();
WebResource webResource = client.resource(url);

public static void ignorarSSL() throws Exception{
    //Cria um gerenciador de confiança que não valide cadeias de certificados
    TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager(){
        public X509Certificate[] getAcceptedIssuers(){return null;}
        public void checkClientTrusted(X509Certificate[] certs, String authType){}
        public void checkServerTrusted(X509Certificate[] certs, String authType){}
    }};

    //Instala o gerenciador de confiança
    try {
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
        ;
    }

}

Answer: Para que a VM que seu processo/servidor/aplicação Java roda se conecte com QUALQUER host https, o certificado daquele host precisa estar presente na keystore da mesma. Como você citou glassfish, estou colocando um link com o passo a passo.
Apenas reforçando, este não é problema de SO, isso é um passo já conhecido e deverá sempre ser feito em qualquer servidor (apena varia o passo a passo).
Comment: certo, vou tentar, mas com Tomcat não foi necessário.
Comment: ainda continua com erro, mesmo adicionando o certificado no cacerts.


Quarter circle arc

Question:
These are congruent sectors (aka quarter circle) with the arc of the lower circle bisects the radius of the upper circle and the radii are parallel. My question is: Is the overlapped part a quarter circle?
My opinion: The arc of the overlapped segment belongs to the circle with point$A$ so it is not a sector
Comment: Your thought is correct
Comment: Curvature of a circle depends on its radius.
Answer: If the intersection of the two quarter circles was a circular sector, let alone a quarter circle, the angle between the straight lines and the arc would be $90^\circ$. It is rather obvious from the diagram that that angle is less than $90^\circ$. So the intersection is not a quarter circle.

Quarter circle arc


How to get a jQuery item in a collection of selectors

Question: I would like to access a selector in my array:

A

B

C

var $elems = $('li.elem');
console.log($elems[1].text()); /* jQuery method call */

I know there is the get() method, but it seems to be an implementation to se [] operator.
So what is the best way to access an item on a jQuery array?
Should we do something like $($elems[1]).text() ?
Comment: http://api.jquery.com/eq/
Comment: @elclanrs thanks it's the method i was looking for, maybe you could reply as an answer so i could valide it. Thanks again!
Comment: Look you select with `elams` but you gave class 'elam' to `li` elements
Answer: Use method for get text .eq
$('li.elem').eq(1).text();

Answer: You can simply do this using the eq() method:
var $elems = $('li.elems');
console.log($elem.eq(0).text());

Since, eq() is zero based index, so eq(0) will give you the first li in the collection.
Answer: You can use eq()
$(document).ready(function(){
  var $elems = $('li.elems');
  console.log( $elems.eq(1).text() );
});

You should note that get() returns a DOM element while eq() returns a jQuery object.
Answer: You could try followings ways
// jQuery Method call
console.log( $($elems[1] ).text() );
console.log( $elems.filter(':eq(1)').text() );
console.log( $elems.eq(1).text() );

//native method
console.log( $elems[1].innerHTML );

All prints same results


Min cost with dynamic programming in java

Question: I'm working on a project where I have to find the min cost with dynamic programming. We have an array A[n*m] filled. Also we have another array b[n*m]. We have to fill another c(n*m)array that c(i,j)filled with the minimum of
for (i=1 to m)
  a[i,j]+B[j,k]+c[i-1,k]

for example we have this arrays.
This is my code:
for (int t = 1; t < n; t++) {
 for (int y = 0; y < m; y++) {
  int min = 9999555;
  for (int k = 0; k < m; k++) {
   if ((a[t][y] + b[y][k]) < min) {
    min= a[t][y] + b[y][k] + c[t - 1][k];
    }
   }c[t][y] += min;
  }
 }
 for (int u = 0; u < n; u++) {
        for (int z = 0; z < m; z++) {
            System.out.print(c[u][z]+" ");
        }
        System.out.println();
    }

The first column of c should be the same with first of column of a.
for example:
c[2,1] ismin{A[2,1]+c[1,1]+b[1,1], A[2,1]+C[1,2]+B[2,1],A[2,1]+c[1,3]+b[3,1]}
I want to ask you if my code is correct method of dynamic programming.
Comment: the question itself has no relation to dynamic programming because you haven't defined the problem statement which (according to your words) is aimed to be solved by means of dyn.programming. We only see that you are trying to fill array C by means of arrays A and B
Comment: The plot of the problem is:We have N steps(processes) and M types of Virtual Machines VMs. The array A has the cost to run 1 process in a type of VM. The second array B M*M has the cost to run a process from a type of VM to another. In the example that I wrote, we have 4 processes and 3 types of VMs.First VM run the 4 processes with cost 5 7 7 and 2. Also communicate with the other types of VM with cost 7 and 2.
Comment: please define more clearly the meaning of A [i,j], B [i,j] and C [i,j]. A[i,j] = the cost of running process i on VM j. C[i,j] = the cost of running processes 0..i on VMs 0..j (correct?) B [i,j]=?
Comment: A[i,j] = the cost of running process i on VM j.C[i,j] = the cost of running processes 0..i on VMs 0..j  that caused from the sum of c[i-1,j] + the cost  of the process a[i,j] + the cost to run on the same virtual machine or the cost to send data to another VM (b[j,k]
Answer: Let's state things clearly:
A[i,j] is the cost of running process i on VM j
State C[i,j] implies the minimal cost of running processes "0..i" on VMs "0..j"
Let's assume for now, that there is no B cost array.
The goal is state C[n,m] which is the minimal cost of running processes "0..n" on VMs "0..m".
We may reach state C[i,j] from:

state C[i-1,j] which means that VMs "0..j" will run additional process "i" and taking into account the costs of running process "i" on VMs "0..j" that's sum(a[i,k]) where k=0..j
Hence the cost is C[i-1, j] + sum(a[i,k]) where k=0..j
state C[i, j-1] which means that processes "0..j" will be running on one more VM "j" (so total "0..j") and taking into account the costs of running processes "0..i" on VM "j" that's sum(a[k,j]) where k=0..i
Hence the cost is C[i, j-1] + sum(a[k,j]) where k=0..i

By taking minimum of these two values we find C[i,j]
Do you agree so far?
UPDATE.
Assuming that process and VM numbering starts from 0:
base case:
for(int j=0; j < m; j++)
     c[ 0 ][ j ] = a[ 0 ][ j ];

DP loop:
for (int i = 1; i < n; i++)
{
 for (int j = 0; j < m; j++)
 {
     int min = Integer.MAX_INT;
     for (int k = 0; k < m; k++)
      {
        if ((a[ i ][ j ] + b[ k ][ j ] + c[ i-1 ][ k ]) < min)

             min= a[ i ][ j ] + b[ k ][ j ] + c[ i-1 ][ k ];

      }//try every VM

     c[ i ][ j ] = min;

  }//for every VM
}//for every process

Comment: @George now could you explain the purpose of B [i,j] a bit clearer? because i couldn't understand that point yet. I will add the needed conditions to my answer above
Comment: I tried to explain the solution in paper. [link](https://imgur.com/a/lk6HFWA)   Min(12,20,12) is 12 . Min(18,14,13) is 13 and Min(12,13,8) is 8.
Comment: @George, check the updated answer above. I didn't fully get what is the goal, but according to your draft in the link you provided (seems that it is different from what I was talking in the previous posts), the base case and the loop should look the way I posted
Comment: and according to the recursive step you provided, the first row (not column) should be the same for A and C.
Comment: the first row is i=0 (process 0) and it is the very first process so there is no VM change prior to it, so c[0][j]=a[0][j] for any VM
Comment: I think your opinion is correct, but my problem is that for large input with 50 processes and 20 VMs  I have wrong results.
Comment: The file with 50 processes is [] (https://expirebox.com/download/2442c0362478dbaa11441c604366eae9.html) , my results is https://expirebox.com/download/f6f3a8ffe9b65b5250d59f0e5185d13f.html and the correct results must be like this https://expirebox.com/download/df1404d55473e545d18f9fa50bc6eaef.html
Comment: @George could you share your project statement (some link or text file) ? Probably you derived an incorrect recursive relation
Comment: @George B[ i ][ j ] is the cost of transfering from VM i to VM j or from VM j to VM i ? Because you're using B [ j ][ k ] instead of B [ k ][ j ], probably you need to use B [ k ][ j ]
Comment: Thank you very much mangusta. That's my mistake. I use B[k][j] and it works fine .
Answer: Visits to Cloud Work with Dynamic Programmers Companies are providing computing cloud computing like i Amazon, they are all about virtual man (VMs, virtual machines) which, in their turn, give them to the others Appropriate remuneration for the total use time. There are many sketches in the process with different each one, for example, one virtual machine A may be superior another virtual machine cost B to carry out the process use more of the CPU, while the B is superior to A in the processes that run the dsc. There may also be a more expensive C system that outperforms both A and B in the performance (but it is more expensive). The prediction of the design of the virtual machine is many financial resources. This problem is addressed to the specific work. We have an in-depth process consisting of N experiments in the form of chains: Δ1 → Δ2 → Δ3 → ..... → ΔΝ. The results show that the results of Δ1 pass as inputs to Δ2, those of Δ2 to Δ3, and so on. We also have M virtual pictorial facilities. As an entry, we also have 2 tables. The man is NXM and causes the total cost to run a transaction in one type of virtual machine. The dignitaries table is MXM and it pays the cost to send the data to another. An example input is the following: In the specific example, the embedded process has 4 scenarios and 3 VM patterns are available. The first performs the 4 routines with a cost of 5, 7, 7 and 2 respectively. It also communicates with the other two types of technicians with a cost of 7 and 2. Algorithm of Dynamic Programming to be implemented : an Algorithm to be filled table Costs NXM, where each Cost cell (i, j) shows the lowest overall cost of the process until i live when i live on the j j. In order to execute life on the move, it either goes the results of the i-1 be found to be either transferable to or from other communities taking into account the cost of communication. In the above example this table has the equivalence, which in practice means that less expensive extinction is 15 and is achieved when the last operation is a virtual machine:


MessageBird sms not sending (php)

Question: I have been trying to send SMS messages with PHP using MessageBird. Currently I'm getting no error messages but I'm not receiving the messages on my phone, but I can see my free SMS credits being deducted.

<?php

    require('header.php');
    require 'php-rest-api-master/autoload.php';

    $client = new \MessageBird\Client('YOUR_ACCESS_KEY'); // Access key goes here

    $message = new \MessageBird\Objects\Message();
    $message->originator = 'Test';
    $message->recipients = ['YOUR_PHONE_NUMBER'];
    $message->body = 'Hello, your meeting request has been processed';

    try{
        $response = $client->messages->create($message);
    } catch (Exception $e){
        echo $e->getMessage();
    }

    require('footer.php');

?>

I was wondering if there was anything I was missing?
Answer: One option for debugging would be to check the SMS logs in the Dashboard.
https://developers.messagebird.com/quickstarts/sms/troubleshooting/

MessageBird sms not sending (php)