On subspace verification

Question: I am struggling with the following Problem:
\begin{align}Y= \lbrace (x^4-y^4,0,0,0) \mid x,y \in \mathbb{R} \rbrace \subset \mathbb{R}^4 \end{align}
Question, is the given Set a subspace of $\mathbb{R}^4 ?$
(Answer given by my tutor: Yes)
I thought about it as follows \begin{align}(x^4-y^4,0,0,0)=\underbrace{(x^4,0,0,0)}_{:=u}+\underbrace{(-y^4,0,0,0)}_{:=v} \end{align}
I defined two new vectors, because the notation $x,y$ is a bit confusing for me (usually the statements only depend on $x$). Then I could say that $u \in Y$ and $v \in Y$ and clearly, the sum would be in $Y$ too. Intuitive that seems fine to me, but I have the daunting feeling that I am being cyclic in this problem or make things too easy for myself.
However, if I continue on this way I would also need to verify that if $u \in Y$ then $\lambda u $ must be in $Y$ too. However, here I see the following the problem, if $u \in Y$ then when $\lambda$ is applied to this vector, this would scale the $x$-component and would contribute to make it not a subspace anymore.
I used WolframAlpha to visualize my idea:
http://www.wolframalpha.com/input/?i=%28x%5E4-y%5E4%2C0%2C0%29+ (before lambda)
http://www.wolframalpha.com/input/?i=%285x%5E4-y%5E4%2C0%2C0%29+ (after lambda being applied)
Comment: First show that $Y = \{(u,0,0,0) \mid u \in \mathbb{R}\}$.
Comment: Why scaling the $x$-component make it not a subspace anymore? Your graph look different only because you give a different scaling to $x$ and $y$, i.e. you are drawing the graph $(x, y, x^4 - y^4)$, which is a totally different question. You mentioned that usually it only depend on $x$, then why don't you simplify your subset $Y$?
Answer: This just has to do with the fact that $f\colon\mathbb{R}\rightarrow\left[0,\infty\right)$
with $f\left(a\right)=a^{4}$ is onto. Suppose $u,v\in Y$. Then
\begin{align*}
u+v & =\left(x_{u}^{4}-y_{u}^{4},0,0,0\right)+\left(x_{v}^{4}-y_{v}^{4},0,0,0\right)\\
 & =\left(\underbrace{\left(x_{u}^{4}+x_{v}^{4}\right)}_{r_{1}}-\underbrace{\left(y_{u}^{4}+y_{v}^{4}\right)}_{r_{2}},0,0,0\right)
\end{align*}
Since $r_{1},r_{2}\in\left[0,\infty\right)$, we can take $x=r_{1}^{1/4}$
and $y=r_{2}^{1/4}$ to get
$$
u+v=\left(x^{4}-y^{4},0,0,0\right)\in Y.
$$

On subspace verification


Transition probability between urn

Question:
$N$ black balls and $N$ white balls are placed in two urns so that
  each urn contains $N$ balls. At each step one ball is selected at
  random from each urn and the two balls interchange. The state of the
  system is the number of white balls in the first urn.

