text:
Q: Algorithm to determine how many items are left (at most) between sets that share items Suppose that we want to take items from 4 sets, S1-S4. The sets share items between them. Some example sets would be:
S1 = ['b1'];
S2 = ['b1', 'b2'];
S3 = ['b1', 'b2', 'b3'];
S4 = ['b1', 'b2', 'b3', 'b4'];

It is pretty obvious that if you pick one item from S1 (b1) then you can only pick 1 item from S2, 2 from S3 and 3 from S4.
But if you pick one item from S4 then at the next step you are able to pick all items from S1 or all items from S2 or all items from S3, simply because the algorithm must be smart enough to know that there is a combination (e.g. allocating b4 from S4) that will allow a higher max free elements from the other sets (by picking b4 you have max free 3 in S3, 2 in S2 and 1 in S1)
To put it in another way, the algorithm, when you occupy one element from a set, should not occupy a specific element but instead be smart enough to know how many elements (max number) can be occupied from the other sets given that the items are picked in a smart way.
Demonstration of how it should work (green = available, red = occupied, orange = occupied because of occupation from another set):

Another demonstration:

(note that the algorithm finds that S5 has 3 unique elements, so any other set is completely free)
And another one:

(notice that the algorithm understands that if you pick all 4 from S5 then you have to give up one from the other categories)
Another one:
(if you pick 3 items from S5 you will have to give up 1 item from S2 and now you can pickup only 2 elements from it at max. Notice that the occupied item in S2 is not a specific element, it's either b1 or b7, it doesn't matter, I'm only interested on what is the max number of elements that I can now pick from it)
All of the above work fine with my algorithm, but it fails in other occasions.
What I've tried so far (nodejs code but any language solution is welcome):
var allCategories = [];

const process = require('process');

Reset = '\x1b[0m'
FgRed = '\x1b[31m'
FgGreen = '\x1b[32m'
FgYellow = '\x1b[33m'

function getCommonCount(s1, s2) {
    return s1.filter((n) => s2.includes(n)).length;
}

var categories = {};
var common = {};
function processCategories() {
    categories = {};
    for (var i in allCategories) {
        categories[i] = {
            total: allCategories[i].length,
            occupied: 0,
            dueTo: {},
            totalDue: 0
        };

        common[i] = {};

        for (var j in allCategories) {
            if (i === j) {
                continue;
            }
            common[i][j] = getCommonCount(allCategories[i], allCategories[j]);
        }
    }
}

function occupy(countToOccupy, categoryId) {
    console.log('OCCUPY', countToOccupy, 'from', categoryId);

    var category = categories[categoryId];
    var free = category.total - category.occupied;

    if (free < countToOccupy) {
        console.log('Cannot occupy that many elements of type', categoryId);
        return false;
    }

    category.occupied += countToOccupy;

    for (var otherCategoryId in common[categoryId]) {
        var commonCount = common[categoryId][otherCategoryId];

        var atLeastThatMustOccupied =  (category.occupied + commonCount) - category.total;

        if (atLeastThatMustOccupied < 0) {
            continue;
        };

        var otherCategory = categories[otherCategoryId];

        if (otherCategory.occupied < atLeastThatMustOccupied) {

            var countToOccupyOtherCategory = atLeastThatMustOccupied - otherCategory.occupied;

            otherCategory.occupied += countToOccupyOtherCategory;

            if (!otherCategory.dueTo.hasOwnProperty(categoryId)) {
                otherCategory.dueTo[categoryId] = 0;
            }

            otherCategory.dueTo[categoryId] += countToOccupyOtherCategory;
            otherCategory.totalDue += countToOccupyOtherCategory;
        }
    }

    return true;
}

function deoccupy(countToDeoccupy, categoryId) {
    console.log('DEOCCUPY', countToDeoccupy, 'from', categoryId);
    var category = categories[categoryId];

    var reallyOccupied = (category.occupied - category.totalDue);

    if (reallyOccupied < countToDeoccupy) {
        console.log('There are not that much really occupied thingies here so as to deoccupy them');
        return false;
    }

    category.occupied -= countToDeoccupy;

    for (var otherCategoryId in common[categoryId]) {

        if (!categories[otherCategoryId].dueTo.hasOwnProperty(categoryId)) {
            continue; // no elements set due to the parent category
        }

        var dueToNumber = categories[otherCategoryId].dueTo[categoryId];

        var countToRemove = Math.min(countToDeoccupy, dueToNumber);

        if (countToRemove === dueToNumber) {
            // remove the dueTo field
            delete categories[otherCategoryId].dueTo[categoryId];
        } else {
            categories[otherCategoryId].dueTo[categoryId] -= countToRemove;
        }

        categories[otherCategoryId].totalDue -= countToRemove;
        categories[otherCategoryId].occupied -= countToRemove;
    }

    return true;
}

function visualizeCategories() {
    process.stdout.write(Reset);

    console.log()
    for (let categoryId in categories) {
        var category = categories[categoryId];
        var reallyOccupied = (category.occupied - category.totalDue);
        var free = category.total - category.occupied;
        process.stdout.write(FgGreen + categoryId + ' ');
        process.stdout.write(FgRed + '0'.repeat(reallyOccupied));
        process.stdout.write(FgYellow + '0'.repeat(category.totalDue));
        process.stdout.write(FgGreen + '0'.repeat(free));
        console.log()
    }

    console.log(Reset);
}

allCategories = {
    S1: ['b1'],
    S2: ['b1', 'b2'],
    S3: ['b1', 'b2', 'b3'],
    S4: ['b1', 'b2', 'b3', 'b4'],
    S5: ['b5', 'b1', 'b7', 'b8']
};

console.log('CATEGORIES:');
console.log(allCategories);

processCategories();

occupy(1, 'S1'); visualizeCategories();
occupy(3, 'S5'); visualizeCategories();
occupy(1, 'S2'); visualizeCategories();
occupy(1, 'S3'); visualizeCategories();

deoccupy(3, 'S5'); visualizeCategories();
deoccupy(1, 'S1'); visualizeCategories();
deoccupy(1, 'S3'); visualizeCategories();
deoccupy(1, 'S2'); visualizeCategories();

allCategories = {
    S1: ['b1'],
    S2: ['b1', 'b2'],
    S3: ['b2']
};

console.log('CATEGORIES:');
console.log(allCategories);

processCategories();

occupy(1, 'S1', true); visualizeCategories();
occupy(1, 'S3', true); visualizeCategories();

Code explanation:
processCategories analyzes the visualized categories and creates the data structure I'm using to figure out what needs to be occupied and deoccupied in occupy and deoccupy calls. The data structure looks like this:
category = { // or "set" of items
    total: // NUMBER: total entries of this set
    occupied: // NUMBER: how many elements of this set are occupied, either directly or indirectly
    dueTo: // OBJECT {categoryId -> number}: how many elements of this set are indirectly occupied and due to which category. (e.g. dueTo = {S1: 1, S3: 1} means 1 occupied indirectly through S1 and 1 indirectly through S3)
    totalDue: 0 // NUMBER: sum of the dueTo entries
};

Notes:

*

*The category processing creates the common object, which is essentially a 2d array and it saves how many common elements the categories have. (e.g. common['S1']['S2'] === 4)

*occupied - totalDue gives the directly occupied (red) entries.

*In order to occupy entries I use
var atLeastThatMustOccupied =  (category.occupied + commonCount) - category.total;
which seems to be working in some cases but in others it doesn't work.

*

*dueTo is used in order to de-occupy entries.

In the first images, the code works fine, in this example the code fails:

In the worst case real world scenario, the sets can have up to 300 items each, have up to 10 sets and the algorithm should be fast enough (hopefully < 1s in common cpus) to determine how many items can be picked from all the sets. Also, the algorithm should be able to de-occupy items e.g. do the opposite thing - remove an item from a set and determine how many items can now be picked from the other sets.
It is assumed that an element can be de-occupied from a set only if it is directly occupied from this set. (e.g. if S3 = ['b1', 'b2', 'b3'] and all of its elements are indirectly occupied, you cannot call de-occupy to remove elements from S3)


text:
Q: document.ready vs document.onLoad I am wondering which one is the right one to run the js code which calculates the height of vertical menu depending on the window height and sets it on time, not late, not early.
I am using document.ready but it is not really helping me with the issue, it is not setting sometimes, I have to reload the page, then it is working, but not on the first load.
How to solve this problem?
Here is my code:
$(document).ready(function(){
     var winh = document.body.clientHeight;
     var footer = document.getElementById('footer').offsetHeight;
     document.getElementById('sidebar').style.height = winh - 5/2*footer + 'px';
     document.getElementById('sidebar').style.marginBottom = footer + 'px';

     $(window).resize(function(){
         var winh = document.body.clientHeight;
         var footer = document.getElementById('footer').offsetHeight;
         document.getElementById('sidebar').style.height = winh - 5/2*footer + 'px';
         document.getElementById('sidebar').style.marginBottom = footer + 'px';
     });
});

A: ready
When you run code when the document is ready, it means the DOM is loaded - but not things like images. If images will affect the height and width and the image tag has no width and height set, ready isn't the choice for you - otherwise it probably is.
onload
This includes images - so everything will be loaded. This means it fires a bit later.
both
var calculateSize = function () {
     var winh = document.body.clientHeight;
     var footer = document.getElementById('footer').offsetHeight;
     document.getElementById('sidebar').style.height = winh - 5/2*footer + 'px';
     document.getElementById('sidebar').style.marginBottom = footer + 'px';
}

$(document).ready(function(){
    calculateSize();

     $(window).resize(calculateSize);
});

window.onload = calculateSize ;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Setting a cell equal to a value in pandas I feel like an idiot right now, why isn't this working
results = pd.DataFrame(columns=['avg_daily_rets','cum_rets','STDEV','Sharpe'])
results.cum_rets = 4
results

returns
avg_daily_rets  cum_rets    STDEV   Sharpe

with no values
whereas
results = pd.DataFrame(columns=['avg_daily_rets','cum_rets','STDEV','Sharpe'])
results.cum_rets = np.arange(5)
results

returns
avg_daily_rets  cum_rets    STDEV   Sharpe
0   NaN 0   NaN NaN
1   NaN 1   NaN NaN
2   NaN 2   NaN NaN
3   NaN 3   NaN NaN
4   NaN 4   NaN NaN

ultimately i'm doing this:
results = DataFrame(columns = ['avg_daily_rets','cum_rets','STDEV','Sharpe'])
results['avg_daily_rets'] = data.Daily_rets.mean()
print data.Daily_rets.mean()
results.cum_rets = data.Daily_rets.sum()
print data.Daily_rets.sum()
results.STDEV = data.Daily_rets.std()
print data.Daily_rets.std()
results.Sharpe = results.avg_daily_rets / results.STDEV * np.sqrt(250)
print results.avg_daily_rets / results.STDEV * np.sqrt(250)

0.0257851999606
46.3102191292
0.052303548452
Series([], dtype: float64)

and getting the same as above:
avg_daily_rets  cum_rets    STDEV   Sharpe

A: I think you can create and filled DataFrame by arrays instead of scalar docs:
print data
   Daily_rets
a           1
b           2
c           3

avg_daily_rets = data.Daily_rets.mean()
print avg_daily_rets
2.0

cum_rets = data.Daily_rets.sum()
print cum_rets
6

STDEV = data.Daily_rets.std()
print STDEV
1.0

Sharpe = avg_daily_rets / STDEV * np.sqrt(250)
print Sharpe
31.6227766017

print pd.DataFrame( { 'avg_daily_rets': [ avg_daily_rets ],
                      'cum_rets': [ cum_rets ],
                      'STDEV': [ STDEV ],
                      'Sharpe': [ Sharpe ] })

   STDEV     Sharpe  avg_daily_rets  cum_rets
0      1  31.622777               2         6

You can add parameter columns, if you want change order of columns:
print pd.DataFrame( { 'avg_daily_rets': [ avg_daily_rets ],
                      'cum_rets': [ cum_rets ],
                      'STDEV': [ STDEV ],
                      'Sharpe': [ Sharpe ] },
                    columns = ['Sharpe', 'STDEV','cum_rets','avg_daily_rets'])

      Sharpe  STDEV  cum_rets  avg_daily_rets
0  31.622777      1         6               2

A: The columns in pandas refer to Series objects, so you can't set them to an Int.
>>> import pandas as pd
>>> results = pd.DataFrame(columns=['avg_daily_rets','cum_rets','STDEV','Sharpe'])
>>> print type(results.cum_rets)
<class 'pandas.core.series.Series'>

Try
>>>results.cum_rets = [5]
>>> print results
  avg_daily_rets  cum_rets STDEV Sharpe
0            NaN         5   NaN    NaN

Pandas converts lists and dicts to Series, so you can make columns out of them.
EDIT:
I should have also pointed out, once you have the value, you can then set individual values directly. Eg:
>>>results.cum_rets[0] = 6
>>>print results.cum_rets
  avg_daily_rets  cum_rets STDEV Sharpe
0            NaN         6   NaN    NaN


text:
Q: jQuery UI error with flex slider I am Integrated a sliding tab on a page but there is error with jqueryui.js When i remove UI js then flex slider is working but sliding tab error. and when i used jqueryui.js the slide tab is working but flex slider is stop.
Below is our demo url in which i integrated both flex slider and UI tab
http://demo5.vivacityinfotech.net/magento/flex-slider

When i remove the jquery-ui. js file then i got below error:
TypeError: m.easing[this.easing] is not a function

Any one have idea to resolve this issue then please share with me.


text:
Q: Testar um construtor com mais de um parâmetro Estou tentando criar uma classe de testes para meu construtor, mas ele recebe três parâmetros e esses parâmetros são validados dentro da própria classe, para permitir ou não a criação da instância dele.
Segue código:
public class Mamiferos{
private String nome;
private Date dataNasc;
private String sexo;

public Mamiferos(String nome, Date dataNasc, String sexo){
    try {

        validaSexo();
        validaNome();
        validaData();

        }catch (Exception e) {
        // TODO: handle exception

        }finally{
            this.nome = nome;
            SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
            try {
                this.dataNasc = format.parse(dataNasc.toString());
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            this.sexo =sexo;
        }
}

private Boolean validaData() {

    Date dataAtual = new Date(System.currentTimeMillis());
    if (dataNasc.before(dataAtual)){
        return true;
    }else{
        System.out.println("Por favor, digite uma data válida.\n");
        return false;
    }
}

private Boolean validaNome() {

    if (nome.isEmpty() || nome.length()<5) {
        System.out.println("O nome deve ter ao menos 5 caracteres.\nDigite novamente.");
        return false;
    }else{
        return true;
    }
}

private Boolean validaSexo() {

    if (sexo != "Male" || sexo != "Female" || sexo.isEmpty()) {

        System.out.println("O sexo não pode ser nulo.\nDigite o sexo (Male/Female).\n");
        return false;

    } else {
        return true;
    }
}

Abaixo minha tentativa frustada de classe de teste:
public class NameTest {
    @Test
    public void test() {

    }

Sim, vazia, não sei como testar os validadores. Não queria deixá-los publicos pois não faz sentido.
PS: Aceito sugestões.
Obrigado!

A: Primeiramente sua classe tem alguns problemas:

*

*Os métodos validaData(), validaNome() e validaSexo() retornam um Boolean indicando se a validação foi bem sucedida ou não. Entretanto, o seu construtor simplesmente ignora o valor retornado, e como resultado, ele aceita os parâmetros mesmo que estejam errados, o que equivale a não realizar validação nenhuma.

*Os métodos validaData(), validaNome() e validaSexo() olham para os valores dos campos da sua classe antes dos mesmos terem sido definidos, e portanto sempre enxergarão os valores null e sempre falharão a validação mesmo se a sua classe for instanciada corretamente.

*Se algum dos métodos validaData(), validaNome() ou validaSexo() lançasse alguma exceção, você apenas a ignoraria, e isto significa simplesmente ignorar qualquer problema de validação e aceitar qualquer coisa.

*Os métodos validaData(), validaNome() e validaSexo() nunca retornam null e nem estão usando Boolean como a especificação de algum tipo genérico covariante. Por este motivo, use boolean ao invés de Boolean. Ou então use o mecanismo de exceções de forma adequada e mude o tipo para void.

*Não há sentido definir os valores dos campos no bloco finally do construtor. Aliás, nem sequer faz sentido usar o finally aqui.
Se o bloco try terminar com uma exceção, o código que invocou o construtor não poderá atribuir o resultado da chamada do construtor a nenhuma variável, e portanto a instância recém-criada será perdida. Ora, se a instância recém-criada será perdida, definir os valores de seus campos será uma atitude em vão.
Por outro lado, se o bloco try terminar normalmente, o código do finally também será executado normalmente tal como se estivesse logo após o try-catch.
Uma vez que o seu bloco try apenas come as exceções que são lançadas dentro dele, executar o finally seria equivalente a apenas seguir com o fluxo normal após o final do bloco try-catch, e neste caso o seu bloco finally é inútil.

*As mensagens de erro da validação são jogados fora no System.out.println e depois esquecidas para sempre. Não dá para utilizá-las após isso.

*Não vejo motivo de usar new Date(System.currentTimeMillis()); ao invés de simplesmente new Date();. Também acho mais simples definir a hora para meia-noite usando o GregorianCalendar ao invés de SimpleDateFormat, pois não há necessidade de tratar um ParseException.

*Se o construtor construir de fato o objeto, você vai precisar testar se ele construiu o objeto adequadamente. Por isso, alguns getters são necessários.

*Você está comparando Strings usando !=. Isso não vai fazer o que você quer. Além disso a sua validação sempre vai falhar porque sexo != "Male" || sexo != "Female" sempre vai ser verdadeiro, afinal o sexo sempre é diferente de macho ou fêmea, pois se for macho, então é diferente de fêmea (e portanto dá verdadeiro) e se for fêmea, então é diferente de macho (e também dá verdadeiro).
Não adianta tentar testar a validação de um construtor, se no final das contas ele efetivamente não consegue fazer validação nenhuma!
Vamos arrumar a sua classe. Vou usar IllegalArgumentException para representar um erro de validação. Vou fazer os métodos de validação validarem um parâmetro e o retornarem se este for aceito ou lançarem uma exceção se o rejeitarem. Também vou colocar a complexidade de jogar o Date para meia-noite (para retirar a hora) em um método a parte. A ideia é que o construtor lance uma exceção se receber parâmetros inválidos, o que significa que neste caso a instanciação do objeto é para todos os efeitos rejeitada.
public class Mamiferos {
    private String nome;
    private Date dataNasc;
    private String sexo;

    public Mamiferos(String nome, Date dataNasc, String sexo) {
        this.sexo = validaSexo();
        this.nome = validaNome();
        this.dataNasc = meiaNoite(validaData());
    }

    public String getNome() {
        return nome;
    }

    public Date getDataNasc() {
        return dataNasc;
    }

    public String getSexo() {
        return sexo;
    }

    public static Date meiaNoite(Date data) {
        GregorianCalendar gc = new GregorianCalendar();
        gc.setTime(data);
        gc.set(Calendar.HOUR, 0);
        gc.set(Calendar.MINUTE, 0);
        gc.set(Calendar.SECOND, 0);
        gc.set(Calendar.MILLISECOND, 0);
        return gc.getTime();
    }

    private static Date validaData(Date dataNasc) {
        Date dataAtual = new Date(System.currentTimeMillis());
        if (!dataNasc.before(dataAtual)) {
            throw new IllegalArgumentException("Por favor, digite uma data válida.");
        }
        return dataNasc;
    }

    private static String validaNome(String nome) {
        if (nome.isEmpty() || nome.length() < 5) {
            throw new IllegalArgumentException("O nome deve ter ao menos 5 caracteres.\nDigite novamente.");
        }
        return nome;
    }

    private static String validaSexo(String sexo) {
        if (!"Male".equals(sexo) && !"Female".equals(sexo)) {
            throw new IllegalArgumentException("O sexo não pode ser diferente de Male/Female.");
        }
        return sexo;
    }
}

Agora vamos testar a sua classe:
public class TestMamiferos {

    private Date amanha() {
        GregorianCalendar gc = new GregorianCalendar();
        gc.add(Calendar.DATE, 1);
        return gc.getTime();
    }

    private Date ontem() {
        GregorianCalendar gc = new GregorianCalendar();
        gc.add(Calendar.DATE, -1);
        return gc.getTime();
    }

    @Test
    public void testInstanciaNormalmenteMale() {
        Date d = ontem();
        Mamiferos m = new Mamiferos("Gatinho", d, "Male");
        Assert.assertEquals("Gatinho", m.getNome());
        Assert.assertEquals(Mamiferos.meiaNoite(d), m.getDataNasc());
        Assert.assertEquals("Male", m.getSexo());
    }

    @Test
    public void testInstanciaNormalmenteFemale() {
        Date d = ontem();
        Mamiferos m = new Mamiferos("Gatinha", d, "Female");
        Assert.assertEquals("Gatinha", m.getNome());
        Assert.assertEquals(Mamiferos.meiaNoite(d), m.getDataNasc());
        Assert.assertEquals("Female", m.getSexo());
    }

    @Test
    public void testInstanciaNomeCurto() {
        try {
            new Mamiferos("A", ontem(), "Female");
            Assert.fail();
        } catch (IllegalArgumentException e) {
            Assert.assertEquals("O nome deve ter ao menos 5 caracteres.\nDigite novamente.", e.getMessage());
        }
    }

    @Test
    public void testInstanciaDataFuturo() {
        try {
            new Mamiferos("Gatinha", amanha(), "Female");
            Assert.fail();
        } catch (IllegalArgumentException e) {
            Assert.assertEquals("Por favor, digite uma data válida.", e.getMessage());
        }
    }

    // Outros testes
}

Enfim, este é o caminho dos testes. Nos testes que verificam o sucesso, o objeto é instanciado e o seu estado é verificado para certificar-se que o objeto foi devidamente inicializado pelo construtor. Nos testes que verificam as falhas, o Assert.fail() faz o teste falhar se o construtor não lançar uma exceção (uma vez que ele deveria lançar) e a exceção esperada é capturada e então é verificada se está correta (ou seja, que não se trata de alguma outra exceção diferente).
Recomendo testar todos os casos aonde uma exceção pode ser lançada, tal como o sexo inválido (que deixei de fora da classe de teste, este fica para você fazer). E aliás, há mais duas coisas que deixo para você resolver e aplicar os teste de unidade correspondentes:

*

*Se você passar null como parâmetros, ele deve rejeitar? O seu código apenas lança um NullPointerException que é imediatamente engolido neste caso. O meu código vai lançá-lo sem engulir. Altere o código para tratar isto e coloque um teste correspondente para cada caso aonde isso puder ocorrer.

*Você realmente deveria usar um enum para representar o sexo. Isso tornaria a sua vida bem mais fácil.
E por fim, recomendo estudar tratamento de exceções, você claramente não entende como ele funciona.

A: Minha sugestão e o Hibernate Validator.
O Hibernate Validator é uma implementação da especificão Bean Validation.
O Bean Validation permite aplica regras de restrições em forma de anotação.
Classe Mamifero usando Hibernate Validator:

public class Mamifero {

@NotEmpty
@Length(min = 5)
private String nome;

@Past(message = "Por favor, digite uma data válida.")
private Calendar dataNasc;

@NotEmpty(message = "O sexo não pode ser nulo.")
@Pattern(regexp = "(Male|Female)", message = "Digite o sexo (Male/Female).")
private String sexo;

public Mamifero(String nome, Calendar dataNasc, String sexo) {
    this.nome = nome;
    this.sexo = sexo;
    this.dataNasc = dataNasc;
  }
}

Para validar:

// Como é de costume nas especificações o método Factory
ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();

// O validador
Validator validator = validatorFactory.getValidator();

Calendar dataNasc = Calendar.getInstance();
dataNasc.set(Calendar.YEAR, 2003);
dataNasc.set(Calendar.DAY_OF_MONTH, 17);
dataNasc.set(Calendar.MONTH, Calendar.JANUARY);

Mamifero mamifero = new Mamifero("Cachorro", dataNasc.getTime(), "Male");

// Valida e retorna uma lista Set com as restrições violadas como objeto ConstraintViolation
Set<ConstraintViolation<Mamifero>> violations = validator.validate(mamifero);

Para validar so uma propriedade do objeto:

Set<ConstraintViolation<Classe>> violations = validator.validateProperty(objeto, "propriedade");

A classe de teste:

public class MamiferoTest {

private Validator validator;

@Before
public void setUp() {
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    this.validator = factory.getValidator();
}

@Test
public void testeArgumentoNomeSemNada() {
    Calendar dataNasc = Calendar.getInstance();

    dataNasc.set(Calendar.YEAR, 2003);
    dataNasc.set(Calendar.DAY_OF_MONTH, 17);
    dataNasc.set(Calendar.MONTH, Calendar.JANUARY);

    Mamifero mamifero = new Mamifero("", dataNasc, "Male");

    Set<ConstraintViolation<Mamifero>> violations = validator.validate(mamifero);

    for (ConstraintViolation<Mamifero> violation : violations) {
        System.out.println(violation);
    }

    assertEquals(2, violations.size());
}

@Test
public void testeDataInvalida() {
    Calendar dataNasc = Calendar.getInstance();

    dataNasc.set(Calendar.YEAR, 2016);
    dataNasc.set(Calendar.DAY_OF_MONTH, 17);
    dataNasc.set(Calendar.MONTH, Calendar.JANUARY);

    Mamifero mamifero = new Mamifero("Cachorro", dataNasc, "Male");

    Set<ConstraintViolation<Mamifero>> violations = validator.validate(mamifero);

    for (ConstraintViolation<Mamifero> violation : violations) {
        System.out.println(violation);
    }

    assertEquals(1, violations.size());
}

@Test
public void testeSexoIncorreto() {
    Calendar dataNasc = Calendar.getInstance();

    dataNasc.set(Calendar.YEAR, 2003);
    dataNasc.set(Calendar.DAY_OF_MONTH, 17);
    dataNasc.set(Calendar.MONTH, Calendar.JANUARY);

    Mamifero mamifero = new Mamifero("Cachorro", dataNasc, "Masculino");

    Set<ConstraintViolation<Mamifero>> violations = validator.validate(mamifero);

    for (ConstraintViolation<Mamifero> violation : violations) {
        System.out.println(violation);
    }

    assertEquals(1, violations.size());
  }
}

Para incluir em um projeto maven adiciona as seguintes dependências:

<dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-validator</artifactId>
   <version>5.1.3.Final</version>
</dependency>

Hibernate Validator requer implementação do Unified Expression Language (EL):

<dependency>
   <groupId> javax.el </groupId>
   <artifactId> javax.el-api </artifactId>
   <version> 2.2.4 </version>
</dependency>
<dependency>
   <groupId> org.glassfish.web </groupId>
   <artifactId> javax.el </artifactId>
   <version> 2.2.4 </version>
</dependency>

Seu projeto não for maven baixa os jars no site.

A: Você quer testar métodos privados de uma classe em um Test Unitário.
Solução Número 1(o ideal é o approach da solução 2, esta é uma alternativa)
Escreva seu Test como como uma membro público e estático da própria classe que tem seus métods privados.
Você vai precisar:

*

*transformar seus métodos de validação em métodos estáticos.

*criar uma classe pública como uma static inner class

*Passar os valores como parametros para esses métodos
A vantagem desse approach é que é o mais simples e rápido, mas não melhor. Você terá um membro público que não tem coesão com a sua classe. E uma mistura de concerns diferentes em uma mesma classe. O ideal é ter seus testes bem separados.
Solução Número 2
Utilize Reflection para executar seus métodos privados em outros contextos.
Essa segunda solução funciona tanto para métodos státicos como para métodos não estáticos.
Reflection vai oferecer a você a opção de suprimir os checks de fields e métodos da JVM.
public void test()throws Exception{
    Class<?> clazz = Mamiferos.class;

    //vai precisar de um construtor publico sem argumento, ou acessar
    //seu contrutor privado, mudar acessibilidade dele e então instanciar
    //Ou apenas crie uma nova instancia de Mamifero
    //Mamifero m = new ....
    Object obj = clazz.newInstance();// = m;

    Method method = clazz.getDeclaredMethod("validaSexo");

    method.setAccesible(true);//Aqui está o segredo, ete método suprirá o modificador de acesso

    method.invoke();//Chamada ao seu método validaSexo
}

Como principal ponto negativo está o fato de você ter de excerver um código mais verboso, que o uso de Reflection em Java implica. Quanto a performance, apenas se você trabalhar em aplicações de ultra baixa latencia, isso será algo para se preoculpar. A JVM tem uma propriedade chamada Fast Reflection:

http://www.oracle.com/technetwork/java/whitepaper-135217.html

Para ter um código mais legível e poderoso para operações reflectivas, considere usar a API Gren-Rfletea;

https://github.com/FilipeGMiranda/GreenReflectea


text:
Q: SharePoint 2010 - Change table row /cell hover effect In SharePoint 2010 when you hover over a column heading (i.e. to sort) in a list table, you get a hover effect, how can you supress / change this? I can see it uses OnChildColumn(this), so is there a way to modify this - either preventing the effect (e.g. when sorting can't be done on a column), or using a different background image?
Also want to do the same when you hover over a cell in any of the list table's contents.

A: I would suggest to use jquery for this.
you can find 's4-ctx' class using selector.
Upload transparent image and on hover you can dynamically change image url. Current it points to "/_layouts/images/ecbarw.png".
Let me know your thoughts on this.

A: I would create an alternate style sheet that overrides the following from corev4.css:

*

*tr.ms-viewheadertr > th.ms-vh:hover,tr.ms-viewheadertr > th.ms-vh2:hover

*anything that uses .s4-ctx-show


text:
Q: Is it bad practice to say "a husband and his wife" because of redundancy? Phrasing like "a husband and his wife" or "a daughter and her father" always irked me, for being a bit redundant. Surely, it is enough to say "man and his wife" (or in the case of same-sex marriages "woman and her wife"), as saying "husband" already includes a relationship with, and existence of, a "wife".
Is it bad practice (or grammatically ill-advised) to say "a husband and his wife"?
Also, is it any better to say "a husband and a wife"? How does "a pet and its owner" fare?

Some examples:

The film ABC features a husband and his wife, on a spiritual journey to master the English language.
A daughter and her father appeared on my doorstep, asking for donations to Wikipedia.

A: Redundancy is not bad practice. The majority of everything we say or write is superfluous, redundant, or pointless. 90% of your question is pointless and redundant. 90% of this answer is. However, it is not a rule of English (or any language) that everything that can be reworded must be reworded, and everything that can be removed must be removed. Pointlessness and redundancy are not wrong, they are merely pointless and redundant.
As to grammaticality, absolutely any pair of noun phrases connected by an and is equally grammatical English. That includes a husband and his wife, a husband and his husband, a husband and my mathematics, a husband and two Russians, and a husband and your insanely speedy frog sleeve bucket. To you, or even to everyone, some of these may make less sense than others, but that has no bearing whatsoever on the fact that they are grammatically impeccable English.
With that out of the way, let's turn to the elephant in the room here.
Why would you want to replace the first term anyway? More often than not that will be plain impossible. That's not how language works. How it works is that you're talking about that cool new series, and you start by saying, "oh, you know that cool new series about a husband and..." and then you realize that now you will have to mention his wife as well, but you can't go back and turn him into something else anymore. You have already said "a husband". So if you now want to avoid the awkwardness of saying "a husband and his wife", you can only do that by changing the second term, the one you've not put in words just yet.
So, what do you say, then? "A husband and his... um, spouse"? "A husband and his, um, better half"? "A husband and his... woman"? That's even worse than "a husband and his wife".
Same for "a daughter and her father". If you happen to have said "a girl and her father" in the first place, you're fine. But if you've already begun by saying "a daughter and", then how do you go on to fix it on the fly? "A daughter and that man whose daughter she is"? "A daughter and her male ancestor"? "A daughter and the grown-up man of whom she's in direct lineage"? "A daughter and the dude whose loins she's the fruit of"?
So saying "a daughter and her father" is actually the best alternative you have at that point.
And you can't even completely drop him from the sentence, either, because you do want to talk about two people, not one. The daughter wasn't there all alone. Just like that cool new series is not about the husband and nobody else.
Now, of course if we are talking exclusively about written language that you can go back and edit, then yes, it's obviously stylistically preferable to say "a girl and her father", or something to that extent. But, even so, as a quick reminder: style is not grammar. Nobody is under any obligation to follow a style that you or I happen to like. Just like nobody is under any obligation to only wear shoes of your favorite color, or my favorite size. Or any shoes at all, for that matter.

A: As Cargill's comment mentions, not all cases can be considered equivalent. Having only one of the words indicate the relationship may imply a heirarchy between them. In cases such as marriage where it is generally accepted that both parties have equal status, the word choice should avoid the implication. This is where "husband/wife and wife/husband" is more accepted. If the two were not married, each would be referred to as "a husband" or "a wife". In general there would be no reason to refer to someone as a "husband/wife" unless it is relevant. It is acceptable to say "woman and her wife" or "man and his husband," as without a gender difference there is less distinction which makes it harder to imply that one is more or less important than the other, and saying something like "wife and wife" is redundant.
In other cases, only one of the two words needs to indicate the relationship. Having both words indicate the relationship may be more explicitly clear but can also sound redundant. In these cases you could say "girl and her father," "man and his daughter," "pet and its owner," or "man/woman and his/her pet."
Another exception to this would be where the relationship is relevant to the subject, and both words should indicate that relationship. This would be cases such as "a father and son talk" or "mother and daughter time."


text:
Q: Has anyone managed to compile nmon for freebsd? or alternatives? Im used to this great tool called nmon.
if you havnt heard of it you should check it out
Anyway im dabbeling with freebsd, and wanted to see if i can get it compiles.
I managed to get the includes working, more or less atleast.
and it compiles.
But it segfaults when i run it.
So has anyone run compiled it under freebsd or anyone have a good alternative?

A: Try these:
systat -vmstat 1 # BSD summary of system statistics (1 s intervals)
systat -tcp 1 # BSD tcp connections (try also -ip)
systat -netstat 1 # BSD active network connections
systat -ifstat 1 # BSD network traffic through active interfaces
systat -iostat 1 # BSD CPU and and disk throughput

A: This tool won't work on FreeBSD since it relies on Linux's /proc filesystem to gather information. FreeBSD's /proc filesystem is totally different.
As an alternative, have a look at the built-in systat program.

A: I ported nmon to FreeBSD and it works fine; the sources and binaries is here: http://mygnuos.tk/software/free/nmon/
Please note this tool could work on FreeBSD only if you mount the linprocfs at /proc

mount -t linprocfs procfs /proc


text:
Q: Include a JS file using jQuery I actually have a problem with including JS file using jQuery. I found many sources but no one work with me. I'm pretty sure that the path of the js file is right. These are my two tries :
The first one (which I prefer) is working with <link> (to include CSS files) but it's not working with <script> tags.
 $('head').append('<script type="text/javascript" src="'+addon+'"></script>');

And the second one is by using get HTTP request. And here is my try :
 $.getScript(addon, function(){});

So, the question is: what is wrong with the first code? Because I tried it before with <link> tags and its working so good.

A: You MUST escape the end tag <\/script> otherwise you close the scripts prematurely

A: Have you considered:
$('<script />', { type : 'text/javascript', src : addon}).appendTo('head');

This avoids having to manually escape the </script> closing tag.

A: try $.holdReady(true);
$.getScript("sample.js", function() {
    $.holdReady(false);
});
This ensures that your js is fully loaded before the onready object is fired and thus you can be sure that any objects/functions of the dynamically included js are available.

A: try
$.when(
    $.getScript( "sample.js" ),
    $.getScript( "simple.js" ),
    $.getScript( "jquery.js" ),
    $.Deferred(function( deferred ){
    $( deferred.resolve );
    })
    ).done(function(){
        //place your code here, the scripts are all loaded
});


text:
Q: Upgrade to Kotlin 1.4 get error compiler about module-info.class I'm using Kotlin version 1.3.7 . So when I upgrade to 1.4.10 I get the compiler error
Cause: cannot find META-INF.versions.9.module-info: module-info found in META-INF/versions/9/module-info.class

Is there any help?

A: Please add the following code inside android block which is present in your app-level gradle file.
android
{
    ...
    packagingOptions {
        exclude 'META-INF/atomicfu.kotlin_module'
    }
}


text:
Q: How do I use VHDL generic parameters when I place a sheet symbol in Altium? I'm using Altium Designer Winter 09 to synthesise a design for an FPGA. This includes a VHDL-defined entity MyShifter that includes generic parameters so I can have it be reuseable:
library IEEE;
use IEEE.Std_Logic_1164.all;

entity MyShifter is

generic
(
       data_width : positive;
       pad_width : positive
);

port
(
    -- ...other ports...
    DataIn        : in std_logic_vector(data_width-1 downto 0)
);

-- architecture follows...

With any other VHDL entity I could just right click on a schematic and use Place » Sheet Symbol, and then synchronise the sheet entries with the ports defined in VHDL. Altium will, later on, automatically generate the higher-level VHDL that maps ports to other ports and I don't have to worry about it.
When I try this with my entity-with-generics, I end up with sheet entry labelled DataIn[-1..0]. This is unsurprising, since I haven't "told" Altium what data_width actually is.
My question is: how do I tell Altium what the generic parameters data_width and pad_width are for a particular instance of MyShifter?

A: I'm not sure a good solution exists.  You could add a second VHDL file that instantiates your first VHDL file's entity with the appropriate generic map.  Then you could just place that second-level VHDL file onto the schematic.
Not ideal, but it maintains reusability, as you can just make new second-level files for every different size you want, and you only have to change the first-level file to affect all instantiations.

A: Have you tried adding it as a parameter to the sheet symbol?
Double-click on the sheet symbol, Go to the parameters tab, and add a parameter data_width. I would guess you want it of type INTEGER.
I'm kinda guessing here. I don't really use Altium with logic synthesis.

You may have to correct the sheet-entry labels manually after you add a parameter (or maybe just recompile the project).

Alternatively:
I know you can define project variables, but I don't know if they are presented to the VHDL synthesis system. If data_width is used in multiple places (and is the same everywhere), it may be worth trying.
Project >> Project Options >> "Parameters" tab.
It does not have the data-type options of the sheet-symbol, as described below, so it's possible that the VHDL synthesis system does not see project parameters.

A: 1- If you add parameters to the VHDL symbol as suggested above:

this will add the following code the the VHDL file:

2- The easiest way to get the results that you requested, is just to add a single line at the beginning of the vhdl file:

to verify that this works, you can quickly synchronize the symbol with the vhdl sheet


text:
Q: How to fix "key pair not generated" when generating CSR I was using the process detailed here to generate a SSL cert for tomcat:
GoDaddy tomcat installation docs
I made a mistake and put the wrong CN name when prompted by the keystore command, and when I tried to start over, I got the error "key pair not generated".
How can I fix it?

A: To fix it, I simply got rid of the 2 files that the tutorial created ("crt.crt" file and "tomcat.keystore") and then I could start the process over again. And as suggested in the comments, backup your original files before doing this.


text:
Q: How to do pagination in my jsp pages I have two jsp pages.One is searchData.jsp and another one is searchResult.jsp.
searchData.jsp
<form action="searchResult.jsp" method="POST">

                                Search Using:
                                <select name="search">
                                        <option value="Company_Name">Company Name</option>
                                        <option value="Contact_Person">Contact Person</option>
                                        <option value="Phone">Phone Number</option>
                                    </select>
                                of Category:
                                <select name="category">
                                        <option value="hospital"><bean:message key="select.hospital" /></option>
                                        <option value="company"><bean:message key="select.company" /></option>
                                        <option value="institution"><bean:message key="select.institution" /></option>
                                        <option value="others"><bean:message key="select.other" /></option>
                                    </select>
                                <input type="text" name="search_tf" />
                                <input type="submit" value="Search" />

                            (Blank Search will result in Full Search Result)

                </form>

when i will select company name and company and click on submit it will go to searchResult.jsp and it will display but my problem is i have 30 to 40 records in it and i have to put 10 records per page.So here pagination is necessary,i have tried using javascript and jquery but i am not getting correct pagination.Here is my code for searchResult.jsp
searchResult.jsp
<form method="post" name="form">

   Id
   Date & Time
   Company Name
   Contact Person
   Address
   Phone
   Company Email
   Follow Up Action
   Status
   Lead Details
   Lead Value
   Follow Up Date
   Category
   Action

    <%@page import="java.sql.ResultSet"%>
    <%@page import="java.util.ArrayList"%>
    <%@page import="java.util.Iterator"%>
    <%@page import="java.sql.Statement"%>
    <%@page import="java.sql.Connection"%>
    <%@page import="java.sql.DriverManager"%>
    <%
    Connection con = null;
    Object o2 = session.getAttribute("email");
    String email = o2.toString();
    String category = request.getParameter("category");
    String search = request.getParameter("search");
    String search_tf = request.getParameter("search_tf");
    Statement st, st1;
    try {
                                        Class.forName("com.mysql.jdbc.Driver").newInstance();
    con = DriverManager.getConnection("jdbc:mysql://localhost:3306/marketing_database", "root", "root");
  st = con.createStatement();
  st1 = con.createStatement();
  System.out.println("At SearchResult.jsp:" + email + "," + category + "," + search + "," + search_tf);
  ResultSet rs = st.executeQuery("Select Id,Company_name,Contact_Person,Address,Phone,Company_Email,Review,Status,Lead_Date,Lead_Details,Lead_Value,followup_Date,Category from marketing_database.lead where Email = '" + email + "' OR " + search + " LIKE '%" + search_tf + "%' ORDER BY Id;");
  String q2 = "update dummy set category='" + category + "' where id = '1';";
  st1.executeUpdate(q2);                    // To insert the category name to dummy table in database
%>

  <%
  while (rs.next()) {
  %>

<%=rs.getString(1)%>
  <%=rs.getString(9)%>
  <%=rs.getString(2)%>
   <%=rs.getString(3)%>
   <%=rs.getString(4)%>
   <%=rs.getString(5)%>
   <%=rs.getString(6)%>
   <%=rs.getString(7)%>
   <%=rs.getString(8)%>
   <%=rs.getString(10)%>
   <%=rs.getString(11)%>
   <%=rs.getString(12)%>
   <%=rs.getString(13)%>
   <input type="button" name="edit" value="Edit" style="background-color:#49743D;font-weight:bold;color:#ffffff;" onclick="editRecord(<%= rs.getString(1)%>);" >
   <input type="button" name="delete" value="Delete" style="background-color:#ff0000;font-weight:bold;color:#ffffff;" onclick="deleteRecord(<%= rs.getString(1)%>);" >
                                        <% count++;%>

                                <%
                                    }
                                %>
                                <%
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                %>

                        </form>


text:
Q: Unable to externally access Nodeport service setup on Minikube (Windows WSL Ubuntu 20.04.2 LTS) I have a running docker image which has been hosted as a pod on my Minikube cluster. However I am not able to access the Nodeport service that I have linked with it. Here are the details:
I start Minikube on my Windows WSL using this command since direct start throws issues with root access.
root@DESKTOP-RNQPOG3:/mnt/c/Users/vijay# minikube start --driver=docker --force
  minikube v1.23.2 on Ubuntu 20.04 (amd64)
❗  minikube skips various validations when --force is supplied; this may lead to unexpected behavior
✨  Using the docker driver based on existing profile
  The "docker" driver should not be used with root privileges.
  If you are running minikube within a VM, consider using --driver=none:
    https://minikube.sigs.k8s.io/docs/reference/drivers/none/
  Tip: To remove this root owned cluster, run: sudo minikube delete
  Starting control plane node minikube in cluster minikube
  Pulling base image ...
  Restarting existing docker container for "minikube" ...
  Preparing Kubernetes v1.22.2 on Docker 20.10.8 ...
  Configuring Calico (Container Networking Interface) ...
  Verifying Kubernetes components...
    ▪ Using image kubernetesui/dashboard:v2.3.1
    ▪ Using image kubernetesui/metrics-scraper:v1.0.7
    ▪ Using image k8s.gcr.io/ingress-nginx/controller:v1.0.0-beta.3
    ▪ Using image k8s.gcr.io/ingress-nginx/kube-webhook-certgen:v1.0
    ▪ Using image k8s.gcr.io/ingress-nginx/kube-webhook-certgen:v1.0
    ▪ Using image gcr.io/k8s-minikube/storage-provisioner:v5
  Verifying ingress addon...
  Enabled addons: storage-provisioner, default-storageclass, ingress, dashboard
  Done! kubectl is now configured to use "minikube" cluster and "default" namespace by default

The image is already present on the cluster and I am able to curl it when I directly run the image alone.
I currently have a deployment and service on my Minikube node like so:
root@DESKTOP-RNQPOG3:/mnt/d/Coding/milestone9/Milestone9# k get deploy -o wide | grep admin
admin-deployment   3/3     3            3           8m53s   admin        admin:alpine                            app=konnectMojo
root@DESKTOP-RNQPOG3:/mnt/d/Coding/milestone9/Milestone9# k get svc -o wide | grep admin
admin-service             NodePort    10.106.40.240   <none>        80:30007/TCP   8m28s   app=konnectMojo
root@DESKTOP-RNQPOG3:/mnt/d/Coding/milestone9/Milestone9# k get node -o wide
NAME       STATUS   ROLES                  AGE     VERSION   INTERNAL-IP    EXTERNAL-IP   OS-IMAGE             KERNEL-VERSION                   CONTAINER-RUNTIME
minikube   Ready    control-plane,master   4d23h   v1.22.2   192.168.49.2   <none>        Ubuntu 20.04.2 LTS   5.4.72-microsoft-standard-WSL2   docker://20.10.8

When I SSH into Minikube and try to curl my output from admin-service, I get the full page:
docker@minikube:~$ curl http://192.168.49.2:30007
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8" />
..........................................................

But when I curl from outside the cluster, I am unable to get the output:
root@DESKTOP-RNQPOG3:/mnt/d/Coding/milestone9/Milestone9# curl http://192.168.49.2:30007
curl: (28) Failed to connect to 192.168.49.2 port 30007: Connection timed out

This is how my policies look. I have tried to open up all internal and external traffic:
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-all-ingress
spec:
  podSelector: {}
  ingress:
  - {}
  policyTypes:
  - Ingress

---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-all-egress
spec:
  podSelector: {}
  egress:
  - {}
  policyTypes:
  - Egress

Any pointers on how I can sort this would be appreciated!
Edit:
I can see that the service is available out of the cluster when I do this:
root@DESKTOP-RNQPOG3:/mnt/d/Coding/milestone9/Milestone9# minikube service admin-service --url
  Starting tunnel for service admin-service.
|-----------|---------------|-------------|------------------------|
| NAMESPACE |     NAME      | TARGET PORT |          URL           |
|-----------|---------------|-------------|------------------------|
| default   | admin-service |             | http://127.0.0.1:42963 |
|-----------|---------------|-------------|------------------------|

However I need to know if this is a Minikube restriction. Kindly do explain if possible.


text:
Q: SharePoint Custom form using SharePoint Designer I have a requirement to create a form in a SharePoint List in which there will be 10 columns like col1,col2....col10.
On submitting col1 to col5 an approval workflow should trigger and once request is approved, another team will fill mandetory columns col6 to col8 and after their submission one more email should trigger and last team will fill col9 and col10. All these columns are mandetory. Please suggest what should be the approach to implement this. Is it possible in one list only or separate lists are required?

A: As SharePoint does not have have column level permission settings. If you put everything in the same list, you will have no way to avoid mistakes like fields modified by another team. Any user who has permission to edit the form, will be able to change the value in all 10 columns. It may be better to put them on separate lists.
Here is an option, List A holding 5 columns, List B col 6-8 and List C for Col 9 to 10. List D to hold all columns.
Once a new form is submitted to List A, trigger an approval workflow. And when the status changes to be approved, trigger another workflow to send an email for the next team for filling their separate form, and create a new item in List D, update first 5 column values. And do the same process for the next list, when a form is submitted and approved, update the corresponding item in List D and notify the next team to fill in required fields.


text:
Q: How to override lodash snakeCase functionality I'm using lodash to convert text to snakeCase and I am stuck in a specific scenario where I should retain alphanumeric value as it is.
When I pass string as "This is AAA456B". lodash snakeCase(str) is converting it as "this_is_aaa_456_b"
The expected result is like "this_is_aaa456b".
Is there a way I can override the lodash snakeCase(str) to ignore the alphanumeric value?

A: You should create your own function, rather than overriding the existing

const str = "This is AAA456B"

_.mixin({
  customSnakeCase: s => _
    .chain(s)
    .split(/(\d+)/)
    .map(_.snakeCase)
    .join('')
    .value()
})

console.log(_.customSnakeCase(str))
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.20/lodash.min.js"></script>


text:
Q: Function is returning value when console logged but showing as a promise object when trying to return value I am trying to figure out this one weird issue with dealing with this promise. I have done my fair share of promises so I am not new to it, but with this one function, it is really weird.
const getTrades = () => {
    const accountId = accounts.find(account => account.type === 'INTERNAL').id;
    const response = showTrades({ accountId: accountId }).then(res => console.log(res))
    if (response.length === 0) return false;
    return true;
  };

So the console log of the response above yields an empty array, which is expected. So if the array is empty, it should return false, otherwise it should return true. However, when I call the function like this, it just returns a Promise object.
getTrades()

Anyone know what could be causing this and how to solve this? Thanks!


text:
Q: Firebase Topic Messaging always return InvalidRegistration error when push notifications in ASP.NET I am developing an Asp.NET MVC application. In my application, I need to push notifications to Android Devices using Firebase. This is the consequence of this question - https://stackoverflow.com/questions/40416654/unable-to-push-firebase-notifications-to-multiple-devices-using-webclient-in-asp I asked.
After I searched for solutions, I realized that I should use Topic Messaging of Firebase - https://firebase.google.com/docs/cloud-messaging/android/topic-messaging. But when I use topic messaging and push from server, it always return Error=InvalidRegistration error.
I subscribe to a topic in Android like this
FirebaseMessaging.getInstance().subscribeToTopic("newsTopic");

Then I push like this in asp.net
public string PushNotifications()
        {
            using (var client = new WebClient())
            {
                client.Headers.Add(string.Format("Authorization:key={0}", Utils.FirebaseServerKey)); //get from firebase
                var values = new NameValueCollection();

                values["to"] = "/topics/newsTopic";
                values["data.message"] = "This is the test FCM test message";
                var response = client.UploadValues("https://fcm.googleapis.com/fcm/send", values);
                string responseString = Encoding.Default.GetString(response);
                if (!string.IsNullOrEmpty(responseString))
                {
                    return responseString;
                }
                else
                {
                    return "Something went wrong";
                }
            }
        }

But when I push, it returns this Error=InvalidRegistration.
Update
I tried replacing
values["to"] = "/topics/newsTopic";

with this
values["condition"] = "'newsTopic' in topics";

It returns, Error=MissingRegistration

A: I could reproduce the problem(Error=MissingRegistration) when I did not include "Content-Type=application/json" header. Can you try adding the Content-Type header?


text:
Q: Merge changes from remote magento repos get aborting Today went to to get new changes from the Magento repo in the develop branch.
I'm using phpstorm.
Commands I used
git remote add mageblob git@github.com:magento/magento2.git
git fetch mageblob
git checkout dev <= this is my local dev
git merge mageblob/develop

Merge process go aborting and suggest me remove files in dev/tests var/.htaccess v.v..
How to fix it.
p/s: Btw this is best way to pull all code changes from repos? i'm newbie in git

A: You have changes in local files. If you want to preserve local changes use:
git stash save
git merge mageblob/develop
git stash pop

see https://stackoverflow.com/questions/11675841/git-stash-merge-stashed-change-with-current-changes
If you don't need these changes just reset (be careful all non-committed changes will be lost):
git reset --hard
git merge mageblob/develop


text:
Q: Connecting to Oracle using Oracle.ManagedDataAccess I am using Oracle.ManagedDataAccess Nuget Package Version 12.1.022 in my C# (.NET 4.0) project. The package automatically creates entries in the app.config file. How can I read the datasource string from this file to be able to connect to the data base?

System.Configuration.ConfigurationManager.AppSettings.Get("dataSource");

is not working for me
<?xml version="1.0" encoding="utf-8"?>

<configuration>
  <configSections>
    <section name="oracle.manageddataaccess.client"
             type="OracleInternal.Common.ODPMSectionHandler, Oracle.ManagedDataAccess, Version=4.121.2.0, Culture=neutral, PublicKeyToken=89b483f429c47342" />
  </configSections>
  <system.data>
    <DbProviderFactories>
      <remove invariant="Oracle.ManagedDataAccess.Client" />
      <add name="ODP.NET, Managed Driver" invariant="Oracle.ManagedDataAccess.Client"
           description="Oracle Data Provider for .NET, Managed Driver"
           type="Oracle.ManagedDataAccess.Client.OracleClientFactory, Oracle.ManagedDataAccess, Version=4.121.2.0, Culture=neutral, PublicKeyToken=89b483f429c47342" />
    </DbProviderFactories>
  </system.data>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <publisherPolicy apply="no" />
        <assemblyIdentity name="Oracle.ManagedDataAccess" publicKeyToken="89b483f429c47342" culture="neutral" />
        <bindingRedirect oldVersion="4.121.0.0 - 4.65535.65535.65535" newVersion="4.121.2.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>

  <oracle.manageddataaccess.client>
    <version number="*">
      <dataSources>
        <dataSource alias="MyDataSource"
                    descriptor="(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=100.100.100.100)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=myservice.com)))" />
      </dataSources>
    </version>
  </oracle.manageddataaccess.client>
</configuration>

A: You can refer to the already defined datasource in the connection string
<oracle.manageddataaccess.client>
    <version number="*">
        <dataSources>
            <dataSource alias="MyDataSource" descriptor="(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=100.100.100.100)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=myservice.com)))" />
        </dataSources>
    </version>
</oracle.manageddataaccess.client>

for instance, in this specific case:
public class OracleDBManager
{
    private OracleConnection _con;
    private const string connectionString = "User Id={0};Password={1};Data Source=MyDataSource;";
    private const string OracleDBUser = "exampleUser";
    private const string OracleDBPassword = "examplePassword";

    public OracleDBManager()
    {
        InitializeDBConnection();
    }

    ~OracleDBManager()
    {
        if (_con != null)
        {
            _con.Close();
            _con.Dispose();
            _con = null;
        }
    }

    private void InitializeDBConnection()
    {
            _con = new OracleConnection();
            _con.ConnectionString = string.Format(connectionString, OracleDBUser, OracleDBPassword);
            _con.Open();
    }
}

A: You can make a separate class file returning the connectionstring like this -
public class OracleDbConnection
{
 public static OracleConnection GetConnection()
 {
  const string connectionString = "Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=127.0.0.1)(PORT=1521)) (CONNECT_DATA=(SERVICE_NAME=PROD))); User Id=userId;Password=password;";
  var connection=new OracleConnection(connectionString);
  return connection;
 }
}

Then you can call it like this where you need to access oracle db-
var oracleConnection = OracleDbConnection.GetConnection();
oracleConnection.Open();

A: Typically, you would refer to the alias in a standard connection string:
  <connectionStrings>
    <add name="MyConnection" connectionString="Data Source=MyDataSource;User Id=scott;Password=tiger;"/>
  </connectionStrings>

Then you would use the standard method for retrieving the string:
ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;

Also keep in mind that the alias in the data source section is optional.  You can embed the descriptor directly in the connection string:
  <connectionStrings>
    <add name="MyConnection" connectionString="Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=100.100.100.100)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=myservice.com)));User Id=scott;Password=tiger;"/>
  </connectionStrings>

You can also refer to aliases in a tnsnames.ora file.  By default the driver looks for a tnsnames.ora in the exe folder, a directory specified in a TNS_ADMIN environment variable, or the TNS_ADMIN config variable:
http://docs.oracle.com/cd/E48297_01/doc/win.121/e41125/featConfig.htm#autoId6
http://docs.oracle.com/cd/E48297_01/doc/win.121/e41125/featConfig.htm#autoId7

A: Using the package Formo, I created following method to get the MyDataSource string from app.config file
using Configuration = Formo.Configuration;
.......
/// <summary>
/// Gets the data source from app.config file
/// </summary>
/// <returns></returns>
public string GetMyDataSource()
{
    dynamic config = new Configuration();
    return config.MyDataSource;
}


text:
Q: Is it possible to change shared library references in a shared object file? I have a .so file which contains a reference to /Library/Frameworks/Python.framework/Versions/2.7/Python (I can see this path hard-coded in plaintext within the .so file). I don't have access to the source that built the .so file.
I'd like to use a different version of the python library (stored in /opt/local/Library). Is it possible to edit the .so file to reassign this path?

A: You may be able to permanently change the reference by using install_name_tool included with OS X Xcode command line tools.
install_name_tool -change old-lib-path new-lib-path path-to.so

However, if new-path is longer than the original old-path, there may not be room in the field in the bundle file (.so) to do so.  The man page for install_name_tool cautions:

For this tool to work when the install names or rpaths are larger the
  binary should be built with the ld(1) -headerpad_max_install_names
  option.

Also, there is no guarantee that the new Python you wish to use was built in a way that is compatible with the old shared library expected by the .so you are trying to modify.  There may be differences in universal CPU architectures, OS X deployment targets, and Python build options (for example, UCS-2 vs UCS-4) that may preclude success.  You should make a copy of the .so before attempting to modify it.


text:
Q: How to color the entire row using xlwt util of pyexcelerator The util talks about a function called this
style0 = xlwt.easyxf(
'font: name Times New Roman, colour_index red'
)

there is color red instead of color_index too .
Is there any provision to color the entire row?

A: pattern: pattern solid

This can be used to add color to row...
then u can add the color u want..
pattern: pattern solid,fore-color "COLOR NAME"

A: You asked this question on the python-excel forum and got a comprehensive answer there ...
By the way: xlwt is a fork of pyExcelerator, with bug-fixes and many enhancements. pyExcelerator is effectively abandoned.


text:
Q: How does the recovery strategy of PostgreSQL exactly work? I'm testing and trying to figure out how the backup and recovery strategy in PostgreSQL 11 works but it does not work as expected. When I recover the backup, I don't get the correct state. I get any state after a given timestamp. In detail:
I have this setup in database:
wal_level = replica
max_wal_senders = 10
archive_mode = on

I have executed the following commands:
postgres=# select pg_create_physical_replication_slot('slot1');
pg_basebackup -D /media/extern/postgresql_basebackup/
pg_receivewal -D /media/extern/postgresql_archive -S slot1 -v

pg_receivewal is writing into postgresql_archive, this seems to work.

*

*then I insert something into the database, let's say at 16:21.

*I wait some minutes, let's say until 16:27 and delete all the insert.

Then I want to recover the inserts by doing...
service postgresql stop

(do I need to stop pg_receivewal as well)?
# mv main main.before_recovery
# cp -rp /media/extern/postgresql_basebackup main

nano /var/lib/postgresql/11/main/recovery.conf

I add the following content
restore_command = 'cp -r /media/extern/postgresql_archive/%f %p'
recovery_target_time='2018-01-06 16:22:00'

Then I execute
# chown postgres:postgres recovery.conf
# chmod 700 recovery.conf

service postgresql start

After startup, the file changes to recovery.done, but the state in database is wrong. It didn't restore the data. The database is still empty, so the PITR didn't work, why?
What should I do In case if everything was successful after recovery?. I'm unsure about these questions:

*

*Creating a new slot2 by executing pg_create_physical_replication_slot('slot2'); and streaming from this slot by pg_receivewal -D /media/extern/postgresql_archive -S slot2 -v?

*Doing a pg_receivewal -D /media/extern/postgresql_archive -S slot1 -v again?

*Do I have to delete anywhen any data in postgresql_archive? (-> Probably not)

*When do I have to create another base backup?

*When and why do I execute select pg_switch_wal(); in this recovery concept?

*How do I deal with new 'timelines' after recovery? I understand the concept of the timelines, but I'm unsure how I should proceed with it after recovery.

[UPDATE]
jjanes pointed out, that the date is wrong. I corrected it, but I still get an empty database after recovery. I tried these steps after I recovered the database, which is now empty:

2019-01-08, 18:50: create a new base backup from this empty database
  to have a good starting point.
2019-01-08, 18:55 created slot1
pg_receivewal -D /media/extern/postgresql_archive -S slot1 -v
2019-01-08, 18:57 insert
2019-01-08, 19:38 delete

service postgresql stop
# mv main main.before_recovery
# cp -rp /media/extern/postgresql_basebackup main
# chmod 700 main

# nano /var/lib/postgresql/11/main/recovery.conf

restore_command = 'cp -r /media/extern/postgresql_archive/%f %p'
recovery_target_time='2019-01-08 19:20:00'

# chown postgres:postgres recovery.conf
# chmod 700 recovery.conf

# service postgresql start

(btw: I saw that it starts by itself new timelimes after recovery.)
[UPDATE]
I activated in postgresql.conf
checkpoint_flush_after = 256kB
checkpoint_timeout = 30s

I tried to restore the database by using the previous method but without recovery_target_time and without any DELETE statement. I just wanted to look if the current full state can be rebuilt at all. Additionally I renamed the current wal file 00000007000000000000002D.partial to 00000007000000000000002D after stopping the database and before recovering the data.
I'm currently not sure which of these things worked, but at least, the non-PITR recovery seem to work, because I was able to restore the latest data by installing the (empty) base backup and the wal files. At least a step into the right direction, but this only works when you don't miss any shipped wal files. Here, question 2 comes into play: What is the correct workflow to handle the "next shipping iteration".
At first, you can't start pg_receivewal -D /media/extern/postgresql_archive -S slot1 -v
 again without deleting the shipped WALs in the external folder. Otherwise it would not start shipping the logs and it would abort with connection errors. This means that you can throw away your old base backup, because when you try the recover again with the old base backup, you would miss all the wal logs between base backup and last recovery point (because you deleted them). That also means that you have to create a new base backup immediately from the recovery point state. When you start log shipping again, you have no "gap" then between the new base backup and the wal files.
[UPDATE]
I got PITR running with the same approach, so I was able to "undo" a delete now. After recovery and service postgresql start, the database remains in read only mode. I had to execute select pg_wal_replay_resume(); to make it RW again. As already mentioned, I can't do WAL shipping again. When I don't modify the archive folder and try to restart the WAL to ship inside the same folder, I get the following exception:

pg_receivewal: could not send replication command "START_REPLICATION":
  ERROR:  requested starting point 0/34000000 on timeline 11 is not in
  this server's history DETAIL:  This server's history forked from
  timeline 11 at 0/3310ADA8.

Sure, I could do log shipping to a new archive folder or something, but I guess this is not the professional way to do that. What is the common used strategy to resume log shipping after recovery?

A:
recovery_target_time='2018-01-06 16:22:00'

This 2019, not 2018. If you look in the server log file, you will probably find the recovery stopped as soon as it could (as soon as it reached a consistent state), because it could not stop as soon as you told it to, being a year late for that.

A: I've done a test following these guidelines:
1) create a new base backup
2) create slot
3) launch pg_receivewal -D PATH -S slotname -v
4) delete records
5) postgresql stop / delete PGDATA
6) cp -rp postgresql_basebackup PGDATA
7) edit recovery.conf
   restore_command = 'cp -ir /PATH/%f %p'
   recovery_target_time=timestamp
