Models for Financial Economics: Determining The Amount to Lend in Synthetic Assets

Question: You are given:
(i) The price of a stock is 43.00$
(ii) The continuously compounded risk-free interest rate is 5%
(iii) The stock pays a dividend of 1 three months from now
(iv) A 3-month European call option on the stock with strike 44 costs 1.90
You wish to create this stock synthetically, using a combination of 44-Strike Options expiring in 3 months and lending: Determine the amount of money you should lend.
So far I understand that using the Put-Call parity:
$C-P=S_0-PV(Dividend)-Ke^{-rt}$
and for a synthetic stock:
$S_0=C-P+PV(Dividend)+Ke^{-rt}$
Hence:
$S=1.90-P+44e^{-0.0125}+e^{-0.0125}$
When I check the solution, it says that the amount to lend is
$45e^{-0.0125}=44.4410$
Where did this answer come from? How can I approach this type of problem?
Answer: By Put-Call parity
$$
\begin{align*}
C(S, K, T)−P(S, K, T) &=S−PV(Divs)−K \,\mathrm{e}^{−rT}\\
\Longrightarrow\quad S &= C(S, K, T)−P(S, K, T) +\overbrace{K\, \mathrm{e}^{−rT}+PV(Divs)}^{\text{amount to lend}}
\end{align*}
$$
and then
$$
\begin{align*}
C(S, 44, 0.25)−P(S, 44, 0.25) &=S−PV(Divs)−K \,\mathrm{e}^{−0.05(0.25)}\\
\Longrightarrow\quad S &= C(S, 44, 0.25)−P(S, 44, 0.25)+\overbrace{K\, \mathrm{e}^{−0.0125}+PV(Divs)}^{\text{amount to lend}}\\
&=C(S, 44, 0.25)−P(S, 44, 0.25)+44\, \mathrm{e}^{−0.0125}+\mathrm{e}^{−0.0125}\\
&=C(S, 44, 0.25)−P(S, 44, 0.25)+45\, \mathrm{e}^{−0.0125}
\end{align*}
$$
So the amount to lend is $45\, \mathrm{e}^{−0.0125}=44.4410$.


Como manter a proporção da tela após ser redimensionada pelo usuário?

Question: Preciso restringir uma certa proporção de um JFrame para que a disposição do que eu quero exibir nela não fique distorcida, mas não gostaria de ter que bloquear o redimensionamento com setRezisable(). A proporção minima que to testando é de 350x500(7:10 de ratio), mas gostaria de manter essa proporção sempre que a tela tiver o tamanho alterado.
Fiz um exemplo para ver como fica:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;

import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class KeepAspectRatioTest extends JFrame {

    private static final long serialVersionUID = 1L;

    private static final int WIDTH = 350;
    private static final int HEIGHT = 500;

    public static void main(String[] args) {

        SwingUtilities.invokeLater(() -> {

            KeepAspectRatioTest screen = new KeepAspectRatioTest();
            screen.setVisible(true);
        });
    }

    public KeepAspectRatioTest() {

        initUI();
    }

    private void initUI() {

        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setPreferredSize(new Dimension(WIDTH, HEIGHT));
        setTitle("Keep Aspect Ratio");

        JPanel board = new JPanel();
        board.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.black));

        JPanel sidePanel = new JPanel();
        sidePanel.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.red));
        sidePanel.setLayout(new BoxLayout(sidePanel, BoxLayout.Y_AXIS));
        sidePanel.setPreferredSize(new Dimension(WIDTH/6, HEIGHT));

        add(board, BorderLayout.CENTER);
        add(sidePanel, BorderLayout.EAST);

        pack();
        setLocationRelativeTo(null);

    }
}

Como faço para manter a proporção da tela após ser  redimensionada?
P.S.: acredito que precise utilizar uma ComponentListener, só não sei como controlar isso com esse listener, ainda mais porque, ao permitir redimensionamento, também é habilitado que a tela seja maximizada.
Comment: Qual o motivo do negativo? Eu nao posso mais ter uma dúvida no site? Negativar apenas não me ajuda a perceber o quanto minha dúvida *"não demonstra esforço de pesquisa, não é clara ou não é útil"*.
Comment: Cara, tentei resolver o seu problema de várias formas, tanto as elegantes quanto as gambiarradas e não consegui ainda. Fico surpreso como é que uma coisa dessa parece não ter solução simples. Quando/se conseguir isso, posto uma resposta.
Comment: @VictorStafusa eu vi algumas resposta no SOEn, mas nenhuma de fato consegue resolver isso, ao que parece. Em uma delas, é sugerido reescrever a classe de redimensionamento da janela na mão para restringir isso.
Comment: Também revirei o SOen e tentei mexer com detalhes internos de `java.awt.Window` e não consegui.
Answer: Você pode utilizar o componentResized do componentListener para realizar o cálculo conforme o ratio. Lembre que o ratio é 10:7 ou aproximadamente 1.42 para ficar na horizontal ou 7:10 = 0.7 para ficar na vertical. Funciona para conteiners e painels. Ex:
public class AspectRatio {
    static final double RATIO = 0.7;
    public static void main(String[] args) {
        final JPanel innerPanel = new JPanel();
        innerPanel.setBackground(Color.BLUE);

        final JPanel container = new JPanel(new GridBagLayout());
        container.add(innerPanel);
        container.addComponentListener(new ComponentAdapter() {
            @Override
            public void componentResized(ComponentEvent e) {
                resizePreview(innerPanel, container);
            }
        });
        final JFrame frame = new JFrame("AspectRatio");
        frame.getContentPane().add(container);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(600, 800);
        frame.setVisible(true);
    }

    private static void resizePreview(JPanel innerPanel, JPanel container) {
        int width = container.getWidth();
        int height = container.getHeight();
        float currentAspectRatio = (float) width / height;

        if (currentAspectRatio > RATIO) {
                 width = (int) (height * RATIO);
        } else {
                 height = (int) (width / RATIO);
        }
        innerPanel.setPreferredSize(new Dimension(width, height));
        container.revalidate();
    }
}

Se quiser manter aspecto do Jframe em si, você precisa sobrescrever o método paint() do JFrame, mas irá funcionar somente se for redimensionado pelos cantos. Vale lembrar que não é uma boa aproximação, já que o usuário deveria ter controle total sobre o redimensionamento da janela, o que deveria manter o aspecto é o conteúdo dentro da mesma:
public class AspectRatio {
    static final double RATIO = 1.42;
    static JFrame frame;
    public static void main(String[] args) {
        final JPanel innerPanel = new JPanel();
        innerPanel.setBackground(Color.BLUE);

        final JPanel container = new JPanel(new GridBagLayout());
        container.add(innerPanel);

        frame = new JFrame("AspectRatio") {
            public void paint(Graphics g) {
                super.paint(g);
                resizePreview(frame);
            };
        };
        frame.getContentPane().add(container);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300, 600);
        frame.setVisible(true);
    }

    private static void resizePreview(JFrame jFrame) {
        int width = jFrame.getWidth();
        int height = jFrame.getHeight();
        float currentAspectRatio = (float) width / height;

        if (currentAspectRatio > RATIO) {
            width = (int) (height * RATIO);
        } else {
            height = (int) (width / RATIO);
        }
        jFrame.setSize(new Dimension(width, height));
        jFrame.revalidate();
        jFrame.repaint();
    }
}

Espero ter ajudado!
Comment: Certo, coloquei as duas para outros usuários não confundirem, já que a maioria utiliza horizontal 10:7 mas no exemplo está 7:10. A maximização chama também o `componentResized`, então sem problemas.
Comment: Funciona para o `JFrame` também, só troque o `setPreferredSize` por `setSize`. Vou adicionar na resposta.
Comment: Consegui remover o flickering, utilizando o método `paint()` do Jframe. Vou atualizar a resposta.
Comment: Já tentou redimensionar pelos cantos?
Comment: O meio termo mais óbvio é deixar a janela (`JFrame`) liberado juntamente com um `JScrollPane` para o SO e usuário, e somente manter a proporção do conteúdo. Assim a resolução não fica única e não permite o usuário mudar de qualquer jeito. Mas você simplesmente pode não querer assim. Então o mais próximo que consegui foi pelo `paint()` do`JFrame`. Talvez alguém venha com um jeito melhor.
Comment: Agradeço pela tentativa, mas a primeira solução pelo componentResized acaba funcionando melhor que a do paint(), que só redimensiona em 4 direções e acaba "zoando" mais quando se tenta.


Finding the probability density function...

Question: I've found the probability density function for other functions, but this one seems rather difficult.
$$F(x)=P(X\le x)=1-e^{-x^2}$$
My teacher's solution manual is showing:
$$
\begin{cases} 0, & x<0 \\ 2xe^{-x}, &  x>0 \end{cases}
$$
Maybe I am just having a hard time finding this integral, but I don't seem to get the same results. If I use u-substitution I am setting $u = x^2$ where $du = 2x$ then, but how does that get into the answer, am I selecting a wrong $u$? Is it integration by parts maybe?
Thanks.
Comment: Is there a typo? I think the PDF for $x > 0$ should be $2x e^{-x^2}$.
Comment: You should have $du = 2x\,dx,$ not $du = 2x. \qquad$
Answer: If the density function is given by
$$
f(x) =
\begin{cases}
0,  & \text{if $x<0$,} \\[2ex]
2xe^{-x^2}, & \text{if $x\ge0$,}
\end{cases}
$$ then we have, by the change of variable, $u=t^2$, $du=2tdt$,
$$
F(x)=\int_0^x2t e^{-t^2}dt=\int_0^{x^2}e^{-u}du=\left[-e^{-u}\right]_0^{x^2}=1-e^{-x^2}
$$ as announced.
Answer: If $F_{\small X}(x) = (1-\mathsf e^{-x^2})~\mathbf 1_{x>0}$
Then $f_{\small X}(x) = \dfrac{\mathrm d~~~}{\mathrm d~x}F_{\small X}(x)\\ \qquad = -\dfrac{\mathrm d~\mathsf e^{-x^2} }{\mathrm d ~x\quad}~\mathbf 1_{x>0}\\\qquad = \left.-\dfrac{\mathrm d~(-x^2)}{\mathrm d~x\qquad}\dfrac{\mathrm d~\mathsf e^{u}}{\mathrm d~u~}\right\rvert_{u=(-x^2)} ~\mathbf 1_{x>0}\\\qquad = 2x\mathsf e^u\big\rvert_{u=(-x^2)} ~\mathbf 1_{x>0}\\\qquad = 2x\mathsf e^{-x^2}~\mathbf 1_{x>0}$


problema do evento blur com botão submit

Question: Boa tarde, tenho um form, nele tem um campo text que dispara o evento .blur que pega o nome digitado e retorna um id com ajax, pega o id salva em outro input hidden, o problema é que o evento blur só é disparado se clicar em lugar vazio (para perder o foco) e depois no botão submit, se clicar diretamente no submit não é disparado o evento blur, alguma solução para tal problema? já tentei mudar para evento change mas também não funcionou se clicar diretamente no submit.
 $("#responsavel").blur(function(){var cdgResp  = $("#responsavel").val();$.post("controller/responsavel.php",  {nomeResponsavel:cdgResp} , function(idResp) {if (idResp != false){$("#idResponsavel").val(idResp); }else { $("#idResponsavel").val("0"); } });});

acima está o javascript que dispara o blur
<form action="javascript:func()" method="post">action="javascript:func()" method="post"><input id="responsavel" type="text" name="responsavel" value=<?php echo $dados['responsavel']; ?>"><input id="idResponsavel" type="hidden" name="idResponsavel" value="<?php echo $dados['idResponsavel']; ?>"><input type="submit" value="enviar"></form>