What I think
Let $X$ the number of white balls in the urn $(1)$ then we want $$P_{jk}=P(X_{n+1}=k|X_n=j)$$
then we have three possibilities for $k$ $$(i)\;k=j+1$$ $$(ii)\;k=j$$ $$(iii)\;k=j-1$$
First we know if $(1)$ have $j$ white balls then $(2)$ have $N-j$ white balls.
Let $A$ the event take a white ball in $(1)$ and $A'$ the event take black ball in $(1)$ then $$P(A)=\frac{j}{N}\space ,\space P(A')=\frac{N-j}{N}$$
analogous let $B$ the event take white ball in $(2)$ and $B'$ the event take a black ball in $(2)$ so $$P(B)=\frac{N-j}{N}\space,\space P(B')=\frac{j}{N}$$
Then we have for
$i)$ $$P(X_{n+1}=k|X_n=j)=P(A')*P(B)=\left(\frac{N-j}{N}\right)^2$$
$ii)$ $$P(X_{n+1}=k|X_n=j)=P(A)P(B)+P(A')P(B')=\left(\frac{j}{N}\right)\left(\frac{N-j}{N}\right)+\left(\frac{N-j}{N}\right)\left(\frac{j}{N}\right)=2\left(\frac{j}{N}\right)\left(\frac{N-j}{N}\right)$$
$iii)$ $$P(X_{n+1}=k|X_n=j)=P(A)P(B')=\frac{j}{N}\frac{j}{N}=\left(\frac{j}{N}\right)^2$$
Is that right? There is an easier way to do?
Comment: The transition matrix is in principle an $N+1$ by $N+1$ matrix.  It has in this case a relatively simple shape, it is a band matrix, with non-zero entries only on the main diagonal and the two "diagonals" just above and just below the main diagonal. There are as you knew three conditional probabilities to calculate,
Comment: It feels like some kind of Dirichlet distribution. It is basicly some kind of stochastic process. It reminds to me to something that asked [some time ago](http://math.stackexchange.com/questions/1275035/evolution-of-a-discrete-distribution-of-probability). Unfortunately I dont have the knowledge to ask your question but it seems very interesting.
Comment: Are you only looking for the transition probabilities?  Then in general outline the procedure is right. One can do it with fewer symbols.
Comment: @AndréNicolas If I were asked to write the matrix of transition, how could I do?In general I do not calculated the conditional, I just used the fact that $X_n=j$ and calculated intersections between two events, there is a direct way to calculate the conditional?
Answer: Yes, that is right. For the transition matrix $(p)_{i,j}$, note that it suffices to determine the entries $p_{ij}$. wich are:
$$P_{jk}=P(X_{n+1}=k|X_n=j) = \delta_{(j+1)k}\left(\frac{N-j}{N}\right)^2 + \delta_{j, k} 2\left(\frac{j}{N}\right)\left(\frac{N-j}{N}\right) + \delta_{(j-1),k} \left(\frac{j}{N}\right)^2$$
Comment: @What this $\delta$ mean?
Comment: $\delta_{xy}= \begin{cases}1 & x=y\\ 0 & x\neq y\end{cases}$
Comment: Isn't this what the question states?
Comment: @Did What you mean?
Comment: That the values of the transition probabilities $p_{ij}$ are already written down in the question.
Comment: @Did Yes, these are the values I've ever found. To be honest I did not understand very well how he wrote the matrix.
Comment: Here is a summary of this page at present: *Question: I need to compute A and I have found that A=42. Is that right? There is an easier way to do? Answer: A=42.* Not sure I see the point of it all.

Transition probability between urn


Delphi issues copying to Windows clipboard

Question: We currently have a couple of clients reporting that our copy-to-clipboard functionality in our Delphi XE2 Win32 app isn't working, and pasting into Excel afterwards results in the old clipboard content being pasted.
We are just copying CSV-like text using Clipboard.AsText, and added some debugging to ensure that we weren't getting silent crashes in the routines building up our CSV string. There's no exception handling around it, so any exceptions should just be displayed to the user (nothing reported).
Has anyone encountered anything like this before, and if so what are the best solutions for it? I notice that in C#-land, according to How to handle blocked Clipboard and other oddities the default behaviour there is to retry 10x with a 100ms delay. Unless that behaviour is written into the WinAPI the Delphi wrapper doesn't seem to do this?
I assume that this is a user-machine problem rather than something in our app, though they apparently don't experience this in other software. In-house we have one user that has the first Ctrl-C fail, but the second succeed (fairly reliably), though testing over 5 other machines didn't show anything.
Due to comments on missing code (I didn't put any originally, as there's nothing really there) - pseudocode implementation is
Data := BuildCSVString();
Clipboard.AsText := Data;
StatusBar.Caption := 'Data copied to clipboard';

So not much scope for failure.
Users see the StatusBar GUI update, so the Clipboard routine is running. Reports are that the clipboard remains unchanged, NOT that it is cleared, so the BuildCSVString routine isn't failing and returning '', either.
There's not much scope to build a reproducible bit of code here (otherwise I'd have probably fixed it by now), I was just wondering whether anyone else had come across this and the best way to solve it.
Comment: So what does `BuildCSVString();` look like?  How do you know it isn't rebuilding an old string?
Comment: Hard to debug without code.  That you have an in-house user with reported failures (needing to re-try) sounds like there is indeed an error in your code.  Are you sure the code is actually executing in all cases?  Maybe you're not catching the keyboard command because of a focus issue - how can we know?  Only you can debug your code.  I'd start with your reproducible in-house user's problem - set up a remote debug session and see what happens.
Comment: It iterates over a table and builds a CSV. It may as well be a string constant or returning a random set of characters for the sake of this question. I can guarantee that it's not the issue as it works on everyone else's machine, and it's not the sort of code that would work on one machine but not others
Answer: Rule out excel by having the user paste into Notepad immediately after Excel appears to fail.  This will tell you whether it's a problem with copying the data, or whether Excel is having trouble pasting the data.  Or, if there is a hybrid clipboard issue, where data appears on the clipboard in multiple formats, from different sources (can happen).
Comment: Also, since Windows Vista, if the Delphi app is running as administrator, the data put on the clipboard may not be accessible to applications not running with administrative privileges.
Comment: You can (and should) have multiple formats on the clipboard at the same time, so you could put both `CF_UNICODETEXT` and `CFSTR_CSV` on the clipboard at the same time, and let Excel (or any other spreadsheet app, for that matter) decide which format it wants to use. Excel also supports an XML Spreadsheet format.
Comment: The `TClipboard.AsText` setter should raise an exception if the data cannot be placed on the clipboard. That being said, note that `AsText` in D2009+ uses the `CF_UNICODETEXT` format for text data, but CSV data should use the `CFSTR_CSV` format instead (use `RegisterClipboardFormat('Csv')` to get the format ID at runtime). Also, Excel is a little particular about the encoding of CSV data. It should be in UTF-8 instead of UTF-16 (you will have to use `TClipboard.SetAsHandle()` for that), and Excel works better when tab is used for the cell separator and LF for the row separator.
Comment: @StijnSanders That's something I wasn't aware of. AFAIK there's no reason to run our app with Admin rights, but I've only inherited this codebase 2 weeks ago, so need to check up. I'll ask at tomorrows standup.
Comment: @StijnSanders If that was the problem then it would never work - it would not be intermittent, I should think.
Comment: @RemyLebeau Thanks - I've never really dealt with the clipboard formats before, so something I need to look into before committing. I think it may be a nicer solution for the user if it prevents them having to do the 'Text to columns' routine after pasting. Unsure whether it will fix the underlying issue of clipboard not being filled, but worth trying
Comment: Thinking about this further, the route I'd likely take is to just provide a tab-delimited form rather than a CSV and pass it as CF_UNICODETEXT, so it's not likely to solve the problem of the clipboard not getting filled. It is a suggestion that would improve the user-experience though, so I'll probably implement it. Confirmation that exceptions should be raised on a lock is useful though, although we're not seeing any.
Comment: Thanks for the tips, @RemyLebeau It was enough for my requirements to cast the string to `pAnsiChar`, and call via the hack: `TClipboardHack(Clipboard).SetBuffer(CF_CSV, p^, strlen(p));`
Comment: @bvj: You *should* be using the public `SetAsHandle()` method instead of the protected `SetBuffer()` method. `SetBuffer()` allocates an `HGLOBAL` handle via `GlobalAlloc()`, copies your input data into it, and then assigns that `HGLOBAL` to the clipboard the same way `SetAsHandle()` does. So you may as well use `SetAsHandle()` directly and not have to use a hack at all.


Não está passando valor variável JS para PHP via ajax

Question: JavaScript
<code>$('#save-update').data('eventId', info.event.id);

$('#delete-update').click(function (info) {
        info.preventDefault();
        let eventID = $('#save-update').data('eventId');
        $.ajax({
            type: 'POST',
            url: 'php/delete-events.php',
            data: eventID,
            contentType: false,
            processData: false,
            success: function(response) {
                location.reload();
            }
        })
    });
</code>
PHP
<code>$id = $_POST['eventID'];</code>
Não está chegando o valor do id para o arquivo PHP.
Notice: Undefined index: eventID
Answer: Você precisa enviar a variavel em um objeto JS
<code>$('#delete-update').click(function (info) {
        info.preventDefault();
        let eventID = $('#save-update').data('eventId');
        $.ajax({
            type: 'POST',
            url: 'php/delete-events.php',
            data: {eventID:eventID},       // Alterado aqui
            contentType: false,
            processData: false,
            success: function(response) {
                location.reload();
            }
        })
    });
</code>
Explicando
<code>           ⬐ ex. $_POST['eventID']
data: { eventID : eventID },
              Valor ⬏
</code>
Comment: Continua do mesmo jeito, o PHP n ta conseguindo pegar o valor. Ele esta fazendo a requisição e até dei um alert em eventID no JS e ta saindo o valor do id, porém n vai para o PHP.
Comment: remove a linha do "processData" e do "contentType"
Comment: Isso, deu certo. Muito obrigado!
Comment: feliz em te ajudar


Qual a diferença entre os diretórios assets, res e raw no Android?

Question: Gostaria de saber qual a diferença entre os diretórios /assets e /res presentes no android, sei que o layout e várias imagens ficam no diretório /res e são acessadas de diferentes modos.
Existe também o diretório /raw que está dentro do /res, sei que ele pode conter arquivos e que podem ser acessados como por exemplo .getIdentifier("arquivo","raw", getPackageName()); onde o arquivo é equivalente a res/raw/arquivo.json, ou seja, o raw pode conter os mesmos arquivos que o assets?
Qual a real diferença entre o raw, o assets e o res no Android, e como eu poderia usar cada um deles?
Answer: Antes de responder a diferença, uma breve explicação sobre os resources:
Alguns itens devem ser externalizados (imagens, strings) para mantê-los independentes e para eles poderem suportar configurações específicas (linguagem do device, tamanho da tela, orientação, etc.).  A pasta res, usa várias subpastas que juntam os resources por tipo e configuração.
Mark Vasconcelos, em seu artigo sobre Android – Estrutura e organização da aplicação, fez um "resumo" sobre a estruturação da aplicação:

As pastas criadas automaticamente no projeto que serão usadas pela
  aplicação são:

src: É onde fica o código fonte da nossa aplicação.
res: Pasta de resources da aplicação, aqui ficarão arquivos de layout, imagens, XML de configuração, XML com strings
  internacionalizáveis, raw files, sons, etc..

As pastas criados por default para resources são:

res/drawable-<screen cfg>: Deve se colocar as imagens, a divisão entre hdpi (High dpi), mdpi (Medium dpi), ldpi (Low dpi)  é
  para guardar as imagens em resoluções diferentes.
res/layout: Fica os arquivos XMLs que representam o layout das nossas Activities.
res/values: XMLs que guardam strings que podem ser usadas na aplicação.

Por default, um arquivo strings.xml é criado nessa pasta, os
  valores são guardados através de tags com a seguinte estrutura
  <string name="nomeString">Valor String</string>
Na pasta res é possível adicionar mais subpastas para
  representar mais resources para aplicação ou alternativas para os
  resources, como por exemplo uma pasta xml para guardar informações de configurações.

gen: pasta de fonte gerado

Essa pasta também guarda código fontes, mas ela só fica com uma única
  classe gerada automaticamente pelo plugin do eclipse chamada "R" no
  mesmo pacote que informamos em "package name" quando criamos nosso
  projeto. Essa classe R contém ids para todos os itens que temos na
  pasta res, e é através desses ids que podemos usar todos os
  resources facilmente na nossa aplicação.

assets: Arquivos raw - A diferença de colocar arquivos raw aqui do que em algo como res/raw é que resources são
  acessíveis por id através da classe R, arquivos nessa pasta podem
  ser abertos por stream dentro da aplicação como um byte array.

Ainda é possível adicionar mais pastas no projeto, para criar
  aplicações nativas é criado uma pasta chamada jni que guarda os
  códigos nativos e AndroidMakeFiles que o Android NDK (Native
  Development Kit) usa para criar a shared lib para aplicação, como
  Android é uma distro unix, a shared lib é um arquivo com extenção
  .so, os arquivos gerados pelo NDK ainda vai para outra pasta chamada libs, essa pasta contém as shared libs que podem ser usadas na
  aplicação em Runtime, que pode ser carregada com um
  System.loadLibrary("nomeLib").

Vale a pena ler essa resposta do stackoverflow em inglês.
Qual a real diferença entre o raw, o assets e o res no Android, e como eu poderia usar cada um deles?

res: Você deve sempre usar os arquivos e pastas de resource para armazenar valores da sua aplicação, além das imagens, é claro. Dessa forma você consegue manter e atualizar seu código muito mais facilmente, além de poder definir alternativas para cada um deles, de acordo com situações específicas, como diferentes idiomas, tamanhos e orientações de tela. A pasta res/ é a pasta do seu projeto que guarda todos os resources da sua aplicação
raw: Salvar arquivos ativos em vez de  salvar no assets/directory. A diferença está na maneira que você vai acessá-los. Esses arquivos são processados por aapt e deve ser referenciado a partir da aplicação que utiliza um identificador de recurso na classe R. Por exemplo, este é um bom lugar para a mídia, como MP3 ou Ogg.
assets: É mais como um sistema de arquivos e oferece mais liberdade para colocar qualquer arquivo. Em seguida, você pode acessar cada um dos arquivos nesse sistema. Este diretório é bom para coisas como detalhes do jogo, dicionários, ... etc.

Referência:

Projects Overview
Projeto Android
Fornecimento de recursos
Answer:
assets/

Você pode usar esta pasta para armazenar qualquer arquivo. Os arquivos que você salva aqui são compilados no .apk e o nome do arquivo original é preservado. Você pode navegar neste diretório da mesma forma que um sistema de arquivos típico usando URIs e ler arquivos como um fluxo de bytes usando um AssetManager. Vale lembrar que a classe R não gera IDs para os arquivos colocados nessa pasta, então ela é menos compatível com algumas classes e métodos do Android. Além disso, é muito mais lento acessar um arquivo armazenado nesta pasta, uma vez que você precisará obter um identificador para ele com base em um String.
Exemplo de uso: Armazenamento de texturas e dados de jogos, e bancos de dados sqlite .

res/

Contém todos os recursos que não são códigos (e.g. .java, .kt), como layouts XML, strings de UI e imagens de bitmap. Esta pasta é dividida em subdiretórios. Basicamente, essa pasta serve apenas como um agrupador de outras pastas com outros recursos, como as pastas animator, color, drawable, etc. Os arquivos contidos nas subpastas desta pasta são processados pelo aapt (Android Asset Packaging Tool), portanto os arquivos destas subpstas devem ser referenciados no aplicativo usando um resource ID da classe R.

raw/

Assim como a pasta assets/, esta pasta serve para armazenar qualquer arquivo. A diferença é que, como essa pasta é uma subpasta da pasta res/, os arquivos contidos nela são processados pelo aapt (Android Asset Packaging Tool), portanto eles devem ser referenciados no aplicativo usando um resource ID da classe R.
Exemplo de uso: Armazenar mídias, como arquivos MP3 ou Ogg.


Babel plugin error unknown node of type undefined with constructor "String"

Question: I am building a shared component library that will be used by both React and Vue.
I am using Styletron, which requires a framework-specific adapter, but otherwise works pretty much the same.
So from my source code (a bunch of functions) I need to generate a folder with the code transpiled as normal and then another folder where the functions are modified slightly.
This is my code:
const MyComponent = styled('div', ({ isActive, hasBorder}) => ({
  color: 'red'
}))

// should not change
const OtherComponent = styled('div', {
  background: 'blue'
})

And it should become:
const MyComponent = styled('div', ({ isActive, hasBorder}) => ({
  color: 'red'
}), ['isActive', 'hasBorder'])

const OtherComponent = styled('div', {
  background: 'blue'
})

I actually have a working example of this working in ASTExplorer, but when I try to make a plugin out of it, I encounter the error Babel plugin error unknown node of type undefined with constructor "String"
This is my first plugin, and I KNOW that I am doing some stuff wrong, but right now I just need to find out what I have to do to make this work outside of ASTExplorer.
This is the plugin I have written in ASTExplorer:
export default function(babel) {
  const { types: t } = babel;
  return {
    name: "ast-transform",
    visitor: {
      CallExpression: (path) => {
        if (
          path.node.callee.name === 'styled' &&
          path.node.arguments.length === 2 &&
          t.isArrowFunctionExpression(path.node.arguments[1])
        ) {
          if (t.isObjectPattern(path.node.arguments[1].params[0])) {
            const props = []
            path.node.arguments[1].params[0].properties.map(prop => props.push(prop.value.name))
            path.node.arguments.push(JSON.stringify(props)) // I suspect that the error is from here
          }
        }

      }
    }
  };
}

Answer: Babel transforms work with AST nodes, so stringifying the props and pushing them into the arguments list in this way won't work quite right. You'll want to actually create an AST structure from your object.
In this case, Babel offers a helper for this, so you can change
path.node.arguments.push(JSON.stringify(props))

to
path.node.arguments.push(t.valueToNode(props))


QuantStrat sigFormula

Question: I am having problem with regards to running sigFormula. I am getting the error:
Error in is.character(x) : 'x' is missing
Error in `colnames<-`(`*tmp*`, value = seq(ncol(tmp_val))) :
  attempt to set colnames on object with less than two dimensions

It seems to occur ether in applySignal or applyStrategy. What does it mean? Is there a bug inside sigFormula?
My code:
library(quantstrat)

#set currency
currency('USD')

#Get Data
initDate="2000-01-01"
endDate="2014-05-31"
symbols = c("SPY")
for(symbol in symbols){
    stock(symbol, currency="USD",multiplier=1) #financial instrument and
    getSymbols(symbols,from=initDate,to=endDate)
    assign(symbol, adjustOHLC(get(symbol),use.Adjusted=TRUE))
}

#Initialize Portfolio,Strategy,Orders,and Account
initEq=1000000
portfolio.st='db'
account.st='db'
initPortf(portfolio.st,symbols=symbols, initDate=initDate)
initAcct(account.st,portfolios=portfolio.st, initDate=initDate)
initOrders(portfolio=portfolio.st,initDate=initDate)
lookback = 50

strat<- strategy(portfolio.st)

ROC2 <- function(x, n = 50, ...)
{
    roc <- ROC(Cl(x), n)
    colnames(roc) <- NULL
    roc
}

TSI <- function(x, nShort = 10, nLong = 100)
{
    atr <- ATR(HLC(x), nShort)$atr
    absd <- abs(diff(Cl(x), nShort))
    ratio <- absd / atr
    tsi <- runMean(runMean(ratio, nShort), nLong)

    # SMA gives the same result as runMean
    #tsi <- SMA(SMA(ratio, nShort), nLong)
    # not needed, as runMean removes colname
    #colnames(tsi) <- NULL
    tsi
}

strat <- add.indicator(strategy=strat, name="SMA", arguments=list(x = quote(Cl(mktdata)), n=50), label="SMA50")
strat <- add.indicator(strategy=strat, name="ROC2", arguments=list(x = quote(Cl(mktdata)), n=150), label="ROC150")
strat <- add.indicator(strategy=strat, name="TSI", arguments=list(x = quote((mktdata)), nShort=10, nLong=100), label="TSI")
strat <- add.indicator(strategy=strat, name="RSI", arguments=list(price = quote(Cl(mktdata)), n=2), label="RSI")

# for debugging purposes
#strat.ind <- applyIndicators(strategy=strat, mktdata=get(symbol))
#tail(strat.ind)

# Cl > SMA(50)
strat <- add.signal(strat, name="sigComparison", arguments=list(columns=c("Close", "SMA50"), relationship="gt"), label="Cl.gt.SMA50")
# ROC(150) > 0
strat <- add.signal(strat, name="sigThreshold", arguments=list(column="ROC150", threshold=0), label="ROC150.gt.zero")
# LongCond: either Cl>SMA or ROC(150) == TRUE
strat <- add.signal(strat, name="sigFormula", arguments=list(columns=c("Cl.gt.SMA50", "ROC150.gt.zero"), formula="(Cl.gt.SMA50 == 1) | (ROC150.gt.zero == 1)", cross=FALSE), label="LongCond")
# Setup1 = LC and (TSI/RSI or TSI/RSI)
strat <- add.signal(strat, name="sigFormula",  arguments=list(columns=c("LongCond", "TSI", "RSI"), formula="(LongCond == 1) & (((TSI > 1.65) & (RSI < 18)) | ((TSI < 1.65) & (RSI < 8)))", cross=FALSE), label="Setup1")
# Setup2 = LC and (TSI/RSI or TSI/RSI)
strat <- add.signal(strat, name="sigFormula", arguments=list(columns=c("LongCond", "TSI", "RSI"), formula="(LongCond != 1) & (((TSI > 1.65) & (RSI < 13)) | ((TSI < 1.65) & (RSI < 2)))", cross=FALSE), label="Setup2")
# Entry = Setup1 or Setup2 == TRUE
strat <- add.signal(strat, name="sigFormula", arguments=list(columns=c("Setup1", "Setup2"), formula="((Setup1 == 1) | (Setup2 == 1))", cross=FALSE), label="EntryCond")
# Exit = TSI/RSI or TSI/RSI
strat <- add.signal(strat, name="sigFormula", arguments=list(columns=c("TSI", "RSI"), formula="(((TSI > 1.65) & (RSI > 61)) | ((TSI < 1.65) & (RSI > 39)))", cross=FALSE), label="ExitCond")

# For debugging purposes. For some reason this does not work, even though
# applyStrategy creates the columns properly?
#strat.sig <- applySignals(strategy=strat, mktdata=SPY, indicators=strat.ind)
#tail(strat.sig)

# entry rule
strat <- add.rule(strat, name="ruleSignal", arguments=list(sigcol="EntryCond", sigval=TRUE, orderqty=1000, ordertype="market", orderside="long", pricemethod="market"), type="enter")
# exit rule
# this generates a large number of orders into order book, which
# subsequently are rejected
strat <- add.rule(strat, name="ruleSignal", arguments=list(sigcol="ExitCond", sigval=TRUE, orderqty="all", ordertype="market", orderside="long", pricemethod="market", orderset="exit1"), type="exit")

out <- try(applyStrategy(strategy=strat, portfolios='db'))
updatePortf(Portfolio=strat.name, Dates=paste("::", as.Date(Sys.time()), sep=""))
chart.Posn(Portfolio = strat.name, Symbol=symbol)

Answer: Look at the mktdata object.  It doesn't have a TSI column, so your attempt to reference that column in sigFormula fails and the lexical scope search finds your TSI function instead.
R> colnames(mktdata)
 [1] "SPY.Open"     "SPY.High"     "SPY.Low"      "SPY.Close"    "SPY.Volume"
 [6] "SPY.Adjusted" "SMA.SMA50"    "X1.ROC150"    "X1.TSI"       "RSI"

The solution is to set the column names on the output of the TSI function in the function's definition:
TSI <- function(x, nShort = 10, nLong = 100)
{
    atr <- ATR(HLC(x), nShort)$atr
    absd <- abs(diff(Cl(x), nShort))
    ratio <- absd / atr
    tsi <- runMean(runMean(ratio, nShort), nLong)
    colnames(tsi) <- "TSI"
    tsi
}

Comment: I am still getting the same error, when I replace TSI function with the one you suggested which changes the `colnames`. I searched online about this problem: https://r-forge.r-project.org/tracker/?func=detail&atid=1271&aid=2680&group_id=316
Comment: this link suggested an alternative `sigFormula` function which solves my other system's codes same problem but it doesn't solve this one that I am having.
Comment: I'm not sure what to tell you. Your code runs for me when I use the latest quantstrat and TTR from R-Forge and make sure that the formula variables match the `mktdata` colnames.
Comment: I am using blotter version= `0.8.19`, quanstrat = '0.8.2', financial instrument = '1.1.9' with R version = `2.15.3`.
Comment: when you say formula variables should match the mktdata object, I find that whenever I run `applyIndicator`, the colnames of `mktdata` always concatenates extra symbols, in your above example `x1`; does that affect the problem?
Comment: Yes, that's exactly the problem. I'm not particularly fond of that behavior, but a better solution would be complicated and take much time to implement.  Also, you should upgrade your R installation if you can. Yours is 1.5 years old.
Comment: i mean that behavior seems to works and don't seem to cause problems in my implementations without the use of `sigFormula`. What is the complicated solution that you are talking about? I really want to get this working as its the only road block that I am having...thanks anyway.
Comment: If you don't use `sigFormula`, we use partial matching to lookup the column names. R's `formula` class does not use partial matching, so you have to make sure your variables match the column names exactly. The more complicated solution is to design, create, and test some new way to ensure the column names of the `mktdata` object have unique and friendly names.
Answer: define you own RSI
RSII <- function(price, n)
{
  rsi <- RSI(price=price, n=n)
  colnames(rsi) <- "RSII"
  rsi
}

replace all RSI with RSII in rest of your codes

QuantStrat sigFormula


Searching for n-th child in n-th parent

Question: There is a strange behaviour when it comes to finding elements by xpath. The situation:

...

Title 1

      ... other stuff

Title 2

      ... other stuff

...

I want to check the text of the H3 tag on the second ingredient-group. So I did the following in Selenium:
WebElement group2 = driver.findElement(By.xpath("//div[@class='ingredients-group'][2]"));
WebElement title2 = group2.findElement(By.xpath("//h3"));
String titleText = title2.GetText();

The last statement returns "Title 1". I would expect it to return "Title 2".
Strangely, this statement returns "Title 2":
String titleText = driver.findElement(By.xpath("//div[@class='ingredients-group'][2]//h3")).getText();

I would like to use the first option (group2.findElement), because there are several other elements in the containers I would like to refer to without having to write the full xpath.
Any ideas on this?
Thanks
Comment: The one you think is "strange" is returning exactly what it should.  You are going to the 2nd instance of @class='ingredients-group' and returning the title of the h3 tag associated with it, 'Title 2'.
Answer: Use findElements to return a list of webelements (h3 tags) and then access them as you would any other list:
WebElement groups = driver.findElements(By.xpath("//div[@class='ingredients-group'][2]"));
WebElement theH3Tag = groups[0].findElement(By.xpath(".//h3")); //make this a relative xpath
String titleText = theH3Tag.GetText();

WebElement the2ndH3Tag = groups[1].findElement(By.xpath(".//h3")); //make this a relative xpath
String titleText = the2ndH3Tag.GetText();

Or loop through the list:
    WebElement[] groups = driver.findElements(By.xpath("//div[@class='ingredients-group'][2]"));
    for (WebElement group : groups) {
        WebElement h3Tag = group.findElement(By.xpath(".//h3")); //make this a relative xpath
        String titleText = h3Tag.GetText();
    }

Comment: Switching to driver.findElements dod not help. But meanwhile I figured out the problem. The H3 tags are dynamic. They are not displayed at the time when Selenium is executing findElement or findElements using xpath. But when I try to find elements using By.id, it works properly. Selenium somehow doesn´t recognize hidden elements using xpath.
Comment: So you just need to add waitFor?
Comment: A tiny dot solves it all. I in findElement by XPath I was using "//h3" instead of ".//h3". In my case Selenium was searching for h3 in the whole DOM and found the first one instead of seraching inside the desired group element. Thank you all for your comments. The case is closed.

Searching for n-th child in n-th parent


Admob using AD_UNIT_ID

Question: I need to find my AD_UNIT_ID for the line:
<code>private static final String AD_UNIT_ID ="";
</code>
So can someone give me an example for an AD_UNIT_ID, i mean how it should look like?
So is it this one:
ca-app-pub-XXXXXXXXXXXXXXXX/yyyyyyyyyy
or only the yyyyyyyyyy?
Comment: No, that is your publisher ID, create an AD Unit and you'll see it.  All of mine have no hyphens in and certainly don't start with `pub-`
Comment: create an app in Admob dashboard. It will generate a unique id for your app. The app need not be a published one.
Comment: @LeeArmstrong So when im going to my banner I find this ,is it this one:
ca-app-pub-XXXXXXXXXXXXXXXX/yyyyyyyyyy
OR only the yyyyyyyyyy?
Comment: @intrepidkarthi Can you see edit plz? I want to test the ads and I don't know if my id is good .. I already created an app
Comment: first one is the adunit id
Answer: Ad Unit Id is a unique ID for each Admob users.
To find the ad unit ID, once you are logged in Admob, click the Monetize tab. Click All apps from the left-hand side and select an app. The ad unit ID is under the ad unit name.
If you dont have one, here is how to create an Ad Unit ID from scratch to end. Create an ad unit
Answer: I have just created an AD_UNIT_ID myself and its in the ca-app-pub-XXXXXXXXXXXXXXXX/NNNNNNNNNN format, ads are being properly displayed in the app.
U can see more clarification in Google Mobile Ads SDK FAQ

Admob using AD_UNIT_ID


Rules reaction: "After updating an existing user account" reacts on user login

Question: I have a rule that I use to create a group node for user when user gets a new role. A group node was created for the user when she got the new role but unfortunately a group keeps getting created for the user whenever she logs in. Not sure of what is going on. How do I fix this? Thanks!
Answer: What event are you using to trigger the node creation? It sounds like maybe there's a "User has logged in" event somewhere in the chain.
The Rules module can be flakey. (I love it but it drives me crazy sometimes.) If you can't figure it out, you could try to preempt the problem by adding a check to the event where you create the group node to see if a group node already exists before adding one.


Check for changes to a SQL Server database?

Question: is there a way to get database checksum using system SQL Server functions?
Or other way to quickly figure out if there are any changes in database?
I do not want to use any specific database analysis software for this.
I look for any changes in database (schema/object changes, data changes).
I use SQL Server 2008.
Comment: Are you talking schema/object changes or data changes, or both?
Comment: What version of Microsoft SQL Server?
Comment: Why dont you want to use any specific database analysis software?
Comment: I don't want to use analysis software because I will use this function from code
Answer: You might find the information in the transaction log...
Use
DBCC LOG(<database name>[,{0|1|2|3|4}])

0 - Basic Log Information (default)
1 - Lengthy Info
2 - Very Length Info
3 - Detailed
4 - Full
Example:
DBCC log (MY_DB, 4)

The result is somewhat cryptic and is better used with a third-party tool thought...
Credits: http://www.mssqlcity.com/Articles/KnowHow/ViewLog.htm
EDIT:
You might try
Select * from ::fn_dblog(null, null)

This page contains some usefull information about the results returned by the functions...
http://www.novicksoftware.com/udfofweek/Vol1/T-SQL-UDF-Volume-1-Number-27-fn_dblog.htm
Keep in mind, that those procedures are not for the public and therefore not easy to understand. The other possibility is to add triggers on all tables. But that is on the otherhand a lot of work.
Comment: And how can I analyze this result? It is not possible to calculate rows from DBCC log
Comment: Well the problem here is that you don't want to use third party tools and you were asking for system functions. That's it.
Comment: Yes, you are correct. That what I really want. It would be great if something like this for database would exist CHECKSUM_AGG http://stackoverflow.com/questions/36/check-for-changes-to-a-sql-table
Answer: One approach to record/log schema changes is to use DDL triggers as of SQL Server 2005.
You can set them up on a database to fire on specific types of schema changes (e.g. CREATE_PROCEDURE, ALTER_PROCEDURE) and then maintain whatever log you want to.
Answer: By "changes" I had a similar problem but not changes to the data, rather changes to the schema. I created the following function to generate a checksum of the whole database schema based on INFORMATION_SCHEMA. Expand to additional information schema tables if your system uses them, this is enough for my usage.
I've used this to create a daily alert to notify me of any changes to our production database, so it's become easy to police unplanned/unauthorised changes by other team members. Simply store the checksum, and then run the function and compare to the stored value. If different, then someone has changed something.
CREATE FUNCTION [dbo].GetDbSchemaChecksum
(
)
RETURNS int
AS
BEGIN
    declare @retVal int
    set @retVal =
    (
    SELECT
        CHECKSUM_AGG(T.Chk) DbSchemaChecksum
    FROM
        (
        select checksum(TABLE_SCHEMA, TABLE_NAME, TABLE_TYPE) Chk from INFORMATION_SCHEMA.TABLES
        union all
        select checksum(TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME, ORDINAL_POSITION, COLUMN_DEFAULT, IS_NULLABLE, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH, NUMERIC_PRECISION, NUMERIC_SCALE, DATETIME_PRECISION) Chk from INFORMATION_SCHEMA.COLUMNS
        union all
        select checksum(CONSTRAINT_SCHEMA, CONSTRAINT_NAME, UNIQUE_CONSTRAINT_CATALOG, UNIQUE_CONSTRAINT_SCHEMA, UNIQUE_CONSTRAINT_NAME, MATCH_OPTION, UPDATE_RULE, DELETE_RULE) Chk from INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS
        union all
        select checksum(CONSTRAINT_NAME, TABLE_SCHEMA, TABLE_NAME, CONSTRAINT_TYPE, IS_DEFERRABLE, INITIALLY_DEFERRED) Chk from INFORMATION_SCHEMA.TABLE_CONSTRAINTS
        union all
        select checksum(TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME, CONSTRAINT_SCHEMA, CONSTRAINT_NAME) Chk from INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE
        union all
        select checksum(CONSTRAINT_SCHEMA, CONSTRAINT_NAME, TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME, ORDINAL_POSITION) Chk from INFORMATION_SCHEMA.KEY_COLUMN_USAGE
        union all
        select checksum(CONSTRAINT_SCHEMA, CONSTRAINT_NAME, CHECK_CLAUSE) Chk from INFORMATION_SCHEMA.CHECK_CONSTRAINTS
        union all
        select checksum(TABLE_SCHEMA, TABLE_NAME, VIEW_DEFINITION, CHECK_OPTION, IS_UPDATABLE) Chk from INFORMATION_SCHEMA.VIEWS
        union all
        select checksum(VIEW_SCHEMA, VIEW_NAME, TABLE_SCHEMA, TABLE_NAME) Chk from INFORMATION_SCHEMA.VIEW_TABLE_USAGE
        union all
        select checksum(SPECIFIC_SCHEMA, SPECIFIC_NAME, ROUTINE_SCHEMA, ROUTINE_NAME, ROUTINE_TYPE, ROUTINE_DEFINITION) Chk from INFORMATION_SCHEMA.ROUTINES
        union all
        select checksum(SPECIFIC_SCHEMA, SPECIFIC_NAME, ORDINAL_POSITION, PARAMETER_MODE, IS_RESULT, AS_LOCATOR, PARAMETER_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH) Chk from INFORMATION_SCHEMA.PARAMETERS
        ) AS T
    )

    return @retVal

END
GO

Answer: Changes in the form of updates to tables in the form of updates/insertions/deletions can be tracked by use of a trigger which would update the timestamp in a master table. We have to maintain a table containing the name of tables and last updated time. Any change in the individual table would update this table in the corresponding row!
Schema changes can also be handled by way of triggers which would update the table of tables. May be in you case, we can have additional column(s) with BOOL data type that would specify if the change was in schema or the data.
Answer: I've found that SQL Server 2008+ Enterprise edition has a feature called Change Data Capture
This will capture any insert, updates, deletes on the database. Unfortunately I don't have Enterprise edition to test this out. I'll add links here so that it will be of help to someone in the future.
Enable/Disable Change Data Capture
Good writeup on how to use this feature
EDIT:
For the Standard Edition there is Change Tracking.
Related Questions:
Auditing SQL Server data changes


Question about a substitution in an integral

Question: So studying integrals for a short duration I found this example of an equation. It goes the following way:
$\int_{-r}^r \! \sqrt{r^2-y^2} \, \mathrm{d}y. \stackrel{y=rz}{=} \int_{-1}^1 \! r^2 \sqrt{1-z^2} \, \mathrm{d}z. $
If I get this right $y$ has been substituted with $rz$. Why could this substitution be made and why could $r^2$ be extrated from the root and not just $r$ ? I think I am missing something bigger here, but I just don't get it.
If you need further context for this equation, message me.
Answer: $r$ is extracted and then multiplied by $dy=rdz $
Comment: What rule has been used here? Substitution rule? I just know Riemann integrals. Is further knowledge required to get the logic behind this?
Comment: Just substitution. Solve your substitution for dy in terms of dz and then plug in
Comment: This is the standard rule of change of variables in integrals. $y=rz$ implies $dy = r dz$. More generally, $y=f(x)$ implies $dy = f'(x)dx$. See https://en.wikipedia.org/wiki/Integration_by_substitution
Answer: By pure textual substitution, then reworking,
$$\int_{y=-r}^r \! \sqrt{r^2-y^2} \, \mathrm{d}y \stackrel{y=rz}{=} \int_{rz=-r}^r \!\sqrt{r^2-(rz)^2} \, \mathrm{d}(rz){=} \int_{z=-1}^1 \!r\sqrt{1-z^2} \, r\mathrm{d}z,$$ hence the claim.
Comment: Thanks, I kinda have difficulties calculating with the Differential like that, because we never properly defined it in our course.
Comment: Like $(rz)'=rz'$, $d(rz)=r\,dz$.


Is this c++ double linked list operation valid? Deletion of elements.

Question: The goal is to do operations with the list ... X1 X2 X3...., specifically delete.
Double linked list
ptr is pointing at X2
<code>(ptr->prev)->next = ptr->next;
(ptr->next)->prev = ptr->prev;
delete ptr;
</code>
Or do I have to declare two new pointers to handle X1 and X3?
Answer: Yes, this should work. Declaring two more pointers should not be necessary.


Does there exists a continuous injection from $R$ to torus $T^2$?

Question: Does there exists a continuous injection $f:R\longrightarrow T^2$?
$T^2=S^1\times S^1$ is a torus embedded naturally in $R^3$?
EDIT: I want the continous injection of the form $f(x)=(g(x),h(x))$ where $g(x):R\longrightarrow S^1$ is a universal covering and $h(x):R\longrightarrow S^1$ is any given continuous map.
Comment: There is already a continuous injection from $\mathbb R$ to the interval $(0,1)$.  Are you sure there are no other constraints on your function?
Comment: If $h$ is any **given** cotinuous map, this will not work in general. Just consider constant $h$
Comment: @ErickWong Yes there are conditions. I have edited the question.
Comment: You can take something like $f(x)=(\exp(ix),\exp(i\arctan(x)))$. The idea is to make $g$ wrap around its $S^1$ using the universal covering, while $h$ just moves increasingly on a little arc that doesn't go all the away around to not risk self-intersection. In this case, the arc from $-\pi/2$ to $\pi/2$.
Answer: Yes. Let $\xi$ be an irrational number. Define
$$f(t) = (e^{t i},e^{\xi t i}) .$$
Both $g(t) = e^{ti}, h(t) =e^{\xi t i}$ are universal coverings.
Now let $f(t) = f(s)$. Then $ti-si = 2k\pi i$ for some $k \in \mathbb Z$ and $\xi t i - \xi s i = 2l\pi i$ for some $l \in \mathbb Z$. We conclude $2k\pi \xi i = 2l \pi i$, i.e. $k\xi = l$. This is possible only when $k = l = 0$. Thus $s = t$.


Elastic Search Bulk is ignoring the last operation provided in the json

Question: I'm trying to perform a Bulk Operation in elastic search. However the last operation given in the JSON is never executed by elastic search.
This is my Request:
<code>curl -XPOST 'localhost:9200/customer/external/_bulk?pretty&pretty' -d'

{"update":{"_id":"1"}}
{"doc": { "name": "Update - John Doe becomes Jane Doe" } }

{"delete":{"_id":"4"}}

{"index":{"_id":"3"}}
{"name": "Create or Update - New Jane Doe" }

{"create":{"_id":"4"}}
{"name": "Only Create - New Jane Doe" }

{"create":{"_id":"5"}}
{"name": "Only Create - New Jane Doe 1" }'
</code>
The Response Contains just 4 Outputs instead of 5 :
<code>{
  "took": 100,
  "errors": false,
  "items": [
    {
      "update": {
        "_index": "customer",
        "_type": "external",
        "_id": "1",
        "_version": 9,
        "result": "noop",
        "_shards": {
          "total": 2,
          "successful": 1,
          "failed": 0
        },
        "status": 200
      }
    },
    {
      "delete": {
        "found": true,
        "_index": "customer",
        "_type": "external",
        "_id": "4",
        "_version": 4,
        "result": "deleted",
        "_shards": {
          "total": 2,
          "successful": 1,
          "failed": 0
        },
        "status": 200
      }
    },
    {
      "index": {
        "_index": "customer",
        "_type": "external",
        "_id": "3",
        "_version": 7,
        "result": "updated",
        "_shards": {
          "total": 2,
          "successful": 1,
          "failed": 0
        },
        "created": false,
        "status": 200
      }
    },
    {
      "create": {
        "_index": "customer",
        "_type": "external",
        "_id": "4",
        "_version": 5,
        "result": "created",
        "_shards": {
          "total": 2,
          "successful": 1,
          "failed": 0
        },
        "created": true,
        "status": 201
      }
    }
  ]
}
</code>
In my scenario, the customer with id "5" (name: "Only Create - New Jane Doe 1") was never created. If I remove this last request (id:5) then even id:4 is not getting created.
I did a search to get all documents for customer index, but id:5 was not present.
Its as if Elastic search is ignoring the last part of JSON. I even tried to post the request through PostmanClient and its still the same.
Elastic Search Version : 5.1.1
Comment: I am not sure, try curl -XPOST 'localhost:9200/customer/external/_bulk?pretty=true' -d
Answer: Looks like the JSON must always end with a new line character (\n) as described here.
I added a new line at the end of JSON and it worked fine.


Proving that sets are recursive

Question: I am stuck on proving that given sets are recursive or recursively enumerable. Those sets are:

$$\begin{align}
f(A) &= \{y, \exists x \in A:f(x) = y\}\\
f^{-1}(A) &= \{x, f(x) \in A\}
\end{align}$$

where $A$ is a recursive set and $f : \mathbb N \to \mathbb N$ is a computable function.
I am new to computability theory so any advice that is understandable for a newbie would be highly appreciated.
Answer: I will use the terminology "recursively enumerable" and "recursive" (= "decidable").
A set $X$ is recursively enumerable iff. there is an algorithm, which started with a word $w \in X$ halts in an accepting state, and which started with a word $w \notin X$ either does not halt or halts in a non-accepting state. Depending on your flavor of computation, you could specify the algorithm in natural language or in a tedious write-up of a Turing machine or combinations.
Note that whenever I use the word "algorithm" I imply the existence of Turing machine exactly implementing that behavior. As you may know there are many computational models — Turing machines and $\lambda$ calculus being the well-known ones.
Let $A \subseteq \mathbb{N}$ be a decidable set and $f: \mathbb{N} \to \mathbb{N}$ a computable function.
Consider your first problem:
$$f(A) = \{y\ |\ \exists x \in A:f(x) = y\}$$
You need to give an algorithm which should halt on an input $y$ for which we have $\exists x\in A: f(x) = y$. For other inputs the algorithm may not halt at all or halt non-acceptingly.
If I gave you such an arbitrary $y \in \mathbb{N}$, how would you go about determining $y \in f(A)$? Surely, you would try out all $x \in A$ and verify whether $f(x) = y$. And that's the algorithm:

Read input $y \in \mathbb{N}$
For all $x \in A$:

Compute $f(x)$.
Test whether $f(x) = y$
If so, then halt acceptingly.
Otherwise continue.

Since we did not give a specific Turing machine (that 7-tuple with states, band alphabet, ... if you remember), but a natural language algorithm. This requires careful observation of the validity of all steps. Are all steps really implementable by a Turing machine, by a human given enough time so to say.
Hence stop for a moment and think why the steps 2 and 2.1 are actually valid. Then also try answering if the whole block 2 ever terminates.

Validity of step 2
Any recursively enumerable set effectively enables the usage of a "for all/each" loop, where the loop terminates iff. the set was finite. Hence, any decidable set has the same property. This can be seen by defining the for all loop in the following way:
For a recursively enumerable set $X$ define "for all $x \in X$" as the following (sub-)algorithm/subroutine:

$X$ was recursively enumerable, hence a Turing machine $M''$ exists, which halts acceptingly on inputs from $X$.
  1. For all $n \in \mathbb{N}$ (or your favorite "base encoding", e.g. $\{0, 1\}$):
    1. Start $M''$ with input $n$ and only perform one step.
    2. Continue exactly one step in all previously started Turing machines.
    3. If any of those machines halted acceptingly, then do ??? (where ??? is determined by the algorithm using this subroutine)
    4. Continue

Validity of step 2.1
$f$ is a computable function, hence there is a Turing machine $M'$ which given an input $n \in \mathbb{N}$ halts in an accepting state with output $f(n)$.
Thoughts on termination
By definition of step 2, the algorithm never terminates for inputs not in $f(A)$. This is not necessary for $f(A)$ to be recursively enumerable. In fact, we could even halt for values outside of $f(A)$ - but notably non-acceptingly in that case!
Correctness of algorithm
Let $M$ denote a Turing machine implementing the main algorithm above. Try proving $L(M) = f(A)$ by proving $L(M) \subseteq f(A)$ and $f(A) \subseteq L(M)$. This may or not may be obvious to you. This requirement corresponds to the wording above:

A set $X$ is recursively enumerable iff. there is an algorithm, which started with a word $w \in X$ halts in an accepting state, and which started with a word $w \notin X$ either does not halt or halts in a non-accepting state.

Now you proved that $f(A)$ is recursively enumerable! Further food for thought: Could $f(A)$ be even decidable? Answer:

 Not in general, but consider $A$ being the recursively enumerable set $H$ of all halting Turing machines and $f \equiv 1$ — a constant function. Surely, $f(A)$ is decidable: if the input is $1$, then accept it, otherwise don't accept it.

If $A$ is decidable, is then $f(A)$ decidable as well? Answer:

 No in general, you still have to search through the whole set $A \subseteq \mathbb{N}$ to look for the preimage of $y$. In other words, step 2 is still a non-halting subroutine.

How could you prove this formally?

 Choose $A = \mathbb{N}$, $f: A \to \mathbb{N}$ so that it enumerates $H$. Note that $f$ is computable with $f(A) = H$. Decidability of $f(A)$ would contradict the well-known undecidability of $H$.
Comment: @Berci Thanks a lot for spotting this blatant mistake! I guess I'll stick to 'recursively enumerable' and 'decidable'.
Comment: Comment on terminology: what you call '*decidable*' is 'recursive' in the OP, and what you call '*recursive*' is the 'recursively enumerable'.
Comment: Thank you very much. I was not expecting such great answer! I have some more qustions.

1. Could the second set recursive enumerability be proven similarly as the first set? I.e. proving that there is an algorithm which halts when f(x) ∈ A

2. function f is computable => f^−1 is computable. Is that correct?
Comment: The second set is even decidable: given $x$, compute $f(x)$ then decide if it's in $A$. If $f$ is computable, it doesn't follow that $f^{-1}$ is so. In general, it's not even a function of elements but of subsets..
Comment: @Berci Let's assume $f: A \to B$ is bijective and $A$ r.e., then surely given a $b \in B$ you can search $A$ for the one $a$ with $f(a) = b$. So this algorithm represents $f^{-1}: B \to A$. See also [this question](https://math.stackexchange.com/q/1133083/85341).
Comment: Hello @ComFreek I have a follow-up question. Wouldn't the first set be recursive (decidable) if the function *f* was **totally** computable? Thanks!
Comment: @dvdblk How do you define "totally computable"? If that's just a total function which happens to be computable as well, then my answer already contains a counterexample at its very end.
Comment: @ComFreek Yes, it is just a total function. Yet I still can't grasp around your counterexample at the end so let me try to rephrase my question. For which inputs is your algorithm non-halting? Since A is decidable you can iterate over the entire set (as you mention in validity of step 2), thus ending the loop in some arbitrary time. Now when we know that f is also total, step 2.1 always halts. In conclusion the algorithm halts on every input, which would imply that it is also decidable? Thank you for any further elaboration.
Comment: @dvdblk Take any TM encoding $ \notin H$, e.g. $M$ just continues running to the right. The alrogithm at the end would try to go through 0, 1, 2, 3, ... in $\mathbb{N}$, apply $f$ to it to get a sequence of encodings of TMs which all halt. The latter sequence will never contain $$, though, hence the algorithm does not terminate. The algorithm must not only halt on inputs of the decidable set in question, but also on all inputs from the complement! Otherwise, the set is only recursively enumerable. Note that the argument in this comment does not constitute a proof of the undecidability...
Comment: ...of $f(A)$, just that the concrete algorithm fails at proving decidability. There might be other algorithms, though. Then again, there aren't, see the formal proof at the end of this answer. If you know about reductions, it amounts to showing $H \leq f(A)$. If $f(A)$ were decidable, so would $H$, hence $f(A)$ is undecidable.

Proving that sets are recursive


How are vectors defined in terms of sequences?

Question: I'm reading this Wikipedia article on sequences Sequence where it mentions 'Sequences over a field may also be viewed as vectors in a vector space.' under vectors section. I'm not able to grasp this, can somebody explain how vectors can be defined in terms of sequences?
Answer: The point is: "How do think of 'vectors'?" or "What is a 'vector'?" Here a vector is just seen as an element of a vector space, not as a $n$-tuple of elements from the ground field. The set \[\sideset{^{\mathbb N}}{} F = \{(a_n) \mid a_n \in F, n \in \mathbb N\} \]of sequences of elements from a field $F$
is a vector space over $F$, if we define the vector space operations

Addition The sum of two sequnecens $(a_n), (b_n) \in \sideset{^{\mathbb N}}{} F$ is defined as the sequence $(a_n + b_n)$
Scalar multiplication The product of $\lambda \in F$ with a sequence $(a_n) \in \sideset{^{\mathbb N}}{} F$ is defined as $(\lambda \cdot a_n)$.

Then all properties of a vector space are fulfilled ($\sideset{^{\mathbb N}}{} F$ with $+$ is an abelian group, and we have associativity of the multiplications, distributivity...). That is, sequences are more or less a vector space in the same way finite tuples are, by elementwise operations.
As the sequences form a vector space, we may call them vectors.
Answer: In mathematics vector spaces are defined formally by being able to add in them and scalar multiply with an element of the field (for details see the corresponding Wikipedia article).
You just need to figure out, what both of them is for sequences, but that is not really a problem.

Addition: Let $(a_n)$ and $(b_n)$ be sequences. We define the addition as follows: $$(a_n) + (b_n) := (c_n) \text{ with } \forall n\in\Bbb N\colon c_n := a_n + b_n$$
Multiplication: Let $(a_n)$ be a sequence and $\lambda$ an element of the underlying field (i.e. $\Bbb R$). Then the multiplication is defined as:
$$ \lambda (a_n) := (c_n) \text{ with } \forall n\in\Bbb N\colon c_n := \lambda a_n$$

You just need to check all the properties from the definition (like associativity etc.) to see that this indeed defines a vector space, however of infinite dimension.


Axis of rotate() of css

Question: I refered the code elsewhere and following the code, it's making a green line square.
But I think the code has to make a cross not the square.
If I run the code it makes the squre lik the picture below

It seems that all lines have different rotation axis.
Can you let me know why it's not making a cross but square?
code:
import styled from "styled-components";

export default function App() {
  const array = [0, 1, 2, 3];

  return (
    <Wrap>

          {array.map((idx) => {
            return <Line number={idx} />;
          })}

    </Wrap>
  );
}

const Wrap = styled.div`
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  min-height: 100vh;
  justify-content: center;
  align-items: center;
  background: #111;

  .container {
    border: 3px solid orange;
    position: relative;
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .container .square {
    top: 200px;
    left: 200px;
    border: 1px solid blue;
    position: absolute;
    width: 200px;
    height: 200px;
  }
`;

const Line = styled.span`
  border: 1px solid red;
  position: absolute;
  inset: 10px;
  transform: ${(props) => `rotate(calc(90deg * ${props.number}))`};

  &::before {
    content: "";
    position: absolute;
    width: 100%;
    height: 4px;
    background: #0f0;
  }
`;

CodeSandBox
https://codesandbox.io/s/zigzag-f2uybc?file=/src/App.js:0-1864
Comment: You have a typo - `.contatiner` - not sure this'll do anything for your issue though.
Comment: it doens't matte but thanks for letting me know a typo
Comment: Why would it make a cross? You literally have a class called square?
To illustrate a bit you can see that transform rotate 90deg will ensure the little square goes in orthogonal angles. Also the keyframes, in which you should have added to your question, with the coordinates: (2px, 2px), (178px, 2px), (178px, 178px), (2px, 178px), (2px, 2px) are travelling through the 4 corners of a square.
Comment: ever used `transform-origin`? https://developer.mozilla.org/en-US/docs/Web/CSS/transform-origin
Answer: Your Line component is a square :
  position: absolute;
  inset: 10px;

Because without a explicit width and a height, a box in a absolute position with have inferred width from left and right properties, and inferred height from the top and bottom properties, so relative to the first parent with a absolute, relative, fixed or sticky positioning.
-> Line parent is the
 element.
So Line will be square.
The reel line is the Line before pseudo element :
    position: absolute;
    width: 100%;
    height: 4px;

And without positioning (top, bottom, left, right), it will start from the top left corner of the first positioned parent.
-> So Every Line component is a transparent square with a green line on top.
When you rotating the square by 90°, the line follows, keeping the same position relative to the square.

If you want it to form a cross :
You can center the speudo element in the Line component, for exemple just add :
  display: flex;
  justify-content: center;
  align-items: center;

In the CSS of the Line component.

Axis of rotate() of css


Modelling time varying volatility when GARCH(1,1) coefficients sum to value greater one

Question: First of all I have to admit that I am not a time-series expert so any help is highly appreciated. I have a financial time-series (a fixed income total return index measured on a weekly basis) for which I would like to fit an AR model. However, I would like to take into account the time varying volatility of the series. In particular, the volatility of the series is very low at the beginning of the series, increases sharply at the end of 2008 and shrinks again:

The log returns exhibit this even more clearly:

I decided upon the order of the AR model by using different information criteria which lead me to an AR(1) model for the log return time-series. After that I tested for ARCH effects using a Lagrange-Multiplier-Test. It turned out that ARCH effects are significant for all tested 12 lags. Considering the high order of the lags I considered a GARCH(1,1) for the conditional volatility. The problem is that the estimated coefficients sum to a value greater than one ($\alpha_1+\beta_1=0.97+0.56=1.53)$ implying that volatility is growing without bounds which is clearly undesirable and also is contradictory to the graph. So my questions are:

Which alternative model could I use to model this behavior of the     volatility of the series considering that my primarily interest is in the coefficient values for the AR(1)?
When modelling the conditional mean of the series the classic approach would be to integrate the series. Is there a similar approach considerable for the volatility?
As the series has only 534 observations how likely is this to be the reason for the sum of the mentioned coefficients to be greater than 1?

I would be also very happy about any hint to a particular Stata or R command that seem promising to model the volatility of this time series. However, I think this is primarily an econometrics question. Thanks for your time and effort!
Answer: First, you have not told us what this series represents. Subject-matter knowledge is generally useful when trying to model the data.

the volatility of the series is increasing <...> The log returns exhibit this even more clearly

It would be more accurate to say that volatility has been very low in the beginning, high for a while and then quite low again. There is no linear trend in the magnitude of volatility -- see your second figure.

Which alternative model could I use to model this behavior of the volatility of the series <...> ?

You may want to reconsider the model for the conditional mean first. Perhaps you could model the apparent trend in the original series and the dip during approx. 2009 by including some other explanatory variables and turning the AR model into an ARX model. Also, you could consider ARCH-in-mean specification, as the volatility seems to have been the highest when the series was going down.
Now to answer the question, there is a great variety of GARCH models suited for different features of the data. One survey (not necessarily the best) can be found here: Terasvirta "An introduction to univariate GARCH models" (2009). You could take a look at the stylized facts and the characteristics of the different models and see if there is one that suits you.
You could also have a GARCH model with exogenous variables. E.g. a GARCH model with a time trend could suit a case where conditional variance is increasing linearly (which does not seem to be the case here, though). Or you could have an IGARCH model where the conditional variance is an integrated process. That also answers your second question:

When modelling the conditional mean of the series the classic approach would be to integrate the series. Is there a similar approach considerable for the volatility?

Sorry for being a bit vague about the choice of the model, but I think it would be careless to recommend a particular model just by having seen a graph of the data.

I would be also very happy about any hint to a particular Stata or R command that seem promising to model the volatility of this time series.

In R I may recommend using "rugarch" package with main functions ugarchspec (for specifying a GARCH model) and ugarchfit (for estimating the specified model for a given data series). There is a nice vignette to consult.
P.S.

the estimated coefficients sum to a value greater than one <...> implying that volatility is growing without bounds which is clearly undesirable

It is not only undesirable, but it also does not seem to fit the data -- I do not see gradually exploding volatility in the second figure.
Comment: Not so sure whether it's standard practice. I tried different ARMA specifications and judged the results using the common information criteria (BIC, AIC, SIC) and they pointed at the AR(1) which is also supported by the partial autocorrelation function. Fitting models of higher order basically results in all coefficients being insignificant.
Comment: I see. I thought maybe ARMA may not be suitable in general, whatever the order ($p,q$) – but such judgement requires subject matter knowledge.
Comment: Thank you Richard for your very helpful comments. I edited my post to incorporate your critic corncerning the details on the data and the time series behavior of volatility. I was also doing some research in the meantime and conducted some simulations. It seems to me that the number of observations (534) might even be too low to fit any meaningful GARCH model.
Comment: 534 observations do not sound too bad. Also, why an AR(1) model for fixed income total return index? Is that a standard practice to assume an AR(1) model for such series?


VueJS Vee-Validate Validation Not Happening On Input

Question: I have a very basic VueJS form, wherein I am validating the input.
The form validation happens on initial call to the validate form method, and the appropriate validation messages are displayed on each input.
What I am puzzled about is that on the vee-validate example for the forms, clicking on the submit button invokes the validation, and then displays the error message for each form input. Once you enter a value on the input (say on the name field), you can clearly see that the validation error and message for that field is removed.
I am providing a sample JSBin illustrating the issue I am having.
On the output panel, click on the Validate Form button, and you can see that the validation is working. But once you enter some text on the input field (i.e. First Name), the validation does not work anymore, unless you explicitly click again on the Validate Form button. This does not seem to be the same behavior on the Vee-Validate form.
Am I overlooking or missing something? Appreciate any input on what may be causing the issue as I am quite new with VueJS.
Thanks.
Codes as from JSBin:
HTML
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
  <title>JS Bin</title>

    <form class="form-horizontal" @submit.prevent="validateBeforeSubmit">

        First Name:

          <input name="FirstName" v-model="firstName" v-validate:firstName.initial="'required|alpha|min:3'" class="form-control" type="text" id="firstName" placeholder="" v-bind:class="{ 'input': true, 'has-error': errors.has('FirstName') }" >
          {{ errors.first('FirstName') }}

        Last Name:

          <input name="LastName" v-model="lastName" v-validate:lastName.initial="'required|alpha|min:3'" class="form-control" type="text" placeholder="" v-bind:class="{ 'input': true, 'has-error': errors.has('lastName') }" >
          {{ errors.first('LastName') }}

    </form>

    Validate Form

{{ errors }}

{{ fields }}

JS
Vue.use(VeeValidate);

var app = new Vue({
  el: '#app',

  data: {
    firstName: null,
    lastName: null
  },

  methods:{
    validateBeforeSubmit: function(){
      function onOk(){
        alert('Form is OK');
      }

      function notOk(){
        alert('Form Not OK');
      }

      this.$validator.validateAll().then(onOk, notOk);
    }
  }
});

Answer: As it is in the documentation, you have to make following changes:

Only put v-validate="'required|alpha|min:3'"
You can add data-vv-delay="100" to get errors after 100ms or whatever time you deem fine.

see HTML below :
<input name="FirstName" v-model="firstName"  data-vv-delay="100" v-validate="'required|alpha|min:3'" class="form-control" type="text" id="firstName" placeholder="" v-bind:class="{ 'input': true, 'has-error': errors.has('FirstName') }" >

See working bin.
Comment: I will accept this as an answer, but I just want to gain an understanding as to why on the example on the site for the Forms Validation, the attributes were specified as:  v-validate:name.initial="'required|alpha'"? I clearly followed the same on my form, and for reason I want to also know, it is breaking the validation.
Comment: There's just another issue on the solution you provided. Once your cursor is in the input field, and you tab away or set focus to another control, the validation occurs outright. Seems removing the v-validate:FIELDNAME.initial removes the behavior to only validate on the click of button.
Comment: @Angelo I am also referring to [documentation](http://vee-validate.logaretm.com/#basic-example) only.


jQuery Mobile get button that opened Popup

Question: I have a listview, when I click a link in the listview it launches a popup.  For simplification purposes I have omitted the listview and am starting with just a single button.
I want to retrieve attributes from the button that caused the popup to show, in my example the attribute named customAttr. I then want to insert the value into popupBasic.
Here is my very basic sample jQuery Mobile code:
Basic Popup

This is a completely basic popup, no options set.

jsFiddle: http://jsfiddle.net/cPRCU/2/
Normally when I work with jQuery (non-Mobile) I am more involved with the click event/opening of popup's/dialogs.  I would like to be able to read the button that caused the popup to show, how can I do this?
Answer: Adding a click handler to the button seems to work. In this handler, modify the popup before it gets shown:
$('a[data-rel="popup"]').click(function () {
    var link = $(this);
    var data = link.attr('customAttr')
    var popup = $(link.attr('href')); // assume href attr has form "#id"
    popup.append(($('
').text(data)));
});

This is a generic handler which supports a page with multiple buttons/popups. If some buttons should not have this behaviour, I would add a class to the desired button, and make the a[data-rel="popup"] selector more specific.
See fiddle: http://jsfiddle.net/cPRCU/3/
Answer: I did it on a listview itself as it would be more useful to you.
For a ListView
You have to register a click event for the  tags in your listview as below first.
$('#mylist a').bind('click', function(event){
});

meanwhile, make sure to store the data inside the anchor tag as below.
data-customattr everything is small here.
e.g.
Basic Popup 2

Now you can read the value of data-customattr inside the click event as below
$(this).data('customattr')

Now I assume that you have a id for the
 tag inside the popup. Something as below

This is a completely basic popup, no options set.

using the ID you can replace the popup's content.
finally putting all together something like below
$('#mylist a').bind('click', function(event){
    console.log($(this).text());
   $('#mypopup').html($(this).data('customattr'));
});

Checkout this live fiddle for the working example http://jsfiddle.net/gFTzt/5/
For a button
If you insist on a example using button then declare a button with an ID as below
button example

As mentioned above register a click event and read the customattr value.
 $('#mybutton').bind('click',function(){
        alert($(this).data('customattr'));
 });

Check out this live fiddle example for both button and listview http://jsfiddle.net/gFTzt/5/
using .attr()
Here I've used the data to get the value. without data attribute we can directly get the value from the anchor tag as below.
E.g. we have a anchor tag as below.
Basic Popup 1

we can read the value1 using the .attr() as below.
$(this).attr('customattr')

Here is a Live fiddle example.
Comment: Nice bro! `.attr()` works with `customattr` if you remove `data-` ;)
Answer: I was having a problem getting popups to work but I finally realized that the popup div needs to be inside the page.  My popup was a sibling to the page where the popup link was and was not showing up until I moved it in to be a sibling of the link and child of the page.


Js Objects Links for one?

Question: I want to make object with different key 'number' with values from arr;
var arr = [1,2,4],
    q = {},
    a = { number : null };

for (i=0;i<3;i++) {

       q[i] = a;
       q[i].number = arr[i];
}

But with this i got 3 same objects.
I tried to make a closure like
var arr = [1,2,4],
    q = {},
    a = { number : null };

for (i=0;i<3;i++) {
       (function(number) {
           q[number] = a;
           q[number].number = arr[number];
       })(i)

}

but result is the same. What i am doing wrong?
Answer: You already define object a. And when you write a to q[i] it just write pointer to this object. Fixed code:
var arr = [1,2,4],
    q = {};

for (i = 0; i < 3; i++) {
    q[i] = {};
    q[i].number = arr[i];
}

And if cleans up here:
var array = [1, 2, 4],
    q = Object.create(null);

array.forEach(function(value, index) {
    $.extend(q[index], {
        number: value
    });
});

.forEach()
Comment: I ask too easy situation, but i want to extend an object and with this i would got the same

var array = [1, 2, 4],
    q = [], a = { a : 1, b : null}

array.forEach(function(value, index) {
    q[index] = $.extend(a, {b : value})
});
Comment: You must call ```$.extend(q, a, {b: value})```. When you call ```q[index] = $.extend``` you override ```q```variable.
Comment: Why override? q[0] = 'one' , next iteration q[1] = 'two'
Comment: You again create object ```a``` and set pointer to ```a``` not a new object. See my updated answer with extending.
Comment: try to execute your code, it's wrong. q equals empty {};

Js Objects Links for one?


$\mathrm{ord}_{mn}a = {\rm lcm}(\mathrm{ord}_ma, \mathrm{ord}_na)$ where $a, m, n$ are relatively prime

Question: Problem

Prove that the $\mathrm{ord}_{mn}a = [\mathrm{ord}_ma, \mathrm{ord}_na]$ where $a, m, n$ are relatively prime.

My attempt was,
Let $x = \mathrm{ord}_ma$, $y = \mathrm{ord}_na$, and $z = \mathrm{ord}_{mn}a$.
By definition of order, we have
$a^x \equiv 1 \pmod{m}$ and $a^y \equiv 1 \pmod{n}$ which implies $(a^{x})^y \equiv 1 \pmod{m}$, and $(a^y)^x \equiv 1 \pmod{n}$. Hence, $a^{xy} \equiv 1 \pmod{m}$ and $a^{xy} \equiv 1 \pmod{n}$. Furthermore, we have $a^{xy}, m, n$ are pairwise relatively prime. Therefore, $a^{xy} \equiv 1 \pmod{mn}$. So if $z$ is the order of $a$ modulo $mn$, then $z$ is the smallest integer such that $a^z \equiv 1 \pmod{mn}$. On the other hand, $z|(xy)$ because $a^{xy} \equiv 1 \pmod{mn}$, which implies $xy = z \cdot k$ for some integers $k$. Next, to satisfy the smallest value that divides $xy$, $k$ must be the greatest common divisor of $x, y$. Hence $z = \dfrac{xy}{(x,y)} = [x,y] \text{    } \square$.
Am I in the right track? Any feedback would be greatly appreciated.
Thank you
Answer: Your solution shows good understanding of the situation, but I think it could be considered technically incomplete. You write "to satisfy the smallest value that divides $xy$."  It is clear that what you have in mind is that you are looking for the smallest (positive) number which is a multiple of $x$ and of $y$, and divides $xy$.  And you do not explicitly say why you are looking for that smallest multiple, although you certainly could explain if asked.  The fact that $x$ and $y$ are the orders of $a$ modulo $m$, $n$ respectively is not used, and needs to be ($a^x \equiv 1 \pmod{m}$ and $a^y \equiv 1 \pmod{n}$ are used, but not the minimality of $x$ and $y$).
The following is a variant of your solution that (in the second part) makes explicit what you had left implicit.  In the first part, I will not use the product $xy$, because of personal preference.
Each of $x$ and $y$ divides $[x,y]$.  Let $[x,y]=xu=yv$.  Then
$a^{[x,y]}=(a^x)^u$.  But since $a$ has order $x$ modulo $m$, it follows that $a^x\equiv 1 \pmod{m}$, and hence $a^{[x,y]}\equiv 1 \pmod{m}$.  In the same way, we can show that $a^{[x,y]}\equiv 1 \pmod{n}$. Since $m$ and $n$ are relatively prime, it follows that $a^{[x,y]}\equiv 1 \pmod{mn}$.
Thus $z$, the order of $a$ modulo $mn$, must divide $[x,y]$.  We will show that in fact $z=[x,y]$.  Since $a^z \equiv 1 \pmod{mn}$, it follows that $a^z \equiv 1 \pmod{m}$.  So the order of $a$ modulo $m$, namely $x$, divides $z$.  Similarly, $y$ divides $z$.  It follows that $[x,y]$ divides $z$, and hence $[x,y]=z$.
Comment: @user6312: It was like you read my mind!Amazing! In fact, before posting, I was stuck with "You write "to satisfy the smallest ... divides xy.", then suddenly I came up with that. Although I didn't know how to say it explicitly, I knew it must be true, otherwise the proof was not true. Thanks for pointing that out. By the way, there are not many people can read other people minds this way, especially very few smart people want to hear and understand other thoughts. I'm totally convinced, everything you said is just verbatim!
Comment: @user6312: I wish I could give at least 5 votes for your answers!
Comment: @Chan: Thank you, but I do not need points, one cannot buy wine with points.
Comment: @user6312: Just a way to show my appreciation! By the way, wine is not healthy :)
Answer: That's exactly right. Well done.
Comment: Great thanks once again! You were also right that this was my homework. However, I won't copy other people' solutions and submit as my work. My rule of thumb is, grade is important, but learning something is much more important. I don't want to regret when I'm getting older, because at that time I won't be able to think like this anymore. Furthermore, understanding new things make me happy, even though it often takes a lot of my time.
Comment: @Chan: That's a good way to go about this. I look forward to hearing from you again.
Answer: This is obvious via CRT (Chinese Remainder Theorem), i.e. since $\rm\ (m,n) = 1\ $ it yields $\rm\ \mathbb Z/mn\ \cong \mathbb Z/m \times \mathbb Z/n ,\,$ via  $\rm\ a_{mn}\: \mapsto\: (a_m,a_n),\:$  thus
$$\rm\ (1,1) = (a_m,a_n)^k\! = (a_m^k,a_n^k) \iff o(a_m),o(a_n)\ |\ k\iff lcm(o(a_m),o(a_n))\ |\ k\qquad $$
Note especially how this method efficiently simultaneously proves both directions of the proof by exploiting the universal bidirectional $(\!\!\iff\!\!)$ definition of $\rm lcm,$ namely $\rm\ a,b\ |\ c \iff [a,b]\ |\ c$


Como parar um programa em determinado tempo de execução - Python

Question: Oi, estou tentando rodar um script que encontrei na internet para rodar um programa chamado "Xfoil". O problema é que ele trava algumas vezes, então eu precisaria colocar um timer para fechar o programa em determinado tempo de execução. Como eu faço isso? Sou leigo em Python, se puderem me ajudar eu agradeço. No Final do código está minha tentativa de finalizar o processo "xfoil.exe".
<code>#Runs an XFOIL analysis for a given airfoil and flow conditions
import os
import subprocess
import numpy as np
import time

# %% Inputs

airfoil_name = "E423"
alpha_i = 0
alpha_f = 20
alpha_step = 1
Re = 100000
n_iter = 100

# %% XFOIL input file writer

if os.path.exists("polar_file.txt"):
    os.remove("polar_file.txt")

input_file = open("input_file.in", 'w')
input_file.write("LOAD {0}.dat\n".format(airfoil_name))
input_file.write(airfoil_name + '\n')
input_file.write("PANE\n")
input_file.write("OPER\n")
input_file.write("Visc {0}\n".format(Re))
input_file.write("PACC\n")
input_file.write("polar_file.txt\n\n")
input_file.write("ITER {0}\n".format(n_iter))
input_file.write("ASeq {0} {1} {2}\n".format(alpha_i, alpha_f,
                                             alpha_step))
input_file.write("\n\n")
input_file.write("quit\n")
input_file.close()

start = time.time()
subprocess.call("xfoil.exe < input_file.in", shell=True)
end = time.time() - start
print(end)
if end>3:
    os.system('wmic process where name="xfoil.exe" delete')

polar_data = np.loadtxt("polar_file.txt", skiprows=12)

</code>
Answer: Em Python 3.3+
<code>#Runs an XFOIL analysis for a given airfoil and flow conditions
import os
import subprocess
import numpy as np
import time

# %% Inputs

airfoil_name = "E423"
alpha_i = 0
alpha_f = 20
alpha_step = 1
Re = 100000
n_iter = 100

# %% XFOIL input file writer

if os.path.exists("polar_file.txt"):
    os.remove("polar_file.txt")

input_file = open("input_file.in", 'w')
input_file.write("LOAD {0}.dat\n".format(airfoil_name))
input_file.write(airfoil_name + '\n')
input_file.write("PANE\n")
input_file.write("OPER\n")
input_file.write("Visc {0}\n".format(Re))
input_file.write("PACC\n")
input_file.write("polar_file.txt\n\n")
input_file.write("ITER {0}\n".format(n_iter))
input_file.write("ASeq {0} {1} {2}\n".format(alpha_i, alpha_f,
                                             alpha_step))
input_file.write("\n\n")
input_file.write("quit\n")
input_file.close()

start = time.time()
subprocess.call("xfoil.exe < input_file.in", shell=True, timeout = 1000)
end = time.time() - start
print(end)
if end>3:
    os.system('wmic process where name="xfoil.exe" delete')

polar_data = np.loadtxt("polar_file.txt", skiprows=12)
</code>
Comment: Sua resposta pode ser melhorada adicionando informações fundamentais. Basta [edit] para adicionar mais detalhes, como citações ou documentação para que outras pessoas possam confirmar que sua resposta está correta. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).


Usuários ativos no site

Question: minha intenção é criar um sistema de pessoas onlines no meu site, a cada 30s eu mando uma requisição em ajax pro meu servidor e marco o ip e a hora da visita, minha duvida é a seguinte no meu banco eu gravo no campo hora ( 03:29 ) usando a função date como posso estar comparando esta hora gravada com meu banco com a hora atual e saber se já se passaram 30 segundos ? pois assim quando se passa 30 segundos eu deleto do banco de dados as visitas ativas
Comment: Talves isso te ajude [Veja](https://pt.stackoverflow.com/questions/264889/bloquear-elemento-por-mais-ou-menos-10-minutos/264893#264893)
Answer:
usando a função date como posso estar comparando esta hora gravada com meu banco com a hora atual e saber se já se passaram 30 segundos ?

Responde a essa pergunta, vamos lá.
Para fazer isso não precisa utilizar a função date (apesar de ser possível), mas nesse caso é melhor utilizar apenas a função strtotime ou strftime, você pode converter a data para segundos ou milissegundos e fazer a substração dos novos dados com os dados antigos.
<?php

/* Captura o tempo em segundos desde 1970 */
$date1 = strtotime("2018-01-06 02:43:00"); //Output: 1515206580
$date2 = strtotime("2018-01-06 02:43:32"); //Output: 1515206612

/* Utilize strtotime("+30 seconds") para capturar a data atual + 30 segundos */

/* Substrai as datas e verifica se $data é maior que 30 (Segundos) */
if ( ($date2 - $date1) > 30 ) {
    echo "Já se passaram mais de 30 segundos";
}

Caso queira fazer com DateTime e DateInterval, também é possível:
<?php

/* Instancia o objeto com as respectivas datas */
$date1 = new DateTime("2018-01-06 02:43:00");
$date2 = new DateTime("2018-01-06 02:43:32");

/* Captura a diferença entre a $data2 e $data1 */
$interval = $date2->diff($date1);

/* Captura a diferença em segundos e verifica se é maior que 30 */
if ($interval->format("%s") > 30) {
    echo "Já se passaram mais de 30 segundos";
}

Ou ainda:
<?php

/* Instancia o objeto com uma data. Para capturar a data/hora atual, deixe em branco ou passe o valor "now" */
$date1 = new DateTime("2018-01-06 02:43:00");

/* Adiciona 30 segundos a data anterior */
$date1->add(new DateInterval("PT30S"));

/* Verifica se a data atual é maior que a data anterior, somado os 30 segundos. */
var_dump( $date1->format("U") < time() );

Usuários ativos no site


ASP.NET Session limit best practice

Question: We're running a PaaS ASP.NET application in an Azure App Service with 3 instances and managing session data outproc in a SQL Server database.
The application is live and we've noticed a large amount of session data for some users when following certain paths e.g. some users have session data upwards of 500k (for a simply site visit with no login the average session is around the 750 - 3000 mark which is what I'd expect).
500k sounds excessive but was wondering what is normal in large enterprise applications these days and the cons of holding so much data in session.
My initial thoughts would be,

No affect on Web App CPU (possible decrease in fact) because not constantly doing queries,
No affect on Web App Memory because we running outproc,
Large spikes in DTU on Sql Server session database when garbage collection runs,
Application may be a bit slower because it takes longer to read and write session data between requests,
May not be ideal for users with poor internet connections,
Possible increase in memory leaks if objects aren't scoped correctly.

Does my reasoning make sense or have I missed something?
Any thoughts and advice would be appreciated,
Many thanks.
Answer: I totally agree with your reasoning behind using out-proc session management in Azure App instances.Using IN-PROC sessions in the cloud is a strict no. The reason to host to cloud is to have high availability which is done by having a distributed environment.
Understanding from your point, i assume that speed is a concern to you or if matters to most of the web application , To overcome this , you might think of using Azure redis cache.
Here is the article for configuring session management using Azure redis cache:
Refer the documentation here: https://learn.microsoft.com/en-us/azure/redis-cache/cache-aspnet-session-state-provider
Comment: Thanks Mohit for your feedback. Yea we were using Redis but switched it out because it wasn't handling our large session data. My understanding is Redis is fast but only if you data size is not to big. It can handle lots of keys but the key (or pair) size can't be to big. I suspect we were hitting the upper limits which is why we started having issues with it.

ASP.NET Session limit best practice


Copy data from one table to another and change id

Question: I want to copy one row from one table to another table. But in the process I want change value of id. For example to 20. How to do it?
I have this code
INSERT INTO work_done
SELECT * FROM work_todo
WHERE id = 10

Answer: Try somethink like tis
INSERT INTO work_done
          ( id
          , col2
           ...
          )
     SELECT 20
          , col2
           ...
      FROM work_todo WHERE id = 10

Comment: Quite possibly, the values `10` and `20` are in fact **numerical** values and stored in a column of numerical type - so then they should **not** be put in double quotes in your query...
Comment: `"20"` is an **identifier** (e.g. a column name) in SQL. I doubt there is a column named `"20"` in the work table
Comment: answer updated :)
Comment: i just tested my query, this work well
Comment: oh, I have used quotation marks in brackets.. tx :)
Answer: select *
 into work_done
 from work_todo
