Doing all possible arithemetic operations between 3 numbers

Question: Summary:
I have a set of 3 numbers, lets say (a,b,c). I want to perform all arithmetic operations (+,-.*,/) between these numbers and get the resultant values.
My idea is to generate subsets.
1] [(a,b), c]
2] [(a,c), b]
3] [(c,b), a]
Now within the set [(a,b),c], I will perform all operations between "a" and "b", store them as "r1","r2", "r3"..etc. Once that is done, I will perform all operations between "r1", "r2"... and "c" to get the final result values.
Is this an optimal way to achieve my goal?
EDIT-1:
As an example, if i have numbers (1,2,3) then I want to do the following
1+2+3 =  6
1+2-3 = 0
1-2-3
1*2*3 = 6
and so on.
Basically, all possible arithmetic operations between the set of numbers.
Comment: Please clarify: What values do you want exactly? Suppose a = 5, b = 5 and c = 3. Do you want `a+b+c`, `a+c+b`, `b+a+c`, `b+c+a` etc. or only a subset of them?
Comment: @thiton , i have clarified the question, please refer to EDIT-1 in the main posting.
Comment: You might be asking for one of several things: (1) all syntactically different expressions regardless of whether they are mathematically equivalent; (2) all expressions that represent mathematically distinct operations, even if they happen to produce the same answer for given input values a, b, and c; (3) a set of expressions that produce distinct values for the given input. Which is it?
Comment: @TedHopp , All different expressions regardless of whether they are mathematically equivalent or not.
Answer: The short answer is simply NO. It is not optimal. For example you will calculate (a+b)+c and (a+c)+b but both of them have the same value.
Comment: @Seed Amiri, i didnt downvote your answer, i just upvoted it :).  Question --> What would be an optimal way to achieve this?
Comment: @bhavesh, because number of possible different valid statements is smaller than 48, you can try all of them in your code (sure is efficient but not programming challenge), but as I wrote this is just short answer, currently is my sleeping time, I'll think about your problem and if I got some elegant way I'll wrote it. Also is better to rephrase your question, one of a reason I wrote this answer is because remind you ask question clearly.
Comment: The number of possible different valid statements is larger than 48. For example, the pattern `[a+b+c, a+b-c, a+b*c, a+b/c]` makes up 24 possible statements because there are six permutations (i.e. (a=1,b=2,c-3), (a=1,b=3,c=2), etc.). Multiply that by 4 because the first operator can be +, -, *, or /. That gives 96 different valid statements. Granted, many of them are semantically identical, but they're syntactically different.
Comment: @JimMischel, that was simple mistake, I thought we have 4^2 different operation and 3! different permutation it will be 3*16 = 48 :) in fact it's 6*16 = 96. As I wrote it was my sleeping time, anyway it means number of different way in this case is small.
Answer: Your approach is basically sound, but incomplete. First, note that under the normal rules of arithmetic you will need to either include some parentheses in your output (to represent groupings such as [(a+b)*c]) or else accept that some combinations of operations will not be present in your final output.
Also, you will not be able to generate certain other combinations of arithmetic operations at all, such as "1*(2+3)". (This assumes that you want to consider "1*(2+3)" as distinct from "(2+3)*1". Lexically it certainly is.) For that, you will also need to include among the subsets, all groupings of the form [a, (b, c)]. If you include this second set of groupings, you will in essence be generating the parse trees of every possible expression. However, this creates a complication that others have noted in comments: "1+(2+3)" and "(1+2)+3" are identical once you remove the redundant parentheses.
There is also another problem if you allow for two (or all three) of a, b, and c to be equal. (For instance, if (a, b, c) = (1, 3, 3), then "1+3+3", among other things, will appear twice, once for [(a+b)+c] and once for [(a+c)+b]. If you allow for groupings like [a,(b,c)], then it will appear a total of four times once you eliminate the unnecessary parentheses.) If you want to allow for equality between a, b, and/or c, and yet avoid duplicate outputs, you will need to eliminate duplicates at some stage:

generate all outputs and test for duplicates (by simple string comparison, for instance)
generate all parse trees and test for duplicates there (not much different from the first, but avoids the work of generating the final output before discarding it)
prune the collection of subsets before starting the process of inserting operators (probably the best)
avoid generating duplicate subsets by a more sophisticated scheme of generation (which I can't think of off the top of my head)

Finally (I think), if you allow for the second set of groupings and also allow for duplicates among a, b, and c, then there are expressions such as "1 / (3 - 3)" that cannot be evaluated. (I don't think this comes up with the groupings [(a,b),c] unless you allow the input to include zero.) You'll have to decide what you want to do about them.


MySQL Select 2 items from multiple tables

Question: I'm trying to select 2 of the same item from multiple tables. Here's a run down of my data.
Items
Item ID    Item name
1          Item1
2          Item2
3          Item3
4          Item4

Item Pairs
Item ID 1  Item ID 2
4          1
4          3
3          1
4          2

The pairs are linked via foreign key.
What I need to be able to do is select the 2 item names based on the item pair ids. I got as far as selecting only 1 of them with the below query but have not been able to select more than that.
SELECT item_name FROM items, item_pairs WHERE item_pairs.item_id_1 = item.item_id

Thanks very much in advance
Answer: Try this one by rejoining the items table
SELECT
  i.item_name,
  i2.item_name
FROM
  items i
  JOIN item_pairs ip
    ON ip.item_id_1 = i.item_id
  JOIN items i2
    ON ip.item_id_2 = i2.item_id
GROUP BY ip.item_id_1,
  ip.item_id_2

Comment: Thank you very, this worked perfectly! I added ip.item_pair_id, to the GROUP BY so that it listed in order of the item paid ids. Thank you very much!


Convention Based Dependency Injection with Ninject 3.0.0

Question: I have two projects in my solution... a domain project and MVC3 web project (e.g. MyApp.Domain and MyApp.Web).  Previously, when using Ninject.Extensions.Conventions ver. 2, I was able to use the following statement in the NinjectMVC3.cs file, and required dependencies throughout my solution (both web and domain) were injected properly (e.g. IFoo automatically bound to Foo).
kernel.Scan(x =>
{
  x.FromAssembliesMatching("*");
  x.BindWith<DefaultBindingGenerator>();
});

I have just upgraded to Ninject 3.0.0 (pre-release) and Ninject.Extensions.Conventions 3.0.0 (another pre-release) but the syntax for convention based binding has changed.  I have figured out that I can use the following statement with the new version, but it only automatically binds the convention based interfaces in MyApp.Web and not in MyApp.Domain.  The previous version bound interfaces throughout the application.
kernel.Bind(x => x
    .FromThisAssembly()
    .SelectAllClasses()
    .BindToAllInterfaces());

Any clue how I can configure convention based binding with the new Ninject version?  I assume it has to do with specifying the assembly, but I have tried using FromAssembliesMatching("*") and it fails for everything then.
-- Edit to show my exisiting code in RegisterServices method: --
private static void RegisterServices(IKernel kernel)
{
  // This code used to work with v.2 of Ninject.Extensions.Conventions
  // kernel.Scan(x =>
  // {
  //   x.FromAssembliesMatching("*");
  //   x.BindWith<DefaultBindingGenerator>();
  // });

  // This is the new v3 code that automatically injects dependencies but only for interfaces in MyApp.Web, not MyApp.Domain
  kernel.Bind(x => x.FromThisAssembly().SelectAllClasses().BindToAllInterfaces());

  // I tried this code, but it throws "Error activating IDependencyResolver" at "bootstrapper.Initialize(CreateKernel)"
  // kernel.Bind(x => x.FromAssembliesInPath(AppDomain.CurrentDomain.RelativeSearchPath).SelectAllClasses().BindToAllInterfaces());

  // These are dependencies in MyApp.Web that ARE being bound properly by the current configuration
  // kernel.Bind<IMemberQueries>().To<MemberQueries>();
  // kernel.Bind<IGrantApplicationQueries>().To<GrantApplicationQueries>();
  // kernel.Bind<IMailController>().To<MailController>();

  // These are dependencies in MyApp.Domain that ARE NOT being bound properly by the current configuration, so I have to declare them manually
  // They used to be injected automatically with version 2 of the conventions extention
  kernel.Bind(typeof(IRepository<>)).To(typeof(Repository<>)).InRequestScope();
  kernel.Bind<IUnitOfWork>().To<UnitOfWork>().InRequestScope();
  kernel.Bind<IMemberServices>().To<MemberServices>();
  kernel.Bind<IGrantApplicationServices>().To<GrantApplicationServices>();

  // These are dependencies that SHOULD NOT be bound by convention as they require a different scope or have unique naming
  kernel.Bind(typeof(EfDbContext)).ToSelf().InRequestScope();
  kernel.Bind<IConfigurationProvider>().To<WebConfigConfigurationProvider>().InSingletonScope();
  kernel.Bind<IAuthorizationProvider>().To<MyAppAuthorizationProvider>();
  kernel.Bind<IPrincipal>().ToMethod(ctx => HttpContext.Current.User).InRequestScope();
  kernel.Bind<IGrantApplicationDocumentServices>().To<MySpecialNameGrantAplicationDocumentServices>().InRequestScope();
}

Comment: You looked at [the wiki](https://github.com/ninject/ninject.extensions.conventions/wiki). If not, can you give some idea of which bit is not making sense to you?
Comment: Ruben, I have looked at the wiki.  What's not making sense is that with the old code `x.FromAssembliesMatching("*")` worked and bound all my interfaces in MyApp.Web and MyApp.Domain.  However, with the new 3.0.0, that syntax doesn't work.  The closest I've found is `x.FromThisAssembly()` but that only binds the interfaces within MyApp.Web (since that's where the injection takes place).  It doesn't automatically bind the interfaces in MyApp.Domain.
Comment: Looking at the code, you could always get the assemblies yourself (either via AppDomain's assemblies list or some opther mechanism) and supply the list explicitly. Other than that I recommend jhust reading the source - its just not big. https://github.com/ninject/ninject.extensions.conventions/blob/master/src/Ninject.Extensions.Conventions/BindingBuilder/AssemblyFinder.cs
Comment: Looking at the algorithm, it uses a combination of AppDomain  relativesearchpoath and basepath. As a quick way of ruling out any issues there, you could do `.FromAssembliesInPath( AppDomain.CurrentDomain.RelativeSearchPath)` which will yield ``
Comment: Thanks for all you help Ruben.  Unfortunately, I tried that, but now I get an exception stating "Error activating IDependencyResolver
More than one matching bindings are available.  Activation path: 1) Request for IDependencyResolver. Suggestions:  1) Ensure that you have defined a binding for IDependencyResolver only once.".  I wish the new version just worked like version 2.
Comment: I also edited my original post to show my current code
Comment: That exception is more likely tpo have something to do with you duplicating your Ninject/MVC 3integration - do you have both derivation from / initialiazation of Ninject in your Global.cs/`HttpApplication` class and the `Ninject.MVC3` NuGet package-generated Application_Start stuff? If so, remove one of them. Unfortunately I have to stop guessing now though as messing with this is not something I've done a lot of - I do know that every permutation of this particular thing (general bootstrapping in MVC environments) hass been covered here on the ninject tag...
Answer: The equivalent is:
kernel.Bind(x => x
    .FromAssembliesMatching("*")
    .SelectAllClasses()
    .BindDefaultInterface());

Comment: Thanks Remo.  I guess I'm a moron.  That was one of the very first things I tried, but I used the BindToDefaultInterfaces (plural) method which failed.  When I changed it to the singular method, it worked.  Sorry for all the posts, but I do greatly appreciate your help.  Great work on all your projects!


In how many ways $10$ people can be seated at a round table as $2$ of them sit next to each other?

Question:
In how many ways $10$ people can be seated at a round table as $2$ of them
  sit next to each other?

We can look at the two of them that want to sit next to each other as a group. Then we have $9$ elements to seat at a round table. This can be done in $8!$ ways. Should we multiply this number by $2$ and is the answer $2\cdot 8!$?
Comment: Yes that is correct
Answer: Yes, and the multiplication by two is to account for the order within that group of two.


O que exatamente git checkout branch -- . faz?

Question: Gostaria de entender este comando de uma forma mais fácil, fiz alguns testes mas não estou muito seguro da conclusão. Tenho dois branches, o branch master e o branch novo, e fiz o teste descrito a seguir.
Diretório no último commit do brach master:
Arquivo    Conteúdo
a.txt      Arquivo a.txt do branch master
b.txt      Arquivo b.txt do branch master

Diretório no último commit do branch novo:
Arquivo    Conteúdo
a.txt      Arquivo a.txt do branch novo
c.txt      Arquivo c.txt do branch novo

Git status:
$ git status
On branch master
nothing to commit, working directory clean

Executando o comando
$ git checkout novo -- .

O diretório ficou:
Arquivo    Conteúdo
a.txt      Arquivo a.txt do branch novo
b.txt      Arquivo b.txt do branch master
c.txt      Arquivo c.txt do branch novo

Git status:
$ git status
On branch master
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)
    modified:   a.txt
    new file:   c.txt