e acima esta o form, criei agora de forma genérica pra exemplificar melhor, os dados ja vem preenchido com php mas caso mude o nome do campo responsável teria que mudar o id do mesmo.
Comment: Tem que por o código amigo para receber ajuda adequada!
Comment: Bom dia, alterei a descrição exemplificando o meu problema.
Comment: Tentou o "onfocusout" ? Tenta dar uma olhada na lista de enventos do js: https://www.w3schools.com/jsref/dom_obj_event.asp
Comment: Na verdade o evento blur até está sendo disparado, mas como é um AJAX que faz ali o submit do form está acontecendo antes do AJAX terminar de ser processado, logo não da tempo de preencher o campo hidden. Tem que sempre lembrar que AJAX são requisições em paralelo. Para o seu caso eu recomendo usar $.ajax ao invés de $.post e usar o atributo ```async: false```
Comment: Já tentei sim @andreia_sp , mas não deu certo.
Comment: @LucasFerreira é exatamente isso que esta acontecendo, está disparando mas os dados que vão para o submit não é alterado, obrigado pela dica, vou tentar dessa forma com async:false
Answer: Utilize o:

keyup

(clique em executar para ver um exemplo)

<!DOCTYPE html>

Nome digitado: <input type="text">

Digite uma letra. Toda vez que ele ficar YELLOW e voltar para o PINK, um evento irá verificar e retornar o ID.

Comment: Obrigado pela resposta @Lollipop, em um caso comum funcionaria, mas no meu caso não deu certo por que nesse mesmo campo text eu uso o autocomplete do jquery, então quando inicio a digitação aparece uma lista de nomes eu seleciono (tipo um select), dai nesse caso já não é disparado o keyup, ao menos que continuasse digitando o nome até o fim
Comment: Mas você não falou que utilizava o autocomplet...E o autocomplet tem seus events, não é pra você ficar usando o input pra isso.
Comment: Não entendi sua colocação sobre "não usar input para isso" mas fui pesquisa sobre os eventos do autocomplet (que não sabia que tinha) e achei o "select" e o "change"  talvez isso resolva meu problema, obrigado!
Comment: esse exemplo aqui resolve meu problema http://www.tutorialspark.com/jqueryUI/jQuery_UI_AutoComplete_Overridding_Default_Select_Action.php
Comment: Exatamente, meu querido. Quando for usar qualquer plugin e precisar implementar algo, veja se a documentação tem o que voce precisa.


Linear Regression for Forecasting: what are the risks?

Question: I have a dataset containing financial data of multiple firms on 7 to 10 years. (yearly data). For each firm/variable i want to predict its value in the next two years.
I don't have enough data (7 to 10 observations for each  variable) so that's not enough for time series analysis (can't capt trend or seasonality). I think a linear regression might do, but i'm not aware of the risks? what kind of error might result on working with regression?
This is a similar question yet it  doesn't really answer my question
Comment: Check: http://stats.stackexchange.com/questions/135061/best-method-for-short-time-series
Answer: you can use tslm  function from RPackage forecast. Of course you should look at the p-value of the model,but not only that. your R² and R² adjusted should be close to 1. well it depends on you data, some times R² that is > 0.5 is enough. you should also test the autocorrelation of the residuals, which is possible whith the Afc function, and the normal distribution of residuals using q-q plot (there are other ways.
If all the tests are good, then the model is valid and you can apply the linear regression to forecast the data over time. The only risk that, the shorter your time series is, the shorter period you'll be able to predict with acceptable error.


O tamanho do nome de uma variável afeta seu peso?

Question: Há diferença de tamanho entre isso:
string packet1234 = "123";

E isso?
string packert1234556 = "123";

Comment: Sorte que não afeta, senão o pessoal do Java estaria lascado.
Comment: Sem falar uns do Oracle ...
Answer: Não, definitivamente não. Na verdade após compilar o código o nome da variável até desaparece. Uma variável é apenas um padrão de projeto bastante conhecido para facilitar o acesso a um endereço de memória. Em linguagens compiladas o nome se transforma em endereços diretos. É uma conveniência de acesso à memória usadas em linguagens ditas de alto nível. Elas são usadas para facilitar o entendimento do código pelo programador. Por isto seus nomes devem ser significativos.
Somente em linguagens totalmente interpretadas, que são bem raras, é que poderia fazer alguma diferença mensurável. Mas esta última palavra é chave. Porque poderia mensurar mas não faria diferença real de fato. E isto em linguagens interpretadas que não possuam nenhum tipo de otimização. Coloco isto mais à título de curiosidade, não afeta em nada o C# que é compilada.
Portanto em qualquer linguagem que eu conheça o tamanho do nome da variável não afetará a performance ou consumo de memória significativamente e na maioria dos casos nem mesmo de forma ínfima. A escolha do nome já deveria ser feita pensando na legibilidade mesmo que houvesse algum custo para nomes grandes.
Até há um custo de memória em C# em certas situações onde o nome da variável não é uma variável local comum, já que C# possui diversos metadados. Então um nome maior traria um consumo maior teórico. Mas é uma diferença tão ínfima e só mesmo na sua definição e não no consumo que seria ridículo achar que isto muda alguma coisa. Seria como reclamar que caiu uma gota de chuva quando você está dentro de uma piscina (sem exagero). Eu coloquei para dar a resposta mais correta possível mas dá até medo haver a interpretação que há um custo extra que deva ser minimamente considerado. Tem tantos outros fatores que afetam o programa que pensar nisto é um absurdo.
E se por acaso a preocupação faça algum sentido é melhor programar em Assembly. É bom que seja uma fera nisto para não fazer código pior que um bom compilador em uma linguagem otimizada faria. Mesmo assim duvido que faria sentido.
Coloquei no GitHub para referência futura.
Comment: Muito bem esclarecido, obrigado!


Concatenate defined variables with dynamic value of loop SCSS

Question: I'm trying to loop some values to concatenate them with some already set variables and just give it a color depth based on some sort of array.
These are my variables with the colors already defined
<code>$brand-primary-surface-0: #fafafaff;
$brand-primary-surface-25: #f5f5f5ff;
$brand-primary-surface-50: #ebebebff;
$brand-primary-surface-75: #d8d8d8ff;
$brand-primary-surface-100: #c0c0c0ff;
$brand-primary-surface-200: #a1a1a1ff;
$brand-primary-surface-300: #767676ff;
$brand-primary-surface-400: #5c5c5cff;
$brand-primary-surface-600: #2e2e2eff;
$brand-primary-surface-700: #242424ff;
$brand-primary-surface-800: #1c1c1cff;
$brand-primary-surface-900: #151515ff;
</code>
This is the map that I want to cycle so that it takes a different value in each cycle
<code>$deeps: 0, 25, 50, 75, 100, 200, 300, 400, 500, 600, 700, 800, 900;
</code>
Finally, I am cycling in this way to dynamically build the classes that I will inject into some components
<code>@each $deep in $deeps {
    .brand-primary-surface-#{$deep} {
        background-color: $brand-primary-surface-#{$deep};
    }
}
</code>
The result I expected is like this
<code>.brand-primary-surface-0 {
    background-color: #fafafaff;
}

.brand-primary-surface-25 {
    background-color: #f5f5f5ff;
}

.brand-primary-surface-50 {
    background-color: #ebebebff;
}
</code>
Instead I get this error
<code>button
ERROR in ./node_modules/css-loader/dist/cjs.js!./node_modules/sass-loader/dist/cjs.js!./src/components/Button/Button.scss undefined
Module build failed (from ./node_modules/sass-loader/dist/cjs.js):
SassError: Undefined variable.
   ╷
94 │ background-color: $brand-primary-surface-#{$deep};
   │ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   ╵
  src\colors.scss 94:27 @import
  src\components\Button\Button.scss 1:9 root stylesheet
</code>
It seems you didn't like how I concatenated the variables. I'm a bit new to SCSS, what do you recommend?
Comment: Does this answer your question? [SCSS / SASS : How to create variables inside an each loop](https://stackoverflow.com/questions/57250528/scss-sass-how-to-create-variables-inside-an-each-loop)
Answer: To access a dynamic variable in SCSS is not possible.
Instead you should use a map:
<code>$brand-primary-surface: (
    25: #f5f5f5ff,
    50: #ebebebff,
    75: #d8d8d8ff,
    100: #c0c0c0ff,
    200: #a1a1a1ff,
    300: #767676ff,
    400: #5c5c5cff,
    600: #2e2e2eff,
    700: #242424ff,
    800: #1c1c1cff,
    900: #151515ff
);

@each $key, $value in $brand-primary-surface {
    .brand-primary-surface-#{$key} {
        background-color: #{$value};
    }
}
</code>

You can also use @each to iterate over every key/value pair in a map by writing it @each ,  in  { ... }. The key is assigned to the first variable name, and the element is assigned to the second. - @each on sass-lang


.End(xlDown).Row changes from Excel 2007 to 2010

Question: After updating from Office 2007 to Office 2010, the macros that worked perfectly in Excel 2007 but do not work in 2010. Specifically i recieved a error on this line:
    y = Worksheets("Raw Data").Range("A2").End(xlDown).Row

Ther error is "error 6  Overflow". I have come to realize that it is due to Excel selecting the max number(1048576) of rows in excel that creates the overflow. There is only data in 975 of these rows. In 2007 it only selected the rows with data. I am wondering what has caused the change in the way that code is handled from 2007 to 2010? Has anyone else experienced this?
Comment: If you have values in column A below row 2, the code should work the same in either version of Excel. If there is nothing below cell A2, then `y` will equal the last row in the sheet and cause the overflow error if `y` is an `int`. Can you post some more code for context? What is in column A?
Answer: Be sure that y variable (and other variables referring to row numbers) are declared as Long, like:
Dim y As Long

I could guess that your variables are Integer at the moment.
I could guess that you have possibly migrated your file from .xls into .xlsm in the meantime which could cause some of that problems.
Comment: In this case, both **Santosh** and **KazJaw** are right and both answers should be incorporated by OP.
Comment: to answer this question I would need to see the whole code, file and know file and code evolution :)
Comment: I know that this would stop the overflow but i am more interested in why it is selecting every row possible in excel when only 975 have data. i am more interested in why it is doing this.
Comment: The file originally is a .xls and i am resaving as .xlsm; if i just copied to a new file and thated the new as a .xlsm would it elminiate the complications between migrating the file?
Comment: we still don't see the way you declare your `y variable`. If you additionally keep my advice (from answer above) you will succeed :)
Comment: Seeing [this question](http://stackoverflow.com/questions/16822875/vba-meaning-of-ampersand-in-range) I'm sure you need to change into `Dim y as Long` as suggested above.
Answer: Try below
  With Worksheets("Raw Data")
        y = .Range("A" & .Rows.Count).End(xlUp).Row
    End With

Comment: @woody If the records are more than 32,767 you need to declare `y variable` as long as answered by kazJaw.


Como destruir um jQuery.fn sempre que for chamado?

Question: Construí um plugin usando jQuery.fn.algumaCoisa = function(options, callback){};, mas quando chamo várias vezes no mesmo elemento, fica multiplicando o comportamento em vez de sobrepor. Tem alguma maneira de sempre que chamar essa função ele resetar o efeito sobre o elemento?
Ao chamar no mesmo elemento ele deveria resetar o comportamento, mas os botões internos estão tendo efeito multiplicado, resumindo, não estão perdendo os efeitos atribuídos anteriormente.
$('div').algumaCoisa(); // usario clica em um botão e chama
$('div').algumaCoisa(); // usario clica em um botão e chama
$('div').algumaCoisa(); // usario clica em um botão e chama

Comment: Orion poderia dar mais detalhes? Pois o `.fn.`  tem a funcao apenas de percorrer os elementos selecionados com uma funcao customizada, o problema parece ser no seu function, entretanto voce pode talvez usar um atributo nos elementos pra detectar se eles foram ja setados. Vou tentar formular uma resposta.
Comment: é um tanto complicado responder esta pergunta, sem saber o que tem nessa função alguma coisa, pois pensando um um função que manipule o `dom` do elemento, com o "`reset`" saberia o que foi alterado? seria necessário criar uma variável com se fosse um log das alteracções.
Answer: Seu problema ocorre pois os eventos são setados de forma acumulativa, para resolvermos isso vamos depender um pouco da forma que você implementou. Irei mostrar dois exemplos o com evento de .click() e com .on() que são dois manipuladores de eventos do jQuery disponíveis nas versões 1.7 + .
Com uso do .click():
jQuery.fn.algumaCoisa = function(){

    //ele remove todos os eventos de click antes de setar
    $(this).unbind('click');

    //seta seu evento
    $(this).click(function() {
        alert("teste1");
    });
}

Com uso do .on():
jQuery.fn.algumaCoisa = function(){

    //ele remove todos os eventos de click antes de setar
    $(this).unbind('click');

    //seta seu evento
    $(this).on('click', function() {
        alert("teste1");
    });
}

Segue jsfiddle, se estiver usando alguma forma diferente de setar o evento é só falar nos comentários!
Comment: O problema é que eu achava que ao remover a função do elemento destruiria todas efeitos internos setados por essa função, resolvi chamando `unbind()` nos elementos internos antes de setar novamente.
Answer: A funcao do jQuery.fn não e atribuir nada, ele apenas passar os nodes selecionados para o seu metodo customizado. Quem define se vai adicionar repetidas vezes e voce.
No caso voce pode usar o attr() pra detectar se o node ja recebeu o atributo (se voce for usar apenas pra nodes), recomendo que tambem verifique se o item selecionado realmente e um node, pois o $(...)  pode receber window e document tambem.
function isDOM(el) {
   return el && el instanceof HTMLElement;
}

jQuery.fn.foo = function() {
    this.each(function() {
       if (isDOM(this) && $(this).attr("data-foo") !== "true") {
           $(this).attr("data-foo", "true");

           //Algo aqui
       }
    });
};

Desta maneira voce pode fazer varios seletores diferentes e ele vai detectar se o elemento html ja recebeu o efeito esperado.
Se o que voce quer e remover o efeito em elementos que ja o tenham, voce pode fazer assim:
function aplicaEfeito(el) {
    //Aqui aplica o efeito
}

function removeEfeito(el) {
    //Aqui remove o efeito
}

function isDOM(el) {
   return el && el instanceof HTMLElement;
}

jQuery.fn.foo = function() {
    this.each(function() {
       if (isDOM(this)) {
           if ($(this).attr("data-foo") !== "true") {
               $(this).attr("data-foo", "true");
                aplicaEfeito($(this));//Aplica o efeito
           } else {
                removeEfeito($(this));//Primeiro remove o efeito
                aplicaEfeito($(this));//Aplica o efeito novamente
           }
       }
    });
};

Answer: Faça isso:
delete $.fn.nomedoplugin;

Isso não afeta as instâncias do plugin já inicializadas.
Comment: O que eu quero na realidade é zerar os efeitos sobre o elemento quando chamar a função novamente.


Problem passing parameters to WebService asp-net C#

Question: Hi everyone let me explain this issue:
Background:

I have two web applications
The first one exposes some web services (server_wapp).
The second one consumes them (client_wapp).
I added a new web service to the server application that takes two strings as parameters, and it work OK using it directly form the .asmx page (new_ws).

Problem:
When I call the new_ws from the client_wapp all the parameters have their right content, but when the method is executed in the server_wapp, one of its parameters is passed as null.
Somthing link this:
In client_wapp I have server_wapp.new_ws("string1", "string2") and it gets executed in server_wapp as new_ws("string1", null).
I already rebuilt both web applications, but the problem remains.
Any ideas/comments?
Thanks in advance!
Comment: Have you checked if both ends use the same name for that parameter (maybe just casing)?
Answer: Update the link to server_wapp so that the proxy source code will be re-generated. WebService is usually used by adding reference to webservice url, and everytime you do some modifications in the webservice, its should be updated.


Geolocation Accurcy When Anonymizing IP

Question: I'm setting up a new server for a website. I want to ensure that my users' privacy is well protected (at least from my side). Initially I wanted to not track IP addresses at all. However, I need some rough estimation of the user's location so that I know where in the world to place my servers to improve access speeds. The city and even region is not that important, I'm only concerned with the country.
Instead of not logging IPs at all, I decided to rather anonymize them. I want to anonymize as many octets of the IP as possible (increase anonymity), but still have a good pinpoint of the country (accuracy).
I found a few articles that discuss this, but they are only concerned with a single octet. According to those articles, about 1-5% of countries might be misclassified if one octet is anonymized.
Does anyone know (more or less) how this accuracy looks like when anonymizing 2 or 3 octets?
Comment: Approximately zero.
Comment: The past few hours I've been implementing a script to check a range of different IPs. With 2 obfuscated octets, the majority are wrong. Although it seems that the continent is still correct - but that might be a coincidence.
Comment: And after thinking a bit, it is kind of obvious. If you have a class A or class B IP and the company/ISP is in control of the entire sub-range, 2 obfuscated octets are still detecting the country accurately, since those companies control the entire range. If the ISP does not control all the IPs or uses a class C, detection is pretty much 0. Since most home users have one of the latter IPs, it seems like 1 octet is the limit.
Answer: Instead of obfuscating parts of the IP address (198.51.100.xx, 198.51.xx.xx, 198.xx.xx.xx) do the GeoIP resolution against a local database and log only the country. This way you'll have accurate statistics without storing any parts of the IP. The local database is crucial as you don't want to send the IP addresses to a 3rd party.

Geolocation Accurcy When Anonymizing IP


data normalisation problems

Question: I am pretty new in machine learning and hence facing a lot of confusion in data normalisation concepts. Someone pls clarify the following doubts :
1) While normalising a data matrix of m-samples x n-features, the normalisation should be done along m-samples or along the n-features i.e we normalise each row or each column here ?
2) We should normalise all the data together or normalisation should be done separately for each class.
3) Suppose I have a vector of 2-samples x n-features as shown
<code>class_1   0.4432       27.19        0.6733   0.0828  0.4134  -0.6662  0.3381  0.0552   0.0    -0.01167    0.0    0.0    0.0    0.00056    0.0    0.0    0.03111    0.05778    0.01333    0.0    -0.02722    -0.02333    0.0    0.00222    -0.02722    0.0    0.0    0.0    10100   10010   11000   10100   10100   11000   11000   10001   11000   10001   10001   10100   10001   10001   10001

