Normal distribution and t-distribution, confidence intervals

Question: In many cases, the $σ$ of a normal distribution is not known. So looking for an interval xn +- (zα/2)$\dfrac{σ}{\sqrt{n}
}$ without knowing the σ leads to a similar expression with σ=Sn .
Since Sn depends on the sample size, we no longer have a normal distribution. It is said that we have a $t$-distribution. What exactly this means, also how could we interpret the degrees of freedom, and eventually why it converges to a normal distribution ? ( as the degrees of freedom increase )
Comment: Peter, I see you're relative new to MSE. If you feel that an answer solved the problem, please mark it as 'accepted' by clicking the green check mark $\left( \color{limegreen}{\checkmark}\right)$. This helps us to keep the focus on (older) question which has no good answers.
Comment: Suppose you have a random sample of size $n$ from a normal population with unknown mean $\nu$ and variance $\sigma^2$.  Then a 95% CI for$\mu$ is of the form $\bar X \pm t^*S/\sqrt{n},$ where $\bar X$ is the sample mean, $S^2$ is the sample variance, and $t^*$ cuts 2.5% of the probability from the upper tail of Student's t distribution with $n-1$ degrees of freedom. // Values of $t^*$ are given in printed tables and can be obtained from statistical software. For example, if $n = 20,$ then R statistical software gives $t^* = 2.093,$ as follows:`qt(.975, 19)` returns 2.093024.
Comment: Please see https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference for formatting your posts properly. Use `\sigma` for $\sigma$, `\alpha` for $\alpha$, etc.
Answer: Comment continued with Example.
In R statistical software, the procedure t.test provides a 95% confidence interval for $\mu$ as part of the output.
Suppose we have a sample of size $n = 20$ from a normal population:
x = rnorm(20, 100, 15)
summary(x); length(x);  sd(x)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
  79.91   86.73  100.52  101.92  109.29  140.36
[1] 20           # sample size
[1] 17.97414     # sample standard deviation

t.test(x)$conf.int
[1]  93.50513 110.32944
attr(,"conf.level")
[1] 0.95

You can use the formula in my Comment along with the value of $t^*$ given there and $\bar X = 101.92$ and $S = 17.97$ to verify this confidence interval
$(93.505, 110.329).$
Notes: (a) Here is the sample used in the example--rounded to 3 places and sorted from smallest to largest:
sort(round(x,3))
 [1]  79.910  80.391  82.185  82.339  86.338  86.867  92.912  93.487  94.925  99.789
[11] 101.253 104.700 107.627 107.857 108.890 110.477 111.960 129.211 136.867 140.360

(b) Here is the same confidence interval from Minitab statistical software:
One-Sample T

 N    Mean  StDev  SE Mean       95% CI
20  101.92  17.97     4.02  (93.51, 110.33)


How to write JUnit test with hardcoded object possesing LocalDate

Question: When I'm trying to test my Api Controller with hardcoded Object everything is fine unitil I try to add LocalDate parameter to Object.
My Test:
@RunWith(SpringRunner.class)
@WebMvcTest(ApiTransitController.class)
public class ApiTransitControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private TestService testService;

    @MockBean
    private ReportsService reportsService;

    @MockBean
    private TransitService transitService;

    @Test
    public void shouldCreateTransit() throws Exception {

        Transit transit = new Transit("London", "Paris", 12L,
    LocalDate.of(2018,10,12));

        ObjectMapper objectMapper = new ObjectMapper();
        String transitJsonString = objectMapper.writeValueAsString(transit);

        this.mockMvc.perform(post("/api/transit")
                .contentType(MediaType.APPLICATION_JSON)
                .content(transitJsonString))
                .andExpect(status().isCreated());

        verify(transitService).addTransit(eq(new Transit("London", "Paris", 12L,
   LocalDate.of(2018,10,12))));
    }
}

Model:
@Entity
public class Transit {
@Column(name = "id")
@Id
@GeneratedValue
private Long id;
private String sourceAdress;
private String destinationAdress;
private Long price;
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
private LocalDate date;
@JsonSerialize(using=DistanceSerializer.class)
private Long distance;

 public Transit(String sourceAdress, String destinationAdress, Long price, LocalDate date) {
        this.sourceAdress = sourceAdress;
        this.destinationAdress = destinationAdress;
        this.price = price;
        this.date = date;
    }

//getters and setters, equals and hashCode and toString

Api Controller:
 @PostMapping("/api/transit")
    @ResponseStatus(HttpStatus.CREATED)
    public void createTransit(@RequestBody Transit transit){
        LOG.info("Saving transit={}", transit);
        transitService.addTransit(transit);
    }

I tried adding DateTimeFormmater and few other ways, but still I cant pass the test. Thank you for your time.
Comment: maybe `Locale.of(..)` returns a new instance, in that case the object would not be equal
Answer: Try changing this line
verify(transitService).addTransit(eq(new Transit("London", "Paris", 12L,
   LocalDate.of(2018,10,12))));

to this:
verify(transitService).addTransit(eq(transit));

The two objects aren't equal, also you don't need to create a new object you can use already created one.
Comment: Nothing changed, the test is not passing.
Answer: I added JsonSerializer to date of the Model:
Model:
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
@JsonSerialize(using=DateSerializerNumberTwo.class)
    private LocalDate date;

Serializer:
public class DateSerializerNumberTwo extends StdSerializer<LocalDate> {

    private static DateTimeFormatter formatter =
            DateTimeFormatter.ofPattern("yyyy-MM-dd");

    public DateSerializerNumberTwo(){
        this(null);
    }
    protected DateSerializerNumberTwo(Class<LocalDate> t){
        super(t);
    }

    @Override
    public void serialize(LocalDate value, JsonGenerator gen, SerializerProvider provider) throws IOException {
        gen.writeString(formatter.format(value));
    }
}

And the test passes without any changes in the test code. I think it's beacuse the Json default response of date is  "yyyy, mm,  dd", not like Local date (yyyy-mm-dd)".


Recursividade em PHP

Question: Para onde vai o return $num*fatorial($num-1); ?
Coloquei um echo antes da condição e de forma decrescente exibe 5 4 ... 1, só não consigo entender para onde vai esse return e como return $num vai me retornar o fatorial se $num é igual(==) a 1, se alguém poder me esclarecer.
 function fatorial($num){
        echo $num;
        if($num == 1){
            return $num;
        }
        return $num*fatorial($num-1);
    }
    echo fatorial(5);

Comment: Eu expliquei isso de maneira bem simples e visual [nesta pergunta sobre o cálculo de Fibonacci em Python](https://pt.stackoverflow.com/a/209220/5878). Não é PHP, nem fatorial, mas o processo é exatamente um mesmo. E é Python, então mesmo nunca utilizado a linguagem, você conseguirá entender o que o código faz (que é basicamente a mesma coisa que o seu em PHP faz).
Comment: https://pt.wikipedia.org/wiki/Recursividade_(ci%C3%AAncia_da_computa%C3%A7%C3%A3o)
Comment: [Imagem de Exemplo](http://www.linhadecodigo.com.br/artigos/img_artigos/Ricardo_Alves/Java_Recursividade/image001.jpg)
Answer: Quando o fatorial é chamado dentro do:
return $num*fatorial($num-1);

O $num é subtraído por - (em fatorial($num-1)), então o $num que começou com 5 na próxima chamada será 4, quando chegar ao fatorial($num-1); novamente vai ser reduzido -1 novamente.
Assim que ($num-1) tiver o valor de 1 ao chamar o fatorial(), ele vai entrar na sua if, que é compara se $num é igual a 1, então neste momento ocorrerá o return "prematuro" que vai terminar a função dentro da if, o que irá retornar o valor atual return $num; que no caso é 1 mesmo.
Então o processo ocorrerá assim:

O input será 5
ignora o if ($num == 1)
O retorno "5 multiplica por fatorial(5-1)"
O input agora será 4 (antes de terminar a multiplicação)
ignora o if ($num == 1)
O retorno "4 multiplica por fatorial(4-1)"
O input agora será 3 (antes de terminar a multiplicação)
ignora o if ($num == 1)
O retorno "3 multiplica por fatorial(3-1)"
O input agora será 2 (antes de terminar a multiplicação)
ignora o if ($num == 1)
O retorno "2 multiplica por fatorial(2-1)"
O input agora será 1 (antes de terminar a multiplicação)
Entra no if ($num == 1)
O retorno irá retornar o valor de $num, que conforme a if é esperado 1 (ocorrerá o return "prematuro" que citei)

Agora ocorre o resto do processo de volta (recursividade):

Era esperado "2 multiplica por fatorial(2-1)", o ultimo retorno foi 1, então é 2*1=2 e envia para o retorno
Era esperado "3 multiplica por fatorial(3-1)", o ultimo retorno foi 2, então é 3*2=6 e envia para o retorno
Era esperado "4 multiplica por fatorial(4-1)", o ultimo retorno foi 6, então é 4*6=24 e envia para o retorno
Era esperado "5 multiplica por fatorial(5-1)", o ultimo retorno foi 24, então é 5*24=120 e envia para o retorno

Recursividade em PHP


Andorid - Abrir Activity apenas uma vez

Question: Como faço para que uma Activity abra apenas na primeira vez que o app for inicializado?
Answer: Primeiro, conceitualmente a primeira vez de uso de um aplicativo, se o controle for offline, é feito diretamente pelo próprio aplicativo, ou seja, você mesmo precisa fazer este controle.
Você pode fazer isto de diversas maneiras. A mais simples é utilizar Preferências Compartilhadas.
Por exemplo, antes da possível inicialização da Activity você pode checar a existência de um determinado valor. Veja:
//obter SharedPreferences
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
//chave de checagem
String isnew = prefs.getString("primeira_vez", null);
if (isnew != null) {
  String name = prefs.getString("name", "Não é a primeira vez");
  int idName = prefs.getInt("idName", 0); //0 is the default value.
} else {
  //... inicialize a atividade
  //... altera o valor de "primeira_vez" para "usado"
}

Answer: Você pode criar na Main, um flag em SharedPreferences, e verificá-lo toda vez que o app iniciar. Caso o flag tiver false, abre a activity desejada e já altera para true.
Não achei aqui um projeto que havia feito, mas achei um AQUI.
Exemplo:
public class Splash extends Activity {

    SharedPreferences sharedpreferences;
    boolean splash;

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);

        sharedpreferences = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
        splash = sharedpreferences.getBoolean("Splash", false);
        if (splash == true) {
            Intent mainIntent = new Intent(Splash.this, MainActivity.class);
            startActivity(mainIntent);
        }
        else
        {
            setContentView(R.layout.splash);

            //animation
            ImageView imageView = (ImageView) findViewById(R.id.imageView);
            Animation alpha = AnimationUtils.loadAnimation(getApplicationContext(),
                    R.anim.fade_in);

            imageView.startAnimation(alpha);

            alpha.setAnimationListener((new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {
                    // TODO Auto-generated method stub
                }

                @Override
                public void onAnimationRepeat(Animation animation) {
                    // TODO Auto-generated method stub
                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    // TODO Start your activity here.
                    SharedPreferences.Editor editor = sharedpreferences.edit();
                    editor.putBoolean("Splash", true);
                    Intent mainIntent = new Intent(Splash.this, MainActivity.class);
                    Splash.this.startActivity(mainIntent);
                    Splash.this.finish();
                }
            }));
        }
    }
}