Pra mim parece que ele está pegando todos os arquivos do branch novo, copiando e colando em cima do diretório de trabalho, sobre-escrevendo todos os arquivos com o mesmo nome. É isso mesmo, posso contar com esse comportamento? Tem como o git sobre-escrever um arquivo de nome diferente?
Note que o comando git checkout possui comportamento diferente dependendo dos parâmetros. Estou perguntando especificamente da versão do comando que possui algum arquivo como parâmetro. No comando que eu mencionei, o ponto está especificando o diretório atual (que no caso contém todos os arquivos) e faz diferença no comportamento do comando. Repare nos dois git status que o comando não muda de branch como o checkout sem "-- .".
Comment: Esse comando está estranho. Acho que o comportamento dele é: Jogue fora todas as modificações/delete na branch atual e copie os arquivos da arvore "novo" para a branch master. O que exatamente você está querendo fazer?
Comment: Inicialmente eu também achei que era isso! Dai fiz o seguinte teste: modifiquei o arquivo b.txt, usei o comando e a modificação do arquivo continuou no diretório de trabalho. Então ele não joga fora as modificações/delete, parece que apenas copia os arquivos.
Comment: Usei esse comando e dei commit em um projeto e obtive um resultado bem estranho, não sei se foi por causa desse ou de algum outro comando. Agora quero entender perfeitamente pra não acontecer o mesmo problema. O que eu queria mesmo saber é se em alguma ocasião o git pode identificar que um arquivo foi renomeado ou algo assim e sobre-escrever nele mesmo com nome diferente. Mas obrigado, foi uma boa opinião =)
Comment: Só pra constar, a partir do Git 2.23 (de 2019) foi criado o `git restore`, então o comando equivalente seria `git restore --source=novo --staged --worktree .`
Answer: O git checkout branch pode ser usado nas seguintes situações:
1 - Mudar de branch.
Quando o git muda de branch, todas as alterações que foram aplicadas na branch serão substituídas pelas alterações da branch que foi feito o checkout.
Ao criar um repositório git, o repositório já começa com uma branch chamada de master. Imagine que nesse momento você cria um arquivo master.txt e faz o commit desse arquivo. Em seguida você cria uma nova branch chamada nova-branch, essa nova branch, nesse momento, possuirá o mesmo conteúdo da branch master. Portanto, quanto você executar o comando git checkout nova-branch, nenhuma diferença será notada.
Imagine agora que você cria um novo arquivo chamado nova-branch.txt e faz o commit desse arquivo. Nesse momento haverão dois arquivos: o master.txt e o nova-branch.txt. Quando você executar o comando git checkout master, o seu working directory irá voltar para o estado em que a branch master está apontando, ou seja, o arquivo nova-branch.txt irá sumir, porque na branch master esse arquivo não existe.
Imagine agora que você cria um arquivo chamado novo-arquivo.txt e não comita esse arquivo. No diretório atual estão presentes os arquivos novo-arquivo.txt e master.txt. Em seguida você executa o comando git checkout nova-branch. O working directory irá voltar para o estado em que a nova-branch está apontando, ou seja, o arquivo nova-branch.txt irá aparecer. Contudo, o arquivo novo-arquivo.txt irá continuar aparecendo, isso porque esse arquivo não foi comitado, então ele não faz parte da branch master. Ele está no que é chamado de working copy, que são os arquivos que foram modificados, criados ou deletados, mas que não foram comitados. Esses arquivos vão continuar no working copy mesmo você alterando de branch. Dessa forma, se você quiser, poderá comitar esses arquivos na branch que desejar.
Os exemplos que eu dei foram em cima de criação de arquivos, mas claro que o mesmo se aplica se forem feitas alterações no arquivo.
2 - O git checkout pode ser usado para criar uma nova branch também. Se o comando for executado dessa forma: git checkout -b nome-branch. A branch será criada e em seguida o checkout será feito.
3 - O git checkout pode ser usado para criar localmente uma branch remota. Se você fizer o clone de algum repositório, será criado localmente somente    a branch master. Se você desejar trabalhar em cima de outra branch, basta executar o comando git checkout nova-branch, e a branch será criada localmente.
Um comando legal que você pode testar é esse: git log --all --decorate --oneline --graph.
O comando git log irá mostrar o histórico dos commits. Colocando o --decorate você irá ver para qual commit cada branch está apontando. O --oneline irá mostrar somente uma linha para cada commit para ficar mais fácil de visualisar. O --graph irá mostrar em quais pontos as branches bifurcaram e em quais pontos foram feitos merges. O --all irá mostrar o commit de todas as branches. Sem o --all somente os commits do HEAD serão mostrados, que no caso, são os commits da atual branch.
Além de mudar de branch, o git checkout pode ser usado para voltar um determinado arquivo para seu estado na staged area. A staged area são os arquivos que estão prontos para serem comitados. Em outras palavras, são os arquivos que executamos o comando git add. Se não há versão do arquivo na staged area, ele será retornado para a sua versão do último commit.
Imaginemos o seguinte cenário:

echo algum texto > a.txt
git add a.txt
git commit -m 'adicionando a'
echo alterando texto de a > a.txt

Nesse ponto, não desejamos comitar a alteração feita em a.txt. Queremos desfazer a alteração. Nesse caso, podemos usar o comando git checkout a.txt. As alterações feitas no arquivo serão descartadas.
Esse comando pode também ser usado das seguintes formas:

Para mais de um arquivo: git checkout a.txt b.txt
Para um diretório: git checkout teste

Podemos, no entanto, fazer um checkout para o arquivo em outra branch.
No exemplo que você deu o que aconteceu foi o seguinte:
Ao executar o comando git checkout novo -- . Foi feito o checkout de todos os arquivos do diretório atual que estão na branch novo. Nesse caso, os arquivos que existem na branch master e existem na branch novo, serão substituídos pela versão que está na branch novo. Os arquivos que apenas existem na branch novo serão adicionados na branch master.
O comportamento é similar se você estiver fazendo checkout dos arquivos na mesma branch. Imaginemos o seguinte cenário:

A branch master possui os seguintes arquivos comitados: a.txt e b.txt.
Você então remove o arquivo b.txt, altera o a.txt e cria o c.txt
Você então executa o comando git checkout .

Veja que o comportamento será o mesmo. O arquivo a.txt volta para o estado do último commit na branch novo, o arquivo b.txt volta a aparecer e o arquivo c.txt continua aparecendo, mas como untracked.
A diferença desses casos são:

git checkout . - Os arquivos do diretório atual serão retornados para suas versões na staged area. Se não houver versão na staged area, serão retornados para suas versões no último commit na branch.
git checkout nome-branch . - Os arquivos do diretório serão retornados para versão do último commit da branch desejada.

No caso de ser criado um novo arquivo e esse arquivo não ser comitado, quando for realizado o git checkout ., esse arquivo não irá sumir. Isso porque o git não tem conhecimento desse arquivo, porque ele ainda não foi versionado. Ele continuará no working copy como um arquivo untracked.
Do mesmo modo, se um arquivo apenas existe na branch master e não existe em outra branch, ao executar o comando git checkout outra-branch, esse arquivo não irá sumir, porque na outra branch o git não tem conhecimento desse arquivo, portanto ele não irá fazer nada com o mesmo.
Para fins de esclarecimento, o "." significa que será utilizado o atual diretório e não todos os arquivos. Se você estiver no diretório raiz coincidentemente serão utilizados todos os arquivos. Mas se você entrar em algum diretório e executar o comando com o ".", será feito o checkout em todos os arquivos desse último diretório.

Tem como o git sobre-escrever um arquivo de nome diferente?

Não. O git só irá sobre-escrever arquivos com o mesmo nome.
Se for utilizado o comando git mv o git saberá que o arquivo foi renomeado. Se o arquivo for renomeado sem esse comando, o git identificará que houve a remoção do arquivo com o antigo nome e que houve a criação do arquivo com o novo nome. Ainda assim, após executar o git add para as duas operações, o git conseguirá identificar que houve um rename.
Se o arquivo for renomeado em uma determinada branch, ao fazer merge com outra branch que está com o arquivo com o nome antigo, o git saberá que se trata do mesmo arquivo e tentará fazer o merge. Contudo, o mesmo não se aplica se for utilizado o git checkout. O git não conseguirá fazer o checkout de um arquivo em outra branch se o arquivo não estiver com o mesmo nome. Exemplo:

echo primeira linha > a.txt
git add a.txt
git commit -m 'adicionando arquivo a.txt'
git checkout novo
git merge master
git mv a.txt novoNome.txt
git commit -m 'alterando nome de a para novoNome'
git checkout master

Nesse ponto, se for executado o comando git checkout novo d.txt, o git não irá encontrar esse arquivo na branch novo. Se for executado o comando git checkout novo novoNome.txt, o subsequente arquivo será trazido para a branch master mas não irá substituir o antigo d.txt.
Comment: Parabéns por essa explanação sucinta.


Is it possible/ feasible to convert ordinary nodes to Ubercart nodes?

Question: I have a site that imports content from several XML and CSV feeds, which creates nodes for each item (the items are products, but the site does not directly sell each product).
I'm just wondering if it's i) possible and ii) feasible to convert these nodes to be usable with Ubercart? Although the site doesn't directly sell the products (each product links to the supplier's site), there are features in Ubercart that are attractive to use - in particular, an Ubercart theme that I would like to use on the site.
Answer: I'm not sure how the ubercart theme you're interested in works, but you can declare any content type as an ubercart 'product' type. This would eliminate the need to convert exsiting/imported nodes, but I'm not sure if the theme you're looking at is only set up for the default Product type that ubercart creates for itself.


Open Editor From Command Line and Fetch Input

Question: I'm currently working on a feature for CocoaPods, a Ruby gem. There's an existing command that accepts a number of options. I'd like to add an extra option that enables the user to enter a custom message by opening the default text editor and, when the user saves and quits the editor, the message is fed to the command that was executed.
What I want to replicate is how you can add -m to the git commit command to have you enter a commit message. I have little experience with creating command line tools so any help is much appreciated.
The goal is to execute a specific command command --message, open the editor, have the user enter a custom message, and execute the command with the custom message being one of the arguments stored in argv.
Comment: The `interactive_editor` gem seems related to what you try to achieve. I did not check the source, but there might be ideas to pick there.
Answer: The common workflow is:

the caller application creates a temporary file;
determines the default editor (for Debian-based it would be /usr/bin/editor, for other linuces — the content of shell variable $EDITOR, etc);
runs a shell command in a subshell with Kernel#system (not with backticks!);
waits for it to exit;
determines the exit code, and skips following if it is not 0;
reads the content of temporary file, created in step 1 and removes this file.

