Listing Table Name from Object_ID in Query

Question: I found this script that will analyze fragmentation for a database using the system function sys.dm_db_index_physical_stats and give me the objectID, IndexID, and % Fragmentation of a given database, but I'd like to know the table name and index name instead of the ID.
The script was found here: Defragmenting Indexes in SQL Server 2005 & 2008
And the query itself is:
SELECT
object_id AS ObjectID,
index_id AS IndexID,
avg_fragmentation_in_percent AS PercentFragment,
fragment_count AS TotalFrags,
avg_fragment_size_in_pages AS PagesPerFrag,
page_count AS NumPages
FROM
sys.dm_db_index_physical_stats(DB_ID('Hemasphere_Train'),NULL, NULL, NULL ,'DETAILED')
WHERE
avg_fragmentation_in_percent > 0
ORDER BY
ObjectID, IndexID

Would it be possible to get the table name & index name instead of the ID? And if so, what should I select instead?
Answer: For the table, use the object_name function.
For the index, join to sys.indexes.
SELECT
ips.object_id AS ObjectID,
object_name(ips.object_id) as table_name,
ips.index_id AS IndexID,
i.name as index_name,
avg_fragmentation_in_percent AS PercentFragment,
fragment_count AS TotalFrags,
avg_fragment_size_in_pages AS PagesPerFrag,
page_count AS NumPages
FROM
sys.dm_db_index_physical_stats(DB_ID('Hemasphere_Train'),NULL, NULL, NULL ,'DETAILED') ips
    inner join sys.indexes i
        on ips.index_id = i.index_id
            and ips.object_id = i.object_id
WHERE
avg_fragmentation_in_percent > 0
ORDER BY
ObjectID, IndexID

Comment: When I do that, the table_name and Index_name are all returned as 'NULL'.
Comment: @MISNole Are you running this query from within the `Hemasphere_Train` database?
Comment: No, from master. When I try to run it from the `Hemasphere_Train` database, it throws the error: Incorrect syntax near 'Hemasphere_Train' on the line `sys.dm_db_index_physical_stats(DB_ID('Hemasphere_Train'),NULL, NULL, NULL ,'DETAILED')`


a Catalan-type problem

Question: It is known that for every $n$ the equation $a^b-c^d=n$ has finite number of solutions (assuming that exponents are not 1's), but the proof requires a lot of hihger mathematics.
Is there an elementary proof that the particular case: $a^b-b^a=n$ has finite number of solutions?
Comment: Assuming $n\neq0$?
Comment: $n$ is a positive integer
Comment: Do you have a reference for your first claim?
Answer:
It is known that for every $n$ the equation $a^b-c^d=n$ has finite number of solutions  $($assuming that exponents are not $1$'s$)$

No, it isn't. Otherwise, it wouldn't be called a "conjecture". :-$)$

The proof requires a lot of higher mathematics.

Yes. Of course it does. And the reason that we know that is because, if it wouldn't, then it'd already be proven. :-$)$

Is there an elementary proof that the particular case: $a^b-b^a=n$ has finite number of solutions?

Take a wild guess$\ldots~$ :-$)$

a Catalan-type problem


How to "blend/merge" two images usingi an objective-c library?

Question: I'm wondering if there is some image manipulation library that will allow me to take two images and blend them together. Or blend together parts of images in a mosaic so that it doesn't look like its a mosaic, but is one whole image.
I've looked on google code and searched for such a library, but couldn't find anything.
Thanks!
Answer: Alpha blending is directly supported by the Quartz graphics engine, so you don't need any additional libraries. You just draw one image, then draw the second image with an alpha of less than 1.0 on top of it. Read the UIImage and Core Graphics documentation for details.


OpenCV cvDrawContours vs drawContours

Question: I am new to using OpenCV on Visual Studio, and I have recently reinstalled my VS2012 to get it to work using OpenCV 2.4.2.
I am trying to calculate the area of region specified by mouse-clicking the vertices and pushing them to CvSeq*, to use with contourArea() function.
I am currently trying to parse in an empty CvSeq* as the last parameter of my custom mouse callback function so that I can add the CvPoint formed of x and y coordinates. However, whenever I try to access the CvSeq* contour afterwards, I get an error. So in the following snippet of the code:
void CallBackFunc(int event, int x, int y, int flags, void* userdata)
{

    CvSeq* contour = (CvSeq*)userdata;
    CvPoint cur;
     if  ( event == EVENT_LBUTTONDOWN )
     {
          cout << "Left button of the mouse is clicked - position (" << x << ", " << y << ") saved as point" << endl;
          // save x,y as a contour point
          cur = cvPoint(x,y);
          cvSeqPush(contour, &cur);
...

I get the correct cout messages, but get an error like this when trying to draw contour using that CvSeq* :
Unhandled exception at at 0x75E3812F in opencvtest.exe: Microsoft C++ exception: cv::Exception at memory location 0x001FF990.
What is the problem here? Would I be better off trying to use Vector> instead of CvSeq?
Comment: Just curious, if you're just starting with OpenCV why not start with the latest version (2.4.9) instead of a very old version (2.4.2)?
Comment: had some installation issues and went back to a version where there was a documented installation guide online
Answer:
cvDrawContours() is from the old, deprecated c-api, you should not use it, or any of those old cv* functions.
drawContours is from the current c++ api, use it with cv::Mat, functions from the cv:: namespace.

also, stop worrying about CvSeq* or IplImage*. if you see any code that contains arcane stuff like that, - move on.
"Would I be better off trying to use vector<vector<Point>> instead of CvSeq?" - yes.

also, when in doubt, have a look at the samples and the docs
Comment: Thanks a lot @berak !!
If my Visual Studio auto complete seems to be showing cvDrawContours() and not the drawContours(), does that mean there is something wrong with my settings?
Comment: that probably means, that you included the c-api headers instead of the c++ ones. please include "opencv2/core/core.hpp", "opencv2/highgui/highgui.hpp", etc.
Comment: Hmm strange... I just checked, and those are the exact ones I have included... is this a version issue perhaps? I'm on OpenCV2.4.2, having reverted back from the most recent version to try to get it to work
Comment: ok, "opencv2/imgproc/imgproc.hpp" to be exact. and make sure, you did not include older headers, like cv.h *before*
Comment: Ah works now, thanks a lot! Is there an easy way to search for which functions are included in which header files?
Comment: in vs that should be: right click on it, -> go to definition
Comment: Oh I meant if there was a website where I can check which of the OpenCV library functions are included in which header files so I can include the correct ones..? My googling ability failed me with drawContours(), as you could probably tell...

OpenCV cvDrawContours vs drawContours


Nested for loop in Python to get equivalent result

Question: I have two for loops to get the result as below.
First loop:
 for row1 in value1:
     print(row1)

The result is:

    A
    B
    C

Second loop:
 for row2 in value2:
     print(row2)

The result is:

    A
    B
    C

The result is expected as below using both the loops:
A A
B B
C C

I have tried using nested loops:
for row1 in value1:
    for row2 in value2:
       print(row1, row2)

The result is coming in as Cartesian values:
A A
A B
A C
B A
B B
B C
C A
C B
C V

What can I try next?
Comment: are the lengths of value1 and value2 same?
Comment: Yes it is always same
Answer: value1=['A','B','C']
value2=['A','B','C']

for x,y in enumerate(value1):
    print(value2[x],y)

A A
B B
C C

Or
for x,y in zip(value1,value2):
    print(x,y)

A A
B B
C C


Probability 6 people 2 tickets

Question: I've been debating the answer to this problem for a while:
Mr. Starnes and his wife have 6 grandchildren: Connor, Declan, Lucas, Piper, Sedona, and Zayne.  They have 2 extra tickets to a holiday show, and will randomly select which 2 grandkids get to see the show with them.
a) What probability does each grandchild have of getting selected to see the show?
b)Find the probability that at least one of the two girls (Piper and Sedona) get to go to the show.
My confusion is due to the fact that there are two tickets.  Does this allow the sum of the probabilities for each grandkid (1/3) to equal 2 rather than 1?
Any explanations would be greatly appreciated.
Answer: My answer to B is different than Yohanes. I used permutation.
A) Lets say that we are computing the probability that Connor is selected. This probability equals to 1- P(Connor is not selected) = 1 - 5*4/(6*5) = 1/3
B) Probability of selecting at least one girl equals to 1- P(selecting all boys) = 1 - 4*3/(6*5) = 3/5
Comment: My confusion is due to the fact that there are two tickets. Does this allow the sum of the probabilities for each grandkid (1/3) to equal 2 instead of 1?
Comment: The probability of distinct outcomes of an experiment sums up to 1. In this case, our experiment is giving tickets to 2 people out of 6. Lets write distinct outcomes:

Connor, Declan;
Connor, Lucas;
Connor, Piper;
...

The probability of each outcome is 1/15. We have 15 distinct outcomes so it sums up to one. However, selecting Connor or selecting Declan is not a distinct outcome of the experiment. You can select Connor and Declan at the same time. Therefore, it does not sum up to 1. It is more than 1 because it also includes the intersection. Does it make more sense?

Probability 6 people 2 tickets


Laplace transform of $(3e)^t\sin^2 t$

Question: The existence of Laplace Transform of $(3e)^t\sin^2 t$ exists but can you help me in finding the Laplace transform of this function?
Answer: HINT
Observe that

$3e=e^{\log 3+1}$, and then $(3e)^t=e^{at}$ with $a=\log 3+1$;
$\sin^2(t)=\frac{1}{2}\big[1-\cos (2t)\big]$

Laplace transform of $(3e)^t\sin^2 t$


Checkbox for Views Filter

Question: I have a view and used Better Exposed Filter module to show this Checkbox to filter the content in the view. The picture may explain the situation properly

