php called python script

Question: I've got a problem with a python script. The script itself generates a string and writes it at the end to a file. This works well when I call the python script directly.
But as soon as I call the python script from PHP with exec(), it can't write to the file anymore.
In python I simply use:
try:
    FILE = open(filename,"w")
    FILE.write(mystring)
except IOError:
    print 'cannot open', filename

and PHP calls the python script like this:
$command = 'python myscript.py input1 input2 > /dev/null &';
exec($command, $stdout, $error);

Does anyone know what to do solve the problem?
Comment: Maybe the process running your PHP script has different permissions than your local user?
Comment: Are the permissions for the PHP process set properly?
Comment: Have you tried setting the permissions on your destination file so that it is open and world writeable?
Comment: do you close your file after writing?. Use with context manager
Comment: are you sure the command is running?  consider the `system` or `passthru` functions that allow you to get return code or program output.
Comment: @larsmans: thanks for the hint. it has been the read/write permission. i set the file to 777 and now its working properly.
Answer: it can't write to the file
What error message are you getting?
I notice that you are reporting an error in the Python script using a straight print to stdout, and redirecting stdout to /dev/null when running. The stderror string is a useful part of an IOError exception.
You could change your except to something like this:
except IOError, err:
    sys.stderr.write("Could not open "+ err.filename + ": " + err.strerror + "\n")

or you could use stdout and redirect the output to a real file instead of /dev/null - at least until you have nailed the problem.
Answer: Is filename a relative or absolute path? I would recommend using absolute paths so your script will work however it's called - for example "/home/matt/scripts/python/test.txt" is an absolute path.
This is a common error with scripts called by other scripts, or called by system events or cronjobs, etc.
Hope that helps
Comment: i tried it with relative and absolute path. both did not work. :(
Answer: There is a system-function which you can find in PHP manual: http://php.net/manual/en/function.system.php
$var = system('python sample.py myargs', $ref);

php called python script


"Array index is less than one" WINBUGS Error

Question: for (i in 1:160) {
    situps[i] ~ dnorm(mu[i],prec[gender[i]+1]);
    mu[i] <- b0+b1[gender[i]]+b2[health[i]]+b1b2[health[i],gender[i]];
}
b0 ~ dnorm(0,.001);
for (i in 1:4) {
    b2[i] ~ dnorm(0,.001);
}
for (j in 1:2) {
    b1[j] ~ dnorm(0,.001);
    prec[j] <- pow(sigma[j],-2);
    sigma[j] ~ dunif(0,10);
}
for (i in 1:4) {
    for (j in 1:2) {
        b1b2[i,j] ~ dnorm(0,.001);
    }
}

I'm not sure why this gives me the error "array index is less than one" because I clearly have all of my arrays starting at 1. Any ideas?
Answer: How is gender coded? Your use of prec[gender[i]+1] looks problematic. Try something like
situps[i]~dnorm(mu[i],tau[i])
tau[i] <- prec[gender[i]] # or some similar function
mu[i]<-b0+b1[gender[i]]+b2[health[i]]+b1b2[health[i],gender[i]]

NB you don't need the semi-colons at the end of each line
Comment: Indexing with `gender[i] + 1` doesn't seem as problematic as indexing with `gender[i]` and `health[i]` in this case.


Sharing photo using facebook sdk 4.2.0

Question: ShareDialog shareDialog = new ShareDialog(this);

shareDialog.registerCallback(callbackManager, new FacebookCallback<Sharer.Result>() {
            @Override
            public void onSuccess(Sharer.Result result) {
                Toast.makeText(SharePage.this, "ok", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancel() {
            }

            @Override
            public void onError(FacebookException error) {
                Toast.makeText(SharePage.this, error.getMessage(), Toast.LENGTH_LONG).show();
            }
        });

SharePhoto photo = new SharePhoto.Builder().setBitmap(bm).setCaption(description).build();
SharePhotoContent content = new SharePhotoContent.Builder().addPhoto(photo).build();
shareDialog.show(content);

The below code is run.
If i have facebook app in the mobile, it's share the photo successful.
But if i delete the facebook app, the callbackManager return the error "Unable to show the provided content via the web or the installed version of the Facebook app. Some dialogs are only supported starting API 14."
Comment: Hi Frankie, have you fixed this issue? I have the same issue on some devices and still not fixed. Can you help?
Answer: You can only show this dialog if you have native facebook app installed in your device. Try the same code in a device in which facebook app is installed it will work.
If you want to make a custom dialog you need to
 -Build a custom interface that posts to the Graph API endpoint /me/feed
 -Implement Facebook Login in your app
 -Request the publish_actions permission when people log into your app

Here's the code for posting a link to Facebook from your own interface:
  ShareApi.share(content, null);

Let me know if you need any assistance.
Mark this answer accepted if this helps.
Comment: In the past, we can use WebDialog to share image without native facebook app. After facebook sdk 4.0, we can't do it?
Comment: U can still use web dialog but that is for story posting.. in which link,caption,name,description parameters are there...If you want to use latest method available.follow my instructions above...
Please mark this answer accepted if this helped.. :) and let me know if still u got a prob.
Comment: In new version sdk, Session is not available. How can i use web dialog?
Comment: You can use LoginManager to use a custom buttton for login or use a default login button of Facebook to maintain session.
If still u does not get me.use any old facebook sdk .Pick from any of your old project and use session class..Please mark this answer up :)
Comment: @Hardeep Can you share small code for here. How to create content.

Sharing photo using facebook sdk 4.2.0


Can I use ext3 as a shared fs if I add a lock manager?

Question: I need a cluster filesystem for an iSCSI device. The problem is that the servers to which it is connected generate datafiles which must be read by every other servers. Except for the writing and deleting of such files, I do not need a full locking scheme like in OCFS2 or GFS2.
So, can I use a distributed lock manager (DLM) on top of an ext3 filesystem or must I use only specialized filesystem ?
Comment: I will try GFS. Just had to ask that question to be sure that it was (or not) a solution.
Comment: This is a strange question. DLM is part of GFS2. Also GFS2 is not a locking scheme, it's a cluster filesystem that uses a locking scheme to share data. And you want to share data.
Comment: Well, I know, but for example OCFS2 use a somewhat restrictive model of distributed lock : no lock, protected read (only one host can read at a time) and exclusive (only one host can access the file). What I need is the ability to read a file, even if it is accessed by another host.
Comment: I don't know how OCFS2 works, but GFS certainly allows concurrent access to the same file. The lock is not per file, it's per FS block. Also the locking is not supposed to be seen by the layers above the filesystem, it's used to handle consistency.
Answer: NO. The main reason is that the filesystem cache is not cluster aware and is not coherent, so you end up mangling your data.
Try mounting the ext3 FS in two boxes, create a file in one box and see if it appears in the other...
Answer: A filesystem must be cluster aware, meaning that it has to know to look for the lock manager (or the nodes need to know to look at the quorum disk). You can't just strap on an DLM and have it work. That would be neat, though. Sorry!
Comment: Happy 10k-day Matt ;)
Comment: Thanks chopper! I'm not entirely sure what happened, but horray!


Problema enviar valor do input (que é atualizado num While) para outra página via POST

Question: Tenho um laço de repetição while que cria campos de acordo com o número de municípios do cliente. Preciso passar a variável codmunicipio via método POST para ser inserir no Banco de Dados em outra página.
No caso se tiver somente um município o POST funciona mas quando tem mais de um município ele continua passando somente uma variável.
Segue os trechos do código:
<?php

   while($dado_ipl3 = mysqli_fetch_array($qry_ipl3)) {

     $nome_municipio = $dado_ipl3['CIDADE'];
     $codmunicipio = $dado_ipl3['COD_CIDADE'];
?>

         IPL3 Distribuição do quantitativo total de acessos fisícos em serviço por tipo de usuário (mensal)

          Nome Município

              <input type="text" name="nome_municipio" id="nome_municipio" class="form-control" value="<?php echo"$nome_municipio" ?>"   maxlength="18" size="18" title="Nome Município">

      Codigo Municipio

          <input type="text" name="codmunicipio[]" id="codmunicipio" class="form-control numero_livre" value="<?php echo $codmunicipio; ?>"  maxlength="7" size="7">

        Acesso físico P.F.

            <input type="text" name="IPL3_valor_F" id="IPL3_valor_F" class="form-control numero" value="0"   maxlength="18" size="18" title="Quantitativo de Acesso físico em serviço pelo tipo da Pessoa Física">

        Acesso físico P.J.

            <input type="text" name="IPL3_valor_J" id="IPL3_valor_J" class="form-control numero" value="0"  maxlength="18" size="18" title="Quantitativo de Acesso físico em serviço pelo tipo da Pessoa Jurídica">

<?php

   }

?>

pagina que recebe:
    $codmunicipio = $_POST['codmunicipio'];
    $valor_ipl3_f = $_POST['IPL3_valor_F'];
    $valor_ipl3_j = $_POST['IPL3_valor_J'];

   $sql3 = "INSERT INTO financeiro_sici_anatel_ipl3 (ano, mes,
    fistel,codmunicipio, IPL3_valor_F, IPL3_valor_J)

    VALUES ('$ano_upload', '$mes_uplooad', '$fistel','$codmunicipio',
     '$valor_ipl3_f', '$valor_ipl3_j')";

      $resultado3 = $banco->pesquisarBD($sql3);

No caso quero passar todos esses campos atualizados:
$codmunicipio', '$valor_ipl3_f', '$valor_ipl3_j

Answer: Tente utilizar:
<input type="text" name="nome_municipio[]" />

E na página onde você receberá o $_POST faça outro loop de repetição para pegar os valores
foreach ($_POST['nome_municipio'] as $pos => $valor) {
    $nome_municipo = $valor;
}

Comment: Continua pegando apenas um valor.
Comment: Você tem que renomear todos os inputs como array `nome_municipio[]`, quando chegar na outra página, use um `print_r($_POST)` para você ver os valores.
Comment: eu to tentando passar assim:

foreach ([$_POST['codmunicipio'], $_POST['IPL3_valor_F'], $_POST['IPL3_valor_J']] as list ($value1, $value2, $value3)) {

        $codmunicipio = $value1;, $valor_ipl3_f = $value2;, $valor_ipl3_j = $value3;
Comment: Pois eu tenho que passar o ipl3_valor_f e ipl3_valor_j para CADA municipio
Answer:
Quando há mais de um município, evidentemente haverá mais de um código de município, portanto, já que seu formulário contem colchetes [ ] no name do input Codigo Municipio, que significa que ele é enviado na forma de vetor ou array para o receptor, é necessário fazer uso de foreach () para percorrer esse array.
Se o seu formulário está correto, os valores dos inputs IPL3_valor_F e IPL3_valor_J  estão setados sempre com valor 0, dessa forma não há necessidade de resgatar esses valores na página insert. Basta colocar no VALUES da declaração insert o valor 0
Outro detalhe é que não há qualquer indicio que Nome Município faz parte da declaração insert portanto desnecessário também recuperar esse valor.

No mais, se eu não estiver enganado sobre o acima exposto nos itens 2 e 3, a pagina que recebe deve ficar assim:
if (isset($_POST['codmunicipio'])){

    $codmunicipio = $_POST['codmunicipio'];
    //desnecessários
    //$valor_ipl3_f = $_POST['IPL3_valor_F'];
    //$valor_ipl3_j = $_POST['IPL3_valor_J'];
    //A cada iteração, a variável "$value" automaticamente recebe o valor de cada item do array,
    foreach ($codmunicipio as $value) {
         $sql3 = "INSERT INTO financeiro_sici_anatel_ipl3 (ano, mes,
            fistel,codmunicipio, IPL3_valor_F, IPL3_valor_J)
            VALUES ('$ano_upload', '$mes_uplooad', '$fistel','$value',
             0, 0)";
    }

}