8) postgresql start

and PITR worked as aspected. Following what I did with comments. I have a fresh postgres installation where I created a db (test) and one table t1 whith 200 rows created with a simple loop. Contents:
postgres=# \c test
You are now connected to database "test" as user "postgres".
test=# \d t1
                    Table "public.t1"
 Column |         Type          | Collation | Nullable | Default
--------+-----------------------+-----------+----------+---------
 col1   | character varying(20) |           |          |

test=# select * from t1 limit 5;
 col1
-------
 1ABCD
 2ABCD
 3ABCD
 4ABCD
 5ABCD
(5 rows)

test=# select count(1) from t1;
count
-------
   200
(1 row)

STEP 1), 2), 3)
First start from a clean situation:
    postgres=# select now();
              now
-------------------------------
 2019-01-11 15:19:19.441022+01
(1 row)

postgres=# select * from pg_catalog.pg_replication_slots;
 slot_name | plugin | slot_type | datoid | database | temporary | active | active_pid | xmin | catalog_xmin | restart_lsn | confirmed_flush_lsn
-----------+--------+-----------+--------+----------+-----------+--------+------------+------+--------------+-------------+---------------------
(0 rows)

postgres=# select pg_switch_wal();
 pg_switch_wal
---------------
 0/B000190
(1 row)