class_2   0.7647       16.1073        0.7867   -0.2414  -0.2264  -0.8025  0.8649  -0.3524   -0.01944    0.0    0.0    0.0    0.0    0.0    0.0    0.0    0.0    0.04611    0.0    -0.01944    0.03556    -0.02722    0.03111    0.0    0.0    0.0    0.0    0.0    10010   10100   11000   10010   10001   10100   10010   10001   10001   11000   10001   10001   10001   11000   10001
</code>
How to normalise in this case as you can see that the first few features have float values but there are some which are encoded binary features ( the 00110 types are some position informations) . If we normalise what will happend to such information ?
4) The training and testing data should be separated after normalisation or before normalisation and then normalised ?
5) What about the user sample ? once I train and prepare my classifier the user give a SINGLE input of 1-sample x n-features ? It is quite obvious that the values for each feature will differ in magnitude greatly as compared to normalised data used in training and testing. How to handle this thing ?
Answer: 1.) The features, typically. If the features are real valued then the most common approach would be to represent each feature by the Standard score. Assuming each row corresponds to a sample and each column to a feature, $\mu_j$ and $\sigma_j$ are the mean and standard deviation of the $j^{th}$ column, and $x_{i,j}$ is the value of feature $j$ for sample $i$ you would compute the normalized value as
$$
\hat{x}_{i,j} = \frac{x_{i,j} - \mu_j}{\sigma_j}.
$$
That being said, there are plenty of other ways to do normalization and cases where normalizing rows makes sense. An example of the later would be if the samples are documents represented by word counts. Then computing
$$
\hat{x}_{i,j} = \frac{x_{i,j}}{\sum_j x_{i,j}}
$$
would give normalized histograms of word counts. This could be useful if your documents have very different length since it would keep features from having wildly different magnitude. This is just an example and there are probably better ways.
2.) All together. The former doesn't make any sense since you'll want to apply the same normalization at test time, when you assume you don't know the labels.
3.) I would start by standard scoring the real valued features. How to handle the binary features will depend on what they represent. If the binary features are encodings (like 0101 = 5) this is a bad idea (see this answer I gave for an explanation why) and you'll either want to convert them to the numerical values or encode them as categorical (1-of-$k$) variables. If they're just presence features (like $x_{ij} = 1$ if age of $i$ is greater than 50), then I would start by not doing anything to them.
4.) Typically before. Then normalize the test data using the same values you used to normalize the training data. For example, if you were using standard scores you wouldn't compute new means and standard deviations for the test data, you would just use the same ones you calculated from the training data. This is important.
5.) This is really the same as question 4. Use the same normalization you applied to the test set using the same parameters (means, standard deviations, whatever).
Comment: thanks alto... this was really helpful and for the first time someone clarified my doubts so nicely regarding mormalisation process...

I have another small query.. the tf-idf method which you mentioned in the link.. can be used for any data where we are considering count of certain patterns or just for text ?

data normalisation problems


Jenkins Pipeline fails when triggering a remote job with option "Block Build Until Complete" is enabled

Question: I created a pipeline which should trigger a job on a different Jenkinsserver.
I use the Remote Trigger Plug-in and I am able to trigger the Job with following statement (currently this is the only statement in my pipeline):
<code>triggerRemoteJob enhancedLogging: true, job: 'myJob', maxConn: 1,     remoteJenkinsName: 'MyJenkins'
</code>
But after the Job is triggered the pipeline tries to connect a job in a job running on localhost which obviously fails.
I tried to disable some options an found that it works if I disable blockBuildUntilComplete.
From the Log I got following with option enabled:
<code>##############################################################################    ##################################

  Parameterized Remote Trigger Configuration:

    - job:                     myJob

    - remoteJenkinsName:       myJenkins

    - parameters:

    - blockBuildUntilComplete: true

    - connectionRetryLimit:    5

################################################################################################################

Triggering non-parameterized remote job 'http://x.x.x.x:8080/job/myJob'

  Using globally defined 'Credentials Authentication' as user 'myUser' (Credentials ID 'myCredentials')

Triggering remote job now.

CSRF protection is disabled on the remote server.

  Remote job queue number: 47

Remote build started!

  Remote build URL: http://localhost:8080/job/myJob /8/

  Remote build number: 8

Blocking local job until remote job completes.

calling remote without locking...

Connection to remote server failed , waiting for to retry - 10 seconds until next attempt. URL: http://localhost:8080/job/myJob /8/api/json/, parameters:

Retry attempt #1 out of 5

Connection to remote server failed , waiting for to retry - 10 seconds until next attempt. URL: http://localhost:8080/job/myJob /8/api/json/, parameters:

Retry attempt #2 out of 5

Connection to remote server failed , waiting for to retry - 10 seconds until next attempt. URL: http://localhost:8080/job/myJob /8/api/json/, parameters:

Retry attempt #3 out of 5

Connection to remote server failed , waiting for to retry - 10 seconds until next attempt. URL: http://localhost:8080/job/myJob /8/api/json/, parameters:

Retry attempt #4 out of 5

Connection to remote server failed , waiting for to retry - 10 seconds until next attempt. URL: http://localhost:8080/job/myJob /8/api/json/, parameters:

Retry attempt #5 out of 5