No caso de passar todos esses campos $codmunicipio', '$valor_ipl3_f', '$valor_ipl3_j atualizados:
if (isset($_POST['codmunicipio'])){

    $codmunicipio = $_POST['codmunicipio'];
    $valor_ipl3_f = $_POST['IPL3_valor_F'];
    $valor_ipl3_j = $_POST['IPL3_valor_J'];

    for($i = 0; $i<count($codmunicipio); $i++) {

       $sql3 = "INSERT INTO financeiro_sici_anatel_ipl3 (ano, mes,
            fistel,codmunicipio, IPL3_valor_F, IPL3_valor_J)
            VALUES ('$ano_upload', '$mes_uplooad', '$fistel','$codmunicipio[$i]',
             '$valor_ipl3_f[$i]', '$valor_ipl3_j[$i]')";
    }

}

sendo que nos inputs IPL3_valor_F e IPL3_valor_J devem conter colchetes no final dos respectivos name


Página em wordpress está sendo redirecionada para o site "oficial do wordpress"

Question: Realizei o backup de um site em wordpress para rodar localmente e realizar alguns testes, porém toda vez que clico em visitar o site no menu superior sou redirecionado para o site oficial (live).
Já realizei o update da coluna option_value na tabela wp_options, e até defini as constantes no wp-config.
define("WP_SITEURL","http://meubackup.dev");
define("WP_HOME","http://meubackup.dev");

E ainda continuo sendo redirecionado para o site em produção.
Comment: Já tentou mudar a URL do site nas configurações do wordpress?
Answer: No painel do Wordpress vá até a aba Configurações -> Geral e insira o link correto


How can I extract or recreate audio for one or more instrumental/vocal parts from a recording?

Question: (In the spirit of this meta-post, and so, in response to this question…)
What approaches can be taken to extract or recreate audio for one or more individual parts from a recording with several layered parts?
Answer: A number of approaches can be taken to reaching the desired goal, of isolating the audio for individual parts, within multitracked recordings. Different approaches may be appropriate for different styles of music.
If an audio recording only has one instrumental/vocal layer, at any particular point (or only one per stereo channel) it is easy to extract the audio for this part, as it will be the same as the original recording! This is the most effective way to take samples from recordings; it seems obvious, but use a bit of the track that only has the instruments/vocals you want, with no other instruments. (A good example is the sample of Suzanne Vega's Tom's Diner used for this remix.) But, of course, the audio you want may already be part of a multi-layered audio texture. And, once multiple instrumental/vocal tracks have been mixed down to two stereo channels, isolating one individual part becomes far more problematic. In this case, three main approaches will be useful:

It is possible to use filters to remove certain frequencies from the audio. This answer to this question addresses this approach. This will be most effective if the audio you want to extract is largely in a different band of frequencies to the other parts. (It should be reasonably easy to extract the audio for the tuba part from a tuba and flute duet recording!) However, the range of frequencies in the audio of any one instrumental/vocal part are often wider than one would expect (once transients, overtones and other resonance are taken into account, for instance). Usually it is only possible to boost some instrumental/vocal parts and cut others; it is difficult to completely isolate parts from a mixed recording. In fact, there are various types of software for doing this. This question, and it's answers, discuss cutting the frequencies of the guitar part in a recording (okay, it's kind of the opposite of isolating a track, but the same principal!)
It's possible the audio you want to extract from a recording is already a sample from elsewhere. This is most likely if the audio is part of a recording in a genre that tends to use sampling (for example, Hip-Hop, but now used in a wide variety of popular music.) There is no exact way to find out if the part you want within an audio recording is a sample, but there will be plenty of clues: if the audio sounds significantly different in style to the other audio layers (eg. "orchestral-sounding" music within a rap song); if the section of audio returns multiple times within the song/piece sounding exactly the same. But these are only clues, and may not be indicative of a sample, after all: the audio may have been recorded for the song/piece in question, even if it seems to be different in style; it is common to repeat small sections of audio, recorded in the studio, in a song/piece - this is effectively the same as creating your own sample. There are other ways to find out if a recording uses sampled audio from elsewhere, though. Websites such as www.whosampled.com have extensive lists of sources of samples used in recordings; the Wikipedia entries for songs often have information about samples used, too. If the audio you want to isolate from a recording is a sample from another recording, you can simply seek out the original recording to find the source of the sample, and so the individual audio part.
If neither of the approaches above works, you can recreate the audio yourself (yes, this is a much harder approach!) Listen to the audio within the recording, that you wish to isolate, and work out what notes it uses. This process is called transcription. There are various types of software available to aid this process, for instance Transcribe! Once you have worked out the notes in a section of an audio layer, you can try to recreate this audio as an individual audio recording, either with live instrument(s) or sampled instruments. Of course, it may not be possible to fully recreate the tone, inflexion and other characteristics (eg. applied effects) of the original audio. As I say, this is by far the most difficult way to get the audio part you want from a recording, but it  is still likely to be easier than getting in touch with the artist, band or record company and being allowed access to the original multitrack recordings!


Plot variant abundance vs. time (e,g, of mutant strains) in python

Question: Given [absolute] numbers for each of a number of variants over time, I would like to produce a plot like the following:

Is there a function for this in Python (preferably, but not necesarily, in matplotlib)? In general, do these sort of plots have a name? I had a hard time googling it even though Iv'e seen them many times in the past.
Answer: This type of plot is called a "time stack plot" matplotlib has a built in function for building time stack plots. The syntax is:
matplotlib.pyplot.stackplot(x, y1, y2, ..., yn, colors=None, ...)

In your case x would be time (e.g. in months), y1,...,yn would be the abundance of each strain, and colors denotes a color map for y1,...,yn. (There are other optional arguments as well.) Here is an example of use:
import matplotlib.pyplot as plt

days = [1,2,3,4,5]

sleep = [6,7,5,8,6]
eat =   [2,2,1,2,1]
work =  [5,7,10,8,6]
exercise=  [3,3,0,1,3]

plt.plot([],[],color='green', label='sleep', linewidth=3)
plt.plot([],[],color='blue', label='eat', linewidth=3)
plt.plot([],[],color='red', label='work', linewidth=3)
plt.plot([],[],color='black', label='play', linewidth=3)

plt.stackplot(days, sleep, eat, work, exercise, colors=['green','blue','red','black'])

plt.xlabel('days')
plt.ylabel('activities')
plt.title('5 DAY ROUTINE')
plt.legend()
plt.show()

Which produces this plot:

See this page for more info: https://www.educative.io/edpresso/how-to-create-a-stack-plot-using-matplotlib
Answer: Density Plot from seaborn package seems to be your case
import seaborn as sns
sns.kdeplot(...)

Stacked Chart from pygal
import pygal
pygal.StackedLine(...)

StackPlot from matplotlib
import matplotlib.pyplot as plt
plt.stackplot(...)


JavaScript Date object with timezone error on Firefox browser

Question: I need to create javascript object with timezone CST/CDT, below line of code is working fine in chrome but not on firefox
new Date("2020-06-06 05:37:34.0" + ' CST/CDT');

Chrome result:
Sat Jun 06 2020 15:37:34 GMT+0500 (Pakistan Standard Time)

Firefox result:
Invalid Date