$ cd /PGDATA-11/pg_wal/
$ ls -lrt
total 32768
drwx------ 2 postgres postgres        6 Jan 11 15:15 archive_status
-rw------- 1 postgres postgres 16777216 Jan 11 15:20 000000010000000000000001
-rw------- 1 postgres postgres 16777216 Jan 11 15:20 000000010000000000000002

Create a backup:
$ /usr/pgsql-11/bin/pg_basebackup -D /home/postgres/HOT-BACKUP/

postgres=# select pg_create_physical_replication_slot('test1');
pg_create_physical_replication_slot
-------------------------------------
 (test1,)
(1 row)

$ /usr/pgsql-11/bin/pg_receivewal -D /home/postgres/BCK-PITR-TEST/ -S test1 -v -n &
[1] 23350
$ pg_receivewal: starting log streaming at 0/4000000 (timeline 1)

I started pg_receivewall with "-n" to make it stop when postgres server goes down, and put it in background.
$ ls -rlt /home/postgres/BCK-PITR-TEST/
total 16384
-rw------- 1 postgres postgres 16777216 Jan 11 15:29 000000010000000000000004.partial

STEP 4)
test=# select now();
          now
-------------------------------
 2019-01-11 15:31:24.201177+01
(1 row)

test=# select count(1) from t1 where col1 like ('1%');
 count