In ruby that would be like:
▶ f = Tempfile.new 'cocoapods'
#⇒ #<File:/tmp/am/cocoapods20151120-6901-u2lubx>
-rw------- 1 am am 0 nov 20 15:03 /tmp/am/cocoapods20151120-6901-u2lubx
▶ path = f.path
#⇒ "/tmp/am/cocoapods20151120-6901-u2lubx"
▶ f.puts 'This content is already presented in file'
#⇒ nil
▶ f.close # HERE MUST BE ENSURE BLOCK, BUT FOR THE SAKE OF AN EXAMPLE...
#⇒ nil
▶ system "editor #{path}"
#⇒ Vim: Warning: Output is not to a terminal

If you are testing this in console, just type anything, followed by Esc:wq. In real life there will be normal vim (or what the default editor is) opened.
▶ File.read path
#⇒ "GGGGGGGGGThis content is already presented in file\n"

All together:
#!/usr/bin/env ruby

require 'tempfile'

f = Tempfile.new 'cocoapods'
path = f.path
f.puts 'This content is already presented in file'
f.close # HERE MUST BE ENSURE BLOCK, BUT FOR THE SAKE OF AN EXAMPLE...
system "editor #{path}"
puts File.read path

Comment: Oh, sorry, I messed things up: to invoke an editor in the same context (in a subshell,) one should use [`Kernel#system`](http://ruby-doc.org/core-2.1.5/Kernel.html#method-i-system) rather that backticks. I updated an answer with the code of the whole script for your convenience.
Comment: That's a great start. The problem I'm running into is getting the contents of the file before the Ruby script exits. The Ruby script exits when the editor is opened. I was hoping/expecting that it would continue its execution the moment the editor is closed. You write `File.read path`. Where do you read the contents of the temporary file?


What faster proxy_pass or redirect to resource

Question: I transfer my website to new webserver, without assets. I have flolowing links: site.com/img/image.png on new website but now, it's got 404 error
also I have old server with images on the same paths, it's look like old.site.com/img/image.png
I have two options:

use proxy_pass to get images by old paths from old.site.com
use redirect to redirect queries for images to old.site.com

what way is more correct and faster?
Answer: proxy_pass is probably the better way to do this as you are presumably updating links and moving images to the new server. A redirect should also return a status response of some kind which could cause problems for search.


Are pairwise-convex cost functions also globally-convex?

Question: I would like to get a better intuition for a cost function of an optimisation problem. The cost function depends on a number of real-valued arguments. I would like to find out if the cost function is convex.
Obviously I can visualise the cost function for 2 arguments in a 3-dimensional plot. I did this for all pairs of arguments and it turned out that the cost function is convex for all these pairs.
Now I would like to know: does this imply that the cost function is also globally convex?
Answer: No.  There is a simple counterexample in two variables that generalizes to more variables: consider
$$f(x,y) = x^2 y^2$$
defined in (say) the square $[0,2]\times[0,2]$.
For fixed $y$, $f$ describes a convex parabola (as a function of $x$) and for fixed $x$ it also describes a convex parabola (as a function of $y$).  The coordinate lines in the figure are examples of these parabolas.

(For clarity, this figure shows a portion of the graph of $f$ restricted to the triangle bounded by $(0,0)$, $(2,0)$, and $(0,2)$.)
However, $f$ is not convex; for instance, although $(1,1) = \frac{1}{2}(2,0) + \frac{1}{2}(0,2)$,
$$f(1,1) = 1^21^2 = 1 \gt \frac{1}{2} 0 + \frac{1}{2} 0 = \frac{1}{2} f(2,0) + \frac{1}{2} f(0,2),$$
demonstrating $f$ cannot be convex on any domain containing the line segment connecting $(2,0)$ to $(0,2)$: the graph of $f$ on this segment, shown in red, clearly is not convex in most locations.
Because this $f$ is about as well behaved as you might like--it is strictly convex away from the coordinate axes and continuously infinitely differentiable (even analytic)--this counterexample is not due to some special "pathology" that can be made to go away through some inconsequential technical restrictions.
For a counterexample with three variables look at $f(x,y,z) = (x^2+y^2)(y^2+z^2)(z^2+x^2)$ defined within the first octant ($x, y,$ and $z$ all positive).  The determinant of its Hessian is everywhere negative, showing this is not a convex function, but it is convex when any single one of the variables is fixed at a positive value (as you can check by calculating the determinant of its Hessian in the remaining two variables, which will be positive in the first quadrant with positive eigenvalues).


Show that $(X,|||\cdot|||)$ is a Banach space.

Question: In the book 'Classical Banach Spaces I and II' by Lindenstrauss, page $1,$ Chapter $1$, he stated the following:

Let $(X,\|\cdot\|)$ be a Banach space with a (Schauder) basis $(x_n)_{n=1}^{\infty}.$ For every $x = \sum_{n=1}^{\infty}a_nx_n$ in $X$ the expression
  $$|||x||| = \sup_{n}\left\Vert \sum_{i=1}^n a_ix_I \right\Vert$$
   is finite. Evidently, $|||\cdot|||$ is a norm on $X$ and $\|x\| \leq |||x|||$ for every $x \in X.$ A simple argument shows that $X$ is complete also with respect to $|||\cdot|||.$

Question: How to use a simple argument to show that $(X, |||\cdot|||)$ is complete? I manage to prove all statements before it. Below is my partial attempt (actually is not even partial).
Suppose that $(x_n)_{n=1}^{\infty}$ is a Cauchy sequence in $(X, |||\cdot|||).$ Since $\|\cdot\| \leq |||\cdot|||$ and $(X,\|\cdot\|)$ is a Banach space, there exists an $x \in X$ such that $\lim_{n}\|x_n - x\| = 0.$
I think I should I show that $x_n$ converges to $x$ in the norm $|||\cdot|||.$ But I have no idea how to show at all.
Any hint would be appreciated.
Answer: $\newcommand{\nv}[1]{{\left\vert\kern-0.25ex\left\vert\kern-0.25ex\left\vert #1\right\vert\kern-0.25ex\right\vert\kern-0.25ex\right\vert}}\newcommand{\veps}{\varepsilon}$Let $\{y_n\}_{n=1}^{\infty}$ be a Cauchy sequence in $(X,\nv{\cdot})$, and for every $n\in\mathbf{N}$ write in the Schauder basis, $$y_n=\sum_{i=1}^{\infty}a^{(n)}_ix_i.$$
    For any fixed $i\in\mathbf{N}$ that $$|a_i^{(n)}-a_i^{(m)}|\|x_i\|=\|(a_i^{(n)}-a_i^{(m)})x_i\|\leq\left\|\sum_{j=1}^{i}(a_j^{(n)}-a_j^{(m)})x_j\right\|+\left\|\sum_{j=1}^{i-1}(a_j^{(n)}-a_j^{(m)})x_j\right\|\leq 2\nv{y_n-y_m}.$$
Since $x_i\neq 0$, we deduce that $\{a_i^{(n)}\}_{n\in\mathbf{N}}$ is a Cauchy sequence in $\mathbf{R}$, and so $a_i^{(n)}\to a_i$ for some sequence of scalars $a_i$.
Now fix $\veps>0$ . Since $\{y_n\}$ is Cauchy with respect to $\nv{\cdot}$ there exists some $N_0\in\mathbf{N}$ such that for all $n,m\geq N_0$ $\nv{y_n-y_m}<\veps/3$. Now fix any $m\geq N_0$, $M\in\mathbf{N}$, and for all $n\in\mathbf{N}$ define $$z_n^{m,M}=\sum_{i=1}^{M}(a_i^{(n)}-a_i^{(m)})x_i.$$ We see that $\|z_n^{m,M}\|\leq\nv{y_n-y_m}<\veps/3$ for all $n\geq N_0$. Since $z_n^{m,M}\to z^{m,M}:=\sum_{i=1}^{M}(a_i-a_i^{(m)})x_i$ as $n\to\infty$ we see that $\|z^{m,M}\|\leq\veps/3$. Since $M$ was arbitrary we see that for all $m\geq N_0$, \begin{align}
 \sup_{M}\left\|\sum_{i=1}^{M}(a_i - a_i^{(m)})x_i\right\|\leq\frac{\veps}{3}.\tag{1}
 \end{align}
    Now we show that $\sum_{i=1}^{\infty}a_ix_i$ converges in $(X,\|\cdot\|)$. Fix any $m\geq N_0$ and since $y_m\in X$ we see that $\sum_{i=1}^{\infty}a_i^{(m)}x_i$ is convergent in $X$, and so the tail of the sequence can be made arbitrarily small. Rigorously, there exists some $N_1\in\mathbf{N}$ such that $M_2>M_2>N_1$ implies $$\left\|\sum_{i=M_1}^{M_2}a_i^{(m)}x_i\right\|<\frac{\veps}{3}.$$ The triangle inequality gives us $$
 \left\|\sum_{i=M_1}^{M_2}a_ix_i\right\| = \left\|\sum_{i=M_1}^{M_2}a_i^{(m)}x_i + \sum_{i=1}^{M_2}(a_i-a_i^{(m)})x_i - \sum_{i=1}^{M_1-1}(a_i-a_i^{(m)})x_i\right\|\leq\veps.$$ Hence $\{\sum_{i=1}^{n}a_ix_i\}_{n\in\mathbf{N}}$ is a Cauchy sequence in $(X,\|\cdot\|)$; since $X$ is complete, $y:=\sum_{i=1}^{\infty}a_ix_i$ converges in $X$.
In light of the above convergence and (1) we see that $\nv{y-y_m}\leq\veps/3$ for all $m\geq N_0$. Since $\veps$ was arbitrary $y_m\to y$ as $m\to\infty$ with respect to $\nv{\cdot}$, which establishes the completeness of $(X,\nv{\cdot})$.
Comment: @Idonknow The coordinate functionals of a *Schauder* basis in a Banach space are always continuous (even in the infinite dimensional case). Of course this does not hold if you are using a Hamel basis or if you are just working in a normed vector space. Using the above result, you can show that the "projection" operators $\Pi_n:X\to X$ defined by $\Pi_n(\sum a_i x_i) = \sum^n a_ix_i$ are continuous and uniformly bounded, from which it follows that the coordinate functionals are continuous by using the argument that daw commented.
Comment: Thanks. How to show that coordinate functionals are continuous? I think it is continuous on a finite dimensional space only?
Comment: @daw you only showed that the coordinate functionals are continuous with respect to $\nv{\cdot}$, and not with respect to the original norm of $X$. I edited my solution not to make use of the fact that the coordinate functionals are continuous!


I'm making a good chord progression, but I'm stuck

Question: It goes Dm, then C#Aug, and then something with the note B as the root. Can someone help me understand where this is going? I don't have a lot of music theory experience, so I'm sorry that I'm asking such a basic question.
Comment: Very much a question with only opinions for answers - there's no other way! It will also depend a lot on what *voicings* are used. That C#+ is also A+, so could take the tune somewhere completely different. Or even back to Dm! Instead of asking for others' opinions, keep at it, and come up with at least half a dozen ideas of your own.Good luck.
Comment: A question to ask oneself: **why is the bass going to B?** There's nothing wrong with that at all, but it is an arbitrary decision. And if there's an answer to that question, perhaps use the principles of that logic to inform a decision on what chord to follow it with.
Answer: Your Dm and C#aug share two pitches. Dm = D F A and C#Aug = C# F A.1 So, for those two chords, you're really just changing the lowest note. Since you hear B next, that would be a logical continuation: D C# B. Try keeping the top two notes the same again: B F A. Since we just heard a D in the Dm chord, our ears can hold onto the memory of that, so B F A will sound very much like B D F A, which is Bm7b5.
So try: Dm C#Aug Bm7b5. That is to say: D F A, C# F A, B F A.

1 The correct spelling of C#aug is C# E# G##; however, I've used the enharmonically equivalent C# F A to make clear the relationship to the Dmin chord. Augmented chords have three enharmonically equivalent instances, differentiated by spelling. In this case: C#aug = C# E# G##; Faug = F A C#; Aaug = A C# E#.
Comment: @Tim https://www.youtube.com/watch?v=hNuhF84wwt0
Comment: With my 'picky' hat on, C#+ is C#, E#, Gx. Worth mentioning for accuracy.
Comment: Doesn't A+ have A C# and E#? Don't understand the last comment, or much else today, it seems...
Comment: @Tim It's a line from the move The Princess Bride — worth a watch if you've never seen. Around these parts it's up there with Monty Python and The Holy Grail for quotability.
Answer: I was initially thinking along the lines of @Aaron and I think that is a nice solution (+1). However I also thought if you want a little contrast to the harmony at that point you could go to a G/B (a G triad with B in the bass). This gives you some nice chromatic and stepwise motion in the harmony:
C# to D or B
F to G
A to G or B.
That can possibly be followed by a Gm/Bb, continuing the descending bass motion.
Comment: I felt the bass run going down to C before it got to B, although that does sound like quite a few other songs.
Comment: @Tim I also thought of chromatic descending when I first read the question. You're right, that has already been used in many other songs.
Answer: From a purely creative standpoint, I followed your first two chords with Bmaj7, and then E6(11).
(This is on a guitar, mind you.)
That's where the muse took me.


Interpreting OLS Cross-Sectional Macro Data

Question: I have the following model: $y=a_0+a_1(x_1/z_1)+a_2(x_2)+e $, where
$y$ = the average log of variable y,
$x_1$ = the average ratio of $ x_1/z_1 $,
$x_2$ = is the averae log of the variable $x_2$.
The values of the coefficients are :
$a_1=0.012$,
$a_2=0.049$.
The data are cross-sectional macroeconomic variables.
I wonder how can I interpret these coefficients since i am confused from some similar papers that i have seen they inerpret it with different ways. I mean in one paper says:
" 1% increase of x1 increases y by 1.2% but another paper says 0.012%" and the same with the x2 which is log " the first says 4.9% and the second 0.049%"
which of them are correct?
Comment: I wonder whether your definition of $x_1$ is correct, since it appears on both sides of the equation?
Answer: It appears you have estimated a relation
$$ \ln Y = a_0 + a_1(X_1/Z_1) + a_2 \ln X_2$$
so
$$a_2 = \frac {\partial \ln Y}{\partial \ln X_2}$$
By treating partial differentials as quantities (I won't tell if you don't)
We have
$$\frac {\partial \ln Y}{\partial \ln X_2} = \frac {\partial \ln Y}{\partial \ln X_2}\cdot \frac {1}{\partial X_2/\partial X_2} = \frac {\partial \ln Y}{\partial X_2}\cdot \frac {1}{\partial \ln X_2/\partial X_2}$$
$$=\frac {1}{Y}\frac {\partial Y}{\partial X_2} \cdot \frac {1}{1/X_2} = \frac {\partial Y}{\partial X_2} \cdot \frac {X_2}{Y} = \frac {\partial Y/\partial X_2}{Y/X_2}$$
The last expression is the definition of point elasticity (the ratio of "marginal over the average"), and for small changes in $X_2$, it approximates the more general definition of elasticity expressed as
$$\frac {\text {% Δ in Y}}{\text{% Δ in}\, X_2}$$
In your case therefore
$$\frac {\text {% Δ in Y}}{\text{% Δ in}\, X_2} = a_2 = 0.049$$
then, if  $\text{% Δ in}\, X_2 =0.01$ we have
$$\text {% Δ in Y} = 0.049 \times 0.01 = 0.00049 = 0.049\%$$
So the second paper is correct (the change in $Y$ is ~"five basis points", as a banker would say).
Comment: Tiny remark: in your second equation, I think you were going for $a_2$, not $a_1$.
Comment: @Alecos Papadopoulos I really thank you about your analytical answer. Now it is totaly clear to me.


Múltiplas conexões com dispositivos usando Sockets

Question: Tenho um método que se conecta a um leitor de cartão via TCP/Ip (ip, porta) usando Sockets. Para a conexão 1:1 está funcionando, mas agora preciso me conectar a mais de um equipamento simultaneamente. Eu teria que criar uma Thread para cada conexão, ou teria outra maneira de fazer isso? Lembrando que meu sistema é um "client" dos leitores.
Comment: E qual é a dúvida/problema?
Comment: "Eu teria que criar uma Thread para cada conexão, ou teria outra maneira de fazer isso?"
Answer: Isso depende dos métodos que está usando para se conectar, enviar e receber dados.
Se estiver usando por exemplo os métodos Connect, Send e Receive eles bloqueiam a execução então seria necessário o uso de Threads, porém isso não é o mais recomendado, o mais recomendado é usar os métodos assíncronos.
Usando os métodos BeginConnect, BeginSend e BeginReceive você não deve ter problemas já que eles não bloqueiam o thread e usam um sistema de Callback para notificar quando terminaram de executar ou receberam dados.
Answer: Prezado JcSaint,
Uma implementação de socket não é uma tarefa tão simples, mesmo com as várias abstrações que o .NET oferece.
É possível sim iniciar uma nova thread por conexão mas este não é o método recomendado pois se houver sobrecarga o sistema operacional provavelmente vai matar seu processo.
Em um servidor web que desenvolvi utilizando C++ utilizei a abordagem assíncrona, utilizando 1 thread para recebimento de novas conexões e uma fila (pool) de conexões a qual é processada pelas demais threads físicas disponíveis no hardware (assim obtive melhor desempenho para meu caso), sendo estas devidamente sincronizadas quando necessário.
Espero ter ajudado.
Comment: Neste caso eu teria que implementar algo em c++, gerar uma dll e consumi-la no c# ?
Comment: A mesma implementação pode ser feita em C#, utilizando as sockets prontas do .NET Framework ou outra tecnologia. Coloquei como um exemplo da implementação que fiz em C++ pois não desenvolvi código equivalente em C#, mas é plenamente possível.


Persistence in time series

Question: Could someone tell me what the term 'persistence' mean in time series analysis? It's regarding econometrics and applied regression.
Answer: Roughly speaking, the term persistence in time series context is often related to the notion of memory properties of time series. To put it another way, you have a persistent time series process if the effect of infinitesimally (very) small shock will be influencing the future predictions of your time series for a very long time. Thus the longer the time of influence the longer is the memory and the extremely persistence. You may consider an integrated process I(1) as an example of highly persistent process (information that comes from the shocks never dies out). Though fractionally integrated (ARFIMA) processes would be more interesting examples of persistent processes. Probably it would be useful to read about Measuring Conditional Persistence in Time Series in G.Kapetanios article.
Comment: In graduate level textbooks the persistence usually is the synonym of unit root.
Comment: I would appreciate if you could answer this question: https://stats.stackexchange.com/questions/388968/how-to-do-psm-with-panel-data-using-panelmatch Thanks @DmitrijCelov
Comment: The link to the article seems to be down. can you pls update
Answer: A persistent series is one where the value of the variable at a certain date is closely related to the previous value. The two basic measures of persistence are the autocovariance and the autocorrelation coefficient.

Persistence in time series


How can I get the current user role in my web app?

Question: I'm working on web app with a Drupal 8 back-end which is accessed by the D8 REST API.  I need to get the current user role so I can manage some options by role. Is there an existing REST route for getting the role and/or ID of the currently authenticated user.  I've had success with other REST routes like http://example.com/drupal/user/1?_format=hal_json, but this returns the user with id=1. What i'd like is http://example.com/cms/user/me?_format=hal_json
Any suggestions?
Comment: The https://www.drupal.org/project/jdrupal module has an example resource called Connect, which returns the current user's information, including their roles: http://cgit.drupalcode.org/jdrupal/tree/src/Plugin/rest/resource/jDrupalConnect.php
Answer: I have just used views to get this working.

Duplicate the default people view and rename it current_user.
Add a rest export route eg. rest/users/current_user.
Add a filter for current user. (User: Current = yes)
Save all.
Retrieve the current user via http get request on example.com/rest/user/current_user?_format=hal_json

Thanks to QueenVictoria for the advice.
Answer: I've used Views to do this as you can customise your permissions, path and fields. Roles aren't available on the native ReST path to anonymous users.
For example here is the role stanza for user 200 when logged in as user 1. This is missing when logged out. I presume that is a factor of
roles: [
  {
    target_id: "student"
  }
],

BTW isn't the default ReST path user/200?_format=hal_json?
Answer: The JSON API entrypoint contains data about the currently logged in user in meta.links.me. The core JSON API module needs to be enabled. The key meta.links.me won't exist for anonymous users. Visit /jsonapi, and get more information about the current user from the link at meta.links.me.href. Example output from /jsonapi:
{
  "jsonapi": {
    "version": "1.0",
    "meta": {
      "links": {
        "self": {
          "href": "http://jsonapi.org/format/1.0/"
        }
      }
    }
  },
  "data": [

  ],
  "meta": {
    "links": {
      "me": {
        "meta": {
          "id": "ba4f782f-2c5d-4280-8897-9e883f36711c"
        },
        "href": "https://example.com/jsonapi/user/user/ba4f782f-2c5d-4280-8897-9e883f36711c"
      }
    }
  }
}


Unable to connect to chef server

Question: I have a Chef server running on AWS. I am able to connect to it via web browser and see the web ui from my machine which isn't the ec2. But when I bootstrap the node, also a ec2, it fails to connect to the server after 5 attempts. If I copy and the exact url that it is trying to connect to from the error message and paste it into my browser it works. If I curl the url from the Chef server it works. If I curl the url or ping the IP from the node, it fails. Any ideas?
Comment: Feel free to post that an an answer and then accept it so this Q doesn't sit unanswered for all of eternity. :)
Comment: Turns out I had the Security group on the server set up to only accept Https  requests from my IP :/
Answer: Turns out I had the Security group on the server set up to only accept Https requests from my IP :/

Unable to connect to chef server


How to avoid having to use fully qualified name for the Styles.Render method in a Razor view

Question: I'm trying to implement the Styles.Render method in a project of mine and I am using the separate, pre-built MVC 4 internet application project that's created from the New Project wizard as my model.  In the pre-built MVC website's _Layout.cshtml layout view, the following code appears within the head tag:
<code>@Styles.Render("~/Content/css")
</code>
However, in my own project, just using the @Styles.Render syntax does not seem to work. For some reason, the view does not like it. And I have to resort to using the fully qualified version of the method:
<code>@System.Web.Optmization.Styles.Render("~/Content/css")
</code>
I would like to know what am I missing or how can I avoid having to use the fully qualified type and member syntax from within a Razor view in the manner of the pre-built version as described above?  Thanks.
Comment: Have you tried building your project and relinking the DLLs?  A lot of the time when I start a new project all of the razor syntax will not be accepted by intellisense until I build the project.
Comment: Yes, I did AgnosticDev. Thanks.
Answer: You're missing the System.Web.Optimization namespace reference in the web.config in the views folder
<code><configuration>
 <system.web.webPages.razor>
  <pages basePageType="...">
   <namespaces>
    <add namespace="System.Web.Optimization"/>
   </namespaces>
  </pages>
 </system.web.webPages.razor>
</configuration>
</code>
Comment: Hi, @RobertSlaney. That did the trick! Although, at first, when I put the namespace in the web.config file inside the Views folder, the build did not seem to take it (failed). And so, I went up a level higher and put the namespace in the web.config of the root level of the application. That worked and the build was successful.

However, still being curious, I took the namespace out of the root level and put it back again in web.config file of the Views folder. This time, the build did not complain about it. I find this interestingly odd. I kept it in the Views' web.config folder. Thanks.
Comment: Compare your web.config frmo the MVC4 template version.  There might be more namespaces you're missing.


jQuery mobile run on pagechange event to a specific page

Question: I want to catch the event if a specific jQuery mobile page changes. For example, I used the code which I indicated below:
$(document).on("pagechange", function () {
    alert("page changed");
});

But, how can I make this function run only for a specific page, for example: the page which has id="myPage"? I want to make it give alert only when myPage is changed.
(* I use multiple page structure in jquery mobile)
Comment: `$('#pageID').on("pagechange", function () { etc....`
Comment: someone answered it here just like what omar had commented.
http://stackoverflow.com/a/9609212/562036
Answer: I think you could register events on page instead of document:
<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">

Page 1

TWO

ONE

Page 2

TWO

ONE

If you prefer pagechange event, you could get the page URL:
$(document).on("pagechange", function(toPage) {
    alert(toPage.currentTarget.URL);
});

Answer: $(document).on('pagechange', '#myPage', function (event) {
    alert("I alert only on #myPage");
});

Comment: $('#myPage').on('pagechange', ... -- doesn't work, because the pagechange event is fired on the pagecontainer, see http://forum.jquery.com/topic/pagechange-event-not-firing


re-saving users with default field collection items

Question: I wanted to post to @Clive comment on How can I quickly re-save all users on my site? and ask about how to do this for fields in a field collection but couldn't because I've never posted to this site before so I had to ask a new question. He provided the following code to run as a php script in VBO on all users:
<code>$items = field_get_items('user', $entity, 'field_name');
if (empty($items)) {
   $entity->field_name[LANGUAGE_NONE][0]['value'] = 1;
}
user_save($entity);
</code>
This solution works great for a single field of a user. I need a similar solution for setting default field values in a field collection after importing users.
I migrated 6000+ users and have set default values for fields in a field collection after the fact that don't show up unless I re-save a user account. I want to bulk re-save all 6000+ users so that the default field collection fields are saved and are visible. It's almost identical to the original question except the field is not just a singular field associated with the entity -- the field(s) in question are part of a field collection. How do I access the fields from my default field collection to then force re-save of users?
Is the proper way to access field data through entity_metadata_wrapper? If this is the case, how do I get/set the values of fields in a field collection that I want to associate with users using this wrapping class?
Answer: This finally worked for me -- may it save someone hours of headaches:
<code>// load the user
$userwrapper = entity_metadata_wrapper('user', $entity);
// apparently you have to create the field collection entity
$fieldCollection = entity_create('field_collection_item', array('field_name' => 'field_yourCollectionName'));
// attach your field collection to the user
$fieldCollection->setHostEntity('user', $entity);
// set the value of one of your fields in your field collection - in my case it's a boolean
$userwrapper->get('field_yourCollectionName')->field_fieldNameInYourCollection->set(0);
// save the entity
$userwrapper->save();
</code>


Proof of $|z^n| = |z|^n$, where $n \neq 0$

Question: With complex numbers, I can see intuitively that the modulus of $z^n$ must be equal to the modulus of $z$, all to the power of $n$, but I'm not sure how to prove it. Thanks
Comment: Are you familiar with the polar form $z=re^{i\theta}$?
Comment: You  can also prove this induction if you first prove that $|z_1z_2|=|z_1||z_2|$.
Comment: Prove the squares are equal, as $|z|=\sqrt{z\,\bar z}$.
Comment: We haven't yet covered the polar form but I will definitely come back to that once we have, both other suggestions are very helpful though, thank you
Answer: Let $z=r(\cos(\theta)+i\sin(\theta))$. By definition, we know that:
$$|z|=|r(\cos(\theta)+i\sin(\theta))|=r$$
By De-Moivre's rule, we have:
$$|z^n|=|r^n(\cos(n\theta)+i\sin(n\theta))|=r^n$$
Using the definition said before, we arrive at:
$$|z^n|=r^n=|z|^n$$
Comment: Thank you! That's very helpful
Answer: $$|a+ib||c+id|=\sqrt{a^2+b^2}\sqrt{c^2+d^2}=\sqrt{a^2c^2+a^2d^2+b^2c^2+b^2d^2}$$ and
$$|(a+ib)(c+id)|=|(ac-bd)+i(ad+bc)|=\sqrt{(ac-bd)^2+(ad+bc)^2}=\sqrt{a^2c^2+a^2d^2+b^2c^2+b^2d^2}$$
shows that $$|wz|=|w||z|.$$
Then you easily prove the claim by induction.
Comment: Thanks very much!
Answer: Since $z\bar z\ge 0$ and $|z|=\sqrt{z\bar z}\quad$ then $$\quad|z^n|=\sqrt{z^n\overline {z^n}}=\sqrt{z^n\bar z^n}=\sqrt{(z\bar z)^n}=(\sqrt{z\bar z})^n=|z|^n$$
I agree though, you can object that we have to display a proof of $(\bar z)^n=\overline{z^n}$ ...
In which case we also have to go for induction as in Y.Daoust answer on
$\begin{align}\overline{uv}&=\overline{(a+ib)(x+iy)}=\overline{(ax-by)+i(ay+bx)}=(ax-by)-i(ay+bx)\\&=(ax-(-b)(-y))+i(a(-y)+(-b)x)=(a-ib)(x-iy)=\bar u\bar v\end{align}$


Help with a recurrence relation?

Question: I stumbled on this recurrence relation while looking at a kind of growth process. Unfortunately I haven't seen anything like this since high school! Is there a way to solve this?
$a_2 = 0$, and for $i=3,4,5,\dots$
$$a_i = \left(1-\frac{1}{i-1}\right)a_{i-1} + \frac{4}{(i-1)(i-2)}$$
The first few terms are $a_2=0$, $a_3=2$, $a_4=2$, $a_5=11/6$, $a_6=5/3$, $a_7=137/90$
Thanks!
Answer: Rewrite $1-\dfrac1{i-1}$ as $\dfrac{i-2}{i-1}$ and multiply both sides by $i-1$ to get
$$(i-1)a_i=(i-2)a_{i-1}+\frac4{i-2}$$
Now let $b_i=(i-1)a_i$ to get
$$b_i=b_{i-1}+\frac4{i-2}$$
and
$$b_i=\sum_{j=3}^i\frac4{j-2}=4H_{i-2}$$
where $\displaystyle H_n:=\sum_{k=1}^n\frac1k$ are the harmonic numbers. This then gives us the solution
$$a_i=\frac{4H_{i-2}}{i-1}$$
Comment: Amazing. Thank you!

Help with a recurrence relation?


Disponibilizar componentes React como dependencia

Question: blz?
eu tenho alguns componentes react aqui e preciso disponibilizar todos eles em uma dependência so, estilo o semantic,
como posso fazer isso?
eu estou tentando exporta os componentes em um index que importa e exporta tudo
mas eu estou tendo um problema
no projeto que usa a dependência dos componentes, o js que chega não vem transpilado
ex: no projeto com os componentes eu faço um index e importo os componentes assim

[imagem 1]
no projeto que usa a dependência eu importo os componentes, mas se eu mandar da um build ele da esse erro
[imagem 2]
caso eu não de um build e mande da start de uma vez, o projeto sob mas da um erro no js do navegado pq o js dos componentes estão vindo como es6
[imagem 3]
alguem sab oq pode ser? e como resolver?
obs: desculpa a imagem, não posso colocar mais de 1 link
Answer: Você precisa compilar sua lib antes de utiliza-la, essa é a melhor forma de reaproveitar seus componentes em outro projeto.
Sabendo disso, agora a pergunta que fica é, como fazer?
Se você estiver usando Webpack, continue usando ele, mas se atente as mudanças que você precisa fazer para publicar seu projeto como uma library, recomendo seguir a própria documentação do Webpack para que você consiga fazer isso no seu projeto:
https://webpack.js.org/guides/author-libraries/#components/sidebar/sidebar.jsx
Caso não esteja usando Webpack, recomendo usa-lo ou então, usar o Rollup.js que é uma solução criada especialmente para este fim.
Um detalhe importante para você se apegar é sobre os stylesheets. Tente extrai-los em um arquivo <code>.css</code> separado, se você não o fizer, os estilos dos seus componentes serão embarcados juntos com a lógica (script), o que vai implicar em perca de performance e visualmente vai parecer estranho também.


Remainders of $(1-3i)^{2009}$ when divided by $13+2i$ in $\Bbb{Z}[i]$

Question:
Find the possible remainders of $(1-3i)^{2009}$ when divided by $13+2i$ in $\mathbb{Z}[i]$.

I'm having a hard time understanding remainders in $\mathbb{Z}[i]$. I'm gonna write my solution to the problem above just to give some context, but you can skip this part and read the question below if you want. We start by noticing that $N(13+2i) = 173$, which is a prime number. Therefore, $13+2i$ is irreducible in $\mathbb{Z}[i]$. This allows us to quickly calculate the number of elements of the multiplicative group $(\mathbb{Z}[i]/(13+2i))^{\times}$, namely $N(13+2i) - 1 = 172$. By Lagrange's Theorem, since $1-3i$ and $13+2i$ are coprime,
$$(1-3i)^{11\cdot 172} \equiv 1\mod(13+2i).$$
We now reduced the problem to finding $(1-3i)^{117} \mod (13+2i)$. Note that $117 = 3^2\cdot 13$, so by a tedious but direct calculation (once we figure out $(1-3i)^{3^2}$ modulo $13+2i$ we get a nice expression, so the $13$th power is relatively straightforward to compute), we arrive at $6-2i$.
Question: Remainders in $\mathbb{Z}[i]$ are not uniquely determined and, from my understanding, there are $4$ possible choices. It is not difficult to find different remainders when we are working with small numbers and can test various quotients. In this case, however, how would I determine the other possible choices? Are they somehow related? For instance, when I was calculating $(1-3i)^{3} = -26+18i$, I found that
$$(1-3i)^{3} = (-2+i)(13+2i) + (2+9i) = (-1+2i)(13+2i) + (-9-6i).$$
The remainders above have norms $N(2+9i) = 85$ and $N(-9-6i) = 117$. I thought they would have to be associates, but the example above shows they are not and, even worse, $\operatorname{gcd}(85, 117) = 1$.
Comment: I am confused by $N(13+2i)$ is a prime, therefore irreducible; is that a theorem? Isn't $N(5)$ a prime, but is clearly reducible, $5=(2+i)(2-i)$. I think the $i$ is throwing you off, maybe it would be better to use $x$, in general the remainder should be of less degree than the divisor (which would be all real I would think).
Comment: $N(5)$ is the norm, so $N(5) = 5^2$.
Comment: Oh right, is that a theorem? I also thought about my second comment, the polynomial is $x^2+1$ so the remainder would be linear not constant.
Comment: Something is wrong. I thought remainders from polynomial division are always unique. Are you sure your calculations are correct? I see that $(13+2j)^3 = (2041+1006j)$, that appears to be different than what you have.
Comment: You're confusing the Gaussian integers with polynomial rings. The euclidean division in a polynomial ring $K[X]$ is given by the degree of the polynomial (when $K$ is a field). In $\mathbb{Z}[i]$ the euclidean function is $N(a+ib) = a^2 + b^2$.
Comment: I'll edit that, it is supposed to be $(1-3i)^3$.
Comment: Sorry, I am still not understanding. You talk about division and remainder of elements in $\mathbb{Z}[i] \approx \mathbb{Z}[x]/$. What exactly do you mean by "division" and "remainder" if not in the same meaning as polynomial division and remainder?
Comment: Again, as I said in the comment above, euclidean division in a polynomial ring is given by the degree of the polynomial only when $K$ is a field. In fact, $D[X]$ is an euclidean domain if and only if $D$ is a field. It doesn't make sense to talk about division in $\mathbb{Z}[X]$.
Comment: Sure, but that still doesn't tell me what you mean by "remainder"? I am clearly not as familiar with Gaussian integers as you and mistakenly assumed that "remainder" had some obvious meaning, this appears to not be the case.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/151639/discussion-between-test1-and-bobby-ocean).
Comment: [A related thread with smaller numbers](https://math.stackexchange.com/q/375071/11619).
Comment: https://www.wolframalpha.com/input?i=%281%2B3i%29%5E2009+mod+13%2B2i
Answer: Posting this because the existing examples I could easily find, indeed, use small numbers only, and that does allow the law of small numbers to kick in and ruin examples (most notably when looking at the remainders modulo $2+i$, when we can always find a remainder of norm $\le1$). Below is how I (and undoubtedly most, if not all, the other teachers) explain remainders in $\Bbb{Z}[i]$.

Write $p=13+2i$ for short. Look at the picture:

The black dots are the grid of Gaussian integers. The red dots mark the elements of the ideal generated by $p$. They also form an infinite pattern of repeating squares with sides given (as vectors) by $p$ and $ip=-2+13i$.
You see that the remainder $r=6-2i$ (marked by a green dot) falls into a square with corners at $0$, $p$,
$-ip$ and $(1-i)p$. The four possible remainders are the separation of $r$ from each of these: $r=6-2i$, $r-p=-7+4i$, $r+ip=4+11i$, and $r-(1-i)p=-9+9i$. All of those happen to have norms $<173$, but this is only because the green dot is not very close to any of the four corners.
It may be even more natural to see where those alternative remainders lie on the plane. You see, they are elements of the coset $r+p\Bbb{Z}[i]$, each in one of the "red" squares touching the origin. The alternatives are marked by blue dots in the accompanying (enlarged) figure below with their coset relation hopefully apparent.

You asked about the norms of the alternative remainders. There is no need for them to be equal. This does not hold in $\Bbb{Z}$ either. When you find the remainder of $a$ modulo $b>0$, the alternatives are $r\in[0,b-1]$ and $r-b$, and more often than not $|r|\neq |r-b|$. It won't surprise me if we can find a relation tying the norms of the four possible remainders together, after all they are the distances from a point inside a square to the four corners. But I don't recall one right away.

As has been explained earlier on this site, the difference between $\Bbb{Z}$ and $\Bbb{Z}[i]$ is that in the case of integers there are only "two regions of remainders touching the origin" as opposed to four. Furthermore, in the integer case we can (artificially) only use one of them (=the non-negative remainders) as no point within is too far from the origin. Here the size of the dividend is the length of the side of the square, and we need to exercise a modicum care not to pick remainder too close to an opposite corner.
Comment: Typically teachers use only smaller numbers when explaining this in class. That's why I posted. The theme has been discussed earlier, but I couldn't find pictures. Will delete, if a good duplicate visualizing the idea is located.
Comment: Thank you! Your explanation really cleared things up for me. Now I've got a better grasp on what's going on geometrically in $\mathbb{Z}[i]$.
Answer: The map $\mathbb{Z}\hookrightarrow \mathbb{Z}[i]$ induces an isomorphism  of fields
$$\mathbb{Z}/173 \simeq\mathbb{Z}[i]/(13+2i)$$
So we could work with representatives in $\mathbb{Z}$, which is sometime easier. By the above $ {80}\mapsto i$, and $107\mapsto 1-3i$. Note that $107$ is a primitive root $\mod 173$.
About remainders : it seemed to me that for the Gaussian integers the remainder of $a \in \mathbb{Z}[i]$ $\mod b$ is obtained as follows: consider a closest element $b q$ of $b \mathbb{Z}[i]$ to $a$. Then $b$ will be the "quotient", and the remainder is $a- b q$. In the case $N(b)$ odd, the closest element is unique, and so is the remainder. (We need the closest so the Euclidean algorithm works). Note that one could do the closest multiple also in $\mathbb{Z}$ ( so the remainder is at most half of the divisor, in absolute value).
Example:
1.
$$\frac{107}{13+2i} = \frac{1391}{173} -\frac{214}{173}i$$
2.
$$(\frac{1391}{173}, -\frac{214}{173})\simeq(8,-1)$$
3.
$$107 - (13+2i)(8-i) = 1-3i$$
Therefore, the remainder of $107$ under division by $(13+2i)$ is $1-3i$.
Now we can complete the answer, working mod $173$. We have
4.
$$107^{2009} \equiv 19 \pmod {173}$$
5.
$$\frac{19}{13+2i} =  \frac{247}{143}-\frac{38}{173}i \simeq 1 - 0 \cdot i$$
(the quotient)
6.
$$19 - (13+2i) \cdot 1 =6-2 i$$
(the remainder)
Note:( $b q$ closest to $a$) is equivalent to ($q$ closest to $\frac{a}{b}$), since multiplication by $b$ increases norms (distances) by $|b|$.


Não Preencher nova coluna como Null e sim com valor especifico no script

Question: Tenho uma tabela especifica no banco de dados, nela eu guardo informações de turmas que são criadas, turmas de natação, turmas de futsal, turmas de musculação e por ai vai, ela já esta em uso e com várias turmas ja cadastradas, porém agora eu preciso da seguinte funcionalidade no sistema, eu precisei acrescentar uma coluna nova , que vai guardar o tempo de tolerância de entrada do aluno na portaria do clube, por exemplo se uma turma de natação  é criada, será cadastrado nela um tempo de tolerância em minutos, por exemplo 10 minutos, isso significa que o aluno só pode chegar até 10 minutos antes da aula, se ele chegar 20 minutos antes, o acesso é bloqueado. pois bem o problema é, como as turmas que já existem não fizeram ainda esta configuração, por padrão, vou deixar para estar turmas esta coluna com o valor de 15 (no caso 15 minutos), a pergunta é, como faço um script que ao invés de deixar a informação nas turmas que já existem como "null" deixe preenchido 15 por exemplo ?
estou usando sqlserver2017
Answer: João, boa tarde!
Você tem que inserir a coluna como nullable, depois disso você faz um update nos registros já existentes para o valor de 15 minutos que você quer.
Uma vez feito isso e sabendo que o campo é obrigatório, você vai poder deixar o non-nullable e exigir preenchimento do sistema, do contrário terá uma exception.
Espero ter ajudado
Update tabela set ColunaNova = 15
****Você pode colocar o valor default como o amigo abaixo disse também, vai depender da necessidade da sua regra de negócio. Meu update não tem where pois entendo que você quer fazer esse processo uma única vez e que não tem registros novos já na tabela (onde eles já estejam preenchendo o valor dos minutos), se houver esses registros, favor considerar a cláusula where colunanova is null
Comment: Obrigado Angelo
Answer: Adicione a coluna com um valor padrão com a instrução WITH VALUES para que as linhas já existentes recebam esse valor, isso também vai lhe dar um respiro para ajustar o sistema que ainda terá de ser alterado para adicionar essa informação nas operações de CRUD.
   ALTER TABLE [TABELA] ADD [COLUNA] INT NOT NULL
   CONSTRAINT Tabela_Coluna
   DEFAULT (15)
   WITH VALUES

Comment: Obrigado Leandro
Comment: @JoãoÁvila se a solução apresentada resolveu o seu problema você deve aceitá-la como resposta. Também seria interessante editar a sua pergunta adicionando a estrutra da sua tabela, nome e tipo da coluna que está adicionando. E para as próximas perguntas, se preocupe em sempre apresentar um [MCVE]
Answer: Há duas maneiras:
1) No Sql Management Studio 2017 clique na tabela com o botão direito e em Design.
   Selecione a coluna que você quer definir um valor Padrão.
   Em Propriedades da Coluna, na guia Geral, em Associação ou Valor Padrão defina como 15.
   Salve a tabela.
2) Execute um script:
UPDATE {table} SET {column} = 15 WHERE {column} IS NULL

Comment: Obrigado Weiner


Rubymine Find in Path: Exclude a particular filename pattern?

Question: Using RubyMine's "Find in Path" search feature, I'd like to do a search on all files whole filenames do not match a particular pattern. For example, all files whose names do not include the string "test".
How can I do this?
Answer: This can be done by prefixing the file name match pattern in the "File mask" field with a ! (exclamation point) character.
For example, to have the search match all files that don't include the string "test", use the pattern: !*test*


Evaluating $\int (\tan^3x+\tan^4x) dx $ using substitution

Question: solving $$\int (\tan^3x+\tan^4x) dx $$ using substitution $$t = \tan x$$
My approach has led me to $ \int (1+t)t\sin^2xdt$ which has an $x$ too much and isn't easily solvable for me. If I remove the $x$ I get $\sin^2(\arctan(t))$ and that's not too nice to work with...
Comment: Well, the function $\frac{1}{\cos x}$ presumably has a name, just not $\sec x$.
Comment: You are possibly misusing the word _solving_. In math, that term usually means that there is some equation involving an unknown of some kind, and you have deduce what the unknown is. There is a tendency to misuse the term _solving_ as to mean "finding the answer to a math question", but that's not how mathematicians use it. Here, it might be better to say that you are _integrating_, _evaluating the integral_, or _simplifying_.
Comment: If $t = \tan x$, what becomes $dx$ in terms of $dt$ and $t$?
Comment: $dx = \cos^2x dt = \cos^2(\arctan(t))dt$ (but I've kept $\cos^2x$ and divide it with $\cos^2x$ from a $\tan x$ so that I've $\sin^2x$ left.
Comment: Not the optimal way, but okay. Now, can you simplify $\cos^2 (\arctan t)$?
Comment: Have you tried the universal substitution. Maybe they would help but not sure, try it only if you have the nerfs to :D
Comment: $\tan^3(x)=\tan(x)(\tan^2(x))=\tan(x)\sec^2(x)-\tan(x)$ gives you the first term, assuming you know the antiderivative for $\tan(x)$.
Comment: @DanielFischer I'm sure it's possible to simplify it. But I don't know how.
Comment: @randomname What's the "universal substitution"? If you mean $t=tan(x/2)$ so yes. And the calculations isn't nice. And the specifications for the exercise it to use$ t=tanx $
Comment: @iveqy Big hint: $\tan' x = 1 + \tan^2 x$. (Another big hint would be the obvious equation $x = \arctan t$)
Comment: @DanielFischer is $tan'x$ the derivate of $tan x$? I'm sorry but I don't get your hints.
Comment: Yes, $\tan' x$ is the derivative of $\tan$, evaluated in $x$.
Comment: Hint: Our function is $(\tan x+\tan^2 x)(\sec^2 x-1)$.
Comment: @AndréNicolas unfortunately $sec$ is not used in my country and hence I should learn to solve this without it. (even if I'm of course open to learn about $sec$ too).
Answer: Let's wrap it up. Let $t = tanx$, so $dt = sec^2xdx = (1 + tan^2x)dx = (1 + t^2)dx$, and $dx = \dfrac{dt}{1 + t^2}$. So $I = \int\dfrac{t^3 + t^4}{1 + t^2} dt = \int \left(t - \dfrac{t}{1 + t^2} + t^2 - 1 + \dfrac{1}{1 + t^2}\right)dt = \dfrac{t^3}{3} + \dfrac{t^2}{2} - t - \dfrac{ln(1 + t^2)}{2} + tan^{-1}t + C = \dfrac{tan^3x}{3} + \dfrac{tan^2x}{2} - tanx - ln|secx| + x + C$
Answer:
unfortunately $\sec$ is not used in my country

If you feel unconfortable with $\sec $ you may proceed from your last integral
\begin{equation*}
I=\int (1+t)t\sin ^{2}\left( \arctan t\right) \,dt
\end{equation*}
by using the following trigonometric identity
\begin{equation*}
\sin ^{2}x=\frac{\tan ^{2}x}{1+\tan ^{2}x},\qquad x=\arctan t,
\end{equation*}
which you can derive from the fundamental identity $\sin^2 x+\cos^2 x=1$ to obtain
\begin{equation*}
\sin ^{2}\left( \arctan t\right) =\frac{t^{2}}{1+t^{2}}.
\end{equation*}
Consequently
\begin{equation*}
I=\int (1+t)t\frac{t^{2}}{1+t^{2}}\,dt=\int \frac{t^{3}+t^{4}}{1+t^{2}}\,dt,
\end{equation*}
which is integrable by partial fractions. By long division we compute
\begin{equation*}
\frac{t^{4}+t^{3}}{1+t^{2}}=t^{2}+t-1+\frac{-t+1}{1+t^{2}}.
\end{equation*}
So
\begin{equation*}
I=\int \left( t^{2}+t-1\right) dt+\int \frac{-t+1}{1+t^{2}}dt.
\end{equation*}
Since
\begin{eqnarray*}
\int \frac{-t+1}{1+t^{2}}dt &=&-\frac{1}{2}\int \frac{2t}{1+t^{2}}dt+\int
\frac{1}{1+t^{2}}dt \\
&=&-\frac{1}{2}\ln \left( 1+t^{2}\right) +\arctan t+C,
\end{eqnarray*}
we thus have
\begin{eqnarray*}
I &=&\frac{1}{3}t^{3}+\frac{1}{2}t^{2}-t-\frac{1}{2}\ln \left(
1+t^{2}\right) +\arctan t+C \\
&=&\frac{1}{3}\tan ^{3}x+\frac{1}{2}\tan ^{2}x-\tan x-\frac{1}{2}\ln \left(
1+\tan ^{2}x\right) +x+C.
\end{eqnarray*}
Answer: Solve separately:
first: $\int \tan^3x dx$:
$$\int \tan^3x dx=\int \tan^2 x (\tan x dx)=\int (\sec^2 x-1)\tan x dx= $$
$$=\int \sec^2x \tan x dx -\int \tan xdx=\int (\sec x)^1( \sec x\tan x dx)+\int \frac{-\sin x dx}{\cos x}=$$
$$=\frac{\sec^2 x}{2}+\ln |\cos x| +c. $$
Second: $\int \tan^4 x dx$:
$$\int \tan^4 x dx=\int (\sec^2x-1)^2dx=\int (\sec^4 x-2\sec^2x +1)dx=  $$
$$=\int \sec^4 x dx -2\int \sec^2 x dx+\int dx = $$
$$=\int (1+\tan^2x)\sec^2x dx -2\int \sec^2x +x+c= $$
$$=\int \sec^2x dx+\int \tan^2x \sec^2 x dx -2\int \sec^2 xdx +x+c= $$
$$\int (\tan x)^2 \sec^2x dx -\int \sec^2 x dx+x+c =$$
$$=\frac{\tan^3 x}{3}-\tan x+x+c. $$
The, the answer is
$$\int(\tan^2x+\tan^4x)dx = \frac{1}{2}\sec^2x+\ln|\cos x|+\frac{1}{3}\tan^3x -\tan x+x+c.$$
Note: is easy to see that my solution and the LAcarguy above differ only a constant.


FragmentPagerAdapter - Set Count and Titles async

Question: I have the folling FragmentPagerAdapter
public class GameListPagerAdapter extends FragmentPagerAdapter implements IGetGameListTaskListener {

GameList _games;
public int int_items = 6 ;

public GameListPagerAdapter(FragmentManager fm) {
    super(fm);

    //async task to get a list of games
    GetGameListTask getGamesTask = new GetGameListTask(this);
    getGamesTask.execute();
}

@Override
public Fragment getItem(int position)
{
    Bundle bundle = new Bundle();
    bundle.putInt("GameId", position);

    //get the generic matchlistfragment and tell it which game it is
    MatchListFragment matchListFragment = new MatchListFragment();
    matchListFragment.setArguments(bundle);

    return matchListFragment; // always return the same fragment, just give it a different game id
}

@Override
public int getCount() {
    return int_items;
}

@Override
public CharSequence getPageTitle(int position) {

    //NEED HELP - Need to get the tiltle here
    //return _games.getGames().get(position-1).getName();

    switch (position) {
        case 0:
            return "One";
        case 1:
            return "Two";
        case 2:
            return "Three";
        case 3:
            return "Four";
        case 4:
            return "Five";
        case 5:
            return "Six";
    }
    return null;
}

@Override
public void onComplete(GameList data) {
    //get the data on onPostExecute of my "getGamesTask"
    _games = data;

    //NEED HELP - need to set the item count here, but it fails**
    //int_items = _games.getGames().size();
}

}
Here is my IGetGameListTaskListener interface:
public interface IGetGameListTaskListener {
    public void onComplete(GameList data);
}

The issue I have here, is, I am getting a list of games  from an api, this is set up as an async task GetGameListTask. I then want to create a tab for each of the games returned in that list.
Once I have a list of the games onComplete(GameList data) I need to set int_items, as well as int_items
However, due to (my understanding of) the life-cycle of the FragmentPagerAdapter, these values needs to be supplied upfront.
how will i be able to handle this implementation of async tabs for my FragmentPagerAdapter?
Comment: Don't create the adapter object beforehand. Create it in onPostExecute() or after you get the results. Once you have the results, you can send them as array or list to the constructor of the adapter and use them.
Comment: hey,why not execute this GetGameListTask getGamesTask = new GetGameListTask(this); before calling the GameListPagerAdapter ? and after DoInBackGround Completes u can pass the GamelIst and set the size, Is there is any prob with this approach?
Comment: @ankitaggarwal this just moves the problem to my viewpager. i now have to do a background task in my viewpager before setting the viewPager.setAdapter
Comment: @DustyRoberts you don't need to set the task in your viewpager. Before even creating the instance of pageradapter, inside your activity or fragment, complete the call. Once the call is finished, than create the instance of adapter passing the result in the constructor
Comment: @ankitaggarwal apologies, i meant to say fragment. I did what you said, and it now loads FragmentPageAdapter with all properties being set :)
Comment: check my answer I've explained more clearly
Answer: move your async task execution to the activity or fragment from wherever you want to set the adapter.
GetGameListTask getGamesTask = new GetGameListTask(this);
getGamesTask.execute();

In the onPostExecute() of the asyncTask, do
@Override
public void onPostExecute(){
    GameList games;
    GameListPagerAdapter adapter = new GameListPagerAdapter(getFragmentManager(), games);
    view_pager.setAdapter(adapter);
}

create your adapter like this
public class GameListPagerAdapter extends FragmentPagerAdapter {

    GameList _games;
    public int int_items = 6 ;

    public GameListPagerAdapter(FragmentManager fm, GameList _games) {
        super(fm);
        this._games = _games;
    }

    @Override
    public Fragment getItem(int position)
    {
        Bundle bundle = new Bundle();
        bundle.putInt("GameId", position);
        MatchListFragment matchListFragment = new MatchListFragment();
        matchListFragment.setArguments(bundle);

        return matchListFragment; // always return the same fragment, just give it a different game id
    }

    @Override
    public int getCount() {
        return int_items;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return _games.get(position);
    }
}

Answer: Instead of returning
public int int_items = 6 ;
in
@Override
public int getCount() {
    return int_items;
}
You might wanna fetch and then return the number of games.
Comment: how is set that value is not really the issue. My problem as described, is that i only get the values after the FragmentPageAdapter is created


Variable throws initialization error after initializing it

Question: I'm trying to make a Discord bot, one of its features is that it plays chess, at the start of the command, I read the JSON file, then check if it's undefined since I'll call a key from the object, so just in case it doesn't exist already, I'll create the data needed
Problem is, when I try to assign the data, it says I haven't initialized the variable, which is weird, because I did initialize it 3 lines before, var, let and const all throw the same error
Another thing is that outside the if statement, just above it, when console.logging it, it works perfectly, but when console.logging it inside the if statement, it throws that error
I honestly have no idea what's happening here, I can't think of anything that's causing this either, is this a NodeJS bug? I feel like it could be.
const games = JSON.parse(fs.readFileSync("./lib/database/games/chess/chess_games.json"))
console.log(games, 'outside if statement') // Here it outputs just fine
if (games[interaction.guild.id] == undefined) {
    console.log(games, 'inside if statement') // Here is where it breaks
    games[interaction.guild.id] = {
        games: {},
        players: {},
        amount_of_games: 0
    }
    fs.writeFileSync("./lib/database/games/chess/chess_games.json", JSON.stringify(games, null, 2));
    const games = JSON.parse(fs.readFileSync("./lib/database/games/chess/chess_games.json"))
}

This is the error:
ReferenceError: Cannot access 'games' before initialization
    at Object.execute (C:\Users\aschr\Dropbox\Coding\Javascript\entropic_bot\lib\database\bot\commands\chess.js:40:4)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async Client.<anonymous> (C:\Users\aschr\Dropbox\Coding\Javascript\entropic_bot\index.js:44:3)

Answer: You have two variables with the same name.
Change the name of one of them
The second games is tried to be accessed instead of the first one because of hoisting. That's why you are getting the error
Comment: Do you mean the one in the object? (`games: {}`)
Comment: I mean `const games`
Comment: Oh that, lemme try that, although the line the error it outputs is the same line as the console.log
Comment: I'm so stupid you're right
Comment: Yes, because of hoisting. Change the sconce `const games` to `const anything` and it will work
Comment: When it said that I didn't realize it meant the second `games` as you mentioned
Comment: Yeah I just added it for good measure, although it's not really necessary so I'll keep it removed, thank you very much
Comment: I'll verify your answer as soon as it lets me, again, thank you lol, been struggling with this for about 15 minutes
Comment: 15 minutes, that probably felt like a lifetime
Comment: Definitely did, I honestly just had no idea what was wrong, I completely forgot I had that second `games` being initialized


I'm a traditional snare drummer who has serious issues using my left hand

Question: I'm looking for exercises to help with my motor control in my left wrist. Ever since I started heavy lifting on a daily basis at work, my left hand has become tighter and stiffer to the point where I have to use my entire arm while playing rather than just moving my wrist.
I'm not even looking for anything music-related, just anything to help loosen my wrists would be of great help!
Thanks,
Cam.
Comment: First, I suggest you use an arm brace at work, and find ways of favoring your left arm in your work.  Try to use your left wrist as little as possible in your lifting.  And maybe take a bit of a break from playing while you get this figured out.  Second, look for a physical therapist who specializes in hands.  Finally, get a doctor's appointment with an orthopedist who specializes in hands.  Maybe you just need some special stretches and strengthening exercises -- but maybe there's something more serious going on.  Knowledge is power.
Comment: Hi Cam. Welcome to Music: P&T! Sorry to hear about your arm. I hope someone will be along soon who's had some similar experience and can give you advice. In the meantime, have you come across Alexander Technique? I've known a couple of musicians who were helped by them. There's information about them at this NHS site that should be useful even if you're not in the UK:  https://www.nhs.uk/conditions/alexander-technique/
Comment: Thanks a lot guys! I'll have a look into both! - A brace sounds like a ready good idea :)
Comment: Just to check - have you had some manual handling training at work?
Answer: It won't solve the problem entirely but before you practice / play do 10 minutes or so of wrist exercises. A lot of the ones for people with arthritis seem to work well for me.
A quick Google of 'wrist exercises for arthiritis' will come back with some good ones and I would personally recommend this NHS one
Answer: I don't know if you are sympathetic to alternative medicine but you could visit an osteopath and have them examine your wrist. They would also give you exercises. Hopefully it may be just be temporary. No criticism of you but possibly it could be something wrong with your posture when heavy lifting, such as having your arms in a bad position.
No consolation but RSI is now very common among musicians and it is aggravated by using a computer mouse and also stress.


Triggering Octopus deploy when files are available

Question: I am currently doing an Octopus project using which I am trying to automate the below process,

Copy the installation files from the folder (TFS automatically drops the new builds to this place) to the octopus tentacle
Install and configure the application
Run the automated tests created using SOAP UI pro on the installed product
Send mail notifications to the user
Revert back the machine/Uninstalling the application

I have implemented all the above process using power shell in Octopus deploy. Only thing I am missing is the trigger process for project.
Requirement: Trigger the Octopus project containing above processes once a new build is created in TFS or new build is placed in the folder
Answer: There are two actions to "Trigger" Octopus Deploy to perform the steps defined in the project process, that can be initialised in a number of ways
Using the UI
1) Create a release
2) Deploy the release.
Using the API
1) Create a release and then instruct that release to be deployed to an environment (the important switch here is --deployto)
<code>octo.exe create-release --server http://xxx --apikey SECRET --project xxx --version x.x.x --packageversion=x.x.x --deployto PRODUCTION
</code>
Note: this can also be done in two steps
Using Lifecycles
1) Create a release manually or using the API
2) Allow lifecycles to control what happens in environments when a release is created
Octopus Lifecycles Documentation
Hope this helps
Answer: You need to have the TFS build server upload newly built nuget packages to the Octopus Deploy server and create a Release post build.
https://octopus.com/blog/using-octopus-and-tfs-builds


