Create MX Record for Subdomain

Question: I have two Zimbra mail servers. One of them serve for stuff and the other one serve for student. So I want to create use two different mail template like email@example.com and firstname.lastname@example.com.
I have no problem for firstname.lastname@example.com.
For student I created a sub domain like studentlogin.domain.edu
I use Bind 9 on Centos 7.
But when a try a mail a have error message like "The address not found".
You can see my config.
<code>    studentlogin.domain.edu.     IN  MX      10   mail.student.domain.edu.
    studentlogin.domain.edu.     IN  A       XX.XXX.XXX.XXX
    studentlogin.domain.edu.     IN  TXT     "v=spf1 a mx ptr a:mail.student.domain.edu mx:mail.student.domain.edu ip4:XX.XXX.XXX.XXX ~all"
</code>
What I should do?
Please help.
Best regards.
Answer: This is how I would configured it, based on the slightly vague information, provided. You could make adjustments, as needed:
<code>$TTL 1D
@                       IN      SOA     ns.domain.edu. support.domain.edu. (
                                        2017090501      ; serial
                                        1D              ; refresh
                                        1H              ; retry
                                        1W              ; expire
                                        3H )            ; minimum

                                NS      ns.domain.edu.
                                MX 10   mail.domain.edu.
                                TXT     "v=spf1 mx ~all"

ns                      IN      A       10.10.10.2
mail                    IN      A       10.10.10.10

student                 IN      MX 10   mail.student.domain.edu.
student                 IN      TXT     "v=spf1 mx ~all"
mail.student            IN      A       10.0.0.10

$ dig domain.edu any

;; ANSWER SECTION:
domain.edu.             86400   IN      SOA     ns.domain.edu. support.domain.edu. 2017090501 86400 3600 604800 10800
domain.edu.             86400   IN      NS      ns.domain.edu.
domain.edu.             86400   IN      MX      10 mail.domain.edu.
domain.edu.             86400   IN      TXT     "v=spf1 mx ~all"

;; ADDITIONAL SECTION:
ns.domain.edu.          86400   IN      A       10.10.10.2
mail.domain.edu.        86400   IN      A       10.10.10.10

$ dig student.domain.edu any

;; ANSWER SECTION:
student.domain.edu.     86400   IN      MX      10 mail.student.domain.edu.
student.domain.edu.     86400   IN      TXT     "v=spf1 mx ~all"

;; AUTHORITY SECTION:
domain.edu.             86400   IN      NS      ns.domain.edu.

;; ADDITIONAL SECTION:
mail.student.domain.edu. 86400  IN      A       10.0.0.10
ns.domain.edu.          86400   IN      A       10.10.10.2
</code>
P.S. Using a particular SPF mechanism is an administrative decision in most of the cases, rather than technical.
Answer: Try removing the "." after the MX record. --> studentlogin.domain.edu
Also be sure to have separate IP addresses as you can only have one rDNS entry per IP and a mail server must have its hostname set as rDNS to be RFC compliant.
Similar question here: How should I setup separate MX records for a subdomain?
PS Any reason why you use ~all instead of -all in your SPF rule? (for reference see https://wordtothewise.com/2014/06/authenticating-spf/)
Comment: Thank you very much Chris. My rDNS record is correct. In addition when i use same subdomain and same mail  address such as  student.domain.edu subdomain and firstname.lastname@example.com mail it works. But when i  use different subdomain and mail address like studentlogin.domain.edu and email@example.com it doesnt work.

Create MX Record for Subdomain


Make a gmap view embeddable on another site

Question: The website I'm building has a google map view. I want to provide a code snippet to site visitors to let them embed this gmap view on their own site. Does anyone know of a way to accomplish this in D7?
I saw this question over at the SO main site, but it appears to be D6-specific since Embed Widgets doesn't have a D7 release and Web Widgets only has an abandoned D7 release. So I'm wondering if there's another way to do this.
Answer: You could create your own iframe: http://www.iframehtml.com/
You will most likely want to create custom page output so that you aren't including extra regions from your site. You can do so by creating a custom html.tpl.php template (might not be necessary) and page template for the map.


Grouping an array of similar words

Question: I have an array with a bunch of words. E.g:
array( developer,develop,development,design,designer,designing )

I want to be able to group these words together with their similar words so I'd get something like this:
array(
   array( develop, developer, development ),
   array( design, designer, designing ),
);

What would be the best way to do this in PHP?
Answer: You can do it easily using metaphone():
$result = array();
foreach ($array as $word) {
    $result[metaphone($word, 2)][] = $word;
}

print_r($result); will show:
Array
(
    [TF] => Array
        (
            [0] => developer
            [1] => develop
            [2] => development
        )

    [TS] => Array
        (
            [0] => design
            [1] => designer
            [2] => designing
        )
)

Comment: The PHP API (if you can call it that) keeps amazing me. The amount of useful "stuff" that's build into the language is just amazing.
Comment: Yes, there is a function for almost everything. Actually it is amazing :)
Answer: A way is comming to my mind
$array = array( 'developer','develop','development','design','designer','designing' );

function matchWords(array $in,$pad='4')
{
    $ret = array();
    foreach ($in as $v) {
        $sub = substr($v, 0, $pad);
        if (!isset($ret[$sub])) {
            $ret[$sub] = array();
        }
        $ret[$sub][] = $v;
    }

    return array_values($ret);
}

print_r(matchWords($array,4));

Array
(
    [0] => Array
        (
            [0] => developer
            [1] => develop
            [2] => development
        )

    [1] => Array
        (
            [0] => design
            [1] => designer
            [2] => designing
        )
)

This matches the $pad first letters of your array values and create a key on it.
Comment: I had a hard time deciding to accept your answer or that of jackflash. In the end I actually used the one jackflash provided so I feel I need to tick that as the correct answer. However, if I was able to accept two answers I would. I praise you for your quick response to my question! Thanks!
Answer: You probably want to extract the stem of each word using a technique such as "Porter Stemming" to identify the similar words, then build your array based on those stems. You can find a PHP implementation of a Porter Stemmer here
Comment: I thought about stemming before asking the question but it might have been to slow in performance (I know, premature optimization is the root of all evil and all that). Thanks anyway!

Grouping an array of similar words


Why is the "webform submission updated" hook not using the correct data?

Question: Created a function in respond to hook_webform_submission_update to generate a FillPdf.
function my_module_webform_submission_update($node, $submission) {

    if ($submission->nid == 43) {

        $uuid = ($submission->data['975'][0]);
        $sid = ($submission->sid);

        $f = "./sites/default/files/docs/mdx_lh_" . $uuid . "_" . $sid . ".pdf";

        if (file_exists($f)) unlink($f);

        $wf = array(array("nid" => 43, "sid" => $sid));

        fillpdf_merge_pdf(326,NULL,$wf);
    }
}

When the event is triggered, after pressing the save button, the FillPdf uses the old data.  Going over the webform a second time without changing anything, just clicking the save button, the FillPdf uses the correct data.
I thought the hook_webform_submission_presave was to change data (if needed) but it seems the event hook_webform_submission_update is triggered before data is actually saved.
Is there a way to force data save before calling fillpdf_merge_pdf, or is there another event to use?
Answer: For whatever reason querying the database give the correct data and yet the FillPdf sevice uses the older one, we moved the routine to the point where the results are showed, where its activated with a button. This option works fine.


Show that these two integrals are the same

Question: I am trying to prove this. Where do I start?
$$ \int_{0}^{x}\Biggl[\int_{0}^{t} F(u)\,du\Biggr]dt = \int_{0}^{x}(x-u)F(u)\,du$$
Comment: Am i using the fundamental theorem of calc?
Comment: Differentiate both sides with respect to x. Show that both sides' results are equal. Then you just have to check both original sides for one value of x.
Comment: Yes use FTC. Note that differentiating the right hand side wrt x doesn't give zero — there is a product rule there.
Answer: Integration by parts using  $u=\int_{0}^{t}{F}(u)du\quad ,dv=dt$
$$=\left. t\int_{0}^{t}{F}(u)du \right|_{0}^{x}-\int_{0}^{x}{tF\left( t \right)dt}=x\int_{0}^{x}{F}(u)du-\int_{0}^{x}{tF\left( t \right)dt}=\int_{0}^{x}{\left( x-t \right)F\left( t \right)dt}$$


Fazer ShellScript atuar como pipLine

Question: Como posso fazer meu script conseguir atuar em um pipeLine
exemplo:
ls|./meuScript|grep 'Mensagem Qualquer'

o que './meuScript' tem que ter para  atuar  como um filtro ?
Answer: Basta que o seu script use comandos que leiam a entrada padrão e escrevam na saída padrão.
Exemplo:
Temos o script abc-lines.sh:
#!/bin/bash
grep abc | wc -l

Podemos usá-lo neste comando:
$ echo -e 'abcd\nefgh\n123abc\nxabcy\nzzz' | \
./abc-lines.sh | \
sed -r 's/(.*)/[\1]/'

...e o resultado será: [3]
Isso porque a entrada padrão dos comandos do seu script será a entrada padrão do seu script (a não ser se o comando estiver após um pipe, como o wc do exemplo). O mesmo vale para funções.
Se você precisa capturar a entrada padrão para manipulações mais elaboradas você pode usar o read. Exemplo:
#!/bin/bash
while read LINE
do
    echo "I read $LINE"
    # alguma mágica aqui
done

Tudo o que você imprimir, seja com echo ou qualquer outro comando, poderá ser usado por outro script na sequencia de pipes feita pelo usuário.
Atenção: Existem duas saídas STDOUT e STDERR. O pipe vai transmitir a STDOUT.
Se você quiser mandar a saída de um comando para STDERR para escapar do PIPE, faça:
echo "mensagem de erro" >&2

Se quiser fundir a STDERR com a STDOUT para pipear as duas, faça:
ls /nowhere 2>&1 | grep something

Comment: Exatamente isso que quis dizer, ( o travar foi no sentido de parar o processamento e esperar a entrada do usuário)

resolvi esse problema fazendo uma verificação nos arquivos descritores

´if [ -t 0 ]; then ...´ que verifica se o arquivo associado ao descritor de arquivo termina na janela do terminal.
Comment: estava apanhando por conta de não saber o detalhe do ` read LINE`
muito obrigado.
Comment: porem quando coloco ´read LINE´ e vou usar o programa fora de um pipe ele trava
Comment: Ele não está travado, está esperando input. Ele vai ler o que vc digitar. ;-)

Fazer ShellScript atuar como pipLine


Unknown provider injecting factory

Question: When I run my app it always throws the following error:

Error: [$injector:unpr] Unknown provider: localStorageServiceProvider <- localStorageService
  http://errors.angularjs.org/1.3.5/$injector/unpr?p0=localStorageServiceProvider%20%3C-%20localStorageService

This is my Code:
home.js:
   angular.module('home', [])

.controller('homeCtrl', ['$scope', '$location', 'localStorageService',
    function ($scope, $location, localStorageService) {
        $scope.username = "maax",
        $scope.buttonType = "icon ion-search",
        $scope.buttonDisable = false,

        $scope.click = function () {
            $scope.buttonDisable = true
            $scope.buttonType = "icon ion-loading-a"

            //Grap geoLocation
            var location = navigator.geolocation.getCurrentPosition(sendToServer);

            function sendToServer(pos) {
                //sendGeoData(pos.coords.latitude, pos.coords.longitude, window.localStorage.getItem("userId"))
                savePlayerData("sd");
            }

            //Ask server for availalble player an get data

            //End server request

            //Link to play-screen
            $location.path("/tab/play-screen");
            localStorageService.addEvent();
        };

}])

