Passing Collection ID to generate Forms in Meteor

Question: I've a collection "Country" which displays a list of countries and their info. A book option leads a user to the "Activity" form which has dropdown fields like To,From. How do I pass the "Country" ID so that the form fields in "Activity" belong to the "Country" whose Book button the user has clicked. I think I should use a reactive var to store the country id and then perform operations to change the form fields accordingly. I'm fairly new to this and a heads up to the approach would be deeply appreciated.
The submit code for activity collection is :
    Template.activitySubmit.onRendered(function () {
    if (Session.get("submit-bypass") === true) {
        Session.set("submit-bypass", false);
        window.history.back();
    }

    $("#activity-goal").material_select();
});

Template.activitySubmit.events({
    "submit form": function (e) {
        e.preventDefault();

        var title = $(e.target).find("#activity-title").val()
        if (title.length === 0) {
            throwError("You must have a title.");
            $("activity-title").focus();
            return;
        }

        var activty = {
            title: title,
            goal: parseInt($(e.target).find("#activity-goal").val())
        };

        Meteor.call("activityInsert", activty, function (error, result) {
            if (error) {
                throwError(error.reason);
                return;
            }

            Session.set("submit-bypass", true);
            Router.go("activityPage", { _id: result._id });
        });
    }
});

Comment: You can use reactive var to store some data within the same template.
http://docs.meteor.com/#/full/reactivevar_pkg
Comment: @alexndm Hey, I'm thinking of the same but I can't quite know the implementation. I was looking forward to a heads up into this! Thanks
Answer: This is how you should use reactive var package

Add the package to your project, in terminal meteor add reactive-var
Open your JS file for the template, like activitySubmit.js
Declare reactive var like so

Template.activitySubmit.onRendered(function () {
 this.selectedCountry = new ReactiveVar(null);
});

Then update the reactive var as needed and use it

`
Template.activitySubmit.events({
      'change #country': function(e){
         var country = $(e.target).val()
         var instance = Template.instance();
         instance.selectedCountry.set(country);
      },

  'submit form': function (e) {
     ....
      var instance = Template.instance();
      var country = instance.selectedCountry.get(country);
     ....
  }

});`

If you'd like to pass the data around across mulitple files (globally), you can simply use Session. Session.set('myId', id) and Session.get('myId')
Comment: Thanks again man, but the way I planned it was to store the ID of the Country on click of the "book" button and in the Acitivity.js use the ID to change the values. How I can use reactive var to capture the ID of an object in a  list using a simple  tag button.
Comment: If it's used across multiple files, maybe you should use Session ?
Comment: I'm going for what would be easier for me as I'm quite new to meteor. Once I get the ID I could do the rest in JS but the meteor part is screwing me up. This is how the list page is http://postimg.org/image/7xycmagcz/ with each of the items generated using a mongodb collection. I need a way to differentiate which "book" button did the user click. Thanks for taking you time though, I'm sorry I tried it myself reading high and low but I couldn't implement this.
Comment: The easiest would be to use Session. On click event (or any event)m just do `Session.set('myId', id)`, where id is the value you'd lilke to store and then retrieve it anywhere in the app with `Session.get('myId')`
Comment: Thanks Alex, I owe you one for this :)! I'll try this right now.


Proximity alerts keep being added, how to remove them by using id's?

Question: I set up my map and a proximity alert for each map marker, here I am passing the lat and long, and place name to the add proximity alert method:
if(alerts==true)
{
addProximityAlert(l1, l2, place);
}

The add proximity alert method:
//The following sets up proximity alerts, getting a unique id for each one
private void addProximityAlert(Double latitude, Double longitude, String tit) {

    Intent intent = new Intent(PROX_ALERT_INTENT);
    intent.putExtra("name", tit);
    intent.putExtra("id", alertid);
    PendingIntent proximityIntent = PendingIntent.getBroadcast(this, alertid, intent, PendingIntent.FLAG_ONE_SHOT);
    lm.addProximityAlert(latitude, longitude, POINT_RADIUS, PROX_ALERT_EXPIRATION,proximityIntent );
    alertid++;

    IntentFilter filter = new IntentFilter(PROX_ALERT_INTENT );
    registerReceiver(new ProximityIntentReceiver(), filter);
}

The following is the proximity alert class:
public class ProximityIntentReceiver extends BroadcastReceiver {
    private static final int NOTIFICATION_ID = 1000;

    @SuppressWarnings("deprecation")
    @Override
    public void onReceive(Context context, Intent intent) {
       String key = LocationManager.KEY_PROXIMITY_ENTERING;
       Boolean entering = intent.getBooleanExtra(key, false);
       if (entering) {
                  Log.d(getClass().getSimpleName(), "entering");
           }else {
                  Log.d(getClass().getSimpleName(), "exiting");
           }
           NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

           Intent notificationIntent = new Intent(context, Map.class);
           PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
           Notification notification = createNotification();

        notification.setLatestEventInfo(context, "Proximity Alert!", "You are approaching: " +intent.getStringExtra("name"), pendingIntent);
        notificationManager.notify( intent.getIntExtra("id", -1), notification);

   }

    private Notification createNotification() {
           Notification notification = new Notification();
           notification.defaults |= Notification.DEFAULT_SOUND;
           notification.icon = R.drawable.ic_launcher;
           notification.when = System.currentTimeMillis();
           notification.flags |= Notification.FLAG_AUTO_CANCEL;
           notification.flags |= Notification.FLAG_SHOW_LIGHTS;
           notification.defaults |= Notification.DEFAULT_VIBRATE;
           notification.defaults |= Notification.DEFAULT_LIGHTS;
           notification.ledARGB = Color.CYAN;
           notification.ledOnMS = 15000;
           notification.ledOffMS = 15000;
           return notification;
     }
}

The first time the map is setup alertid is 0, and there are four map markers, and four proximity alerts are setup and it works fine. When leaving the map and returning it is setup again, alertid is reset to 0, but the alerts are added again, so 8 alerts go off, 4 new alerts added every time. I thought by resetting alertid to 0, recreating them again would overwrite the previous ones as they have an id, but this is obviously not happening. Can anyone see how they are building up, and maybe show me how to ensure they are only created once for every setup?
Answer: I guess you should maintain some kind of List where you keep all your Alerts with their intents to avoid adding them twice or several times. Also depending on your usage scenario, you should probably remove them, after notification:
lm.removeProximityAlert(PendingIntent intent)

But more probable is that you registered your BroadcastReceiver several times :)
Try to call this only once (and not every time you add an alert):
registerReceiver(new ProximityIntentReceiver(), filter);

Comment: I am not sure exactly how to remove a proximity alert, can you look at my add proximity alert method and show me the code to create a remove method please ? I tried this for two weeks with no luck :( Thank you!
Comment: To be honest, I also had a lot of problems when trying to remove proximityAlerts if I reconsider correctly. Try to save your PendingIntents in a List (e.g.ArrayList) to later be able to remove them again.
Comment: Ok I will give that a try, is that what you did and it worked? Thanks!
Comment: Sorry, can't remember exactly. But this guy seems to got it tackled: http://stackoverflow.com/questions/9761033/android-removing-proximity-alert
Comment: Yeah I was keeping an eye on this question and I got in touch with OP! Cheers!


I defined my funtion but it wont run. why not?

Question: My function that asks the user to input a 7 character number. but when i define it, it wont run. reason why? any help is appreciated.
def eticketNum():
    while True:
        eTickNum = input('please enter eticket number:')
        if len(eTickNum) == 7:
            break
        print ('Sorry, entry is invalid. Your e-ticket number has to be 7 characters long.')
    eTickNum = eTickNum.lower()
    # next part of function (I guess)

Comment: Do you call the function?  You should fix your indentation so it's clear where the function ends.
Comment: Can you show your full code and the error message?
Answer: You have to call the function,
add a eticketNum() to the last line of your code, It will be something like this:
def eticketNum():
    # your code
eticketNum()

edit:
if you want to use return value:
def eticketNum():
    # your code
x = eticketNum()
# do whatever you want with 'x' variable.

Comment: yes it worked! would i be able to use it to return a value at later stage?
Answer: Indentation is not correct, select what's after the def line and hit "tab" on your keyboard should work fine it's the alternative for {} if java


Solve $\int_{|z|=3}\frac{2z^2-z+1}{(z-1)^2(z-2)}dz$

Question: Find
$$\int_{|z|=3}\frac{2z^2-z+1}{(z-1)^2(z-2)}dz$$
I thought of using partial fractions so i ended up with
$$\int_{|z|=3}\frac{-5}{z-1}+\frac{-2}{(z-1)^2}+\frac{7}{z-2} dz$$
I did this because both singularities at 1 and 2 matter.
After this i would apply the cauchy integral formula to get the solution. is that right?
Answer: Yes, that is right.
Another way of solving the problem consists in applying the residue theorem. In order to do so, you would have to compute the residue of $\frac{2z^2-z-1}{(z-1)^2(z-2)}$ at the points $1$ and $2$.
Comment: Ahh. interesting, didn't think of that. Thank you so much!


How do I find the equation of the plane through the origin that is parallel to the plane?

Question: Plane = $4x-2y+7z+12=0$
How do I find the equation of the plane through the origin that is parallel to the plane?
Comment: [This](https://math.stackexchange.com/q/664884) may help you. Also, first check whether a similar question exist in the system which can help you before posting a new one.
Comment: @SarGe nope. I have no idea what that means
Comment: @SarGe Thanks dude. Appreciate ur help
Answer: The normal vector to your given plane is $(4,-2,7)$.  Any plane parallel to your given plane will have the same normal vector.  Can you find a plane with this normal vector that contains the origin?
Answer: To every plane you can associate a normal vector $\vec n$, that is, a vector that is perpendicular to the plane. The trick is to realize that if there is a vector $\vec v$ in the plane then the angle between the two vectors is $90^o$. This means that $\vec n\cdot\vec v=0$ for any vector $\vec v$ in the plane.
If $\vec n=(n_1,n_2,n_3)$ and $\vec v=(x,y,z)$ is any vector then the vector is inside the plane, associated to $\vec n$, if and only if $$\vec n\cdot \vec v=n_1x+n_2y+n_3z=0$$

Hint:

If two planes are parallel, what do they have in common?
You are given the plane $$4x-2y+7x+12=0$$ How would you check whether, say the point $(-3,0,0)$ is inside it? Now, what about $(0,0,0)$?


Performance de substituição em string

Question: Preciso fazer algumas operações de substituição em massa com Javascript. Para o meu problema específico, vamos supor que preciso substituir uma substring específica. Preciso trocar cada ocorrência de "azul" por "verde".
Então, tenho duas formas de fazer:
var foo = pegaTexto(); // imagine que isso retorna uma string qualquer;
foo = foo.replace("azul", "verde");

Ou:
var foo = pegaTexto();
foo = foo.replace(new RegExp("azul"), "verde");

A meu ver, numa situação dessas, a única utilidade prática de se utilizar uma expressão regular seria para especificar uma flag (para dizer por exemplo se a busca deve ser global), mas no meu caso estou omitindo as flags do construtor  da expressão.
Tenho uma dúvida, no entanto, com relação a performance dessas duas formas distintas.
Forçar o uso de expressão regular provoca algum impacto na performance?
Como eu posso medir isso?
Comment: http://jsperf.com/teste-de-replace
Comment: @Sergio muitíssimo obrigado! Isso vale uma resposta, se você a fizer, terei o prazer de pontuar e marcar como correta :)
Answer: Você pode usar o jsperf.com, aí é possivel montar testes para testar variações diferentes.
Fiz um teste e deu-me 13~15% mais lento com RegExp.
O código que usei:
var texto = 'amarelo verde encarnado azul branco';

// com regex
var regex = new RegExp("azul");
for(var i = 0; i < 50000; i++){
   var resultado = texto.replace(regex, "verde");
}

// com replace de string
for(var i = 0; i < 50000; i++){
   var resultado = texto.replace("azul", "verde");
}

A maneira mais rápida para esta função parece contudo ser o split/join - partir a string a cada palavra e voltar a juntar com a palavra nova. Crédito para a resposta do @utluiz.
var novaString = texto.split('palavraAntiga').join('palavraNova');

Comment: Não conhecia o `jsperf`, muito obrigado :) fico a imaginar que a operação com `RegExp` seja mais lenta devido ao tempo perdido com a operação de construção do objeto de expressão regular.
Comment: Se colocar o 'new RegExp("azul")' para fora do for fica mais rápido, mas, ainda sim, é mais lento que o 'replace("azul", "verde")'.
Comment: @GabrielGartz, boa! interessante ver o split/join também na corrida :)
Comment: @Renan, fiz um update: http://jsperf.com/teste-de-replace
Comment: Em tempo: mesmo construindo a expressão regular fora do laço e reaproveitando um único objeto todas as cinquenta mil vezes, a expressão regular ainda é mais lenta.
Comment: @Sergio Adicionei a revisão em http://jsperf.com/teste-de-replace/3. Aqui ficou 13% mais lenta. Se puder, atualize a resposta.
Comment: @LucasNunes, obrigado. Actualizei.
Comment: @Sergio revisei seu teste, removendo o loop interno: http://jsperf.com/teste-de-replace/5
Acontece que o loop também estava sendo testado, no caso o desempenho do loop também caia na avaliação o que prejudica o resultado, sendo que o jsperf já faz uma série de repetições de teste do algorítimo, quanto mais isolado mais preciso o resultado.
Comment: Fiquei **surpreso** com o fato de que o método mais performático varia tanto de um navegador para outro!
Answer: Acrescentei mais duas técnicas de substituição que não usam expressões regulares ao jsperf original do Sergio.
split/join
var resultado = texto.split('azul').join('verde');