Solving for arima and exponential smoothing coefficients

Question: I am looking to How do you solve for the optimum values with the lowest MSE for the coefficients and dampening constant in exponential smoothing and ARIMA models? What are the equation used?
Comment: I am interested too. For the exponential smoothing, I usually use grid search which can be long for triple exponential smoothing.
Answer:
ARIMA coefficients are estimated using Log Likelihood function. For background, you can consult either the classic text book by Box, Jenkins & Reinsel or much more accessible book by Pankratz. I tried to
post an example in this website which also has references to lecture notes. I used R optim function to
solve for ARMA parameters.
As far as Exponential smoothing, there
        are two publications that I know of, both in the Omega -
        International Journal of Management Science show how to solve for
        optimal Parameters using spreadsheet. Both the papers give you very clear numerical illustrations with equations (see below for links). If you would want to get indepth on equations I would recommend an excellent text by Spyros G. Makridakis,Steven C. Wheelwright, Rob J Hyndman  or this free text book by Hyndman and Athanasopoulos. I like them both.

On time series data and optimal parameters
On modeling time series data using spreadsheets


Como ficaria o insert numa tabela que só tem chave estrangeira

Question: Eu tenho um cadastro de usuários e esse cadastro pode ser feito de duas maneiras, pelo facebook ou pelo e-mail. A minha dúvida seria como dar o insert nessas tabela, pois tenho uma tabela de controle que recebe os ids das outras duas tabelas por chave estrangeira.
Tabela:
Answer: Se o usuário se cadastrar a partir de um e-mail, ficaria algo como:
INSERT INTO user (id_user, nome, email, senha) VALUES (DEFAULT, "Fulano", "firstname.lastname@example.com", "1234");
INSERT INTO user_controller (id_controller, id_user) VALUES (DEFAULT, LAST_INSERT_ID());

