How do I limit the number of total appended elements to a div?

Question: I have two buttons that add two different images to  a div respectively. I have been able to limit their individual appends four. So I can add four of each image (eight total). However, I want to limit the total amount of images to six. For example, if I added four of "image1", I could only add 2 of "image2".

<button id ="addbiscuit" >add biscuit</button>

<button id ="addcement" >add cement</button>

 SAMPLE BOX

Comment: Why not just counting the total amount of [children](https://api.jquery.com/children/)?
Answer: You are close. First - don't use 2 document ready functions and make the variable available for both click methods (which will be the case if you are inside the same ready function body) - this should do it.
$(document).ready(function () {
    var maxAppend = 6: // your total value
    var currAppended = 0; // currently added

    $("#addcement").click(function () {
        var $imageElement = $("

<input type='image' src='Images/sample_thumbs/61_cement_smallglass.jpg' width='5%' name='closeStory' class='closebtn' width='22px'>

");
        if (currAppended >= maxAppend) return; // if added >= max return
        $("#samplebox").append($imageElement);
        currAppended++; // increase the variable
        $("i").append(addinput);
    });

    $("#addbiscuit").click(function () {
        var $imageElement = $("

<input type='image' src='Images/sample_thumbs/102_biscuit.jpg' width='5%' name='closeStory' class='closebtn' width='22px'>

");
        if (currAppended >= maxAppend) return; // same here
        $("#samplebox").append($imageElement);
        currAppended++; // increase the variable
        $("i").append(addinput);
    });

    $("#samplebox").on('click', '.close_bisq_btn', function(){
        $(this).closest('.biscuit').remove();
        currAppended++; // decrease the variable
    });

    $("#samplebox").on('click', '.closebtn', function(){
        $(this).closest('.cement').remove();
        currAppended--; // decrease the variable
    })
});

Answer:

    <button id ="addbiscuit" >add biscuit</button>

    <button id ="addcement" >add cement</button>

 SAMPLE BOX

Comment: This works. I lost my ability to only add "4" of each individually, but this will do. Thanks !


Javascript, buttons, and nested divs

Question: 3 div's nested as shown below:

servicesContainer

service-type

service

The servicesContainer div has a button to add a new service-type to the servicesContainer
The service-type div has a button to add a new service to that service-type
The javascript to add a new service-type to the servicesContainer works correctly, however the javascript to add a new service to the service-type does not, and just adds a new service to the first service-type.
Below is a link to what I currently have, I feel like I'm close, but just missing something obvious.
http://jsfiddle.net/gHbss/324/
function AddService ()
{
    var serviceDiv = document.createElement ("div");
    serviceDiv.setAttribute("id", "service");

    var serviceHTML = '

11	12	13

21	22	23

31	32	33

';

    serviceDiv.innerHTML = serviceHTML;

    var container = document.getElementById("service-type");
    container.appendChild(serviceDiv);
}

Thank you in advance!
Comment: Dont use the same `id` every time you create a new ``. Think about using a datastructure to hold your services and types.
Answer: Your service type ids are not unique enough. When you append the HTML it will look for the first instance of the service-type id.
Easiest option would be to give it a number as well (i.e. id="service-type1"). Then when you add the service it will have to check which "number" it is nested under to append to that div.
Comment: I'd rather not change the id's if I can help it because then I'd have to change the overwhelming majority of my code in rails.
Answer: When you click on 'Add Service Type', you are creating a new div with same id (service-type). An id should always be unique. JS will always capture the first element with id='service-type' and append 'service' to it. You should create a new div with different ids and then on clicking 'Add Service' find the id of the container containing that button. Once that is done, you can add new 'Service' in that container.
Also, id should always be unique
Answer: Demo
I changed your addService function to take an element.  I changed the onclick of your buttons to pass this.  In the addService, I then find the appropriate parentNode of the object passed in instead of searching for document.getElementById("service-type");
So, your '+ Service' button should now read:
<button onclick="AddService(this)">+ Service</button>

And your addService function should now read:
function AddService (el)
{
    var serviceDiv = document.createElement ("div");
    serviceDiv.setAttribute("id", "service");

    var serviceHTML = '

11	12	13

21	22	23

31	32	33

';

    serviceDiv.innerHTML = serviceHTML;
    el.parentNode.parentNode.appendChild(serviceDiv);
}

EDIT: Based on your comment, I made an updated Demo.
The code change looks like so:
function AddService(el) {
    var ParEls = el.parentNode.parentNode.childNodes;
    var serviceDiv;
    for (var i = 0; i < ParEls.length; i++) {
        if (ParEls[i].id == "service") {
            serviceDiv = ParEls[i];
        }
    }
    var serviceHTML = serviceDiv.innerHTML;
    serviceHTML += '

11	12	13

21	22	23

31	32	33

';
    serviceDiv.innerHTML = serviceHTML;
    el.parentNode.parentNode.appendChild(serviceDiv);
}

Comment: You know that feeling when you feel like an idiot because you've been banging your head against a wall for an hour when the solution was way easier than you thought it was going to be? That's me right now! You, sir, deserve a cookie.
Comment: Gotta love when requirements change. Instead of creating a new service div, now I have to append the new table to the existing one, and I can't figure out how to go about that. Is there a way to search for a specific element in the current node?
Comment: @George, yes, you can use `.childNodes` to get the children of an element.  After that, you can iterate through checking for the id `service`.  After which you would want to save and append to it's current HTML.

Javascript, buttons, and nested divs


Como adicionar métodos à uma classe nativa?

Question: Como adicionar funções em uma classe nativa do C#, no meu caso, tentei fazer em System.Math só como teste:
public class Math
{
    public static double test(double a)
    {
        return a;
    }
}

E chamá-lo assim:
Math.test(10);

Mas não obtive o resultado esperado. Como seria possível adicionar o método nesta classe?
Comment: Você chamou `Math.test(10)` simplesmente ? Colocou o resultado em uma variável ? Ou salvou em um arquivo de log ou exibiu no console/trace ?
O que você fez com o resultado ? Gerou algum erro do compilador ? Gerou alguma exceção em runtime ? Veja um exemplo que acabei de fazer baseado no seu: http://rextester.com/YZX58485
Tem 2 métodos, Dobro e Metade, como o nome já sugere, o Dobro multiplica o valor por 2 e o Metade divide por 2, funcionaram perfeitamente...
Answer: Isto não é possível hoje, e tem pouca vantagem fazer isto. Crie uma nova classe e boa.
public class MathExt {
    public static double test(double a) => a;
}

MathExt.test(10);

Coloquei no GitHub para referência futura.
Está em estudos permitir extension everything, e aí poderá existir métodos de extensão estáticos, em tese poderia ser em classes estáticas.
Comment: Vou reforçar que não tem como estender uma classes estática, como quer saber a pergunta. A resposta aceita está estendendo a classe `Float32` e não `Math`, como está na pergunta. Eu fico com minha resposta, porque ela responde ao que foi perguntado. Se o desejo era perguntar outras coisa, deveria ter sido perguntado, por isso fechei a pergunta, a intenção era uma, mas o texto era outro.
Comment: Ok, percebi que sua resposta realmente era a mais correta e a que mais condizia com o que eu realmente queria, a marquei como correta, obrigado pela explicação da resposta do Rodolpho. Poderia agora tirar a marcação?
Comment: @Francisco não fechei porque você aceitou outra resposta. Eu preciso avaliar melhor porque ainda está confuso o que deseja de fato, o fechamento de não claro é porque não se sabe exatamente o que está sendo perguntado, e não qual a resposta aceita. Ficou uma coisa complicada porque tem respostas antagônicas bem votadas. Isso passa a mensagem errada, mostra que a pergunta deixou margem para interpretações equivocadas, ou seja, isso é a definição de não clara. Eu até achei que tinha entendido porque falava em `Math`. Eu acho que não deveria ter respondido e ter fechado antes de ter respostas.
Comment: "Ficou uma coisa complicada porque tem respostas antagônicas bem votadas." Isso não tem nada a ver, as pessoas podem ter votado só pelo fato da resposta ter sido bem elaborada e ter mostrado exemplos de utilização. A pergunta não tem erros, descreve exatamente qual meu problema, para não entende-la a pessoa tem que ser muito burra.
Answer: Acredito que o que você esteja procurando chama-se Extension Methods.
Veja mais em : Métodos de extensão !
Utilizando este conceito, você pode criar extensões para todas as classes e estruturas, desde que as mesmas não sejam estáticas.
A classe Math é estática e não pode ser estendida:

As demais respostas até parecem funcionar, mas na verdade você estaria acessando uma classe nova e não a existente :System.Math.
Veja a diferença abaixo:

Lista de métodos da classe nova, em comparação com a lista de métodos da classe System.Math abaixo :

Abaixo um exemplo de como poderia ser uma extensão do double para você ter uma ideia:
class Program
{
    public static void Main()
    {
        double dez = 10;
        Console.WriteLine("Dobro(10) => {0}", dez.Dobro());
        Console.WriteLine("Metade(10) => {0}", dez.Metade());
    }
}

public static class DoubleEx
{
    public static double Dobro(this double a)
    {
        return a * 2;
    }

    public static double Metade(this double a)
    {
        return a / 2;
    }
}

Com a seguinte saída:
Dobro(10) => 20
Metade(10) => 5


When adding means of different sample sizes with known standard deviations, how can I compute the standard deviation of the combined mean?

Question: I have three means and standard deviations that represent subscales of a factor. Each subscale has a different number of items. I am summing the three subscale means together to form a factor, and am wondering if there is any way to obtain a standard deviation for the resulting factor score. Below is my example, with means listed in the first column and SDs in the second:
Sub1 (18 items)     49.80    8.16
Sub2 (13 items)     42.10    5.50
Sub3 (14 items)     36.27    7.91
Fact (45 items)     128.17   XXX
Comment: Do you want to add the means or average them in some way? You have done the former, but I have my doubts that you want to.
Comment: Thank you so much for engaging me. I have been working on this for 6 hours. So the three subscales of this particular assessment instrument are traditionally added together to form a "factor" score that represents a latent variable of interest.
Comment: So I do want to add them.
Comment: 0. Welcome to CV.SE. 1. If we assume that each subscale is Gaussian and independent of the others, we can quickly derive the results with simple Algebra. Please see my answer below for more details.
Answer: If the "factor" score of interest ($Z$) can be view as adding together the three subscales of this particular interest and each subscale is assumed to be normally distributed and independent of the others, then the we simply see $Z$ as being the linear combination of three independent Gaussian variables $A$, $B$ and $C$.
The general case is such that if our variable of interest $Z$ is the mixture of $K$ independent Gaussian variables, ie: $Z = \sum_k^{K} w_k N(\mu_{k}, \sigma_k^2)$, then $Z$ is itself normal-distributed as $Z\sim N(\sum_k^K w_k \mu_{k}, \sum_k^K (w_k \sigma_k)^2)$. The Wikipedia article on the sum of normally distributed random variables covers nicely if you want to read more details.
Now, using the above for the case of three Gaussian random variables $A$, $B$ and $C$, distributed as $N(\mu_A,\sigma_A^2)$, $N(\mu_B,\sigma_B^2)$ and $N(\mu_C,\sigma_C^2)$ respectively and assuming that $w_A = w_B = w_C = 1$, then we can immediately substitute $\mu_{A} = 49.80$, $\sigma_A = 8.16$,
$\mu_{B} = 42.1$, $\sigma_b = 5.5$, $\mu_{C} = 36.27$ and $\sigma_C = 7.91$, to get:
$\mu_Z = w_A \mu_A + w_B \mu_B + w_C \mu_C = 128.17$ (as you have derived yourself) and
$\sigma_Z^2 = w_A^2 \sigma_A^2 + w_B^2 \sigma_B^2 + w_C^2 \sigma_C^2 = 159.4037$ (or $\sigma_Z = 12.62552$)
Here is a quick R snippet showing this in action:
<code>N = 10^6
mu = c(49.8, 42.1, 36.27)
sigma = c(8.16, 5.5, 7.91)
set.seed(710)
A =  rnorm(N, mu[1], sd = sigma[1])
B =  rnorm(N, mu[2], sd = sigma[2])
C =  rnorm(N, mu[3], sd = sigma[3])
Z = A+B+C
round(c(mean(Z), sd(Z)),3)
# 128.170  12.625 as expected
</code>
Comment: Thank you so much for helping!
Comment: I am glad I could help. If this answer is helpful please consider upvoting it and if it resolves your question marking it as the accepted answer.


Moment of Inertia of a Square Based Pyramid

Question: I want to find the moment of inertia about the axis perpendicular to the base and passing through the center of mass (z-axis?). Mass is M and height is H and base has sides $a$.
I know I can take a slab of the pyramid and take the volume of the slab dv = $b^2$ x dH where $b$ is the length of the slab and dH is the height and then get the mass dm = $\rho$ x dv = $\rho$ x $b^2$ x dh. I'm stuck at this point and would appreciate any help.
Answer: let $\rho$ be the mass per unit volume, so that $M=\frac 13\rho a^2H$
Set the origin at the vertex and let the axis through the vertex and the centre of the base be the $x$ axis.
Consider an element in the form of a thin square lamina of thickness $\delta x$ which is parallel to the base and at a distance $x$ from O. Let the side of this square be $2y$.
Then $$\frac yx=\frac {a}{2H}.$$
The volume of the element is $\delta V=4y^2\delta x$
The mass of the element is $\delta m=4\rho y^2 \delta x$
Now using the standard result for the moment of inertia of a square lamina about an axis perpendicular to the plane of the lamina and through the centre, we have the MI of the element as $$\frac 16\delta m (2y)^2=\frac 83\rho y^4\delta x$$
So the MI is given by $$\frac 83\frac {3M}{a^2H}\int_0^H\frac{a^4x^4}{16H^4}dx=\frac{1}{10}Ma^2$$
Answer: The basic integral you need is $\displaystyle I=\int_Q r^2 \, dm$. The problem with your approach so far is that the slab is not equidistant from the axis of rotation, so that $r^2$ varies over your slab. You need to take a chunk where you can approximate the $r^2$ as constant over your chunk. That means a chunk $dV=dx\,dy\,dz$. So here, $dm=\rho\,dx\,dy\,dz$, where you can get $\rho=M/V$, assuming constant density. Then you need to set up your integral as
$$I=\rho\iiint_Qr^2\,dx\,dy\,dz.$$
If you draw some careful pictures, you can find out how $r^2$ varies with respect to $x,y,$ and $z$, and you can get your limits for each of the variables. Can you proceed from here?
Comment: Is this the center of mass? I'm not sure how I would get the limit of x,y and z
Comment: No, I am not describing the center of mass. That's a different integral entirely. You mentioned the moment of inertia about an axis, and that is what I am talking about as well. To get the limits, you need to draw a careful picture, find the relationships among $x, y,$ and $z$. That will give you both $r^2$ in terms of $z$, as well as the limits on the integrals.
Comment: Ah so if I take an arbitrary point from the z-axis then the distance between that point and the z-axis is [(x,y,z) - (0,0,z)] so r^2 = x^2 + y^2. Im unsure how to get the limits from there.


CSS/HTML background image not working

Question: I have been programming for over a month now non-stop. Now I have a problem. I am doing a background image. And it does not work!
Here is the HTML code:
Html Code
And here is the CSS code:
CSS Code
Comment: Please include the actual code, rather than images of your code.
Comment: Most likely your image path is wrong. Check your console for errors.
Comment: is your background image in the root directory?
Comment: If you post the actual code here on this page (use the "<>" icon) then we can tell you what went wrong.
Comment: what will we do with your HTML in image. use this before asking ur question http://stackoverflow.com/help/how-to-ask
Comment: please make sure, your image that you are setting for background and the css file should be at same label/same place (i.e in same folder weather at root level or inside and folder).
Answer: I couldn't run your code but I got my own version of your code to work as long as you have no-repeat set, and center center the background image in a div it works. Set a min-height for the container so the background always shows:

.background-thing {
  border-bottom: 1px solid #bbbbbb;
  background: url('http://placehold.it/400x400') no-repeat center center;
  background-size: cover;
  min-height: 200px;
  }

CSS/HTML background image not working


MVC 5 content globalization

Question: I have a really complex situation when I need both static localization with dynamic localization in a project I'm working on.
What I need to localize:

Static pages (like: "About", "Help", "Contact"...)

For example:

"domain.com/about"         - For English localization.
"domain.com/es-es/about"   - For Spanish localization.

This is where I'm now, and it's working.
Currently the culture is provided and specified in the routing mechanism (best for SEO), and not stored in a cookie or session.
RouteConfig.cs looks like this:
    // Localized Default:
    routes.MapRoute(
        name: "LocalizedDefault",
        url: "{culture}/{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
        constraints: new { culture = new CultureRouteConstraint() }
    );

    // Default:
    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { culture = "en-us", controller = "Home", action = "Index", id = UrlParameter.Optional }
    );

Dynamic pages - content users enter in their profile (like: "Full Name", "About"...)

Now here is what I have problem with...
Basically I need to allow users to enter many translations of their profile, and also pick the right translation for the user visiting the profile.
In addition, if a user visiting a profile that the user didn't provide a translation for his language, I need to show him a "default" translation, but the site interface will remain in his language.
So, my approach for this:
For dynamic pages, I think I need a help from a cookie, that contains the user's culture, and eliminate the {culture} route parameter in the URL, the site interface localization will be determined from the cookie or browser (user-languages) when there's no cookie. And the content localization will be determined from a route parameter in the end of the URL "{content}".
For Example:

"domain.com/user/username"          - For Default content localization (the language the user will set as default).
"domain.com/user/username/en-us"    - For English content localization.
"domain.com/user/username/es-es"    - For Spanish content localization.

I reached the following conclusions:
• For anonymous users = for static pages the localization is determined by the {culture} route parameter in the URL, but for dynamic pages the {culture} parameter is eliminated, the site interface is determined from a cookie and the {content} parameter in the end of the URL stands for the content localization.
• For authenticated users = for all pages (static & dynamic) the localization is determined only by the cookie, this makes a short & friendly URL and SEO is not affected.
Is this approach acceptable?
I can't figure what is the best practice solution in order to implement that, while preserving SEO, and friendly / easy URL?
BTW - I'm focusing on URL and SEO, database and other concerns are well performed.
Thank you!
Answer:

For anonymous users = for static pages the localization is determined by the {culture} route parameter in the URL, but for dynamic pages the {culture} parameter is eliminated, the site interface is determined from a cookie and the {content} parameter in the end of the URL stands for the content localization.

Since you are concerned with SEO, cookies are off-limits on anonymous pages. All content on these pages should be controlled via URL.
For this scenario, I think it would be most intuitive to put both the {culture} and {content} parameter into the URL, but at opposite ends.
{culture}/{controller}/{action}/{content}

You could potentially make both of these parameters optional with a logical default with a carefully crafted routing configuration. For readability, you might consider adding a static /content/ segment before the last parameter, which will require an additional route to make both segments optional.

the site interface localization will be determined from the cookie or browser (user-languages) when there's no cookie.

This is fine (assuming you use the URL not a cookie for the optional value as I mentioned above). This provides an easy way user to override the browser (user-languages) via URL. Since (user-languages) is a header that can be altered by firewalls, this may not be the user's true preference and if you don't provide a way to override it is a horrible UX. I also suggest making the way to override user-languages visible on the UI (via a link to the URL with the culture in it), not just available via URL.
Keep in mind search engines may not provide this header, so you should also have a fallback plan (default culture) when it is not available. Always consider the URL to be the first choice for culture when provided and ignore the (user-languages) header.

For authenticated users = for all pages (static & dynamic) the localization is determined only by the cookie, this makes a short & friendly URL and SEO is not affected.

You have more flexibility for URLs that can only reached by authenticated users, so using a cookie here is fine. Although, if the rest of the site puts the culture in the URL that might feel a bit odd to power users who use the URL to navigate.
Personally, I would aim for consistency with the rest of the site rather than "nice short URLs" for authenticated pages, since it is usually only anonymous pages where "nice short URLs" count for both SEO and sharing purposes. But, if you are expecting to have a lot of power users that edit the URL in the browser it may be worth considering.

MVC 5 content globalization


proof for $e\leq 3(v-2)$ [Why does $d(f) \geq 3$?]

Question: Here is the well known theorem, "For planar graph $G$, if $v\geq3$ then $e\leq 3(v-2)$"
I've reviewed my discrete mathematics note, suddenly the question crossed my mind.
When we proving the  $e\leq 3(v-2)$ for planar graph, $G$. We used $d(f) \geq 3$.
In my note, it told me the reason why does $d(f) \geq 3$ is "each face is bounded by at least three edges, but each edge borders two faces."
When I first saw it, it was clear for me. But the time passed I doubt about that.
Because... Let me suggest the counter example below.

The above graph is planar graph and $v=3, e=2,f=1$. But the $d(f) \lt 3$ (I.e. the face is not bounded three edges)
Still I've confused what the point did I mistake.
Any help would be appreciated.
Answer: Your counterexample is discussed in this answer. Because the edges are boundaries of the same face, in the proof the "boundary of the face" has 4 edges (each edge is counted twice).


Erro de leitura de código HTML na função Mail.php

Question: Então, criei um formulário de contato do qual precisaria que ele viesse bem formatado no e-mail destinatário. Por isso deixei o HTML um pouco mais estruturado e utilizei CSS Inline para as configurações, conforme ditam as boas práticas para envio de HTML por e-mail.
Armazenei todo o código abaixo dentro de uma variável (da qual eu utilizo-a depois na função mail para o corpo da mensagem):
<!DOCTYPE html>

1. Dados Pessoais

Nome: $nome

Estado Civil: $estadoCivil	Resid.: $telefoneFixo	Cel.: $telefoneCelular

Sexo: $sexo 	Nascimento: $datanascimentoPessoal Naturalidade: $naturalidade

Endereço: $endereco

Bairro: $bairro 	CEP: $cep 	Cidade: $cidade

Nome do Pai: $nomePai 	Nome da Mãe: $nomeMae

Gru de Instrução: $grauInstrucao 	Completo? $grauCompleto 	Raça/Cor: $racaCor

2. Beneficiários

Cônjuge: $conjuge 	Nascimento: $datanascimentoConjuge 	IRRF: $irrfConjuge

Dependente: $dep1 	Nascimento: $datanascimentoDep1 	IRRF: $irrfDep1

Dependente: $dep2 	Nascimento: $datanascimentoDep2 	IRRF: $irrfDep2

Dependente: $dep3 	Nascimento: $datanascimentoDep3 	IRRF: $irrfDep3

Dependente: $dep4 	Nascimento: $datanascimentoDep4 	IRRF: $irrfDep3

3. Documentação

RG: $rg 	Orgão Exp.: $orgaoExpedidor 	Data de Exp.: $dataexpedicaoRG 	CPF: $cpf

Título de Eleitor: $tituloEleitor 	Zona: $zonaEleitor 	Seção: $secaoEleitor

CTPS: $ctps 	Série: $serieCTPS 	UF: $ufCTPS 	Data de Exp.: $dataexpedicaoCTPS 	PIS: $pis

Carteira de Hab.: $carteiraHabilitacao 	Categoria: $categoriaHab 	Vencimento: $vencimentoHab	UF: $ufHab 	Reservista: $reservista

4. Dados Bancários

Banco: $nomeBanco 	 Agência: $agenciaBanco 	Conta: $contaBanco

5. Benefícios

Vale Transporte: $valeTransporte 	Qtde por dia: $qtdeVT 	Valor da Tarifa: $valorVT 	Empresa: $empres

Número Cartão Transporte/SIC: $numeroTransporte

Vale Alimentação: $valeAlimentacao 	Vale Refeição: $valeRefeicao 	Valor por Dia: $valorDia

6. Informações Adicionais

Centro de Custo: $centroCusto

Já trabalhou nesta empresa: $jaTrabalhou	 Contrato de Experiência: $contratoExp

Período de Experiência: $periodoExp

Sindicato: $sindicato

Forma de Contratação: $formaContratacao

Cargo e Funação: $cargoFuncao 	 Data de Início: $dataInicio

Horário de Trabalho: $horarioTrabalho 	 Intervalo: $intervalo

Sábado: $sabado 	 Horário: $horarioSabado 	 Qtde Sábados Mês: $qtdeSabado

Salário: $salario

Já realizou contribuição sindical este ano? $contrSindical

Insalubridade: $insalubridade

Crachá: $cracha

    <tfooter align="center" width="790">

$data

    </tfooter>

Defini os headers corretamente para indicar as configurações do corpo da mensagem:
   $headers = "xxxxxxxxxxxx";
   $headers .= 'MIME-Version: 1.0' . "\r\n";
   $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

Entretanto, ao enviar o formulário, ele não está reconhecendo as configurações do HTML.
Ele fica acusando erros como (no caso do witdh="790" da tabela):
Parse error: syntax error, unexpected '790' (T_LNUMBER)

E consequentemente ele acusa erro em todas as outras configurações inline, como o valor do width, align, colspan, etc.
Alguém sabe porque isso está acontecendo?
Comment: Não da pra saber exatamente pq não tem atribuição da variável na pergunta mas desconfio que tenha um aspa dupla antes e `width="` é interpretado como o fechamento.
Comment: Provavelmente é o que o @rray comentou, quando tenho de enviar e-mail dessa deixo o html em arquivo _.html_ e carrego o arquivo com `file_get_contents` e dou um `replace` nas variáveis. Tipo o `$data` estaria assim `@data@`.
Comment: Quando vai armazenar o HTML na variável, como está fazendo?
Comment: Era exatamente isso @rray  acabei não me atentando. O erro ocorre porque está sendo interpretado o fechamento da variável mesmo.

Quais seriam as alternativas viáveis para essa situação? Não compreendi muito bem a sugestão do fernandoandrade (Sou iniciante ainda).
Comment: @caiocafardo $mensagem = "meu html";
Comment: Pode usar o heredoc para montar um template [veja nessa resposta](http://pt.stackoverflow.com/a/14258/91)
Answer: Faça a atribuição da variável assim:
$var = '<!DOCTYPE html>

1. Dados Pessoais

Nome: $nome

Estado Civil: $estadoCivil	Resid.: $telefoneFixo	Cel.: $telefoneCelular

Sexo: $sexo 	Nascimento: $datanascimentoPessoal Naturalidade: $naturalidade

Endereço: $endereco

Bairro: $bairro 	CEP: $cep 	Cidade: $cidade

Nome do Pai: $nomePai 	Nome da Mãe: $nomeMae

Gru de Instrução: $grauInstrucao 	Completo? $grauCompleto 	Raça/Cor: $racaCor

2. Beneficiários

Cônjuge: $conjuge 	Nascimento: $datanascimentoConjuge 	IRRF: $irrfConjuge

Dependente: $dep1 	Nascimento: $datanascimentoDep1 	IRRF: $irrfDep1

Dependente: $dep2 	Nascimento: $datanascimentoDep2 	IRRF: $irrfDep2

Dependente: $dep3 	Nascimento: $datanascimentoDep3 	IRRF: $irrfDep3

Dependente: $dep4 	Nascimento: $datanascimentoDep4 	IRRF: $irrfDep3

3. Documentação

RG: $rg 	Orgão Exp.: $orgaoExpedidor 	Data de Exp.: $dataexpedicaoRG 	CPF: $cpf

Título de Eleitor: $tituloEleitor 	Zona: $zonaEleitor 	Seção: $secaoEleitor

CTPS: $ctps 	Série: $serieCTPS 	UF: $ufCTPS 	Data de Exp.: $dataexpedicaoCTPS 	PIS: $pis

Carteira de Hab.: $carteiraHabilitacao 	Categoria: $categoriaHab 	Vencimento: $vencimentoHab	UF: $ufHab 	Reservista: $reservista

4. Dados Bancários

Banco: $nomeBanco 	 Agência: $agenciaBanco 	Conta: $contaBanco

5. Benefícios

Vale Transporte: $valeTransporte 	Qtde por dia: $qtdeVT 	Valor da Tarifa: $valorVT 	Empresa: $empres

Número Cartão Transporte/SIC: $numeroTransporte

Vale Alimentação: $valeAlimentacao 	Vale Refeição: $valeRefeicao 	Valor por Dia: $valorDia

6. Informações Adicionais

Centro de Custo: $centroCusto

Já trabalhou nesta empresa: $jaTrabalhou	 Contrato de Experiência: $contratoExp

Período de Experiência: $periodoExp

Sindicato: $sindicato

Forma de Contratação: $formaContratacao

Cargo e Funação: $cargoFuncao 	 Data de Início: $dataInicio

Horário de Trabalho: $horarioTrabalho 	 Intervalo: $intervalo

Sábado: $sabado 	 Horário: $horarioSabado 	 Qtde Sábados Mês: $qtdeSabado

Salário: $salario

Já realizou contribuição sindical este ano? $contrSindical

Insalubridade: $insalubridade

Crachá: $cracha

    <tfooter align="center" width="790">

$data

    </tfooter>

';

quando utilizamos aspas duplas no html, o php permite utilizar na definição de string as aspas simples.
Comment: Quando utiliza aspas simples variáveis não são interpretadas.
Comment: Interessante @NIZZOLA, não sabia dessa possibilidade, resolveu meu problema, o formulário agora não da mais erro!

Entretanto, no e-mail ele não está imprimindo o valor da variável e sim a variável em si. Por exemplo: "Nome: $nome". Devo mudar algo na sintaxe por usar as aspas simples?
Comment: Faça a concatenação das variáveis assim: $nome = 'abde' . $var .'fghij'; ou a inversão das aspas duplas pelas simples assim $nome = "abde $var tags html assim ";
Comment: @NIZZOLA desculpa minha ignorância, mas não compreendi muito bem como fazer esse procedimento que você sugeriu.

A concatenação deve ser feita no momento da declaração das variáveis ou no momento de declaração delas no início?

Se você puder mostrar com 1 linha do código que montei como deveria ficar a sintaxe acho que facilitaria minha compreensão.

Caso necessite, segue como declarei algumas varíaveis:
nome = $_POST['nome'];
$estadoCivil = $_POST['estado-civil'];
$sexo = $_POST['sexo'];
$telefoneFixo = $_POST['tel'];
$telefoneCelular = $_POST['cel'];
Comment: @ViniciusGabriel Eu já precisei fazer isso e há duas formas, você coloca num bloco de notas seu html e substitui todas as apas duplas por simples assim poderá usar no php as aspas duplas como delimitadores. exemplo: $var = " ";   veja que as apas simples estarão fazendo o papel no html normal e aí você pode colocar variáveis dentro. Uma outra forma é concatenar a string você termina a string onde a variavel entra e depois continua. exemplo : $var = 'xyz'.$var2.'abdde'; sem mexer no seu código html.
Comment: @ViniciusGabriel por favor, verificar e colocar a pergunta como respondida.
Comment: @NIZZOLA me desculpa, é que sou novo no portal, não consegui achar onde colocar a pergunta como respondida? Não era só assinalar a aceitação da resposta na sua resposta com códigos?


What permissions does a pod have when accessing the Kubernetes API?

Question: The kubernetes documentation states the following under "Accessing the API from within a Pod":

The easiest way to use the Kubernetes API from a Pod is to use one of the official client libraries. These libraries can automatically discover the API server and authenticate.

I have pods running theia-ide, a cloud-based IDE, where each user can access the console for their container. Can they access the Kubernetes API from that container without authenticating?
Answer: I found some other documentation that explained things further. Apparently pods get assigned to the default service account, which (as I understand) does not come with any permissions by default. If a pod needs more permissions, you can create a custom service account with its own role bindings, and then assign the pod to use that service account instead of default using the spec.serviceAccountName property.


Preprocess a Paragraph when Added to Content Type

Question: I'm trying to disable a field in a Paragraph when it's added to a certain content type. Currently I'm using the following:
function my_module_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  switch($form_id) {
    case "node_content_type_form":
        $form['field_paragraph_content']['widget'][0]['subform']['field_paragraph_field']['#disabled'] = 'disabled';
      break;
  }
}

This works only after the node containing the paragraph has already been saved. When the paragraph in question is first added to the node the field_paragraph_field is not disabled.
How can I preprocess the Paragraph form when it is initially added to the content type so this field is always disabled?
Answer: If you want it to work when creating a node and when editing the node, you should make the change using both the node add form and the node edit form:
mymodule_form_node_content_type_form_alter()

mymodule_form_node_content_type_edit_form_alter()

Or in your hook_form_alter in the question:
case "node_content_type_form":
case "node_content_type_edit_form":

There's another way to do this using hook_field_widget_form_alter():
function mymodule_field_widget_form_alter(&$element, FormStateInterface $form_state, $context) {

  if ($context['items']->getFieldDefinition()->getTargetBundle() == 'content_type' && $context['items']->getFieldDefinition()->getName() == 'field_paragraph_field') {
    $element['#disabled'] = TRUE;
  }

}


a problem involving geometric sequence

Question: The question I am asking is this

Suppose $a$, $b$, and $c$ are real numbers such that $a$, $b$, $c$ and $a$, $b + 1$, $c + 2$ are both geometric sequences in their respective orders. Compute the smallest possible value of $(a + b + c)^2$.

This problem is related to a question in an AMC competition. I have nowhere to start except $xa=b$, $xb= c$, and $ya=b+1$, $y(b+1)=c+2$.
Any help on this?
Answer: Hint $a c = b^2$ and $a (c+2) = (b+1)^2$. Compute $b$ and $c$ in terms of $a$.

a problem involving geometric sequence


css image link change opacity on hover

Question:

 #contentimage {
    display:block;
    background:url(../images/contimg.jpg);
    top:500px;
    width:500px;
    height:400px;
    position:relative;
}
#contentimage:hover {
    opacity:0.5;
}

