Fazer uma query e ver numa dropdownList

Question: Está dar o erro abaixo na dropdowList e não percebo porquê.
Erro:

Não é possível associar o objecto de tipo 'System.Collections.Generic.List1[<>f__AnonymousType82[System.Int32,System.String]]' ao tipo 'System.Web.Mvc.SelectList
  Controlador:

public ActionResult CriarInscricao()
        {
            var queryNomeCatequizando = ( from c in db.Catequizando
                                          join p in db.Pessoa on c.CatequizandoID equals p.PessoaID
                                          where c.CatequizandoID == p.PessoaID
                                          select new { PessoaID = p.PessoaID,  Nome = p.Nome});

            ViewBag.Catequizando = queryNomeCatequizando.ToList();
            return View();
        }

View:
@Html.DropDownListFor(model => model.CatequizandoID, (SelectList)ViewBag.Catequizando, htmlAttributes: new { @class = "form-control" })

Comment: Que erro está dando?
Comment: "Não é possível associar o objecto de tipo 'System.Collections.Generic.List`1[<>f__AnonymousType8`2[System.Int32,System.String]]' ao tipo 'System.Web.Mvc.SelectList'."
Answer: ViewBag.Catequizando não é uma SelectList. É uma lista normal. Você precisa converter pra funcionar. Tem duas formas de fazer:
Primeira forma, em Controller:
ViewBag.Catequizando = new SelectList(queryNomeCatequizando, "CatequizandoID", "Nome");

Segunda forma, em View:
@Html.DropDownListFor(model => model.CatequizandoID, ((IEnumerable<CatequizandoViewModel>)ViewBag.Catequizando).Select(option => new SelectListItem {
    Text = option.Nome,
    Value = option.CatequizandoID.ToString(),
    Selected = (Model != null) && (Model.CatequizandoID == option.CatequizandoID)
}), htmlAttributes: new { @class = "form-control" })

Na segunda forma, é preciso criar CatequizandoViewModel antes.

Fazer uma query e ver numa dropdownList


Como recuperar uma base de dados em MySQL

Question: Tive um problema num cliente que o sistema operativo deixou de funcionar.
Consegui aceder ao disco e nele está uma base de dados MySQL dentro da pasta C:\ProgramData\MySQL\MySQL Server 5.7\Data\BDados que contém os ficheiros .FRM e .IDB.
Como é que consigo recuperar essa base de dados?
Já copiei os ficheiros dessa pasta para a pasta do meu computador mas não consigo aceder. Quando entro pelo MySQL Workbench as tabelas aparecem mas não consigo aceder ao conteúdo. Dá sempre o erro:

Error Code: 1812. Tablespace is missing for table bdados.clientes

Gostaria de ter a vossa ajuda para resolver esta situação.
Answer: Tem uma dica nesse site que pode te ajudar:
Primeiro você cria uma nova base de dados com as tabelas.
Depois exclua os arquivos recém criados usando a instrução DISCARD
ALTER TABLE newdb.table1 DISCARD TABLESPACE;

Em seguida, copie todos os arquivos .ibd e .frm do backup para a pasta do banco de dados, depois acesse o banco de dados.
Peça ao MySQL para aceitar os novos arquivos usando a instrução IMPORT.
ALTER TABLE newdb.table1 IMPORT TABLESPACE;

Isso pode ajudar a recuperar as tabelas do banco de dados.
Comment: Obrigado pela resposta. Como é que atribuo a propriedade mysql:mysql?
Comment: Editei a reposta, no caso você tem que acessar seu database para fazer as alterações seguintes. Tomara que isso possa lhe ajudar.
Comment: Quais são as alterações que sugere? Já fiz o que me indicou até ao ALTER TABLE. Aí deu-me o seguinte erro: Error Code: 1815. Internal error: Cannot reset LSNs in table `bdados`.`clientes` : Unsupported 0.157 sec
Comment: Já tentei tudo e não consegui nada. O pc onde estavam os dados tem instalado o MySQL 8. Arranjei um outro pc e instalei o MySQL 8 também. Segui as instruções todas. Quando executo a instrução ALTER TABLE mewdb.table1 IMPORT TABLESPACE; dá o seguinte erro: ALTER TABLE newdb.table1 IMPORT TABLESPACE Error Code: 1034. Incorrect key file for table 'table1'; try to repair it. Conseguem-me ajudar com este erro?
Comment: Preciso mesmo da vossa ajuda nesta situação. Já experimentei com vários parâmetros e dá sempre este esso
Comment: Você está usando algum programa? Ou esta indo direto pelo terminal/DOS?
Comment: Estou a utilizar o MySQL Workbench
Comment: Ok, então, o que entendi é que quando você cria uma nova base de dados para recuperar os dados do arquivo .frm e .ibd é preciso encontrar o ID da tabela em que o MySQL está atualmente configurado, assim como o ID da  tabela que precisa ser recuperar. Dá uma olhada nesse linq: http://www.chriscalender.com/tag/innodb-error-tablespace-id-in-file/
Comment: O erro na recuperação esta acontecendo porque o ID da tabela atual do MySQL não correspondesse ao id da tabela ibd preexistente.
Comment: Fiz aquilo que o link diz mas no ponto 2.E o erro que me dá não é "ERROR 1030 (HY000): Got error -1 from storage engine" mas sim o erro "ERROR 1812 (HY000): Tablespace is missing for table `test1`.`product`." Não consegui chegar ao ponto onde se sabe qual o ID para depois o poder "acertar"
Comment: Então é porque não há essa tabela no banco de dados que você quer recuperar, eu ainda não precisei fazer isso, e estou sem tempo para testar, mas você sabe o nome de todas as tabelas que você tem nesse banco que você quer recuperar? Se você tiver algum script de criação, você monta um novo banco de dados com a mesma estrutura do banco a ser recuperado, daí você vai conseguir recuperar esses dados seguindo os passos seguintes após montar o banco.


transposing an open Bm chord with the capo on the 5th fret

Question: What would the open Bm chord in G progression be when transposed with capo on the 5th fret?
Comment: It's not clear whether you're *transposing* (changing key of G to key of C) or *re-voicing the chord* (changing Bm from Am shape at fret 2 to Em shape at fret 7).
Answer: Bm moved 5 frets up would result in Em.
Comment: What would the Em on the 5th be a BM then?
Comment: No, it's always +5 semitones. Em + 5 semitones results in Am.
Answer: An open Bm? Open chords are so-called because they contain notes played on open strings, like an open G or open C which are probably in the same piece.
On to the answer. When any chord shape is moved along the fingerboard, its name will change. By moving the capo 5 frets, the chord will be called Em, as it's a perfect 5th higher. Another way to look at it is Bm is the iii of G. But now, we're in C major, so that chord will be the iii of C, which is Em.


Timestamp of generated bitmap - Android

Question: I have an app where I have downloaded an image file from the web and I save this file in external storage.
Later, to add this image to the media store, I call:
<code>MediaStore.Images.Media.insertImage(getContentResolver(),
                fullPath, "IMG_"+System.currentTimeMillis(),null);