-------
   111
(1 row)

SLEEP two minutes.........
test=# select now();
              now
-------------------------------
 2019-01-11 15:33:24.886394+01
(1 row)

test=# delete from t1 where col1 like '1%';
DELETE 111
test=#

STEP 5)
$ /usr/pgsql-11/bin/pg_ctl stop -D /PGDATA-11/
waiting for server to shut down....pg_receivewal: not renaming "000000010000000000000004.partial", segment is not complete
pg_receivewal: replication stream was terminated before stop point
pg_receivewal: disconnected
 done
server stopped
[1]+  Exit 1                  /usr/pgsql-11/bin/pg_receivewal -D /home/postgres/BCK-PITR-TEST/ -S test1 -v -n

Note how pg_receivewal stops itself because of parameter "-n" during start.
Let's check the contents in the most recent WAL (XXX4):
 $ /usr/pgsql-11/bin/pg_waldump 000000010000000000000004 000000010000000000000004
rmgr: Standby     len (rec/tot):     50/    50, tx:          0, lsn: 0/04000028, prev 0/030000F8, desc: RUNNING_XACTS nextXid 572 latestCompletedXid 571 oldestRunningXid 572
rmgr: Standby     len (rec/tot):     50/    50, tx:          0, lsn: 0/04000060, prev 0/04000028, desc: RUNNING_XACTS nextXid 572 latestCompletedXid 571 oldestRunningXid 572
rmgr: XLOG        len (rec/tot):    106/   106, tx:          0, lsn: 0/04000098, prev 0/04000060, desc: CHECKPOINT_ONLINE redo 0/4000060; tli 1; prev tli 1; fpw true; xid 0:572; oid 24576; multi 1; offset 0; oldest xid 561 in DB 1; oldest multi 1 in DB 1; oldest/newest commit timestamp xid: 0/0; oldest running xid 572; online
rmgr: Standby     len (rec/tot):     50/    50, tx:          0, lsn: 0/04000108, prev 0/04000098, desc: RUNNING_XACTS nextXid 572 latestCompletedXid 571 oldestRunningXid 572
rmgr: Heap        len (rec/tot):     59/  7283, tx:        572, lsn: 0/04000140, prev 0/04000108, desc: DELETE off 1 KEYS_UPDATED , blkref #0: rel 1663/16384/16385 blk 0 FPW
rmgr: Heap        len (rec/tot):     54/    54, tx:        572, lsn: 0/04001DB8, prev 0/04000140, desc: DELETE off 10 KEYS_UPDATED , blkref #0: rel 1663/16384/16385 blk 0
rmgr: Heap        len (rec/tot):     54/    54, tx:        572, lsn: 0/04001DF0, prev 0/04001DB8, desc: DELETE off 11 KEYS_UPDATED , blkref #0: rel 1663/16384/16385 blk 0
...........................................................................................................................................................................
rmgr: Transaction len (rec/tot):     34/    34, tx:        572, lsn: 0/040035E0, prev 0/040035A8, desc: COMMIT 2019-01-11 15:33:31.342763 CET