In above filter by criteria, those values are Taxonomy Terms, which will increase later.
However my problem is, I want to have a Checkbox only for Development Taxonomy. So, instead of Filter by and list of Taxonomies, it would only be Filter by Development with a checkbox near to it. When the checkbox is checked it'd show the view which is Listed Under only Development
I tried something like CSS or jQuery show only this taxonomy class and hide other taxonomy terms, but that's last resort.
Any Drupal way I can accomplish this without writing codes?
Comment: @squarecandy No it doesn't seem to be a duplicate of that question.
Comment: possible duplicate of [Drupal Better Exposed filter](http://drupal.stackexchange.com/questions/82847/drupal-better-exposed-filter)
Answer: In your filter settings there is an option "Limit to the selected items".
Check that and select "Development" from the select field of options and it should do what you are trying to achieve.
Then change the label of your filter as required.
See the attached image:

The view itself looks like (note I changed the filter to be cat, not car as in the previous image, because I already had content tagged with cat):
Comment: The example screenshot I included was from me doing it with a taxonomy field.
Comment: Thanks for the reply. I could accomplish this easily with new `Field` as `Text or list`, but it is quite challenging to do with `Taxonomy`. I might be referring to something else using `Taxonomy` as when I check the box, no any result shows. But same filter with new `text field` works perfectly.
Comment: I had to give up the idea of using `Taxonomy` here, as taxonomy is mere term reference which doesn't technically lie in my content type.
Comment: But are you using `BEF Module` with this? If so, then It'd be great to see your filtered screenshot
Comment: Yep, I already had BEF installed on my play site for something else. Image attached in the answer.
Comment: I got it working. The problem was in `Taxonomy` filter criteria there was extra settings which had `select list` and `autocomplete`. While selecting `autocomplete` it showed to me `some illegal things, contact site admin` something like that. But when I changed it to `select list` its working. I can't understand the issue, but glad its working anyhow. Thanks !!!

Checkbox for Views Filter


Como verificar caso um select é nulo

Question: Gente, possuo este código que puxa info do server
try {
    $conecta  = new PDO("mysql:host=$servidor;dbname=$banco", $usuario, $senha);
    $consulta = $conecta->prepare('SELECT * FROM tb02_cardapiosem WHERE tb02_diasemana=' . $data);
    $consulta->execute(array());
    $resultadoDaConsulta = $consulta->fetchAll();

    $StringJson = "[";

    if (count($resultadoDaConsulta)) {
        foreach ($resultadoDaConsulta as $registro) {

            if ($StringJson != "[") {
                $StringJson .= ",";
            }
            $StringJson .= '{"tb02_lanchedia":"' . $registro[tb02_lanchedia] . '",';
            $StringJson .= '"tb02_almoco":"' . $registro[tb02_almoco] . '",';
            $StringJson .= '"tb02_cafe":"' . $registro[tb02_cafe] . '",';
            $StringJson .= '"tb02_lanchenoite":"' . $registro[tb02_lanchenoite] . '",';
            $StringJson .= '"tb02_diasemana":"' . $registro[tb02_diasemana] . '"}';

        }
        echo $StringJson . "]"; // Exibe o vettor JSON
    }
}
catch (PDOException $e) {
    echo 'ERROR: ' . $e->getMessage(); // opcional, apenas para teste
}

Depois, tenho este código que joga as informações encontradas numa div
function ConectaServidor(response) {
    var dados = JSON.parse(response); //faz a conversão do texto da WEB para JSON
    var i;
    var conteudo = "";
    var conteudo2 = "";
    var conteudo3 = "";
    var conteudo4 = "";
    for (i = 0; i < dados.length; i++) //dados.length retorna o tamanho do vetor.
    {
        conteudo += dados[i].tb02_cafe;
        conteudo2 += dados[i].tb02_lanchedia;
        conteudo3 += dados[i].tb02_almoco;
        conteudo4 += dados[i].tb02_lanchenoite;
    }

    document.getElementById("cafe1").innerHTML = conteudo;
    document.getElementById("lanche1").innerHTML = conteudo2;
    document.getElementById("almoco1").innerHTML = conteudo3;
    document.getElementById("lanchen1").innerHTML = conteudo4;
}

Porém não são todas as datas que estão cadastradas e gostaria que quando uma data não fosse encontrada, ele colocasse o innerHTML das Div's como "Não há registro!". Como fazer?
Comment: Pergunta: Por quê não utiliza a função [`json_encode`](http://php.net/manual/pt_BR/function.json-encode.php) para converter seu *array* para JSON?
Answer: Bom dia!
Primeiramente, te sugiro a utilizar alguma biblioteca Javascript como Jquery, por exemplo. Acredito que realmente vá facilitar teu trabalho no front-end e a maneira como tu vai tratar os dados.
O segundo ponto que na minha opinião que deve ser melhorado é a maneira como tu estás tratando os dados no back-end. Seria muito mais simples e correto tu retornar o resultado da tua consulta SQL e transformá-la para um formato json de verdade (não montando uma String), usando a função json_encode() que é nativa do PHP.
Respondendo a tua pergunta, vamos lá. No front-end, quando tu recebe os dados e manipula eles me parece um pouco confuso pois os lanches/cafés estão sendos todos concatenados em uma única variável que depois será exibida em um elemento HTML. Acredito que cada um destes valores deveriam ser atribuidos a uma lista, por exemplo, faria mais sentido. Deste modo, a única coisa que tu deveria realizar para atribuir o conteúdo desejado para as datas que não possuem valor seria algo do gênero:
conteudoX = (dados[i].tb02_dia_semana) ? dados[i].tb02_dia_semana: 'Data não informada';

Após a execução deste condicional a tua variável conteudoX possuirá o valor esperado e desta maneira tu poderás atribuir ao elemento que tu quiseres no HTML.
Espero ter ajudado :)
Abraços!
Answer: Você pode usar a própria query SQL para retornar "Não há registro!" como valor de um campo, caso ele seja nulo na tb02, usando coalesce(). Essa função retorna o primeiro valor não-nulo encontrado na lista:
SELECT
    tb02_diasemana,
    coalesce(tb02_lanchedia,   'Não há registro!') as tb02_lanchedia,
    coalesce(tb02_almoco,      'Não há registro!') as tb02_almoco,
    coalesce(tb02_cafe,        'Não há registro!') as tb02_cafe,
    coalesce(tb02_lanchenoite, 'Não há registro!') as tb02_lanchenoite
FROM tb02_cardapiosem
WHERE tb02_diasemana=' . $data

A vantagem é que o resto do seu código não muda. De quebra evita o uso de select *, que pode te causar dores de cabeça no futuro caso sejam adicionadas colunas novas na tabela.
Answer: Gente, resolvi com um simples else. Vejam e comparem com o código anterior:
    try {
$conecta  = new PDO("mysql:host=$servidor;dbname=$banco", $usuario, $senha);
$consulta = $conecta->prepare('SELECT * FROM tb02_cardapiosem WHERE tb02_diasemana=' . $data);
$consulta->execute(array());
$resultadoDaConsulta = $consulta->fetchAll();

$StringJson = "[";

if (count($resultadoDaConsulta)) {
    foreach ($resultadoDaConsulta as $registro) {

        if ($StringJson != "[") {
            $StringJson .= ",";
        }
        $StringJson .= '{"tb02_lanchedia":"' . $registro[tb02_lanchedia] . '",';
        $StringJson .= '"tb02_almoco":"' . $registro[tb02_almoco] . '",';
        $StringJson .= '"tb02_cafe":"' . $registro[tb02_cafe] . '",';
        $StringJson .= '"tb02_lanchenoite":"' . $registro[tb02_lanchenoite] . '",';
        $StringJson .= '"tb02_diasemana":"' . $registro[tb02_diasemana] . '"}';

    }
    echo $StringJson . "]"; // Exibe o vettor JSON
}else{
        echo $StringJson = '["Não há dados!"]';
    }
}
   catch (PDOException $e) {
       echo 'ERROR: ' . $e->getMessage(); // opcional, apenas para teste
     }

Aí no meu javascript:
    function ConectaServidor(response) {
    var dados = JSON.parse(response);
    if(dados=="Não há dados!"){
        document.getElementById("cafe1").innerHTML = dados;
        document.getElementById("lanche1").innerHTML = dados;
        document.getElementById("almoco1").innerHTML = dados;
        document.getElementById("lanchen1").innerHTML = dados;
    }else{
    var i;
    var conteudo = "";
    var conteudo2 = "";
    var conteudo3 = "";
    var conteudo4 = "";
    for (i = 0; i < dados.length; i++) //dados.length retorna o tamanho do vetor.
    {
        conteudo += dados[i].tb02_cafe;
        conteudo2 += dados[i].tb02_lanchedia;
        conteudo3 += dados[i].tb02_almoco;
        conteudo4 += dados[i].tb02_lanchenoite;
    }

    document.getElementById("cafe1").innerHTML = conteudo;
    document.getElementById("lanche1").innerHTML = conteudo2;
    document.getElementById("almoco1").innerHTML = conteudo3;
    document.getElementById("lanchen1").innerHTML = conteudo4;
    }}}

De qualquer forma, obrigado à todos! ;)
Comment: pode crer, eu tinha entendido que podia não haver dados pra uma das refeições, não me liguei que você estava falando da data inteira, hehe

Como verificar caso um select é nulo


Resolução de tela (DPI) css

Question: Pretendo fazer um layout de um livro, e existem milhares de informações. Eu consigo buscá-las em uma página e adicioná-las no BD. Posteriormente iria puxá-las, fazer alguns cálculos, e retorná-las em milhares de tópicos na tela.
Nessa tela, haveria um botão de gerar um PDF em 300 dpi.
1º - Assim, gostaria de saber, se no CSS temos a possibilidade de setar a resolução do site, como é feito em imagens, em 300 pixels por polegada.
2º - É possível criar com css páginas em tamanho A5. Ao clicar em imprimir, o navegador entenda que corresponde a uma folha A5 (21 x 15 cm)
Comment: Acho que pode ser possível usando transform:scale() na proporção de 300/72 = 4.16, logo transform:scale(-4.16), deveria ter na tela algo de 300dpi, mas no tamanho de 72dpi. Só que eu acho isso "besteira" pq a impressora sempre imprime os textos na resolução máxima, pois o texto não deixa de ser um vetor, por isso existe tantas Icon Fonts por ai tipo a FontAwesome ou Material Icon! Fonte é vetor, e veto não precisa preocupa com resolução. A não ser que vc transforme o texto e imagem pra depois imprimir, o que não faria sentido algum...
Comment: Rapaz dei uma atualizada sobre a primeira parta da sua pergunta, acho que vai te ajudar a definir qual imagem usar na impressão!
Comment: Meu caro, encontrei isso que ajuda a entender a resolução atual da tela: https://developer.mozilla.org/en-US/docs/Web/CSS/@media/resolution , tentei usar ZOOM, mas não da certo. Eu poderia criar um (elemento) com 15 x 21 cm, mas converteria em 300 ppi, pois minha tela é de 96ppi, ou seja, ficaria enorme, e depois com zoom, eu ajustaria a minha tela para os 96ppi, mas na hora da impressão eu manteria os 300 ppi ... Mas pelo que vejo não é possível...
Answer:
1º - Assim, gostaria de saber, se no CSS temos a possibilidade de
  setar a resolução do site, como é feito em imagens, em 300 pixels por
  polegada.

Sobre a primeira parte da pergunta não sei te responder com precisão, mas acho que isso tem mais a ver com a API que vai gerar o PDF do que com a tela em si. Principalmente pq estamos falando de texto e não necessariamente de imagem...
Sobre as imagens inicialmente eu pensei no srcset, mas para isso ele não vai servir, pois ele determina a "qualidade" da imagem dependo ta largura da tela ou da densidade de pixel da tela, não da impressão. Isso significa que ele determina a imagem no @media screen e não no @media print.
Então para ajustar a resolução da sua imagem para impressão vc tem duas opções. A primeira que é a mais fácil e acredito que é mais crossbrowser e que vai te dar menos problemas é ter 2 imagens. Uma em baixa resolução que só aparece na tela no @media screen, e outra img de alta resolução que só aparece no @media print
Usando a propriedade image-resolution: 300dpi;
Veja que:
Fonte oficial W3C: https://www.w3.org/TR/css3-images/#image-resolution

Impressoras tendem a ter resolução substancialmente maior do que monitores de computador; devido a isso, uma imagem que parece bem na tela pode parecer pixelada quando impressa. A propriedade image-resolution pode ser usada para incorporar uma imagem de alta resolução no documento e manter um tamanho apropriado, garantindo a exibição atraente na tela e no papel:

img.high-res {
    image-resolution: 300dpi;
}

Logo teremos algo tipo isso: OBS: Repare que temos duas tags de IMG abaixo, mas só uma delas aparece, que é a imagem com a classe .screen, já na impressão só a imagem classe .print vai aparecer, a outra some!

.print {
    image-resolution: 300dpi;
}
@media only screen {
  .print {
    display: none;
  }
}
@media only print {
  .screen {
    display: none;
  }
}

DICA: A W3C tem em sua documentação a opção de usar valores em DPI para tratar imagens dentro de um media query, por exemplo
@media print and (min-resolution: 300dpi) { … }

Fonte: https://www.w3.org/TR/css3-mediaqueries/#resolution
Mas tenha em mente que as configurações de impressão são feitas pelo usuário, tipo se a impressão vai ser Colorida ou não, ou se vai ser em modo econômico ou não. Sendo assim é difícil saber se essa regra de resolução vai funcionar caso o usuário tenha mudado as configurações da impressora...