Max number of connection retries have been exeeded.
</code>
I changed the names and the IP-Adress of my Jenkins-Server.
I must do some steps after my remote job finished which are depending from its results. So I must wait until the job is done.
Is there a way to do this without the block-option or what must I do to get the option working?
Answer: I checked the released of the plugin and I found an improvement for release 3.0.8 called "Extend POST timeout & avoid re-POST after timeout"
I reviewed the change an since it looked good with regards to our problem I updated our plugin (v3.0.7) to the current version.
Now the error does not appear anymore.


Constraints on variables to form orthonormal columns

Question: I have a series of equations \begin{align} u_{11} &= \frac{zc_1}{x} \frac{\sin(\delta + \omega)}{\sin \alpha} \\
u_{21} &= \frac{zc_2}{x} \frac{\sin \omega}{\sin \alpha} \\
u_{31} &= \frac{tc_1}{x} \frac{\sin \delta }{\sin \alpha} \\
u_{41} &= 0 \end{align}
and \begin{align} u_{13} &= \frac{zc_1}{y} \Bigg( \cos(\delta+\omega)+\frac{\sin(\delta + \omega)}{\tan \alpha} \Bigg)\\
u_{23} &= \frac{zc_2}{y} \Bigg( \cos(\omega)+\frac{\sin( \omega)}{\tan \alpha} \Bigg) \\
u_{33} &= \frac{tc_1}{y} \Bigg( \cos(\delta)+\frac{\sin(\delta)}{\tan \alpha} \Bigg) \\
u_{43} &= \frac{tc_2}{y} \end{align}
Where I know that $$0 <x,y<1$$ $$0 \leq z,t,c_1,c_2 \leq 1$$ $$0<\alpha<\pi/2$$ $$0 \leq \delta, \omega \leq \pi/2$$ and $$x^2+y^2=z^2+t^2=c_1^2+c_2^2=1$$ and all parameters are real. My goal is to find out the constraints needed to make the $(u_{11},u_{21},u_{31},u_{41})$ and $(u_{13},u_{23},u_{33},u_{43})$ orthonormal vectors. That is, given $(x,y,z,t,\alpha,\omega)$, can one find $c_1,c_2,\delta$ that will make these columns orthonormal? We therefore impose that $$u_{11}^2+u_{21}^2+u_{31}^2=1$$
$$u_{13}^2+u_{23}^2+u_{33}^2+u_{43}^2=1$$ and
$$u_{11}u_{13}+u_{21}u_{23}+u_{31}u_{33}=0$$ however expanding these expressions do not allow me to solve for $c_1,c_2$ or $\delta$. Is there an efficient way to go about this?
Comment: Since $(x,y)$, $(z,t)$ and $(c_1,c_2)$ are all points on $S^1$ it may help to write them as angles (say $x=\cos\theta$, $y=\sin\theta$, $z=\cos\varphi$, $t=\sin\varphi$, $c_1=\cos\zeta$, $c_2=\sin\zeta$) so that all equations are expressed in terms of trigonometric functions.
Answer: With some additional border conditions, this problem could be directly transformed into the modal solution of a physical problem. Which is the original problem bringing these expressions? That could help to clarify a better solution.
As is, none of the given expression can be simplified in a simple way enabling to give  "closed" inequalities on the given variables.
By applying the constraints, it is straightforward to find:
$$
\mathscr{C}_{11}:
(zc_1)^2(s\delta\omega)^2+(zc_2)^2(s\omega)^2+(tc_1)^2(s\delta)^2
=(xs\alpha)^2\\
\mathscr{C}_{33}:
(zc_1)^2(s\delta\omega\alpha)^2+(zc_2)^2(s\omega\alpha)^2+(tc_1)^2(s\delta\alpha)^2+(tc_2)^2(s\alpha)^2
=(ys\alpha)^2\\
\mathscr{C}_{13}:
(zc_1)^2s\delta\omega s\delta\omega\alpha+(zc_2)^2s\omega s\omega\alpha+(tc_1)^2s\delta s\delta\alpha
=0
$$
where $s\phi_1\cdots\phi_n$ and $c\phi_1\cdots\phi_n$ represent the $\sin$ and $\cos$ functions applied over the sum of the $\phi_i$ angles denoted right in front of it, not to be confused with $c_1$ and $c_2$, variables part of the problem.
Reordering between the $c_1$, $c_2$ terms:
$$
\mathscr{C}_{11}:
c_1^2 (z^2(s\delta\omega)^2+t^2(s\delta)^2)
+c_2^2 z^2(s\omega)^2
= (xs\alpha)^2\\
\mathscr{C}_{33}:
c_1^2 (z^2(s\delta\omega\alpha)^2+t^2(s\delta\alpha)^2)
+c_2^2 (z^2(s\omega\alpha)^2+t^2(s\alpha)^2)
= (ys\alpha)^2\\
\mathscr{C}_{13}:
c_1^2(z^2s\delta\omega s\delta\omega\alpha+t^2s\delta s\delta\alpha)
+c_2^2(z^2s\omega s\omega\alpha)
=0
$$
From Cramer's on $\mathscr{C}_{11}$ and $\mathscr{C}_{33}$:
$$
\Delta=
(z^2(s\delta\omega)^2+t^2(s\delta)^2)  (z^2(s\omega\alpha)^2+t^2(s\alpha)^2)-
z^2(s\omega)^2  (z^2(s\delta\omega\alpha)^2+t^2(s\delta\alpha)^2)\\
\Delta_1=
(xs\alpha)^2  (z^2(s\omega\alpha)^2+t^2(s\alpha)^2)-
(ys\alpha)^2  (z^2(s\delta\omega\alpha)^2+t^2(s\delta\alpha)^2)\\
\Delta_3=
(xs\alpha)^2  (z^2(s\delta\omega)^2+t^2(s\delta)^2)  -
(ys\alpha)^2  z^2(s\omega)^2
$$
The $c_1$ and $c_2$ values are the square roots from:
$$
c_1^2={\Delta_1 \over \Delta}=
{
(xs\alpha)^2  (z^2(s\omega\alpha)^2+t^2(s\alpha)^2)-
(ys\alpha)^2  (z^2(s\delta\omega\alpha)^2+t^2(s\delta\alpha)^2)
\over
(z^2(s\delta\omega)^2+t^2(s\delta)^2)(z^2(s\omega\alpha)^2+t^2(s\alpha)^2)-
z^2(s\omega)^2 (z^2(s\delta\omega\alpha)^2+t^2(s\delta\alpha)^2)}\\
c_2^2={\Delta_3 \over \Delta}=
{
(xs\alpha)^2 ( z^2(s\delta\omega)^2+t^2(s\delta)^2)  -
(ys\alpha)^2  z^2(s\omega)^2
\over
(z^2(s\delta\omega)^2+t^2(s\delta)^2)(z^2(s\omega\alpha)^2+t^2(s\alpha)^2)-
z^2(s\omega)^2 (z^2(s\delta\omega\alpha)^2+t^2(s\delta\alpha)^2)}
$$
Note that the term $s\delta\omega\alpha$ must be negative in order the signs be preserved (!). This is the only term which can be negative after a $\sin$ operator involving angles in the $(0,pi/2)$ range.
And from $\mathscr{C}_{13}$ we have a expression able to be numerically solved for $\delta$:
$$
\mathscr{C}_{13}:
\Delta_1^2
(z^2 s\delta\omega s\delta\omega\alpha+t^2 s\delta s\delta\alpha)
=
-\Delta_3^2
(z^2 s\omega s\omega\alpha)
$$
Hence:
$$
(
x^2  (z^2 s\omega\alpha^2
+t^2 s\alpha^2)-
y^2  (z^2 s\delta\omega\alpha^2
+t^2 s\delta\alpha^2)
)^2
(z^2 s\delta\omega s\delta\omega\alpha
+t^2 s\delta s\delta\alpha)
=
-(
x^2  (z^2 s\delta\omega^2
+t^2 s\delta^2)  -
y^2  z^2 s\omega^2
)^2
(z^2 s\omega s\omega\alpha)
$$
Which, spite of the closed solution for $c_1(\delta)$ and $c_2(\delta)$, cannot be solved in a closed for the last parameter $\delta$.
Comment: This answer is unclear and incorrect. Given that $c_1$ and $c_2$ are positive one may easily solve for these variables by squaring and adding OP's equations.
Comment: I rechecked. Expressions are added for $c_1$, and $c_2$, but the original expressions are correct. Which is your results or solution so far?


Deep NNs, backpropagation and error calculation

Question: I was following the backpropagation tutorial by Michael Nielsen on http://neuralnetworksanddeeplearning.com/chap2.html, one of the very few places where the backprop algorithm is nicely explained both in theory and practice with an actual implementation in python.
Now, something is not clear when he explains how to calculate the error on a specific layer in terms of error in the next layer (I will provide a screenshot because I don't want to mess with notation):

Here, delta^l is the error in layer l, the circled dot is the elementwise product betweeen vectors, w is a weight matrix, and sigma primed indicates the derivative of an activation function.
Now, observe he points out that by applying the transpose operator to the next-layer-error vector (which is the previous layer during backprop), one is "sending back" the error across the network, and then, multiplying by the derivative of sigma, one applies the chain rule which completes the backprop step.
I have troubles understanding what does he really mean by saying that the traspose operator "sends back".
Perhaps he wants to apply the inverse trasformation? But unless the matrix happens to be orthogonal, which is not the case AFAIK, the transpose does NOT equal the inverse..
In any case, I would have thought of applying some kind of differential operator to matrix w, and not the transpose one.
Opinions?
NOTE: Please let me know whether this post is correctly suited for stackoverflow, or should it be posted on stats or math stackexchange.
Answer: "When we apply the transpose weight matrix, $(w^{l+1})^T$, we can think intuitively of this as moving the error backward through the network"
Is that the sentence you're confused about? Note that in this sentence he's not trying to provide intuition for ''applying the transpose operator'', he's trying to provide intuition for ''aplplying the transpose weight matrix'', which basically means ''multiplying by the transpose weight matrix''. That entire act of multiplying the error vector with the transposed weight matrix, that is what can be understood intuitively as moving the error backward through the network. Not just the transpose operator on its own.
The reason for doing the transpose is simply to make the dimensions work out, that matrix needs to be transposed in order to guarantee that multiplying it with the error vector afterwards results in the correct dimensionality.
The reason why this application (~= multiplication) with the transposed weight matrix can be understood as moving the error backward through the network is kind of exactly the same intuition you probably already have for the forwards pass. In the forwards pass, a high/strong weight means a node in one layer has a large influence on the connected node in the next layer. Exactly the same intuition holds here for the backwards pass, because, just like in the forwards pass, we're multiplying something with a weight. In the forwards pass, that something is the activation level of a node in the previous layer. In the backwards pass, that something is the error observed in a node in the later layer. If a particular connection is ''strong'' (weight has a high value), and we also have a large error, we should put a large amount of ''blame'' for the error on that large weight. This is what we get by multiplying by the (transposed) weight matrix; large weights take a large portion of the ''blame'' for large errors.

More Elaborate explanation for transpose:
Let's consider the forwards pass, following the notation from your link. For simplicity, let's ignore activation functions and biases for now, they're not really important for our intuition. Then, equation 25 in your link tells us that the activation vector $a^l$ of layer $l$ is defined as $a^l = w^l * a^{l-1}$. To make the notation a bit more consistent with the equation for the backwards pass, we'll rewrite this as $a^{l+1} = w^{l+1} * a^l$ (simply added $1$ to all layer indices).
$w^{l+1}$ is a matrix, and the $a$ things are vectors, so it's convenient to consider again what the matrix-vector multiplication looks like. Take a look at the image near the top here for example: http://mathinsight.org/matrix_vector_multiplication , copied at the bottom of this answer.
Let's consider the activation level of the very first node (at the top) of layer $l+1$. This would be the top element of the vector in the right-hand side of the equation on the page I linked. This one activation level is determined by the complete vector of activation levels of the entire previous layer, and the very first row of weights in the weight matrix.
Now suppose we have a vector $\delta^{l+1}$ of errors in layer $l+1$. Let's again consider only the top node of this layer. The activation level of this particular node was determined by the top row of the weight matrix $w^{l+1}$, and the entire vector of activation levels $a^l$. We'll want to "punish" each of the weights in that top row proportional to the magnitude of that weight and our error. So, to do that, we'll want some kind of multiplication between $w^{l+1}$ and $\delta^{l+1}$ (note that this is different from the forwards pass, in which we had a multiplication between the same weight matrix, but an activation vector from a different layer). This should again result in a vector with the same shape as $a^l$ (this is already one clue that we have to do the transpose, otherwise the shape simply won't be correct).
To figure out how this multiplication should look exactly, we'll have to investigate which weights exactly are to blame for which errors. The top row of weights in the matrix $w^{l+1}$ had (during the forwards pass) influence on only the top element of $a^{l+1}$, and is therefore now only to blame for the top element of the error vector $\delta^{l+1}$ and that entire top row of weights should therefore now also only be multiplied by the top element of $\delta^{l+1}$ in order to compute a part of $\delta^l$. In the notation of the image near the top of that page I linked, this means that we would like our top row of weights to be only multiplied $x_1$. But that's not what the picture of matrix-vector multiplication says, that picture says that elements of the top row of the matrix are multiplied with all $x$. If you look carefully, there is a vector in that matrix which is solely multiplied by the top element $x_1$ though, which is the very first column of the (weight matrix). By transposing the weight matrix, we interchange rows and columns, and we essentially get exactly the multiplications we desire.
Linked matrix-vector multiplication
$\begin{align*}
  A{x}=
  \left[
    \begin{array}{cccc}
      a_{11}& a_{12}& \ldots& a_{1n}\\
      a_{21}& a_{22}& \ldots& a_{2n}\\
      \vdots& \vdots& \ddots& \vdots\\
      a_{m1}& a_{m2}& \ldots& a_{mn}
    \end{array}
  \right]
  \left[
    \begin{array}{c}
      x_1\\
      x_2\\
      \vdots\\
      x_n
    \end{array}
  \right]
  =
  \left[
    \begin{array}{c}
      a_{11}x_1+a_{12}x_2 + \cdots + a_{1n} x_n\\
      a_{21}x_1+a_{22}x_2 + \cdots + a_{2n} x_n\\
      \vdots\\
      a_{m1}x_1+a_{m2}x_2 + \cdots + a_{mn} x_n\\
    \end{array}
  \right]