In the last line, you can see the commit timestamp for the delete: COMMIT 2019-01-11 15:33:31.342763 CET. This is the timestamp we need to avoid to reach, in order to reject the delete statement. So the recovery.conf will be edited with a timestamp sometimes before this one.
After deleting PGDATA and restoring backup files from HOT-backup path into PGDATA, I edited recovery.conf and restarted postgres.
STEPS 6), 7), 8):
$ cp -rp /home/postgres/HOT-BACKUP/* /PGDATA-11/
$ vi recovery.conf

$ cat recovery.conf
restore_command = 'cp -ir /home/postgres/BCK-PITR-TEST/%f %p'
recovery_target_time='2019-01-11 15:31:24.201177+01'

$ /usr/pgsql-11/bin/pg_ctl start -D /PGDATA-11/ &

Look at the server log, I left only important lines:
2019-01-11 15:56:46.873 CET [28768] LOG:  database system was interrupted; last known up at 2019-01-11 15:27:52 CET
2019-01-11 15:56:46.885 CET [28768] LOG:  starting point-in-time recovery to 2019-01-11 15:31:24.201177+01
2019-01-11 15:56:46.911 CET [28768] LOG:  redo starts at 0/3000028
2019-01-11 15:56:46.913 CET [28768] LOG:  consistent recovery state reached at 0/30000F8
2019-01-11 15:56:46.914 CET [28766] LOG:  database system is ready to accept read only connections
2019-01-11 15:56:46.931 CET [28768] LOG:  restored log file "000000010000000000000004" from archive
2019-01-11 15:56:46.951 CET [28768] LOG:  recovery stopping before commit of transaction 572, time 2019-01-11 15:33:31.342763+01
2019-01-11 15:56:46.951 CET [28768] LOG:  recovery has paused
2019-01-11 15:56:46.951 CET [28768] HINT:  Execute pg_wal_replay_resume() to continue.

We can see that the recovery process reached a consistent state at lsn 0/30000F8, which is in WAl file XXX3: following WAL XXX4 has been copied but not applied because of the timestamp I configured in recovery.conf.
Of course the rows deleted are now present into the db, so I executed pg_wal_replay_resume() to bring the db RW again:
test=# select count(1) from t1;
 count
-------
    200
(1 row)

test=# select pg_wal_replay_resume();
 pg_wal_replay_resume
----------------------

(1 row)

Now wal files moved to timeline 2:
$  ls -lrt
total 49156
-rw------- 1 postgres postgres 16777216 Jan 11 15:54 000000020000000000000005
-rw------- 1 postgres postgres 16777216 Jan 11 15:56 000000010000000000000004
drwx------ 2 postgres postgres       42 Jan 11 15:56 archive_status
-rw------- 1 postgres postgres       50 Jan 11 15:59 00000002.history
-rw------- 1 postgres postgres 16777216 Jan 11 15:59 000000020000000000000004

I did a similar test using an archive_command insted of pg_receivewal and obtained identical results. I suggest you to put the db log in debug, and to check with pg_waldump what is inside WAL files. Something strange is happening to you, and it could be interesting catch out WHAT is happening.
Hope this help.
MarcoP
Some answers added on 15 Jan.
What should I do In case if everything was successful after recovery?. I'm unsure about these questions:
Creating a new slot2 by executing     pg_create_physical_replication_slot('slot2'); and streaming from this slot by pg_receivewal -D /media/extern/postgresql_archive -S slot2 -v?
This could be a choice. It's up to you to decide which techology best fit your requirements. We do not user pg_receivewal at all, we prefer to use an archive_command.
Doing a pg_receivewal -D /media/extern/postgresql_archive -S slot1 -v again?
No, you cant! replication slost are not included in backup by pg_basebackup. If you look at serverlog during basebackup you will see:
2019-01-14 16:32:02.886 CET sending backup "pg_basebackup base backup"     5c3cab72.27fc-12 4/0-0 [10236] DEBUG:  contents of directory "pg_replslot"   excluded from backup

so, when you restore the PGDATA from hot-backup you will not restore any replication slot.
When do I have to create another base backup?
It really depends on your requirements. What are your constraints about Recovery Time Objective and Recovery Point Objective?
How many Wal files your db switches in a single day?
From the doc: Since you have to keep around all the archived WAL files back to your last base backup, the interval between base backups should usually be chosen based on how much storage you want to expend on archived WAL files. You should also consider how long you are prepared to spend recovering, if recovery should be necessary — the system will have to replay all those WAL segments, and that could take awhile if it has been a long time since the last base backup.
When and why do I execute select pg_switch_wal(); in this recovery concept?
This command basically force wal file to shitch to the following one. This grants that the last completed wal is moved to archive dir.
     In case of disaster where the live PGDATA is lost (and so the pg_wal subdir) this can be important.  Wal file are 16MB by default. archive_command
copies the wal to the archive destination when switch occurs.
If a disaster happens, let say a single byte before the switch, you lose 16MB of transaction activity. This is why someone prefer pg_receivewal which does not wait for wal completition. BTW you can user archive_timeout to set a value which is compatible with
your requirements.


text:
Q: Why can't templates be within extern "C" blocks? This is a follow-up question to an answer to Is it possible to typedef a pointer-to-extern-"C"-function type within a template?
This code fails to compile with g++, Visual C/C++, and Comeau C/C++ with basically the same error message:
#include <cstdlib>

extern "C" {
    static int do_stuff(int) {
        return 3;
    }

    template <typename return_t_, typename arg1_t_>
    struct test {
        static void foo(return_t_ (*)(arg1_t_)) { }
    };
}

int main()
{
    test<int, int>::foo(&do_stuff);
    return EXIT_SUCCESS;
}

g++ says "error: template with C linkage", Visual C/C++ emits compiler error C2894, and Comeau C/C++ says "error: this declaration may not have extern "C" linkage".
The thing is, all are happy with:
#include <cstdlib>

extern "C" {
    static int do_stuff(int) {
        return 3;
    }

    struct test {
        static void foo(int (*)(int)) { }
    };
}

int main()
{
    test::foo(&do_stuff);
    return EXIT_SUCCESS;
}

Section 7.5, Linkage specifications, of the C++ Standard states:

A C language linkage is ignored for the names of class members and the member function
  type of class member functions.

And it even gives the example:
extern "C" {
    class X {
        void mf(); // the name of the function mf and the member
                // function's type have C++ language linkage
        void mf2(void(*)()); // the name of the function mf2 has C++ language
                // linkage; the parameter has type pointer to C function
    };
}

If templates were allowed in extern "C" blocks, then the member functions of the instantiations would have C++ linkage.
Why, then, does chapter 14, Templates, of the C++98 Standard state:

A template name may have linkage (3.5). A template, a template explicit specialization (14.7.3), and a class template partial specialization shall not have C linkage.

What does it mean that a template "may" have linkage? What is template linkage?
Why is it explicitly forbidden to have a template with C linkage, when a class is okay, and all member functions of instantiations of the template (the default constructor, destructor, and assignment operator overload) would have C++ linkage?

A: Because extern C disables name mangling, which templates use
To see that templates are implemented with name mangling, compile and decompile:
#include <cassert>

template <class C>
C f(C i) { return i; }

int main() {
    f<int>(1);
    f<double>(1.5);
}

with:
g++ -c -g -std=c++98 main.cpp
objdump -Sr main.o

The output contains:
int main() {
   0:   55                      push   %rbp
   1:   48 89 e5                mov    %rsp,%rbp
   4:   48 83 ec 10             sub    $0x10,%rsp
    f<int>(1);
   8:   bf 01 00 00 00          mov    $0x1,%edi
   d:   e8 00 00 00 00          callq  12 <main+0x12>
            e: R_X86_64_PC32    _Z1fIiET_S0_-0x4
    f<double>(1.5);
  12:   48 b8 00 00 00 00 00    movabs $0x3ff8000000000000,%rax
  19:   00 f8 3f
  1c:   48 89 45 f8             mov    %rax,-0x8(%rbp)
  20:   f2 0f 10 45 f8          movsd  -0x8(%rbp),%xmm0
  25:   e8 00 00 00 00          callq  2a <main+0x2a>
            26: R_X86_64_PC32   _Z1fIdET_S0_-0x4
}
  2a:   b8 00 00 00 00          mov    $0x0,%eax
  2f:   c9                      leaveq
  30:   c3                      retq

Note how all callq were made to call weird names like _Z1fIiET_S0_.
The same goes for other features which depend on name mangling, e.g. function overloading.
I have written a more detailed answer at: What is the effect of extern "C" in C++?

A: Because template function names need to be decorated with additional information, and extern "C" turns decoration off. The purpose of extern "C" is to be able to declare functions that can be called with C linkage, which is something that will never work with a template function obviously.

A: Templates aren't actual code, they're just guidelines to the compiler for how to generate the code once the template parameters are known. As such they don't actually exist until you try to use them. You can't provide linkage to something that doesn't exist.

A:
What does it mean that a template "may" have linkage? What is template linkage?

All names either have external linkage, internal linkage, or have no linkage (C++03 §3.5p2), but this is not the same linkage as language linkage.  (Confusing, I know. C++0x changes things around considerably with linkage, too.)  External linkage is required for anything used as a template argument:
void f() {
  struct S {};
  vector<S> v;  // Not allowed as S has internal linkage.
}

Notice that C++98 has "may" in what you quoted of §14p4, but C++03 removes the "may", as templates cannot be declared in a context that would give them internal linkage:
void f() {
  // Not allowed:
  template<class T>
  struct S {};
}

A: Since the standard says

A C language linkage is ignored in determining the language linkage of class members

it appears to be a bug in all compilers.

A: Because there are no templates in C.


text:
Q: bootstrap-datepicker : how to close only when clicking outside I want to make datepicker close only if click outside.
To prevent closing before clicking outside, I delete hide function like this:
$('#datepicker').data('datepicker').hide = function () {};

But if I do this, it's not able to close datepicker.
How do I fix this?
Code below:
<input type="text" name="datepicker" id="datepicker" class="form-control" value='<%=selectDate%>' onchange="hide()">

<script>

    $('#datepicker').datepicker({
        dateFormat : 'yyyy-mm-dd',
        autoclose: false
    });
    $('#datepicker').data('datepicker').hide = function () {};

</script>

A: just add the class datetimepicker-input ej.
<input type="text" class=" datetimepicker-input" id="datetimepicker4" data-toggle="datetimepicker" data-target="#datetimepicker4" dir="auto" required=""  readonly >

when de jquery is
$('#datetimepicker4').datetimepicker();

I found this page to explain the details https://tempusdominus.github.io/bootstrap-4

A: <input type="text" name="datepicker" id="datepicker" class="form-control" value='<%=selectDate%>' onchange="hide()">

<script>

    $('#datepicker').datepicker({
        dateFormat : 'yyyy-mm-dd',
        autoclose: false
    });
    $('#datepicker').data('datepicker').hide = function () {};

</script>

on this code, onSelect func didn't work and couldn't use hide() func
so changed this into by using
.on("changeDate", function (e) {
    $('.datepicker').show();
}

it worked for me


text:
Q: WPF Calling function in Page from "Master" Window I have a button in a Window that needs to call a function in pages contained within a frame.  The page inside the frame will change based on a navigation contained in the main Window, so I will know the current Page within the frame.
Can someone help with how to call function in frame pages?

A: If you wish to approach this from an MVVM perspective, you'll want to make sure you're not working with the actual view here, but the ViewModel abstraction of it. In that case, your parent Window is probably backed by a ViewModel that contains some sort of a collection that backs your pages in the frame/tab control/container of choice. In that case, the button should link to a command on your Window-backing ViewModel and use the selected item in the collection to access the function. If you do not have a direct reference in this fashion (for example loading in from another module or something for frame contents) you can also use EventAggregator from the Prism/CAL libraries and publish an event when the window button is pressed and set up your pages to receive that event and handle the call there. EventAggregator can be a slick way to handle cross-module logic in a clean way.


text:
Q: Laravel 5.1 loop and merge Collection I am trying to merge values together into one collection while I loop.
Here is my current setup
$collection = collect([]);

foreach($array as $item){

    $temp = $item->do_something;
    !is_null($temp) ? $collection->merge($temp) : null;
}

What $temp can hold is following:
array['records' => $array, 'details' => $array]
Now the closest I got was $array of $temp values but instead I would like to merge all those values into one collection. Instead of array of $temp arrays I would like one collection with Records, and Details.
Thanks
More details what I got visual:
[0]=> ['records' => $array
       'details' => $array]
[1]=> ['records' => $array
       'details' => $array]
[2]=> ['records' => $array
       'details' => $array]

What I would like is to merge all those into one
['records' => $array, 'details' => $array]


text:
Q: How to change x values on scatter plot I have a project I am working on and the X values on my scatter plot go from 0-1400. I would like the upper X value to be 80, but I cannot find a way to do this.
My code is:
plot(Toyota.df$Price - Toyota.df$Age_08_04, xlab = "Age", ylab = "Price")

A: @Plecos, try this:
 plot(Toyota.df$Price - Toyota.df$Age_08_04, xlab = "Age", ylab = "Price", xlim=c(0,80))


text:
Q: elasticsearch time series data aggregation reverse countdown I have data in elasticsearch whose records looks like:
{
      checkat: 2019-11-01,
      imei: "123",
      version: "abc"
},
{
      checkat: 2019-11-02,
      imei: "123",
      version: "def"
},
{
      checkat: 2019-11-02,
      imei: "456",
      version: "ghi"
},
{
      checkat: 2019-11-03,
      imei: "123",
      version: "ghi"
},
{
      checkat: 2019-11-03,
      imei: "456",
      version: "ghi"
}

How to represent a chart where query is :
              "query": {
                "bool": {
                  "filter": {
                    "range": {
                      "checkat": {
                        "gte": "2019-11-01",
                        "lte": "2019-11-03"
                      }
                    }
                  }
                }
              }

Because the previous day count is erased by the next day count.
Is it clear ?

A: Finally I created a new index that only takes the latest version saved for each IMEI
{
      checkat: 2019-11-01,
      imei: "123",
      version: "abc"
},
{
      checkat: 2019-11-02,
      imei: "123",
      version: "def"
},
{
      checkat: 2019-11-02,
      imei: "456",
      version: "ghi"
},
{
      checkat: 2019-11-03,
      imei: "123",
      version: "ghi"
},
{
      checkat: 2019-11-03,
      imei: "456",
      version: "ghi"
}
Merge done by Logstash make that :
{
      checkat: 2019-11-03,
      imei: "123",
      version: "ghi"
},
{
      checkat: 2019-11-03,
      imei: "456",
      version: "ghi"
}


text:
Q: Formulário fixo passa por cima do menu Possuo uma aplicação onde tenho um menu normal no topo da página, e logo abaixo dele um formulário, onde esse formulário tem que ser fixo, de uma forma que quando eu role a página para baixo, esse formulário fique no topo da página, e o resto da página vá correndo por trás dele.
Meu problema está em deixar esse formulário da forma que preciso. Coloco a propriedade position: fixed, ele fica fixo, mas ou por cima do menu, ou totalmente desposionado na tela, e também pelo fato que vou usar essa mesma aplicação no celular, estou meio perdido em como fazer.

A: O elemento pai do form deve estar:
position: fixed;
top: 0;
width: 100%;
z-index: 99999; /* Pra Garantir */

