Combinatorics problem - Amount of basketball teams

Question: The question goes as follow:
A basketball team of five players must be selected from among $12$ players.
The players are first divided into two groups of six in each, of which
you must choose three from group $1$ and two from group $2.$
a) How many different teams can be selected from among the $12$ players.
b) How many teams do not contain both the weakest and the strongest player?
My solution for a):
Choose $3$ from group $1$: $\binom63 $(sorry I don't know how to do the symbol)
Choose 2 from group 2: $\binom62$
Total: $\binom63 \times \binom62 = 300 $ teams.
My solution for b):
Split into cases:
1.) Both players in group 1: $\binom{4}{3}\times\binom62=60$ teams
2.) Both players in group 2: $\binom63 \times \binom42 =120$ teams
3.) Players in different groups: $\binom53 \times\binom52=100$ teams
Total: $60 + 120 + 100 = 280$ teams
Basically I got it wrong for both a) and b) and I can't seem to figure out why. Any solution or help to this problem?
Comment: The way that I would interpret the problem statement is that you are allowed to divide the 12 players into two groups of 6 in any way that you like, not just a single specified way.  In this case, the initial step of dividing the team in half is a red herring and the solution to (a) is 12 choose 5.  That's just my interpretation though.
Comment: You can produce $\binom{n}{k}$ by typing `$\binom{n}{k}$`.  This [MathJax tutorial](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) explains how to typeset mathematics on this site.
Answer: There are , unfortunately, various ways to interpret the question. The interpretation I am taking (based on mention of Group 1 and Group2) is that the 12 are divided, once for all, into two distinct groups (eg people being allotted hostels, for instance) and that remains fixed.
In other words, if A,C,D,F,G,H have benn allotted to Group 1, that's it, you can't say that Group 1 could instead have been A,B,C,D,E,F
On this premise, you can't ignore the initial division into groups.
Ways to form Gr $1 = \binom{12}{6}$, Gr $2$ automatically formed
(a): Ways to form teams $= \binom{12}6\binom63\binom62 =277 200$
(b):
A better strategy would be to exclude from the total computed above, teams having  both the "marked" players, dividing into cases as you have done
Comment: I think this is still not correct.  If ${12 \choose 5} = 792$, then how can there be 277200 ways to form teams?  Given your interpretation of the problem, I would say that leun did the problem correctly and that the solution is ${6\choose 3}{6 \choose 2} = 300$.  You would not need to multiply by ${12 \choose 6}$ if the initial groups are set in stone.
Comment: @ChrisDuerschner: U agree with you that the. question is very poorly worded, But bear in mind that OP says that his answers (going by your interpretation) have been marked wrong.
Comment: Thanks for the response. But basically on b) coudn't I do the same as you've done here? I just mulitply every case by $\binom{12}{6}$. And then add all the cases together as I've done.

Also @ChrisDuerschner I agree that the task is poorly worded but basically we don't have an inital determined set of two groups and maybe thats why I got it wrong
Comment: Also by the way the answer seems extremely odd to me even though somehow the idea makes sense. $\binom{12}{5}$ should be the maxiumum amount of possible teams to ever create. I can't seem to understand how there could be 277200 ways to create this team
Comment: @leun: I know the whole thing appears strange, but **given** that both your answers were marked wrong, the only other possible idea that struck me was that a person is identified  by name as well as the team, which means if Jane is on team $1$, she is $J1$, and if on team $2, J2$. (Note that this sidesteps the question of overcounting, too)
Answer: I believe that true blue anil's solution 'double counts' many teams.  To see why, consider a simpler case of the problem with only a three player team being selected from a set of six players.  Let's call the players A, B, C, D, E, and F.  One way to choose a team would be to initially divide the players according to (A,B,C) and (D,E,F) then, choosing A and B from the first group and D from the second group, arrive at the team (A,B,D).
However you could also initially group the teams according to (A,C,D) and (B,E,F). Then, choosing A and D from the first group and B from the second, arrive at the same team as before.
If you are allowed to initially divide the 12 players at will, instead of being presented with an already chosen initial grouping, then the solution to (a) is just ${12 \choose 5}$ - the total number of teams.
The other way I know that 277200 is not the correct answer to (a) is that it is greater than ${12 \choose 5} = 792$.  The number of possible teams that you get by initially grouping, then choosing 3 and 2 from the groups cannot be greater than the number of teams you would get by just choosing 5 players from the 12 without initial grouping.
EDITING again to address part (b) - note my previous edit was incorrect, and that this answer also labors under the assumption that the initial grouping is not predetermined.
So we need to subtract from the total number of teams the teams that have both of two specific players.  The number of teams we should subtract in this case is ${10 \choose 3} = 120$, so the solution would be 792-120=672.  Why?  Suppose we exclude the two players from the initial group of 12, leaving only 10 players left.  Then, we need to count the number of teams we could create with only 3 players.  Then, if we just tack the 2 excluded players onto these teams, we have every possible team with both of the excluded players.  In general, if 'n' is the number of players to choose from, 'k' is the size of the teams, and 'a' is the number of players we need to exclude, then the number of teams that don't have the excluded players is ${n\choose k} - {n-a \choose k-a}$.
Comment: Maybe we should consider (A,B,C,D,E) is not similar to (B,C,D,E,A), because we choose Center , then Post-guard, then ... ... ; it is the only reason I can find if we say that answer 300 for Question 1 is wrong.  For question 2, the constraint is not to exclude teams with Best or Worst, but to exclude Teams with both (Best+Worst).
Comment: Yeah, I realized that I misunderstood part (b), so I deleted that part of my answer.  As for caring about order... that seems a little far fetched, but I agree that if the initial order is predetermined then the answer should be 300.


R chi square test with degrees of freedom

Question: Does anybody know of a chi-square test function in R for which you can specify the degrees of freedom?
Example: I want to test if the Hardy-Weinberg distribution holds true for a sample of the MN blood group.
M <- 3156
MN <- 4997
N <- 1847
FM <- 2*M + MN
FN <- MN + 2*N

indiv.num <- M + MN + N
alleles.num <- (M + MN + N) * 2
alleles.num
p <- FM / alleles.num
q <- FN / alleles.num

M.exp <- p^2 * indiv.num
M.exp
MN.exp <- 2*p*q * indiv.num
MN.exp
N.exp <- q^2 * indiv.num
N.exp

chisq.test(c(M, MN, N), c(M.exp, MN.exp, N.exp))

chisq.test automatically calculates df=4:
    Pearson's Chi-squared test

data:  c(M, MN, N) and c(M.exp, MN.exp, N.exp)
X-squared = 6, df = 4, p-value = 0.1991