indexOf
var pos = texto.indexOf('azul');
var ultpos = 0;
var resultado = '';
while (pos >= 0) {
    resultado += texto.substring(ultpos, pos) + 'verde';
    ultpos = pos + 4;
    pos = texto.indexOf('azul', pos + 4);
}
if (ultpos < texto.length) {
    resultado += texto.substring(ultpos, texto.length);
}

Resultados
Analisando os resultados em outros navegadores por outros usuários, notei que não existem um consenso sobre o método mais rápido.
Veja o gráfico no momento em que escrevo:

Em resumo:

split/join ganha no Chrome
indexOf ganha no Firefox e no Ópera
regex ganha no IE :/
Comment: Boa ideia trazer o split/join para a "corrida" `+1`!
Comment: Interessante, eu não tinha pensado em usar split e join dessa forma. Fico surpreso. +1.

Performance de substituição em string


Why has not Pressflow been upgraded to 6.24?

Question: Two weeks ago, Drupal released 6.23 to fix a security vulnerabilities, which was followed from Drupal 6.24. However, Pressflow is still in 6.22 (although, there are some files have been changed at the last week).
I am wondering whether Pressflow 6.22 has not been affected by the vulnerabilities in Drupal 6.22, or it does but it takes time for the team to upgrade it. If so, how insecure is Pressflow 6.22?
Answer: I'm a developer at Four Kitchens.
Drupal 6.24 introduced changes to the bootstrap process, and those created a merge conflict with Pressflow. See David Strauss' comments here on Github.
The forks of Pressflow on Github may have the latest 6.24 but these changes have not been reviewed by Pressflow maintainers and no pull requests have been sent.
The forks also include patches from the Drupal issue queue to fix some serious issues that appeared in 6.24, and they are not the most recent patches in the actual issue nodes:

drupal.org/node/1425868
drupal.org/node/1425260

So beware: Using a fork means you're using Pressflow upgraded to 6.x-dev essentially, except it's not even -dev as these issues are not yet adequately resolved; at least, not sufficiently enough to be accepted into Drupal 6.x-dev.
We're working on getting a full 6.24 stable version of Pressflow out. In the meantime, Pressflow 6.23 contains the security fix and was available when Drupal 6.23 was released.
You can also follow Pressflow at https://twitter.com/#!/pressflow.
Answer: They only merged in the parts of Drupal that changed for the security update. See https://github.com/pressflow/6/blob/master/modules/system/system.module.
<code>/**
 * The current system version.
 */
define('VERSION', '6.23');
</code>
Answer: https://github.com/pressflow/6
If you want 6.24 try https://github.com/omega8cc/pressflow6. See http://groups.drupal.org/node/187209 for some of the extras included in this fork of pressflow.


Javascript não pega array alterado antes do click

Question: Tenho um código click:
var layerMap = [];

$(document).on('click', '#TipoMapa', function(){

    console.log(layerMap);

});

E tenho um código que altera a variável layerMap:
$(document).on('click', '#tipo', function(){
    layerMap['regional'] = layerMap['regional'] || [];
    layerMap['regional'] = 'Alisson';
});

O que acontece é que clico no botão que cria um array em layerMap e após isso, clico no botão para dar o console.log na variável layerMap, mas o conteúdo sempre está me retornando como [], ou seja, vazio. O que pode ser?
Comment: voce esta tentando acessar uma propriedade de um array, nao desejaria um objeto ao inves de um array?
Comment: so pra confirmar voce clica no botao com id `#tipo` e depois clica no botao com id `#TipoMapa` e nesse ponto o `layerMap` ainda esta vazio certo?
Comment: sim, segundo o JS sim, mas se eu dou um console.log após criar o array na função do click `#tipo` ele retorna o array. Mas se clico no `#tipo` ele da como vazio
Comment: pode ser um monte de coisa, pode postar um pouco mais do seu js e o html ou se possivel reproduzir o seu problema no jsfiddle
Answer: Quando você tenta escrever uma variável no console, o que vai para o console é o resultado da chamada de .toString() no que você passou.
Para arrays, o resultado de .toString() é equivalente à chamada de .join(), segundo a documentação:

Implementado no JavaScript 1.8.5 (Firefox 4), e compatível com a 5ª versão do ECMAScript, a função toString() é genérica e pode ser usada em qualquer Objeto. Se o objeto tem um método join(), ele será chamado e esse valor será devolvido.

O importante saber é que .join() retorna os elementos do Array, separados por vírgula. Mas você não colocou nenhum elemento no Array.
Epa
como assim não coloquei nenhum elemento no Array?
Essa sintaxe:
layerMap['regional'] = layerMap['regional'] || [];

É sintaxe de objeto. Você adicionou uma propriedade ao Array, chamada "regional", mas uma propriedade é uma coisa. Um elemento é outra.
Então, de duas uma:

Ou você passa a usar índices numéricos ao invés de strings, e aí layerMap se comportará como você esperava...
Ou você faz com que layerMap seja um objeto ao invés de Array, e assim as propriedades aparecerão no console.

Basta fazer assim:
var layerMap = {};

Answer: Infelizmente, diferente de outras linguagens como PHP, Python, etc...
O Javascript não aceita chave nomeada como você fez neste exemplo:
layerMap['regional'].
Ele aceita apenas chaves numérias.
Caso você queira chaves nomeadas, tente trabalhar com objetos, pois arrays não serão sua melhor opção para chavear.
Aconselho olhar no w3schools mais sobre Arrays Javascript:
Arrays em javascript
Comment: O incrível é que ele cria o array certinho. Dentro do click do `#tipo` após criar o array dou um console.log e ele retorna o array certinho. Mas se eu clicar em `#TipoMapa` ele fala que está vazio.
Comment: Javascript aceita chave nomeada. É uma forma de se criar e acessar propriedades em objetos. Inclusive o código do AP roda sem erros, pois a propriedade é criada corretamente no Array.
Comment: Justamente por quê ele internamente, transforma sua chave em numérica. Ele não reconhece e tenta converter. Quando você vai buscar, não encontra nada. Tenta associar um numero a um tipo de informação, tipo: região 1, estado 2, cidade 3, e assim você consegue ir definindo.
Comment: Acho que não @Renan. Olhe a documentação do JavaScript, ele a respeito disso acusa um warning.
Comment: @DávilAndré Não. Além de não haver nada na documentação sobre isso, você pode experimentar no seu ambiente favorito: `'use strict'; var arr = []; arr['foo'] = 'bar'`. Nem em modo estrito isso dá erro ;)
Comment: Funciounou de fato @Renan. Estranho é que no site ele fala a respeito disso: WARNING !!
If you use named indexes, JavaScript will redefine the array to a standard object.
After that, some array methods and properties will produce incorrect results. Não entendo.
Comment: @DávilAndré esse aviso é do W3Schools. O W3Schools é o pior lugar do mundo para se aprender a programar (o SO em inglês vive falando mal de lá), mas assim como um relógio parado, até o W3S tá certo ao menos uma vez por dia. Misturar sintaxe de Array e objeto na mesma variável é pedir para sofrer, porque aí você perde qualquer garantia de que aquele array vai se comportar sempre como Array. A decisão de como ele vai se comportar cabe à quem for implementar o ambiente, então você pode ter resultados diferentes em navegadores diferentes, por exemplo.


Simulate probit marginal effects with an interaction term

Question: I have the following probit model:
library(foreign)
library(MASS)

data <- read.dta("Braith_statecap_JPR.dta")
data <- data[data$year > 1959,]

model1 <- glm(allons3 ~ confbord + rpc + confbord_rpc + neighlgdp + polity2l + polity2sq + lgdp96l + lnpop + postcoldw + peaceall, data = data, family = "binomial"(link = "probit"))

The data along with a stata do file can be downloaded at:
Journal of Peace Research: Bratithwaite
The paper can be found at:
Braithwaite2010
In the paper from which the data is taken, the author simulates the effects of the interaction term in the model (the confbord_rpc term, the multiplication has been done in advance). "confbord" is a dummy variable and "rpc" ranges from 0 to 7. He first calculates the effects with "confbord" set to 0, and "rpc" varying from 0 to 7 (everything else held constant at their means), and then subtracts the effects from the same models with "confbord" held constant at 1. He obtains a very substantial effect from the "cpr" variable through this procedure. I have been replicating this using the following code:
    #simulate coefficients based on the model
    beta <- coef(model1)
    covvar <- summary(model1)$cov.unscaled
    coefs.sim <- mvrnorm(10000, beta, covvar)

    #let rpc vary hold confbord constant at 0, and the other variables at their means
    constant <- 1
    confbord <- 0
    rpc <- seq(0,7,1)
    ncivwar_rpc <- ncivwar * rpc
    neighlgdp <- 8.077
    polity2l <- -0.4691
    polity2sq <- 56.51
    lgdp96l <- 8.123
    lnpop <- 9.028
    postcoldw  <- 0
    peaceall <- 16.14

    #bind them together in a matrix
    effects0 <- cbind(constant,ncivwar,rpc, ncivwar_rpc, neighlgdp, polity2l, polity2sq, lgdp96l, lnpop, postcoldw, peaceall)

    #multiply the effects matrix with the matrix of simulated coefficients to obtain marginal effects
    results0 <- coefs.sim %*% t(effects0)

    #evaluate each marginal effect on the standardized normal CDF, to obtain predicted probabilities
    results0 <- apply(results0,1:2, function(x) pnorm(x))

    #do the same procedure for confbord held constant at 1
    constant <- 1
    confbord <- 1
    rcp <- seq(0,7,1)
    ncivwar_rpc <- ncivwar * rpc
    neighlgdp <- 8.077
    polity2l <- -0.4691
    polity2sq <- 56.51
    lgdp96l <- 8.123
    lnpop <- 9.028
    postcoldw  <- 0
    peaceall <- 16.14

    effects1 <- cbind(constant,ncivwar,rpc, ncivwar_rpc, neighlgdp, polity2l, polity2sq, lgdp96l, lnpop, postcoldw, peaceall)
    results1 <- coefs.sim %*% t(effects1)
    results1 <- apply(results1,1:2,function(x) pnorm(x))

    # subtract the estimated probabilities from each other
    results <- results1 - results0

    #graph the results
    x <- seq(0,7,1)
    means <- apply(results,2,mean)
    sdUpper <- apply(results,2,function(x) quantile(x, .975))
    sdLower <- apply(results,2,function(x) quantile(x, .025))
    plot(x,means, ylim = c(-1,.2), type = "l")
    lines(x,sdUpper, lty = 2)
    lines(x,sdLower, lty = 2)
    lines(x,rep(0,8), col = "red")