\end{align*}
$
Comment: I understand your qualitative considerations about sensitivity and errors. What I still miss, though, is why we use the transposed matrix in order to "move the error backwards". It couldn't be just a matter of dimensions.. Remember that the matrix-vector product is like applying a linear transformation to that vector (and the entire space it lies within).
Comment: @MadHatter I've edited a large block of extra text into my answer. Does this help?
Comment: Although, to be honest, there is still something I'm missing. The top row of W is to blame for errors in the top node. Fine, but:

1. What is the connection between the error vector (which comes backwards from the output layer) and the activation vector a_(l+1) which is directly produced by Wa_l?

2. If the top row is the only to blame, for errors in the top node, by trasposing we somewhat lose track of this, since as you duly noticed, we multiply that error by the first COLUMN, which has little to to, aside from its first element with how that error has been produced.
Comment: 1. The connection between error vector and activation vector is that high activation levels (in an absolute sense, so also very negative numbers) should be blamed more for high errors than low activation levels. 2. The transposing is necessary because we change the equation a bit. In forwards pass, `W*a^l  = a^{l+1}`. In backwards pass, `W*delta^{l+1} = delta^l` (ignoring activation functions etc). Note how the l+1 moved from right side of the equation to the left side of the equation. To make sure that the correct weights still get the correct amount of ''blame'', the transpose is necessary.
Comment: Good, thanks. Still, the question about row/column exchange remains. That is: " If the top row is the only to blame, for errors in the top node, by trasposing we somewhat lose track of this, since as you duly noticed, we multiply that error by the first COLUMN, which has little to to, aside from its first element with how that error has been produced."
Comment: No, that first column has everything to do with it. It's very important to note that layer indices `l+1` and just plain `l` get swapped around between forwards and backwards. In the picture on the webpage, A is the matrix of weights. x is the vector of previous activations a^l in forwards, but it's the vector of (already known) ''next'' errors delta^{l+1} in backwards. Error x_1 was ''created'' by the top row of weights, so we also again want to multiply it by that same top row of weights to compute the top element of delta^l. The math for that only works out if you transpose the weight matrix
Comment: Hell, that should have been clear from the beginning, and yet I didn't chatch it till now. Many thanks. All the machinery is in place to keep the blame where it belongs, in order to reduce it afterwards. And it's even elegant algebraically.
Comment: If I may, I would point out that my confusion arose from getting misled when considering the three-layer-notation: l-1, l, and l+1, where the process should be analyzed in a two-layer setting in order to be more readily understood. As you pointed out, one could do that by "swapping" the indices during the backward pass.


How to notate a quick open and close hi-hat?

Question: How do I notate a hit on the hi-hat where the drummer opens the hi-hat when the stick hits the cymbal and immediately closes it?
Answer: Here is an example of hi-hat open and close notation:

The hats are notated by the x note heads above the top line of the staff. The + above a note indicates playing the closed hi-hat with a stick, and the o above a note head indicates playing an open hi-hat with a stick. If you want the drummer to play the hat with the stick again when closing the hat, you would notate it like this.
There are two ways to notate closing the hat without playing it again with the stick. One way is to notate it as above with a parentheses around the note head, like (x), to indicate a ghost note. Another way would be to indicate playing the hat with the foot with a + above the foot note for clarity. Playing the hats with a foot is indicated with an x note head on the space below the bottom line of the staff as below:

Use normal note duration notation to indicate the timing of the opening and closing of the hats. If you find yourself feeling like 32nd or 64th notes are required for the very short duration you want, you might instead use a grace note for the open hat note.
Grace notes (often used to indicate a flam) look like this:
Answer: This should be understandable.


Utilizando o Helper do Codeigniter (Download_helper)

Question: Boa noite! Estou utilizando a função force_download() para realizar o download de um arquivo. Contudo, preciso fazer esse mesmo procedimento, mas com o download de vários arquivos ao mesmo tempo. Implementei um código, a lógica que utilizei não está realizando tal procedimento. Alguém pode me dar uma dica do que posso fazer?
Controller:
 public function download($id = NULL){
    $this->load->helper('download');
    $download = $this->db->query('SELECT * FROM arquivos WHERE protocolo_id ='.$id);
    foreach ($download->result() as $itens){
        $diretorio = file_get_contents('./uploads/'.$itens->arquivo);
        $arquivo = $itens->arquivo;
        force_download($arquivo, $diretorio);
    }
}

Answer: O que recomendo pra você é usar a library Zip para adicionar seus arquivos em um compactado e então baixa-los: Abaixo sua função de forma similar, que, acredito atender sua necessidade:
public function download($id = NULL){
    $this->load->library('zip');

    $download = $this->db->query('SELECT * FROM arquivos WHERE protocolo_id ='.$id);

    foreach ($download->result() as $itens){
        $this->zip->add_data('./uploads/'.$itens->arquivo, file_get_contents('./uploads/'.$itens->arquivo));
    }

    if($download->num_rows() > 0){
        $this->zip->archive('/path/arquivos.zip');
        $this->zip->download('arquivos.zip');
    }
}

Comment: Teoricamente funcionou, só que quando extraiu o arquivo zip, não exibi as imagens. diz: "O Visualizar de fotos do Windows não pode abrir esta imagem porque não oferece suporte a este formato...." Sendo o problema só nos arquivos que faço download. Tem alguma configuração a se fazer?
Comment: Funcionou sim, só mudei a posição do `file_get_contents` como segundo parâmetro. Pois o primeiro é o nome do arquivo e o segundo é o conteúdo do arquivo. Tanks!


Fast n-gram calculation

Question: I'm using NLTK to search for n-grams in a corpus but it's taking a very long time in some cases. I've noticed calculating n-grams isn't an uncommon feature in other packages (apparently Haystack has some functionality for it). Does this mean there's a potentially faster way of finding n-grams in my corpus if I abandon NLTK? If so, what can I use to speed things up?
Comment: More reading for those interested: http://packages.python.org/Whoosh/ngrams.html
Comment: Related question: http://stackoverflow.com/questions/21883108/fast-optimize-n-gram-implementations-in-python
Answer: Since you didn't indicate whether you want word or character-level n-grams, I'm just going to assume the former, without loss of generality.
I also assume you start with a list of tokens, represented by strings. What you can easily do is write n-gram extraction yourself.
def ngrams(tokens, MIN_N, MAX_N):
    n_tokens = len(tokens)
    for i in xrange(n_tokens):
        for j in xrange(i+MIN_N, min(n_tokens, i+MAX_N)+1):
            yield tokens[i:j]

Then replace the yield with the actual action you want to take on each n-gram (add it to a dict, store it in a database, whatever) to get rid of the generator overhead.
Finally, if it's really not fast enough, convert the above to Cython and compile it. Example using a defaultdict instead of yield:
def ngrams(tokens, int MIN_N, int MAX_N):
    cdef Py_ssize_t i, j, n_tokens

    count = defaultdict(int)

    join_spaces = " ".join

    n_tokens = len(tokens)
    for i in xrange(n_tokens):
        for j in xrange(i+MIN_N, min(n_tokens, i+MAX_N)+1):
            count[join_spaces(tokens[i:j])] += 1

    return count

Comment: The newer versions of Cython recognize Python for statements and speeds them up if possible. Further you have a method lookup in the inner iteration. defining 'tokenjoiner=" ".join' outside the loop and replacing the inner " ".join should speed things up.
Comment: and you can rewrite the inner line with "count.get(....) +=1" introduce another var for avoiding method lookup.
Answer: You might find a pythonic, elegant and fast ngram generation function using  zip  and splat (*) operator here :
def find_ngrams(input_list, n):
  return zip(*[input_list[i:] for i in range(n)])

Answer: For character-level n-grams you could use the following function
def ngrams(text, n):
    n-=1
    return [text[i-n:i+1] for i,char in enumerate(text)][n:]

Answer: def generate_ngrams(words, ngram=2):
  return [words[i:i+ngram] for i in range(len(words)-ngram+1)]

sentence = "I really like python, it's pretty awesome."
words = sentence.split()
words

['I', 'really', 'like', 'python,', "it's", 'pretty', 'awesome.']

res = generate_ngrams(words, ngram=2)
res

[['I', 'really'],
 ['really', 'like'],
 ['like', 'python,'],
 ['python,', "it's"],
 ["it's", 'pretty'],
 ['pretty', 'awesome.']]

res = generate_ngrams(words, ngram=3)
res

[['I', 'really', 'like'],
 ['really', 'like', 'python,'],
 ['like', 'python,', "it's"],
 ['python,', "it's", 'pretty'],
 ["it's", 'pretty', 'awesome.']]

res = generate_ngrams(words, ngram=4)
res

[['I', 'really', 'like', 'python,'],
 ['really', 'like', 'python,', "it's"],
 ['like', 'python,', "it's", 'pretty'],
 ['python,', "it's", 'pretty', 'awesome.']]

Fast n-gram calculation


Estou tentando criar um TRIGGER BEFORE AFTER mas da um erro de variável não declarada no IF da trigger