A: Caso o menu seja no topo, utilize uma margem do top para garantir que não fique sobre o menu, margin-top: 150px e utilize a propriedade z-index: 999 para garantir que fique sobre os elementos de forma fixa.
CSS:
form{
     position: fixed;
     margin-top: 100px; // distancia do top
     right: 0;
     z-index: 9999;
}


text:
Q: Need to filter a column every X rows I have a column with dates, and I want to filter every X rows.
df <- read.table(text = 'date
01-02-2010
02-02-2010
03-02-2010
07-02-2010
08-02-2010
09-02-2010
10-02-2010
11-02-2010
12-02-2010
13-02-2010
14-02-2010 ', header = TRUE)

A: library(dplyr)

iris |>
  mutate(row = row_number()) |>
  filter(row %% 3 == 0) # Change the value 3 to whatever you are looking for.


text:
Q: Check whether an OpenLayers map is being currently zoomed? I know you can check whether a map is being dragged by examping its dragging property like
olMap.dragging

This is a boolean value that is true if the map is being dragged (with the mouse or even with keyboard arrows).
But what about zooming in and out?


text:
Q: unix all if statements in one place I am newly learning shell script ! i tried following code but i have error

line 15: syntax error near unexpected token `elif

#!/bin/bash

read -p "Enter the number : " n

if [ $n -eq 1 ]
then
    echo "$n is equal to 1 true"

    elif [ $n -lt 4 ]
    then
        echo "$n is less than value of 4 ture"
    else
        echo "$n is not less then value of 4 false"

    elif [ $n -gt 10 ]
    then
        echo "$n is greater than the value of 10 true"
    else
        echo "$n is not greater than the value of 10 false"

    if [ $n -ge 0 ]
    then
        echo "$n is greater than or equal to 0"
    else
        echo "$n is not greater than or equal to 0"
    fi
else
    "Bye"
fi

Can anyone help ?

A: It's a bit hard to tell what your intention is. The correct answer depends on what you want to do here. My guess is that you want this:
if [ $n -eq 1 ]
then
    echo "$n is equal to 1 true"

elif [ $n -lt 4 ]
then
    echo "$n is less than value of 4 true"

elif [ $n -gt 10 ]
then
    echo "$n is greater than the value of 10 true"

elif [ $n -ge 0 ]
then
    # This will be true if $n is >= 4 and <= 10
    echo "$n is greater than or equal to 0"
else
    # Negative
    "Bye"
fi


text:
Q: How to calculate the space I need for the indexes? CREATE TABLE info(
home CHAR(10) CHARACTER SET latin1 NOT NULL,
id TINYINT UNSIGNED NOT NULL,
galaxy TINYINT UNSIGNED NOT NULL,
galaxy_pos INT UNSIGNED NOT NULL,
events TEXT NOT NULL,
UNIQUE KEY(galaxy, galaxy_pos, id), PRIMARY KEY(home, id)) ENGINE = INNODB

10+1+1+4+2 = 18 bytes + TEXT, are needed for the data. How to calculate the space I need for the indexes?

A: For the data record add:

*

*6 bytes transaction id

*7 bytes rollback pointer

*5 bytes extra bytes header

*2 bytes - for length of TEXT field (however if TEXT values longer than 7k overhead will be bigger)

Index record stores indexed fields + primary key. So its length will be

*

*5 bytes - extra bytes

*indexed fields length

*primary key length (in your case it's 1+4+1 bytes)

Take into account an InnoDB page may be filled up to 15/16 i.e. 15k of data+headers.
Each page has 120 bytes in headers.
Plus take into account space that is used by non-leaf pages. It's not huge, but still.