matrix form of dummy expansion?

Question: It's common in many applications to interact a set of numeric variables with a factor variable.  The factor variable is a convenient abstraction for what is actually a matrix of dummy variables.  For example, say I've got a $N\times 3$ matrix $X$ and a 3-level factor $fac$.  In R I could generate the model matrix quite simply:
> set.seed(5)
> X <- data.frame(v1 = rnorm(10), v2 = rnorm(10), v3 = rnorm(10))
> fac <- c(rep("A",2), rep("B", 4), rep("C", 4))
> model.matrix(~ (X$v1 + X$v2 + X$v3):fac - 1)
    X$v1:facA   X$v1:facB  X$v1:facC  X$v2:facA  X$v2:facB  X$v2:facC X$v3:facA  X$v3:facB  X$v3:facC
1  -0.8408555  0.00000000  0.0000000  1.2276303  0.0000000  0.0000000 0.9005119  0.0000000  0.0000000
2   1.3843593  0.00000000  0.0000000 -0.8017795  0.0000000  0.0000000 0.9418694  0.0000000  0.0000000
3   0.0000000 -1.25549186  0.0000000  0.0000000 -1.0803926  0.0000000 0.0000000  1.4679619  0.0000000
4   0.0000000  0.07014277  0.0000000  0.0000000 -0.1575344  0.0000000 0.0000000  0.7067611  0.0000000
5   0.0000000  1.71144087  0.0000000  0.0000000 -1.0717600  0.0000000 0.0000000  0.8190089  0.0000000
6   0.0000000 -0.60290798  0.0000000  0.0000000 -0.1389861  0.0000000 0.0000000 -0.2934818  0.0000000
7   0.0000000  0.00000000 -0.4721664  0.0000000  0.0000000 -0.5973131 0.0000000  0.0000000  1.4185891
8   0.0000000  0.00000000 -0.6353713  0.0000000  0.0000000 -2.1839668 0.0000000  0.0000000  1.4987738
9   0.0000000  0.00000000 -0.2857736  0.0000000  0.0000000  0.2408173 0.0000000  0.0000000 -0.6570821
10  0.0000000  0.00000000  0.1381082  0.0000000  0.0000000 -0.2593554 0.0000000  0.0000000 -0.8527954

Is there a way to do this that relies only on matrix algebra?  Such that I could do something like the following:
facdum <- model.matrix(~fac - 1)
identical(X %?% facdum, model.matrix(~ (X$v1 + X$v2 + X$v3):fac - 1))

Where %?% would be some sort of matrix product?
Answer: The Khatri-Rao product (related to the Kronecker product) can do this. There's an implementation in the Matrix package in R, though I don't think it's been implemented in the %?% "operator" notation (there's nothing to stop you from doing so, however).
I'll assume there's equal numbers of observations per group, as that's extraneous to the point here, and so that you can construct a matrix mapping groups to observations with a single Kronecker product. Thus everything can be done with "standard" matrix operations (a Kronecker product and a Khatri-Rao product).
set.seed(1)
grp <- 3 #number of groups
n   <- 4 #obs per group
k   <- 2 #covariates
Z   <- kronecker(diag(grp), rep(1,n))   #maps groups to observations
X   <- matrix(rnorm(n*grp*k), n*grp, k) #continuous covariates
library(Matrix)
t(KhatriRao(t(X), t(Z)))

#compare to:
fac <- rep(LETTERS[1:grp], each=n)
model.matrix(~fac:X - 1)

Comment: Great, thanks!  The lack of terminology was preventing me from expressing my algorithm in math, and complicating various derivations.  FYI your answer doesn't require that the groups have equal observations -- I don't understand your comment about extra matrix multiplication:  `X <- data.frame(v1 = rnorm(10), v2 = rnorm(10), v3 = rnorm(10));
fac <- c(rep("A",2), rep("B", 4), rep("C", 4));
facdum <- model.matrix(~fac-1);
t(KhatriRao(t(X), t(facdum)))`
Comment: @generic_user Ya, I just meant that if you want to use all known "matrix" operations, you can use the Kronecker product to build the "group design matrix" (Z in my answer). In which case you would need another matrix product to drop rows that you didn't want. If you don't need to express the whole thing as a matrix equation, then definitely `rep(...)` will work fine.
Comment: ... I'll clarify that in my answer.

matrix form of dummy expansion?


What am I missing in basic OLS?