Here is my service, that I try to inject:
'use strict'
angular.module('service', [])

//var testEvent = {
//    "playerName": "Max",
//    "aufgabe": "Döner kaufen"
//}
//
//localStorage.setItem('events', testEvent);
//Create a hitsotry of Events to see the recent Events

.factory('localStorageService', function () {
    return {
        addEvent: function () {
            return null
        }
    }
    //
    //    return 1;
    //    //Pull the current events
    //    var event = JSON.parse(localStorage.getItem('events'));
    //
    //    /*overwrite the localStorage with the newest Event added in
    //            the begining */
    //
    //    var eventUpdatet = newEvent;
    //    eventUpdatet.push(events);
    //    localStorage.setItem('events', JSON.stringify(eventUpdated));

});

I hope you can help me, because I really do not see my error.
Thank you very much!!
Answer: You need to plug the dependency of both modules, fix this line:
angular.module('home', ['service'])

Comment: unfortunateley does not help!
now it says: "angular.js:63 Uncaught Error: [$injector:modulerr] Failed to instantiate module starter due to:
Error: [$injector:modulerr] Failed to instantiate module home due to:
Error: [$injector:modulerr] Failed to instantiate module services due to:
Error: [$injector:nomod] Module 'services' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument."
Comment: make sure you add both files in your index.html, where servicemodule.js is loaded above @user3122136

Unknown provider injecting factory


JavaScript foreach loop through an array of hex values, using setTimeout to loop through background colors

Question: I've been trying to come up with the most concise way that I can possibly change background colors using JavaScript. (Trying to get the hang of forEach and higher order functions just for fun.) Anyway, this will run on page load, and I think I'm pretty close:
function background(){
    var colorArray = ["#14183b", "#002e2e", "#0d2d40", "#173052", "#194759", "#296b73"];
    function change(newcolor){
        document.body.style.backgroundColor=newcolor;
    }
    colorArray.forEach(function(color){
        setTimeout(change(color), 1000);
    });
}

The problem is that the background color is only showing the last element in the array. I also am not sure how to start the forEach loop over again when it is has finished. Thanks for any help!
Comment: Do you have to use JavaScript?  What about CSS transitions and keyframes?
Answer: Like this ... Also can ...
var colorArray = ["#14183b", "#002e2e", "#0d2d40", "#173052", "#194759", "#296b73"];
var count = 0;
    function change() {
        document.body.style.backgroundColor = colorArray[count];
        count++;
        if(count == colorArray.length) {
            count = 0;
        }
    }

    setInterval(function(){
        change();
    }, 1000);

Comment: thanks, and just for fun with your solution, if we want to loop more smoothly e.g. 1234554321 vs 123451234 I added: colorArray.reverse(); right before the count reset. cheers YLS!
Answer: The problem is you are passing the value returned by change as the timeout handler, instead you need to pass a function reference.
If you want to have an infinite loop, then you can use setInterval() like

function background() {
  var colorArray = ["#14183b", "#002e2e", "#0d2d40", "#173052", "#194759", "#296b73"];

  function change() {
    index = index >= colorArray.length ? 0 : index;
    document.body.style.backgroundColor = colorArray[index++];
  }

  var index = 0;
  var interval = setInterval(change, 1000);
}

background();

If you want to use setTimeout() itself and want to iterate only once then you can use

function background() {
  var colorArray = ["#14183b", "#002e2e", "#0d2d40", "#173052", "#194759", "#296b73"];

  function change(newcolor) {
    document.body.style.backgroundColor = newcolor;
  }
  colorArray.forEach(function(color, i) {
    setTimeout(change.bind(undefined, color), i * 1000);
  });
}

background();
Comment: That was an awesome answer. Can you explain a little bit about what:

 index = index >= colorArray.length ? 0 : index;

is doing?
Comment: @Trevor That is to reset the index to 0 once we reach the last item in the array
Answer: Improving ....
var colorArray = ["#14183b", "#002e2e", "#0d2d40", "#173052", "#194759", "#296b73"];

 var count = 0;

setInterval(function(){
    document.body.style.backgroundColor = colorArray[count];
    count++;
    if(count == colorArray.length) {
        count = 0;
    }
}, 1000);


Convert list of character vectors to tidy data frame

Question: I have a list of character vectors that I would like to convert into a tidy data frame. The lengths of the character vectors are unequal.
dput(data)
list(`ko03008 Ribosome biogenesis in eukaryotes` = c("G5382",
"G13330", "G4043", "G13255"), `ko03010 Ribosome` = c("G16823",
"G4822", "G11737", "G114", "G18144", "G6031", "G24182", "G9882",
"G14270", "G16903", "G2506", "G3550"), `ko03013 RNA transport` = c("G18058",
"G20817", "G6913", "G18004", "G4129", "G5382", "G5264", "G17529",
"G5114", "G21371", "G19351", "G15511", "G1049", "G14663"), `ko03015 mRNA surveillance pathway` = c("G20817",
"G6913", "G18004", "G4129", "G5382", "G19351", "G15511", "G1463"
), `ko03018 RNA degradation` = c("G11453", "G7437", "G11483",
"G12095"), `ko03020 RNA polymerase` = c("G13069", "G10917", "G6973",
"G7432"))