need suggestions to fix it.
Comment: Does this answer your question? [What are valid Date Time Strings in JavaScript?](https://stackoverflow.com/questions/51715259/what-are-valid-date-time-strings-in-javascript)
Answer: Always try to use UTC dates, meaning storing and performing calculations on Dates as UTC.
If you want to create a Date object specific to the timezone, do the below, I have shown how it can be converted back to UTC/local time zone:
const date = new Date('2010-05-11T10:11:00-0500');//CDT time
console.log(date.toString()); //date as per the current timezone of the machine this code is executed => "Tue May 11 2010 20:41:00 GMT+0530 (India Standard Time)"
console.log(date.toISOString());//converts the Date as UTC based ISO date string => "2010-05-11T15:11:00.000Z"

Comment: but the result is different when creat date object with "CST/CDT"


Habilitar campo quando radio está selecionado

Question: Eu estou aprendendo javascript, então estava testando fazer um radio que, quando selecionado, habilita um text area, e quando não selecionado, desabilita ele.
Porém o que eu estava fazendo não funcionou e eu não entendi o motivo. Dessa forma gostaria de ajuda para entender isso. O trecho do codigo que eu implementei está abaixo.
<form action="logs-sistema.php" class="form-inline">

    <input type="radio" name="optionsRadiosInline" id="optionsRadiosInline1"
      value="option1" >Último semestre

     <input type="radio" name="optionsRadiosInline" id="optionsRadiosInline2"
       value="option2">Último mês

     <input type="radio" name="optionsRadiosInline" id="optionsRadiosInline3"
       value="option3" checked>Última semana

      <input type="radio" name="optionsRadiosInline" id="radio4"
      onClick="habilitacao()" value="option4" >Entre

       <input type="date" class="form-control" id="dataInicial" placeholder="Data inicial" disabled>

        <input type="date" class="form-control" id="dataFinal" placeholder="Data final" disabled>

      <button type="submit" class="btn btn-primary">Pesquisar</button>
 </form>

Answer: Pode fazer isso usando Jquery:

$(document).ready(function() {
  $("input[name='optionsRadiosInline[]'").on('click', function() {
    if ($("#radio_1").prop("checked", true)) {
      $("#dataInicial,#dataFinal").prop("disabled", false);
    } else {
      $("#dataInicial,#dataFinal").prop("disabled", true);
    }
  });
});

  <input type="radio" name="optionsRadiosInline[]" id="optionsRadiosInline1" value="option1">Último semestre

  <input type="radio" name="optionsRadiosInline[]" id="optionsRadiosInline2" value="option2">Último mês

  <input type="radio" name="optionsRadiosInline[]" id="optionsRadiosInline3" value="option3" checked>Última semana

  <input type="radio" name="optionsRadiosInline[]" id="radio4" value="option4">Entre

  <input type="date" class="form-control" id="dataInicial" placeholder="Data inicial" disabled>

  <input type="date" class="form-control" id="dataFinal" placeholder="Data final" disabled>

<button type="submit" class="btn btn-primary">Pesquisar</button>
Answer: Bom dia, amigo.
A sua implementação está correta. Entretanto, ficou faltando adicionar o evento onClick nos outros radio button(optionsRadiosInline1, optionsRadiosInline2, optionsRadiosInline3).

form action="logs-sistema.php" class="form-inline">

    <input type="radio" onClick="habilitacao()" name="optionsRadiosInline" id="optionsRadiosInline1"
      value="option1" >Último semestre

     <input type="radio" onClick="habilitacao()" name="optionsRadiosInline" id="optionsRadiosInline2"
       value="option2">Último mês

     <input type="radio" name="optionsRadiosInline" id="optionsRadiosInline3"
       value="option3" onClick="habilitacao()" checked>Última semana

      <input type="radio" name="optionsRadiosInline" id="radio4"
      onClick="habilitacao()" value="option4" >Entre

       <input type="date" class="form-control" id="dataInicial" placeholder="Data inicial" disabled>

        <input type="date" class="form-control" id="dataFinal" placeholder="Data final" disabled>

      <button type="submit" class="btn btn-primary">Pesquisar</button>
 </form>


Não posso imprimir objetos usando template string?

Question: Por que template string não imprime objetos corretamente? Tenho o seguinte código de teste:
const obj = { a: 1, b: 2, c: 3,}
console.log(`Novo Obj ${obj}`)

e o resultado no console sai como:
Novo Obj [object Object]

não entendo, por que se eu peço pra imprimir sem a template, console.log('Novo Obj ', obj) ele imprime certo
Novo Obj  { a: 1, b: 2, c: 3 }

Não posso imprimir objetos usando a template?
Comment: Você provavelmente está se referindo ao Visual Studio Code (ou apenas VS Code) e não Visual Code Studio. Se sim, ele não é só pra JavaScript, tem suporte pra diversas linguagens, incluindo o Java. A segunda pergunta é completamente diferente da primeira, a faça em uma outra pergunta
Answer: Quando você faz console.log('Novo Obj ', obj), está passando o objeto como um dos argumentos de console.log (a vírgula separa os argumentos, então a string 'Novo Obj' é o primeiro argumento, e o objeto é o segundo).
Ou seja, obj é tratado "isoladamente" e impresso conforme a implementação - ou seja, varia conforme o ambiente: testando no Chrome e no Node, e o resultado foi { a: 1, b: 2, c: 3 }, no Firefox foi Object { a: 1, b: 2, c: 3 }, e no snippet do site, o resultado é:
{
  "a": 1,
  "b": 2,
  "c": 3
}

Rode e veja a diferença (aperte F12 e compare a saída do snippet abaixo com o console do seu browser):

const obj = { a: 1, b: 2, c: 3 };
console.log(obj);

Repare que no caso acima, há aspas em volta de a, b e c, e há quebras de linha entre eles (no caso do Chrome e Firefox, obtive o resultado sem as aspas e tudo em uma única linha). O fato é que o resultado de console.log varia conforme a implementação, mas em linhas gerais, "todas" imprimem os atributos e valores do objeto.

Já quando você coloca o objeto dentro de uma template string, internamente é chamado o seu método toString. Mas como você não definiu este método no seu objeto, ele usa o método herdado de Object, que sempre retorna algo como "[object type]" - sendo que type será o tipo do mesmo, que no seu caso é Object.
Sendo assim, uma forma de resolver é definir o método toString no seu objeto:

const obj = { a: 1, b: 2, c: 3,
    toString: function() {
        return `a=${this.a}, b=${this.b}, c=${this.c}`;
    }
};
console.log(`Novo Obj ${obj}`); // Novo Obj a=1, b=2, c=3

Claro que se quiser, pode usar JSON.stringify (que costuma ser uma maneira rápida, fácil e por isso muito usada para este propósito):

const obj = { a: 1, b: 2, c: 3,
    toString: function() {
        return JSON.stringify(this);
    }
};
console.log(`Novo Obj ${obj}`); // Novo Obj {"a":1,"b":2,"c":3}
// ou use JSON.stringify diretamente
console.log(`Novo Obj ${JSON.stringify(obj)}`); // Novo Obj {"a":1,"b":2,"c":3}

Um porém com JSON.stringify é quando você tem referências circulares:

let a = { x: 1 };
let b = { y: 2, z: a }; // "b" tem referência para "a"
a['z'] = b; // "a" tem referência para "b"

console.log(JSON.stringify(a)); // erro

Aí você teria que usar algo assim para resolver. Mas aí eu acho mais fácil sobrescrever toString e colocar os campos que você quer.
Answer: Usando o template literal funciona um pouco diferente, nesse caso precisa serializar o objeto usando por exemplo stringify, ou acessar as propriedades:

const obj = { a: 1, b: 2, c: 3}

console.log(`Novo obj.a ${obj.a}`);

console.log(`Novo obj completo ${JSON.stringify(obj)}`)


Check if file already exist in the same path

Question: I want to check if a specific file already exist in the same folder.
If it doesn't exist then create a new file and type in certain thing.
for example.  if filePath = test.txt and test.txt doesn't exist.
Create a new file name test.txt and put 12345 in the first line of the file.
Currently my method wont even run this if statement despite the condition is met. (test.txt does not exist)
    PrintWriter output;
    File file = new File(filePath);
    if(!file.isFile()){
        try {
            output = new PrintWriter(new FileWriter(filePath));
        } catch (IOException ex) {
            throw new PersistenceException("Error!", ex);
        }
        output.print("12345");
        output.flush();
        output.close();
    }

Comment: You can use [exists()](https://docs.oracle.com/javase/7/docs/api/java/io/File.html#exists()) available to `File` objects.
Comment: And what if it does exist? And what if it exists but doesn't have the 12345?
Answer: You can check whether a file exist or not by creating a File object and using exist method. File objects are different in java compared to C, when you create a File object you do not necessarily create a physical file.
File file = new File(pathString);
if (file.exists())
{
    //  File already exists
}
else
{
    //  You can create your new file
}

Answer: I think you could use this condition in your if:
Files.exists(Paths.get(file))

You can decide to use the specification NOFOLLOW_LINKS in order to avoid to follow symbolic link.
This will help you to check if the file exists or not.
I hope this could help you.


Prove that $(\cot A+\cot B)(\cot B+\cot C)(\cot A+\cot C)=\csc A\csc B\csc C$

Question: I was trying to find the value of $(\cot A+\cot B)(\cot B+\cot C)(\cot A+\cot C)$, given that $A+B+C=\pi$.
I tried using the identity $\cot A+\cot B+\cot C=-\cot A\cot B\cot C$ (It can be easily derived), if $A+B+C=\pi$. But it doesn't help much, and I am stuck now. I know the answer should be $cosecAcosecBcosecC$(this I verified by simply substituting angles and checking which combination of T-ratios gives the same answer). Please help.
Thanks in advance!!
Answer: HINT:
$$\cot A+\cot B=\dfrac{\sin(B+A)}{\sin A\sin B}=\dfrac{\sin(\pi-C)}{\sin A\sin B}=?$$
Comment: Thanks a lot @labbhattacharjee.......i should have converted to sine-cosine format.....I cannot accept the answer for another 9 minutes, I'll do it once the warning thing goes
Answer: Notice, in $\triangle ABC$, $A+B+C=\pi=180^\circ$
Now, we have $$LHS=(\cot A+\cot B)(\cot B+\cot C)(\cot C+\cot A)$$
$$=\left(\frac{\cos A}{\sin A}+\frac{\cos B}{\sin B}\right)\left(\frac{\cos B}{\sin B}+\frac{\cos C}{\sin C}\right)\left(\frac{\cos C}{\sin C}+\frac{\cos A}{\sin A}\right)$$
$$=\left(\frac{\sin A\cos B+\cos A\sin B}{\sin A\sin B}\right)\left(\frac{\sin B\cos C+\cos B\sin C}{\sin B\sin C}\right)\left(\frac{\sin C\cos A+\cos C\sin A}{\sin C\sin A}\right)$$
$$=\left(\frac{\sin(A+B)}{\sin A\sin B}\right)\left(\frac{\sin(B+C)}{\sin B\sin C}\right)\left(\frac{\sin(C+A)}{\sin C\sin A}\right)$$
$$=\left(\frac{\sin(180^\circ-C)}{\sin A\sin B}\right)\left(\frac{\sin(180^\circ-A)}{\sin B\sin C}\right)\left(\frac{\sin(180^\circ-B)}{\sin C\sin A}\right)$$
$$=\left(\frac{\sin C}{\sin A\sin B}\right)\left(\frac{\sin A}{\sin B\sin C}\right)\left(\frac{\sin B}{\sin C\sin A}\right)$$ $$=\frac{1}{\sin A\sin B\sin C}$$ $$=cosec A cosec B cesec C=RHS$$
Comment: thanks a lot@HarishChandraRajpoot.....but I already accepted @labbhattacharjee's answer(they are the same though)..upvote though


Concatenar dois arquivos que possuem mesmo nome NodeJS

Question: basicamente eu preciso concatenar dois arquivos (o conteúdo) que possuem o mesmo nome e possuem formato MDX, em um novo arquivo. Atualmente estou utilizando o concat-files mas estou fazendo isso manualmente, ou seja, arquivo por arquivo. Os arquivos estão localizados em pastas diferentes, exemplo:
Arquivo 1: node_modules/meumodulo/docs/doc1.md
Arquivo 2: docs/half/doc1.md
Então, com esse módulo concat-files, eu gero um terceiro arquivo que é o produto dos arquivos 1 e 2 e ele vai pra outra pasta.
Minha ideia é deixar isso de forma automática, para ele varrer a pasta node_modules/meumodulo/docs/ e docs/half/ e concatenar os arquivos que possuem o mesmo nome, mas estou sem ideia de como fazer isso. Se puderem dar uma força! Obrigado!
Answer: Esta é uma solução que não utiliza o concat-files.
Para esta implementação estou utilizando exclusivamente o módulo fs, disponibilizado no nodejs.
Conforme a sua necessidade, você deseja "concatenar" (unir) dois arquivos que possuem o mesmo nome, porém estão em diretórios diferentes, então inicialmente eu declarei duas variáveis patha e pathb que são os diretórios que desejamos "procurar" por arquivos com o mesmo nome.
Também declarei uma variável pathdestino que é o diretório em que serão armazenados os arquivos que são o resultado da concatenação dos arquivos.
Para auxiliar nesta tarefa utilizei a função readdirSync que serve para listar os nomes dos arquivos que pertecem a um diretório. O sufixo Sync no nome do método (readFileSync) significa que estou utilizando a implementação síncrona deste método. Esta função vai retornar uma lista que contém os nomes dos arquivos.
Com a função writeFileSync ela vai escrever em um certo diretório o conteúdo do arquivo (aqui é o que deseja fazer que é concatenar o conteúdo dos arquivos que possuem o mesmo nome). Esta função vai apenas criar um novo arquivo no sistema de arquivos do sistema operacional. Você deve passar apenas o nome do diretório que deseja criar.
Com a função readFileSync serve apenas para ler o conteúdo do arquivo.
Nesta solução eu criei uma função auxiliar lerConteudoDiretorio e escreverConteudoArquivo que manipula as funções descritas acima caso aconteça algum erro.
No foreach e que eu comparo os nomes dos arquivos que estão no diretório a com os nomes dos arquivos que estão no diretório b caso eles sejam iguais então eu concateno o seu conteúdo separados por uma quebra de linha.
Esta lógica está descrita neste trecho de código:
if (filea === fileb) {
        const a = fs.readFileSync(patha + `/${filea}`).toString();
        const b = fs.readFileSync(pathb + `/${fileb}`).toString();
        escreverConteudoArquivo(pathdestino + `${filea}`, `${a}\n${b}\n`)
}

A solução completa é a seguinte:
const fs = require('fs');
const patha = '/caminho/diretorio/a';
const pathb = '/caminho/diretorio/b';
const pathdestino = '/caminho/diretorio/destino/';

const lerConteudoDiretorio = (diretorio) => {
    try {
        return fs.readdirSync(diretorio);
    } catch (err) {
        console.log(`Não foi possível ler o conteúdo do diretório '${diretorio}'. Detalhe: ${err}`)
    }
};

const escreverConteudoArquivo = (diretoriodestino, conteudo) => {
    try {
        fs.writeFileSync(diretoriodestino, conteudo);
        console.log(`Arquivo ${diretoriodestino} escrito com sucesso`)
    } catch (err) {
        console.log(`Não foi possível escrever o conteúdo do arquivo no diretório '${diretorio}'. Detalhe: ${err}`)
    }
}

const filesa = lerConteudoDiretorio(patha);
const filesb = lerConteudoDiretorio(pathb);

filesa.forEach(function (filea) {
    filesb.forEach(function (fileb) {
        if (filea === fileb) { //se os nomes dos arquivos são iguais
            const a = fs.readFileSync(patha + `/${filea}`).toString();
            const b = fs.readFileSync(pathb + `/${fileb}`).toString();
            escreverConteudoArquivo(pathdestino + `${filea}`, `${a}\n${b}\n`)
        }
    });
});

Para executar com sucesso estou supondo que o conteúdo dos arquivos são texto.
Explicação do algoritmo
supondo que temos a seguinte estrutura de pastas:
.
+-- _diretorioa
|   +-- a.txt
|   +-- b.txt
|   +-- c.txt
+-- _diretoriob
    +-- b.txt
    +-- c.txt
    +-- d.txt

Então após a execução do script o resultado será:
.
+-- _diretoriodestino
    +-- b.txt
    +-- c.txt

Que são os arquivos que possuem o mesmo nome.

Em relação ao conteúdo dos arquivos eles serão gerados da seguinte forma:
diretorioa/b.txt
hello

diretoriob/b.txt
world

diretoriodestino/b.txt
hello
world

Comment: Perfeito! Muito obrigado!


Orthogonal intersection of linear family and exponential family

Question: I asked the following question in MSE for which I couldn't get any answer yet. I thought this would be a better place for that question.
In statistical maniolds $S=\{p_\theta\}$,$\theta=(\theta_1,\dots,\theta_n)$, the Riemaanian metric usually defined is the Fisher information metric $$g_{ij}(\partial_i,\partial_j)=\int \partial_i(\log p_\theta) \partial_i(\log p_\theta)~p_\theta~dx$$
The associated connection coefficients are defined by $$\Gamma_{ij}^k=\int \partial_i\partial_j(\log p_\theta)\partial_k (\log p_\theta)~ p_{\theta}~dx$$
where $\partial_i=\frac{\partial}{\partial\theta_i}$.
My question is, what is the intuition behind defining these? Is there a way to prove using the above metric and connection that the linear family of probability distributions $$L=\{p:\int f_i(x)p(x)~dx=m_i, i=1,\dots,k\}$$ intersects "orthogonally" the associated exponential family $$\mathcal{E}=\{p:p(x)=c(\theta)q(x)\exp(-\sum_{i=1}^k\theta_i f_i(x))\}$$ in the sense that $L\cap\mathcal{E}=\{p^*\}$ where $p^*$ satisfies $$D(p\|q)=D(p\|p^*)+D(p^*\|q)$$ for every $p\in L, q\in \mathcal{E}$.
I recently came to know about the connection between Fisher information metric and the relative entropy: $$D( p(\cdot , a+da) \| p(.,a) )\approx\frac{1}{2} g_{i,j} da^{i} da^{j}$$ Would this be a backbone in establishing the above result?
Answer: Very short "answer": we've discussed in your other question the roots of the idea of geometrization of statistical models by Jeffreys, how they become Riemannian manifolds with metric $g_{ij}$, etc. Much later, classical statisticians such as Efron, Amari, etc, got interested in the idea of the curvature of these manifolds, because there is a link with the concept of second order efficiency of classical estimators. It turns out that the Jeffreys metric (aka Fisher-Rao Information Metric) is kind of boring from the curvature standpoint. For example, for the normal model, if you consider the connection compatible with $g_{ij}$, compute the corresponding Christoffel symbols $\Gamma^i_{jk}$, and the Riemann tensor $R^i_{jkl}$, you will figure out that this is a space of constant scalar curvature $R=g^{ij} R^k_{ijk}$ (this is a good exercise: do it!). To "enrich" the geometry, Amari considered a family of $\alpha$-connections, which are not, in general, compatible with $g_{ij}$, and studied the curvature induced by this family of connections. Amari succeeded in establishing links with second order efficiency, and did a lot of interesting things with his $\alpha$-connections. You can find all this and much more in his book.
http://www.amazon.com/Information-Translations-Mathematical-Monographs-Tanslations/dp/0821843028
Comment: One more question: I came to know about the result mentioned in my question from Csiszar's [Information Theory And Statistics: A Tutorial](http://books.google.co.in/books?id=eTXlN0LRiFgC&printsec=frontcover#v=onepage&q&f=false) where the result is proven for the finite sample space using basic calculus and linear algebra. Do you think the fundamental idea might change when we try to prove the same result using Riemannian geometry?
Comment: Thank you. I will try to get Amari's book and look at these concepts very carefully.
Comment: I would need to take a look at Csiszar's book.
Comment: You may need to look at only page no. 24-26 (Theorem 3.2/Cor.3.1).


TypeError: app.auth() is not a function? (React App)

Question: I'm adding authentication to a react app I'm working on with a basic signup page and firebase. I have a firebase.js, a Signup.js, and an AuthContext.js. I have my Signup component, Auth Context and signup comp functionality done, and it should be working in a basic way at this point, but I'm now getting an error that says:TypeError: app.auth is not a function. It's referring to the export from my firebase.js file. Can anyone help me figure out what I'm doing wrong?
firebase.js:
import firebase from "firebase/compat/app";
import "firebase/auth";

const app = firebase.initializeApp({
  apiKey: process.env.REACT_APP_FIREBASE_API_KEY,
  authDomain: process.env.REACT_APP_FIREBASE_AUTH_DOMAIN,
  projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID,
  storageBucket: process.env.REACT_APP_FIREBASE_STORAGE_BUCKET,
  messagingSenderId: process.env.REACT_APP_FIREBASE_MESSAGING_SENDER_ID,
  appId: process.env.REACT_APP_FIREBASE_APP_ID,
});

export const auth = app.auth();
export default app;

Signup.js:
import React, { useRef, useState } from "react";
import { Form, Button, Card, Alert } from "react-bootstrap";
import { useAuth } from "../context/AuthContext";

export default function Signup() {
  const emailRef = useRef();
  const passwordRef = useRef();
  const passwordConfirmRef = useRef();
  const { signup } = useAuth();
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);

  async function handleSubmit(e) {
    e.preventDefault();

    if (passwordRef.current.value !== passwordConfirmRef.current.value) {
      return setError("Passwords do not match");
    }
    try {
      setError("");
      setLoading(true);
      await signup(emailRef.current.value, passwordRef.current.value);
    } catch {
      setError("Failed to create account");
    }

    setLoading(false);
  }

  return (
    <>
      <Card>
        <Card.Body>

Sign Up

          {error && <Alert variant="danger">{error}</Alert>}
          <Form onSubmit={handleSubmit}>
            <Form.Group id="email">
              <Form.Label>Email</Form.Label>
              <Form.Control type="email" ref={emailRef} required />
            </Form.Group>
            <Form.Group id="password">
              <Form.Label>Password</Form.Label>
              <Form.Control type="password" ref={passwordRef} required />
            </Form.Group>
            <Form.Group id="password-confirm">
              <Form.Label>Password Confirmation</Form.Label>
              <Form.Control type="password" ref={passwordConfirmRef} required />
            </Form.Group>
            <Button disabled={loading} className="w-100" type="submit">
              Sign Up
            </Button>
          </Form>
        </Card.Body>
      </Card>

        Already have an account? Log in

    </>
  );
}

AuthContext.js:
import React, { useContext, useState, useEffect } from "react";
import { auth } from "../firebase";

const AuthContext = React.createContext();

export function useAuth() {
  return useContext(AuthContext);
}

export function AuthProvider({ children }) {
  const [currentUser, setCurrentUser] = useState();
  const [loading, setLoading] = useState(true);

  function signup(email, password) {
    return auth.createUserWithEmailAndPassword(email, password);
  }

  useEffect(() => {
    const unsubscribe = auth.onAuthStateChanged((user) => {
      setCurrentUser(user);
      setLoading(false);
    });

    return unsubscribe;
  }, []);

  const value = {
    currentUser,
    signup,
  };

  return (
    <AuthContext.Provider value={value}>
      {!loading && children}
    </AuthContext.Provider>
  );
}

App.js:
import Signup from "./pages/Signup";
import "bootstrap/dist/css/bootstrap.min.css";
import { Container } from "react-bootstrap";
import { AuthProvider } from "./context/AuthContext";

function App() {
  return (
    <AuthProvider>
      <Container
        className="d-flex align-items-center justify-content-center"
        style={{ minHeight: "100vh" }}
      >

          <Signup />

      </Container>
    </AuthProvider>
  );
}

package.json:
{
  "name": "my-app",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.15.1",
    "@testing-library/react": "^11.2.7",
    "@testing-library/user-event": "^12.8.3",
    "bootstrap": "^5.1.3",
    "firebase": "^9.6.2",
    "react": "^17.0.2",
    "react-bootstrap": "^2.0.3",
    "react-dom": "^17.0.2",
    "react-router-dom": "^6.0.2",
    "react-scripts": "4.0.3",
    "web-vitals": "^1.1.2"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

Greatly appreciated!
Answer: In web version 9 your code should be like this
import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";

// TODO: Replace the following with your app's Firebase project configuration
// See: https://firebase.google.com/docs/web/learn-more#config-object
const firebaseConfig = {
  // ...
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);

// Initialize Firebase Authentication and get a reference to the service
const auth = getAuth(app);

Answer: The problem was that in firebase 9, the imports have changed, so in my firebase import, I had:
import firebase from "firebase/compat/app";
import "firebase/auth";

and it should be:
import firebase from "firebase/compat/app";
import "firebase/compat/auth";

adding compat solved it.


Does an out made after a failure to tag up count as a force out?

Question: Consider the following play:

There are runners on 2nd and 3rd with one out.
The batter hits a line out to center for the second out.
The runner on 3rd tags up correctly and crosses home plate.
The runner on 2nd fails to tag and breaks for 3rd on contact.
The throw goes home and the catcher immediately throws to 2nd for the third out.

Does the run count, or is this a force out negating the run?
Answer: The following rules are relevant here:
How a Run Scores, Rule 5.08:

5.08 How a Team Scores

(a) One run shall be scored each time a runner legally advances to and touches first, second, third and home base before three men are put out to end the inning.
EXCEPTION: A run is not scored if the runner ad- vances to home base during a play in which the third out is made (1) by the batter-runner before he touches first base; (2) by any runner being forced out; or (3) by a pre- ceding runner who is declared out because he failed to touch one of the bases.

Rule 5.09(b)(6), which defines "forced out":

He or the next base is tagged before he touches the next base, after he has been forced to advance by reason of the batter becoming a runner. However, if a following run- ner is put out on a force play, the force is removed and the runner must be tagged to be put out. The force is re- moved as soon as the runner touches the base to which he is forced to advance, and if he overslides or overruns the base, the runner must be tagged to be put out. However, if the forced runner, after touching the next base, retreats for any reason towards the base he had last occupied, the force play is reinstated, and he can again be put out if the defense tags the base to which he is forced;

In the example given, the run scored before three were out, and the third out was not scored on a force play.  As such, the run counts.
I assume the question here is, "is failing to tag up a force play"; the answer is no.  While the runner is put out in a similar manner (by tagging the bag), it is not considered a force play.
Comment: So in sense it becomes an appeal rather than a force out.
Comment: _Literally_ an appeal play. 5.09(c): "Appeal plays: Any runner shall be called out, on appeal, when: (1) After a fly ball is caught, he fails to retouch his original base before he or his original base is tagged"
Comment: @PhilipKendall I believe technically an appeal is only when it's after the play is completed (and they do the appeal process where they step off and throw to the bag ).
Answer: Tag ups are not force outs.  They're called timing plays.  Any runs scored before an out is made for not tagging up count.
Rule 8-2-6 section 8
Answer:
However, if the forced runner, after touching the next base, retreats for any reason towards the base he had last occupied, the force play is reinstated, and he can again be put out if the defense tags the base to which he is forced.

And there it is... yes, it is a definitely a force-play. Anytime a player is forced to go to a bag, the force is on, and therefore, no tag has to be made.
I just saw this happen in a game, and my first thought was that the run should count because it happened first, but when the umpires ruled otherwise because the force was on, I realized that I was wrong. Luckily, we had umpires who knew their stuff!
Comment: You are quoting from the later part of 5.09(b)(6), which only applies during a force play.  But with no runner on first, this was never a force play.  A force can't be reinstated if it wasn't there in the first place.


Show no available downloads when array value is empty or non existent

Question: I'm trying to create a simple list of pdfs with an if else statement, where the pdfs are shown as normal when there are pdfs present, and when there are none it needs to show: no available downloads.
Now it always shows that message no matter what (when there are no pdf files, and when there are pdf files).
I tried everything now and nothing is working.
When there is no id present or id is empty it needs to show the message, but only when there are no pdf files at all.
What I tried so far:
 <?
//pdf bestanden
$pdf                = "SELECT * FROM `snm_attachments` WHERE parent_id = '".$conn->real_escape_string($contentcr[0]['id'])."'";
$pdfcon             = $conn->query($pdf);
$pdfcr              = array();
while ($pdfcr[]     = $pdfcon->fetch_array());

foreach($pdfcr as $pdf){
    if(isset($pdf['id']) && !empty($pdf['id'])){
        $downloads .= '
'.$pdf['filename'].'
';
    }else{
        $downloads .= '
No available downloads
';
    }

    echo '
'.print_r($pdfcr).'
';
}

echo $downloads;
?>

I also tried this:
<?
//pdf bestanden
$pdf                = "SELECT * FROM `snm_attachments` WHERE parent_id = '".$conn->real_escape_string($contentcr[0]['id'])."'";
$pdfcon             = $conn->query($pdf);
$pdfcr              = array();
while ($pdfcr[]     = $pdfcon->fetch_array());

if(count($pdfcr) > 0) {
  foreach($pdfcr as $pdf){
    if($pdf['id'] != ''){
        $downloads .= '
'.$pdf['filename'].'
';
    }
  }
}else{
    $downloads .= 'leeg';
}
echo $downloads;
?>

The above doesn't even display the message, it displays nothing when there are no pdfs present. When I echo the PDF id on a page without pdfs it doesn't show anything, but it also doesn't show the no downloads available message.
How can I achieve this? It can't be that hard yet it is taking me hours to do this.
How it is now (see how it still shows the message, even when there are two pdfs):

Correct behaviour:

Here is the output of print_r($pdfcr)
https://kobra.io/#/e/-KIgRDOAz_Ki2PpOKTU5
Answer: You are adding and empty value of last fetch function. This is correct way:
$downloads = '';
while ($pdf= $pdfcon->fetch_array()) {
        $downloads .= '
'.$pdf['filename'].'
';
}

if ($downloads) echo $downloads; else echo 'No data';

Comment: This worked, it makes sense but the only thing I don't understand is how it adds an empty value?
Comment: Because when you reach all records, `fetch` returns FALSE value and you put this value into array with your old code. In my code, first is checked conditions then pushed value. In your code you first push value then check condition ;)


Prove that $\int_0^{\infty}\int_0^{\infty}e^{-(x^2 + 2xy\cos(\alpha)+y^2)}\mathrm dx\mathrm dy=\frac{\alpha}{2\sin(\alpha)}$

Question: I'm having difficulty with a question. It says

By putting $x=r\cos(\theta), y=r\sin(\theta)$, prove that $$\int_0^{\infty}\int_0^{\infty}e^{-(x^2 + 2xy\cos(\alpha)+y^2)}\mathrm dx\mathrm dy=\frac{\alpha}{2\sin(\alpha)}$$

Making the substitution we get \begin{align*}&\int_0^{\pi/2}\int_0^{\infty}re^{-r^2 (\sin(2\theta) \cos(\alpha) + 1)}dr\ d\theta \\ \\
=&\int_0^{\pi/2} \frac{1}{2(\sin(2\theta) \cos(\alpha) + 1)} d\theta\\ \\
=&\frac{\alpha}{2\sin(\alpha)} \int_0^{\pi/2} \frac{\sin(\alpha)}{2 \alpha \cos(\alpha) \sin(\theta) \cos(\theta) + \alpha} d\theta\\ \\
=&\frac{\alpha}{2\sin(\alpha)} \int_0^{\pi/2}\frac{\tan(\alpha) \sec^2(\theta)}{2 \alpha \tan(\theta) + \alpha \sec(\alpha) \sec^2(\theta)} d\theta
\end{align*}
setting $u=\tan(\theta),\ du=\sec^2(\theta)\ d\theta$
$$=\frac{\alpha}{2\sin(\alpha)}\int_0^{\infty}\frac{\tan(\alpha)\ du}{\alpha \sec(\alpha) + 2\alpha u+ \alpha \sec(\alpha) u^2}$$
Now \begin{align*}u&=\frac{\cos(\alpha)\{-2\alpha\pm\sqrt{4\alpha ^2 - 4\alpha ^2\sec^2(\alpha)}\}}{2\alpha}\\ \\
&=-\cos(\alpha) \mp i\sin(\alpha)\\
&=-e^{\pm i\alpha}
\end{align*}
So substituting in
\begin{align*}
=&\frac{\alpha}{2\sin(\alpha)}\int_0^{\infty}\frac{\tan(\alpha)\ du}{(u-e^{i\alpha})(u-e^{- i\alpha})}\\ \\
=&\frac{\alpha}{2\sin(\alpha)}\left[ \frac{\tan(\alpha)\{\log(1-ue^{i\alpha}) - \log(-u+e^{i\alpha})\}}{-1+e^{2i\alpha}} \right]^{\infty}_{u\, =\, 0}
\end{align*}
which I then can't evaluate (and certainly isn't $1$). Any help?
Answer: $\int_{0}^{\frac{\pi}{2}}\frac{1}{2(\sin(2\theta)\cos(\alpha)+1)}d\theta=\frac{1}{2}\int_{0}^{\frac{\pi}{2}}\frac{1}{2\sin(\theta)\cos(\theta)\cos(\alpha)+1}d\theta=\frac{1}{2}\int_{0}^{\frac{\pi}{2}}\frac{\sec^{2}(\theta)}{2\tan(\theta)\cos(\alpha)+\sec^{2}(\theta))}d\theta$
$=\frac{1}{2}\int_{0}^{\frac{\pi}{2}}\frac{\sec^{2}(\theta)}{\tan^{2}(\theta)+2\tan(\theta)\cos(\alpha)+1}d\theta=\frac{1}{2}\int_{0}^{\frac{\pi}{2}}\frac{\sec^{2}(\theta)}{(\tan(\theta)+\cos(\alpha))^{2}+(1-\cos^{2}(\alpha))}d\theta$
$=\frac{1}{2}\int_{0}^{\frac{\pi}{2}}\frac{\sec^{2}(\theta)}{(\tan^{2}(\theta)+\cos(\alpha))^{2}+\sin^{2}(\alpha)}du=\frac{1}{2}\int_{\cos(\alpha)}^{\infty}\frac{1}{u^{2}+\sin^{2}(\alpha)}du=\frac{1}{2}\frac{1}{\sin(\alpha)}\int_{\cos(\alpha)}^{\infty}\frac{\frac{1}{\sin(\alpha)}}{\big(\frac{u}{\sin(\alpha)}\big)^{2}+1}du$
where I have made the substitution $u=\tan(\theta)+\cos(\alpha)$. The integral now becomes:
$=\frac{1}{2\sin(\alpha)}\int_{\cot(\alpha)}^{\infty}\frac{1}{w^{2}+1}dw=\frac{1}{2\sin(\alpha)}\big(\frac{\pi}{2}-\arctan(\cot(\alpha))\big)=\frac{1}{2\sin(\alpha)}arccot(\cot(\alpha))=\frac{\alpha}{2\sin(\alpha)}$
where I have made the substitution $w=\frac{u}{\sin(\alpha)}$ and used that $\arctan(x)+arccot(x)=\frac{\pi}{2}$.
Answer: \begin{align}
 \frac{1}{1+\sin{(2\, \theta)}\, \cos{\alpha}} &=\frac{1}{1+2\sin{\theta}\cos{\theta}\, \cos{\alpha}}\\