The problem is that with this procedure I get a much lower effect than the author reports in the paper (figure 1), can anyone spot what I am doing wrong?
Answer: You ran the regression for Fig. 2 that uses confbord variable, but you try to get the margins from regression for Fig. 1 that uses nciwvar variable.
Comment: The Stata code looks rather inefficient, even accounting for it being four versions old. These days, all this machinery is bundled in `margins` and `marginsplot`, and they produce results that are quite different from what's published in the paper. Approaching this by simulation sounded a bit odd to me. This looks more like a job for Stata's `nlcom`. Ah well... it's not my paper that we are looking at here :)


I'm having trouble with centering.... Again

Question: I am trying to center my image slider to the center of the page but i cant make it work, can anyone see what i am doing wrong?
here is the code:
<code>#conteudo{
height: 600px;
width: 100%;
text-align: center;
display: inline-block;
margin: 0 auto;
clear: both;
}

/* @group Slider */

#slider {
overflow: hidden;
margin:0 auto;
height: 593px;
width: 1281px;
text-align: center;
float: left;
clear: both;
}

#slider ul {
  margin: 0;
  padding: 0;
  list-style: none;

}

#slider ul li {
  padding: 0;
  height: 593px;
  width: 1280px;

}

/* @end */
</code>
And here is the link to the site:
Link
Also, how can i make the image transition smoother?
Answer: remove the float:left; in #slider you cant center any elements with floats
<code>#slider {
overflow: hidden;
margin:0 auto;
height: 593px;
width: 1281px;
text-align: center;
float: left; // remove this..
clear: both;
}
</code>
Comment: thank you so much <3, any idea on how to make the transition smoother?
Comment: what do you mean, transition of?
Comment: can you click the check if my answer help you or you accept it as right, i need to have at least 50 reputation, thank you
Comment: from one image to the other
Comment: how do i adapt it to the one i have?
Comment: use twitterbootstrap... there is tutorial in website
Comment: did you accept that as correct? can you hit the accepting the correct answer, thank you


Converter String encoded to byte