A primeira linha adiciona os dados do usuário em user e a segunda insere a chave estrangeira na tabela de relação user_controller. Neste caso, LAST_INSERT_ID() retornará o valor de id_user gerado na primeira instrução.
Para o cadastro a partir do Facebook seria algo bem semelhante:
INSERT INTO user_fb (id_userfb, nome, sobrenome, idfacebook) VALUES (DEFAULT, "Fulano", "Snow", "314159");
INSERT INTO user_controller (id_controller, id_userfb) VALUES (DEFAULT, LAST_INSERT_ID());

Neste caso, a chave estrangeira seria escrita na coluna id_userfb.
Comment: Obrigado pela ajuda. Eu tenho mais uma duvida poderia me ajudar pf?
Comment: Basta criar uma nova pergunta no site com ela.


Prevent specific application information event IDs from Source Security-SPP flooding the Windows Application Event Viewer Log

Question: Is there a way to prevent event IDs: 1003 and 1033 from Source: Security-SPP with Level: Information from flooding a Windows server Application Event Viewer Log?
I am seeing approx 4500 of these events logged daily and we do not need to see or log these particular Information events.
I know you can setup filters to filter out specific events when viewing the Application log but this does not stop the logging of these events bloating the application events log file.
Answer: No, there isn't a mechanism to prevent event(s) from being recorded in a Windows event log.