&= \frac{\sec{(\theta)}^2}{\sec{(\theta)}^2+2\tan{\theta}\, \cos{\alpha}}\\
&= \frac{\sec{(\theta)}^2}{1+\tan{(\theta)}^2+2\tan{\theta}\, \cos{\alpha}}\\
&= \frac{\sec{(\theta)}^2}{\sin{(\alpha)}^2+\cos{(\alpha)}^2+\tan{(\theta)}^2+2\tan{\theta}\, \cos{\alpha}}\\
&= \frac{\sec{(\theta)}^2}{\sin{(\alpha)}^2+\left(\cos{(\alpha)}+\tan{(\theta)}\right)^2}\\
\end{align}
\begin{align}
\therefore  \int \frac{1}{1+\sin{(2\, \theta)}\, \cos{\alpha}} d\theta &= \int \frac{\sec{(\theta)}^2}{\sin{(\alpha)}^2+\left(\cos{(\alpha)}+\tan{(\theta)}\right)^2}\, d\theta\\
&= \frac{1}{\sin{\alpha}}\, \arctan{\frac{\tan{\theta}+\cos{\alpha}}{\sin{\alpha}}}+C
\end{align}
Thus, the required integral is
\begin{align}
\frac{1}{2} \int_0^{\pi/2} \frac{1}{1+\sin{(2\, \theta)}\, \cos{\alpha}} d\theta &= \frac{\alpha}{2\, \sin{\alpha}}
\end{align}


