Prós e contras de uma aplicação web 100% HTML/JavaScript

Question: Estou seriamente pensando de desenvolver uma aplicação web, utilizando somente HTML/JavaScript no client-side para ganho de desempenho e pelo qual, toda e qualquer comunicação necessária com o servidor seja feita através de requisições a um WebService (lá sim, conterá minha regra de negócios).
Gostaria que citassem (tecnicamente) os prós e contras desta técnica.
Comment: Esse tipo de pergunta vai ter muita resposta baseada em opiniões, mas pode existir uma parte técnica mais profunda, caso você deixe a pergunta um pouco mais "fechada" a questões técnicas, tente dar uma melhorada no texto da pergunta. (:
Comment: Iago, sugiro a mudança do título. Não sei se "Aplicação 100% HTML/Javascript" passa a ideia correta. Talvez ficasse melhor: "Prós e Contras de uma Aplicação de Página Única (Single Page Application)".
Comment: Mais uma coisa: reabri a questão porque depois da edição ela ficou melhor. É possível responder objetivamente prós e contras desta técnica. As respostas abaixo soam estranho por começarem com "No meu ponto de vista" e "Na minha opinião", o que ocorreu porque a pergunta não estava tão bem formulada, mas ainda assim acrescentaram algumas informações pertinentes.
Answer: Obviamente todos os prós e contras dependem não só da técnica utilizada, mas também da implementação real.
Prós

Melhor experiência do usuário respondendo mais rápido e sem quebras no fluxo da informação. O usuário não vê o mecanismo funcionando.
Redução de carga do servidor que não precisa "renderizar" as páginas, só trabalha com os dados.
Menor volume de dados trafegados (na maioria dos casos não muita diferença). Costuma haver um ganho perceptível de performance.
Há um desacoplamento maior entre o que está no servidor e o cliente. Dá mais liberdade ao designer. Eventualmente pode aumentar a segurança.

Contras

Obviamente a exigência do JavaScript (ou outra linguagem) funcionando corretamente.
Problemas com SEO (não, o fato do Google interpretar JS, não resolveu o problema).
É comum ter mais brechas de segurança expondo coisas que não deveria (XSS principalmente). A exposição pode causar outros problemas também.
Uma aplicação dessas rodando muito tempo no navegador pode ser devoradora de recursos, principalmente se houver vazamento de recursos, o que é comum.
Há casos que precisa duplicar código do servidor no cliente.
A carga inicial pode ser maior e causar frustração (UX ruim).
Não é simples fazer corretamente.

Existem algumas coisas que as pessoas reclamam que não são problemas mais.
Obviamente posso ter esquecido alguma coisa.
Coloquei no GitHub para referência futura.
Answer: Prós :

WebDesigners tem grande facilidade com essa arquitetura.
Sua aplicação é facilmente integrada com outros sistemas. Pois assim você obrigatoriamente tem que criar uma API para conectar com seu frontend. Logo é possível criar múltiplos frontends,
Facilidade para testes unitários.

Contras :

Duplicidade de Validações. Mais do que nunca, você precisa desenvolver validações do lado do servidor e do lado do cliente. Nunca confie em uma validação que está apenas do lado do cliente.
Cuidado com frameworks Javascript que ainda estão em estágio de amadurecimento, podem gerar retrabalho.
Answer: Havia cometido um equívoco de interpretação da pergunta, por isso resolvi reestruturar minha resposta. Espero que ajude na solução de sua dúvida.
Prós:

Centralização do acesso à fonte de dados o que facilita à analise de uso, performance.
Fácil manutenção/atualização do da parte pública da aplicação
Compartilhamento de código

Contras:

Sobrecarga de processamento
Arquitetura bloqueante, uma vez que um processamento que utiliza recursos compartilhados espera um processo dependente finalizar antes de inicializar outro.
Dificuldade para equiparar o comportamento visual em todas as plataformas e dispositivos.
Alto acoplamento/dependência à internet.

Um Abraço.
Vinicius
Comment: Obrigado Luiz. Sou novo por aqui, e estou com dificuldades pra aprender a utilizar esta plataforma. Quando iniciei minha carreira, tive grande ajuda desta comunidade, e gostaria de retribuir à esta ajuda, contribuindo com aqueles que estão passando pelo que passei, Por isso qualquer dica(links , artigos) será bem vinda para aprender a gerar conteúdos de qualidade. Obrigado!
Comment: Olá, Vinicius. Bem-vindo ao [pt.so]! Eu sei que o título da pergunta fala de HTML e JavaScript, mas a questão na verdade está pedindo os prós e contras de se fazer um sistema assíncrono, assim como é o Gmail e outras aplicações que não atualizam a página, acessando todas as informações via web services.
Answer: No meu ponto de vista essa é a melhor maneira de se trabalhar na Web, pois a maioria dos outros modelos de trabalho, trafegam HTML do server pro client e isso não faz muito sentido. Dessa forma você tem um ganho de performance, trafegando somente dados necessários.
Trabalhando dessa forma você pode aproveitar seu código de front e empacotar ele com phonegap, assim criar web apps sem tem que programar novamente.
Para questão de SEO como o Afonso sitou existem ferramentas ou modos de trabalho que te ajudam nisso. Por exemplo caso você use Angularjs que é algo que realmente complica o SEO, você pode utilizar o Prerender (https://prerender.io/), que ajuda você no SEO.
Eu particularmente não vejo contras em trabalhar dessa forma.
Answer: Prós:

Sem dependência do Framework ou biblioteca;
Fácil manutenção;
Código simples;
Absorção maior do conhecimento característico sobre a linguagem.

Contras:

Códigos verbosos
Aumento na estrutura da aplicação
Reinventar a roda;
Retrabalho se não for bem estruturado.


prove that $A^n$=$0$ for some integer $n$

Question: Suppose that, $A$ is a square matrix of order $n$ such that $a_i$$_j$$=$$0$ for $i$$\geq$$j.$
Prove that,$A^n$=$0$.
Comment: What can you say about the shape of $A^k$? Look at an example to see what exactly is going on, then prove that stronger fact, perhaps by induction.
Comment: Is the use of $n$ as both the order of the matrix and the exponent in the equation $A^n = 0$ purposeful?
Comment: yeah...may b...
Answer: Hints:
One way is to employ of Cayley-Hamilton theorem: $A$ is an upper triangular matrix with diagonal $0,$ hence with the characteristic polynomial$=(-x)^n.$
Another is by induction: show that, if $A^m=(a^{(m)}_{ij}),$ then $a^{(m)}_{ij}=0, \forall i\ge j-m+1, $ for $m\ge1.$
Maybe there are other ways around; here are only two of them.
Answer: Let $e_i$ be the canonical basis of $\mathbb R^n$ (or whatever field you're working with). Then $Ae_1=0$; $Ae_2= a_{12} e_1$ and so $A^2e=0$; $Ae_3=a_{13} e_1 + a_{23}e_2$ and so $A^3e_3=0$, etc. and so $A^n e_i=0$ for all $i$, which means $A^n=0$.
Answer: Proof I. The characteristic polynomial of $A$ is
$$
p_A(\lambda)=\det (A-xI)=
\det\,\left(\begin{matrix}
-x & a_{12} & a_{13} &\cdots & a_{1n}\\
0 & -x & a_{23} & \cdots & a_{1n}\\
\vdots & \vdots &\vdots& & \vdots \\
0 & 0 & 0 & \cdots & -x
\end{matrix}\right)=(-x)^n,
$$
which due to Cayley-Hamilton Theorem implies that $A^n=0$.
Proof II. One can show that, if $A^2=(A^2_{ij})$, then $A_{ij}^2=0$ if $i+2\ge j$, and inductively that if $A^k=(A^k_{ij})$, then $A_{ij}^k=0$ if $i+k\ge j$, and hence $A^n_{ij}=0$, for all $i,j$.
Answer: HINT: what are the eigenvalues of this matrix?
Comment: 0...So then? What can be said about A^n?


Calling .parseInt() on something that can't be parsed - JavaScript

Question: I have an array of strings.
a = ['1', 'car', '2'];

I want to parse only the parsable elements, my objective is:
a = [1, 'car', 2];

How can I do that?
What does it happen when I try to parse a[1] ?
Comment: `What does it happen when I try to parse ...` - You could have tried that yourself
Comment: use `isNaN`. that function checks if the input is not a number
Comment: really? that's a pretty useful answer
Comment: Like @Mouser suggests: use a loop and isNan
Comment: Before you accept an answer, why don't you check it and make sure it actually does what you are asking. The one you accepted does not. It does not even create an array. The object it does create does not contain the non-numeric values.
Answer: Try
a.map(function(x) { return +x || x; })

+x will try to convert the value to a number, and return NaN if it fails. That is falsy, and cause the RHS of the || to be evaluated, returning the original value.
However, this will fail on '0', so you need to do
a.map(function(x) { return isNaN(x) ? x : +x; }

It's a bit more compact in ES6 environments:
a.map(x => isNaN(x) ? x : +x);

Comment: `+'0'` is falsy but definitely a parsable number.
Answer: Since the purpose of the question has become more clear now, an edit:

     var a = ["1", 'car', 2];
     a = a.map(function(element) {
       //check if element is a number and not NaN or empty string
       if (!isNaN(element) && element != "") {
          return parseInt(element, 10);
       }
       else
       {
          return element;
       }
     });

     document.body.textContent = a;

This will traverse your array. Testing if the array element is a number, if so transform the number if possible. I'm using Array.prototype.map for this. Please note that this only filters integers. If you want to filter floats use parseFloat. That will parse integers and floats.
Comment: Be careful with this method and empty strings. `!isNaN("")` resolves to true, which is unexpected
Comment: You don't need `isNan(parseInt(element))`; `isNaN(element)` will work fine byitself. Anyway, he doesn't want to filter the array, he wants to convert to numbers where possible.
Comment: @torazaburo, still this now map the integers, converting strings to integers where possible and skipping values that are not
Comment: Must be missing something. Your solution doesn't transform or replace anything, it just counts the numbers in the array. If that's all you wanted to do, it could be just `a.length - a.filter(isNaN).length`.
Comment: @torazaburo It isn't entirely clear what the OP wants parsed. Should the array contain only numbers or should all items that can be converted to a number be converted and the rest left untouched?
Comment: You don't need `isNaN(parseInt(...`, just `isNan(element)` will do fine.
Comment: @camiblanch, thank you, updated this to reflect your comment.
Answer: For this you have to loop for each value and check the parse int or not. Here is sample example and create another array.
var count_a = {};
for(var i=0; i<a.length;i++)
    {
        if (!isNaN(a[i]))
        {
           count_a[i] = parseInt(a[i], 10);
        }
        else { count_a[i] = a[i] }
    }
    a = count_a

or as first link below you can try this. whenever you want to use of array element.
var a = ['1','2','3'];
var result = a.map(function (x) {
    return parseInt(x, 10);
});

How to convert all elements in an array to integer in JavaScript?
Parsing every element of an array as an integer
Comment: will a become   [ 1,  'nan', 2 ] ?
Comment: no, will be ['1','2']. if you wish 'car' index shoulb be there , so you can add '0' when if condition not satisfy.
Comment: I think you mean `if (!isNaN...)` (note `!`).
Comment: You are using object, not an array. Why?
Comment: I wonder if you tested this. It will create an object `count_a` which contains values only for numeric entries. That's not what the OP said he wanted.
Answer: Array construction:
a[0] = 1;
a[1] = 'car';
a[2] = 2;

You need an indexed array.


Sys.WebForms.PageRequestManager.getInstance();

Question: I am trying to call a JavaScript function after asp:UpdatePanel. The following solution works fine for IE 8 and above, but throws exception for IE 7.
<code>var prm = Sys.WebForms.PageRequestManager.getInstance();

                prm.add_endRequest(function () {
                    DoJobOne();
                    DoJobTwo();
                });
</code>
Exception: Unable to get property 'PageRequestManager' of undefined or null reference
I tried adding the App_browser from NuGet. Still the problem exists. Any work around to load javascript post UpdatePanel?
Thank you in advance :)
Answer: Here is the solution, might be helpful for others.
<code>    $(function () {
       DoJobOne();
       DoJObTwo();
   });

   function pageLoad(sender, args) {
       if (args.get_isPartialLoad()) {
           DoJobOne();
           DoJObTwo();
       }

   }
</code>


Approximation of reals by rationals

Question: Is this fact true:
For all real $\alpha$, and natural numbers $n$, there exists some $a, q$ with $n^{2/3} \le q \le n$ and $(a, q) = 1$ such that $\left\lvert\alpha - \frac{a}{q}\right\rvert \le \frac{1}{q^2}$. It should be true in most cases, but I am unsure what those cases are.
Comment: Check for "Liouville Criterium" and "transcendence degree"
Answer: It is wrong for rational $\alpha$. In fact for $\alpha=0$ you demand that $|a|\le \frac1q$, and that is only possible if $a=0$ and $q=1$ (as $\gcd(a,q)=1$), so there is no solution for $\alpha=0$ and $n> 1$. More generally, if $\alpha=\frac uv\in\mathbb Q$ with $\gcd(u,v)=1$, then $|\alpha-\frac aq|=\frac{|uq-av|}{vq}\ge \frac1{vq}$ unless $\frac aq=\frac uv$ (and henec $q=v$). This is $>\frac1{q^2}$ as soon as $q>v$. Hence for large $n$, no solution exists.
If $\alpha$ is irrational, consider the set $$A=[\alpha,\alpha+1]\cap\bigcup_{k=1}^n \frac1k{\mathbb Z}$$ of fractions "slightly above" $\alpha$ and having denominator $\le n$.
The set $A$ is finite (contains at most $k$ elements of $\frac1k\mathbb Z$) and is nonempty because  $\lceil\alpha\rceil\in A$. Let $\frac ab$ be the smallest element of $A$. Since $\gcd(a,b)=1$ there exist integers $d,c$ with $ad-bc=1$. With $(c,d)$ also $(c\pm a,d\pm b)$ is such a pair. Therefore let $(c,d)$ be such a pair with $d\le n$, but as large as possible, i.e. $d+b>n$. By minimality  of $\frac ab$ we conclude $\frac cd<\alpha$.
From $$\frac ab-\frac cd=\frac{ad-bc}{bd}=\frac1{bd}<\max\left\{\frac1{b^2},\frac1{d^2}\right\}$$
we see that one of $\frac ab$, $\frac cd$ is a good approximation to $\alpha$ with denominator $\le n$.
But is the denominator $\ge n^{2/3}$?
In general, no. Especially by considering numbers with rapidly growing continued fractions, we can construct $\alpha$ that has infinitely many good approximations, but their  denominators grow too fast for the $\n^{2/3}\le q\le n$ constraint.
Comment: Can you elaborate? I don't understand why it doesn't work for rationals.

Approximation of reals by rationals


Checkstyle ConstantName rule kicks in for things that are not really constant

Question: I would like to check that my field names are uppercase only for fields that meet my preferred definition of "constant", as stated in Google's Java Coding Guidelines.
Thus:
private static final integer NUM = 1974;  // is a constant
private static final String NAME = "Freddie"  // is a constant

private static final Map<String, String> myMap = new HashMap<>();  // is NOT a constant
private static final Logger myLogger = LogManager.getLogger();  // is NOT a constant

Is it possible to specify a rule that requires uppercase naming only if the type is a primitive type or a final reference to a String or other immutable class?
Answer: Not really.  Checkstyle would have to execute the code.  For instance, private static final Map<String, String> myMap = Map.of("One", "Blue", "Two", "Red"); is an immutable value.
One thing you can do is tell Checkstyle that it should not enforce the naming scheme on private fields:
<module name="ConstantName">
    <property name="applyToPrivate" value="false"/>
</module>

Another option is to specify the permitted names:
<module name="ConstantName">
    <property name="format"
        value="^([A-Z][A-Z0-9]*(_[A-Z0-9]+)*|myMap|myLogger)$"/>
</module>

Comment: Thanks. That's probably the best we can do for now. I'll wait and see if there are any other answers before accepting yours. It would have been nice if checkstyle at least recognised some well-known immutable classes and treated those as constant and did not apply the rule when it wasn't certain whether a class was immutable. Especially given the definition of "constant" by Google Coding Guidelines and many other popular guidelines.


Colocar popup apenas 1x a cada 24h por usuario

Question: Estou tentando manipular o cookies aqui com javascript, to tentando colocar, que so  exibe o popups uma vez a cada 24h por usuário,  porem ele ta aparecendo toda hora que entro na página.
Aqui o meu código, onde estou errando? Minha lógica está errada ?
function checkLoading(e){
    d = new Date();
    document. cookie = "visto= true; expires = " + d.toUTCString() + ";path=/";
    d.setDate(d.getDate() + 1*24*60*60);

    if ( popupFormSubmitting == true ) {
        if(document.cookie == null){
            signupFormLoader.style.display = 'block';

        }
    }else{

        signupFormLoader.style.display = 'none';
    }
}

Answer: Não está de total errado a sua maneira de manipulação, mas seria melhor você fazer de uma maneira mais simples como esta:
if (document.cookie.indexOf("popupShown=true") == -1) {
    document.cookie = "popupShown=true; max-age=86400"; //86400: segundos em um dia
    // Faça o restante logo aqui abaixo
}

Sendo assim, após o cookie vencer (Depois dessas 24H), na próxima vez que a página carregar o popup irá aparecer! Veja direitinho na documentação do cookie para tirar demasiadas dúvidas ou deixe o comentário aqui caso haja mais dúvidas sobre o mesmo! :)

Já que o código anterior não funcionou com você, vamos tentar algo diferente... Segundo esta reposta no Stack, você deve fazer desta maneira para que possa realmente definir/ler o seu cookie pelo JavaScript e adaptando para o que deseja:
function createCookie(name,value) {
    var date = new Date();
    date.setTime(date.getTime()+(3600*24));
    var expires = "; expires="+date.toGMTString();
    document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

E uma vez feito isso, você basta adicionar isto:
jQuery(document).ready(function() {
    var visto = readCookie('visto');
    if (!visto || visto !== "true") {
        createCookie('visto', "true");
        // Código do popup e demais códigos aqui
    }
});

Comment: A função createCookie só admite dois parâmetros. Você está chamando-a com três. Pelo que entendi, o correto na declaração da função seria `function createCookie(name,value, expireDays)` E na linha do date.setTime fazer:  `date.setTime(date.getTime()+(expireDays*3600*24));`. Inclusive, é uma boa prática fazer `const MILLISECONDS_IN_A_DAY = 86400000` e reutilizar essa constante ao invés de usar a opção "hardcode" de fazer `3600*24`, digitando o valor diretamente. Seguindo essa recomendação, teríamos: `date.setTime(date.getTime()+(expireDays*MILLISECONDS_IN_A_DAY));`
Comment: não foi, o codigo não deu certo.
Comment: Eu implementei em minha prévia resposta outra solução, se puder tentar! :)
Answer: Pode usar LocalStorage (LS), que também é um cookie. Basta você guardar no LS o valor primitivo da data atual e criar outra data adicionando +24 horas à data atual e depois fazer a comparação. Se o LS não existir mostra a popup e define o seu valor +24 horas. Se existir, faz a comparação, se for menor mostra a popup e redefine o tempo.
Considerando que o id da sua popup seja #popup, tipo:

  CONTEÚDO DA POPUP

Esconda a div da popup no CSS:
#popup{ display: none }

E ficaria assim toda a função:
document.addEventListener("DOMContentLoaded", function(){

   // pega o elemento da popup
   var popup = document.getElementById("popup");

   // atribui o LS a uma vaviável
   var ls = localStorage.getItem("popup");

   // pega a data atual
   var data = new Date();

   // variável para guardar a data atual
   var data_atual = data.valueOf();

   // adiciona 24 horas à data atual
   var data24 = data.setHours(data.getHours()+24);

   // verifica se o LS é menor do que a data atual
   // ou se o LS for inexistente
   if(ls < data_atual){

      // mostra a popup
      popup.style.display = "block";

      // cria/redefine o LS com o nome "popup" com a data +24 horas
      localStorage.setItem("popup", data24);

   }

});

Teste de 5 segundos:
Como aqui no sandbox o LS não funciona, altere a linha:
var data24 = data.setHours(data.getHours()+24);

Para
var data24 = data.setSeconds(data.getSeconds()+5);

Faça reload na sua página dentro dos 5 segundos e verá que a popup não irá aparecer. Após 5 segundos ela irá aparecer 1 vez, e assim sucessivamente.

Vou deixar abaixo o código enxuto sem comentários:

document.addEventListener("DOMContentLoaded", function(){
   var popup = document.getElementById("popup");
   var ls = localStorage.getItem("popup");
   var data = new Date();
   var data_atual = data.valueOf();
   var data24 = data.setHours(data.getHours()+24);

   if(ls < data_atual){
      popup.style.display = "block";
      localStorage.setItem("popup", data24);
   }
});


How to get Text coordinates using PyUNO with OpenOffice writer

Question: I have a python script that successfully does a search and replace in an OpenOffice Writer document using PyUNO. I wanna to ask how to get the coordinate of found text?
import string
search = document.createSearchDescriptor()
search.SearchString = unicode('find')
#search.SearchCaseSensitive = True
#search.SearchWords = True
found = document.findFirst(search)
if found:
    #log.debug('Found %s' % find)
    ## any code here help to get the coordinate of found text?
    pass

Comment: What do you mean by "coordinates"?
Position of text in a document depends on page/char sizes and other facts (screen/print resoltuion).
What would you like to do with such values?
Comment: purpose question is that I want to add a 'specified' text in odt file, and detect this text's postion for page size adjusting.
Answer: This is some StarBASIC code to find the page number of a search expression in a Writer document:
SUB find_page_number()

oDoc = ThisComponent
oViewCursor = oDoc.getCurrentController().getViewCursor()
oSearchFor = "My Search example"

oSearch = oDoc.createSearchDescriptor()
With oSearch
   .SearchRegularExpression = False
   .SearchBackwards = False
   .setSearchString(oSearchFor)
End With

oFirstFind = oDoc.findFirst(oSearch)

If NOT isNull(oFirstFind) Then
    oViewCursor.gotoRange(oFirstFind, False)
    MsgBox oViewCursor.getPage()
Else
   msgbox "not found: " & oSearchFor
End If

Hope this helps you


Distribution Group Owner Management Exchange PowerShell

Question: In an Exchange 2010 (version 14.3 Build 123.4) environment, how do you add a new user to the "ManagedBy" attribute and remove another at the same time via PowerShell?  (I'll be doing this for multiple lists using foreach)
In this TechNet blog post, http://blogs.technet.com/b/dstrome/archive/2011/05/29/multivalued-properties-in-exchange-2010.aspx  the array syntax, (I've tried Add before Remove, same results):
Set-DistributionGroup Sales -ManagedBy @{Remove="David"; Add="Gerald"}

results in the message:
All groups must have at least one owner who manages membership, message approval, and other settings for the group.

What is the correct way to add and remove managers from Exchange 2010 distribution groups?
Comment: Is it possible the Remove action is occurring first, and therefore throwing this error before the new value is applied?  Have you tried listing the Add action first in the list?

Also, what version of Exchange are you running (SP and CU, as well), as it would appear that is an important consid
Comment: I've tried Add first, even Add alone but the array syntax doesn't seem to work.  Question updated with version info...
Comment: More likely you'll need two separate commands. First run the add command and then the remove command. That way the timing can't be messed up.
Comment: I think the blog article isn't accurate anymore as the MSDN documentation says the Exchange 2010 version of the cmdlet doesn't have that capability (it is available in Exchange Online).
Answer: If the end result is to replace "David" with "Gerald" as the owner, avoid the Add/Replace syntax altogether:
Set-DistributionGroup Sales -ManagedBy "Gerald"

If you must do these two operations atomically (if you have cases where you might not want to replace existing values), split it into two distinct operations:
Set-DistributionGroup Sales -ManagedBy @{Add="Gerald"}
Set-DistributionGroup Sales -ManagedBy @{Remove="David"}

Comment: @jcarpio interesting ... Could it be that "Gerald" cannot actually be resolved to a principal?
Comment: Splitting the operation atomically sounds reasonable.  However, just running the Add (first) I still get "All groups must have at least one owner who manages membership, message approval, and other settings for the group. Make sure you assign an owner for this group.
    + CategoryInfo          : NotSpecified: (:) [], RecipientTaskException
    + FullyQualifiedErrorId : A28AC387"
Comment: No, I just used that as a simple example.  I use get-user to capture the member.
Answer: ManagedBy is a MultiValuedProperty parameter.
To add, use the plus (+) operation, see example below.
To subtract, use the subtract equals (-=) operation, see second example below.
Example of adding a user:
$mgr = get-user gerald

foreach ($thing in $things) {
    $group = Get-DistributionGroup $thing
    $managers = $group.ManagedBy
    $newmanagers = $managers+$mgr
    Set-DistributionGroup -BypassSecurityGroupManagerCheck -ManagedBy $newmanagers -Identity $thing
}

And, to remove a user (using DistinguishedName):
$removethis = "CN=David,OU=Houston,DC=company,DC=com"

while iterating through the list of $managers (see above):
foreach ($manager in $managers) {
    $dn = $manager.DistinguishedName
    if ($dn -eq $removethis) {
        $modifiedmanagers = ($managers -= $removethis)
    }
}

then use that in the cmdlet:
    Set-DistributionGroup -BypassSecurityGroupManagerCheck -ManagedBy $modifiedmanagers -Identity $thing


Functioning/ Error Handling of WebView

Question: Firstly, I am a newbie in webview so mind if I am asking a stupid question.
What I am doing here is to open a URL on a panel through webview and till now I am successfully doing it, for both local files and internet URL as well, but just needed to know if there is any mechanism from webview side to do the error handling stuff itself.
Like for example, if I put a wrong URL or the added URL is taking time to load or even if there is no Internet Connection, in all these cases, webview doesn't prompt me any error and I have to handle all these exceptions manually.
Please help me and let me know what can be done or if there is any documents or books that can be referred.
Answer: Just a tip, since i don't use webview in my current projects.
Have you tried with
onReceivedError

?
WebView wv = your veiw;
wv.setWebViewClient(new WebViewClient() {
   @Override
   public void onReceivedError(WebView pView, int pErrorCode, String pDescription, String pFailingUrl) {
           Log.i("put your messaage here");
           super.onReceivedError(pView, pErrorCode, pDescription, pFailingUrl);
   }
});

If you use many webview you can write your own class that extends WebViewClient, and write all the checks you need only once (maybe you would like to test if the connection to internet is prresent, or some other things)
Answer: Thanks for your reply but what exactly am looking for is Webview Loadworker's progress/workdone property... Though I finally got my answer and by adding listeners to its property, I was also able to determine the exception occurred if any...
Click here for reference.

Functioning/ Error Handling of WebView


Erro de "unwrapping an Optional value swift" em esconder label

Question: Toda vez que tendo esconder um label da minha tela usando label.isHidden = true esse erro aparece, já vi em outras perguntas aqui no forum sobre o tema, porem não consegui entender corretamente.
Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value

@IBOutlet weak var txtHE: UILabel!
@IBOutlet weak var txtHS: UILabel!
@IBOutlet weak var txtHT: UILabel!
@IBOutlet weak var txtHL: UILabel!

var esconder:Bool!

override func viewDidLoad() {
    super.viewDidLoad()

    esconder = true

    txtHE.isHidden = esco
    txtHS.isHidden = esco
    txtHT.isHidden = esco
    txtHL.isHidden = esco

}

Answer: O que está acontecendo é que sua Label ainda não foi carregada na memória e como você colocou um ! na declaração dela, o compilador tenta acessar a Label, e dá erro. Essa exclamação indica que a Label nunca pode estar nula.
Confira se a Label está sendo carregada corretamente no Interface Builder e cheque se a Label não está nula antes de tentar acessa-lá.
Como boa prática, não declare como ! e sim com ? e faça uma checagem toda vez que acessar a Label.
Comment: Ok, vou verificar.


Rails + Angular + sqlite3 Deployment

Question: I'm a beginner for this and currently finding a free web host and has a couple of questions.

Will Heroku be able to handle all of this: AngularJS, Ruby on Rails, and sqlite3?
What are other good free web hosts? This is just for a personal portfolio/blog.

I'm seeing several tutorials in the internet and just like to have the simplest one.
If it helps, my root/home page is at app>views>application>application.html.erb and I don't have an index.html. I also develop on Windows 8.1.
Thanks in advance!
Comment: sqlite is not supported by heroku
Answer: If you are using Rails to serve the API to the Angular-powered frontend in your app, there shouldn't be a problem with Heroku hosting your app. Here is a live example of an Angular/Rails app being hosted on Heroku.
However, Heroku does not support SQLite.

While easy to use, SQLite is not intended as a production grade database. Instead Heroku provides production grade PostgreSQL databases as a service.
- SQLite on Heroku

The article above shows you how to configure your app from using SQLite to Postgres, which Heroku supports.

Note: It's always a good idea to have the same database setup for both your development and production environments. However, if you're starting out and building a very simple application, and want to quickly get started with Heroku, there's another option below:
If you want to continue using SQLite3 in development, you can leave your sqlite3 gem in your :development group, and add the pg gem to the :production group in the app's Gemfile:
group :development do
  gem 'sqlite3'
  ...
end

group :production do
  gem 'pg'
  gem 'rails_12factor'
  ...
end

And then set up your config/database.yml file accordingly (sqlite for development/test, postgres in production):
development:
  adapter: sqlite3
  database: db/development.sqlite3
  pool: 5
  timeout: 5000

production:
  adapter: postgres
  pool: 5
  timeout: 5000

This way you wouldn't need to install/configure Postgres locally if you only want to make a simple application to host on Heroku.
Hope this helped!
Comment: Cool. But can I switch from SQLite3 to PostgreSQL now? I still don't have data in it. Just several tables I always clean up. I'm using RubyMine and initialized my app to have SQLite3.
Comment: You can definitely switch over. You would have to install PostgreSQL on your local machine and modify your config/database.yml adapters to use postgres. If you want to keep using SQLite, I have updated my answer with another option.
Comment: No, man. Will be switching now so that on both development and production I'll have a common database. I'll follow what the instructions on the link you gave (https://devcenter.heroku.com/articles/sqlite3) on switching. Really helpful! Thank you!
Comment: Yeah it's def a good idea for your dev/production environments to be as close to each other as possible. Glad it was helpful!

Rails + Angular + sqlite3 Deployment


How to get a list of all .properties files in an application

Question: I'm looking for a method to get a list of filenames of all properties files in an application using java.
The target is to dynamically build the content for a language selection dropdown.
Comment: you should add JSF tag to this question, I think it is more JSF related question
Answer: This class provides the method getPropertFileList() which returns all property files (language resource files) in the current database as a java..util.Vector
package ch.hasselba.xpages;

import java.util.Vector;
import javax.faces.context.FacesContext;
import lotus.domino.Database;
import lotus.domino.Document;
import lotus.domino.NoteCollection;
import lotus.domino.NotesException;

public class DesignElements {

    private final String EMPTY_STRING = "";
    private final String FLAG_PROPERTY = "gC~4K2P";
    private final String FIELD_$FLAGS = "$Flags";
    private final String FIELD_TITLE = "$TITLE";

    /**
     * returns Vector containing all property files
     * of a database
     *
     * No error handling included!
     *
     * @category Domino
     * @author Sven Hasselbach
     * @category Tools
     * @version 0.1
     */
    public Vector getPropertFileList() {

        FacesContext fc = FacesContext.getCurrentInstance();

        Vector data = new Vector();
        try {

            // get DB
            Database db = (Database) fc.getApplication().getVariableResolver()
                    .resolveVariable(fc, "database");

            // get all design docs
            NoteCollection nc = db.createNoteCollection(false);
            nc.selectAllDesignElements(true);
            nc.buildCollection();

            // process all notes
            String noteId = "";
            noteId = nc.getFirstNoteID();

            Document doc = null;
            //
            while (!(EMPTY_STRING.equals(noteId))) {

                // get design doc
                doc = db.getDocumentByID(noteId);

                // check if its a property file
                if (FLAG_PROPERTY.equals(doc.getItemValueString(FIELD_$FLAGS))) {
                    // add to Vector
                    data.add(doc.getItemValueString(FIELD_TITLE));
                }

                // next one
                noteId = nc.getNextNoteID(noteId);

                // recycle doc
                recycleObject( doc );
            }

        } catch (NotesException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return data;

    }
    /**
     * recycles a domino document instance
     *
     * @param lotus.domino.Base
     *           obj to recycle
     * @category Domino
     * @author Sven Hasselbach
     * @category Tools
     * @version 1.1
     */
    public static void recycleObject(lotus.domino.Base obj) {
        if (obj != null) {
           try {
              obj.recycle();
           } catch (Exception e) {}
       }
    }
}

To use it in a XPage just call it like this:
<?xml version="1.0" encoding="UTF-8"?>
<xp:view xmlns:xp="http://www.ibm.com/xsp/core">

   <xp:comboBox id="comboBox1">
      <xp:selectItems>
         <xp:this.value>
            <![CDATA[#{javascript:
               importPackage(ch.hasselba.xpages);
               DesignElements().getPropertFileList()
            }]]>
         </xp:this.value>
      </xp:selectItems>
   </xp:comboBox>
</xp:view>


Can I salvage a project from a compromised server?

Question: Our server was compromised last week.  The developer team I was working on hadn't been backing up our work or using GIT Hub, so everything that we've been working on is on the server.  I know that we need to rebuild the server.  I was wondering if there is anyway to salvage the project, or if we should delete our changes and start over.
Comment: Just be sure to review every line of code from files that you pull. Should be fine.
Comment: Any server that has been compromised can no longer be trusted. So apply the same code scrutiny as you would from a copy-pasta from StackOverflow and don't even think about salvaging binaries.
Answer: I wouldn't have too much of an issue pulling data files from a compromised server, assuming its going to be wiped and installed clean anyway. Take the server off the network, get an external drive and grab your files. After you collect them, put them into an isolated environment and run a virus/malware scan before putting back into production.
Could there still be risk? It depends on how the server was compromised. Weigh that against what losing all that data would cost.


How to pull out Twig variables?

Question: Trying to use some Twig variables (simple strings) in a template that I created from a custom module. Using the Devel and Kint modules I can see the info under Iterator contents with:
{{kint(transaction[0])}}

I just can't get the template to print it out on the page.
I tried this:
$ {{transaction.amount }} total donation

and
$ {{transaction[0].amount }} total donation

Either way comes up empty. Not sure what I'm missing here. It works in other modules just fine. Maybe I'm too high on the Twig templates? I don't understand the tree structure very well. I created a template called transaction.html.twig.
This is what my controller looks like.

This is the .module file. It's passing over from the controller to this theme which then passes it to the twig file. At least this is how all the tutorials tell me to do it. I create this same thing on another module and it works fine.
function touchdownclub_theme($existing, $type, $theme, $path) {

 return array(
    'touchdownclubtransaction' => array(
      'variables' => array(
        'transaction' => NULL,
      ),
       'template' => 'touchdownclubtransaction',
    ),
  );
}

Comment: When you used {{kint(transaction[0])}} was it inside transaction.html.twig?
Comment: Is this a database query result?
Comment: Is it also empty when you do `{{ kint(transaction[0].value) }}` ?
Comment: This looks like an excecuted DB Statement object, try using {{ transaction[0].fetchCol(0) }} where 0 = first column (amount_per_touchdown?) and 1 is second column...
Comment: Yes. {{kint(transaction[0])}} is inside transaction.html.twig
Comment: Yes. Its a database query.
Comment: You are printing in Twig above, is this a preprocess? Is `$output` being set to `$variables`? e.g. `$variables['output'] = $output` so it's sent to your template?
Comment: Yes, I send $output to $variables through the theme function in the .module file for this module.
Answer: I looked at some other modules controllers and saw that in the controller they used
$result = db_query
$output = $result->fetchAll();

Before pushing the code to the return array. I tried it and it worked for me like it should. Problem solved.

How to pull out Twig variables?


How can I test $H_0:\sigma^2_1=\sigma^2_2$?

Question: I have a few hundred estimates of a parameter calculated from two different models and I would like to know if these parameters have different variances.
What is a straightforward test for comparing the variances of these parameters? (straightforward meaning, least assumptions).
Comment: Are you comparing *variances* (as asserted in the first line) or *means* (as indicated in the third line)?
Comment: @whuber I had confused myself; I have clarified my question.
Comment: @Abe It seems now you have reversed "means" and "variances" but there's still a contradiction!  (Unless perhaps you want to compare the variances of the means.)  What do you mean by "variable": the means or the underlying values on which they are based?
Comment: @whuber sorry, is that better?
Comment: @Abe The new title helps a lot.  But just to be clear: are the sigma-squareds the variances of the *means* or of the underlying *variables* upon which the means are based?
Comment: @whuber the underlying variables; I have removed the term 'mean' for clarity.
Comment: Anwsers (including mine :) )  to that question http://stats.stackexchange.com/questions/841/comparing-the-variance-of-paired-observations/7013#7013 might help.
Comment: [This paper][1] gives a method you could use to test if variances are different. [1]:http://bayes.wustl.edu/glb/diff.pdf
Answer: For comparing variances, Wilcox suggests a percentile bootstrap method. See chapter 5.5.1 of 'Introduction to Robust Estimation and Hypothesis Testing'. This is available as comvar2 from the wrs package in R.
edit: to find the amount of bootstrap differences to trim from each side for different values of $\alpha$, one would perform a Monte Carlo study, as suggested by Wilcox. I have a quick and dirty one here in Matlab (duck from thrown shoes):
randn('state',0);           %to make the results replicable.
alphas = [0.001,0.005,0.01,0.025,0.05,0.10,0.15,0.20,0.25,0.333];
nreps  = 4096;
nsizes = round(2.^ (4:0.5:9));
nboots = 599;
cutls  = nan(numel(nsizes),numel(alphas));

for ii=1:numel(nsizes)
    n = nsizes(ii);
    imbalance = nan(nreps,1);
    for jj=1:nreps
        x1 = randn(n,1);x2 = randn(n,1);
        %make bootstrap samples;
        x1b = x1(ceil(n * rand(n,nboots)));
        x2b = x2(ceil(n * rand(n,nboots)));
        %compute stdevs
        sig1 = std(x1b,1);sig2 = std(x2b,1);
        %compute difference in stdevs
        Dvar = (sig1.^2 - sig2.^2);
        %compute the minimum of {the # < 0} and {the # > 0}
        %in (1-alpha) of the cases you want this minimum to match
        %your l number; then let u = 599 - l + 1
        imbalance(jj,1) = min(sum(Dvar < 0),sum(Dvar > 0));
    end
    imbalance = sort(imbalance);
    cutls(ii,:) = interp1(linspace(0,1,numel(imbalance)),imbalance(:)',alphas,'nearest');
end
%plot them;
lh = loglog(nsizes(:),cutls + 1);
legend(lh,arrayfun(@(x)(sprintf('alpha = %g',x)),alphas,'UniformOutput',false))
ylabel('l + 1');
xlabel('sample size, n_m');

I get the rather unhelpful plot:

A little bit of hackery indicates that a model of the form $l + 0.5 = \exp{5.18} \alpha^{0.94} n^{0.067}$ fits my Monte Carlo simulations fairly well, but they do not give the same results that Wilcox quotes in his book. You might be better served running these experiments yourself at your preferred $\alpha$.
edit I ran this experiment again, using many more replicates ($2^{18}$) per sample size. Here's a table of the empirical values of $l$. The first row is a NaN, then the alpha (type I rate). Following that, the first column is the size of the samples, $n$, then the empirical values of $l$. (I would expect that as $n \to \infty$ we would have $l \to 599 \alpha /2$)
NaN,0.001,0.005,0.01,0.025,0.05,0.1,0.15,0.2,0.25,0.333
16,0,0,1,4,9,22,35,49,64,88
23,0,0,1,4,10,23,37,51,66,91
32,0,0,1,4,10,24,38,52,67,92
45,0,0,1,5,11,25,39,54,69,94
64,0,0,2,5,12,26,41,55,70,95
91,0,1,2,6,13,27,42,56,71,96
128,0,1,2,6,13,28,42,58,72,97
181,0,1,2,6,13,28,43,58,73,98
256,0,1,2,6,14,28,43,58,73,98
362,0,1,2,7,14,29,44,59,74,99
512,0,1,2,7,14,29,44,59,74,99

Comment: @shabbychef thanks for pointing me in this direction. It only took me about 5 min to download, read the section chapter, and compute; very much appreciated, but I am going to hold of on accepting your answer in hopes that other methods will be suggested - as this one is rather limited (only tests at alpha = 0.05, and there may be other options for large samples as in the present case)
Comment: @shabbychef I've already +1 but was very unlucky with the R package -- OS X build doesn't include the aforementioned function :(
Comment: @chl AFAIK the package is just a convenient bundle for the functions that are available at http://www-rcf.usc.edu/~rwilcox/Rallfun-v13
Comment: @Abe: for values of $\alpha \ne 0.05$, Wilcox outlines the method for constructing the cutoff values of $l$ and $u$, but I agree it would be nice if they were available as rough functions of $\alpha$.
Comment: @shabbychef I am confused - in the book it says 'the method can be applied only with $\alpha=0.05$, modifications based on other $\alpha$ values have not been derived"? His 2002 paper abstract hints otherwise, but I am not able to access it.
Comment: 'The method just described is based on a strategy similar to Gosset's derivation of Student's t: Assume normality and then make adjustments so that for small sample sizes, accurate probability coverage is obtained.'
Comment: @caracal Thanks. I guess the Win/Linux versions available on RForge are more up to date.
Comment: I had thought there were 3 or 4 tried and true methods, such as Levene's, for testing the difference between variances. Why would one want to turn to these intricate and improvised approaches?


where does the variables defined using "--dart-define" go and can we reverse engineer them?

Question: I am building a flluter application.
I don't want to compromise my secret_key by putting it in the code, so I tried making a .env file and created an apk. Then I unzipped the apk and found my config file there. So now I am not doing that.
The next thing I tried is using --dart-define variable declarations to put my secret_key while building the app and I am accessing it using
const secret = String.fromEnvironment("secret_key");

Coming to the question, where do these variables go inside the dart code and is there a way to get them by reverse engineering.
Basically is it safe to put my secret key this way?
Comment: Yes its safe because  `--dart-define` variable you need to define in build command and that is not saved any where in code at the time of build generation these keys used.
Comment: If your code needs `secret_key` at runtime, then it is not strictly safe.  Anything your code can do, someone sufficiently determined can also do by examining your code.
Comment: @jamesdlin what do you mean by that? I didn't get it.
My use case is to call an API using that secret key that's it. without it, I can not call the API.
Comment: I mean that what you're asking is, strictly speaking, impossible.  If code running on a client needs a fixed secret to operate, the client needs access to the secret, and someone sufficiently determined will be able to extract it from client-side code.  See [How to store a secret API key in an application's binary?](https://stackoverflow.com/questions/5525305/)
Comment: Thanks, @jamesdlin. I got that. but what about `--dart-define` saving the variables which has no trace in code other than the binaries?
Comment: Well, using `--dart-define` avoids needing to hard-code your secrets and make them plainly visible to anyone who can read your source code (which is good), but it won't help against someone reverse-engineering your program (which is impossible).
Comment: so I can use that to at least avoid putting the key inside the code.
Answer: From what I found, you can find the --dart-define variables in the binary file generated for each ABI, so yes, you can reverse-engineer it.
How to try:

Call the variable from your code with String.fromEnvironment("ANIMAL").

Run flutter build apk --dart-define=ANIMAL=Dog to build for Android

Open the generated .APK file with a file archiver (7-Zip, for example) and navigate to /lib/(ABI)/

Open /lib/(ABI)/libapp.so file with a text editor or hex viewer and search for the value Dog and you will find it

Observations:

If you don't use the variable in your code, it won't be added to the binary
Using --obfuscate with flutter build won't help, because it doesn't obfuscate environment variables


Encoding Video and Audio together is much slower than encoding each separately

Question: Encoding audio and video separately with Media Foundation then multiplexing with ffmpeg, is much faster than encoding both audio and video together, multiplexing in Media Foundation. I'm curious to know why?
I'm encoding aac audio and h264 video; the video input into the encoder is at variable frame rate (quite low). The speed I'm getting is probably what I would expect if the video input was at a constant frame rate (same as that of the output).
Notably, if I write all the audio(video) stream then the video(audio) stream, all the time encoding is taken writing the first stream, and the second stream is written near instantly.
Can some one tell me what is going on?
Answer: The multipexer is likely to be throttling the video leg of the input because the produced file has, with default settings at least, the layout where video and audio data related to close time points is packaged together.

By default, the sink writer's IMFSinkWriter::WriteSample method limits the data rate by blocking the calling thread. This prevents the application from delivering samples too quickly. To disable this behavior, set the MF_SINK_WRITER_DISABLE_THROTTLING attribute to TRUE when you create the sink writer.


showing error Insecure dependency in parameter 3 of DBI::db=HASH(0xa32bd40)->do method call while running with -T switch

Question: i got the error Insecure dependency in parameter 3 of DBI::db=HASH(0xa32bd40)->do method call while running with -T switch while i modified the file show_bug.cgi
what is the reason?
Comment: could any one pls answer this?
Answer: To untaint ie. variable $unsecure, a regular expression should be applied
my ($secure) = $unsecure =~ / (\d+) /x
  or die q{we couldn't find number in $unsecure};

Answer: To untaint a variable, you must match it against a capturing regular expression. See perlsec - Perl Security for details.
Comment: what can be regular expression for strings?
Comment: @Jenifer_justin: You probably added a new parameter to a function. You should check that the value of the parameter is valid, e.g. if it is a number, use `$number =~ /^([0-9]+)$/`.
Comment: k. can i use the expression /^([-\@\w.]+)$/ for strings?
Comment: @Jenifer_justin: It really depends on what you expect in the new parameter.


How do I keep my concentration going to the end and not get distracted thinking about how well it's going?

Question: Often when I am performing a piece of music and it's going really well - all that practice really paid off! - I start thinking, "wow, things are going really well. This sounds really good!" But as that thought floats through my head my playing falls apart and I make mistakes. Then my mind starts arguing with itself to stop thinking about how it's going and stay focused on the task at hand. I recover but then I finish upset that the performance did not go well instead of regaining focus.
I'm not sure if the problem is distraction, lack of focus, not enough practice, or I'm too comfortable with the piece and not concentrating enough? I feel like I need to be able to switch off or suppress part of my mind to keep focused all the way through.
Looking for some ideas on how to avoid this scenario. And if not avoid it, more gracefully recover from it.
Comment: I share your pain, I have the exact same problem, though it occurs when I practice because I don't perform publicly.
Comment: Hahah. I had the same problem a few years ago. It was a little hard for me to get myself focused.
Comment: When I used to play, this was my biggest fear!
Comment: To get a good performance, I try to love the music I'm playing, even when it's not that good. (Perhaps especially then.)
Answer: For me, the issue stems from the difference between practice and public performance.  Most of us, I think, practice far more than we perform publicly.  Since a primary goal of practice is improvement, and improvement requires self-assessment, a musician can get used to constant self-assessment when practicing.
Understanding that, I think the key is to "turn off" this self-assessment.  It is not enough to be able to do this just in performance; rather, one must practice this skill of "not practicing!"  The way I suggest is to designate part of a practice as a run-through, just as though it was a performance.  Record this run-through!  Doing so is important so that you know in advance that any mistakes will be picked up by the recorder for later identification, so it is not necessary to self-assess during the run-through, at least not the way one does in typical practice.  You can then listen to the recording to see what problems you had.  In all likelihood, you will find problems you did not find during normal practice, simply because the situation is different.
As you try this technique, you will become more adept at turning off the constant self-assessment.  You can then focus on the present moment in your music without worry.
I must caution, of course, that not all self-assessment gets turned off in performance.  For example, playing in tune requires assessment throughout the performance.  If I find that I have gone sharp relative to the ensemble, I will make the mouthpiece adjustment necessary at my next reasonable opportunity.  Granted, I can force pitches down, but for my own comfort and better tone, moving the mouthpiece is needed.  I could not know to do so if I was not self-assessing in this way.  However, doing so does not entail assessing notes already gone by.  Instead, it requires "living in the present," as I think you are seeking to do during a performance.
Comment: @Edgar Gonzalez You did!
Comment: Great answer, I wish I could've read this 5 years ago
Comment: This answer, and @Flounderer's comment just made my night, all these years later.
Answer: It is not unusual to become self critiquing during the act of doing something. Writers are often taught to just write, and then edit later, rather than writing a bit, editing it, writing a bit more, or continually deleting and rewriting as they are going. The problem is, if we start concentrating on the critique, we lose concentration on the act, and so it goes down hill!
Barry Green wrote a marvelous book on the concept, and ways to overcome it, called The Inner Game of Music.
http://www.amazon.com/Inner-Game-Music-Barry-Green/dp/0385231261
http://www.innergameofmusic.com/
Its well worth picking up.
Answer: I also have the 'self-watching' tendency.  A simple solution is to try to pay attention to the notes and rhythms and how they feel to you.  This tends to absorb your attention and pull you back into the music.  You want your brain to operate less in the realm of language and self-awareness and more in the 'language' of music.
This may sound like a spacy answer, but doing this can truly help.  A long-standing technique in meditation is concentration on a physical object to still all the babbling of the mind, and a musician can reduce the background noise of unwanted thought by reapplying attention to the notes -- not merely executing them or their letter symbols, but what they're saying and how you can best express that.
You can also use this to alter your emotions.  Put on music which you associate with the desired emotion, then open yourself very fully to the sounds and what they express.
Answer: It sounds to me like your problem is the same as mine. My mind starts wandering. This usually happens to me when I am singing. When I finally "Wake Up!" from my thoughts, I get lost in the song. Because I think much faster then I sing, I usually think I'm on the second verse and not the first.
One thing that I found helped me is focusing on the meaning of the song (the words in my case) and practicing to enhance the song by using motion, volume, and expression. Also I close my eyes some times to help me "Get Into The Music". So my advice is Get Into The Music, get absorbed in your own song. You can also try to Get Into The Music while there are major distractions.
Comment: Yes. Singing and the meaning of words is part of it. On occasion I substitute for the music director at church and my biggest problem is keeping focus while playing a hymn with the congregation.
Answer: The keys is to first get it done and then getting it done right. In computer science we call this 'Premature optimization' and this is synonymous with disaster.
I think the key for you will be to just concentrate on getting it right, then take time to think improvise and see if you can do it better.
Comment: Is that 2 keys or 1? It kind of reads like the second is the exact opposite of the first.


Find a smooth atlas for the manifold $M=\left\{(x,y,z,t) \in \mathbb{R}^4\ | \ x^4+y^4+zt=1\right\}$

Question: I have this exercise:

Let $M=\left\{(x,y,z,t) \in \mathbb{R}^4\ | \ x^4+y^4+zt=1\right\}$

Prove that M is a smooth manifold and find the dimension
Explicitly build a smooth atlas (it's not necessary to check the $\mathscr{C}^\infty$-compatibility beetween the charts)

For the first point I have proved that $M$ is a smooth manifolds with $\dim{M}=3$ using the theorem about the fiber of an element on a differential function beetween manifolds.
But for the second point I have no idea about what to do. Generally I have  a vague geometric interpretation of the manifold that permits me to try to build some atlases, but this time I can't. So, what is the correct approach?
Answer: Hint Solve the defining equation for, e.g., $t$, as function of the other variables, so that $M$ is a graph of that function.


How can you pre-load a module when invoking `cabal repl`?

Question: Is there a way to have a module automatically load when cabal repl shows the ready prompt? I'd like to shortcut the following workflow with some command line options or something equivalent for cabal repl:
cabal repl
ghci> :m + Note.Query
... now I do stuff with functions in the Note.Query module

Answer: You can put the command :m + Note.Query in a file called .ghci. If there is a file called .ghci in the current directory, then it will be run when you invoke GHCi. If there is no .ghci file in the current directory, but there is one in your home directory, then that will be run. This allows you to have project-specific .ghci files.


git ls-remote without remote name

Question: My repository is configured to have more than one remote. Then when I run git ls-remote for which remote is it showing the data ?
Earlier I thought it defaults to origin but upon changing remote name to origin1 , it still  shows for it. Then moving on different branches in repository , it seems like choosing remotes from there. I am not sure. Not all branches are pushed to all remote repository.
Comment: From the source code `remote.c`,https://github.com/git/git/blob/master/remote.c, Line 666-675, we can see it's the remote specified by `branch..remote`. If not specified, `origin` is used if it exists.
Comment: From memory, I think it defaults to the remote of the upstream branch you're currently tracking on the branch that you have checked out. Try `git checkout -b TEMP` and then `git ls-remote`, this branch does not have an upstream branch yet, does it still show remote information through `git ls-remote` ?
Comment: No. It is not showing remote info. `fatal: No remote configured to list refs from.`
Comment: @LasseVågsætherKarlsen what if a local branch have 2 remote tracking branch ?
Comment: No, you cannot track two remote branches at the same time: if you track a 2nd remote, the 1st is no longer tracked.
Comment: @ElpieKay this is right answer. please post as answer
Comment: @MincongHuang I did not get you. I can see both remote tracking branch exists when I do `git branch -a`
Comment: Command `git branch -a` lists both local branches and remote branches. If you see the same branch appeared in both local and remote, it doesn't mean the local branch is tracked by the remote one. You should run `git branch -vv` to show the tracked information. For example, `master  c63e9c1 [origin/master] Add sth` means the local master is tracked to `origin/master`.
Answer: As @ElpieKay mentioned in the comments , (I am just posting it as answer)
From the source code remote.c, Line 666-675, we can see it's the remote specified by branch.<name>.remote. If not specified, origin is used if it exists.

git ls-remote without remote name


Joomla 3 Custom Inquiry Form Module

Question: I've tried to create simple module where I created a inquiry form with attachment. The basics are there however I'm stuck on what will be the form action and how can I handle the form inputs to sent as email. I have no plans on saving it to the database. The purpose is when user fill out the form and send it, the email marketer will receive it as an email. Below are my codes.
mod_inquire.php
defined('_JEXEC') or die;
require_once dirname(__FILE__) . '/helper.php';
$inquire = modMessageHelper::getInquire($params);
require JModuleHelper::getLayoutPath('mod_inquire');

mod_inquire.xml
<extension type="module" version="3.1.0" client="site" method="upgrade">
<name>Inquire Here</name>
<author>John Doenut</author>
<version>1.0.0</version>
<description>A simple Inquiry module.</description>
<files>
    <filename module="mod_message">mod_inquire.php</filename>
    <folder>tmpl</folder>
    <filename>helper.php</filename>
</files>
<config>
</config>
</extension>

helper.php
class ModInquireHelper{
public static function getInquire($params){
    return "Inquiry!";
}
}

default.php
defined('_JEXEC') or die;

?>

<form action="" method="post" id="inquiry-form" class="form-inline" enctype="multipart/form-data">

        Name
        <input type="text" class="form-control" id="inquiry-name" placeholder="Enter name">

        Email address
        <input type="email" class="form-control" id="inquiry-email" aria-describedby="emailHelp" placeholder="Enter email">
        We'll never share your email with anyone else.

        Message
        <textarea class="form-control" id="inquiry-message" rows="3"></textarea>

        Attach a file
        <input type="file" class="form-control-file" id="inquiry-attachment">

    <button type="submit" class="btn btn-primary">Submit</button>
</form>

Questions:

How do I passed and process the form inquiry?
How do I attach a file?
What will be my form action?

If there are similar questions and answers about this, let me know. Also, If there are tutorials you can send the links and if you can directly answer my question, that would be great.
Answer: Why don't you just use one of the ready made forms from extensions directory? It's much easier than code your own.
link here

Joomla 3 Custom Inquiry Form Module


infinitetly loop array with setTimeout javascript

Question: I have an array of strings that I'm passing to a for loop with a setTimeout inside.
I've tried to for(; ;) and while(true) the function but this just causes the browser to crash.
I've also tried adding an if statement inside the function
if (x == links.length) { loopUrls() }

Which works kind of but skips the entire interval section of the function, cycling the entire array infinitely with no wait.
        function loopUrls() {
            for (var x = 0, ln = links.length; x < ln; x++) {
                setTimeout(function (y) {
                    document.getElementById('ifURLS').src = links[y];
                },x * 500,x);
            }
    };

    loopUrls();

The aim is to have a list of urls that infinitely assigned to the iframe to show reports on a sreen. (the time interval is just small for testing purposes)
Comment: why don't you use a setIntervel ?
Comment: Let me confirm if I understood that. You want a script that forever loops between the URL in the array and change between them every x amount of time?
Comment: Isn't it better to write with `setInterval`?
`setInterval(() => document.getElementById('ifURLS').src = links[y], 1000);`
Answer: If I understand correctly, you want for every link to have some function that is being executed every X milliseconds.
In order to achieve this I think it's better to use setInterval.
You can do something like:
links.forEach((link) => {
  setInterval(() => {
    //do something every X milliseconds
  }, X)
})

Comment: Bad answer, your are making multiple setInterval() wich are never ending
Answer: a way to do that :
// const links = [ ... ]

const myImg = document.queryselector('#ifURLS')

function LoadImg()
  {
  let
    indx = 0
  , let refIntv =
      setInterval( ()=>
        {
        myImg.src = links[indx++]

        if (indx >= links.length)
          clearInterval( refIntv )
        }
        , 5000 )  // 5s delay
  }

Answer: There is no need to have multiple timeouts. You can achieve this using setInterval which executes a function every x amount of time. Then in that funciton you keep a state of the current url so you can show the next time the function is run
// creates a function that iterates over the array and every time its called returns the next element
function createIterator(array){
    let sourceArray = [...array];
    // starts at the end so it resets automatically
  let topIndex = sourceArray.length;
    let currentIndex = topIndex - 1;
    return function (){
        currentIndex++;
        // if the limit is reached, its reseated
        if (currentIndex === topIndex) {
            currentIndex = 0;
        }
        return sourceArray[currentIndex];
    }
}
// your urls
let urls = ["a", "b", "c"];
// uses the function to create the iterator
let iterator = createIterator(urls);

setInterval(function() {
    let currentUrl = iterator();
    document.getElementById('ifURLS').src = currentUrl;
},1000);

No need for loops, as the iterator handles seamlessly
Comment: Hi Daniel,
Thanks for the great solution.
Comment: You're welcome. If this resolves your question you can mark it as the selected answer using the green check on the left of the answer


Filtro função php pdo

Question: Estou com uma função php que me retorna numa tabela html todas placas NrPlaca porem eu precisaria por um filtro na função do php para mostrar na tabela apenas as placas que no DsTpVeiculo são bitruck, gostaria de algumas dicas de como fazer.Segue imagem do banco de dados:
Função php:
class ProgDAO{

  private $conn;

  public function __construct($connection) {
      $this->conn = $connection;
  }

  public function ListaTodos(){
          $results = array();
          $stmt = $this->conn->prepare(
              'SELECT * FROM GTCLogist'
          );
          $stmt->execute();
          if($stmt) {
              while($row = $stmt->fetch(PDO::FETCH_OBJ)) {
                  $prog = new Prog();
                  $prog->setplaca($row->NrPlaca);
                  $prog->setmot(stripslashes($row->DsMotorista));
                  $results[] = $prog;
              }
          }
      return $results;
  }

}
Table que mostra os dados:

                BITRUCK
                Motorista
                Data Saída
                Origem
                Destino
                Prev. Cheg. Dest
                Carga/Manifesto
                Adiantamento Fincanceiro
                Agendas
                Malote
                Obs

            <?php
                    foreach ($controller->listarEmail() as $objProg) {
                        ?>

                                <?php echo $objProg->getplaca(); ?>
                                <?php echo $objProg->getmot(); ?>

                <?php
                    }
                ?>

Comment: Você precisa mesmo trazer a tabela inteira do banco? Senão, basta alterar sua SQL para `SELECT * FROM GTCLogist where DsTpVeiculo ='Bitruck'`.
Comment: Pode ser no SQl não? Tem que ser feito no php mesmo?
Comment: É, gostaria que fosse no php mesmo mas se tiver uma outra opção aceito também.
Comment: Pode criar um método novo, que faz um `WHERE` no campo desejado ou usar o método com um parâmetro que informa o valor a ser buscado.
Comment: Ou caso queira fazer no php mesmo, pode colocar um `if($row->DsTpVeiculo == 'Bitruck')` dentro do `while`, mas isso é desperdicio da query ao banco, já que você pode trazer filtrado diretamente dele.
Comment: Tentei mudar o select pois deu erro no mesmo:  **Parse error: syntax error, unexpected 'Bitruck' (T_STRING) in DAO\progDAO.php on line 14**
Comment: Você escapou as aspas? `'SELECT * FROM GTCLogist where DsTpVeiculo = \'Bitruck\''`
Comment: Justo haha, não sabia isso da contra barra. Me ajudou bastante.
Answer: Pode criar um método novo para listar as placas por tipo, a diferença é que esse método recebe um parâmetro, o qual será usado na clásula WHERE
public function ListaPorTipo($tipo){
    $results = array();
    $stmt = $this->conn->prepare('SELECT * FROM GTCLogist WHERE DsTpVeiculo = ?');
    $stmt->execute(array($tipo));
    if($stmt) {
        while($row = $stmt->fetch(PDO::FETCH_OBJ)) {
        $prog = new Prog();
        $prog->setplaca($row->NrPlaca);
        $prog->setmot(stripslashes($row->DsMotorista));
        $results[] = $prog;
    }else{
        print_r($stmt->errorInfo());
    }
    return $results;
}

E a chamada fica algo como:
<?php
$prog = new ProgDAO ($conexao);
$itens = $prog->listaPorTipo('bitruck');

Comment: Por questão de organização e reusabilidade, esta forma é realmente a mais apropriada. +1
Comment: Muito obrigado, deu uma grande ajuda. Era isso mesmo.
Comment: Só uma duvida, não estou conseguindo chamar a função estou usando MVC, preciso criar uma função dentro da class na model para chamar ?
Comment: @Kevin.F, a função deve  ser criada na classe `ProgDAO`
Comment: @rray sim certo, porem essa chamada onde deve ser posta ?
Comment: @Kevin.F coloca no controller que faz essa pesquisa, aí ele chama o DAO pega os valores e repassa para view(html).
Comment: @rray no controller estou usando isto:
`class Comando {

 private $conn;

         public function __construct($connec) {
         $this->conn = $connec;
     }

         public function listarTodos(){
   $dao = new ProgDAO($this->conn);
   return $dao -> ListaTodos();
  }
}

` um metodo construct, no caso teria que ter uma function dentro da class comando **listarPorTipo** não ?
Comment: @Kevin.F isso mesmo,
Comment: Agora foi rs, Vlw.

Filtro função php pdo


Frequency distribution of Chinese Restaurant Process?

Question: Set-up
I was simulating the Generalized Chinese Restaurant Process as shown on the wikipedia page  [link] with a discount, $\alpha$,  and concentration parameter $\theta$
For $n=5$ total customers being seated with $\alpha=.3$ and $\theta=1.5$ and 100,000 simulations I saw a distribution of the number of tables needed as

1 | 5.6%
2 | 20.2%
3 | 33.5%
4 | 29.3%
5 | 11.4%

with expected value of 3.207 tables, which matches the theoretical answer (link) for these parameters.
Question
Does there exist a formula to determine the probability of different frequency distributions among those tables?
For example, within the simulation, the following frequency distributions appeared with the following probabilities, with notation being $n_k$ represents $n$ tables with $k$ people; and $\sum(k n_k)=n$

[0,0,0,0,1]  5.6%
[0,1,1,0,0]  6.9%
[1,0,0,1,0]  13.3%
[1,2,0,0,0]  12.8%
[2,0,1,0,0]  20.7%
[3,1,0,0,0]  29.3%
[5,0,0,0,0]  11.4%

(29.3% of the time the frequency distribution was 3 tables with 1 person, and 1 table with two; whereas only 5.6% of the time one table had all five people)
Notice that the 33.5% probability observed for having three tables match the sum of the individual frequency distribution which also have three tables (12.8% + 20.7%). Likewise for other numbers.
Reason
The reason for asking the question is say I know the frequency distribution of the number of tables that contain $k$ people, for a large number of customers - say, 1,000 customers, and they were:
$n_k=\{500,100,40,30,12\}$
(500 tables have 1 person, 100 have two people, 40 have three, etc)
Is there a way to determine the discount $(\alpha$) and concentration parameter $(\theta)$ which would yield the maximum likelihood of producing that known observed outcome?
Answer: Your data {500,100,40,30,12} implies that 500+100+40+30+12 customers chose to sit at a new table, 100+40+30+12 customers chose to sit at a table that had exactly 1 customer at the time, 40+30+12 chose to sit at a table that had exactly 2 customers at the time, etc.
Suppose you also knew the ordering of these 1000 customers.  Given $\alpha$ and $\theta$, the probability of their sequence of 1000 choices would be easy to work out -- it is a product of the 1000 independent (but not identical) probabilities of their individual decisions.  Those probabilities are just as in your simulation.
But that is just the likelihood of $\alpha,\theta$, which you can maximize by gradient ascent on the log-likelihood.
Now, you don't actually know the ordering, so you have to sum over possible orderings.  But as it turns out, the probability above doesn't depend on the ordering -- that's what it means to say that the process is exchangeable.  So just pick any convenient ordering and compute its probability.  (For example, assume that the customers that start a new table show up first, and then the customers that sit at a table with exactly 1 previous customer, etc.  You should be able to verify that changing the ordering wouldn't change the probability.)
This is the probability of a single ordering.  To get your actual likelihood, you'd need to multiply by the number of possible orderings.  But that number is a constant that depends only on your data and not on $\alpha,\theta$. So you can ignore it for the purposes of finding the likelihood maximizer.  In other words, just find the  $\alpha,\theta$ that maximize the probability of the single ordering.
Answer: For the original CRP, the number of tables $m$ used after N draws is distributed with pdf:
$$P(M=m | \alpha, N)=s(N, m)\alpha^m \frac{\Gamma(\alpha)}{\Gamma(\alpha+N)}$$
where $s(N,m)$ are stirling numbers of the first kind. This is explained here. Perhaps the generalized CRP is a generalization of this?


Entendendo parâmetros lambda de um delegate em uma função

Question: Tenho a função abaixo. Só gostaria de entender quem é X e que valores ele vai atingindo no decorrer da função. Não consegui pegar no debug. Não precisam dizer exata,ente os valores literalmente, mas como ele sendo aringido. Estou estudando e quero entender tudo isso.
public int qualquerCoisa(int tamanho)
        {
            Func<int, int> calcFib = null;

            calcFib = x => (x - 1 + x - 2);

            return calcFib(tamanho);
        }

Comment: Não devia ter editado a pergunta. Ela agora pede algo diferente do inicialmente pedido, deixando as resposta dadas de alguma forma sem sentido. Em vez de editar deveria dar esta pergunta como encerrada e criar uma nova.
Comment: O código acima, eu sei que está errado. Só coloquei para dizer o que eu estou querendo fazer. O resultado seria: 0,1,1,2,3,5,8,13,21,34, ou seja, uma lista ou array retornados.
Comment: Favor, não envie código pronto. Só preciso entender para eu poder fazer e chegar às minhas conclusões.
Comment: ok, vou remover a edição e encerrar e fazer outra.
Answer: O X representa o parâmetro que e passado para a função calcFib. Se reescrever a função calcFib como um método ficaria:
public int calcFic(int x)
{
    return x - 1 + x -2;
}

No caso do código que colocou, X vai receber o valor de tamanho.
Comment: Ou seja, no caso específico, ele não percorre até o valor máximo, começando em um determinado valor. Teria que passar, um array ou lista, para que ele fosse percorrendo até o valor de tamanho, falando especificamente no caso acima.
Comment: Exactamente. Caso queira que a função seja executada para uma lista pode: ou criar um ciclo `for` e passar os valores um a a um para a função. Ou então mudar a função para aceitar uma lista/array e dentro da função executar o ciclo `for`.
Answer: Func<int,int> declara um delegate que representa uma função que recebe um parâmetro do tipo int e retorna um valor do tipo int.
Pegando no seu exemplo o resultado de return calcFib(tamanho); será:
int resultado = tamanho - 1 + tamanho - 2;

O valor que x recebe é aquele que é passado à função.


React useEffect restarting timer

Question: I have been trying the useEffect hook and have come across a problem that I don't know to fix.
I have written a simple counter example which uses setTimeout within useEffect to update values.
        if (countState.stopWatch === 0) {
            dispatch({ type: 'reset' });
        }
        else {
            const timeId = setTimeout(() => {
                console.log("Timeout " + JSON.stringify(countState));
                if (countState.stopWatch > 0) {
                    dispatch({ type: 'decrement_stopwatch' });
                }
            }, 1000);

            return () => {
                clearTimeout(timeId);
            };
        }
    });

The code works ok but has one problem. When the function is being rerendered, it causes the timer to exit and be set up again which causes gaps (i.e. the timer is not running every 1 sec but every sec plus time to re-render the app).
When I use a class based solution, I run the timer in the class constructor and the timer runs smoothly as it is not cancelled by re-rendering.
Any ideas as to how I get round this in the functional version?
The full code including the function and class based solutions can be found here:
https://github.com/jmc420/react_examples/blob/master/counter/hooks_counter/src/StopWatch.tsx
Comment: How come you chose to use setTimeout for the functional one but setInterval for the class one? If you use setInterval in the functional comp, you'd make your life a lot easier
Comment: https://www.npmjs.com/package/react-countdown-hook
Comment: No particular reason for using setTimeout.
Answer: I was trying to rack my brain to come up with a way to use setTimeout like you were trying to do in a functional component but like you realised, there is an issue with the tiny bit of time between rendering and resetting the timeout.
The best I could come up was to just use setInterval. If you weren't sure how to use that with hooks, I made a quick Codesandbox with my experiments: https://codesandbox.io/s/rough-shape-rjmjs
The key here is that we set the interval once and only remove it on unmount so it is ticking away consistently.
For the first one, we do all the logic inside of where set state call because this intrinsically has access to the most recent state args to avoid issues where the interval is closed over the initial state like:
setCount(c => {
  // c is the most recent count state
  if (c > 0) {
    return c - 1;
  }
  return c;
});

If that doesn't meet your needs, I added a second one as well where it uses a ref to bypass the closure problem as well. We just call the function assigned to the ref each interval tick but we reassign what that function is each render.
timerLogicRef.current = () => {
  if (otherCount > 0) {
    setOtherCount(otherCount - 1);
  }
};

It might be easier to make the second fit with your reducer set up.
Answer: I found out what the solution is. If useEffect is used without dependencies, you get a warning from react but the timer does not exit when the timer decrements. You then get the problem Of referring to out of date closure variables, but this is fixed by using useRef.

React useEffect restarting timer


Having trouble mounting .ISO file when using QEMU

Question: I'm running a MacBook Air M1 with Big Sur 11.4 installed
I'm trying to mount an ISO image of the Virtio-Win networking driver, using the following commands in my start.sh file.
  -drive file=/Users/username/Downloads/windows-10/virtio-win-0.1.190.iso,media=cdrom,if=none,id=drivers \
  -device usb-storage,drive=drivers

The drive does not show up when I run the QEMU Windows 10 ARM instance, everything else works just fine.
Are there other options for moving files or images from my host to the QEMU instance?
Comment: Try run the `SimpleHTTPServer` in you host by `python -m SimpleHTTPServer PORT` under the drive file path( **/Users/username/Downloads/** ), and open the `host:PORT` in the QEMU instance's browser and download the file.
Answer: In my case, I need to use -cdrom and -boot d
This works for me:
         -bios ./bios.fd \
         -drive if=virtio,format=raw,file=./debian.qcow2,discard=on \
         -cdrom ./ubuntu-21.04-live-server-arm64.iso \
         -boot d


How do I retrieve media from a reference field?

Question: Inside a node type, I have a reference field to target a media.
With a db select, I need to load all related medias of the nodes.
For this I use this code:
<code>$database = \Drupal::database();
$result = $database->select('media_field_data', 'm')
->fields('m', ['mid'])
->condition('m.bundle', 'gallery')
->leftjoin('node__field_related_gallery', 'n', 'media_field_data.mid = node__field_related_gallery.field_related_gallery_target_id')
->leftjoin('field_related_gallery_media_field_data', 'd', 'node__field_related_gallery.entity_id = field_related_gallery_media_field_data.nid')
->range(0, 5)
->execute()
->fetchAllKeyed(0, 0);
dpm($result);
</code>
But with this code I get an error and don't get the related mids. If I remove the line with the leftjoin I get the mids.
How can I proceed to verify if a media is related to a node and get only the media with a related node?
With views I can get easily the results with this query:
<code>SELECT media_field_data.mid AS mid,
field_related_gallery_media_field_data.nid AS
field_related_gallery_media_field_data_nid
FROM
{media_field_data} media_field_data
LEFT JOIN {node__field_related_gallery} node__field_related_gallery ON
 media_field_data.mid =
 node__field_related_gallery.field_related_gallery_target_id AND
 node__field_related_gallery.deleted = '0'
 LEFT JOIN {node_field_data} field_related_gallery_media_field_data ON
 node__field_related_gallery.entity_id =
 field_related_gallery_media_field_data.nid
 WHERE (media_field_data.status = '1') AND (media_field_data.bundle IN
 ('gallery')) AND (field_related_gallery_media_field_data.nid IS NOT NULL)
 LIMIT 26 OFFSET 0
</code>
Thanks.
Answer: Do you have to do it with a DB call? Why not use Drupal's existing functions?
<code>  // Load a node by node ID.
  $nid = '213';
  $node = \Drupal\node\Entity\Node::load($nid);

  // OR load current node.
  $node = \Drupal::routeMatch()->getParameter('node');

  if (!empty($node)) {
    // Assumes you have a media field called "Related gallery"
    $medias = $node->get('field_related_gallery')->referencedEntities();

    foreach ($medias as $media) {
      // Do stuff with the media.
    }
  }
</code>


Classic Geometry

Question:
In a triangle $\triangle ABC$, $D$ and $E$ are the points on sides $BC$ and $AC$ respectively such that $AE = BD$. If the line joining the circumcentres of triangles $\triangle ADC$ and $\triangle BEC$ cut $AC$ and $BC$ at $K$ and $L$ respectively, then show that $KC=LC$.
Comment: What is the question?
Comment: Isn't it visible.. I don't know how to post. If not visible then please tell, I will repost. And if it is visible then we have to prove using the given conditions.
Comment: _We_ can only help you if _we_ know what part you are stuck at. I would suggest you edit the question and add what you have done so far.
Comment: Okay. I was not able to proceed in the very beginning only. How to proceed or what tools we need or what to show first... Or something like a hint may help
Comment: The usual, accepted way to ask a question is by given a problem, (fixing the definitions and relevant framework,) and showing the own work, a starting point, the problem point, providing context, etc. In this case a picture is a minimal effort, that user are expecting, since this is the way the site works. (Showing as much as possible from the own thoughts tends to let potential answers point exact the critical bridge to go further, this spares time and make a fair share of the efforts.) So what have you tried? (No further information results in many downvotes and a close of the thread.)
Comment: The best way to get an answer to problems in geometry is to add a diagram to your post depicting what you have described in words.
Answer: You have asked for a hint. The following method does work so you can, if you wish, try it and ask if you get stuck.
Take $C$ as the origin and let $x$ and $y$ be unit vectors in the directions $CA$ and $CB$. For convenience assume the triangle is scaled so the vectors $EA=x$ and $DB=y$. Let $CE=\lambda x$ and $CD=\mu y$.
Let the position vector of the centre of the circumcircle of $ADC$ be $r$ then $$|r|^2=|r-\mu y|^2=|r-(\lambda+1)x|^2$$
From this equation you can obtain $r.y$ and $r.x$. Do the same for the circumcentre, with position vector $s$, of the other circle.
Then find $(r-s).(x+y)$. You will obtain zero.

Classic Geometry


Chance of guessing 5 out of 8 letters in sequence

Question:
Everybody guessed or copied a word with 8 letters. • If someone had
mutations at 3 of 8 positions from my word, there was a 1  chance
238,659 that they did not copy (they have written down 8-letter words
with 3 different letters just by chance). • What if the class has 238,
659 people in it? • Then, even if everyone came up with their word
randomly (and are therefore not related to each other) we would expect
someone to have 3 mutations off my word, simply by chance.

That is an analogy given by my bioinformatics teacher but I have no idea where 238,659 is from.
I looked at permutation,
P(n,r) = P(26,8)
= 6.2999E + 10
Is the probability of guessing all 8 letters correctly in sequence I think.
So the chances of guessing 5 out of 8 correctly in sequence is a permutation or combination and can someone throw up the equation/formula or more importantly what is 238,659?
Edit:  My Professor is a very intelligent woman from China but her English is not so good.  I posted on the course forum asking where 238,659 comes from so hopefully she will clarify everything regarding cases, etc etc.  In the meanwhile, I thought there might be a simple explanation based on a few simple assumptions but I guess not.
Comment: First of all $238659 = 3 \times 19 \times 53 \times 79$.  Beyond that, normally I would edit your query to judiciously place line breaks.  Here I am scared to, because I don't want to garble your intent, which I can **not** at this moment decipher.  Questions: (1) Does each "letter" have exactly 26 independent possibilities (as if, there
is no distinction between upper case and lower case, and numbers are disallowed
and letters can repeat in the word)? (2) What **precisely** do you mean by
"mutations at 3 of 8 positions"? ...see next comment
Comment: (3) What does "...they did not copy..." signify?
Please do **not** respond by commenting.  Instead, please edit your query directly.
After that, if no one else responds, you can address a comment to @user2661923.
Comment: problem solved : see answer.
Answer: I was able to reverse engineer what the solution, based on the number
238,659.  The key issue is:
What constitutes a valid password?
Primary answer is :
Letters only, not case sensitive.  So there are 26 different characters that can be used.
The OP made the natural presumption that letters may not be repeated.  Using the
OP's presumption, I could not reverse engineer the answer.
I then explored the opposite presumption:
Letters may be repeated in the password.  This presumption ended up explaining 238,659.
The number of possible passwords is $D = (26)^8.$
There are $F = \binom{8}{3} = 56$ choices, for which 3 of the 8 letters will be wrong.
The # of ways that these 3 letters can be wrong is $N = (25)^3$.
Therefore, the chances of getting exactly 3 wrong characters out of the 8 are:
$$P = F \times \frac{N}{D} = \frac{56 \times (25)^3}{(26)^8}.$$
$P$ is approximately
$$\frac{1}{238659.5024}.$$
Comment: yes, I'm sorry I should have clarified more as my teacher is making an analogy with gene/nucleotide sequences or protein sequences so yes repetition is allowed.
Comment: @webNoob13 Also, your posting indicated "...P(n,r) = P(26,8)..." which is relevant **only** when repeated letters are not allowed in the password.
Comment: I see, that is what I tried, not something the instructor showed us.  Sorry again for the confusion.


How to correlate time series to a variable

Question: In an experiment, heart rate of participants is collected for 60 seconds (1 reading per seconds) and pupil diameter whilst performing one of three tasks. The success of the task is measured with a binary value (success/failure) indicating whether they achieved the expected result or not.
What is a good statistical model to find a correlation between two time series and the success/failure variable? I'm not trying to correlate the two time series, I'm trying to correlate both of them individually or together with the success/failure variable.
Data look like this
```
<code>Time, HR Reading, pupil size
0, 75, 0.01
1, 78, 0.012
2, 76, 0.011
...
...
59, 98, 0.04
</code>
```
Observation for this data is true.
Answer: As I've understood it, you basically want the probability of success depending the twao variables. In this case, a probit/logit model would be a good point to start:
$\pi_t=\alpha+\beta_1HR+\beta_2PS$
$P(y_t=1)=\Phi(\pi_t)$
with HR as the heart rate and PS as the pupil size.
Best wishes,
Richard
Comment: I think probit/logit models require independent variables to be independent of each other. In this case, I have 60 reading for HR and PS per dependent variable and HR readings are correlated and dependent.


Tips for Introducing New Exchange 2007 Cluster to Exisiting Single Exchange 2003 Server Domain

Question: Greetings!  Thanks in advance from a novice sys admin that's learning by living :)
I currently have a single Windows 2003 Std server running Exchange 2003 Ent that I inherited a few years ago.  We've got about 270 mailboxes and a database of about 100GB, so nothing crazy.  We're depending on email for business critical operations now more than when the system was built and put in place, so I'm working on building a more robust solution using CCR Exchange 2007/Server 2008 Ent clustering.  I'm buying the two servers and I've got a 3rd 2003 R2 server that's going to be the File Share Witness (Not an hub transport server but a server in the same domain).  I'm wondering when I build the cluster in the OS and start to install Exchange 2007 on both machines how it will effect the live 2003 exchange server and active 2003 domain?
What I'm hoping to do is bring up the cluster and install Exchange 2007 on both, which I think will show as one exchange server when I view it on the exchange 2003 box, then start migrating users a few at a time to the exchange 2007 cluster and eventually shutdown the exchange 2003 box.  With the domain running in 2003 native mode with a couple separate 2003 domain controllers, does anyone foresee any terrible issue I could be running into during this process?
I'm hoping to join the two new 2008 ent servers into the domain without breaking anything and then immediately installing exchange 2007 on them and just moving users over.  What do you think or what should I be concerned about?  Thanks!
Answer: When transitioning from Exchange 2003 to Exchange 2007, Microsoft recommends that you deploy your Exchange 2007 servers in this order:
Client Access Server, Hub Transport server ,Mailbox server, Unified Messaging Server.
It sounds like in your case all of those roles will be running on the new cluster, so before migrating the users mailboxes you'd want to verify that the CAS role is working properly.
Before you begin I would highly reccommend that you take a look at this series of articles:
A Practical Look at Migrating From Exchange 2003 to Exchange 2007
I would also watch this webcast:
TechNet Webcast: 24 Hours of Exchange Server 2007 (Part 05 of 24): Transitioning and Migrating to Exchange Server 2007 (Level 200)
Comment: Thanks so much!  I will have a single machine responsible for all the roles but have another as part of the cluster for fail-over.  So two in total just one active at a time.


Throwing 8 sided dice 3 times with the sum of the throws being 6, whats the probability that the first throw was 3?

Question: We already threw the 8 sided dice 3 times. The sum of these 3 throws was 6. Whats the probability that in our first throw we got 3?
I am a little lost on this one, but I would probably do it something like this:
3 _ _ -> 3 2 1 | 3 1 2  which is the 2 ways that we are trying to find the probability of happening. All possible ways to get sum of 6 would be: _ _ _ -> 2 2 2 -> 2 3 1 | 2 1 3 | 1 2 3 | 1 3 2 | 3 2 1 | 3 1 2 | 4 1 1 | 1 4 1 | 1 1 4. So is the probability 2/10?
Comment: The answer should be $\frac{2}{7}$, you counted the number of possible ways wrongly.
Comment: What are the values on this $8$-sided die??? Sounds to me like there should be at least $8$ distinct values. Not that it makes any difference from a $6$-sided die in the context of this question, but it sure as hell makes a difference with regards to your bizarre way of answering it, where you chose to ignore the value $4$. If this value is not present on the die, then I think you should care to mention that!!!
Comment: @barakmanos forgot about the 4. :b The thing is, I think this way of solving it is wrong, because it is conditional probability.
Comment: @Mykybo: You are now (after your fix) implicitly applying conditional probability (you can divide both the numerator and the denominator by $8^3$, but you'd get the same result).
Answer: The first roll is $3$ in $2$ out of $10$ cases (of the sum of $3$ rolls being $6$):

$1,1,4$
$1,2,3$
$1,3,2$
$1,4,1$
$2,1,3$
$2,2,2$
$2,3,1$
$\color\red{3,1,2}$
$\color\red{3,2,1}$
$4,1,1$

So the probability is $\dfrac{2}{10}$
Comment: Are you sure this is the way to solve it? Isn't it a conditional probability?
Comment: @Mykybo: By taking into account only the cases of the condition (the sum of $3$ rolls being $6$), I have effectively applied conditional probability. By editing your question and adding all the cases that I've mentioned above, you have effectively made my answer obsolete!
Answer: This is conditional probability.
If $A$ is the event that the first throw was $3$ and $B$ is the event that the sum is $6$, then you are looking for $P(A|B)$.
Using Bayes' Theorem:
$$ P(A|B) = \frac{P(A)P(B|A)}{P(B)}$$
$$P(A) = \frac{1}{8}$$
$$P(B|A) = P(sum\quad of\quad two\quad throws\quad is\quad 3) = \frac{2}{64}$$
$$P(B) = \frac{10}{512}$$
Thus
$$P(A|B) = \frac{2}{10} = \frac{1}{5}$$
Answer: You've missed the combinations 4 1 1, 1 4 1, 1 1 4
There'll be a total of 10 combinations with seven that you've mentioned
Thus the probability will be 2/10


Width of img parent is not scaled when image is up-scaled

Question: Container:

Image parent:

Image:

Example: https://codesandbox.io/s/q4q6lwj719
The image on the right (and a couple of css rules) makes left image render larger than its natural size. But its parent doesn't scale with it and is sized as if the image was rendered in its natural size.
Seems weird to me. Am I missing something?
NOTE: Some times (seems to be random) it's fixed in Chrome (v72.0.3626.119). In Firefox (v65), it's always broken.
Comment: Sorry I am not able understand what exactly you want. If you can explain how you would like them to show up then i can help
Comment: I want `div.item` to stretch horizontally based on its content width (the image). AFAIK, This is what normally happens for an element with `display: inline-block`
Comment: But it's sized based on **natural width of image**. In other words, the problem is only for the case when image is rendered larger than its natural size. Which is the case in this example.
Answer: It's because of the first element style
. By default the style align-items sets to stretch so your image makes larger than its natural size. Use the style align-items: center; or set it to baseline or whatever you want to prevent changing the size.

body {
  font-family: sans-serif;
}

.item {
  display: inline-block;
  max-height: 250px;
}

.item img {
  height: 100%;
}

Comment: Thanks. I actually want the `div.item` to stretch. I want images to have equal height. width should be adjusted according to aspect ratio.
Comment: The most weird thing is that when I uncheck 'display: inline-block' in chrome dev tools and check it again, `div.item` resizes correctly to match image width!


Area bound by algebraic curve $x^4 + y^3 = x^2y$ in first quadrant

Question: The area of the loop formed by the algebraic curve $x^4 + y^3 = x^2y$ in the first quadrant can be expressed in the form $A/B$, where $A$ and $B$ are relatively prime. Find $A+B$.
My attempt: I tried using a polar substitution $x = (rcosa)^{1/2}$ and $y = (rsina)^{2/3}$, but the resulting equation ended up being too difficult to integrate. Any help would be appreciated.
Comment: @B.Mehta In addition to my previous problem, it would be nice if you could provide a complete solution to these problems. I don't mind approving your answers and upvoting them, but I don't understand how parametric would even help in this and would rather see a solution to fully understand your thought process and how you solved this problem.
Answer: HINT:
If we draw the curve with some software ( for instance with WA ) then we see three branches through the point $(0,0)$. Therefore, a line $y = t x$ intersects the curve at $(0,0)$ with multiplicity $3$. There should be one more point of intersection, it's
$$(x,y) = (t-t^3, t^2 - t^4)=\gamma(t)$$
The desired loop is described by $0\le t \le 1$. The area equals
$$\int_{\gamma} x d y $$
Obs: In general, every curve of form $P_n(x,y) + P_{n-1}(x,y)=0$, where $P_n$, $P_{n-1}$ are homogenous of degree $n$, $n-1$, is parametrizable in a similar way.
Comment: Nice solution! From the diagram, is it obvious that the substitution $y=tx$ gives a convenient parametrisation - how does the multiplicity help?
Comment: @B. Mehta: It guarantees that the one more point of intersection has rational coordinates in $t$.
Comment: Your solution is easier than mine. Very nice! (I could swear that I actually tried to put $y=t x$ first, but I must have done some error in my calculation.)
Comment: @mickep: Thanks!  I use software for calculations whenever possible... so by hand I might have done some error too :)
Comment: I keep getting 4/105
Answer: From the expressions I would try with polar coordinates. You get the equation
$$
r^4\cos^4\theta+r^3\sin^3\theta=r^3\cos^2\theta\sin\theta
$$
from where you can conclude that you are interested in
$$
r(\theta)=\frac{\cos^2\theta\sin\theta-\sin^3\theta}{\cos^4\theta}
$$
You will find easily that the correct limits for $\theta$ are $0$ and $\pi/4$. I leave it to you to find the area, i.e. to integrate (it is elementary, but perhaps not the easiest way)
$$
\frac{1}{2}\int_0^{\pi/4}r(\theta)^2\,d\theta.
$$


Find all $n \in \Bbb Z$ such that $n^2 + n + 1$ divide $n^3-22$

Question: I need help with this problem:
Find all $n \in \Bbb Z$ such that $n^2 + n + 1$ divide $n^3-22$.
I've got to a point where I know that $n^2 + n + 1 | -21$. So it should be among {${-21, -7, -3, -1, 1, 3, 7, 21}$}.
How could I continue? Thanks
Comment: That's only $8$ possibilities, why not check them all?
Comment: @MichaelBurr Isnt there a another way? It's only ok for a small amount of numbers... and besides those would be numbers that satisfy $n^2+n+1$. So I should also then find which of these are solutions to that equation.
Answer: Check for all eight of these numbers whether they satisfy the given property. The ones that do are your solution.