liquibase : modify csv file and insert new records

Question: I load data into my database from a CSV file :
<loadUpdateData encoding="UTF-8"
    primaryKey="pk_id"
    file="config/liquibase/roles_admin.csv"
    separator=";"
    tableName="role_admin">
       <column name="libelle" type="STRING"/>
</loadUpdateData>

Is it possible to tell liquibase to insert new records if I add lines to my csv file?
Answer: You can modify your changeSet and add runAllways="true" this way it will run always (even if there is no change).
Comment: If you do this, you will also get duplicate records. Liquibase does not currently have any logic to only insert data that doesn't exist.
Answer: Using runOnChange="true" on your changeSet should do the trick.
Answer: The only way that i found to do that, is creating other csv file with the same columns like the original csv file and with the updated data, and create a new changeSet with loadUpdatedData inside and pointed to the new csv file.


1 of 4 power tubes went bad; buy a matching quartet or replace the one?

Question: I have a Peavey Windsor running Ruby EL34B-STR's. One of the power tubes went bad.
I can order another Ruby EL34BSTR and re-bias the amp (idk if it has a bias for each tube or not) and I assume it'll be fine. However, everyone's talking about matching pairs. I understand that if I end up getting a tube that doesn't match the pc and tc of the other 3 tubes, the bias and breakup will be completely off. But I can't seem to order based on these figures.
So if that's so important, does that mean you need to buy a matched quartet every time a single power tube goes out?
Answer: To oversimplify slightly, assume that matched tubes all have the same "bias point". Meaning, if you have unmatched tubes, the bias adjustment that works for one of them might not work very well at all for the rest. If you have matched tubes, they are close enough that one bias point will work for all four.
You only have one bias adjustment dial on that amp, so you can't even adjust it in pairs to accommodate two different matched pairs.
Besides all of that, either the tube was really old when it failed or it was maybe less than two years old. If it was that young, then there might be something wrong with your bias control, the amp, or maybe they are really cheap tubes. Power tubes should last a couple years without failing. If the tube was really old, then consider changing your tubes more often. Tubes don't sound as good when they get old. And they definitely age. Just having the tube heaters warmed up causes the tube to slowly wear down as electrons are slowly boiled off the cathode (the cloud of electrons is what makes the tube work). Consider changing your tubes once a year or so if you play frequently.
If you've tried other brands and you prefer Ruby tubes, then go ahead and stick with them. If you've never used another brand, you may be surprised at how much better your amp can sound with a nice set of tubes. The Ruby (actually Shuguang) tubes are rated four stars at The Tube Store but there are other tubes rated higher for not much more money, and the JJ EL34L is rated higher at the same price.
When you get a new matched quad, you probably will need to at least check the bias on your amp, or have it checked. Your amp does have a bias test point, which allows you to check the voltage between the test point and ground with a multimeter. One source indicates the correct bias voltage for EL-34s is 44 volts. You can more accurately set the bias point for the exact tubes you have by using a bias probe, like the Weber Bias Rite. There is at least one handy online bias point calculator based on plate voltage. Looks like a Peavey Windsor has a nominal plate voltage of 470 Volts. So with a bias probe you might go for 26 - 37 mA bias current depending on how you like it to sound. I've read that Peavey amps sound a lot better run hot, so you might go closer to 37 mA.
Since you're asking this question, my assumption is you haven't done a lot of work on amps. If that's true, I recommend you get your tubes replaced and bias checked by a pro. If you insist on DIY, please read the following:

There are dangerous voltages inside your amp!! Use extreme caution!
Obtain a non-conducting tool or set of tools to adjust the bias pot in your amp.
Keep one hand in your pocket or behind your back whenever your amp chassis is opened up and especially when poking around.
Note that in order to keep one hand in your pocket, if you use the voltage bias test point you'll have to clamp the ground lead of your tester to the chassis somehow. Do this with the amp unplugged.
Also note that dangerous voltages can remain in the amp (in charged up capacitors) even when it is unplugged from the wall. Always assume the amp is live.
A bias probe is the easier, safer, and more accurate way to go, since you can look at the display as you turn the bias pot with one hand while your other hand is behind your back, and you don't have to put a test lead inside the amp chassis to check the voltage. Note that the tubes and the bias probe may get very hot. Turn the amp off and let everything cool before disconnecting tubes and/or a bias probe.
Answer: Assuming the amp originally contained a matched quartet, you can get away with a matched pair, and install both of them with the following setup in mind:
The four output tubes in your Windsor are used in pairs to achieve the combined amplification (schematics here).
Your tubes are placed in row A,B,C,D (thats V4-V7) and A,B is amplifying the positive output and C,D is amplifying the negative output.
The matching of tubes is done to ensure that the positive and negative output is amplified equally. In other words the amplification factor of A,B and C,D should be the same.
So if tube A is out, you change A and C, If tube B is out, you change B and D etc.
(this is mainly theoretical though - in practice even a matched set is not perfectly balanced and over time the tubes changes, so an amp tech would most likely measure all of them and reposition tubes according to A,B and C,D currents.. or so he should).
Answer: Old and new is not the only difference. If these four tubes really must be balanced, you need a tube testing tool for selecting the matching group from much  more than just four tubes.
However selecting the matching pairs was much more critical for transistor electronics, as individual transistors vary in parameters much more dramatically than tubes. Maybe the pair matching is not required for your amplifier; then replacement of the single failed tube is ok.
Answer: Good answers above, I'd just like to add that the amp bias circuit needs to be checked closely to determine if the tube failed because the bias circuit had a problem. Otherwise the new tube will probably fail very quickly, if put into an amp with a faulty bias circuit.