where id = 10;

update work_done a
   set a.id = 20;

OR
 select case id
            when id = 10
              then id = 20
     into work_done
     from work_todo
    where id = 10;


In this piano notation, which hand plays which notes?

Question: For the final 3 chords/notes, what hand plays what?
(The piece is Lilium Elfen Lied OP, Transcribed by TehIshter.)
Comment: Are there pedal markings in the piece?
Comment: there are no pedal markings in this entire piece, so the player has to put them whenever they see it suited
Comment: See whether TheIshter has a video of himself playing this piece, then look at his hands as he plays that passage if possible.
Answer: It seems to me that the transcriber intends all pitches in the bass clef to be played with the left hand and all pitches in the treble clef to be played by the right hand.
The slurred eighth-note passage that begins on the low F♯ is all one line (as shown with the dotted line in the score), but the G♯, B, and A should be played with the right hand. You'll have the release the half-note chord in the right hand early, but you can use pedal to keep that chord sustained.
And make sure you practice a smooth trade-off between the hands!
Comment: I might use the left to take that G#, though.
Answer: Right hand plays top clef, left hand plays bottom.   The dotted line indicates the musical phrase moving from one hand to the other.  Some pedalling certainly seems appropriate!
Comment: I might take the B in beat 3 with the right hand myself, since I would certainly take the following A with the right hand. Also, I would probably pedal the entire half-note chord, so the low F would carry through.
Answer: I would use the left hand to play G#-B (3 crotchets in). The following A would probably have to be played (despite the notation) with your right hand (unless you have extremely large hands) as you are required to play an F# and D as well. I believe it is notated in such a way for fluency of phrasing.