But this is not applicable for this case: df must be one, since
from the frequency of one allele the frequency of the other allele is known.
Comment: I think you need to tell us more about your data and why you think you need 1 df. You may be trying to solve this using the wrong test / model.
Comment: Not so sure but, maybe [this](https://stat.ethz.ch/R-manual/R-devel/library/stats/html/Chisquare.html) one.
Answer: The question is about testing for Hardy-Weinberg equilibrium.  Genetically, that's the condition that the two alleles at a locus are independent. Statistically, its the condition that the number of alleles of each type for an individual has a Binom$(2,p)$ distribution.
In this case, the $M$ group has MM genotype and the $N$ group has NN genotype (would have been helpful to say this up front).
So the test is for $(M,MN,N)$ being the counts of the 0,1,2 outcomes from a Binom$(2,p)$ distribution (with estimated $p$) vs the alternative of a general trinomial distribution.
chisq.test() is not ideally suited to this: it's designed for either a contingency table or a fixed set of probabilities.
The data
> M <- 3156
> MN <- 4997
> N <- 1847

Estimate $p$
> FM <- 2*M + MN
> FN <- MN + 2*N
>
> indiv.num <- M + MN + N
> alleles.num <- (M + MN + N) * 2
> alleles.num
[1] 20000
> p <- FM / alleles.num
> q <- FN / alleles.num

Work out the expected counts
> M.exp <- p^2 * indiv.num
> M.exp
[1] 3197.337
> MN.exp <- 2*p*q * indiv.num
> MN.exp
[1] 4914.326
> N.exp <- q^2 * indiv.num
> N.exp
[1] 1888.337

And now, finally, the test
> chisq.test(c(M, MN, N), p=c(M.exp, MN.exp, N.exp), rescale.p=TRUE)

    Chi-squared test for given probabilities

data:  c(M, MN, N)
X-squared = 2.8302, df = 2, p-value = 0.2429

The test statistic is correct, but the df isn't (because the function doesn't know there's an estimated parameter)
The $p$-value you want.
> pchisq(2.8302,df=1,lower.tail=FALSE)
[1] 0.09250684

It would be easier to just compute the statistic yourself
hwe<-function(AA,Aa,aa){

  Npeople<-AA+Aa+aa
  af<-(2*aa+Aa)/(2*Npeople)

  est.p <-dbinom(0:2, 2,af)

  chisq<-sum((c(AA,Aa,aa)-est.p*Npeople)^2/(Npeople*est.p))

c(chisq=chisq, p=pchisq(chisq,1,lower.tail=FALSE))
}

giving
> hwe(M,MN,N)
     chisq          p
2.83015688 0.09250932

(Going beyond diallelic markers or dizygotic species will take a little more effort)
Answer: I have the same problem. Using your code, if you calculate the chi-squared the hard way:
chisq_res <- ((M-M.exp)^2)/M.exp + ((MN-MN.exp)^2)/MN.exp + ((N-N.exp)^2)/N.exp

chisq_res = 2.83 and NOT 6. I think this is because the package expects contingency tables. But the genotype distribution is more complex.
Then, as suggested by machine, you can use:
p_val = pchisq(chisq_rs, df = 1, lower.tail = FALSE)

df = 3 (number of categories) - 1 (chi-squared) - 1 (because the genotype categories can be entirely defined by only 2 numbers, the third must add to the total).
Comment: You could also use `chisq.test` with the `p` argument specifying the probabilities.
Answer: If you want to know the p value for some chi-square value and a certain df you can find it out like that
# example
library(MASS)
tbl = table(survey$Smoke, survey$Exer)
chisq.test(tbl)
# here you see that for df= 6 p is 0.4828

chi_val <- chisq.test(tbl)$statistic
pchisq(chi_val,df= 6,lower.tail=FALSE)
# gives you the same p value

In your case with a chi-square value of 6 and df= 1 you can use pchisq(x= 6,df= 1,lower.tail=FALSE), which is 0.01430588. Here, I set Chi-square to $6$ with x= 6 and the degrees of freedom to $1$ by using df= 1 to match your example.
Please note that I am not sure what your code above is doing. Your variables are saying ".exp", but we do not need to provide expected values for the chisq.test function unless you await certain probabilities (See answer from Sal Mangiafico). This means if your question is whether chi-square for the frequencies c(M, MN, N) is significant, you can use chisq.test(c(M, MN, N)). But here df is 2 since the vector has length 3.
Comment: Can you elaborate how you can set df in that particular function? How does that work?
Comment: @user2974951 in `pchisq(6,df= 1,lower.tail=FALSE)` I set the degrees of freedom to $1$ by using `df= 1`. You can choose the df of interest for the `df` argument inside of `pchisq`. In this example, $6$ the chi-square value, which you can set, too. I add the exmplanation to the answer
Answer: It looks like you are trying to perform a chi-square goodness-of-fit test.  That's about all I can suss out, so I can't say the following is correct for your purposes.  In this case, the last line of your code could be replaced with the following.  My advice is to perform the desired test by hand, or to compare to a published example similar to yours, and then compare the R output to be sure the code is doing what you want.
Theoretical = c(M.exp  / sum(M.exp, MN.exp, N.exp),
                MN.exp / sum(M.exp, MN.exp, N.exp),
                N.exp  / sum(M.exp, MN.exp, N.exp))

Theoretical

chisq.test(c(M, MN, N), p= Theoretical)

Comment: Although it remains unclear why the OP is asking for df being 1.
Comment: The OP is doing a test for Hardy-Weinberg equilibrium, which is the condition that two alleles are independent.  Under HWE, the numbers of M alleles are Binom(2,p) for some p; as opposed to being just Multinomial(p1,p2,1-p1-p2). So it's a 1 df test.


Pesquisar se há ou não registro na array()

Question: $detalhes->pro_are_id = '["4","1","2","3","6"]'; // Dados foram gravados no banco atraés do json_encode()
$valor->are_id = 2;

if(!empty($detalhes) and isset($detalhes->pro_are_id)){
    $are_id = json_decode($detalhes->pro_are_id);
    if(array_search($valor->are_id, $are_id)){
        $existe = 1;
    }
}

O problema é que dentro do loop com todos os objetos selecionados ou 1 ou 2, ele exibe sempre faltando um.
Exemplo, se eu pesquisar pelo id 2,3,6 ele só vem o 3 e 4. O 2 já não exibe.
é sempre o primeiro id que não compara.
Como ajustar isto?
No conjunto geral é este:

Selecione uma ou mais áreas

<select id="select-multi" name="pro_are_id[]" data-placeholder="Escolha 1 ou +" multiple="" class="width300 select2-offscreen" tabindex="-1">
    <option>Selecione</option>
    <?php
        $existe = 0;
        foreach($listagem_area as $valor){
            if(!empty($detalhes) and isset($detalhes->pro_are_id)){
                $are_id = json_decode($detalhes->pro_are_id);
                if(array_search($valor->are_id, $are_id)){
                    $existe = 1;
                }
            }

    ?>
    <option value="<?php echo $valor->are_id; ?>" <?php if($existe==1) echo "selected"; ?> ><?php echo $valor->are_titulo; ?></option>
    <?php } ?>
</select>

Comment: O `array_search` retorna a chave da array encontrada, se ela for `0` o `if` entenderá como `false` (devido a fraca tipagem do PHP). Logo você deveria utilizar `array_search($valor->are_id, $are_id) !== false`, isto é um dos erros. Na verdade poderia utilizar o `in_array()` ou poderia utilizar o `array_intersect()` para obter os valores comuns em ambas as arrays.
Comment: O que é `$listagem_area`?
Answer: Isso provavelmente ocorre devido a tipagem fraca do PHP, o array_search retorna a chave da array que possui o valor indicado.
Portanto considere isto:
var_export( array_search(1, [1,2,3]) );
// 0

Isto é equivalente a fazer:
if(0){
   echo 'Nunca será exibido :(';
}

Isso é o que ocorre porque a array_search(1, [1,2,3]) é 0 que será "convertido" para um boolean como false, nunca será mostrado a mensagem.
Portanto altere para:
if(array_search(1, [1,2,3]) !== false){
   $existe = 1;
}

Neste caso o 0 é diferente de false (utilizando o  ===). Nesta condição ele existe. Se não existir o array_search retorna false e neste caso false === false logo não existe.
Teste isto.
Comment: Perfeitamente @Inkeliz obrigado, era isso. E entendi também sua explicação, simples e objetiva. Grato!


Migration Custom Plugin Return Value

Question: I have a migration and it is very simple. I have a CSV file of employee number and years of service. I have added the two fields to the users in the system and populate them when the users have been added. I now I have a yearly file to update the years of service value. I created the below Migration to import/update the seniority:
id: seniority_import
label: Seniority CSV file import
description: Seniority CSV file import
migration_group: timeoff
migration_tags:
  - seniority_timeoff
langcode: en
status: true
dependencies:
  enforced:
    module:
    - timeoff_seniority
source:
  plugin: csv
  track_changes: true
  path: "/Users/rfulcher/Downloads/Seniority2017-2.csv"
  keys:
    - EMPNO
  column_names:
    0:
      EMPNO: "Employee Number"
    1:
      SENIORITY: "Employee Seniority"
process:
  uid:
    -
      plugin: user_lookup
      source: EMPNO
      value_key: field_employee_id
      entity_type: user
      bundle: 1
      bundle_key: status
      ignore_case: true
    -
      plugin: skip_on_empty
      method: row
      source: uid
      message: 'no empno found'
  field_employee_id: {}
  field_seniority: SENIORITY
destination:
  plugin: entity:user
  overwrite_properties:
    - field_seniority

I also create the custom process plugin to lookup the uid of the user using the employee number
   <?php

namespace Drupal\timeoff_seniority\Plugin\migrate\process;

use Drupal\migrate\ProcessPluginBase;
use Drupal\migrate\MigrateExecutableInterface;
use Drupal\migrate\Row;

/**
 * Returns a user if exists.
 *
 * Example:
 *
 * @code
 * process:
 *   field_your_field_name:
 *     -
 *       plugin: your_plugin_name
 *       source: some_source_value
 * @endcode
 *
 *
 * @see \Drupal\migrate\Plugin\MigrateProcessInterface
 *
 * @MigrateProcessPlugin(
 *   id = "user_lookup"
 * )
 */
class UserLookup extends ProcessPluginBase {
  /**
   * {@inheritdoc}
   */
  public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {

    $user_uid = $this->getUserByEmpNo($value);

    if ($user_uid == FALSE){
      drush_print('usernotfound for ' . $value . ' returning 0');
      return 0;
    } else {
      drush_print('userfound:'.$user_uid.': for ' . $value);
      return $user_uid;
    }
  }

  protected function getUserByEmpNo($employeenumber) {

    $id = \Drupal::entityQuery('user')
                  ->condition('field_employee_id', $employeenumber)
                  ->execute();
    $users =  \Drupal\user\Entity\User::loadMultiple($id);

    if (!empty($users)) {
      foreach ($users as $user) {
        $update_id = $user->id();
        return $update_id;
      }
    } else {
      return FALSE;
    }
  }

  public function prepareRow($row) {

  }
}

The import runs and I find the uid and return the value but it is like the migration ignores it and skips the row.
Am I missing something. I have worked on this way too long and this should be simple but I must not be understanding how this is supposed to work or something. I am totally at a loss.
Simple csv file with just two fields empno, seniority. Nothing fancy. Any help with this would be appreciated, thanks very much.
Thanks
Comment: Welcome to Drupal Answers :) Where's it breaking down exactly? Have you verified that you're getting the expected results from your entity query, for example? Have you confirmed that the `value` is being passed through correctly? Without a bit more information as to where the problem lies, it's going to be difficult to advise without reproducing your whole migration (which people might not be willing to do). If you could add some information to the post which details what your own debugging has for you so far, that would be very useful and probably get you a quicker answer
Comment: The migration annotation is missing. Something like `/* @MigrateProcessPlugin( id = "user_lookup") */` on top of your class file.
Comment: @Hudri - I updated the post to include the whole file UserLookup.php.  Let me know if that is what you were referring to.  Thanks
Comment: @Clive - Thanks for commenting. I have verified that the value is getting past to the UserLookup class and the lookup is happening correctly. It is the return $user_uid; that is not happening. Actually, the return does not seem to work at all. I have tried returning other hard-coded numbers and it never goes back to migration.
Answer: I think the problem might be the source on the skip_on_empty plugin. It looks like you're trying to refer to the result of the previous plugin to obtain the destination uid; I don't think you can do that until after all plugins have run on the field.
Even if you can make that reference, there's a special syntax for referring to destination fields on the source side, which is an @ symbol plus the field name (e.g. '@uid').
A solution that should remove all doubt would be to load the uid in a fake field, and re-use it for the proper destination field. For example:
process:
  _uid:
    plugin: user_lookup
    source: EMPNO
    value_key: field_employee_id
    entity_type: user
    bundle: 1
    bundle_key: status
    ignore_case: true
  uid:
    plugin: skip_on_empty
    method: row
    source: '@_uid'
    message: 'no empno found'