Já sobre isso:

2º - É possível criar com css páginas em tamanho A5. Ao clicar em
  imprimir, o navegador entenda que corresponde a uma folha A5 (21 x 15
  cm)

Vc pode usar a at-rule @page e definir o tamanho da página:
@page {
  size: A5;
}

Ou
@page {
  size: 15cm 21cm;
}

Para controlar as margens vc pode fazer assim
@page :left {
  margin-left: 4cm;
  margin-right: 3cm;
}

@page :right {
  margin-left: 3cm;
  margin-right: 4cm;
}

DICA: Vc também pode controlar a orientação da página em vertical e horizontal (landscape / portrair): https://www.w3.org/TR/css3-page/#page-size
@page {
    size: A5 landscape;
}

Essa reposta pote te interessar tb: Diminuir tabelas para caber em uma página

Documentação oficial W3C: https://www.w3.org/TR/css3-page/#at-page-rule
Artigo sobre impressão com CSS da Smash Magazine que pode te interessar: https://www.smashingmagazine.com/2015/01/designing-for-print-with-css/
Comment: @abcd Para imagens na tela, que é usado quando a tela é retina, vc pode fazer assim: https://css-tricks.com/snippets/css/retina-display-media-query/ mas isso é para display na tela, para controlar na impressão vc teria que ter uma imagem em baixa para tela, mas no @ media print {} vc coloca uma imagem com 300dpi, tem que ver como criar essa regra e fazer um teste de impressão pra ver se da qualidade mesmo!
Comment: @abcd sobre o image-resolution vou dar uma pesquisada, se eu conseguir algo novo vou editar a resposta ;)
Comment: Essa da impressão não conhecia, ótima dica. Encontrei algo, mas poucas informações: image-resolution: 300dpi;

Resolução de tela (DPI) css


C# naming convention for extension methods for interface

Question: I typically name my C# interfaces as IThing.  I'm creating an extension method class for IThing, but I don't know what to name it.  On one hand, calling it ThingExtensions seems to imply it is an extension class to some Thing class instead of to the IThing interface.  It also makes the extension class be sorted away from the interface it extends, when viewing files alphabetically.  On the other hand, naming it IThingExtensions makes it look like it is an interface itself, instead of an extension class for an interface.  What would you suggest?
Edit:  there is not a Thing class that implements IThing, in response to some of the comments.
Comment: Should be migrated to [Programmers](http://programmers.stackexchange.com), because it doesn't deal with a coding problem, but rather pertains to development practice (how to name extension methods).
Comment: Came here looking for a clear winning answer and was actually not surprised not to find one...  I was forced to upvote both your question and **both** Reed's and Jared's answers!
Answer: I definitely prefer the name ThingExtensions over IThingExtensions.  The reason being that to most programmers an I prefix on a type implies that it is an interface.  This is both a very common pattern and part of the .Net Design Guidelines.
Adding an I prefix for the extension method case breaks both assumptions and established guidelines.
There is also precedence for this in the Base Class Library.  The majority of the extension methods available for IEnumerable are contained in the type Enumerable.
Comment: I'm imagining that there's a class called `Thing` that implements `IThing`, therefore it would be confusing if it was called `ThingExtensions` but worked on `IThing`'s. But, @Sarah Vessels does not specify this...
Comment: I would think the "Extensions" suffix kind of removes this ambiguity?
Comment: @klausbyskov:  there actually isn't a `Thing` class that implements `IThing`.  I'll update my question.
Comment: We can't "reserve" objects that begin with "I" strictly for interfaces.  Example: class Integrations, class Interrupts, class InsufficientMemoryException ...
Answer: I, personally, would use IThingExtensions.
From a usability standpoint, the end user never sees this class - they only include it's namespace.  If the namespace is the same as IThing, then it doesn't matter - they'll already have it.
That being said, I think that the fact these are extensions for any IThing makes IThingExtensions the most clear.  If you have a Thing class, calling this ThingExtensions may seem ambiguous (are you extending the interface or the implementation itself?).
That being said, the framework uses a very different approach.  The framework's approach is to use a class named Thing to extend IThing.  For examples, see Enumerable (extending IEnumerable) and Queryable (extending IQueryable).  This would also be a very good option.
Comment: I still don't like this approach because it violates the design guidelines for type naming.  In particular only prefix type names with an I if it's actually an interface.  http://msdn.microsoft.com/en-us/library/ms229040.aspx
Comment: @JaredPar: Yes, but unfortunately, the design guidelines don't really have any guidance for naming Extension method classes - they really just talk about when to use them (ie: http://blogs.msdn.com/brada/archive/2009/01/12/framework-design-guidelines-extension-methods.aspx)  Using Thing is my preference unless you're making a Thing class - in which case, ThingExtensions becomes confusing...  Hopefully, there will be official guidance on this at some point.
Comment: I follow the framework's approach in my projects. Hasn't lead to any nasty side-effects yet.
Comment: @Programming: It works great, provided you don't have a default implementation for `IThing` that's named `Thing`...
Comment: Luckily, however, the user never uses the class name, so the extension method class name is (effectively) an implementation detail, and not part of the API.  The user only "uses" and "knows" the namespace name directly.
Comment: @Reed agreed they are a bit silent on the naming convention.  But in the absence of one I usually fall back to precedence and for the BCL and most of VS APIs the precedence is `ThingExtensions`.  Additionally it seems unlikely the design guidelines would come out in favor of `IThingExtensions` because it would mean too much existing code was no longer up to par.  My guess is they will continue to remain silent on the subject
Comment: @JaredPar: Does the BCL use "ThingExtensions" anywhere?  Every BCL class seems to use "Thing"... This is my preference (and what I typically do) unless there is a "Thing" class, in which case it gets confusing :(
Comment: @Reed,  Not that I know of.  The new Visual Studio APIs have the `ThingExtensions` pattern in several places.
Comment: @JaredPar `System.Web.Mvc.Html` has plenty, but the name doesn't imply the extended class. Rather, it groups the extension methods by subject, such as `FormExtensions` or `ChildActionExtensions`. There is also `AjaxRequestExtensions` at `System.Web.Mvc`, which extends `HttpRequestBase`. All of theses didn't exist at the time the above comments were added, though.
Comment: Roslyn has class ISymbolExtensions: https://learn.microsoft.com/en-us/dotnet/api/microsoft.codeanalysis.isymbolextensions?view=roslyn-dotnet
Answer: I would prefer putting it in a folder (and namespace) called Extensions and naming it IThingExtensions.
Answer: Most programmers I know put all of their extension methods for an application in a static class called ExtensionMethods (or something like that), regardless of the class the extensions modify,  and then they put this class into their main program namespace.
Their rationale is that, if you put the extension method in the same namespace as the class it modifies, you can confuse the method with the methods that are part of the actual class, which suggests that the extension method is part of the original functionality when it isn't.
Their isn't universal agreement on this, of course.  See here: How do you manage the namespaces of your extension methods?
Comment: If you want to share those extension methods across several apps you will have to search , copy and paste the desired extension methods into your working project. not good.
Answer: I've taken a slightly different approach, and rather than suffix with Extension reversed the naming strategy to prefix the class containing the extension methods with Extend; my rationale is as follows:

As pointed out in Reed Copsey's answer, very (very) seldom will client code reference the containing class directly as the very point of extension methods is to emulate reference methods. They won't see the classes, so your class naming convention choice should have insignificant impact.
The classes must be static, and thus you'll never instantiate them. Therefore you never end up with the semantic oddity of new ExtendThing() as far as naming is concerned.
All of your Extend* classes are visually grouped with alpha file sorting.
And with respect to your question specifically, there isn't any interface naming prefix confusion; you can have ExtendThing and ExtendIThing and (IMO) their intent and target is clear.

namespace MyCompany.Extensions
{
    public static class ExtendObject { }

    public static class ExtendDateTime { }

    public static class ExtendIEnumerable { }
}

Comment: seems nice way of doing it.
Answer: I am not aware of any standard convention for this.  I would use either ThingExtensions or ThingInterfaceExtensions.  I would stay away from IThingExtensions as you also suggested.


Moving a web application to use HAProxy, Varnish, and nginx

Question: I currently have 4 web application servers (running on application) on Rackspace that sit behind a Load Balancer (on Rackspace). In front of the Load Balancer. The application itself makes moderate use of caching so I know this can be improved on quite a bit.
My current architecture:
RS Load Balancer (SSL Termination) -> 4 Web Servers (Apache) -> MySql
This set up was put in place before me and now I have the opportunity to clean things up a bit so I was thinking of either this:
Varnish -> HAProxy (reverse proxy, LB, SSL Termination) -> 4 Web Servers (nginx) -> Redis / MySql
OR
Varnish -> nginx (reverse proxy, LB, SSL Termination) -> 4 Web Servers (nginx) -> Redis / MySql
OR is it better to have Varnish behind the proxy and in front of each web server like so?:
nginx or HAProxy -> 4 Varnish Servers -> 4 Web Servers (nginx) -> Redis / MySql
I would also move my servers to Linode as they seem to provide better pricing and while I've heard mixed reviews of their load balancers (the call them "NodeBalancers"), I have heard great things about their service and reliability in general.
My questions are:

Of the above, which set up makes more sense?
Is there anything I should add — or replace?
What type of hardware should I provision for Varnish?
Is it okay to put Varnish on the same server as each web server?
Answer: Varnish does not do SSL, so doing Varnish->nginx, or Varnish->HAProxy won't work with SSL.
On the other hand, putting anything in front of Varnish (besides SSL termination) will probably strip you of the performance benefits Varnish provides.
Having Varnish (cache) share hardware and/or OS with webserver may, or may not be a problem. It hugely depends on the parameters of traffic you are serving. The same is true for hardware scaling. It depends on your goals as well.


Criar fluxo de controle na playlist para web player

Question: Para exemplificar o que estou querendo, observe a figura:

Screen Shot

Para isso coloco o código fonte para exemplo:

Código

 &#171 Anterior

1
2
3
4

   Próximo &#187

Não defini thumbnail nos seguintes links:
1
2
3
4

Preferi deixar por números para detectar eventuais erros, ja que esta em fase de criação.

A minha dificuldade está em fazer a lógica fluxo controle entre "próximo/anterior"

Sei que o problema esta por aqui..

if (indice == img.length - 1) {

indice = 0;

} else {

indice++;

}

Comment: Veja se isso ajuda http://pt.stackoverflow.com/a/168525/3635 (obs: não fui eu quem negativou e também não entendi o motivo)
Comment: Não entendi, é video ou foto?
Comment: Isso esta claro, mas as pessoas (provavelmente) estão esperando tentar entender se você quer passar um video, foto ou outra coisa para criar um exemplo em cima do uso que necessita.
Comment: Veja se a resposta lhe ajuda
Answer: Altera a sua função troca por essa aqui que deve funcionar. Tente adicionar um JSFiddle que vai ajudar muito.

img = ['1','2','3','4']

indice = 0;

function resetThumbnail () {
 document.getElementById("screenshot1").className = "";
    document.getElementById("screenshot2").className = "";
    document.getElementById("screenshot3").className = "";
    document.getElementById("screenshot4").className = "";
    document.getElementById("screenshot" + img[indice]).className = "hover";
}

function troca(i) {
    indice += i;

    resetThumbnail();

    this.className = 'hover';

    // edit - adicionando um limitador.
    if (indice < 0) {
        indice = 0;
    } else if (indice > img.length - 1) {
        indice = img.length - 1;
    }

    document.getElementById("screenshot").innerHTML = "";
}
#slide #screenshot {
width: 480px;
height: 360px;
border: solid 3px #333;
}

#slide a {
border: solid 1px #333;
background-color: #F7F7F7;
padding: 5px;
text-decoration: none;
color: #000;
}

