Como que excluir do resultado os campos multivalue que não batem com minha query?

Question: Eu tenho alguns documentos indexados como o abaixo:
<code>{
  "doc_desc": "Indexing Child Documents in JSON",
  "doc_id": "379",
  "image_id": [
          "28086# ho hum... this is page 1 of chapter 1",
          "28087# more text... this is page 2 of chapter 1",
          "28088# more text... this is page 3 of chapter 1"
      ]
}
</code>
Quando eu buscar por "ho hum", preciso que o documento retornado seja algo como:
<code>{
      "doc_desc": "Indexing Child Documents in JSON",
      "doc_id": "379",
      "image_id": [
              "28086# ho hum... this is page 1 of chapter 1"
       ]
}
</code>
Então eu posso saber exatamente qual página contêm as palavras que eu estava procurando. Como posso fazer isso?
Em outras palavras... Como que eu excluo do resultado os campos multivalue que não batem com minha query?
OBS: solr-4.10.2 e um data-import (db-data-config.xml) do meu banco de dados SQL Server.
Answer: Existe um ticket aberto no JIRA do Solr desde 2012 para o desenvolvimento dessa funcionalidade, mas ainda está aberto e sem resolução.
Solr: Return only matched multiValued field
Por enquanto isso ainda não é possível de ser feito com o Solr nativo.


Bootstrap columns are stacking, they should be aligned horizontally

Question: My images are in three col-4s, which should make them all fit in a row, but for some reason they stack instead. I was trying to hide the content below md display, but .d-block seems break the row layout.
Image of the inspection
Code:

Answer: Remove the d-block. It's overriding the normal display:flex on the Bootstrap .row. If you want to hide/show responsively use row d-none d-md-flex.
Comment: but then how do I make it display on md+?
Comment: make what display? do you mean you want a different layout on `md` and up? please edit and clarify the question.
Comment: clarification: I was trying to hide the content below md display, but and .block seemed to be the "show" function, so I added that I wanted flexed after the block and it worked out
Answer: Added a flex to the row

Worth noting that without the md clarification to the flex, the images appeared in format below md


Problema ao definir 'allowTimes' no xdsoft DateTimePicker dinamicamente

Question: Bem galera, tô com um problema aqui com o DateTimePicker. Estou tentando definir os horários aceitos dinamicamente com o atributo allowTimes. Pra ficar mais fácil o código tá asism:
$('#datetimepicker2').datetimepicker({
    datepicker: false,
    format: 'H:i',
    onShow: function () {
        var id = $('#id').find('option:selected').val();
        var horarios = PegaHorarios(id);
        console.log("allowTimes:"+horarios);
        this.setOptions({
           allowTimes:horarios
        });
    }
});

Explicando rapidamente o código: Eu pego a 'id' pra fazer uma busca com a função PegaHorarios(), utilizando AJAX, coloquei o 'dataType' como 'script'(já tentei json, html nenhum funcionou), a função me retorna os valores corretamente, que testei via console.log:

allowTimes:['14:00','14:20','14:40','15:00','15:20','15:40','16:00','16:20','16:40','17:00','17:20','17:40']

Então não sei o que fazer... Tentei algumas opções e nada, alguém tem alguma idéia de como consertar?
Obrigado.
A, só pra constar eu copiei e colei esse log na função e o código funcionou...
Edit 1:
Essa é a funcão PegaHorarios.
function PegaHorarios(id) {
var retorno = "";
carregando(true);
$.ajax({
    type: 'POST',
    dataType: 'script',
    url: 'includes/monta-horas.php',
    async: false, // não achei método alternativo
    // Valor default é true então essa opção é desnecessária agora - async: true,
    data: 'id='+id,
    success: function (response) {
        //console.log("Sucesso no envio da solicitação Ajax");
        //console.log(response);
        carregando(true);
        retorno = response;
    },
    error: function (response) {
        //console.log("Erro na Solicitação Ajax");
        //console.log(response);
        retorno = false;
    },
    complete: function (response) {
        //console.log("Solicitação Ajax Completada");
        //console.log(response);
        carregando(false);
    }

});
return retorno;
}

No caso o retorno vem de um código PHP que retorna a String que é mostrada no console.log.
//echo json_encode($retorno);
echo $retorno;

Usei o json_encode quando o dataType foi json e o resultado foi o mesmo.
Não lembro se tinha utilizado o JSON.parse @Marconi, mas utilizei e não funcionou.
Edit 2:
Pra completar um resumo, ao mostrar a horas no datetimepicker eu chamo a função
   PegaHorarios()

com a value de um campo select através de
  $('#id').find('option:selected').val();

Já na função PegaHorarios() eu faço uma solicitação AJAX a uma página PHP que me retorna uma String com var_dump:
   string(97) "['14:00','14:20','14:40','15:00','15:20','15:40','16:00','16:20','16:40','17:00','17:20','17:40']"

Recebo essa string e retorno na função para a
var horarios;

Comment: Qual o retorno da função `PegaHorarios()`? Poste o código dela.
Comment: você já tentou dá um JSON.Parse(horarios)?
Comment: Editei com mais informações, @Marconi como disse ali em cima testei o JSON.parse mas não funcionou. Obrigado pela ajuda.
Comment: @RafaelFontenele você fez a inclusão do Jquery antes do datetimepicker? Fiz um teste aqui funciona tudo normal.
Comment: @Marconi, sim, é tanto que quando eu defino manualmente o allowTimes para allowTimes:['08:00'] (por exemplo) ela funciona. Achei que poderia ser o escopo da variavel horarios e tentei torná-la global, mas de nada adiantou :/. Obrigado novamente.
Comment: @RafaelFontenele tenta usar novamente o JSON.Parse(horarios), eu escrevi errado o "P" era maiúsculo, veja se dá algum erro de console.
Comment: Quando utilizo JSON.Parse diz:     Uncaught TypeError: JSON.Parse is not a function e quando uso JSON.parse diz:    Uncaught SyntaxError: Unexpected token '
Answer: Finalmente resolvi isto. As alterações no código que fiz foram essas:
Primeiro de tudo no meu código PHP onde ele retornava uma String com todos os horários alterei para retornar um:
array()
$retorno = array();

onde cada horário é uma posição no array.
Depois disso removi o:
dataType: 'script',

que mesmo mudando para 'JSON' não funcionava, o que é estranho... Em seguida usei o
JSON.parse(horarios)

que quando usava o dataType como JSON dava erro.
Então fiz uma:
var teste = JSON.parse(horarios);

E usei no final:
this.setOptions({
       allowTimes:teste
    });

E agora finalmente funciona. Vlw!
Resumindo o problema de tudo isso se deve ao fato do allowTimes receber um array e não uma string.


Block websites that provide games

Question: I have Windows Server 2008 and I want to block ALL websites that provide games.  Can I do this using DNS?
Comment: Block **all** websites that provide games? Impossible. Don't believe anyone who tells you differently. You can probably get results that are good enough for most people by using OpenDNS.
Comment: The definition of *"ALL"* will only be as accurate as the site-content-classification-service which you use. No service will identify 100% of the sites providing "games".
Answer: Yes, I use opendns. they already have all these categorized so you just manage it from their website. Put the DNS on your router so that everyone that uses your router as a DNS server will use opendns to resolve IPs.
Answer: You could use opendns as your dns server. They provide content filtering.http://www.opendns.com/
Answer: Your best bet is through a firewall if you have one in your network.
The catch is that if your users are computer savvy enough they can modify the TCP settings on their workstations to use an open DNS server such as Google's and in addition they can edit the hosts files on their windows systems to manually provide domain name resolution and or simply use the IP address in a browser if the site allows it.
A combination of multiple steps will block suggested sites.
Comment: Firewall DNS traffic at the edge so that only your internal DNS servers can query public DNS servers.
Comment: Only Admins / Power Users can modify network settings.  Your users aren't in these groups, right?  Also, I'll +1 what Graeme says.
Comment: yes of course just in speculation here since we are not for certain what the domain policy settings are set as.
Answer: If it is only few websites to block, you can edit the hosts file located in %systemdrive%/windows/system32/drivers/etc/hosts, and add corresponding entries to block the websites.
Comment: Mucking about with the hosts file is about *the* worst way I can think to manage this, or any thing else. If he's the sysadmin, he's probably managing DNS already.
Answer: To be honest, DNS is not the best way to do this. Even though you can make a decent start, you should probably think about a proper web filter if you believe there may be more call for this sort of thing down the line. Web filters aren't expensive these days.

Block websites that provide games


rules for generated files with variable part in filename

Question: There're source files: a.asn1, b.asn1
first I need to preprocess them to add a prefix to identifiers (different prefix for different files).
./prefixASN1.pl -file "foo.asn1" -prefix PREF-

does so and outputs the result to PREF-foo.asn1
Then I need to generate C parsers from PREF-foo.asn1.
./snacc -mm PREF-foo.asn1

will create foo.c and foo.h (filenames without prefix)
How to achive same behavior as this long makefile has:
a.c a.h: AAA-a.asn1
    ./snacc -mm $<
# serialize
a.h: a.c

b.c b.h: BBB-b.asn1
    ./snacc -mm $<
# serialize
b.h: b.c

AAA-a.asn1: a.asn1
    ./prefixASN1.pl -file $< -prefix AAA-

BBB-b.asn1: b.asn1
    ./prefixASN1.pl -file $< -prefix BBB-

with something shorter, like this:
# ??? set PREFIX=AAA for a
# ??? set PREFIX=BBB for b

%.c %.h: $(PREFIX)%.asn1
    ./snacc -mm $<
# serialize
???

$(PREFIX)%.asn1: %.asn1
    ./prefixASN1.pl -file $< -prefix $(PREFIX)

?
I'm using autotools and GNU make.
Answer: I decided that it's more correct to have same prefix in all files.

Renamed the source specs to %.unprefixed.asn1
modified the perl script to allow custom output filename
defined several ASN1_PREFIX_<stem> variables:

_
ASN1_PREFIX_a = AAA-
ASN1_PREFIX_b = BBB-

added rules:

_
%.asn1: %.unprefixed.asn1`
    $(PREFIXASN1) -file $< -prefix "$(ASN1_PREFIX_$*)" -outfile $@

%.c %.h: %.asn1
    ...

_
To pass variable prefix to the rule I prefered Computed Variable Names over Target-specific Variable Values


fetchAllAssoc() is returning only first row

Question: I have a query like this:
  $product_classes = db_select('node_type', 't')->fields('t', array('name', 'type'))->condition('module','uc_product')
  ->execute()->fetchAllAssoc('orig_type', PDO::FETCH_ASSOC);

It will return an array with only first valid table row, however there are more valid rows.
If I use this query, without specified fields:
  $product_classes = db_select('node_type', 't')->fields('t')-:condition('module','uc_product')
  ->execute()->fetchAllAssoc('orig_type', PDO::FETCH_ASSOC);

It will return array with all the valid rows. It is a drupal bug?
Comment: No it's not a Drupal bug, but it could theoretically be a bug in a custom/contrib module, however unlikely that is. It's more likely you've got something wrong and haven't realised it, like the syntax error in your 2nd PHP statement, for example. Instead of executing the queries, cast them to a string and inspect the output. That will give you the actual SQL statements that will be run, which you can easily compare with one another, and try out directly against the db server to make sure the results are the same
Answer: The column name orig_type used in ->fetchAllAssoc('orig_type') must be included in
->fields('p', array('name', 'type', 'orig_type))
too, otherwise only one record will be returned.
Answer: Maybe the reason?
"If the given key appears multiple times, later records will overwrite earlier ones."
https://api.drupal.org/api/drupal/includes!database!database.inc/function/DatabaseStatementInterface%3A%3AfetchAllAssoc/7
Comment: The key is the same in both the cases, so it should returns the same value.


Do any comment modules play well with revisioning?

Question: I'm faced with a situation where we need to keep track of which node revision a comment was made for, so that we can display whether the comment was made for a newer/older revision, or for the one currently being looked at. Do any comment modules allow this in D7?

Use cases

Not the actual use case, but a decent, easy-to-follow approximation of the idea: imagine a bookstore, where users can post comments about books. Typically, when a user asks to see a book's page, he sees the page about the book's newest edition, but in some cases a page for an older edition of the book is presented. In the list of comments for the book, comments are annotated with whether they were made about a different edition than the one being currently looked at, since the comment might not be applicable for other editions.
The actual use case is: teacher A creates learning material LM.v1 and then revises it to LM.v2; teacher B starts using LM.v2 with her class; when A revises LM.v2 to LM.v3, we still need to allow B and her class to use LM.v2, because LM.v3 might not work for B's needs at all (and changing a learning material mid-project is a big no-no); so, when looking at LM.v2, we want to be able to see all comments made about it, but with an annotation if the comment was about LM.v1 or LM.v3, since these may or may not be applicable in the LM.v2 case.
Comment: Did you ever implement a solution?
Comment: We never got around to the commenting, because we never had a good idea what would work reliably in our various situations... Ergo, still a work in progress.
Answer: I'm thinking out loud here... to simplify some aspects, I would probably try something like this first:

set up each 'revision' as it's own content
add a field that will follow each revision (ie. an internal product code that doesn't change even with revisions)
add a Views block to the bottom of the content page for that content type which includes a filter of ALL comments where those comments share the same internal product code but not from the current content - that way direct comments show normally, and then there's a view showing comments from the other revisions
Comment: Thanks, Geoff - that's an interesting solution we hadn't thought of. Unfortunately, it seems a bit cumbersome for the project we're working on (we also have translations in the works etc - resulting in a lot lot lot of nodes etc). It would probably suit very well someone with a less convoluted project, though. :)
Comment: Does your comment basically imply that there is no support for versioning in any comment modules that you know of?
Comment: via Core? No, there isn't. I believe there a few modules that allow revisionned comments, but I'm not sure how much they would offer. Search for 'drupal comment revision'
Comment: Thanks... that's what I found too, but I wanted to double check. We've figured out a hook-based hack that _should_ work - will answer this question with it if that's the case, unless someone else comes up with another solution before that...
Answer: Surprising that this isn't addressed anywhere. I have a similar requirement and can't find any modules in this space. There is a Drupal core issue about this but it hasn't received any love.
Somehow, comments (comment.cid) need to be mapped to node versions (node_revision.vid). This could be done with a custom table, or simply use a field on the comment to track vid. Pros and cons either way. Either way, expose to Views as needed, and implement hook_comment_insert() to add an entry to the table/set the field (and similarly hook_comment_delete()).
Since they are all attached to the node though, I think comments would have to be filtered on node view (see related question), which is far from ideal.
I hope to get something working and update this post with more detail.

UPDATE WITH MORE DETAIL
I ended up going for the field strategy. I added an integer field to the comment fields on my content type (machine name field_comment_node_version), and then added a piece of code to populate it:
/*
* Implements hook_comment_insert().
*/
function MYMODULE_comment_insert($comment) {
  // Populate the comment field for node version
  $node = node_load($comment->nid);
  $wrapper = entity_metadata_wrapper('comment', $comment);
  $wrapper->field_comment_node_version->set($node->vid);
  $wrapper->save();
}

And that's really all there is to it. Now you can use views to get the vid the comment was submitted against.


Speed, Distance and Time GCSE Physics Question. Help please...

Question: It takes me 20 minutes to walk from home to the bus station. I catch the bus from the bus station to work each morning. My bus journey is 10 miles and usually takes 30 minutes. I can catch a bus at 20 minutes past the hour or 10 minutes to the hour. When I get off the bus, it takes me 5 minutes to walk to work.
a) What is the average speed of the bus?
b) I have to be at work for 8:30. What time for the latest I can leave home to be at work on time?
My working out:
10 miles = 0.5h
Speed:
10 / 0.5
= 20mph
How would I use that to work out b?
Thank you and help is appreciated
Comment: 1) I highly recommend that you use MathJax to edit you equations. 2) Assuming you must get to work at 8:30a.m., then in the ideal world where the bus runs every minute, if you were to walk from home, to the Bus station, then immediately get a bus to work, get off the bus and then walk to work, this would take $20+ 30 + 5 = 55$ minutes. So assuming no delays, the latest you can leave home is 7:35a.m. However, for your problem statement, and taking the bus schedule into account, the earliest time to depart home is 7:30a.m, and you arrive to work at 8:25a.m.
Answer: From bus stop to work you need $30+5=35$ minutes. If we subtract $35$ minutes from $8:30$ we get $7:55$. There is $7:50$ bus which you can catch if you leave house at $7:30$.


Envio de formulário via jquery ajax

Question: Tenho um formulário que preciso enviar sempre que der um focusout no input do valor. Porem não estou conseguindo ele dar o submit.
Alguma dica para fazer isso? Agradeço desde já.
<?php foreach ($produtos as $produto) {
            echo "
";
            echo form_open(base_url()."backend/home/alterar_preco/".$produto->id_produto, "id = salva_preco");
            echo "

foto." title=".$produto->nome.">

                ".$produto->nome."

                ".$produto->descricao."

                <input type='text' name='preco_produto' style='width:60px;' value='".number_format($produto->preco,2,",",".")."' placeholder='Preço' class='preco'>

";
    echo form_close();
    echo "
";
} ?>

$(document).ready(function(){
$('.preco').focusout(function(){
    $("#salva_preco").submit(function(){
        var dados = jQuery( this ).serialize();
        $.ajax({
            url: CI_ROOT + "backend/home/salva_preco",
            data: {
                dados:dados,
            },
            dataType: "json",
            type: "POST",
            success: function(data){

            }
        });
    });
});
});

Comment: Pode colocar o HTML renderizado, ie o HTML do lado do cliente para o ``?
Answer: Você está a imprimir inumeras <form> com o mesmo ID. Isso é HTML inválido.
Sugestão:
<?php
    $formNr = 0;
    foreach ($produtos as $produto) {
            $formNr++;
            echo "
";
            echo form_open(base_url()."backend/home/alterar_preco/".$produto->id_produto, "id = salva_preco_".$formNr);

jQuery:
 $('.preco').focusout(function () {
     var dados = $(this).closest('form').serialize();
     $.ajax({
         url: CI_ROOT + "backend/home/salva_preco",
         data: {
             dados: dados
         },
         dataType: "json",
         type: "POST",
         success: function (data) {

         }
     });
 });

Assim, cada vez que fizer foucusout ele faz uma chamada ajax. Na prática sem submeter a form, sem recarregar a página.
Comment: como fazer para enviar para o mysql via ajax sendo que o form é preenchida com dados vindo do mysql.
Answer: Na documentação do $.submit() está escrito:

Bind an event handler to the "submit" JavaScript event, or trigger that event on an element.

Ou seja, atribui um handler ao evento de submit OU ativa o evento submit no elemento. Como você está passando uma função para o submit, ele não irá ativar o evento.
Uma possível solução:
$("#salva_preco").submit(function () {
  var dados = jQuery(this).serialize();
  $.ajax({
    url: CI_ROOT + "backend/home/salva_preco",
    data: {
      dados: dados,
    },
    dataType: "json",
    type: "POST",
    success: function (data) {
      // handler
    }
  });
});

$('.preco').focusout(function(){
   $("#salva_preco").submit();
});

Envio de formulário via jquery ajax


jQuery find content and highlight element

Question: I am getting this error "Please enter your email address." from server side validation after form is submit. I am checkig if this error display "Please enter your email address." i am applying CSS border to spacific input element for highlighting.
My jQuery Code:
jQuery.noConflict();
jQuery(".register_btn").click(function(){
    if(jQuery( ".left_reset_bar li:contains('Please enter your email address.')" )){
        jQuery('.left_reset_bar #jform_email').addClass('highlightError');
    }
});

But code is not working :(
Any ideas or suggestions? Thanks.
Answer: Try this:
jQuery.noConflict();
if(jQuery( ".left_reset_bar li:contains('Please enter your email address.')" )){
    jQuery('.left_reset_bar #jform_email').addClass('highlightError');
}

You don't need to bind click handler, because the function is triggered before form submit. Meaning there wasn't li element with "Please enter your email address." text in DOM, when the function trigger.
Answer: As you mentioned that you are getting the error "Please enter your email address." from server side validation after form is submit. But below mentioned code will check for string "Please enter your email address." on click of register button.i.e., before passing request to server (before form submit).
jQuery(".register_btn").click(function(){
    if(jQuery( ".left_reset_bar li:contains('Please enter your email address.')" )){
        jQuery('.left_reset_bar #jform_email').addClass('highlightError');
    }
});

You should handle this after getting response from server.
Answer: Click event for the register button will fire prior to your server side event. Hence the Class will not be added to your required tag. Inorder to execute as per your requirement move your logic to some function as below and then call your javascript function from the code behind as below mentioned code and then check
function HighlightMessage()
{
//Your logic to add Class
}

Code to call your javascript function from the code behind
this.ClientScript.RegisterStartupScript(this.GetType(), Guid.NewGuid().ToString(), "HighlightMessage();", true);
Add the above line in your server side click event handler of your register button i.e below the line where you set your message "Please enter your email address.".
Answer:
    $(document).ready(function(){
        jQuery(".register_btn").click(function(){alert("dsd");
         if(jQuery( ".left_reset_bar li:contains('Please enter your email address.')" ))
            {
                jQuery( ".left_reset_bar li:contains('Please enter your email address.')" ).addClass('highlightError');
            }
        });
    });

Comment: class is not adding :(
Comment: yes it's add a class on li i test it,please check attached image
Comment: yes now class added but after page reload it gone. i want also after page reload.
Comment: @manan: You have to call your javascript code to add class after your server side event is fired. Please check my above post for that and follow that, you will find your solution. Hope you understand what i mean to say.
Comment: @PrashantKankhara okay let me try.


Reference Request: Finite Borel measure are Radon

Question: Original:
Let $\mu$ be a finite measure on $\mathbb{R}^k$ dominated by the Lebesgue measure.  Does $\mu$ need to be a Radon measure?
Updated Question:
Does anyone have a reference to the fact that if $\mu$ is a finite Borel measure on $\mathbb{R}^k$ then it is a Radon measure?
Comment: In fact, you can change $\mathbf{R}^d$ for a metrisable, separable, locally compact space (or even for just a complete metrisable, separable space, a.k.a. a "Polish space").
Comment: I learnt measure theory from Ash's Real Analysis and Probability. You will find the result there. I also read Cohn's Measure Theory and the result is also there. I grab the book by Klenke (Probability theory) from my shelf (that I really haven't read) and the result is also there. As I said, you will likely find this in any self-respecting book on measure theory.
Comment: @Will If you'd like to post exactly that comment I'd accept it as a reference.
Comment: What does "dominated" mean?
Comment: Also, if $\mu$ is finite, it is certainly a Radon measure (which is a measure with the imposition to be finite on every compact set).
Comment: But why would it be inner and outer regular?  Dominated I mean that $\mu(A)=0$ only if $m(A)=0$ where $m$ is the Lebesgue measure and $A$ is a Borel subset of $\mathbb{R}^k$.
Comment: It is a well-known fact that finite measures defined on $\mathbf{R}^d$ are Radon measures. It should appear on every self-respecting book on measure theory.
Comment: But why should a finite measure be inner regular?
Comment: It's also in "Folland: Real Analysis".
Comment: Theorem 13.6 in Klenke's _Probability theory._
Comment: @FlabbyTheKatsu I have given a proof for the more general statement referred to by Will M.
Answer: So to verify that some measure is a Radon measure we need to verify, that it is inner regular, outer regular and is finite on all compact sets. In your case, since $\mu$ is assumed to be finite, we only need to verify the other two properties. Since we can do that in an even more general setting than $\mathbb{R}^k$ I will do so and prove the following:

If $(X, d)$ is a metric space and $\mu$ is a finite measure on the Borel sigma algeba $B_X$, then $$\mu(A) = \inf\{\mu(O) \mid A \subset O, O \text{ open}\} = \sup\{\mu(F) \mid F \subset A, F \text{ closed}\}$$
  In particular, if $(X,d)$ is complete and separable, then $$\mu(A) = \sup\{\mu(K) \mid K \subset A, K \text{ compact}\}$$

Proof: Define the set $$\mathcal{G} = \{A \in B_X \mid \forall \epsilon>0 \colon\exists F \subset A \subset O \colon \mu(O\backslash F) < \epsilon\} \tag{$\star$}$$ where the sets $F$ are closed, and the sets $O$ are assumed open in the definition of $(\star)$. First note, that $\mathcal{G}$ contains all closed sets. Indeed, if $A$ is a closed set, just choose $F = A$ in $(\star)$ and consider the open sets $O_k = \{x \in X \mid \text{dist}(x, A) < 1/k\}$, where $\text{dist}(x, A) = \inf\limits_{a \in A} d(x,a)$. Since $O_k \searrow A$ (since $A$ is closed) we may find an index $K$ such that $\mu(O_K) < \mu(A) + \epsilon$ by continuity of finite measures from above. So set $O = O_K$. Thus all closed sets are indeed in $\mathcal{G}$. Furthermore, $\mathcal{G}$ is a sigma algebra: It is clear, that $X \in \mathcal{G}$. If $A \in \mathcal{G}$, then let $\epsilon > 0$ and let $F \subset A \subset O$ be given such that $\mu(O \backslash F) < \epsilon$. Now consider the closed set $C = O^c$ and the open set $U = F^c$, then $C \subset A^c \subset U$ and $\mu(U \backslash C) = \mu(O \backslash F) < \epsilon$, so $A^c \in \mathcal{G}$. Last but not least, if $\{A_n\}_n \subset \mathcal{G}$ is a countable collection of sets, then set $A = \bigcup A_n$. Let $\epsilon > 0$, then for each $n \geq 1$ we may find $F_n \subset A_n \subset O_n$ such that $\mu(O_n \backslash F_n) < 2^{-(n+1)} \epsilon$. Set $O = \bigcup O_n$ and $F = \bigcup\limits_{n = 1}^N F_n$ where $N$ is so big, that $\mu(\bigcup F_n) < \epsilon/2 + \mu(F)$ (this is possible by continuity from below). Now note, that \begin{eqnarray}
\mu(O \backslash F) = \mu(O) - \mu(F) < \mu(O) - \mu(\bigcup F_n) + \epsilon/2 = \mu(\bigcup O_n \backslash \bigcup F_n) + \epsilon/2 \\ \leq \mu(\bigcup O_n\backslash F_n) + \epsilon/2 \leq \sum \mu(O_n \backslash F_n) + \epsilon/2 < \epsilon
\end{eqnarray}
Hence $\mathcal{G}$ is a sigma algebra containing all closed sets, which form a generator for $B_X$. Thus $B_X = \mathcal{G}$.
Now assume $(X, d)$ to be complete and separable. Consider a countable dense subset $\{x_n\}_n \subset X$ and the closed delta-balls $K(x_n, \delta) = \{x \in X \mid d(x_n,x) \leq \delta\}$. For all $m \geq 1$ fixed we have $X = \bigcup\limits_{n \geq 1} K(x_n, 1/m)$. Thus if $\epsilon > 0$ is given, then for all $m \geq 1$ there exists $N_m$ such that $$\mu \big(X \backslash \bigcup\limits_{n = 1}^{N_m} K(x_n, 1/m) \big)< 2^{-m}\epsilon$$
Let $K = \bigcap\limits_{m \geq 1} \bigcup\limits_{n=1}^{N_m} K(x_n, 1/m)$, then $\mu(K^c) \leq \epsilon$ by construction (check this). Moreover, it is clear, that $K$ is closed and it is in particular totally bounded. Thus $K$ is compact. Now if $A \in B_X$ we can find a closed set $F \subset A$ such that $\mu(F) > \mu(A) - \epsilon$. But then $F \cap K$ is compact with $F \cap K \subset A$ and satisfies $\mu(F \cap K) > \mu(A) -2 \epsilon$.
This answers your question, since $\mathbb{R}^k$ is of course a separable, complete metric space.


Is there a Kubota-Leopoldt $p$-adic zeta function implementation in SageMath?

Question: Exactly as in the title. I am learning the $\mathbb{Z}_p^\times$ measure-theoretic construction of $p$-adic $L$-functions and was wondering if there was an `easy' way produce some example computations with these in the specific case of the interpolated $p$-adic Riemann zeta function.
Any code for this or suggestions for how one might algorithmically implement this would also be very welcomed!
Thank you in advance!
Answer: Interestingly, I just completed my dissertation on this exact topic and implemented the Kubota-Leopoldt $p$-adic zeta function into Sage. I'm not sure if this is the way you wanted to implement it, but I worked through Jacinto-Williams' fantastic notes on the topic - which I highly recommend (http://www.ltcc.ac.uk/media/london-taught-course-centre/documents/Number-Theory---Full-Lecture-Notes-2017-18.pdf).
Note that this more measure-theoretic approach is quite different to Koblitz's which @Merosity cites in another answer.
My 'code' is not at all efficient (rather its purpose was more illustrative) but it did seem to agree with expected results provided the precision was kept sufficiently large.
I've included my construction for it in the pictures attached if you'd like to improve it!
Cheers :)
Comment: Welcome to MSE! Nice first answer ^_^. I've edited your answer to include the photos inline rather than linked, but if you could find a way to add a pdf of the relevant pages, that would be best. (+1) btw
Comment: thank you for the edit! I was wondering how to get the pictures to display properly so you've really helped me out there :D
Answer: According to the p-Adics section of the reference manual there is nothing I could find to do with zeta functions nor integration.
At any rate, here's a suggestion on algorithmically getting an arbitrary level of accuracy on your integral. In order to be called a p-adic measure we require it to be a bounded p-adic distribution, and this is enough to imply that the limit of Riemann sums of a continuous function is independent of the choices of representatives. It can then be easily shown that we can approximate our integral by an integral of a locally constant function that approximates our function.
By continuity we know there exists a $M$ so that $|x-a|\le p^{-M}$ that gets us $|f(x)-f(a)|\le p^{-N}$, and so in particular the most convenient choice is for $a \in \{0,1,..., p^M-1\}$ define the locally constant function $g(x)=f(a)$ for $|x-a|\le p^{-M}$.
Specifically, let's suppose your measure is bounded $|\mu(U)|_p\le p^{-K}$ for all compact open $U \in \mathbb{Z}_p^\times$ then $$\left|\int f \mu -\int g \mu\right|\le p^{-K-M}$$ and we have the exact expression for a sum that approximates $\int f \mu$ which shouldn't be difficult to code,
$$\int g \mu = \sum_{\substack{0\le a <p^N \\ a+p^N \mathbb{Z}_p \subseteq \mathbb{Z}_p^\times}} g(a)\mu(a+p^N \mathbb{Z}_p) = \sum_{a_0=1}^{p-1} \sum_{a=0}^{p^{N-1}-1} f(a_0+ap) \mu(a_0+ap+p^N \mathbb{Z}_p) $$
I can elaborate on more details here, but I highly recommend you see chapter 2, sections 3 and 5 of Koblitz's p-adic Numbers, p-adic Analysis, and Zeta-Functions for more information and proofs on the theorems above.