Of course that might be wrong, and you may just have meant to use EMPNO instead of uid for the source, in which case you should just fix that and move the skip_on_empty plugin so it runs first, saving yourself DB queries with empty conditions.
Comment: I see what you are saying and I made the appropriate changes.  Your assumption is correct.  The import file has an employee ID and I am using that to get the actual uid of the user.  Then trying to pass that back to the migration to match up the user.  So I made the changes you suggested and the below is the result of the migration.
Comment: I had to double check somethings and also uninstall / reinstall the module and the import is now working.  Thanks very much for your assistance.
Comment: Great news, no problem!

Migration Custom Plugin Return Value


WebClient.DownloadFile(Address, FileName) Dúvida usando variável

Question: Bom, estou criando um sistema de atualização, e está dando erro em uma parte
WebClient web = new WebClient();
string DownloadVersion = web.DownloadString("https://drive.google.com/uc?authuser=0&id=1bpVdsyUj3oOn1gLbcVRE7uZjIczI5Yc_&export=download");
string UltimaVersao = DownloadVersion.Split('\n')[0];
string VersaoDessePrograma = Application.ProductVersion;

if (Convert.ToDecimal(VersaoDessePrograma) < Convert.ToDecimal(UltimaVersao))
{
    if (MessageBox.Show("Um novo update está disponivel!" + Environment.NewLine + "Você quer atualizar?", "Atualização", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
    {
        web.DownloadFile(DownloadVersion.Split('\n')[1], "Algoritmos 1.0.1.exe");
        MessageBox.Show("O programa foi baixado!" + Environment.NewLine + "O aplicativo será fechado.", "Atualização", MessageBoxButtons.OK, MessageBoxIcon.Information);
        System.Diagnostics.Process.Start(Application.StartupPath + @"\Algoritmos 1.0.1.exe");
        Close();
    }
}
else
{
    MessageBox.Show("O programa já está atualizado!", "Verificador", MessageBoxButtons.OK, MessageBoxIcon.Information);
}

Esse erro é o seguinte, quando eu coloco na linha web.DownloadFile na parte do fileName o seguinte código: Algoritmos 1.0.1.exe dá certo, normalmente. Mas quando eu utilizo a variável da última versão: Algoritmos " + UltimaVersao + ".exe, lança um erro.
Vai a imagem utilizando o código Algoritmos 1.0.1.exe:

Vai a imagem utilizando o código Algoritmos " + UltimaVersao + ".exe:

Por que acontece esse erro? Como resolver? Podem me ajudar? Grato!
Comment: Onde UltimaVersao = "1.0.1"
Comment: Lucas tem certeza que UltimaVersao não foi alterado? Tente usar um `MessageBox.Show(UltimaVersao);` ou `Console.Write(UltimaVersao)` pra ter certeza que o valor dessa variavel não tem caracteres como quebras de linha, tabulações, nulos ou outros sinais como `:` e `?`
Answer: Provavelmente isto:
 string UltimaVersao = DownloadVersion.Split('\n')[0];

Esta retornando algo que você não imagina, você provavelmente espera por algo como 1.0.1, mas talvez isto esteja retornando qualquer outra coisa, se fiz simplesmente isto:
MessageBox.Show(UltimaVersao);

ou
Console.Write(UltimaVersao);

Você verá que provavelmente deve haver caracteres não válidos, como:

Quebra de linhas (\n)
Retorno (\r)
Tabulação (\t)
Nulo (\0)
outros como não aceitos como: ? e :

Pois para criar arquivos nas pastas alguns caracteres não são permitidos, o que ocasionará o erro:

ArgumentException: Illegal characters in path.

Se parecer no MessageBox.show que esta "normal", algo como 1.0.1 então é porque deve ter alguma quebra de linha, pode experimentar remover todos com replace:
UltimaVersao = UltimaVersao.Replace(System.Environment.NewLine, "");

Ou então usar o .Trim:
UltimaVersao = UltimaVersao.Trim();

Mas se tiver receio de ter mais caracteres inválidos você pode usar Path.GetInvalidPathChars(); para limpar os caracteres inválidos


Como excluir todos arquivos JPG dentro de uma pasta usando PHP

Question: Tenho um script que importa fotos e cria miniaturas mini e medias dentro da pasta de cadastro e gostaria que depois que rodasse esse, ele apagasse as fotos originais.
A estrutura da pasta é assim:
<code>pasta_fotos
--original1.jpg
--original2.jpg
--pasta_miniatura
----mini1.jpg
----mini2.jpg
--pasta_medio
----medio1.jpg
----medio2.jpg
</code>
O que preciso é que no fim do script ele apague as fotos originais, ou seja, todas que estão dentro do pasta_fotos, mas não excluir as outras fotos nem as outras pastas.
Excluir apenas:
<code>--original1.jpg
--original2.jpg
</code>
Answer: Olha, você pode fazer da seguinte forma:
<code>$files = glob('pasta_fotos/original*.jpg'); // obtém as imagens que começam com o nome "original"
foreach($files as $file){ // percorre os arquivos encontrados
  if(is_file($file))
    unlink($file); // remove o arquivo
}
</code>
Acredito que seja o suficiente. Se pretente fazer algo mais avançado da uma lida sobre as funções glob do PHP.
Comment: Obrigado, isso mesmo!
Comment: só alterei o original* para apenas *, cada arquivo tem um nome diferente


Abrir uma guia diferente para cada link

Question: Olá!
Estou começando a aprender HTML agora e me deparei com a seguinte situação: ao selecionar um dos links do body abro uma nova guia e ao selecionar o outro link é aberta uma nova guia que substitui a anterior.
O comportamento que gostaria de reproduzir é que a cada link clicado fosse aberta uma nova guia.
Como posso fazer isso usando o html?
Obs.: Qualquer dica ou instrução de boas práticas é bem vindo.
Abaixo um código exemplo que estou usando.

<!DOCTYPE html>

        <meta charset = "UTF-8">
        <title>Exemplo 04</title>
        <link rel="icon" type="image/png" href = "icone.png"/>
        <base href = "http://www.w3c.org/"/>
        <base target="_blank/"/>

Título do conteúdo

Link - padrões: link

Link - google: link

Desde já grata!
Comment: Dá uma olhada aqui que pode te ajudar: https://pt.stackoverflow.com/questions/349963/diferen%c3%a7a-entre-blank-self-e-blank-self
Answer: Olá, tudo bem?
Também sou novo em HTML 5 mas creio que sei a resposta. Para abrir o link em uma nova guia, basta adicionar o atributo target="" dentro da tag , desta forma:

Link - padrões: link

Nesse caso, preenchemos o target com _blank para abrir o link em uma nova aba em branco (acho que daí que veio o nome).
O padrão, se você não especifica e não coloca _blank, é o _self, no qual o link abre na mesma página.
Eu uso o VSCode para programar e nele já mostra as diversas funcionalidades dentro do atributo target="", mas encontrei um artigo em inglês que fala sobre isso:
https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/target
Esse site de developers da Mozilla é muito bom (https://developer.mozilla.org/pt-BR/), eu recomendo pois além de uma boa documentação, existem alguns documentos em português do Brasil. Enfim, existem mais alguns usos para esse atributo, mas creio que para o que você está querendo fazer é isso. Espero ter ajudado!
Answer: Olá, boa tarde!
Basta que você adicione dentro da sua tag  o atributo target="_blank", assim:

Link - padrões: link

Desta forma você está dizendo ao navegador que ao ser clicado o hyperlink tem como alvo (target) um nova aba em branco (blank).
Seu código deve ficar assim:

<!DOCTYPE html>

        <meta charset = "UTF-8">
        <title>Exemplo 04</title>
        <link rel="icon" type="image/png" href = "icone.png"/>
        <base href = "http://www.w3c.org/"/>
        <base target="_blank/"/>

Título do conteúdo

Link - padrões: link

Link - google: link

Espero ter ajudado!
Bons estudos!

Abrir uma guia diferente para cada link


Qual é a diferença entre Settings e Resource?

Question: Settings salva as preferências do usuário para o esquema de cores de um aplicativo por exemplo e o Resource serve para a mesma coisa ?
Quando devo usar Settings e quando devo usar Resource na aplicação Winforms  ?
Answer: A grande diferença é que ao utilizar Resource após alterar algum valor, adicionar ou remover uma key, você precisa recompilar a aplicação. Então Resources deve ser utilizado para conteúdos mais "estáticos" como textos, labels e outros itens apresentados na UI, principalmente quando se tem variações de cultura (diversos idiomas). Ou seja, deve ser utilizado para a apresentação de recursos relacionados ao core da sua aplicação.
Já através de Settings você tem uma maior flexibilidade para configurações relativas a uma distribuição para customizações mais dinâmicas em relação à preferências do usuário ou do que você pretende alterar para um cliente em específico sem depender de uma redistribuição da sua aplicação. Aí entram outras variáveis do sistema, como: strings de conexão, mapeamento de diretórios e etc.
No seu caso, se o objetivo é permitir que o usuário escolha uma paleta de core pré-definida, esses temas podem estar no Resource e você guarda no Settings qual foi o tema escolhido.
Comment: Ele é compilado junto à aplicação
Comment: Onde fica armazenado o Resource ? Depois da instalação do software.


Big-O analysis of ratio of log

Question: Based on various trial-and-error in desmos, it seems like the following statement is true but kind of unsure about a formal proof.
Any helps/hints are appreciated.
Claim:
$$\forall \epsilon\in(0,1); \frac{\ln(\frac{n^2\epsilon^2}{n-1}+1)}{\ln(\frac{n\epsilon^2}{n-1}+1)}\in O(\frac{\ln(n)}{\epsilon})$$
Comment: Why not just say $O(\ln n)$ on the right?
Comment: what is $n\,\,$?
Comment: natural number at least 2
Comment: It involves the detail of the problem: $\epsilon$ is like a hyperparameter where can optimize an algorithm slightly better,
Comment: So you want a big O constant independent of $\epsilon?$
Comment: Yeah, that's true
Comment: I don't think you can do that.
Answer: De Facto way- even though writing $\epsilon$ in $\frac{\ln(n)}{\epsilon}$ is redundant.
For simplicity: $ \epsilon = t$
$$ f(n) = \frac{\ln( \frac{n^2 t^2}{n-1} +1)}{\ln( \frac{n t^2}{n-1} +1)}$$
We need to prove that $$ f(n) = O( \frac{\ln(n)}{t}) \\ \text{A.K.A} \\ \lim_{n \to \infty} \frac{f(n)}{ \ln(n) /t } \ne \infty$$
$$\lim_{n \to \infty}  \frac{f(n)}{\ln (n) / t} = \lim_{n \to \infty} \frac{t\ln( \frac{n^2 t^2}{n-1} +1)}{\ln( \frac{n t^2}{n-1} +1) \ln (n)} = t\lim_{n \to \infty} \frac{1}{\ln( \frac{t^2 n + n- 1}{n-1})} \cdot \lim_{n \to \infty} \frac{\ln ( \frac{t^2 n^2 + n - 1}{n-1})}{\ln(n)} $$
First limit is not that hard to calculate: $$\lim_{n \to \infty}\frac{1}{\ln( \frac{t^2 n + n- 1}{n-1})} =  \frac{1}{\ln(t^2 + 1)}$$
Second limit can be broken up into again, $2$ limits:
$$\lim_{n \to \infty} \frac{\ln ( \frac{t^2 n^2 + n - 1}{n-1})}{\ln(n)} = \lim_{n \to \infty} \frac{\ln(t^2 n^2 +  n-1) - \ln(n-1)}{\ln(n)} \\= \lim_{n \to \infty} \frac{\ln(t^2 n^2 +  n-1)}{\ln(n)} - \frac{\ln(n-1)}{\ln(n)} \\ = \lim_{n \to \infty} \frac{\ln(n^2(t^2 + t^{-1} - n^{-2}))}{\ln(n)} - \lim_{n \to \infty} \frac{\ln(n-1)}{\ln(n)}  \\ = \lim_{n \to \infty} \frac{2\ln(n) + \ln(t^2 + t^{-1} - n^{-2}))}{\ln(n)} - \lim_{n \to \infty} \frac{\ln(n-1)}{\ln(n)} = 2 - 0 -1 = 1$$
Thus this whole limit is equal to:
$$ \frac{1}{\ln(t^2 + 1)} $$
Which is not infinity as $t \ne 0$ as it is not in the interval $(0,1)$
Comment: Great analysis, super appreciate for the effort.
Comment: @laziestperson1 You are welcome!
Answer: Hint:

You can more easily say $O(\ln(n))$ here, because Big-O ignores multiplicative constants (and $\epsilon$ is a constant here).
The denominator clearly converges to a constant. So, you only need to worry about the numerator.
The inside of the logarithm is visibly asymptotic to $\epsilon^2n$. Try factoring $\epsilon^2n$ out (and using $\ln(ab)=\ln(a)+\ln(b)$ and easy limits) to rewrite this expression in terms of $\ln(n)$.

Big-O analysis of ratio of log


Migration SVN to Gitlab

Question: How can we migrate a project SVN to Gitlab ?
if we commit to SVN , will  be automatically change in gitlab  referenciel ?
Answer: All the information you need is located on the following page: GitLab Docs: Migrate projects to a GitLab instance.

Migration SVN to Gitlab


Keep dropdown menu open Bootstrap 2.3.2 on Rails 4.0

Question: I am using dropdown on Bootstrap 2.3.2 on Rails 4.0 and I am trying to keep the dropdown menu open even after clicking a button from the dropdown menu (so I only want it to close when I re-click the dropdown-toggle element)
I tried to follow the solution here https://stackoverflow.com/questions/14544741/angularjs-directive-to-stoppropagation#= to no avail...Below is what I tried to do on my html.erb to make it work. Please tell me what I am doing wrong or if you have a better working solution, let me know. Any hint would be much appreciated, thanks in advance!

    Dropdown

      <button type="button" class="btn btn-primary" data-toggle="button">
    </di>

Comment: Could someone please point me in the right direction? I really don't know what to d. If I need to post more things, let me know.
Answer: Shouldn't be the stop propagation applied to the clickable element itself ?

    Dropdown

      <button type="button" class="btn btn-primary" data-toggle="button">
    </di>

Comment: I already tried that, unfortunately, it doesnt work.....I even tried to just have it in the body of my layout (outside of any div tags besides its own) and it still doesn't work....I tried to recreate this fiddle (http://jsfiddle.net/Palpatim/vuNA7/3/) in my app as well to no avail. Maybe there's something wrong with my environment?? I can't really figure out what's wrong


Colocar data em arquivo gerado pelo mysqldump

Question: Olá, quero colocar data no arquivo gerado pelo mysqldump, tenho um script shell que gera o dump, porem necessito colocar a data que foi gerado no nome do arquivo
Ex:
//tenho este comando
mysqldump -uroot -p12345 base_diversos > base_diversos.sql

é gerado o arquivo "base_diversos.sql sem problemas", necessito que o arquivo fique com data no nome:
Ex:
mysqldump -uroot -p12345 base_diversos > base_diversos_25_02_2015.sql

como colocar no script as variaveis de data para ficar dinamico e gerar com a data atual que esta sendo feito o backup?
seria algo como:
Ex:
mysqldump -uroot -p12345 base_diversos > base_diversos_%d_%m_%Y.sql

já tentei varias maneiras e da erro.
Obrigado
Answer: Por expansão do comando date:
base_diversos_$(date +%d_%m_%Y).sql

Na man page do date (man date) tem a lista dos formatos possíveis.
Comment: Funcionou certinho, tmb vi a documentação sobre a função tiha tudo lá mas não como vc descreveu. Obrigado pela ajuda.
Answer: mysqldump -hlocalhost -uroot -proot test_111 > "C:\Users\USER_2\Desktop\backup folder\test_111_%date:~-4,4%%date:~-10,2%%date:~-7,2%_%time:~0,2%%time:~3,2%%time:~6,2%.sql"


why $\int{\cos({\pi}t)} dt = \frac{1}{\pi}\sin({\pi}t)$?

Question: Why?
$$\int{\cos({\pi}t)} dt = \frac{1}{\pi}\sin({\pi}t)$$
the indefinite integral of $ \cos(x) = \sin(x) $ isn't it?
so this suppose to be $$\int{\cos({\pi}t)} dt = \sin({\pi}t)$$
Why in the video at the minute 3:50 (https://www.youtube.com/watch?v=EuWaisQj3hU&index=29&list=PLF5E22224459D23D9) the professor says the first one?
Am I missing something?
please explain to me step by step and in detail. Thank you very much.
Comment: Try a change of variables. Set $u = \pi t \implies du = \pi dt \implies \frac{du}{\pi} = dt$ and integrate over $u$. Alternatively, use the chain rule to differentiate $$\frac{\sin(\pi t)}{\pi}$$ and see what you get.
Comment: It would be what you're saying if differentiation was done with respect to piT, but it isn't. It's an application of the chain rule. Differentiating sin(piT) gives picos(piT) ... But we only want sin(piT) so we divide by pi,
Comment: When something new is "added" we can assume the old rules will work, but often they don't work meaning there's more going on than we know. One way to think is to always remember that the rules we know at present are some special case of more general rules. So e.g. your statement $\int\cos(x)dx=\sin(x)+C$ is a special way of writing $\int\cos(1\cdot x)=\sin(x)+C$, but what if the $1$ were some other number $a$. What general rule is there to handle such cases? It's not as straight forward as the case when $a=1$.
Answer: Use $u$-substitution, let $u = \pi t$, then
$$\int \cos(\pi t)\,dt = \int \cos(u)\cdot\frac{1}{\pi}\,du = \frac{1}{\pi}\sin(\pi t)+C$$
To check your work, you can take the derivative of the RHS to check that it matches the integrand:
$$\left(\frac{1}{\pi}\sin(\pi t)+C\right)' = \frac{1}{\pi}\cos (\pi t)\cdot \pi+0 = \cos(\pi t),$$
which matches the original integrand.
In fact, he explicitly says to take the derivative of "something" and that should match the integrand. That "something" is
$$\frac{1}{\pi}\sin(\pi t)+C.$$
Remember that the derivative of a constant is zero.
Answer: The derivative $f'(x)$ is the slope of the tangent at point $x$ to the curve $y=f(x)$. If you change $x$ into $\pi x$, you are shrinking the curve : for instance $\sin(\pi x)$ oscillates $\pi$ times faster that $\sin(x)$. This is why the factor $\pi$ is necessary : the slope of the tangent is $\pi$ times larger.
Answer: Since you are asking why:
Due to chain rule, when we differentiate $\sin\pi t$ wrt $t$, we get an additional constant $\pi$ which is the coefficient of $t$
$$\dfrac{d(\sin\pi t)}{dt} = \cos\pi t \cdot \pi$$
So when we differentiate $\dfrac{\sin\pi t}{\pi}$ wrt $t$, we get $\cos\pi$
$$\dfrac{d}{dt}\left(\frac{\sin\pi t}{\pi}\right) = \cos\pi t $$
hence $$\int \cos(\pi t) \ dt = \frac{\sin\pi t}{\pi} + C$$
Answer: $\int \cos \left(\pi x\right)dx$

$\mathrm{Apply\:Integral\:Substitution:}\:\int
> f\left(g\left(x\right)\right)\cdot g^{'}\left(x\right)dx=\int
> f\left(u\right)du,\:\quad u=g\left(x\right)$ $u=\pi x\quad \:du=\pi
> dx$
$\mathrm{Substitute:}\:u=\pi x$
$\frac{du}{dx}=\pi $
$\frac{d}{dx}\left(\pi x\right)$
$\mathrm{Take\:the\:constant\:out}:\quad \left(a\cdot
> f\right)^{'}=a\cdot f^{'}$
$=\pi \frac{d}{dx}\left(x\right)$
$\mathrm{Apply\:the\:common\:derivative}:\quad
> \frac{d}{dx}\left(x\right)=1$
$=\pi 1$
$\mathrm{Simplify}$
$=\pi $
$\Rightarrow \:du=\pi dx$
$\Rightarrow \:dx=\frac{1}{\pi }du$
$=\int \cos \left(u\right)\frac{1}{\pi }du$
$=\int \frac{\cos \left(u\right)}{\pi }du$
$=\int \frac{\cos \left(u\right)}{\pi }du$

$=\int \frac{\cos \left(u\right)}{\pi }du$

$\mathrm{Take\:the\:constant\:out}:\quad \int a\cdot
> f\left(x\right)dx=a\cdot \int f\left(x\right)dx$

$=\frac{1}{\pi }\int \cos \left(u\right)du$

$\mathrm{Use\:the\:common\:integral}:\quad \int \:\cos
> \left(u\right)du=\sin \left(u\right)$

$=\frac{1}{\pi }\sin \left(u\right)$

$\mathrm{Substitute\:back}\:u=\pi x$

$=\frac{1}{\pi }\sin \left(\pi x\right)$

$\mathrm{Simplify}$

$=\frac{\sin \left(\pi x\right)}{\pi }$

$Add\:a\:constant\:to\:the\:solution$

$=\frac{\sin \left(\pi x\right)}{\pi }+C$


Are whole and half note rests supposed to only be written on specific lines?

Question: I've always written the whole note rest on the 4th line of the staff and the half note rest on the 3rd. I always see it that way and never thought much about it until recently a musician with a lot more experience than me wrote them on different lines and when I pointed it out that person said that it didn't matter and they could just be written on any line.
I was left wondering if this was true or not. Personally I see no reason to write them anywhere else, since I think it would be pointless and maybe confusing. I'm asking about the correct notation. Do these rests belong on specific lines or not?
Answer: Yes, whole and half rests should always be pointing into the third space on the staff.  As Dr Mayhem notes, it's standardized for ease of reading.  They don't mean anything different if you place them elsewhere, but there's no point in moving them elsewhere unless you want to confuse people.  Your experienced acquaintance should recognize that it takes no extra effort to draw them in the right place!
I would expect to have been docked marks on my theory exams had I drawn rests on the wrong lines.  All notation is arbitrary, of course, but if placement doesn't matter then why not draw the note stems on the left side of the note instead of the right?  And so on.  Conventions exist to enable and enhance communication, and I see no reason to forgo them when the alternatives offer no benefit.
As noted in the comments, multiple voicings are one good reason to adjust the position of rests.
Comment: Note that multiple voices on the same staff can become an exception to the general rule of where to place the whole and half rests; in those cases, you would essentially place them for clarity.  Realistically, you would not likely be using a whole rest in that context, though.  And, yes, as a theory instructor, I deducted points for nonstandard notation.
Comment: Sometimes you can see these rests even outside of the staff. They look like short top hats.
Comment: Indeed, I'm all for exceptions when they make things *better*!
Answer: The rests belong on specific lines to conform to the standards that most sight-readers would expect, but to expand on the case of different voices on a staff...
If you are asking one of the two parts on a staff to drop out for a few measures (rather than to be in unison with the other part), it's normal to indicate this by having whole bar rests either higher than the notes of the other part (part 1 drops out) or lower (part 2 drops out).
I often come across this in vocal scores where you have either soprano and alto or tenor and bass on one staff, and in orchestral conductor's scores where multiple players (such as flute 1 and 2) share a staff.
Comment: Hey! In the situation I was in it was a sigle voice, but thank you for mentioning a case where it does make sense, since I hadn't thought of that and it might be interesting to somebody else in the future. Wish I could merge this with @Matthew's answer!!
Comment: For cases where a voice drops out for many measures, it may be better to simply have a notation "Altos only" or "Soprano tacet until measure 37", but if voices are entering and leaving frequently, using rests is often clearer.
Answer: It's not really going to matter where they are written, as they have no note associated, however if I was sight reading a fast piece I would want them to be in the standard place to speed up my reading and hopefully prevent confusion.
Comment: Notational conventions do exist; certainly the meaning would not change, but if there is no reason (like multiple voices per staff) to change the convention, one should not do so.  In that sense, it does matter where the rests are written, and it is at least technically incorrect to do otherwise.


Order comments by thread path and by number of total votes

Question: I'm having some trouble ordering comments by their thread path and by number of upvotes of each comment.
Now they are only ordering by thread path. I've tried and searched a lot of things but nothings results.
This is my query
WITH RECURSIVE first_comments AS (
(
 (
   SELECT id, text, level, parent_id, array[id] AS thread_path, total_votes FROM comments
   WHERE comments."postId" = 1 AND comments."level" = 0
 )
)
UNION
 (
  SELECT e.id, e.text, e.level, e.parent_id, (fle.thread_path || e.id), e.total_votes
  FROM
  (
    SELECT id, text, level, parent_id, total_votes FROM comments
    WHERE comments."postId" = 1
  ) e, first_comments fle
  WHERE e.parent_id = fle.id
 )
)
SELECT id, text, level, total_votes, thread_path from first_comments ORDER BY 5 ASC

This query results in:
--------------------------------------------------
| id  | level  | total_votes |    thread_path    |
--------------------------------------------------
| 1   |   0    |      5      |  {1}              |
| 3   |   1    |      9      |  {1,3}            |
| 7   |   2    |      5      |  {1,3,7}          |
| 9   |   2    |      7      |  {1,3,9}          |
| 11  |   3    |      0      |  {1,3,9,11}       |
| 12  |   4    |      0      |  {1,3,9,11,12}    |
| 13  |   5    |      0      |  {1,3,9,11,12,13} |
| 10  |   1    |     20      |  {1,10}           |
| 2   |   0    |     10      |  {2}              |
| 6   |   1    |      1      |  {2,6}            |
| 4   |   0    |      8      |  {4}              |
| 8   |   1    |      6      |  {4,8}            |
| 5   |   0    |      3      |  {5}              |
--------------------------------------------------

And the result should be
--------------------------------------------------
| id  | level  | total_votes |    thread_path    |
--------------------------------------------------
| 2   |   0    |     10      |  {2}              |
| 6   |   1    |      1      |  {2,6}            |
| 4   |   0    |      8      |  {4}              |
| 8   |   1    |      6      |  {4,8}            |
| 1   |   0    |      5      |  {1}              |
| 10  |   1    |     20      |  {1,10}           |
| 3   |   1    |      9      |  {1,3}            |
| 9   |   2    |      7      |  {1,3,9}          |
| 11  |   3    |      0      |  {1,3,9,11}       |
| 12  |   4    |      0      |  {1,3,9,11,12}    |
| 13  |   5    |      0      |  {1,3,9,11,12,13} |
| 7   |   2    |      5      |  {1,3,7}          |
| 5   |   0    |      3      |  {5}              |
--------------------------------------------------

What I'm missing here...?
Thank for the help
Comment: I removed the MySQL tag because MySQL does not support recursive CTEs.
Comment: Aren't you supposed to do a `ORDER BY 4,5` or `ORDER BY 5,4` ?
Comment: I must admit I don't see the progression in the sought result set though.
Comment: I think I understand: ordering by path results the replies come after the comments, which was "replied to". But you want to sort the comments on the same level (top level or the comments, which is replied to the same comment) by `total_votes`?
Comment: @Gordon, thank you but **pozs** really nailed it. Just one more question do you think the title it's appropriate? I found really hard searching this terms
Comment: Right, I was staring at the last columns, without thinking about the meanings of paths (you should call them `thread_path` perhaps?). Now I understand.
Comment: @didierc you're right. Already changed it! thanks
Answer: Just accumulate another array next to path, witch will contain not just the id of each comment in its path, but the total_votes (as a negative number) before each id. After that, you can order by that column.
WITH RECURSIVE first_comments AS (
(
 (
   SELECT id, text, level, parent_id, array[id] AS path, total_votes,
          array[-total_votes, id] AS path_and_votes
   FROM comments
   WHERE comments."postId" = 1 AND comments."level" = 0
 )
)
UNION
 (
  SELECT e.id, e.text, e.level, e.parent_id, (fle.path || e.id), e.total_votes,
         (fle.path_and_votes || -e.total_votes || e.id)
  FROM
  (
    SELECT id, text, level, parent_id, total_votes FROM comments
    WHERE comments."postId" = 1
  ) e, first_comments fle
  WHERE e.parent_id = fle.id
 )
)
SELECT id, text, level, total_votes, path from first_comments ORDER BY path_and_votes ASC

SQLFiddle (only data -- without the recursive CTE)
Answer: You want to order by the total votes at the top level.  I think I'll approach this by by using a window function.
Instead of:
SELECT id, text, level, total_votes, path
from first_comments
ORDER BY 5 ASC;

which explicitly orders by the path.  Try this:
select id, text, level, total_votes,
       max(total_votes) over (partition by path[1]) as toplevel_votes
from first_comments
order by 6 desc;

This calculates the total votes at the top most level and uses that for ordering.


Usando jQuery, como selecionar elementos com duas classes CSS

Question: Tenho uma div que usa duas classes CSS.
Eis o HTML :

Quero selecionar a div que tenha as classe box1 e destaque (no meu exemplo a segunda div) apenas.
O que já tentei :
Se faço : $('.box1') seleciono as duas divs com classe box1. Não é o que quero.
E se faço : $('.destaque') acabo selecionado uma div com box1 e outra com box2 (o que não quero)
Já tentei $('.box1 .destaque') mas não seleciona nada.
Então como devo montar o seletor jQuery para buscar as divs que usam as classes box1 e destaque?
Answer: Tira o espaço:
$('.box1.destaque')

http://jsfiddle.net/2w9x7/
Comment: uhul! Já imaginava que era algo simples. Valeu!
Answer: No caso de ser só div com .box1 e .destaque:
$('div.box1.destaque');

Na ordem dos seletores, o primeiro pode ser o elemento desejado, no exemplo div em seguida você vai especificar algumas características do elemento:

# para ID
. para classes
[] para atributos, exemplo: [rel=teste] seleciona

No final é possível usar o : para pseudo seletores (estado, como :hover, :active, etc ou primeiro filho, impares, etc)
Quando você adiciona o espaço no seletor, ele identifica que você está querendo ir para o próximo nível, então agora são elementos filhos da caracteristica que você está buscando.
Então $('.box1 .destaque'); vai achar isso:

 <-- este elemento foi o único selecionado

Answer: Quando você diz que um elemento tem várias propriedades tanto no css quanto no jquery você insere todos os seletores e pseudo classes juntos
Exemplo:
#id.classe1.classe2[atributo=valor] {
    display: inherit;
}

O exemplo acima corresponderia a um elemento assim:
elemento

Se você separar por espaço você está procurando um elemento que contém
o outro.
 Exemplo:
#id .classe1 .classe2 [atributo='valor'] {
    display: inherit;
}

O exemplo acima corresponderia a um elemento assim:

            elemento

Answer: Ao informar o seletor: .box1 .destaque você procura por a classe .destaque dentro de .box1. Como o elemento que você deseja selecionar possui ambas as classes, o seletor correto é:.box1.destaque, que iria retornar:

Espero ter ajudado.
Answer:

$(".box2.destaque").html('Class 1');
$(".box1.destaque").html('Class 2');
.box1{
  color: red;
}

.box2{
  color: blue;
}


Question about convergence of matrices (Linear algebra)

Question: Let $O(n)$ to be the orthogonal group, and define $m(A)$ for every $A \in O(n)$ as follows:
$$m(A) = \max \left\{ \frac{|Ax-x|}{|x|} : x \in \mathbb{R} ^ n -\{0\} \right\}\;.$$
Given a sequence $ \{B_i \}$ , we can assume by compactness that it converges.
Why does this imply that for every $\epsilon>0$  there exist $i<j$ such that $m(B_j B_i^{-1} )\leq \epsilon $ ?
Thanks in advance
Answer: Suppose $B_i \to L$ as $i \to \infty$. Since both multiplication and inverse are continuous, as $i \to \infty$ and $j \to \infty$ we have $B_j B_i^{-1} \to L L^{-1} = I$.  Now $m$ is continuous (note that by homogeneity we may take $x$ to be in the unit sphere which is compact), and $m(I) = 0$.


What will end up in the variable y after this code is executed (Python) ?

Question: Could someone explain to me this silly question ?
x , y = 3, 4

Is it going to be a list or a tuple after this execution of the code above?
Answer: You could just run it in python interpreter to find out. Anyways, it wont be list, x and y will end up with respective scalar values
Python 2.7.6 (default, Mar 22 2014, 22:59:56)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> x, y = 3,4
>>> x
3
>>> y
4

To create x and y as list/tuple in single line you can assign

Tuple x = y = (3,4)
List x = y = [3,4]
Answer: it will only set x = 3 and y = 4. I think this feature is called unpacking. It's really neat and lets you do some interesting things. For instance, you can have a function that returns a tuple of 3 different items, which can be set to 3 different variables:
def upack_example():
    return({}, [], 3)

a, b, c = unpack_example()

Comment: I think you thought right:   >>> x, y = 1, 3, 4
        Traceback (most recent call last):
          File "", line 1, in
        ValueError: too many values to unpack, the exception said it ;)


Activating a player from Injured Reserve/Designated To Return

Question: The NFL allows one player per team per year to be placed on the IR and be marked as designated to return.
What does the return process look like?  How long must they be on IR, and how soon must they be activated?  What are they allowed to do while still on IR (ie practice)?
Answer: In football, there is IR (Injury Reserve) and IR/Designated for Return. This new IR/Designated for Return was created in 2012 to allow a team to put one player on IR that is eligible to come back during the season.
The team can put a player on the IR/Designated for Return list only if...

The player was on the team's final 53-man preseason roster
The player's injury will prevent him from practicing or playing football for an estimated 6 weeks

The player then will be allowed to practice with the team after 6 weeks and can be activated after 8 weeks.
When activated, the team must make room for him on the 53 man roster. This can be done by trading or waiving a current rostered player
Source
Comment: Can you elaborate a bit?  Is there a time they must be activated by?  What can they do while still not activated?
Comment: @BradKoch Just edited my post to explain a bit more
Comment: Cool, could you leave this person sitting on the IR for, say, 9 weeks, if you didn't want to open a roster spot just yet?
Comment: FYI, Mark Sanchez is on "short-term" IR, which is ~8 weeks long. http://profootballtalk.nbcsports.com/2013/09/14/jets-place-mark-sanchez-on-short-term-injured-reserve/
Comment: @BradKoch It seems so yes. Though it would not make sense because the only reason you would put someone on this list is so that you can get the player back as soon as possible


How do I know if the autovacuumer in postgres 8.3 is actually working?

Question: I have a couple of postgres 8.3 databases, and they are showing symptoms of lack of vacuuming.
I've checked the config, and they are in the default state of having the autovacummer turned on.  Also, I see in my postgres logs "autovacuum launcher started" when I start the database.
The problem is, I never actually see a vacuum running.  I also never see anything in the logs about a vacuum taking place (should I be seeing anything?)
So how do I tell if the vacuumer is working?  Is there a way to see when the last vacuum completed, for example?  Better yet, is there some documentation someone can point me to with the answer to that question?
Thanks!
Answer: pg_stat_user_tables has columns last_autovacuum and last_autoanalyze. They will be updated whenever it does something.
Comment: Awesome, that was exactly what I was looking for!  Incidentally, everything is being vacuumed as expected.
Answer: At a higher level, PgSnap is your friend ;-)
Here is un example of last vaccuum report
Answer: Google is your friend, and www.postgresql.org even greater:
18.9. Automatic Vacuuming
log_autovacuum_min_duration (integer)
Causes each action executed by autovacuum to be logged if it ran for at least the specified number of milliseconds. Setting this to zero logs all autovacuum actions. Minus-one (the default) disables logging autovacuum actions. For example, if you set this to 250ms then all automatic vacuums and analyzes that run 250ms or longer will be logged. Enabling this parameter can be helpful in tracking autovacuum activity. This setting can only be set in the postgresql.conf file or on the server command line.
Comment: Thanks!  That is the doc for postgres 8.4, but it appears to apply to 8.3 as well.  The only reason I didn't accept your answer is because I didn't have to restart with Magnus's answer, but it they let me, I would have accepted your answer too. :)
Comment: No problem :) It was anyway easy to find in the docs :)