</code>
However,  my picture always adds to the end of the gallery - it thinks that the picture was taken in 1970.  How do I change this information?
Thanks!
Comment: I believe you can write a specific date/timestamp to the img by way of [ExifInterface](http://developer.android.com/reference/android/media/ExifInterface.html#TAG_DATETIME) `setAttribute()`
Comment: I tried this but I get "Can't write back - didn't read all" in the logs :(
Comment: got it working thanks! I was saving my images as png's originally!
Comment: Awesome, so just to make sure, did you converted them to jpeg's and then used the `ExifInterface`?
Answer: Worked using JPEGS (not PNG!) with ExifInterface
Comment: I'm using your same method and i can't change the date, can you post me the code that worked please??

Timestamp of generated bitmap - Android


Survey sampling: How many participants per group (current, former, and potential users) should we recruit?

Question: We are designing research in which we will explore the perception of users (C current, F former, and P potential) on a product. We apply the same questionnaire for each group adapting (verb tenses) some questions depending on user group (C, F, and P). We use five-point Likert scales, multiple and single choices questions to measure intention to use the product, and willingness to give feedback, among others factors. We adapted some scales from previous studies like Lajunen and Summala [1] (attitude towards driving).
We want to compare the results from each group to conclude, for example: current users are more willing to get feedback using the product than potential users, former users are more willing to share their personal information using this product than potential users, etc.
After running a screening survey we identified 30 current, 70 former, and 400 potential users of the product that we want to evaluate. Thus, we could recruit a maximum of 30 current users and 70 former users (the best-case scenario).
We want to know if recruiting different sample sizes for the three groups (C current, F former, and P potential users) could add value to our analysis, for example running the survey with 30C/70F/70P, or 30C/70F/200P. In case of deciding to conduct the study with different sample sizes for each group:
-> How many participants per group should we recruit?
-> How could we analyse/compare the output from a small sample (less than 30) with another big sample (more than 100)?
-> Could we compare the analysis from a parametric test with a non-parametric test?
[1] Lajunen, T., & Summala, H. (1995). Driving experience, personality, and skill and safety-motive dimensions in drivers' self-assessments. Personality and Individual Differences, 19(3), 307-318.
We also appreciate getting any relevant literature.
Answer: In terms of questionnaire results, you give no idea how you will assess willingness of subjects to give feedback. I guess, some kind of questionnaire score.
The required sample size $n$ depends on what test you will use, the significance level of the contemplated test test (5%?), the size $\Delta$ of score difference you want to detect, the desired probability of detecting those differences, and the common standard deviation $\sigma$ of the scores at the three levels of the factor.
So more input is required in order to determine the required sample size.
As a general rule it would be a more efficient use of subjects to have equal sample sizes in each of the three groups. You ask what sample size to use, and yet you say you will have sizes 20, 70, & 400. How did you get those sample sizes?  What are you really asking? Just for "statistical blessing" of
what you've already decided to do?
Below are results from Minitab's power and sample size procedure for a
one-factor ANOVA. Scores are assumed to be normal with standard deviation $\sigma = 15.$ For an ANOVA test at the 5% level, seeking to detect
differences of sizes $\Delta = 5, 10.$ and power levels 80% and 90%
(probabilities of detecting differences of sizes $\Delta)$ the output
shows the number required in each group.
I don't suppose your data and objectives will match my assumptions, but
this is one way to illustrate the kind of information that is required to answer your question.
Notes:

Most of these pre-programmed
power and sample size procedures assume that all three levels of the
factor will have have the same number of subjects. If you insist on
different sample sizes, other methods can be used.

If your data are not normal, then you would not use ANOVA to
analyze your data, and other methods of finding required sample sizes would be required.]

Minitab Output:
Power and Sample Size

One-way ANOVA

α = 0.05  Assumed standard deviation = 15

Factors: 1  Number of levels: 3

   Maximum  Sample  Target
Difference    Size   Power  Actual Power
         5     175     0.8      0.801385
         5     229     0.9      0.900303
        10      45     0.8      0.806033
        10      58     0.9      0.900245

The sample size is for each level.

 Power Curve for One-way ANOVA

Other quantities being equal, it is the ratios of $\Delta/\sigma$ that
matter. So we would get the same recommended sample sizes for
$\Delta = 1, 2$ with $\sigma = 3.$
The power curve below, gives an idea of power values for different $\Delta$s.

Addendum per comments:  Rough power values for K-W test on normal data.
Sample sizes 30, 70, 70, with $\sigma=15,$ differences in means as shown, power about 78% for detecting largest difference $\Delta=10.$
set.seed(2021)
pv = replicate(10^4, kruskal.test(list( rnorm(30,100,15),
              rnorm(70,105,15), rnorm(70,110,15) ))$p.val)
mean(pv <= .05)
[1] 0.7811

Change to sample sizes 30, 70, 200, gives power about 92%.
set.seed(2021)
pv = replicate(10^4, kruskal.test(list( rnorm(30,100,15),
              rnorm(70,105,15), rnorm(200,110,15) ))$p.val)
mean(pv <= .05)
[1] 0.9254

This is good news if it's the largest difference that really matters.
Comment: I think the intention of the question is to understand whether given the sample size of 30 current (C) users (more of these are hard to recruit), does it makes sense to recruit more participants for the other categories (F former, P potential)? In other words, is there added value in going from 30C/30F/30P to 30C/70F/400P, or 30C/70F/70P? In the first case the sample sizes are equal, but they're equally small; in the latter cases some categories have more participants, but the sample size is not the same.
Comment: Thanks for the reply @BruceET. I edited the question to provide additional context and more details about the problem. Have I answered your questions?
Comment: @ralien you are right. This is the intention of the question. We want to know if recruiting different sample sizes for the three groups (C current, F former, and P potential users) could add value to our analysis, for example running the survey with 30C/70F/70P, or 30C/70F/200P.
Comment: Going from 30C/70F/70P, to 30C/70F/200P would increase the probability of finding a difference between P and the other two groups, but not much if any to the probability of distinguishing between C and F. // I could do a simulation to show the approx effect. Summaries of some of your Likert data might make the simulation results more realistic. Are you planning to use Kruskal-Wallis test to compare the three groups? (Simulation results w/ ANOVA might give rough clues what to expect from K-W.)  What difference in Likert medians is important to detect> .// Unclear why you deleted your question.
Comment: See Addendum to answer.
Comment: Thanks for the reply @BruceET. We will use Kruskal-Wallis test if we get a non-normal distribution, otherwise we will use One-way ANOVA. At this point I have another question: if we get different distribution on one group (for example, 30C group has a non-normal distribution and 70F/200P have a normal distribution), could we use Kruskal-Wallis test to compare the three groups? Or could we use ANOVA to compare them?


Troca de Mascara usando Jquery Mask Plugin?

Question: Estou criando um sistema Web e neste sistema existe o campo telefone, neste campo telefone, o usuário pode colocar um 0800 ou então um telefone convencional padrão DDD-Sufixo-Prefixo.
Atéai tudo bem, consegui criar com um if, só que ao digitar o segundo número ele muda a mascara se for do padrão escolhido, então no caso eu queria segurar o padrão somente para o primeiro caractere.
Segue abaixo o código que criei.
<input type="text" id="telefone"
   name="escTelefone"
   class="medio"
   placeholder="(99)1111-1111" maxlength="13" />

Answer: Em vez de utilizar o evento keypress, você pode utilizar o evento blur:

Evento Blur
O evento blur é disparado quando um determinado elemento perde o foco,
  o que pode ocorrer se o usuário pressionar TAB, por exemplo, sobre o
  controle ou se clicar em outra região da página que também receba
  foco.
Fonte: Linha de Código

Verificar se o campo não está vazio e quais os primeiros dígitos que ele contém.

$(document).on('blur', '#telefone', function(event) {
  var campo = $(this).val();
  // Verifica quais os primeiros dígitos informados.
  if (campo !== "" && campo.substring(0,2) === "08" || campo.substring(0,3) === "(08") {
    $("#telefone").mask("0000-000-0000");
  } else {
    $("#telefone").mask("(00) 0000-0000");
  }
  // console.log(campo.substring(0, 2));
});
<input type="text" id="telefone" name="escTelefone" class="medio" placeholder="(99)1111-1111" maxlength="13"  />


Creating internal file in android

Question: I want to create a file in android application during runtime. As i understand i can do it using :
openFileOutput("samplefile.txt", MODE_WORLD_READABLE);

The problem is, i want to create this file in another class not in Activity. How can I do this ?
Answer: send context instance as parameters of method in  your second class
public class classOI{

    public void writeToFile(Context ctx,String string,String FILENAME){

    try{
      FileOutputStream fos = ctx.openFileOutput(FILENAME, Context.MODE_PRIVATE);
      fos.write(string.getBytes());
      fos.close();
      }catch(Exception e){
        //log for error
      }
    }
}

now you can call it like this in you main activilty :
new classOI().writeToFile(this,"text to write","myFile");

Comment: you can specify the path of the file you've created in the file name or not ?? example ( new classOI().writeToFile(this,"text to write", "android/data/myfile.txt");
Comment: Where this file is stored in android system?
Comment: It should be @ /data/data/packageName/files/FILENAME

Creating internal file in android


Stuck in the error: "Not Started" when try to access BigTable through Dataflow Pipeline

Question: My pipeline is very simple.
Pipeline p = Pipeline.create();
         p.apply("Read", (BigtableIO.read().withBigtableOptions(BIGTABLE_OPTIONS)).withKeyRange(keyRange).withTableId("myTable"));
        p.run().waitUntilFinish();

But when I run I constantly receiving:
Exception in thread "main" java.lang.IllegalStateException: **Not started**
    at com.google.common.base.Preconditions.checkState(Preconditions.java:459)
    at io.grpc.internal.ClientCallImpl.request(ClientCallImpl.java:344)
    at io.grpc.ForwardingClientCall.request(ForwardingClientCall.java:52)
    at io.grpc.ForwardingClientCall.request(ForwardingClientCall.java:52)
    at io.grpc.ForwardingClientCall.request(ForwardingClientCall.java:52)
    at io.grpc.stub.ClientCalls.startCall(ClientCalls.java:276)
    at io.grpc.stub.ClientCalls.asyncUnaryRequestCall(ClientCalls.java:249)
    at io.grpc.stub.ClientCalls.futureUnaryCall(ClientCalls.java:186)
    at io.grpc.stub.ClientCalls.blockingUnaryCall(ClientCalls.java:132)
    at com.google.bigtable.admin.v2.BigtableTableAdminGrpc$BigtableTableAdminBlockingStub.getTable(BigtableTableAdminGrpc.java:381)
    at com.google.cloud.bigtable.grpc.BigtableTableAdminGrpcClient.getTable(BigtableTableAdminGrpcClient.java:58)
    at org.apache.beam.sdk.io.gcp.bigtable.BigtableServiceImpl.tableExists(BigtableServiceImpl.java:82)
    at org.apache.beam.sdk.io.gcp.bigtable.BigtableIO$Read.validate(BigtableIO.java:294)
    at org.apache.beam.sdk.Pipeline$ValidateVisitor.enterCompositeTransform(Pipeline.java:578)
    at org.apache.beam.sdk.runners.TransformHierarchy$Node.visit(TransformHierarchy.java:482)
    at org.apache.beam.sdk.runners.TransformHierarchy$Node.visit(TransformHierarchy.java:486)
    at org.apache.beam.sdk.runners.TransformHierarchy$Node.access$400(TransformHierarchy.java:235)
    at org.apache.beam.sdk.runners.TransformHierarchy.visit(TransformHierarchy.java:210)
    at org.apache.beam.sdk.Pipeline.traverseTopologically(Pipeline.java:409)
    at org.apache.beam.sdk.Pipeline.validate(Pipeline.java:520)
    at org.apache.beam.sdk.Pipeline.run(Pipeline.java:294)
    at org.apache.beam.sdk.Pipeline.run(Pipeline.java:281)

I already tried the inside my IDE, outside through command line.
And every attempt I keep getting this error.
I'm running on Windows environment.
Any help would be appreciated.
Thanks.
Comment: What runner are you using to run this? Directrunner?
Comment: I want to run it locally so I'm not providing any. I just run: mvn exec:java -Dexec.mainClass="xx.xx.ingestion.TimeSeriesLoad"  to execute the main program.
Comment: I'm not completely sure of what could be your problem. One thing that happens in the Dataflow runner (perhaps others) is that `Read` transforms won't execute if they are not consumed. Have you tried adding a ParDo after the read in your pipeline?
Answer: I believe this is an issue in Cloud Bigtable client that has been fixed in a later version. Beam 2.1.0 uses the new version, please try using Beam 2.1.0 and let us know if the problem persists.
Comment: Yep. It works fine now. I just updated the version to 2.1.0 and its working as expected. Thank you for your help.
Comment: I'm the author of the java Cloud Bigtable client.  We did indeed have a problem in the Cloud Bigtable (cbt) java client version 0.9.6 that Beam 2.0.0 used.  This was fixed in the 0.9.7 cbt java client that Beam 2.1.0.  For some context... everything worked fine when invoking operations in GCP in the 0.9.6 release, so we didn't notice the problem.  The problem was a bit nuanced.  This was the Pull Request that fixed the problem: https://github.com/GoogleCloudPlatform/cloud-bigtable-client/commit/9ad8d0c545a3c8c2beaf80f8a9e1111227f9a033


cronjob php file duplicated continously

Question: I have setup a few cronjobs in cPanel and it seems that everytime it runs the scripts, it writes a file to the root folder of that cPanel account. The problem is that the cronjobs run often and therefor there are hundreds of files created daily.
The files it creates are "phpfile.php.1" and "phpfile.php.2" and so on. And they are all completely empty. Here is a screenshot: https://i.stack.imgur.com/kCctw.png
I have also posted about this issue at the official cPanel forums but they have no idea. So im thinking that it must be a setting either in cPanel or WHM that is causing this. Im running Redhat 32bit e5 and I have full root access. Any ideas?
Answer: Are you running these crons using wget? I think that you need to send the answer of the wget command to /dev/null with the -O option.
You need to run the cron with this:
<code>wget http://mysite.com/phpfile.php -O /dev/null
</code>
Otherwise the wget will write the result of the command on phpfile.php, phpfile.php.1, etcphpfile.php.2, every time it runs. With /dev/null you're discarding the answer and no file is written.
Comment: Yes I am using wget, could you please elaborate on your answer? I am not very experienced with scripting...

cronjob php file duplicated continously


fittedbox with maximum two lines in flutter

Question: <code>Container(
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 60),
        child: Text(
          //  subCategoryName,
          "This is a very Long Text takes more space",
          textAlign: TextAlign.center,
          maxLines: 2,
          overflow: TextOverflow.fade,
          style: Theme.of(context)
              .textTheme
              .headline3
              .copyWith(color: Colors.white, fontSize: 32),
        ),
      ),
    ),