Unable to install SSMS with Azure Data Studio 18.9.1 - getting fatal error

Question: I am trying to install Sql Server Management Studio with Azure Data Studio 18.9.1, but I always get error as below in screenshot:

Also, I am logged-in as an administrator on my Windows 10 Pro laptop, so I don't understand that this is an admin access issue.
Please help me rectify the error and install SSMS successfully. I have googled the error but I unable to solve this issue. I reinstalled my VS2019 full setup with modify and repair options but still I am unable to install SSMS 18.9.1.
In the log file this message is there:
"mainviewModel.OnBundleAction: Bundle action failed: Fatal error during installation (0x80070643)"
Comment: So when you click on the link that says `Click here for the log file` what does the log file say happened? Do you have anti-virus software "helping" you by scanning that folder while you're trying to install files into it? Since Windows Vista UAC and privilege separation have been a thing - when you launch the setup program do you right-click on it and select `Run as Administrator` to get a proper Administrator token?
Comment: @AlwaysLearning I updated the ques with log file error msg..
Comment: Right click on SSMS an execute "Run as Administrator"
Comment: @Max already tried that many times
Answer: So, I was able to resolve my issue by uninstalling anti virus (Symantec End Point Protection). First, I turned off the anti virus but still the issue was not resolved. Finally, I uninstalled my anti virus and then I was able to install SSMS 18.9.1


Como verificar no console as conexões websockets abertas?

Question: Eu estava analizando como o StackOverflow verifica por atualizações na lista de perguntas, mas nada aparece no console (Firebug), por isso, imagino que estejam utilizando websockets.
Então me surgiu uma dúvida: é possível verificar as conexões websockets abertas através do console (do próprio navegador ou pelo Firebug)? Como?
Answer: Se você estiver usando o Google Chrome pode fazer:

Abra a janela de Ferramentas de Desenvolvedor, atalho: CTRL + Shift + I.

Clique sobre a aba Network.

Clique sobre a aba WebSockets.

Clique no botão Filter.

No Firebug é possível fazer isso a partir da versão 2, como citado no roadmap.
Comment: Parece que no Firebug ainda não é possível. No roadmap o websockets ainda está com o status `not started` =s


Many "unresolved external symbol" after installing SFML on Visual Studio 2019

Question: I want to get started in creating some games with graphics. From what I've gathered from the internet it seemed to me that SFML is the best tool to get for beginners. I tried to follow the steps indicated in the tutorial SFML and Visual Studio (only the DLL setup) and nothing whatsoever...
I've already spent a lot of hours trying to figure out how to do this thing with no success and I hope that, with you here, I'll be able to solve it. These are the errors I get:
This is my setup:

Thank you in advance :)
Comment: Your screenshot makes it clear. You were compiling for 32-bit (/MACHINE:x86) and the linker is complaining that you're giving it 64-bit libraries ("library machine type x64 conflicts with target machine type x86")
Comment: From the [SFML download page](https://www.sfml-dev.org/download/sfml/2.5.1/), which version exactly did you download? Also, which platform are you compiling for? x86 (32 bit) or x64 (64 bit). That must match the libraries you downloaded.
Comment: I downloaded Visual C++ 15 (2017), I have Visual Studio 2019 installed and I checked for Visual C++ Redistributable and I have 2015-2019 both for x86 and x64. I also checked the platform and it is for 64 bits
Comment: And which Visual C++ 15 (2017) variant did you download? There are two, and your download must match the platform you're compiling for.
Comment: I downloaded the x64 version, because I thought it has to match my OS variant... but even so, no result
Comment: Windows 64 bit can run both 32bit and 64bit executables. But the version needs to match the platform you're compiling against. Although typically it tells you something about incompatible architectures.
Comment: Can you enable [Verbose linking](https://learn.microsoft.com/en-us/cpp/build/reference/verbose-print-progress-messages?view=msvc-160) and/or provide us the full linker commandline used? As well as a textual copy of the output window (which is distinct from the error window and contains more information)
Comment: I downloaded the x32 bit version and tried to repeat the exact same steps I did with x64... Good news: errors disappeared
Bad news: new errors appeared :) only 2 now, but still regarding the linker
Answer: Alright, I solved it :D the main problem was that I had the x64 version and stuck with it for the rest of my "solving quest"... The tutorial from SFML website is clear and correct, it was just my mistake because I was thinking of something else...
Note for who might run into this problem in the future: the version of SFML from their website (x32/x64) is not your PC system type, it is the "target audience" you are working for, the platform you are compiling/working on. Thank you, Botje, for helping me and making me search more into the problem :D


OSX 10.8.4 xcode Sigabrt

Question: Just got done updating my box to osx 10.8.4 and everything appeared to be functioning fine until I began using xcode. The first time I build a project it runs on the simulator fine. The second time I build the same project I get a sigabrt in main. I tried catching all exceptions but none are being thrown. This happens on existing projects or even brand new ones. I tried 'Reset content and settings' on simulator, rebooting the machine, and cleaning the project. All of which had no effect. Considering re-installing xcode, but wanted to see if anyone else can reproduce or had any ideas.
Answer: Update your Xcode. Xcode 4.6.3 solves the issue.
If you can't, TUAW has a solution (or workaround, however you want to see it).
Comment: Great find. I am just happy to confirm I am not the only one. Saved me an afternoon of pointlessly installing xcode.
Comment: You are not the only one... definitely...

OSX 10.8.4 xcode Sigabrt


Find points of discontinuity of $x(x-1)^{2/3}e^{\sqrt[3]{x}}$

Question: I want to find the points of discontinuity for the following function:
$$f(x)=x(x-1)^{2/3}e^{\sqrt[3]{x}}$$
My textbook says it can be derived for every number except $0$ and $1$ which could be points of discontinuity. I have no idea how it reached that conclusion without deriving the function first.  Now, I find the first derivative by using the product rule:
$$f'(x)=e^{\sqrt[3]{x}}\left[{\frac {x^{4/3}-x^{1/3}+5x-3}{3(x-1)^{1/3}}}\right]$$
My textbook asks for the domain. I know that $\sqrt[3]{x}$ are defined for any $x$ so I focus on the denominator which should not be equal to $0$, therefore $3(x-1)^{1/3}\neq0\implies x-1\neq0\implies x \neq 1$. Wolfram Alpha says the domain should be $x>1$.
Any hints on what I'm doing wrong?
Comment: As for domain, see [Rational powers](https://en.m.wikipedia.org/wiki/Exponentiation#Power_functions). Then $(x-1)^{2/3}$ is defined only for $x >1$.
Comment: The non-differentiable points could be spotted via the fraction in the definition of derivatives.
Comment: @xbh $\lim_{h\rightarrow0}{\frac{f(x+h)-f(x)}{h}}$ you mean by replacing, e.g. $f(x) =x$ (which is a term of the product of the function)?
Comment: Probably… I am not sure what you mean… I was saying that you could verify the fact by directly computing the limit in the definition.
Comment: However for $2/3$-power, $x <0$ would not cause any ambiguity in set of real numbers. So you might be correct.
Answer: Probability Wolfram assumes $(x-1)^{2/3}$ defined only for $x-1\ge 0\implies x\ge 1$.
Comment: Thanks this is correct, now I need to investigate why. I thought that $(x-1)^{2/3}=\sqrt[3]{(x-1)^2}$ would always be defined
Comment: I agree there is something unclear, as anyway the cubic root is defined everywhere in $\Bbb R$, so $(\sqrt[3]{x-1})^2$ has $\Bbb R$ as domain as well.
Comment: No idea what's going on. Very unclear (Wolfram not the answer).
Comment: @Cesare It is solely a matter of definition $x^{2/3}$ is well defined for any $x\in \mathbb{R}$ but in general $x^{m/n}$ is not therefore in general the limitation $x\ge 0$ is assumed.
Answer: Probably Wolfram assumes $(x−1)^{2/3}$ has abranch cut in $x=1$


Zend Routing -- Grabbing Variables from URL with Ampersands and not Slashes - Tapjoy

Question: I'm currently creating attempting to integrate with the Tapjoy API with their callback URL request which comes in this form:
<code><callback_url>?snuid=<user_id>&currency=&mac_address=<mac_address>&display_multiplier=<display_multiplier>
</code>
However, using ZF1 --
the Zend_Controller_Router_Route seems to be dependent on the variable separation being delimited by slashes and not ampersands.
Here is my current Route code
<code>>     $router->addRoute( 'api-tapjoy', new Zend_Controller_Router_Route('api/tapjoy?snuid=:snuid&mac_address=:&mac_address&display_multiplier....etc.etc,
array('controller'=>'api', 'action' =>'tapjoy')));
</code>
Whenever I remove the ampersands and initial question mark  and replace them with slashes it works. How can I properly receive the HTTP Request whilst using ampersands?
Answer: Looks like I figured it out. It has nothing to do with ampersands and slashes, etc. but rather that my Route wasn't created properly.
I was thrown off by this documentation on ZF1's website about routers:

The first parameter in the Zend_Controller_Router_Route constructor is
  a route definition that will be matched to a URL. Route definitions
  consist of static and dynamic parts separated by the slash ('/')
  character. Static parts are just simple text: author. Dynamic parts,
  called variables, are marked by prepending a colon to the variable
  name: :username.


Finding the probability of survival of an insurance company

Question: I was given as a homework exercise the following problem:

however, I came into a disagreement with one of my classmates. Given that the solution is not shown, I was wondering whether mine was correct. I performed a simulation of 1000 runs and obtained a probability of survival of approximately $0.931$, however, intuitively, this seems very high.
Answer: Here is my take.  Using vectorization can make this a little easier.  Comments indicate my logic
import numpy as np
import numba

@numba.jit
def sim():

    # Draw the number of claims for the entire year in advance
    num_claims = np.random.poisson(lam = 10, size = 365)

    #Compute the cost of the claims
    cost_of_claims = np.zeros_like(num_claims)
    for i,day in enumerate(num_claims):
        cost_of_claims[i] = np.random.exponential(scale = 1000, size = day).sum()

    # Capital is where we start plus how much we gain/lose on the ith day
    capital = 25000.0 + np.cumsum(11000.0-cost_of_claims)

    # Any negative?
    return np.min(capital)<0

sims = [sim() for _ in range(1000)]

1000 iterations takes less than a second and winds up with 7.6% of the runs having an instance where the insurance company has less than 0 capital.
Here is a plot of the simulations

And here is one with a confidence interval
Comment: I tried running this on python, but the function returns a boolean, how did you get the probability?
Comment: Take the average.  Python treats booleans as ints when you do math on them.  Alternatively, just count the Trues and Falses.
Answer: Your answer looks plausible to me. I got a similar answer to you when I did it in R; about a 91% of avoiding ruin (getting to $\leq 0$ capital).

The plot above shows a few such simulations.
nsim = 10000
initcap = 25
dclaimrate = 10
meancl = 1
prem = 11
dpyr = 365

mincap = replicate(nsim,{
  nclaim = rpois(1,dclaimrate*dpyr)
  t.claim = sort(runif(nclaim,0,dpyr))
  claimsize = rexp(nclaim,1/meancl)
  cap = initcap + t.claim*prem - cumsum(claimsize)
  min(cap)
})
mean(mincap>0)

100K simulations took 83 seconds on my laptop, 1000 simulations takes just under a second. This operates in units of $1000. It make use of the connection between the Poisson process and the uniform.


Vector calculus in statistics

Question: I'm teaching a class on integration of functions of several variables and vector calculus this semester. The class is made up most of economics majors and engineering majors, with a smattering of math and physics folks as well. I taught this class last semester, and I found that a lot of the economics majors were rather bored during the second half. I was able to motivate multiple integrals by doing some calculations with jointly distributed random variables, but for the vector analysis part of the course the only motivation I could think of was based on physics.
So I'm wondering if anybody knows a statistical/probabilistic interpretation of any of the main theorems of vector calculus: Green's theorem, Stokes' theorem, and the divergence theorem.  Part of the problem is that vector fields don't seem to come up very often in probability theory, let alone divergence, gradient, or curl.  I also posted this question on math.stackexchange a few days ago, but I'm still looking for more ideas.
Comment: Vector fields actually appear in a fundamental way within the answer at http://stats.stackexchange.com/questions/29121/intuitive-explanation-of-unit-root/29129#29129, showing that they can crop up in unexpected places.  Moreover, the comment thread after that answer suggests (to me, at least) that a very well established statistician would have appreciated this theory better had he had more training and practice in geometric and analytic methods.
Comment: I have an MA in econ and I never recall needing divergence or curl (or the theorems you listed). If there are applications (perhaps to a DSGE), it would be at the PhD level. However, gradients are used in optimization, which is important for economics and portfolio management.
Comment: It's very difficult to get even physicists interested in the theorems and their proof, even with Stokes' theorem, which is very important in physics. I have no recollection of the proof at all! Yet I remember how to use it. So, I wouldn't worry too much about making it interesting, it's basically impossible.
Answer: One example you could look into is quasi-likelihood. The discussion of these in McCullagh & Nelder: Generalized Linear Models uses (for the theoretical part) gradients and path-integrals in an essential way!  See chapeter 9 of that book.
Answer: I doubt many statisticians will have to use vector calculus as it is taught for physics and engineering. But for what it's worth here are a few topics that would use it, at least tangentially. The underlying theme here is that holomorphic functions from complex analysis, which are composed of harmonic functions, are intimately linked through the Cauchy Riemann equations to both Stokes' and Green's theorems. These functions can be studied both by examining the the interior of their domain along with their boundary.
Probability Currents. This isn't just for quantum mechanics. In general, probability diffusions arise when studying time-varying probability distributions which change smoothly. This includes stochastic version of classical systems, such as the heat equation, Navier Stokes for fluid dynamics, wave equations for quantum mechanics, etc. Examples of equations include the Fokker-Planck equation and Kolmogorov Backwards/Forwards equations involve divergences, which in turn relate to heat equations, Feynan-Kac integrals, dirichlet problems and Green's functions. The keywords here are complex harmonic functions, which satisfy the mean value property, which in turn is a consequence of Green's integral theorem and Stokes' theorem. A classical example is calculating the exit time of a diffusion from a closed region, which reduces to evaluating integrals on the boundary of the surface and exploiting harmonicity within the region.
The main example here is problems involving Brownian motion, and in general the wide class of Ito Diffusions. A wonderful (and eccentric!) book on this is Green, Brown and Probability by the legendary Kai Chung.
The Disintegration Theorem for probability is implicity Stokes' Thoerem, in that one disintegrates a 3 dimensional probability measure onto the boundary of the surface that encloses its support.
In statistical mechanics and in markov random fields, there is a large prevalence of conservation in the form of currents. The Ising Model, especially at criticality, and its relatives can be studied from the point of view of discrete harmonic and holomorphic functions. From the Cauchy Riemann equations, one recovers both Green's Theorem and Stokes's theorem, in that currents are both divergence free and curl free, which together imply that the underlying field is holomorphic. A great reference on this is from the work of Smirnov, Chelkak and Dominil-Copin.

Vector calculus in statistics


HTML and corresponding DOM Tree

Question: I have to create a DOM Tree for class and just wanted to know if I did it correctly before I turn it in. If anyone could confirm for me that it is correct or point out what I did wrong I would appreciate it. Here is the code:
<!DOCTYPE html>

<title>Lab 2</title>
<link href="lab2.css" type="text/css" rel="stylesheet">

Images

<button onclick="change()" id="changeImage">Display Image</button>

The image is blank

Comment: The `homework` tag is deprecated. Please do not use it.
Answer: The img and the h2 are children of the div, not siblings.
Also, what happened to the button and the br?
Comment: @user1157541 - They sure are.
Comment: Ah thank you. That makes sense. Are the button and br children as well?

HTML and corresponding DOM Tree


Seasonal time series prediction formula

Question: I've got this prediction problem for daily data across several years. My data has both yearly and weekly seasonality. It's also stationary.
I tried using the following recurrence:(which I just came up with, from nowhere if you like) xn = 1/4(xn-738 + xn-364 + xn-7 + 1/6(xn-1+xn-2+xn-3+xn-4+xn-5+xn-6)
Basically, I am taking into consideration some of the previous days in the week before the day I am trying to predict and also the corresponding day a year and two years earlier. I am doing an average over them.
I got the following histogram of residuals:

Why or Why not would such a formula be a good idea and can I improve this FOR example by adding some terms sampled from a distribution or in another way? Thanks!
Comment: Stationary series can't be seasonal. Please double check your data.
Comment: Yeah, I didn't realise that stationarity had such a technical definition...I didn't really check the stationarity But maybe people could help me regardless of that condition? Thanks!
Answer: Based on the recurrence formula you've come up with, you seem to be trying to reinvent an Auto-Regressive model AR(p), which is essentially any model of the form:
$X_n = a_1 X_{n-1} + a_2 X_{n-2} + a_3 X_{n-3} + ... a_p X_{n-p}$.
Although your intuition is correct and your approach is on the correct path, there is a more systematic way of arriving at the same type of model that you are trying to achieve, using ARIMA and Seasonal ARIMA models.
Comment: Hi Alex and thanks for the answer!
I tried using ARIMA and Seasonal ARIMA but the problem is that ARIMA cannot capture double seasonality, so I tried to come up with something myself. Any idea how one could find the optimal a1,...,ap ? Optimal wrt to mean squared residual error for example
Comment: @SorinTirc I don't know of any ARIMA model that can capture multiple seasonalities (In theory a really high order ARIMA model could, but in practice that would lead to bad results). You should try TBATs or Facebook Prophet - but those models use completely different approaches from the auto-regressive models.

Seasonal time series prediction formula


Issues migrating site config at various points in project lifecycle

Question: Issues migrating site config at various points in project lifecycle
Hi
My team and I have begun a new project for our company using the very latest version of Drupal 8 (version 8.5.6)
We wanted to use config migration in order to carry config changes from one developer across to another seamlessly and across to staging and production environments.
We are in the middle of testing the migration workflow and have run into a problem.
I started off the project by doing a standard Drupal 8 installation. I then did a migrations export (drupal ce), committed this to the repository.
My colleague proceeded to install Drupal also, also a standard install, composer install, drush cr etc., and then pulled the latest changes and ran drupal ci and ran into an error, namely:
[ERROR] An error occurred while trying to write the config file: "Entities exist of type Shortcut link and Shortcut set Default. These entities need to be deleted before importing."

Prior to this we had an additional issue where Drupal complained about mismatched UUID's. We got around this by updating his UUID as follows:
Error received:
[ERROR] An error occurred while trying to write the config file: "Site UUID in source storage does not match the target storage.

Fixed with:
drush config-set "system.site" uuid "42e3c541-5ebc-4ec9-a8f0-e8c6ad1ccfb7

The above UUID was gained from my installation.
So now we are left with the first error explained above.
We tried deleting the shortcuts manually, as suggested in several places on the internet, but this caused his system to completely break.
I also thought possibly that instead of him doing a clean, standard install at the start of the work that he should have used a snapshot of my initial installation, and when we move the app to staging and/or development it will follow suit that we use backups for the initial setup to ensure the DB is in sync with regard to UUIDs, but I am not convinced this is the correct way to do it.
So, we are a little lost on exactly what is the recommended workflow for migrations, with the view that we will be using the workflow going into production also, e.g. after launch we will want to use config migration export/imports to apply changes made locally.
Comment: If you install with something other than standard profile, that error regarding the shortcuts will disappear. Minimal should be fine I think. A clean install definitely wouldn't break just by deleting a couple of shortcuts, so you might have a deeper problem to dig out
Answer:
My colleague proceeded to install Drupal also, also a standard install, composer install, drush cr etc., and then pulled the latest changes and ran drupal ci and ran into an error, namely:

Don't do that. Config import/export is meant to be used for the same site. That's exactly why the site UUID check exists, that's to tell you that what you are trying to do doesn't work.
Either you need to sync the database or you need to use something like https://www.drupal.org/project/config_installer to install based on an existing set of configuration.
Usually the process is that content and configuration flow in opposite direction. You have your production site where new content is created, from time to time you want to sync the full DB down to your staging/development and then you have configuration changes that you are creating locally and then deploying to dev/staging/production.
See also presentations like https://events.drupal.org/vienna2017/sessions/advanced-configuration-management-config-split-et-al for example.


how to display the contents of a file from highest to lowest

Question: option= input("alphabetically(a), high to low(b)")
if option == "a":
    with open('Class4.txt', 'r') as r:
        for line in sorted(r):
            print(line)

elif option == "b":
            def score(line):
                return int(line.split(',')[1])

            with open('Class4.txt', 'r') as r:
                for line in sorted(r, key=score, reverse=True):
                    print(line)

I was able to display aplhabetically but was not able to display high to low
the file class 4 contains variable name and score
ab 9
z 4
b 6
a10
Comment: Is that the exact contents of your Class4.txt file? Why are you doing `line.split(",")` when the file doesn't have any commas in it?
Comment: You are splitting on commas instead of whitespace.
Comment: yes thats the exact contents
Comment: @Kevin if i remove the coma should that solve the problem
Comment: @python, I don't know, when you remove it does your code start working?
Comment: @Kevin when i remove the error message goes ut nothing is displasyed
Comment: Wait, there was an error message? You didn't mention that before. What did it say?
Comment: @Kevin it said Traceback (most recent call last):
  File "C:\Users\a\Desktop\Computing ca\task 3 aplha.py", line 14, in
    for line in sorted(r, key=score, reverse=True):
  File "C:\Users\a\Desktop\Computing ca\task 3 aplha.py", line 11, in score
    return int(line.split(","))
TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'
Answer: The file contains empty lines and you are trying to split it into a list and accessing the second element. This is why you are getting IndexError.
So ignore the empty lines.
And also you should do line.split() since there is no comma
option= input("alphabetically(a), high to low(b)")
if option == "a":
    with open('Class4.txt', 'r') as r:
        for line in sorted(r):
            print(line)

elif option == "b":
        def score(line):
            if line != '\n':
                return int(line.split()[1])

        with open('Class4.txt', 'r') as r:
            for line in sorted(r, key=score, reverse=True):
                print(line)

Comment: hi the code display displays it  in alphabetical order even if b is chosen it just displays it backwards
Comment: for this particular data the result for both options is same. Try with some other data then you will see the difference


Diagonalise a matrix and show the formula

Question: I have diagonlised P to get
$$P=\left(\begin{matrix}
-1 &0 &0\\
0 &0 &0\\
0 &0 &1
\end{matrix}\right)$$
however am unsure on how to proceed, would appreciate any help!
By diagonalising P by a transformation of similarity, show that
$$    e^{Pt} = (I_3 - P^2) + P \sinh( t) + P^2 \cosh(t)$$
when
$P$ is the matrix
$$P=\left(\begin{matrix}
0 &1 &0\\
0 &0 &1\\
0 &1 &0
\end{matrix}\right)$$
and where $I_3$ is the identity matrix of a $3\times3$
Comment: Downvoted for seemingly deliberate vandalism of your own post. Please ping me if someone rolls back to the old version.
Comment: @NilsMatthes I've rolled it back.
Comment: @jim: thanks. undone my vote
Answer: Edit: You do not need to diagonalize, actually. Simply compute and observe that
$$
P^3=P.
$$
To figure this out, of course, one might need to compute the eigenvalues: $-1,0,1$. So actually, $P^3-P=0$ is nothing but Cayley-Hamilton.
Note that
$$
P^0=I_3\qquad P^{2n}=P^2\qquad P^{2n-1}=P\qquad\forall n\geq 1.
$$
So
$$
e^{tP}=\sum_{n\geq 0}\frac{t^nP^n}{n!}=I_3+\sum_{n\geq 1}\frac{t^{2n}}{(2n)!}P^2+\sum_{n\geq 1}\frac{t^{2n+1}}{(2n+1)!}P
$$
$$
=I_3 +(\cosh t-1)P^2+\sinh t P=I_3-P^2+\sinh tP+\cosh tP^2.
$$
Note: if you do absolutely need to diagonalize, go ahead and write
$$
P=AQA^{-1}
$$
where $Q$ is the diagonalized form you found.
Then all the previous argument holds for $Q$ and you find
$$
e^{tQ}=I_3 +(\cosh t-1)Q^2+\sinh t Q=I_3-Q^2+\sinh tQ+\cosh tQ^2.
$$
It only remains to see that
$$
AQ^nA^{-1}=(AQA^{-1})^n=P^n\qquad\forall n\geq 0
$$
to deduce that
$$
e^{tP}=Ae^{tQ}A^{-1}=I_3 +(\cosh t-1)P^2+\sinh t P=I_3-P^2+\sinh tP+\cosh tP^2.
$$
Comment: Hi @Julien thanks for your help that looks great! Do you know any other method to get to this answer without using Cayley Hamilton theory? Thank you
Comment: @Jay What do you mean: without Cayley-Hamilton theory? Without diagonalization?
Comment: I don't think julien used the Cayley-Hamilton theorem.
Comment: @Jay There you go. No diagonalization. What do you think?
Comment: You do need to diagonalize, if the problem statement begins, "By diagonalising $P$...."
Comment: @GerryMyerson Sure. But it's still useless.
Comment: @GerryMyerson Note that I did it like this first, using the diagonalized form given by the OP. But then the OP asked me a question which seemed to mean that he/she was curious about an alternative.
Comment: Perhaps it will bridge the apparent gap if we note that if $P,Q$ are similar matrices, then they satisfy exactly the same polynomial equations.  My guess is the problem suggest the diagonalized form (which is ambiguously also labeled $P$ in the Question) because checking the satisfaction of a polynomial equation can be done diagonal-entry-by-diagonal-entry.
Comment: @hardmath What gap?
Comment: @julien: By "gap" I mean your difference of opinion as to diagonalization being unneeded or "still useless".
Comment: @hardmath Ah, ok. I was exaggerating a little bit when I said diagonalization is useless. Like I said in my answer, the natural steps consist in computing the characteristic polynomial first. Like you would do to diagonalize anyway. But then you obser the Cayley-Hamilton gives this neat relation which allows to compute the exponential easily. If there was no such nice relation, diagonalization would be the way. But since it's here, we should use it. That's what I was taught and it's pretty helpful, so I can't help it.
Answer: Given:
$$P=\left(\begin{matrix}
-1 &0 &0\\
0 &0 &0\\
0 &0 &1
\end{matrix}\right)$$
By diagonalising P by a transformation of similarity, show that
$$    e^{Pt} = (I_3 - P^2) + P \sinh( t) + P^2 \cosh(t)$$
If we diagonalize the matrix $P$, we arrive at:
$$P = S J S^{-1} = \begin{bmatrix} 1 & 1 & 1 \\ -1 & 0 & 1\\ 1 & 0 & 1\end{bmatrix} \cdot \begin{bmatrix} -1 & 0 & 0 \\ 0 & 0 & 0\\ 0 & 0 & 1\end{bmatrix} \cdot \begin{bmatrix} 0 & -\frac{1}{2} & \frac{1}{2} \\ 1 & 0 & -1\\ 0 & \frac{1}{2} & \frac{1}{2}\end{bmatrix}$$
Note: $\cosh t = \frac{1}{2}(e^{-t} + e^{t}) ~ \text{and} ~ \sinh t = \frac{1}{2}(-e^{-t} + e^{t}) ~\text{and}~ P^{2} = \begin{bmatrix} 0 & 0 & 1 \\ 0 & 1 & 0\\ 0 & 0 & 1\end{bmatrix}$.
Using this diagonalization, the matrix exponential is given by:
$$\displaystyle e^{Pt} = e^{S J S^{-1} t} = \begin{bmatrix} 1 & -1 & 1 \\ -1 & 0 & 1\\ 1 & 0 & 1\end{bmatrix} \cdot \begin{bmatrix} e^{-1} & 0 & 0 \\ 0 & 0 & 0\\ 0 & 0 & e^{t}\end{bmatrix} \cdot \begin{bmatrix} 0 & -\frac{1}{2} & \frac{1}{2} \\ 1 & 0 & -1\\ 0 & \frac{1}{2} & \frac{1}{2}\end{bmatrix} = \begin{bmatrix} 1 & 0 & -1 \\ 0 & 0 & 0\\ 0 & 0 & 0\end{bmatrix} + \begin{bmatrix} 0 & 0 & \frac{1}{2}(e^{-t}+e^{t}) \\ 0 & \frac{1}{2}(e^{-t}+e^{t}) & 0\\ 0 & 0 & \frac{1}{2}(e^{-t}+e^{t})\end{bmatrix} + \begin{bmatrix} 0 & \frac{1}{2}(-e^{-t}+e^{t}) & 0 \\ 0 & 0 & \frac{1}{2}(-e^{-t}+e^{t})\\ 0 & \frac{1}{2}(-e^{-t}+e^{t}) & 0\end{bmatrix} = (I_3 - P^2) + P \sinh( t) + P^2 \cosh(t) = \begin{bmatrix} 1 & \frac{1}{2}(-e^{-t}+e^{t}) & -1 + \frac{1}{2}(e^{-t}+e^{t}) \\ 0 & \frac{1}{2}(e^{-t}+e^{t}) & \frac{1}{2}(-e^{-t}+e^{t})\\ 0 & \frac{1}{2}(-e^{-t}+e^{t}) & \frac{1}{2}(e^{-t}+e^{t})\end{bmatrix}$$
Comment: Nice work! All the formatting, yikes! + 1
Comment: @amWhy: I recall that one and it was a nightmare writing up, but not the worst one I've had! thx!
Comment: I don't get how some users "whip these up" in no time at all!!
Comment: That's a great idea, Amzoti!
Comment: Of course, all sort of matrix variants are in there as are the special characters I use often and then some of the ones I use infrequently that are harder to find. It really helps me to write things up faster and I use notepad++ as my scratch pad - a really handy text processor.


Backprop: Calc gradients for embed layers and how to do gradient check

Question: First I want to check is I understand correctly how backprop works for NN with embed layers.
Lets create simplest NN with embed layer

Input Layer [i1; i2; i3; i4] - input nodes
Embed layer [h1] [h2] - here we have 2 nodes h1 and h2; h1 is connected to i1, i2 and h2 is connected to i3, i4. Corresponded weights of these connections w1, w2, w3, w4. Hence 2 embed blocks with only 1 node in each.
Output layer with node y connected with outputs from embed layer. I.e two connections, h1 -> y, h2 -> y

Now I want to use back prop to calc gradient of weights.
As I understand shared weights between input layer and embed layer must always have the same values, i.e. w1 = w3, w2 = w4, so when initializing weights for network we should ensure that; also after each epoch these weights (shared) should remains equal, so after we calculate gradients for w1 and w3 (as normal) we should average them like this w1 = w3 = (w1 + w3) / 2 and w2 = w4 = (w2 + w4) / 2, this will ensure us shared weights will remains the same after each epoch.
Now if this is correct, then how could I use gradient check to test my backprop works, since gradient check knows nothing about restrictions of how we calculate gradients for shared weights in embed layer.
Thanks.
Answer: First of, adding restrictions like that are a possibility and can work quite well in some case, however they certainly aren't mandatory. In the general case, they aren't there.
If you do want them, you usually calculate the gradients separately, average them and then add that average to both. That ensures that both weights remain the same


Is PostgreSQL database optimised for any particular CPU?

Question: This question may sound strange, but some CPU have instruction sets for virtualisation technologies, while some non-related software can use those sets, or even GPU to improve their performance.
So, anything like this for PostgreSQL, or is it something along the lines of "install 4x 8core of latest stuff and be happy"?
Comment: I don't think this is worthy of an answer, but I suppose you could say that the database might benefit from running on the amd64 architecture depending on your data set and whether or not 64-bit allows PostgreSQL to work more efficiently. Also, Ignacio is right, the amount of memory installed and hard drive speed is going to matter a lot more than CPU.
Answer: Databases don't actually use the CPU very much. I/O is far more important for database performance.


Tune Easton FMJ arrows for a 30# bow?

Question: I'd like to shoot the FMJ series of Easton because I really like how easy you can pull aluminium arrows out of the target in comparison to carbon ones. But the spine will only get as light as 500.
Is there any way to get them working with a bow weight of 30#@28,5" by adjusting the point weight far enough up? If yes how much point weight would that need? The easton chart only shows up to 125gr point weight. It would fit with that according to the chart, but the chart is giving too hard spine values all the time.
Answer: May I suggest the use of the Easton Carbon Ones, the shafts are excellent quality for the price and because they were originally only sold in spines for recurve or low poundage bows, there should be a spine that suits your needs, they can be also be pulled from the buttress with ease because Easton put a coating on them, the ease of removal the arrows from the target could also be improved by using Scorpian Venon or other arrow lubricant.

Tune Easton FMJ arrows for a 30# bow?


if $x+y+z=1$ then find the maximum of the form

Question:
Let $x>0$, $y>0$ and $z>0$ such that $x+y+z=1$. Find the maximal value of
  $$x\sqrt{y}+y\sqrt{z}$$

I think $x=y=\dfrac{4}{9},z=\dfrac{1}{9}$ then the maximum $\dfrac{4}{9}$,but how to use AM-GM prove it?
Answer: By AM-GM
$$x\sqrt{y}+y\sqrt{z}=\sqrt{y}\left(x+2\sqrt{\frac{y}{4}\cdot{z}}\right)\leq\sqrt{y}\left(x+\frac{y}{4}+z\right)=$$
$$=\sqrt{y}\left(1-y+\frac{y}{4}\right)=\frac{4}{9}-\frac{1}{36}\left(\left(3\sqrt{y}\right)^3+16-36\sqrt{y}\right)\leq$$
$$\leq\frac{4}{9}-\frac{1}{36}\left(3\sqrt[3]{\left(3\sqrt{y}\right)^3\cdot8^2}-36\sqrt{y}\right)=\frac{4}{9}.$$
The equality occurs for $x=y=\frac{4}{9}$ and $z=\frac{1}{9}$, which says that $\frac{4}{9}$ is the maximal value.
Done!
Answer: Without AM-GM, the Lagrange multiplier method will do:
$$L=x\sqrt{y}+y\sqrt{z}+t(1-x-y-z).$$
$$\begin{cases} L_x=\sqrt{y}-t=0 \\ L_y=\frac{x}{2\sqrt{y}}+\sqrt{z}-t=0 \\ L_z=\frac{y}{2\sqrt{z}}-t=0 \\ L_t=1-(x+y+z)=0 \end{cases} \Rightarrow x=y=\frac{4}{9}, z=\frac{1}{9}.$$
Note: To solve the system of equations, square $(1)$ divide it by $(3)$ to find $t=2\sqrt{z}$. Then substitute this into $(1)$ to find $y=4z$. Then substitute these into $(2)$ to find $x=4z$. And finally substitute all into $(4)$ to find $z=\frac{1}{9}$, hence the rest.


"[node:flag-vote-count]" displays the token name, not the number

Question: I have a problem in the Flag module with the [node:flag-vote-count] token. I googled for a solution, but I couldn't find one.
On my content page, the Flag module displays the token name (i.e. [node:flag-vote-count]) on the node creation preview page, instead of a number.
I am putting the token on the Flag -> Edit -> "Flag link text" field. Meaning inside the flag itself. [node:title] is working perfectly fine there.
Someone can help me here?
Comment: Where are you putting the token exactly? If it's in the content body do you have a filter module installed that converts tokens?
Comment: I am putting the token on the Flag -> Edit -> "Flag link text" field. Meaning inside the flag itself.
The [node:title] token is working perfectly fine there.
I edit my question and add this clarification.
Answer: OK , so I solve it.
The [node:flag-vote-count] is really not working.
But you can look for another count token for the flag you created, under the TOKEN REPLACEMENT -> nodes.
Good luck :)
Answer: It's works fine:
If i have name variable of flag: 'bookmarks'
I most replace this [node:flag-vote-count] to this [node:flag-bookmarks-count]
If your name variable for example like this: 'bookmarks_this',
you need write toke like so: [node:flag-bookmarks-this-count]
Answer: When a single token is not replace, it means that none of the modules implementing tags gave a value for the token you are using.
Looking at flag.tokens.inc, which contains the code for listing and generating the Flag module tokens, I notice it is using the following code to generate the token you are trying to use.
<code>  // We only provide tokens on entity types if we have token module's helper
  // methods available.
  if (isset($data[$type]) && module_exists('token')) {
    $entity_type = token_get_entity_mapping('token', $type);
    if ($entity_type && in_array($entity_type, flag_get_types())) {
      $flags = flag_get_flags($entity_type);
      $object = $data[$type];
      foreach ($flags as $flag) {
        foreach ($tokens as $name => $original) {
          $flag_count_token = 'flag-' . str_replace('_', '-', $flag->name) . '-count';
          $flag_link_token = 'flag-' . str_replace('_', '-', $flag->name) . '-link';
          if ($name == $flag_count_token) {
            $replacements[$original] = $flag->get_count($flag->get_entity_id($object));
          }
          elseif ($name == $flag_link_token) {
            $replacements[$original] = flag_create_link($flag->name, $flag->get_entity_id($object));
          }
        }
      }
    }
  }
</code>
To see that token, you need to have the Token module installed, since flag.info doesn't require it as dependency, if not for executing the tests. You also need to use the correct flag name, which means that if you are using [node:flag-vote-count], but the flag name is bookmarks, you are using the wrong token name, which should instead be [node:flag-bookmarks-count].
I didn't test it, but probably you would get back the token name if the node doesn't have any value for that flag.


The recurrence $a_k(n) = \sum_{0\leqslant j<n} a_{k-1}(n+j)$

Question: I'm trying to find a closed form expression to the following recurrence relation:
\begin{align}
&a_k(0) = 0, \quad \forall k\geqslant 1; \\
&a_k(1) = 1, \quad \forall k\geqslant 1; \\
&a_0(n) = 1, \quad \forall n\geqslant 1; \\
&a_k(n) = \sum_{0\leqslant j<n} a_{k-1}(n+j).
\end{align}
The case $k=2$ are particularly interesting, since it gives the pentagonal numbers,
$$ a_2(n) = \sum_{0\leqslant j<n} a_1(n+j) = \sum_{0\leqslant j<n} (n+j) = \binom{2n}{2} - \binom{n}{2} = \frac{n(3n-1)}{2}.$$
But for higher $k$ it seems to behave very "chaotically" (in a not exactly strict sense of this word).
If instead of "$n+j$" one chooses "$n-j$" on the definition, the closed form of the recurrence becomes much more friendly, namely $\binom{n+k-1}{k}$, that is well-known counting way, and even can be extended to the complex function in two variables $\frac{\Gamma(z+w)}{\Gamma(z)\Gamma(w+1)}$. It makes me wonder whether the above recurrence relation also have a combinatorial interest, or even a closed form that can be naturally extended to complex variables.
Comment: Have you tried writing down a general generating function?
Comment: @AlexR. I am not very familiar with the concept of generating functions, the only thing I've done was brute force, literally do some calculations and hope to something good to appear haha. But how could I find a generating function to this recurrence?
Answer: Not a comprehensive answer yet, but still food for thought : For all $k$, there is a systematic way to compute a closed form formula for $a_k(n)$ valid for all $n$. The steps are the following :
You can easily prove that for all $k$, $a_k(n)$ is a polynomial function of the variable $n$.
Proof :
It is true for $k=0$ since $a_O(n) = 1$. If $a_{k-1}(n)$ is polynomial, then $a_{k-1}(n+j)$ is also a polynomial in $n$ for all $j$ (cf Taylor's theorem for polynomials), and $a_k(n) = \sum_{j=0}^{n-1} a_{k-1}(n+j)$ is a sum of polynomials, Hence a polynomial itself.
Hence, for all $k$ and $n$, $a_{k-1}(n+j)$ is a polynomial function of the variable $j$. Rewrite $a_k(n) = \sum_{j=0}^{n-1} a_{k-1}(n+j)$ leaving only the monomial $j$ terms under the sum. Then using Faulhaber's formula (see Faulhaber's formula on Wikipedia), you can give a closed form expression for $a_k(n)$ without any $j$. This formula is heavily dependent on the concept of Bernoulli numbers (see Bernoulli number on Wikipedia), which arise in several other mathematical fields (they are involved in the closed form fomula for the even integer values of the Riemann zeta function for instance !!!)
Exemple : $k = 1$
$$a_1(n)  = \sum_{j=0}^{n-1} a_0(n+j) = \sum_{j=0}^{n-1} 1 = n$$
$k = 2$ :
$$a_2(n)  = \sum_{j=0}^{n-1} a_1(n+j) = \sum_{j=0}^{n-1} n+j = n \sum_{j=0}^{n-1} 1 + \sum_{j=0}^{n-1} j = n^2 + \frac{n(n-1)}{2}$$
And so on ...
Comment: Yes, nice Idea. An exact solution can be coded very efficiently in a small computer program since all polynomials will actually have rationnal coefficients (Prove it !) :-)
Comment: I've already thought that the general form of this recurrence was somewhat related with Bernoulli numbers because of Faulhaber's formula. But you indirectly gave me the idea of interpolate some values of $a_k(n)$ for fixed $k$ to find the polynomial for each $k$ and try to "heuristically" find out this relation for every $k$. I can't believe I haven't thought anything like that until now hahaha. Thanks!


Finding all ideals $T$ in number ring $\mathbb Z[\sqrt{-3}]$ s.t. $\langle 4 \rangle \subset T$.

Question: I want to find all ideals $T$ in number ring $\mathbb Z[\sqrt{-3}]$ s.t. $\langle 4 \rangle \subset T$.
My idea:
$  4= 2\times2 = (1-\sqrt{-3}) (1+\sqrt{-3})$ so $\langle4\rangle = \langle 2\rangle \langle2\rangle = \langle(1-\sqrt{-3})\rangle \langle (1+\sqrt{-3})\rangle$
Let $I = \langle2\rangle, J = \langle(1-\sqrt{-3})\rangle, K = (1+\sqrt{-3})\rangle$
Now, note that $\langle4\rangle \subset I, J, K, IJ, JK, IK, IJK, \langle4\rangle, \mathbb Z[\sqrt{-3}]$ and these are the all ideals that contain $\langle4\rangle$.
Now, as easy as this problem may seem, I'm having doubts whether my solution is correct or not, especially I am not able to convince myself that there are no other ideals containing $\langle4\rangle$. Can someone help me figuring this out?
Thanks!
Comment: @Andrews Thanks stranger for the edit! Alternatively, I think we can somehow make use of the one-one correspondence between ideals of a ring $R$ contained in an ideal $I$ of $R$ and the ideals of the quotient ring $R/I$, but finding ideals of this quotient ring doesn't seem very easy either.
Answer: You could use the universial property of the polynomial ring to construct a ring homomorphism $\varphi: \mathbb{Z}[T] \rightarrow \mathbb{Z}[\sqrt-3]$ by mapping $T$ to $\sqrt-3$. As $\varphi(T^2+3)= 0$, this induces a map from the quotient $\bar{\varphi}: \mathbb{Z}[T]/\langle T^2+3\rangle \rightarrow \mathbb{Z}[\sqrt-3]$. Furthermore $\bar{\varphi}$ is clearly surjective and the domain and codomain of $\bar{\varphi}$ are both free $\mathbb{Z}$-modules of rank 2 so this map is even an isomorphism by general theory. As you said, it suffices to compute how many ideals $(\mathbb{Z}[T]/\langle T^2+3 \rangle)/\langle 4 \rangle $ has. Again using universal properties, you can constuct an isomorphism $(\mathbb{Z}[T]/\langle T^2+3 \rangle)/\langle 4 \rangle \cong (\mathbb{Z}[T]/ \langle 4 \rangle) / \langle T^2+3 \rangle \cong \mathbb{(Z/\langle 4\rangle}[T])/\langle T^2 - 1 \rangle$. This ring is now in particular a free $\mathbb{Z}/\langle 4 \rangle$-module of rank $2$ so it only has $16$ elements. Also you can do very explicit calulations in this ring using polynomial division, so it should not be to hard to calculate all ideals of this ring. Finally following the ismorphisms above backwards will give you all ideals above $\langle 4 \rangle$. If you need any more details please let me know!
Comment: I want to know the detail of the process of finding the ideal of (Z/4Z)[x]/(x^2-1), I would be appreciated if you could show me the details.


Is it okay to use the same Redis store for both cache and django-channels channel layer in Django?

Question: I have a Django 3.1 app that uses Redis for its cache backing store (django-redis). I wish to use django-channels, which has the ability to use Redis for channel layers.
Is it safe or unsafe to use the same Redis store for both the cache and the django-channels channel layer at the same time? In other words, I wish to have the following in my settings.py, and I want to know if that's okay.
import environ

env = environ.Env()

REDIS_HOST = env('REDIS_HOST', default='127.0.0.1')
REDIS_PORT = env('REDIS_PORT', default='6379')

CACHES = {
    'default': {
        'BACKEND': 'django_redis.cache.RedisCache',
        "LOCATION": "redis://" + REDIS_HOST + ":" + REDIS_PORT + "/0",
        'OPTIONS': {
            'CLIENT_CLASS': 'django_redis.client.DefaultClient',
            'CONNECTION_POOL_KWARGS': {'max_connections': 30},
            'IGNORE_EXCEPTIONS': True,
        }
    }
}

CHANNEL_LAYERS = {
    "default": {
        'BACKEND': 'channels_redis.core.RedisChannelLayer',
        "CONFIG": {
            "hosts": [(REDIS_HOST, int(REDIS_PORT))],
        },
    }
}

Answer: It is safe unless your cache have name collisions, which is rarely to happen since keys are prefixed by default in channels:
By default, channel key is prefixed with asgi: and group key is prefixed with asgi:group: You can read more here: channel key prefix


Setting up experiment for statistical analysis

Question: I am looking at setting up an experiment concerning a hobby of mine, basically measuring a variety of parameters 'before' and 'after' and see which one, if any, gives the most reliable prediction of a final parameter i.e. do they have a linear relationship, etc.  The object being to save some time and effort later not sorting by the parameters that have little actual bearing on the final results, and to see if some of the more tedious sorting methods are actually as useful as thought.
The experiment is an extension of one I did for my final paper in my stats class a couple years ago:  investigating the relationship between case weight & volume vs. muzzle velocity for centerfire rifle cases as used in modern target competition (in which I'm fairly active).  For that paper I had to spend a fair amount of 'time' demonstrating various methods that didn't really pertain to what I wanted to know, but had to cover anyway to get an 'A' ;)
For this go-around... I'm looking at taking one hundred pieces of brass cases from one box, one lot.  These are the 'non-consumable' parts, as they can and do get re-used and reloaded multiple times.  Everything else - bullet, powder, primer - get shot down the barrel and cannot be re-used/re-measured.  Specifically, the cases can and do become 'fire-formed' to the interior dimensions of the chamber under extreme pressure (50-70k psi).  In my original experiment, I found a significant, but not especially strong, correlation between the initial case weight and the muzzle velocity... of the first firing.  Case volume, on the other hand, which should be very strongly related to MV... was not, theoretically because the 'virgin' cases don't necessarily 'fit' the internal dimensions of the chamber and a certain amount of the energy generated is expended not just in heat, but in squashing the brass against the case wall during firing.
So again, I'm looking at taking 100pcs of brass, weighing them straight out of the box, taking various measurements (case wall thickness inside near the case web, case neck thickness near the mouth, weight, volume, etc.) in their 'virgin' untouched state, then performing several routine case prep steps (trim to length, chamfer/debur the mouth, debur the flash hole, uniform primer pocket) and repeat the measurements.  Then load and fire the rounds as uniformly as possible - bullets sorted for maximum consistency, powder weighed on a milligram-capable analytic lab scale, etc. while controlling the rate of fire so as to regulate temperature rise along the barrel and measuring the muzzle velocity via a chronograph approx. 15 feet down range.  Then I plan to completely clean the cases inside and out to remove any buildup of carbon or powder residue, and repeat the measurements and then load and fire again and then clean and measure one last time.
Part of what I want to see is how the distributions of some of the measurements change as the cases are prepped, then again as they are fired and formed to the chamber.  After that... I want to see how much difference is there really between 'virgin' cases and fire-formed cases in terms of muzzle velocity, and finally... of all the tedious measurement steps mentioned above, which ones actually give a reasonable indication of consistent MV so I can successfully cull suspect pieces of brass during preliminary sorting rather than suffer lost points when using them on target in competition.
The single biggest problem in my mind, at least on the surface, is the chronograph.  Getting anything approaching credible numbers for accuracy or % error from the vendors is somewhere between difficult and impossible.  Given the nature of the device, it is extremely difficult to test on a consumer level - every round through it may (or may not) be just slightly different, so determining how much of the variation displayed on its screen is really the ammunition and how much is the variability of the instrument itself... has me scratching my head, to say the least.
As to why I was kind of vague before about the details of the experiment... well, sometimes people get kinda weird as soon as they realize something involves GUNS and won't touch it with a 10 ft pole regardless of how reasonable it may be.
Thanks,
Monte
Comment: Many questions: 1. Is it an experiment or an observational study? 2. State clearly what are your predictors and what is your outcome variable. 3. Try to be more specific. 4. What do you mean by sorting? 5. What is your sample? Is it n=100 pieces?
Comment: To add to Jeromy's comment. It would be nice if you could state your research question. So far I am pretty confused.
Comment: Okay, more detail - you got it ;)
Answer: Actually, people get paid big money for statistical guidance through experiments... If you're not too sure about it, I'd also advise to consult a statistician. An internet forum is not the best aid for complex analyses. Much of what is possible depends on the structure within the dataset: How are the variables distributed, how is the correlation structure,...
But I'll take a shot at it.
So you have $m$ measurements at 4 different times, being:

virgin state
after preparation
after first round (shot in "virgin state")
after second round (shot in "non-virgin state")

Your response variable is $MV$. Let's assume the error of the chronograph is random and normally distributed, this makes life a lot more easy. Let's also assume that for all other measurements the assumptions of parametric models apply, i.e. that every measurement consists of $n$ indipendent and identically distributed random variables, being your $n$ tested cases.
A rather basic approach would involve

using a Kolgomorov-Smirnov test to compare distributions (think about correction for multitesting)
a model selection procedure to determine the best predictors for $MV$ using either set

So in theory, you could use a GEE with "round" as a factor, indicating whether the measurement was made in the first round or in the second round, thus allowing for different intercepts and coefficients for first and second round that can be compared and tested. You have to specify "case" as a random factor in the GEE to get correct estimates of your SE. Basically, if the main effect "round" is significant, there is a difference before and after in average $MV$. If the interaction "round":measurement is significant, the impact of the measurement is different between the two rounds. Now it boils down to use any sensible criterium to select the best model.
Without seeing the data, it's impossible to say whether this approach is actually valid. You will have to do some descriptive and exploratory analysis to really understand the underlying distributions and correlations. Otherwise you can never know whether you violated assumptions of any method.
On a sidenote: Give this dataset to 10 statisticians, and chance is big you get as many different models. You should keep in mind whether or not the model also makes sense in real life.
my 2 cents