Falha ao conectar ao SQL server com nodeJs (Sequelize)

Question: Estou desenvolvendo um CRUD com nodejs mas estou com problemas ao conectar ao SQL server.
Classe responsável por fazer a conexão:
const sequelize = require('sequelize');

const database = new sequelize('master', 'sa', '1#kaLvX91', {

    dialect: 'mssql', host:'localhost', port:1433
});

database.sync();

module.exports = database;
});

database.sync();

module.exports = database;

O erro que estou recebendo:
\connection-manager.js:109
          throw new sequelizeErrors.ConnectionError(error);
                ^

ConnectionError [SequelizeConnectionError]: Failed to connect to localhost:1433 - Could not connect (sequence)
    at ConnectionManager.connect (C:\Users\raf_r\OneDrive\Nodejs\CRUD\node_modules\sequelize\lib\dialects\mssql\connection-manager.js:109:17)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async ConnectionManager._connect (C:\Users\raf_r\OneDrive\Nodejs\CRUD\node_modules\sequelize\lib\dialects\abstract\connection-manager.js:220:24)
    at async C:\Users\raf_r\OneDrive\Nodejs\CRUD\node_modules\sequelize\lib\dialects\abstract\connection-manager.js:174:32
    at async ConnectionManager.getConnection (C:\Users\raf_r\OneDrive\Nodejs\CRUD\node_modules\sequelize\lib\dialects\abstract\connection-manager.js:197:7)
    at async C:\Users\raf_r\OneDrive\Nodejs\CRUD\node_modules\sequelize\lib\sequelize.js:301:26
    at async MSSqlQueryInterface.tableExists (C:\Users\raf_r\OneDrive\Nodejs\CRUD\node_modules\sequelize\lib\dialects\abstract\query-interface.js:102:17)
    at async Function.sync (C:\Users\raf_r\OneDrive\Nodejs\CRUD\node_modules\sequelize\lib\model.js:939:21)
    at async Sequelize.sync (C:\Users\raf_r\OneDrive\Nodejs\CRUD\node_modules\sequelize\lib\sequelize.js:373:9) {
  parent: ConnectionError: Failed to connect to localhost:1433 - Could not connect (sequence)
      at Connection.socketError (C:\Users\raf_r\OneDrive\Nodejs\CRUD\node_modules\tedious\lib\connection.js:1425:28)
      at C:\Users\raf_r\OneDrive\Nodejs\CRUD\node_modules\tedious\lib\connection.js:1185:21
      at SequentialConnectionStrategy.connect (C:\Users\raf_r\OneDrive\Nodejs\CRUD\node_modules\tedious\lib\connector.js:129:14)
      at Socket.onError (C:\Users\raf_r\OneDrive\Nodejs\CRUD\node_modules\tedious\lib\connector.js:149:12)
      at Socket.emit (node:events:527:28)
      at emitErrorNT (node:internal/streams/destroy:157:8)
      at emitErrorCloseNT (node:internal/streams/destroy:122:3)
      at processTicksAndRejections (node:internal/process/task_queues:83:21) {
    code: 'ESOCKET',
    isTransient: undefined
  },
  original: ConnectionError: Failed to connect to localhost:1433 - Could not connect (sequence)
      at Connection.socketError (C:\Users\raf_r\OneDrive\Nodejs\CRUD\node_modules\tedious\lib\connection.js:1425:28)
      at C:\Users\raf_r\OneDrive\Nodejs\CRUD\node_modules\tedious\lib\connection.js:1185:21
      at SequentialConnectionStrategy.connect (C:\Users\raf_r\OneDrive\Nodejs\CRUD\node_modules\tedious\lib\connector.js:129:14)
      at Socket.onError (C:\Users\raf_r\OneDrive\Nodejs\CRUD\node_modules\tedious\lib\connector.js:149:12)
      at Socket.emit (node:events:527:28)
      at emitErrorNT (node:internal/streams/destroy:157:8)
      at emitErrorCloseNT (node:internal/streams/destroy:122:3)
      at processTicksAndRejections (node:internal/process/task_queues:83:21) {
    code: 'ESOCKET',
    isTransient: undefined
  }
}