Question: I must first admit that I haven't done stats in a loooong time, but I need to do some rudimentary analyses.  My issue is that my findings just don't "look right," so I want to see if anyone can spot any glaring issues in an OLS model.  My concern is that I have extremely low correlations for everything, even things that I think should be highly related, and the majority of my variables are significant in my model.  Any help would be much appreciated.  My DV is continuous (with a max of 1), my IVs are all nominal or ordinal, with the exception of number of arrests.
Right click on the links below and click "view image" to see.
Valid Correlation
Valid Sum
Valid OLS
Valid RVFPlot
Valid LVR2Plot
Comment: Maybe add the images somewhere that hosts more cleanly?
Comment: I edited your post and fixed the links so they work. Please look at the source so you know how to do it. Or use the link widget (looks like a chain) above the compose window.
Comment: As your question stands now, it is unclear what you are asking. You may have several questions in here that need development on your side. I am pretty sure that your dependent variable requires a transformation, so you can ask "How do I decide if I need a transformation, and how to choose the right one?". If you are concerned with low correlations (I wouldn't be; data are data), you can ask "Do low correlation matter if the final regression is significant?" (and you will probably get a lecture on power analysis in return). And please repost with everything in the question itself.
Answer:
Check how you are coding race in your model.  It looks like you have five values for race and are treating them as a continious variable.  That probably isn't what you want.
You may want to recode gender, fam_support, etc to 0 and 1 (dummy code) to make your coefficients more interpretable.  For that matter, you may want to mean center a number of your variables.
It seems likely that num_arr is not normally distributed or you have an outlier (max 62).  You might want to look at that data more carefully.  In a similar vein, plot everything to sanity check your data.  Your leverage plot seems to suggest a number of data points of concern... look at those more carefully and maybe also consider Cooks D or DFFITs.
Make sure your data is actually independent.
What is the _cons variable, it didn't show up until your regression model results.
Your outcomes are restricted in range between 0 and 1, it may make sense to use a link function (even though it probably won't change things all that much).
Comment: It looks like he's using Stata, where `_cons` is the constant that Stata adds by default to regressions.

What am I missing in basic OLS?


How to select date from date picker using selenium web driver?

Question: I am trying to select date from below calendar. Where there is no td available.Also input field click  tag is visible and if try select it, getting disappear. Now, how can I get locator of date? or how can I select any date from it?

Here is below HTML code snippets.

ngui-datepicker tag is visible on the click on input field.
Comment: Can you right click on the text input file and click "Inspect Element" to bring up the browser debug console? Then maybe you can see the calendar HTML structure show up and manually navigate the DOM in the debugging tool without interacting with the date field anymore?
Comment: Do you know where you go this date picker from?
Comment: At the very least, you may want to specify which language bindings you are using.  Or post some of the code you're written to address the problem...
Comment: @GregBurghardt, input field is there for datepicker only, once you click on it, div gets visible as you can see it in 3rd screen shot but if i try click on that div, it gets vanishes. It doesn't find in DOM.
Comment: Please read why [a screenshot of code is a bad idea](https://meta.stackoverflow.com/questions/303812/discourage-screenshots-of-code-and-or-errors). Paste the code and properly format it instead.
Answer: I assume that it is allowing the user to input the date in the field too as I can see input tag in the screenshot. In that case, you can still use sendtext which input a valid format required which is mm/dd/yyyy in your case. so for that you can use below code
<code>`IWebDriver driver = new ChromeDriver(option);
driver.FindElement(By.XPath("")).SendKeys("06/26/2019");
</code>
If you are not able to input then you need to perform click and then perform key actions as per your requirement. let me know by comment if you need help with a specific scenario with more details what action you want to make I can help
Comment: Thanks Krunal, But i tried sendKeys as well before posting this query. Its not working
Comment: Krunal, i could add date in that input field with below code spinet but when I am trying to save the form, its saying "Required field" where format is correct .

JavascriptExecutor js = (JavascriptExecutor) driver;
  js.executeScript("arguments[0].value ='"+"06/28/2019"+"'",getAddEventFormPerformanceDateInput());
Comment: Did you try using Actions to select a date from datepicker it can be a temporary workaround. You can use tabs to reach datepicker and up and down arrows to select a date. Let me know if you need action codes for tab and other keys. Meanwhile, if your website is hosted, you can give a URL so that I can try and help you better.


Guitar notes: rest vs tie

Question: I'm learning to play the guitar using notes, but there is something I don't completely get (and I haven't seen explanation anywhere).
What is the difference between: a note and a rest of a certain duration vs a note and a tie?
Because usually if you have a rest note the previous note isn't muted, right? So it seems to me that the rest is equivalent to the tie.
Can you you clarify this for me.
Answer: The tie adds duration. A note tied to another note equals both added together. No stopping. (e.g. Two quarter notes tied together equals a half note.) A rest between the two notes means you stop (mute, I guess you could say) and then play it again. It has different purposes.
For more info:
http://en.wikipedia.org/wiki/Tie_(music)
http://en.wikipedia.org/wiki/Rest_(music)
Comment: Just want to clarify here that a tie **does not** add duration, it merely *links* two notes together such that the pitch or sound is sustained through the full duration of each note.  A **dot** adds duration.  Also, a guitarist can still play notes while muted, so if you see a rest, that means to be *silent* for the appropriate duration. In that sense you are stopping the strings from vibrating instead of merely muting them.
Comment: Thanks, I've read the wikipedia pages. But I don't think I've ever saw that you  supposed to stop/mute the sounding strings when having a rest note. Although now, after doing another google search it looks like that's what needs to be done.
Comment: sorry I was little confused with your terminology, so I just explained what I could. btw it's just called a rest. Do you happen to have any sheet music in particular you're wondering about?
Answer: Generally there are three places in written music where a tie will be needed.

Where there is no note shape for a particular note length, as in duration one and three quarter beats. This could be written as a one beat tied to a half beat tied to a quarter (crotchet - quaver- semiquaver).(Yes, I know about double dots, but that's not my point).
Where a long note lasts more than a whole bar. This could be a 6 beat note in 4/4 time, where a semibreve will be tied to a minim.(4 beat - 2 beat)
Sadly going out of  fashion, where there's for instance, a 2 beat note lasting from beat 2 to beat 3 in a 4/4 bar.This bar may be written crotchet - crotchet tied to crotchet - crotchet. The idea being in 4/4 any bar can be split visually into half. This idea shows up 'push' notes.

Rests, on the other hand, are exactly what they say - a 1 beat rest is 1 beat's worth of silence and silence is so important in music.
With guitar, sometimes the rest is superfluous as the note played previously has decayed to silence anyway, and the same thing in reverse with long notes shown with ties.
Comment: In my experience, double dots are pretty rare anyway.  Theoretically they're useful, but if you're sightreading at speed a tied note is much easier to follow.
Answer: With a percussive instrument like a guitar, there tends to be some leeway in the execution of note ends: the score reflects an abstract idea of music that the execution reduces to the perspective of a particular instrument.
Rests may often not be explicitly executed in guitar play.  Depending on what other notes are sustained or played and whether the harmony changes, muting the string at a rest might be appropriate when the sound from that string is not otherwise masked.
A tie, however, is a rather explicit instruction to let the string ring on.  You don't mute, and most importantly, you don't unfinger the note.
Answer: In music notation a note means "make sound" a rest means "don't make sound".  Guitar is not granted an exception to this!
Comment: The question is about the rest and the tie. Not the rest and the note.
Comment: We start with a note.  We either prolong it by tying over to another note or we don't, hence leaving a rest.

Guitar notes: rest vs tie


Find a function $f$ which satisfies $f(mn) = f(m)f(n)$ for positive integers $m,n$ and $f(2)=2$

Question: We are to find a function f which follows the following properties
$$f(mn)=f(m)f(n),\; f(2)=2.$$
I can easily find all the values of $f(2^n)$ but I am confused on how to find for the odd numbers and the primes so as to find the function using induction. Please help.
Comment: Why not use the identity function?
Comment: $f(m)\leq f(n)$ under which assumptions on $m$ and $n$? Obviously, it cannot hold unconditionally.
Comment: John Douma , please elaborate your opinion.
Comment: It's not an opinion, it's a solution. Please finish it by doing your own work.
Comment: If i assume that the function that i am seeking is the identity function, then how can i use induction to check it for all the numbers. I can prove that f(1)  = 1 but assuming f(k)=k to be true i can't figure out how i am to prove f(k+1) is true too.
Comment: You don't need to use induction. You are just looking for a function with those properties. If $f(x) = x$, what can be said about $f(mn)$ and $f(2)$?
Comment: So you mean I do not have to prove it algebrically?
Comment: Is there any way by which we can f(3) using the given conditions with a proof?
Comment: Right. You only have to show that $f(mn) = f(m)f(n)$ and $f(2)=2$
Answer: Let $g:\mathbb{P}\rightarrow \mathbb{R}$ be a given function with $g(2)=2$, in which $\mathbb{P}$ is set of all prime number. Define the function $f:\mathbb{N}\rightarrow \mathbb{R}$ as follow
$$f(n)=\prod_{i=1}^{k}g(p_{i})^{s_i}$$
where $n=\prod_{i=1}^{k}p_{i}^{s_i}$ factorises into distinct prime powers. Then
$$f(mn)=f(n)f(m)$$
and $f(2)=2$. Therefore there is infinitly functions that satisfy in your functional equation.
Hint. This functional equation is called "Multiplicative Arithmetic Functions" and is an important branch of Theory of Arithmetic Functions and also there is a lot of results about this subject.
R Sivaramakrishnan, Classical Theory of Arithmetic Functions, CRC Press


How to get facebook app to work on both example.com and www.example.com?

Question: Right now, if I set my facebook application url to: http://www.example.com, then all requests from http://example.com don't work. If I set the url to just http://example.com from within facebook, then all requests from http://www.example.com don't work.
How can I fix this so it'll work in both places?
Comment: It should work with www.example.com as the website url and example.com in your 'app domains', no?
Comment: @Igy Yes, that was it, the app domain wasn't set, setting it fixed it. Post as answer if you like and I'll accept.
Comment: possible duplicate of [Facebook API error 191](http://facebook.stackoverflow.com/questions/4691782/facebook-api-error-191)
Comment: Voted to merge with the 'standard' 191 error question instead, it's the same fix usually
Comment: @Igy That error is obsolete since I didn't get this error from them. So IMO this question should have its own answer to help people who have this problem in future.
Answer: Setting an app domain in facebook app settings fixed this issue.


How can I implement meteor score when evaluating a model when using the meteor_score module from nltk?

Question: I currently have 2 files, reference.txt and model.txt. These two text files contain original captions and generated captions after training.
Can I simply do the following to obtain the meteor score:
score = nltk.translate.meteor_score.meteor_score(reference, model)
print(np.mean(meteor_score))

I have also looked to https://github.com/tylin/coco-caption but I have no clue how to implement this.
Answer: Lets start by defining terms
Reference: The actual text/ground truth. If there are multiple people generating the ground truth for same datapoint you will have multiple references and all of them are assumed to be correct
hypothesis: The candidate/predicted.
Lets say the 2 people look at an image and they caption

this is an apple
that is an apple

Now your model looked at the image and predicted

an apple on this tree

You can calculate the meteor_score of how good the prediction was using
print (nltk.translate.meteor_score.meteor_score(
    ["this is an apple", "that is an apple"], "an apple on this tree"))
print (nltk.translate.meteor_score.meteor_score(
    ["this is an apple", "that is an apple"], "a red color fruit"))

Output:
0.6233062330623306
0.0

In your case you have to read reference.txt into a list and similarly model predicitons into another. Now you have to get the meteor_score for each line in the first list with the each line in the second list and finally take a mean.


Prevent Roaming profiles from syncing certain elements

Question: I'm somewhat new to the Server 2008 front, and I'm afraid I've hit my first snag:
I've set up roaming profiles, and they appear to be working too well.
Is there a way to limit, ideally on a folder/object basis, what gets synced with a roaming profile?
What I'm trying to do is:
1) stop my roaming profile from syncing desktop layout - I run a dual-screen desktop and a laptop, and it's really annoying to have to reposition everything after logging onto the laptop, because it forces everything onto one screen.
2) stop it from syncing registry variables - specifically, I want Visual Studio to load different setting files on each computer. Currently, the variable that contains that path is getting synced whenever I log in, so I get the settings from whatever box I last logged out from.
3) stop syncing the start menu - this one's not as big, but I'm noticing 'program not found' icons even for programs that are installed. they work when I click them - they just look ugly.
I'm running Windows SBS 2008 x64 with two Win7 clients (x86 Pro, and X64 Ultimate).
Is there a simple way to do that? Or am I trying to work too much against what roaming profiles are designed for?
I could, of course, set up different profiles for the desktop and laptop, but that seems to defeat the point of roaming profiles entirely...
Thanks in advance!
Any help will be much appreciated =)
Comment: Awesome, thanks for the answers =)
I'll post an update once I get a chance to try this out.
Answer: What about just using the Redirected Folders?
Run the "Redirect folders for user accounts to the server" task from the Users and Groups tab of the SBS Console.  From here you can choose Desktop, My Documents, and Start Menu (although you may just want the My Documents).
You can fine-tune what gets redirected in the Group Policy Management Console > "Small Business Server Folder Redirection Policy" and then drill down to User Configuration > Policies > WIndows Settings > Folder Redirection
you should be able to change which folders you want to include there.  May take some trial and error (and gpupdate /force) to get the right folders you want/need as I'm not sure where some of those registry key are located (likely Application Data).
Answer: You can exclude certain things from roaming with the profile. In your case you would want to exclude whatever folder contains those settings.
http://support.microsoft.com/kb/814592
It would not be possible to do with the registry though. You could make a complicated script to accomplish it. Redirecting the Desktop and My Documents folder to a network location and then disabling roaming profiles might be better suited for your direct question, but that is also a drastic change from your current setup.
Answer: Roaming profiles are best used in conjunction with common workstation images or automated deployment tools to allow users to just log into another computer and work.  Generally speaking, the best solution for exception users is to not have their profile roam.
Admins and techs (who log into lots of machines) and executives (or others with custom configurations) aren't good candidates for roaming profiles.  Better to use the folder redirection policy for your documents and manage your desktop and installed apps yourself.


Why can EFB(Exclusive Feature Bundling) works in lightGBM?

Question: As I know, EFB can help you to decrease features which are sparse. They put two features together and add offset every feature in feature bundles. They combine features into same histogram.
After creating histogram, how can it works when finding the best split point?
There is a question, and I can't find answer in the paper. https://dl.acm.org/doi/pdf/10.5555/3294996.3295074
Comment: Nice question (+1) and welcome to CV.SE.
Answer: Given a new feature $Z$ created by merging features $A$, $B$ and $C$ together, feature $Z$ is treated like any other feature. Note that features $A$, $B$ and $C$ can be either categorical or continuous and ideally, all the sparse features will be combined into fully dense features.
More details: LightGBM does not actually work with the raw values directly but  with the discretized version of feature values (the histogram bins).
EFB (Exclusive Feature Bundling) merges together mutually exclusive (sparse) features; in that way it performs indirect feature elimination and engineering without hurting (at face value) the performance of the learner. Non-zero values of each of the constituent features are "almost never" taken simultaneously. To ensure that "almost never" we use an offset value; that offset all but guarantees that the histogram-based algorithm is able to "construct a feature bundle by letting
exclusive features reside in different bins" (direct quote from Sect. 4 from the paper LightGBM: A Highly Efficient Gradient Boosting
Decision Tree (2017) by Ke et al.) Note that EFB is an NP-hard problem (i.e. takes long to solve fully) so LightGBM allows a small number of non-mutually exclusive  points (~0.01% of the total number of points). To re-iterate though: EBF is done once before training (either GOSS or anything else); see this Github issue on How does EBF sort features for bundling? too, I found it very helpful for my understanding of EBF.


Alternating Series: Intervals

Question: can you take a look at the link below where I uploaded a math problem solved by my professor. In part d), how did he arrive to -0.234? The -0.242 is 0.008 + that 0.234, but both intervals are negative. Both interval numbers have confused me, I'd appreciate it if someone could clarify. I would ask him but it's the weekend and I need to understand before I proceed with the problem.
Thank you!
Answer: We are evaluating the sum up to the first 10 terms and we obtain $-0.2346$ since the next term is negative we are over estimating the sum and the lower bound is obtained adding the $11^{th}$ term which leads to $-0.2421$.
The key fact is that the upper sum (even terms) is decreasing and the lower sum (odd terms) is increasing that is for any $n$
$$S_{2}\le S_{4} \le \ldots \le S_{2n}\le S_{\infty} \le S_{2n-1} \le \ldots \le S_{3}\le S_{1}$$
Comment: Got it. Thank you both!!

Alternating Series: Intervals


Como criar tabelas no postgreSQL utilizando geração automática de id de chave primaria?

Question: Quero que me perdoe-me por essa postagem, talvez seja a dúvida de alguém, mas vamos lá...
Eu sei que o programador tem que dominar algumas coisas, e essa coisas são consideradas como trívias, por exemplo; Todo programador tem que saber inglês avançado para não ficar dependendo de cursos e sim de documentação Oficial de uma determinada tecnologia, todo programador tem que saber Orientação Objeto e todo programador tem que saber o básico de SQL, então... Eu não sei de todas essas coisas mais estou aprendendo moderadamente os assuntos.
Eu tinha o costume de criar minhas aplicações no MySQL, mas estou com um cliente que quer fazer de qualquer jeito o sistema no PostgreSQL, com ele não tem conversa, mas hoje fiquei sem emprego e tem surgido esses trabalhos rápidos para fazer, então estou abraçando e preciso muito da ajuda de vocês.
Atualmente estou precisando implementar o sistema de segurança de uma aplicação, e necessário eu criar algumas tabelas com instrução SQL, o projeto que estou fazendo ele já faz muita coisa para mim, e cria algumas tabelas de forma automática, estou usando Spring Boot, porém a parte de segurança é necessário criar as tabelas através de instrução SQL, eu sei fazer sem nenhum problema em banco de dados MySQL, mas da mesma forma que sei fazer em Mysql não sei realizar a criação do banco de dados em PosgreSQL, estou me deparando com erros de sintaxe, e não tenho infelizmente um banco de dados de teste para criar o sistema, eu sei que isso é um enorme erro, mas vou tentar resolver esse problema mais pra frente.
Tentei pesquisar cursos Gratuitos de como criar as tabelas em SQL, mas existem poucas informações na internet em relação a isso, é claro que existem muita informação em inglês, mas não estou conseguindo entender porque ainda estou aprendendo inglês.
As tabelas são justamente essas abaixo, estou tentando criar essas tabelas no PostgreSQL, mas parece que para criar uma chave auto incremento tem que criar ela separadamente, eu fiz algumas tentativas, mas estou com medo que danificar as configurações do banco no servidor Heroku.
CREATE TABLE usuario (
    codigo BIGINT(20) PRIMARY KEY AUTO_INCREMENT,
    nome VARCHAR(50) NOT NULL,
    email VARCHAR(50) NOT NULL,
    senha VARCHAR(120) NOT NULL,
    ativo BOOLEAN DEFAULT true,
    data_nascimento DATE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE grupo (
    codigo BIGINT(20) PRIMARY KEY,
    nome VARCHAR(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE permissao (
    codigo BIGINT(20) PRIMARY KEY,
    nome VARCHAR(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE usuario_grupo (
    codigo_usuario BIGINT(20) NOT NULL,
    codigo_grupo BIGINT(20) NOT NULL,
    PRIMARY KEY (codigo_usuario, codigo_grupo),
    FOREIGN KEY (codigo_usuario) REFERENCES usuario(codigo),
    FOREIGN KEY (codigo_grupo) REFERENCES grupo(codigo)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE grupo_permissao (
    codigo_grupo BIGINT(20) NOT NULL,
    codigo_permissao BIGINT(20) NOT NULL,
    PRIMARY KEY (codigo_grupo, codigo_permissao),
    FOREIGN KEY (codigo_grupo) REFERENCES grupo(codigo),
    FOREIGN KEY (codigo_permissao) REFERENCES permissao(codigo)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Será que alguém poderia generosamente me dizer como ficariam essas tabelas se fossem feitas em PosgreSQL ?
Ao tentar executar a Query  da criação de usuario_grupo deu o seguinte erro;
ERROR:  syntax error at or near "("
LINE 2:     codigo_usuario BIGINT(20) NOT NULL,
                                 ^
********** Error **********

ERROR: syntax error at or near "("
SQL state: 42601
Character: 55

Answer: Para definir um coluna como o auto increment do MySQL use o tipo chamado  serial ou bigserial isso vai criar uma sequence que vai atulizando o número a cada registro inserido.
A DDL da tabela deve ficar dessa forma. O PostgreSQL não trabalha com engines como o MySQL logo pode omitir definição dele.
CREATE TABLE usuario (
    codigo BIGSERIAL,
    nome VARCHAR(50) NOT NULL,
    email VARCHAR(50) NOT NULL,
    senha VARCHAR(120) NOT NULL,
    ativo BOOLEAN DEFAULT true,
    data_nascimento DATE
    PRIMARY KEY(codigo)
);

Documentação postgreSQL
Comment: @wladyband deu algum erro? essa tabela não tem nenhum campo serial.
Comment: @wladyband em tipos inteiros você não especifica o tamanho, pode remover aquele `(20)` depois do `BIGINT`
Comment: será que poderia me dá mais uma ajuda? Como ficaria a tabela usuario_grupo ?
Comment: eu atualizei minha postagem, dá uma olhada por favor   :(
Comment: muito obrigado deu certo.
Answer: No PostgreSQL o AUTO_INCREMENT é sempre feito por meio de SEQUENCES. Quando se usa o tipo numérico BIGSERIAL, um objeto de SEQUENCE é criado implicitamente pelo servidor.

Os tipos de dado serial e bigserial não são tipos verdadeiros, mas
  meramente uma notação conveniente para definir colunas identificadoras
  únicas (semelhante à propriedade AUTO_INCREMENTO existente em alguns
  outros bancos de dados).

Particularmente, eu não sou fã dessas "conveniências" e prefiro ter controle do que está acontecendo.
Sugiro a criação do objeto de SEQUENCE manualmente e recomendo evitar a utilização desses tipos numéricos tais como SERIAL e BIGERIAL:
--
-- PRIMEIRO, CRIA-SE A SEQUENCE MANUALMENTE
--
CREATE SEQUENCE public.sq_pk_usuario START 1;

--
-- CRIACAO DA TABELA COM VALOR DEFAULT
--
CREATE TABLE public.usuario
(
    codigo BIGINT NOT NULL DEFAULT nextval('public.sq_pk_usuario'),
    nome VARCHAR(50) NOT NULL,
    email VARCHAR(50) NOT NULL,
    senha VARCHAR(120) NOT NULL,
    ativo BOOLEAN DEFAULT true,
    data_nascimento DATE,

    CONSTRAINT pk_usuario PRIMARY KEY (codigo)
);


Show whether this linear transformation is one-to-one and onto.

Question: $T:P_2$ $\rightarrow$ $R^3$ is a linear transformation defined by $$T(a+bx+cx^2) =  \left[ \begin{array}{ccc}
2a-b \\
a+b-3c \\
c-a \end{array} \right]$$
This linear transformation is neither one-to-one nor onto, but I don't really get why. I have read the definition of what a one-to-one linear transformation is and what an onto linear transformation is, but I still don't fully grasp the concept. If you could show me why it is neither one-to-one nor onto that would be a big help.
Answer: Hint:First note that as $dim(P_2(R))=3=dim(R^3)$ so $T$ is one one iff T is onto{A linear transformation $T:V\to V$ is one-to-one if and only if it is onto} Now show that $T$ is not one to one by showing that ker(T) is nonzero
Answer: Let
\begin{align*}
  f_0(t) &= 1 & f_1(t) &= t & f_2(t) &= t^2
\end{align*}
and note that $\beta=\{f_0,f_1,f_2\}$ is a basis for $P_2$. Let
$\alpha=\{e_1,e_2,e_3\}$ be the standard basis for $\Bbb R^3$. Then the
computations
\begin{array}{lcrcrcr}
T(f_0) & = & \color{red}2\,e_1    & + & \color{blue}1\,e_2 & + & \color{green}{-1}\,e_3 \\
T(f_1) & = & \color{red}{-1}\,e_1 & + & \color{blue}1\,e_2 & + & \color{green}0\,e_3 \\
T(f_2) & = & \color{red}0\,e_1   & + & \color{blue}{-3}\,e_2 & + & \color{green}1\,e_3
\end{array}
imply that the matrix of $T$ relative to the bases $\alpha$ and    $\beta$    is
$$
[T]_\alpha^\beta=
\begin{bmatrix}
\color{red}2 &\color{red}{-1} & \color{red}0 \\
\color{blue}1 & \color{blue}1 & \color{blue}{-3} \\
\color{green}{-1} & \color{green}0 & \color{green}1
\end{bmatrix}
$$
But $\DeclareMathOperator{rank}{rank}\rank[T]_\alpha^\beta=2$ so $T$ is neither injective nor surjective.
Answer: In the case of a linear transformation (as opposed to a more general function) it is relatively simple to tell whether or not it is one-to-one.

Theorem.  A linear transformation $T$ is one-to-one if and only if the equation $T(v)=0$ has the unique solution $v=0$.

In this case you can see by trial and error (or more systematically if you need to) that $c=a$, $b=2a$ gives a zero vector for your RHS, that is,
$$T(1+2x+x^2)=\pmatrix{0\cr0\cr0\cr}\ .$$
So $T$ is not one-to-one.
Comment: Oh, I see. I was overthinking. So since v is nonzero and T(v) is 0, then T cannot possibly be one-to-one.
Comment: I think I got this now. Thank you!


Combine multiple select queries from one table into a single statement used for exporting to a file while containing unique values between each select

Question: This task that I'm working on is melting my brain a little bit. I'm trying to apply 18 types of select statements each containing specific conditions to get a combined list of accounts to use in an export file. Wondering if it is possible to apply numerous amount of select statements against a single table and select only unique values.
I'm trying to get it so my select statement for conditions row 2 and so forth do not contain accounts that exist in the previous condition statements.
For example... my list looks like this:
1.  3K accounts that are delinquent with BadPhones as Primary.
2.  3K accounts that are delinquent with BadPhones as Secondary.
3.  3K accounts that are delinquent with BadPhones as ANI.
4.  3K accounts that are current with BadPhones as Primary.
5.  3K accounts that are current with BadPhones as Secondary.
6.  3K accounts that are current with BadPhones as ANI.
7.  3K accounts that are delinquent with WrongPhones as Primary.
8.  3K accounts that are delinquent with WrongPhones as Secondary.
9.  3K accounts that are delinquent with WrongPhones as ANI.
10. 3K accounts that are current with WrongPhones as Primary.
11. 3K accounts that are current with WrongPhones as Secondary.
12. 3K accounts that are current with WrongPhones as ANI.
13. 3K accounts that are delinquent with Good Phones as Primary.
14. 3K accounts that are delinquent with Good Phones as Secondary.
15. 3K accounts that are delinquent with Good Phones as ANI.
16. 3K accounts that are current with Good Phones as Primary.
17. 3K accounts that are current with Good Phones as Secondary.
18. 3K accounts that are current with Good Phones as ANI.

And my query to select all the accounts for the file would look like this:
SELECT
a.AccountCode as AccountInformation,
c.LastName InputConsumerLastName,
c.FirstName as InputConsumerFirstName,
LEFT(c.MiddleName,1) as InputConsumerMiddleInitial,
s.Suffix as InputConsumerSuffix,
ad.AddressLine1 as InputStreetAddress,
ad.AddressLine2 as InputStreetAddress2,
ad.City as InputCity,
st.StateCode as InputState,
ad.ZipCode as InputZip,
ad.ZipCode4 as InputZip4,
CONVERT(VARCHAR(8), GETDATE(), 112) as ScrubDate,
p.cp_PhoneNumber as PhoneNumber
FROM
Account a
LEFT JOIN Customer c on a.XID =c.AccountXID
LEFT JOIN Suffix s on c.SuffixXID=s.XID
LEFT JOIN AccountAddress aa on a.XID=aa.AccountXID
LEFT JOIN Address ad on aa.AddressXID=ad.XID
LEFT JOIN State st on ad.StateXID=st.XID
LEFT JOIN AccountPhone ap on a.XID=ap.AccountXID
LEFT JOIN Phone p on ap.PhoneXID=p.XID
WHERE aa.AddressTypeXID=1
AND ISNUMERIC(p.cp_PhoneNumber)=1
AND p.cp_PhoneNumber!='3201111111'
AND ISNUMERIC(p.AreaCode)=1
AND CAST(AreaCode as int)>=200

But I need to select the 3K samples each meeting their own conditions and then compile it all into a single select without having duplicate AccountCode.
I'm not worried about the specific where conditions to be applied to each type of select. My concern is selecting the total amount of 54K unique accounts containing each of the 18 conditions that select 3K accounts to total the 54K unique accounts.
Any ideas would be appreciated. Thank you.
Comment: The complexity of this problem is far beyond what SQL is designed for. What if the "first" batch randomly picks all the matches for the "second" batch (that can no longer be met), yet a different set matching the first criteria does exist? You probably need to rethink your requirements.
Answer: Create a temp table. Add an index on the AccountCode column in the temp table. Insert "TOP 3,000" into the temp table for the first select. For subsequent selects, use a "where not exists" checking to make sure the AcccountCode is not already represented in the temp table. Finally, export your 54k rows from the temp table.
Comment: I'm going to try using this approach.


Finding $pdf$ of $V=X+Y$ where $X$~$unif(0,1)$ and $f_Y(y) =e^{−y}I_{(0,\infty)}(y)$

Question:
Consider independent random variables $X$ and $Y$, where $X$ has a
  uniform $(0,1)$ distribution and $Y$ has $pdf$ $$f_Y(y)
 =e^{−y}I_{(0,\infty)}(y)$$
Give the pdf of $V=X+Y$.

I found a similar problem here but I would like to make sure I am applying it correctly to this problem.
In the case that $v \geq 1$ we have
$$\begin{align*}
F_{X+Y}(v)
&= \int_0^1 \int_0^{v-x} e^{-y}dydx \\\\
&= \int_0^1 -e^{-y} |_0^{v-x}dx \\\\
&= \int_0^1(-e^{-(v-x)}-(-e^0))dx \\\\
&= \int_0^1 (-e^{-v}e^x+1)dx \\\\
&= (-e^{-v}e^x+x) |_0^1 \\\\
&= (-e^{-v}e+1)-(-e^{-v}e^0+0) \\\\
&= -e^{-v+1}+e^{-v}+1 \\\\
\end{align*}$$
And so differentiating, I get that
$$f_{X+Y}(v)=e^{-v+1}-e^{-v}$$
In the case that $v\in(0,1)$ we have
$$\begin{align*}
F_{X+Y}(v)
&= \int_0^v \int_0^{v-x} e^{-y}dydx \\\\
&= \int_0^v -e^{-y} |_0^{v-x}dx \\\\
&= \int_0^v(-e^{-(v-x)}-(-e^0))dx \\\\
&= \int_0^v (-e^{-v}e^x+1)dx \\\\
&= (-e^{-v}e^x+x) |_0^v \\\\
&= (-e^{-v}e^v+v)-(-e^{-v}e^0+0) \\\\
&= -1+v+e^{-v}\\\\
\end{align*}$$
And so differentiating, I get that
$$f_{X+Y}(v)=1-e^{-v}$$
So the $pdf$ would be a piecewise function looking like
$$ f_{X+Y}(v)=
\begin{cases}
1-e^{-v} & 0 \lt v \lt 1 \\
e^{-v+1}-e^{-v} & v \ge 1
\end{cases} $$
Comment: Wolfram can do that too, but it can be tricky to ask it in the right way. I just got it to work (and it's right btw).
Comment: I have added an alternate proof.
Comment: Also, is there an integration calculator that I can use to check the integration in the case where the solution is in terms of a variable v?
Comment: Looks right to me.
Comment: You mean to check if the result integrates to 1? Try wolframalpha.com
Comment: Oh, I suppose I could do that. I meant is there a way to check that, say, $\int_0^v \int_0^{v-x} e^{-y} dydx$ results in $-1+v+e^{-v}$. But I suppose checking that the density integrates to 1 would also verify that.
Comment: I got that $\int_0^1 v(1-e^{-v})dv \neq 1$. Does that mean I made an error
Comment: Oh wait, should it be the sum of the two densities that equals 1, since it's piecewise?
Comment: @John H Yes of course.
Comment: I got that that is 1.5.
Comment: The function you suggest as PDF integrates to $1$ since $$\int_0^1(1-e^{-v})dv=(v+e^{-v})^1_0=1+e^{-1}-1=e^{-1}$$ and $$\int_1^\infty (e^{-v+1}-e^{-v})dv=(e^{-v}-e^{-v+1})^\infty_1=1-e^{-1}$$
Comment: Oh, I thought that you had to multiply by $v$ within each integral
Comment: No, actually your lecture notes should mention that $$\int_\mathbb Rf_V(v)dv=1$$ and $$\int_\mathbb Rvf_V(v)dv=E(V)$$
Comment: Oh you're right. Was going off memory. Thanks!
Answer: Here is an alternate proof :
The pdf of the sum of two independant random variables is equal to the convolution of their pdfs, say $\varphi$ and $\psi$ under the form:
$$f_{X+Y}(v)= \int \varphi_X(v-y)\psi_Y(y)du=\int 1_{[0,1]}(v-y)1_{[0,+\infty)}e^{-y}dy=$$
$$= \int_{\max(v-1,0)}^v e^{-y}dy=[-e^{-y}]_{\max(v-1,0)}^v=e^{-\max(v-1,0)}-e^{-v}$$
whence your result.
Now, how can we check it ? One of the best ways to test a pdf is to use simulation.
Here is the result showing an excellent fit between theory (red curve) and experiment (histogram on one million samples):

Here is the Matlab program that has generated the figure (note that the standard exponential distribution is equivalent with $-\ln(U)$ where $U$ is a uniform variable on $[0,1]$):

clear all;close all;hold on
n=1000000;set(gcf,'color','w');
S=rand(1,n)-log(rand(1,n));
hist(S,100)
u=0:01:1;v=1:0.01:7;
M=145000;
plot(u,M*(1-exp(-u)),'r')
plot(v,M*(exp(-v+1)-exp(-v)),'r')


Lifetime estimation - Weibull vs Survival

Question: Survival analysis is mainly about estimating the lifetime of nearly anything or even anything:

And Weibull analysis is also about estimating the lifetime:

How are they different (in general) and which should be used when?
Answer: If the failure times have a distribution $F(t)$ then the corresponding survival function is $S(t)=1-F(t)$. That's a critical thing to keep in mind.
The Weibull plots are just plots of a transformed $F(t)=1-S(t)$ against the log of time. So the Weibull plot is just a particular replotting of the survival curve.
A Weibull model can be written in the form:
$$\log T= \alpha + \sigma W, $$
where $W$ has a minimum extreme-value distribution and $\sigma$ is a scale factor. The y-axis transformation of $F(t)$ in a Weibull plot gives a straight line if the underlying distribution $W$ is minimum extreme-value. If there is a well fitting line, then the values of $\alpha$ and $\sigma$ can be deduced from the plot.
My sense is that the plots were most important before modern computational technology became available. I don't see that there's anything they do that can't be done with more general survival modeling, which doesn't restrict you to a Weibull form. You can always generate a Weibull plot from your survival model if you want to.
Comment: thank you very, very much! You've helped me so much recently, I really appreciate!


How to pass parameter in webstart/browser mode in Javafx2

Question: I have read the material on how to do this but I'm stuck trying to figureout how to pass a parameter to my JavaFX2 application with in browser mode or webstart mode.
I've asked the question on OTN forums also here
So I imported ColorfulCircles project from the Ensemble into Netbeans.  Then I modified the code and put in a small snippet to pull a parameter after init method, like so. I just get the parameter and set it as title for the stage.
                @Override public void start(Stage primaryStage) throws Exception {
                init(primaryStage);

                Parameters params = getParameters();
                String myTitle = params.getNamed().get("myTitle");
                primaryStage.setTitle(myTitle);

                primaryStage.show();
                play();
                }

I then did a clean and build in netbeans...all html, jar, jnlp etc was generated.
I then manually modified the HTML as shown below.  But the title for the stage doesnt update/show, for either modes.
What is missing here?

Test page for ColorfulCircles

              Webstart: click to launch this app as webstart

Comment: getParameters() is JavaFX2 API call
Comment: Given `getParameters()` is not an applet method, I can safely say I have no idea what it does or how it works.  For better help sooner, post an [SSCCE](http://sscce.org/).
Answer: That was fixed in JavaFX 2.2 you can try developers version here: http://www.oracle.com/technetwork/java/javafx/downloads/devpreview-1429449.html
But make sure you regenerate your html/jnlp files using new ant-javafx.jar  (or copy them from samples)


Confusion about tensor fields taking values in vector fields rather than functions

Question: I'm beginning with tensorial calculus and I have some questions. Let $(M,g)$ a riemannian manifold with $\nabla$ his Levi Civita connection. The curvature tensor $R$ is defined as
\begin{align*}
R : \mathfrak{X}(M) \times \mathfrak{X}(M) \times \mathfrak{X}(M) &\to \mathfrak{X}(M)\\
(X,Y,Z) &\mapsto R(X,Y)Z
\end{align*}
where
$$R(X,Y)Z = \nabla_X \nabla_Y Z - \nabla_Y \nabla_X Z - \nabla_{[X,Y]}Z.$$
In all books of differential geometry, they said that $R$ is a $(1,3)$ tensor but I don't know why, because a $(1,3)$ tensor is a multilinear map
$$\Omega^1(M) \times \mathfrak{X}(M) \times \mathfrak{X}(M)\times\mathfrak{X}(M) \to C^\infty(M).$$
I think that I don't understand any concept or because for example, let $X \in \mathfrak{X}(M)$, then $\nabla X : TM \to TM$, $(\nabla X)(v_p) = \nabla_{v_p}X$, is a $(1,1)$ tensor field and I don't know why.
$\textbf{Remark}$: $\Omega^1(M)$ is the set of all 1-forms, $\alpha : M \to TM^*$.
Answer: A $(p, q)$-tensor field on a smooth manifold $M$ is a $C^{\infty}(M)$-multilinear map $T : \Omega^1(M)^p\times\mathfrak{X}(M)^q \to C^{\infty}(M)$.
Given a $C^{\infty}(M)$-multilinear map $S : \Omega^1(M)^p\times\mathfrak{X}(M)^q \to \mathfrak{X}(M)$, there is an associated $(p + 1, q)$-tensor field $T : \Omega^1(M)^{p+1}\times\mathfrak{X}(M)^q \to C^{\infty}(M)$ defined by
$$T(\beta, \alpha^1, \dots, \alpha^p, X_1, \dots, X_q) := \beta(S(\alpha^1, \dots, \alpha^p, X_1, \dots, X_q)).$$
Likewise, given a $C^{\infty}(M)$-multilinear map $S : \Omega^1(M)^p\times\mathfrak{X}(M)^q \to \Omega^1(M)$, there is an associated $(p, q + 1)$-tensor field $T : \Omega^1(M)^p\times\mathfrak{X}(M)^{q+1} \to C^{\infty}(M)$ defined by
$$T(\alpha^1, \dots, \alpha^p, Y, X_1, \dots, X_q) := (S(\alpha^1, \dots, \alpha^p, X_1, \dots, X_q))(Y).$$


How to create a column view in Emacs Lisp?

Question: I'm writing my own mode in Elisp. It's basically a simple crud application showing rows of data which can be manipulated via the minibuffer. I'd like to create a view for these rows which looks like the emacs package manager: columns of data nicely aligned. What's the best way to implement such a view?
Answer: The answer from phils got me on track. There are no tutorials or simple examples anywhere though, so I created one. Here is an example of a tabulated-list-mode derivative which has static data and can print the ID of the current column:
(define-derived-mode mymode tabulated-list-mode "mymode" "Major mode My Mode, just a test"
  (setq tabulated-list-format [("Col1" 18 t)
                               ("Col2" 12 nil)
                               ("Col3"  10 t)
                               ("Col4" 0 nil)])
  (setq tabulated-list-padding 2)
  (setq tabulated-list-sort-key (cons "Col3" nil))
  (tabulated-list-init-header))

(defun print-current-line-id ()
  (interactive)
   (message (concat "current line ID is: " (tabulated-list-get-id))))

(defun my-listing-command ()
  (interactive)
  (pop-to-buffer "*MY MODE*" nil)
  (mymode)
  (setq tabulated-list-entries (list
                (list "1" ["1" "2" "3" "4"])
                (list "2" ["a" "b" "c" "d"])))
  (tabulated-list-print t))

Answer: If you look at the code for the package listing function you mention, you'll see that it employs package-menu-mode which derives from tabulated-list-mode.

M-x find-function RET package-menu-mode RET
C-hf tabulated-list-mode RET
Answer: I use org-mode for this kind of task all the time.
This should be a starting point for your development, because you already have nice tables.
Answer: In addition to tabulated-list there is tblui.el, which provides tblui-define a macro that will create a derived major mode of tabulated-list-mode, fairly rapidly.
As well as making it easier to get the table view, it also provides a simple way to integrate with magit popup. So you can add quick shortcut keys and group them by actions.  So creating a tabulated list based 'app' is simpler.
Here's a simple example...
(tblui-define ocodo/gh-run-list-tblui
              "GitHub Workflow Runlist"
              "Display workflow runs in a tabulated list."
              ocodo/gh-run-list-entries-provider
              [("startedAt" 15 nil)
               ("url" 1 nil)
               ("status" 10 nil)
               ("event" 10 nil)
               ("workflowName" 15 nil)]

              ((:key "w" ;; tiny popup
                :name browse-row-url
                :funcs ((?W "Browse URL for current run" ocodo/gh-run-list-browse-row-url)))))

The entries must be provided by a function, we're using
(ocodo/gh-run-list-entries-provider)

Which fetches and transforms a github JSON run list, and makes it usable for tabulated-list (more on this below.)
Popup functions, we also have the tiny popup definition, which calls a function that opens a url at row.
(defun ocodo/gh-run-list-browse-row-url ()
  "Open the url for the current row."
  (interactive)
  (shell-command-to-string
   (format "open \"%s\""
           (elt (tabulated-list-get-entry) 1))))

tabulated-list provides the functions you need to get the row entries or row id  at point:
(tabulated-list-get-entry) and (tabulated-list-get-id)
Use (elt n entry) to get the content at column n (zero based)
Transforming data
I won't delve too deeply into transforming JSON into tblui entries.
But the tl;dr is, you'd map from (output of (json-parse-string JSON-STRING)) a vector of alists, converting to a list of lists containing an entry id (car) and a vector of column values (cdr).
The columns we define will need to match the column positions of values in a row vector.  So, in our example row entries be like this:
;;(id [vector of col values])
(list 0 ["10m ago" "https://github.com/org/repo/actions/runs/60324234205" "completed" "push" "MyFlow"])

Structurally:
(list
  (list 0 [... column values ...])
  (list 1 [... column values ...])
  (list 2 [... column values ...])
  (list 3 [... column values ...])
  ;; ... etc ...
)

https://github.com/Yuki-Inoue/tblui.el
https://www.gnu.org/software/emacs/manual/html_node/elisp/Tabulated-List-Mode.html -- For all the functions available for the tabulated list view which tblui creates.


Question about understanding the tab of guitar

Question: I just bought a guitar today and try to play with it. However, I found I have a problem of understanding the note of tab.

Under G, I do not know what does "3-vertical line-x" mean.  I am thinking if it wants me to play String E, A, D, G, B at the same time and my left hand should press on the String B on the fret 3?
Also, under Am, what does 3 mean here?
Thank you so much.
Heis
Comment: This tab is too advanced for beginner. There are plenty of advice for beginners on the internet [for example](https://blog.udemy.com/easy-guitar-tabs/)
Comment: This appears to be a blend of tab notation and staff notation, and along the lines what some of the guitar tab software like Guitar Pro 5 use. I am a relative newbie too, and stick to the easier form of guitar tabs, and my (human) teacher.
Answer: The "3" under the Am indicates a triplet, where three notes are played with the time value of two notes. The "3" under the G indicates the note at the third fret of the B string, which is D in a standard tuning and fits the G chord nicely. The "X" under that three suggests to me that the bass note of that chord is played in a muted or damped fashion; since no fret number is provided, I would recommend the chord root G on the third fret of the E string.
Above all, the best bet is listen closely to the music and attempt work out the unknown bits on your own. This will help train your ears, your mind, and allow you to readily transcribe future music. Enjoy!
Comment: I'm not sure your first sentence answers her question, and its probably a  bit complicated for someone just starting out?
Answer: Usually with tab, a 'x' means mute the note, so it sounds like a dull thud rather than a proper sounding note - like you may do lots of the time as a beginner! This tab is being helpful in that it shows the note values (lengths) too. That's why the vertical line is there, it's one beat long.Two lines joined together are half a beat each, and as Kirk says, with a '3' under or over, 3 will be played in the time of two - triplets.
Having said that, it may be that the 'x' is what you actually play whilst holding down the chord as shown. Incidentally, the chord 'F7' in the 1st window should be called Fmaj7, slightly different, as the top string shows an open E note, not found in 'F7'.
You will learn over time that a heck of a lot of tab available on the internet is inaccurate, to say the least. Trust your ears more than tab!


Como usar a referencia de um arquivo de um barrel na mesma pasta com Typescript

Question: Estou tendo problemas em fazer a referência de arquivos que estão na mesma pasta quando trabalhando com um arquivo do tipo barrel no meu projeto é em Angular (versão: ^4.0.0). Meu problema é o seguinte, vejam a estrutura de arquivos e diretórios abaixo:
|-app
   |-index.ts
   |-app.module.ts
   |-app.routes.ts
   |-app.component.ts
   |-foo
      |-index.ts
      |-foo.module.ts
      |-foo.routes.ts
      |-foo.component.ts

os dois arquivos do tipo index, contém uma estrutura simples de arquivos "barrel", como mostra aqui:
app/index.ts
export * from './app.module';
export * from './app.routes';
export * from './app.component';

app/foo/index.ts
export * from './foo.module';
export * from './foo.routes';
export * from './foo.component';

Meu problema é, quando estou em qualquer arquivo dentro do diretório app, consigo chamar uma referência do barrel de foo, assim:
app.module.ts

import { FooRoutes, FooComponent } from './foo' // -> vai reconhecer o barrel
...

Mas se eu dentro do diretório app/foo tentar buscar um arquivo existente no próprio barrel dele da erro, diz que não foi possível encontrar o elemento (retorna undefined). Serial algo como:
foo.module.ts

import { FooComponent } from '../foo' // -> não acha
import { FooComponent } from '..' // -> não acha
import { FooComponent } from 'foo' // -> não acha
//wtf???
...

Alguém pode me ajudar a resolver esse problema?
Comment: `import { FooComponent } from './foo'` também não funciona?
Comment: Acho que cria uma dependence circular importar do barrel de um arquivo que tbm esta declarado no barrel.
Answer: A solução era a forma que eu estava declarando a importação porque eu deveria usar a mesma lógica para navegação entre pastas onde . representa que estou buscando algo no mesmo diretório e .. no diretório anterior. Ficaria assim então:
import { FooComponent } from '.'; // funciona
import { FooComponent } from './index'; // também funciona


What is the easiest way to automate Excel tasks

Question: If I need to automate a series a task on an excel sheet like

remove all rows where column 3 contains value "asdf"
remove column 7 and column 9
sort according to column 4

etc.
What is the easiest way of automating such tasks in excel? I think it would recording a macro but sometimes macro have to be edited a lot to actually make them work and even then macros stop if the excel sheet has a variation. Editing macro scripts could be a time taking process which becomes inefficient for such tasks. The automation is required since number of excel sheets will be a lot. Can you suggest an easier way ?
Answer: As long as, you have the activities defined - Macro is still the better thing to look for.
There could be some things that could change.
Please explain the problem with the help of code.
If you have defined the steps with a few variables, it should be easy to write a macro that wouldn't stop in case of variation.
Please post the code and describe in detail what you would want? which point does it stop, in case of variation? What would you like the code to do?
EDIT: Alternatively, you can write code in VB6/.net (c#/vb.net)/Python for automation.
Answer: If you record these steps using the macro recorder it will work fine, these are the ideal types of things for the macro recorder as the parameters (i.e. your sort by and delete conditions) are always the same. Just make sure that you always import/paste the data to the same place!
Thanks
Ross


How do we prove that $\int_{0}^{\infty}\frac{\mathrm{d}x}{x^{2} + 7}$ converges?

Question: Tell if the following improper integral converges or not.
$$\int_0^{+\infty} \dfrac{1}{x^2+7}\ \text{d}x$$
I know that a necessary but not sufficient condition is that $\lim_{x\to +\infty} f(x) = 0$. Here this holds, so the integral might converge.
Now, I thought of the comparison:
$$\int_0^{+\infty} \dfrac{1}{x^2+7}\ \text{d}x < \int_0^{+\infty} \dfrac{1}{x^2}\ \text{d}x$$
Since the second integral diverges, and the first one is $<$, it converges.
Is this method valid?
Comment: Yes, your solution is the simplest. I suggest you [edit it as an answer to your own question](https://math.stackexchange.com/help/self-answer).
Comment: Incidentally, it is *not* a necessary condition for convergence of an improper integral that $\lim_{x\to \infty} f(x) = 0$, in general.  (Though it is necessary for a nonnegative and decreasing function $f$.)
Comment: No. To prove convergence this way you need to find a larger integral that _converges_, Hinr: why/where does the second integral diverge? Can you fix that?
Comment: @EthanBolker Can I say that $$\dfrac{1}{x^2+7} < \dfrac{1}{x^2+1}$$ and then conclude? The integral of $\dfrac{1}{x^2+1}$ is the arctangent so it's convergent
Comment: Oh, sorry, I meant diverges.
Comment: @AnneBauval Thank you!!
Comment: Indeed, [look](https://math.stackexchange.com/questions/370317).
Comment: @DanielSchepler Oh, I did not know. On my notes it was underlined as necessary... Thank you for having specified when it really is. Also, say I have $$\int_1^{+\infty} \dfrac{e^x}{(x+4)^2}\ \text{d}x$$

In this case, does noticing that $\lim_{x\to +\infty} f(x) = +\infty$ straightly tell me that the integral diverges instead?
Comment: Yes, it's true that if $\lim_{x\to \infty} f(x) = \infty$, then $\int_a^\infty f(x)\,dx$ converges.  And also, if $\lim_{x\to \infty} f(x) = L \ne 0$, then $\int_a^\infty f(x)\,dx$ diverges.  It's when $\lim_{x\to \infty} f(x)$ does not exist that it's still possible for $\int_a^\infty f(x)\,dx$ to converge.
Comment: @DanielSchepler I'm confused: when as $x\to +\infty$, $f(x) \to \infty$, the integral converges or diverges?
Answer: According to your efforts, I would recommend you to split the integral into two parts as follows:
\begin{align*}
\int_{0}^{\infty}\frac{\mathrm{d}x}{x^{2} + 7} & = \int_{0}^{1}\frac{\mathrm{d}x}{x^{2} + 7} + \int_{1}^{\infty}\frac{\mathrm{d}x}{x^{2} + 7}
\end{align*}
The first part is integrable because its argument is a continuous function on the compact interval $[0,1]$, hence uniformly continuous and integrable. The second part is also integrable. That is because we can apply the monotonicity of the integral to conclude that:
\begin{align*}
\int_{1}^{\infty}\frac{\mathrm{d}x}{x^{2} + 7} < \int_{1}^{\infty}\frac{\mathrm{d}x}{x^{2}} = -\frac{1}{x}\bigg\rvert_{1}^{\infty} = 1 < + \infty
\end{align*}
Hopefully this helps!
Answer: In a simpler way, we can say
$$\dfrac{1}{x^2+7} < \dfrac{1}{x^2+1}$$
Thence
$$\int_0^{+\infty} \dfrac{1}{x^2+7} \text{d}x < \int_0^{+\infty} \dfrac{1}{x^2+1}\ \text{d}x$$
The second integral gives the arctangent function which evaluates to $\pi/2$. Hence
$$\int_0^{+\infty} \dfrac{1}{x^2+7} \text{d}x < \dfrac{\pi}{2}$$
Whence it converges.
To prove that the integral of $\dfrac{1}{x^2+1}$ converges indeed, see @Atila Correia's answer!
Comment: Your last sentence is kind but inappropriate. You already proved "that the integral of $\frac1{x^2+1}$ converges indeed"!
Answer: For $a>0$ we have  $$\int\limits_0^\infty {1\over x^2+a^2}\,dx=
{1\over a}\arctan\left ({x\over a}\right )\bigg\rvert_{0}^{\infty}={\pi\over 2a}$$
In OP case we have $a=\sqrt{7}.$


How to track Drupal user login-logout session length and registration activities?

Question: Is there any hook_function/code in Drupal where I can track user activity, like:

User core logged in time / or third party login
User log out time
Login-Logout session length (active time)
registration submit core or / third party submit.

Please share event for these activity.
Comment: Try hook_user_login and hook_user_logout for 1 and 2
Comment: thanks, but same will work if I logged in using 3rd party apps like fb/G+
Comment: I think it will work
Answer: For standard login, and 3rd-party login modules that are properly integrated with core, you can use:

hook_user_login()
hook_user_logout()
hook_user_insert()

For 3rd-party login modules that aren't properly integrated with core (i.e. don't fire those hooks), you'll need to approach each on a case-by-case basis, and find out what hooks they provide.
You could measure the duration of the session in hook_user_logout, by checking the account object's login property against the current time -  there's no hook for such a thing as it's not an event, just a value which needs some context to give it meaning.
Answer: Have a look at the Event log module (a module also consists of "Drupal code", right?). Some details about it, from its project page:

This module logs specific events. The events are saved in the database and can be viewed on the page admin/reports/events. Furthermore, a views integration is provided in which you can relate for instance a node to its events. You could use this to display the total number of views, or the number of times that the node has been modified and by which users.
Currently, the following events are supported:

User authentication (login/logout/request password)
Node operations (CRUD)
User operations (CRUD)
Menu operations (custom menu's and menu items CUD operations)
Taxonomy operations (vocabulary and term CUD operations)

The event log can be easily extended with custom events. For more information please have a look at the API documentation and the available sub modules.

You are probably going to be interested in these specific events and facilities of it:

User authentication.
User operations (CRUD).
... log can be easily extended with custom events.
Views integration.
API documentation.
The available sub modules.


Firefox displaying negative margin incorrectly

Question: My layout is working correctly, but not in Firefox. I am using a negative margin to indent the top and the bottom of the green box behind the YouTube video.
Here is how it should look:

Here's how it looks in Firefox:

Here's a live version to look at: live site
Here's a js fiddle of the relevant code: jsfiddle
I originally forgot to mention that the height is variable, because there will be different types of videos and photos within the .frame class. Is there any way to solve this Firefox problem without defining the height?
I'm also open to re-organizing this if there's a better way to write it and get the same effect.
Comment: IE9 standards mode gets it "wrong" too, IE9 'IE8 standards'  mode and compatibility view get it "right" ;))
Answer: If you set the height of the green box it seems to sit fine.
<code>.framewrap-gr { height: 390px; }
</code>
I only say this because your iframe height seems fixed.

After comment
I would recommend changing how you built it. Keep a container div, put a bg div and video div inside of it, z-index the video on top of the bg layer and style the bg layer how you need it (relative to their parent)
Comment: Ah! I forgot to mention, that there will be different videos and photos in the .frame so the height needs to be variable. Sorry.
Comment: Hmm... I am trying to layer the background color and video using z-index. I am having trouble getting the height of the background to be limited by the height of the video. Maybe I should write a new question.
Answer: Take:

Watch more videos on our YouTube Channel

out of the  and put it just below
That fixes it for me, you'll then just need to shift the h4 to the left a bit which should be easy enough.
Hope that helps, below is the copied code
Martyn
Edit:
Leave the HTML alone, and change the css for: h4.caption to
<code>h4.caption{
display:table;
padding-right:5px;
text-align:right;
width:100%;
}
</code>
Comment: oh also, I noticed on firefox the menus, about our goods, find our... are slighly low in the boxes. take the padding out of .ffnav a and add in: line-height:30px; or how ever many px you want, the box will resize and middle align the text for you
Comment: I see what you mean, but the width of the video is also variable. So I am using the captionwrap to right-align the "watch youtube channel" text to the right edge of the video.
Comment: edited so it affects just the css. This also seems to work, it's stopping the framewrap-gr div expanding over the h4
Comment: This works!!! Thank you thank you thank you! So glad I don't have to rework everything.
Answer: here is your css:
<code>.framewrap-gr, .framewrap-fb, .framewrap-map {
-moz-border-radius: 10px;
border-radius: 10px;
margin: 50px 0 80px 0;
position: relative;
</code>
}
Try do it:
<code>.framewrap-gr, .framewrap-fb, .framewrap-map {
-moz-border-radius: 10px;
border-radius: 10px;
margin: 50px 0 80px 0;
position: relative;
margin-bottom: -15px;
</code>
}
It can work, but if it doesnt, check what firebug says to you!
Sorry for the bad english, I'm Brazilian.


Bernoulli distribution on i.i.d. random variables

Question:
Let $(X_n)$ be an independent and identically distributed sequence of random variables with distribution Bernoulli of parameter $p$, this is $\mathbb{P}(X_i = 1) = p$, $\mathbb{P}(X_i = 0) = (1−p)$. Set $T_0 = 0$ and for all $n\ge1$, define recursively
$T_n :=\inf\{k>T_{n−1} :X_k =1\}$.

Show that the random variables $T_1, T_2 − T_1,..., T_n − T_{n−1}$ are independent and identically distributed.
Compute the generating function of $T_1$, and deduce the generating function of $T_n$.

My attempt: First is it right that $\mathbb{P}(T_1 = k) = p(1 − p)^k$ for $k\ge0$?. In this case we would have that
$\mathbb{P}(T_2−T_1=k)=\mathbb{P}(T_2=k+T_1)=\sum^\infty_{j=0}\mathbb{P}(T_2=k+j,T_1 =j)
=\sum^\infty_{j=0}p(1−p)^kp(1−p)^j =p(1−p)^k$
Then: $\mathbb{P}(T_2−T_1=k,T_1 =j)=\mathbb{P}(T_2=k+j,T_1 =j)=p(1−p)^kp(1−p)^j$
which shows that these random variables are independent.
Does this suffices to say that all $T_i, i=1,...,n$, are independent iteratively? Or do I have to do a (I would say complicated) rigorous proof by induction?
For point 2) first I'm not sure I got the right probability in the first part. Can anyone tell me something please?
Answer: Your approach for 1) is correct but you will have to handle $T_1,T_2-T_1,...,T_n-T_{n-1}$ in a similar fashion.
Note that $T_1=\inf \{k >0: X_k=1\}=\inf \{k \geq 1: X_k=1\}$. So the correct pmf of $T_1$ is given by $P(T_1=k)=p(1-p)^{k-1}$ for $k \geq 1$. Hence, $Es^{T_1}=\sum\limits_{k=1}^{\infty}s^{k} p(1-p)^{k-1}$. This is a geometric series with common ratio $(1-p)s$. Can you write down the sum?
Finally, $Es^{T_n}=Es^{T_1+(T_2-T_1)+\cdots+ (T_n-T_{n-1})}=E(e^{T_1})^{n}$.


Python - how to get executable program to get the windows file browser to pop up for user to choose an excel file or any other document?

Question: The program would follow the below steps:

Click on executable program made through python
File explorer pops up for user to choose excel file to alter
Choose excel file for executable program to alter
Spits out txt file OR excel spreadsheet with newly altered data to same folder location as the original spreadsheet
Comment: Windows Explorer isn't made for selecting files; that's what file open dialogs are for. You're going to need some kind of GUI library.
Comment: Hi @Rawing, I was referring to a pop up such as the following image: https://learn.microsoft.com/en-us/windows/uwp/files/images/picker-multifile-600px.png
Answer: Yes this is perfectly doable. I suggest you look at PyQT5 or TkInter for the user interface, pyexcel for the excel interface and pyinstaller for packaging up an executable as you asked. There are many great tutorials on all of these modules.
Comment: Thank you @StuartBuckingham. Firstly, I've just begun self-learning Python and have many questions, apologies in advance if they may seem very basic haha. In regards to PyQT5 and TkInter, I have looked into both packages and they definitely have to do with the UI but there doesn't seem to be a feature where I am prompted to search through my windows explorer to identify the excel spreadsheet I require. For example, it would look like the following image: https://learn.microsoft.com/en-us/windows/uwp/files/images/picker-multifile-600px.png.
Comment: Here's a full tutorial on file dialogs. https://pythonspot.com/en/pyqt5-file-dialog/ Please try searching for this material instead.
Comment: Thanks @StuartBuckingham. TkInter script I came across has helped tremendously. Appreciate the answers of course. What a collaborative community. I will continue to search for more material instead.
Comment: Good luck @Ajo. If my answer helped, click the green tick and upvote the answer please.


Nginx rewrite using $args to create a shorter url with parameters

Question: My scenario is this:
For 20+ years I've used the following URL for search result on a old website:
https://www.example.com/cgi-bin/website.cgi?type=search_result&query=examplequery
https://www.example.com/cgi-bin/website.cgi?type=search_result&query=examplequery&page=72

I would like to start using a new, shorter url for search results, like this:
https://www.example.com/?q=examplequery
https://www.example.com/?q=examplequery&p=72

I would also like the old URLs to permanent redirect to the new URL, if possible.
This is what I have tried, after searching for a solution (this is in the location block in nginx.conf).
if ($args ~ "^/?q=val1&p=val2") {
   rewrite ^ /cgi-bin/website.cgi?type=search_result&query=$arg_q&page=$arg_p? last;
}
if ($args ~ "^/?q=val1") {
   rewrite ^ /cgi-bin/website.cgi?type=search_result&query=$arg_q? last;
}

For some reason, this is not working. I don't get any error.
In order to redirect old urls to the new format, I will use:
if ($args ~ "type=search_result&query=$val1&page=$val2") {
   rewrite ^ /&q=$arg_query&p=$arg_page? permanent;
}
if ($args ~ "type=search_result&query=$val1") {
   rewrite ^ /&q=$arg_query? permanent;
}

Not sure if this is working or not, since it depends on the above statements, I have not been able to test. But I don't get any errors.
I'm not sure that I'm doing wrong. If someone could have a look I would be very greatful.
Comment: `$args` will not match `^/?q=val1&p=val2`. It might match `^q=.*&p=`
Comment: You may need to add the `location` block that handles the `/cgi-bin/website.cgi` URL so that we can understand how the argument list is passed to the script.
Comment: @RichardSmith I don't understand your comment. What am I doing wrong?
Comment: Welcome to ServerFault. It is better to handle one issue at a time. You'd want to take consider 301 redirects as a separate question once the issue with shorter URLs are resolved!
Answer: I got it working!
if ($args ~ "^q=([^&]+)$") {
  set $q $1;
  rewrite ^ /cgi-bin/website.cgi?type=search_result&query=$1 last;
}

if ($args ~ "^q=([^&]+)&p=(\d+)") {
  set $q $1;
  set $p $2;
  rewrite ^ /cgi-bin/website.cgi?type=search_result&query=$1&page=$2 last;
}


Multiple sites/default folders

Question: I have a Drupal 8 website on Docker containers. Drupal sites folders contains, besides the default folder, two folders, the settings.php file, and configuration.
The goal is to have different configuration inside each folder (inside each settings.php) and connected to same or different database.
Because client wants only one instance of Drupal (a single set of containers), how can I manage the website to change symlink from the default folder to each folders with different configurations?
Comment: It sounds like you're looking to set up a multisite. You may want to start [here](https://www.drupal.org/docs/multisite-drupal/set-up-a-multisite).
Answer: sites/sites.php is the file that allows to define a set of aliases that map hostnames, ports, and pathnames to configuration directories in the sites directory

Multiple sites/default folders


Help with equivalence stated in average reward setting RL in Sutton's book

Question: In page 202 of the latest draft of Richard S. Sutton's RL book, the average-reward setting for RL is introduced, and there the author states the equivalence:
$$\lim_{h\to \infty} \frac{1}{h} \sum_{t=1}^h \mathbb E[R_t | A_{0:t-1}\sim \pi] = \lim_{t\to\infty} \mathbb E[R_t| A_{0:t-1}\sim \pi]~. $$
Why is this true? How can I prove this?
Answer: You can write $\frac{1}{h} \sum\limits_{t=1}^{h} E[\ldots]$ as $E [E[\ldots]]$. Then the proof is trivial.
Of course you have to use the assumption that the reward is well bounded or dominated by some function. In this case I think its easier to argue with a bound.
Comment: In order to write the summation as an integral, I assume you're forced to interpret the term $\frac{1}{h}$ as a probability, correct? If that's the case, isn't that a uniform distribution over the positive integers ([which can't exist](https://math.stackexchange.com/questions/14777/why-isnt-there-a-uniform-probability-distribution-over-the-positive-real-number))?
Comment: Ah, now I noticed your equation doesn't have a limit in it. So it is a uniform distribution over only a finite number of integers.
Comment: And I also noticed that the link I posted relates to uniform distribution over reals, not integers.


Prove: The set of all interior points of a set E is always open.

Question:
Prove: The set of all interior points of a set E is always open.

Here is my proof; is it valid?
Let $P_a$ be an interior point of $E$. Then, $P_a$ has a neighborhood $$N_{r_{P_a}}\subset E$$
By theorems, every neighborhood is an open set and the union of any collection of opens sets is also open, so $$\bigcup_a N_{r_{P_a}}$$ is open, hence the set of all interior points of $E$ is open.
pic of proof
Comment: In some books, the interior of $E$ is _defined_ as the union of all open sets contained in $E$. It's an interpretation that's worth being aware of.
Comment: Looks good to me. One thing is that the index is not necessarily countable so you might write $\bigcup_{a\in A}$.
Answer: I add this to give this old post an answer.

Your proof might be incomplete because you do not prove that the set $\bigcup_a{N_{r_{P_a}}}$, which you actually show to be open, is indeed your desired set of all interior points. E.g. how do you know that $N_{r_{P_a}}$ does only contain interior points of $E$?
However, this last question is not hard to answer. You just need to observe that since $N_{r_{P_a}}$ is open as well, every point $x\in N_{r_{P_a}}$ has a neighborhood $M\subseteq N_{r_{P_a}}\subseteq E$, hence $x$ is also interior to $E$.


Prove by induction that $4^n≥n^4$ for all $n≥4$

Question: Our teacher wrote the answer as follows
$$\begin{align}
4^{n+1}&=4\cdot 4^n\\
&≥4\cdot n^4\\
&≥4n^4\\
&≥n^4\\
&≥n^4 + 3n^4\\
&≥n^4 + 15n^3\\
&≥n^4 + 4n^3 + 6n^2 + 4n + 1\\
&=(n+1)^4
\end{align}$$
However, my class and I are not sure how he came to this conclusion.
Comment: The first step of the induction process is missing. A starting value of $n$
Answer: Remark that, for $n=0 \ $ is true:
$$ 1=4^{0}\geq 0^{4} $$
for $n=1 \ $ is false
$$ 4^{1} < 1^{4}$$
for $n=2 \ $   is true:
$$ 16=4^{2} \geq 2^{4}=16 $$
for $n=3 \ $   is not true:
$$ 64=4^{3}<3^{4}=81 $$
Let $n\geq 4$, then when $n=4$, you just have $4^{4}\geq 4^{4}$. When $n>4$ you can use induction on $n$ by saying that $n=4$ is your starting value and you do:
First by the induction hypothesis we have $4^{n}\geq n^{4}$ for all $n\geq 4$ and this implies the following:
$$4^{n+1}=4\cdot 4^{n}\geq 4\cdot n^{4} = n^{4}+3n^{4}$$
Assume $n\geq 5$, then you can multiply side by side by 3 and get:
$$ 3n\geq 15 $$
as $n\geq 5$ you can multiply both sides by $n^{3}$ to have:
$$ 3n^{4}\geq 15n^{3}$$
add to both sides $n^{4}$ to get:
$$ n^{4}+3n^{4}\geq n^{4}+15n^{3} $$
Finally, you have to show that $$ 15n^3 \geq 4n^3 + 6n^2 + 4n + 1 $$ which is true because:
$$ 15n^{3} = 4n^{3}+6n^{3}+4n^{3}+n^{3}$$ and the fact that $n\geq 5\geq 1$ give us:
$$ 4n^{3} \geq 4n^{3} $$
$$ 6n^{3} \geq 6n^{2} $$
$$ 4n^{3} \geq 4n$$
$$ n^{3}\geq 1 $$
because $n\geq 5$.
You can now add all these last inequalities together to get:
$$  15n^{3} \geq  4n^3 + 6n^2 + 4n + 1 $$
add to both sides $n^{4}$ to get:
$$ n^{4} + 15n^{3} \geq  n^{4}+4n^3 + 6n^2 + 4n + 1 =(n+1)^{4}$$
and we already show that $$ 4^{n+1} \geq n^{4}+3n^{4}\geq n^{4} + 15n^{3} $$
You can assume $n\geq 5$ because for $n=4$ is direct the result. You can peak $n=5$ as starting value for induction.
Comment: How did you get from: add to both sides $n^{4}$ to get:

$$ n^{4}+3n^{4}\geq n^{4}+15n^{3} $$

Finally, you have to show that $$ 15n^3 \geq 4n^3 + 6n^2 + 4n + 1 $$
Comment: @Ashivs: You just say, since 15n^3≥4n^3+6n^2+4n+1, then  n^4+15n^3≥n^4+4n3+6n2+4n+1=(n+1)^4
Answer: You seem to have some errors in what you've written.  I'll try to correct the proof and provide details while keeping the same proof outline.  Sections underlined are corrections or are things that are missing from your original post.
Step 1: State the claim
We wish to prove that $4^n\geq n^4$ $\underline{\textbf{for all}~n\geq 4}$
$\underline{\textit{Step 2: Base case}}$
We check that it is in fact true for the smallest intended value of $n$, in this case $n=4$.  We see that indeed when $n=4$ we have $4^n\geq n^4$ as both sides are equal to $4^4$.
As a special case for this specific proof, we find it easier to also prove a second base case to make the induction step more convenient.  We see that indeed when $n=5$ we have $1024=4^5\geq 5^4=625$ is true.
Step 3: Induction step
We state again our induction hypothesis.  We assume that for some value of $k\geq 4$ that $4^k\geq k^4$ is true.  We wish to show that this being true for some value of $k$ will further imply that the claim will be true for $k+1$ as well, i.e. that $4^{k+1}\geq (k+1)^4$
We have:
$\require{cancel}\begin{array}{rlr}
4^{k+1}&=4\cdot 4^k&\text{properties of exponents}\\
\hline&\geq 4k^4&\text{by induction hypothesis}\\
\hline&\color{red}{\cancel{≥ n^4}}&\text{erroneous, removed}\\
\hline&\geq k^4 + 3k^4&\text{equal to previous line}\\
\hline&=\underline{k^4+3k\cdot k^3}&\text{properties of exponents}\\
\hline&\geq k^4 + 15k^3&\text{as}~k\geq 5~~(\dagger)\\
\hline&\underline{\geq k^4 + 4k^3+6k^3+4k^3+k^3}&\text{equal to previous line}\\
\hline&\geq k^4 + 4k^3 + 6k^2 + 4k + 1&\text{as}~k\geq 1\\
\hline&= (k + 1 )^4&\text{by binomial theorem}\end{array}$
Note, in the step marked with a $(\dagger)$ this was only true for values of $k\geq 5$ and is not true for $k=4$.  The step follows from the fact that since $k\geq 5$ we have $3k\geq 15$.  This is the reason why in this case we found it easier to use an additional base case.
Comment: beautiful writing, very clear.


Active Directory Users - All Attributes Suddenly Blank

Question: We had an instance yesterday where approximately 130 of our well over 5,000 user objects suddenly became corrupted. Every attribute you can possible set with the exception of sAMAccountName and cn were wiped clean including their password despite policy forbidding anything less than 8 characters. The modified timestamps were all seconds apart from one another. Their accounts were also disabled. I suspect because of the blanking of the password. When we went to re-enable the accounts, we would get an error saying the password did not meet requirements. So, we had to reset all of their passwords. The accounts were also unlinked from their Exchange mailbox and we had to re-connect them. Even all of their group memberships were removed.
Something odd we noticed is that all of them were, when sorted alphabetically by cn, among the first one to three users within their OU container. Beyond that, no patterns were noticed.
Initially, I thought this might have been caused by someone writing a script and screwing up. But, the fact the passwords were set to blanks leads me to believe that couldn't have been done via a script.
Unfortunately, for reasons I won't go into we did not have auditing turned on.
Has anyone seen this before? Do you know what might have caused it?
Comment: Have you fired any IT people in the last few months?
Comment: In a manner of speaking, yes. We went from one outsourced IT service provider to another. I don't view either of them as having the know how to have done something that elaborate though.
Comment: It doesn't take a lot of knowledge to be utterly destructive, [and it does happen](http://serverfault.com/q/171893/126632).
Answer: This sounds like someone or something deleted the accounts, and then restored them. (Picture an admin saying "oh shit" - we've all been there.) This is the same kind of behavior you'd see when you restore/reanimate objects that have been deleted, back in the old days before the AD Recycle Bin. The object is restored with a blanked password and is disabled as a result, and most of the attributes and group memberships are lost.
Check Security event logs on your DCs if you have auditing enabled. If you don't, check repadmin /showobjmeta.
Comment: Nevermind, found out there are tools like `AdRestore` from SysInternals to do this in bulk.
Comment: Yep. This is the answer. They are almost certainly reanimated tombstones. Someone screwed up and tried to cover their tracks.
Comment: This makes sense. In fact, now that you mention it. I recall one of the other IT admins saying some of those users under their OU had been deleted a week or so ago. Also, we're probably still living in the "old days" as we're still in a 2003 R2 environment.
Comment: **+1**, Doing some research on this I was able to confirm this is what happened. All of the affected user's show the `isDeleted` attribute in their replication history. Unfortunately, we don't have auditing turned on, and the security logs for the DC don't go back far enough to see who was logged on during that time. Thank you for your help!
Comment: Something still unexplained. How did they re-animate 130 of them within a matter of minutes (the modified timestamps were also approximately the same)? The only way I found to do this was using `ldp` and it seems you have to do them one-at-a-time? `ldp` also seems to update the modified timestamp from my testing.


Create pdf document in asp.net 2.0

Question: I am using asp.net 2.0 with c#.
I have to convert my label text into pdf. For this I have used this tutorial
http://www.codeproject.com/KB/aspnet/Creating_PDF_documents_in.aspx
now I am facing two problems:

Every time it is creating 1.pdf, what if there are so many user wants to see the the pdf format of any page
As my label text contains HTML content, it is showing a HTMl output. I don't want HTML to be display in the pdf.

please let me know if you have any other way to create a pdf.
Thanks in advance.
Answer: Creating a PDF with HTML-formatted content is not entirely trivial, and the CodeProject sample code isn't quite suitable for that. You'll most likely want to look into a (commercial) third-party solution for this: I myself use Siberix Report Writer: it's flexible, quite affordable, works in partial-trust scenarios (nice for shared web hosting environments) and most importantly doesn't require a per-server license, so you can embed it in your product without redistribution issues.
Answer: Item 1) You cache your pdf files to disk. When a request is made for a pdf check if the pdf has been created (i.e. there is a file on disk) and if not generate it. Then send the pdf using the response.writefile command
Item 2) If you are trying to print formatted html into pdf then you will need something that is capable of rendering html. There are a number of html to pdf converters however I have not found them to be all that good. If you are comfortable with php then there are some pretty good converters you can use. Joomla supports html to pdf, so whilst it may not be the exact solution it maybe a good starting point.
Answer: I would also suggest you take a look at Aspose PDF.
Answer: I would suggest using RDLC Report or Crystal Reports as suggested by @Jeroen
Answer: Cete Pdf Generator has HtmlTextArea element and supports some limited HTML
http://www.cete.com/support/net_help_library/html/ceTeDynamicPDFPageElementsHtmlTextArea.htm
Answer: You could try the itextsharp library. I've not used it but it has been highly commended by other developers I know. http://sourceforge.net/projects/itextsharp/
In regards to the caching issue. I would check the file system for a pdf named via a convention. If the file is found then serve it. Otherwise, call another method which generates the pdf and saves it to the drive. This way only the first ever request will cause the generation of the pdf. Naming conventions will be key here. The basic implementation wont be thread safe. But it's a good start.
Answer: ABCpdf is another commercial component which converts html to pdf.
http://www.websupergoo.com/abcpdf-5.htm
Answer: I use CrystalReports. It can create a PDF on the fly and output it to disk or http directly.

Create pdf document in asp.net 2.0


Como fazer o Firebase Cloud Messaging enviar uma mensagem para um usuário em especifico?

Question: Estou tentando fazer o Firebase Cloud Messaging enviar uma mensagem para um usuário em especifico mais não estou conseguindo...
Primeiro eu estou registrando o aparelho e salvando o id no meu servidor:
<code>FirebaseInstanceId.getInstance().getInstanceId()
    .addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
        @Override
        public void onComplete(@NonNull Task<InstanceIdResult> task) {
            if (!task.isSuccessful()) {
                Log.w(TAG, "getInstanceId failed", task.getException());
                return;
            }

            // Pega o ID token
            String token = task.getResult().getToken();
            // depois envia para o servidor
            saveToken(token);

        }
    });
</code>
Então eu tento enviar a minha mensagem pelo back-end para:
https://fcm.googleapis.com/fcm/send
Com o id que foi cadastrado no banco de dados
Como neste tutorial de exemplo:
http://ricardolecheta.com.br/?p=894
Answer:
Primeiro verifique se o token esta salvando no seu servidor,
  Teste no postman com o token que vc pegar no Android e veja se da success, por que se vc não colocou o google-services.json corretamente não gera o token certo

Não esquece de incluir no manifest.xml do service do push
<code>  <service android:name=".MyFirebaseMessagingService">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT"/>
        </intent-filter>
    </service>
</code>
Answer: O envio para um usuário especifico é feito pelo console do firebase inserindo o token firebase do dispositivo ou configurando um servidor para enviar para aquele token especifico.
Clique aqui


Partitioning effects from a Poisson GLM

Question: I'm using a Poisson GLM to model the effects of advertising (number of ads bought) on the number of sales (numConvs). If possible I'd like to use the model to get an idea of how many sales are due to one type of ad (ad1), how many are due to another type of ad (ad2), and how many were not caused by either type of ad - a 'baseline' number of sales.
Intuitively I thought I could do this by using the model to predict how many sales I would get when the number of ads bought for one or both types of ad was zero. However the predicted values do not add up:
#===============
# Simulate data
#===============

set.seed(1)
intercept <- 1
ad1Coef <- 0.03
ad2Coef <- 0.05

ad1 <- sample(1:50, size=100, replace=TRUE)
ad2 <- sample(1:50, size=100, replace=TRUE)
numConvs <- rpois(n=length(ad1), lambda=exp(intercept + ad1Coef*ad1 + ad2Coef*ad2))

df <- data.frame(numConvs=numConvs, ad1=ad1, ad2=ad2)

#===============
# Model & predict
#===============

# Model
mPois <- glm(numConvs ~ ad1 + ad2, data=df, family='poisson')
summary(mPois)$coef

# Predict num conversions based on number of ads in final row of data
finalRowDF <- df[nrow(df),]
finalRowDF # 43 actual conversions

library('dplyr')
predict(mPois, type='response', newdata=finalRowDF) # Predicted conversions when both ads are playing: 49
predict(mPois, type='response', newdata=mutate(finalRowDF, ad1=0, ad2=0)) # Predicted conversions when no ads are playing: 3
predict(mPois, type='response', newdata=mutate(finalRowDF, ad1=0)) # Predicted conversions when only ad2 is playing: 18
predict(mPois, type='response', newdata=mutate(finalRowDF, ad2=0)) # Predicted conversions when only ad1 is playing: 7

As shown in the code above, the model predicts that there are 49 sales when both ads are playing, 18 sales when only ad2 is playing, 7 sales when only ad1 is playing, and 3 sales when no ads are playing.
From this, I would intuitively think that:

there was a 'baseline' number of sales of 3
ad2 caused 18 - 3 = 16 sales
ad1 caused 7 - 3 = 4 sales

However, these numbers ad up to 23, less than half of the 49 predicted when both ads are playing. What is going on here? I get that a Poisson GLM is a multiplicative model on the response scale, so it's probably not appropriate to use my 'adding and subtracting' method above to partition effects. But even so, where do the remaining 26 predicted conversions come from? Is this some kind of interaction effect, where the effect of ad1 depends on the level of ad2? And is there some appropriate way to get a broad idea of how many ads are caused by ad1 vs ad2 vs baseline effect?
Answer: In a Poisson model, the expected number of sales given advertising levels $x$ and $w$ would be $$E[y \vert x,w] = \exp(\alpha + \beta \cdot x +\gamma \cdot w ) = \exp(\alpha) \cdot \exp(\beta \cdot x) \cdot \exp(\gamma \cdot w )$$
You can think of $\exp(\alpha)$ as a baseline level of sales without advertising, which is then scaled by the terms involving the ads. If there's no advertising the effect is $\exp(0)=1$ (no effect). In general, however, the effect is multiplicative and definitely depends on the level of the other type.
I think the easiest thing is to examine the ratio of these multipliers $$\frac{\exp(\beta \cdot x)}{\exp(\gamma \cdot w)}=\exp(\beta \cdot x-\gamma \cdot w).$$
One caveat is that the validity of this comparison hinges on the the levels of advertising being uncorrelated with demand shocks, which is often not the case, particularly with internet advertising.
Comment: Thanks @Dimitriy. I thought the answer might be something along these lines, but that nonetheless it seems strange to me... As I understand it, this means that a Poisson model automatically includes interactions between the terms (insofar as effects of ad1 depends on the effects of ad2). What if you believe that their effects are additive - is this impossible to model with a Poisson GLM?
Comment: I have seen a lot of evidence that marketing effects are interactive, so this seems like a feature rather than a bug to me (without knowing more about your setting). If you want to do something additive, why not try OLS?
Comment: Agree with you yes marketing effects are interactive, but advertising is just used as an example in this case. The question is really about whether it is possible to partition effects using a Poisson GLM model. It's surprising that a Poisson GLM implicitly models interactions - this isn't something I've ever read/been taught about them.
Comment: And just to confirm from your answer, it's impossible to attribute x sales to effects of ad1, y sales to effects of ad2, and z sales to baseline, using a Poisson GLM?
Comment: @jay It's not easy to do, but if you want to go this route, I would show three numbers: the $\exp(\alpha)$ no ads baseline, and the predicted value setting each type of advertising to the historic average or median, leaving the other type as is was.

Partitioning effects from a Poisson GLM


Homebrew elasticsearch/kibana installation is failing

Question: I have updated to macOS ventura, there was some issue with ES(v7.17.4) so I uninstalled it and now when I'm trying to re-install the same, running into below error.
<code>/System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/specification_policy.rb:4:in '<top (required)>': superclass mismatch for class SpecificationPolicy (TypeError)
    from /Library/Ruby/Site/2.6.0/rubygems/core_ext/kernel_require.rb:85:in 'require'
    from /Library/Ruby/Site/2.6.0/rubygems/core_ext/kernel_require.rb:85:in 'require'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/specification.rb:16:in '<top (required)>'
    from /Library/Ruby/Site/2.6.0/rubygems/core_ext/kernel_require.rb:85:in `require'
    from /Library/Ruby/Site/2.6.0/rubygems/core_ext/kernel_require.rb:85:in `require'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems.rb:1365:in '<module:Gem>'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems.rb:116:in '<top (required)>'
    from /Library/Ruby/Site/2.6.0/rubygems/core_ext/kernel_require.rb:85:in 'require'
    from /Library/Ruby/Site/2.6.0/rubygems/core_ext/kernel_require.rb:85:in 'require'
    from /usr/local/Homebrew/Library/Homebrew/utils/gems.rb:47:in 'setup_gem_environment!'
    from /usr/local/Homebrew/Library/Homebrew/standalone/load_path.rb:13:in '<top (required)>'
    from /usr/local/Homebrew/Library/Homebrew/startup.rb:6:in 'require_relative'
    from /usr/local/Homebrew/Library/Homebrew/startup.rb:6:in '<top (required)>'
    from /usr/local/Homebrew/Library/Homebrew/global.rb:4:in 'require_relative'
    from /usr/local/Homebrew/Library/Homebrew/global.rb:4:in '<top (required)>'
    from /usr/local/Homebrew/Library/Homebrew/build.rb:11:in 'require_relative'
    from /usr/local/Homebrew/Library/Homebrew/build.rb:11:in '<main>'
Error: Failure while executing; `/usr/bin/sandbox-exec -f /private/tmp/homebrew20221031-58137-1t7tz3a.sb nice /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/bin/ruby -W1 -- /usr/local/Homebrew/Library/Homebrew/build.rb /usr/local/Homebrew/Library/Taps/elastic/homebrew-tap/Formula/elasticsearch-full.rb --debug` exited with 1.
/usr/local/Homebrew/Library/Homebrew/sandbox.rb:157:in 'exec'
/usr/local/Homebrew/Library/Homebrew/formula_installer.rb:917:in 'block in build'
/usr/local/Homebrew/Library/Homebrew/utils/fork.rb:45:in 'block (3 levels) in safe_fork'
/usr/local/Homebrew/Library/Homebrew/utils/fork.rb:37:in 'fork'
/usr/local/Homebrew/Library/Homebrew/utils/fork.rb:37:in 'block (2 levels) in safe_fork'
/usr/local/Homebrew/Library/Homebrew/utils/fork.rb:34:in 'open'
/usr/local/Homebrew/Library/Homebrew/utils/fork.rb:34:in 'block in safe_fork'
/System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/tmpdir.rb:93:in 'mktmpdir'
/usr/local/Homebrew/Library/Homebrew/utils/fork.rb:33:in 'safe_fork'
/usr/local/Homebrew/Library/Homebrew/formula_installer.rb:905:in 'build'
/usr/local/Homebrew/Library/Homebrew/formula_installer.rb:450:in 'install'
/usr/local/Homebrew/Library/Homebrew/upgrade.rb:203:in 'install_formula'
/usr/local/Homebrew/Library/Homebrew/install.rb:350:in 'install_formula'
/usr/local/Homebrew/Library/Homebrew/install.rb:340:in 'block in install_formulae'
/usr/local/Homebrew/Library/Homebrew/install.rb:339:in 'each'
/usr/local/Homebrew/Library/Homebrew/install.rb:339:in 'install_formulae'
/usr/local/Homebrew/Library/Homebrew/cmd/install.rb:233:in 'install'
/usr/local/Homebrew/Library/Homebrew/brew.rb:95:in '<main>'
</code>
Tried couple of solutions, found here and there on the Internet.
Answer: See my answer at superclass mismatch for class SpecificationPolicy, what I did to help me overcome what looks like the same error


Storing and displaying image files in grails application in cloud foundry

Question: I have an grails application, which allows users to upload image files and these images can be displayed. The application actually only stores file path in database and saves the image files in file system.
I've read some posts which says Cloud Foundry doesn't support local file system access. So my question is what modification should I do if I want to deploy my application to Cloud Foudry? I hope images still can be displayed directly on the webpage and users don't have to download them to their own computer only for viewing them.
Answer: The images stored on file system can disappear when your application stops, crashes, or moves. It should not be used for content that you want to persist. Further, the file system storage is not scalable. That is to say if more than one instance of your app is running the local storage is only visible to a specific instance of the app, and is not visible or shared across all instances.
To meet your requirements, a local service such as MongoDB GridFS, MySQL with blob data type or external blob stores such as Box.net or Amazon S3 can be used.


how do i change outgoing ip address for server centos

Question: I need to make sure my clients outgoing ip address uses the dedicated ip they are assigned.
For example,
site123.com has an ip of 126.96.36.199(eth0:1) (resolves fine when incoming)
but it is using my main server ip 22.214.171.124 (eth0) when it makes outgoing requests
How can I go about changing this?
I am using centOS on the dedicated server.
Answer: By default, everything will go out the default route, which is associated with the default eth0 ip.   You can change the eth0 and eth0:0 ips and then change the default route....
If you only want it for some things, then you need to use the iproute2 package and use ip route command to specify certain routing rules.
http://linux-ip.net/html/tools-ip-route.html is a good place to see the nitty gritty.
This is also called "source based routing". This used with "tc" command (traffic shaping) will accomplish what you want...It can be done, but it's very difficult for the novice administrator on a linux server with hundreds of ips.
However, some programs like wget etc, will allow you to specify the network interface to use, so you can specify -i eth0:0 for instance.
Good luck!
Answer: I would expect changing the default route on your CentOS to the aliased interface 'eth0:1' should make it work as you want.
The reason for correct incoming resolution has nothing to do with your CentOS configuration;
it is controlled by the external name lookup resolution for your 'site123.com' domain name.
It resolves to '18.104.22.168' so you get incoming connections there.

Update: Section 13.2.4: Alias and Clone Files, in Interface Configuration Files page of CentOS deployment guide refers this Network Configuration page for Device Aliases.
Comment: thanks, any idea where i would make this change?
Answer: cd /etc/sysconfig/network-scripts/

Your interface config scripts will be named "ifcfg-eth0", "ifcfg-eth1", etc.  Edit the one for the appropriate interface, changing the "GATEWAY" setting.  For example, on my box "ifcfg-eth0" looks like this:
DEVICE=eth0
BOOTPROTO=static
ONBOOT=yes
IPADDR=188.8.131.52
NETMASK=255.255.255.255
GATEWAY=10.255.255.1

In your case, remove the "GATEWAY" line from your "ifcfg-eth0" file and move it to "ifcfg-eth0:1" (changing the gateway address to whatever is correct for that NIC). Then restart your networking:
/etc/init.d/network restart

Comment: there are no files for ifcfg-eth0:1, only ifcfg-eth0

should i create this file?