I would like to create a data frame with two columns. One with the name of each character vector within the list (e.g. 'ko03008 Ribosome biogeneis in eukaryotes') and the other with gene IDs (e.g. 'G5382).
I've used enframe to create a tibble that looks like this:

but I would like to format it like this (an example of what the first vector in the list should look like):
Answer: Use unnest_longer:
library(tidyverse)

data %>%
  enframe() %>%
  unnest_longer(value)

# A tibble: 46 x 2
   name                                      value
   <chr>                                     <chr>
 1 ko03008 Ribosome biogenesis in eukaryotes G5382
 2 ko03008 Ribosome biogenesis in eukaryotes G13330
 3 ko03008 Ribosome biogenesis in eukaryotes G4043
 4 ko03008 Ribosome biogenesis in eukaryotes G13255
 5 ko03010 Ribosome                          G16823
 6 ko03010 Ribosome                          G4822
 7 ko03010 Ribosome                          G11737
 8 ko03010 Ribosome                          G114
 9 ko03010 Ribosome                          G18144
10 ko03010 Ribosome                          G6031
# ... with 36 more rows


Substituir ou tratar método obsoleto

Question: Estou atualizando uma aplicação Android e me deparei com a seguinte situação:

Possuo um sdk mínimo de 21 e target de 27.
Um método que foi obsoletona versão 24.

Minha dúvida é a seguinte: qual a melhor ação para corrigir um método obsoleto?

Substituir o método antigo pelo novo?
Tratar para que o método antigo realize sua função para versões de android anteriores a 24 e o método novo realize as demais versões? (um simples if/else comparando as versões de api do celular com a do método.)
if{versão atual > 24){
    //Executa método novo.
}else{
    //Executa método antigo.
}
Answer: Depende.

A classe que tem esse método existe numa biblioteca de compatibilidade.

Use essa classe e mantenha a biblioteca actualizada.

A classe não existe na biblioteca de compatibilidade.

O método acrescenta funcionalidades nas versões mais recentes.

Recorra ao if(versao) e use o método correspondente.

O método não acrescenta funcionalidades.

Se o target for para manter, pode usar o método antigo.
Se o target é para ser actualizado para a versão mais recente, enquanto compilar pode usar o método antigo. Caso deixe de compilar e a condição 2 se mantiver, use if(versao)

O minSdk pode ser aumentado com impacto mínimo no alcance da aplicação.

Altere o minSdk e use o método novo.

Substituir ou tratar método obsoleto


create radio buttons using javascript

Question: I tried to create radio buttons dynamiclly(for a quiz project i make) using javascript but im having a prblem with it.
The radio button were created and i can see them on the screen, but for some reason i can not click them.
That's what i wrote:
    question += '<input type="radio" id="option1" name="question_option" value="option1" style="align-content: center" >firstOption';
    question += '<input type="radio" id="option2" name="question_option" value="option2" style="align-content: center" >secondOption';
    question += '
<input type="radio" id="option3" name="question_option" value="option3" style="align-content: center" >thirdOption';
    question += '<input type="radio" id="option4" name="question_option" value="option4" style="align-content: center" >fourthOption';
    question += '</form>';
    document.write(question);

Answer: Try to use like this .

$(function () {
  $('#div-radio-btns').empty();

var question='';

  question='<form>'+
    '<input type="radio" id="option1" name="question_option" value="option1" style="align-content:center" >firstOption
'+
    '<input type="radio" id="option2" name="question_option" value="option2" style="align-content: center" >secondOption
'+
    '<input type="radio" id="option3" name="question_option" value="option3" style="align-content: center" >thirdOption
'+
    '<input type="radio" id="option4" name="question_option" value="option4" style="align-content: center" >fourthOption'+
    '</form>';

   $('#div-radio-btns').append(question);
  });

Comment: That's jquery not javascript.
Answer: I'm really not sure what the details of your project are, but here's a rough example of how you could dynamically render radio buttons :D

const root = document.querySelector('#root');

const questions = [
    {
        name: 'choose an answer',
        options: [
            {
                name: 'first',
                isCorrect: false,
            },
            {
                name: 'second',
                isCorrect: false,
            },
            {
                name: 'third',
                isCorrect: true,
            },
            {
                name: 'fourth',
                isCorrect: false,
            },
        ],
    },
];

const createOptionRadio = (name) => {
    const container = document.createElement('div');

    const input = document.createElement('input');
    input.type = 'radio';
    input.className = 'question-option';
    input.value = name;
    input.id = name;
    input.name = 'question-option';

    const label = document.createElement('label');
    label.for = name;
    label.textContent = name[0].toUpperCase() + name.slice(1);

    container.appendChild(input);
    container.appendChild(label);

    return container;
};

const createQuestion = (questionObject) => {
    const container = document.createElement('div');
    container.className = 'question-container';

    const h3 = document.createElement('h3');
    h3.textContent = questionObject.name;
    container.appendChild(h3);

    const form = document.createElement('form');
    questionObject.options.forEach(({ name }) => form.appendChild(createOptionRadio(name)));
    container.appendChild(form);

    return container;
};

window.addEventListener('DOMContentLoaded', () => document.body.appendChild(createQuestion(questions[0])));

create radio buttons using javascript


Select de Estrutura de Produtos

Question: Bom dia!
existe alguma forma de criar uma query que traga o "produto" e todos os "Componentes e SubComponentes" da estrutura deste produto?
Deixe-me tentar explicar melhor
Estrutura
Imagem

Link da Imagem: https://i.stack.imgur.com/tGNZ4.jpg
Formato texto
- Bicicleta
  |
  + - Guidão
  |
  + - Quadro
  |   |
  |   + - Garfo
  |
  + - Banco
  |   |
  |   + - Selim
  |
  + - Roda
      |
      + - Aro
          |
          + - Raio
          |
          + - Pneu
              |
              + - Camara

Tenho a estrutura do equipamento "bicicleta" inserida no banco de dados e preciso obter quem é o "produto" e todos que estão abaixo (Componentes[eCOMP] e SubComponentes[eCOMP]) ligando todos ao produto principal
Exemplo
+--------+----------+--------+----------+
|eCOD    |eDESC2    |eCOMP   | eDESC2   |
+--------+----------+--------+----------+
|01.0001 |Bicicleta |01.0002 | Guidão   |
|01.0001 |Bicicleta |01.0003 | Quadro   |
|01.0001 |Bicicleta |01.0004 | Garfo    |
|01.0001 |Bicicleta |01.0005 | Banco    |
|01.0001 |Bicicleta |01.0006 | Selim    |
|01.0001 |Bicicleta |01.0007 | Roda     |
|01.0001 |Bicicleta |01.0008 | Aro      |
|01.0001 |Bicicleta |01.0009 | Raio     |
|01.0001 |Bicicleta |01.0010 | Pneu     |
|01.0001 |Bicicleta |01.0011 | Camara   |
+--------+----------+--------+----------+

Estrutura da Tabela
Dados no SQLFiddle
Dados em formato Texto
Cadastro de Produto [Tabela PROD]
pCOD     pDESC
01.0001  Bicicleta
01.0002  Guidão
01.0003  Quadro
01.0004  Garfo
01.0005  Banco
01.0006  Selim
01.0007  Roda
01.0008  Aro
01.0009  Raio
01.0010  Pneu
01.0011  Camara

Estrutura do Produto [Tabela ESTR]
eCOD     eCOMP    eQTD  eNiv
01.0001  01.0002     1     1
01.0001  01.0003     1     1
01.0003  01.0004     1     2
01.0001  01.0005     1     1
01.0005  01.0006     1     2
01.0001  01.0007     2     1
01.0007  01.0008     1     2
01.0008  01.0009     1     3
01.0008  01.0010     1     3
01.0010  01.0011     1     4

Dados em Formato SQL
CREATE TABLE PROD (
 pCOD varchar(15),
 pDESC varchar(100)
 );

insert into PROD (pCOD, pDESC) values
('01.0001','Bicicleta'),
('01.0002','Guidão'),
('01.0003','Quadro'),
('01.0004','Garfo'),
('01.0005','Banco'),
('01.0006','Selim'),
('01.0007','Roda'),
('01.0008','Aro'),
('01.0009','Raio'),
('01.0010','Pneu'),
('01.0011','Camara')

CREATE TABLE ESTR (
 eCOD varchar(15),
 eCOMP varchar(15),
 eQTD integer,
 eNIV integer
 );

insert into ESTR (eCOD, eCOMP, eQTD, eNIV) values
('01.0001','01.0002','1','1'),
('01.0001','01.0003','1','1'),
('01.0003','01.0004','1','2'),
('01.0001','01.0005','1','1'),
('01.0005','01.0006','1','2'),
('01.0001','01.0007','2','1'),
('01.0007','01.0008','1','2'),
('01.0008','01.0009','1','3'),
('01.0008','01.0010','1','3'),
('01.0010','01.0011','1','4')

Comment: Posta a estrutura das tabelas?
Comment: Inclua a imagem na pergunta, além de ficar melhor para visualizar, alguns links são bloqueados dependendo de onde acessamos o site
Comment: Vou adicionar a estrutura da tabela em formato texto.
Answer: É possível chegar ao resultado que pretende de duas formas: criando uma tabela temporária e ir preenchendo, linha a linha, a partir de um CURSOR (ou loop), que é mais trabalhoso porque terá que fazer a consulta por cada nível e em termos de performance (por norma) é mais lento, ou simplesmente utiliza CTE:
;WITH REC AS
(
    SELECT      E.*
    FROM        ESTR E
    INNER JOIN  PROD P ON P.pCOD = E.eCOD
    WHERE       E.eNIV = 1
    UNION ALL
    SELECT      R.eCOD, E.eCOMP, E.eQTD, E.eNIV
    FROM        ESTR E
    INNER JOIN  REC  R ON R.ecomp = E.ecod
)
SELECT      R.eCOD
        ,   P1.pDESC
        ,   R.eCOMP
        ,   P2.pDESC
        ,   R.eNIV
FROM        REC     R
INNER JOIN  PROD    P1 ON P1.pCOD = R.eCOD
INNER JOIN  PROD    P2 ON P2.pCOD = R.eCOMP
ORDER BY    R.eCOD
        ,   R.eNIV

Pode testar aqui no SQLFiddle.
Comment: Interessante, não tinha pensando por esse lado, irei realizar os testes e fazer alguns incrementos necessários para ver como vai ficar...

Select de Estrutura de Produtos


create a child node via api

Question: Running Drupal 9.3, I have two content types, job and and Job detail. Every job has many job details.
Lets say i created a job with node ID of 5. I have a field in job detail called "field_job_id" that will take the node ID of the parent, in this case "5".
When creating a job detail node, i have tried inputting the node ID as a int, as a string and nothing works.
<code>    "_links": {
    "type": {
      "href": "https://domain.com/rest/type/node/job_detail"
    }
  },
  "title": [
    {
      "value": filename
    }
  ],
  "field_job_id": [
    {
      "value": jobTitle
    }
  ],
  "field_document_type": [
    {
      "value": "PDF"
    }
  ],
  "field_author": [
    {
      "value": author
    }
  ],
  "field_remediation_cost": [
    {
      "value": "0"
    }
  ]
})
headers = {
  'Content-Type': 'application/hal+json',
  'Authorization': 'Basic HDHBdbdb83hcn8echw8fy389hfeuivbwe'
}
</code>
The node get posted but the field that should display the parent node is blank every time. Is there something i am doing wrong?
Comment: Is job id an entity reference? Should it be target_id instead?
Comment: ok...so it seems I need to add a "relationships" field to this but not quite sure how to do that.
Comment: @kevin Yes. it is a entity reference. I am very new to rest api so i will try that
Comment: @Kevin I could not for the life of me get a relationship into a rest api. Do you have an example?
Answer: FINALLY figured it out. since I am dealing with a entity ref, that being "field_job_id" I had to add a field
<code>  "field_job_id":[{"target_id":8}],
</code>
with 8 being the node of the job it is referencing

create a child node via api


Solving logarithms using variables

Question: LogQ= a+bLogP+cLogI+dLogPm
b= -2.174
c= 0.461
d= 1.909
Determine price elasticity of demand, income elasticity, and cross price elasticity
Comment: This question seems specialized to economics.  To achieve wider understanding of what you are asking, please tell your audience what $Q$, $P$, $I$, and $P_m$ mean and how they are supposed to be related to these elasticities.
Comment: I've tried utilizing the following computations: LogQ = PI(with a as the exponent)Pm(with -2.174 as the exponent), also LogQ = Log (PIPm)+ 4.544
Comment: Looks like a question on how to interpret the coefficients. Is it useful to `exp` both sides?
Comment: That I am unsure of. I can't determine if it would be better to use the independent variables instead of the actual values.
Answer: http://en.wikipedia.org/wiki/Elasticity_(economics)
This isn't really a statistics question, more just a straightforward application of the definitions of demand, income and cross-price elasticity.
Comment: This isn't really an answer, more like a comment. In future, please discriminate between them.

Solving logarithms using variables


Erro com o Webdriver no Python3.5 AttributeError: can't set attribute

Question: Estou precisando baixar o conteúdo de um site. Fiz um código em python 3.5. Quando eu o rodo apenas para uma única pagina o código funciona muito bem porém quando eu o coloco em um loop ou função ele dá erro.
O código como função é o seguinte:
from bs4 import BeautifulSoup
from selenium import webdriver
import html2text

def getPEP(strg):
    driver = webdriver.Firefox()
    driver.page_source = driver.get(strg)
    html = driver.page_source
    driver.close()
    text=html2text.html2text(html)
    return(text);

def salva():
    peps = open('PEP.txt', 'r')
    lines = tuple(peps)
    peps.close()
    for i in range(1):
        strg=lines[i].replace('\n','')
        print(strg + '\n')
        str(strg)
        getPEP(strg)
        start = '#  '
        end = ', \n\n[ ![Join us on'
        cleaned=(text.split(start))[1].split(end)[0]
        file = open(str(i)+'.txt', 'w')
        file.write(cleaned.replace(' ** ','').replace('**',''))
        file.close()
        print('arquivo ' + str(i) + 'gravado com sucesso' )
    return;

salva()

Quando eu coloco apenas na linha de comando como a seguinte:
>>> strg='http://www.mtsamples.com/site/pages/sample.asp?type=3-Allergy%20/%20Immunology&sample=386-Allergic%20Rhinitis, Allergic Rhinitis'
>>> driver = webdriver.Firefox()
>>> driver.page_source = driver.get(strg)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: can't set attribute
>>> html = driver.page_source
>>> driver.close()
>>> text=html2text.html2text(html)

Por mais que retorne esse erro eu ainda consigo recuperar o texto do site.
agora quando eu coloco como função:
>>> def getPEP(strg):
...     driver = webdriver.Firefox()
...     driver.page_source = driver.get(strg)
...     html = driver.page_source
...     driver.close()
...     text=html2text.html2text(html)
...     return(text);
...
>>> text=getPEP()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: getPEP() missing 1 required positional argument: 'strg'

Então o programa para no erro e não retorna o texto que eu preciso! Alguém pode me ajudar?

A fucao getPEP() funcionou, obrigada! Agora o meu código está assim:
from bs4 import BeautifulSoup
from selenium import webdriver
import html2text

# driver.page_source = driver.get())#
def getPEP(strg):
    driver = webdriver.Firefox()
    driver.get(strg)
    html = driver.page_source
    driver.close()
    text=html2text.html2text(html)
    return(text);

def salva(arqv):
    peps = open(arqv, 'r')
    lines = tuple(peps)
    peps.close()
    for i in range(len(lines)):
        strg=lines[i].replace('\n','')
        text=getPEP(strg)
        start = '#  '
        end = ', \n\n[ ![Join us on'
        cleaned=(text.split(start))[1].split(end)[0]
        file = open(str(i)+'.txt', 'w')
        file.write(cleaned.replace(' ** ','').replace('**',''))
        file.close()
        print('arquivo ' + str(i) + 'gravado com sucesso' )
    return;

getPEP('PEP.txt')

A função getPEP(strg) esta funcionando perfeitamente, obrigada!
Porám quando chamo a função salva(arqv) que era para ler as urls que eu quero baixar, coletar o texto que eu quero salvar por meio da função getPEP(strg) e gravar em um arquivo, está dando o seguinte erro:
Traceback (most recent call last):
  File "crawlerPEP.py", line 35, in <module>
    getPEP('PEP.txt')
  File "crawlerPEP.py", line 10, in getPEP
    driver.get(strg)
  File "/home/angelica/Documents/PyEnv3/lib/python3.5/site-packages/selenium/webdriver/remote/webdriver.py", line 248, in get
    self.execute(Command.GET, {'url': url})
  File "/home/angelica/Documents/PyEnv3/lib/python3.5/site-packages/selenium/webdriver/remote/webdriver.py", line 236, in execute
    self.error_handler.check_response(response)
  File "/home/angelica/Documents/PyEnv3/lib/python3.5/site-packages/selenium/webdriver/remote/errorhandler.py", line 192, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: Target URL PEP.txt is not well-formed.