</code>
Look this Picture
I need this line to be a maximum of two lines and shrink the size like a FittedBox (with BoxFit.fitWidth) if the text gets even longer
When I used the FittedBox it looking like this. But I need to take it up to 2 lines if needed.. Any solution is appreciated
Comment: Maybe [this package](https://pub.dev/packages/auto_size_text) can help you
Answer: Got it working by the reply of Sam Chan.
I used the AutoSizeText Package


How to get update from Master to branch in TortoiseGit

Question: I have checked out the master version from remote repository and did switch to branch named dev. Now I did some changes in dev branch which need to be pushed into dev remote branch. But I need to have a sync and updates from master too before pushing my changes into dev branch.
Help me how to achieve this in TortoiseGit.
Answer: Merge

Switch/Checkout to "master"
Pull
Switch/Checkout to "dev"
Right click on "master" branch, and Merge to "dev"
Push dev

Rebase

Fetch origin
Right click on "origin/master" and Rebase "dev" onto this...
Start Rebase
Push dev
Answer: I had the same problem, so in order to merge the master to branch was like do the merge branch to master.
TIP: before you get update from master to realize the merge you should:

update your local repository (master) before to switch to your branch;
switch to your branch;
peform the stash save;

Peform the merge, so:

peform the stash pop;
solve the conflits;
perform the push;
perform the commit;

Otherwise the changes made at master wont go to branch.
See also: Merging code branch to master using tortoisegit


Area of a rhombus in co-ordinate geometry

Question: I am trying to solve the question:

In the $xy$-plane, two adjacent vertices of the rhombus are $(-2,2)$ and $(2,7)$
A. Area of rhombus is greater
B. 41 is greater
C. Both are equal
D. Cannot be determined

I tried the distance formula to get the distance between the two points which is $\sqrt{41}$ but I don't know what to do next.
Comment: @Vai I'm still not entirely sure what your question is. Are you saying that (A) should read 'area of rhombus is greater than $41$' and (B) should read '$41$ is greater than the area of the rhombus'?
Comment: Have you missed part of the question out? Area of the rhombus is greater than what?
Comment: Has your book defined "rhombus" so that a square is a rhombus, or so that a square is not a rhombus?
Comment: @lioness99a No. The question asks what is greater between A and B. C and D are equal and cannot be determined respectively.
Answer: Since the side of the rhombus is $\sqrt{41}$, the area of the rhombus is $41\sin\theta$, where $\theta$ is either of the (supplementary) internal angles of the rhombus.  So the area is somewhere between $0$ (if the rhombus is totally "flat") and $41$ (if the rhombus is a square).  If we were told that the rhombus is not a square, B would be the correct answer.  As we were not told that, D is the correct answer.
Answer: The area cannot be determined as two points are insufficient to describe a rhombus.
Comment: There's more to it than that. If the points had bee $(0,0)$ and $(0,5)$ then we would know the area is less than $41.$
Comment: Well think of the other parallel side of the rhombus, it may be inclined at any angle from ${\pi}\over 2$ to $0$ and still satisfy the conditions to be a rhombus. Since you do not know anything else about the rhombus, its area cannot be determined.
Comment: That is what is given in the answer key. You're correct but can you kindly provide me with an explanation for that ?
Comment: @DavidK thanks for the explanation
Comment: @Sam thanks for the explanation
Comment: Well, as @Mathew Daly notes, a square is actually the only such rhombus with area 41. All of the other ones have less area. So, though you don't know, since they could be equal, you almost have enough information, in some sense.
Answer: Using https://artofproblemsolving.com/wiki/index.php/Rhombus#Proof_that_the_diagonals_of_a_rhombus_divide_it_into_4_congruent_triangles
the intersection of the two diagonals will lie on the circle
$$(x-2)(x+2)+(y-2)(y-7)=0$$
Hence the point cannot be determined with the information supplied
So, will be the lengths of the two diagonals


is there a way to discard all mail sent to a user

Question: I started to get some spam mails to a unique user, and that user does not exist in our system.
so I want that all mail for that nonexistent user gets discard.
is this possible?
[update]
my scenario is like this:

we have a few defined users.
we have a unique account to get all mail that get all mail (for undefined accounts), D_PASS and luser_relay.
spamassassin usually score and discard the mail marked as spam.
we started to receive some spam and their score like not spam, but is only to one
unique (nonexistent) account.
I want to discard all mail to that user, I don't care about the
score.
Comment: Is it not already bouncing since the user doesn't exist?
Comment: no, because I have the general rule D_PASS all mail to a defined account, but in this special case, the mail scores like not spam (amavis).
Answer: you can use luser_relay, in this way, you setup an email address for emails users that doesn't exist in your system
http://www.postfix.org/ADDRESS_REWRITING_README.html#luser_relay
Comment: I updated my question.


Why are these double notes labeled 'contrary motion'?

Question: In my PDF version of Slonimsky's Thesaurus, there's a section called 'Double Notes in Contrary Motion' on page 215. Can anyone explain why he is calling these contrary motion? To me, apart from the very last example no. 343 (at the bottom of page 217), they all seem to be either similar or parallel motion. I'm sure I must be missing something obvious.
Comment: we need a picture, could you please provide one?
Comment: I don't know  whether we have the same sheet?
do you mean this pdf: http://www.lapetitedistribution.org/archive/Nicolas_Slonimsky.pdf
answer: in each line p. 215 is at least one group of 4 - 6  16th in countrary motion ...
Answer: Each hand plays 3rds in similar motion.   The contrary motion is between the two hands, as marked.  It's not ALL contrary motion, but there's a lot of it]1


Alternativa a Observable e Observer em Java 9

Question: Para fins de teste, estou portando uma aplicação da versão 7 para a versão 9 do Java.
Esta aplicação possuí algumas funcionalidades que utilizam Observer e Observable.
Percebi que ambas se tornaram obsoletas:
@Deprecated(since="9") public class Observable extends Object
@Deprecated(since="9") public interface Observer

Porque foram marcadas como tal?
Existe uma alternativa para essa funcionalidade?
Como fica o Design Pattern Observer?
Answer: Como toda função que se torna obsoleta, elas não atendiam bem as necessidades, foram mal projetadas e agora tem soluções melhores.
Esses tipos eram gerais demais, não carregavam informações importantes sobre o evento e não eram tão seguras do ponto de vista da tipagem.
O pessoal reclamava que não era capaz de lidar com concorrência e serializar o objeto.
Posição oficial:

They don't provide a rich enough event model for applications. For example, they support only the notion that something has changed, but they don't convey any information about what has changed. There are also some thread-safety and sequencing issues that cannot be fixed compatibly.

Fonte.
Todo o padrão foi mal pensado. Por isso que deve se tomar cuidado com design patterns.
Uma das alternativas é o PropertyChangeListener que geralmente é mais específico, mais simples e é o que deseja.
Se precisar de algo mais poderoso pode usar a classe Flow. A própria documentação indica isso.
Answer: A criação do Observer é creditada, segundo Martin Fowler, à implementação do MVC no SmallTalk (veja GUI Architectures). A ideia central do padrão é notificar observadores quando algum observável encontra-se em um estado de interesse dos observadores. No caso do MVC, os modelos eram observáveis e as visões observadoras. Quando o modelo mudava, a visão era notificada e alterava aquilo que era exibido para o usuário.
Nenhum (nenhum talvez seja muito forte) padrão de projeto é, em essência, ruim. Existem cenários em que seu uso pode ser interessante e outros em que não. É sempre importante avaliar os prós e contras, bem como alternativas, quando se escolhe entre um padrão ou outro.
No caso do Java, conforme o Maniero mencionou, a Oracle menciona como motivação para tornar os componentes obsoletos principalmente o fato de não existir uma ordem garantida para a notificação dos observadores (o que pode ser um problema).
Mas o fato da Oracle ter tornado os componentes obsoletos não significa que você deva parar de usar o padrão. A implementação de Observable e Observer no Java é bem simples. Não é difícil criar uma versão sua que corrija os problemas mencionados pela Oracle.
No link mencionado pelo Maniero com motivos para não usar o Observer, existem várias críticas que se aplicam muito mais ao exemplo que o autor do post escolheu dar do que propriamente às características do padrão, para citar apenas alguns:
Side-effects Observadores não precisam ser stateless. Não creio que haja menção a isso no livro do GoF, mas, mesmo que haja, é uma sugestão de como usar, não uma regra.
Encapsulation Para o exemplo que o autor deu, sim, mas no próprio exemplo mecionado da visão (MVC), não há quebra de encapsulamento.
Composability A necessidade de descartar diversos observadores ao mesmo tempo é muito mais uma demanda específica de domínio do que uma regra geral que possa desmerecer o padrão.
Separation of concerns Aqui o autor do post sugere usar o MVC, talvez não sabendo que sua implementação original previa justamente o Observer...
Quanto ao PropertyChangeListener, um ponto a observar é que ele trata mudanças em propriedades individualmente e não em conjunto, como uma implementação mais genérica do Observer permitiria fazer. Se este for o seu contexto, atende bem.


Django can't click the button

Question: this is jquery
{% block custom_js %}

{% endblock %}

this is submit html

Studing

   <form class="rightform" id="jsStayForm">

                    <input type="text" name="name" id="companyName" placeholder="name" maxlength="25" />

                    <input type="text" name="mobile" id="companyMobile" placeholder="mobile"/>

                    <input type="text" name="course_name" id="companyAddress" placeholder="course_name" maxlength="50" />

                <input class="btn" type="text" id="jsStayBtn" value="consult >" />

            {% csrf_token %}
            </form>

this is urls
urlpatterns = [
    # 课程机构列表页
    url('^list/$', OrgView.as_view(), name="org_list"),
    url('^add_ask/$',AddUserAskView.as_view(), name='add_ask'),
]

There is an input box on the page, which is ajax and is implemented through jquery.But when I'm done, I don't have any reaction to the click of the button, I don't know what went wrong.This should be a POST request,How should I modify the normal submission?
Comment: When you debug in your browser, is there any error on the debugging console?  Is the click handler invoked at all?  Is the AJAX request made?  Is it what you expect?  What is the server's response?
Comment: there might be one issue of html structure try with just form tag and remove div.
i need to check it but let me know after doing it.
Answer: my bad.Because I didn't use jquery, I made a small mistake in using django for the first time.It should be written like this:
url:"{% url 'org:add_ask' %}",

Answer: try like this
$(document).on('click', '#jsStayBtn',function(){

   //ajax function

});

Sometimes compiler will not found the class/id. Hope this helps

Django can't click the button


Images too large when wrapped with with css generated content

Question: I have a sample page here
As you can see, the "recipe maker" and "video" images in that 4-up row overflow their parents.
The are in a standard Zurb Foundation 3 "block-grid" and, as such, are set to max-width 100%.  All the images WITHOUT the orange bar on top work fine.
Also, this whole setup works fine in Webkit browsers (Chrome 26, Safari 6, iOS): it does not work in FF (21) or IE (10).
If I remove display inline block from the callout, the image size goes back to normal, but I need the orange boxed text to be at the top, as in Webkit.
Answer: Adding max-width to the callout fixes it. Without that the images are becoming too wide:
<code>.callout {
    display: inline-block;
    max-width: 100%;
    position: relative;
}
</code>
This also fixes it in Opera, as it originally only works in WebKit browsers.


Weighting output of cost function based on user input

Question: Hi I am creating an android app that will generate a cycling route for users using a route finder.
I am trying to allow the user to either prefer distance or routes with cyclelanes present.
I have a slider from 0 to 10, where 0 means the user wants the shortest route, and 10 where the user wants roads with cyclelanes (if available).
The roads are represented as a graph and I have a function that calculate the shortest path from one point to another.
Given the output of this function: if there is a cyclelane present on the road I want to weight the result so that the higher the number the user chose, the lower the cost of the road and vice versa.
I am not really sure how weighted functions work.
Comment: Is a slider really the best way to collect such potentially serious user preferences as the presence of cycle lanes?
Answer: if you calculate the route with dijkstra-like algorithm, in case of a cyclelane-edge, you should simply decrease the distance between two point by some value according to the slider-value


Signature length not correct when calling PGPOnePassSignature.verify

Question: We're using a Java libarary called license3j for license management. The library uses asymmetric encryption and relies itself on Bouncycastle. We create a license file using a simple gpg command and verify the license within our software using our public key. So far everything worked fine. BUT: In 1,000 generated licenses, there is a very small fraction which cannot be verified correctly, although, they are in fact valid (approximately 5/1000).
What happens in this case: When the license is to be verified in com.verhas.licensor.License.setLicenseEncoded(InputStream), the org.bouncycastle.openpgp.PGPOnePassSignature.verify(PGPSignature) throws the following exception:
org.bouncycastle.openpgp.PGPRuntimeOperationException: unable to verify signature: Signature length not correct: got 511 but was expecting 512
Sounds rather obscure to me, having only basic cryptography knowledge. Spending hours googling, gave me the clue, that there is something about "leading zeros". So, in the given example, obviously a leading zero was stripped away somewhere (where?), and the lengths of the signature data to compare do not match. Makes sense.
Now, I've no clue, where the issue might be located. Is it during creation of the license file? Essentially, we're just doing the following:
gpg --armor --local-user=name.of.software --sign