Comment: As opções passadas como parâmetro não parecem estar corretas, veja https://sequelize.org/docs/v6/other-topics/dialect-specific-things/#mssql . O sequelize utiliza o pacote tedious como conector MSSQL e esse precisa de opções próprias.
Answer: Primeiro você precisa remover o "database.sync()" e o "module.exports" repetidos do seu código, deixar apenas umas vez. E instala o pacote 'tedious' necessário pra conexão com o mssql. Pra instalar: npm install tedious
Sugiro tu dá uma lida no artigo abaixo que me ajudou bastante a entender: Node.js + MSSQL


Java2D using buttons and Graphics2D

Question: I want to create a tile editor sort of program where I have a viewport for rendering on the left side of the program, and then a panel of buttons on the right to use for opening files, saving the tiles etc... I was going to use LWJGL to do this, but it seems theres no good way to do it.
Essentially I guess I'm asking, how do I have a viewport for rendering using g.DrawImage or something, and then also have a panel of buttons next to that viewport?
Comment: you have to create a 'draw-panel', a panel which has a grid, and you can set the color of each grid field. if you set the color on the panel you also set the color (ans position) in the image you want to produce - this 'draw-panel' can be implementent in various form. once you have it you can add that panel with a scrollpanel so you can zoom (need implementation) and pan the image;

in my opinion it's cheaper to use a freeware - but feel free to refine your questions^^
Answer: You can do this using jME3 as they support rendering in a canvas on a Swing window. There is even a tutorial on doing it in the tutorials section of the website.
You can also do it using a fully rendered window and then putting the buttons inside the scene. I'm surprised LWJGL doesn't support this though as jME3 is built on top of LWJGL.
Comment: LWJGL is just a graphics API, it doesn't know anything besides manipulating vertices and buffers. And I really don't want to use JME, I want to use Java2D.
Comment: You can write 2d games in jME (although you may be better off choosing a 2d graphics engine). For example see: http://gamedevelopment.tutsplus.com/tutorials/make-a-neon-vector-shooter-in-jmonkeyengine-the-basics--gamedev-11616
Comment: No, I really don't want to use JME. I already have been learning OpenGL for two years, I don't need an engine for the games I make. I was just asking how to make a sort of tile editor in Java2D because I don't have much experience with it.

Java2D using buttons and Graphics2D


Replacing file line with a string