#slide a:hover {
border: solid 1px #333;
text-decoration: underline;
background-color: #333;
color: #FFF;
}

#slide a.hover {
background-color: #333;
color: #FFF;
}

#slide #controle {
width: 480px;
height: 360px;
text-align: center;
padding-top: 15px;
}

 &#171 Anterior

1
2
3
4

   Próximo &#187

Eu não entendi o propósito do restante da sua função.
Comment: `troca(-1);` vai alterar a `` para o índice anterior, `troca(1);` para a próxima.
Comment: No seu código a thumbnail tbm não está funcionando?
Comment: Atualizei o código, teste aí.
Comment: Fico contente por ter partilhado comigo um pouco do seu conhecimento, embora não sei o porque ainda, não funcionou como deveria. Mas ficou claro como aprendizado.
Comment: Ja descobri o caso do teu código falhar em meus testes. Vou reeditar sua reposta com detalhe exato. Assim ficará para futura pesquisa como a segunda alternativa a esta questão.
Answer: Acredito que o código deva ficar assim:

var img = ['1','2','3','4'];

var indice = 0;

function troca(i) {
    //Verifica se o numero esta dentro da quantidade de indices
    if (i < img.length) {
       indice = i;
    } else {
       return;
    }

    document.getElementById("screenshot1").className = "";
    document.getElementById("screenshot2").className = "";
    document.getElementById("screenshot3").className = "";
    document.getElementById("screenshot4").className = "";
    document.getElementById("screenshot" + img[indice]).className = "hover";

    document.getElementById("screenshot").innerHTML = "";
}

function proximo() {
    //Soma mais 1 e se passar do limite do indice torna 0 novamente
    indice++;

    if (indice >= img.length) {
       indice = 0;
    }

    troca(indice);
}

function anterior() {
    //Subtrai 1, se for menor que 0 move para o ultimo item do indice
    indice--;

    if (indice < 0) {
       indice = img.length - 1;
    }

    troca(indice);
}
.hover {
    padding: 5px;
    background-color: #F00;
    color: #fff;
}

 &#171 Anterior

1
2
3
4

  Próximo &#187
Comment: Agradeço, desde ja pelo tempo disposto em me ajudar. Coloco o meu voto sobre seu desempenho por finalizar com precisão e atenção.


ip routing on cent os

Question: I have a web server with installation of Cent OS 5.6, cPanel/WHM.
Currently the server have 2 ethernet and the configuration for both is listed below:
--------------------------------------------------------------
      | IP              | Subnet Mask     | Gateway
--------------------------------------------------------------
eth0  | XXX.XX.XXX.150  | 255.255.255.252 | XXX.XX.XXX.149
--------------------------------------------------------------
eth1  | 192.168.86.2    | 255.255.255.252 | 192.168.86.1
--------------------------------------------------------------

Current default route is eth1 with gateway 192.168.86.1
Now what I need is to set eth0 as a default route for all connection except for 3 IPs (10.10.6.2, 10.10.6.3 and 10.10.6.4). I also need to set route for those 3 IPs from eth1.
eth0 is connected to optical fiber for internet connection whereas eth1 is connected to a DSL router for intranet connection
so can anyone help me to set this properly and permanently?
Answer: There are a few things you need to configure.  First of all, a router attached to the 192.168.86.2/30 interface must be configured to route traffic destined for this network to it.  Assuming you're in some hosted environment where this has already been completed, you only have to configure the routing table on the server.
You can specify a default route for all traffic in /etc/sysconfig/network by setting the GATEWAY option:
GATEWAY=XXX.XX.XXX.149

Next, you'll need custom routing for the IPs you specified.  You do this with the /etc/sysconfig/network-scripts/route-eth1 file by adding:
10.10.6.2/32 via 192.168.86.1
10.10.6.3/32 via 192.168.86.1
10.10.6.4/32 via 192.168.86.1

(I'm making the assumption that the router listed as 'Gateway' next to eth1 will get you there, of course.)
You should be able to restart networking (service network restart) and verify the routing table with route -n.
Comment: to change the default gateway to eth0 I simply added GATEWAYDEV=eth0 on /etc/sysconfig/network and I added the rule on route-eth1 but got this reply from 192.168.86.1 "Destination Host Unreachable". This means the route is working and may be destination is probably down.
Comment: I also want to know do I need to add subnet mask? If so how? As `route -n` shows 255.255.255.255 as a genmask whereas I think it should be 255.255.255.252
Comment: The /32 is the subnet mask written in CIDR format.  The mask specifies which IPs in the network (based on the network address) to include.  I  have listed 3 individual IPs so the network mask is 255.255.255.255.  This could be expressed in a /30 (255.255.255.252) as well, but I was unsure about the .1 address.
Comment: I added following on route-eth1 `10.10.6.2/30 via 192.168.86.1
10.10.6.3/30 via 192.168.86.1
10.10.6.4/30 via 192.168.86.1` and restarted the network service. But which checking `route -n` it output error like `RTNETLINK answers: Invalid argument`
Comment: Please put the contents of that file into a pastebin and add the URL to your question or via a comment here.
Comment: it just worked without adding /30 subnet mask. Thanks for the answer.

ip routing on cent os


O que !cin significa em c++?

Question: Código:
using namespace std;

int main()
{
    cout << "Por favor, insira uma expressao (podemos processar +, -, * e /): " << endl;
    cout << "acrescente um x para terminar a expressao (p.ex., 1+2*3x): " << endl;
    int lval = 0;
    int rval;
    char op;
    cin >> lval; // ler operando esquerdo
>>  if (!cin)
        printf("falta primeiro operando");
    while (cin >> op)
    { // ler repetidamente o operador e operando direito
        if (op != 'x')
            cin >> rval;
        if (!cin)
            printf("falta segundo operando");
        switch (op)
        {
        case '+':
            lval += rval; // somar: lval = lval + rval
            break;
        case '-':
            lval -= rval; // subtrair: lval = lval – rval
            break;
        case '*':
            lval *= rval; // multiplicar: lval = lval * rval
            break;
        case '/':
            lval /= rval; // dividir: lval = lval / rval
            break;
        default: // mais nenhum operando: imprimir resultado
            cout << "Resultado: " << lval << '\n';
            system("pause");
            return 0;
        }
    }
    printf("expressão incorreta");
}

O que ele verifica fazendo isso ?
Answer: Ao escrever !cin, você está implicitamente tentando converter cin, que é do tipo basic_istream em um tipo bool. Isso funciona pois basic_istream define em algum lugar da sua cadeia hierárquica uma sobrecarga de operador para este tipo de conversão.
O comportamento da conversão de cin em específico está definida aqui: https://pt.cppreference.com/w/cpp/io/basic_ios/operator_bool

"true se o fluxo não tem erros, caso contrário false."

Para ser mais especifico, uma basic_istream será convertida para true somente se basic_istream.fail() e basic_istream.bad() forem falsos. E diferentemente de basic_istream.good(), a conversão para bool ainda resulta em true mesmo se o fim do stream eof já tiver sido alcançado.
Aqui é possível ver o que pode causar o bit de fail e bad a serem acionados (em inglês):
https://en.cppreference.com/w/cpp/io/ios_base/iostate
Por exemplo, se no seu código cin >> lval falhasse por motivo do usuário entrar com um valor que não pode ser convertido no tipo de lval, o fail bit seria acionado e a conversão para bool que segue retornaria false.
Exemplo de sobrecarga para bool:
#include <iostream>

// Classe de exemplo para demonstar a capacidade de sobrecarregar conversões
class GuardaNumero
{
    int m_meuNumero;

public:
    GuardaNumero(int numero)
    {
        this->m_meuNumero = numero;
    }

    // Esta função está sobrecarregando a conversão para bool, sempre que GuardaNumero sofrer
    // conversão para bool, esta função determinará o valor desta booleanica.
    operator bool()
    {
        // true caso meuNumero seja maior que 25, falso caso contrário.
        return this->m_meuNumero > 25;
    }

};

int main()
{
    GuardaNumero a(10); // Menor que 25
    GuardaNumero b(24); // Menor que 25
    GuardaNumero c(26); // Maior que 25

    // Conversão implícita para bool de a
    if (a)
        std::cout << "O numero de a e maior que 25" "\n";

    // Conversão explícita para bool, mesmo processo da implícita de b
    if (static_cast<bool>(b))
        std::cout << "O numero de b e maior que 25" "\n";

    // Conversão implícita para bool de c
    if (c)
        std::cout << "O numero de c e maior que 25" "\n";

    // Conversão explícita para bool, mesmo processo da implícita de c
    if (static_cast<bool>(c))
        std::cout << "O numero de c ainda e maior que 25" "\n";

}

Output:
O numero de c e maior que 25
O numero de c ainda e maior que 25

A sobrecarga de bool normalmente serve para trazer informações relacionadas ao estado do objeto.
Comment: @LuizFelipe Editei a resposta para ser mais específica em relação aos erros de cin em geral.

O que !cin significa em c++?


Change pickup order on a 5-way blade switch

Question: I'm going to be following the following set up for my telecaster's controller:
https://sixstringsupplies.co.uk/pages/5-way-telecaster-wiring
But I don't like the default order of the selection.
I want to have:

Neck
Neck with series cap
Neck & Bridge parallel
Neck & Bridge HOOP
Bridge

Is this possible? And how do I work out the wiring order on the switch to match this?
Answer: I'm afraid that unless I miss some smart solution, this is impossible with a standard 5-way blade switch.
Please see this explanation of how a 5-way switch works:
http://alloutput.com/guitar/5-way-switches-explained/
or
https://www.fralinpickups.com/2017/06/18/blade-switch-basics/

In particular, I think that with a regular switch, the "pickup with series cap" and "HOOP" need to be next to each other, as both of them use a capacitor.
Some producers make switches which offer more possibilities for connections. With some googling I was able to find e.g. these:

Schaller Megaswitches https://schaller.info/en/megaswitches
Grigsby Superswitch https://www.stewmac.com/video-and-ideas/online-resources/learn-about-guitar-pickups-and-electronics-and-wiring/super-switch-installation-and-wiring/|
Freeway switches https://www.freewayswitch.com/schematics-blade/

I'm sorry, but I cannot find a specific solution for you at this time, but perhaps you would be able to find a switch that allows you to make the connections you are looking for.
Comment: Thank you for a, though disappointing, clear answer. You've saved me a lot of time trying to do the impossible.


IOC across visual studio projects?

Question: I'm trying to retro-fit (bad idea I know, but better late than never) IOC and DI into an existing solution.
The code base is made of up about 30 projects, each which have classes in them which have little or no visibility to the outside world. Being relatively new to the IOC thing I'm trying to use best practise when reworking the code, and it seems best not to pass the IOC container around or make it static, hence I'm trying to do everything via constructor injection.
However, and here comes my question, I am having to make an awful lot of the classes public across projects (i.e. physical .csproj files). I'm having to do this because my 'configuration module' (i'm using Ninject, but this is an IOC agnostic question) needs to know about everything in any class in any project in order to be able to resolve the dependencies.
Have I missed something significant? Are all my classes supposed to be public if they are based on an interface? Can I somehow create an IOC container for each of my csproj boundaries and have that do the injection for me?
Ta
Answer: Could you not write a configuration module inside each project, and only make that public? Then configure ninject with all of the modules instead of a single one...
Comment: Pros: Encapsulation. Cons: Every module now has a dependency on Ninject; configuration may be more rigid (what if consumer A wants IFoo to be implemented by Bar instead of Foo?); no one place to see all the mappings.
Answer: I believe you're on the right track. In general any IoC Container is going to need to be aware of (a) the interface and (b) the implementation so it can wire everything up. You generally do the "wiring" in higher-level modules (your configuration module project in this case); the lower-level modules don't need to know about all possible implementations of the interfaces. In order to make this happen (and to facilitate testability) the implementations need to be public.
If you really wanted to you could use InternalsVisibleTo, but I wouldn't. If you were not using IoC, you'd need to make these classes public anyway.
You could also look into MEF; apparently it allows the implementations to be private or internal.