How to enable insert module in installation profile?

Question: I want to use the insert module for a file field but I can't get it to be enabled programmaticly. Is there a setting like 'insert' => true, or something like that? Is there any documentation about the these settings because I can't seem to find any info on the web?
Comment: @Mołot Well the point of an installation profile is to preset settings etc. I always use an attachment field with insert. So that is why I want to enable it programatically so I don't have to do this everytime I make a new site. I know how to make the fields using field_create_field, my question is now how do I enable this kind of settings.
Comment: Why do you need to enable it programatically?
Answer: You can enable insert by updating the field instance settings with these two core functions:

field_info_instance
field_update_instance

for example:
/**
 * Enable insert field settings
 */
function MODULE_field_settings_enable_insert($entity_type, $field_name, $bundle){
  // Load field instance
  $instance = field_info_instance($entity_type, $field_name, $bundle);
  // Build insert settings array, these image styles are just examples
  $insert_settings = array(
    'insert' => 1,
    'insert_absolute' => 1,
    'insert_styles' =>
    array (
      'image_236w' => 'image_236w',
      'image_237x147' => 'image_237x147',
      'image_486w' => 'image_486w',
      'colorbox__236w' => 'colorbox__236w',
      'colorbox__237x147' => 'colorbox__237x147',
      'colorbox__486w' => 'colorbox__486w',
      'auto' => 0,
      'link' => 0,
      'icon_link' => 0,
      'image' => 0,
      'image_60x60' => 0,
      'image_62x62' => 0,
      'image_62x82' => 0,
      'image_67x67' => 0,
      'image_69x52' => 0,
      'image_71x44' => 0,
      'image_71x71' => 0,
    ),
    'insert_default' => 'image_237x147',
    'insert_class' => 'caption',
  );
  // Add the insert settings to the field instance widget settings
  foreach($insert_settings as $key => $setting){
    $instance['widget']['settings'][$key] = $setting;
  }
  // Save the field instance
  field_update_instance($instance);
}

