Where to put the "such that", given multiple quantifier

Question: Personally, I would put the "such that" (i.e. the symbol $:$ or $|$) behind any quantification. That is given an assertion $A(x,y)$, I'd write
$$
\forall x\in X\exists y\in Y:A(x,y)\\
\exists x\in X\forall y\in Y:A(x,y)
$$
However, the lecturer giving the first graders course I'm tutoring writes
$$
\exists x\in X:\forall y\in Y A(x,y)
$$
in the second case (and the same as me in the first case), wich looks "wrong" to me. However, googling didn't produce any source that talks about placement of "such that" at all, so the question is: is there any rule or guideline where to put the "such that", and if so, what is it?
Comment: If the formula is prenexified, it only makes sense to put it after all quantifiers.
Answer: The "such that" is not required by the syntax of first-order logic.
The official syntax is :

$\forall x \exists y (x < y)$

which is an example of : $\forall x \exists y A(x,y)$.
The "such that" (i.e. the symbol ":" or "|") is used with the set builder notation :

$\{ x : \varphi(x) \}$ or $\{ x | \varphi(x) \}$

meaning : "the set of objects in the domain of discourse such that $\varphi$ holds of".

But the issue is with the "good" translation into natural language of the above formulae.
With :

$∀x∃yA(x,y)$

the natural reading is :

"for all $x$, there is an $y$ such that ..."

while for

$∃x∀yA(x,y)$

it "sounds better" :