Question: Estou tentando criar uma trigger before insert na minha tabela Consultas mas o erro 1327 aponta que a variável tipoConsulta não está declarada;
Trigger BEFORE INSERT da tabela Consultas:
CREATE DEFINER = CURRENT_USER TRIGGER `agendadeconsultorio`.`consultas_BEFORE_INSERT`
BEFORE INSERT ON `consultas`
FOR EACH ROW
BEGIN

    IF tipoConsulta = "M" THEN
        SET
            data := NEW.data,
            hora := NEW.hora,
            ordem := NULL;
    ELSE
        SET
            data := NEW.data,
            hora := NULL,
            ordem := ordem + 1;
    END IF;

END

Abaixo a tabela da trigger acima
CREATE TABLE IF NOT EXISTS Consultas (

  id int primary key,
  ordem INT UNIQUE AUTO_INCREMENT,
  nomePaciente VARCHAR(100) NOT NULL,
  nomeMédico VARCHAR(100) NOT NULL,
  data DATETIME,
  hora TIME,
  tipoConsulta ENUM("M","O"),

    FOREIGN KEY(nomePaciente) REFERENCES Pacientes(nome)
    ON DELETE CASCADE

)ENGINE=InnoDB  DEFAULT CHARSET=utf8mb4;

Comment: É Oracle o Mysql ou ambas , triggers são objetos que dependem da sintaxe do Banco.
Answer: Opa, tudo bom?
Antes de utilizar as variáveis, instância elas na triagger, dessa forma:
    CREATE DEFINER = CURRENT_USER TRIGGER `agendadeconsultorio`.`consultas_BEFORE_INSERT`
    BEFORE INSERT ON `consultas`
    FOR EACH ROW
    BEGIN
    DECLARE data DATE;
    DECLARE hora TIME;
    DECLARE ordem INT;
    DECLARE v_tipoConsulta CHAR;
SELECT tipoConsulta INTO v_tipoConsulta FROM consultas_BEFORE_INSERT order by registro_sequencial desc;

        IF NEW.tipoConsulta = "M" THEN
            SET
                data := NEW.data,
                hora := NEW.hora,
                ordem := NULL;
        ELSE
            SET
                data := NEW.data,
                hora := NULL,
                ordem := ordem + 1;
        END IF;

    END

Me avisa se funcionar


CLIUSR certificate expiration

Question: I have an Exchange 2019 DAG and the CLIUSR certificate (clusinfracert) will expire soon.  I have extensively researched this and there are very few resources online that address this certificate.
There is nothing to 'try', it's either manually renew it via ECP or allow it to expire and see what happens to the DAG.
Do I need to manually renew this cert or will it renew on its own?
Comment: How about this issue now?
Answer: The certificate 'CLIUSR' on server 'servername' is about to expire on 'date'
https://social.technet.microsoft.com/Forums/en-US/eda7a791-032b-45a5-9df8-0fd5a488d0f5/the-certificate-cliusr-on-server-servername-is-about-to-expire-on-date?forum=Exch2019
yes, there is not much documentation that we could find that references a certificate issued to CLIUSR, but according to this thread, we could know:
"Windows clustering appears to self-manage these, making the Exchange ECP warnings unnecessary (and a bit scary).
So nothing to do in exchange, despite the warnings. "

CLIUSR certificate expiration


Updating multiple rows in a single transaction in Slick 3.1.x

Question: Assume a table table1 has three columns col1, col2 and col3. Also, assume I need to update col1 based on the value of col2. For example, with the following SQL statement
update table1 set col1=111 where col2=222

Let's also say I have to update 1000 times table1 and I have the information in the following Seq:
case class Table1 (col1: Int, col2: Int, col3: Int)
val list = Seq(Table1(111,222,333),Table1(111,333,444), .... )

What's the best way to update 1000 rows in Slick 3.1.x? Is it possible to run a batch statement with foreach?
 val action = table1.foreach(....)

Answer: You can use DBIO.sequence to build a list of actions to execute, something like this:
db.run(DBIO.sequence(list.map(l => ???)))

Here is a more complete example:
import scala.concurrent.Await
import scala.concurrent.duration.Duration
import slick.driver.H2Driver.api._

object main {

    // The class and corresponding table
    case class Thing (id: String, col1: Int, col2: Int)
    class Things(tag: Tag) extends Table[Thing](tag, "things") {
        def id = column[String]("id", O.PrimaryKey)
        def col1 = column[Int]("col1")
        def col2 = column[Int]("col2")

        def * = (id, col1, col2) <> ((Thing.apply _).tupled, Thing.unapply)
    }

    val things = TableQuery[Things]

    def main(args: Array[String]) {

        val db = Database.forConfig("h2mem1")

        try {

            // Create schema
            Await.result(db.run(things.schema.create), Duration.Inf)

            // Insert some things for testing
            Await.result(db.run(DBIO.seq(
                things += Thing("id4", 111, 111),
                things += Thing("id5", 222, 222),
                things += Thing("id6", 333, 333)
            )), Duration.Inf)

            // List of things to update
            val list = Seq(Thing("id1", 111, 112), Thing("id2", 222, 223), Thing("id3", 333, 334))

            // ----- The part you care about is here -----
            // Create a list of Actions to update
            val actions = DBIO.sequence(list.map(current => {

                // Whatever it is you want to do here
                things.filter(_.col1 === current.col1).update(current)
            }))

            // Run the actions
            Await.result(db.run(actions), Duration.Inf).value

            // Print out the results
            val results = Await.result(db.run(things.result), Duration.Inf)
            println(results)

        }
        finally db.close
    }
}

The output has the updated col2 values:
Vector(Thing(id1,111,112), Thing(id2,222,223), Thing(id3,333,334))

Comment: Thanks. Can a `DBIO.sequence` action be part of a transaction (i.e. using `transactionally`) ?
Comment: Yes - it's normal `DBIO`. So you can e.g. do `Await.result(db.run(actions.transactionally), Duration.Inf).value`


Meteor MongoDB - Getting the next element from a multi sorted cursor

Question: I created method to get an upcoming game from a collection of games. I include the current game id as an argument. The cursor is sorted by most 'hype points'(int) first, then from oldest to newest date.
<code>getUpcomingGame: function(current_game_id, skip) {
  var current_game_hype = Games.findOne({_id: current_game_id}).hype;

  var upcoming_game = Games.find({hype: {$lte: current_game_hype}}, {sort: {hype: -1, submitted: 1}, limit: 10}).fetch()[skip + 1];
  // skip: 0) get the next game, skip: 1) get the next-next game and so on..

  return upcoming_game._id;
}
</code>
To get the next closest game, I could do: Meteor.call('getUpcomingGame', current_game_id, 0). The problem comes when the current game has the same 'hype points' as the previous game. If I use $lte, it could show me the current game (as the next game). On the other side, if I use $lt it bypasses the games with the same hype points but with a newest date.
Is there any way I could say, get the index of the current game within the cursor and return the next document. For this I would need to access to this cursor's indexing and I don't know if it's possible.
Answer: I think cursor.forEach does what you need.
http://docs.meteor.com/#foreach
Answer: You could try iterating through the games array and removing any that match the current game.
Untested code:
<code>//...

var upcoming_games = Games.find({hype: {$lte: current_game_hype}}, {sort: {hype: -1, submitted: 1}, limit: 10}).fetch();

var upcoming_games_modified = upcoming_games;

upcoming_games.forEach(function(game, index) {
    if(game._id === current_game_id)
        upcoming_games = upcoming_games_modified.splice(index);
});

return upcoming_games[skip + 1]._id;
</code>


Module Questions

Question: Yesterday I had my question closed and while I do understand that questions about modules are not allowed  I do NOT understand why questions about modules specifically Fooman Modules have been allowed in the past.
There is even a fooman-extension tag so:
Please explain OR mods get on the same page because I find it hypocritical that there are other questions that were not closed
Either close them all, delete the tag  or allow them, make up your minds because it's not clear!
Comment: Who are you yelling at? We are people here trying to build a stronger platform, not a bunch of hippies trying to scam someone allowing some questions and closing others.
Comment: I'm looking for consistency. Click on the links and tell me that they are consistent.
Comment: Can you point me on the rule where said that module questions are not allowed?
Comment: It's lightly touched upon in the Help Center and I believe there is an option when flagging posts which would consider module questions "off topic" because it is not specifically about magento.
Comment: @sr_magento, do you think the questions are related: http://meta.magento.stackexchange.com/a/259/12293
Comment: @mbalparda I don't think you know what a "hippie" is.
Answer: If you take a look at other questions about Fooman Modules, you will see that most of them are answered by Fooman himself.
If there are unanswered questions, I guess he did not see them, or for some reason did not want to answer them.
These should be also closed in my opinion.
Comment: Thanks Marius, but in my case the question was closed quickly and Fooman was not given the opportunity to respond in a timely manner.  He did respond the next day but in a comment.
Comment: @sr_magento. There...I voted to reopen it and asked fooman to write his comment as an answer. all good now?
Comment: Yes - I ultimately got my answer from the post, I do believe that others would benefit from it otherwise I would have resolved the issue on my own without posting it here. Anyway, thank you Marius :)

Module Questions


Update table based on value inside this table

Question: I'm trying to update a tablecolumn based on another value inside this table but I keep getting an error.
My query is as follows:
    UPDATE partcreditor
    SET partcreditor.creditorid = creditor.creditorid
    FROM partcreditor
    INNER JOIN creditor ON partcreditor.creditornr = creditor.creditornr
    WHERE creditor.relgroupid = 1
    AND creditor.creditortypeid = 1

Comment: Could you at least past the whole error message?
Comment: Remove FROM clause and move JOIN closer to UPDATE. Look here: http://stackoverflow.com/a/15209489/4099089
Answer: UPDATE partcreditor AS PC
INNER JOIN creditor AS CR ON PC.creditornr = CR.creditornr
SET PC.creditorid = CR.creditorid
WHERE CR.relgroupid = 1 AND CR.creditortypeid = 1

No need to use the FROM clause in the update. As well as use alias name for better readability.


Sending data to a controller with AJAX POST

Question: I am using AJAX to send request to controller, but the data is sent with the GET method. I want the request send with the POST method.
The following is the code I used.
var table_url = '/table-data'+params;
var elementSettings = {};
elementSettings.url = table_url;
elementSettings.progress = {
  type: 'throbber'
};
Drupal.ajax(elementSettings).execute();