IOC across visual studio projects?


How to adapt crossAxisCount of GridView based on its width in Flutter?

Question: What is the best practice to adapt the number of columns (crossAxisCount) of a GridView based on its width in Flutter?
Maybe I can better explain the intended behaviour by referencing HTML:

I create 6 boxes (e.g. DIVs) with a width of 200 px (and same height) each.
(a) If the element surrounding these boxes has a width of 400 px, it would automatically show 2 boxes per row in 3 rows.
(b) If the element surrounding these boxes has a width of 700 px, it would automatically show 3 boxes per row in 2 rows.
Comment: Awesome, this is exactly what I needed! Thanks!
Answer: Use Wrap. It can put renderboxes as many as fit to a row, then wrap to the next row. (formerly a comment, but it looks like the answer!)
Comment: it's very nice, thank you
Answer: I do this like below. You can try..
<code>  int getItemCountPerRow(BuildContext context) {
    double minTileWidth = 200; //in your case
    double availableWidth = MediaQuery.of(context).size.width;

    int i = availableWidth ~/ minTileWidth;
    return i;

  }
</code>
Comment: If I understand this solution correctly, it is a method that calculates the amount of items per row based on the screen width. So this solution would be limited to use cases, where the width of the GridView equals the width of the screen. This solution is close, but not the solution I need in my very specific use case.
Comment: yes. you need to modify according to your need. i have just shared the approach what i generally do.


Definition of "degree of interaction" in the MARS model

Question: What exactly is the meaning of the "degree of interaction" or "interaction degree" in the MARS model?
e.g.  R: earth(..., degree=2)
Answer: The degree of interaction is the maximum degree of input terms in the regression function. For example a model such as $y=0.5x_1+0.2x_2 -.3$ has degree $1$. While $y=0.5x_1+0.2x_2 + .05x_1x_2-.3$ has degree $2$. For simplicity, I have given a linear regression example instead of MARS.
Or, paraphrasing from the wikipedia entry, something like
$\text{ozone} =  5.2
      +    0.93 \max(0, \mathrm{temp} - 58)
      -   0.64 \max(0, \mathrm{temp} - 68)$
$     -   0.016 \max(0, \mathrm{wind} - 7) \max(0, 200 - \text{vis})$
is an example of a MARS model with degree of interaction $2$.


Display data from three tables without duplicates

Question: I have three tables in a hierarchical setup.  The top table:
Group             ID|Title
RiskFactor        GroupID|Question
Choices           RiskFactorID|Label|Score

There is a one to many relation where one group will have multiple riskfactors and each riskfactor with have multiple answers and each answer will have a score.  So a query with an INNER JOIN or LEFT JOIN gives the same result.
Query:
    SELECT
           Groups.Title,
           RiskFactors.Question,
           Choices.Label,
           Choices.Score
    FROM
           Groups Inner JOIN
           RiskFactors ON Groups.GroupId = RiskFactors.GroupId inner JOIN
           Choices ON RiskFactors.RiskFactorId = Choices.RiskFactorId
    ORDER BY
           Groups.groupid

Will produce a result like this:
Title                       Question                                                   Label  Score
4.1 - Employment & Finance  Is your current job in JEOPARDY?  (Describe why in notes)   Yes 3
4.1 - Employment & Finance  Is your current job in JEOPARDY?  (Describe why in notes)   Maybe   2
4.1 - Employment & Finance  Is your current job in JEOPARDY?  (Describe why in notes)   NA  1
4.1 - Employment & Finance  Is your current job in JEOPARDY?  (Describe why in notes)   No  1
4.1 - Employment & Finance  How LONG was (is) your longest FULL TIME job?   NA  1
4.1 - Employment & Finance  How LONG was (is) your longest FULL TIME job?   0-6 Months  1
4.1 - Employment & Finance  How LONG was (is) your longest FULL TIME job?   1-3 Years   1
4.1 - Employment & Finance  How LONG was (is) your longest FULL TIME job?   6-12 Months 1
4.1 - Employment & Finance  How LONG was (is) your longest FULL TIME job?   Only Part Time  1
4.1 - Employment & Finance  How LONG was (is) your longest FULL TIME job?   More than 3 Years   1

I would like to remove the duplicates in the title and question fields and replace them with NULL or empty values so it looks more like this:
TITLE                       QUESTION                                                    Label SCORE
4.1 - Employment & Finance  Is your current job in JEOPARDY?  (Describe why in notes)   Yes 3
                                                                                Maybe   2
                                                                                NA  1
                                                                                No  1
                            How LONG was (is) your longest FULL TIME job?   NA  1
                                                                            0-6 Months  1
                                                                            1-3 Years   1
                                                                            6-12 Months 1
                                                                            Only Part Time  1
                                                                            More than 3 Years   1

I've tried using a CTE and a pivot table both without any success. I'm not a SQL developer, and I'm sure this isn't a unique problem.  How can this data in a hierarchal way?  Before I would throw it into a grid an set the grid control to remove duplicates in the columns.
Comment: This sort of task should be a function of your rendering application - trying to do it as part of the query is just making life hard for yourself.
Comment: What you are asking for can easily be done but it looks like you're trying to do the job of your presentation layer?
Comment: Normally I would do this as two separate `select`s, map them into a dictionary/hashmap on the client and use that for display
Comment: Most of the time I to push this to presentation layer, but this time, the user just needs a dump of the data to an excel file without duplicates.
Answer: Here's a possible hack you can try - you haven't offered any sample data so - disclaimer! untested - simply use row_number to order within each group and use an empty string (or null or whatever) when it's not the first row of the group:
SELECT
  Iif(Row_Number() over(partition by groups.title order by Groups.groupid)=1,Groups.Title,'') Title,
  Iif(Row_Number() over(partition by groups.title, RiskFactors.question order by Groups.groupid)=1,RiskFactors.Question,'') Question,
  Choices.Label,
  Choices.Score
FROM
  Groups Inner JOIN
  RiskFactors ON Groups.GroupId = RiskFactors.GroupId inner JOIN
  Choices ON RiskFactors.RiskFactorId = Choices.RiskFactorId
ORDER BY
  Groups.groupid

Comment: Thanks, I'll give this a try and see what happens.


Button inside ListView unable to Receive OnClick?

Question: Currently, my listView is sitting inside a fragment. However, the buttons inside my view are not able to receive the on click event whenever I tap on them.
I am not sure what to do.
Here is my code:
public class ViewInvitationsCursorAdapter extends CursorAdapter {

private Activity activity;

private int layout;
private Cursor cr;
private final LayoutInflater inflater;
private Fragment f;
private boolean displayAcceptDeny;

public ViewInvitationsCursorAdapter(Activity activity, Fragment f,
        int layout, Cursor c, boolean displayAcceptDeny) {
    super(activity, c);
    this.layout = layout;
    this.activity = activity;
    this.inflater = LayoutInflater.from(activity);
    this.cr = c;
    this.f = f;
    this.displayAcceptDeny = displayAcceptDeny;
}

public static class ViewHolder {

    public TextView sender;
    public TextView sender_email;
    public TextView author_role;
    public Button deny;
    public Button accept;
    public Button cancel;
}

@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {

    ViewHolder holder = new ViewHolder();
    View view = inflater.inflate(layout, parent, false);

    holder.sender = (TextView) view.findViewById(R.id.connection_sender);
    holder.sender_email = (TextView) view
            .findViewById(R.id.connection_sender_email);

    holder.author_role = (TextView) view.findViewById(R.id.connection_role);

    holder.accept = (Button) view.findViewById(R.id.connection_allow);
    holder.deny = (Button) view.findViewById(R.id.connection_deny);
    holder.cancel = (Button) view.findViewById(R.id.connection_cancel);

    view.setTag(holder);
    return view;
}

@Override
public void bindView(View view, Context context, final Cursor cursor) {
    // .bindView(view, context, cursor);
    final ViewHolder holder = (ViewHolder) view.getTag();

    int sender_index = cursor
            .getColumnIndexOrThrow(FamilyDBHelper.COLUMN_SENDER_BY_NAME);
    int sender_email_index = cursor
            .getColumnIndexOrThrow(FamilyDBHelper.COLUMN_SENDER_BY_EMAIL);

    String senderString = cursor.getString(sender_email_index);

    int author_role_name = cursor
            .getColumnIndexOrThrow(FamilyDBHelper.COLUMN_RELATIONTYPE_NAME);
    int message_index = cursor
            .getColumnIndexOrThrow(FamilyDBHelper.COLUMN_MESSAGE);

    holder.sender.setText(cursor.getString(sender_index));

    holder.author_role.setText(cursor.getString(author_role_name));
    holder.sender_email.setText(cursor.getString(sender_email_index));

    holder.cancel.setVisibility(View.VISIBLE);
    // setUpCancel(view, cursor);
    holder.cancel.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {

              Log.i("cancel", "cancel clicked!");

        }
    });

}

protected void setUpAcceptDeny(View view, final Cursor cursor) {
    final ViewHolder holder = (ViewHolder) view.getTag();

    holder.accept.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            Log.i("accept", "accept clicked!");
        }
    });
    holder.deny.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            Log.i("deny", "deny clicked!");
        }
    });
}

}
Here is the xml for each of the items:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/connection_item_row_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:paddingBottom="8dp"
    android:paddingLeft="8dp"
    android:paddingRight="8dp"
    android:paddingTop="8dp" >

    <LinearLayout
        android:id="@+id/connection_item_info_layout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="left"
            android:layout_weight="1"
            android:orientation="vertical" >

            <TextView
                android:id="@+id/connection_sender"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="#000000"
                android:textSize="16sp"
                android:textStyle="bold"
                tools:text="ANDROID: PREFERENCEFRAGMENTCOMPAT" >
            </TextView>

            <TextView
                android:id="@+id/connection_sender_email"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/connection_sender"
                android:textColor="#000000"
                android:textSize="14sp"
                tools:text="ANDROID: PREFERENCEFRAGMENTCOMPAT" >
            </TextView>

            <TextView
                android:id="@+id/connection_role"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/connection_sender_email"
                android:textColor="#000000"
                android:textSize="14sp"
                 >
            </TextView>
        </RelativeLayout>

    </LinearLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/connection_item_info_layout"
        android:orientation="horizontal"
        android:paddingBottom="1.0dip"
        android:paddingLeft="4.0dip"
        android:paddingRight="4.0dip"
        android:paddingTop="5.0dip" >

        <Button
            android:id="@+id/connection_allow"
            android:layout_width="0.0dip"
            android:layout_height="wrap_content"
            android:layout_weight="1.0"
            android:text="Allow"
            android:background="@color/green"
            android:textColor="@color/white"
            android:visibility="gone" />

        <Button
            android:id="@+id/connection_deny"
            android:layout_width="0.0dip"
            android:layout_height="wrap_content"
            android:layout_weight="1.0"
             android:background="@color/red"
             android:textColor="@color/white"
            android:text="Deny"
            android:visibility="gone" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/connection_item_info_layout_request"
        android:orientation="horizontal"
        android:paddingBottom="1.0dip"
        android:paddingLeft="4.0dip"
        android:paddingRight="4.0dip"
        android:paddingTop="5.0dip" >

        <Button

            android:id="@+id/connection_cancel"
            android:layout_width="0.0dip"
             android:background="@color/red"
             android:textColor="@color/white"

            android:layout_height="wrap_content"
            android:layout_weight="1.0"
            android:text="Cancel Request"
            android:visibility="gone" />
    </LinearLayout>