Which will give us the license file.
Or does the error happen during verification? Do I have to modify any Bouncycastle configuration to correctly address the leading zero issue? Their FAQ gives some hints, but the License3j source obviously never makes use of any Cipher instance, so I'm totally lost on how to integrate this into the given API.
I'm aware that this is a very special problem with a library which is obviously not very well known. Thus, I appreciate any little feedback or input.
Answer: Looks like it is a bug in bouncycastle, only encountered in versions of Java after 1.6, bouncycastle has always created the data wrong, but Java became more strict since 1.7 in the data it will accept during verification.
Bouncycastle is failing to pad the signature to the right length when it serializes it to the file, if the integer has enough leading zeros then the byte representation of it will be smaller.
Java versions 1.7 and above expect RSA signature bytes to be the same length as the key.
Bouncycastle converts the RSA signature byte array(returned from Java's RSA JCE provider) into an integer and it discards information about its length.
Line 263 of the PGPSignatureGenerator shows where the RSA signature bytes are returned from JCE and converted into an integer.
This integer is eventually written to the outputstream using MPInteger#encode which just uses the bitlength of the underlying biginteger to determine how much data to write.
This answer describes more about why you see this aproximatley one in every 200 cases and how the version of Java plays a role.
Comment: Unfortunately, fixing it in bouncycastle looks to be non-trivial, you could try raising a bug in their issue tracker but im not sure how much success you will have. A hacky work around could be to try and verify each license and regenerate it if it fails.
Comment: I don't believe there are any other free Java libraries that do PGP.
The actual RSA signature verification is being processed by the Java standard library, which is why the behavior changed in 1.7. If you want to modify license3j, you might be able to hack in some padding by wrapping the verifier provider, but im not sure if it will work. https://gist.github.com/magJ/27b2909ce749da6dd0ea19a3eb334a53
Comment: Thank you Magnus, that really helped on understanding the issue! Do you have any suggestions how I could solve this problem with a manageable effort? Stepping through the BC source doesn't reveal any point where I could hook into. Are there any alternatives which I could use?
Comment: Actually I also had the idea with regenerating the licenses, but our server where the licenses are generated is not running in a Java environment. It would be a huge pita to set up a JRE just for verifying the licenses. I'll try to raise an issue at BC about it. One more question: Are there further crypto libraries beside BC, or can the verification of a GPG signature also be performed with classes from the Java API nowadays? After all, there is e.g. a `java.security.Signature` class. The verification steps do not seem too complicated at all, so I'd also consider re-writing that functionality.
Comment: Cool, I'll check this out once I find some more free minutes! Thank you!!


Sion's MinMax theorem over matrices

Question: Suppose $A\in R^{n\times n}$ is positive definite, i.e., $A>0$. Can we apply Sion's theorem to conclude the following:
$\underset{Y\in R^{n\times n}}{\min}\underset{X\in \mathcal{S}}{\max} \text{Trace}(YAY^T+YXY^T)=\underset{X\in \mathcal{S}}{\max}\underset{Y\in R^{n\times n}}{\min}\text{Trace}(YAY^T+YXY^T)$
where $\mathcal{S}$ is the set of all positive definite matrices? How about if $\mathcal{S}$ is the set of all positive semi-definite matrices?
Comment: Are there any transposes missing or are you assuming $Y$ to be symmetric by any chance?
Comment: I edited and added the transpose.
Answer: $f(Y,B):=\text{Tr}(YBY^T)\ge0$ for all positive semi-definite $B$. $f(0,B)=0$. So $\min_{Y\in R^{n\times n}}f(Y,B)=0$ for every $B$. Therefore both sides of your desired equation are $0$ and thus the equation holds. There is no need for Sion's theorem. Besides, the premise of Sion's theorem is not satisfied as $R^{n\times n}$ is not compact.
Comment: For Sion's theorem we only need for one of the sets to be compact.
Comment: My questions here will be whether $X\geq 0$, $X\in R^{n\times n}$ is homeomorphic to the open ball of $\mathbb{R}^{n(n+1)/2}$ for an arbitrary norm
Comment: @EricBrown: Yes, the homeomorphism exists but then you need to map infinity onto the shell of the ball to close the set. Once you do that, do you still have the semi-concavity and semi-convexity?
Comment: I think I used a bad example for my question. What I was wondering was more like: Can we apply Sion's theorem to conclude the following:

$\underset{Y\in R^{n\times n}}{\min}\underset{X\in \mathcal{S}}{\max} f(X,Y)=\underset{X\in \mathcal{S}}{\max}\underset{Y\in R^{n\times n}}{\min}f(X,Y)$
where $f$ is concave in X and convex in $Y$, and $\mathcal{S}=\{X\in R^{n\times n}| \|X\|\leq 1\}$. Here $\|Y\|$ is the spectral norm of matrix Y.
Comment: @EricBrown: Well yes, but is it not just Sion's theorem directly?
Comment: To apply the Sion theorem here we need to show $\mathcal{S}$ is homeomorphic to a compact and convex set in $R^{n^2}$. How can we show this? Would $\mathcal{S}$ be compact and convex if $\|X\|<1$?
Comment: @EricBrown: Of course, any bounded and closed set in $R^n$ for finite $n$ is compact. Your $<$ or open ball should be replaced by $\le$ or closed ball. Do you need the proof of convexity of $\|X\|\le1$?
Comment: I think I know how to prove the convexity. Here $X\in R^{n\times n}$ is a matrix. I just want to know how to show that set of matrices that satisfy $\|X\|\leq1$ is homeomorphic to a compact and convex set in $R^{n^2}$ (vector space).
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/71882/discussion-between-hans-and-eric-brown).
Comment: @EricBrown: If you know how to show the convexity, and I have told you how to prove compactness, you are all set.
Comment: Convexity can be shown as follows: consider $\|X_1\|\leq 1$ and $\|X_2\|\leq 1$. Then $\|\lambda X_1+(1-\lambda)X_2\|\leq \lambda\|X_1\|+(1-\lambda)\|X_2\|\leq \lambda+(1-\lambda)=1$, for all $\lambda\in[0,1]$.
Comment: @EricBrown: Then you, as I said, are all set and have no more problem with this question. Do you agree? I just don't see why you keep referring to a homeomorphism. The closed ball $\|X\|\le1$ IS a compact and convex set already under the topology defined by the norm.
Comment: The reason I am using homeomorphism is because this question is asked in the context of optimization problem whose decision variables should live in vector space, rather than matrix space. So to use Sion's theorem, I think we should prove convex and compactness in vector space. I am not a mathematician, so I would appreciate it if you correct me.
Comment: @EricBrown: I see. That explains the apparent slight confusion here. The homeomorphism here is the trivial one, as $R^{m\times n}$ IS a (abstract) vector space since it satisfies the definition of one. More concretely, you can simply reshape or unravel an $m\times n$ matrix  into a column one of size $(m\times n)\times1$.
Answer: I am not sure if you would need Sion' minmax theorem to prove this.
Note that the max on the left-hand side when fixing $Y\neq 0$ is $+\infty$ as the objective is linear in $X$ and $Y^TY\succeq 0$. The left-hand side is only bounded for $Y=0$, so the left-hand side is 0.
Now let's look at the right-hand side: $Tr(AB) \geq 0$, when $A$ and $B$ are PSD. So the min on the right-hand side should be 0, which is achieved at $Y=0$, regardless of X. So the right-hand side is also 0.

Sion's MinMax theorem over matrices


How to make PDF viewer in PHP