Does there exist a non-abelian group with roots?

Question: I just learned the definition of a division group:

An abelian group $G$ is called divisible if for every $x\in G$ and every $k\in\mathbb{Z}^+$, there exists $y\in G$ such that $y^k=x$ (or $ky=x$, in additive notation).

So I was wondering if the property of "existence of roots" implies that a group is abelian. I believe this is not the case, but I couldn't find a counterexample. I had some ideas of using free groups and/or semidirect products (involving $\mathbb{Q}$, which I believe is the "simplest" division group), but I didn't get anywhere.
Comment: http://math.stackexchange.com/questions/612649/is-so-n-mathbb-r-a-divisible-group
Comment: For finitely generated examples see https://math.stackexchange.com/questions/2392881/if-every-nonzero-quotient-of-g-is-infinite-then-g-is-divisible?rq=1
Answer: Consider the complex affine group $\mathrm{Aff}(\mathbb{C})$, which we can regard as the group of affine maps $$\mathbb{C} \to \mathbb{C},~~ f(z) =  a z + b,~~ a \neq 0$$ under composition. Induction gives that
$$f^k(z) = a^k z + (a^{k - 1} + \cdots + a^2 + a) b.$$
So, for any $g \in \mathrm{Aff}(\mathbb{C})$, say, $g(z) = cz + d$, we can find $f$ such that $f^k = g$, that is, we can find $a,b$ such that $a^k z + (a^{k - 1} + \cdots + a^2 + a) b = c z + d$: There are $k$ distinct solutions $a$ to $a^k = c$; since $a^{k - 1} + \cdots + a^2 + a = 0$ for at most $k - 1$ values of $a$, there is some solution $a$ for which $a^{k - 1} + \cdots + a^2 + a \neq 0$. For such solutions $a$, we can solve $(a^{k - 1} + \cdots + a^2 + a)b = d$.
In fact, this should work just as well for the affine group over any algebraically closed field, perhaps requiring zero characteristic.
Remark 1 There's actually a simpler related example: Consider the group $\mathrm{Aff}_+(\mathbb{R}) = \mathbb{R} \rtimes \mathbb{R}_+$ of invertible, orientation-preserving affine transformations of $\mathbb{R}$, namely the maps
$$\mathbb{R} \to \mathbb{R},~~f(x) = a x + b,~~a > 0$$
under composition. In fact, using the above formula, which applies formally here, we can show that each $f \in \textrm{Aff}_+(\mathbb{R})$ has precisely one $k$th root for all $k \in \mathbb{Z}$.
Remark 2 In fact, both of these examples are subordinate to Micah's example, as we can show that the exponential maps for these groups are both onto:
If we embed $\textrm{Aff}(\mathbb{C})$ into $GL(2, \mathbb{C})$ in the usual way, namely via
$$(z \mapsto a z + b) \mapsto \left(\begin{array}{c}1&0\\b&a\end{array}\right),$$
then we can identify the Lie algebra $\mathfrak{aff}(\mathbb{C})$ of $\textrm{Aff}(\mathbb{C})$ with
$$\left\{\left(\begin{array}{c}0&0\\ \beta&\alpha\end{array}\right) : \alpha, \beta \in \mathbb{C} \right\} \subset \mathfrak{gl}(2, \mathbb{C}).$$ Computing gives that
$$\exp \left(\begin{array}{c}0&0\\ \beta&\alpha\end{array}\right) = \left(\begin{array}{c}1&0\\ \frac{\exp \alpha - 1}{\alpha}\beta&\exp \alpha\end{array}\right) \leftrightarrow \left(z \mapsto (\exp \alpha) z + \left(\frac{\exp \alpha - 1}{\alpha}\right)\beta\right),$$
and it's not hard to show that this is surjective. The same argument works for $\textrm{Aff}_+(\mathbb{R})$.
Answer: The multiplicative group of (nonzero) quaternions is non-abelian. However, any single element is contained in a subgroup isomorphic to the multiplicative group of complex numbers, and thus has $n$th roots for all $n$.
In general, any Lie group whose exponential map is surjective (in particular, any compact connected Lie group) will be divisible in this sense: if $g \in G$ with $g=\exp(v)$ for some $v \in \mathfrak{g}$, then $\exp\left(\frac{1}{n}v\right)$ is an $n$th root of $g$.
Comment: Theorem A in the reference http://jlms.oxfordjournals.org/content/s2-27/3/427.full.pdf+html given in an answer to http://math.stackexchange.com/questions/924557/if-a-connected-lie-group-is-divisible-is-its-exponential-map-surjective shows that for connected Lie groups $G$, surjectivity of $\exp: \mathfrak{g} \to G$ is not only sufficient but also necessary for divisibility of $G$.
Answer: You can also consider the set of the isometries of $\Bbb R^2$ that also preserve the standard orientation. Here noncommutatity is witnessed by translation to a certain point and rotation by a certain angle.
Arriving at the $n$th root of a pure rotation or translation is fairly easy, getting an $n$th root of a translation composed with a rotation is fairly tricky. You can think of taking a piecewise linear approximation to a circular arc starting at the origin going to the final point you're rotating around.
Comment: This group doesn't appear to be divisible. For example, suppose $A := \left(\begin{array}{c}a&b\\c&d\end{array}\right)$ is a square root of $C := \left(\begin{array}{c}-1&0\\0&-2\end{array}\right)$. The off-diagonal entries of $A^2$ are $b(a + d)$ and $c(a + d)$, so either $b = c = 0$ or $a + d = 0$. In the former case, $A^2 = \left(\begin{array}{c}a^2&0\\0&d^2\end{array}\right)$, but there is no real $a$ such that $a^2 = -1$. The latter case implies that the diagonal entries $a^2 + bc$ and $d^2 + bc$ coincide, which again is a contradiction, and hence $A$ has no square root in the set.
Comment: @Travis thank you for the correction. I had isometries in mind but wrote the wrong thing.
Comment: You're welcome. I was fooled myself and some nagging thought led to me looking for a counterexample in an old course text. In fact, $SL(2, \mathbb{R})$ is isomorphic to to $Spin_+(1, 2)$, which acts by isometries on Lorentzian $3$-space $\mathbb{R}^{1, 2}$, so we can see that the definite signature is in a way essential in your example. (That said I don't know whether $SO_+(1, 2) = PSL(2, \mathbb{R}) = SL(2, \mathbb{R}) / \{\pm I\}$ is divisible---here, the counterexample $C$ projects to $[C]$, which does have a square root, namely $[\textrm{diag}(1, \sqrt{2})]$.)