"there is an $x$ such that, for all $y$ ...".
Comment: Yeah, i noticed the absence of $:$ in literature about logic, although the notation seems to be heavily used in papers and lecture notes in different fields. So it seems there's no real right and wrong here...
Comment: @roman - we can say that it is used in your examples as a "punctuation mark", for an easier reading of the formulae.
Comment: Well, it's as unnecessary as using it as a literal translation of "such that" ;) And since it's not part of the official syntax, it all boils down to personal opinion... Anyway, I think you gave a sufficient answer which I might very well accept in the near future.
Comment: Yeah, I get that point of view. Although, after finally figuring out what prenexified means, I think I agree more with GitGuts point of view. I.e. seeing the $:$ as a seperator of the string of quantifiers and the quantifier free part in a prenex normal form, instead of a literal "such that".
Comment: @roman - I understand ... but this is exactly why I've said that the symbol in the offical syntax is unnecessary; we have already parentheses to separate the prefix from the subformula which is the scope of the quantifiers, like : $\forall x \exists y ((x < y) \rightarrow (x \le y+1))$.
Comment: (-1). Firstly, there is no "official syntax." Rather, there is a "standard syntax." More importantly, your answer doesn't deal with the notational problem at hand. The issue is not the notation $\exists x \varphi$ and $\forall x \varphi$. Rather, it is the notation $\forall x \in X \varphi$ and $\exists x \in X \varphi$. And there is no standard notation here; some write a separating colon for both, others just for existence; I have even seen $\forall (x \in X) \varphi$ and $\exists(x \in X) \varphi,$ which is probably what I prefer.
Comment: @goblin - perhaps you do not know that $∀x \in X \varphi$ is only an **abbreviation** for $∀x (x \in X \rightarrow \varphi)$; so, the problem is in any case what is the "use" of the colon after the quantifier : it is only an issue of "readibility" or it affect the menaing of the formula ?
Answer: If you are talking at the colon (:), it is just a convenient delimiter for readability. You could also have written equivalently:
$\exists x\in X:\forall y\in Y : A(x,y)$.
Or you could leave them out entirely:
$\exists x\in X\space \forall y\in Y\space A(x,y)$.
Answer: 'Such that' typically introduces a restriction or condition that in many statements we do not want.
If we say 'for all $x$ in $S$, property $P$ holds', we are saying something different than if we say, 'for all $x$ in $S$ such that property $P$ holds,...'.
In the former case we are saying that $P$ holds for all $x\in S$. In the latter case we are saying we are looking at those $x\in S$ for which $P$ holds (which may or may not be all $x$ in $S$.


jQuery resizing animação

Question: Olá eu estou a fazer um site com uma pequena animação que é alterada consoante o tamanho
da janela mas existem 2 problemas na barra de nav. Os problemas são:

window > 800: a animação só é trigered quando quando eu mexo no tamanho da janela.
window < 800: queria que a animação deixa-se de fazer efeito e que respeita-se só os css (media queries para window < 800), mas continua, e o menu não respeita os media queries se o abrirmos depois da animação > 800 for ativada.

jQuery:
    $(document).ready(function(){

     $(window).resize(function () {
              if ($(window).width() > 800) {

        $('#upBar, nav').hover(function(){

            $('#upBar, nav ul').stop(true).animate({
                height: '60px'
            }, 200);

      });

      $('#upBar, nav').mouseleave(function(){

            $('#upBar, nav ul').stop(true).animate({
                height: '45px'
            }, 200);
    }
    else {

    }
    })
})

Comment: tinha fechado só a copiar para aqui é que não ficou
Answer: Resposta
O teu problema actual é que a acção só é anexada ao(s) elemento(s) se determinada condição se verificar, neste caso, a largura do ecrã maior que 800 pixeis.
Além disso, da forma que tens o código actualmente, é necessário a realização de uma "limpeza" de estilos resultantes da animação para que o layout continue a responder às media queries e/ou demais estilos no teu CSS.
A minha sugestão é alterares o teu código de forma a que os eventos de hover e mouseleave estejam sempre anexados aos elementos mas só ser realizada a animação se a condição se verificar: largura do ecrã superior a 800 pixeis.

Animação rato a entrar no elemento
Função com o código responsável por realizar a animação quando o rato entra no(s) elemento(s) alvo:
// Animação quando o rato vai para cima
function mouseEnterAnimation(allowAnimation) {
    if (allowAnimation) {
        $('#upBar, nav ul').stop(true).animate({
            "height" : "60px"
        }, 200);

        $('nav ul li').stop(true).animate({
            "padding-top"    : "20px",
            "padding-bottom" : "20px",
            "height"         : "60px"
        }, 200);

        $('#lang').stop(true).animate({
            "padding-top"    : "23px",
            "padding-bottom" : "23px",
            "height"         : "60px"
        }, 200);

        $('#logo').stop(true).animate({
            "margin-top"  : "15px",
            "margin-left" : "10px"
        }, 200);
    }
}

Animação rato a sair no elemento
Função com o código responsável por realizar a animação quando o rato sai do(s) elemento(s):
// Animação quando o rato sai de cima
function mouseLeaveAnimation(allowAnimation) {

    if (allowAnimation) {

        $('#upBar, nav ul').stop(true).animate({
            "height": "45px"
        }, 200, function() {
            $('#upBar, nav ul').removeAttr("style"); // limpeza
        });

        $('nav ul li').stop(true).animate({
            "padding-top"    : "13px",
            "padding-bottom" : "13px",
            "height"         : "45px"
        }, 200);

        $('#lang').stop(true).animate({
            "padding-top"    : "16px",
            "padding-bottom" : "16px",
            "height"         : "45px"
        }, 200);

        $('#logo').stop(true).animate({
            "margin-top"  : "7px",
            "margin-left" : "10px"
        }, 200);
    }
}

Dado importante, adicionei uma limpeza após a realização da animação, pois ficava o resíduo da mesma nos elementos e quebrava a altura do menu quando em telas menores que 800 pixeis.
O que fiz foi chamar uma função quando a animação termina em $('#upBar, nav ul'), onde digo que deve ser removida a tag style onde ficaram os estilos resultantes da animação:
$('#upBar, nav ul').removeAttr("style");

Inicialização do código e controlo da animação
Aqui estamos a inicializar o código e a controlar se a animação deve ou não ocorrer:
$(document).ready(function () {

    var $topNav = $('#upBar, nav'),                 // colocar elementos alvo em cache
        allowAnimation = ($(window).width() > 800); // verifica se deve animar

    $topNav.hover(
        function(){  // rato a entrar
            mouseEnterAnimation(allowAnimation);
        },
        function(){  // rato a sair
            mouseLeaveAnimation(allowAnimation);
        }
    );

    $(window).resize(function() {
        allowAnimation = ($(window).width() > 800); // atualiza se deve animar
    });
});

Em primeiro estamos a colocar os elementos alvo em cache, para evitar que estejamos sempre a localizar os mesmos no DOM;
Depois estamos a iniciar a variável que autoriza ou nega a animação com o valor resultante da condição largura de tela maior que 800 pixeis (vamos obter ou true ou false);
Anexamos o evento de rato a entrar e rato a sair ao elemento que colocamos em cache;
Se o rato estiver a entrar, chamamos a função mouseEnterAnimation() e passamos à mesma o estado da animação contido na variável allowAnimation;
Se o rato estiver a sair, chamamos a função mouseLeaveAnimation() e passamos à mesma o estado da animação contido na variável allowAnimation;
Por último, sempre que a janela está a ser redimensionada, vamos actualizando a nossa variável de controlo com o resultado da condição.

Resultado das alterações em cima apresentadas
O teu ficheiro navBar.js ficaria assim:
// Animação quando o rato vai para cima
function mouseEnterAnimation(allowAnimation) {
    if (allowAnimation) {
        $('#upBar, nav ul').stop(true).animate({
            "height" : "60px"
        }, 200);

        $('nav ul li').stop(true).animate({
            "padding-top"    : "20px",
            "padding-bottom" : "20px",
            "height"         : "60px"
        }, 200);

        $('#lang').stop(true).animate({
            "padding-top"    : "23px",
            "padding-bottom" : "23px",
            "height"         : "60px"
        }, 200);

        $('#logo').stop(true).animate({
            "margin-top"  : "15px",
            "margin-left" : "10px"
        }, 200);
    }
}

// Animação quando o rato sai de cima
function mouseLeaveAnimation(allowAnimation) {

    if (allowAnimation) {

        $('#upBar, nav ul').stop(true).animate({
            "height": "45px"
        }, 200, function() {
            $('#upBar, nav ul').removeAttr("style");
        });

        $('nav ul li').stop(true).animate({
            "padding-top"    : "13px",
            "padding-bottom" : "13px",
            "height"         : "45px"
        }, 200);

        $('#lang').stop(true).animate({
            "padding-top"    : "16px",
            "padding-bottom" : "16px",
            "height"         : "45px"
        }, 200);

        $('#logo').stop(true).animate({
            "margin-top"  : "7px",
            "margin-left" : "10px"
        }, 200);
    }
}

$(document).ready(function () {

    var $topNav = $('#upBar, nav'),
        allowAnimation = ($(window).width() > 800);

    $topNav.hover(
        function(){
            mouseEnterAnimation(allowAnimation);
        },
        function() {
            mouseLeaveAnimation(allowAnimation);
        }
    );

    $(window).resize(function() {
        allowAnimation = ($(window).width() > 800);
    });
});

Revisão
Eu fiz o download dos ficheiros do site a que te referes na pergunta, e devo alertar para o facto de que tens um exército de problemas a resolver se queres que as coisas funcionem como pretendido:

Auto-fechar tag HTML
Não é suposto estares a auto-fechar a tag html, uma vez que a mesma deve ser fechada no final de toda a markup do documento:

Deveria estar:

O menu tem a markup trocada
No teu menu, tens uma lista que contém links para as várias áreas do web-site, mas a mesma contém a markup trocada onde estás a envolver as li em a quando deveria ser ao contrário, as li a envolver os a:

PT / EN

Notícias

Logística

Serviços

Quem Somos

Deveria ser:

    PT / EN

    Notícias

    Logística

    Serviços

    Quem Somos

Tens um erro referente ao Stellar.js v0.6.2:

TypeError: $.stellar is not a function
  file:///home/salustiano/Desktop/w/Intertrafego/quem_somos.html
  Line 82

Erros de JavaScript geralmente interrompem a execução de JavaScript na página, particularmente em navegadores um pouco duros com o programador.
O problema está na tag script que inclui o Stellar.js cuja mesma está:

Mas o ficheiro chama-se jquery.stellar.js, repara na palavra jquery tudo em letras minúsculas, pelo que ou alteras o nome do ficheiro ou a chamada ao mesmo:

A tag de script (Inglês) pode ser utilizada para conter diversos tipos de script, pelo que deve ser indicado qual o tipo presente na mesma uma vez que não existe um valor por defeito e o atributo type é obrigatório:

This attribute specifies the scripting language of the element's contents and overrides the default scripting language. The scripting language is specified as a content type (e.g., "text/javascript"). Authors must supply a value for this attribute. There is no default value for this attribute.

Que traduzido:

Este atributo especifica a linguagem de script do conteúdo do elemento e substitui a linguagem de script padrão. A linguagem de script é especificada como um tipo de conteúdo (por exemplo, "text/javascript"). Os autores devem fornecer um valor para este atributo. Não há valor padrão para este atributo.

No teu documento, onde tens:

Deverias ter:

Resultado da revisão
Uma versão melhorada do teu ficheiro quem_somos.html:
<!DOCTYPE html>

        <meta charset="UTF-8">
        <title>Intertrafego - Quem Somos</title>

        <link rel="stylesheet" href ="css/navBar.css">
        <link rel="stylesheet" href ="css/footer.css">
        <link rel="stylesheet" href ="css/stylesAboutUs.css">
        <meta name="viewport" content="width=width-device, initial-scale=1.0"/>

PT
↓
En

                            PT / EN

                            Notícias

                            Logística

                            Serviços

                            Quem Somos

3 GERAÇÕES DE SERVIÇOS

Fundada em 1967, a Intertráfego atua como agente de transportes e transitários internacionais. Tem como base de clientes algumas das mais prestigiadas empresas do nosso país, com um serviço profissional e personalizado. Possui uma frota própria e capacidade de armazenagem. O crescimento gradual desde o seu nascimento, traduz o sucesso de negócio em 3 gerações.

PEDRO NUNES & TOMÉ ELIAS

MATURIDADE

Fundadores

Experiência de mercado e metodologia.

JOAQUIM PEDRO

PARCERIAS

Experiência e know-how no mercado internacional, participando em congressos e feiras internacionais

Rede de contactos, agentes, fornecedores e clientes.

MIGUEL NUNES

INOVAÇÃO

Novos conceitos e empreendorismo

Inovação e novas tecnologias.

MISSÃO

A Intertráfego tem como principal missão crescer em conjunto com os seus parceiros, sempre com alta qualidade de serviço e flexibilidade na resolução das necessidades dos seus clientes. Acreditamos que a chave do sucesso está na disponibilidade e empenho que alocamos a cada projecto o que se revela também nas nossas práticas e ambições além fronteiras.

VALORES

A identidade da Intertráfego é moldada pelos seus clientes e serviços. Quatro valores fundamentais unem a empresa e formam a base da cultura de sucesso empresarial da mesma: Segurança, Inovação, Fiabilidade e Flexibilidade. Os valores assentam na herança das suas gerações e são fonte de inspiração para o futuro.

firstname.lastname@example.com

+(351) 263 470 020

PEDIR COTAÇÃO

Nota: Existem outras coisas que podiam ser melhoradas, mas realcei apenas o mais problemático.
Comment: Muito obrigado Zuul, perfeito funcionamento. És muito bom nisto. obgado pelas dicas
Answer: O código está adicionando eventos aos elementos quando a window > 800
Só que depois quando a janela fica menor, os eventos ainda estao la, pois eles nao foram removidos.
.hover() API: http://api.jquery.com/hover/

"Bind one or two handlers to the matched elements"

Uma solução possível é colocar o teste do tamanho da janela dentro de cada função executada quando os eventos são acionados:
$(window).resize(function () {
    $('#upBar, nav').hover(function(){
        if ($(window).width() > 800) {
          $('#upBar, nav ul').stop(true).animate({
              height: '60px'
          }, 200);
        }
    });

    $('#upBar, nav').mouseleave(function(){
        if ($(window).width() > 800) {
          $('#upBar, nav ul').stop(true).animate({
              height: '45px'
          }, 200);
        }
    }
});

Comment: Não preciso adicionar um 'else' vazio? esse codigo faz sentido mas não está a acontecer nada. Obgado

jQuery resizing animação


How can I make my application I filter a custom inherited angular default filter it?

Question: I just want to repackage the currency filter,someone knows filter inherited way?
If anyone knows the best solution, please tell me, I would be appreciate it!!!!
Comment: You want to create a filter that extends the currency filter? Your best bet might be to just copy it and have your own. You can sometimes override built in directive behavior, just depends on what you want to do. Can you provide some more detail?
Comment: yes,I want to creat a filter extends the currency filter
Answer: You can list more than one filter in your expression.
First, use the currency filter, then follow up in the same expression with your own custom filter.
For example:

{{model.property | currency: '€' | customfilter}}

customfilter here is the filter you defined. the value of model.property will first be processed by the standard Angular currency filter, then the result will in turn be processed by your customfilter. The final result is displayed.


Minus values Oracle SQL

Question: I have the below Oracle working fine however I want to calculate Sum(manhours)-Leavetaken
I am unsure if this is because some of values of Leavetaken are null so it's pulling back null if I try it as above. But if even leavetaken is null, I want just the full value of sum(manhours)
Here's  my current query:
select lsc.work_date, location,site, sum(manhours), Leavetaken
from location_site_capacity lsc
left outer join (
    select work_date, sum(manhours) as Leavetaken from location_site_capacity
    where break is not null
    group by work_date) A on A.work_date = lsc.work_Date
where lsc.work_date between '01/JUN/15' and '30/JUN/15'
group by  lsc.work_date, location,site, Leavetaken
order by lsc.work_Date,location

Answer: Use coalesce() on Leavetaken, like this:
select ..., sum(manhours) - coalesce(Leavetaken, 0) as calc

coalesce() returns the first non-null value.
Comment: seems perfect :) will run a few quick tests but looks exactly like what i need :) thanks so much! not aware of the 'coalesce' function will read into it for future knowledge

Minus values Oracle SQL


Simplificar subtração entre tabelas MySQL

Question: Queria saber como simplificar o seguinte trecho:
SELECT FORMAT((SUM(r.valor_receita) - (SELECT SUM(d.valor_despesa)
FROM despesas AS d WHERE d.pago = 1 AND YEAR(r.data_vencimento) <= YEAR(d.data_vencimento)
AND MONTH(r.data_vencimento) <= MONTH(d.data_vencimento) AND r.id_usuario = d.id_usuario)),2,'de_DE')
AS saldo_efetivo
FROM receitas AS r WHERE r.recebido = 1 AND YEAR(r.data_vencimento) <= '2017' AND MONTH(r.data_vencimento) <= '06' AND r.id_usuario = 1

O que ele faz atualmente é somar o valor de todas as receitas recebidas (recebido = 1) e subtrair com o subselect que soma todas as despesas pagas (pago = 1).
Queria saber se dá pra simplificar esse query.
Comment: Alguém pra me ajudar aqui?
Answer: Da maneira que está montada a estrutura de tabelas acredito que não há maneira melhor para fazer, porém se as estruturas de tabelas forem iguais, aconselho você a deixar tudo na mesma tabela com um campo que defina o tipo ("Despesa" ou "Receita"), por exemplo:
SELECT
    SUM(IF(tipo = 1,valor,valor*-1)) -- 1 - Receita / 2 - Despesa, Sendo assim faria o valor *-1 para ficar negativo
FROM tabela_contas
WHERE confirmado = 1 -- Seria se o valor foi pago ou recebido
-- E aqui o resto das suas condições


Cordova: Android target: not installed avdmanager: Command failed with exit code 1

Question: I am trying to work with cordova and after installing android studio, SDK and all other requirements when I check the requirements I get the following error:

all solutions I found here say I should add Both JAVA_HOME and ANDROID_HOME to environment variables, also the path of tools, tools/bin and platform-tools, which I did:

and still the same error.. I dont know what to do :(
OS: Ubuntu 18.04
Answer: looks like I needed to also set java home in /etc/environment as follows:
JAVA_HOME="/usr/lib/jvm/java-8-openjdk-amd64"
and now the problem is solved:)


Unsupervised soft clustering methods

Question: I have a D-dimensional dataset composed of exactly two clusters (this is known) for which I have no labels; the clusters can potentially be wildly imbalanced.
I'm after a soft (or fuzzy) clustering method to assign probabilities to each element of belonging to either cluster. So far I've been able to come up with basically two:

Fuzzy K-means
Gaussian Mixture Models

Then there are methods that apply hard clustering that could perhaps be softened by re-running varying the inputs (and averaging all the iterations?):

DBSCAN
Hierarchical

And finally there's also those methods that I'm not sure whether they can be applied in an unsupervised way at all:

Random Forests
Mean Shift
BIRCH

Am I missing some method? Did I miss-classify any of the above? Is any method more suited to my particular issue than the rest?
Any insight will be much appreciatted.
Comment: Of course model-based clustering based on any mixture will do, not only Gaussian.
Answer: UPDATE
(Looking back on the OP, I would recommend running FKM and GMM, then try to publish the analysis based on that, or give a talk based on use of FKM/GMM.  There is nothing wrong with use of FKM/GMM for your OP.  You may be "missing" a lot other unknown/unpopular methods which develop probabilities -- so construction of list that misses nothing would become open-ended).
Only fuzzy k-means provides "membership function" values for each object, and GMM provides cluster-specific probabilities, $P(cluster|x)$.  "Crisp" k-means cluster analysis (opposite of fuzzy, i.e., the typical k-means) can provide something like a cluster-specific probability if you assume that Euclidean distance to the closest centroid represents a probability. There may be more methods that do this, but generally speaking, most other unsupervised methods are based on distance metrics, not probabilities.
I wouldn't get "hung up," i.e., interested on being exact about all the various unsupervised methods and which ones do and don't provide cluster-specific probabilities.  If you are writing a review, book chapter, or a report for school, you shouldn't ask this forum about it.
Have you grasped the full literature on this topic?  You'd get a much better answer doing your own research.
Comment: see the updated answer - if a final list were required, it would be an open-ended question.
Comment: Also, did you run FKM and GMM yet, and submit the paper or give the talk?  What did the reviewers (audience) say?

Unsupervised soft clustering methods


Do while em python

Question: Existe algum comando semelhante ao do while de c e Java na linguagem python?
Estou entrando na linguagem agora e já desenvolvia em java aí me surgiu essa dúvida
Answer: Não, mas praticamente todo loop na maioria das linguagens pode ser feito de várias maneiras.
Pseudocódigo:
do:
  fazCoisa()
  while condicaodesejadaparacontinuar

Escrevendo em Py:
while True:
  fazCoisa()
  if not condicaodesejadaparacontinuar:
    break

Ou seja, em vez de fazer e dar loop se verdadeiro, invertemos para fazer sempre (while True) até que seja falsa a condição desejada (break para quebrar o loop).
Answer: Não!
Mas você pode Simular um do while...

Linguagem C:

int i = 1;

do{
  printf("%d\n", i);
  i = i + 1;
} while(i <= 3);

Python:

i = 1

while True:
    print(i)
    i = i + 1
    if(i > 3):
        break

Answer: Não propriamente.
While:
O comando while faz com que um conjunto de instruções seja executado enquanto uma condição é atendida. Quando o resultado dessa condição passa a ser falso, a execução do loop é interrompida, como mostra o exemplo a seguir:
    contador = 0
    while (contador < 5):
           print(contador)
           contador   = contador + 1

    contador = 0
    while (contador < 5):
           print(contador)
           contador = contador + 1
    else:
           print("O loop while foi encerrado com sucesso!")

While - Else:
Ao final do while podemos utilizar a instrução else. O propósito disso é executar alguma instrução ou bloco de código ao final do loop,

Do while em python


How to preserve audio from old tapes: baking tapes to transfer to digital?

Question: In my loft I have a collection of old quarter-inch tapes dating back to the eighties, mostly, though some as far back as the sixties. I'd like to be able to hear these again, and maybe transfer some of them to digital. However, I've heard that old tapes deteriorate and shed their oxide when attempting to play them. I've heard that they can be baked in an oven, and that this can allow one last play, sufficient to transfer the material. Before I try for myself and maybe damage them, does anyone have a definitive answer and/or practical experience of this? Is a domestic oven suitable? What time and temp? How about other formats - I also have some miniDV video tapes from the early 2000's - anything I should know about those too? Any suggestions welcome - thanks.
Comment: I'm voting to close this question because it has nothing to do with music, practice *or* theory.
Comment: @Tim  OTOH I view this as just as appropriate as the myriad questions about connecting stompboxes or MIDI tool interactions.   Now get offa my lawn you youngsters
Comment: @CarlWitthoft  - point taken, although it's hardly about *music* per se. It ccould be speeches, etc... And I allow youths onto my lawn - but only behind a lawnmower!
Comment: @Tim, Carl There is an at least tenuous, (but IMO sufficient!), connection to music. The tapes are mostly 8-track and stereo masters from the studio I had in my basement in the 80's, plus a few live performances by local bands - one of whom are building a nostalgic website featuring their music - and my tape is the only record of them playing live that still exists.
Answer: Sticky-shed
The great 80s tape debacle  - which I'm determined these days should be called  ShedShed;) - affected a few tape types from the period. The first to be spotted & which spawned the investigation to find a cure was the Ampex 456, which was the studio mastering tape of the era.
Even if your tape doesn't suffer from it, you still need to take care, ensure paths are clean & that there's no 'simple' age-shedding, which can still happen, even if you don't get sticky-shed.
Sticky-shed is different from regular shedding. Old tape passing over the heads will cast off 'dust' [literally losing particulate of the magnetic surface] from its surface, causing loss of top-end as it starts to crowd the repro head. Cleaning the heads after each tape, or at worst each track, will give you a pass at rescue.
Sticky-shed, however, takes this one large leap further. Not only does the surface shed particulate, but the entire substrate will cling to the heads. It may squeak or judder & in the worst cases will be sticky enough to actually jam solid on a head - causing havoc .
If you get sticky-shed, you have to bake your tapes.
Do not do this in a domestic kitchen oven! The temperature control is nowhere near good enough.
Tape baking is a 'fun' task best done with either a commercial incubator [very expensive] or an American Harvest food dehydrator.
I kid you not.
They are the perfect shape for 10" reels & even have a post in the middle that the NAB centres fit round. You can get 4 ¼" tapes at a time in the regular model - double in the 'deluxe' - or by removing some of the internal shelves 2 ½" or even a 1" or 2".
All you need is the cheapest old one you can find on eBay, so long as it has a variable thermostat. You don't need any of the fancy gubbins they put in the lid of the modern ones.
I did my entire 80's Ampex collection with one, irreplaceable master tapes - took weeks, but I rescued every one. A friend of mine borrowed it a couple of years ago to rescue his, with similar success.
I did find this - Wikipedia - Sticky-Shed Syndrome whilst I was trying to remember the temperature range - 130 °F to 140 °F (54 to 60 °C) for 1 to 8 hours.
Practically, though, you should leave them a good while to warm, then another while to cool & settle before swapping batches. It's probably over-kill, but it's safe. I used to set up a batch in the evening, switch off in the morning, leaving it to cool & set a new batch the next evening.
BTW, this shouldn't wreck any edits/splices in itself, but depending on the quality of your splicing tape, it may have already degraded. Mine was absolutely fine, before & after, fortunately; including some heavily-edited 12" mixes.
Late edit - Reading the Wikipedia article [which I hadn't done previously] it says that baking drives off moisture - that is presumably why a dedicated dehydrator turns out to be the perfect machine for the task, aside from the fact it looks like it was made to put tapes in anyway ;) It has constant controlled heat & a fan system which pulls air through the device all the time you are 'baking', evaporating & extracting the moist air.
Note:
You only get one go at this.
Bake, rescue to digital in one pass. That's it. A second pass will start to degrade & a few weeks later the tapes will have reverted to sticky-shed.
[There's a little more leeway than that sometimes, but it's best to play safe.]
You can get plugins/apps these days that can correct for azimuth, wow & flutter, so if it's 'close enough for jazz' without doing a proper line-up, just go for it & 'fix it in the mix'. If you have line-up tones, transfer them too.
Comment: Even assuming you get no water in the bag at all, you also wouldn't be releasing any other gases - & I honestly don't know what 'boils off' in this process, but something must.
Comment: @Tetsujin Thorough and comprehensive answer, thanks. Everything I need to know.
Comment: I wonder if you could bake effectively in a home sous-vide.
Comment: @kojiro - reading the Wikipedia article [which I hadn't done previously] it says that baking drives off moisture - that is presumably why a dedicated dehydrator turns out to be the perfect machine for the task. It has constant controlled heat & a fan system which pulls air through the device all the time you are 'baking'.


How do I structure the batch API array?

Question: I'm working on a Drupal 8 custom module to scrape pages from a site for migration. Since we're dealing with a large number of pages, I wanted to set up batch processing, to deal with timeouts.
I looked at two tutorials, this one, and one here. However, when I ran my batch, it didn't work as expected. The progress bar immediately filled up to all 71 items, and there were no imported pages, but a number of errors in the error log.
To rule out confounding factors, I created a simple module for testing the batch api (I didn't find the batch represented in the D8 examples module). It exhibits the same behavior: it immediately processes all items, and there are no successes, just errors. This an the example error:
 Warning: call_user_func_array() expects parameter 1 to be a valid callback, class '\Drupal\batch_test\BatchTestForm' not found in _batch_process() (line 252 of C:\wamp64\www\D8\core\includes\batch.inc)
`#0` C:\wamp64\www\D8\core\includes\bootstrap.inc(566): _drupal_error_handler_real(2, 'call_user_func_...', 'C:\\wamp64\\www\\p...', 252, Array)
`#1` [internal function]: _drupal_error_handler(2, 'call_user_func_...', 'C:\\wamp64\\www\\p...', 252, Array)
`#2` C:\wamp64\www\D8\core\includes\batch.inc(252): call_user_func_array('\\Drupal\\batch_t...', NULL)
`#3` C:\wamp64\www\D8\core\includes\batch.inc(95): _batch_process()
`#4` C:\wamp64\www\D8\core\includes\batch.inc(77): _batch_do()
`#5` C:\wamp64\www\D8\core\modules\system\src\Controller\BatchController.php(55): _batch_page(Object(Symfony\Component\HttpFoundation\Request))
`#6` [internal function]: Drupal\system\Controller\BatchController->batchPage(Object(Symfony\Component\HttpFoundation\Request))
`#7` C:\wamp64\www\D8\core\lib\Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber.php(123): call_user_func_array(Array, Array)
`#8` C:\wamp64\www\D8\core\lib\Drupal\Core\Render\Renderer.php(574): Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber\{closure}()

The following is the form that I'm using. Both of the tutorials indicate that calling _batch_process() is not necessary when calling batch_set() in a form submit.
namespace Drupal\batch_test\Form;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Form\FormBase;

class BatchTestForm extends FormBase {

  public function getFormId() {
    return 'batch_test_admin_form';
  }

  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Test Batch'),
      '#button_type' => 'primary',
    ];
    return $form;
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {
    $batch = array(
      'title' => t('Test Batch'),
      'operations' => [],
      'finished' => 'Drupal\BatchTest\Form\batchCallback',
      'progress_message' => t('Processed @current out of @total.'),
    );

    for ( $i = 0; $i <= mt_rand(10,100); $i++ ) {
      $batch['operations'][] = ['\Drupal\batch_test\BatchTestForm::process',$i];
    }

    batch_set($batch);
  }

  public function process($input, &$context) {
    // log a random string
    \Drupal::logger('batch_test')->notice(base64_encode(random_bytes(10)));
    sleep(mt_rand(1,100));
  }

  public function batchCallback($success, $results, $operations) {
    if ($success) {
      $message = \Drupal::translation()->formatPlural(
        count($results),
        'One page scraped.', '@count pages scraped.'
      );
    }
    else {
      $message = t('Finished with an error.');
    }
    drupal_set_message($message);
  }
}

I suspect that something is wrong in the specification of the $batch variable, but I've cross-checked it, and it seems to conform to what the tutorials indicate.
The example in the documentation does not clearly indicate how to pass multiple data points to be called on with the same function.
  'operations' => array(
    array('my_function_1', array($account->id(), 'story')),
    array('my_function_2', array()),
  ),

Interestingly, one tutorial says to pass the data as a single array.
$batch = array(
  'title' => t('Deleting Node...'),
  'operations' => array(
    array(
      '\Drupal\batch_example\DeleteNode::deleteNodeExample',
      array($nids)
    ),
  ),
  'finished' => '\Drupal\batch_example\DeleteNode::deleteNodeExampleFinishedCallback',
);

Another tutorial indicates to pass each data point as a separate element in the operations array.
$operations = [];
foreach ($letters as $letter) {
  $operations[] = ['smackmybatch_process_letter', [$letter]];
}

I'm not entirely sure what this one is specifying.
  'operations' => array(
    array('disc_migrate', array('courses', array('foo' => 'bar'))),
  ),

So, what is the correct way to pass the data that I want to have processed in the batch API?
Comment: According to your namespace declaration `$batch['operations'][] = ['\Drupal\batch_test\BatchTestForm::process',$i];` should be `$batch['operations'][] = ['\Drupal\batch_test\Form\BatchTestForm::process',$i];`; which would explain the warning your get first.
Answer: I have a working batch similar to your example. Here is my code with some comments. I see that you don't use a .batch.inc file, maybe there is the problem, just try using it. I will try to use the same class to see if it works for me.
  public function submitForm(array &$form, FormStateInterface $form_state) {
    //path to file
    $file = drupal_get_path('module', 'diocese_migrate') . '/csv/saint-du-jour.csv';
    //Exploding by ;"0" because the file is malformed
    $lines = explode(';"0"', file_get_contents($file));
    array_pop($lines);

    $operations = [];
    foreach ($lines as $line) {
      $operations[] = ['process_line_saint_du_jour', [$line]];
    }

    $batch = array(
      'title' => t('Migrating Saint of the Day'),
      'operations' => $operations,
      'finished' => 'process_line_saint_du_jour_batch_finished',
      'init_message' => t('Saint of the Day migration is starting.'),
      'progress_message' => t('Processed @current out of @total. Estimated time: @estimate.'),
      'error_message' => t('The migration process has encountered an error.'),
      'file' => drupal_get_path('module', 'diocese_migrate') . '/diocese_migrate.batch.inc',
    );

    batch_set($batch);
  }

diocese_migrate.batch.inc file
<?php
use Drupal\node\Entity\Node;

function process_line_saint_du_jour($line, &$context) {
  $info = str_getcsv($line, ";", '"');

  $title_fr = 'Saint du jour ' . $info[2];

  $node = Node::create([
    // The node entity bundle.
    'type' => 'saint_du_jour',
    'langcode' => 'fr',
    'created' => REQUEST_TIME,
    'changed' => REQUEST_TIME,
    // The user ID.
    'uid' => 1,
    'title' => $title_fr,
  ]);
  $node->save();

  $context['results'][] = $info[3];
  $context['message'] = t('Migrating Saint du jour @day', array('@day' => $info[3]));
}

function process_line_saint_du_jour_batch_finished($success, $results, $operations) {
  // The 'success' parameter means no fatal PHP errors were detected. All
  // other error management should be handled using 'results'.
  if ($success) {
    $message = \Drupal::translation()->formatPlural(
      count($results),
      'One Saint of the Day processed.', '@count Saint of the Day processed.'
    );
  }
  else {
    $message = t('Finished with an error.');
  }
  drupal_set_message($message);
  //$_SESSION['disc_migrate_batch_results'] = $results;
}

Comment: Can you think of a way t improve your answer by trying to answer the question at the very end of the question itself?
Comment: @Pierre.Vriens it seems that the user found the answer using the class version :-) I'm prefer this approach using a file with functions, What version do you think is better? Using a class with static functions or using a file with functions?
Comment: Adrian, not sure which one is "better", but my preference is similar to yours! PS: a shame the bounty hasn't been granted (yet) ... to "your" answer (a much better way to say "thanks", no?). Nevertheless, looking at the [timeline](https://drupal.stackexchange.com/posts/247147/timeline) of this question it looks like in about 2 hours from now your answer will receive 50% of that bounty anyway ... according to the [Rules](https://www.drupal.org/project/rules) (oeps: rules) of SE-bounties ...
Comment: @Pierre.Vriens it seems that is not for me, the point has gone with no reward: "If the bounty was started by the question owner, and the question owner accepts an answer posted during the bounty period, and the bounty expires without an explicit award then we assume the bounty owner liked the answer they accepted and award it the full bounty amount at the time of bounty expiration."
Comment: The bounty started on Oct 4, at 15:00 UTC. Add to that exactly 7 days + 1 day grace period. If then the bounty expired (and not granted to anybody), it takes about 1 more hour for some "next batch run" to execute. That run will then pick the first answer posted AFTER the bounty, which has a voting balance of at least 2 ... and grant 50% of the bounty amount anyway ... Check the timeline again, to see which answer will get that 50% in the coming minutes or so, wanna bet? If it's not your answer, then it is a bug in this process, trust me ... PS: some SE users don't like my SE-knowledge ...
Comment: ***Voilà!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*** I told you so only 5 mins ago ... Some day I might add a ´answers_bounty´-submodule to the [Answers](https://www.drupal.org/project/ad), which will have "Rules" and "User Points" as a prereq, and with a functionality equivalent to the SE bounty system ... BTW, how about a auestion on SE like "How to implement the equivalent of an SE-bounty system in a Drupal site?"
Comment: @Pierre.Vriens I just see it, I really need to learn more about how this site works ;-)
Answer: Some points about the code you provided:

The method (or methods) defined in the 'operations' list should be correctly namespaced; you are using the wrong namespace, which is why see that warning comes and the whole batch is failing.
The method (or methods) defined in the 'operations' list should be part of a separate class, as a best practice.
The method (or methods) defined in the 'operations' list should be defined as public static methods, as the batch API should not be expected to construct objects, and it should be able to access the method.

General answer to your question:
The correct way to pass data to the batch processing function, is by enclosing them in an array; this is the normalized format that allows you to pass multiple arguments to your function. For example, and for the following batch processing function:
namespace Drupal\mymodule;

class MyBatchClass {
  ...
  public static function myBatchProcessorCallback(
    $someString,
    $uid = 1,
    &$context) {
    ...
  }
}

you can add the following operations to your batch definition array:
$batch = array(
  'title' => $this->t('Dummy processing'),
  'operations' => [
    [
      '\Drupal\mymodule\MyBatchClass::myBatchProcessorCallback',
      ['randomStringA'],
    ],
    [
      '\Drupal\mymodule\MyBatchClass::myBatchProcessorCallback',
      ['randomStringB', 2],
    ],
  ],
);

Hope this helps, it really does seem that the namespacing is causing all your worries, good luck.
Answer: As this was for me a really time consuming issue, I uploaded an example module on my GitHub page: drupal 8 batch import example with interaction.
$batch = [
  'title' => t('Importing animals'),
  'operations' => [],
  'init_message' => t('Import process is starting.'),
  'progress_message' => t('Processed @current out of @total. Estimated time: @estimate.'),
  'error_message' => t('The process has encountered an error.'),
];

foreach($data as $item) {
  $batch['operations'][] = [['\Drupal\batch_import_example\Form\ImportForm', 'importAnimal'], [$item]];
}

batch_set($batch);

Answer: Thanks for your answers, everyone. First off, I did not name the function properly, as several have noted.
Second, it turns out that the fourth example has the structure that worked for me. I don't know why it would vary, but whatever.
Here's the submit function from my actual, final module:
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $batch = array(
      'title' => t('test batch'),
      'operations' => array(),
      'finished' => 'Drupal\test_batch\Api\Form\batchCallback',
      'progress_message' => t('Scraped @current out of @total urls.'),
    );
    foreach ( \Drupal\test_scrape\Api\Scraper::loadUrls() as $url ) {
      $batch['operations'][] = [
        '\Drupal\test_scrape\Api\Scraper::batchScrape',
        ['test_scrape', [$url]]
      ];
    }
    batch_set($batch);

And here's the callback its referencing:
src/Api/Scraper.php
  /**
   *  wrapper for batch callback
   */
  public static function batchScrape($type, $operations=[], &$context) {
    foreach ( $operations as $url) {
      self::scrape($url);
      $context['message'] = "Migrated $url
\n"  . $context['message'] ;
    }
  }

How do I structure the batch API array?


Setas não se movem em campo de texto com regex

Question: Tenho a seguinte código com uma expressão regular dentro de um método Keyreleased, que permite somente alguns caracteres ser digitados pelo usuário em um campo de texto:
String text = input.getText();
text = text.replaceAll("[^A-Za-z&\\|!]", "");
input.setText(text.toUpper());

Ao tentar pressionar as teclas de setas como <-(esquerda) ou (direita) ->, a expressão regular não deixa eu voltar na string para editar algo, o Regex não permite.
Exemplo:

O cursor nesse momento está a frente de C, mas não consigo voltar o cursor de forma que fique na frente de B ou A.
Alguém saberia me dizer como resolver esse problema?
Comment: Eu apliquei essa mesma query aqui e não deu o problema. Se você não fornecer um **[mcve]** fica complicado te ajudar. Repito: **o problema em nada tem a ver com o replaceAll ou com a regex**, é outro pedaço do código que você não está informando.
Comment: E o código pra testar?
Comment: Normalmente esse `text.replaceAll` não é usado para tratar eventos de chave pressionada. Onde está o resto do código?
Answer: Conforme mencionei nos comentários mas nunca é demais repetir, o problema em nada tem a ver com o replaceAll ou com a regex, e sim com o listener que você está usando.
O evento KeyReleased é disparado toda vez que uma tecla é liberada após ser pressionada. Setas também são teclas, então cada vez que você apertar alguma, o evento será disparado.
Como você não forneceu um trecho relevante para análise, vou supor que seu evento esteja semelhante ao abaixo:
@Override
public void keyReleased(KeyEvent e) {
    JTextComponent input = ((JTextComponent) e.getSource());
    String text = input.getText();
    text = text.replaceAll("[^A-Za-z&\\|!]", "");
    input.setText(text.toUpperCase());
}

Perceba que cada vez que uma tecla for pressionada no campo de texto, toda esta rotina irá ocorrer. E quando você pressionar uma tecla de direção(ou setas), todo o texto do campo será filtrado pela regex e depois reaplicado no campo, e isso fará com que o Caret padrão(aquele cursor de texto que aparece no campo),se mova para o final da nova sentença aplicada.
Não é recomendado que se use eventos de teclado para filtrar strings em campos de textos, haja visto que campos de textos possuem outro meio adequado para isso, que é através das classes derivadas de Document .
Nesta resposta há um exemplo de uso da classe PlainDocument, adaptando para sua situação, seria algo como abaixo:
input.setDocument(new PlainDocument() {
    @Override
    public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
        if (str == null) {
            return;
        }
        super.insertString(offs, str.replaceAll("[^A-Za-z&\\|!]", "").toUpperCase(), a);
    }
});

Funcionando:

Na resposta que linkei há mais detalhes sobre esta classe.


What's the best method to implement swiping between views in OS X?

Question: What's the best method to implement swiping between views in OS X? These views are initialized from nibs with their view controllers and they're the same class type. To give some background, each view displays relevant data for the current date.
I'd like to create a function that loads the data for the next (or previous) date. I could simply load the data into the current view, but can I do that with an animation that's similar to swiping between spaces in OS X? I imagine I'd have to initialize a new view, load the data there, and then initiate the swiping transition to the new view.
I'm worried that the performance of creating all these new views would be pretty bad. Here are some options I've considered to address this:

Create a dictionary of NSDate to MYViewController. Load and store each view from this hashmap, but this could take a lot of memory.
Create a doubly-linked list of MYViewController and load/store sequentially dated views. This could potentially take a lot of memory also and if the user jumps to a date, the caching would just be erased.

Any thoughts? If there's some way to load the data in the current view, I feel like that'd be the best option.
Thanks!
Comment: Have you looked at NSPageController?
Comment: Have you considered using just two instances of your view controller?  One displaying the data that is moving off the screen and one displaying the data that is moving onto the screen?  This would be analogous to reusing cells in a UITableView.
Comment: I suppose I could do this. Then I could just keep swapping between the two view controllers? My only reservation with this is that I have other references to the view controller. So I'd have to keep track of which one is current or something? Do you have an example of how this might be done?
Comment: Ok, so I think I'm going to implement something along the lines of [this](http://liberatiluca.com/blog/2011/08/03/how-uitableview-reuses-cells/). In my implementation ESViewCache will be analogous to UITableView and ESViewCacheCell will be analagous to UITableviewCell. Before I do this though I'm going to see if I can just subclass NSTableView and have it display the current "ESViewCacheCell".
Comment: Sorry, I'm still brainstorming. Does OS X provide built in support for this? It looks like iCal implements this behavior in iCal when you change months (except with a different animation).
Comment: @Peter Thanks for informing us about NSPageController.
Answer: Have you considered just simply using UIScrollView and having a single UIViewController to manage all the views? Here's a good tutorial from Ray Wenderlich's site on UIScrollView :
http://www.raywenderlich.com/10518/how-to-use-uiscrollview-to-scroll-and-zoom-content
Alternatively, have you considered possibly using horizontal table view? Here's a third party implementation, which I've seen recommended on other SO posts:
https://github.com/TheVole/HorizontalTable
Edit
Sorry, I quickly read your question and assumed it was for iOS...
I think you might be looking for something like NSCollectionView perhaps (not sure if this would support offscreen views in a horizontal manner well or not...?)
Here's the docs on it:
https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/NSCollectionView_Class/Introduction/Introduction.html
Here's a tutorial on it:
http://andrehoffmann.wordpress.com/2009/08/29/nscollectionview-tutorial-for-dummies-xcode-3-1-3/
(Honestly haven't done much OSX development, so a bit out of my area of expertise here... I wish you luck though!)
Comment: I have considered a UIScrollView, but I don't think it is appropriate for my case. This implementation requires a finite number of views right? Each view in my program corresponds to the selected day so there are technically an infinite number of views. The horizontal table sounds somewhat like what I want. Do you know of any OS X implementations? Otherwise I can probably use this as a model and implement it myself.
Comment: I ended up following the concept of a horizontal table in my implementation and it appears to be working. You can download a video [here](https://dl.dropbox.com/u/345040/Screen%20Recording%202.mov). I'll probably post the code when I polish it a little. Does anyone know how to get rid of that grey stuff when scroller? Also is it possible to add a divider or separator during the animations? Maybe I should ask another question..
Answer: Cocoa view transition animation is not an easy thing. This is much more complicated coding than view controller management.
You need to decide how to achieve the desired effects. Take a look this document and other references: Animation Programming Guide for Cocoa
I did similar work a few months ago. My final resolution was using single view and show animation effects only with graphics APIs (image drawing) because it was more simpler than Core Animation.


How do I set a cookie that expires after a certain time using Tritium?

Question: I'd like to create a cookie that expires within 5 minutes of the user visiting my page.
I know about add_cookie() function, but have no idea how to set it to expire.
Answer: You can set cookies in the scripts/response_main.ts file as such:
set_cookie("cookie_name", "cookie_val")
cookie("cookie_name") {
  cookie.expires("Wed, 09 Jun 2021 10:18:14 GMT")
}

Check out this link for more info.
Comment: Aye @GiovanniAnthonyBrydenJr. you gotta mark my answer as correct


prove a polynomial is divisible

Question: How do I prove that if a polynomial $p(x)$ is divisible by $(ax+b)^n$ where $n>1$ then $p'(x)$ is divisible by $(ax+b)^{n-1}$
I have no idea how to prove that but by logic it is obvious that is true since the derivate of $p(x)$ lowers the power by 1.
Thank you
Comment: Let $p(x)=(ax+b)^nq(x)$, and compute the derivative.
Comment: $q(x)$ is just some other polynomial, you don't need to worry about its exact value.
Comment: Hint: write $p(x)=(ax+b)^nq(x)$ and take the derivative.
Comment: thanks for the answers but what is $q(x)$ ?
Comment: @ben Any polynomial term, doesn't matter
Comment: great, thanks everyone
Answer: Hint. Write down what in means for $p$ to be a multiple of $(ax+ b)^n$, namely there is some $q$ such that
$$ p(x) = q(x)(ax+b)^n $$
Now differentiate this equation and see.
Comment: By the definition of being divisible, $p$ is divisible by $(ax+b)^n$, iff there is a polynomial $q$ such that $p(x) = q(x)(ax+b)^n$, this $q$ is called the quotient.
Comment: thanks for the answer but what is $q(x)$ ? any random polynom?

prove a polynomial is divisible


Generate meta in controller

Question: I'm creating a custom module. This module displays public custom content without node and views . For this content custom page , I would like to add dynamic meta keyword and meta description .
I have read this excellent answer
How do I add a meta tag in ... section?
and it said we can use
mymodulename_page_attachments(&$page)

and update variable
$page

But the meta contents are getting in a controller's method. For this raison, I would like to
pass the meta contents to mymodulename_page_attachments hook.
How can I call and update $page in my controller module to do this ? Or how can I generate meta in my controller ?
Comment: Move the logic into a service then use the service in both contexts (controller and hook). You can statically cache the results of the op if it's expensive. Or maybe try attaching html_head to the render array you return from the controller and see if it bubbles up to the page layer (something tells me it will but I'm not sure)
Comment: tank's I didn't think to this. I will try .
Comment: @Clive than'ks . Your message told me what to do and what to learnt . ^^
Answer: hook_page_attachments() is only needed so you can attach it to any possible route/url. You should be to just add it directly to the response that you re returning, and it should bubble up and be added.
Comment: thank's to your response . I didn't understood realy what was Drupal Service. It's mistake . :-)
Answer: Service was the key to my problem .
After i understood Drupal services
https://www.drupal.org/docs/8/api/services-and-dependency-injection/services-and-dependency-injection-in-drupal-8
and
http://valuebound.com/resources/blog/how-to-define-your-own-services-drupal-8
It's easy to define dynamic keyword and meta to one page
function mymodulename_page_attachments(array &$page) {
    $currentUrl = Drupal::request()->get(Symfony\Cmf\Component\Routing\RouteObjectInterface::ROUTE_NAME);
    switch($currentUrl){
        case 'path_url':
        //call my service
          $description = array(
                '#tag' => 'meta',
                '#attributes' => array(
                    'property' => 'description',
                    'content' => /* value to my service return */,
                ),
            );

            $page['#attached']['html_head'][] = [$description, 'description'];
        break;

    }
}

Generate meta in controller


How can I check the emails that EC2 has blocked me from sending?

Question: I just got a notification that I'm not allowed to send any more emails from my EC2 instance. Which is a bit perplexing since I wasn't aware that I was sending any. Is there some way for me to have a look at the emails, or at least check which applications tried to send emails? I'm on ubuntu.
Answer: On Linux, from and to addresses of mail are typically logged by the default settings of most mail packages.
Try looking in /var/log/mail.log, or /var/log/syslog, or, if that doesn't help,
try: grep 'to=<' /var/log/* | less
The actual mail itself may not be available.
Remember, mail is pretty easy to fake.  It may not be coming from your machine.  But if you are not sending mail from your machine and want to eliminate the possibility, consider uninstalling any mail software and/or blocking ports like smtp/25 in your firewall settings.


Array busca por nome

Question: Tem como usar  Arrow Function neste exemplo? Se sim como ficaria? Qual a melhor forma de fazer busca pelo valor?

var msg =  ["Orange", "Melancia", "Abobora"];

var fruta = "Melancia"

buscar(fruta);

 function buscar(str){
  if(msg.indexOf(str) > -1){
    console.log(str);
  }else{
    console.log("Fruta não encontrada");
  }
 }
Comment: Não deu para entender o que você quer. Você busca na lista pelo índice onde está a palavra "melancia" para no final retornar "melancia"? Não fez sentido para mim.
Comment: @AndersonCarlosWoss vou arrumar a lógica pra fazer sentido
Answer: Ela ficaria assim:

var lista =  ["Orange", "Melancia", "Abobora"];
const buscar = str => (lista.indexOf(str) > -1) ? console.log('Encontrada') : console.log("Não encontrada");
buscar("Melancia");
buscar("Não existe");

Você também pode utilizar o método includes(), mas segundo a documentação ele ainda esta em testes e pode ocorrer alterações na sintaxe e no comportamento.

Esta é uma tecnologia experimental, parte da proposta ECMAScript 2016 (ES7).
  Como a especificação desta tecnologia não se estabilizou, verifique a tabela de compatibilidade para uso em vários navegadores. Observe também que a sintaxe e o comportamento de uma tecnologia experimental estão sujeitos a alterações na futura versão dos navegadores à medida que a especificação muda. - Tradução livre.

var lista =  ["Orange", "Melancia", "Abobora"];
const buscar = str => (lista.includes(str)) ? console.log('Encontrada') : console.log("Não encontrada");
buscar("Melancia");
buscar("Não existe");

Referências

includes() - Compatibilidade
Arrow functions
Qual a diferença entre function() {} e () => {}? Por que não funciona o $http.get?
Answer: var msg = ["Orange", "Melancia", "Abobora"];

var buscar = nome => msg.filter((elemento) => elemento.toLowerCase() === nome.toLowerCase())

invocando função
buscar("Melancia")

Comment: `filter` retorna um novo `array` logo teria que fazer uma condição para saber se obteve retorno.

Array busca por nome


Client-side browser language/plugin that supports sockets?

Question: I am a Application Developer (java,c,c#) and do not have experience with any web-based languages yet.
I want to embed an application in a webpage.  The application may need to connect to a database that could be on the same host as the webpage.
But most importantly, I need client-side socket support (like java's Socket class).
I could relatively easily implement it using a java applet, but it seems java applets are not used very often anymore, and the java runtime is required on the clients pc.
Javascript seems like the most widely used, but is it capable of directly using the clients network?
Silverlight seems to be gaining popularity and might fit my needs, but has the same problem as java applets (not guaranteed to be installed on the client machine).
What are the other alternatives?
Thanks for your help!
Comment: Don't forget Flash. It has a *very high* market penetration (for desktops, anyway) and the JavaScript on the page can communicate with it, if needed.
Comment: @pst well it's something that hit the webs a few weeks ago -- consider the Windows 8 hype about HTML5 etc. ...  the writing is on the wall
Comment: @Pointy Have a link to "dumping Silverlight"?
Comment: If you already know C#, silverlight is a good option. What Pointy said about Microsoft dumping Silverlight is not true.
Comment: @Pointy: lol.  MS is dumping SL, that's hilarious.  BTW, all the hype about W8 and HTML5 is BS.  MS is providing a compatability layer that javascript will be able to access, which means you could write W8 apps strictly using 5 and J.  Saying that this means they are dumping SL is like saying that when MS introduced .NET they were dumping C++.  The Build conference had some good presentations on the subject; you should watch some.
Comment: The comment was unwise and based on pseudo-data I probably picked up from reddit or something. I'll delete it.
Comment: I'm re-thinking my retraction at this point :)
Answer: Java is still alive, and I think in your case Java works better than JavaScript. I wouldn't worry so much about people having the Java runtime.. it takes a few minutes to get it and it's still very common.
The main reason here is that you already know Java well and don't have experience with web-based languages- why spend loads of time with something else?
Java applets are a bit dated though.
So the new HTML5 provides socket support(thanks Pointy), and that's the wisest choice overall(use JavaScript + HTML5 ).
Comment: Relying on normal non-web-aware persons to install the Java runtime is pretty questionable. And if you'd read up on HTML5 web sockets, you'd realize that JavaScript **will** give you client-side socket support.
Comment: Thanks for the tips.  I'll read up on HTML5 and javascript.  Is HTML5 supported on most browsers now?
Comment: @Pointy - Well if Gramps can't figure it out, there's always good ole' TV to watch ;)  I think maybe OP can include a link showing how to install Java runtime. Thing is, he says he has NO experience with web dev...
Comment: Wow - HTML5 gives socket support, well then that's the best choice now :)
Comment: I'd say about 50-80% of browsers, Here's a nice link though: http://html5test.com/ and http://stackoverflow.com/questions/1355082/is-html-5-supported-by-all-the-main-browsers
Answer: After some research I think my two best options are Silverlight or a Java Applet.
Both have rich client-side capability and can be easily embedded in a web-page.  Not everyone is guaranteed to have either installed but both are relatively easy to install and run on almost any desktop.  No linux for silverlight though :(
This may be possible with pure HTML5/javascript as well, but would require significantly more work because you would not get the pre-made libraries of C# or Java.
Java Applets are quite dated however, and it would take a sizable amount of work to get a java applet looking like a modernly styled web app.
For that reason I decided to try out silverlight.
Thanks for all the tips!
Edit:  After some further digging it seems like silverlight will not work for me since it has many restrictions on the use of client side sockets.  http://msdn.microsoft.com/en-us/library/cc645032%28v=vs.95%29.aspx
A java applet would be much more flexible.


Critically damped system

Question: Coming from engineering background, my math might not be as rigour here. Please enlighten me.

By definition, critically damped 2nd order system ($\zeta=1$) does not have overshoot.

Is the statement above (my assumption) false?
For context, this is the system:
$$
Q\ddot{x}+2\zeta \omega_n\dot{x}+\omega_n^2x=\omega_n^2r
$$
which is also in the form:
$$
Q\ddot{x}+a\dot{x}+bx=br
$$
where $r$ is some constant.
I know that the response is in the form:
$$
x(t)=r\left[1−(k_1+k_2t)e^{\frac{−\omega_n}{Q}t}\right]
$$
Where $k_1$, $k_2$ is some constant depend on initial condition.
For $x(0) = 0$, We know that $k_1=0$, but how to determine $k_2$ (which depends on $x'(0)$)?
I know that this might be very trivial for some of you, but I'm really confused.
For context, I asked a similar question in the electrical engineering site. If you are interested, the problem is the 2nd order system that I set "gains" for (gains correspond to changing the coefficient in the ode (a & b)), behave critically damped. However, when I set up a the original first order system with the input of the controlled gains, it had an overshoot. If you know why kindly please enlighten me as well.
This is the unstable first order system trying to be controlled:
$$
p\dot{x}-lx=r
$$
Letting
$$
r= K_p\left(c-x\right) + K_i\int _0^tc-x\ dt\ + K_d\left(\dot{c} - \dot{x}\right)
$$
This is a PID control for 1st order system. Making the sytem to become 2nd order. and track the value $c$
Comment: To determine $k_2$, you differentiate $x(t)$ to get $\dot{x}(0)=\dot{x}_0$. This expression can be solved for $k_2$. Because this is a second-order system, you need two initial values, $x(0)$ and $\dot{x}(0)$.
Answer: OK, there's a lot to unpack here, so let's take this one step at a time.
ODE solution
The ODE
$$
Q\ddot{x}+2\zeta\omega_n\dot{x}+\omega_n^2x=\omega_n^2r
$$
has the characteristic equation
$$
Q\lambda^2 + 2\zeta\omega_n\lambda + \omega_n^2 = 0
$$
and eigenvalues
$$
\lambda \in \left\{{\omega_n \over Q}\left(-\zeta + \sqrt{\zeta^2 - Q}\right), {\omega_n \over Q}\left(-\zeta -\sqrt{\zeta^2 - Q} \right)  \right\}
$$
so it can only be critically damped if $\zeta^2 = Q$. For  the sake of argument, let's assume it is so that
$$
\lambda = -{\omega_n\zeta \over Q} = -{\omega_n \over \zeta}
$$
and $x$ has the homogeneous solution
$$
x_h = (k_1 + k_2t)e^{-t\omega_n/\zeta}.
$$
For the particular solution, since the input $\omega_n^2 r$ is constant, so is the steady-state response, therefore $x_p=C$. The complete solution is
$$
x = x_p + x_h = C + (k_1 + k_2t)e^{-t\omega_n/\zeta}
$$
with first derivative
$$
\dot{x} = \left[k_2 - {\omega_n \over \zeta}(k_1 + k_2t) \right]e^{-t\omega_n/\zeta}
$$
In control problems, it's usual to assume that the system has no energy stored at $t=0$ unless you have information indicating otherwise, so $x(0)=\dot{x}(0)=0$. From the initial conditions, we have $k_1 = -C$ and
$$
k_2 = {\omega_n \over \zeta}k_1 = -{\omega_n \over \zeta}C.
$$
To find $C$, we notice that $x = C$ and $\dot{x}=\ddot{x}=0$ for $t\to\infty$, so, if we were to plug our candidate solution and its derivatives back into the ODE and evaluate it for $t\to\infty$ we'd get $\omega_n^2C = \omega_n^2r$, hence
$$
C = r\quad k_1 = -r\quad k_2 = -{\omega_n \over \zeta}r
$$
which gives the final solution
$$
x = r \left[ 1 - \left(1 + {\omega_n \over \zeta}t\right)e^{-t\omega_n/\zeta}\right].
$$
Having said all that, I believe you may have gotten your coefficients mixed up. If you want $\zeta$ to represent the damping ratio, your ODE has to be expressed in the form $\ddot{x} + 2\zeta\omega_n\dot{x} + \omega_n^2x = f(x)$.
System control
Now, for the control problem. You said you're trying to control a 1st-order unstable plant with a PID controller. Your controlled system then has a closed-loop transfer function of the form (assuming unity feedback)
$$
H(s) = {(s^2K_d + sK_p + K_i)/p \over s^2(1 + K_d/p) + s[(K_p-l)/p] + K_i/p},
$$
where
$$
\omega_n^2 = {K_i/p \over 1 +K_d/p} = {K_i \over p + K_d}
$$
and
$$
2\zeta\omega_n = {(K_p - l)/p \over 1 + K_d/p} = {K_p - l \over p + K_d}.
$$
If all you care about is having a critically damped system, you can find, after a few manipulations, the constraint
$$
2K_i^2 = (p+K_d)(K_p-l).
$$
If you also need a specific natural frequency $\omega_n$, it can provide you an extra constraint that helps narrow down the possible values for $K_p$, $K_i$ and $K_d$. Of course, you have to make sure the closed-loop poles are stable.
Comment: Wow...Very thorough answer. +1. And I apologize for mixing up the variables. You are absolutely correct
Comment: @John.Apple not sure I follow your question. If you have any integral action, you will get closed-loop zeros. This is what causes the overshoot. However, if you want zero steady-state error, you need some integral gain. There are non-linear strategies to minimise integral overshoot like limiting integral output
Comment: Just out of curiosity, if you notice the cl-tf you gave (H(s)) is correct. However, it creates 2 zeros. I have been using MATLAB to simulate this, and I got an overshoot because of these zeros. I thought that there is no zeros, considering that r is constant (its derivative is zero). However, I still got an overshoot. Do you know why the zeros still exist?
Comment: Also, I know that I should have used lag compensator, but suppose that I do use PID controller, I know pre-filter can fixed the problem, do you happened to know any other method to eliminate the overshoot caused by the zeros?
Comment: Do you mean integral with anti-windup system?
Comment: @John.Apple Yes

Critically damped system


Erro "Doesn't have a default value" ao tentar inserir dados no DB

Question: Estava a tentar inserir as variáveis que recebi de um formulário, quando recebi esta mensagem de erro:

'nidcrespons1' doesn't have a default value

Meu código:
<?php
    $link = mysqli_connect("localhost", "root", "vertrigo", "winit");
    $nomeempresa = $_POST["nomeempresa"];
    $paisempresa = $_POST["paisempresa"];
    $moradaempresa = $_POST["moradaempresa"];
    $nifempresa = $_POST["nifempresa"];
    $crc = $_POST["crc"];
    $telefoneempresa = $_POST["telefoneempresa"];
    $respons1 = $_POST["respons1"];
    $nidcrespons1 = $_POST["nidcrespons1"];
    $nifrespons1 = $_POST["nifrespons1"];
    $emailempresa = $_POST["emailempresa"];
    $senhaempresa = $_POST["senhaempresa"];

    echo $nomeempresa;
    echo $paisempresa;

    $insere = mysqli_query($link, "INSERT INTO empresas (nomeempresa, respons1) VALUES ('$nomeempresa', '$respons1')") or die(mysqli_error($link));
?>

Comment: Não tem a ver com a pergunta, mas fica a dica: use [prepared statements](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) no seu código SQL.
Comment: Passa um valor p ele, deve vir do form, faça isso para todas as colunas.
Comment: Você pode criar um resposta :)
Comment: O problema é esse mesmo, coloca isso como resposta para eu dar pontuação.
Answer: O problema é que você tem que passar algum valor para as colunas do banco de dados que são NOT NULL, a coluna não pode estar sem nada, ou seja o INSERT tem que ter algo, para preencher a coluna.


autocomplete not working with add row javascript

Question: I tried to insert input box with id as tags. After insert, I need the auto complete to function. I tried many ways but the input with tags cannot auto complete.
my javascript
$(document).ready(function () {
    $("#addCF").click(function () {
        $("#customFields").append('
1	<input class="form-control" name="kode_barang[]" id="cariBrg" placeholder="Ketik Kode / Nama Barang" type="text">	<input   class="form-control" name="harga_satuan[]" id="input1" onkeyup="calc()" value="" type="text">	<input class="form-control" id="input2" onkeyup="calc()" name="jumlah_beli[]"   type="text">	<input class="form-control" name="sub_total[]" value="" id="output" type="text">	<button class="remCF"></  button>
');
    });
    $("#customFields").on('click', '.remCF', function () {
        $(this).parent().parent().remove();
    });
});

autocomplete
$(function () {
    $("#cariBrg").autocomplete({
        source: "cari-barang.php",
        minLength: 2,
    });
});

my HTML
            1

                <input class="form-control" name="kode_barang[]" id="cariBrg" placeholder="Ketik Kode / Nama Barang" type="text">

                <input class="form-control" name="harga_satuan[]" id="input1" onkeyup="calc()" value="" type="text">

                <input class="form-control" id="input2" onkeyup="calc()" name="jumlah_beli[]" type="text">

                <input class="form-control" name="sub_total[]" value="" id="output" type="text">

                <button class="remCF"></button>

    <button id='addCF' class='btn btn-default pull-left'>Baris Baru (F7)</button>

Please Help
Answer: instead of...
$("#cariBrg").autocomplete({
    source: "cari-barang.php",
    minLength: 2,
});

try this:
$('body').find("#cariBrg").autocomplete({
    source: "cari-barang.php",
    minLength: 2,
});


OpenTSDB: Zookeeper Error

Question: I am doing installation of opentsdb for the first time on Ubuntu. I am following these documentations for installation:
http://opentsdb.net/docs/build/html/installation.html#id1
http://opentsdb.net/setup-hbase.html
I am getting following error on executing the command
Abharthan/opentsdb$ env COMPRESSION=NONE HBASE_HOME=/home/administrator/Abharthan/hbase-0.98.13-hadoop1
 ./src/create_table.sh
after installing OpenTSDB:
I have already installed hbase, gnuplot, JDK etc.
There were some errors regarding:

Can't get connection to zookeeper
Some answers to this suggest:
It seems like your zookeeper is down/not configured on poort 2181
you can start by checking the zoo.cfg file where you installed zookeepr

But, I didn't installed zookeeper explicitly, it was supposed to be installed by the opentsdb/hbase itself. Where can I find this file to make this change.

Unable to load native-hadoop library for your platform
SLF4J: Classpath contains multiple SLF4J building

HBase Shell; enter 'help' for list of
  supported commands. Type "exit" to leave the HBase Shell
  Version 0.98.13-hadoop1, r8f54f8daf8cf4d1a629f8ed62363be29141c1b6e,
  Wed Jun 10 22:18:15 PDT 2015
create 'tsdb-uid',   {NAME => 'id', COMPRESSION => 'NONE', BLOOMFILTER
  => 'ROW'},   {NAME => 'name', COMPRESSION => 'NONE', BLOOMFILTER => 'ROW'} SLF4J: Class path contains multiple SLF4J bindings. SLF4J:
  Found binding in
  [jar:file:/home/administrator/Abharthan/hbase-0.98.13-hadoop1/lib/slf4j-log4j12-1.6.4.jar!/org/slf4j/impl/StaticLoggerBinder.class]
  SLF4J: Found binding in
  [jar:file:/usr/local/hadoop/share/hadoop/common/lib/slf4j-log4j12-1.7.10.jar!/org/slf4j/impl/StaticLoggerBinder.class]
  SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an
  explanation. 2015-07-03 08:44:12,270 ERROR [main]
  zookeeper.RecoverableZooKeeper: ZooKeeper exists failed after 4
  attempts 2015-07-03 08:44:12,273 WARN  [main] zookeeper.ZKUtil:
  hconnection-0x225875070x0, quorum=localhost:2181, baseZNode=/hbase
  Unable to set watcher on znode (/hbase/hbaseid)
  org.apache.zookeeper.KeeperException$ConnectionLossException:
  KeeperErrorCode = ConnectionLoss for /hbase/hbaseid   at
  org.apache.zookeeper.KeeperException.create(KeeperException.java:99)
    at
  org.apache.zookeeper.KeeperException.create(KeeperException.java:51)
    at org.apache.zookeeper.ZooKeeper.exists(ZooKeeper.java:1045)   at
  org.apache.hadoop.hbase.zookeeper.RecoverableZooKeeper.exists(RecoverableZooKeeper.java:222)
    at
  org.apache.hadoop.hbase.zookeeper.ZKUtil.checkExists(ZKUtil.java:481)
    at
  org.apache.hadoop.hbase.zookeeper.ZKClusterId.readClusterIdZNode(ZKClusterId.java:65)
    at
  org.apache.hadoop.hbase.client.ZooKeeperRegistry.getClusterId(ZooKeeperRegistry.java:83)
    at
  org.apache.hadoop.hbase.client.HConnectionManager$HConnectionImplementation.retrieveClusterId(HConnectionManager.java:909)
    at
  org.apache.hadoop.hbase.client.HConnectionManager$HConnectionImplementation.(HConnectionManager.java:703)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native
  Method)   at
  sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at
  sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:408)
    at
  org.apache.hadoop.hbase.client.HConnectionManager.createConnection(HConnectionManager.java:459)
  . . .

I am able to start the hbase server as:

<code>Abharthan/hbase-0.98.13-hadoop1$ ./bin/start-hbase.sh
starting master, logging to /usr/lib/hbase/hbase-220.127.116.11/logs/hbaseIdeaCentre-Q190.out
</code>

Running following command

Abharthan/opentsdb$ ./build/tsdb tsd --port=4242 --staticroot=build/staticroot --cachedir="$tsdtemp"

gives this result:

2015-07-03 09:49:19,220 INFO  [main] TSDMain: Starting. 2015-07-03
  09:49:19,231 INFO  [main] TSDMain: net.opentsdb 2.1.0 built at
  revision 45e575a (MINT) 2015-07-03 09:49:19,232 INFO  [main] TSDMain:
  Built on 2015/06/30 21:00:14 +0000 by
  IdeaCentre-Q190:/home/administrator/Abharthan/opentsdb/build
  2015-07-03 09:49:19,255 INFO  [main] Config: No configuration found,
  will use defaults Missing cache directory

Can someone suggest what is the problem.
Also, it says I can open it in browser as localhost:4242, but where to mention the port the service use.
Answer: Number 1 (The failing zookeeper) is the problem. We have a running openTSDB and often see errors 2 and 3; they are not serious.
You will need to track down the cause of zookeepers failure; look for the zookeeper log files.
Answer: Making sure your hadoop and hbase have already started before create opentsdb table, and it will be fine.

OpenTSDB: Zookeeper Error


Abrir intent de uma listview

Question: Possuo uma lista de clientes. Gostaria de quando clicasse em um cliente ele abrisse uma nova intent.
Mas fiz alguma coisa errada.
Segue os códigos:
 list.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(ClienteActivity.this, DetalhesCatalogo.class);
            startActivity(intent);

        }

    });

}

Quando rodo ele dá o seguinte erro:
09-16 13:13:25.047 1532-1532/com.example.jnior.decorus E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.jnior.decorus, PID: 1532
    *java.lang.RuntimeException: Unable to start activity ComponentInfo{xxxxxxxxxxxxxxxxxxxxxxxx.ClienteActivity}:
    java.lang.RuntimeException: Don't call setOnClickListener for an AdapterView. You probably want setOnItemClickListener instead*

Comment: Já tá no erro:

Don't call setOnClickListener for an AdapterView. You probably want setOnItemClickListener instead

Não chame setOnClickListener.
Chama setOnItemClickListener.
Comment: Mas ai tenho que mudar o código, pois se colocar setOnItemClickListener ele dá erro.
Comment: olha ali embaixo a reposta
Comment: é só dar listView.setOnItem (e apertar enter que o android studio auto-completa. depois é só colocar o intent no meio do click)
Comment: Fechou cara. Obrigado. ABS.
Comment: marca como certo. agradeço.
Answer: list.setOnItemClickListener(new AdapterView.OnItemClickListener(){
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent intent = new Intent(ClienteActivity.this, DetalhesCatalogo.class);
            startActivity(intent);
        }
    });
}

setOnItemClickListener ao invés de setOnClickListener

Abrir intent de uma listview


Adding fields via ajax in form does not show in arrays in form_submit

Question: I have am trying to add fields to a form in drupal via ajax.  I am able to have my fields show up on the form without issue but the problem is seeing values of those fields when the form is submitted.  I have read many tutorials on this tonight and I am very confused why my input fields are not even showing up in $_POST.  Here is an example of what I am trying to do:
function add_product($form, &$form_state) {
    //Several other fields but the main one around this issue is below.
    $form['img_mng'] = array(
        'label' => array(
            '#type'     =>  'markup',
            '#markup'   =>  '
Upload Images
',
        ),
        'file1' => array(
            '#type'     => 'file',
            '#size'     => 22,
        ),
        'addMore'   =>  array(
            '#type' =>  'button',
            '#value'    => t('Add More Images'),
            '#ajax' => array(
                'callback'  =>  'add_img_upload',
                'method'    =>  'append',
                'wrapper'   =>  'kc_img_uploads',
                'keypress'  =>  'true',

            ),
            '#prefix'               =>  '

',
        ),
    );

    $form['submit'] = array(
        '#type'             => 'submit',
        '#value'            => t('Add Product'),
    );
    return $form;
}

function add_product_validate($form,&$form_state) {
    //Appropriate Validation
    dpm($_POST); //$_POST does not show the fields, not sure how that is even possible since the new fields are added to the form.
    dpm(get_defined_vars()); //None of the variables show the new fields.
}

function add_product_submit($form,&$form_state) {
    // Appropriate database actions....
    dpm($form_state); //No values for new fields.
    dpm($_POST);  //New fields do not even show in the $_POST.
}

function add_img_upload($form,&$form_state) {
    dpm($form_state);  //Does not show the added field below if the button is clicked more than once.
    $num_of_files = 1;
    foreach ( $form['img_mng'] as $key => $value ) {
        if ( preg_match('/^file[0-9]+$/',$key) )
            $num_of_files++;
    }
    $form['img_mng'][sprintf('file%d',$num_of_files)] = array(
        '#type'     => 'file',
        '#size'     => 22,
        '#id'       => sprintf('edit_file%d',$num_of_files),
        '#name'     => sprintf('files[file%d]',$num_of_files),
        '#parents'  => sprintf('file%d',$num_of_files),
        '#array_parents'    => sprintf('file%d',$num_of_files),
    );
    $form_state['values'][sprintf('file%d',$num_of_files)] = '';
    $form_state['file2'] = NULL;
    return $form['img_mng'][sprintf('file%d',$num_of_files)];  //The fields are added to the form every time the button is clicked.  However, the id and name of the elements are only incremented once.  ie file1 becomes file2 but never makes it to file3+.  So I will have one file1 and 1 to many file2's.
}

I originally tried this with managed_file type but I see several people have run into the issue of it returning an empty string.  I was actually able to get it to return the field details but found clicking the upload button on any of the new fields submitted the form?  Any advice on how to correct this issue with managed_file type is highly desired but will settle for file type.  Thanks again.
Comment: I noticed an issue in add_img_upload after I posted.  I had the following defined:

$form_state['file2'] = NULL;

it should be

$form_state['input'][sprintf('file%d',$num_of_files)] = NULL;

That change had no impact.
Comment: I forgot to update this thread.  I found a work around but not what I would consider an answer so I am leaving open.  The problem appears to be that the $form is already re-built by the time add_img_upload is called in the example above.  You can only send form fields that were already added to the $form.  You make those fields not visible basically in the initial build of the form.  My workaround was to always build 5 empty managed_file fields.  If files already exist, I build a managed_file field for each existing file and then add the 5 empty ones.
Answer: The form builder function is what Drupal refers to whenever it needs to rebuild the form. Parts of the form should not be built in the ajax callback. Instead, you can return them using something like
function add_img_upload($form,&$form_state) {
  return $form['img_mng'];
}

Your form builder has access to form state information, which allows you to build the form conditionally depending on the state of the form.


Fitting distributions on censored data

Question: My question deals with fitting distributions on censored data; for the purposes of clarity, we can consider a continuous distribution which is both left and right-censored. In such a case, the variates are "clubbed" into a maximal upper-value if they are greater than a threshold $t_h$, or into a minimal lower-value if they are less than a threshold $t_l$.  We have only observed this censored data and want to fit a distribution which in some sense appropriately models the data which we have observed.
I've seen a number of cases in dealing with fitting distributions, where parameter fitting is done via Maximum Likelihood Estimation.  In such cases, the probability for the points which are censored is set via the CDF F(x) = P(X < x): $F(x)$ is used to evaluate left-truncated points and $1-F(x)$ is used to evaluate right-truncated points.  Meanwhile, for the non-truncated points, the probability density f(x) is used for evaluation.  For some examples, please see these posts if you don't understand what I mean:
https://www.r-bloggers.com/fitting-censored-log-normal-data/
How to model this odd-shaped distribution (almost a reverse-J)
My question is, why is it commonly accepted to fit the censored parts using probability $mass$, but the non-censored parts using probability $density$?  Since these are different units, don't the results become unstable or influenced by the differences in scales of magnitude differences that might exist between the density and mass?
My rationalization of why this procedure might be okay is that in a model-selection regime such as distribution fitting, these problems persist across various parameters of the model class -- in some sense, we have a "level playing field" across contender distributions.  This doesn't really address the problem of different scales for mass and density, but at least it seems "fair."
Could someone shed some light on this?  Any other pointers on dealing with such distributions (continuous over a range, and then with point masses thrown in) would be helpful as I'm very new to this space.
Answer: A short answer which might be expanded:  This is really about how the likelihood function is defined, see for instance How to rigorously define the likelihood?.  It doesn't really matter if you use probability densities or probability mass functions to define your likelihood. The likelihood function is always defined with respect to some dominating measure on the sample space of the observations.
If the dominating measure is Lebesgue measure on the real line, we get probability distributions defined via densities. If the dominating measure is counting measure, we get probability mass functions. But there are many other possibilities, an example is modeling daily rainfall, where there might be some positive probability of zero rain, but else a density on positive values. That can be represented as a density (formally: Radon-Nikodym derivative) with respect to a sum of Lebesgue measure on the positive real line, and a probability atom at zero.
In your case, with censoring at the high and low ends, say at $a < b$, your dominating measure is a sum of Lebesgue measure on $(a,b)$ and probability atoms at $a$ and at $b$. In this abstract setting, this is no different than a density with respect to Lebesgue measure or with respect to counting measure. So you have nothing to be preoccupied about! What is important is that the dominating measure is the same for all the possible particular models (whether parametrized or not) that you entertain. And, as far as I know, this framework do not allow for estimating the dominating measure, that has to be known by the modeler.
For information about Radon-Nikodym derivatives and dominating measures, see Interpretation of Radon-Nikodym derivative between probability measures?
Comment: Thanks for this!  This provides some formal justification for the informal intuition that I had about this case.  One question: in such a dominating measure, how might one compare intuitively the "relative probability" of a sample in the Lebesgue region (a,b) and atoms at $a$ and $b$?  Perhaps it's nonsensical or an ill-defined question given P(X = x) = 0 on (a, b).  I'm interested from the perspective of comparing likelihood of a variate observed on (a,b) versus at $a$ or $b$, if that makes sense.  Thank you so much for your help!  Can one naively compare these two likelihoods?
Comment: You *never needs* such a comparison. For each data point $x_i$, it will be either $a$, $b$ or in $(a,b)$.  What you compare is *different parameter values*, that is, different models, at the same data points!

Fitting distributions on censored data


Como publicar um projeto Angular CLI no meu servidor?

Question: Tenho um projeto em Angularjs rodando localhost perfeitamente.
Estou tentando hospedar no servidor "HOSTGATOR" e não estou obtendo sucesso.
Estou gerando o Build com o Angular CLI e Hospedando o Dir "Dist" na "www". Ao tentar acessar o index.html ocorre os seguintes erros:

Falha no carregamento do


"every prime number $p$ $(p>3)$ can be expressed sum of consecutive numbers " is it true?

Question: I'm finding some necessary and sufficient conditions for a integer $n$ to be a prime number. But I'm not sure if "every prime number $p \, ,(p>3)$ can be expressed sum of consecutive number" is true.
If it is right, I hope you help me prove that.
Thank you very much.
Comment: Every odd number can be expressed as $2n+1=n+(n+1)$. Every number $m \equiv 2  \pmod{4}$ can ... $m= (n-1) +n +(n+1)+(n+2)$. Every number $ 4  \pmod{8}$ can ... The only ones that cannot are powers of $2$.
Comment: It's a well-known fun problem to determine which integers are (or aren't) sums of sequences of at least two consecutive positive integers.
Answer: Every prime greater than or equal to $3$ is odd, and every odd is of the form $2k+1$  that is, $$\exists \,k \in \mathbb N \, : \,p=2k+1=\underbrace{(k)+(k+1)}_{\text{Sum of two consecutive integers}}$$
Comment: so if $n$ is odd and can be expressed sum of consecutive numbers , is $n$ prime number?
Comment: @AnhThư No!! I am saying that every odd number can be expressed as the sum of two consecutive integers. Only this. What I continued is that every prime number is an odd number, thus it can be expressed as sum of two consecutive integers.
Answer: More generally, any positive integer which is not a power of $2$ can be written as the sum of two or more consecutive integers. See LINK
Answer: In addition primes are expressible ONLY as the sum of two consecutive positive integers - never as the sum of $3$ or more consecutive integers because any sequence of $k > 2$ consecutive integers is expressible as $n + (n+1) +  ..(n+k-1)$ = $kn+ \frac{(k-1)k}{2}$.
If $k$ is odd, $k-1$ is divisible by $2$ so $k$ is a factor.
If $k$ is even, say $k=2m$ then $2mn+(2m-1)2m/2$ so $m$ is a factor.
Either way, the sum is nonprime.
Comment: The prime $3$ is the sum of three consecutive integers: $3=0+1+2$. No doubt you had *positive* integers in mind. (No doubt the OP did too, since clearly *any* number $p$ can be written trivially as the sum of the consecutive integers from $-(p-1)$ to $p$.)
Comment: apologies for the meta comment and improvements


Why do I get a AttrributeError on this bit of code?

Question: I get the error,"AttributeError: 'NoneType' object has no attribute 'send'" when I run the following line of code:
How do I fix this?
    if now.weekday() == 3:
        if thursday_lunch_time.shift(minutes=1).time() > now.time() > thursday_lunch_time.time():
            print(f"Got channel {channel}")
            await channel.send(random.choice(list_warning))
            await asyncio.sleep(65)

Comment: Please post the whole error message, with full traceback, and all the relevant portions of your code (including the part that sets `channel`).
Comment: Alright, sorry for the rushed post.
Answer: The bot can not get the channel so its None and you're doing channel.send means None.send which is why you get that error
Make sure the bot has permissions to read messages for that channel and you pass in the correct channel ID or channel Name.


Japanese text to speech Android?

Question: I am programming an app which can speech to text in Japanese. However, when I code, I know that Android doesn't support Japanese language.
I try to use SVOX. However, it isn't the best solution?
Can you help me to solve my problem?
Thanks you.
Here is my code after @ErsinGülbahar help :)
package com.example.tts;

import java.io.IOException;
import java.util.Locale;

import org.apache.http.util.LangUtils;

import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.speech.tts.TextToSpeech;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

public class MainActivity extends Activity implements
        TextToSpeech.OnInitListener {
    /** Called when the activity is first created. */
    MediaPlayer mediaPlayer;
    Thread x;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        x = new Thread() {
            public void run() {
                try {
                    String url1 = "http://www.translate.google.com/translate_tts?ie=UTF-8&q="
                            + "Hello".replace(' ', '+').replace('\n', '.')
                            + "%0A&tl=" + "ja" + "&prev=input";
                    String url2 = "http://www.translate.google.com/translate_tts?ie=UTF-8&q=nihongo%0A&tl=ja&prev=input";
                    mediaPlayer = new MediaPlayer();
                    mediaPlayer.reset();
                    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                    mediaPlayer.setDataSource(url2);
                    mediaPlayer.prepare(); // might take long! (for buffering,
                                            // etc)
                    mediaPlayer.start();
                } catch (IllegalArgumentException e) {
                    mediaPlayer.reset();
                } catch (IllegalStateException e) {
                    mediaPlayer.reset();
                } catch (IOException e) {
                    mediaPlayer.reset();
                }

                finally {
                }
            }

        };
        ImageButton ibm = (ImageButton) findViewById(R.id.imageButton1);
        ibm.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Toast.makeText(getApplicationContext(), "Callme", 4).show();
                x.run();
            }
        });

    }

    @Override
    public void onInit(int arg0) {
        // TODO Auto-generated method stub
    }
}