</LinearLayout>

Comment: @Faytll I do not see setUpAcceptDeny gettting called
Comment: @Maddy: I reduced the code in order to try and pinpoint where the problem may have been.
Comment: @Krylez: none of those solutions worked for me. Does it change if my listview is inside a fragment?
Answer: Add this line to your list item xml file.
android:descendantFocusability="blocksDescendants"

Comment: Does not work. Unfortunately, the test fails when I add it to the LinearLayout that wraps the entire item view.
Answer: if you set clicklistener inside newView method like this it should work. I generally user getView() for this method and there has never been a problem..
@Override
public View getView(Context context, View View, ViewGroup parent) {
ViewHolder holder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
         View = inflater.inflate(R.layout.your_layout_file_id, parent,
                false);

holder.sender = (TextView) view.findViewById(R.id.connection_sender);
holder.sender_email = (TextView) view
        .findViewById(R.id.connection_sender_email);

holder.author_role = (TextView) view.findViewById(R.id.connection_role);

holder.accept = (Button) view.findViewById(R.id.connection_allow);
holder.deny = (Button) view.findViewById(R.id.connection_deny);
holder.cancel = (Button) view.findViewById(R.id.connection_cancel);

view.setTag(holder);

holder.cancel.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View arg0) {

          Log.i("cancel", "cancel clicked!");

    }
});

return view;

}
Comment: Does not work. The button does not trigger.
Comment: Note that my code is for getView() method and this is a way to implement a custom adapter for ListView


Como definir a posição do cursor em um elemento editável?

Question: Eu tenho a seguinte estrutura:

"Always pass on what you have learned." - Yoda

> {|}

--
X

Eu quero que quando alguém clique em um botão eu coloque o cursor no lugar de {|}. Esse texto {|} realmente existe no meu elemento, eu posso substituí-lo por um elemento html se necessário.
Como posso definir a posição do cursor, para que quando começar a digitar meu texto apareça ali naquela posição?
Comment: http://jsfiddle.net/Td3pV/
Answer: Você precisa usar os objectos Range e Selection para obter um intervalo selecionado dentro do elemento:
// marca lugar para posicionar o cursor em `editor`
var marker = '{|}';

// cria intervalo
var range = document.createRange();
var index = editor.innerText ? editor.innerText.indexOf(marker) : editor.textContent.indexOf(marker);
range.setStart(editor.childNodes[0], index);
range.setEnd(editor.childNodes[0], index + marker.length);

// faz seleção
var selection = window.getSelection();
selection.addRange(range);

editor.focus();

Fiddle aqui.
Comment: Em Linux com Firefox 25.0, nenhuma das soluções coloca o cursor na posição indicada para iniciar a escrita. Podes indicar que navegadores suportam esta solução?
Comment: Alterei o código para usar `textContent` quando `innerText` não estiver disponível e focar no editor. Funciona no Firefox 23 para Windows. Mas, como mencionado por @utluiz, você deve adaptar o código se a div contém outros elementos (adaptando `childNodes[0]`).
Comment: ... também funciona no Firefox 26 para Windows.
Answer: Como o Jordão já respondeu, com uma boa resposta por sinal, é possível localizar o texto dentro do editor.
No entanto, usar o childNodes[0] não vai funcionar caso haja tags html dentro do editor que englobem o marcador do cursor. Veja um exemplo neste jsfiddle, cujo HTML é:

"Always pass on what you have learned." - Yoda

> {|}

--
X

Preparei uma versão usando uma tag HTML com um id especial que evita esse problema e ainda permite posicionar o cursor sem precisar de um elemento visual.
O código ficou assim:
function setCursor(node, cursorElement) {
    var range = document.createRange();
    range.setStart(cursorElement, 0);
    range.collapse(true);
    if (window.getSelection) {
        var sel = window.getSelection();
        sel.removeAllRanges();
        sel.addRange(range);
        node.focus();
    } else if (document.selection && range.select) {
        range.select();
    }
}

var editor = document.querySelector("#editor");
var button = document.querySelector("button");

button.addEventListener("click", function(e) {
    setTimeout(function () {
        setCursor(editor, document.querySelector("#cur"));
    }, 200);
}, false);

O marcador é uma tag span, como no trecho abaixo:

"Always pass on what you have learned." - Yoda

>

--
X