How do I deal with a floor function is a system of equations?

Question: How would one solve an equation with a floor function in it:
\begin{cases}
  y=12(x-\lfloor x \rfloor) \\
  x=12(y-\lfloor y \rfloor)
\end{cases}
Maybe an algebraic method could be used?
Answer: Write $x = m + \alpha, y = n + \beta$ where $m, n$ are integers and $0 \leq \alpha, \beta < 1$. The system is equivalent to the conditions $x = 12 \beta$, $y = 12 \alpha$ and the linear system
$$\begin{align*}
-\alpha + 12\beta &= m, \\
12 \alpha - \beta &= n.
\end{align*}
$$
Solving this system, we find
$$\alpha = \frac{1}{143}(m + 12n) ,\quad \beta = \frac{1}{143}(12m + n).$$
Therefore the solutions to the original system are all pairs $(x,y)$ with
$$x = \frac{12}{143}(m + 12n) ,\quad y = \frac{12}{143}(12m + n),$$
where $m, n$ are integers satisfying $0 \leq 12m + n, m + 12n < 143$. Moreover it is clear from the original problem that we must have $0 \leq m, n \leq 11$, and that all $m, n$ satisfying these inequalities yield solutions, except $m = n = 11$. Since $m + 12n$ runs through all numbers $0, 1, 2, \dots , 142$, we find in conclusion that the solutions are all pairs $(x,y)$ with
$$x = 12p/143, \text{ for $p = 0, 1, 2, \dots , 142$ }; \quad y = 12(x - \lfloor x \rfloor).$$
Comment: Your answer is more complete than mine. Nice finish.
Comment: Thanks very much for the very neat and clear solution but would be glad if you can explain how you get " 0≤12m+n,m+12n<143".
Comment: That's because the condition on $\alpha$ and $\beta$ is that they belong to $[0,1)$.
Comment: Can you show me how to break the  given two equations into 23 set of simple of linear equations from which the 143 points can be found geometrically? thanks
Comment: I'm not sure. For a fixed value of $m$, all the solutions lie on one line. The solutions will be located on the $12$ lines corresponding to $m = 0, 1, 2, \dots, 11$. Perhaps you want to take the intersections with the $12$ lines given by $n = 0, 1, 2, \dots, 11$.
Comment: rewriting the two equations as y=12(x−a ),x=12(y-b) and putting integers from 0 to 11 for a and b will give me 24 linear equations and using graphical calculator I can see all the 144-1 solutions. But I wonder  I cannot find  mathematically reasoning behind it which allows me to replace the floor function value for integer values from 0 to 11 plus do not know why there is an extra one value ( 144 instead of 143)
Comment: $0 \leq y - \lfloor y \rfloor < 1$, so multiplying by $12$, we find $0 \leq x < 12$. Therefore $a = \lfloor x \rfloor \in \{0, 1, \dots, 11\}$. Similarly for $b$. If you read my answer, you'll see that $a = b = 11$ is an exception. Just a comment now. If you already have a specific solution you want to understand but don't understand all the details, it's best to put that information in your question.
Answer: Let
$x = n+a$,
$y=m+b$
where
$0 \le a, b < 1$.
Then
$m+b
=12a
$,
so
$0 \le m+b < 12$.
Similarly
$n+a
= 12b
$
so
$0 \le n+a < 12$.
This gives a very finite
number of possible cases,
which can be readily checked.
Possibly more could come from
$n+a
= 12 b
= 12 (12a-m)
=144a-12m
$
or
$n+12m
=143a
$.