Duvida sobre o uso do npx junto com o npm

Question: Tenho uma dúvida quanto ao uso do npx. Quando uso o npx  para criar um projeto React, ele usa o yarn para instalar os pacotes por baixo dos panos.
Eu queria saber se tem alguma forma de usar o npx, mas ao invés de instalar os pacotes com yarn, setar alguma flag pra que seja com o npm, alguem sabe se teria como fazer isso ?
Já tentei:
npx create-react-app nomedoprojeto --npm

Mas não deu certo, até pesquisei não achei nada.
Answer: Você deveria informar a flag --use-npm usando o comando do npx.
Tente desta forma:
npx create-react-app nomedoprojeto --use-npm

O motivo do create-react-app usar por padrão o yarn é que ambos foram criados e mantidos pelo Facebook. Acredito eu que seja este o motivo, mas com esta flag, você obriga o npx a usar o npm.
Se você não queria o yarn, uma outra solução seria excluir o arquivo yarn.lock e executar o comando npm install.


What are the pitches in this donso ngoni tuning?

Question: Please see the image below depicting the donso ngoni.

I'm bad at identifying notes from clefs. But if I'm giving a try to guess the notes I think in the key of A: it is A - B - D - E - G - A. Is that correct?
What are the pitches and notes from the image above?
Answer: The pitches, from left to right, are:
B, E, A, G or G#, D, A
Comment: Thank you, Aaron! Regardless what the key is whether the root note is B or C, etc., the arrangements of notes are still the same. Like if it is in the key of B it is B-C#-E-F#-A-B. Correct?
Comment: @MohamedObeidallah It's not clear what you're asking. When you say "root note", do you mean the lowest pitch? If yes, then to keep all of the strings tuned in the same way relative to each other, the tuning, in the left-to-right order given in the chart, would be C#-F#-B-A or A#-E-B. Does that answer your question?
Comment: Sorry, what I mean by B - C# - E - F# - A or A# - B is the arrangement of notes in ascending order, if we play it on the piano or maybe a guitar note by note. Yes, I'm talking about the lowest note of the scale or in a key regarding the "root note".


The definition of stationary distribution of a Markov chain seems strange

Question: In Brilliant.org as well as Wikipedia, the definition of stationary distribution of Markov chain is $\pi P = \pi$, in which $\pi$ a state distribution and $P$ the transition matrix. Why was it defined that way?
I think it makes way more sense if it is defined as $P\pi$, since by the definition of matrix multiplication, $P\pi$ means $P$ transforms $\pi$ versus a distribution transform the transition matrix.
My guess is that it is due to the defition of transition matrix. According to 11.1.2 here, row $i$ of the transition matrix lays out the probability of what happen after state $i$. Therefore, we want $pi$ to be a row matrix, and in order to make the shape compatible in multiplication, it must be $\pi P$ instead of $P\pi$. However, I could not see which is more correct.
Comment: Then what about the definition of matrix vector multiplication? Interpreting as "vector is transforming the matrix" feels a bit strange to me.
Comment: I think I get it now, using $AB = (B^T A^T)^T. Please make your comments an answer so that I can accept
Comment: I was too confined on the matrix-vector multiplication that the stationary distribution definition seems strange. Your second answer dealt with it, so all good :)
Answer: It was defined that way because the $(i,j)$-th entry of transition matrix $P$ was defined in a certain way, namely, that $p_{ij}$ is the probability of jumping from state $i$ to state $j$ (rather than from state $j$ to state $i$).
It feels strange to have the vector-matrix multiplication $\rm v^\top M$ instead of the more common matrix-vector multiplication $\rm M v$ because you're used to reading function composition from right to left ;-)