Veja o Jsfiddle.
Comment: Em Linux com Firefox 25.0, nenhuma das soluções coloca o cursor na posição indicada para iniciar a escrita. Podes indicar que navegadores suportam esta solução?
Comment: +1 Sim! Se a `div` em questão tiver outros elementos, `childNodes[0]` deverá ser adaptado.
Comment: @Zuul No firefox precisa de um `node.focus()`. Atualizei a resposta. Havia testado no Chrome e no IE 9. :(
Comment: @utluiz Oi! Estou tendo problemas relacionados a essa pergunta, contudo estou com receio de criar outra. Veja, eu possuo a posição númerica em que o cursor deverá ficar, contudo dentro dessa div editável existem tags como  que são emojis e que devem ser considerados caracteres igualmente. Meu código não as considera caracter, veja: https://jsfiddle.net/3uvn0mqv/


Fermat's theorem

Question: In Fermat's little theorem $k^{p-1}$ is congruent to $1\pmod p$. Condition is that $p$ must be a prime number. Can anyone tell why it is so?
What I have understood is that if $p$ is not a prime, then writing down all
the integers between $1$ to $p-1$, there would be an integer which would be a factor of $p$, therefore we can't find the inverse.
Comment: A simple example: $2^3$ is **not** $1$ mod $4$.
Answer: Obviously you can't have $k^{n-1} \equiv 1 \mod n$ if $k$ and $n$ have a factor in common.  On the other hand, there are numbers $n$ that are not primes, but $k^{n-1} \equiv 1 \mod n$ for all $k$ that have no common factor with $n$ (i.e. are relatively prime to $n$).  These are called Carmichael numbers, and the smallest is $561$.

Fermat's theorem


Pairwise comparisons on mcglm joint model in r

Question: Using the mcglm package in r, I have been able to get pairwise comparisons from single-DV models but have not figured out how to get pairwise comparisons for an IV according to both DVs in a joint model.
df <- data.frame("r1" = rnorm(75),
                 "r2" = rnorm(75),
                 "p1" = c("f1","f2","f3"))

single-DV models
mat <- mc_id(df)
e1 <- r1 ~ p1
e2 <- r2 ~ p1
m1  <- mcglm(linear_pred = c(e1), matrix_pred = list(resp = mat),
             control_algorithm = list(correct = FALSE), data = df)
m2  <- mcglm(linear_pred = c(e2), matrix_pred = list(resp = mat),
             control_algorithm = list(correct = FALSE), data = df)

joint model
joint <- mcglm(linear_pred = c(e1,e2),
               matrix_pred = list(resp = mat,resp = mat),
               control_algorithm = list(correct = FALSE),
               data = df)

Pairwise comparisons from single-DV model
x = data.frame(df$p1);colnames(x)<-"x"
y = fitted(m1)
y=matrix(y); colnames(y)<-"y"
dat <- cbind(y,x)
m1.anova<-aov(y~x,data=dat)
TukeyHSD(m1.anova,"x")`

Does anyone have a solution for the joint model?
Comment: Firstly, because there are now multiple independent and dependent variables, you need to define your contrasts over specific variables in both groups. I haven't worked with mcglm in a while, but I'd check the documentation. Can it interface with emmeans? You can also always calculate the estimated marginal means (predict) and run the t-tests yourself.
Comment: mcglm doesn't interface with emmeans, nor does it have a predict() function - although it might have something similar to predict that I'm not familiar with. As for contrasts, there is a function called mc_initial_values that the package claims allows the user to obtain initial values, including contrasts, but there are no examples of how to use it and I've had no luck thus far.
Comment: Initial values is simply a function for initializing the model parameters BEFORE fitting; it won't be much use to you after fitting. It looks like you can get predictions with the fitted function. If that doesn't work, you can build then yourself from basic linear algebra operations. Check the mcglm white paper for a explanation.
Comment: I think my example above shows that I can get pairwise comparisons from the fitted() function, but as the question states, I don't know how that would work with two DVs. As for building them from basic linear algebra operations, that would be one option for how to answer this question. Alas, I'm not a statistician and there are 0 references to pairwise comparisons in any of the mcglm publications.
Comment: Now I'm confused: do you want to measure the overall effect of your independent variables on all your dependent variables. If so, you can just run `anova` on the `mcglm` model object and it should perform a Wald-type test. I assumed you wanted particular comparison (the difference between level 0 of factor 1 and level 1 of factor 1 with respect to one of the variables). If you want to latter, it should be enough to use t-tests between means and then apply a correction. TukeyHSD is nearly identical to a t-test and can be replaced by independent t-tests with an appropriate correction.
Answer: Unfortunately, the mcglm package has no support for multivariate multiple comparison tests. It is an on going work with my colleague (Guilherme Parreira) and a preliminary code is available on github https://github.com/guilhermeparreira/code/blob/master/code/comp.R. However, the code is not completely generic, thus probably you have to adapt it to your problem.
I have a paper under review explaining the methodology behind multivariate multiple hypothesis tests using the mcglm package, but it is a simple extension of the standard Wald-type test. It should be available soon.
Thanks for your interest in the mcglm package.
Best wishes.


Visual Studio C# Updating Localized Languages resx

Question: I have multi Language Application, first it was made in English only,
than one time i added support for German and Russian version and send resx files for translation to mates.
But while they do translation, i added few more checkboxes in GUI
and now when i copy their files and load German \ Russian GUI version those not translated checkboxes do not shown in in those languages.
My Question is:
Is there a way to update localized .resx files to version of main, as i can see it:
in Localized files if controls are missing - they will display in default language.
For translation they used: Zeta Resource Editor
Answer: Found answer by myself :) Maybe someone need it:
In this free program (Zeta Resource Editor) You can Add group of existing resources from Your VS Project - just select them an add, Zeta Resource Editor will auto show which strings are missing, so you can easily find them.


How to kill an openvz container?

Question: An openvz container can be stopped with
vzctl stop <id>

, but this needs the cooperation from the init inside the container.
In case a container is compromised a way is needed to stop the container withouts its cooperation. Something like a
vzctl kill <id>

is needed which kills all processes inside the container and puts it into the stopped state. Such a kill command is not listed in the manpage.
How can an openvz container be killed/stopped without needing it's cooperation?
Answer: http://wiki.openvz.org/User_Guide/Operations_on_Containers#Starting.2C_Stopping.2C_Restarting.2C_and_Querying_Status_of_Container

in case of a Container that is known to be corrupt, you may use the --fast switch:

# vzctl stop 101 --fast
Stopping container ...
Container was stopped
Container is unmounted

Make sure that you do not use the --fast switch with healthy Containers, unless necessary, as the forcible killing of Container processes may be potentially dangerous.

How to kill an openvz container?


Simple recommender system - where to start?

Question: Without going into specifics, I'm currently working on a system that involves 20-25 questions being answered as either Green, Yellow, Orange or Red. After completing a subset of these questions (many questions can be left as defaulting to Green), the system allows our users to choose one outcome out of four, roughly corresponding to the answers they entered (OutcomeGreen, OutcomeYellow, OutcomeOrange or OutcomeRed). The answer that was selected most tends to be a good indicator as to what outcome they will select, but that's not always the case.
After having this system in place for the last 2 years, now I've received a request to have the system itself make a recommendation as to which outcome the user should select. Using data already accumulated over this period, I'd like to get some insight as to which questions/answers tend to be most influential for specific outcomes, and possibly give them more weight when determining what to recommend.
My main dilemma is that my last class on statistics was more than 20 years ago, and just looking through the tags here made me feel that I'm out of my depth. With the description I've provided, and the vast knowledge contained within this SE:

Is there anything I should be looking into (tools, subset of
CrossValidated tags) that would help gain better insight, and where I
should look for more information?
Is there a quick way to get up-to-speed on what I'm missing?

Background: I'm a developer in many programming languages, and an amateur mathematician (mostly playing around in number theory and linear programming). I'm also a quick learner; I've been learning how to use R in my spare time. I just need some indication as to where I would find info quickly that would help me move forward with this.
Answer: You could try CART (tree) classification regression. That would select a decision tree algorithm for the outcomes based on the answers to the questions. As a bi-product, it would indicate which questions are most important in predicting outcome.
Comment: Thank you for the guidance; I've got a better handle on what I'm capable of, now that I've poked around in R and not made too much of a mess.
Answer: Actually, this isn't by most definitions a recommender system, and anything you read in the literature about recommender systems might be geared toward solving a similar but slightly different problem (namely, where the input and output space are the same set).
This is, by most conventional definitions, a classification problem, so looking for tags related to Classification might help.
In terms of actual approaches: as Placidia mentioned, CART and random forest methods are quite popular right now. Additionally, a classic method is Logistic Regression, which might be worth checking at (I'm not an R user, but I believe R has an implementation of it provided).
More than that is tough to provide without a knowledge of what your system is doing and what approaches might be valid. I'd recommend refreshing your basic probability and statistics and thinking about the way that your variables might be related, then taking a look at the classification methods included with R (and their respective Wikipedia pages).
Comment: Thank you for helping me with the terminology; coming in with an idea on what I need and what I thought was a descriptive term, only to find out that the term is loaded with other preconceptions is something I experience a lot when developing systems for fields in which I'm unfamiliar.
Answer: Before starting any research you should know about good resources and the research groups working in the filed. May be you can have a read of following paper to get some valuable resources and authors.
"A Scientometric Analysis of Research in Recommender Systems" . Journal of Scientometric Research: 71–84. doi:10.5530/jscires.5.1.1 [PDF]


g++ no longer finding standard libraries OSX 10.6.8

Question: no solutions I found on the internet have worked so far.
I am running OSX 10.6.8. I had previously been using the gnu compiler for C/C++ fine. I switched to XCode and have no problem with that but I would like to use the command line. However, after wiping my computer and restoring from a backup I was getting the error bash: g++ command not found.
First, I figured my $PATH got a bit wonky, so I tried to add in the correct path to the Path variable and now it recognizes g++ and tries to compile. But, I get this error now:
hello.cpp:3:20: error: iostream: No such file or directory
hello.cpp: In function 'int main()':
hello.cpp:8: error: 'cout' is not a member of 'std'

Here is the Hello World! code:
#include <iostream>

int main ()
{
std::cout << "Hello World!";
return 0;
}

Solutions that have been posted online have mainly been problems with namespaces and #include statements but I do not believe this to be the error at this time.
when I type "which g++" into Terminal I get: /Developer/usr/bin/g++
and when I type g++ -v I get:
Using built-in specs.
Target: i686-apple-darwin10
Configured with: /var/tmp/gcc/gcc-5666.3~6/src/configure --disable-checking --enable-werror --prefix=/usr --mandir=/share/man --enable-languages=c,objc,c++,obj-c++ --program-transform-name=/^[cg][^.-]*$/s/$/-4.2/ --with-slibdir=/usr/lib --build=i686-apple-darwin10 --program-prefix=i686-apple-darwin10- --host=x86_64-apple-darwin10 --target=i686-apple-darwin10 --with-gxx-include-dir=/include/c++/4.2.1
Thread model: posix
gcc version 4.2.1 (Apple Inc. build 5666) (dot 3)

4.2.1 is an older version so if there is one thing I could change it would be switching to 4.7.2 which I found in usr/local/Cellar/gcc. I am not sure what Cellar is perhaps that comes from when I tried using homebrew to install gcc as I found on some other forum.
Thanks in advance, this is beyond my ken.
Comment: "I had previously been using the gnu compiler for C/C++ fine. I switched to Xcode" - here you screwed up. Go back to the command line, really. Xcode is crap. (Oh, and +1 for compensating the time you wasted on this problem introduced by Xcode's programming antipatterns.)
Answer: When you installed XCode, you simply forgot to check that little checkbox that says "install Unix command line utilities." When you do that, you'll get a fully working GCC installed in /usr/. The one installed in /Developer/ is not for command-line use. It's only for the XCode graphical IDE.
Comment: alright so I should be reinstalling Xcode then and checking that box? My version of Xcode is 3.2.6 and I had checked Apple's Developer site and they didn't seem to have the download for anything before 4. I will check the cd though.
Comment: @DavidH The latest XCode for OS X 10.6 is 3.2.6 (xcode_3.2.6_and_ios_sdk_4.3.dmg). So you already have the latest version. Later versions of XCode are only for OS X 10.7 and up. I don't think you need to reinstall completely though. Maybe launching the installer again will simply allow you to modify the existing installation. Try that and simply install the Unix tools.


Theorem of Three Perpendiculars for N dimensional case?

Question: This is Theorem of Three Perpendiculars, How to prove variation of it for N dimensional case (or to prove that it is false)?
Let $\mathbb{R}^N$ is N dimensional Euclidean space and $h_1, h_2$ are two intersecting hyperplanes (each has dimension N-1), $\mathbb{S}$ is intersection of hyperplanes $h_1$ and $h_2$. Let $x_1$ is a point at $h_1$, $x_2$ is an orthogonal projection of $x_1$ to the second hyperplane $h_2$, $x_1^p$ is an orthogonal projection of point $x_1$ to $\mathbb{S}$, $x_2^p$ is orthogonal projection of $x_2$ to $\mathbb{S}$.
How to prove that $x_1^p$ is equal $x_2^p$?
Answer: Okay, I write solution I have just found.
Hyperplane $h_1$ is $\{x| a_1^Tx +b_1 = 0\}$, for some vector $a_1$ and number $b_1$. Similar $h_2 = \{x| a_1^Tx + b_2 = 0\}$. Intersection set is defined as $\mathbb{S} = \{x|a_1^Tx +b_1 = 0, and\  a_1^Tx + b_2 = 0\}$.
Projection point $x_1^p$ is a solution of next optimization problem:
$x_1^p = \arg\max ||x-x_1||^2,\ with\ respect\ to\ x\in\mathbb{S}$.
Similarly, $x_2^p = \arg\max ||x-x_2||^2,\ with\ respect\ to\ x\in\mathbb{S}$.
Because $x_2$ is a projection of $x_1$ in $h_2$, we have $x_2-x_1 = \alpha a_2$, where $\alpha$ is some scalar.
Next step is $||x - x_2||^2 = ||x - x_1 - \alpha a_2|| ^2 = ||x - x_1|| - 2((x - x_1)\cdot \alpha a_2) + ||\alpha a_2||^2 = ||x-x_1|| ^2 + const$,
where we used that $x^Ta_2 = b_2$ because of the constraint set.
So, essentially optimization problems are the same, which means that points $x_1^p$ and $x_2^p$ coincide.
Do you like the proof?


If $X_1, ..., X_n$ come from $\exp(5)$ using CLT, Calculate the probability $P(Z<z)$

Question: Please advise if the approach i am taking below is correct, I don't see how else to go about solving this problem.

import numpy as np

# generate data
np.random.seed(0)
dataset = np.random.exponential(scale =1/5, size = (30,1))
n = len(dataset)

# for an exponential distribution E[x] = 1/lambda = mean and var = 1/lambda**2
expected_value = 1/(1/5) # reciprocal of lambda we are given as 5 in this instance
standard_deviation = np.sqrt(1/(1/5)**2)

# Z = (X_bar - E[X_bar])/sd(X_bar) using CLT.
Z = ((dataset.mean() - expected_value)/standard_deviation)*np.sqrt(n)

# Calculate z_score for the dataset z_score = (sample - sample_mean)/sample_deviation
z_scores  = (dataset - dataset.mean())/(dataset.std())

# Check dataset where z_score > Z random variable
condition = z_scores > Z

# Probability is number of desired outcome condition/ total outcomes
prob = len(dataset[condition])/len(dataset)
print(prob)

Comment: I do not follow what you say about the population parameter (do you mean $n$ vs $n-1$?), but the central limit theorem concerns $Z=\sqrt{n}\dfrac{\bar{X}_n-\mu} {\sigma}$.
Comment: Your $Z$ does not appear to consider the sample size, $n$.
Comment: @Dave thanks i will add it, i was just not sure if i needed to divide by $\sqrt(n)$ for $Z$ if i am using the population parameter to obtain the standard deviation. I however see that i need to add it when calculating the z_scores.
Comment: I understand what you mean now, i have edited the calculation for $Z$ above, any other comments with regards to the approach?
Comment: It is impossible to tell what the question really is, because it appears to be a combination of coding problems and conceptual ones--but everything is expressed in code only.  Could you back up a little and explain, in words, what your problem is?
Comment: @whuber i was basically asked to draw 30 samples from  the $exp(5)$ distribution and having obtained that compute $P(Z<z)$ where $Z=\sqrt{n}\dfrac{\bar{X}-\mu} {\sigma}$ does this help?. That is the extent to which i understand the problem.
Comment: This becomes more mysterious.  What are $\mu$ and $\sigma$?  Would they be the true mean and SD or the sample mean and SD?  And how is it proposed that you use a *sample* to calculate a property of a distribution?
Comment: @whuber that is precisely why i asked the question here as im not sure what to make of the parameters. I found that given the $\lambda$ for the exponential distribution one can determine $\mu$ and  $\sigma$ i.e. true mean and SD.  And then perhaphs do something with the $z score$ of the sample. i'd hoped it would make sense to someone who is more seasoned in the topic, im fairly new to all this. Unfortunately i couldnt get more information out of the lecturer besides what i have already given.
Comment: On closer inspection perhaps this is similar to my previous question https://stats.stackexchange.com/questions/532136/calculate-the-probability-ps2-n-1s2-n-1-by-monte-carlo-simulation-of/532183#532183 where i also needed to determine the  probability between a distribution and sample.
Answer: Comment:
Suppose $X_i$ are IID $\mathsf{Exp}(\mathrm{rate}=\lambda=1/3)\equiv
\mathsf{Exp}(\mu = 3)$ and $Z = \frac{\bar X - \mu}{\sigma/\sqrt{n}}.$ Then $Z$ is not well modeled by a normal distribution unless $n$ is in the hundreds. This is because of the skewness of the exponential distribution and the consequent slowness of the convergence of the CLT.
Illustrations by simulation in R for $\mu = 3$ and for $n=36, n=400.$
set.seed(2021)
a.36 = replicate(10^5, mean(rexp(36, 1/3)))
z.36 = (a.36-3)/(3/sqrt(36))
summary(z.36);  sd(z.36)

     Min.   1st Qu.    Median      Mean   3rd Qu.      Max.
-3.234041 -0.701673 -0.057333 -0.000163  0.643720  5.548458
[1] 1.00098  # SD

set.seed(620)
a.400 = replicate(10^5, mean(rexp(400, 1/3)))
z.400 = (a.400-3)/(3/sqrt(400))
summary(z.400);  sd(z.400)
     Min.   1st Qu.    Median      Mean   3rd Qu.      Max.
-4.092648 -0.686992 -0.019076 -0.001976  0.663559  4.777723
[1] 0.9988278

R code for figure:
par(mfrow=c(1,2))
hdr = "n=36: z-Scores of Exponential Means"
hist(z.36, prob=T, col="skyblue2", main=hdr)
 curve(dnorm(x), add=T, col="brown", lwd=2)
hdr = "n=400: z-Scores of Exponential Means"
hist(z.400, prob=T, col="skyblue2", main=hdr)
 curve(dnorm(x), add=T, col="brown", lwd=2)
par(mfrow=c(1,1))

By contrast, for any $n,$ exponential means are exactly
distributed according to the ratios $\frac{\bar X}{\mu} \sim
\mathsf{Gamma}(\mathrm{shape}=n, \mathrm{rate}=n).$ This is
easy to show, using moment generating functions. (Appropriate gamma density functions are superimposed on histograms below.)

par(mfrow=c(1,2))
hdr = "n=36: Distn's of Exponential Mean Ratios"
hist(a.36/3, prob=T, br=30, col="skyblue2", main=hdr)
 curve(dgamma(x,36,36), add=T, col="brown", lwd=2)
hdr = "n=400: Distn's of Exponential Mean Ratios"
hist(a.400/3, prob=T, col="skyblue2", main=hdr)
 curve(dgamma(x, 400,400), add=T, col="brown", lwd=2)
par(mfrow=c(1,1))

Answers for $X_i \stackrel{iid}{\sim} \mathsf{Exp}(\lambda=.2)$ with $E(X_i) = SD(X_i) = 5.$
We have the normal approximation $P(\bar X_n \le 5) = P\left(Z_n = \frac{\bar X_n-5}{5/\sqrt{n}} \le 0\right) \approx 0.5,$ for all $n>1.$
By contrast, we have the values
$P(Z_n \le 0) = P(\bar X_n \le 5) =
P\left(\frac{\bar X_n}{5} \le \frac 5 5 = 1\right),$
which can be evaluated exactly using the distribution
$\mathsf{Gamma}(n,n)$ for all $n>0.$ Values for $n = 10, 36, 100, 400$ are shown below.
pgamma(1, 10, 10)
[1] 0.5420703
pgamma(1, 36, 36)
[1] 0.5221667
pgamma(1, 100, 100)
[1] 0.5132988
pgamma(1, 400, 400)
[1] 0.5066491


Criar estilo e não estilizar xhtml css

Question: Viva,
Estou a tentar criar um titulo desde tipo: Compras .com
Pretendo que o ".com" esteja a negrito mas não quero usar o "em" porque não é um paragrafo.
Sabem como fazer isso?
Answer: Use CSS:
Style sheet:
.destaque {
    font-weight:bold;
}

HTML:
Compras .com

Veja também que o html possuí tags de títulos

, etc, e que essas tags, por padrão, já usam negrito.

Criar estilo e não estilizar xhtml css


Solve $\mathrm{arccot}\left(\tan\frac{4\pi}{5}\right)$

Question: Solve:

$\mathrm{arccot}\left(\tan\frac{4\pi}{5}\right)$

$\mathrm{arccot}\left(\tan\frac{4\pi}{5}\right)=\mathrm{arccot}\left(\frac{1}{\cot\frac{4\pi}{5}}\right)\\\frac{1}{\cot\frac{4\pi}{5}}=\alpha$
at the moment I don't know what to do
Answer: Let $x=\operatorname{arccot}(\tan y)$; then, by definition, $\cot x=\tan y$, so $\cot x=\cot(\pi/2-y)$ and therefore
$$
x=\frac{\pi}{2}-y+k\pi
$$
with the integer $k$ chosen so that $0<x<\pi$ (the range of the cotangent function).


Converter query SQL para MongoDB

Question: Tenho pouco (ou nenhum) conhecimento em bancos não-relacionais. Preciso converter a consulta abaixo (SQLite) em uma query equivalente a ser executada no MongoDB.
SELECT COUNT(*) FROM match_table
WHERE (home_team_api_id=9991 AND home_team_goal > away_team_goal)
OR (away_team_api_id=9991 AND away_team_goal > home_team_goal);

Pelo que entendi, o MongoDB não aceita querys com agrupamento em parênteses, entre outras "incompatibilidades". É possível realizar uma query equivalente no MongoDB?? Agradeço a ajuda!
Answer: Ficaria assim:
db.match_table.find({
   "$or":[
      {
         "$and":[
            {
               home_team_api_id:9991
            },
            {
               "home_team_goal":{
                  "$gt":"away_team_goal"
               }
            }
         ]
      },
      {
         "$and":[
            {
               "away_team_api_id":9991
            },
            {
               "away_team_goal":{
                  "$gt":"home_team_goal"
               }
            }
         ]
      }
   ]
}).count()

Pode usar esse link para ajudar: https://klaus.dk/sqltomongodb/
Comment: Assim a consulta MongoDB está comparando o membro `away_team_goal` com a string `"home_team_goal"`, e vice-versa
Answer: db.match_table.find({$or: [ [ {"home_team_api_id": 9991}, {$where: "this.home_team_goal > this.away_team_goal"} ], [ {"away_team_api_id": 9991}, {$where: "this.away_team_goal > this.home_team_goal"} ] ]}).count()

Converter query SQL para MongoDB


How to make an array as a word embedding, similar to tf.keras.datasets.imdb.get_word_index?

Question: Im new to machine learning. I saw a code for binary classification with Movie reviewsd from IMDB. I was trying to use the same code with my own dataset (where the columns are "text": this is my emotional sentence, "labels": 0 or 1).
I want to make a word embedding called word_index, similar to tf.keras.datasets.imdb.get_word_index
{'fawn': 34701, 'tsukino': 52006, 'nunnery': 52007, 'sonja': 16816, 'vani': 63951, 'woods': 1408, ...}

What I tried is this, but Im not sure if is the same result than get_word_index gives
{k: v for k, v in enumerate(my_dataset)}

Answer: I think you have mixed up the terms word embeddings and word_index. Word embeddings are vector representations of words in a language, there are many methods available to get these representations (for eg. using pre-trained word embeddings like Word2Vec, GloVe, BERT, etc.). It can be used instead of one-hot encodings for words.
Word_index is a vocabulary generated from the input text collection based on the frequencies of words. tf.keras.datasets.imdb.get_word_index gives the word_index to the IMDB dataset. To get word_index for your dataset, you can use keras.preprocessing.text.Tokenizer.fit_on_texts(input_dataset). It is also nicely explained in this previous post.


What is the name of this device for back massage?

Question: What is the name of the device?
Comment: Welcome to Sports SE! I closed your question because it is [not clear what you are asking](http://chat.stackexchange.com/transcript/message/10937530#10937530) **in the context of sports**. However, I am glad you were able to find an answer.
Comment: Again, how so in the context of sports? The question is as simple as read, yes, but in what relation does your question have with sports?
Comment: I see nothing in your question in how you relate regression specific to sports. Do you plan to use this device to help your recovery in a specific sport/exercise/fitness activity? Simply asking to identify the device doesn't scope your question in any of the aforementioned categories.
Comment: The question was so simple as it is in the title. I only added to the body text to meet the requirements about length. It was easy to find answers to the rest of the questions by google. I think it is now enough clear.
Comment: Regression is very important part of sports.
Answer: This thing seems to be an Arco Largo. I don't know if it has a generic name.
Comment: Over here its known as a Backstretcher


Horizontal centering of staffs in Lilypond

Question: I'm trying to set a score in Lilypond displaying several short themes each on its own staff. The themes don't span the full horizontal width, and I'd like to center them horizontally. I suspect there must be a way to do so, but haven't found it yet.
There is a command called \tweak self-alignment-X, but it doesn't seem to have any effect. And I'm not even sure of which level to put this in, should it go in \paper, or in \layout or somewhere where I put \new Staff?
Answer: You can use the Lilypond feature that a complete score can be included in a line of text markup. The only special requirement is that the included score must have a \layout block (but an empty one will do).
So: make a separate score for each theme, the put them in a centered column inside text markup block, like this:
   \version "2.18.2"
   \markup \fill-line {
      \override #'(baseline-skip . 10) \center-column {
      \line { \score {
         \new Staff { \relative c' { c d e } } \layout {} } }
      \line { \score {
         \new Staff { \relative c' { f g a b } } \layout {} } }
      \line { \score {
         \new Staff { \relative c
         { \time 3/4 \key d \major \clef "bass" d2. } }
         \layout {} } }
   } }

Set the \baseline-skip property to adjust the vertical spacing between the examples.
If you have a lot of themes you will probably want to define some macros for the repetitive parts of the input, of course.
This complete \markup block goes outside of your "real" score (either before or after it). See Chapter 3 of the Notation manual.
Note: the \line { \score { ... } } constructs can be changed to just \score { ... }, as an anonymous user (whose edit was rejected by other users) correctly pointed out. Having built and tested the answer incrementally, I didn't check if it was a minimal solution to the problem. The \line macros may have some value as self-documentation of the input.
Answer: You can set a short line width, a null indent and ragged-right to false. Then, each theme could be a simple, separate Score.
\paper {
  line-width=8\cm
  ragged-right=##f
  system-count=1
  indent=0\cm
}
\header {
  tagline =##f
}

\score {
  \new Staff \relative {
    \time 24/16 \clef treble \key g \major \tempo "Praeludium XV"
    g'16 b d g d b d b g b g d e g c
  }
}

\score {
  \new Staff  \relative {
    \time 9/8 \clef treble \key a \minor \tempo "Praeludium XX"
    a'16 b c8 e c a e a c e b16 c d8 f
  }
}

Result of the above is


How to keep index in pandas pivot table

Question: Suppose I create a pandas pivot table:
  adults_per_hh= pd.pivot_table(data,index=["hh_id"],values=["adult"],aggfunc=np.sum)
  adults_per_hh.shape
  (1000,1)

I want to keep hh_id as a column in addition to adult. What is the most efficient way to do this?
Answer: I think you need reset_index if use pivot_table, because first column is index:
print (data)
   adult  hh_id
0      4      1
1      5      1
2      6      3
3      1      2
4      2      2

print (pd.pivot_table(data,index=["hh_id"],values=["adult"],aggfunc=np.sum))
       adult
hh_id
1          9
2          3
3          6

adults_per_hh= pd.pivot_table(data,index=["hh_id"],values=["adult"],aggfunc=np.sum)
                .reset_index()
print (adults_per_hh)
   hh_id  adult
0      1      9
1      2      3
2      3      6

Another solution is use groupby and aggregate sum:
adults_per_hh = data.groupby("hh_id")["adult"].sum().reset_index()
print (adults_per_hh)
   hh_id  adult
0      1      9
1      2      3
2      3      6

Timings:
#random dataframe
np.random.seed(100)
N = 10000000
data = pd.DataFrame(np.random.randint(50, size=(N,2)), columns=['hh_id','adult'])
#[10000000 rows x 2 columns]
print (data)

In [60]: %timeit (pd.pivot_table(data,index=["hh_id"],values=["adult"],aggfunc=np.sum).reset_index())
1 loop, best of 3: 384 ms per loop

In [61]: %timeit (data.groupby("hh_id", as_index=False)["adult"].sum())
1 loop, best of 3: 381 ms per loop

In [62]: %timeit (data.groupby("hh_id")["adult"].sum().reset_index())
1 loop, best of 3: 355 ms per loop

Comment: I don't want 1000 columns. I want 2 columns, 1 column for the hh_id, and one column for the count of adults.
Comment: I add timing, it seems `groupby` with `sum` and reset_index is the fastest.

How to keep index in pandas pivot table