Stacktrace:
    at FirefoxDriver.prototype.get (file:///email@example.com/components/driver-component.js:10636)
    at DelayedCommand.prototype.executeInternal_/h (file:///firstname.lastname@example.com/components/command-processor.js:12661)
    at DelayedCommand.prototype.executeInternal_ (file:///email@example.com/components/command-processor.js:12666)
    at DelayedCommand.prototype.execute/< (file:///firstname.lastname@example.com/components/command-processor.js:12608)

Answer: >>> driver = webdriver.Firefox()
>>> driver.page_source = driver.get(strg)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: can't set attribute

O erro indica que não foi possível definir um atributo, page_source é usado para retornar o conteúdo da página, você não pode sobrescrevê-lo. Coloque o resultado em uma variável:
>>> driver = webdriver.Firefox()
>>> driver.get(strg)
>>> conteudo = driver.page_source

O segundo erro:
>>> text=getPEP()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: getPEP() missing 1 required positional argument: 'strg'

A função getPEP espera um argumento, que neste caso é a URL  que você quer obter o conteúdo. Passe a URL para a função:
>>> strg = 'http://www.mtsamples.com/site/pages/......'
>>> text = getPEP(strg)

A função getPEP deve ficar assim:
>>> def getPEP(strg):
...     driver = webdriver.Firefox()
...     driver.get(strg)
...     html = driver.page_source
...     driver.close()
...     text = html2text.html2text(html)
...     return (text)

Comment: Obrigada! Agora esta apresentando outro erro coloquei na pergunta acima poderia me ajudar novamente?
Comment: @user2535338 Você está passando o nome do arquivo para `getPEP` (ele pede uma URL), não era para usar a função `salva`? assim: `salva('PEP.txt')`.
Comment: Sao varias URLs que estao nesse arquivo 'PEP.txt'
Comment: @user2535338 Na função `salva` você chama `getPEP` para cada linha (URL) presente no arquivo e salva o resultado num novo arquivo tendo como nome o número da linha.


Conexão com o banco fica aberta em método estático?

Question: Tenho a seguinte classe estática disponível para toda a aplicação:
public static class MinhaClasse
{
   public static void Salvar(Item meuItem)
   {
       using (MeuEntities db = new MeuEntities())
       {
           db.Item.Add(meuItem);
           db.SaveChanges();
           db.Dispose();
       }
   }
}

Este é apenas um exemplo, mas minha classe precisa necessariamente ser
  estática.

A dúvida é:
Por ser uma classe estática e possuir conexão com o banco de dados, esta  conexão fica aberta a todo tempo ou apenas é aberta quando chamo MinhaClasse.Salvar(Item); ?
Estou usando Entity Framework.
Comment: Baseado em experiencia com outro `Framework` penso que é redundante `db.Dispose()` já que `using` automaticamente faria este trabalho.

Portanto, tanto  `db.Dispose()` quanto `using` fechariam a conexão.
Answer: MeuEntities é uma classe gerada pelo Entity Framework, herdando de de DbContext, certo?
Ciclo de vida da conexão
Usando o Entity Framework, você não controla o ciclo de vida da conexão mas sim o ciclo de vida do contexto. Em momentos específicos o contexto vai requisitar uma conexão com o banco para buscar ou persistir entidades.
A conexão física com o banco de dados é gerenciada pelo ADO.Net, que mantém um pool de conexões para evitar criar uma nova conexão todas as vezes que o consumidor precisar de uma, com isso ele oferece melhor performance já que criar conexão com o banco de dados tem custo alto.

Mantenha curta a vida do contexto e deixe a gerência de conexões com o Entity Framework e o ADO.Net que ele usa por baixo.

E isso você já está fazendo já que você cria o contexto apenas para persistir e já se desfaz dele.
Relação entre a classe ser estática e o ciclo de vida da conexão.
Não há nenhuma relação. O escopo do contexto ou fato de você se desfazer dele (seja por invocar o método dispose ou seja por instanciá-lo com o using) é que vai afetar o ciclo de vida da conexão. O fato de a classe que consome o contexto ser estática não tem nenhuma relação.
Agora, se você declarar o contexto numa variável estática e não se desfizer dele nunca, daí sim você poderá afetar negativamente o ciclo de vida da conexão.
Por fim
Remova do seu código a chamada ao método dispose pois o using serve justamente para garantir esta chamada.
Comment: Ótima resposta. `MeuEntities` está herdando sim de `DbContext`. Muito obrigado, ficou bem claro!
Answer: Eu questionaria se realmente precisa que a classe precisa ser estática. Muitas vezes achamos que precisa mas na realidade não precisa. Mas não estou dizendo que isto seja um problema em si.
Eu não sei bem como funcionam essa classe que está usando mas vou confiar que ela abre a conexão. Sei que ela abre algum recurso que precisa ser fechado. E você usou da forma correta, com using. A linguagem se encarrega de dispor o recurso quando ele não for mais necessário sem seu código ter que se preocupar com isto.
Então o Dispose() usado é desnecessário.
Se a classe MeuEntities foi escrita corretamente, a conexão será fechada automaticamente. Como ela deve ter como base algo escrito no EF, ela deve estar fazendo corretamente.
Answer:
Por ser uma classe estática e possuir conexão com o banco de dados, esta conexão fica aberta a todo tempo ou apenas é aberta quando chamo MinhaClasse.Salvar(Item);?

Não.
O Dispose do DbContext chama o Dispose da DbConnection associada. Significa que, ao final do using, a conexão é fechada.
Ou seja, a cada chamada do seu método estático, uma nova conexão é aberta.
Para sistemas Web, isto está correto, já que o ciclo de vida de uma requisição em ASP.NET MVC não conta com conexões persistentes, sejam elas a bancos de dados ou serviços. O Entity Framework apenas segue a mesma premissa, fechando a conexão ao banco quando ela não é usada.


How to disable "publish" content for a particular role?

Question: I created a role called writer who should have the ability to create content, but not be allowed to publish it.  A person with the admin role can review the content then publish it.
Also, if a writer edits existing content, it can not be immediately published to the website.  Only an admin can publish it after review.  Until then, the old version is displayed.
How do i disable the ability to publish for a person with the writer role?
Comment: Possible dup of http://drupal.stackexchange.com/questions/3468/forbid-the-publication
Answer: Just unchecked publish checkbox on content type setting page and hide this field with CSS if user has writer role or remove it programmatically on the same condition with hook_form_alter
Comment: this almost works.  The only problem now is if the writer edits published content, his changes are immediately visible to the public.  His changes need to be published by admin before visible to the public.  Until then, the last published copy remain.
Comment: Use the revisioning module to prevent writer's from publishing "revisions of existing content".
Answer: You might also want to take a look at The Workbench module. Out of the box it gives three important solutions:

a unified and simplified user interface for users who ONLY have to work with content. This decreases training and support time.
the ability to control who has access to edit any content based on an organization's structure not the web site structure
a customizable editorial workflow that integrates with the access control feature described above or works independently on its own
Comment: Thanks nigel, do you know if it satisfies the criteria: if writer "edits" existing content, it should not be immediately viewable to the web until admin reviews and publishes.
Comment: I have not yet full utilized this module, but it does allow for pretty granular control over the publishing workflow. So, I am would assume yes, but you may have to investigate more. Or maybe someone else can chime in.


insert debug env json propety VSCode

Question: I want to configure go debug env json properties like following
DEV_PROP=
'{
 "run": "app.sh",
 "server_port": "8081",
 "app_url":"http://localhost:3000"
}'

Ive tried to enter the following to the env but I got error
"configurations": [

    {
        "name": "Launch",
        "type": "go",
        "request": "launch",
        "mode": "debug",
        "remotePath": "",
        "port": 2345,
        "host": "127.0.0.1",
        "program": "${fileDirname}",
        "env": {

        },

when I insert the DEV_PROP to the env object I got lots of error, ive tried to play with quotas without success, any idea?
Answer: Did you try this way?
{
    "name": "Launch",
    "type": "go",
    "request": "launch",
    "mode": "debug",
    "remotePath": "",
    "port": 2345,
    "host": "127.0.0.1",
    "program": "${fileDirname}",
    "env": {
        "run": "app.sh",
        "server_port": "8081",
        "app_url":"http://localhost:3000"
    },

As shown here http://techbrij.com/visual-studio-code-tasks-debugging
Also by convention environment variables should be all UPPER_CASE as shown here https://stackoverflow.com/a/673940/6314736
So it should look like that:
{
    "name": "Launch",
    "type": "go",
    "request": "launch",
    "mode": "debug",
    "remotePath": "",
    "port": 2345,
    "host": "127.0.0.1",
    "program": "${fileDirname}",
    "env": {
        "RUN": "app.sh",
        "SERVER_PORT": "8081",
        "APP_URL":"http://localhost:3000"
    }
}

Also if you want to have separate launch for dev environment just copy this object and change "name" property to whatever you like. It should be in Configuration array.
EDIT
As Adrian pointed out, my answer to this question was wrong.
The correct answer is to escape double quotes with backslashes.
"env":{
"DEV_PROP":"\"run\":\"app.sh\",\"server_port\":\"8081\",\"app_url\":\"http
://localhost:3000\"}"
}
I've tested it and it works fine.
Picture for proof
Comment: Not 100% sure but judging by the way the question is written, they want a single environment variable `DEV_PROP` whose value is the JSON they gave.
Comment: oh yeah, you are probably right. Then maybe escape quotes with backslashes
`"DEV_PROP":"
{
 \"run\": \"app.sh\",
 \"server_port\": \"8081\",
 \"app_url\":\"http://localhost:3000\"
}"`

insert debug env json propety VSCode


Verificar se existe determinado item dentro de array, através de uma variável

Question: Digamos que eu tenha esse array:
let checkOne = [
{
"id": 273,
"attributes": {
"humidity": {
"qty": 74.3223333333333,
"unit": "percents"
},
"protein": {
"qty": 23.525,
"unit": "g"
},
"lipid": {
"qty": 1.23766666666667,
"unit": "g"
},
}
}];

Quero atráves da variável tipo verificar se o conteúdo que está na mesma existe dentro do array:
//Tentava
let tipo = 'protein'
let resultado = (typeof checkOne[0].attributes.tipo !== 'undefined');

console.log(resultado) //era para retornar true, mas aparece false

Answer: O problema está na forma de acessar os atributos de um objeto. Considere este exemplo simples:

let pessoa = {
    idade: 20
};

console.log(pessoa.idade); // 20
console.log(pessoa['idade']); // 20

O objeto pessoa possui um atributo chamado "idade". E para acessá-lo, você pode usar pessoa.idade ou pessoa["idade"] - na primeira você acessa o atributo diretamente, na segunda, como uma string contendo o nome da propriedade entre colchetes.
Agora, se o nome da propriedade está em uma variável, a primeira forma não funciona (somente a segunda):

let pessoa = {
    idade: 20
};

let nomePropriedade = 'idade';
console.log(pessoa.nomePropriedade); // undefined
console.log(pessoa[nomePropriedade]); // 20

Isso porque pessoa.nomePropriedade é o mesmo que pessoa["nomePropriedade"], ou seja, estou procurando por uma propriedade cujo nome é "nomePropriedade". Somente usando  pessoa[nomePropriedade] eu consigo obter a propriedade cujo nome é o valor da variável nomePropriedade.

Sendo assim, no seu caso attributes.tipo está buscando por uma propriedade chamada "tipo" e não vai funcionar. Então você precisaria usar a segunda opção (a variável entre colchetes, ou seja, attributes[tipo]):

let checkOne = [{
        "id": 273,
        "attributes": {
            "humidity": {
                "qty": 74.3223333333333,
                "unit": "percents"
            },
            "protein": {
                "qty": 23.525,
                "unit": "g"
            },
            "lipid": {
                "qty": 1.23766666666667,
                "unit": "g"
            },
        }
    }
];

let tipo = 'protein';
let resultado = (typeof checkOne[0].attributes[tipo] !== 'undefined');

console.log(resultado); // true
Answer: Olá!
Se você tentar acessar o atributo desta maneira checkOne[0].attributes.tipo, você está tentando acessar a variável tipo dentro dos atributos, e sempre dará falso.
Se precisa acessar um atributo de um objeto de forma dinâmica, você precisa acessá-lo com colchetes:
let tipo = 'protein';
checkOne[0].attributes[tipo] // js vai interpretar como checkOne[0].attributes.protein

Então você pode utilizar isso para criar uma função e verificar se o item possui o atributo.
function possuiTipo(item, tipo) {
    return item.attributes[tipo] !== undefined; // se existir retornará true;
}

Se quiser saber quais são todos os itens que possui esse tipo, você pode utilizar a função filter() juntamente com a função anterior.
const tipo = "protein";
const resultado = checkOne.filter(item => {
    return possuiTipo(item, tipo)
});

Answer: Essa condição typeof checkOne[0].attributes.tipo !== 'undefined' será sempre false, pois não existe uma propriedade tipo dentro de attributes, ou seja, attributes.tipo é undefined.
Além disso você pode checar diretamente a propriedade protein usando a função some:
checkOne.some(item=>item.attributes.protein) // return true se ao menos um elemento possui attributes.protein

Comment: mas no meu caso eu preciso verificar mais de uma propriedade.
Comment: digamos que preciso verificar 100 propriedades, se for por essa lógica teria que escrever checkOne.some(item=>item.attributes.propX) 100 vezes


Spring RabbitMQ SimpleRabbitListenerContainerFactory usage

Question: From the docs, I want to use consume from queues by dynamically changing the consumers without restarting the application.
I do see that Spring RabbitMQ latest version supports the same, but no clue/example/explanation to change the same. I couldn't see proper source code for the same or how to pass params like maxConcurrentConsumers
I am using XML based configuration of Spring RabbitMQ along with Spring integration
<bean id="rabbitListenerContainerFactory"
      class="org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory">
    <property name="connectionFactory" ref="rabbitConnectionFactory"/>
    <property name="concurrentConsumers" value="3"/>
    <property name="maxConcurrentConsumers" value="10"/>
    <property name="acknowledgeMode" value="AUTO" />
</bean>

<int-amqp:inbound-channel-adapter channel="lowInboundChannel" queue-names="lowLoadQueue" advice-chain="retryInterceptor" acknowledge-mode="AUTO" listener-container="rabbitListenerContainerFactory" />
<int-amqp:inbound-channel-adapter channel="highInboundChannel" queue-names="highLoadQueue" advice-chain="retryInterceptor" acknowledge-mode="AUTO" listener-container="rabbitListenerContainerFactory" />

Can anyone guide me how to dynamically configure the consumers?
Answer: First of all you shouldn't share the same rabbitListenerContainerFactory for different <int-amqp:inbound-channel-adapter>s, because they do this:
protected void onInit() {
    this.messageListenerContainer.setMessageListener(new ChannelAwareMessageListener() {

So, only last adapter wins.
From other side there is even no reason to have several adapters. You can specify queue-names="highLoadQueue,lowLoadQueue" for a single adapter.
Although in case of listener-container you must specify queues on the SimpleRabbitListenerContainerFactory.
If you want to change some rabbitListenerContainerFactory options at runtime, you can just inject it to some service and invoke its setters.
Let me know if I have missed anything.
Comment: sorry for late reply. so you are saying single adapter for different `queues`. Each queue will have it's own (different) payload. Why should we combine into single adapter?

so do we need to have multiple listenerContainerFactory for each `queue`? Why it's named as `Factory`, I thought it's single connection point to listen to multiple queues!!
Comment: Oh! Sorry, I really have missed that part. No, you can't use `SimpleRabbitListenerContainerFactory` for the ``. Its goal for the Annotation `@RabbitListener` configuration. For the XML config you should use `SimpleMessageListenerContainer` bean definition. And yes: separate bean for each  ``. Or just rely on the default container from the ``
Comment: I couldn't figure out the way still how to change dynamically the consumers. Can you please give me sample example/code/xml config?


java -cp h2*.jar org.h2.tools.Backup -? no work

Question: I have Windows 7 and try to execute
java -cp h2*.jar org.h2.tools.Backup -?
 In prompt i see that file with jar extenson is not find. How solve this problem. I aldhougt write all path (C/Program Files/H2 ... etc.).
Answer: That's not the syntax for classpath wildcards. You need either to list each JAR separated by (semi)colons or use <code>[directory/]*</code> to sweep up all the JARs in the directory. You can't use wildcards to cherry-pick specific file patterns. All this would have been clear to you had you Read the Fine Manual at
https://docs.oracle.com/javase/8/docs/technotes/tools/unix/classpath.html#A1100762
and related pages.


Can Drupal's search index external tables?

Question: Can Drupal's search system index external tables?
I have looked up how external tables can be linked to Drupal using the Data module, hook_views_data etc.,
Can the content of the external tables be indexed and searched by Drupal's search system?
Answer: Yes, you can use the search api to specify your additional content. In particular you will need

hook_search_info
hook_update_index
hook_search_execute
Comment: Is there something simpler, like a module? I am rather code phobic.


Erro ao incluir a class no arquivo index assim não consigo instanciar ela [PHP]

Question: Olá tenho dois arquivo o INDEX.PHP que se localiza na raiz do projeto e o Arquivo SYSTEM.PHP que se localiza dentro da pasta LIB.
Resumo do Arquivo INDEX
<?php
  define('APP_ROOT', 'home');
  require_once 'config/Bootstrap.php';
  require_once 'lib/System.php';
  $System = new System();
  $System->start();

Resumo do arquivo SYSTEM
<?php
  namespace lib;
  require_once 'Router.php';
  class System extends Router {

   Aqui contem o method **START**

  }

O php retorna o seguinte erro: Fatal error: Uncaught Error: Class 'System' not found in 'Meu diretorio'
Já dei um var_dump exists_file no caminho direto da INDEX para o caminho lib/System.php e retornou TRUE, o caminho está correto mas pq não encontro a class?
Answer: A sua classe System pertence ao namespace lib e, portanto, seu "nome completo" (ou fully-qualified name) é lib\System.  Sendo assim, para invocá-la, você precisa referencia-la por seu "nome completo".
// ...
$System = new lib\System();

Ou usar aliases:
require_once 'caminho/para/arquivo.php';

use lib\System;

$System = new System();

Ou ainda,
require_once 'caminho/para/arquivo.php';

use lib\System as MyClass;

$System = new MyClass();

Comment: @Otávio Se você acha que minha resposta solucionou seu problema, clica no "vezinho" que está na esqueda da minha resposta (veja aqui [como aceitar uma resposta](https://pt.meta.stackoverflow.com/questions/1078/como-e-por-que-aceitar-uma-resposta)) para ajudar a comunidade. Obrigado


When to use Object map vs Map class in ES6

Question: Suppose I wanted to create a dictionary of, say, car makes to one or more models.
It seems that I could do this in two different ways in ES6.
1. Create an Object map:
Code:
const makesAndModels = {
    "mazda": [
        { name: "Miata" },
        { name: "626" }
    ],
    "toyota": [
        { name: "Camry" }
    ],
    ...
};

2. Create an ES6 Map instance:
Code:
const makes = {
    mazda: { name: "Mazda" },
    toyota: { name: "Toyota" }
};

const makesAndModels = new Map([
    [makes.mazda, [
        { name: "Miata" },
        { name: "626" }
    ]],
    [makes.toyota, [
        { name: "Camry" }
    ]],
    ...
]);

What are the key differences and pros/cons between the above two methods?
Comment: The map you create in the example has a serious problem: you cannot get the values by key. Because maps compare keys using standard equality and this cannot be customized, `makesAndModels[{name: "Mazda"}]` will always evaluate to `undefined`.
Comment: Actually, I'm slightly mistaken. You can get the keys with map.keys.
Comment: I'm thinking of generalising this question because I think it actually applies to Javascript in general, not only Typescript. Anyone agree? Upvote this comment if yes?
Comment: Ah right you are... will fix the example.
Comment: Your second code makes no sense. To be comparable to the first, it should use strings as keys of the `Map` as well
Answer: Here are the differences I've found thus-far:

Map allows you to use any type for the key. So if you want, you can store an entire object in the key, where, for an index signature, Typescript currently only supports string or number keys.

Map is only natively supported in ES6. If targeting ES5 or lower, you need to provide a polyfill.

Not sure if these are exhaustive though.
Edit: Just discovered an Objects vs. Maps section in the Mozilla docs, which looks pretty comprehensive.
It includes the following items not mentioned above:

The keys in Map are ordered while keys added to object are not. Thus, when iterating over it, a Map object returns keys in order of insertion.

You can get the size of a Map easily with the size property, while the number of properties in an Object must be determined manually.

A Map is an iterable and can thus be directly iterated, whereas iterating over an Object requires obtaining its keys in some fashion and iterating over them.

An Object has a prototype, so there are default keys in the map that could collide with your keys if you're not careful. As of ES5 this can be bypassed by using map = Object.create(null), but this is seldom done.

A Map may perform better in scenarios involving frequent addition and removal of key pairs.
Comment: The primary advantage of Maps, being able to use any value as a key, is diminished significantly by the lack of customizable equality. The API for both Set and Map is pathetic. Another failure of the Maximally Minimal approach of TC39
Comment: Also worth mentioning is that `Map` is not deserialized by default
Comment: As of ES2020 Object.keys are ordered. https://stackoverflow.com/a/30919039/19212
Comment: Depends on the use case. If string, number, or symbol keys are all you need, use an object for ease of use, especially at API boundaries like function parameters. If you need to use other kinds of values as keys then you must use a map. Also WeakMap offers functionality, whatever the key requirements, which simple objects cannot provide. A WeakMap is very powerful but you likely won't need it often.
Comment: Noted. I wonder if it's worth still using Map, in hopes that the API will improve, so that I don't have to change all my code down the track. Or whether it's a better overall approach to just use the 'object-map' approach.
Comment: @Buggy Quite so. JSON has no way to express a `Map` or a `Set`. It also can't express symbols for similar reasons


How to Create and Retrive a product programmatically in Drupal commerce 2.x

Question: I have created the store in Drupal commerce 2.x. I have added a product for the product type from the dashboard. Now i want to create Product grammatically  in  my custom module. how  this can be done Drupal 8 for Drupal commerce 2.x
Answer: To create a product is similar to how you'd create a node:
<code>use Drupal\commerce_product\Entity\ProductVariation;
use Drupal\commerce_product\Entity\Product;
use Drupal\commerce_price\Price;

$variation1 = ProductVariation::create([
  'type' => 'default',
   'sku' => '123',
   'price' => new Price('14.50', 'USD'),
]);
$variation1->save();

$variation2 = ProductVariation::create([
  'type' => 'default',
   'sku' => '1234',
   'price' => new Price('10.00', 'USD'),
]);
$variation2->save();

$product = Product::create([
   'type' => 'default',
   'title' => t('Product Title'),
    'variations' => [$variation1, $variation2],
]);
$product->save();
</code>
Answer: It seems duplicate of https://stackoverflow.com/a/56225927/7528823 or please see the documentation --- Creating Products


laravel + vue  doesn't change the content

Question: I have a project using laravel + vue ,i listed all articles in the main page ,When the user clicks on a specific article, a page opens and displays the article with the most prominent articles appearing on the side like this: .
the main page code is:
    <template>

                <top-articles />

                <new-articles />

                <router-link :to="{ name: 'SinglePost', params: { id: article.id } }">

{{ article.title.ar }}

                </router-link>

{{ article.excerpt.ar + ' Read more' }}

                <our-stories />

</template>

in post page:

the post page code is:
    <template>

        <go-back />

{{articles.body.en}}

                       <top-articles />
                     {{articlesId}}

                     <our-stories />

         <router-view :key="$route.path"> </router-view>

            {{articlesId}}

</template>

the problem is: When the user clicks on an article on the main page, it opens and displays on the page and the top articles appear with you on the side. Everything is good so far, but when the user clicks on one of the articles on the side of the post, nothing happens (only the id in the url changes to the article's id New) but the content remains the previous article , I want the content to change whenever the user clicks on an article from the articles on the side of the post
Answer: You need to move the axios request to a method and call it inside created hook. Then use watch to reactive route changes and call the axios request again inside watch.


pdf.savefig gives "An error opening...This file is already open...corrupted" when saving Pie chart to PDF

Question: I am trying to plot pie graphs using my a CSV file I have created via webscrapping.
I am able to print/show the pie graphs but unable to save it on PDF file. I tried removing plt.show()/adding it back after pdf.savefig(fig) but that did not work. Here is my Code:
(Part of the CSV file is below the Python code)
from cmath import inf
from bs4 import BeautifulSoup
import requests
from csv import writer
import pandas as pd
#%matplotlib inline
import numpy as np
import re
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(palette="Paired")
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.backends.backend_pdf

data_frame = pd.read_csv("UFCstats.csv")

data_frame.head(500)
df = pd.DataFrame(columns=["totalwins","totalloss"], data=data_frame.head(500))
pdf = matplotlib.backends.backend_pdf.PdfPages('pic.pdf')

for ind in df.index:
    fig, ax = plt.subplots(1,1)
    fig.set_size_inches(5,5)
    df.iloc[ind].plot(kind='pie', ax=ax, shadow=True, title=data_frame.iloc[ind]["Fullname"], explode=[0.03,0.03], autopct='%1.1f%%')
    ax.set_ylabel("total wins are " + str(data_frame.iloc[ind]["totalwins"]))
    ax.set_xlabel("total losses are " + str(data_frame.iloc[ind]["totalloss"]))
    pdf.savefig(fig)
plt.show()

Error when trying to open the PDF file: "There was an error opening this document. This file is already open or in use by another application"
Comment: Thank you so much! please put your answer onto Solution area so I can give you credit. thanks again
Answer: you need to close the pdf file at the end of the code (outside the for loop). This will close the file and you can open it without issues. Use pdf.close() to close the file.


Quadratic form greater than zero

Question: This appeared as a subproblem in a linear algebra exercise.
What values can $γ_{ij} \in \Bbb R,i=1,2,j=1,2$, have such that $$a_1^2γ_{11}+a_1a_2(γ_{12}+γ_{21})+a_2^2γ_{22} \ge 0?$$
where $a_k \in \Bbb R,k=1,2$
This is closely related to the $Δ$ of a polynomial $ax^2+bx+c$, but since it is not a polynomial we have here, I can't set the $Δ \ge 0$. So how do we approach such a problem and find $γ_{ij}$?
Answer: You've almost got it! The key realization is that the expression
$$
a_1^2γ_{11}+a_1a_2(γ_{12}+γ_{21})+a_2^2γ_{22} = a_2^2 \bigg( \Big(\frac{a_1}{a_2}\Big)^2γ_{11}+\frac{a_1}{a_2}(γ_{12}+γ_{21})+γ_{22} \bigg)
$$
is essentially a quadratic polynomial, but in the variable $\frac{a_1}{a_2}$ (or its reciprocal, alternatively). So the discriminant is indeed the thing you want to look at (as well as the signs of $\gamma_{11}$ and $\gamma_{22}$, of course).
Comment: Yes, this seems to be correct. Though the exercise has a different result..the $γ_{ij}$ are elements of a matrix and it set $γ_{12}=γ_{21}$ so that it is a symmetric matrix for some reason.

Quadratic form greater than zero


How to solve problem with javascript files served from cache?

Question: When server side code is updated (related to JavaScript) the old JavaScript files are served from cache.
I need a solution where the old JavaScript files get updated to their newer versions. Browser cache (related to JavaScript) need to be invalidated once the files on server are updated.
I have got the following solution to this problem.
var randomnumber=Math.floor(Math.random()*10000);

var scriptfile='http://www.whatever.com/myjs.js?rnd='+randnumber;

But I need to clear cache only when there is some update on the JavaScript files not on every reload of the page.
Answer: Most sites - including Stack Overflow - use a revision number from their version control system for this:
var scriptfile='http://www.whatever.com/myjs.js?rnd='+revision_number;

whenever the revision changes, the browser gets pointed to a "new" JavaScript file.
You can do this manually as well, by specifying a version number at a central place somewhere, and adding that version number to every script call. When you update a part of the JavaScript, you simply increment the version number.
A third approach would be checking the "last modified" time of the JavaScript files you are including, and building a timestamp from it:
var scriptfile='http://www.whatever.com/myjs.js?version=20100803';

but that would require server-side scripting and may be too expensive to do on every page request.
Answer: Instead of using a random number, use a version number or update timestamp, so it becomes:
var script = 'http://mysite.com/the_script.js?2010-08-02';

// or

var script = 'http://mysite.com/the_script.js?v1.20';

If you don't want to update this manually, you can either use a make script that searches for and replaces a tag with a version number:
var script = 'http://mysite.com/the_script.js?{{script_update_date}}';

// have a shell script find and replace the above {{ }} tag with the date or such
// when deploying to production

Or if your version control system uses it (like SVN) you can have it replaced with the revision number so that it is updated when a new script is checked in.
Comment: @Pekka  and Jesse Dhillon- Thanks a lot for your suggestion


How do I show the site-wide contact form on a page in Drupal 7?

Question: I have seen other posts about this, but none specifically for Drupal 7, and I can't get it to work. I am trying to get the default contact form to show up below the main content of a page, perhaps in a block.
Do you have any suggestions?
Answer: You could create a custom block in a module and embed the form there. Something like this (I haven't tested this code!):
<code>/**
 * Implements hook_block_info().
 *
 * This hook declares what blocks are provided by the module.
 */
function MODULENAME_block_info() {

  $blocks['contact_block_form'] = array(
    'info' => t('Contact Form'),
    );

  return $blocks;
}

/**
 * Implements hook_block_view().
 *
 * This hook generates the contents of the blocks themselves.
 */
function MODULENAME_block_view($delta = '') {
  //The $delta parameter tells us which block is being requested.
  switch ($delta) {
        case 'contact_block_form':
      $block['subject'] = t('Contact Us');
      // Load contact pages inc as the form definition sits there.
          module_load_include('inc', 'contact', 'contact.pages');
      $block['content'] = drupal_get_form('contact_site_form');
    break;
  }
  return $block;
}
</code>
Hope this helps
Comment: I solved this problem by using the module http://drupal.org/project/contact_form_on_node which easily allowed me to add the form to a block.

Thank you Reece Marsland for taking the time to help me out as well!
Comment: No problem. Glad you got a solution.
Comment: You saved my day. Many many thanks to you. Instead of making new module, i played with hook and it worked. But, full credits to you for the hint...


Receber quantidade indefinida de parâmetros em C#

Question: O método Main(string[] args) recebe um array de parâmetros de quantidade indefinida. Mas sei que isso não funciona em um método comum. Como se cria um método que receba quantos parâmetros forem necessários?
Comment: Há um equívoco na sua pergunta, se não fosse possível como a função `Main` o faria? A resposta do @Lucas Nunes está correta, mas é possível fazer das duas maneiras. Existe uma diferença de própositos entre receber uma array de tamanho indeterminado e receber uma quantidade indeterminada de parâmetros.
Comment: @Cahe Editei a resposta acrescentando alguns detalhes. No caso, o `Main` já recebe um `string[]` devidamente tratado enquanto os métodos com `params` tem os argumentos convertidas em tempo de compilação para algo do tipo `new int[] {1,2,3}`, e funcionam como um `int[]` normal.
Comment: Meu propósito é simples: dar liberdade ao usuário de informar quantos valores ele quiser somar, ou multiplicar, por exemplo. `params`, como ensinado pelo @Lucas Nunes, parece ser o mais correto, mas se houver outras formas, por favor apresente como resposta ou mesmo comentário. O importante é nós aprendermos.
Answer: Você pode fazer isso utilizando a palavra-chave params.Com ela você define um parâmetro que utiliza vários argumentos ou nenhum.
Por exemplo:
    private static int Somar(params int[] values)
    {
        int sum = 0;

        for (int i = 0; i < values.Length; i++)
        {
            sum += values[i];
        }

        return sum;
    }

E, com isso, você pode chamar as Somar() da seguinte forma:
    static void Main(string[] args)
    {
        Console.WriteLine("O resultado da soma é " + Somar(1, 2, 3, 4, 5));
        Console.WriteLine("Outro resultado da soma é " + Somar(10, 20, 4));
        Console.WriteLine("Quando não soma nada é " + Somar());

        Console.Read();
    }

Deve-se ressaltar que o parâmetro com params deve ser o último na função. Por exemplo:
// A seguite declaração é inválida:
private static void Imprimir(params int[] valores, string titulo) { }

// Já essa é válida (pois params vai por último):
private static void Imprimir(string titulo, params int[] valores) { }

Outro detalha importante é que o compilador dará prioridade para a versão especializada do método (se esse existir).
Por exemplo, se você tem os seguintes métodos definidos:
private static int Somar(int a, int b) { }
private static int Somar(params int[] values) { }

e chamar Somar(10, 20), o compilador dará prioridade ao primeiro.

Outro caso especial é quando deseja-se utilizar params para vários tipos. Nesse caso, utiliza-se object ao invés do tipo específico.
Um exemplo é o seguinte:
public static void ImprimirLista(params object[] list)
{
    for (int i = 0; i < list.Length; i++)
    {
        Console.Write(list[i] + " ");
    }

    Console.WriteLine();
}

Que é aplicado assim:
ImprimirLista(10, "String", 20.4);

Quando se compara os métodos que usam params aos métodos que não usam params, deve-se considerar que o palavra-chave params é tratada pelo compilador de forma que quando se chama Somar(2, 3, 4), o compilador transforma em Somar(new int[]{2,3,4}). Sem params, o compilador não fará essa consideração e exigirá que um int[].
Por isso, a definição dos seguintes métodos resultarão em um conflito pois são equivalentes:
 public static void ImprimirLista(params int[] list) {}
 public static void ImprimirLista(int[] list) {}

Answer: A resposta do Lucas Nunes está correta e bem completa. Só vou oferecer alternativas que podem ser úteis para outras pessoas hoje e no futuro.
É possível que não seja necessário ter um número de parâmetros completamente indeterminado. Você pode ter uma quantidade variável mas ter um limite máximo pequeno. E mais pode ser que cada parâmetros tenha um tipo diferente conhecido. Existem algumas alternativas nesses casos.
void M(int p1 = 1, string p2 = "", bool p3 = true, int p4 = 0) { ... }

Esta forma utiliza optional arguments. Então na chamada do método é possível usar apenas os parâmetros que não são iguais aos valores default. Ex.:
M(2); //na prática chama M(2, "", true, 0)

Além disso é possível usar a chamada através named arguments:
void M(p1: 1, p4: 0, p3: true)

Ainda há uma forma de passar parâmetros desta forma de forma explícita:
void M(Tuple<int, string, bool, int> p) { ... }

A chamada ficaria:
M(new Tuple<int, string, bool, int>(3, "teste", false, 1));

No C# também é possível:
M(new Tuple(3, "teste", false, 1));

Em algumas situações você pode não querer receber exatamente um array. Há propostas para usar um tipo enumerável, quase entrou no C# 6 e 7. Quem sabe no 8.
void M(params IEnumerable<int> p) { foreach(int i in p) Console.WriteLine(i); }

No C# 7 tem tuplas na linguagem o que pode facilitar mais ainda:
void M((int valor, string nome, bool status, int outro) p) { ... }

A chamada ficaria:
M((3, "teste", false, 1));

Coloquei no GitHub para referência futura.


Handling data on an android app

Question: I'm working on a school project and I'm having trouble coming to a conclusion on how to handle the data it involves.
Basically my app lets you create recipes (cooking) that are stored on the phone.
I don't really have any usable code just yet, so far the structure I thought of is as following:

A class Recipe that represents an individual recipe for manipulation via the app (has all the properties)
A class RecipeList that has a HashMap with all the Recipe objects in it that lets you get a certain recipe by an Id RecipeList.GetRecipe("id") and save Recipes via RecipeList.SaveRecipe(Recipe), it also handles saving to the SD card

The thing is though that eventually I want to outsource saving to a web space (using PHP) which is part of my project assignment, that's why I decided on using a HashMap so I could utilize an Id.
What's the best way to go about it given my current structure? Or is there a better structure for what I'm doing?
Answer: This will tell you everything you need to know.
Comment: That section can be a bit misleading. It's well known that content providers in tandem with a SQLite database is the best way to store large amounts of persistent data.
Comment: MySQL is a server based SQL database. SQLite is used for mobile devices. It's a much lighter-weight version of SQL, and it's stored on the device instead of a server. I think you need a bit of reading to do before getting started on this project :) This is a great place to start: http://www.wrox.com/WileyCDA/WroxTitle/Beginning-Android-4-Application-Development.productCd-1118199545.html
Comment: I read the "Decide if you need a content provider." section on it and none of those seemed to apply to my case.
Comment: To be honest I don't exactly know the difference between MySQL and SQLite but I have never used the latter, is there a possibility of using MySQL as well?

Handling data on an android app


How to implement single item DragDrop WPF Listview in MVVM way?

Question: I have two listviews (and Gridview inside that) inmy WPF/MVVM application. How would I implement Drag/Drop for single item in this case?
Any help would be appreciated. Thanks
Answer: I have made a sample application where you can have an idea about how it works with the MVVM i have ItemsControl ListView and another Listview Where you can drag and drop single item.
you can find it here a project named DragDropItems Credit Bea Stollnitz's
Comment: I am unable to get the source code. I dont know why it is so.
Comment: I have edited the link there you will find a project DragDropItems
Comment: this is the best code i found yet. No tons of interfaces etc , it does the work :)
Comment: @NividDholakia the link is dead :(
Comment: @NividDholakia It looks like your DragDrop code was taken from Bea Stollnitz's blog (http://www.zagstudio.com/blog/488#.VSeTIJONvMs), and there are no references at all in the source code.
You make it seem as though you have written the code yourself. Could you indicate where the code came from, please?
Comment: Why not just put the relevant code parts here directly ? Your answer would be way more useful that way.
Answer: Usually for DragDrop I use the code found at Bea Stollnitz's Blog. It's simple, easy to understand, and easy to modify as needed.
Comment: The linked page seems to have been moved to a new site - but the new site is also down. Here's an archived version of the blog post: https://web.archive.org/web/20151107025019/http://www.zagstudio.com/blog/488


How do i represent an image through CAML?

Question: How do i represent an image through CAML? I have a list and im trying to create a list instance by adding data through CAML
 <Data>
      <Rows>
        <Row>
          <Field Name="Title">Promotion 2</Field>
          <Field Name="Promotion Image">/SiteCollectionImages/PR.gif</Field>

        </Row>
      </Rows>
    </Data>

Answer: Have you tried:
<Field Name="Promotion Image"><![CDATA[[]]></Field>

Comment: Yea, I forgot the IMG element.
Answer: this did the trick:
<Field Name="Promotion Image"><![CDATA[]]></Field>

thanks Magnus
Comment: You should click the tick next to Magnus' answer. Gives him a bit of reputation and you may get a badge :D


Connecting hundreds of servers via the local network (LAN)

Question: I'm caching lots of data in memory to a local Redis server.  The server will need to connect to hundreds of other servers in the same data center (as they all need to access the same information hosted by the Redis server).
In order to minimize latency and maximize throughput I plan on connecting all of the servers to the Redis server with a 40 Gigabit Ethernet (40 Gbit/s).
I understand how to connect a couple of servers to one server, but how would I go about connecting hundreds of servers to a single server? I mean, I don't see enough ports to connect so many servers...
Is there a device that will allow me to connect all of these servers together?
Comment: As kindly as possible : please hire a sysadmin for whatever you're doing. Hire a good one. Spend a lot of money on them.
Comment: It's pretty strange to encounter a programmer who's never heard of an Ethernet switch, but [you're one of today's lucky 10000](https://xkcd.com/1053/)
Comment: Redis is apparently single-threaded. Can one thread push 40Gb of bandwidth? I really doubt it - you'll probably be slowed down by Redis. You could use more than one copy of Redis, but if you can use 5 copies of Redis on one server, you can also use one copy on 5 servers (that you already have) and save money by not buying the one big server just for Redis.
Comment: "Hundreds of servers in the data-center" - Is the data-center already setup? If yes, your server can just be connected to a switch in the existing network of the data-center. If not, then the question should be "How do I setup a data-center with 100s of servers".
Comment: You have tested this design on plain old 1Gb ethernet and you found that Ethernet bandwidth was a problem, right? Or you calculated it, at least?
Comment: Consider your redundancy setup too - one single redis server is a SPOF and if it is production-impacting then an outage will be bad.
Comment: Typically each rack has an Ethernet Switch, and each of these uplinks to a main Ethernet Switch.  https://www.cisco.com/c/en/us/products/switches/what-is-an-ethernet-switch.html#~q-a
Comment: So... machines fail. A lot. Have you thought what happens if your single cache server fails? Or needs to be taken down for maintenance? Perhaps some sort of Redis cluster would be a better fit?
Comment: If you truly don't understand or wasn't previously aware what a network switch does, I would recommend researching network hardware a lot more before investing on actual hardware. 40 Gbps connections are pretty expensive and you shoudn't get all that hardware just for fun. Even 2x10 Gbps in 802.3ad (LACP) configuration with redundant switches gets you plenty of bandwidth and the latency for each server often starts to be bigger bottleneck than the network bandwidth. And you don't lose the whole network when a single switch fails. When you have more than 3 servers, you should make it redundant.
Comment: Do you really need that bandwidth? You will have to create a star network just like with any other Ethernet setup. bond/trunk multiple ports for higher bandwidth and single link failure, consider multipath, as well as multiple synced redis instances.
Comment: If anyone is looking for a question that is getting an unjustified amount of positive attention, here it is.
Comment: If these are all the same o/s, and one o/s is compromised, then all the others will be too in very short order.
Answer:
I understand how to connect a couple of servers to one server but how
would I go about connecting hundreds of servers to a single server? I
mean, I don't see enough ports to connect so many servers.

Well... you would need to connect all of the servers to an appropriately sized network switch. They've been in use for decades. The first commercial multiport Ethernet network switch was introduced in 1989.
Answer:
I'm caching lots of data in memory to a local redis server. The server will need to connect to hundreds of other servers in the same data center (as they all need to access the same information hosted by the redis server).

The amount of data you store/cache is rather irrelevant. Relevant is the speed at which you need to transmit data to or from storage.

In order to minimize latency and maximize throughput I plan on connecting all of the servers to redis server with a 40 Gigabit Ethernet (40GbE).

For a large number of high-volume network ports you need a good infrastructure design. You not only require a huge bandwidth inside the redis server - network, storage and processing - but also the means to distribute that bandwidth.
Depending on the exact size, a large chassis switch (up to 800 ports or so) or a hierarchical tree is required. This paper from Cisco should provide a good starting point. A collapsed-core design is likely sufficient for your size.
Comment: "hundreds of servers" talking to a single-threaded Redis instance don't need a developer to buy a million dollar switch. They need to use that money to hire someone who has *heard* of a switch, and then buy a couple of 48-port unmanaged Gigabit switches.
Comment: @JacobKrall We don't know how well that Redis server scales or whether it is *single-threaded* - I was trying to point out the necessity to evaluate the *network, storage and processing* requirements.
Answer: Well, it depends on your needs.
You may ask your distributor where you want to buy that hardware. They want to help you to get that deal.
One example:
If the hundreds of servers have only gigabit you might use up to 10x HPE 2930M stacked with stacking modules and stacking cables. Then add a 40 Gbit/s module in at least two of them for redundancy and connect your server with both modules via DAC cables.
The 2930M has up to 48 ports, so 480 servers + the one 40G server. Depending in your needs select different switches.
If you don't need the flexibility, but more throughput you should go with a modular switch.
You can find help on several vendors sites, but here I give you HPE's solution for finding a switch if you want to do it all alone:
HPE Networking Switch Selector
Again: ask someone who sells that solution to you if he/she can help with the order. Otherwise, you might get in trouble when trying to put everything together and you notice that there are different power supplies, modules, cables that fit into different models. Some 2930Ms, for example, need more power than other 2930M models.
Comment: Asking a salesperson for a complex technical solution is a recipe for a disaster.
Comment: Asking anyone with a vested interest in upselling, whether that's a salesperson or the distributor's technical advisor, is still a recipe for disaster :-)
Comment: For that size of course not a salesperson. The Distributors i worked with had technicans/architects to help in cases like that


What is the difference between a census and a parameter in statistics?

Question: I'm going through my class textbook and the definition for a census is

When desired information is available for all objects in the population, we have what is called a census.

I remember from biostatistics that a parameter is essentially a characteristic of an entire population while a statistic is a characteristic about a sample. Are the terms parameter and census synonymous then? If not, what is the difference?
Comment: https://en.wikipedia.org/wiki/Statistical_parameter (see the first sentence). So, for example, a population mean, population standard deviation, population 90th percentile, population regression slope, etc. A census is a complete collection of some quantity (or quantities) of interest for all of the members of the population. If you have a census you could (at least in principle) compute a population parameter.
Answer: We generally call it as parameter when we don't have its true value and we would like to make a inference over it, we call census when we just evaluate some quantity over all population.
Comment: This is incorrect: the definition of parameter quoted in the question is the correct one and is fully general.  It does *not* depend on your state of mind or knowledge of it.  The problem with this question is that a parameter and a census are such completely different things that they cannot even be compared and contrasted.
Comment: what would be your answer
Comment: Look at any definition of these terms in an authoritative textbook.


python: opencv,some issue when count pixel

Question: I use opencv to count the number of white and black pixels of picture(I have convert them into black and white image), and everytime I run my code it return the number is 0,and the code is
output_path = "/content/drive/MyDrive/dataset_demo/result_pic"

for pic in os.listdir(output_path):
  if pic.endswith('.jpg'):
    image = cv2.imread(pic,cv2.IMREAD_UNCHANGED)
    number_of_white_pix = np.sum(image == 255)
    number_of_black_pix = np.sum(image == 0)
    number_of_total = number_of_white_pix + number_of_black_pix
    number_of_ratio = number_of_white_pix / number_of_black_pix
    print(number_of_total)

Comment: did you notice that `image is None`? debug your code before asking. -- [tour], [ask], [mre]
Answer: The pic variable contains only the file name of the image, but cv2.imread needs the full path to the image in order to read it. You need to use the full path to the image when you call cv2.imread.
output_path = "/content/drive/MyDrive/dataset_demo/result_pic"

for pic in os.listdir(output_path):
  if pic.endswith('.jpg'):
    pic = os.path.join(output_path, pic) #full path to the image
    image = cv2.imread(pic,cv2.IMREAD_UNCHANGED)
    number_of_white_pix = np.sum(image == 255)
    number_of_black_pix = np.sum(image == 0)
    number_of_total = number_of_white_pix + number_of_black_pix
    number_of_ratio = number_of_white_pix / number_of_black_pix
    print(number_of_total)

Comment: thanks! It seems that I am reading a path not a image, and it worked now! Thanks again!
Comment: well it doesn't need the full (absolute) path, relative would work too. it needs a **correct path.** `os.path.join` is definitely the right thing to use here.
Comment: yes, my mistake is I read the path instead of an image, os.path.join certainly will work! Thanks too!


Number of stationary areas for polynomial of many variables

Question: Suppose we have a polynomial $f$ of $k$ variables of degree $n$. $\mathcal S$ is a set of stationary points, on which equation $\nabla f=0$ holds. What is the maximum number of connected components of $\mathcal S$.
For example, for ($k=2$, $n=2$):
$$
f(x,y)=x^2
$$
$\mathcal S$ has one connected component.
Comment: It would be better if you made a certain example.
Comment: Could be infinitely many if $k \ge 2$ and $n \ge 2$, e.g. $f(x,y) = x^2$.
Comment: What I really meant is how many distinct areas are there with zero gradient. In example $f(x,y)=x^2$ there is one area with zero gradient.
Answer: Let be $p$ a one variable polynomial with $r$ zeros (for example...). Consider the polynomial
$$f(x,y) = \int p(x)\,dx.$$
How many connected components has your $S$?


Advantages of a dedicated audio interface device over microphone jack on desktop

Question: I have been doing some recordings from an OP-1 synth using the line out on the OP-1 connected to the microphone jack on my desktop and then using audacity to record while playing to my headphones. I was told this is a very amateur setup and I should use a dedicated audio interface so I borrowed a friends Scarlet 2i2 and tried recording with that and I really can't tell the difference between them. The only possible advantage I see is the 2i2 lets me record 2 inputs at once but other than that I can't see any reason the dedicated device is better.
What are the advantages to these devices that I am missing? Is there a good reason to buy one over just using the microphone jack?
Comment: Btw, you can transfer individual tracks as audio files to your computer over USB. Of course you lose any master effects you put over the whole mix, and you can't transfer a live performance. But it's the cleanest way to get audio from the OP-1 to you DAW.
Comment: @YourUncleBob Yeah thats what I usually do but I record the line out when I am recording video as well.
Comment: Then that would make an excellent test. Transfer some tracks via USB and also record them through your desktop's audio input, then check whether you can hear much difference. If you don't, then I guess it's good enough (for now).
Answer:
I was told this is a very amateur setup

It's probably not very useful to think of equipment in terms of how 'amateur' or 'pro' it is. As your question alludes to, it's better to think about what is a match for your requirements.
Some advantages of external interfaces may be:

Drivers (such as ASIO drivers) that allow lower latency. This is useful if you're playing a virtual instrument on your computer, or using virtual effects. ASIO drivers also allow the computer to compensate for the overall amount of latency, so that what you record stays in-sync with previously-laid tracks you were listening to.
Possibly less noise and distortion (although some computers have inputs that are ok for line-level sources)
related to the above, higher sample rates and bit depths (though these are only of benefit in certain situations)
better interfacing capability (balanced inputs, more gain, high-impedance inputs).
multiple inputs and outputs

Is there a good reason to buy one over just using the microphone jack?

Well, for you, it doesn't sound like there is - at least until you need more tracks, low-latency thru monitoring, or are recording from other sources (like microphones).
Answer: The mic jack on a computer is designed to take the sort of head-set microphone used for e.g. Skype calls.  It won't work very well with the sort of better-quality microphone we'd normally choose for recording vocals.
But modern electronics are very forgiving.  If you can deliver the sort of level from your synth that won't overload the mic input (and remember, overload occurs BEFORE the input is digitised and can be affected by any controls in software) and the result sounds good, maybe a 'proper' audio interface won't make much difference.    It's even possible that the computer's 'Mic' input will auto-detect the synth's signal and switch to being a 'Line In'.  Anyway, if you're getting an acceptable result, don't argue!
But, I repeat, I don't think you'll be so lucky if and when you want to add input from a microphone to your recording projects.
Answer: I like the requirements comment above. If you're a "bedroom musician" like me, most of your music composition is just done on a laptop or desktop. I think the advantage of a dedicated audio interface is more apparent if you are singing or playing analog instruments that need more sophisticated microphones. I use the exact same scarlett interface, but use it with an MXL studio microphone for my singing tracks or if I'm live recording acoustic guitar. I'll record a whole tune, all of the instrumental tracks. Then drop those tracks to one mp3 file as a reference and save it on my phone. Then with headphones connected to my phone, I'll listen to the track and sing my vocal parts or play guitar via the USB Scarlett interface into Audacity on my laptop. The interface offers better headroom, less distortion, more gain, better dynamics, and of course that 48Volt phantom power for cartioid mikes.
Then I'll drop the Audacity audio track to a WAV file and import it as a new track into my DAW software (Propellerhead Reason version 10). Ultimately my laptop CPU can manage 15-20 tracks of midi note lanes, audio tracks, and some VST's.


GKE: Google Compute Engine: Required 'compute.networks.get' but permissions are there?

Question: When attempting to create a GKE cluster via gcloud, web console, or pulumi I'm receiving the error: Google Compute Engine: Required 'compute.networks.get.
The permission for this account have Owner, Editor, and Compute Admin. Testing for compute.networks.get using the troubleshooter also shows that it is good.
Not sure why this is happening. It seemed to have been working fine the day before.
Thanks in advance.
Edit:
I can also run gcloud compute regions describe us-east1 --project=myproj as well as the list command without issue so something is not adding up.
Edit 2:
Full error is:
googleapi: Error 403: Retry budget exhausted (5 attempts): Google Compute Engine: Required 'compute.regions.get' permission for 'projects/myproj/regions/us-central1'., forbidden
Answer: It seems that the issue is with shared VPC. You need to allow the service accounts in the service project to use the sub-network with a binding resource. To do this:
Enable the permissions in the service account(s) to include 'roles/compute.networkUser' . This provides access to a shared VPC network.
I've found a similar issue on the terraform GitHub, and this is the workaround a user proposed.
Also you can disabling and then re-enabling both Compute API and Kubernetes API
You could also check the following documentation: Enabling the Google Kubernetes Engine API in your projects
Additionally at this moment Google Kubernetes Engine is reporting issues: Incident began at 2021-02-19 05:47 (all times are US/Pacific).
You can track the current status  on https://status.cloud.google.com/ and for this particular error you could check https://status.cloud.google.com/incident/container-engine/21004

Description: We are experiencing an intermittent issue with Google Kubernetes Engine creation.
Our engineering team continues to investigate the issue.
We will provide an update by Friday, 2021-02-19 10:30 US/Pacific with current details.
Comment: > Also you can disabling and then re-enabling both Compute API and Kubernetes API You could also check the following documentation: Enabling the Google Kubernetes Engine API in your projects

This worked! Looks like a service account was deleted.


Defining the wagon wheel

Question: The wagon wheel in cricket is that... spokes they put out, and define scoring areas. The areas are:

Behind square Offside
Behind square Legside
In front of square Offside
In front of square Legside
Straight Offside
Straight Legside

My question comes in the line which splits straight and in front of square. Is it 45 degrees? or is it trying to make each scoring area is equal (assuming the pitch is in the middle) in terms of area and the field is symmetric (which it can't really be since the behind square is smaller than the others).
I don't know if it's been defined anywhere, and as much as I would like equal sized scoring areas, having 45 degrees is just so much simpler. I also tried to do 45 degree from the middle of the pitch, creating a strange weird scoring polygon.

I did 2 scenarios here, one with 45 degrees on the legside (for right hander) and on the right is a slightly different idea if no official definition exists. PS: I'm not super good with geogebra so I just estimated the sizes, but they should be fairly accurate.
Comment: I'm struggling to see an actual question here. What _specifically_ would you like answered? (that fits in the Stack Exchange format and isn't opinion-based)
Comment: I wanted to know if there are a official definition for the lines. Meaning the square of the wicket lines are defined by the wicket (or perhaps the crease?), and the off/legside are defined by the middle stump.  I want a definition for "exactly" the divider line.  But 45 degrees is probably the cleanest.
Answer: As a general rule, the lines are drawn around (likely exactly on) 45 degree angles, but the reasoning behind this is most likely due to the way shots are played through those two regions.
"Front-foot" shots (such as on- and off-drives, cover drives, or drives through mid-wicket) are played on the front foot (stepping forward into the shot) and generally are played through the forward two sectors. Conversely, "back-foot" shots (such as the cut, pull and hook shot), are played by stepping back towards the wicket-keeper, and normally direct the ball square.
This is clearly not an ideal breakdown of stroke-play, as it doesn't account for miss-hits, edges, late drives or other "unconventional" shots, but it is sufficient, over a long enough innings, to show how a particular batsmen or team has played.

Defining the wagon wheel


Commerce - Require login only for specific products

Question: I'm building a commerce site using drupal commerce. I know how to have anonymous users checkout, I know how to require login before checkout, but I can't figure out how to specify for each product if it requires a login or not...
Answer: You could use Rules to enforce login when the product is added to the cart.
e.g

Event: Before/After adding product to cart
Conditions: if user is not logged in (i.e. uid=0) and product match (e.g SKU matches)
Action: Redirect to user/login?destination=cart

Something like that could suffice.
Answer: You could add some special field to flag this. After you can use rules to force some users to log in.