Comment: The [default appears to be POST](https://i.imgur.com/SlrZaMs.png) you sure its using GET?
Comment: @NoSssweat is right, POST is default. asdsadsaadasdsa, are you aware that POST requests can also send GET parameters?
Comment: Did you try to send the params via elementSettings.submit?
Comment: @NoSssweat Yes I am sure Its using GET
Comment: @4k4 No I am not aware about this. When I send a request with which contain around 1700 values like var param =&agr="ayx abc anc | anchd hdbdbc hdhd | cbcbc ccc cccc ccc cc cc cbcccnc| value 4....  | value 1700"  and i am getting an error i.e Error: URI Too Long
Comment: OK, this is then as I had suspected in my first comment. Add the parameters to `elementSettings.submit` and not to the URL. This will then be transferred to the `data` parameter of the lower level $.ajax you see in @NoSssweat answer.
Comment: @4k4 could you please look on the screenshot - https://prnt.sc/up7bgr. Request Url showing  all send parameter's value even showing Request Method : POST
Comment: Yes, the screenshot confirms what I've tried to clarify. I'm not sure what is still unclear to you?
Comment: Yes got is : elementSettings.url = table_url;
elementSettings.progress = {
  type: 'throbber'
};
Drupal.ajax(elementSettings).execute(); Drupal consider this as a url rather a var param is a paramter. Is there any way that I can pass var param as paramter?
Answer: If you want to send POST parameters add them to elementSettings.submit:
elementSettings.submit = {
  foo: 'bar'
};

and remove the GET parameters from elementSettings.url.
Answer: You could always non-Drupaly do it like this
$("#some-id").click(function(){
  $.ajax({
    type: 'POST',
    url: '/table-data'+params',
    data: JSON.stringify ({username: 'No Sssweat'}),
    contentType: "application/json",
    dataType: 'json',
    beforeSend: function(){
      $(this).prepend('

');
    },
    success: function(data) {
      alert(data);
    },
    complete: function(){
     $('.ajax-progress-throbber').remove();
    }
  });
});

Comment: I want to use  drupal ajax function because pagination seem running with drupal ajax


Como funciona o método get()?

Question: Queria entender o método get(), como ele funciona e pra que está servindo nesse código (de preferencia queria uma explicação de forma imaginária sem nomes técnicos).
package exemplo_oo;

public class Game {

    private Player player;
    private Inimigo inimigo;

    public Game() {
        player = new Player();
        inimigo = new Inimigo();
    }

    public Player getPlayer() {
        return player;
    }

    public Inimigo getInimigo() {
        return inimigo;
    }

    public static void main(String[] args) {
        Game game = new Game();
        Player player = game.getPlayer();
        player.atacarInimigo(game.getInimigo());
        System.out.println(game.getInimigo().life);
    }

}

package exemplo_oo;

public class Player {
    private int life = 100;

    public void atacarInimigo(Inimigo inimigo) {
        inimigo.life--;
    }
}

    package exemplo_oo;

public class Inimigo {
    public int life = 5;
}

Answer: Um método get() usualmente tem como objetivo obter um valor, um objeto ou até uma classe.
Depois dê uma olhada em polimorfismo e encapsulamento.
Tentando deixar de forma clara, a partir do seu exemplo:
O método getPlayer() te retorna um objeto do tipo Player, por isso a sua variável player pode ser atribuída a esse método get. Ou seja, ele pega um objeto do tipo Player que pertence a classe Game e atribui em sua váriavel player.
Para tentar deixar um pouco mais claro:
Usando o exemplo to método getInimigo():
Como dito, o método vai retornar um objeto do tipo Inimigo, e isso quer dizer que você pode ter acesso a métodos e variáveis públicas dessa classe Inimigos, por isso ele consegue acessar a variável life definida na classe Inimigos.
Ou seja, ao chamar um método get(), usualmente você vai obter algo de retorno, do tipo definido.
Answer: Complementando a resposta do Higor: métodos get (assim como métodos set) também é  uma convenção. Nada impede que você use retornarInimigo em vez de getInimigo. Mas como toda convenção, está ali para te ajudar. IDEs implementam facilitadores de geração de código para vocẽ e há até mesmo uma biblioteca (https://projectlombok.org/) que fornece anotações que geram os getters e setters em tempo de compilação.
No caso de componentes JavaBeans não é apenas uma convenção mas um dos 3 itens a serem implementados (os outros dois são ter um construtor sem argumentos e implementar java.io.Serializable).

Como funciona o método get()?


Unable to transfer php logic from node--post-esl-material.tpl.php to template.php

Question: If I use the following code in template.php and print $link in node--post-esl-material.tpl.php, everything works fine; I get "hey baby."
function eslmooc_preprocess_node(&$vars, $hook) {
   if ($vars['type'] == 'post_esl_material'){
      $vars['link'] ='hey baby';
   }
}

However, if I use the following code and print $link in node--post-esl-material.tpl.php, it doesn't print anything.
function eslmooc_preprocess_node(&$vars, $hook) {
   if ($vars['type'] == 'post_esl_material'){
      $xyz = '';
      if (empty($content['field_link']))
         $xyz .= '';
      else {
         $xyz .= '
';
          $xyz .= '
LINK
';
           $xyz .= '
';
            $xyz .= $content['field_link'];
           $xyz .= '
';
         $xyz .= '
';
      }
      $vars['link'] = $xyz;
   }
}

I cannot get the PHP logic to work. Can anyone see a mistake within the code?
Comment: If that condition returns true, then it will be empty. Just check that.
Answer: I think that the problem is that $content is not defined there. You have it only inside the template file but not in the preprocess hook.
Answer: The following code works:
function eslmooc_preprocess_node(&$vars, $hook) {
   if ($vars['type'] == 'post_esl_material'){
      $xyz = '';
      $node = $vars['node'];
      $field_link = field_view_field('node', $node, 'field_link');

      if (empty($field_link))
         $xyz .= '';
      else {
     $xyz .= '
';
       $xyz .= '
LINK
';
         $xyz .= '
';
           $xyz .= drupal_render($field_link);
         $xyz .= '
';
     $xyz .= '
';
      }

      $vars['link'] = $xyz;
   }
}

Comment: field_view_value() can be used to get only the value.


Information about the roots of a polynomial without their calculation

Question: Suppose I have a polynomial (of any order) and I'm not able to calculate the roots. Is there a way to get at least some information about the roots such as how many of them are complex, negative or positive? For example, I can safely identify the behavior (and therefore roots' character) of $f(x)=ax+b$ or even a quadratic expression just by inspection.
I'm aware of Descartes' sign rule http://en.wikipedia.org/wiki/Descartes%27_rule_of_signs  but it apparently provides only an upper bound on the number of positive/negative roots. Is there something more general giving an exact number (of positive roots) preferably without using the methods of calculus?
Comment: You can use [Sturm's theorem](http://en.wikipedia.org/wiki/Sturm%27s_theorem) to compute the number of distinct real roots located in an interval or the total number of real roots.
Comment: http://mathworld.wolfram.com/PolynomialRoots.html
Comment: @achille hui: Thx, that is something I was looking for. I said no calculus but this calculus is likely doable in my case.
Comment: @ darya khosrotash: Nice page but how does it help to answer my question beyond what I already wrote?
Answer: A couple of ideas:
1)Rational roots theorem
Given $p(x):=a_nx^n+a_{n-1}x^{n-1}+...+a_1x+a_0$ with all $a_i$ integer and $a_0, a_n \neq 0$ and $r=c/d$ a root, then :
i)$c|a_0$ and
ii) $d|a_n$,
where $x|y$ means " x divides y" , i.e., $y=cx$ for some integer $c$.
http://en.wikipedia.org/wiki/Rational_root_theorem,
2) An odd-degree polynomial has at least one Real root. When your polynomial has
integer coefficients:
Because if $z=a+ib$ is a root of $p(x)$, so is its conjugate $w=a-ib$, so Complex roots come in pairs, so an odd-degree polynomial must have at least one Real root.
Comment: 2) I would need to know the existence of complex roots to appreciate this. 1) What about non-rational roots?
Comment: @user155002: Sorry to get back to you so late; let me think it through some more.
Answer: If $P=\sum_{k=0}^n a_kX^k$, then the roots of $P$ are bounded by $\displaystyle \max\{1,\sum_{k=0}^{n-1}\left|\frac{a_k}{a_n}\right|\}$
Note that the proof adapts to complex polynomials as well.

Suppose $P=\sum_{k=0}^n a_kX^k$ has complex roots $\alpha_1,\ldots,\alpha_n$.
Let $i\in \{1,\ldots,n\}$
$\displaystyle P(\alpha_i)=0=\sum_{k=0}^n a_k\alpha_i^k$
Two cases come up:

$|\alpha_i|\leq 1$
$|\alpha_i|> 1$

In this last case, write $\displaystyle |\alpha_i|=|\sum_{k=0}^{n-1}\frac{a_k}{a_n}\alpha_i^{k-n+1}|\leq \sum_{k=0}^{n-1}\left|\frac{a_k}{a_n}\alpha_i^{k-n+1}\right|$
By assumption, $\forall k\in\{0,\ldots,n-1\},|\alpha_i^{k-n+1}|\leq 1$
Hence $\displaystyle |\alpha_i|\leq \sum_{k=0}^{n-1}\left|\frac{a_k}{a_n}\right|$

Therefore, if $P=\sum_{k=0}^n a_kX^k$, then the roots of $P$ are bounded by $\displaystyle \max\{1,\sum_{k=0}^{n-1}\left|\frac{a_k}{a_n}\right|\}$
Comment: Nice, I also dicovered this page summarizing some other bounds: http://en.wikipedia.org/wiki/Properties_of_polynomial_roots
Comment: @user155002 Props to Lagrange :)


Slideshow caption when logged in displays in different location when logged out

Question: I've got a slideshow displaying on the homepage, and at the bottom of the images, I've got captions. I am using:
.views-field-body { margin-top: 250px; }

To position the caption, but the position is not consistent when logged in and out. For example, the code above displays the caption in the correct location when logged out, but when logged in, the caption is pushed further down.
What is the correct way to position the caption?
Answer: You are checking your CSS by log in as an administrator. Try those of you who have Google chrome installed.

Go to Option
Open a new incognito window (or shortcut Ctrl+Shift+N)

and check your css there when you logged in as an administrator. The extra space your slogan is getting is due to the edit this link and all other links which are for administrator use only.For a normal user these links are not available (which is the case when you logged out) so it works fine.
Answer: First of all, this problem is not just for admin, its for all users with access to administer views.
Since the user have access to administer views, Drupal views adds some additional classes to provide contextual-links and wrappers for easy edit of that particular view.
I think, you must have used position attribute somewhere in your css for that particular field or the container holding that div you mentioned, which gets contradicted to the attributes provided by contextual wrapper classes.
See if you really need that attribute, or write one more css property for admin too.


OnlinePlayer Location Loop

Question: I have a method that creates a wall and uses the parameter Location l. This is triggered when a snowball hits a block or person and creates the wall along the X or Z axes. My problem is that if I use Location l, I can't use Player p to get which direction the player is facing and rotate the wall along the X and Z axes accordingly. If I use Player p, I can't find the Location of the block hit by the snowball. So to solve my dilemma, I used Location l and for when Player p was needed I looped through all online player locations and find a player who was at Location l and then casted it to Player p.
My Code:
public static void wall(Location l){
        Player p = null;
        for(Player players: Bukkit.getOnlinePlayers()){
            if (players.getLocation().equals(l)){
                p = players;
            }
            else{
                return;
            }
        }

My Questions:
Is this a valid solution to the issue? Was it valid but did I do it incorrectly? Is there a better way to solve the problem?
Thanks in advance!
Answer: One solution could be extending Location to keep track of the player(s) that are at that location.
public static void wall(Location l) {
    List<Player> pList = l.getPlayers();
    for(Player p : pList) {
        //do Something
    }
}

Since you're already storing Location in Player, you can update the values whenever the player moves to a new location.
Another solution would be to maintain a Map of Locations and Players
Map <Location, Set<Player>> locationPlayerMap //or
Map <Player, Location> playerLocationMap

Determining which solution is the best really comes down to factors like:
 "How Many Players are going to be on a Server", "How many Locations are there", "Are Multiple Players Allowed at a single Location", etc...
EDIT:
You can also structure your method like the following:
public static void wall(Object o) {
    if(o instanceof Player) {
        //Snowball hit a player, use the direction they are facing and location
    } else if(o instanceof Location) {
        //Showball hit a Location, use some other factor.
    }
}

Comment: I'm just trying to use the location to get a player, I don't really need everyone's locations
Comment: I would store a List in Location then to represent the Player or Players that are in a single location. Whenever a player moves to a new location, you will have to do something like oldLocation.removePlayer(player) newLocation.addPlayer(player). Then you can use Location.getPlayers() to return a List of Players at the location where the snowball hits.
Comment: I doesn't matter when they move, I just need to confirm that they are at location l when they are hit by the snowball
Comment: I updated my answer to include another alternative option of passing in the snowball's target as a generic object and checking the type.
Comment: That's actually a really good idea, but I'm trying to keep my code short, not have multiple methods, I also wanted to know if the code I had would work. If it doesn't, I'll have to do something along the lines of what you suggested
Comment: I would say your current solution would not work reliably for three reasons: 1) if there are a lot of players, the performance would suffer greatly. 2) The idea of multiple players being at the same location means you have to iterate through the entire list of players every time. 3) You have no idea if the snowball actually hit a player or just the block they were standing on.
Comment: the player limit is 25 and there are usually 10-15 people on so i don't think players would be a limit and as long as I have 1 player it should still work fine so would my code still work?
Comment: If the snowball doesn't hit the player but hits the block they were standing on, your code will still use the player. As long as you are ok with that then your code will work.