Comment: As far as I know, Japanese language is supported since Android version 1.5 (API Level 4)
Comment: No. I use some other app, which has similar function. It must connect to Internet to can speech it
Comment: Look: [http://stackoverflow.com/a/7989085/2649012](http://stackoverflow.com/a/7989085/2649012)
Comment: what are u using ? google translate or whatelse?
Comment: Look at this example: [http://android.okhelp.cz/tts-text-to-speech/](http://android.okhelp.cz/tts-text-to-speech/)
Comment: Sorry. it doesn't support Japanese.
Comment: @ErsinGülbahar I wanna use google translate. can you give any an example :)
Comment: sure I will add an answer soon
Comment: @VanDerCong I add an answer please look it
Comment: @ErsinGülbahar sorry. It can not speech. I will update my code on question
Comment: Sorry. I run successfull. I forget add to my code: ``
Answer: Here's the list

Language / Locale                 Supported since version

English, US (en_US)               1.1
German, Germany (de_DE)           1.1
Chinese, PRC (zh_CN)              1.5
Chinese, Taiwan (zh_TW)           1.5
Czech, Czech Republic (cs_CZ)     1.5
Dutch, Belgium (nl_BE)            1.5
Dutch, Netherlands (nl_NL)        1.5
English, Australia (en_AU)        1.5
English, Britain (en_GB)          1.5
English, Canada (en_CA)           1.5
English, New Zealand (en_NZ)      1.5
English, Singapore(en_SG)         1.5
French, Belgium (fr_BE)           1.5
French, Canada (fr_CA)            1.5
French, France (fr_FR)            1.5
French, Switzerland (fr_CH)       1.5
German, Austria (de_AT)           1.5
German, Liechtenstein (de_LI)     1.5
German, Switzerland (de_CH)       1.5
Italian, Italy (it_IT)            1.5
Italian, Switzerland (it_CH)      1.5
Japanese (ja_JP)                  1.5
Korean (ko_KR)                    1.5
Polish (pl_PL)                    1.5
Russian (ru_RU)                   1.5
Spanish (es_ES)                   1.5
Arabic, Egypt (ar_EG)             2.3
Arabic, Israel (ar_IL)            2.3
Bulgarian, Bulgaria (bg_BG)       2.3
Catalan, Spain (ca_ES)            2.3
Croatian, Croatia (hr_HR)         2.3
Danish, Denmark(da_DK)            2.3
English, India (en_IN)            2.3
English, Ireland (en_IE)          2.3
English, Zimbabwe (en_ZA)         2.3
Finnish, Finland (fi_FI)          2.3
Greek, Greece (el_GR)             2.3
Hebrew, Israel (iw_IL)*           2.3
Hindi, India (hi_IN)              2.3
Hungarian, Hungary (hu_HU)        2.3
Indonesian, Indonesia (in_ID)*    2.3
Latvian, Latvia (lv_LV)           2.3
Lithuanian, Lithuania (lt_LT)     2.3
Norwegian-Bokmol, Norway(nb_NO)   2.3
Portuguese, Brazil (pt_BR)        2.3
Portuguese, Portugal (pt_PT)      2.3
Romanian, Romania (ro_RO)         2.3
Serbian (sr_RS)                   2.3
Slovak, Slovakia (sk_SK)          2.3
Slovenian, Slovenia (sl_SI)       2.3
Spanish, US (es_US)               2.3
Swedish, Sweden (sv_SE)           2.3
Tagalog, Philippines (tl_PH)      2.3
Thai, Thailand (th_TH)            2.3
Turkish, Turkey (tr_TR)           2.3
Ukrainian, Ukraine (uk_UA)        2.3
Vietnamese, Vietnam (vi_VN)       2.3

Answer: you can define a thread:
Thread x=new Thread(){  public void run(){
         try{
             url1="http://www.translate.google.com/translate_tts?ie=UTF-8&q="+word_which_read.replace(' ','+' ).replace('\n','.' )+"%0A&tl="+language+"&prev=input";

            mediaPlayer=new MediaPlayer();
            mediaPlayer.reset();
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.setDataSource(url1);
            mediaPlayer.prepare(); // might take long! (for buffering, etc)
            mediaPlayer.start();
                    } catch (IllegalArgumentException e) {
                        mediaPlayer.reset();
                    } catch (IllegalStateException e) {
                        mediaPlayer.reset();
                    } catch (IOException e) {
                        mediaPlayer.reset();
                    }

            finally{
            //  x.suspend();
            }
     }

    };

You can call x.run(); In the url you should set language as ja this is japanese.
and you should set *word_which_read* as your word
Comment: By now, the url does not have "www" prefix. And there is a box to check if user is human or not. Therefore, I think this trick not work anymore..

Japanese text to speech Android?