// Then you can enable insert on a field instance with
MODULE_field_settings_enable_insert('node', 'field_images', 'article')

Comment: Insert stores its settings per field instance, not at the global field level. So you may need to use field_create_instance prior to adding the insert settings or just add them at that time.
Comment: @mparryy there may have been a problem with the `$array += $array2` not overwriting the default values. Please try the adjusted answer that uses `foreach` to force the setting values instead. Tested and working from here.
Comment: Thanks for your answer, is there a possibility that these settings are set at the creation of the field? so at `$field = array([settings]); field_create_field($field);` or can it only be done with an update? I did try this but got the following error:  PHP Fatal error:  Unsupported operand types. I changed it to fit in my profile but apparently something is still going wrong. Any ideas?
Comment: I still can't get it to work. I load the instance (works) and then I try this: `$instance['widget']['settings']['insert'] = 1;` and then save it again: `field_update_instance($instance);` That should work right?
Answer: This is pretty simple to do if you are installing Drupal with an installation profile.
Let's say your installation profile name is custom_profile, just add the following line to custom_profile.info file to install insert module when Drupal installs:
dependencies[] = insert

Comment: This is to enable the module in general and not to enable the insert button at a field.
Comment: @mparryy Exactly! And that is how the question should have been asked. The title asks how to enable the module via installation profile. And the body of the question just says, you need to use the module, but you couldn't enable it programmatically. Please alter your question according to your specific requirements, so that I can delete this answer. But, in current state, I feel this answers your question just right ;-)
Comment: Excuse me? What does this say then: I want to use the insert module for a **file field** but I can't get it to be enabled programmaticly. So no your answer is not even close if you read this sentence.
Comment: @mparryy My intention wasn't to be rude or something. Please don't take me wrong; English is not my first language. But, when I look at the sentence, _I want to use the insert module for a file field but I can't get it to be enabled programmaticly._ I get an impression that you want to use the insert module for a certain functionality but can't get it to be enabled programmatically. By _it_ it thought you were referring to the module; because we _enable_ a module and _implement_ an functionality. For the functionality you're trying to implement I think David has given you some useful pointers.