Andorid - Abrir Activity apenas uma vez


Upgrade Devel module and disable Kint

Question: When upgrading from Devel 8.x-2.x to Devel 8.x-4.x in a composer based build, how do I handle the Kint module being removed per Remove Kint module and create a kint dumper plugin in devel?
The service container can't be created because the Kint class is missing. I'll add the class path to Kint when I blow up the build again. :) Thank you.
Comment: Did you try upgrading from 2 to 3, and then 3 to 4?
Answer: Since Devel 4 you have to add Kint youself:
composer require drupal/devel kint-php/kint

You can read through this epic issue to learn more: Unknown "kint" function. in Twig\ExpressionParser.

Also important to read the release notes. On all 4.0.0+ releases the following is written. You have to do this before upgrading:

If you have Kint module enabled, please run these commands before
upgrading:

drush pm:uninstall kint or uninstall Kint using the Drupal UI
composer require kint-php/kint

To fix any Kint-missing-module-error, simply downgrade Devel composer require 'drupal/devel:^2.1', uninstall Kint drush pmu kint and then upgrade again composer require drupal/devel kint-php/kint.
Comment: @AbdulSadikYalcin – Downgrade like described in the last section of my post. Or create a bare bone custom module with just an info file. web/modules/custom/kint/kint.info.yml. Fill the info file, see https://www.drupal.org/docs/creating-custom-modules/let-drupal-know-about-your-module-with-an-infoyml-file. Then run `drush pmu kint`, done.
Comment: I've upgraded to `9` and updated `devel` before I uninstalled kint. I'm now stuck. When I try to enable other modules, I get this error: `Drupal\Core\Extension\Exception\UnknownExtensionException: The module kint does not exist.`
Comment: Downgrading is not an option unfortunately. Done too much work to risk losing. I'll try creating a dummy kint module and see how it goes.
Answer: The problem was I was including
// Change Kint maxLevels setting.
// @see https://gist.github.com/JPustkuchen/a5f1eaeb7058856b7ef087b028ffdfeb
include_once(DRUPAL_ROOT . '/modules/contrib/devel/kint/kint/Kint.class.php');
if (class_exists('Kint')) {
  Kint::$maxLevels = 6;
}

in settings.local.php. I recall reading somewhere that the default maxLevels in Kint is now 6 which makes the custom code snippet unnecessary. When I removed it, removed kint from core.extension.yml (in our case config_split.local) and added kint-php/kint via composer, all was well.
Thanks again @leymannx
Answer: If you are facing the issue.
Use the development module 4.x-dev If you are using the 4+ versions then use development version 4.x-dev .
https://www.drupal.org/project/devel
$ composer require drupal/devel:4.x-dev
$ composer require kint-php/kint
$ drush en -y devel

Enable Twig debugging it in development.services.yml file
twig.config:
    debug: true
    auto_reload: null
    cache: false

Goto /admin/config/development/devel and  set the "Variables dumper" to "Kint"
Add {{ kint() }} into template files.
Comment: Or just `composer require drupal/devel_kint_extras && drush -y en devel_kint_extras`. It gets the other dependencies automagically.
Comment: Thank you @leymannx

Upgrade Devel module and disable Kint


How to divide a variable multiple times

Question: I would appreciate any help.
So the prompt was to create a program with integers userNum and x as inputs and have the output be userNum divided by x a certain amount of times(in my case, let's say 4).
This is the code I have so far which works finely for dividing userNum by X but it only does it once when I need it be done however many times is specified. Any advice?

public class LabProgram
{
   public static void main(String[] args)
   {
      int userNum;
      int x;
      Scanner scnr = new Scanner(System.in);

      userNum = scnr.nextInt();
      x = scnr.nextInt();

      System.out.println(userNum / x);

   }
}

If my input 2000 2, I only get 1000 as an output when my required output is 1000 500 250 125.
Comment: You need to learn the language features. To do the repetitive task, you need to use loops or recursion. For the fix time, better use loops.
Answer: I think it's time for you to use something called a 'loop'.
Something like:
for (int i = 0; i < 4; i++) {

}

Put some parts of your code inside this loop and magic will appear.
Answer: You will need to use some form of loop such as a for loop.
   public static void main(String[] args)
   {
      int userNum;
      int x;
      int times;
      Scanner scnr = new Scanner(System.in);

      userNum = scnr.nextInt();
      x = scnr.nextInt();
      times = scnr.nextInt();
      for(int i = 0; i < times; i++){
          userNum /= x;
      }
      System.out.println(userNum);
   }

You may want to make userNum a double as integer division will result in truncation of decimal values by removing the decimal portion.
Comment: Ah, so I put in your code of ```userNum /= x;``` and wrote something like this: ```System.out.println(userNum /= x);``` and that seemed to do the trick! Much thanks!
Answer: Here, You can use loops here if you want to divide number 4 times then you can use for loop and if you want to divide UserNum until value of UserNum is not equals to 0 then you can use while loop.

How to divide a variable multiple times


How to properly alter the output for fields of type file?

Question: I have a file upload field which's format is set to generic file. It prints the following markup:

    Lorem ipsum

    ...

But I'd rather not show the img at all, alter url text, something similar like this:

    $filename
    $description text of this field

What hooks would I have to use for this? And why is this so hard to find on the docs?!
Comment: It's a field so you'd normally alter it with `field--type.tpl.php`, probably `field--file.tpl.php` for a file field
Comment: yeah but there is no tpl which renders  in it markup specially for file fields, is there?
Comment: Take a look here: https://api.drupal.org/api/drupal/modules!field!field.module/function/template_preprocess_field/7
Comment: Another way, without programming, is to use Custom Formatters https://drupal.org/project/custom_formatters
Comment: @Alex not directly, but one of the contained theme functions looks to be responsible
Answer: I'm guessing a bit here as I can't see what you have installed/configured...
The file formatter function is file_field_formatter_view(), and the only formatter which has an image attached to it runs through theme_file_link(). I would assume that's where the markup you're referring to comes from.
You can override that in your theme:
function MYTHEME_file_link($vars) {
  ...
}

Or, if you can get away without having to reproduce the function, just preprocess is:
function MYTHEME_preprocess_file_link(&$vars){
  ...
}

Comment: MYTHEME_file_link($vars) does the trick for me. thanks for your help
Answer: If it is a file field, not an image field, then it shouldn't be necessary to alter the template, but instead change the display configuration. See the attached screenshots.
Or am I misunderstanding your question?

Which then renders like this:

Update: Sorry, misunderstood the question, you don't want the icon in front, didn't catch that.


How do I configure my whm/cpanel setup so that I can have many domains using the 2 ip's I have?

Question: I have 2 IPs and 3 domains. But whm/cpanel currently only seems to be able to assign 2 domains to my IPs.
In WHM, under Account Functions > Change Site's IP Address there is the domains I have.
I select the 3rd domain (yet to be assigned) and click 'change'.
There are 3 IP addresses there, 1 is an IP I don't own and I don't know why its there... and the other 2, are the ones I have assigned to my nameservers. I can't select the ones I own and point my 3rd domain to either of these, and so my 3rd domain is pointing to some random IP I don't know how to get rid of.

Where is this phantom IP address I don't own stored?
How do I configure my IPs so that I'm able to delegate more than 2 domains to my server?
Comment: I think I have just learned that I need to make an account a reseller and then create new domains through that...
Comment: Is the IP address you don't recognize 127.0.0.1? If so it is called the localhost or loopback address and is found on every unix machine as a way of talking to itself.
Comment: This question appears to be off-topic because it is about [`working with a service provider's management interface, such as cPanel`](http://serverfault.com/help/on-topic).
Answer: As you have 2 IP's in the Cpanel server, one will be the main shared IP of the server and other can be used as a dedicated or shared IP.
You can host as many domains in the main shared IP. If you need to install ssl certificate to any of the domains, that domain can be assigned the other ip as a dedicated ip.
You can see the current IP address usage from:
Main >> IP Functions >> Show IP Address Usage
You have mentioned that you are able to see a third Ip which is not yours. There can be two chances.
1) its a private ip or loopback address 127.0.0.1.
2)The ip belongs to another server, which might be added wrongly or might have been added wrongly while restoring a domain from the cpanel backup.
For the first case let the ip unchanged ...
And for the second case, you need to delete the ip from the server which can be done from the cpanel. If there is any domain assigned to that IP, assign it with another ip and delete the ip from the server which can be done from:
Main >> IP Functions >> Change Site's IP Address
Main >> IP Functions >> Show or Delete Current IP Addresses
Do post here for further queries regarding this.


Filtrar Dados de uma lista do Banco de dados com PHP apartir de um Input

Question: Tenho um input text com o evento onkeyup no qual digito uma palavra e ele está comparando com uma lista do banco de dados e retornando um botão com o mesmo caso exista..
Eu quero que no decorrer que eu vá digitando vá surgindo as opções, exemplo:
Tenho uma lista com as palavras teste,tornado,tempestade e quando já digitar o t surgir as três opções e conforme for digitando vai excluindo algumas.
Observações :
Estou usando ajax para gerar os botões dinamicamente, mas procuro uma solução dentro do php para o problema
Por enquanto ele só ta comparando se a palavra for exatamente igual ao que digitei no input para imprimir o botão, eu quero que ele imprima os botões no decorrer que eu vá digitando.
Tem que ser com botão, não pode select nem opções como datalist do html5.
Comment: Tem como mostrar como estão sendo gerados os botões dinamicamente? Estou produzindo um script sem banco de dados.
Answer: A única forma de fazer isso sem atualizar a página é com Ajax.
Para fazer isso você tem que usar o operador LIKE do sql junto com o %:
<code>"SELECT coluna FROM tabela WHERE coluna LIKE '$variavel%' "
</code>
Onde '$variavel' é o retorno do teu input e o '%' diz que tem mais caracteres depois.
Nesse link tem mais coisas https://www.w3schools.com/sql/sql_like.asp
Comment: Obrigado, tinha esquecido do like, solucionou perfeitamente o que eu procurava, apenas para complementar pra quem precisar, a sintaxe ficaria WHERE nome LIKE '%$AquiSeriaOvalor%' "; o valor entre % %, Abraço !
Comment: Se não for realmente necessário é melhor deixar o '%' só no final para poupar processamento do banco de dados.


Simplify nested lapplys

Question: I want to map a list to a list of lists and do a function. Currently I have nested lapplys, but I just don't like it and want to do this in one mapping, if it's possible. I've created a simplified version of my code where I paste the year and day together. Really my function is raster() and I'm creating a list of list of raster objects by year and then by day. Thanks for any help, or pointing me to any previous posts I missed!
Example reproducible code I want to simplify-
exmp1 <- list(list(4, 7,9), list(23, 28), list(5, 32, 82, 99))
exmp2 <- list(1999, 2000, 2001)

exmp3 <- seq(from = 1, to = length(exmp1))
foo <- lapply(exmp3, function(w) {
  lapply(exmp1[[w]], function(k){
    paste(exmp2[[w]], k)
    })})