Question: I have a .txt file in which I want to replace a specific line (line #3) with a string. I don't want to use a simple file.replace(targetString, newString) because I have multiple targetString in the file, and the orders in which they're in is unknown. I do know that the string I want to replace is always at the 3rd line, and it is the only thing on the 3rd line.
Currently my code looks something like this, I'm terrible at programming so I would appreciate the easiest answer you can think of
with open("LAB5INFO.txt", "r+") as file:
    content = file.read()
    file.seek(0)
    file.truncate()
    file.write(content.replace(<<LINE3>>, string))

Comment: Hi Oliver, I made a few changes to your question.  I took the Python tag out of the title; as tags are discouraged.  More significantly, I changed the spacing of your code block.  Since this is python, the spacing change is significant.  Please either edit the question or roll back my change if you find the change I made was not a true representation of the code you've written.
Comment: Also, if you're terrible at programming, why not just open the file in an editor and change that line?  (If you want to change that line in a batch script, there are usually scripting alternatives that will do what you want.)
Answer: I guess?
with open("LAB5INFO.txt", "rb") as file:
    lines = file.readlines()
    lines[2].replace("old","new")
with open("LAB5INFO.txt", "wb") as file:
    file.write("\n".join(lines)

Answer: borrowing from other answer, but here we don't need to know the content of the original line
with open("LAB5INFO.txt", "rb") as file:lines = file.readlines()
lines[2]="new third line"
with open("LAB5INFO.txt", "wb") as file: file.write("\n".join(lines))

Replacing file line with a string


Reading image files serially from a folder in matlab

Question: I tried to read .jpg files from a folder in matlab using dir command. But I am not getting them from the first image stored in the folder. Instead it started from 10th image. I want to know how to read the files serially starting from the beginning.
Comment: What matlab function are you using to "get" *.jpg from the folder?  I assume you want them sorted by name, or date, etc.  Which is it?
Comment: please show your code
Comment: I am using dir command
Comment: Template = dir('IrisTemplates\*.jpg');                                 If I type  Template(1).name

It gives the ans = template_10_1_1.jpg                                                    But I am expecting Template(1).name as template_1_1_1.jpg
Answer: I am almost certain that if you are using a simple enough command, it will give you all files that are there. However, this may not seem to be the case because of this little line in the description:
Results appear in the order returned by the operating system.

This may mean, that you will first see files like 1, 100, 1000,1999 and only later a file with numer 2. Of course you can sort the results after you have collected them, and then process them in your desired order.

For completenes, one would like to have something like:
dir *.jpg

or if you want to be sure to catch everything that even remotely resembles .jpg:
dir *.*j*p*g*

Comment: I have a folder containing only image files(.jpg files) which are the results of some pre processing steps. Each file corresponds to an image. Now I want to access them one by one serially by name, for the further processing... and later I need to compare the results                        I use dir command to access the files. But the first structure element returned by the dir command is giving me 10th file instead of first file.


Configuring two different application server in one nginx?

Question: I have two different app servers one is my custom application and other is CRM.
My custom app will get request and it will request crm server for some data and at the end server the customer.
I have one nginx which is handling the crm and I want the same nginx deal with my application and let those app communicate in between.
I have tried with the following config
upstream example.net{
server 192.168.200.144:8080; # virtual machine web1 site
server 192.168.200.143:8080; # virtual machine web2 site

}

upstream example-crm.net{
server 192.168.200.85:8080; # virtual machine web1 site
server 192.168.200.86:8080; # virtual machine web2 site

}

server {
listen       192.168.200.173; # public IP address of your server
server_name  example.net;
server_name     example-crm.net

location / {

proxy_pass           http://example.net;
proxy_pass           http://example-crm.net;

proxy_connect_timeout       900;
proxy_send_timeout          900;
proxy_read_timeout          900;
send_timeout                900;

proxy_redirect       off;
proxy_set_header     Host $http_host;
proxy_set_header     X-Real-IP $remote_addr;
proxy_set_header     X-Forwarded-For $proxy_add_x_forwarded_for;
}
}

but it doesn't work.
to make it more clear i have drawn a diagram which explain the scenario

Diagram Explanation:
customer send request 1 on virtual IP 192.168.200.173, nginx send request 2 to app 1 server, app 1 server sends request 3 to nginx for app 2 server, nginx send request 4 to app 2 server, and app 2 send request 5 to nginx and nginx send request 6 to app 1 and app 1 performs its business logic and send request 7 to nginx and nginx serve the request 8 to the customer.
Any suggestion ?
Comment: You should have two different server with different server_name and proxy_pass.
Comment: It is not very clear what you are trying to achieve. For one thing, the IP addresses in your diagram do not match up with those in your configuration. Also in your diagram, both App 1 server and App 2 server are labeled with the same IP addresses. It is also unclear what "Request 1" through "Request 8" are. Please clarify.
Comment: @TilmanSchmidt I have just updated the diagram and its explanation, have a look now.
Comment: It is still not clear. The IP addresses still do not match. I do not understand the relationship between requests 1 .. 8. Why should Nginx generate requests of its own? Why does it send a request to the user? Should some of these perhaps be labeled "reply" instead? Are some of these really the same request being forwarded? Please clarify.
Comment: yes you can say reply instead, request 8 is the end reply which will be served to the customer
Comment: @Navern so for that i will need two Virtual IPs too ?
Comment: @Waqas you don't need to have two virtual IPs. Read how nginx choose server. It will chose right server depend on your server_name.
Comment: That diagram does not help at all. The user issues a request against _a_ server (the one labelled nginx) and expects a reply from that same server; the server _may_ talk to something else (labelled request 2 in the diagram) to get that response, but that's where the chain ends; anything app-server-1 does to generate the response is separate/kind of irrelevant. It's almost like you want the server labelled nginx to be a load balancer.
Comment: @AD7six yes, I'm trying to use nginx as loadbalencer
Answer: You are doing it wrong. How it should be:
server {
    listen       192.168.200.173; # public IP address of your server
    server_name     example.net

    location / {

        proxy_pass           http://example.net;

        proxy_connect_timeout       900;
        proxy_send_timeout          900;
        proxy_read_timeout          900;
        send_timeout                900;

        proxy_redirect       off;
        proxy_set_header     Host $http_host;
        proxy_set_header     X-Real-IP $remote_addr;
        proxy_set_header     X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

server {
    listen       192.168.200.173; # public IP address of your server
    server_name     example-crm.net

    location / {

        proxy_pass           http://example-crm.net;

        proxy_connect_timeout       900;
        proxy_send_timeout          900;
        proxy_read_timeout          900;
        send_timeout                900;

        proxy_redirect       off;
        proxy_set_header     Host $http_host;
        proxy_set_header     X-Real-IP $remote_addr;
        proxy_set_header     X-Forwarded-For $proxy_add_x_forwarded_for;
        }
}

Read how nginx process request:
http://nginx.org/en/docs/http/request_processing.html
It short it will find two server for this IP address, then it will check "Host" header in HTTP request and process request in server which have corresponding server_name.
Comment: if i want to send request http://example-crm.net how would I do it (using the virtual ip)?
Comment: curl -H 'Host: example-crm.net' http://virtual_ip
Comment: Provide full output of command and how you do this.
Comment: it is working using curl, what should be the url for browser ?
Comment: example-crm.net for example-crm.net, and example.net for example.net.


A wrong corollary of Kolmogorov's $0-1$ Law

Question: I either broke Probability Theory, or what is more likely, I am confused.
Let $X_{n}$ be a sequence of i.i.d random variables.
Then by Kolmogorov's $0-1$ Law, the probability that $S_{n}=\sum_{k=1}^n X_{k}$ converges is $\in \{0,1\}$.
Furthermore, the random variables $\lim \sup S_{n}$ and $\lim \inf S_{n}$ are measurable with respect to the terminal sigma-field generated by the $X_{n}$ and hence a.s. constant (a consequence of the 0-1 law) - is this true?
Now if $S_{n}$ converges a.s. then $\lim \sup S_{n} = \lim \inf S_{n}$ a.s.
Does this mean that if $S_{n}$ converges it does so to a constant?
It can't...
Comment: Surely $\limsup S_n$ can't be measurable with respect to the terminal sigma - field , because each $S_n$ depends on $X_1$, so for example $\limsup S_n$ can't be a Borel function of just $X_2,X_3,....$, hence is not even $\sigma(X_2,X_3,...)$ measurable.
Answer: By the Hewitt–Savage 0-1 law, $\limsup S_n$ is a constant $C\in[-\infty,\infty]$ ($\because \limsup S_n$ is measurable w.r.t. the exchangeable $\sigma$-algebra). Since $S_n\overset{d}{=} S_{n+1}-X_1$, $C=C-X_1$ a.s. There are two possibilities for the last equality to hold: (1) $|C|<\infty$ and $X_1=0$ a.s., (2) $C=\pm\infty$. The same is true for $\liminf S_n$.
Answer:
If $S_n$ converges a.s. then $\limsup S_n = \liminf S_n$ a.s.

So far, so good.

Does this mean that if $S_n$ converges it does so to a constant?

That the answer is "yes" seems surprising, until you remember that a conditional statement "If $P$, then $Q$" is vacuously true when $P$ is false.
In your example, $S_n$ does not converge unless each of the $X_n = 0$ a.s., in which case, $S_n = 0$ a.s. for all $n$ as well and therefore we trivially have $S_n \to 0$ a.s.
If $P(X_n = 0) \neq 1$, then since $S_n$ does not converge, the "if" part of "if $S_n$ converges it does so to a constant" is false, and so the conditional statement is vacuously true.
Comment: @Vincent I think it's clear, from my answer and in the context of OP's question, that what I meant by "$S_n$ does not converge unless..." was really "$S_n$ converges with probability zero/fails to converge with probability one unless..." Ironically, I phrased it the way I did because I was trying to **avoid** verbal confusion when connecting the example with vacuous truth of conditional statements. If it ain't one thing, it's another, lol.
Comment: "$S_n$ does not converge unless each of the $X_n = 0$ a.s." does seem incorrect. It could be that $S_n$ converges by coincidence because each of the $X_n = 0$ due to some extremely unlikely form of coincidence. However the slightly modified statement "$S_n$ does not converge **a.s.** unless $X_n = 0$ a.s." is true of course. I think this distinction is at the heart of the OPs confusion although only the OP self can confirm/deny this..
Answer: The abbreviation 'a.s' stands for 'almost surely', right? I think the correct statement is not 'if $S_n$ converges it converges to a constant' but 'if $S_n$ converges with probability 1 then it converges to a constant'.
If the probability of convergence is zero then you may happen to witness such a probability zero event and this limit can be anywhere, but there is not much reason to worry about this scenario because almost surely it won't happen.
On the other hand the situation where the probability of convergence is 1 is quite different and there we don't have just probability 1 of convergence but probability one of convergence to a limit that can be known beforehand for pretty much the reason you describe.
Unless I'm confused as well...


a new method to solve some congruence problems

Question: I'm new to number theory and I've newly learnt congruence and there are a special kind of questions in my book which I usually face problems to solve an example of them is as follows:

If $18a\equiv12b\ (\mathrm{mod}\ 9)$ then which of the following statments is wrong?
$$(1)\ a\equiv0\ (\mathrm{mod}\  2)$$
$$(2)\ b\equiv0\ (\mathrm{mod}\ 3)$$
$$(3)\ 3a\equiv b\ (\mathrm{mod}\ 3)$$
$$(4)\ 3a\equiv2b\ (\mathrm{mod}\ 3)$$

The point is that I can solve them but with a long and hard effort so I was thinking of a shorter way and I remember the short way my teacher told me for division problems which is as follows:
If $d|2n+5, d|9n+2$,then $d|\det\begin{bmatrix}
2 & 5 \\
9 & 2 \\
\end{bmatrix}$ but he also mentioned that we have to check the determinant for paradoxes.
Anyway I don't know where this formula has come from and I wonder to know two things.

Where does this method come from and can I use it for the problems I mentioned first(since you can write every congruence as a division)?

Actually I have some ideas when they don't change to $\mathrm{mod}$ in question choices but I don't know what to do when there's a change in the base.
Any help is appreciated!
Answer: Three tips:

You can divide both sides of a congruence by an integer if you divide the modulus by that same integer; so for instance, $18a\equiv12b \pmod 9$ is exactly the same as $6a\equiv4b \pmod 3$.
We might as well reduce all integers that appear modulo the modulus; so for instance, since $6\equiv0\pmod3$ and $4\equiv1\pmod3$, we know that $6a\equiv4b \pmod 3$ is exactly the same as $0a\equiv1b \pmod 3$, or $b\equiv0\pmod3$.
Finally, if two moduli are relatively prime, then whether the congruences hold or not are completely independent of each other. For example, since $\gcd(9,2)=1$, whether $18a\equiv12b \pmod 9$ is completely independent of whether $a\equiv0\pmod 2$ (they might be both true, both false, or one of each either way).
Comment: thanks both for your edit and tips on solving the problem but which is more important to me is the determinant solving method and how it works.


Mapstruct maven dependency download not working in Spring Tool Suite

Question: STS is showing the message "Updating Maven Project: (75%)" at the bottom right corner and never ends that for hours (literally).
It happens when I add mapstruct to pom.xml (as in the first pom.xml below).
If I remove mapstruct lines from pom.xml (as in the second pom.xml below) the maven update completes just fine.
But I need to use mapstruct.
Tried with Mapstruct 1.5.1.Final and 1.5.2.Final. Same issue on both.
With mapstruct (maven update not working)
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.7</version>
        <relativePath/>
    </parent>
    <groupId>com.xyz</groupId>
    <artifactId>xxx</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>xxx</name>
    <description>aaaaaaaaa</description>
    <properties>
        <java.version>11</java.version>
        <org.mapstruct.version>1.5.2.Final</org.mapstruct.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jdbc</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-rest</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.25</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.mapstruct</groupId>
            <artifactId>mapstruct</artifactId>
            <version>${org.mapstruct.version}</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <annotationProcessorPaths>
                        <path>
                            <groupId>org.mapstruct</groupId>
                            <artifactId>mapstruct-processor</artifactId>
                            <version>${org.mapstruct.version}</version>
                        </path>

                    </annotationProcessorPaths>
                </configuration>
            </plugin>

        </plugins>

    </build>

</project>

Without mapstruct (maven update working fine)

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.7</version>
        <relativePath/>
    </parent>
    <groupId>com.xyz</groupId>
    <artifactId>xxx</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>xxx</name>
    <description>aaaaaaaaa</description>
    <properties>
        <java.version>11</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jdbc</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-rest</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.25</version>
        </dependency>

            <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>

        </plugins>

    </build>

</project>

Comment: Plain command build works?
Comment: @khmarbaise I'm using maven that comes built in STS. So running mvn command in command prompt doesn't work. I might install maven outside STS to give a try.
Comment: So first try to install MVN and try your build on plain command line...if that works... than into STS...
Answer: Works fine for me from STS.
Maybe your local maven repo is damaged. Try deleting folder 1.5.2.Final from $USER/.m2/repository/org/mapstruct/mapstruct/1.5.2.Final or from wherever your repo is.
Comment: I deleted the whole .m2 folder before and downloaded all dependencies from scratch. Same result.
Comment: If you go to https://repo1.maven.org/maven2/org/mapstruct/mapstruct/1.5.2.Final/ and download the .jar and the .pom to $USER/.m2/repository/org/mapstruct/mapstruct/1.5.2.Final you should be able to work.
Comment: The issue is in mapstruct-processor, not in mapstruct. The mapstruct code in the  section of pom.xml is working fine. The problem is when I add the mapstruct-processor section in the  part of pom.xml.
Comment: So I followed your suggestion and downloaded from https://repo1.maven.org/maven2/org/mapstruct/mapstruct-processor/1.5.2.Final/ the following files: mapstruct-processor-1.5.2.Final.jar, mapstruct-processor-1.5.2.Final.jar.sha1, mapstruct-processor-1.5.2.Final.pom, mapstruct-processor-1.5.2.Final.pom.sha1 and copied them directly to local \.m2\repository\org\mapstruct\mapstruct-processor\1.5.2.Final. I left the  _remote.respositories file that was in that folder already. The problem continued. Should I add the other files available in the maven remote repo or just those four are enough?
Comment: You also need mapstruct, not just mapstruct-processor. Having the jars in your rep should allow you to work but will still indicate problems collecting the dependency (75% in STS)
Comment: BTW what does your _remote.respositories file contain. I suspect that STS is struggling to reach a specific repo. Also, do you have a mvnw.bat/cmd in the root of your project?
Comment: Sure. I do have mapstruct. It's in the .m2 repo and running well. Just said that the problem (75% in STS) happens when I add the mapstruct-processor xml section to pom.xml
Comment: Here is the content of \.m2\repository\org\mapstruct\mapstruct-processor\1.5.2.Final\ _remote.repositories:
#NOTE: This is a Maven Resolver internal implementation file, its format can be changed without prior notice.
#Fri Jan 27 13:28:24 BRT 2023
mapstruct-processor-1.5.2.Final.jar>central=
mapstruct-processor-1.5.2.Final.pom>central=
Comment: About your comment "Having the jars in your rep should allow you to work but will still indicate problems collecting the dependency (75% in STS) ". That is not what I'm experiencing. STS is pretty blocked trying to do that update.
Comment: If you restart STS and try and do a Run As > Maven test, does it compile?
Comment: If I close STS and open it again it will directly get to the "Updating Maven Project: (75%)" message. Then if I go to Run As > Maven Test, it will show this message in the Progress window: "Launching Executing test in C.... (Blocked: The user operation in waiting for "Building" to complete)". So it is waiting for the 75% to complete to then run maven test.
Comment: I created a new application in a new STS workspace. Then copied the exact content of this pom.xml file and it worked. Looks like the original application has something else conflicting.
Answer: Looks like you need to add a mapstruct processor.
This should help you:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.10.1</version>
    <configuration>
        <source>${java.version}</source>
        <target>${java.version}</target>
        <annotationProcessorPaths>
            <path>
                <groupId>org.mapstruct</groupId>
                <artifactId>mapstruct-processor</artifactId>
                <version>${org.mapstruct.version}</version>
            </path>
        </annotationProcessorPaths>
    </configuration>
</plugin>

Comment: I know it could be an issue due to Lombok, but I don't see it in your pom. Have you tried to mnv package + Reload Maven Project and then Invalidate Caches?
Comment: From the main menu, select File | Invalidate Caches.

https://www.jetbrains.com/help/idea/invalidate-caches.html
Comment: Did you see the first block of code that I posted? Processor that you suggested is already there.
Comment: Damn, now I see. Sorry for misguiding.
Comment: btw, this part of my code that has the processor is the exact one that is blocking maven update. If I remove that but leave the other parts that make reference to mapstruct the maven update works fine.
Comment: Right, I'm not using lombok. As for the mvn, I'm using the maven that comes bundled in STS. So executing maven from STS, not command line. Not sure I can do mvn package command with that. Think it would be needed an external maven installation right? Also... how to invalidate caches?
Comment: I'm using Spring Tool Suite.


Can I apply the same DCC-GARCH model on sub-samples to investigate differences in co-movements?

Question: I am using DCC-GARCH for a master thesis in which I am investigating the co- movement of the Green bond and other markets pre and during the current economic crisis. Based on the signficant ARCH/GARCH parameters in Table 1 and the failure to reject the  null hypothesis of the Ljung-Box test used on the models standardized residuls in Table 2., the ARMA(1,0)-GARCH(1,1) model seems to adequitely fit the conditional variance of the time series.
The graphs below display the DCC(GB,i) (i = Treasury, Carbon, MSCI.World, Carbon) and was computed using DCC-ARMA(1,0)-GARCH(1,1). The dotted line is the divisor of the "pre-crisis" and "during crisis" periods.  When looking at them, no difference in the DCC of "pre-crisis" and "during crisis" is shown. I wonder how I should proceed to answer my research quesiton "What are the differences in the co-movements between the GB market and the treasury, corporate, stock, and carbon markets pre and during the Covid-19 crisis period?" Is there any formal test I could do to see if the co-movement has changed, should I just interpret what I see from the graphs or can I run the DCC—ARMA(1,0)-GARCH(1,1) model on two subsets "pre-crisis" and "during crisis" and compare the dccalpha and dccbeta?
Using the same model for the two subperiods intuitively seems wrong since if there is any changes in the markets volatility in-between these two periods, the model created to fit data over the entire period could be a bad fit for at least one of these periods? Or can the model be a good fit for the entire period since it is developed for time series with inconsistent volatility? Another problem of this method would be that I only got 254 observations for the "during crisis period". Don't know if this helps in answering the question but since I don't think it will hurt, I included the graphs of the markets conditional SD. In them we can see that the volatility of the Green Bond, Corporate and stock (MSCI.World's) markets seem to be a bit higher during crisis than before crisis. To give an idea of the results of this method for comparing the co-movements of the different periods, I included the outputs using the DCC-ARMA(1,0)-GARCH(1,1) model in Table 3 and Table 4.

----------------------------------------DCC GRAPHS--------------------------------------
[
-------------------------------------Conditional SD GRAPHS------------------------------
Comment: What do you think about my answer? If it is helpful and clear, you may accept it by clicking on the tick mark to the left. Otherwise, you may ask for further clarification. This is [how Cross Validated works](https://stats.stackexchange.com/tour).
Answer:
"What are the differences in the co-movements between the GB market and the treasury, corporate, stock, and carbon markets pre and during the Covid-19 crisis period?" <...> Using the same model for the two subperiods intuitively seems wrong since if there are any changes in the markets volatility in-between these two periods, the model created to fit data over the entire period could be a bad fit for at least one of these periods? Or can the model be a good fit for the entire period since it is developed for time series with inconsistent volatility?

If the data generating process changes over time, then fitting a single model with time-constant parameters indeed cannot reflect that. It would be a simplification, and an unwelcome one at that if your goal is to assess whether there have been changes and what they have been like. So it would make sense to fit the model on subsamples and compare the results. If you believe some of the model's parameters stay constant over the entire sample period, you could fit the model for the entire period and use some dummies to account for the variations in some parameters (the ones that are not supposed to have stayed constant). A problem with that is that it may not be an option in the software you are using.

Another problem of this method would be that I only got 254 observations for the "during crisis period"

Regarding the sample size and estimation precision, this is a genuine problem. If there is little data, it is fundamentally difficult to estimate a model's parameters, and I am not sure there is any nice way to circumvent this. Simplifying assumptions (such as assuming some parameters stay fixed for the entire sample) may be necessary to make modeling feasible.
(This answer has been moved from another thread, so the quotes might not be 100% accurate, though they were for the original thread.)


proof that the instantaneous center of rotation has to have zero speed

Question: We're on the plane $\mathbb C$ or $\mathbb R^2$.
Definition 1: A movement is a colection of isometries $H_t$ in the plane, with $t \in [0,1]$ and $H_0$ being the identity isometry and such that $H_t(X)$ is a continuous funtion on $t$.
Definition 2: A rigid body is any subset $F_t \subset \mathbb C$ which will be subjected to $H_t$.
I can prove that the most generic proper isometry that can happen in the plane is a rotation around some point (or a pure translation but that's easier I guess). Meaning that for all $H_t$, there exists a point $C_t$ such that $H_t$ is a rotation around $C_t$ of the original $H_0$.
Because $H_t$ is continuous in $t$, there exists the point $I = \lim _{t \rightarrow 0^+} C_t$ which we will call the instantaneous center of rotation at the moment $0$.
From this definition is there a good way to prove that the velocity of point $I$ must be zero at the moment $t =0$?
EDIT: position of a point $X$ is just $\vec H_t(X)$ (measured with the point $(0,0)$ which is fixed in time, because we measure speed with respect to an stationary earth and not with respect to moving points of the body, right?), velocity of a point $X$ is $\frac{d \vec H_t(X)}{dt}$.
EDIT: We should have $H_t (z)= \alpha _ t z + \beta _ t$, $|\alpha_t| = 1$, $\alpha_0=1$ and $\beta _ 0 =0$ but this seems to imply $I = (0,0)$ always.
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/132799/discussion-on-question-by-hellofriends-proof-that-the-instantaneous-center-of-ro).
Answer: In complex notation, as you noticed, $H_t(z)=\alpha_t z+\beta_t$.
By definition, the center of rotation is the unique solution $c_t$ of $H_t(c_t)=c_t$. That is:
$$c_t=\frac{\beta_t}{1-\alpha_t}$$
And the instantaneous center $I$, if it exists, is represented by complex number
$$c=\lim_{t\rightarrow 0}\frac{\beta_t}{1-\alpha_t}\tag{1}$$
First, notice that the hypotheses of continuity on $H_t$, that is, on $\alpha_t$ and $\beta_t$, are not enough to guarantee the existence of that limit. For instance, if $\alpha_t=e^{it}$ and $\beta_t=\sqrt t$ the limit is at one complex infinity and the instantaneous center is at some infinity (in the direction $\frac \pi 4$) in the plane. That's because the shift/glide factor is much larger than the rotation factor, so you would expect the center to be sent to an infinity. In fact a more extreme example is what $\alpha_t=1$, which means your move is a pure shift/translation (there's no center of rotation).
But let's assume that the limit in $(1)$ exists. Then it's not necessarily the origin, as you had initially thought. It can literally be any point in the plane. More precisely, we can design $\alpha_t$ and $\beta_t$ such that the limit is any given point.
Now, by your definition, the velocity of any point $z$ at $t=0$ is given by $$\left.\frac{dH_t z}{dt}\right|_{t=0} = \left.\frac{d\alpha_t}{dt}\right|_{t=0}\cdot z + \left.\frac{d\beta_t}{dt}\right|_{t=0}\tag{2}$$
Now as you know, $\alpha_0=1$ and $\beta_0=0$, thus
$$\left\{\begin{split}
\left.\frac{d\alpha_t}{dt}\right|_{t=0} &= \lim_{t\rightarrow 0}\frac{\alpha_t-1}{t}\\
\left.\frac{d\beta_t}{dt}\right|_{t=0} &= \lim_{t\rightarrow 0}\frac{\beta_t}{t}
\end{split}\right.\tag{3}$$
Now combining $(1)$, $(2)$ and $(3)$ gives the velocity of the instantaneous center at $t=0$ as
$$\begin{split}
\left.\frac{dH_t c}{dt}\right|_{t=0} &= \left.\frac{d\alpha_t}{dt}\right|_{t=0}\cdot \lim_{t\rightarrow 0}\frac{\beta_t}{1-\alpha_t} + \left.\frac{d\beta_t}{dt}\right|_{t=0}\\
&= \lim_{t\rightarrow 0}\frac{\alpha_t-1}{t} \cdot \lim_{t\rightarrow 0}\frac{\beta_t}{1-\alpha_t} + \lim_{t\rightarrow 0}\frac{\beta_t}{t}\\
&= \lim_{t\rightarrow 0}\left( \frac{\alpha_t-1}{t} \cdot \frac{\beta_t}{1-\alpha_t}+\frac{\beta_t}{t}\right)\\
&=0
\end{split}$$
which is the desired result.
Comment: thanks, God bless you
Comment: just so you know, reflections/glide reflections are $H(z) = \alpha_t \bar z + \beta _t$ instead of the function we have here. The only way for the limit to not exist is a pure translation
Comment: Note that reflections are not possible because $H_tz$ converges to $z$ as $t\rightarrow 0$ (IOW, $H_0$ is the identity and it cannot continuously be connected to a reflection, because they have opposite orientations).