Como limpar uma variavel int em java?

Question: Estou desenvolvendo um programinha que tem um menu que se eu digitar 1 cadastro um curso e se eu digitar 2 cadastro um aluno ambos os ifs estão funcionando tipo se eu digitar 1 cadastrar um curso fechar o console abrir de novo digitar 2 e cadstrar um aluno ocorre tudo normalmente mas se caso eu digitar 1 cadastrar o curso o menu reaparecer e eu digitar 2 para cadastrar um aluno msm eu digitando 2 ele entra de novo no if do curso segue o codigo
<code>public static void main(String[] args) {

tela.menu();

if (opc == 1){

for(posc=0;posc<10;posc++){

//seta o nome do curso
System.out.print("Digite o nome do curso: ");
nomecurso = entrada.next();
sala.setNome(nomecurso);
nomescurso[posc] = nomecurso;

//seta o codigo do curso
System.out.print("Digite o codigo do curso: ");
codigocurso = entrada.nextInt();
sala.setCodigo(codigocurso);
codigoscurso[posc] = codigocurso;

System.out.print("\\n");
posc++;
tela.menu();

}

}else if(opc == 2){

for(posa=0;posa<10;posa++){

//seta o nome do aluno
System.out.print("Digite o nome do aluno: ");
nomealuno = entrada.next();
pessoa.setNome(nomealuno);
nomesaluno[posa] = nomealuno;

//seta a matricula do aluno
System.out.print("Digite a matricula do aluno: ");
matricula = entrada.nextInt();
pessoa.setMatricula(matricula);
matriculas[posa] = matricula;

//seta o cpf do aluno
System.out.print("Digite o cpf do aluno: ");
cpf = entrada.next();
pessoa.setCpf(cpf);
cpfs[posa] = cpf;

//liga um aluno a um curso
System.out.print("Digite o codigo do curso cursado pelo aluno: ");
alunocursa = entrada.nextInt();
alunoscursam[posa] = alunocursa;
}

System.out.print("\\n");
posa++;
tela.menu();
</code>
Comment: Onde está o metodo tela.menu()?
Comment: E este código está incompleto, algumas chaves não estão sendo fechadas.
Comment: Copiei e coloei só o main , mas vc entendeu meu problema ?
Answer: Você quer limpar uma variável de número inteiro da memória?
Fazer isso diretamente não é possível... O java tem Garbage Collector, isso faz com que ele tire da memória sozinho quando a mesma já não é mais utilizada.
Você pode defini-la como -1 para identificar em qualquer lugar do código que ela está vazia caso seja necessário.
Comment: Já fiz isso ela continua com o primeiro valor que eu digitar sempre , tipo se eu entrar no if do 1 na primeira execução  e na segunda tentar entrar no if do 2 ele entra de novo no if de um e visse e versa, quero entrar em um if e zerala para na próxima execução entrar no if que quiser

Como limpar uma variavel int em java?


calculate effect size for fixed effect variable with >2 levels binomial glmm (lme4)

Question: I have a mixed effects model with a binomial outcome which I constructed using glmer from the lme4 package in R. In the output from summary(model) I get estimates for each of the fixed effects. This is fine for continuous and dichotomous variables, however, for categorical variables with >2 levels this does not work (as the output produces contrasts). To get the effects for these, I use the anova or drop1 functions. However, these do not include any measure of effect size.
Using the effectsize package, I tried effectsize(model) which provides effect sizes and confidence intervals for the output produced by summary(model), however, what I am interested in is the global effect of a categorical variable with >2 levels (the equivalent to Cohen's d when conducting a normal ANOVA).
How can I calculate this?
Comment: How would you define such a global effect size?
Comment: the equivalent to cohen's d when conducting a normal ANOVA
Comment: Please add that new information to the post as an edit! not only as a comment. Not everybody reads comments, and we want posts to be self-contained.
Answer: There aren't really global effect sizes for glm(m)s.
You can try Nagelkerke's pseudo-$R^2$. E.g.:
m1 <- glm(gear ~ hp, data = mtcars,
          family = poisson())

m2 <- glm(gear ~ hp + am, data = mtcars,
          family = poisson())

performance::r2(m1)
#> # R2 for Generalized Linear Regression
#>   Nagelkerke's R2: 0.017

performance::r2(m2)
#> # R2 for Generalized Linear Regression
#>   Nagelkerke's R2: 0.657

Created on 2022-01-13 by the reprex package (v2.0.1)


Carregando script.js (externo) usando DOMContentLoaded?

Question: vou apresentar meu código de teste resumido para melhor entendimento.
index.php
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Teste</title>

script.js
function init() {
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = '//externo.com/js/encurtador.js';
    document.body.appendChild(script);
}

window.addEventListener("DOMContentLoaded", init);

encurtador.js (externo, não possuo acesso ao arquivo)
document.addEventListener("DOMContentLoaded", function(e) {
    // Codigo que faz a analise de todas tags  e insere o url encurtado
});

Meu Problema
Estou tentando carregar um script externo no qual ele também faz o uso do 'DOMContentLoaded'.
Pelo meu entendimento (me perdoa se estiver equivocado) é que quando o script externo é inserido no final do  o DOM já esta concluído, e devido a esse motivo o script externo não consegue executar sua funcionalidade.

Você deve esta se perguntando o motivo deu esta querendo fazer isso, invés de simplesmente adicionar o script direto a página?

É que pretendo deixar aleatório essa inserção , será digamos (5 links) de varias empresas diferentes de encurtador, será controlado por cookies quando usar um ou outro.
Desculpe se não consegui explicar claramente minha dúvida, posso tentar ser mais detalhado enquanto a duvidas de vocês caso não tenha entendido algo.
Agradeço de coração quem conseguir me ajudar, muito obrigado :)
Comment: Já que está usando PHP, não seria mais fácil fazer isso com ele?
Comment: Opa @GuilhermeCostamilam , minha pagina de teste é em .php rodando em um servidor apache localhost , porem no lugar que vai rodar é somente pagina .html, tambem gostaria de saber se existe alguma correção para resolver o problema utilizando somente o javascript. Muito obrigado pelo comentário :)
Answer: Tens razão, o problema é que quando o ficheiro encurtador.js é incluido, o evento DOMContentLoaded já foi disparado, logo o novo script nunca vai ser triggered.
Felizmente isto é tudo javascript, e há sempre forma de dar a volta.
Podes criar tu o evento DOMContentLoaded artificialmente e dispara-lo num elemento (neste caso o document).
Provavelmente terás de confirmar que o


how to add search box on specific page?

Question: I need to show the search box on that page and specific search if sometime type related news then search result appear. I need only the search box for this content type.
Answer: If I understand your question correctly, you want to display the 'Search form' block for a specific content type.
On admin/structure/block/manage/search/form/configure you can change the 'Visibility settings' and show the block for specific content types. Below a screenshot where I have selected to display the search form on nodes of my custom content type 'Blog overview':
Comment: search form block is working fine and i need another search form which is working for latest news only

how to add search box on specific page?