link datasource and datadelegate of a UITableView to ViewController cause error 'Exc Bad Access'

Question: I try to link datasource and datadelegate of a UITableView to ViewController.
It always causes error 'Exc Bad Access'.
I try to locate where causes this happen by setting the breakpoint in viewDidLoad of the ViewController and RootViewController and AppDelegate, unfortunetly, no result.
Welcome any comment
Answer: I'm not sure what the problem might be. Though I know working with Tables can be a little tricky. I suggest this excellent tutorial that helped me get my head around some problems I had with making it work properly:
http://www.youtube.com/watch?v=LBnPfAtswgw&feature=player_embedded


Unable to access file using .Net Core 3 or .Net Framework on Windows 10

Question: My new projects generated by VS 2019 cannot read or write files. Even the following simple code does not work.
public class Program
{
    public static void Main(string[] args)
    {
        Console.WriteLine("hello");

        string codeBase = Assembly.GetExecutingAssembly().CodeBase;
        UriBuilder uri = new UriBuilder(codeBase);
        string path = Uri.UnescapeDataString(uri.Path);
        var folder = Path.GetDirectoryName(path);

        var filePath = Path.Combine(folder, "test.txt");
        Console.WriteLine(filePath);

        // File.WriteAllLines(filePath, new[] { "hello" });

        using (var f = new FileStream(filePath, FileMode.OpenOrCreate))
        {
            f.Write(new byte[] { 0x39 }, 0, 1);
        }
    }
}