Answer: I think you can use Map here :
Map(paste, exmp1, exmp2)

For more complicated function you can use an anonymous function to include more lines of code.
Map(function(x, y) paste(x, y), exmp1, exmp2)

Comment: Yes, you can do `Map(function(x, y) lapply(y, function(p) raster(x, p)), exmp1, exmp2)` but this is no different than your nested `lapply`.
Comment: I believe OP needs `Map(function(...) as.list(paste(...)), exmp2, exmp1)`.
Comment: This worked for my simplified example, but not working for the function I actually care about, ```foo <- Map(function(x, y) raster(x, layer = y), r, days)``` I end up with just a list of three raster objects, instead of a list of lists
Comment: in the raster() function, because y has a length greater than one, only the first element is evaluated, instead of evaluating x and each value of y.
Comment: This is still better than my first solution, so I'm gonna call it good.

Simplify nested lapplys


How to get the value of $x$ to solve the statement?

Question: I have a statement that says:

Determine the value of x, so that it is fulfilled:
$$\binom{x}{2} = 10$$

Ok, i try this:
$$\begin{align*}
\frac{x!}{(x - 2)! \cdot 2!} &= 10 \\
x! &= 10(2x -4) \\
x! &= 20x - 40 \\
x! - 20x &= 40
\end{align*}$$
I was here, and I did not know what else to do.
How should I solve it? What is my error?
Comment: $(x-2)!\not=(x-2)$
Answer: Hint: $\frac{x!}{(x-2)!}=x(x-1)$
Answer: Note that
$$\frac{x!}{(x - 2)! \cdot 2!} = 10\iff\frac{x(x-1)(x-2)!}{(x - 2)! \cdot 2!} = 10$$
Comment: By definition $x!=x(x-1)(x-2)(x-3)...2\cdot 1=x(x-1)(x-2)!$
Comment: How you get $x(x -1)(x-2)!$
Comment: Ah, its so easy now, thanks gimusi
Comment: @Mattiu You are welcome! Bye
Answer: There are several good answers here, but I don't think that any of them have directly attempted to address the error you made (though it is pointed out in the comment).  There are actually two critiques that I would make regarding your argument, as summarized below:
First, you write
\begin{align*}
\frac{x!}{(x - 2)! \cdot 2!} &= 10 \\
x! &= 10(2x -4) \\
x! &= 20x - 40 \\
x! - 20x &= 40.
\end{align*}
I would argue that this is unclear—were I grading your work, I almost certainly would not give full marks to such an answer, even if it were otherwise correct.  You have written down a series of statements, but have giving no indication about how they relate to each other.  If your intention is to say that one line follows from the next, then you should indicate that in some way, for example:
\begin{align*}
\frac{x!}{(x - 2)! \cdot 2!} = 10
&\stackrel{(*)}{\implies} x! = 10(2x -4) \\
&\implies x! = 20x - 40 \\
&\implies x! - 20x = 40
\end{align*}
Second, there is a significant error in your computation, which I have highlighted with an (*).  You appear to have concluded that $(x-2)!\cdot 2! = (2x-4)$, then attempted to clear the denominator by multiplying both sides of the equation by this term.  However, this computation is incorrect.  You might be better off noting that the term
$$ \frac{x!}{(x-2)!} $$
simplifies rather nicely.  Indeed, if you write it out in painful and pedantic detail, you get
$$ \frac{x!}{(x-2)!\cdot 2!}
= \frac{x(x-1)\color{red}{(x-2)(x-3)\dotsb(3)(2)(1)}}{\color{red}{(x-2)(x-3)\dotsb(3)(2)(1)}\cdot 2}
= \frac{x(x-1)}{2}. $$
Therefore
\begin{align}
10 = \frac{x!}{(x-2)!\cdot 2!} = \frac{x(x-1)}{2}
&\implies 20 = x(x-1) = x^2-x \\
&\implies 0 = x^2 - x - 20 = (x-5)(x+4) \\
&\implies x=5 \quad\text{or}\quad x=-4.
\end{align}
From the start, we know that $x > 0$, therefore $x=5$.
Answer: From
$$\frac{x!}{(x - 2)! \cdot 2!} = 10$$
we get
$$\frac{x(x-1)(x-2)!}{(x-2)!\cdot 2}=10$$
Then
$$\frac{x(x-1)}2=10\quad\text{so}\quad x(x-1)=20$$
Comment: How you get $x(x -1)(x-2)!$
Comment: @Mattiu Expand the first couple of terms of $x!$.
Answer: You can be lazy and just check if any solution works (it might have been the case there was no solution....  in general there shouldn't always be a solution).
By direct computation $\binom 2 2=1, \binom 3 2= 3, \binom 4 2 = 6, and \binom 5 2 =10 $
This seems like a natural approach since for fixed $n$, $f(m)=\binom m n$ is an increasing function, so that if $f(m)< k$ and $f(m+1)>k$ then there is no solution to be found.  But there is a solution... $f(5)=10$.


DataTables - Exportação para Excel

Question: Possuo uma tabela que, depois de carregada, cada linha tem um botão de mostrar detalhes (ícone +) como mostrado na imagem abaixo:

Ao clicar nesse botão abre-se uma nova tabela abaixo que pode ser recolhida depois. O problema é na hora da exportação para Excel. A tabela sai toda desconfigurada, assim:

Este é o meu JSP de listagem:

                Data de Início
                Evento
                Quartos Vendidos

            <c:forEach items="${salesList}" var="sales">

                        <input type="hidden" class="eventId" value="${sales.event.id}">

                    <fmt:formatDate value="${sales.event.startDate}"/>
                    ${sales.event.shortName}
                    ${sales.qty}

            </c:forEach>

E este é o Datatable que estou usando:
function applyReportDataTables(table) {
    oReportTable = $(table).dataTable({
        "aoColumnDefs": [
            {"bSortable": false, "aTargets": ["unsortable"]},
            {"sType": "pt-br-date", "aTargets": ["date"]}
        ],
        "aaSorting": [],
        "sDom": "T<'clear'>lfrtip",
        "oTableTools": {
            "aButtons": ["xls"],
            "sSwfPath": $("#rootPath").val() + "/media/swf/copy_cvs_xls_pdf.swf"
        },
        "sPaginationType": "full_numbers",
        "bStateSave": false,
        "aLengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "Todos"]],
        "paging": false,
        "oLanguage": {
            "oPaginate": {
                "sFirst": "Primeira",
                "sLast": "Última",
                "sPrevious": "Anterior",
                "sNext": "Próxima"
            },
            "sSearch": "Busca",
            "sInfo": "Mostrando de _START_ à _END_ de _TOTAL_ registros",
            "sInfoEmpty": "Nenhum resultado",
            "sInfoFiltered": " - filtrados de um total de _MAX_ registros",
            "sLengthMenu": "Mostrando _MENU_ registros",
            "sLoadingRecords": "Por favor - espere...",
            "sProcessing": "Carregando...",
            "sZeroRecords": "Nenhum resultado foi encontrado com esses filtros!"
        }
    });
    return oReportTable;
}

Eu poderia, antes do export, remover essas colunas que possuem o botão ?
Imagino que sem eles o excel sairia normalmente.
Answer: Consegui resolver o problema removendo o "alt" da listagem. Ele de alguma forma desconfigurava toda a página e quebrava a exportação.

DataTables - Exportação para Excel


wp.data.select('meta') property undefined with Gutenberg for WordPress

Question: I use Gutenberg with WordPress and I would like to check some fields before the user publish his post.
I would like to check if the featured image, the title and a simple text field in a meta-box are not empty.
If a field is empty a notification is displayed and I locked the "Publish" button.
For the moment all works fine with the featured image and the title. But when I'm trying to check is the text field in the meta-box is empty I got errors :
Uncaught TypeError: Cannot read property '_myprefix_text_metafield' of undefined

I created my meta-box with a text field like that :
import { __ } from '@wordpress/i18n';
import { useSelect, useDispatch } from '@wordpress/data';
import { registerPlugin } from '@wordpress/plugins';
import { PluginDocumentSettingPanel } from '@wordpress/edit-post';
import { TextControl } from '@wordpress/components';

const TextController = (props) => {
    const meta = useSelect(
        (select) =>
        select('core/editor').getEditedPostAttribute('meta')['_myprefix_text_metafield']
    );
    const { editPost } = useDispatch('core/editor');
    return (
        <TextControl
        label={__("Text Meta", "textdomain")}
        value={meta}
        onChange={(value) => editPost({ meta: { _myprefix_text_metafield: value } })}
        />
    );
};

const PluginDocumentSettingPanelDemo = () => (
    <PluginDocumentSettingPanel name="text-presentation" title="Texte de présentation" className="custom-panel custom-panel-presentation" icon=" ">
        <TextController />
    </PluginDocumentSettingPanel>
);

registerPlugin('plugin-document-setting-panel-demo', {
    render: PluginDocumentSettingPanelDemo
});

And to check if all fields are not empty :
const locks = [];

function lock( lockIt, handle, message ) {
    if ( lockIt ) {
        if ( ! locks[ handle ] ) {
            locks[ handle ] = true;
            wp.data.dispatch( 'core/editor' ).lockPostSaving( handle );
            wp.data.dispatch( 'core/notices' ).createNotice(
                'error',
                message,
                { id: handle, isDismissible: false }
            );
        }
    } else if ( locks[ handle ] ) {
        locks[ handle ] = false;
        wp.data.dispatch( 'core/editor' ).unlockPostSaving( handle );
        wp.data.dispatch( 'core/notices' ).removeNotice( handle );
    }
}

wp.data.subscribe( () => {
    // get presentation
    const textPresentation = wp.data.select( 'core/editor' ).getEditedPostAttribute('meta')['_myprefix_text_metafield'];

    // Lock the post if the presentation is empty.
    lock(
        ! textPresentation,
        'presentation-lock',
        'Please add a presentation text',
    );

    // get the current title
    const postTitle = wp.data.select( 'core/editor' ).getEditedPostAttribute( 'title' );

    // Lock the post if the title is empty.
    lock(
        ! postTitle,
        'title-lock',
        'Please add a title',
    );

    // get the Featured Image
    const featuredImage = wp.data.select( 'core/editor' ).getEditedPostAttribute( 'featured_media' );

    // Lock post if there is no Featured Image selected
    lock(
        featuredImage === 0,
        'featured-image-lock',
        'Please add a featured image',
    );

});

When I write this in the console :
wp.data.select( 'core/editor' ).getEditedPostAttribute('meta')['_myprefix_text_metafield'];
The value returned well the value of my text field.
Answer: That could happen when the XHR/AJAX request that fetches post data from the REST API hasn't been fully resolved, so you can't simply access the metadata like that. You need to ensure that getEditedPostAttribute('meta') actually returns an object and only then access the _myprefix_text_metafield property.
So try with this instead:
const textPresentation = wp.data.select( 'core/editor' ) // wrapped for brevity
    .getEditedPostAttribute( 'meta' )?._myprefix_text_metafield;

// Lock the post if the presentation is empty.
lock(
    undefined !== textPresentation && ! textPresentation,
    'presentation-lock',
    'Please add a presentation text'
);

Comment: Thank you very much for your help. That's works fine. In `lock` function you tested at the beggining if `textPresentation ` is `undefiend`, and when the page is completely loaded if `textPresentation ` is not empty ?

What does "?" means in `wp.data.select( 'core/editor' ).getEditedPostAttribute( 'meta' )?.myprefix_text_metafield`
Comment: It's called [optional chaining operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining). And equivalent code without using that, is 1) `const meta = wp.data.select( 'core/editor' ).getEditedPostAttribute( 'meta' ) || {};` and 2) `undefined !== meta._myprefix_text_metafield && ! meta._myprefix_text_metafield`


Definition of a smooth function on $[0,1]^k$

Question: Let $M$ be a smooth manifold, and $f: [0,1]^k \rightarrow M$ be a continuous function which is smooth on $(0,1)^k$.  I have seen two definitions of what it means for $f$ to be smooth.  First, there exists an open neighborhood $U \subset \mathbb R^k$ such that $f$ extends to a smooth function on $U$.  Second, at each point $p$ on the boundary of $[0,1]^k$, there exists an open neighborhood $U$ of $p$ such that $f$ extends to a smooth function on $U \cap (0,1)^k$.
Are these two definitions equivalent?  If not, what should be the "correct" definition?  Say, for the purpose of defining singular homology and integration of differential forms?
Answer: Yes, both definition are equivalent. You can use partitions of unity: Suppose that for every $x$ in $[0,1]^k$ there exists an open neighborhood of $x$ and a smooth function $f_x:U\cap (0,1)^k \to M$ wich agrees with $f$. By compactness of $[0,1]^k$ there exists a finite cover $\{U_1,\ldots, U_r\}$  of $[0,1]^k$ consisting in some of such neighborhoods. Take a partition of unity $\{\varphi_1,\ldots,\varphi_r\}$ subordinated to the cover and define $F:\cup_iU_i\to M$ by the formula $F(x)=\sum_i\varphi_i(x)f_i(x)$.
Answer: Yes, these definitions are equivalents. The first one clearly implies the second. Using the notion of partition of unity (see here), you can show that the second one also implies the first.


Exchange 2007 send as different user by default

Question: Allow me to explain in detail.
I have a client who runs 3 companies under the same roof.  Each user has 3 exchange mailbox accounts (for each company domain) which they load under either Outlook 2007 or 2010.
The company has been using CompanyA.com as the main account with CompanyB.com and CompanyC.com as additional accounts.  They now are now changing their main company to name from CompanyA to CompanyB.
I need help to see if it's possible for the following to be performed:

When a user sends an email from ANY of the mailbox accounts from Outlook, OWA, Activesync - the SMTP address is AUTOMATICALLY sent from CompanyB.com (right now it sends as whichever account they send from).
If so, can this be configured on a user by user basis and/or configured on a global scale?

Please note that simply forwarding all emails for CompanyA and CompanyC won't be sufficient as they'd like to keep their current inbox rules for the various folders in each mailbox account.
Thank you!
Answer: You can't have multiple mailboxes sharing the same email address.  What is your exact setup?  Does Company A, and B and C each have different mailboxes?  or is it a single mailbox per company?  Are you still looking to have three separate entities or do you want to merge them?
Edit 1:
Based on your comment this isn't possible with native exchange / outlook.  Exchange will only allow you to bind one email address to one mailbox.  No exceptions...
The only way to accomplish what you're looking for (in its entirety) is to merge the mailboxes and their email addresses.  Then you'd simply set the primary SMTP address to be the domain that you want.
You can use "send as" rights, but that will only work in Outlook, not EAS, and I'm pretty sure not OWA.
Don't forget, if you send out as one address, that's where its going to return.  So if you send out companya.com from companyb.com, the email will come back to companya.com.  So really, you should just merge the mailboxes.
Comment: There is one user mailbox per Company so thy each have their own SMTP address: ie User Jane Doe has email@example.com, email@example.com, firstname.lastname@example.com.  I need to have exchange configure so that it doesn't matter which mailbox use used to send email from Jane Doe, they all appear to be sent as email@example.com.
Comment: see my edit above.
Comment: That was my assumption as well but I wanted a 2nd opinion.  Another colleague indicated a transport service or something to that effect could be modified to accomplish but he was not sure and I was unable to find any documentation outlining this.


checkbox + Model + Controller. Como pegar as linhas selecionadas?

Question: estou enviado a minha model tipada para uma view e carregado os dados em uma tabela onde incluo um checkbox para cada linha. O usuário irá selecionar os itens que interessa para posteriormente ser gravada no banco de dados. Minha dúvida está justamente neste ponto. Como faço para enviar para o controller os itens. Alem da minha lista de dados também envio outras informações.
Minha model é essa:
public int Id { get; set; }
public string CodigoUsuario { get; set; }
public string NomeUsuario { get; set; }
public List<Fornecedor> ListaFornecedorViewModels { get; set; }

Meu controller é esse:
public ActionResult UsuarioNovo() {
    UsuarioViewModel usuarioViewModel = new UsuarioViewModel();
    ViewData["Colaborador"] = _userLogado;
    return View(usuarioViewModel);
}
[HttpPost]
public ActionResult UsuarioNovo(UsuarioViewModel usuarioViewModel)
{
    if (usuarioViewModel.ListaFornecedorViewModels != null)
    {
        if (!string.IsNullOrEmpty(usuarioViewModel.FornecedorBusca)) {
            int iCnpj;
            var listFornecedor = new BuscaDadosFornecedorBo().BuscaRequisicaoFornecedorBo(usuarioViewModel.FornecedorBusca, "");
            usuarioViewModel.ListaFornecedorViewModels = listFornecedor;
        }
    }
    else
    {
        //Gravar Dados
    }
    return View(usuarioViewModel);
}

E essa é a minha View:
@using (@Html.BeginForm()) {

        @Html.LabelFor(model => model.NomeUsuario)
        @Html.EditorFor(model => model.NomeUsuario)

        @Html.LabelFor(model => model.SobrenomeUsuario)
        @Html.EditorFor(model => model.SobrenomeUsuario)

            @Html.LabelFor(model => model.FornecedorBusca)
            @Html.EditorFor(model => model.FornecedorBusca)

        <input class="btn btn-primary" type="submit" value="Buscar" />

@if (Model.ListaFornecedorViewModels != null) {

                    Selecionar
                    CNPJ
                    RazaoSocial
                    Municipio

                @foreach (var forn in Model.ListaFornecedorViewModels) {

                        <input type="checkbox" value="@forn.Codigocnpj" name="chkForn"/>
                        @forn.Codigocnpj
                        @forn.RazaoSocial
                        @forn.Municipio

                }

}

}
Vou precisar dar dois post na mesmo action "UsuarioNovo"... O primeiro pra buscar a lista de fornecedores e o segundo para enviar os dados mais os itens da lista selecionados. Como farei isso?

EDIT
Fiz os ajustes que o @Cigano mencionou na model e estou utilizando BeginCollectionItem, porém o selecionado está vindo sempre como false e os demais campos como null. Veja as imagens:

E no meu código mostra isso:

O que estou fazendo de errado?
Comment: Já instalou o [BeginCollectionItem](https://www.nuget.org/packages/BeginCollectionItem/)?
Comment: E o que isso poderia me ajudar Cigano?
Comment: A resolver seu problema. Se não, coloco uma resposta.
Comment: Não sei como utilizar o que mencionou. Por favor, aguardo a sua resposta.
Comment: Se você quer que os campos vão para o Controller, é preciso transformá-los em `@Html.EditorFor()` ou `@Html.HiddenFor()`, mas só recomendo fazer isso para o Id do Fornecedor. Não para todos os campos.
Comment: Boa... Vou fazer o hiddenfor() para pegar o ID. Porem minha duvida esta ainda quando envio os dados para o controller e o check estão todos nulos.
Comment: Deu certo agora?
Answer: Não é uma boa prática deixar na mesma Action funções muito diferentes, como montar uma ViewModel e persistir um usuário novo. O correto seria você fazer o seguinte:
public ActionResult UsuarioNovo()
{
    UsuarioViewModel usuarioViewModel = new UsuarioViewModel {
        ListaFornecedorViewModels = new BuscaDadosFornecedorBo().BuscaRequisicaoFornecedorBo(usuarioViewModel.FornecedorBusca, "")
    };
    ViewData["Colaborador"] = _userLogado;
    return View(usuarioViewModel);
}

[HttpPost]
public ActionResult UsuarioNovo(UsuarioViewModel usuarioViewModel)
{
    if (usuarioViewModel.ListaFornecedorViewModels != null)
    {
        //Gravar Dados
    }

    return View(usuarioViewModel);
}

Como mencionei em comentário, isto é um caso clássico do uso do pacote BeginCollectionItem. Há várias perguntas e respostas a respeito que você pode se basear, mas vou deixar o caminho pavimentado para a solução.
Se o objetivo é trabalhar com uma lista de fornecedores com uma CheckBox, nada mais justo que definir a CheckBox no ViewModel, afinal, você não vai salvar o fornecedor. Apenas pegar se ele foi selecionado ou não.
public class FornecedorViewModel
{
    public bool Selecionado { get; set; }
    public Fornecedor Fornecedor { get; set; }
}

Mudando o ViewModel de Usuário:
public class UsuarioViewModel
{
    public int Id { get; set; }
    public string CodigoUsuario { get; set; }
    public string NomeUsuario { get; set; }
    public List<FornecedorViewModel> Fornecedores { get; set; }
}

Vamos ter que mudar um pouco nosso método GET:
public ActionResult UsuarioNovo()
{
    UsuarioViewModel usuarioViewModel = new UsuarioViewModel {
        Fornecedores = new BuscaDadosFornecedorBo()
                           .BuscaRequisicaoFornecedorBo(usuarioViewModel.FornecedorBusca, "")
                           .Select(f => new FornecedorViewModel { Fornecedor = f })
                           .ToList()
    };

    ViewData["Colaborador"] = _userLogado;
    return View(usuarioViewModel);
}

Sua View, portanto, fica assim:
@if (Model.Fornecedores != null) {

                    Selecionar
                    CNPJ
                    RazaoSocial
                    Municipio

                @foreach (var form in Model.Fornecedores) {

                        @Html.CheckBoxFor(_ => form.Selecionado)
                        @form.Fornecedor.Codigocnpj
                        @form.Fornecedor.RazaoSocial
                        @form.Fornecedor.Municipio

                }

}

Agora vamos usar o BeginCollectionItem.
@if (Model.Fornecedores != null) {

                    Selecionar
                    CNPJ
                    RazaoSocial
                    Municipio

                @foreach (var form in Model.Fornecedores) {
                    @using (Html.BeginCollectionItem("Fornecedores"))
                    {

                            @Html.CheckBoxFor(_ => form.Selecionado)
                            @form.Fornecedor.Codigocnpj
                            @form.Fornecedor.RazaoSocial
                            @form.Fornecedor.Municipio

                    }
                }

}

Com isso, fica bem fácil de terminar a lógica:
if (usuarioViewModel.Fornecedores != null)
{
    foreach (usuarioViewModel.Fornecedores.Where(f => f.Selecionado))
    {
        // Gravar dados
    }
}

Comment: Fiz um outro comentário abaixo. O que fiz de errado?
Comment: Amigo, isto não é um fórum. Você não fez um comentário, mas sim, tentou responder à pergunta. Use o botão de edição da sua pergunta para editar. Já fiz isso por você agora, mas nas próximas edite sua pergunta. Não coloque uma resposta.
Comment: Entendi... É que queria enviar a imagem para demostrar o erro e não consegui por aqui.


Win Server 2008 IIS7: Copy/Paste Directory + "Add Web Site" = 500 Error

Question: I have windows server 2008 with IIS7.
I was having problems getting a new website to work in today...I've been troublshooting for about 2 hours now and haven't come up with anything.
Heres what is weird:
I have a working website running on IIS named "TI." It points to the directory "C:\Websites\TI\web". This website works perfectly!!!
If I:

copy this directory then paste it as "C:\Websites\TI\web - Copy"
go to IIS Manager
"Add Web Site"
then select the "web - copy" directory
point a new domain to it
fireup my browser to point to the site
I get: "500 - Internal server error. There is a problem with the resource you are looking for, and it cannot be displayed."

Any ideas as to what the problem could be?
Imma 'bout gunna break this here darned keyboard over my face outta frustration.

UPDATE
If I change the original site ("TI") to point to the new copy of itself ("web - Copy")
 the website will work fine! WTF?
Answer: Maybe try something that doesn't contain spaces or special characters? It worked for me once.
Comment: nope. it didn't work...but it did surface another issue....i can change the directory name without stopping the Web Site in IIS. I shouldn't be able to do that right?
Comment: Hm, I didn't even tried it. I always stop Web Sites before changing directory names. IIS's log does say something useful releated to a file or something else?
Answer: The web sites may be configured to use the same HTTP port without setting up a host header in IIS. If you check for ASP.NET errors in the event viewer you may find an error stating that IIS failed to set up the new website using those particular bindings.
If you stop the original website, then create the new one does it work?
Answer: It ended up being a problem with windows' Permissions. Resetting them did the trick.


How do you prove this statement? If there exists a subset $Y$ of $X$ such that $Y\sim N$, then for any $x_0 \in X$, $(X-{x_o}) \sim X$

Question: How do you prove this statement in the set theory?
$X$ and $Y$ are sets. $X\sim Y$ means $X$ and $Y$ are equipotent, i.e. there is a bijection $f\colon X \to Y$. $x_o$ is a element of the set $X$.
If there exists a subset $Y$ of $X$ such that $Y\sim N$, then for any  $x_0 \in X$, $(X-{x_o}) \sim X$
Answer: Hints:

Try to prove that $\mathbb N - \{x_0\}\sim \mathbb N$
Now try to prove $X - \{x_0\}\sim X$ when $x_0\in Y$
solve the problem
profit


How do you count the number of occurences of a letter in a given word?

Question: Hi how would you count the number of occurences in the given word like shown below because with the program I have right now it doesn't seem to room correctly.
#include <stdio.h>

int main(void)
{
 char a;
 char lang[] = "pneumonoultramicroscopicsilicovolcanoconiosis";
 char i = 0;
 char count = 0;

 printf("pneumonoultramicroscopicsilicovolcanoconiosis\n");
 printf("\nEnter the letter you want to find the number of\n");
 scanf("%c", &lang);
 for (i = 0; i <= 46; i++)
  if (a == lang[i]) {
   count++;
  }
 printf("Number of %c is %d..\n", a, count);

 return 0;

Comment: You never appear to set `a`.
Comment: http://stackoverflow.com/questions/4235519/counting-number-of-occurrences-of-a-char-in-a-string-in-c
Answer: Your scanf is the problem.
Try:
 scanf("%c",&a);

Comment: Hi but it keeps giving me an error that says "unresolved external symbol"
Comment: "unresolved external symbol" is a link error, when it cannot find the implementation of a function used in program. In your program, we only have print,scanf. So most likely check ur installation and paths of libraries.
Answer: You probably shouldn't hard code the max length of the string (46) if at all possible in case you are given a longer string, but assuming it's an assigned assignment that is set it shouldn't be a problem.
i and count should also be ints if possible for a bigger size count. And &lang should be &a since lang is already assigned while a is your checker.
Answer: declare count as int instead of char
also change scanf to take input a
#include <stdio.h>

int main(void)
{
 char a;
 char lang[] = "pneumonoultramicroscopicsilicovolcanoconiosis";
 char i = 0;
 int count = 0;

 printf("pneumonoultramicroscopicsilicovolcanoconiosis\n");
 printf("\nEnter the letter you want to find the number of\n");
 scanf("%c", &a);
 for (i = 0; i <= 46; i++)
  if (a == lang[i]) {
   count++;
  }
 printf("Number of %c is %d..\n", a, count);

 return 0;
}

Comment: "declare count as `int` instead of `char`" is a good idea, but not needed.  Accumulating  the count in a `char`, though more limited that `int`, is OK.


JFileChooser shows only d: drive content

Question: May I know how I can make JFileChooser to show only d: drive content? I cannot see any of its public method enables me to do so.
Thanks.
Answer: There is a discussion here with some examples.
<code>class RestrictedWinFileSystemView extends FileSystemView{
    private File[] allowed = null;

    public RestrictedWinFileSystemView(){

    }

    public RestrictedWinFileSystemView(File[] allowed){
        this.allowed = allowed;
    }

    // apply filter here
    public File[] getRoots(){
        if(allowed != null){
            return allowed;
        }

        File[] files = super.getRoots();
        java.util.List allow = new ArrayList();
        for(int i=0; i<files.length; i++){
            File desktop = files[i];
            File[] roots = desktop.listFiles();
            int rl = roots.length;
            for(int j=0; j<rl; j++){
                File cr = roots[j];
                File[] sroots = cr.listFiles();
                if(sroots != null){
                    for(int k=0; k<sroots.length; k++){
                        File cr1 = sroots[k];
                        String path = cr1.getAbsolutePath();
                        if(path.equals("D:\\"){
                            allow.add(cr1);
                        }
                    }
                }
            }
        }
        allowed = (File[])allow.toArray(new File[0]);
        return allowed;
    }

    public File createNewFolder(File dir){
        return null;
    }

    public boolean isHiddenFile(File f) {
        return super.isHiddenFile(f);
    }

    public boolean isRoot(File f){
        return super.isRoot(f);
    }
}

JFileChooser fc = new JFileChooser(new RestrictedWinFileSystemView());
</code>
Comment: fine, but imho expression path.equals("D:\\") should not be hardcoded.
Answer: Single Root File Chooser


How to monitor svnserve.exe?

Question: I have a subversion server on Windows (CollabNet download 1.6.16 on Windows Server 2003), and it regulary starts using up 100% CPU for hours. Sadly, there is no logfile for svnserve.exe, nor a possibility to see what he is working on (AFAIK).
How do i found out

what he is doing?
what he was doing?

Regards,
Daniel
Answer: There can be a log file. Add --log-file <path> to the point where svnserve.exe is launched. Also, running it with --foreground temporarily can be useful in seeing what's happening as it happens.
Comment: +1 Thanks... I didn't find anything about the option in the docs, but I should have tried to use the --help option, since the command comes from the unix world.

How to monitor svnserve.exe?


Why is sample mean minus location parameter of shifted exponential gamma distributed?

Question: My book says the following
Suppose $X_{i} \sim$ iid $Exp(1,\eta)$
Where $Exp(\theta,\eta)$ is the shifted exponential ie has density
$$\frac{1}{\theta}e^\frac{-(x-\eta)}{\theta}$$ for $x \ge \eta$ and zero otherwise.
Then my book states
$\bar X-\eta$ $\sim$ $Gamma(\frac{1}{n},n)$
But I do not see why this is true.
I tried using mgf but it is hard to work with sample mean in mgf.
So why is it true?
Comment: What expression for the the gamma pdf are you using?
Comment: k Shape- $\theta$ Scale
Answer: If we expand your final expression, we have:$$\bar{X}-\eta=\frac{1}{n}\sum ( X_i - \eta )$$
$X_i-\eta$ is classic exponential RV with parameter $\theta = 1$. By denition Sum of $n$ iid exp RVs (with parameter $\theta$) is gamma distributed, i.e. $G(n,\theta)$, so, the sum $\sum (X_i-\eta)\sim G(n, 1)$. And gamma Rv has scaling property, i.e. if $Y$ is Gamma with $(k,\theta)$, then $cY\sim G(k,c\theta)$. Applying here $\bar{X}-\eta\sim G(n,1/n)$. I think the parameter order is swapped in your book, I'm following wiki convention, where you can also find sum and scale properties.


How might I go about flagging a post or comment containing certain keywords?

Question: I have nodes coming in via FeedAPI and direct user submission, and I've got comments. A client requires me to check incoming nodes against a watch list of keywords. The posts and comments don't need to be blocked, because the watch list is fairly expansive (~1000 words but many are very context dependent). Rather, I need to be able to check the contents of a post or comment against the list and set a flag that triggers a notification to a moderator, who will manually review the content.
Is there a module that can help me with this? Barring a module, I could use a few clues to get me started on this, e.g.
"To check the content on a newly published node or comment, you could do these things."
"To flag based on a hit, you could do this thing."
Comment: We resolved it with a rule using custom PHP: We built a regexp around the blacklist, evaluated the node content against the regexp, and we send notifications to our compliance team if the PHP returns true.
Comment: There's also the "Text comparison" Rules condition, which may be helpful, too.
Answer: Look at hook_node_xyz (d7) or hook_nodeapi (d6) to add code after node save or update.
Answer: I hope you are using D6 because most related modules are not released in D7 yet. Here is an overview.
Spam module hasn't been ported yet either.
Mollom is more of an automated service solution, don't think you can use your custom word list with it.
Answer: Have you looked at the Search ApI for SolR module? I have not worked with it, but I have read a bit on it. SOLR search works on the Apache Database (if that is what you are using) and the module links it into Drupal.


What is the main difference between key-value and wide column nosql databases?

Question: What is the main difference between key-value and wide column? Is it that all data from a given column is stored together, which makes reads of specific columns faster?
Answer: With a key-value nosql db, every key only maps to one value. With a wide-column nosql db, every key maps to potentially many columns that can be selected. This can make reads more efficient, since we only need to read the columns that we are interested in. With the key-value nosql db, all the columns would be in the same value field, so everything would have to be read.
Comment: So is DynamoDB actually a wide-column store that only has the query capacities of document-store unless the fields are indexed?

This answer says DynamoDB is ""wide-column"", but could not query unindexed fields without reading the whole record: https://stackoverflow.com/a/65067047/7053488
Answer: A wide-column store is like a 2-dimensional key-value store, where the first key is used as a row identifier and the second is used as a column identifier.


How to position object in react-three-fiber

Question: I have a cube mesh on a canvas here and I would like to move it to the left (change its X-axis) without changing its point of rotation. I have tried applying the argument position={[1,0,0]} to the mesh component in the box component but it seems that it only shifted the box away from the point of rotation, which is at the center of the canvas. I am planning on creating more 3d boxes similar to the one in the image below in the future, so how would I position them while also keeping each box's point of rotation at the center of the box, separately?

Here is my code:
import React from "react";
import { Canvas } from "@react-three/fiber";
import { OrbitControls } from "@react-three/drei";

function Box() {
  return (
    <mesh>
      <boxBufferGeometry attach="geometry" />
      <meshLambertMaterial attacah="material" color="white" />
    </mesh>
  );
}

const Background= () => {
  return (
    <Canvas>
      <OrbitControls
        enableZoom={false}
        rotateSpeed={2}
        autoRotate={true}
        autoRotateSpeed={5}
      />
      <ambientLight intensity={0.5} />
      <spotLight position={[10, 15, 10]} angle={0.3} />
      <Box />
    </Canvas>
  );
};

export default Background;

I am new to using React Three Fiber so any references/documentation or suggestions would be very helpful. Thanks
Comment: Just to be sure, you want to move the cube and not the camera ? Because that's what it could mean to change the boxes x axis position without changing its center. I might guess that you're trying to make the box rotate around the center and not on itself maybe ?
Answer: The mesh component just like the spotLight component takes a position property which is an array of length 3 for x, y and z co-ordinate


Tell pianist to play entire piece softly, except one part

Question: I've composed a short melody, however I'm very new to all this piano theory, how would I tell the pianist to play the entire piece softly? (mp, not pp), and how would I write exceptions for specific notes? For example, take this piece of music.
How would I get the pianist to play the entire piece softly, but the bar in red, to be played regularly?
Answer: Another approach would be to simply state the instructions either in a blob of text preceding the music page or perhaps somewhere between the title and the music:

This though would require translation should the work be published for e.g. Klingons or Lojbanists who may be familiar with classical music scoring conventions but not English.
<code>% LilyPond engraving system - http://www.lilypond.org/
\version "2.18.0"
\header {
  title = "Vuvuzela Concerto in D"
}

\markup {
  \vspace #2
  \italic {
    "Play entire piece softly ("
    \dynamic mp
    ") except for measure 7." }
}

bbbb = {
 \tempo 4=96
 bes1~bes~bes~bes~bes~bes~bes\ppp
}

\score {
  \new Staff << \bbbb >>
  \layout { }
}
</code>
(Redundant information may also help future translators link language to the musical notation of the time, and will otherwise help reinforce the composer's intentions—however bizarre they may seem.)
Comment: Vuvuzela Concerto in D. Key signature is C. The entire song is a Bb played for seven measures. This checks out.
Comment: @Kevin: Like most wind instruments, the vuvuzela is a transposing instrument. This concerto is scored for a vuvuzela in E. (Since the vuvuzela repertoire is mostly atonal, key signatures are typically not employed).
Comment: Can a vuvuzela be played *ppp*? Would circular breathing help that long note? So many questions...
Comment: Yeah, that is pretty hilarious. It's got to be one of the more difficult pieces in the vuvuzela repertoire.
Comment: @Restioson https://www.youtube.com/watch?v=wf2P8SnOwLo
Comment: I come from South Africa, the not-so-proud home of the Vuvuzela. Up until this day, I did not know that there was such a thing as a "Vuvuzela Concerto"
Answer: Why are we making such a fuss over this?  If you want the piece to start mp, write 'mp' in the first bar.  If you want a particular section played mf, write 'mf' at that point. Then 'mp' again.
A confirmatory '(sempre mp)' might be useful at a new section of the piece.
BTW, there is no such thing as 'regular volume'.   If you want mf, say so.
Comment: If the piece is longer than a few bars, then some pianists may interpret ***mp*** as merely a starting point, rather than as something that needs to be maintained throughout. I think that it is worth adding ***sempre*** if an even volume is important.
Comment: Blimey!  My concise, common-sense answers aren't always THAT popular!  :-)
Comment: @AndrewWoods I'm not so sure; if there were no other markings then I'd say you're right.  If there is a bar in the middle with a different marking and then back to mp in the subsequent bar, there is no ambiguity whatsoever.  If you want to enforce dynamics in the player beyond what is conventional, I would like to point out that the player is free to ignore your markings anyway.
Answer: The conventional method is to write sempre mp in the first measure. Sempre means always.
The exceptional measure could be marked as più forte ("louder"), followed by sempre mp again.
Another possibility is rinforzando ("reinforced") with a dashed line after it to indicate the emphasized part. Individual notes can be marked as rfz.
Answer: You can instruct the pianist to use the soft pedal by writing una corda above the score, at the very beginning.
Mark the louder passage with tutte le corde or tre corde to indicate normal volume.
Soft pedal can affect timbre. If you don't want that, you can just use the standard dynamic markings to indicate soft (piano) or loud (forte) in the appropriate sections.


ERROR TypeError: Cannot read property 'grower' of undefined

Question: I have a button which calls a function 'SaveNewOpportunity'. In component file I have defined the function.
However on Clicking the button I  am getting error
ERROR TypeError: Cannot read property 'grower' of undefined

HTML Code:
  <button
   mat-flat-button
   color="accent"
   (click)="saveNewOpportunity()"
   [disabled]="isEdit">
   Save </button>

Typescript code:-
saveNewOpportunity() {
    this.opportunity.projectId = this.project.id;
    this.opportunity.opportunityId = null;
    this.opportunity.oppName = this.opportunity.oppName;
    this.opportunity.description = this.opportunity.description;
    this.opportunity.formula = this.opportunity.formula;
    this.opportunity.createdDate = this.opportunity.createdDate;
    this.opportunity.createdBy = sessionStorage.getItem('username');
    this.opportunity.ptnlFormula = this.ptnl_formula;
    this.opportunity.isonmain = this.opportunity.isonmain;
    this.opportunity.active = this.opportunity.active;
    this.opportunity.elgblFormula = this.eligible_formula;
    this.opportunity.oppAction = this.opportunity.oppAction;
    this.opportunity.flatCutOff = this.thresholdGroups.grower.cutOff;
    this.opportunity.stopperCutOff = this.thresholdGroups.stopper.cutOff;
    this.opportunity.dropperCutOff = this.thresholdGroups.dropper.cutOff;

    // loader
    this.isLoadingResults = true;
    this.recommendationService
        .saveNewOpportunity(this.opportunity)
        .subscribe(
            response => {
                let newOppData: any = response;

                if (this.opportunityList !== undefined) {
                    this.opportunityList.push(newOppData);
                }
                this.oppList = new MatTableDataSource<any>(
                    this.opportunityList
                );
                this.snakbar.statusBar(
                    'New Opportunity saved successfully',
                    'Success'
                );
                this.isOpportunityCreationScreen = true;
                this.isLoadingResults = false; //loader
            },
            error => {
                this.isLoadingResults = false; //loader
                this.snakbar.statusBar(
                    'New Opportunity save failed',
                    'Failure'
                );
            }
        );
}

I can't seem to locate the problem.The error shown in browser console is
OpportunityComponent.html:734 ERROR TypeError: Cannot read property 'grower' of undefined
at OpportunityComponent.push../src/app/layout/opportunity/opportunity.component.ts.OpportunityComponent.saveNewOpportunity (opportunity.component.ts:772)
at Object.eval [as handleEvent] (OpportunityComponent.html:737)
at handleEvent (core.js:21652)

Comment: It seems that your `this.thresholdGroups` in undefined. Please check if it was initialized correctly. You cannot get `grower` because you are trying to get this value from undefined
Comment: @saad in your html check around your line 734, you try to use `grower` property ?
Comment: `this.thresholdGroups` is not initialized correctly. Can you show how you initialize it?
Comment: Thankyou @OleksiiMiroshnyk I initalised it and its working now
Comment: No I have imported thresholdGroups and created instance of it. I didnt post the entire component.ts code because its too lengthy.
Comment: Ok, I didn`t catch that thing: ```this.recommendationService.saveNewOpportunity(this.opportunity)```. The signature of your method does not include any parameters, but you pass arguments here. Maybe you have problems caused by context lost.
Comment: @Florian You are right, my fault )
Comment: Maybe inside your html-template you need use `?.` operator
Comment: import {
    ThresholdStats,
    ThresholdGroups
} from '../custom-components/threshold/threshold.model';                                            export class OpportunityComponent implements OnInit {                                             thresholdGroups: ThresholdGroups;
Comment: @saad You just declared your thresholdGroups, but did not initialize it
Comment: @Florian No I have posted my html code...I have not used or written any extra code in my html
Comment: @OleksiiMiroshnyk How do I initialize it then???
Comment: @OleksiiMiroshnyk How do use ?. inside html .... I don't know
Comment: @saad ```thresholdGroups: ThresholdGroups = new ThresholdGroups()```
Comment: @saad Yeah, cool :)
Answer: As per the suggestion by @OleksiiMiroshnyk
Changing my code from this
thresholdGroups: ThresholdGroups

to
thresholdGroups: ThresholdGroups = new ThresholdGroups()

did the trick.
Although it used to work initially but I don't know what changed.
Anyway creating instance of object like OleksiiMiroshnyk suggested me solved the problem.


Identifying target machine (32 bit or 64 bit) with ClickOnce deployment

Question: I have a Windows Forms application and am deploying that application through ClickOnce deployment. Now, I've a third-party DLL file and it has different versions for 32-bit and 64-bit OS.
Is it possible to deploy different DLL files based on the target machine (32-bit or 64-bit) through ClickOnce?
Comment: Do the two different dll versions have the same file name?
Comment: @whatknott: Yes, both dlls are having same name, even the version number. Only difference is size.
Answer: [Edit]
It's not necessary to use reflection. You can add a reference to your program directly in the loader and kick it off. Did a blog post with code about it at Tech and Me.

You could include both versions in your deployment, but name them differently. Then have a loader app check if you are on a 32bit or 64bit system, copy the correct dll (eg thirdparty64.dll -> thirdparty.dll) which your real program is linked to, and then invoke your program from the loader with for example Assembly.Load and use reflection to start your main method.
An easier method is to compile your application to run as x86, ensuring it will always run in 32bit mode. If you don´t rely on some specific application being installed on the machine in 32/64bit versions this could be the best choice.
Comment: Thanks for your answer. Is this possible with Clickonce? Is this loader application going to run while clickonce deploys the application or it should be run on my application first run? During the clickonce deployment I'm not sure how do we copy this dll, as I'm not sure whether it gives us the installation location. Please correct me if I'm wrong.
Comment: You would have to do it once the application runs the first time, not on deployment. I´ll try it myself as well.
Comment: Did a small test project and blog post on this. Edited my answer to reflect it.


Manipulating the product of the dot product of multiple vectors is producing a paradox

Question: Unless otherwise indicated all defined vectors lie on the surface of the unit sphere (i.e their norm is 1).
Let's take the following expression:
$(V\cdot Z_1)(V\cdot Z_2) = V^TZ_1V^TZ_2$
Given that the dot product is commutative the following is true:
$V^TZ_1V^TZ_2 = V^TZ_1 Z_2^TV$
Let's assume there exists a vector $Z'$ such that $V^TZ_1 Z_2^TV = V^TZ'$
Then:
$VV^TZ_1 Z_2^TV = VV^TZ'$ but since $V$ is of norm 1 we get:
$Z_1 Z_2^TV = Z'$
Which is a vector colinear to Z_1 and norm $Z_2^TV$.
However $Z_1$ and $Z_2$ were arbitrary so you can redo the proof and multiply by $V^T$ from the right instead and you get that $Z'$ must be colinear to $Z_2$. It is of course impossible for $Z'$ to always be colinear to 2 arbtirary vectors.
So one might be tempted to say no such $Z'$ exists. However that's not possible.
Take $0 \leq (V\cdot Z_1)(V\cdot Z_2) = \theta \leq 1$ Since that scalar is in the range of $\cos$, trivially there exists $Z'$ such that $Z' \cdot V = \theta$
What did I do wrong?
Answer: Even if
$$V^T V = \left[ \begin{matrix} V_x & V_y & V_z \end{matrix} \right] \left[ \begin{matrix} V_x \\ V_y \\ V_z \end{matrix} \right] = V_x^2 + V_y^2 + V_z^2 = 1$$
you have
$$V V^T = \left[ \begin{matrix} V_x \\ V_y \\ V_z \end{matrix} \right] \left[ \begin{matrix} V_x & V_y & V_z \end{matrix} \right] = \left[ \begin{matrix} V_x^2 & V_x V_y & V_x V_z \\ V_y V_x & V_y^2 & V_y V_z \\ V_z V_x & V_z V_y & V_z^2 \end{matrix} \right] \ne I$$
In particular,
$$V V^T Z = \left[ \begin{matrix} V_x^2 & V_x V_y & V_x V_z \\ V_y V_x & V_y^2 & V_y V_z \\ V_z V_x & V_z V_y & V_z^2 \end{matrix} \right] \left[ \begin{matrix} Z_x \\ Z_y \\ Z_z \end{matrix} \right ] = \left[ \begin{matrix} V_x^2 Z_x + V_x V_y Z_y + V_x V_z Z_z \\ V_x V_y Z_x + V_y^2 Z_y + V_y V_z Z_z \\ V_x V_z Z_x + V_y V_z Z_y + V_z^2 Z_z \end{matrix} \right] \ne \left[ \begin{matrix} Z_x \\ Z_y \\ Z_z \end{matrix} \right ]$$
Perhaps you forgot that matrix multiplication isn't commutative?
Comment: Right I am an idiot I was doing $(V^TV)$ instead of $VV^T$


Firebase Messaging: Unable to send message to iOS device due to required APNs SSL Cert expired or not uploaded

Question: After checking this similar question and another, I am still unable to send messages to my iOS device.
I am sending messages via my Firebase Cloud Functions which is working correctly for android but for iOS devices I receive this error in the end: A message targeted to an iOS device could not be sent because the required APNs SSL certificate was not uploaded or has expired. Check the validity of your development and production certificates.
I have confirmed that I do have the proper certificates under Push Notifications

And within my Firebase Project Settings, I have also added my APN Key here from the Apple Dev Console.

I have done this process 3 times already and it still is not working appropriately.
To confirm, here is my code for cloud functions
const functions = require("firebase-functions");
const admin = require('firebase-admin')
const { CloudTasksClient } = require('@google-cloud/tasks');
const serviceAccount = require('./serviceAccountKey.json');
admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
    databaseURL: "https://[project-id].firebaseio.com"
})

exports.firestoreTtlCallback = functions.https.onRequest(async (req, res) => {
    try {
        const payload = req.body;
        let entry = await (await admin.firestore().doc(payload.docPath).get()).data();
        let tokens = await (await admin.firestore().doc(`/users/${payload.uid}`).get()).get('tokens')
        const notification = {
            notification: {
                title: 'App',
                body: entry['text']
            }
        }
        const response = await admin.messaging().sendToDevice(
            tokens,
            notification
        )
        response.results.forEach((result, index) => {
            const error = result.error;
            if (error) {
                functions.logger.error('Failure sending notification to', tokens[index],
                    error)
                if (error.code === 'messaging/invalid-registration-token' || error.code === 'messaging/registration-token-not-registered') {
                    // remove token here

                }
            } else {
                log("Successfully send message!")
            }
        })
        await admin.firestore().doc(payload.docPath).update({ expirationTask: admin.firestore.FieldValue.delete() })
        res.sendStatus(200)

    } catch (err) {
        log(err)
        await admin.firestore().doc(payload.docPath).update({ expirationTask: admin.firestore.FieldValue.delete() })
        res.status(500).send(err)
    }
})

Answer: The reason why I was not getting authorized is because my Team ID in my Firebase Project Settings was not the same ID that created in the Apple Developer Console. Once I made sure that these were equal and went through the process once more, I was able to get notifications successfully.


UEC 10.10 Node Controller installation problem; no access to internet

Question: I am trying to setup a new UEC Cloud network using Ubuntu UEC 10.10, but I am having some difficulties with the Node Controller setup !
I am working (for the moment) on a small setup, using two computers. The first one, for CLC, CC, Walrus and SC. Second computer to be used as NC.
I am doing fresh and clean re-installation of everything.
My problem is that the NC do not have any access to the internet after its installation. As if the CC's computer would not do any forwarding from the private network to the public network. I cant finish the setup, I cant update/upgrade the NC. I can't apt-get install ntp.
If the NC can't talk to the internet, I will see the same problem with the instances too. From the NC, the only computer I can ping is the CC, using its private and public address.
Why would the CC block the NC access to internet ?
Note that I don't have these problems on Ubuntu 10.04 (using the same hardware), but I really need to be on Ubuntu 10.10.
Comment: What does your /etc/network/interfaces file show?  Can you append these files to your question?
Answer: Assuming your public IPs are in the network 188.8.131.52 and that your private switch is using the network 192.168.1.0.
You need to enable the communications to get through between the private addresses (ranging from 192.168.1.1 to 192.168.1.254) to all the public addresses (ranging from 220.127.116.11 to 220.127.116.11).
Calling the following command on the CC would do that:
<code>iptables -t nat -I POSTROUTING -s 192.168.1.0/24 -d 18.104.22.168/8 -j MASQUERADE
</code>
Answer: Likely you need to add a masquerading rule to iptables to facilitate forwarding packets from your private node network to the WAN/Internet.
Assuming you have a single Cloud Controller and a single Node Controller;  the topology implemented something close to the following:
INTERNET<--> eth0[CloudController]eth1 <-->[Switch]<-->eth0[NodeController]
...........192.168.1.100......................10.0.0.1.....................10.0.0.2
Try something like this on the Cloud Controller:
$ sudo /sbin/iptables -t nat -A POSTROUTING -s 10.0.0.0/24 -o eth0 -j MASQUERADE
This assumes your Cloud Controllers public facing interface is eth0, and that the Cloud Controllers private facing interface is eth1 on a 10.0.0.0 network of which the Node Controller is also a member.
If this works, make the rule permanent ( you can even simply write it to /etc/rc.local )
Good luck!
SLR-
Answer: Neither of the other answers here give a permanent fix.  Yes, that does make the nodes be able to access your Internet or other network, which may include making them able to access the Walrus and/or Cloud Controller.
Unfortunately Eucalyptus is notorious for blowing away the nat table and recreating it, making your server forget the MASQ rule.  I find I have to run the iptables MASQ rule periodically before starting a new instance or the node can't reach my Walrus to download the image.

Would have just done this as a comment, but my score here started as a 1 despite my higher ranking on Stack Exchange since I've never posted on serverfault.


The relationship between covariance and inner product

Question: It looks like covariance has some relationship between inner product. I have checked that covariance is bilinear and symmetric, but not positive definite (it is positive semi-definite). Although in WIKI, there are some information about the relationship between covariance and inner product, I still cannot really get the point. Hope someone will give me a more detailed answer about the relationship.
Answer: If $X$ and $Y$ are random variables with finite second moments on a probability space $(\Omega, \mathcal F ,P)$  and $L^{2}$ is the space of square integrable random variables on $(\Omega, \mathcal F ,P)$ with the inner product $ \langle X, Y \rangle=EXY$ then covariance of $X$ and $Y$ is the inner product of $X-EX$ and $Y-EY$.
Comment: Very appreciate for your answer. But since I haven't learn advanced probability yet, which makes me hard to understand what "finite second moment on probability space" means. Would you mind explaining more about it or give me some advice how to learn it?
Comment: @AlexanderWang Well, $EXY$ is an inner product for random variables and covariance is the inner product of $X-EX$ and $Y-EY$.
Comment: Oh I see what "finite second moment" means. Excuse my poor English. I see your point and I finally understand what Wiki says. Thank you very much.


Boxes in grid too tall

Question: I'm trying to create a grid of squares where some blocks are double the size of others and some others are double the width, but the same height.
This Codepen illustrates what I'm trying to do. The fourth and fifth blocks should be double the width, but only one row high. But instead, they're two rows high.
HTML

CSS
.grid {
  display: grid;
  gap: 20px;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
}

img {
  width: 100%;
  height: auto;
}

.grid>div:nth-child(1),
.grid>div:nth-child(8) {
  grid-row: auto / span 2;
  grid-column: auto / span 2;
}
.grid>div:nth-child(4),
.grid>div:nth-child(5){
  grid-column: auto / span 2;
}

I'm not telling those blocks to span two rows so I don't understand why they are.
Answer:
I'm not telling those blocks to span two rows so I don't understand
why they are.

They are not spanning two rows. The image inside the grid cell has an aspect ratio of 1-to-1, therefore filling only half of some cells (this can be seen in your browser's Developer Tools.)
The first example illustrates this with:
.grid div {
    background-color: cornflowerblue;
    border: 1px solid;
}

.grid div {
    background-color: cornflowerblue;
    border: 1px solid;
}

.grid {
  display: grid;
  gap: 20px;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
}

img {
  width: 100%;
  height: auto;
}

.grid>div:nth-child(1),
.grid>div:nth-child(8) {
  grid-row-start: span 2;
  grid-column-start: span 2;
}
.grid>div:nth-child(4),
.grid>div:nth-child(5){
  grid-column-start: span 2;
}

The second example illustrates this with:
img {
   height: 100%;
}

.grid {
  display: grid;
  gap: 20px;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
}

img {
  width: 100%;
  height: 100%;
}

.grid>div:nth-child(1),
.grid>div:nth-child(8) {
  grid-row-start: span 2;
  grid-column-start: span 2;
}
.grid>div:nth-child(4),
.grid>div:nth-child(5){
  grid-column-start: span 2;
}

Boxes in grid too tall


Lebesgue measure: show that $\mu^*(k\,A)=k \mu^*(A)$

Question: For $k\gt 0$ and a subset $A$ of $\mathbb{R}$, let $k\,A=\{kx\mid x∈A\}$. Show that $$\mu^*(k\,A)=k \mu^*(A)$$
and that $A$ is measurable if and only if $k\,A$ is measurable.
Comment: assuming A is measurebale, I tried to use the outer measure definition.And I know that, if a set A is covered by an interval [a, b], then the corresponding set kA is covered by the interval [ka, kb].but I can't recall any path to find the answer for this.
Comment: Denote by $l([a,b])$ the length of the interval $[a,b]$. Is it clear that $l([ka, kb])= k\cdot l([a,b])$?
Answer: To show the equality, you can try showing each is $\leq$ the other by using the definition of outer measure, i.e. let $A$ be covered by a countable union of intervals $I_{n}$ such that $\mu^{*}(A)+\varepsilon<\sum_{n}l(I_{n})$, then go on to say something about $\mu^{*}(kA)$, and vice versa.
Take a subset $B$ of $\mathbb{R}$. Then by the equality to be shown, you can get $\mu^{*}(B\cap A)+\mu^{*}(B\cap A^{c})=\mu^{*}(k(B\cap A))+\mu^{*}(k(B\cap A^{c}))=\mu^{*}(kB\cap kA)$ $+\mu^{*}(kB\cap kA^{c})$ which may be useful for the second statement.


Exchange Server Online Rewriting "To" Addresses

Question: I'm using Exchange Server as part of a 365 subscription.
I've added multiple 'accepted domains'.
There is a single mailbox, with multiple email addresses using a mix of these accepted domains. I can receive email sent to any of these addresses without a problem.
But for some reason no matter which of these email addresses I send to, once the message arrives the "To:" addresses has been rewritten. This happens if I downloaded the messages in Outlook or another mail program so I assume it's happening in Exchange Server.
The "To:" address is the User ID of the mailbox.
I've know there's a feature on On Premise Exchange (https://docs.microsoft.com/en-us/exchange/architecture/edge-transport-servers/address-rewriting-procedures?view=exchserver-2019) but for the life of me I can't figure out how to turn it off.
Ideas?
Answer: Based on your description, whichever of the specific mailbox's email addresses is put to the 'To:', once the messages are received, the 'To:' address will be rewrote? Is my understanding right? What does the address to rewritten to?
As far as I know, the address rewrite is not supported in Office 365 by default. Do you have Edge Transport server configured in your environment?
To disable address rewriting, run the following command:
Disable-TransportAgent "Address Rewriting Inbound Agent"; Disable-TransportAgent "Address Rewriting Outbound Agent"
Comment: Hi, what's going on with your problem now?


Texto e inputs na mesma linha

Question: Preciso colocar um texto, um input-text, outro texto e outro input text na mesma linha (row) em html. Não consigo encontrar uma maneira.
Alguém pode me ajudar?
Comment: `texto `
Comment: Não entendi sua duvida? você quer colocar `label` e `input` um do lado do outro?
Comment: Teria um exemplo de como vc esta fazendo?
Answer: Você pode colocar um label na frente do seu input, ficando assim:

Nome: <input type="text" name="nome">
Email: <input type="text" name="email">

Caso queira colocar um input em baixo de outro, você coloca um br pra quebrar a linha.
Answer: com um simples CSS

#inline {
    display: inline;
}

   um texto <input type="text" placeholder="um input"/>
   outro texto <input type="text" placeholder="outro input"/>

Texto e inputs na mesma linha


When you randomly shuffle a deck of cards, what is the probability that it is a unique permutation never before configured?

Question: I just came back from a class on Probability in Game Theory, and was musing over something in my head.
Assuming, for the sake of the question:

Playing cards in their current state have been around for approximately eight centuries
A deck of playing cards is shuffled to a random configuration one billion times per day
Every shuffle ever is completely (theoretically) random and unaffected by biases caused by human shuffling and the games the cards are used for
By "deck of cards", I refer to a stack of unordered $52$ unique cards, with a composition that is identical from deck to deck.

This would, approximately, be on the order of $3 \cdot 10^{14}$ random shuffles in the history of playing cards.
If I were to shuffle a new deck today, completely randomly, what are the probabilistic odds (out of $1$) that you create a new unique permutation of the playing cards that has never before been achieved in the history of $3 \cdot 10^{14}$ similarly random shuffles?
My first thought was to think that it was a simple matter of $\frac{1}{52!} \cdot 3 \cdot 10^{14}$, but then I ran into things like Birthday Paradox.  While it is not analogous (I would have to be asking about the odds that any two shuffled decks in the history of shuffled decks ever matched), it has caused me to question my intuitive notions of Probability.
What is wrong in my initial approach, if it is wrong?
What is the true probability?
And, if the probability is less than $0.5$, if we how many more years (centuries?) must we wait, assuming the current rate of one billion shuffles per day, until we reach a state where the probability is $0.5$+?   $0.9$+?
(Out of curiosity, it would be neat to know the analogous birthday paradox answer, as well)
Comment: The situation is not the same as in the birthday paradox. The birthday paradox works because the two identical birthdays may appear between *any two* of the persons. However, in your experiment, you demand that you are one of the two persons involved in the same card deck. A situation analogous to the birthday paradox would be given by the question "what is the chance that over the last 600 years, two persons have produced the same random shuffle".
Comment: The last part of this question doesn't make sense; the probability will go *down* over time, not up.
Answer: Your original answer of $\dfrac{3 \times 10^{14}}{52!}$ is not far from being right. That is in fact the expected number of times any ordering of the cards has occurred.
The probability that any particular ordering of the cards has not occurred, given your initial assumptions, is $\left(1-\frac1{52!}\right)^{(3\times10^{14})}$, and the probability that it has occurred is 1 minus this value.  But for small values of $n\epsilon$, $(1+\epsilon)^n$ is nearly $1+n\epsilon$.  In particular, since $52!\approx 8\times 10^{67}$ and so $\dfrac{3\times10^{14}}{52!}\approx 3.75\times 10^{-54}$ is microscopically small, $1-\left(1-\frac1{52!}\right)^{(3\times10^{14})}$ is very nearly $\frac1{52!}\times (3\times10^{14})$.
Comment: In most contexts(including this one) epsilon is a small value. In this case it means the wonderfully small 1/52! Just an aside, not always but in many contexts epsilon is going to be a placeholder for an infinitesimal, or a numberthat we are going to let arbitrarily small.
Comment: Just correcting a phrasing mistake: the final answer, proven to be right, is the probability that the combination is **not** unique. So the chances to be unique are extremely close to 100%.
Comment: I'm sorry, could you explain what ε represents in this case?
Comment: What BBischof said is correct.
Answer: There are $52!$ possible orders for a deck of $52$ cards. If a unique order of a deck of $52$ unique cards had been created every second since the big bang, the chances that any two of them were repeated is approximated by $$1-(1-1/52!)^{(10^{17})} = 1.2397999\times10^{-51}\ .$$
To show the size of this number, assume that the same shuffling has taken place every second on one planet orbiting every one of the estimated $10^{24}$ stars in the known universe since the beginning of time. The chances that all of those orders has been unique is still
$$99.999999999999999999999999876\%\ .$$
Go shuffle a deck of cards six times and create something truly unique!
Answer: Suppose we shuffle a deck and get a permutation p. For each previous shuffling there is a 1-1/52! chance that p doesn't match it. Each previous shuffling is independent, in that regardless of what p and the other permutations are, the chance of p matching the shuffling is 1-1/52! When probabilities are independent we can simply multiple them to find the chance of all the events happening. In this case, the each event is actually a match not happening, so the chance of no matches given n previous shuffles is (1-1/52!)^n. We can then complete the calculations as Michael did.
Answer: You're right to question your assumptions and right that the formula you give ($n=$number of shuffles that have been made/$N=$number of possible shuffles) isn't quite right (as others have noted), but unlike the birthday paradox, here the difference works to lower the chances of a match, not raise them.  Working with smaller numbers helps with the intuition a bit: suppose that there have been $n$ rolls of a $N=$20-sided die, and you want to know what your chances are of hitting a match to some previous roll.  Then a reasonable first approximation for small $n$ is that the probability of a match is $n/20$: this is correct for $n=0$ and $n=1$, and it matches the 'intuition' of having $n$ previous rolls to match against.  But bumping the number up to $n=20$ shows the breakdown of the approximation; after 20 rolls, your odds aren't 100% of rolling a number that's already been rolled once, and after 21 rolls they certainly aren't greater than 100%!
The flaw here, of course, is that after $n$ rolls there won't have been $n$ unique numbers rolled; instead, there are likely to already be some duplicates.  But it's also clear from thinking about the probability this way that the odds of a match on your next shuffle (or roll) must be less than what the odds would be if all the previous shuffles were unique, and so must be less than the $n/N$ approximation that you use (with $n=3\times 10^{14}$ and $N=52!$).
(There's also a relatively intuitive way of looking at the birthday paradox that explains its 'paradoxical' nature; there you're not trying to match one thing against $n$, but $n$ things against each other - so the correct quantity to use isn't $n$ itself, but instead the number of possible matches, $n(n-1)/2\approx n^2/2$, with each one (heuristically) having a $1$ in $N$ chance of actually matching; this is why you can start expecting a match for a value of $n$ that's proportional to $\sqrt{N}$ rather than for a value of $n$ that's proportional to $N$.)
Answer: Applying the birthday paradox logic when calculating the chance a 52 cards deck order has been shuffled before in the history of mankind.
x= the number of times a 52 deck of cards has been shuffled before in the entire history.
p = 1 - ((52!)! / 52!^x * (52!-x)!)
This part is highly speculative:
Lets say there have lived 30 Billion humans in the last 800 years that playing cards been around. When somebody play cards 1x a month for 50 years he shuffles 600 times. Some people never play cards, other way more than once a month. Lets take 600 times in a lifetime as an average, then in the entire history there would been 18000 billion shuffles.
Now comes a practical problem it's easy to fill in 18000 Billion for x but I can't find a calculator who can handle the big numbers involved in the the calculation and I lack the math skills to solve the calculation in a different way.
Comment: He said that the birthday paradox variant of this problem isn't the one he has in mind: in that version of the question, you're not asking whether or not a *particular* shuffle has ever happened before, but rather just whether or not *any* two shuffles in the history of mankind were the same.

Anyway, if we do use your numbers and use the birthday paradox version of the problem as you suggested, we get $p \approx 2 \times 10^{-42}$.


Finding the intersection of circles in Stewart's Galois Theory

Question: On page 94 of Stewart's "Galois Theory", 4th edition, he leaves as an exercise the the case of the intersection of two circles.
He is proving that the pythagorean closure $\mathbb{Q}^{py}$ of $\mathbb{Q}$ contains all constructible points. Taking $z$ in the intersection $C(z_1, \left|z_2 - z_3\right|) \cap C(z_4, \left|z_5 - z_6\right|)$ of two circles where $z_j \in \mathbb{Q}^{py}$ he arrives at
$(z - z_1) (\overline{z} - \overline{z_1}) = r^2$
$(z - z_4) (\overline{z} - \overline{z_4}) = s^2$
where $r = \left|z_2 - z_3\right|$ and $s = \left|z_5 - z_6\right|$. He says that one can solve in $z$ and $\overline{z}$ and get that $z$ satisfies a quadratic equation with coefficients in $\mathbb{Q}^{py}$. I am having trouble proving that, can someone help?
Answer: Sure. The main idea is: intersection two circles is the same than intersecting a circle and a line.
If you substract your two equations, you will get a linear equation in $z$ and $\bar{z}$, so you can write $\bar{z}$ under the form $az+b$, where $a$ and $b$ are constructible (easy to see from the constructibility of the $z_j's$), then you can plug the expression of $\bar{z}$ into your first equation to get a quadratic equation satisfied by $z$, where the coefficients are also constructible.
Comment: Thank you very much!