I'd like the opacity of the image link to change when I hover. However it's not even treating the image as a link (no click option)?
Comment: Works here.. http://jsfiddle.net/JoshC/QuC4u/
Comment: your fiddle is working fine and it is treating image as link..
Comment: yea forgot i had a lesser z-index on the parent div preventing me clicking the
Answer: Maybe you can try this:

Answer: The code looks good except for one error.
In your css, use url with quotes
background:url('../images/contimg.jpg');
Edit: Your code works fine.
Comment: Yes, while quotes are proper syntax, virtually every browser will deal with the image correctly even if left unquoted.
Comment: You are correct. Then the code works fine. There is no problem.

css image link change opacity on hover


Small question about contravariant functors

Question: I am new to Category Theory and it was recommended to me to start my understanding of basic concepts by reading $\textit{Basic Category Theory}$ by Tom Leinster.
But I am finding myself struggling a bit with the notion of $\textit{Contravariant Functor}$. In one of his many examples, namely $\textit{Example 1.2.11}$, it is meant to show that, given a topological space $X$ and $C(X)$, the ring of real-valued functions at X, $C$ corresponds to a contravariant functor from $\textbf{Top}$ to $\textbf{Ring}$.
However, the part that I am not understanding is why when we define a function
$$
f:X \rightarrow Y
$$
we induce a ring homomorphism
$$
C(f):C(Y)\rightarrow C(X)
$$
More particularly, I wish someone could give me some hints as to why $C(f)$ goes in the opposite direction from $f$.
Any help is really appreciated! Thank you in advance, for taking your time to read my question.
Comment: If we have a continuous real valued function on Y and a continuous function from X to Y, we can precompose by the latter and get a continuous real valued function on X. The functor reverses the direction of the arrows because it is mapping morphisms in Top to the operation of precomposition by that morphism on the continuous real valued functions of the codomain.
Comment: Covariant goes in the "same" direction, and Contravariant in the opposite direction - by definition of these words for functors - see [here](https://mathworld.wolfram.com/CovariantFunctor.html) and [here](https://mathworld.wolfram.com/ContravariantFunctor.html).
Comment: sorry, the real valued functions, not necessarily continuous, though the point is the same
Comment: Tom Leinster's book is terrific, but I suspect it is a bit tougher going than he perhaps intends. So check out https://www.logicmatters.net/categories/ for links to a LOT of freely available resources at varying levels -- it might be a good plan to find one or two others that work for you to read in parallel to _Basic Category Theory_.
Answer: Given topological spaces $X, Y$ and a continuous function $f : X \to Y$, given any real-valued function $\phi : Y \to \mathbb{R}$ we can produce a function $X \to \mathbb{R}$ by composing:
$$X \xrightarrow{f} Y \xrightarrow{\phi} \mathbb{R}$$
That is, we get the real valued function sending $x \in X$ to $\phi (f (x)) \in \mathbb{R}$.
This is an example of a much more general phenomenon:

Precomposing flips the direction of arrows, while postcomposing keeps it as it is

Another instance of this fact can be seen when you consider the following setup: fix any category $\mathcal{C}$ and an object $c : \mathcal{C}$ in it. We can cook up a functor $\mathbf{Y}_c : \mathcal{C} \to \mathbf{Set}$ into the category of sets by defining
$$\mathbf{Y}_c(a) := \mathbf{Hom}_{\mathcal{C}}[a, c]$$
using the hom-sets. Now, this functor is contravariant just as the one you described, and for the same exact reason: given a morphism $f : a \to a^\prime$ in $\mathcal{C}$, we want to produce a function between the hom-sets:
$$\mathbf{Y}_c(a^\prime) = \mathbf{Hom}_\mathcal{C}[a^\prime, c] \xrightarrow{f^*} \mathbf{Hom}_\mathcal{C}[a, c] = \mathbf{Y}_c(a)$$
The function $f^*$ is given in the same way: given $\phi : a^\prime \to c$, we produce
$$a \xrightarrow{f} a^\prime \xrightarrow{\phi} c$$
The functor $\mathbf{Y}_c$ is extremely important, by the way: it's called the Yoneda embedding of $c : \mathcal{C}$.
As you'll see later on, the assignment $c \mapsto \mathbf{Y}_c$ is actually a (covariant) functor itself (from $\mathcal{C}$ to the category of contravariant functors $\mathcal{C} \to \mathbf{Set}$ into the category of sets). This functor is the main player of a very important result in category theory: the Yoneda lemma.


Take photo in service using Camera2 API

Question: I am using the camera2 API. I need to take a photo in the service without a preview. It works, but the photos have a bad exposure. The pictures are very dark or sometimes very light. How can I fix my code so that the photos are of high quality? I'm using the front camera.
public class Camera2Service extends Service
{

    protected static final String TAG = "myLog";
    protected static final int CAMERACHOICE = CameraCharacteristics.LENS_FACING_BACK;
    protected CameraDevice cameraDevice;
    protected CameraCaptureSession session;
    protected ImageReader imageReader;

    protected CameraDevice.StateCallback cameraStateCallback = new CameraDevice.StateCallback() {
        @Override
        public void onOpened(@NonNull CameraDevice camera) {
            Log.d(TAG, "CameraDevice.StateCallback onOpened");
            cameraDevice = camera;
            actOnReadyCameraDevice();
        }

        @Override
        public void onDisconnected(@NonNull CameraDevice camera) {
            Log.w(TAG, "CameraDevice.StateCallback onDisconnected");
        }

        @Override
        public void onError(@NonNull CameraDevice camera, int error) {
            Log.e(TAG, "CameraDevice.StateCallback onError " + error);
        }
    };

    protected CameraCaptureSession.StateCallback sessionStateCallback = new CameraCaptureSession.StateCallback() {

        @Override
        public void onReady(CameraCaptureSession session) {
            Camera2Service.this.session = session;
            try {
                session.setRepeatingRequest(createCaptureRequest(), null, null);
            } catch (CameraAccessException e) {
                Log.e(TAG, e.getMessage());
            }
        }

        @Override
        public void onConfigured(CameraCaptureSession session) {

        }

        @Override
        public void onConfigureFailed(@NonNull CameraCaptureSession session) {
        }
    };

    protected ImageReader.OnImageAvailableListener onImageAvailableListener = new ImageReader.OnImageAvailableListener() {
        @Override
        public void onImageAvailable(ImageReader reader) {
            Log.d(TAG, "onImageAvailable");
            Image img = reader.acquireLatestImage();
            if (img != null) {
                processImage(img);
                img.close();
            }
        }
    };

    public void readyCamera() {
        CameraManager manager = (CameraManager) getSystemService(CAMERA_SERVICE);
        try {
            String pickedCamera = getCamera(manager);
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
            manager.openCamera(pickedCamera, cameraStateCallback, null);
            imageReader = ImageReader.newInstance(1920, 1088, ImageFormat.JPEG, 2 /* images buffered */);
            imageReader.setOnImageAvailableListener(onImageAvailableListener, null);
            Log.d(TAG, "imageReader created");
        } catch (CameraAccessException e){
            Log.e(TAG, e.getMessage());
        }
    }

    public String getCamera(CameraManager manager){
        try {
            for (String cameraId : manager.getCameraIdList()) {
                CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);
                int cOrientation = characteristics.get(CameraCharacteristics.LENS_FACING);
                if (cOrientation != CAMERACHOICE) {
                    return cameraId;
                }
            }
        } catch (CameraAccessException e){
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "onStartCommand flags " + flags + " startId " + startId);

        readyCamera();

        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onCreate() {
        Log.d(TAG,"onCreate service");
        super.onCreate();
    }

    public void actOnReadyCameraDevice()
    {
        try {
            cameraDevice.createCaptureSession(Arrays.asList(imageReader.getSurface()), sessionStateCallback, null);
        } catch (CameraAccessException e){
            Log.e(TAG, e.getMessage());
        }
    }

    @Override
    public void onDestroy() {
        try {
            session.abortCaptures();
        } catch (CameraAccessException e){
            Log.e(TAG, e.getMessage());
        }
        session.close();
    }

    private void processImage(Image image){
        //Process image data
        ByteBuffer buffer;
        byte[] bytes;
        boolean success = false;
        File file = new File(Environment.getExternalStorageDirectory() + "/Pictures/image.jpg");
        FileOutputStream output = null;

        if(image.getFormat() == ImageFormat.JPEG) {
            buffer = image.getPlanes()[0].getBuffer();
            bytes = new byte[buffer.remaining()]; // makes byte array large enough to hold image
            buffer.get(bytes); // copies image from buffer to byte array
            try {
                output = new FileOutputStream(file);
                output.write(bytes);    // write the byte array to file
                j++;
                success = true;
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                image.close(); // close this to free up buffer for other images
                if (null != output) {
                    try {
                        output.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

        }

    }

    protected CaptureRequest createCaptureRequest() {
        try {
            CaptureRequest.Builder builder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_RECORD);
            builder.addTarget(imageReader.getSurface());
            return builder.build();
        } catch (CameraAccessException e) {
            Log.e(TAG, e.getMessage());
            return null;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

Comment: Did you ever find an aswer?
Comment: njho, no((((((((
Comment: Why fun `onImageAvailable` is called nonstop(many times)? How to stop the call of the method after first success?
Answer: Sergey, I copied your code and indeed I was able to reproduce the issue. I got totally black pictures out of Google Pixel 2 (Android 8.1).
However, I have successfully resolved the black-pic issue as follows:
First, in case anyone is wondering, you actually do NOT need any Activity, or any preview UI element as many other threads about the Camera API claim! That used to be true for the deprecated Camera v1 API. Now, with the new Camera v2 API, all I needed was a foreground service.
To start the capturing process, I used this code:
CaptureRequest.Builder builder = cameraDevice.createCaptureRequest (CameraDevice.TEMPLATE_VIDEO_SNAPSHOT);
builder.set (CaptureRequest.CONTROL_MODE, CaptureRequest.CONTROL_MODE_AUTO);
builder.set (CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_OFF);
builder.addTarget (imageReader.getSurface ());
captureRequest = builder.build ();

Then, in ImageReader.onImageAvailable, I skipped the first N pictures (meaning I did not save them). I let the session run, and capture more pics without saving them.
That gave the camera enough time to automatically gradually adjust the exposition parameters. Then, after N ignored photos, I saved a photo, which was normally exposed, not black at all.
The value of the N constant will depend on characteristics of your hardware. So you will need to determine the ideal value of N experimentally for your hardware. You can also use histogram-based heuristic automation. At the beginning of experiments, don't be afraid to start saving only after hundreds of milliseconds of calibration have passed.
Finally, in a lot of similar threads people suggest to just wait e.g. 500 ms after creating the session and only then taking a single picture. That does not help. One really has to let the camera run and let it take many pictures rapidly (at the fastest rate possible). For that, simply use the setRepeatingRequest method (as in your original code).
Hope this helps. :)
EDITED TO ADD: When skipping the initial N pictures, you need to call the acquireLatestImage method of ImageReader for each of those skipped pictures too. Otherwise, it won't work.
Full original code with my changes incorporated that resolved the issue, tested and confirmed as working on Google Pixel 2, Android 8.1:
public class Camera2Service extends Service
{
    protected static final int CAMERA_CALIBRATION_DELAY = 500;
    protected static final String TAG = "myLog";
    protected static final int CAMERACHOICE = CameraCharacteristics.LENS_FACING_BACK;
    protected static long cameraCaptureStartTime;
    protected CameraDevice cameraDevice;
    protected CameraCaptureSession session;
    protected ImageReader imageReader;

    protected CameraDevice.StateCallback cameraStateCallback = new CameraDevice.StateCallback() {
        @Override
        public void onOpened(@NonNull CameraDevice camera) {
            Log.d(TAG, "CameraDevice.StateCallback onOpened");
            cameraDevice = camera;
            actOnReadyCameraDevice();
        }

        @Override
        public void onDisconnected(@NonNull CameraDevice camera) {
            Log.w(TAG, "CameraDevice.StateCallback onDisconnected");
        }

        @Override
        public void onError(@NonNull CameraDevice camera, int error) {
            Log.e(TAG, "CameraDevice.StateCallback onError " + error);
        }
    };

    protected CameraCaptureSession.StateCallback sessionStateCallback = new CameraCaptureSession.StateCallback() {

        @Override
        public void onReady(CameraCaptureSession session) {
            Camera2Service.this.session = session;
            try {
                session.setRepeatingRequest(createCaptureRequest(), null, null);
                cameraCaptureStartTime = System.currentTimeMillis ();
            } catch (CameraAccessException e) {
                Log.e(TAG, e.getMessage());
            }
        }

        @Override
        public void onConfigured(CameraCaptureSession session) {

        }

        @Override
        public void onConfigureFailed(@NonNull CameraCaptureSession session) {
        }
    };

    protected ImageReader.OnImageAvailableListener onImageAvailableListener = new ImageReader.OnImageAvailableListener() {
        @Override
        public void onImageAvailable(ImageReader reader) {
            Log.d(TAG, "onImageAvailable");
            Image img = reader.acquireLatestImage();
            if (img != null) {
                if (System.currentTimeMillis () > cameraCaptureStartTime + CAMERA_CALIBRATION_DELAY) {
                    processImage(img);
                }
                img.close();
            }
        }
    };

    public void readyCamera() {
        CameraManager manager = (CameraManager) getSystemService(CAMERA_SERVICE);
        try {
            String pickedCamera = getCamera(manager);
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
            manager.openCamera(pickedCamera, cameraStateCallback, null);
            imageReader = ImageReader.newInstance(1920, 1088, ImageFormat.JPEG, 2 /* images buffered */);
            imageReader.setOnImageAvailableListener(onImageAvailableListener, null);
            Log.d(TAG, "imageReader created");
        } catch (CameraAccessException e){
            Log.e(TAG, e.getMessage());
        }
    }

    public String getCamera(CameraManager manager){
        try {
            for (String cameraId : manager.getCameraIdList()) {
                CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);
                int cOrientation = characteristics.get(CameraCharacteristics.LENS_FACING);
                if (cOrientation == CAMERACHOICE) {
                    return cameraId;
                }
            }
        } catch (CameraAccessException e){
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "onStartCommand flags " + flags + " startId " + startId);

        readyCamera();

        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onCreate() {
        Log.d(TAG,"onCreate service");
        super.onCreate();
    }

    public void actOnReadyCameraDevice()
    {
        try {
            cameraDevice.createCaptureSession(Arrays.asList(imageReader.getSurface()), sessionStateCallback, null);
        } catch (CameraAccessException e){
            Log.e(TAG, e.getMessage());
        }
    }

    @Override
    public void onDestroy() {
        try {
            session.abortCaptures();
        } catch (CameraAccessException e){
            Log.e(TAG, e.getMessage());
        }
        session.close();
    }

     private void processImage(Image image){
    //Process image data
    ByteBuffer buffer;
    byte[] bytes;
    boolean success = false;
    File file = new File(Environment.getExternalStorageDirectory() + "/Pictures/image.jpg");
    FileOutputStream output = null;

    if(image.getFormat() == ImageFormat.JPEG) {
        buffer = image.getPlanes()[0].getBuffer();
        bytes = new byte[buffer.remaining()]; // makes byte array large enough to hold image
        buffer.get(bytes); // copies image from buffer to byte array
        try {
            output = new FileOutputStream(file);
            output.write(bytes);    // write the byte array to file
            j++;
            success = true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            image.close(); // close this to free up buffer for other images
            if (null != output) {
                try {
                    output.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

}

protected CaptureRequest createCaptureRequest() {
    try {
        CaptureRequest.Builder builder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_RECORD);
        builder.addTarget(imageReader.getSurface());
        return builder.build();
    } catch (CameraAccessException e) {
        Log.e(TAG, e.getMessage());
        return null;
    }
}

@Override
public IBinder onBind(Intent intent) {
    return null;
}

}
Comment: What is the j++ for? I can't see any other mention of it?
Comment: @stuart194 you are asking the wrong poster. If you read the very first line of my post, you will find out that I "copied the code" from the OP, from the first post, and enhanced it, so that it works for me. And if you search the original code, you will find j++ there too. So ask him, why he had j++ there. In any case, in this excerpt from his code, it is obviously not used for anything. :)
Comment: Original solution! Can I ask you to look at the resulting source code? I'm afraid I will reproduce your decision for a long time)
Comment: My source code is exactly the same as yours, except the changed code for the CaptureRequest, which I posted in my answer, and also in your onImageAvailable I test the condition if enough time has passed since I started the capturing process (to do that, you can simply use this, for example: "if (System.currentTimeMillis () > capturingStartTime + EXPERIMENTALLY_DETERMINED_INTERVAL)". Otherwise, I did not make any other changes to your source code.
Comment: Also, I suppose TEMPLATE_VIDEO_SNAPSHOT might not be the only one that works. It's just the one I chose as the first to test, and it worked for me. I did not try any other template after that.
Comment: after calling `CaptureRequest.Builder builder = cameraDevice.createCaptureRequest (CameraDevice.TEMPLATE_VIDEO_SNAPSHOT);` an error occurs `IllegalArgumentException while invoking public void android.hardware.camera2.CameraCaptureSession$StateCallback.onReady(android.hardware.camera2.CameraCaptureSession)
    java.lang.IllegalArgumentException: createDefaultRequest - invalid templateId specified`
Comment: It's very strange that the code does not work. Could you show your code to Gist? I want to compare two classes
Comment: I'm sorry, I don't know what Gist is. It might be the case that your hardware does not support the TEMPLATE_VIDEO_SNAPSHOT template. But in principle, you could try any other template and it should work too. Try for example one of these: TEMPLATE_STILL_CAPTURE or TEMPLATE_RECORD or TEMPLATE_PREVIEW
Comment: The photos again turn out to be dark ((Please publish the source code here https://gist.github.com. This will help me a lot.
Comment: I've added the full source code to my answer above. You will really need to try different templates. They might be the culprit.
Comment: I tried all the templates. The result does not change. It seems to me that CAMERA_CALIBRATION_DELAY does not affect the result when using these templates. I used 500, 1000,3000 - the photos are equally dark. Have you tried using other templates besides TEMPLATE_VIDEO_SNAPSHOT?
Comment: I've tested the following templates just now: TEMPLATE_STILL_CAPTURE -- did not work. But TEMPLATE_RECORD works well! Also, I use builder.set (CaptureRequest.CONTROL_SCENE_MODE, CaptureRequest.CONTROL_SCENE_MODE_NIGHT); Maybe that helps me too. If none of the other templates work for you, note that there is a bug in your code: (cOrientation != CAMERACHOICE) should actually be: (cOrientation == CAMERACHOICE). Which leads me to a question: Are you sure you are using the right camera and not physically covering the lens with anything?
Comment: I updated the code I posted -- fixed two bugs: 1) img wasn't closed when it was skipped, 2) camera choice (front/back) was incorrect.
Comment: I need to take a photo from the front camera. Unfortunately, on the phone xiaomi redmi 4a, android 7.1.1 the pictures again turn out to be dark ((((
Comment: I'm really sorry to hear that, man. :( If you tried all of the templates, the last thing that I can think of for you to try is to copy the official Camera2 example and see if it works -- good luck. https://github.com/googlesamples/android-Camera2Video/blob/master/Application/src/main/java/com/example/android/camera2video/Camera2VideoFragment.java
Comment: When I start the service it works fine but when I try to stop the service it gives error "    java.lang.IllegalStateException: Session has been closed; further changes are illegal" .... Please help
Comment: How can I use this service to take both front and back side of picture at the same time
Comment: @PakistanBeauty If you mean both front and back _camera_ (both cameras) at the same time, then you need a phone that supports that (few do). Software-wise, there might be some Camera API stuff for that, I don't know. If there isn't, you could try using my code in two separate threads, one for each camera. If that doesn't work, then obviously do a loop with two iterations per frame, each iteration using a different camera.

Take photo in service using Camera2 API


Create a file on back-end, from the text coming from front-end

Question: I'm trying to make an app that grabs code from two different code editors (using angular-ui-codemirror), one for the code to be tested and the other for the test code, and outputs the output of the tests back onto the site.
As of now, I can get the text from both code editors concatenated and console.logged out in the browser.
I'm wondering how I could take that code and save it into a file on the back- end, so that I could spawn a child-process that runs tests on it and does something with the stdout.
I'm using angular, node and express for coding and for testing, I am using mocha.
Answer: fs.writeFile('./yournewfile.js', newCode, function (error) {
  if (error) return callback(error)

  var Exec = require('child_process').exec;

  // change node to mocha if your newCode is mocha test code
  Exec('node ./yournewfile.js', function (error, stdout, stderr) {
    // do something here
  })
})


How to periodically deduct user points for flagged nodes?

Question: I have a node which is published. And I have a global flag, which users have to mark to make nodes visible in Views. This is easy to do.
But then I need to charge 40 user points for every day that node remains flagged. And when user doesn't have enough points anymore, then node must be unflagged.
Possible realization what I tried:
via CRON: I tried to make a rule for that, but when I add an Event (= On CRON Run), then I cannot add an action with user points. Some people say it should be an extra script for cron, but I don't know how to make it.
via Rules: I tried to make a rule on Event "When node is flagged" and make a Scheduled Rule with the same -40pts for user nextday. It works only once until the Scheduled Rule completed or until cron is running. So I cannot make a loop properly.
I've no more ideas to get it working. Maybe I just lost something while making Rules?
Answer: Part 1 - Deducting user points
Repeat the daily deduction of user points
Use the rules scheduler as explained in the video about "Repeating scheduled events". The "clue" here is:

as the last action of your rule, you reschedule the same rule to be executed again after +1 day(s).
the very first time you need to trigger the execution of this rule manually (from the Rules UI). Or you can use the Rules Event "when node is flagged".

Video tutorials
If you're not familiar (enough/yet) with Rules, checkout the 32 (!!!) great, and free, video tutorials Learn the Rules framework.
Part 2 - Stop deducting if insufficient user points
The 2nd part of your question is about "... when user doesn't have enough points anymore, then node must be unflagged ...". The challenge with that is that there is no Rules Condition like "If user has less then X user points".
However, to also make that work, you can use a Rules Action "Load user points of a user", as an alternative (work around?) for something like a missing Rules Condition to "check the current user points for a user". Have a look at my answer to "How to create rule to change user role based on points (using User Points module)?", which includes an sample rule that uses this Rules Action.
So all you have to do is to further enhance your rule as in Part 1, by using the Conditional Rules module so that your Rules Action will look something like so:

Load user points balance
If user points balance > 40
then reschedule the same rule to execute in 1 day.


What are the criteria to decide between modules ThemeKey and Switchtheme?

Question: There are (at least) 2 modules that allow for switching between themes, i.e.:

ThemeKey.
Switchtheme.

What are the typical criteria, or pros/cons, for a site builder (without any custom coding or custom theming) to decide for either one?
I have the impression that using ThemeKey the administrator (only) determines how the theme is switched, while by using Switchtheme it is rather the user who decides (from a list predefined by the administrator). Am I close?
Answer: Switchtheme is a user-driven theme switcher with a couple of automatic options. It provides a couple of blocks (displayed via a custom Switchtheme permission) where a user can select a theme to choose on a per session (or user account) basis.
Its automatic (admin configured) solutions are:

A per-browser automatic switcher through the Browscap module
A per-URL switch through adding a ?theme=theme_machine_name query parameter to the page request (e.g. http://example.com/?theme=seven)

ThemeKey is a combination of user/admin driven theme switching based on various settings & rules.
Its theme switching solutions provided are:

A per-alias solution that allows to set a theme for each Drupal alias
A per-node solution that allows a permissioned user to set a theme for any node they create (as well a default option).
A per-user solution that allow a user to set a default theme for their configured account.
A chain of custom rules that evaluates various Drupal system, user, comment, node, taxonomy, and Views properties.


Get domain logo in views (using Domain Access module)

Question: I'm using Domain Access module and I have different logo for each domain. I have setup logo for each domain in domain theme settings.
I have view which lists all the domains (over relationship with user profiles, because each user has it's own domain), but I'm not able to display the logos for each domain.
Is it possible to get the domain logo in views?
Answer: I don't think you can do that with views only. You'll need to do some coding.
The point is that your logos are not linked to your Domains, but to your themes.
So you need to get your theme based on the domain_id, and then print the logo of the theme.
[EDIT]
If you look at the api of theme_get_setting, then you can see that you can pass as a second parameter the name of the theme you want the logo.
So it should be something like:
<code>$MY_THEME_ID = domain_theme_lookup($MY_DOMAIN_ID);
$logo = theme_get_setting("logo", $MY_THEME_ID);
</code>
Comment: I edited my answer, take a look at it.
Comment: Thank you! It needed some more coding, because domain_theme_lookup returns array with domain settings, but I got it working: $theme = domain_theme_lookup($row->domain_id);
$settings = unserialize($theme["settings"]);
return file_create_url($settings["logo_path"]);
Comment: Ok, I installed Views PHP modul and tried some coding. I tried theme_get_setting("logo") function but it returns logo of the active theme, not the logo of domain. Probably I need to run some code before this function? But I'm lost...
Comment: You guys should put the final code in one of your main posts. Maybe to Matts one, since he has pointed to the right direction? Great work by the way. :-)
Comment: hell ... I should learn to read post dates ... :-/ sorry ...


Proof that $\frac{e^x}{e^{\frac{x^2}{2}}} < 1+x$

Question:
For $0<x<1$, prove that $\dfrac{e^x}{e^{\frac{x^2}{2}}} < 1+x$ holds.

I've tried rewriting this in numerous ways, for example by multiplying the RHS with the denominator of the LHS, however nothing so far has given me a result or something I can work with.
Answer: The derivative of $\ln (1+x)-x+\frac {x^{2}} 2$ is $\frac 1 {1+x} -1+x=\frac {x^{2}} {1+x}$ which is positive. Hence this functinn is increasing. Since its value when $x=0$ is $0$ we get $\ln (1+x)-x+\frac {x^{2}} 2 >0$. Take exponential to complete the proof.
Answer: A possible approach would be to prove that
$$f(x)=e^{\frac{x^2}{2}} (x+1)-e^x$$ is positive if $x >0$.
Using Taylor expansion built at $x=0$, you would have
$$f(x)=\frac{x^3}{3}+\frac{x^4}{12}+\frac{7 x^5}{60}+\frac{7 x^6}{360}+O\left(x^7\right)$$ and, if you continue the expansion, you should notice that all coefficients are positive. This means that the inequality holds for any $x >0$.
Comment: Hi Claude ! All the best and good health in 2020 !


Problema com AJAX, PHP, MySQL select dependentes

Question: Boa tarde! Estou enfrentado um problema em linkar 2 select.
Já segui um monte de tutoriais, porém nenhum resolveu.
    <?php include ('conection.php'); ?>

Cidade Escolha

            <form class="text-center" method="get" enctype="multipart/form-data" action="">

                    <select class="form-control" id="estados" name="estados">
                        <option>Escolha seu Estado</option>
                        <?php

                            $query = "select * from estados;";
                            $dt = mysqli_query($conn, $query);

                            while ($row = mysqli_fetch_array($dt)){
                            ?>
                            <option value="<?php echo $row['estado_id'];?>"><?php echo $row['nome'];?></option>
                            <?php }; ?>

                    </select>
                    <select class="form-control" id="cidades" name="cidades">
                        <option value="">Escolha sua Cidade</option>
                    </select>
                    <input type="text" name="nome" placeholder="Nome">
                    <input type="submit" name="submit" placeholder="enviar">

            </form>

O arquivo de conexão com o banco de dados
<?php
$host = "localhost";
$user = "root";
$pas = "";
$banco = "brasil";
$conn = mysqli_connect($host,$user,$pas);
$db = mysqli_select_db($conn, $banco);
$charset = 'utf8';
mysqli_set_charset ($conn, $charset);  ?>

O código ajax
<?
include 'conection.php';

if(!empty($_POST['estado_id'])){
    $query = "SELECT * FROM cidades WHERE estado_id = ".$_POST['estado_id']." AND status = 1 ORDER BY nome ASC;";
    $dt = mysqli_query($conn, $query);
    $rowcount = mysqli_num_rows($dt);

    if ($rowcount >0) {
        while ($row = mysqli_fetch_assoc($dt)){
            echo '<option value="'.$row['cidade_id'].'">'.$row['nome'].'</option>';
        };

    }else{
        echo '<option value="">Cidade não Disponível</option>';
    }
    };
   ?>

Resultado:

Por favor me ajudem
Comment: acho que está faltando um `?` no `data:'estado_id='+estado_id`.Tenta colocar o `?` no inicio do `estado_id`. Como assim: `data: '?estado_id='+estado_id`.
Comment: Se você está enviando com post, não precisa concatenar assim `data:'estado_id='+estadoid,` basta usar assim: `data: {estado_id: estadoid},`. E existe uma forma mais 'limpa' de alimentar o select option utilizando o jquery
Answer: Boa tarde,
Encontrei um problema e vou passar o que e como consegui resolver e reescrevi com meu gosto de concatenar.

No retorno no ajax.php, altere na primeira linha o <?, para <?php ,
  quando você passa a abertura do PHP apenas como <? isso significa pro php a
  mesma coisa que um echo, por isso recebia o código todo como um
  retorno.
Nesse mesmo arquivo criei uma variável para receber esse retorno em string, ficando assim:

$str = '';
while ($row = mysqli_fetch_assoc($dt)){
    $str .= "<option value='{$row['cidade_id']}'>{$row['nome']}</option>";
};
echo $str;

para facilitar a leitura e visibilidade usei essa escrita de concatenar na criação
  das option dentro do while,

"<option value='{$id}'>{$nome}</option>";


estimation for n-th prime

Question: The famous theorem of Hadamard and Vallee-Poussin
https://en.wikipedia.org/wiki/Prime_number_theorem
implies that $p_n\sim n\ln n$, so $C_1 n\ln n \le p_n \le C_2 n\ln n$ holds for all $n\ge 2$ with some constants $C_1,C_2$.
Since $p_n\sim n\ln n$, we obviously have $C_1\le 1$.
I found somewhere in the internet (I don't remember the exact source) that $C_1=1$ and $C_2=29$ works fine.
How these values were derived?
Is $C_2=29$ optimal or a smaller value is known?
Answer: The lower bound, that $n \log n < p_n$ was proved by Rosser in 1938, and is sometimes called Rosser's Theorem.
For upper bounds, the indisputable expert is Pierre Dusart, who has several results revolving around explicit bounds related to the sizes of primes and collections of primes. He proved that
$$ p_n < n \log n + n \log \log n$$
for $n \geq 6$. In particular, $n \log \log n < n \log n$, so the bound $C_2 = 2$ should be fine for $n \geq 6$. If you are interested in particular for the bound holding for all $n \geq 2$, then it's just a matter of checking for $n \leq 5$. A quick numeric check indicates that $C_2 \approx 2.16405$ suffices for $n \geq 2$.
Comment: Also see Axler 2013, as well as both Dusart 2010 and Dusart 1999.  There is a range where each of Dusart 1999 p 14; Dusart 2010 pg 7; Dusart 2010 pg 2; and Axler 2013 Kor G  give the best results (Axler's is best for values over 8,009,824).

estimation for n-th prime


Build-Deploy-Test Workflow does not reach Test Agent

Question: at First im New to automated Tests with TFS, so i try actual many Things with try on Error.
But I Hope you can give me some Ideas What i perhaps do wrong.
I have set up a Environment in Microsoft Test Manager like described in serveral Blogs from MSDN. http://msdn.microsoft.com/en-us/library/hh873102.aspx#Prerequisites for example.
My Infrastructure is as follows: The Build Server and Test Controller are on the Same Machine (Win2012) but my Test Agent(Win2008R2) is an other Machine. Everything is TFS 2013 or VS 2013 Update 3.
I have a Build definition which builds the Tests on the Buildserver into a specified Dropfolder. This is working fine. And a Second Build Definition which uses the LabDefaultTemplate.11 for working with the Environment. Within i specified the Environment, the other Build Definiton a Deployment Script and also my Testplan with the associated Automated Tests.
But if i try to Start my Build-Deploy-Test Workflow i have got two outcomes.
First, without specifed a Deploment Script the Workflow Reaches Test Run and the Workflow became endless (It runs 16 Hours) then i aborted it.
And Second i specified the Deployment Script and now it seems i get the same but on the Deployment Step. I let it Run for almost 20 Minutes and i watched my Agent on VM Console.
All i saw is that he sometimes Disconnected for a short moment and then was Online again.
Now I'm Asking, why this Build Workflow could becomes endless?
The Tests would be CodedUiTests.
Here the Log of the last Run i stopped:
20:37 Overall Build Process
20:37 Application Deployment Workflow
00:00 Update Build Number
00:00 Get Build Details
01:00 If Build is needed
01:00 Do Build
00:00 Start Build Workflow
01:00 Wait For Build To Complete
00:00 Set Build Location
00:00 Get Build Location And Build Number
00:00 Compute build location needed
00:00 Compute build path
00:00 If user selected stored environment
00:00 Get Lab Environment Uri
00:00 Get Lab Environment
00:00 If Restore Snapshot
00:00 No Clean Snapshot
00:00 If Virtual Environment
00:00 If deployment or test needed
00:00 Wait For Environment To Be Ready
19:36 If deployment needed
19:36 Do deployment
00:00 Reserve Environment For Deployment
19:36 Deploy Build on Environment
19:36 Deploying Build
19:36 Run Deployment scripts
19:36 Run Deployment Task Deployment Task Logs for Machine: Win2008R2
00:00 Release Environment From Deployment

If you would need more specific informations please leave a Answer with the needed Things, and i will care about it, but i actual do not know what you could need and don't want to overfill this Question
Edit Dec 16th 2014:
Here the requested Details:
Deploying Build 00:30:00
Run Deployment scripts 00:30:00

Inputs
Values: Win2008R2TA02 | $(BuildLocation)\Uitest\deploymentScript.cmd $(BuildLocation)

Run Deployment Task00:30:00

Inputs
        UseRoleForDeployment: False
        MaxWaitTime: 00:30:00
        ThrowOnError: True
        BuildLocation: \\BuildServer\TFS Build\UiTest.Dev.Build\UiTest.Dev.Build_20141216.1
        LabEnvironmentUri: vstfs:///LabManagement/LabEnvironment/11
        DeploymentScriptDetails: Win2008R2TA02 | $(BuildLocation)\Uitest\deploymentScript.cmd $(BuildLocation)

The Deployment Script i found in the Internet, but i thought this could be working.
REM set build path
set buildlocation=%1

REM set deployment path
set targetdir="C:\deploy"

REM create deployment directory
if not exist %targetdir% (cmd /c mkdir %targetdir%)

REM copy build to the deployment directory
xcopy /c /y /e %buildlocation%\*.* %targetdir%

REM if you are using a deployment package you can run it here, after you copy it to your deployment directory

And i Call it as follows:
$(BuildLocation)\Uitest\deploymentScript.cmd $(BuildLocation)

In the Eventlog of the Test Controller there are some Errors Repeating while the Build is running:
Service Control Managar:

The Visual Studio Test Controller service terminated unexpectedly.  It
  has done this 1 time(s).  The following corrective action will be
  taken in 0 milliseconds: Restart the service.

.Net Runtime:

Application: QTController.exe Framework Version: v4.0.30319
  Description: The process was terminated due to an unhandled exception.
  Exception Info: System.NullReferenceException Stack:    at
  Microsoft.TeamFoundation.TestManagement.Controller.BuildDropDownloadManager.GetLocalSharePath(System.String)
  at
  Microsoft.VisualStudio.QualityTools.Controller.DeploymentTaskMonitor.IsUsingServerDrop(Microsoft.VisualStudio.TestTools.Execution.DeploymentTask)
  at
  Microsoft.VisualStudio.QualityTools.Controller.DeploymentTaskMonitor.ProvisionBuildSharePermision(Microsoft.VisualStudio.TestTools.Execution.DeploymentTask)
  at
  Microsoft.VisualStudio.QualityTools.Controller.DeploymentTaskMonitor.ProcessNewDeploymentTasks()
  at
  Microsoft.VisualStudio.QualityTools.Controller.DeploymentTaskMonitor.Poll(System.Object)
  at System.Threading.ThreadHelper.ThreadStart_Context(System.Object)
  at
  System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext,
  System.Threading.ContextCallback, System.Object, Boolean)    at
  System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext,
  System.Threading.ContextCallback, System.Object, Boolean)    at
  System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext,
  System.Threading.ContextCallback, System.Object)    at
  System.Threading.ThreadHelper.ThreadStart(System.Object)

I tried this solution but i does not helping and related to the Link i have no "Web Access" Folder to clear the Cache out.
https://social.msdn.microsoft.com/Forums/vstudio/en-US/c1ba09a8-5b8a-4c6d-8635-83085593647b/tfs-2013-deploy-to-testlab-is-failing-labdefaulttemplate11?forum=tfsbuild
I realy stuck on that Problem. Any Help would be very appreciated.
Answer: Ok, i found the issue.
The problem was a corrupt Visual Studio and MTM Installation on the Buildserver where also the TestController is installed.
If you stumble on this problem, try the following things.
 - Are all Components on the same Version (in my case 2013 Update 3) Check also Agent and Controller (in it's Configuration Dialog you find a About Button)
 - open the MTM on the Server and Check if it can switch between different testplans of the project (in m case that bring up an error, and thats why the Controller could not deliver the Cases to the Agent.)
if it is like in my case so try a uninstallation and reinstallation of Visual Studio and MTM
My order was to deinstall first MTM then VS after that install VS then MTM then the actual Update.
Answer: The build report log on visual studio is not that great. Have you checked the log on the tfs website? (build failed report -> diagnostics -> view log or on the website under builds -> definition -> diagnostics)
Have you set the timeout for the deployment script? 16 hours is a long time.
also can you link the deployment code to the script. Do you have any other tests that do run on the agent? Have you checked the login/password and deactivated the login screen on the agent because tfs has a problem accessing this.
Comment: Thanks for your Answer. I Checked the Log on tfs Website and there are nearly the same details as on the Build Report page, if you hit View Log. I checked also the inputs in the Step which fails (Run Deployment Task) and the parent one (Run Deployment scripts).

Yes i Have set the Timeout for Deployment but the 16 Hours was before i added Deployment Script cause i tried first without it.
Sidequestion, do i always need a Deployment script?

In the Situation i entered in this Company no Tests where running and now i try to get it to work, so no Tests working right now.
Comment: Sorry for Doublepost but i cant edit my Comment anymore.
Yes, the Agent is configured to login automaticaly and to ensure disabled Screensaver.
Comment: No you don't need a Deployment script. (can be usefull when you use snapshots) Have you tried to make a small test (for example open notepad...) and let it run on your system. If the basics fail its easier to find the problem. About the script, is it included in your visual studio project? (I use "$(BuildLocation)\Resources\Bat Files\Script.cmd" /Y) and this does work. And in your cmd file you use the %buildlocation%  and i do not know if this works. (have to test it myself...)  Just checking some things I had problems with.
Comment: Ok, i removed the Deployment Script, cause i actual not use snapshots and my target is to get it run first before it get complex. Trying this get me the result that it is still endless but it say it would "Run Tests" also telling me that:
The following Suite ID will be used to create the test run: 2579
The following test run was created: ID: 2661
and there it stucks. Event log from Test Controller seems quiet but at the Agent it says still:
"Unable to connect to the controller on 'BuildServer:6901'. Cannont communicate with the Controller due to version mismatch"
Comment: Cannot communicate with the Controller due to version mismatch means you might be running 2 different versions. can you verify this? the tfs version and visual studio version?
Comment: I Checked the Versions and found out that a Visual Studio on Test Controller Machine and also my Client on the Personal Machine where not Updated, but after Update and Reboot from both Machines it still wont running on the Agent. The Error Message of different Version is gone, and no new Messages came up. I haven't any idea what could be the Problem. Situation in the Build is like before, it stucked as it ment to do tests but the Agent Idle and also the Environment shows no Change in Status...


From local scrapy to scrapy cloud (scraping hub) - Unexpected results

Question: The scraper I deployed on Scrapy cloud is producing an unexpected result  compared to the local version.
My local version can easily extract every field of a product item (from an online retailer) but on the scrapy cloud, the field "ingredients" and the field "list of prices" are always displayed as empty.
You'll see in a picture attached the two elements I'm always having empty as a result whereas it's perfectly working
I'mu using Python 3 and the stack was configured with  a scrapy:1.3-py3 configuration.
I thought first it was in a issue with the regex and unicode but seems not.
So i tried everything : ur, ur RE.ENCODE .... and didn't work.
For the ingredients part, my code is the following :
    data_box=response.xpath('//*[@id="ingredients"]').css('div.information__tab__content *::text').extract()
    data_inter=''.join(data_box).strip()

    match1=re.search(r'([Ii]ngr[ée]dients\s*\:{0,1})\s*(.*)\.*',data_inter)
    match2=re.search(r'([Cc]omposition\s*\:{0,1})\s*(.*)\.*',data_inter)

    if match1:
        result_matching_ingredients=match1.group(1,2)[1].replace('"','').replace(".","").replace(";",",").strip()

    elif match2 :
        result_matching_ingredients=match2.group(1,2)[1].replace('"','').replace(".","").replace(";",",").strip()

    else:
        result_matching_ingredients=''

    ingredients=result_matching_ingredients

It seems that the matching never occurs on scrapy cloud.
For prices, my code is the following :
    list_prices=[]

    for package in list_packaging :
        tonnage=package.css('div.product__varianttitle::text').extract_first().strip()
        prix_inter=(''.join(package.css('span.product__smallprice__text').re(r'\(\s*\d+\,\d*\s*€\s*\/\s*kg\)')))
        prix=prix_inter.replace("(","").replace(")","").replace("/","").replace("€","").replace("kg","").replace(",",".").strip()

        list_prices.append(prix)

That's the same story. Still empty.
I repeat : it's working fine on my local version.
Those two data are the only one causing issue : i'm extracting a bunch of other data (with Regex too) with scrapy cloud and I'm very satisfied with it ?
Any ideas guys ?
Answer: I work really often with ScrapingHub, and usually the way I do to debug is:

Check the job requests (through the ScrapingHub interface)

In order to check if there is not a redirection which makes the page slightly different, like a query string ?lang=en

Check the job logs (through the ScrapingHub interface)

You can either print or use a logger to check everything you want trough your parser. So if you really want to be sure the scraper display the same on local machine and on ScrapingHub, you can print(response.body) and compare what might cause this difference.
If you can not find, I'll try to deploy a little spider on ScrapingHub and edit this post if I can manage to have some time left today !
Comment: Okay it was very simple. It was only the python 3.6 stack which wasn't launching. It was no coding issue or scraping difficulty. Just the stack.
Comment: Thansks for your input. Request seems ok. No language issue so far.
One thing. I'm using python3 locally and whereas I used this in yml `stacks:
  default: scrapy:1.3-py3`the log is showing me a 2.7 setup.
Concerning the response.body, it seems okay and comparable. We are just having an "encoding issue". Scrappy hub is displaying some unicode character but it shouldn't be a problem from regex.
Comment: Sewake would you have any other idea to solve this headaches giving issue ?
Comment: Mhh if you don't see anything strange in response.body right now I don't have many ideas... If we focus on the first field, what is output of `data_inter` ? Is it what you expect ?

The encoding issue could be the reason why, because of the `é` accent of `Ingrédient` and `€` special character of price field.

(Sorry I didn't had time to look in more detail)
Answer: Check that Scrapping Hub's logs are displaying the expected version of Python even if the stack is correctly set up in the project's yml file.


Hypothesis Testing: Is a Tool Better Than Random?

Question: I am testing a tool that tries to select the correct outcome. I am trying to do significance testing to see if the tool is better then choosing the outcome at random.
It picks from 4 categories, and I have a list of the correct category, and the one the tool picked.
What test should I use?
Answer: Consider that you're interested in whether the proportion of times correct is greater than the proportion you'd reasonably get under random guessing (presumably with equal probability on each outcome).
With 4 outcomes therefore, the chance you get it by random guessing would be $\frac14$. Assuming independence of trials, the number of correct guesses under the null hypothesis would be $\text{binomial}(n, \frac14)$, where $n$ is the number of trials (attempts at guessing); this leads to a binomial test (see the example at the link involving testing whether a die rolls too many 6's, at heart the same problem as yours with a different number of outcomes).
If $n$ is large you could use a normal approximation (leading to the typical one-sample proportions test covered in a non-mathematical introductory stats text), but more generally you can base a test directly off the binomial.
Presumably from the way the question was phrased, you seek a one-tailed test.
[Alternatively, in place of the normal approximation to the binomial, you could perform a chi-squared goodness of fit test (two outcomes, with probabilities 1/4 and 3/4 under the null), but this would prevent doing a one-tailed test.]
Comment: It depends on what exactly "random guessing" means. Consider the case where the 4 categories are imbalanced, & you want to include that information. I might see if the OP can form a confusion matrix (cf., [How to calculate information included in R's confusion matrix](https://stats.stackexchange.com/a/253435/7290)).
Comment: Presumably yes, but it's worth clarifying (IMO).
Comment: I agree with the point (indeed my answer hints at this issue in the first sentence). Nevertheless, I expect (as stated in my answer) that the OP intends the random choice of outcomes to be with equal probability.


Are these 3 summation expressions equivalent?

Question: $$\sum_{i=1}^{n}f(i)+k = \sum_{i=1}^{n}\{f(i)+k\} = k+\sum_{i=1}^{n}f(i) $$
I'm more confused about the working of expression:
$$\sum_{i=1}^{n}\{f(i)+k\}$$
Are all the 3 expressions equivalent?
Comment: In the first expression put the parentheses to make it more easily understandable: is it $$\sum_{i=1}^n f(i)+k = \sum_{i=1}^n (f(i)+k)? $$
Answer: Nope. But these are:$$\sum_{i=1}^{n}f(i)+nk = \sum_{i=1}^{n}\{f(i)+k\} = nk+\sum_{i=1}^{n}f(i) $$
If you're summing a constant $n$ times, you need to multiply it by $n$ if you want to bring it outside the summation
Comment: None of the above expressions in the question are equivalent?
Comment: @Sidsec9 No, because there is no $n$ in front of $k$. I mean you can try it yourself, take $f(i) = i$, $n=2$, $k=3$ and see if the results are the same
Answer: The second and third are different.  The second one is
$$\{f(1)+k\}+\{f(2)+k\}+\{f(3)+k\}+...$$ which contains $n$ lots of $k$, so it equals $kn+\sum_{i=1}^nf(i)$.
The first one is ambiguous; I am not certain whether the sum includes $k$ within its scope, so it is equal to either the second or third one.
Comment: I understand what you do there, but I think it's better to avoid writing a sum of sets: $\{a\}+\{b\}$ is neither $a+b$ nor $\{a+b\}$ (though there are of course canonical bijections between these objects)


Magento - Move cart dropdown plugin to top.links. Reference name="top.Links" not changing location

Question: A cart dropdown plug-in I'm using has the following XML and I'm having trouble moving it to top links.
<?xml version="1.0"?>
<layout version="0.1.0">
    <default>
        <reference name="head">
            <action method="addCss"  ifconfig="cartdrop/general/enabled"></action>
            <action method="addJs"  ifconfig="cartdrop/general/enabled"></action>
            <action method="addJs"  ifconfig="cartdrop/general/enabled"></action>
        </reference>

     <reference name="top.container">

<block type="core/template" name="cartheader_sidebar" template="cartdrop/cartheader.phtml">
    <block type="checkout/cart_sidebar" name="cart_sidebar" template="checkout/cart/sidebar.phtml" before="-">
        <action method="addItemRender"><type>simple</type><block>checkout/cart_item_renderer</block><template>checkout/cart/sidebar/default.phtml</template></action>
        <action method="addItemRender"><type>grouped</type><block>checkout/cart_item_renderer_grouped</block><template>checkout/cart/sidebar/default.phtml</template></action>
        <action method="addItemRender"><type>configurable</type><block>checkout/cart_item_renderer_configurable</block><template>checkout/cart/sidebar/default.phtml</template></action>
        <block type="core/text_list" name="cart_sidebar.extra_actions" as="extra_actions"/>
    </block>
</block>

        </reference>
    </default>
</layout>

I've tried changing the reference name to reference name="topLinks" and reference name="top.Links"
I've also tried copying the block and pasting it in local.xml under <reference name="top.links">  and putting it in page.xml but to no avail.
Answer: It should be <reference name="top.links"> as the attribute said -> reference NAME
The problem why it is not displayed is:
- Look at the definition of top.links -> <block type="page/template_links" name="top.links" as="topLinks"/>
- Then go to Mage/Page/Block/Template/Links.php
class Mage_Page_Block_Template_Links extends Mage_Core_Block_Template
{
    ...

    protected function _construct()
    {
        $this->setTemplate('page/template/links.phtml');
    }

    ...
}

Now we know that top.links extend from core/template.
For those blocks which extend from core/template require a template (simple isn't it),
it will display everything inside the template (in your case, the template is page/template/links.phtml)
For a template, to be able to render its child, it should explicitly call getChildHtml
<?php echo $this->getChildHtml(); ?> -> will render all child under it
<?php echo $this->getChildHtml('cartheader_sidebar'); ?> -> will render child with alias/name cartheader_sidebar
It means if you want cartheader_sidebar to be displayed in top.links, you need to put <?php echo $this->getChildHtml('cartheader_sidebar'); ?> in page/template/links.phtml
PS: I don't check your layout, I assume it is already correct
Answer: Layout XML:
 <block class="Magento\Framework\View\Element\Html\Link" name="cart-link" template="Magento_Theme::cart_link.phtml">
            <arguments>
                <argument name="label" xsi:type="string" translate="true">Cart</argument>
                <argument name="path" xsi:type="string" translate="true">#/</argument>
            </arguments>
        </block>

And:
    <move element="minicart" destination="cart-link" />

cart_link.phtml:

My Cart
 <?php echo $block->getChildHtml('minicart');?>


Callbacks em JavaScript

Question: Gostaria de entender uma coisa sobre callbacks! Sei que existe outros tópicos sobre o assunto, mas o meu é uma dúvida simples e que não está clara pra mim ainda.
Por exemplo, vamos supor que tenho esse array:
['Banana', 'Maçã', 'Melancia']

Pra percorrer o mesmo eu vou usar o forEach com uma função e vou exibir com console.log

const minhaArray = ['Banana', 'Maçã', 'Melancia'];

function impri(nome, indice){
  console.log(`${indice + 1}. ${nome}`);
}

minhaArray.forEach(impri);

O callback no caso, é somente a função impri ou o callback é tudo em conjunto? A função impri junto da array e do forEach?
Answer: Callback ou Callback function é a função que é passada a outra função, e que irá ser chamada mais tarde, quando necessário.
Confirme a definição de Callback function no MDN
Por isso no seu exemplo, o callback é a função impri, pois é ela que é passada ao forEach.
Answer: O conceito de callback é mais habitual em casos assíncronos. É possível dizer que impri é a callback, se bem que o conceito em si é mais comum em processos assíncronos, porque é a função que é passada como argumento e vai ser chamada de volta.
Neste caso, para responder à tua pergunta: impri é a callback, a função em si e não o conjunto onde ela é usada.

Callbacks em JavaScript


JavaScript: Print HTML Form Values onChange

Question: I'm trying to echo out the value of the chosen value out of the form drop down box (named sets) once it has been selected. At the moment, I'm having no luck. Also to note I am using codeigniter but I dout this will be the problem.

New Entry

<?php

echo form_open('log/add_entry');

/*Weight Entry*/
echo form_label('Weight:', 'weight');
echo form_input('weight');

/*Weight Measurement*/
$measurementOptions = array('kg' => 'KG', 'lbs' => 'LBS');
echo form_dropdown('measurement', $measurementOptions, 'kg');

echo " - ";

/*Sets at Weight*/
echo form_label('Sets:', 'sets');
$setOptions = array('' => '', '1' => '1', '2' => '2', '3' => '3', '4' => '4', '5' => '5', '6' => '6', );
$js = 'onChange="set_boxes(this.form);"';
echo form_dropdown('sets', $setOptions, '', $js);

Answer: A few possibilities:
Your function and its call aren't consistent with each other:
onChange="set_boxes(this.form)" // 1 argument

function set_boxes()            // 0 arguments

I think what you want is this:
function set_boxes(form)

With that, the form variable within the function will equal the expected DOM object:
var TestVar = form.sets.value;

Also, did you mean to alert the string "TestVar"? If you want to alert the value of the variable, just drop the quotes:
alert(TestVar);

So, give this a try:
function set_boxes(form)
{
    var TestVar = form.sets.value;
    alert(TestVar);
}

Answer: For select boxes, you can't just use .value It's a little more complicated. This should be what you want:
var TestVar = form.sets.options[form.sets.selectedIndex].value;


How can we prove $\sum_{p\leq x}\ln(p) < 2x$?

Question: I've been reading this paper for Merten's second theorem. Every thing is just fine but I think that theorem 11 (3.5.2) can have an easier proof.
Is there any better approach or an explanation that why that $\ln([x]!)$ can be written in the form of those thetas.
Comment: You can also use some insights from [here](https://math.stackexchange.com/questions/2665439/showing-prod-limits-p-leq-x-p-e1-epsilon-x-and-prod-limits-p-le/).
Answer: It was well-known that the divisor sum of von Mangoldt function $\Lambda(n)=[n=p^k]\log p$ is logarithm:
$$
\sum_{d|n}\Lambda(d)=\log n
$$
Using identities of logarithm, we have
$$
\begin{aligned}
\log\lfloor x\rfloor!
&=\sum_{n\le x}\log n=\sum_{n\le x}\sum_{d|n}\Lambda(d) \\
&=\sum_{qd\le x}\Lambda(q)=\sum_{n\le x}\Lambda(n)\sum_{m\le x/n}1 \\
&=\sum_{n\le x}\Lambda(n)\left\lfloor\frac xn\right\rfloor
\end{aligned}
$$
Now, if we gather all the prime powers, then
$$
\log\lfloor x\rfloor!=\sum_{p\le x}\left(\sum_{k\ge1}\left\lfloor x\over p^k\right\rfloor\right)\log p
$$
By exchanging summation order, we have
$$
\begin{aligned}
\log\lfloor x\rfloor!
&=\sum_{k\ge1}\sum_{p\le x}\left\lfloor x\over p^k\right\rfloor\log p=\sum_{k\ge1}\sum_{p\le x}\sum_{m\le x/p^k}\log p \\
&=\sum_{mp^k\le x}\log p=\sum_{m,k\ge1}\sum_{p\le\sqrt[k]{x/m}}\log p \\
&=\sum_{m,k\ge1}\vartheta\left(\sqrt[k]\frac xm\right)
\end{aligned}
$$
where $\vartheta(x)=\sum_{p\le x}\log p$.
Comment: Seems like that your first line has a little problem.There should $d$ as the input of the Mangoldt function. Can I you please correct it so others can go through reading it more confidently ?
Comment: @ParsaNoori Edited. Thanks for pointing that out
Comment: You're welcome. Forgot to say that it's on the second mathematical line too.
Comment: @ParsaNoori Edited again, thanks for that one :D