Question: Estou a user encriptação AES-GCM no meu servidor, e a desencriptar no meu android client.
Contudo estou a ter um problema na conversão.
Supomos que:
1- O texto encriptado gera o valor em bytes: [B@541fe858
2- Esse valo é embebido num JSONObject e enviado para o cliente.
3- O cliente recebe esse valor com:
  String cryptoJSON =  JSONencryptedresponseWS.getString("crypto");

Que resulta com o valor correcto de [B@541fe858.
4- Contudo depois esta String tem de ser convertida para bytes, para passar esse valor para a função de decrypt. O problema é que ao fazer os métodos cryptoJSON.getBytes ou usando o base64.decode, resulta num valor diferente do esperado (e.g [B@f2f55b3).
Alguém sabe como posso retirar o valor concreto que está na String para o formato byte, fazer uma conversão directa?
Answer:
1- O texto encriptado gera o valor em bytes: [B@541fe858

Errado. Isso daí não é o valor em encriptado. É apenas o resultado de chamar o método toString() em um array.
Por exemplo:
byte[] bytes = {(byte) 'a', (byte) 'b', (byte) 'c'};
System.out.println(bytes);
System.out.println(bytes.toString());
byte[] bytes2 = {(byte) 'a', (byte) 'b', (byte) 'c'};
System.out.println(bytes2);

Produz como saída:
[B@1540e19d
[B@1540e19d
[B@677327b6

Veja aqui no ideone.
O que você deveria fazer é usar o construtor de String que recebe um byte[] como parâmetro:
byte[] bytes = {(byte) 'a', (byte) 'b', (byte) 'c'};
String s = new String(bytes);
System.out.println(s);

Eis a saída:
abc

Todo o resto da sua pergunta está errada porque se baseia no fato de que o formato começando com [B@ está correto, mas não está. Isso acontece porque arrays não sobreescrevem o método toString() da classe Object, que por padrão produz como resultado o nome binário da classe, seguido de um '@' e seguido do resultado do hashCode() em hexadecimal. O nome binário de byte[] é [B. O hashCode() de um array também é herdado de Object e derivado do endereço de memória do objeto.
Esse comportamento padrão do toString() herdado de Object é na maioria das vezes um comportamento inútil que produz um resultado sem qualquer serventia. Mesmo objetos com idêntico conteúdo mas em diferentes locais na memória gerarão resultados diferentes e igualmente inúteis no toString() (veja no primeiro código desta resposta que os dois arrays de idênticos conteúdos geram resultados diferentes no toString()). É isso que está acontecendo com você. Você deveria usar o construtor adequado de String para ter a codificação de byte[] correta.
Comment: "1- O texto encriptado gera o valor em bytes: [B@541fe858
Errado. Isso daí não é o valor em encriptado. "

Você amigo é que não leu bem. Concordo que isso é um metodo toString de um CRIPTOGRAMA (TEXTO ENCRIPTADO).

O seu primeiro exemplo ta muito bom e já o tenho implementado exactamente da mesma maneira. O  que eu preciso é do processo inverso!

Exemplo: Recebo no meu android cliente

String jsonCryptograma=JSONencryptedresponseWS.getString("crypto")

Que produz o valor [B@1540e19d. Agora como converto o jsonCryptograma para bytes?
Comment: @rew1nd Que tal chamar o [método `getBytes()`](https://docs.oracle.com/javase/9/docs/api/java/lang/String.html#getBytes--)?
Comment: @Vitor por favor lê a pergunta!

 String crypto = [B@541fe858
 byte[] bt = crypto.getBytes();      = [B@f2f55b3

O que eu necessito é que o valor [B@541fe858 seja transformado para o formato byte sem alterações!

Converter String encoded to byte


What is changed with Bluetooth in Android SDK 32?

Question: After changing my targetSdk to 32, I get the following error:
Settings key: <bluetooth_address> is only readable to apps with targetSdkVersion lower than or equal to: 31

I think this is happening while checking permissions while loading my app.
Comment: Does your app include any third party libraries especially for tracking/showing ads?
Comment: Yes, it does. The library causing the issue is the Zebra Scanner SDK.
Comment: @Sean did you figure out what the solution was ?
Comment: Unfortunately, no. I've reverted to targetSdk 31 and I'm waiting for an update to the Zebra scanner SDK to switch to 32. I've seen some things now require a target sdk of 32. Worst case, I'll drop support for the barcode scanner until they update it or I find a workaround.
Comment: did you find a workaround for this? i am getting the same issue with bluetooth_name
Comment: Unfortunately, no. I switched back to 31. I'm waiting for an update for the library causing the issue.
Comment: I have same problem but don't have Zebra Scanner SDK. My compileSdkVersion/targetSdk is 33
Comment: But it looks like OneSignal has the same problem: https://github.com/OneSignal/onesignal-expo-plugin/issues/107
Comment: Zebra has released a new scanner SDK version that fixes this issue.
Answer: Issue is due to few parameters are annotated with maxTargetSdk = Build.VERSION_CODES.S
enter image description here
For bluetooth_name I found the alternative and reading device_name using below code:
Settings.Global.getString(application.contentResolver, Settings.Global.DEVICE_NAME)
        ?: "UNKNOWN"

Answer: I solved this for me by downgrading the gradle version to 7.0.4 and setting both the compileSdkVersion and the targetSdkVersion to 31.
Unfortunately it's not the fix that i wanted but this is an intermediate step for now to continue working
Comment: You shouldn't need to downgrade gradle. I assume you actually mean the Android Gradle Plugin. Just lowering your target SDK version should work. Do you know what library is causing this issue?
Answer: You cannot change Target version directly. Before doing so see android documentation on migrating your application to specific target version.
Failing to do so will result in errors, as the changes each android SDK has its own features and upgrades which are not compatible with old code. Just by changing Target SDK version back you can solve this error. However, could most like to be or soon to be deprecated.
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Estimating variance of success probability in Poisson-binomial distribution

Question: I am looking at a very large yet finite sequence of Bernoulli trials, each with its own probability. From the physical nature of the process, I know that the probabilities $p_i$ of each trial should be normally distributed around some small value $\langle p_i \rangle\sim0.1$ and have standard deviation $\sigma_{p_i}\sim0.005$. My ultimate goal is to estimate the mean and variance of $p_i$ based on the measured sequence of Bernoulli trials.

I have grouped the sequential trials in blocks of $N = 1000$. The distribution of $X$ - the number of successes $k$ per $N$ trials - should follow the Poisson-binomial distribution, shouldn't it? Is there a way to estimate the variance of $p_i$ in this case?
Plotting frequency vs $k$, I observe that the distribution is broader than the binomial with the success probability $\langle k\rangle/N$. It is surprisingly well described by the beta-binomial distribution, which also gives meaningful values for mean and variance of success probability $p_i$. Is there some limiting case when beta-binomial and Poisson-binomial distributions merge, or is it just a lucky coincidence?
There is no physical sense for the measured probability to follow the beta-binomial protocol. Furthermore, if I group trials in blocks of $N$ not in the order they were obtained but rather randomly, the variance of the distribution of $X$ (as well as the variance of $p_i$) does not change much. Altogether this makes me think that the data, in general case, could not be described by the beta-binomial distribution.

PS: Sorry if I miss trivial things.
Answer: There's definitely a situation where you expect the Poisson-binomial to be well approximated by a Poisson.
That's when each of the p's is small.
In that case all the Bernoulli($p_i$) components are well approximated by a Poisson($p_i$) and then the sum of independent components should be well approximated by a Poisson($\sum_i p_i$).
You don't necessarily require a beta-binomial per se; any collection of sufficiently small $p$'s will work fairly well.
It will somewhat over-estimate the variance (all those $(1-p_i)$ terms in the contributions to variance are treated as $1$), but when all the $p_i$ values are small this effect may be small enough that it doesn't cause us difficulty.
In your case the $p_i$'s are all close to $0.1$ which is a tad on the larger side but still the  standard deviation of the sum will only be about $5\%$ ($1/\sqrt{1-0.1} - 1\approx 0.05$) too large which may be close enough for some purposes.
Comment: Thanks, I see your point. I have another parameter in the problem that shows me that overdispersion is a function of this parameter in a different way than the mean $p_i$.
In principle, my naive understanding would be the following: since Poisson distribution approximates both binomial and Poisson-binomial -> there should be some regime when beta-binomial and Poisson-binomial would also be close. Does that make sense?
Comment: Well, sure, if the set of $p_i$'s in the Poisson binomial was close to what you would reasonably see from sampling a beta distribution, in the sense than if we treated the $p_i$'s 'like a sample', their empirical cdf was consistent with a sizable sample from a beta, then the two mixtures (finite for the Poisson-binomial and continuous/uncountable for the beta-binomial) should also be quite similar (apart, perhaps, from the extreme tail). Consider what would happen if you literally sampled a beta $n$ times and called those values the $p_i$'s in your Poisson-binomial.


Content by credit/level in Drupal?

Question: Ideally I want users to earn "credits". These credits will allow them to redeem "content" (nodes). My goal is basically to allow users to only gain access to content they "redeem" using their credits, and they only gain credits by submitting content which I approve and assign value to. So if user X submits content, I think its great and rank it 8 out of 10 and decide that he gets 8 credits, he then gets 8 credits. He can then use those 8 credits to redeem content, and content can have different values.
What is the best way to go about getting this functionality in Drupal?
Answer: The Userpoint provides a mean to store a user credits and can be combined with the Userpoints Node Access to sell node (ie. content) access in exchange of userpoints (credits). The User points Nodes and Comments allow you to setup automatic rewards for content contribution (ie. nodes and comments creation). But it doesn't seems to provides the rating feature you ask for, nor does any of listed User Points Contributed modules.
What should be easily doable, is to use the Fivestar to rates node and then to grant, and revoke userpoint to the rated node author on voting (hook_votingapi_insert() and hook_votingapi_delete()). By restricting access to voting (ie. the 'rate content' permission or through an hook_fivestar_access() implementation), you can control who is allowed to grant credits to your users.
Answer: I would take a look at the User Points module and the User Points Contributed modules module.
If that does not satisfy you, it should be easy enough to write a custom module for that.

Create a table with primary key as nid and an credit value.
Create another table with primary key as uid and  assigned credits.
Make a third table for access. uid as primary and nid. There you can store the nodes a certain user has access to.
Create the table trough the schema api.
Now with a menu hook, add a MENU_LOCAL_TASK item that assigns values for easy administration by adding a callback that gets a form API form.

With hook_access(), you can define when a user has access to a node trough tables mentioned above and the database layer API.

Content by credit/level in Drupal?


VBA - Utilizar valores de uma coluna para montar tabela

Question: Bom dia,
Eu estou extraindo uma base de dados com datas e número de ocorrências. Mas para meu modelo estatístico eu preciso organizar ela de uma forma que apenas apareçam as datas multiplicado pelo número de ocorrências.

Eu entendo que tenho que fazer um loop para armazenar os valores para depois utilizá-los, consegui com esse código, mas não sei como utilizar esse valores para montar minha tabela, se alguém puder me ajudar, por favor:
<code>Sub table_array()

Dim myTable As ListObject
Dim myArray As Variant

Set myTable = ActiveSheet.ListObjects("Tabela1")
myArray = myTable.DataBodyRange

'Loop through each item in the Table Array (displayed in Immediate Window [ctrl + g])

 For x = LBound(myArray) To UBound(myArray)
    Debug.Print myArray(x, 2)

 Next
</code>
Answer: Consegui achar a resposta
Sub table_array()
Dim myTable As ListObject
Dim myArray As Variant
'Definir o nome da tabela no Excel e se necessário modificar abaixo
Set myTable = ActiveSheet.ListObjects("Tabela1")
myArray = myTable.DataBodyRange
Dim i As Date
Dim Linha As Integer
'Loop through each item in the Table Array (displayed in Immediate Window [ctrl + g])
' Linha mostra em qual linha serão incluídos os valores
Linha = 2
' Essa função abaixo pega os dados do corpo da tabela
For x = LBound(myArray) To UBound(myArray)
' Busca todos os valores da coluna 2 e usa o número encontrado para repetir as entradas na coluna um.
For Z = 1 To myArray(x, 2)
Cells(Linha, 6).Value = myArray(x, 1)
Linha = Linha + 1
Next
Next
End Sub


Generating random samples with bivariate t-copula

Question: I'm trying to generate a bivariate random sample of the t-copula (using rho = 0.8), without using the "copula" package and its function "rCopula" with method "tCopula". I'm using the following R-code:
N <- 10000
R <- array(c(1,0.8,0.8,1), dim=c(2,2))
L <- t(chol(R))
Z <- rbind(rnorm(N),rnorm(N))
X <- L%*%Z
df <- 2
W <- df/rchisq(N,df)
Y <- sqrt(W)*X
plot(Y[1,],Y[2,])
U <- pt(Y,df)
plot(U[1,],U[2,])

But the plot does not look like random points from a t-copula:

Does anyone know if I'm making a conceptual error or a mistake in the code?
It should look more like this: (generated using the copula package and its inbuilt functions)
Answer: Despite their relative simplicity I've found it quite difficult to find a straightforward guide to copulas besides this short blog post. I went back through your code, fixed it up a bit and annotated what the steps were doing, but not why, as best I could if it should be of any use to others just starting out.
Update: After a bit more research I found this pdf, section 5 / pg 18 of which outlines pseudo code for a number of different copulas.
#a tcopula using rho = 0.8
#done from first principles
require(mvtnorm)
numObs <- 10000
#NX2 shaped matrix
initialObservations <- rmvnorm(numObs,mean=rep(0,2))

#this is a 2X2 symmetric matrix based off of rho=0.8 and is positive definite
psdRhoMatrix <- matrix(c(1,0.8,0.8,1),2,2)
#the transpose of the cholesky decomposition of the psdRhoMatrix
#which gives us a lower triangle matrix for some particular reason
lowerTriangleCholesky <- chol(psdRhoMatrix)

#this lower triangle matrix (for whatever reason) is able to make
#the observations in each column correlated
# NX2 = NX2 %*% 2X2
correlatedObservations <- initialObservations %*% lowerTriangleCholesky

degreesOfFreedom <- 2
#the meaning of this step eludes me, it's a vector of random chi-square observations.
#Maybe something to do with applying the inverse CDF.
randomChiSqrStep <- degreesOfFreedom/rchisq(numObs,degreesOfFreedom)
#transforming the correlated variables
#the random chiSquaredStep is applied to each column of the correlatedObservations
#for element wise multiplication to be properly applied the data needs to be
#sorted into columns rather than rows. NX2 = NX1 * NX2
penultimateTransformation <- sqrt(randomChiSqrStep) *  correlatedObservations
plot(penultimateTransformation[,1],penultimateTransformation[,2])

#run the fully transformed and correlated observations through the t-dist PDF and that's it
tCopulaOutPut <- pt(penultimateTransformation,degreesOfFreedom)
plot(tcopulaOutPut[,1],tcopulaOutPut[,2])

Answer: I found the mistake, it has to do with the element-wise multiplication in line 8. It should be
Y <- rbind(sqrt(W),sqrt(W))*X


Como fazer APPEND em um componente criado automaticamente, não esta encontrando o ID do elemento

Question: Estou tentando adicionar uma div via append pois estou adicionando em uma tabela que tem componestes criados automático como filtro, responsiva, paginação, assim sendo gostaria de colocar dentro duma dessas div que fica ao lado do filtro porem ao colocar o id da div desses componentes via jquery ele não consegue identificar e não adiciona
por exemplo:

ou
$("#data-table-simple_wrapper").append("
teste
");

a div "data-table-simple_wrapper" não tem no html porem quando inspeciono a tabela consigo pegar o id da div e adicionar manualmete editando o html para testar porem o jquery não encontra esse ID
Comment: Não tem no HTML pois essa div é gerada por algum plugin?

Seria interessante postar o trecho de HTML do inspecionar se for o caso. E Seu código javascript está no mesmo arquivo do HTML? Em que posição exatamente, início ou fim?
Answer: Adicione $( document ).ready(function() em seu código, pois no momento da execução do javascript o documento html pode não ter sido ainda totalmente carregado, veja documentação https://learn.jquery.com/using-jquery-core/document-ready

Answer: Para afetar elementos no html que não existiam no DOM inicialmente (criados dinamicamente) você pode usar o document antes e depois o find pela div. Com isso ele vai procurar dentro do documento atual e irá achar sua div.
$(document).find("#data-table-simple_wrapper").append("
teste
");


Finding the table row number of a clicked row

Question: How can functionaity be added to the existing javascript coding below to find out as to what row number is clicked. The table headers should be exempt, and the dataset will start at ID number 0.
So for example, if the 2nd row of the table was clicked, an alert box would popup saying that "ID # is 1"
<!DOCTYPE html>

        File Number
        Date1
        Date2
        Status
        Num.

        KABC
        09/12/2002
        09/12/2002
        Submitted
        0

        KCBS
        09/11/2002
        09/11/2002
        Approved
        1

        WFLA
        09/11/2002
        09/11/2002
        Submitted
        2

        WTSP
        09/15/2002
        09/15/2002
        In-Progress
        3

Comment: If you are using JQuery, check http://stackoverflow.com/questions/7554218/html-table-clicked-rows-number
Answer: Checkout rowIndex property here. It starts from 0.
Answer: Just put data-row-no attribut to every
. Then from JavaScript call trow.getAttribute('data-row-no') to get current row.
...

    File Number
    Date1
    Date2
    Status
    Num.

    KABC
    09/12/2002
    09/12/2002
    Submitted
    0

    KCBS
    09/11/2002
    09/11/2002
    Approved
    1

    WFLA
    09/11/2002
    09/11/2002
    Submitted
    2

    WTSP
    09/15/2002
    09/15/2002
    In-Progress
    3

...
(
function( )
{
  var trows = document.getElementById("mstrTable").rows;

  for ( var t = 1; t < trows.length; ++t )
  {
      trow = trows[t];
      trow.className = "normal";
      trow.onclick = highlightRow;
  }

  function highlightRow( )
  {
      for ( var t = 1; t < trows.length; ++t )
      {
          trow = trows[t];
          trow.className = ( trow == this && trow.className != "highlighted") ? "highlighted" : "normal";
          alert(trow.getAttribute('data-row-no'));
      }
  }
}
)();


Prove using mathematical induction that $\sum_{i=1}^n if_i = nf_{n+2} - f_{n+3} + 2\ for\ all\ n \geqq 1$

Question: This question is for the Fibonacci sequence, where $\mathit f $ is represented by the fibonacci function.
I have done my base step and elaborated my inductive hypothesis already, but I am having trouble with my inductive step.
$\pmb Inductive\ Hypothesis:$ Let z $\in$ $\mathbb Z^+$ be given. Assume $\sum_{i=1}^n if_i = nf_{n+2} - f_{n+3} + 2 $ is true for all n = z.
From what I believe, I must prove that $\sum_{i=1}^{z+1} if_i $ = $\ (z+1)f_{z+3} - f_{z+4} + 2$.
I have reached the following:
\begin{align}
\sum_{i=1}^{z+1} if_i &= (\sum_{i=1}^z if_i) + (z+1)f_{z+1} \\
& = zf_{z+2} - f_{z+3} + 2 + (z+1)f_{z+1}\ \pmb(by\ inductive\ hypothesis)
\end{align}
I do not know where to take it from this point on.
Any help would be greatly appreciated!
Comment: You need to show it is true for $n=0$, then you should use $f_n+f_{n+1}=f_{n+2}$.
Answer: First, for $n=1$, the equality is
$$f_1=f_3-f_4+2$$
This is true because the first terms of the Fibonacci sequence are $f_1 = 1$, $f_2 = 1$, $f_3 = 2$, $f_4 = 3$.
Now, let's suppose that you have, for an integer $n \geq 1$, the relation
$$\sum_{i=1}^n if_i = nf_{n+2} - f_{n+3} + 2$$
Then you have
$$\sum_{i=1}^{n+1} if_i = (n+1)f_{n+1} + \sum_{i=1}^n if_i = (n+1)f_{n+1} + nf_{n+2} - f_{n+3} + 2$$
(the last step uses induction hypothesis). Using now that $f_{n+1} = f_{n+3} - f_{n+2}$, you get
$$\sum_{i=1}^{n+1} if_i = nf_{n+3} - f_{n+2} + 2$$
and using $f_{n+2} = f_{n+4}- f_{n+3}$, you get
$$\sum_{i=1}^{n+1} if_i = (n+1)f_{n+3} - f_{n+4} + 2$$
i.e. the equality at rank $n+1$. This concludes the induction.


Definition of prime ideal sheaf

Question: In the chapter I.3.3 of Eisenbud & Harris "The Geometry of Schemes" they give a definition of "prime ideal sheaf":
Let $\mathcal{O}_S$ be the structure sheaf of a scheme $S$, and let $\mathcal{F}$ be a quasicoherent sheaf of $\mathcal{O}_S$-algebras. Then a prime ideal sheaf $\mathcal{I} \subset \mathcal{F}$ is a quasicoherent sheaf of ideals of $\mathcal{F}$, such that on eash open affine $U \subset S$ the ideal $\mathcal{I}_U$ is prime (or unit).
After that they claim that prime ideal sheaves of $\mathcal{O}_S$ itself correspond to points of $S$. And here probably I miss some point, since I don't see why the following is not a counterexample.
Consider the following non-separated scheme, presented earlier in the same book. Let $S$ be a scheme that is obtained by gluing two copies of the affine line $S_1 \simeq S_2 \simeq \mathrm{Spec} \, k[X]$ along the complement of $0$ (I mean the ideal $(X)$, of course) by identity morphism, and let $0_1$ and $0_2$ be the "two zeroes" of $S$. Then I think that the sheaf of ideals corresponding to the reduced two-point subscheme supported on $\{0_1, 0_2\}$ satisfies the definition of prime ideal sheaf, since no affine open subset can contain both points simultaneously. However, I don't think this sheaf of ideals deserves to be called prime, and it clearly violates their claim.
So where am I wrong? Or if it is really a counterexample, what is the right definition then? Is it enough to add that $\mathcal{F}/\mathcal{I}$ should have irreducible support?
Edit: It turned out that in the (more recent) paper edition they only claim that for affine schemes.
Comment: Where exactly do they claim that the prime ideal sheaves correspond to points of $S$? As far as I see, they only claim this for affine $S$.
Comment: @Vladimir: In my edition of the book, directly after the definition, it is remarked (in brackets!): "(Observe that for any scheme $X$, the points of $X$ are simply the prime ideal sheaves of $\mathcal{O}_X$.)"
Comment: @VladimirSotirov: Moreover, the same is actually given as Exercise I-51.
Comment: In my edition it says "(Observe that for any affine scheme $X$, the points of $X$ are simply the prime ideal sheaves of $\mathcal O_X$.)" The exercise likewise asks to show that the points of an affine scheme correspond to prime ideal sheaves (restricted to every open affine it is a prime ideal or the unit ideal).
Comment: Mine is probably a draft compiled directly from latex, so I assume they just corrected this before publishing. But anyway, the definition is the same, and I can only say that I don't like it for the reason explained in the post. :)
Answer: I think your counterexample is correct (and this also means that Eisenbud's Spec construction breaks down; by the way there is a global Spec construction which even works for locally ringed spaces, see here). The correct definition of a prime ideal sheaf is that the corresponding closed subscheme is integral. Equivalently, it should be irreducible and reduced. Whereas reducedness can be checked locally, this is not the case for irreduciblity. So here is a more down-to-earth description: $I \subseteq \mathcal{O}_S$ is prime if $I \neq \mathcal{O}_S$, for every open affine $U \subseteq S$ the ideal $\Gamma(U,I) \subseteq \Gamma(U,\mathcal{O}_S)$ is prime or $(1)$, and for every inclusion $V \subseteq U$ of open affines the map $\Gamma(U,\mathcal{O}_S) / \Gamma(U,I) \to \Gamma(V,\mathcal{O}_S) / \Gamma(V,I)$ is injective.
PS: You may contact Eisenbud. He collects errata for his book.
Comment: Thank you. In your down-to-earth description you are still only working locally on affines, so I believe my counterexample still applies here. And the last injectivity condition, I think, should be automatically true if $\Gamma(U,I)$ is prime and $\Gamma(V,I) \neq (1)$, and wrong if $\Gamma(V,I) = (1)$. Anyway, this is what I wanted to know, that there should be no issues besides this "global" irreducibility...
Comment: Hm, so what is the correct down-to-earth description?
Comment: @MartinBrandenburg could you add a fixed link?
Comment: @Arrow: Please ask Hanno Becker (Bonn) for the pdf.

Definition of prime ideal sheaf


Why jQuery's event.which gives different results in Firefox and Chrome?

Question: Have a look at this live demo (from jQuery's site).
Clicking - (dash) in Firefox says that event.which is 173, while doing the same in Chrome produces 189.
This jQuery page says that event.which should be normalized for cross browser consistency. But, it looks like this is not true.
Why is this inconsistency?
Answer:
This jQuery page says that event.which should be normalized for cross browser consistency. But, it looks like this is not true.

jQuery normalizes the property name (e.g., always which, rather than which or keyCode depending on browser), but not the value of the property, which would be dramatically more complex.
The value for the key you get from keydown / keyup will vary not only by browser, but by keyboard layout. There are lots of gory details on the JavaScript Madness: Keyboard Events page by Jan Wolter. Amongst other things, you can see on that page that for that key, Firefox will give you 109, IE (and apparently Chrome) will give you 189, and Opera apparently used to go with 45 (but in my tests on Linux, they now go with 109).
For printable keystrokes (like -), you're better off with the keypress event, which gives you the resulting character.
Comment: As of jQuery 1.11, it does not appear that jQuery fully normalizes the `event.which` property, at least under FireFox. As can be seen here: http://jsbin.com/sozoqiro/1/edit?html,console `event.which` and `event.keyCode` both have different values depending on what key you press.  Pressing a printing character seems to populate `e.which` while the Tab key for instance populates `e.keyCode` and the Enter key populates both `e.which` and `e.keyCode` with the same value. In FireFox, the unpopulated property value is set to `0`.
Comment: In Chrome, this seems to be normalized, but `keypress` does not seem to trigger for Tab keys in Chrome.


How to read a specific value from within a JSON file?

Question: I want to know how to read a specific objects value from within a JSON object.
    "worker_01": {
        "data": {
            "name": "Juan",
            "manager": 0,
            "weight": 75,
            "positions": {
                "FOH": 1,
                "MOH": 1,
                "BOH": 1
            }
        }
    },

I know previously in Node.js I could read them by doing *.get(worker_01.data.name)*
but python doesn't really allow that. I want to know how do I do something similar to that in python.
Here is my source code.
import json as js

data_json = open('hello.json')
data_worker = js.load(data_json)

for i in data_worker['worker_01']:
    print(i)

Comment: Please, show valid JSON
Comment: well, it is somewhat similar in Python really, something like `data_worker['worker_01']['data']['name']`, as a type `data_worker` here is a python dictionary if you use `load`, also a bit related: I would suggest using `with` to open files
Comment: Buran, i just copied a snipet of the JSON file, so it wasn't the correct format.
Matiiss, thank you, this helped. works as i wanted it.
Comment: Once you have loaded the JSON, you work with the resulting structure of nested dictionaries and/or lists *the exact same way that you would, if the data came from anywhere else*.
Answer: In Python, you can read JSON as a big python dictionary with mini listed dictionaries in between them all. With that in mind, you can index specific attributes from the JSON. For example based on your JSON, if a user wanted to get data on a persons name, you would do data_worker['worker_01']['data']['name'] to get the output 'Juan'
Here is more resources for you to look at too!
https://www.w3schools.com/python/python_json.asp
https://www.codegrepper.com/code-examples/python/how+to+get+specific+data+from+json+using+python
https://www.w3schools.com/python/python_dictionaries.asp


Is there any command to list all the GCP project quota in a single excel file with only top headers

Question: Is there any command to list all the GCP project quota in a single excel file with only top headers. I tried to apply FOR loop on quota management however it gives me output with header included every time with new projects when appended.
gcloud compute project-info describe --flatten=quotas -- format='csv(quotas.metric,quotas.limit,quotas.usage)' will provide for one project. However require for all project on Org level and folder level in a single excel file.
Comment: There is no quota export at Org or folder level. It's per project. You have to build yourselves the script.
Comment: @guillaumeblaquiere Yes, hence asking for assistance if anyone had created the script. I am not able to achieve the same
Answer: I crafted this bash code that can help you in order to iterate all projects related with  the account used with GCloud feel free to modify this code according your use case
#!/bin/bash
#unique header
echo "ProjectId,Metric,Quota,Usage"
gcloud projects list --format="csv[no-heading](projectId,name)" |\
while IFS="," read -r ID NAME
do
  RESULT=$(\
    gcloud compute project-info describe --project ${ID} \
    --flatten=quotas \
    --format="csv[no-heading](quotas.metric,quotas.limit,quotas.usage)")
  # Prefix ${ID} to each line in the result
  for LINE in ${RESULT}
  do
    echo ${ID},${LINE}
  done
done

it is important that the account authenticated has the role project/viewer over all projects associated, also  Compute Engine API must be enabled in the projects.
Having said that, you can create a service account associated per organization or by folder in order to get all necessary information.
Comment: Awesome, Thanks for your efforts.
Comment: @Amit if this answer was useful please do not forget accept or upvote


powershell email body from file

Question: I'm trying to read the content of a text file into a string variable with powershell in order to use it to send an email (via smtp).
Using Get-Content I have no problem reading the contents of a file into a variable:
$body = Get-Content 'C:\somewhere\some-file.html'

The problem is
Send-MailMessage -To [recipient] -From [sender] -Subject [subject] -Body $body -SmtpServer [ip address]

fails with the message

Cannot convert 'System.Object[]' to 'System.String' required by 'Body' parameter. Specified method not supported.

How can I get the file contents into the variable as a String? I've tried converting the resulting Object[] array to a String by piping the $body variable with Convert-String but with no success.
Edit
To anyone looking for a one-liner, with the help of Mark's answer below here it is:
Send-MailMessage -To firstname.lastname@example.com -From firstname.lastname@example.com -Subject "Test" -Body (Get-Content 'C:\somewhere\some-file.html' | Out-String) -SmtpServer 123.456.789.012 -BodyAsHtml

Answer: Try:
$body = Get-Content 'C:\somewhere\some-file.html' | Out-String

The problem is probably that Get-Content is creating an array of strings and the -Body parameter is expecting a single string.
The Out-String cmdlet I think would convert it to a single string.
Comment: From PSv3+ you could use the `-raw` prarameter of [Get-Content](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/get-content?view=powershell-6)

powershell email body from file


Applications of fpqc descent of quasicoherent sheaves

Question: I have been learning about fibered categories and stacks from Vistoli's notes. One of the main results in the notes is the statement that the fibered category of quasicoherent sheaves over a scheme $X$ is a stack in the fpqc topology on the category of $X$-schemes. I can appreciate that this is a surprising result, as quasicoherent sheaves are a priori constructed as a Zariski stack, and the fpqc topology is strictly finer than the Zariski topology. Incidentally, I also think the proof presented in the notes is good practice with the concepts he introduces.
I am wondering about applications of this result, as they are not really mentioned in the notes. I am not familiar with descent theory outside of what is discussed in Vistoli, so I'm partly asking this to get a feel for the topic - a sort of "what's next?" The question: What are some examples of interesting results in which in some way use the fact that the fibered category of quasicoherent sheaves over a scheme is a stack in the fpqc topology?
Comment: This allows you to prove descent for the moduli space of polarized varieties, for example the moduli space of polarized K3 surfaces.
Answer: I don't know of any immediate applications, but this is a key result in showing you can descend curves (with the appropriate definition, see references) of genus $g \neq 1$. This is mentioned in example 4.39 of Vistoli's notes. A thorough investigation of this is given in this master's thesis. One wants descent for projective morphisms, which only works if they come with an ample line bundle with descent data - this is where we need the result about quasicoherent sheaves.
As Vistoli notes, this means that $\mathcal{M}_g$, the moduli space of genus $g$ smooth curves, is a stack. Deligne and Mumford study it in this paper, and use the fact that it's a DM-stack to prove some cool results about the geometry of the moduli space of smooth curves. I'm told that this really uses the fact that $\mathcal{M}_g$ is a stack, and hence better behaved than the coarse moduli space. For example, the coarse moduli space is not smooth, whereas $\mathcal{M}_g$ is a smooth DM-stack.
Finally, this is not an application, but the proof that QCoh is a stack is a prototypical example of fpqc descent, from which you can deduce many other cases such as descent for quasicoherent $\mathcal{O}_X$-algebras or (quasi-)affine morphisms.


Odd result when reading first byte of a PNG header

Question: I'm trying to read the header from a PNG file.
The result should be
Dec: 137 80 78 71 13 10 26 10
Hex: 89 50 4E 47 0D 0A 1A 0A

However, I get
Dec: 4294967 80 78 71 13 10 26 10

What am I doing wrong?
Code:
char T;
pngFile = fopen(Filename, "rb");
if(pngFile)
{
    fread(&T, 1, 1, pngFile);
    fclose(pngFile);
    printf("T: %u\n", T);
}

Comment: You seem to be reading a single byte only into a `char`, then printing that char out with an `unsigned int` format specifier.
Answer: 137 is too big for signed char - use unsigned char instead...
see this link for limits of data types.


How can I as a developer help system administrators improve webfarm deployments and stability of a web application?

Question: Problem:
Deploying, and managing this site has become a nightmare.  Deployment, going from development to QA, and pre production, takes a couple of days.  We have lots of errors, and it involves a lot of manual labor.  We often have config files that have been updated or changed incorrectly, and then the entire site on that web server fails.
The environment:

Plenty of web front end servers (windows 2003, IIS6)
Plenty of MemCached Servers (Linux)
Multiple database servers (SQL 2005)
Approx 5 million unique per month

More Detail:
I am one of the developers that are responsible for developing the system. Currently there is zero automation, zero automated testing, and the deploy process involves logging into the servers, with terminal server, and manually changing IIS settings, updating config files, and similar horror's. Disaster recovery documentation leaves a lot to be desired.
I would like to enable the team that handles the operations of the servers, to successfully deploy and maintain the application that I am working on. So for partly very selfish reasons, I want them to succeed.
I would like some direction; on what are specific questions I can ask them, or suggestions that I can make, on how as developers we can create things to help them be more successful.
Currently there is a bit of mudslinging going on, and I figure the only way to really fix that is to ignore the mudslinging, and focus on the problem.  And the problem currently is that it is VERY labor intensive to maintain, troubleshoot and deploy the site.
Thanks
Rihan
Answer:
Write code that checks the sanity of any configuration it gets given and reports problems both directly to the person doing the configuration, and in the logs.
Make a clear separation between configuration values that are environment-specific and those which should be carried unchanged up your Dev, Test, Acceptance, Prod (DTAP) street.
Use version management software (e.g. subversion) to track configuration changes in all your environments.
Manage the configuration of your DTAP environments like a megalomaniac.
Just after you deliver a release, and before you start coding again, arrange to have the Production environment copied over all the other environments including development. When you communicate this to your fellow devs, see which of them turn white, and ask them which assets they couldn't replace at will from source control.
Most importantly!!! You're probably reading this thinking, who is this idiot? That's impossible! We couldn't do all that. Dead right - of course you can't - not now. (If you weren't already in trouble, you wouldn't be asking the question). So separate vision from implementation. Share that vision with the other stakeholders. Decide together which capabilities you should have, and make a plan that starts getting you there. Each cycle or release or whatever, make sure you move another step closer to the vision. Set realistic targets, and meet them. (Of course, you're allowed to change your vision based on experience as you go along.)
Comment: With version managment software, we are using SVN, do you suggest updating SVN, and doing the deploy via svn?  Currently our msbuild script does create all of the required enviroment settings, builds the dll, and package it all up neatly- Do you suggest to move that process to the server level?

Thanks for your time in giving a very structured well thought out answer)
Comment: Actually - my answer was aimed at the generic case, rather than specifically your technology. Obviously, creating a .msi is also quite an attractive approach. The most important thing is being very clear which parts of the configuration are part of your delivery (and therefore must go through test), and which belong to the server admins. You can use SVN as a means of moving things up the environments (I have done this.) but also as a means of managing manual changes in a given environment. Perhaps you could create a branch for local changes in a given environment.
Comment: How strict should one be on the way that servers are being built?  The only way that I know to ensure constancy, across different machines, is using an automated build process / image as also pointed out by Alex. How high do you rate this as getting to a stable site?  How would you go about, if the system administrators did not feel the need to automate this process, and feel that installing the OS by hand is sufficient?
Comment: Dominic, what you said in your last point, made me realize you dont walk with your head in the clouds.  I have worked before with a sys admin that was a security freak, and the funny thing is, we never had downtime.  So I tend to feel that knowing what happens on your system and controling it like a megalomaniac is how you get a stable enviroment
Comment: Just re-reading this a few years on..... these days, I'd use git instead of svn.
Answer: I would say that apart from keeping the server settings and config files the same, you should have test environments to deploy to in your office. If your developers test that the code they developed works on an environment thats very much like a live environment, then they would feel more confident. More confidence means they necessarily develop faster (as this is something we have learnt from our SCRUM teams) and far less mudslinging and feeling of not being in control.
So basically what I am saying is, just give the developers lots of machines to play and test with and you will see positive results.
Comment: If you were in my shoes, and given the scenario, would you take this as your first priority.  We do the deployment in our SCRUM setup.  We do have a QA enviroment that is virtual, would you then just make a copy of the virtual enviroment, do the deploy, if it works great, if it does not, delete the state, and back to the drawing board?
Comment: Hear hear. If the only way to test is to deploy to the live environment and see what happens, there are serious risks.
Answer: The most important step is a simple way to make the configuration of all servers across your infrastructure as consistent as possible. A Standard Operating Environment (SOE), if you will:

All IIS instances have identical configuration.
All web servers have the same copy of the site on them.

Once you have this, it should become significantly more possible to implement automated rollouts, testing, and so on.
If the IIS configuration is identical across all servers, you can update the config file IIS uses on one master server and run a script to push it out to all webservers, test it, and reload IIS. You can do the same for your actual website files.
Answer: My guess is that if you had the option to standardize the servers you are going to deploy to, you would have done that by now, so I am going to skip that suggestion.  What you are going to need to do is build scripts/MSIs etc. to automate the deployment process for the operations team.  It will take some time to setup, but removing the Ops team's manual intervention from the process is the only way to make it run smoothly.  Now I am not insulting their intelligence, far from it.  The problem is that they don't know how the code works.  They don't know what a config file with a bad value will look like.  They depend on you knowing that to help them and the reason why automation is key to solving your problem.
My suggestion would be to setup virtual machines locally which mimic the various servers, so you can test over and over again how the install is going to work.  If your IT department is anything like mine, getting new servers will be difficult, as it involves budgeting and resource allocation etc.  Virtual machines remove a large part of the headache as you don't need new hardware, and input from anyone will be minimal as you'll only need to know how the servers are configured and then you can probably do the rest yourself.  VMs also allow you to quickly reset the machine to it's original state and try the install process again.
Comment: Kevin how far would you go with this "virtual" enviroment setup.  If we have load balancers setup, would you included that?  How about multiple SQL servers?  What do you guys measure, in terms of a good deployment.  Opening up the site in a browser, to say that the site code release has been sucessfully dont feel right to me.
Comment: @Rihan Mei I would just have virtual servers which mimic the ones which host the code.  We have it set up so that all the code is deployed through MSIs, and if there are any problems, the MSI roles back the installation.  Since we use it to deploy to everything (Test servers etc.) we know the code and process we deploy has been checked for errors, so all we have to worry about when we deploy to production is if it actually installs.
Answer: In my infrastructure, we've got a staging environment called preview where the data goes before it hits production. The application code in the staging level is exactly the same as the production code, so any data problems will show themselves there.
We've also got a test environment for new code, which operates on old, known-good data (which we can mangle when needed to test how the code fails).
Generally speaking, this segregation allows us to have a pretty solid production environment, and we don't see too many unexpected things crop up.
I should note that I don't deal too much with that, since I'm not a programmer. I just sync the databases and refresh the files when they ask me to ;-)
Answer: First and foremost CONSISTENCY.  Make sure that all of your servers are exactly the same. All W2003 web servers should look like the rest. All DB servers, All Linux server.  I mean same.  Same OS version, same patches, same directory structure... Everything!
Second comes staging.  You should have a separate server of each type, that can be used to test your deployment.  This is where you make all your configuration mistakes.  You would then copy your system from these deployment servers to production.
Third the "Separation of Concern" concept should be applied to your config files.  If different modules have different configuration items, put them in their own config file.  If there is machine specific configuration, move IT to its own config file.  This way you can deploy the affected config files from the deployment server along with the components themselves.
Answer: One word:  Backups
Make sure they have a good, centralized, redundant, and consistent backups in place.


Create update table of features vs plans

Question: I am looking for a way to achieve this with minimum custom module work.
Imagine a table with features listed down the left, and the plan names are going across the top as headings. Where these columns and rows meet is an icon to say whether this plan has that specific feature.
The ability to add new features needs to be possible easily through Drupal.
I was thinking of creating a plan content type and then the feature could be a field collection with a boolean, and some other data (a booleon on its own is not sufficient).
The issue with this is that you can't reuse field collections, so that would mean creating a field collection for each feature, not very user friendly and too much work for the end-user when they have to add a booleon, and a couple of other fields, also the template file would need to be modified to allow for this new field.
My next thought was to set the field collection as unlimited and then have the features as taxonomy terms, to then use hook_form_alter to first pull in the taxonomy terms and then pre-populate a term reference field for each instance of the field collection.
However this gets a little complicated when you think about a scenario in which someone adds a new feature as a taxonomy term. The custom module would need to look at the fields on the node in the field collections and check to see if the term exists already.
Maybe this would work, but is there a better way?
Answer: You might want to give a try to Editable Views module. So you would create a view page with columns and rows as you desire, making all the fields editable. Then you could change any field value (boolean if checkbox is used) just in place.


What is the bayesian uninformative exponential prior?

Question: I am looking to model a poisson process $X \sim Poisson(\lambda)$ and infer $\lambda$ using bayesian inference from $X$ e.g. $[0,0,0,2,1,0,0,2,1]$ could be my dataset. The data comes from the count of something occurring in a day.
I am considering $Exponential(\alpha)$ as my prior as it can represent positive real numbers, and I am wondering how to pick $\alpha$. If it is not possible to do so in an uninformative way, I would also like to know if there are methods to sensibly pick $\alpha$ or possibly whether there is a more suitable prior distribution.
The output would be a distribution around $\lambda$
Comment: It is not possible to pick $\alpha$ with no prior information about the scale of the problem.
Comment: Thank you Xi'an, that's good to know. Given this, is there a logical way to go about it's selection?
Comment: $\alpha$ is the inverse of the prior scale parameter for $\lambda$. Hence you need a prior opinion on the scale of $\lambda$. To know that this is a daily count does not help, as it could be a rare or a frequent event...
Answer: The conjugate prior for a Poisson likelihood is the Gamma distribution, conveniently described with a shape parameter and a rate parameter (the inverse of a scale parameter).
Your choice of an exponential distribution would correspond to a prior shape parameter of $1$, at which point you would need to choose a prior rate parameter, inserting information into your prior.
An alternative approach might be to choose a prior shape parameter of $0$ and a prior rate parameter of $0$, which is improper and largely meaningless in itself but would have the result that after observing $x_1,x_2,\ldots,x_n$ your posterior distribution would have a shape parameter of $\sum\limits_{i=1}^n x_i$ and a rate parameter of $n$. Providing that at least one of your observations was non-zero, this could be a fairly sensible posterior distribution with mean the intuitive $\frac{\sum x_i}{n}$,  and easy to work with and update further; you can see how little prior information is involved.
In your example, your Gamma posterior distribution for $\lambda$ would then have shape parameter $6$ and rate parameter $9$ under this alternative approach; compare this with starting with an exponential prior where the posterior would have shape parameter $7$ and rate parameter $9$ plus whatever rate you had chosen initially for your exponential.


An undirected graph $G$ can be decomposed into simple edge-disjoint cycles if and only if all of its vertices have even degree.

Question: Research effort:
$\rightarrow)$ I think this is relatively easy.
$\leftarrow)$ Let $G = (V,E)$, let $w$ be any vertex of $G$, given that all the vertex have even degree, I'm assured that I can construct a simple edge-disjoint cycle.
Now let's call this set of edges $S$.
Let $G' = (V,E/S)$
It's easy to see that given that I deleted a pair number of edges for each vertex (or none, in case the vertex was not part of the cycle), and every vertex in $G$ had a pair number of vertex, then, all the vertex in $G'$ have even degree or degree $0$.
Let $w'$ be a vertex in $G'$ whit degree more than $0$. I can construct another simple edge-disjoint cycle...
I can keep doing this procedure until all the vertex in the graph have degree $0$. And at this point I'll have decomposed $G$ into simple edge-disjoint cycles, then QED.
This proof is horrible, I can see some errors whit the reasoning, such when I say: "I'm assured that I can construct a simple edge-disjoint cycle".
Can you help me whit a more sound proof?
Comment: Try induction on the number of edges.
Comment: "I can construct a simple edge-disjoint cycle." What is an edge-disjoint cycle?? I mean, I know what a *set* of edge-disjoint cycles is, it just doesn't seem to mean much for a single cycle.
Comment: @vadim123 added an answer using your idea, works fine
Answer: I think this proof works. You are missing proper formulation of your ideas into proof. I will be using strong induction to prove that every even graph decomposes into cycles.
Lemma 1. : If every vertex of a graph G has degree at least 2, then G contains a cycle.
(Hint : consider maximal path in G).
Proof :
We apply induction on number of edges. For e = 3, triangle is the even graph, and it is the cycle itself. Let, this be true for all graphs having number of edges less than e, for some e > 3. Using Lemma 1. this even graph G contains a cycle C.
Consider the graph G' = G - E(C). G' is also an even graph, as the cycle has 0 or 2 edges at each vertex, so degree of each vertex remains even after removing edges of the cycle C. Now, G' is an even graph having lesser number of edges, so by principle of using induction it can be decomposed into cycles. The graph G now has the decomposition of G' and the cycle C. Hence proved.
QED.
Hope this clarifies your argument.
Comment: What do you mean with `Hint : consider maximal path in G`? How can I write a "maximal path" in a mathematical notation instead of words? Where did you find this lemma, source? Thx in advance!
Comment: Also your answer does not really address the question "if AND ONLY IF", i.e. shouldn't we show in addition to your approach, that cycles are not possible if the degree is odd?
Answer: Your proof would be absolutely fine if we can prove that the construction of a simple edge disjoint cycle is always possible. Take any vertex u with a positive degree and start a tour on adjacent vertices until you are unable to explore further. Keep deleting the edges you have traveled. Assume you end at vertex v. What we have is a trail (not path):
$$u,u_{1},u_{2}........v$$
The claim is, v has to be u.
Assume u and v are different. For every appearance of vertex v except the last one in the above list, there need to be two edges incident on v, one incoming and other outgoing. But for the last appearance, we need only one edge to enter the vertex v. Hence odd number of edges incident on v are used in the above trail. This leads to the fact there is at least one more edge on v yet to be explored. So the vertex v can not be the end of traversal. This proves u=v.
Now we have the circuit, which can be broken into disjoint edge cycles. How? For every two occurrence of a vertex y in the circuit, remove the circuit y-y from the parent circuit. Keep doing this recursively to get cycles.
Example: circuit $u,u_{1},u_{2},u_{3},u_{2},u$ be broken into $u,u_{1},u_{2},u$ and
$u_{2},u_{3},u_{2}$
Since we have deleted the edges explored, the cycles have disjoint edges. We recursively keep finding circuits in the main graph, deleting the edges until we have explored all the edges. Which completes your proof.
An easy proof- let $G_{1}$,$G_{2}$,$G_{3}$... be connected components of the graph. Since the degree of each vertex is even there are Eulerian circuit for each component. Then the trails can be broken into disjoint cycles for each component.
Comment: Fine. I think it would be simpler to stop exploring as soon as you visit some vertex $v$ for the second time; then discarding the vertices seen before the first visit to $v$ leaves you with a simple cycle $C$. Removing the edges of $C$, the remaining graph still has all degrees even, etc.
Comment: @bof yes we can do this. I constructed the circuit first to pave way for the easy proof using Eulerian circuits.
Comment: How is it easier? First, you have to have the theorem on Eulerian circuits available. (Maybe this exercise comes *before* Eulerian circuits?) Second, the proof that an Eulerian circuit can be decomposed into disjoint cycles seems to be just about the same as the proof that a graph with no odd degree vertices can be decomposed into disjoint cycles.
Comment: @bof true if one has to prove Eulerian circuit first, then it doesn't make things simpler.
Comment: I have tried to simply the proof further and make it less involved


How can I access the 'this' in a read.onloadend in a React component?

Question: I'm trying to read a file that the user uploads in a React component and set the state of the React component to the file contents. However, in the read.onloadend callback function, I can't access the state through this.
Here is the actual form part (I am using react-bootstrap)
      <FormGroup>
          <FormControl
            id="fileUpload"
            type="file"
            accept=".txt"
            onChange={this.handleSubmit.bind(this)}
          />
      </FormGroup>

And here is my function to handle submit:
  handleSubmit(e) {
    e.preventDefault()
    let inputtext;
    let file = e.target.files[0];
    let read = new FileReader();
    read.readAsBinaryString(file);
    read.onloadend = function(){
      this.setState({filetext : read.result});
    }
    read.onloadend.bind(this);
  }

Comment: please check working example to here https://codepen.io/santoshshinde2012/pen/XZwgLJ
Comment: If following answers solves your problem, please mark anyone as accepted and upvote. So that people can go ahead and solve other's questions.
Answer: Just use an arrow function.
That way this will not change.
handleSubmit(e) {
    e.preventDefault()
    let inputtext;
    let file = e.target.files[0];
    let read = new FileReader();
    read.readAsBinaryString(file);
    read.onloadend = () => {
      this.setState({filetext : read.result});
    }
  }

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#No_separate_this
Comment: Thank you! This was perfect! Arrow function was simplist solution.
Answer: It fails in the onload callback due to changed context (this). JavaScript natively change the context in callback. In your case in onload this is the same as reader.
Solution1: Use arrow operator (() =>).
Solution2: Assign that variable in parent scope of this.
Use following code
  read.onloadend = () => {
    this.setState({filetext : read.result});
  }

OR
   handleSubmit(e) {
      e.preventDefault()

      // assign parent scope to here
      let that =  this;

      let inputtext;
      let file = e.target.files[0];
      let read = new FileReader();
      read.readAsBinaryString(file);

      read.onloadend = function(){
        that.setState({filetext : read.result});
      }
      read.onloadend.bind(this);
    }

Please check the working example to here.
Hope this will help you!!
Answer: Since you don't have access to this inside. You have to implement it in following way.

handleSubmit(e) {
        e.preventDefault()
        let _this = this;
        let inputtext;
        let file = e.target.files[0];
        let read = new FileReader();
        read.readAsBinaryString(file);
        read.onloadend = function(){
            _this.setState({filetext : read.result});
            console.log(read.result);
        }

        read.onloadend.bind(this);
    }
<FormGroup>
    <FormControl
        id="fileUpload"
        type="file"
        accept=".txt"
        onChange={this.handleSubmit.bind(this)}
    />
</FormGroup>


Understanding the upper bound implications of $R(p,n) \le \log_p n$ in the context of Wikipedia's proof of Bertrand's Postulate

Question: In Wikipedia's proof of Bertrand's Postulate, in the second lemma, it is concluded that:
$$R = R(p,{{2n}\choose{n}}) \le \log_p 2n$$
where $R(p,n)$ is the p-adic order of ${2n}\choose{n}$
Later in the main proof, the implication is:
$$\prod\limits_{p \le \sqrt{2n}}p^{R(p,{{2n}\choose{n}})} \le (2n)^{\pi(\sqrt{2n})}$$
It seems to me that there is a slightly stronger upper bound that is also implied.
$$\prod\limits_{p \le \sqrt{2n}}p^{R(p,{{2n}\choose{n}})} \le \frac{(2n)!}{(2n - \pi(\sqrt{2n}))!}$$
Am I wrong?
Here's my thinking:
(1)  For each prime $p \le \sqrt{2n}$, there exists one unique number $p^{R(p,{{2n}\choose{n}})}$ that is less than or equal to $2n$.
(2)  Since each $p^{R(p,{{2n}\choose{n}})} \le 2n$ and distinct, it follows that $\prod\limits_{p \le \sqrt{2n}} p^{R(p,{{2n}\choose{n}})}$ will be less than or equal to $\frac{(2n)!}{(2n - \pi(\sqrt{2n}))!}$

Edit: I made the changes pointed out by John Omielan.
Comment: Two very minor points are that your $2n^{\pi(\sqrt{2n})}$ should be $(2n)^{\pi(\sqrt{2n})}$ instead, and your (2)'s "will be less than" doesn't technically follow, with "will be less than or equal to" being the correct phrase (although I believe that it will actually always be less than, the logic you're using technically only allows it to be less than or equal).
Answer: Your slightly stronger upper bound, and your thinking regarding it, are both correct. Good work. Nonetheless, FWIW, here's an alternate way to explain your (2). Let $\sigma$ be a permutation of $p^{R(p,{{2n}\choose{n}})}$ for all primes $p \le \sqrt{2n}$, with the values being in strictly decreasing order. With $m = \pi(\sqrt{2n})$, we therefore have
$$2n \ge \sigma_{1} \gt \sigma_{2} \gt \ldots \gt \sigma_{m} \;\;\to\;\; \sigma_{i} \le 2n - (i - 1) \; \forall \; 1 \le i \le m$$
Thus, by the commutative property of multiplication, we then get
$$\prod_{p \le \sqrt{2n}}p^{R(p,{{2n}\choose{n}})} = \prod_{i=1}^{m}\sigma_{i} \le \\
\prod_{i=1}^{m}(2n - i + 1) = (2n)\cdots(2n-\pi(\sqrt{2n})+1) = \frac{(2n)!}{(2n - \pi(\sqrt{2n}))!}$$


Trustwave PCI Complaince scan fails for fully patched CentOS 5.5

Question: I have a fully patched CentOS 5.5 server that is failing the Trustwave PCI compliance scan.  The items it is complaining about is openssl < 0.9.8.o.
rpm -q openssl shows:
openssl-0.9.8e-12.el5_5.7
The apache header banner shows:
Server: Apache/1.3.41 (Unix) PHP/5.2.14 mod_psoft_traffic/0.2 mod_ssl/2.8.31 OpenSSL/0.9.8b mod_macro/1.1.2
(note: that apache banner is not even showing the the installed version)
openssh and php have a similar situation (reported version is less than the minimum for PCI compliance).
Do I need to build all these libraries from source to get them on the latest version?  Or is there a way to tell CentOS yum to install the new version instead of their back-ported patched version?  I'd rather not go outside yum if possible so future maintenance will be simplified
Answer: All PCI scans do a version check based on headers and then they complain about the thirty or so problems you've got. What they don't take into account is that security fixes are backported to RHEL packages. As long as you're running the latests packages you should be fine. What you have to do after a failed scan is open a ticket to contest the results. Then you have to show what version is really installed
rpm -q httpd

Then you have to dig through the rpm changlog to find each CVE instance they mentioned.
rpm -q --changelog httpd

Where you're find things like this:
 * Thu Dec 03 2009 Joe Orton <firstname.lastname@example.com> - 2.2.14-1
 - add partial security fix for CVE-2009-3555 (#533125)

Finally you should link to the relevant link on Redhat's site to show it's been addressed since no one on the PCI scan side is actually going to look at an RPM.
https://www.redhat.com/security/data/cve/CVE-2009-3555.html
You'll probably go back and forth a few times and then finally you'll get a clean bill of health if you are actually updated. Once you've finished make sure to put all the support docs on your wiki since the PCI scan will reset every quarter or so and remove any mention of the information you provided and you'll need to do this again.
Answer: Back-porting fixes seems to be the preferred route for a lot of distributions.  It's not a solution but you should suppress server identity by setting "ServerTokens Prod" and "ServerSignature Off" in your httpd.conf.
It may be controversial for me to say this but I don't think scraping the banner counts for a vulnerability scan as it often results in a lot of false positives.  I think the scanner should actually be trying to see whether the known vulnerabilities for a particular version of a library actually exists and not making simple assumptions.  In some cases, they actually do make some effort to see whether a vulnerability exists.  An example would be the ssl cipher and protocol portions of the scans.
Of course, the problem one runs into when suppressing server identity is that many vulnerabilities previously reported are no longer reported and the administrator runs the risk of becoming lax in patching duties.  It is a bit of a paradox however because other types of vulnerability scans complain about the Information Disclosure issues when not setting ServerTokens to Prod.
You should compile everything from source, essentially creating your own custom apache distribution but with the frequency of updates, you'll be compiling new builds frequently and not everyone has the time to do this.
Answer: This isn't an answer to your question but I suspect apache is reporting the version of openssl it was compiled against, not the version it actually uses. On Fedora it is clearer:
[Fri May 13 03:45:05 2011] [info] mod_ssl/2.2.17 compiled against Server: Apache/2.2.17, Library: OpenSSL/1.0.0a-fips
[Fri May 13 03:45:05 2011] [notice] Apache/2.2.17 (Unix) DAV/2 PHP/5.3.6 mod_ssl/2.2.17 OpenSSL/1.0.0d-fips configured -- resuming normal operations

$ rpm -q openssl.x86_64
openssl-1.0.0d-1.fc14.x86_64


Why can't my Azure App service connect to my Azure Linux MongoDB instance?

Question: I have a standard Azure app service running NodeJS through IIS and a Linux VM running mongoDB.
When I set the firewall to allow all incoming connections into the VM, my app service has no trouble connecting to mongo. However, once I take this rule away, no connection is possible.
Now I know the solution seems obvious, "just add in a firewall rule", however, I don't know the IP address of the App Service as it's currently using shared hosting so I suspect it might change even if I did know.
There are currently 3 firewall rules.

Name: AllowVnetInBound Port:Any Protocol:Any Source:VirtualNetwork Destination: VirtualNetwork
Name: AllowAzureLoadBalancerInBound Port:Any Protocol:Any Source:AzureLoadBalancer Destination:Any
Name:DenyAllInBound Port:Any Protocol:Any Source:Any Desination:Any

Any help would be appreciated as I'm pulling my hair out over this.
Answer: App Service supports dedicated outbound IP addresses for apps deployed using the App Service Environment (ASE) feature.  You can determine the outbound addresses by looking at the properties of your webapp.
For the foreseeable future, apps running in the public multi-tenant service will continue to use outbound addresses from a shared address pool.  Please upvote this feature request if you would like to see dedicated outbound addresses.


Integration of characteristic function with varying boundaries

Question: I'm a bit puzzled about integrals with indicator/characteristic functions in them. How do I start computing the following integrals?
$$
A\int_{-\infty}^{\infty}f(x)\chi_{[-a+x,a+x]}dx
$$
and
$$
A\int_{-\infty}^{\infty}xf(x)\chi_{[-a+x,a+x]}dx
$$
In these integrals, $A$ is just a function that doesn't matter, a is a parameter value determined already (could be 2 for example), $x$ runs over the real axis and $f(x)$ is a function where assumptions can be made (so you may impose quadratic integrability if it would lead to a solution).
Any help would be greatly appreciated appreciated.
Answer: If $a \geq 0$ then $\chi_{[-a+x,a+x]}(x) = 1$ for all $x$ since $x \in [-a+x,a+x]$.  The first integral is just
$$
\int_{-\infty}^{\infty} f(x)\,dx
$$
and the second is
$$
\int_{-\infty}^{\infty} xf(x)\,dx.
$$


Understanding the statement of a question.

Question: The question is given below:
Let $f : S^n \rightarrow S^n$ be a map of degree $m.$ Let  $ X=S^n \cup_{f} D^{n+1}$ be the space attained from $S^n$ by attaching an $(n+1)$-cell via $f.$ Compute homology groups of $X.$
My questions are:
1- What is the importance of our map to be of degree m? what is the relation between $m$ and $n$?
2-Why when attaching an $(n+1)$-cell via $f$ that means we are attaching D ^{n+1} ?
3- Is the union supposed to be a disjoint union?
Answer: Regarding question 1, $m$ and $n$ are independent parameters. What you are asked to do is to answer this question for all $(m,n) \in \mathbb N \times \mathbb N$.
Regarding questions 2 and 3, what the expression
$$X = S^n \cup_f D^{n+1}
$$
means is that $X$ is the quotient of the disjoint union $S^n \coprod D^{n+1}$, using the decomposition which identifies each $x \in S^n = \partial D^{n+1} \subseteq D^{n+1}$ (the second term of the disjoint union) with the point $f(x) \in S^n$ (the first term of the disjoint union).
Answer: This should answer 2 and 3.
$X=S^n\cup_f D^{n+1}$ means, by definition that
$$X=\big(\text{disjoint unionion of }S^n\text{ and }D^{n+1}\big)/R$$
where $R$ is an equivalence relation given by: $xRy\iff f(x)=y$ for $x\in S^n$ and $y\in \partial D^{n+1}(=S^n)$.


Scaling the random variables $x$ and $y$ in $P(x > y)$ by some positive parameter

Question: Let $x$ and $y$ be two independent random variables and assume that both are
exponentially distributed,
\begin{align*}
x  & \sim\exp\left(  \lambda\right)  \\
y  & \sim\exp\left(  \mu\right)
\end{align*}
then we have that
$$
\Pr\left(  x<y\right)  =\frac{\lambda}{\lambda+\mu}.
$$
Suppose I need to know the probability of the scaled random variables
$\Pr\left(  x^{\alpha}<y^{\alpha}\right)  $ for $\alpha>0$. Is it true that
$$
\Pr\left(  x<y\right)  =\Pr\left(  x^{\alpha}<y^{\alpha}\right)  ?
$$
If yes, how can I show that? Does this hold for other distributions as well?
Comment: $X^a$ and $Y^a$ are not _scaled_ versions of $X$ and $Y$. _Scaled_ versions are $aX$ and $aY$.
Comment: This isn't a question about distributions: it's about *events*.  That's what the notations like "$x\lt y$" and "$x^\alpha\lt y^\alpha$" are referring to.
Comment: Since both are non-negative random variables, x x^a < y^a. It may not hold if x,y can take negative values.
Answer: Supposing $x$, $y$ positive:
$$ \Pr\left(  x^{\alpha}<y^{\alpha}\right) \\ = \Pr\left(  \ln (x^{\alpha})<\ln(y^{\alpha})\right) \\ = \Pr\left(  \alpha \ln (x)<\alpha\ln(y)\right) \\ = \Pr\left( \ln (x)< \ln(y)\right) \\ = \Pr\left( x< y\right)$$


Enable mysqlx plugin on AWS RDS

Question: Is there any way to enable the mysqlx plugin on an AWS RDS running MySQL 8?
When I do a SHOW plugins, it shows that the mysqlx plugin is installed, but DISABLED.
I have some C++ code that's using the MySQL C++ 8 connector and I want to avoid using the legacy JDBC connector; I already have the code running on a local VM and it's "easy" enough to have setup across the systems I need to deploy it save the fact that it needs the mysqlx plugin to be enabled on the SQL server.
Follow-up question: why would I not want to enable the mysqlx plugin? Specifically, I could not find much (or any) documentation as to why it's disabled on an AWS RDS (I presume there's some reason why it's disabled by default)?
Side note: if there's no way to enable it in AWS, and my only option is to go with the legacy JDBC C code, that's an acceptable answer, but if it's something as simple as UPDATE plugins SET mysqlx = ACTIVE and the only security/performance implications are the same as any other SQL server instance, then I'd rather go that route and avoid rewriting portions of my C++ app.
Answer: Answering my own question since I can't delete it: it seems they don't allow it, though the documentation is not only abysmal, it's practically non existent. It seems as though if it's not explicitly documented to being disabled, it's implicit that it's just not allowed for "reasons".
If you find this page in search of an "easy" way to write "modern" SQL connectors in the "cloud", good luck to you!

Enable mysqlx plugin on AWS RDS