OnlinePlayer Location Loop


Show multiple term references as ID in one row

Question: I've got a view of nodes, displayed as fields. As each node may have references to multiple terms/tags, I would like to show all these tags.
When I use field "term_node_tid", then I get the multiple values properly displayed in one row separated by commas. But instead of the readable term, I need the term-IDs.
So I set up another field using "tid", but now only the ID of the first term is shown. There's no multiple value field setting, where I could tweak things. Any help much appreciated.
Comment: Perhaps using [template_preprocess_views_view_fields(&$variables)](https://api.drupal.org/api/drupal/core!modules!views!views.theme.inc/function/template_preprocess_views_view_fields/8.2.x) you might be able to get a hold of all those id's
Answer: Change field Formatter
If you're showing the actual Content field you can change the Formatter. Instead of using Label use Entity ID under Formatter.
This will output Term IDs instead of term names, and all the Multi-valued settings will apply the same way as for the names output.
Rewrite results with TID replacement token
Another way or changing the field output in D8 views (if the Formatter option isn't available for example) is to use the Rewrite results > Override the output of this field with custom text and enter the token for the TID in there. You can look up the correct token pattern under Replacement patterns below the Text area.
That is also how you would get the TID to display instead of the name if you use the field Content: All taxonomy terms.
Comment: neither the formatter option is available, nor rewriting like {{ tid }} reveals all values … I can't believe this standard task isn't a no-brainer. Maybe I am missing something?
Comment: Can you post more information and screesnhots about your configuration? For example the field settings for `term_node_tid`, multivalue and rewrite results?
Comment: It is unbelievable: in order to make screenshots I built the view from scratch and the options for multi-value fields and ID-formatter just appeared. Realy don't know what happened before.
Comment: It's a well-known issue in programming that sometimes software starts behaving erratically with no reason :) Or maybe it's a case of "It's harder to read code than to write it". Do you still have the original views? You can compare it to the new one and find out where the "ghost" is.
Comment: unfortunately, I deleted the old view…


Globally Lipschitz if and only if derivative is bounded?

Question: If I have a function $f:\mathbb R\to\mathbb R^n$ I can say that it is globally Lipschitz in $t$ if its Jacobian is bounded in $t$.
However, does it work the other way around? If I find that the function Jacobian is not bounded, does this mean that the function is not globally Lipschitz?
Comment: Yes, but that works only if $f$ is differentiable, while being Lipschitz or not is well defined for any function.
Comment: @DanielRobert-Nicoud Could you explain what you mean by this please? Thanks!
Comment: You already know the answer for $n=1$.   Such functions are differentiable almost everywhere (not everywhere) and, even if they have a bounded derivative almost everywhere that wouldn't imply a Lipschitz condition.  Why would things get better for any other $n$?
Comment: Well, the notion of "Jacobian" is not defined for non-differentiable functions...
Answer: A function with unbounded derivative is not Lipschitz. Indeed, if $f'$ is unbounded, then for every $M$ there is $x$ such that $\|f'(x)\|>M$. By the definition of derivative (used with $\epsilon = \|f'(x)\|-M$, there is $h\ne 0$ such that
$$\left\|\frac{f(x+h)-f(x)}{h}\right\|>M $$
The inequality $\|f(x+h)-f(x)\|>M|h|$ shows that $f$ is not  Lipschitz with constant $M$. And since $M$ is arbitrary, it's not Lipschitz.
Comment: Perfect, thanks for this :)


Weak convergence of sequence of polynomials.

Question: A sequence $(x_n)$ in a normed linear space $X$ is said to converge weakly to $x$ if
$$ \lim _{n\rightarrow\infty} \ell(x_n) = \ell(x)$$
Consider the sequence $(f_n) \in C([0,1])$ defined by $$f_n(t) = t^n.$$
Does this sequence converge weakly? Does it have weakly convergent subsequences?
I don't really see the sequences here, do we get one different sequence depending on what $t$ is? $ \lim _{n\rightarrow\infty} \ell f_n(t) = 0, $ for $t \neq 1$. So it seems that f would converge to something not continuous?
Comment: You did not correctly state what weak convergence means.  What is $\ell$?
Answer: Consider evaluation functionals
$$
\mathrm{ev}_t:C([0,1])\to\mathbb{C}:f\mapsto f(t)
$$
Assume $(f_n)$ weakly converges to $f\in C([0,1])$, then
$$
f(t)=\lim\limits_{n\to\infty}\mathrm{ev}_t(f_n)=\lim\limits_{n\to\infty}f_n(t)=
\begin{cases}
0\quad\mbox{ if }\quad t\neq 1\\
1\quad\mbox{ if }\quad t= 1
\end{cases}
$$
Thus $f$ is discontinuous at $1$. Contradiction, so there is no weak limit for $(f_n)$. The same argument shows that $(f_n)$ have no weakly convergent subsequence.
Comment: I'm a bit confused, for any $x \in [0,1]$ don't you have a functional $\ell_x$ given by $\ell_x(f)=f(x)$. Which would mean that weak convergence implies point-wise convergence. The sequence converges pointwise to $\chi_{\{1\}}$, so I don't see how it could have a weak limit.
Comment: @JacobSchlather, thanks your idea is much simpler
Comment: @DamianSobota thank you!


IIS Won't authenticate domain user: 401.2

Question: I'm having a lot of trouble with configuring authentication for IIS correctly.  I have a SharePoint site running under IIS 6.0, and the IIS web site is configured for Integrated Windows Authentication.  The web server is on a domain called STAGING, and most of my users are an another domain, called CORP.  The CORP users have STAGING domain accounts, and are able to log into the SharePoint site across the domains (e.g., the users are logged into their CORP workstations and are able to log in to the site).  However, STAGING domain users are unable to log in from within the STAGING domain.  My understanding was that STAGING domain users should be able to access the site without being prompted for credentials, but this isn't the case.  Even so, once the credentials are entered, the result is always a 401.
I looked at the HTTP session in Fiddler, and it appears that the server simple isn't accepting the negotiated credentials sent by the client browser.  Here's an abbreviated record:
HTTP GET  server /sites/mysite with headers: { }
    --> 401.2, with headers: { WWW-Authenticate: Negotiate, WWW-Authenticate: NTLM }
HTTP GET  server /sites/mysite with headers: { Authorization: Negotiate <digest1> }
    --> 401.1, with headers: { WWW-Authenticate: Negotiate <digest2> }
HTTP GET  server /sites/mysite with headers: { Authorization: Negotiate <digest3> }
    --> 401.1, with headers: { WWW-Authenticate: Negotiate <digest4> }

The GET/401.1 cycle repeats 3 times before the browser finally gives up.
I would expect that if I had everything configured correctly, the in-domain client would just pass the credentials and life would be good, but that's not what's happening, and life isn't good :-(
Anyone have any suggestions?
Comment: Are Staging users using IE? Is the site in the Local Intranet-zone and is the integrated Windows Authentication enabled in their browsers?
Comment: Yes.  I've checked those issues.  Turned out to be a kerberos vs. ntlm configuration issue in SharePoint.
Answer: 401.2 typically means that IIS isn't supporting the type of authentication that you are trying to use. Are you sure Windows Integrated Auth is enabled?
Check out the IIS settings on your STAGING machines - the User Authentication/Logon setting in Security setttings (for the zone your SharePoint site is in...) should be set to "automatic logon with current user name and password" - or, if you SharePoint site is in the intranet zone you could use "automatic logon only in intranet zone"
Check out AuthDiag - it is built to help diagnose authentication errors.
Comment: I tried to use AuthDiag, actually.  It always failed, saying "the url is invalid" or some such.  I gave up on that.
Comment: Ok.  It turned out that the Windows auth provider in the sharepoint site was configured to use Kerberos, instead of NTLM.  Once I switched it to NTLM, that fixed my problem.  I'm sure my site wasn't configured correctly for Kerberos, so it all makes sense now.


"Unsupported type 'PreferenceActivity' in file" Android

Question: I'm still new in Android programming, and I just can't solve this problem.
I'm creating a Preference Screen, but at the moment I run the application, I get the following error:
Error:Execution failed for task ':app:mergeDebugResources'.
> Unsupported type 'PreferenceScreen' in file C:\Users\Fidel Sebastián\AndroidStudioProjects\Asteroides\app\src\main\res\values\preferencias.xml

This is the XML file:
    <?xml version="1.0" encoding="utf-8"?>
<resources>
    <PreferenceScreen
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:key="preferencias_principal" >
        <CheckBoxPreference
            android:key="music"
            android:title="Start music"
            android:summary="Select for background music"/>
        <ListPreference
            android:key="graphics"
            android:title="Graphics type"
            android:summary="Choose your graphics type"
            android:entries="@array/graphicstype"
            android:entryValues="@array/graphicsTypeValues"
            android:defaultValue="1"/>
        <EditTextPreference
            android:key="fragments"
            android:title="Number of fragments"
            android:summary="Select for meteor fragments"
            android:defaultValue="3"/>
    </PreferenceScreen>
</resources>

This is the Java file:
package com.example.fidelsebastin.asteroides;

import android.os.Bundle;
import android.preference.PreferenceFragment;

public class Preferences extends PreferenceFragment {
    @Override
   public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.arrays);
    }
}

I've searched all over the Web, but I still can't find the answer. Any help would be really appreciated. Thanks in advance.
Answer: Get rid of the <resource> tags. A PreferenceScreen is not a resource. It should be defined as the top-level object in the XML, as shown in the documentation example:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:key="preferencias_principal" >
    <CheckBoxPreference
        android:key="music"
        android:title="Start music"
        android:summary="Select for background music"/>
    <ListPreference
        android:key="graphics"
        android:title="Graphics type"
        android:summary="Choose your graphics type"
        android:entries="@array/graphicstype"
        android:entryValues="@array/graphicsTypeValues"
        android:defaultValue="1"/>
    <EditTextPreference
        android:key="fragments"
        android:title="Number of fragments"
        android:summary="Select for meteor fragments"
        android:defaultValue="3"/>
</PreferenceScreen>

Additionally:

You need to move the preferences file into res/xml instead of res/values
You should pass the identifier for the preferences file into addPreferencesFromResource(), not R.xml.arrays:
public class Preferences extends PreferenceFragment {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferencias);
    }
}

Comment: Thanks, but now I have another error: "Element PreferenceScreen must be declared". What does that mean?
Comment: Move your preferences file out of `res/values` and into a `res/xml` folder. You also need to pass the right file into `addPreferencesFromResource()`, @MexicanGuy
Comment: Many, many thanks man! I'm very grateful for you help. I just can't thank you enough! I know I'm going a little off-topic here, but final question: do you have any knowledge of a good YouTube channel that teaches Android programming? I'm more of the visual kind when it comes to learning. Again, thanks!
Comment: To be honest, I do not, @MexicanGuy. I've mostly used online texts and code samples from android.com. [CommonsWare](https://commonsware.com/) books are good resources (but not video-based). I've also heard generally good things about some of the University of Maryland's [Coursera classes](https://www.coursera.org/course/androidpart1), but haven't taken them myself.
Comment: Oh I see, no problem-o. I'll check both the books and the classes later. Again, many thanks eldarerathis, and goodbye!