Accessing files using

.Net Core 3.0 + debugger
.Net Core 3.0 + generated exe
.Net Framework 4.6.2, 4.8 (have not tested others)

gives the exception
Unhandled exception. System.UnauthorizedAccessException: Access to the path 'C:\Users\user\Documents\ConsoleApp1\ConsoleApp1\Debug\netcoreapp3.1\test.txt' is denied.

However, it works in .Net Core 2.2 or below or using dotnet ConsoleApp1.dll.
My other few years old projects work. I have never encountered such a problem before. What is the problem and how to fix it?
Comment: [Docs](https://learn.microsoft.com/en-us/dotnet/api/system.io.filestream.-ctor?view=net-5.0#System_IO_FileStream__ctor_System_String_System_IO_FileMode_) says that `UnauthorizedAccessException` will be thrown when file is read-only. You may add `FileAccess.Read` or `FileAccess.ReadWrite`
Comment: I have tried `FileAccess` but it is the same. The file did not get created.
Comment: Your code actually works. There must be another application that is using that file or the folder is read-only.
Answer: It turns out my anti-virus blocked the file access. There were no pop-ups the first day so I could not know. Later, there were finally popups.


Fixar div na parte de baixo da página

Question: Gostaria de saber como deixo uma
 fixa na parte de baixo da página, tipo eu fiz ela ficar em baixo com margin-top, mas só que no Firefox e uma coisa quando abro no Chrome a
 não fica no rodapé.
Comment: Dá uma olhada nesta oura resposta que dei: http://pt.stackoverflow.com/questions/72075/como-fixar-um-rodap%C3%A9-no-bottom-mesmo-com-muito-conte%C3%BAdo/72097#72097
Comment: na verdade eu queria que desse um auto poscionamento. por que quando abro no firefox e uma coisa mais quando abro no chrome ele não fica em baixo na tela
Comment: eu quero ver se deixo a div fixa na parte de baixo da tela
Comment: O que queres é um rodapé que fique sempre no fundo ([sticky footer](https://css-tricks.com/snippets/css/sticky-footer/))?
Comment: Alguma resposta resolveu seu problema? Não se esqueça de dar um voto positivo e escolher a resposta correta.
Answer: Finalmente uma solução testada nos 3 browsers principais (Chrome, FireFox e Internet Explorer 8+)
CSS

HTML

Cabeçalho (Funciona no FF, IE 8+, Chrome)

            Conteúdo aqui

Rodapé

Completo
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Incluindo JS</title>

Cabeçalho (Funciona no FF, IE 8+, Chrome)

            Conteúdo aqui

Rodapé

JSFIDDLE
Answer: Podes utilizar o seguinte código para fixar em todos os browser da mesma forma.
Desta maneira utilizando o "position: fixed;"
.footer {
margin: auto;
width: 100%;
bottom: 0;
position: fixed;
}

Answer: geralmente o pessoal fixa ele usando posicionamento absoluto, dessa maneira:
.footer {
  height: 60px;
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: #eee;
}

Answer: Use uma combinação de position:absolute no elemento que deseja fixar abaixo.
footer {
  padding-top: 10px;
  padding-bottom: 10px;
  background-color: #BBBDBF;
  position: absolute;
  bottom: 0;
  margin-bottom: -40px;
  width: 100%;
}

Com um position:relative no body do documento:
body{
    position:relative
}

Fixar div na parte de baixo da página


Saving outputs as record in class & update if same product name given as input python

Question: I've a code like this.
class salesperson:

    def __init__(self, name):
        self.name=name
        self.market_price=0
        self.quantity=0
        self.product_name=0

        #if self.product_name != self.product_name:

        #self.finalamount=0

    def buy_pro(self, product_name, market_price, quantity):
        self.product_name = product_name
        self.market_price=market_price
        self.quantity=quantity

        self.a= ({self.product_name: [self.market_price, self.quantity]})

    def get_value(self):

            #self.buyproduct()
            finalamount = self.market_price * -self.quantity

            return finalamount

    def get_name(self):
        return (self.name)

    def get_record(self):
        return (self.a)

input:
sp_name=salesperson('name')
sp_name.buy_pro('mobile',30,20)
sp_name.get_value()
sp_name.get_record()

output:
600
Explanation(30*20 =600)

Know, If I give same input with same item name, Then record should be updated.
    Example:
    sp_name.buy_pro('mobile',10,2)
    sp_name.get_value()
    sp_name.get_record()

Expected output:
620
Explination(As item name is same (600(previous value) + (10*2)20= 620

But output I'm getting.
20

Can you guys pls suggest what Is the logic I can use that previous value is added to current input if product name is same?
Answer: in method buy_pro the line which states self.quantity=quantity should be self.quantity += quantity  This will update the self.quantity value with the current order quatity
Answer: use these codes under def init():
self.last=""
self.finalamount=0

and use this get_value():
def get_value(self):
    if self.last == self.name:
        self.finalamount += self.market_price * self.quantity
    else:
        self.finalamount = self.market_price * self.quantity

    self.last=self.name
    return self.finalamount

or you can create a list of last_names for compare with after names
fullcode:
class salesperson:

    def __init__(self, name):
        self.name=name
        self.market_price=0
        self.quantity=0
        self.product_name=0

        self.last=""
        self.finalamount=0

    def buy_pro(self, product_name, market_price, quantity):
        self.product_name = product_name
        self.market_price=market_price
        self.quantity=quantity

        self.a= ({self.product_name: [self.market_price, self.quantity]})

    def get_value(self):
        if self.last == self.name:
            self.finalamount += self.market_price * self.quantity
        else:
            self.finalamount = self.market_price * self.quantity

        self.last=self.name
        return self.finalamount

    def get_name(self):
        return (self.name)

sp_name=salesperson('name')

sp_name.buy_pro('mobile',30,20)
print(sp_name.get_value())

sp_name.buy_pro('mobile',10,2)
print(sp_name.get_value())

Comment: Actually, I don't get any error, isn't this the whole code? I've updated it.
Comment: but you want memory for control next names dont forget use last name list :)
Comment: Hi this was nice explanation..But, Have checked expected outputs?...I mean My expected outputs should be 620...But here when I implement your code I'm getting 820...Here previous record is 600..so new record with same item should (600(old)+(10*2))=620
Comment: Yes, this is whole code
Comment: ~Thanks man. It's working


Determine original size of image cross browser?

Question: Is there a reliable, framework independent way of determining the physical dimensions of a  resized on the client side?
Comment: `img.onload = function () {console.log(img.height, img.width)} `
Answer: You have 2 options:
Option 1:
Remove the width and height attributes and read offsetWidth and offsetHeight
Option 2:
Create a JavaScript Image object, set the src, and read the width and height (you don't even have to add it to the page to do this).
function getImgSize(imgSrc) {
    var newImg = new Image();

    newImg.onload = function() {
      var height = newImg.height;
      var width = newImg.width;
      alert ('The image size is '+width+'*'+height);
    }

    newImg.src = imgSrc; // this must be done AFTER setting onload
}

Edit by Pekka: As agreed in the comments, I changed the function to run on the ´onload´ event of the image. Otherwise, with big images, height and width would not return anything because the image was not loaded yet.
Comment: @Gabriel, I am using this but with an `newImg.onload` function to make sure the image is loaded when I set the width/height. Are you ok with me editing your answer accordingly?
Comment: @GabrielMcAdams, if you add `if(newImg.complete || newImg.readyState === 4) newImg.onload();` at the end of your function it will fix the issue on Chrome/OSX that causes onload not to fire when images are loaded from cache.
Comment: how ca i get return hieght and width...?? because those variable are not getting outside of onload
Comment: Just a side note: Chrome/OSX can have problems with cached images where you get 0 as height/width using this technique.
Comment: That won't work with images that aren't loaded yet. It might be worth adjusting it to work properly for other people stumbling across this answer.
Comment: @jafar: That's more complicated than I would like to put into a comment.  If I were you, I would ask that as a question of its own.  Include the source from here, and maybe a link to here in your question.
Comment: Note that I tried with a base64 image that was just dragged and dropped and even with those you need to use the onload handler to get the right dimensions.
Comment: I've also seen a problem in Firefox, that the picture dimensions would not be loaded even if the onload function is called. I fixed it with a timeout.
Answer: Images (on Firefox at least) have a naturalWidth/height property so you can use img.naturalWidth to get the original width
var img = document.getElementsByTagName("img")[0];
img.onload=function(){
    console.log("Width",img.naturalWidth);
    console.log("Height",img.naturalHeight);
}

Source
Comment: This is the winning answer in 2018. Works everywhere. (Per [browser compatibility table](https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement#Browser_compatibility) at MDN.)
Comment: This topic is still relevant in 2013. Here's a link with a great workaround for IE7/8: http://www.jacklmoore.com/notes/naturalwidth-and-naturalheight-in-ie/
Comment: `if (currentYear >= 2022)` You have to use this option.
Answer: You can preload the image into a javascript Image object, then check the width and height properties on that object.
Comment: Of course - I don't have to put it into the document. Will do it that way, cheers!
Answer: /* Function to return the DOM object's in crossbrowser style */
function widthCrossBrowser(element) {
    /* element - DOM element */

    /* For FireFox & IE */
    if(     element.width != undefined && element.width != '' && element.width != 0){
        this.width  =   element.width;
    }
    /* For FireFox & IE */
    else if(element.clientWidth != undefined && element.clientWidth != '' && element.clientWidth != 0){
        this.width  =   element.clientWidth;
    }
    /* For Chrome * FireFox */
    else if(element.naturalWidth != undefined && element.naturalWidth != '' && element.naturalWidth != 0){
        this.width  =   element.naturalWidth;
    }
    /* For FireFox & IE */
    else if(element.offsetWidth != undefined && element.offsetWidth != '' && element.offsetWidth != 0){
        this.width  =   element.offsetWidth;
    }
        /*
            console.info(' widthWidth width:',      element.width);
            console.info(' clntWidth clientWidth:', element.clientWidth);
            console.info(' natWidth naturalWidth:', element.naturalWidth);
            console.info(' offstWidth offsetWidth:',element.offsetWidth);
            console.info(' parseInt(this.width):',parseInt(this.width));
        */
    return parseInt(this.width);

}

var elementWidth    = widthCrossBrowser(element);

Comment: is `element` a jQuery selection? What is about height ?
Answer: Just changing a little bit Gabriel's second option, to be more easy to use:
function getImgSize(imgSrc, callback) {
    var newImg = new Image();

    newImg.onload = function () {
        if (callback != undefined)
            callback({width: newImg.width, height: newImg.height})
    }

    newImg.src = imgSrc;
}

Html:

Sample call:
getImgSize($("#_temp_circlePic").attr("src"), function (imgSize) {
    // do what you want with the image's size.
    var ratio = imgSize.height / $("#_temp_circlePic").height();
});

Answer: Adding adjustments to Gabriel's second option to help people working with react-grid-gallery.
const [images, setImages] = useState([])

const getImgSize = function (imgSrc, index) {
    var newImg = new Image()

    newImg.onload = function () {
        setImages((images) => [
            ...images,
            {
                id: index,
                src: imgSrc,
                thumbnail: imgSrc,
                width: newImg.width,
                height: newImg.height,
            },
        ])
    }

    newImg.src = imgSrc
}

In useEffect you can call this method
gallery_urls?.map((url, index) => {
            getImgSize(url, index)
        })


"reducing" a vector to a single value

Question: In programming languages like JavaScript, you can reduce an array to a single value by having a function that takes an accumulator and the current value of the array. Does such a thing exist in maths for vectors?
e.g. if I wanted to subtract each element of the vector $(4, 3, 2)$ from the previous result, the "reducer" function would be $f(a, b) = a - b$, then it would be $4 - 3 = 1$ and then $1 - 2 = -1$ (as $1$ is the result of the previous function).
Comment: Not really. Vectors are restricted to the vector space axioms in mathematics. In computer science they play the role of iterables more than mathematical vectors.
Answer: I think you are referring to what Wikipedia names
fold.
It gives this example:

The folding of the list $[1,2,3,4,5]$ with the addition operator
would result in $15$, the sum of the elements of the list
$[1,2,3,4,5]$. To a rough approximation, one can think of this fold
as replacing the commas in the list with the $+$ operation, giving
$1 + 2 + 3 + 4 + 5$.

Many Computer Algebra Systems (CAS) implement this kind of operation.
Many use the name "fold" for the operation. Despite this, it seems
that mathematicians do not find a great need for this operation in
such generality. In very special cases, such as for addition and
multiplication, there is special notation such as $\sum_i x_i$
and $\prod_i x_i$. That is about it.
NOTE: There is a big difference between a list $[1,2,3]$
and a vector in a vector space. A vector has coordinates
only with respect to an ordered basis. Different basis gives
different coordinates.

"reducing" a vector to a single value


Erro no Xcode após atualização para versão 11

Question: Desde que minha versão do Xcode atualizou não consigo mais rodar nenhum dos projetos que implementei,
Abaixo o está o print do meu problema, desde que o Xcode se atualizou automaticamente para versão 11 venho enfretando esse problema.
Comment: Você tentou com a versão do emulador mais recente(iphone 11)?
Answer: Muda o modo de Build para o modo legacy:
- Vai em File -> Workspace Settings -> Build System: Legacy Build System.
Boa sorte.


Web deploy publishes wrong version of assembly

Question: I have a Web API project that has a dependency on System.Web.Http.WebHost and in my project I have set Copy Local = True on that reference, and the version (in this case) is 220.127.116.11.
When I publish the project to the server via web deploy, an older version of this assembly is published (5.2.2.x). This seems to only affect certain people when they publish and not others.
We've run into the same issue with other assemblies in other projects, so this is meant as an example. I can add the affected assembly to the server's GAC or something so it doesn't die when published by a user so affected, but I'd like to know how this happens and how it might be avoided.
Comment: I'm also having this problem, except with Autofac. Is this VS 2015?
Comment: @Loren Yes, though some of the devs affected are using VS 2013 too, so it doesn't seem specifically tied to ide version.
Answer: In my case, I found that the wrong version of Autofac was being deployed, even though the correct version was referenced and was placed into the bin folder while running locally. I re-installed the NuGet package and even that didn't work.
Ultimately, I found the obj\Release\Package\PackageTmp\bin directory (within the project directory) contained the outdated version, and nothing I did would cause it to update. Simply deleting the directory and letting it regenerate solved the issue.
Comment: This happens constantly for us. We have ended up creating pre-publish rule that will delete the bin folder from our target location before publishing. Pretty infuriating. Baffling that Microsoft struggles with crucial environment stuff like this.
Comment: I've tried reinstalling Nuget, all packages, nothing helped. After spending 4 hours pulling my hair out I found Your answer. It solved my issue. Thank You!
Comment: And here, several years later, I had a similar problem with multiple projects after updating recommended NuGet packages from version 6.0.0 to 6.0.1. I've spent about 5 days on this. Deleted the *bin* and *obj* folder of every project involved and rebuild. Problem solved. Thank you!
Comment: I had a similar issue with System.Web.Http 5.2.2 -> 5.2.3 and in Visual Studio 2015 performing a Clean removed the PackageTmp folder from obj. We're now advising our team to perform a clean before every publish.
Comment: LIKE OMFG M$. THANK YOU. I was going nuts because my "obj\publish" folder had the wrong stuff...
Comment: With VS 2019, .Net Core 3.1, the path is 'obj\Release\netcoreapp3.1\win-x64\R2R', win-x64 is the target platform, from my side, limited to Windows X64
Comment: You should get some MS reward for this answer!


NID as a contextual filter doesn't work on some nodes

Question: I have a view where the NID is getting passed as a contextual filter for a specific content type, but some nodes doesn't pass at all and for some of them there is no problem.
I've checked the database, and I can see that the node NID I am trying to expose is there, but I still can't see it in Preview with contextual filters.
Comment: Are you sure those nodes (nids) belong to the specific content type? Are the any other filters, such as published = Yes? that could be filtering them out.
Comment: Yes I'm sure. And I can see the nodes in group view for particular node type when there is no contextual filter (http://sbch.org.mk/events-page). But when I click on link to view full node I can't see content, for some nodes (try last ones)
Comment: I see that the last 2 are duplicates, something weird is going on, and neither of them show anything on full node. When going to `/node/215` doesn't work either. Are you able to edit the node? `node/215/edit` ? is it filled out?
Comment: Yes I can edit the node. As a matter of fact I made the node with same content twice to checkout does it show the content with different NID (216).
Answer: Finally I configured what was the problem. There were two referenced fields related with Relationship in view, and for those two relations I have checked the box "Require this relationship". So whenever I created content without any of those fields, content view was empty. When I unchecked  "Require this relationship" boxes, everything works good.
How ever thanks for your effords to help me.


C# recovery techniques from a timeout

Question: If I have a "Timeout Expired" exception, what can be a good ways to recover from it and continue doing what you are doing by trying again calling the same routing?
Thank you
Answer: <code>while (true)
{
    try
    {
        /////put your code here
        break; // Exit the loop. Could return from the method, depending
               // on what it does...
    }
    catch
    {
        // Log, I suspect...
    }
}
</code>

C# recovery techniques from a timeout


How to make psql completion with Windows?

Question: There is a completion function by the psql command of Cygwin or UNIX
There is not the function in psql for a Windows native.
How to make psql completion with  Windows?
may be need readline!?
Answer: Readline is disabled by default on Windows. You can rebuild with it enabled - but it is broken for most non-english locales. For example, in most western european locales you can no longer type backslash - an essential character to use readline. This is a bug in readline, but last time I checked they had zero interest in the win32 platform and won't fix it.
Comment: Is the missing readline also the reason for the arrow up not working? I would expect arrow up to repeat the last input.