Question: I want to open PDF file with PHP. Don't want to use Flash. Like google doc viewer. I just want to open PDF file. Can I do with PHP ?
Comment: If you just want to open up a PDF file with php, there are a set of PDF functions (http://php.net/manual/en/book.pdf.php).
Comment: are you opening it just to display it in a site/web app or are you  trying to read text from the PDF for other purposes?
Comment: I want to get some text from PDF. If PHP can do like google doc viewer, I want to do.
Answer: PHP cannot natively open and display a PDF file to the browser. In most cases you want to just send the file to the browser and allow the Adobe Reader to open and display the file. However, if you are looking to pull data out of the PDF itself, then the PDF function built-into PHP may be of some help.
http://php.net/manual/en/book.pdf.php
Answer: You can't BUT
You can make one with PHP
making a previews of each page
like google reader
this links may help you
How do I convert a PDF document to a preview image in PHP?

How to make PDF viewer in PHP


jQuery animating with ".not()"

Question: I am creating a very simple quiz application with jQuery. How it works is you have a question and three answers. Clicking on the wrong answer makes the clicked answer's opacity fade to 60%. Clicking on the correct answer should make all the wrong answers fade out completely leaving only the correct answer remaining.
The page has 3 quizzes selectable by a navigation. So I am sorting through tests and questions using .index() to target the specific question at hand. Which works as other elements of the quiz are working fine.
The only issue I am having is getting the other answers to fade out on selecting the correct answer. Right now, only the first question is functioning this way; all other questions remain at 100% opacity. I've been staring at it all night trying to get it to go and could use an extra set of eyes on this.
CODE :
 $('#test .test li ol li').click(function()
{
    if($(this).attr('class') == 'correct')
    {
        var testNum = $(this).closest('.test').index('.test');
        var qustNum = $(this).index('.correct');
        var corAns = $(this);
        var theList = $('.test:eq(' + testNum + ') li:eq(' + qustNum + ') ol li');

        //find other questions
        theList.not('.correct').animate({ opacity : 0 }, 1000);

        getAnswer(testNum, qustNum, corAns);
    }
    else
    {
        $(this).animate({ opacity : 0.6 }, 500);
    }
});

function getAnswer(testNum, qustNum, corAns)
{
    console.log(testNum + ' : ' + qustNum + ' : ' + corAns.text());

    //get xml file with answers
    $.ajax({
        type: "GET",
        url: "answers.xml",
        dataType: "xml",
        success: function(xml) {
             $(xml).find('Answers').each(function(){
                //find the answer in the xml
                var answer = $(this).find('test:eq(' + testNum + ') answer:eq(' + qustNum + ')').text();
                console.log(answer);
                //place answer inside correct li
                corAns.html(answer);
             });
        }
    });

    //fade in next button
    $('#test span').css({ 'display' : 'block' }).delay(2000).animate({ opacity : 1 }, 1000);

    $('#test span').click(function()
    {
        $('.test:eq(' + testNum + ')').animate({ top : '-=286px' }, 500);
    });
}

HTML :

test

How Much Do You Know?(choose a test)

                    Which blood cells carry oxygen throughout your body?

White Blood Cells

Red Blood Cells

Oxygen Cells

                    A blood test procedure can be made easier if you…

imagine you are in a comfortable place during the test.

wear something red.

don't sleep for a week before the test.

Why do you need to have blood tests?

To make sure you have blood

Because it's easier than a math test

So the doctor can check your health

How often do you need to have a blood test?

Once a year

Twice a month

It depends on your health

How long does it take for your body to replace the blood taken from a blood test?

One year

One day

One hour

How much blood is drawn in a typical blood test?

About half a cup

About one teaspoon

About 1/2 gallon

On average, about how much blood does a person have in their body?

A little more then one gallon

1/2 gallon

Four gallons

Which blood cells help your body fight infection?

Army cells

White blood cells

Red blood cells

Which cells help you stop bleeding if get a cut?

Platelets

Red blood cells

Plug-up cells

The area on your skin where blood is drawn must be cleaned because…

It's always better to look clean

It is important that the blood sample is not infected

The test won't hurt as much

If you have anemia it means your blood has…

too many red blood cells.

too few red blood cells.

too many white blood cells.

About how many blood chemistry tests are preformed in the United States each year?

100,000

3 million

6 billion

Where are blood cells made?

Your heart

Your bone marrow

California

A Complete Blood Count (CBC) is a test in which…

all of the different cells in your blood are counted.

a machine looks at the chemicals in your blood to check for disease.

the amount of blood in your body is counted.

Testing for blood types is important in order to…

receive the right blood type if you ever need blood.

be eligible for a drivers license.

learn about your personality.

            Next Question -->

Additional:
All console.log's show the correct index is being targeted by the variables on each click.
The test html is built of nested ordered lists.
Thanks for any help on this. I'll bet its something simple I've overlooked.
Comment: Ok added the html and also the getAnswer function that is reference in the click function. Thanks
Answer: Replace:
theList.not('.correct').animate({ opacity : 0 }, 1000);

With:
$(this).siblings().animate({ opacity : 0 }, 1000);

Comment: That was it!
Thank you. Looks like I need to revisit the jQuery documentation.
Answer: Change this
var theList = $('.test:eq(' + testNum + ') li:eq(' + qustNum + ') ol li');

to
var theList = $('.test').eq(testNum).find('li').eq(qustNum).find('ol li');

Comment: The same problem persists. I think the issue comes from elsewhere. Thanks though

jQuery animating with ".not()"


Autocovariance of an ARMA(2,1) process - derivation of analytical model for $\gamma( k)$

Question: I need to derive analytic expressions for the autocovariance function $\gamma\left(k\right)$ of an ARMA(2,1) process denoted by:
$y_t=\phi_1y_{t-1}+\phi_2y_{t-2}+\theta_1\epsilon_{t-1}+\epsilon_t$
So, I know that:
$\gamma\left(k\right) = \mathrm{E}\left[y_t,y_{t-k}\right]$
so I can write:
$\gamma\left(k\right) = \phi_1 \mathrm{E}\left[y_{t-1}y_{t-k}\right]+\phi_2 \mathrm{E}\left[y_{t-2}y_{t-k}\right]+\theta_1 \mathrm{E}\left[\epsilon_{t-1}y_{t-k}\right]+\mathrm{E}\left[\epsilon_{t}y_{t-k}\right]$
then, to derive the analytic version of the autocovariance function, I need to substitute values of $k$ - 0, 1, 2 ... until I get a recursion that is valid for all $k$ greater than some integer.
Therefore, I substitute $k=0$ and work this through to get:
$$
\gamma \left(0\right) = \mathrm{E}\left[y_t,y_t\right]
 =  \phi_1 \mathrm{E}\left[y_{t-1}y_t\right] + \phi_2 \mathrm{E}\left[y_{t-2}y_t\right]+\theta_1 \mathrm{E}\left[\epsilon_{t-1}y_t\right]+\mathrm{E}\left[\epsilon_ty_t\right]\\
$$
now I can simplify the first two of these terms, and then substitute for $y_t$ as before:
$$
\gamma\left(0\right) = \phi_1 \gamma\left(1\right) + \phi_2 \gamma\left(2\right)\\
+ \theta_1 \mathrm{E}\left[\epsilon_{t-1} \left(\phi_1 y_{t-1} +\phi_2 y_{t-2} +\theta_1 \epsilon_{t-1} + \epsilon_t \right)\right]\\
+ \mathrm{E}\left[\epsilon_t \left(\phi_1 y_{t-1} +\phi_2 y_{t-2} +\theta_1 \epsilon_{t-1} + \epsilon_t \right)\right]
$$
then I multiply out the eight terms, which are:
$$
+\theta_1\phi_1\mathrm{E}\left[\epsilon_{t-1}y_{t-1}\right]\\
+\theta_1\phi_2\mathrm{E}\left[\epsilon_{t-1}y_{t-2}\right]\\
+\theta_1^2\mathrm{E}\left[\left(\epsilon_{t-1}\right)^2\right]=\theta_1^2\sigma_{\epsilon}^2\\
+\theta_1\mathrm{E}\left[\epsilon_{t-1}\epsilon_{t}\right]=\theta_1\mathrm{E}\left[\epsilon_{t-1}\right]\mathrm{E}\left[\epsilon_{t}\right]=0\\
+\phi_1\mathrm{E}\left[\epsilon_{t}y_{t-1}\right]\\
+\phi_2\mathrm{E}\left[\epsilon_{t}y_{t-2}\right]\\
+\theta_1\mathrm{E}\left[\epsilon_t\epsilon_{t-1}\right] = \theta_1\mathrm{E}\left[\epsilon_{t}\right]\mathrm{E}\left[\epsilon_{t-1}\right]=0 \\
+\mathrm{E}\left[\left(\epsilon_t\right)^2\right] = \sigma_{\epsilon}^2
$$
So, I am left needing to resolve the four remaining terms.  I want to use the same logic for lines 1, 2, 5 and 6 as I used on lines 4 and 7 - for example for line 1:
$\theta_1\phi_1\mathrm{E}\left[\epsilon_{t-1}y_{t-1}\right] = \theta_1\phi_1\mathrm{E}\left[\epsilon_{t-1}\right]\mathrm{E}\left[y_{t-1}\right] = 0$ because $\mathrm{E}\left[\epsilon_{t-1}\right]=0$.
Similarly for lines 2, 5 and 6.  But I have a model solution that suggests the expression for $\gamma\left(0\right)$ simplifies to:
$\gamma\left(0\right) = \phi_1\gamma\left(1\right)+\phi_2\gamma\left(2\right) +\theta_1\left(\phi_1+\theta_1\right)\sigma_{\epsilon}^2+\sigma_{\epsilon}^2$
This suggests my simplification as described above would miss the term with the coefficient $\phi_1$ - which under my logic should be 0. Is my logic at fault, or is the model solution I found incorrect?
The worked solution also suggest that "analogously" $\gamma\left(1\right)$ can be found as:
$\gamma\left(1\right) = \phi_1\gamma\left(0\right)+\phi_2\gamma\left(1\right) + \theta_1\sigma_{\epsilon}^2$
and for $k>1$:
$\gamma\left(k\right) = \phi_1\gamma\left(k-1\right)+\phi_2\left(k-2\right)$
I hope the question is clear.  Any assistance will be much appreciated. Thank you in advance.
This is a question related to my research, and is not in preparation for any exam or coursework.
Answer: If the ARMA process is causal there is a general formula that provides the autocovariance coefficients.
Consider the causal $\text{ARMA}(p,q)$ process
$$
y_t = \sum_{i = 1}^p \phi_i y_{t-1} + \sum_{j = 1}^q \theta_j \epsilon_{t - j} + \epsilon_t,
$$
where $\epsilon_t$ is a white noise with mean zero and variance $\sigma_\epsilon^2$.
By the causality property, the process can be written as
$$
y_t = \sum_{j = 0}^\infty \psi_j \epsilon_{t - j},
$$
where $\psi_j$ denotes the $\psi$-weights.
The general homogeneous equation for the autocovariance coefficients of a causal $\text{ARMA}(p,q)$ process is
$$
\gamma (k) - \phi_1 \gamma (k-1) - \cdots - \phi_p \gamma (k-p) = 0,
\quad k \geq \max (p, q+1),
$$
with initial conditions
$$
\gamma (k) - \sum_{j = 1}^p \phi_j \gamma (k-j)
  = \sigma_\epsilon^2 \sum_{j = k}^q \theta_j \psi_{j - k},
\quad 0 \leq k < \max (p, q+1).
$$
Comment: What are these $\psi$ in the second and last equation? How are they expressed in terms of the ARMA parameters? Is there no closed-form solution in term of the original ARMA parameters? Perhaps in a matrix form? Thank you
Comment: there is an indexing error in the formula of the AR part of the general ARMA formula. t-1 should be t-i
Answer: Your calculation mistake in your original question lies in
$$\theta_1\phi_1\mathrm{E}\left[\epsilon_{t-1}y_{t-1}\right] = \theta_1\phi_1\mathrm{E}\left[\epsilon_{t-1}\right]\mathrm{E}\left[y_{t-1}\right] = 0 \qquad \text{(mistaken)}$$
You cannot separate the expectation $\mathrm{E}\left[\epsilon_{t-1}y_{t-1}\right]$ - $\epsilon_{t-1}$ and $y_{t-1}$ are not independent.
Comment: As you can see from my update (below) I realised this soon after completing the post - but many thanks for your help!
Answer: I would like to share here an approach for calculating the initial conditions mentioned in the answer from @QuantIbex, since the appearance of the $\psi$ parameters from the $MA(\infty)$ representation in that equation does not allow for immediate calculation based on the original ARMA parameters.
Using ARAM(2,2) as an example, we first multiply the ARMA equation
$$\phi_0 y_t + \phi_1 y_{t-1} + \phi_2 y_{t-2} = \theta_0 \epsilon_t + \theta_1 \epsilon_{t-1} + \theta_2 \epsilon_{t-2}$$
by $\epsilon_t$, $\epsilon_{t-1}$, and $\epsilon_{t-2}$, and take expectations to get three equations which can be written is a matrix form as
$$
\begin{bmatrix}
\delta_0 & 0 & 0\\
 \delta_1 & \delta_0 & 0\\
\delta_2 & \delta_1 & \delta_0
\end{bmatrix}
\begin{bmatrix}
\phi_0 \\ \phi_1 \\ \phi_2
\end{bmatrix}
=
\sigma^2_{\epsilon}
\begin{bmatrix}
\theta_0 \\ \theta_1 \\ \theta_2
\end{bmatrix}
$$
where $\delta_{j-i} = \mathbb{E}[\epsilon_{t-j}, y_{t-i}]$ and which is equal to 0 for $j > i$. The left-hand side of the above can be re-arranged so that we can write
$$
\mathbf{L} \boldsymbol{\delta} =
\begin{bmatrix}
\phi_0 & 0 & 0\\
 \phi_1 & \phi_0 & 0\\
\phi_2 & \phi_1 & \phi_0
\end{bmatrix}
\begin{bmatrix}
\delta_0 \\ \delta_1 \\ \delta_2
\end{bmatrix}
=
\sigma^2_{\epsilon}
\begin{bmatrix}
\theta_0 \\ \theta_1 \\ \theta_2
\end{bmatrix}
=
\sigma^2_{\epsilon}
\boldsymbol{\theta}
$$
which can be readily solved by forward substitution which we express formally as
$$
\boldsymbol{\delta} = \sigma^2_{\epsilon} \boldsymbol{L}^{-1} \boldsymbol{\theta}.
$$
Often we would have $\phi_0 = \theta_0 = 1$, which would results in $\delta_0 = \sigma^2_{\epsilon}$.
Then we multiply the ARMA equation by $y_t$, $y_{t-1}$, and $y_{t-2}$, and take expectations to get three equations which can be written is a matrix form as
$$
\mathbf{\Gamma} \boldsymbol{\phi} =
\begin{bmatrix}
\gamma_0 & \gamma_1 & \gamma_2 \\
\gamma_1 & \gamma_0 & \gamma_1 \\
\gamma_2 & \gamma_1 & \gamma_0
\end{bmatrix}
\begin{bmatrix}
\phi_0 \\ \phi_1 \\ \phi_2
\end{bmatrix}
=
\begin{bmatrix}
\delta_0 & \delta_1 & \delta_2 \\
 0 & \delta_0 & \delta_1 \\
 0 & 0 & \delta_0
\end{bmatrix}
\begin{bmatrix}
\theta_0 \\ \theta_1 \\ \theta_2
\end{bmatrix}
$$
where
$$\gamma_{|i-j|} = \mathbb{E}[y_{t-i}y_{t-j}] = \mathbb{Cov}[y_{t-i},y_{t-j}]$$
where the last equality is due to us using a "demeaned" process for which $\mathbb{E}[y_{t}] = 0$. The above can also be rearranged as
$$
\mathbf{\Phi} \boldsymbol{\gamma} =
\begin{bmatrix}
\phi_0 & \phi_1 & \phi_2 \\
\phi_1 & \phi_0 + \phi_2 & 0\\
\phi_2 & \phi_1 & \phi_0
\end{bmatrix}
\begin{bmatrix}
\gamma_0 \\ \gamma_1 \\ \gamma_2
\end{bmatrix}
=
\begin{bmatrix}
\theta_0 & \theta_1 & \theta_2 \\
\theta_1 & \theta_2 & 0 \\
\theta_2 & 0 & 0
\end{bmatrix}
\begin{bmatrix}
\delta_0 \\ \delta_1 \\ \delta_2
\end{bmatrix}
=
\mathbf{U} \boldsymbol{\delta}
$$
which leads to a solution for the initial condition of the auto-covariance function
$$
\boldsymbol{\gamma} =
\mathbf{\Phi}^{-1}\mathbf{U} \boldsymbol{\delta} =
\sigma^2_{\epsilon} \mathbf{\Phi}^{-1}\mathbf{U} \boldsymbol{L}^{-1} \boldsymbol{\theta}.
$$
The general forms for the triangular matrices $\mathbf{L}$ and $\mathbf{U}$ are apprant from the above example. The elements of $\mathbf{\Phi}$ in row $i$ and column $j$ can be inferred by looking at the row numbers of $\gamma_i$ in column $j$ of the $\boldsymbol{\Gamma}$ matrix and are in general given by (I believe)
$$
(\mathbf{\Phi})_{ij} = \sum_{k=0}^{p} \phi_k \mathbb{I}(|k - i| = j)
$$
where we assume that the row and column index begins with $0$ (not $1$) and where $\mathbb{I}(A)$ is the indicator function which is equal to 1 when $A$ is TRUE and $0$ otherwise.
Answer: OK. So the process of writing the post actually pointed me to the solution.
Consider the Expectation terms 1, 2, 5 and 6 from above that I thought should be 0.
Immediately for terms 5 - $\mathrm{E}\left[\epsilon_ty_{t-1}\right]$ - and 6 - $\mathrm{E}\left[\epsilon_ty_{t-2}\right]$:  these terms are definitely zero, because $y_{t-1}$ and $y_{t-2}$ are independent of $\epsilon_t$ and $\mathrm{E}\left[\epsilon_t\right] = 0$.
However, terms 1 and 2 look as though the Expectation is of two correlated variables.  So, consider the expressions for $y_{t-1}$ and $y_{t-2}$ thus:
$$
y_{t-1} = \phi_1y_{t-2}+\phi_2y_{t-3}+\theta_1\epsilon_{t-2}+\epsilon_{t-1}\\
y_{t-2} = \phi_1y_{t-3}+\phi_2y_{t-4}+\theta_1\epsilon_{t-3}+\epsilon_{t-2}
$$
And recall term 1 - $\phi_1\theta_1\mathrm{E}\left[\epsilon_{t-1}y_{t-1}\right]$. If we multiply both sides of the expression for $y_{t-1}$ by $\epsilon_{t-1}$ and then take Expectations, it is clear that all terms on the right hand side except the last become zero (because the values of $y_{t-2}$, $y_{t-3}$, and $\epsilon_{t-2}$ are independent of $\epsilon_{t-1}$ and $\mathrm{E}\left[\epsilon_{t-1}\right]=0$) to give:
$$\mathrm{E}\left[\epsilon_{t-1}y_{t-1}\right] = \mathrm{E}\left[\left(\epsilon_{t-1}\right)^2\right] = \sigma_{\epsilon}^2$$
So term 1 becomes $+\phi_1\theta_1\sigma_{\epsilon}^2$. For term 2, it should be clear that, by the same logic, all terms are zero.
Hence the original model answer was correct.
However, if anyone can suggest an alternative way to obtain a general (even if messy) solution, I would be very pleased to hear it!
Comment: So, did you get expression for the auto-covariance function in terms of the model parameters? Could you share your results please?
Comment: @Confounded - are you still interested in this problem?
Comment: Not really.  I think my answer from 16 Nov 2020 provides an algorithm for finding the solution using original model parameters.


Pulling data from multiple Excel sheets with @Dataprovider and passing it to @test

Question: I am facing an issue related to @Dataprovider and @Test
Scenario : I need to get data from multiple sheets(sheet1, sheet2, sheet3, .....) with help of @dataprovider annotation, I have web application in which there are multiple webpages in which I have to pass data.
I've implemented it using POM, I need to get the data from multiple sheets at once and pass it to @test.
below is the snippet:
 @DataProvider
    public Object[][] getHrwsIdentityData() throws IOException
    {
        List<Object[]> DataList = null;
        loggerManager.logger.info("Reading the position testdata from excel sheet");

        DataList = Excel.excelRead(".\\resources\\data\\HR Workwise Automation -New Hires.xlsx", "Identity Details", "Execute Flag", "Y");
        return DataList.toArray(new Object[DataList.size()][]);
    }

    @DataProvider
    public Object[][] getHrwsPersonalData() throws IOException
    {
        List<Object[]> DataList = null;
        loggerManager.logger.info("Reading the position testdata from excel sheet");
        DataList = Excel.excelRead(".\\resources\\data\\HR Workwise Automation -New Hires.xlsx", "Personal Information", "Execute Flag", "Y");
        return DataList.toArray(new Object[DataList.size()][]);
    }

 @Test(priority = 1,enabled = true, dataProvider="getHrwsPersonalData", description="Add New Employee in Manage Employees Page; Coverage: AddNewEmployee")
    public void updateEmployeePersonalInfo(LinkedHashMap<String, String> DataSet) throws IOException
    {
        hrws.addEmployeePersonalInfo(DataSet);
    }

    @Test(priority = 2,enabled = true, dataProvider="getHrwsJobInformation", description="Add New Employee in Manage Employees Page; Coverage: AddNewEmployee")
    public void updateEmployeeJobInfo(LinkedHashMap<String, String> DataSet) throws IOException
    {
        hrws.addEmployeeJobInfo(DataSet);
    }

I tried using different single @DataProviders for each @Test, but No Luck!!
Also below is the readExcel file
public static List<Object[]> excelRead(String sExcelPath, String sSheetName, String sCondCol, String sCondVal) throws IOException{

        String[] sHeaderKey = new String[0];
        String[] sValue = new String[0];
        LinkedHashMap<String, String> RowData;
        List<Object[]> DataList = new ArrayList<>();

        try {
            FileInputStream oFis = new FileInputStream(sExcelPath);

            Workbook workbook = null;

            // Using XSSF for xlsx format, for xls use HSSF

            workbook = new XSSFWorkbook(oFis);

            Sheet sheet = workbook.getSheet(sSheetName);

            Iterator<Row> rowIterator = sheet.iterator();

            DataFormatter formatter = new DataFormatter(Locale.US);

            while (rowIterator.hasNext()) {
                Boolean bHeaderRow = false;
                sValue = new String[0];
                Row row = rowIterator.next();
                if (row.getRowNum() == 0) {
                    bHeaderRow = true;
                }

                Iterator<Cell> cellIterator = row.cellIterator();
                while (cellIterator.hasNext()) {
                    Cell cell = cellIterator.next();
                    if (bHeaderRow && (cell.getCellType() != Cell.CELL_TYPE_BLANK)) {
                        sHeaderKey = Arrays.copyOf(sHeaderKey, sHeaderKey.length + 1);
                        sHeaderKey[cell.getColumnIndex()] = formatter.formatCellValue(cell);
                    } else if ((!bHeaderRow) && (sHeaderKey[cell.getColumnIndex()] != null)) {
                        sValue = Arrays.copyOf(sValue, sValue.length + 1);
                        sValue[cell.getColumnIndex()] = formatter.formatCellValue(cell);
                    }
                }

                if ((sHeaderKey.length != 0) && (sValue.length != 0)) {
                    RowData = new LinkedHashMap<String, String>();

                    for (int i = 0; i < sHeaderKey.length; i++) {
                        RowData.put(sHeaderKey[i], sValue[i]);
                    }

                    if(RowData.get(sCondCol).trim().toLowerCase().equals(sCondVal.trim().toLowerCase())){
                        DataList.add(new Object[]{RowData});
                    }

                }
            }
            workbook.close();
            oFis.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            throw e;
        }
        return DataList;

    }

I need to merge these two @dataproviders into one!!
Answer: You dont need to have multiple data provider for different tests. You need a mechanism to identify which test is calling the data provider. TestNg data providers are overloaded, you can create a data provider method like this Please don't be critical to the code inside this method as its just for demonstration
    @DataProvider(name = "AllTestData")
public static Object[][] GetDataForEveryOne(ITestNGMethod testContext)
{
    if(testContext.getMethodName().equals("LoginWithMultipleUsersTest"))
    {
        String[][] usernamePassArray = { { "testType1", "pass1" },
                                         { "testType2", "pass1" }};

        return usernamePassArray;
    }
    else if(testContext.getMethodName().equals("LoginWithMultipleDataTest"))
    {
        String[][] usernamePassArray = { { "user1", "pass1" },
                 { "user2", "pass2" },
                 { "user3", "pass3" } };

        return usernamePassArray;
    }
    return null;
}

I have just trying to show how you can get the Test context in data provider which in turn can let you get the test method name. This test method name can be used as a key to extract data from Excel corresponding to this test.
Comment: I Got your Point!! But in here the data is linear(like in the datadriven framework)all i need to do is pass each test data to that particular page eg: sheet 1 : data : a, b, c, d
sheet 2 : data : d, e, f, g
I need to extract these two sheets data in one Go!!
and pass it on the two webpages
webpage1 : sheet1 data
webpage 2: sheet2 data
Comment: I Got your Point!! But in here the data is linear(like in the datadriven framework)all i need to do is pass each test data to that particular page eg: sheet 1 : data : a, b, c, d
sheet 2 : data : d, e, f, g


Rails URL doesn't show, only the view renders

Question: I have this route:
get 'events/new' => 'events#new'

and for this, an appropriate action and a template with form_for accepting an empty @event model object:
<%= form_for(@event) do |f| %>

Now, I also have this route:
post '/events' => 'events#hey'

and inside the hey action I don't do anything but let the view template take over which displays some static content.
Here's the problem: When I go to site.com/events/new, enter anything and click on the submit button, Rails redirects me to site.com/events/, displaying the content of the hey.html.erb view template!
Is this expected behavior? What I expected was to go to site.com/events/hey. Is there some implicit redirect of form_for does after the POST request?
Comment: can you please post all your event routes `rake routes | grep event`
Answer: Your post '/events' => 'events#hey' brings you to '/events' where you just render the hey.html.erb template, but that doesn't change the url. What you want to do is this:
post '/events/hey' => 'events#hey'


change colour for parameters on powershell linux

Question:
can you see the -Uri Parameter? this is very hard to read on linux.
is there a way to change the colour?
Comment: This is good and useful information, but probably would be more appropriate on [su] or [unix.se], as the issue is not "[unique to software development](/help/on-topic)". As always, prior to posting on another site, please read the on-topic page for whichever site on which you are thinking of posting this.
Answer: Hemant answered my question on twitter. You can see the colour settings with the Cmdlet Get-PSReadLineOption. To edit the property ParameterColor I ran Set-PSReadLineOption -Colors @{"Parameter"=[ConsoleColor]::Gray}.
Comment: Yes.. Looking at `Get-Help -Name Set-PSReadLineOption` would tell you this.
Comment: also useful: `Get-Help -Name Set-PSReadLineOption -examples`


Resolution of a linear system and optimization problem

Question: I have read everywhere that the resolution of the linear system
$$Ax+b=0$$
where $A\in S_n(\mathbb R)$ and $b\in \mathbb R^n$ is equivalent to the resolution of the following optimization problem:
$$f(x)=\frac 12\langle Ax,x\rangle+\langle b,x\rangle.$$

Which means that if $x\in \mathbb R^n$ minimize the function $f(x)=\frac 12\langle Ax,x\rangle+\langle b,x\rangle$, then $x$ is solution of the linear sytem $Ax+b=0$ where $A\in S_n(\mathbb R)$.

I do not understand why this should be true... Can someone please explain it?
Comment: Did you try finding the gradient of $f$?
Comment: @E.Joseph Because there is only one zero for the gradient. The only other option would be for the function to go toward its minimum "at infinity", but that is also impossible.
Comment: @E.Joseph I see that you have created ([tag:linear-system]) tag. I just wanted to let you know that I have started a post on meta about this new tag: http://meta.math.stackexchange.com/questions/25694/tag-management-2017/25938#25938
Comment: @5xum The gradient of $f$ seems to be $\nabla f(x)=Ax+b$, but I think there is still some arguments missing here...
Comment: It is not true. The sign is wrong.
Comment: @E.Joseph Apart from some sign mixup, yes that's the gradient. And since the function is a continuous and continuously differentiable function, you know that the gradient at its extreme value must be $0$.
Comment: @5xum I am starting to see it! But how do I know there is only one extreme value for $f$?
Answer: U cannot prove this by taking the gradient! This is not a function but a functional! You should variate it!
U have the following functional
$$F[x]=\langle{Ax}, x\rangle-\langle{b, x}\rangle$$
U variate the functional
$$\delta{F[x]}=\langle{Ax}, \delta{x}\rangle-\langle{b, \delta{x}}\rangle=\langle{Ax-b}, \delta{x}\rangle$$
For the extremum, u require the functional to be stationary with respect to any variations, i.e.
$$\delta{F[x]}=\langle{Ax-b}, \delta{x}\rangle=0$$
As the above equality holds for any $\delta{x}$, u better have
$$x^{T}A^{T}-b^{T}=0$$
Taking the transpose of this equation, u arrive at
$Ax=b$
!


How to make the agent pick the highest value between two values?

Question: guys. I created this procedure in NetLogo for my agents (farmers):
to calculate-deforestation

 ask farmers [
  set net-family-labor ( family-labor - ( ag-size * cell-labor-ag-keep ) )
  set net-family-money ( family-money - ( ag-size * cell-cost-ag-keep ) )
  ifelse  net-family-labor < 0 or net-family-money < 0
    [ set n-aband-cell-labor ( family-labor / cell-labor-ag-keep )
      set n-aband-cell-money ( family-money / cell-cost-ag-keep )

      set n-aband with-max [ n-aband-cell-labor n-aband-cell-money ]

      ]

    [ set n-def-cell-labor ( net-family-labor / cell-labor-deforest )
      set n-def-cell-money ( net-family-money / cell-cost-deforest )

      set n-def with-min [ n-def-cell-labor n-def-cell-money ]

      ]
]
end

For the "n-aband", I would like to get the max value between "n-aband-cell-labor" and "n-aband-cell-money" (either one or the other; the same goes for "n-def"). I know a limited number of NetLogo primitives but the ones I was able to find do not work for my case, for instance, "with-max", "max-n-of", "max-one-of". I am sure there must be one that would work but I am having trouble finding it in the NetLogo dictionary. I wonder if anyone could suggest me one that could work for my case. Thank you in advance.
Answer: If you want to get the max value of a list, simply use max. So,
set n-aband max (list n-aband-cell-labor n-aband-cell-money )
will set n-aband to the highest of the two values.
Comment: I did not know I was supposed to use "list" for that, thanks!


Is there a way to dump an Oracle db as SQL statements, à la pg_dump?

Question: I'm very new to Oracle. It looks like all the Oracle DBA use binary only dumps. This sometimes cause problems, and seems rather useless to me (performance gain is bound to be negligible), but what do I know.

Is there a good reason that escapes me?
Is there a tool like pg_dump for Postgres that can generate SQL statements from a database?

One of the application could be moving from one version to another, or converting the data to another DB.
Answer: I am not aware of any tool provided by Oracle that does what you ask. While I have in the past used DbVisualizer to export smaller tables/schemas from oracle (DDL and and insert statements) it isn't quite the same as pg_dump.
However, if you are planing on "converting the data to another DB" where the other DB is postgres then take a look at ora2pg.
Answer: You can use datapump for this. Use expdp with option content=metadat_only, this creates a export with no data. You can use an export file containing data if available, but if you need to create one just for this writing the data is needless. Use impdp with option sqlfile=file_name.sql. This writes all DDL to file_name.sql.
See this link for details


Is it possible to define default config entities in a single yml file?

Question: Following drupal handbook I've created configuration entity type. All works fine except that I have to create ~100 default entities. It would be significantly easier to maintain these default entities if I could define them in a single YML file but that does not work as expected.
If I create files like this:
config/install/example.entity.id1.yml
config/install/example.entity.id2.yml
config/install/example.entity.id3.yml

The config entities are created correctly. However if I create one file config/install/example.entity.yml:
id1:
  field1: val1
  field2: val2

id2:
  field1: val1
  field2: val3

id3:
  field1: val4
  field2: val12

Drupal creates simple config with key example.entity. I'd expected it to create config entities as defined in schema file.
It would be real pain to manage those default config entities with 100 separate files instead of having everything in one yml file. Is this expected behaviour?
Answer: According to Configuration Storage in Drupal 8:

Configuration Entities must each be put into their own YAML files, and they should be generated by having the module write out its configuration (don't try writing them by hand).

So it sounds like what you're experiencing is indeed the expected behaviour, and for the time being at least, you'll need to separate each default entity into its own YAML file.
Comment: I can write a generator for my own use but I already feel sorry for anyone who'll have to manage those files in the future.
Answer: Little note to the yml code in the question.
In the drupal handbook looks the yml code for example/config/schema/example.schema.yml like this:
example.example.*:
  type: config_entity
  label: 'Example config'
  mapping:
    id:
      type: string
      label: 'ID'
    label:
      type: label
      label: 'Label'

In this case should the yml files, which are in the directory example/config/install, have the following names:

example.example.entity.id1.yml
example.example.entity.id2.yml
example.example.entity.id3.yml

And the code of the yml files should contain also ids:
id: 1
label: Some text

(I've had similar problems as @SiliconMind and needed some time to find the correct way to add the default configuration...).


How to interpret TraMineRs results of disstreedisplay and seqtreedisplay?

Question: I am not quite sure what the differences are between the outputs and results of disstreedisplay and seqtreedisplay. Maybe you could explain me the differences?
The TraMineR users guide and the otherwise detailed working paper about the WeightedCluster library do not explain so much about that. Here is my example R script:
library(TraMineR)
library(WeightedCluster)

data(mvad)
mvad.alphabet <- c("employment", "FE", "HE", "joblessness", "school", "training")
mvad.labels <- c("Employment", "Further Education", "Higher Education", "Joblessness",
"School", "Training")
mvad.scodes <- c("EM", "FE", "HE", "JL", "SC", "TR")
mvadseq <- seqdef(mvad[, 17:86], alphabet = mvad.alphabet, states = mvad.scodes,
labels = mvad.labels, weights = mvad$weight, xtstep = 6)

mvad.ham <- seqdist(mvadseq, method="HAM")

seqtree <- seqtree(mvadseq ~ gcse5eq + Grammar + funemp, data=mvad, diss=mvad.ham,
weight.permutation="diss")
seqtreedisplay(seqtree, type="d", border=NA)

disstree <- disstree(mvaddist ~ gcse5eq + Grammar + funemp, data = mvad, R = 10)
disstreedisplay(disstree, imagefunc=seqdplot, imagedata=mvadseq, border=NA,
withlegend=FALSE, axes=FALSE, ylab="")

You need to have installed GraphViz to see the graphs.
Answer: Sequence regression trees and dissimilarity based trees are fully presented in the following paper:
Studer, M., Ritschard, G., Gabadinho, A. & Müller, N.S. (2011), "Discrepancy Analysis of State Sequences", Sociological Methods and Research. Vol. 40(3), pp. 471-510.
Basically, seqtree and seqtreedisplay are shortcuts (helper functions) to disstree and disstreedisplay functions (specifying some defaults such as the plotting and printing function to use and so on). disstree is more general and can be used to analyse any kind of objects described by a distance matrix.
The difference in your output comes from the use of the weights. seqtree uses the sequences weights by default (those defined in seqdef). If you use disstree, you need to specify the weights explicitly to get the same result.
Thus, disstree must be:
disstree <- disstree(mvad.ham ~ gcse5eq + Grammar + funemp, data=mvad,
weights=mvad$weight, R=10, weight.permutation="diss")


In 2020 - are there any viable Linux block-level replication alternatives for DRBD?

Question: I'm researching how can we implement near-realtime replication from primary datacenter to a disaster recovery site. Data that would get replicated would be:

Images of KVM VMs
MySQL and PostgreSQL databases

For the sake of simplicity let's assume it's less than 10TB of data in total with average write speed of under 100MB/s, peaking at 1500MB/s and link between the primary and backup datacenter would have throughput of 10gbit/s.
Asynchronous replication is acceptable and desired - in case of bursty writes or short outage of the connectivity between both datacenters - we don't want to slow down local write speed and are willing to sacrifice the most recent portion of data that might be lost in case of catastrophic failure affecting the primary datacenter.
My understanding is that we can choose between:

proprietary SAN hardware that can come with replication feature and can provide iSCSI LUNs
DRBD that will likely need to be combined with DRBD proxy [ to make sure that temporary drop of available bandwidth or latency spike between both datacenters does not affect write performance at the source ]
Software-based solutions like http://schoebel.github.io/mars/, which - sadly - will take quite a while to be merged into mainline kernel in the best case scenario
For DBs - database-level replication is an option as well but - we'd like to carry occasional DR tests for which we want to switch all workloads between the datacenters. Failing back from the DR site to the main site would be quite cumbersome.

Are there any other solutions worth considering?
Thank you!
Comment: Software recommendations are off topic here - and you have already found the alternative (MARS).  I never found a suitable alternative to DRBD+drbd-proxy ($$) but you should look at ZFS streaming. There are also some hacks around LVM for block replication out there as well.
Comment: @davidgo - you linked to *this* question
Answer: For DBs and DB-aware & dependent applications their proprietary replication is always preferred over the "generic" block-level one due to many reasons, DB consistency is one of those. So use SQL Server Availability Groups (AGs) available with some limitations even with a Standard version of SQL Server since 2014 or 2015, use MS Exchange DAG, SAP HANA, AeroSpike replicas etc. I wouldn't do DRBD in 2020 due to it's rather poor I/O performance especially with an all-flash configurations, DRBD is clearly made for spinning disks and high latency non-RDMA networks back in early 2000s, and extremely poor protection against split brain issues. Virtual SAN technology you can find as a part of the major hypervisors is another good option to DB's built-in replication tech.
Comment: As a VSAN, OP might consider StarWind VSAN. Their Linux edition, might be helpful. Windows version still works great. https://www.starwindsoftware.com/starwind-virtual-san-goes-linux
Answer: You could consider geo-replicated SDS solutions like Gluster and Ceph, utilize ZFS, or LVM replication.
For KVM, qemu now has a CDC feature, and various solutions are being built towards streaming the changed blocks across a network link without replicating the entire underlying block device.
For any other software (you mentioned databases) it is really a better approach to use the native tools your database might provide. Many modern NoSQL databases are masterless and can simply run in multi-DC mode, with replicas pushed per DC or rack.
Comment: Both Ceph and Gluster are an overkill for OP's basic two-node scenario. ZFS is OK, but doing it inside a VM is kinda challenge...
Comment: My answer contains way more than just a brief mention of ceph and gluster.


Copy colored cells in another spreadsheet to current spreadsheet

Question: What I want to do is to copy the same range("F2: F403") in the worksheetB in the workbookB
to the same range("F2:F403") in worksheet A in ThisWorkBook if the cells in worksheetB
is colored in green(colorIndex=4).
Otherwise, no doing copying.
I am pretty new in VBA(not used for one year).
Any help would be highly appreciated!
Thanks!
    Option Explicit

    Sub fillgreen()

    Dim wb As Workbook: Set wb = ThisWorkbook
    Dim ws, ws1, ws2 As Worksheet
    Dim SUD_F As Range, S_Cell As Range, U_Cell As Range, Usage_F As Range
    Dim i As Variant

    Set ws1 = ThisWorkbook.Worksheets("WorksheetA")
    Set ws2 = Workbooks("WorkbookB.xlsx").Worksheets("WorksheetB")

    With ws1
        Set SUD_F = ThisWorkbook.Worksheets("WorksheetA").Range("F2: F403")
    End With

    With ws2
        Set Usage_F =_
        Workbooks("WorkbookB.xlsx").Worksheets("WorksheetB").Range("F2: F403")
    End With

    ' now fill the Usage_F green value to SUD_F

    For i = 2 To 403
        If Usage_F.Cells(i, "F").Value.Interior.ColorIndex = 4 Then
            SUD_F.Cells(i, "F").Value = Usage_F.Cells(i, "F").Value
        Else
            SUD_F.Cells(i, "F").Value = SUD_F.Cells(i, "F").Value

    End If
    Next i

    End Sub

Comment: Please try to *indent* code when posting  - non-indented code is more difficult (for us *and* you) to follow.  Your With blocks are not doing anything - you can just remove the With...End With
Comment: @TimWilliams I am so sorry for the miss. I would edit that right away, I indented with Python and C++, I did not touch vba too long..
Answer: Maybe more like this:
Sub fillgreen()

    Dim SUD_F As Range, Usage_F As Range
    Dim i As Long, v

    Set SUD_F = ThisWorkbook.Worksheets("WorksheetA").Range("F2:F403")
    Set Usage_F = Workbooks("WorkbookB.xlsx").Worksheets("WorksheetB").Range("F2:F403")

    For i = 1 To Usage_F.Cells.Count

        If Usage_F.Cells(i, "F").Interior.ColorIndex = 4 Then
            SUD_F.Cells(i, "F").Value = Usage_F.Cells(i, "F").Value
        Else
            SUD_F.Cells(i, "F").Value = SUD_F.Cells(i, "F").Value '??
        End If

    Next i

End Sub

Comment: If you use RGB then make sure to use `Interior.Color` and not `ColorIndex`
Comment: Thanks Tim! I would try that tomorrow( not available right now) and if this solved that I would mark it as answer. Just I wonder why i starts with 1? Maybe I can change that to For i = 2 to 403 if your i refers to row index as I planned to.Maybe that does not matter.
Comment: I assumed that `UsageF` was your actual data (excluding headers) and that you'd want to loop over all the rows in that data.   If Row 2 has headers then feel free to adjust the starting row accordingly.
Comment: Thanks so much! There was no error nor doing anything.. I am trying to see where has been wrong
Comment: Is your coloring because of Conditional Formatting?
Comment: I am not super sure, but I recorded Macro and see the green color is RGB(198, 224, 280), so I set this, and I tried to use ".copy" as what I tried was actually copy all the green cells to another worksheet and the range and index are the same. This should be doable. Unfortunately, I am still struggling.
Comment: If you put breakpoints on the lines in the `If` test do they get hit?  Select one of your green cells, then in the Immediate pane enter `? Selection.Interior.ColorIndex` and press Enter.  What is the result?
Answer: Many thanks to @Tim continuous help, and I know it is not easy to see the problem off hand. After searching for some other tutorial outside, I succeeded with the code below:
Option Explicit

Sub Color()

Dim Workbook As ThisWorkbook
Dim workksheet As Worksheet
Dim i As Variant
Dim S_range, U_range As Range
Dim rw As Range

Set S_range = ThisWorkbook.Worksheets("Journals with no use").Range("F2:F403")
Set U_range = ThisWorkbook.Worksheets("Use").Range("F2: F403")

For i = 2 To 403
    If U_range.Cells.Rows(i).Interior.Color = RGB(198, 224, 180) Then
        S_range.Cells.Rows(i).Value = U_range.Cells.Rows(i).Value
    End If
Next i

End Sub


Organic Groups - How to disable "Groups" Tab

Question: I enabled OG and now I have a tab that lists all "public" groups if you're not registered, and it'll show the groups you belong to if registered. What's the best way to get rid of the groups tab for Anonymous users? It can be visible to authenticated users.
Answer: I had a similar problem with OG Extras installed, the view and members tab would show even when a site visitor wasn't logged in, I wanted it hidden for non registered users or non-admin users.
To stop it showing I edited the view 'OG Extras group members (User)' made sure I had the Page, not the block of the view selected and changed 'Access:' for the 'tab menu' to Role | administrator, this means that when logged in as an administrator I can see the desired tabs but when logged out the tabs are hidden.
Answer: The quickest way I can think of doing it would be to use the Tab Tamer module. I've used it to do the exact same thing on a Drupal 6 site and it worked really well.
Comment: Didn't work for me in this instance, but tab tamer seems to be pretty good.
Answer: Also if you created the menu links by the modules views, you can restrict access to the menu link and the viewed page from the views module.
Answer: OG Invite People provides an "invite" for existing users as well as new users.
In 2.x it has an option to disable the OG group tab.
Usual use case is to make your own "manage members" tab beneath via views or panels.


Why is the output from getDefinition($type) different from getStorage($type)->getEntityType()?

Question: In a Controller, when calling: $this->entityTypeManager()->getStorage($type)->getEntityType(), I do not have the exact same return value as: $this->entityTypeManager()->getDefinition($type).
They both return the same class (in my tests, it was ContentEntityType), but the only difference is in the entity_keys definition. Here is a diff of var export highlighting the diff between the two calls:
--- a/fromStorage.txt
+++ b/fromStorage.txt
@@ -19,6 +19,7 @@ Drupal\Core\Entity\ContentEntityType::__set_state(array(
     'uuid' => 'uuid',
     'langcode' => 'langcode',
     'published' => 'status',
+    'test' => 'entity_key_value',
     'revision' => '',
     'bundle' => '',
     'default_langcode' => 'default_langcode',

The test entity key was added after the module was installed (a custom entity). Only the $this->entityTypeManager()->getDefinition($type) call returns this entity key. The remaining of the entity definition is 100% the same.
At first, I thought that an entity update was needed, but the entity update manager detects no update to apply. Clearing the caches did not help either. Why the inconsistency? Am I missing an update call somewhere?
Comment: The difference is that storage handlers are cached in memory the first time getStorage() is invoked for the entity type. Would be interesting to set a breakpoint to see when this is happening and why the definition is different then.
Comment: You're right, there is some sort of cache somewhere. I cannot track the issue anymore because I have reinstalled my website from scratch (due to an unrelated hard crash), and guess what? The diff is gone. So it seems it's something related to an "event" which is triggered on module install. Which event, though? :D That is the question.
Answer: After digging into the internals of the entity type / storage management, I am fairly confident that I have found the answer: $this->entityTypeManager()->getStorage($type)->getEntityType() uses the result of EntityManager::getActiveDefinition which loads a sort of cached representation of the entity type. This was introduced by https://www.drupal.org/project/drupal/issues/2554235 which added the concept of last installed definition, which is meant to mitigate problems during update processes.
The difference between codebase and database means that the entity may need an update, like the following:
$codefieldstoragedef = $this->entityTypeManager->getDefinition($this->entityType->id());
\Drupal::entityDefinitionUpdateManager()->updateEntityType($codefieldstoragedef);

As $this->entityTypeManager->getDefinition() returns the codebase representation, this will tell Drupal to update the database representation with it. After doing this (preferably in a hook update), the entity keys will match.

This answer is also meant to fix some entity definition mismatch as shown in the status report page, especially regarding base fields to update which are used as entity keys.


Javascript code not working properly(works for some time and crashes)

Question: I've made a javascript slideshow for text but it gets bugged after a couple of loops.
This is what it should be like(don't mind the cursor in gif):

This is what happens after a couple of loops:

The Javascript code:
var quote_array = [
    "Aš supratau, kad kuo daugiau dirbu,
tuo labiau man sekasi.",
    "Dirbdamas sau malonų darbą
pasieki tobuliausių rezultatų.",
    "Tikras darbas yra darbas
kurio tu nemėgsti."
    ];
var quoteName_array = [
    "-Tomas Džefersonas",
    "-Aristotelis",
    "-Bilas Watersonas"
    ];
var quote_i = Math.floor(Math.random()*quote_array.length);
var quote_elem;
var quoteName_elem;
var patikrinti
function quoteNext()
{
    quote_i = Math.floor(Math.random()*quote_array.length);
    if(patikrinti==quote_i)
    {
        quoteNext();
    }
    quote_elem.style.opacity = 0;
    quoteName_elem.style.opacity = 0;
    setTimeout("quoteSlide()",1100);
}
function quoteSlide()
{
    patikrinti = quote_i;
    quote_elem.innerHTML = quote_array[quote_i];
    quoteName_elem.innerHTML = quoteName_array[quote_i];
    quote_elem.style.opacity = 1;
    quoteName_elem.style.opacity = 1;
    setTimeout("quoteNext()",13900);
}

Comment: How do you start it? Looks like it runs a couple of times in parallel
Comment: I start it right after HTML part(div,blockquote and p elements) are loaded
...

...
Answer: I didn't see the recurion at first, but in quoteNext() you're (randomly) calling quoteNext() a second time - which will add another setTimeout("quoteSlide()",1100) so over time more and more "loops" are running in parallel, leading to total flickering in the end. Change your function to
function quoteNext() {
    quote_i = Math.floor(Math.random()*quote_array.length);
    if (patikrinti==quote_i) {
        quoteNext(); // try again
    } else { // but do not continue
        quote_elem.style.opacity = 0;
        quoteName_elem.style.opacity = 0;
        setTimeout(quoteSlide, 1100); // pass functions, not code strings
    }
}

Comment: Thank you, really love the way you explained everything, understood the problem,everything works fine now :)


Given nonzero vectors $x$ and $y$, does there exist an invertible matrix $A$ such that $Ax=y$?

Question:
Given any $x, y \in \mathbb{R}^n \setminus\{0_n\}$, does there exist an invertible matrix $A$ such that $Ax=y$?

I was examining the orbits of set $\mathbb{R^n}$ under the action of the group $\mbox{GL}_n(R)$ by left multiplication, i.e., $$O_x = \left\{ A x \mid A \in \mbox{GL}_n(R) \right\}$$ and $x\in \mathbb{R^n}$. Since $O_0=\{0\}$, I thought there is only one more orbit of nonzero vectors. This can be shown if my above question holds true.
Comment: if $|x| = |y|,$ then a reflection matrix $R$ will do. otherwise, a reflection followed by a scaling should work.
Comment: I think rotations, reflections, etc, are a distraction. This is just basic linear algebra, as in copper.hat's answer below, and it works for any field, not just for ${\mathbb R}$.
Comment: @abel can you give a matrix? Do you mean a rotation or reflection?
Comment: To expand upon @abel's answer, see https://en.wikipedia.org/wiki/Householder_transformation
Comment: reflection matrix $R = 2uu^T/(u^Tu) - I$ where $u$ is either
Comment: @abel can you explain a bit??
Comment: this is continuation of my 2nd comment. pick $u = x+y$ form the reflection matrix. there is another method that i found on page 65 of the text canonical matrix by turnbull and aitken. there you construct a elementary row matrix but you need to know which component of $x$ is not zero.
Answer: Here is a brute force approach to show existence.
Given a non-zero vector $v_1$ add vectors so that $v_1,...,v_n$ form a basis and let $V$ be the resulting matrix, that is
$V=\begin{bmatrix} v_1 & \cdots & v_n \end{bmatrix}$. Then $V e_1 = v$
($e_1$ is the vector $(1,0,\cdots,0)^T$). Note that $V$ is invertible.
So, given $x$, find $V_1$ such that $V_1 e_1 = x$, then $e_1 = V_1^{-1} x$.
Now, given $y$, find $V_2$ such that $V_2 e_1 = y$. then $V_2 V_1^{-1} x = y$, so letting $A = V_2 V_1^{-1}$ will do the trick.
Aside: If $\|v_1\| = 1$ above, the basis can be chosen to be orthonormal, and so the resulting $V$ will be orthogonal (unitary).
Hence we can find an orthogonal (unitary) $A$ such that ${ \|y\| \over \|x\| } Ax = y$.
Comment: what is $v$?? $V$ is the matrix with $v_1,v_2,..v_n$ in its columns??
Comment: $v$ is an arbitrary non-zero vector. I was just showing that you can find a $V$ such that $Ve_1 = v$.
Answer: I will make copper.hat's answer more concrete by constructing the matrices for the case $n = 5.$
First I will deal with the case the first component of both $x$ and $y$ is $1.$
The matrix $$Y = \left( \begin{array}{lllll} 1 & 0 & 0 & 0 & 0\cr y_2 & 1 & 0 & 0 & 0\cr y_3 & 0 & 1 & 0 & 0\cr y_4 & 0 & 0 & 1 & 0\cr y_5 & 0 & 0 & 0 & 1\end{array} \right)$$
and its inverse $$Y^{-1} =\left( \begin{array}{lllll} 1 & 0 & 0 & 0 & 0\cr -y_2 & 1 & 0 & 0 & 0\cr -y_3 & 0 & 1 & 0 & 0\cr -y_4 & 0 & 0 & 1 & 0\cr -y_5 & 0 & 0 & 0 & 1\end{array} \right)$$ have the property $Ye_1 = y$ and $Y^{-1}y = e_1.$ In the same way form the matrices $X$ and its inverse $X^{-1}.$
Now, the matrix $YX^{-1}$ will send $x$ to $y$ for $YX^{-1}x = Ye_1 = y.$
If the first components of $y$ or $x$ are not $1$ use permutation matrices and scaling to make the first component of both to be $1.$