Erro na listagem com PDO

Question: Estou tentando aprender PDO mas estou tendo dificuldades.
Tenho 3 arquivos:
Planos.php
<?php

  namespace PLANOS;

  use BASE\Base;

  require_once "Base.php";

  class Planos extends Base {

      public function __construct ($_conexao, $_tabela) {

         parent::__construct ($_conexao, $_tabela);

     }

  }

?>

Base.php
<?php

 namespace BASE;

 abstract class Base {

     private $conexao;
     private $tabela;
     private $ultimoCadastrado;

     public function __construct($_conexao, $_tabela) {

         $this->conexao = $_conexao;

         $this->tabela = $_tabela;

     }

     public function cadastrar (array $objeto) {

         $parametros = $valores = "";

         foreach ($objeto as $objeto=>$valor):

           $parametros.= $objeto.",";
           $valores.= "'".$valor."',";

         endforeach;

         $parametros = substr($parametros,0, -1);
         $valores = substr($valores,0, -1);

         $sql = "INSERT INTO ".$this->tabela." (".$parametros.") VALUES (".$valores.")";

         $query = $this->conexao->prepare($sql);

         $execucao = $query->execute();

         $this->ultimoCadastrado = $this->conexao->lastInsertId();

         return $execucao;

     }

     public function ultimoIdCadastrado () {

         return $this->ultimoCadastrado;

     }

     public function editar (array $objeto, $id) {

         $str = "";

         foreach ($objeto as $objeto=>$valor):

           $str .= $objeto ."='". $valor."',";

         endforeach;

         $str = substr($str, 0, -1);

         $sql = "UPDATE ".$this->tabela." SET ".$str." WHERE id".ucfirst($this->tabela)."=".$id;

         $query = $this->conexao->prepare($sql);

         return $query->execute();

     }

     public function bloquear ($id, $bloqueado) {

         $sql = "UPDATE ".$this->tabela." SET bloqueado = '".$bloqueado."' WHERE id".$this->tabela." = ".$id;

         $query = $this->conexao->prepare($sql);

         return $query->execute();

     }

     public function excluir ($id) {

         $sql = "DELETE FROM ".$this->tabela." WHERE id".$this->tabela." = ".$id;

         $query = $this->conexao->prepare($sql);

         return $query->execute();

     }

     public function listar () {

         $sql = "SELECT * FROM ".$this->tabela;

         $query = $this->conexao->prepare($sql);

         $query->execute();

         return $query->fetchAll( PDO::FETCH_ASSOC );

     }

     public function listarId ($id = null) {

         $sql = "SELECT * FROM ".$this->tabela;

         if ($id != null) $sql .= " WHERE id".ucfirst($this->tabela)."=".$id;

         $query = $this->conexao->prepare($sql);

         $query->execute();

         return $query->fetch( PDO::FETCH_ASSOC );

     }

     public function listarParametros ($where) {

         $sql = "SELECT * FROM ".$this->tabela." ".$where;

         $query = $this->conexao->prepare($sql);

         $query->execute();

         return $query->fetchAll( PDO::FETCH_ASSOC );

     }

 }

?>

Index.php
<?php

  ini_set("display_errors",true);
  ini_set("display_startup_erros",1);
  error_reporting(E_ALL | E_NOTICE | E_STRICT);

  use PLANOS\Planos;

  $conexao = new PDO('mysql:host=localhost;dbname=funeraria2', 'root', 'mysql');

  $objeto = array (

      "tipo" => 's',
      "nome" => "Carlos",
      "login" => "caca",
      "senha" => "1234",
      "bloqueado" => "n"

  );

  $objeto2 = array (
      "idAdministradores" => 3,
      "tipo" => 's',
      "nome" => "Castro",
      "login" => "abcd",
      "senha" => "4321",
      "bloqueado" => "s"
  );

  require_once "Planos.php";

  $planos = new Planos($conexao, "administradores");
//  echo $planos->cadastrar($objeto) ? 1 : 2;
//  echo "
";
  echo $planos->ultimoIdCadastrado();
  echo "
";
  echo $planos->editar($objeto2, 3) ? 1 : 2;
  echo "
";
  echo $planos->bloquear(3, 's') ? 1 : 2;
  echo "
";
  echo $planos->excluir(4) ? 1 : 2;
  echo "
";

print "
";
print_r($planos->listar());
print_r($planos->listarId(1));
foreach ($planos->listarParametros("WHERE nome = 'Carlos'") as $admin):
  print_r($admin);
endforeach;
print "
";

?>

Quando rodo esse script recebo o erro abaixo:
Fatal error:  Uncaught Error: Class 'BASE\PDO' not found in D:\Trabalhos\host\htdocs\crud\Base.php:102
Stack trace:
#0 D:\Trabalhos\host\htdocs\crud\index.php(47): BASE\Base->listar()
#1 {main}
  thrown in D:\Trabalhos\host\htdocs\crud\Base.php on line 102

Mas não consigo achar que erro é esse!
A dúvida é que só não está fazendo leitura.
Porém gravação, exclusão, edição, normal!
Comment: Ou simplesmente coloque uma barra invertida ( \ ) em `return $query->fetch( PDO::FETCH_ASSOC );` ... `return $query->fetch( \PDO::FETCH_ASSOC );`
Comment: Já tentou importar `use \PDO;` no arquivo *Tabelas.php* ?
Comment: Possível duplicata de [Namespace e PDO = Erro](https://pt.stackoverflow.com/questions/67773/namespace-e-pdo-erro)
Comment: mas poque as outras operações como inserção, deleção e update dão certo. Apenas o select não dá?
Comment: Então, use PDO; na classe abstrata resolveu. Mas ainda fica a dúvida. Porque apenas para s SELECT? porque não também para UPDATE, DELETE e INSERT?
Comment: Porque é o único que você esta usando diretamente `PDO::FETCH_ASSOC`, a resposta da pergunta que marquei como duplicata.
Comment: Então, mas a minha conexão já é feita por PDO. Então, não seria seria o caso de precisar também de fazer use PDO na classe Tabelas? Senão, porque? Pode postar como resposta que eu marco ela como aceite!
Comment: Veja: [Namespaces e Use quando usar e para que servem?](https://pt.stackoverflow.com/questions/151487/), [Como funciona namespaces no PHP?](https://pt.stackoverflow.com/questions/104420), [Para que serve realmente namespace?](https://pt.stackoverflow.com/questions/195742)
Answer: Você deve indicar que está usando uma classe nativa do PHP usando \ antes do PDO deixando assim:
new \PDO();

e
 return $query->fetch( \PDO::FETCH_ASSOC );

Acho que isso deve resolver os seus problemas. Se não resolver me mande o erro que o PHP esta retornando com as alterações que eu falei.
Comment: Oi, isso já havia resolvido. O que eu gostaria de saber é porque apenas com SELECT deu isso? Com UPDATE, DELETE e INSERT não foi preciso fazer use PDO
Comment: É por que com o SELECT você solicita um retorno para a classe  "return $query->fetch( \PDO::FETCH_ASSOC );" já nos outros você tem um retorno predefinido.
Comment: Entedeu agora o porque o SELECT deu problema?
Comment: Não sei se entendi bem. Veja. Olhe o método cadastrar, ultima linha: return $execucao;. Iso não é pedir retorno ao método? Acho que ainda estou meio confuso. Mas acxho que vou conseguir entender depois dessa tua outra resposta!
Comment: No exemplo que você deu do return $execucao o método retorna somente True ou false, já no select ele retorna ou array, ou em objetos e etc.. de certa forma você precisa informar o formato que o php vai retornar à sua consulta. que no caso seria colocando por exemplo \PDO::FETCH_ASSOC para ele retorna a consulta na forma de array.
Comment: hum, mas sem o \ ele já está retornando em forma de array. Não? Pelo menos é o que aparece no print_r(). Resolvi o problema apenas  colocando use PDO na classe de tabelas. Mas ainda estou com essa dúvida cruel!
Comment: Ele retorna por que isso default dele, você nem precisava ter colocado o  \PDO::FETCH_ASSOC dentro da função.
Comment: Vamos [continuar esta discussão no chat](https://chat.stackexchange.com/rooms/78972/discussion-between-dudut-and-carlos-rocha).
Comment: Não está dando certo o chat para mim.Mas entendi!
Comment: Espero que tenha ajudado, qualquer coisa estou a disposição.
Comment: Eu adicionei uma resposta mais próxima do que eu precisava pois apenas teve a tua resposta. Apenas para contribuir um pouco mais com o tópico e ajudar também a outras pessoas. Mas agradeço a sua ajuda!
Answer: A solução da dúvida era adicionar
use PDO

à classe Base conforme abaixo:
<?php

 namespace BASE;

 use PDO;

 abstract class Base {
...

PDO é uma classe também. Logo, mesmo sendo nativa, para que possa trazer retorno diferente de 0 ou 1, e True ou False, precisará ser referenciada!

Erro na listagem com PDO


Minimum numbers of observations for OLS (MLE) depending on number of parameters

Question: Say I want to minimize my error term $\epsilon_i = y_i - ( \sum_{n=1}^{N} \beta_n x_{in} )$ given N observed inputs $x_{in}$ and one output $y_i$ for I observations.
I am looking for the optimal parameters $\beta$ that best describe my observations. Let's just assume the $\epsilon$ are normal distributed, so we can do a OLS estimation $\min \sum_{i=1}^I \epsilon_i^2$.
I heard there is the requirement, that $I > N+1$.  But I fail to understand why.
Answer: This is because it will lead to your system being under-determined and therefore will have infinitely many solutions.
For example consider the case where $N=2$ and $I=1$. This means you are trying to fit a straight line through a single point. There are an infinite number of straight lines that will fit this point with precisely $0$ error.
The same happen if $N=3$ and $I<3$ as here you are fitting a 2-D plane to either a single point (clearly infinite solutions) or to two points. Two point make a line and you can rotate the plane around the orthogonal direction to that line thus again giving you infinitely many solutions.
Think of $N$ as your degrees of freedom and $I$ as your constraints. If you have fewer constraints than degrees of freedom then you will have an infinite number of solutions.
By contrast when $I>N$ the system is likely to be over-determined and therefore there is no solution with $0$ error which is why we used OLS to find a best fit.
Here is a poorly made illustration:

Top left image shows $N=2$ and $I=1$, you can see that the green, red and blue lines will all have zero error but also have completely different values for $\beta$ where as top right shows $N=2$ and $I=2$. Now there is only one solution (error is still zero). Bottom left shows the same thing as the top left for $N=3$, $I=2$ and bottom right attempts to show that when $N=3$ and $I=3$ there is only one 2-D plane that can pass through all three points.
Comment: thx, that was helpful.


Word Problem: What is the largest amount you cannot buy?

Question: There is a bakery with 3 options for a box of cupcakes: a box of 5, a box of 9 and a box of 24.
The question being asked is "What is the largest number of cupcakes that you cannot buy?"
Using these order sizes, you can, for example, order exactly 19 bite-size cupcakes. You'd order a box of 9 and two boxes of 5. But, you can't order exactly 17 bite-size cupcakes. There's no way to combine boxes of 5, 9 and 24 to get exactly 17 cupcakes. Are there larger size orders than 17 cupcakes that you cannot get exactly?
I've been stuck on this problem because I keep wanting to just add up all the possible combinations but I'm curious if there is a faster/more reliable way to do so.
I understand that the answer will be a number that cannot work because it won't share a common divisor among the numbers and none of the boxes of cupcakes numbers will add equally into the number being found.
Please share any insight you have to help me figure this out!
Comment: https://en.wikipedia.org/wiki/Coin_problem  There is no easy formula for three coins  They talk a bit about how to be sure you have finished the problem in the section on the Mcnugget number
Comment: Hint:  as $5$ is the smallest, try to get all the possible remainders upon division by $5$.  Turns out that it is hardest to get the remainder of $1$.  First instance is $36$.  It follows that $31$ is the largest unreachable case.
Answer: The message that I got from the wikipedia article on the Frobenius coin problem is that, for three or more coins, we need to investigate numbers that can be represented by hand or by computer, there is no magic formula. At the same time, having done that much, there is an easy means of proving that we have finished the job.
We cannot represent $31$ as $5x+9y+24z$ for integers $x,y,z \geq 0.$ The smallest denomination is $5,$ next we represent five in a row.
$$ 32 = 5 \cdot 1 + 9 \cdot 3 + 24 \cdot 0,    $$
$$ 33 = 5 \cdot 0 + 9 \cdot 1 + 24 \cdot 1,    $$
$$ 34 = 5 \cdot 2 + 9 \cdot 0 + 24 \cdot 1,    $$
$$ 35 = 5 \cdot 7 + 9 \cdot 0 + 24 \cdot 0,    $$
$$ 36 = 5 \cdot 0 + 9 \cdot 4 + 24 \cdot 0.    $$
If we want to represent any number larger than $36$ we can do it. Take some $n \geq 37.$ There is some $k \geq 1$ such that $n - 5 k$ is in the range from $32$ to $36,$
$$ 32 \leq n - 5 k < 36.$$
Indeed,
$$ k = \left\lfloor \frac{n-32}{5} \right\rfloor  $$
From the list above, find
$$ n-5k = 5x + 9 y + 24 z. $$
Then
$$ n = 5(x+k) + 9 y + 24 z.  $$
$$ \bigcirc   \bigcirc   \bigcirc   \bigcirc   \bigcirc   \bigcirc   \bigcirc  $$
Addendum: we had
$$ 32 \leq n - 5 k < 36. $$
We could write this as
$$ n - 5 k = 32 + \delta, \; \; \; \; \mbox{where} \; \; \; 0 \leq \delta \leq 4. $$
$$ n - 32 = 5 k +  \delta, \; \; \; \; \mbox{where} \; \; \; 0 \leq \delta \leq 4. $$
Indeed,
$$  \left\lfloor \frac{n-32}{5} \right\rfloor =  \left\lfloor \frac{ 5k + \delta }{5} \right\rfloor  =  \left\lfloor k + \frac{  \delta }{5} \right\rfloor  = k, $$
because  $k$ is a positive integer and
$$ 0 \leq \frac{  \delta }{5} < 1; $$
$$ k \leq k + \frac{  \delta }{5} < k + 1. $$


How to check whether a string input from the user contains a number or not?

Question: The title says it all. I'm looking to check if a string contains even a single digit somewhere. No idea how to do this. If there is a pre-built function for this, I'd still like an unorthodox, long way of actually doing it (if you know what I mean).
Thanks!
Comment: Should be pretty straightforward to convert this to a loop `std::any_of(str.begin(), std.end(), [](unsigned char c) { return std::is_digit(c);})`
Answer:
If there is a pre-built function for this, I'd still like an unorthodox, long way of actually doing it (if you know what I mean).

You could just use a simple for-loop and check if any of the characters present in the string are digits and return true if any is found, otherwise false:
#include <string>
#include <cctype>
// ...

bool contains_number(std::string const& s) {
    for (std::string::size_type i = 0; i < s.size(); i++)
        if (std::isdigit(s[i]))
            return true;
    return false;
}

Or if you're fine with using std::string::find_first_of().
bool contains_number(std::string const& s) {
    return s.find_first_of("0123456789") != std::string::npos;
}

Comment: Now then if I wanted to something even more orthodox could I do:  if ( s[i] >= 0 ) ? Would this work as a condition instead of using the isdigit() function?
Comment: @Themeiscool It would be something along those lines, but the digits have to be surrounded with single quotes since you want to compare characters. Moreover, you also need to check if the character's ASCII value is less than or equal to that of `'9'`s: `if (s[i] >= '0' && s[i] <= '9')`
Comment: @Ruks -- concerning your comment, you're right about those tests, but that does not depend on ASCII; it's true for **every** valid character encoding.
Comment: @Ruks Aye thanks a heck lot. I'm really interested in seeing how to formulate this logic instead of using it pre-fabricated (if you know what I mean). You really helped me get it thanks a lot.
Answer: using std::isdigit in iostream
It will return true or false
#include <iostream>

using namespace std;

bool isnumber(string n){
    for (int i = 0;i < n.size();i++){
        if (isdigit(n[i]) == 1){
            return true;
        }
    }
    return false;
}
int main(){
   string n;
   cin >> n;
   if (isnumber(n)){
       cout << "Have number in string";
   }else{
       cout << "Doesn't have number in string";
   }
   return 0 ;
}


Android Studio Emulator Error

Question: When I try to run an app, the emulator never gets past the Android logo. After a few minutes or so, this message would appear - emulator: ERROR: _factory_client_recv: Unknown camera factory query name in 'list0@���'.
There was another post about this on stack overflow and someone suggested: "set front camera to emulated and back camera to none". I tried that and the same error is still there. (This may or may not be related to the problem, but I've already tried increasing RAM and heap size.)
Does anyone know what this error means or have suggestions as to how to fix this?
Here is a link to an image showing the issue I'm talking about:
emulator: ERROR: _factory_client_recv: Unknown camera factory query name in 'list0@���'
Comment: Have you tried creating a new emulator?
Comment: I just made a new emulator. I don't see the error anymore, but it's back to my original problem where the emulator never gets past the Android logo.
Comment: Do you have a computer with a quick enough processor and enough ram to run the emulator? One of my friends that has a computer which takes about 10 minutes to fully boot the emulator.
Comment: it's a mac air (processor 1.3 GHz Intel Core i5). doesn't take long for the device to show up (probably no more than a minute) and gets stuck at the android logo.
Comment: Have you tried leaving it to load for a while?
Comment: yes, it times out after 5 minutes. and the emulator closes. i try again and same thing
Comment: What is your VM application heap size? Go to AVD Manager, find your AVD, click Edit (the pencil icon), then click Advanced Settings, scroll down to "Memory and Storage", and look where it says "VM Heap". Make sure this is at least 32 MB.
Comment: RAM is 1GB, VM Heap is 2GB, Internal Storage is 800MB
Comment: My VM heap is only 64MB... I'm wondering if yours is too big for your computer. Try changing your VM heap size to only 64MB and see what happens.
Answer: Had the same problem with same messages . I resolved it by wiping the data off the emulator through Android Virtual Device Manger. Other settings - I had the Emulator GPU ticked and Front & Back Camera set as none.

Android Studio Emulator Error


Render menu in twig template

Question: In admin/structure/menu I created a menu. Is it possible to render this menu (with machinename: my_menu) in a twig template? Somehow like:
{{ my_menu }}

Answer: Simplify Menu sounds like what you'd want.

The simplify_menu module uses a TwigExtension to gain access to
  Drupal's main menu's (or any other menu for that matter), render array
  so it can be accessed from a twig template. Among the many advantages
  of having full control of the menu's render array in a twig template
  is the ability to customize the markup for your menus to ensure they
  are accessible and comply with standards.

// Get menu items
{% set items = simplify_menu('main') %}

// Iterate menu tree

  {% for menu_item in items.menu_tree %}

      {{ menu_item.text }}

  {% endfor %}

Otherwise, there are a handful of menu-* twig templates to use when rendering a menu from a block. Turn on your Twig debugging settings in Drupal to see what the suggestions are.
However, you need to have pretty good knowledge of menu theming to get it exactly right (like handling child items and not flat menu structure as the example above displays) - that said, I would stick to letting a block render out the menu in a given region. Then, inspect menu.html.twig from your base theme (either classy or stable) to get an idea of what your options are if you want to modify markup.
Be sure to use a decent twig template suggestion and not just menu.html.twig - as that will affect every menu that gets rendered by Drupal... it is the default template.
I would also suggest to install Menu Block as that will grant extra flexibility in theming and twig file suggestions. It also makes rendering trees of a menu (like section based navigation in a sidebar) a breeze.
Comment: thanks. The reason why I asked my question above is because I am not able to render my menu (my block menu) in a nested twig template? [See here my question](http://drupal.stackexchange.com/questions/225562/render-menu-block-in-twig-template?noredirect=1#comment275338_225562). Maybe you have the answer..?
Comment: Simplify Menu lets you call any menu from any twig template it looks like.
Comment: I installed and enabled Simplify Menu. In my header.twig file I added `{% set items = simplify_menu('main') %}` but (in this case) the Main navigation menu is not rendered?
Comment: Did you follow the rest of the example? You either have to do it that way, or call a block that holds a menu, render it and create a variable. It's best to leave it to the block system, honestly, instead of inject menus into other twig templates they wouldn't normally be in.
Comment: ok thanks If I follow the rest of the example it's working! But like you suggest, it's better to leave it to the block system. How do I do this with Simplify Menu? **1)** In admin/structure/block I placed the menu in a region and then I disabled it (so now I have the Block ID). **2)** In my `header.twig` I tried `{{ simplify_menu('crmnavigation') }}`, but it's not loading the block? Do you know how do I load the block and the menu within it in my `header.twig` using Simplify Menu?
Comment: You have to iterate over the result - check the example code above and on the module project page.
Comment: sorry I don't understand what you mean. The code from the project page is working. But how do I load the block menu (containing the menu) instead of the menu items themselves? See my last comment above...
Comment: sorry do you have an answer how I render the block with Simplify Menu module? Thanks
Comment: It's meant for menus only, not blocks. That's a separate question
Comment: Ok. But in your comment you said _"It's best to leave it to the block system, honestly, instead of inject menus into other twig templates they wouldn't normally be in"_. What do you mean with this?
Comment: Are you aware that menus have corresponding blocks and can be placed in regions in the Block admin? That's what I was talking about.
Comment: Ok that's what you mean. Yes I know! But I can't please it in a region because from the twig file `header.twig` I can't use `{{ my_region }}` because it's not a page template / page twig file... (like e.g. `page--front.html.twig`). Or do I mis something?
Comment: How to get the `menu_levels` here? Suppose i need to a custom class for the sub level menus?
Answer: For those who are still looking for an alternative approach, I suggest using Twig Tweak module as a more stable and more global use case, check out its cheat sheet
For rendering the menu via twig tweak,  you can just do the following:
{# Expand menu items to display the entire menu tree. #}
{{ drupal_menu('menu_machine_name') }}

{# Specify menu level and depth. #}
{{ drupal_menu('admin', 2, 3) }}

Answer: Enable the simplify_menu module, then add the code below to your page.html.twig or other twig template where you would like to render your menu:

  {% set item_class = 'navigation__item' %}
  {% set link_class = 'navigation__link' %}

    {% set items = simplify_menu('main') %}
      {% for menu_item in items.menu_tree %}

{{ menu_item.text }}

      {% endfor %}

the 'main' is the menu id which you can find by hovering over the menu's edit button in the menus page and looking at the url displayed at the bottom of the browser.
Answer: If you are sick of installing modules for basic things, call this function in a preprocess and add the return value into variables and you can then use it in twig:
 /**
 * Helper function to get menu items as array for a given menu id/name
 *
 * @param String $menu_id
 *
 * @return Array menu items array with url, title properties
 */
function getArrayFromMenu($menu_id) {
   // Load menu as array to render in twig file
   $tree = \Drupal::menuTree()->load($menu_id, new MenuTreeParameters());
   $menu_array = [];

   if (!$tree) {
      return $menu_array;
   }

   // Sort according to the weight. @see https://www.drupal.org/project/drupal/issues/3019572
   $menu_tree = \Drupal::service('menu.link_tree');
   $manipulators = array(
      array('callable' => 'menu.default_tree_manipulators:generateIndexAndSort'),
   );

   $tree = $menu_tree->transform($tree, $manipulators);
   foreach ($tree as $item) {
      $title = $item->link->getTitle();
      /** @var \Drupal\Core\Url */
      $url_obj = $item->link->getUrlObject();
      $menu_array[] = array(
         'title' => $title,
         'url' => $url_obj->toString()
      );
   }

   return $menu_array;
}

It will just do the complex work, you just need to pass the menu id. In my case, menu id was mapped with a field of custom block type.

Render menu in twig template


Cauchy sequence of random variable

Question: I know (from calculus) the Cauchy convergence theorem for sequence of real numbers...how to show it with random variables?
I have $S_n=\sum_{i=1}^n X_i;$  $X_i$ being iid centered r.v., $S_n$ is a Cauchy sequence in $L^2$, I have to show it converges to $S$ ($E((S_n-S)^2)=0$)
I have to show also that $E(\sum_i^\infty X_i^2)<\infty$ (this should be easy) and that $X_n\rightarrow 0 (a.s.)$ (here I need help)
Answer: Because $E(\sum_i^\infty X_i^2)<\infty$, so $\sum_i^\infty X_i^2<+\infty, a.s$. So $X_i^2\rightarrow 0, a.s$ as well as $X_i$.
Comment: $L^2$ is Banach space, so any cauchy sequence of r.v's in $L^2$ converges to a certain r.v which is also in $L^2$. So $S_n \rightarrow S $ in $L^2$.
Comment: ok...and about the convergence of $S_n$ to $S$ in quadratic mean?
Comment: You have shown that $E(\sum_n^\infty X_n^2)=\sum_n^\infty E(X_n^2)<\infty$, so $E(S_n-S)^2=E(\sum_{k=n+1}^\infty X_k^2) =\sum_{k=n+1}^\infty E(X_k^2)\rightarrow 0$ when $n\rightarrow 0$ because they are the remained terms.
Comment: ok, but I didn't show that, if $S_n$ is a cauchy sequence in $L^2$, it converges in quadratic mean (that's my main problem)
Comment: is that a definition? I remember from my calculus studies there was a theorem (at least for real numbers).
Comment: It is a theorem in analysis, if you don't familiar with it, just use $E(S-S_n)^2=\sum_{k=n+1}^\infty E(X_k^2)\rightarrow 0$, we directly got $S_n$ converges to $S$ in quadratic mean.

Cauchy sequence of random variable


Uncaught Error Attempting to use a disconnected port object in Vue CLI App?

Question: I've created a VueCLI App and once it runs on any web browser, the console shows following error when any action performed on a page, like a scroll down or up and click  anywhere on the page,
Uncaught Error: Attempting to use a disconnected port object
    at w.k.fa (content.js:16)
any help?
Comment: Possible duplication of
https://stackoverflow.com/questions/5337672/reason-for-uncaught-error-attempting-to-use-a-disconnected-port-object/6462762
Comment: problem solved, the error comes with chrome extensions. thanks @RóbertKovács
Answer: As this thread says, I disabled some plugins on browser, and re-run it. Then this error didn't rise.


Display certain field values of submissions from multiple webforms in one view

Question: I have two separate webforms, and I want to be able to display all submissions from both webforms that have the same value of a specific field. I also want different fields to be displayed based on what form they're coming from.
For example, both webforms have a field called area.
I would like to display the submissions of both these webforms if they both have area set to the same value. Amongst these submissions, if they're from form 1, I want to display the values for field1,field2,and field3 in the view. If they're from form2, I want to display the values for field4,field5, and field6 in the view.
Is there a way to accomplish this in a view?
Comment: Is this 7 or 8? And are you using the webform module? Also by answers what do you mean? A list of all the submissions?
Comment: Drupal 7, yes I am using the webform module. I'm sorry not answers but Webform submission data: Value for two different webform nodes.
Comment: Do you mean the values of every submission of the two webforms?
Comment: Not every value but most
Comment: Do you mean the most recent submissions?
Comment: No. I have a webform with one field being "Areas", I am filtering the webform by the different "Areas" into their own specific view. I want to filter an additional webform with the same "Areas" into the same view. I added a new block in the view and filitered using the specific "Area" and webform node but the results don't show.
Comment: If I understand correctly, you want to show the submissions of each webform that have the same value for 'Areas'?
Comment: Yes. But I want to be able to pull specific values, not all of them
Comment: So as an example, you want to be able to pull 'field 1', 'field 3', and 'field 7' of the submissions from webform 1 and webform 2 that have 'area' set to 'area1'?
Comment: I want to be able to pull 'field 1', 'field 3', and 'field 7' of the submissions from webform 1 and 'field 2', 'field 3', and field 5' of the submissions from webform 2 while both webforms have 'area' set to 'area1'
Comment: I'm not sure how to accomplish this in drupal 7 inside a view, but I have edited your question for clarity so hopefully it will get more help and attention. Edit your question again if I made any mistakes.
Answer: You may want to read this: https://www.drupal.org/node/2497183

Views cannot display information from more than one webform at a time
  unless the webforms share the same components.
One solution would be to add order# as a hidden field so that all
  webforms have a component by this field key. I haven't tried having
  mixed component types for with the same field key, but I suspect it
  will work, at least with some view configurations

You may wind up having to create a template for a module to get the report you are looking for.
Drupal answers actually already has a post on this:
Multiple Webforms in one View


Prove a function f is uniformly bounded throughout [0, ∞)

Question: Let f : [0, ∞) → [0, ∞) be a continuous function with f(0) = 0. Show that if $f(t) ≤ 1 +f(t)^3/10 $ for all t ∈ [0, ∞), then f is uniformly bounded throughout [0, ∞)
I am wondering if the function is uniformly bounded since the definition of uniformly bounded is for a set of functions. And Suppose f(t)= any positive large number (like greater than 10), it seems to be always true that $f(t) ≤ 1 + f(t)^3/10 $.
I am also considering if I can prove the function is uniformly continuous to show it is uniformly bounded.
Answer: Note that $2 > 1+2^3/10$, which entails that $f$ is never equal to $2$. By IVT, $f$ remains in $[0,2)$ so is bounded.
Comment: That is exactly what I wrote.
Comment: It is f(t)≤1+f(t)^3/10, hence f(x) cannot be 2


Double braces in angular not evaluating , going through as text

Question: I have the following code in angular.

The HTML for the accordion-group is :

Also, the js for the same is :
home.directive("vhAccordionGroup", ['version', function (version) {
return {
    restrict: 'EA',
    replace: true,
    transclude: true,
    scope: {
        panelClass: '@'
    },
    templateUrl: "JS/HomeModule/Directives/vhAccordion/vhAccordionGroup.html?v=" + version,
    controller: ['$scope', '$element', function ($scope, $element) {
        $scope.accordionId = $element.attr("id") + "vhAcc";

        this.getAccordionId = function () {
            return $scope.accordionId;
        };
    }],
    link: function (scope, element, attrs, vhAccordionGroupController) {
        element.addClass(scope.panelClass);
        scope.accordionId = element.attr("id") + "vhAcc";
    }
};
}]);

These accordions are called in a loop using ng-repeat.
The problem is the {{$index}} which I am passing in the Id is being taken as a string rather then an expression.
I need each of the accordions to have a unique Id so that they can open and close correctly.
Please let me know what I am missing, as I am a newbie to angular.
Comment: I see, you are seeing `{{$index}}` correct?
Comment: `$index` is a special variable that shows up inside and `ng-repeat`.  Are you repeating?
Comment: yes, but the value is not evaluated but taken as string
Comment: remove **double braces** then it will work for you.
Comment: What is the *actual* value that you are seeing?  Is the value the literal string `$index`?
Comment: @DavinTryon I am seeing the string but I need the value
Comment: What is the **value**?  Is it a `1` or is it `$index`?
Comment: @DavinTryon yes, but I need the value or any other value to distinguish the accordions
Answer: Simply add id to the isolated scope:
home.directive("vhAccordionGroup", ['version', function (version) {
return {
    restrict: 'EA',
    replace: true,
    transclude: true,
    scope: {
        panelClass: '@',
        id: '@'
    },
    templateUrl: "JS/HomeModule/Directives/vhAccordion/vhAccordionGroup.html?v=" + version,
    controller: ['$scope', '$element', function ($scope, $element) {
        $scope.accordionId = $scope.id + "vhAcc";

        this.getAccordionId = function () {
            return $scope.accordionId;
        };
    }],
    link: function (scope, element, attrs, vhAccordionGroupController) {
        element.addClass(scope.panelClass);
        scope.accordionId = scope.id + "vhAcc";
    }
};
}]);

Then, use $scope.id (and scope.id) instead of $element.attr.  $element.attr gives access to the actual DOM element and so it makes sense that the value would not be interpolated.


How to make sense of chain rule here

Question: Context: We are currently on topic of 1st order linear differential equations, and below there are 2 substitutions we have to perform to obtain a differential equation in the form $y'+ f(t)y = g(t)$ in order to use integrating factor to solve:

For the first one I differentiated $u$ to obtain $u' = \frac{-1}{y^2}\cdot y'$ which yielded me the correct form, but for the second one, when I differentiate u, it seems that $u' = y''$ instead of $u' = y'' \cdot y'$ because only the former yields the appropriate format. Why is it the case that chain rule doesn't apply to give $u' = y'' \cdot y'$?
Comment: To perhaps expand on Peter's comment above, in the first case you are defining a function $u$ by $u(y) = 1/y$, while in the second case you are defining a function $u$ by $u(x) = y'(x)$. In the first case, we have $u'(y) = \frac{d}{dy} 1/y$, while in the second case we have $u'(x) = \frac{d}{dx} y'(x) = y''(x)$. This sorta comes down to common abuse of notation
Comment: Because $1/y$ is a function of $y$ but $y'$ is a function of $x$.
Comment: Answered, thanks.
Answer: (1): It is also easy to see that the left side is a complete differential, so that
$$
(xy'(x))=\frac{(xy(x))^2}{x}
$$
is a separable ODE in $u(x)=xy(x)$.
(2): In principle, the same applies here, the left side is $(xy(x))''$, so that one can directly integrate twice.
Contrary to the comments, in neither case you change the independent variable to $y$. If you want to formally apply the chain rule in (1), consider the function $g(y)=\frac1y$, then the substitution is the composite function $u(x)=g(y(x))$ and thus $u'(x)=g'(y(x))y'(x)$ which results in the formula you found and used (apparently correctly).
In the equation (2) you just change the differentiation order of the dependent variable by "hiding" one differentiation, writing out the arguments it is intended to be $u(x)=y'(x)$ so that consequently $u'(x)=y''(x)$ and you find the integrating factor $x$ to get $(x^2u(x))'=12x^3$, which can again be easily integrated.
It is only in autonomous second order DE, usually non-linear, that sometimes the change of independent variable from $x$ to $y$ provides a more clear insight into the necessary and possible transformations. Under the assumption that $y$ is non-constant and locally monotonous, one sets $y'(x)=u(y(x))$ with some new unknown function $u$. Then the derivative of that relation gives $y''(x)=u'(y(x))y'(x)=u'(y)u=\frac12\frac{d(u^2)}{dy}$, which transforms the DE into a first order non-autonomous DE for $u(y)$.

How to make sense of chain rule here


Does the first extracted factor in EFA always have the highest eigenvalue?

Question: I have run many EFAs (exploratory factor analysis) and always find that the first extracted factor has the highest eigenvalue.
However, I read in Petscher et al (2013) "Applied Quantitative Analysis in Education and the Social Sciences" a chapter by Rex Kline that states (p183) that "The first extracted factor tends to have the highest eigenvalue" (emphasis mine).
As far as I can tell Kline does not explain the circumstances in which the first extracted factor does not have the highest eigenvalue. How can this happen?
Comment: Weird, I can't see how that might happen (unless the first and second were exactly equal), but I can't see where it says it on page 188 on the Google books preview.
Comment: Sorry, it's p183. I'll fix the original post.
Answer: I have no access to the text you are citing, but let me suppose several explanations; one of them is possibly the one which fits in the context of the citation.

The extraction itself needs not that the factors appear in descending order of their variances (sum of squared loadings). The important requirement is only that they are orthogonal. Even in PCA, which - unlike the majority of FA methods - hunts to maximize the variance, the eigenvalues can first appear in not decreasing order. It is afterwards that they (and the corresponding eigenvectors/loadings) are being sorted by the procedure. The same thing is in FA. Some eigen-decomposition and PCA functions in some packages do not do the sorting. However, even then the first eigenvalue is usually the highest. The principal distinction between FA and PCA in the issue we are discussing is that PCA components have to be sorted sooner or later because the purpose of the analysis is to select some number of first most strong of them; but in FA all the extracted factors are already modeled as existent (important): therefore it makes neither theoretical nor practical difference how you order them.
Another option which comes to mind is that the authors speak about how it is after the rotation of factors. Of course, after it variances change and may go in any order, not necessarily descending one.
One more guess is that sometimes, rarely, variances of several first (or even all) factors or components are the same or very close by magnitudes. One can easily generate such "discus" shape data clouds artificially.


Unable to renew Let's Encrypt SSL certificate in Nginx Proxy Manager

Question: I've set up a few sites in Docker, on Linode.
I started by following these instructions:
Connect Your Docker Containers to Domain Names For Easy Access using Portainer on Linode
The steps I followed are:

Created a Linode
Installed NGINX Proxy Manager in a Docker container
Add my domain in https://cloud.linode.com/domains, point it to my Linode
Redirect my domain's domain server to Linode on my domain's registrar
Add Portainer in a Docker container

Then I installed VaultWarden in a Docker container, following these instructions:
Take Control of AND Secure Your Passwords Using Vaultwarden on Portainer
Steps here as follows:

Setup A Sub-Domain
Installed VaultWarden in Docker
Enabled HTTPS In NGINX
Created a Proxy Host in NGINX Proxy Manager that pointed to my VaultWarden container

In this process, I created an SSL Certificate using Let's Encrypt, through the NGINX Proxy Manager UI.  (starting at 11:00 in the second video).
And all of that seemed to work, mostly.
Or, rather, in NGINX Proxy Manager's "Add Let's Encrypt Certificate" there;'s a "Test Server Reachability" button, and that always returned a "Communication with the API failed, is NPM running correctly?" error.
But, regardless of this, I was able to configure the redirect to the VaultWarden container, using the generated SSL key.
And then was able to access VaultWarden using the subdomain, and see that the browser can see the valid certificate.
My problem, now, is that I'm getting certificate is going to expire soon emails.
When I go back into NGINX Proxy Manager and look at SSL Certficates, I see a "Renew Now" option, and when I try it I get "Please Wait" for a while, then an "Internal Error" message.
What may or may not be relevant, the "Test Server Reachability" option still returns a "Communication with the API failed, is NPM running correctly?" error.
My problem is that these pretty GUIs aren't returning any sort of information as to what is going on, or why exactly it is failing.
There has to be some sort of logging, somewhere, that could give me a hint as to what the problem is.
Can someone help me find it?
Comment: I'm actually encountering the exact same issue as you're experiencing. Unfortunately; I don't currently have a solution. However; I can point you in the direction of the logs directory: ~/npm/data/logs
Answer: I've done some further research on this issue. I believe the problem is relative to two bugs within NPM.

One that seems to have been partially fixed for SSL renew in version v2.9.21
After multiple renewal attempts the SSL certificate does renew; If it does not work the first time I would wait about 15 seconds and try again. Make sure you're running the latest version: v2.9.21.

The "Test Server Reachability" button does not seem to work at all for multiple people.
You'll find there are multiple issues on Github that indicate the same behavior; Either for SSL renewal or the error shown when testing server reachability: "Communication with the API failed, is NPM running correctly?"

https://github.com/NginxProxyManager/nginx-proxy-manager/issues/2439 (This one has the most info on the Test Server Reachability Error)
https://github.com/NginxProxyManager/nginx-proxy-manager/issues/2713 (This one has the most info about SSL Renewal)
https://github.com/NginxProxyManager/nginx-proxy-manager/issues/2593
https://github.com/NginxProxyManager/nginx-proxy-manager/issues/2442

After further review of my logs I was also noticing a lot of the following error:
could not build optimal proxy_headers_hash, you should increase either proxy_headers_hash_max_size: 512 or proxy_headers_hash_bucket_size: 64; ignoring proxy_headers_hash_bucket_size
I found improvements with including the following two lines in my ~/npm/data/nginx/custom/http.conf
<code>proxy_headers_hash_max_size 1024;
proxy_headers_hash_bucket_size 128;
</code>


How to configure netty logger factory in order to see the output of LoggingHandler?

Question: I am using slf4j logging with logback and at the beginning of my app I wrote
InternalLoggerFactory.setDefaultFactory(new Slf4JLoggerFactory());

then I added to the pipeline a new LoggingHandler(InternalLogLevel.DEBUG) instance.
Unfortunately, this still does not log anything, I was debugging into and the debug level is the problem, just skips the logging itself.
How should I setup to get working this LoggingHandler?
Comment: Can you give me some more detail what the problem with DEBUG is ?
Comment: I don't see any reason why logging at DEBUG level wouldn't work.  Does logging at DEBUG level by yourself work?  If so, could you please provide us specific code that reproduces the problem?
Comment: Do you have the `slf4j-api.jar` and some implementation of `sl4j` (like `logback`) in your project's classpath? You'll also need to configure the log level in the implementation specific config file (like `logback.xml` for `logback`).
Comment: Can you try putting the above line of code in `static {}` initialization code block?
Answer: I have done a small example, that does work - I placed it on gist on github. It uses logback as the backend of the slf4j. The moments that should be paid attention to are:

InternalLoggerFactory.setDefaultFactory(Slf4JLoggerFactory.INSTANCE); should be executed right on the entry point of your program. Sometimes this "entry point" may be very hard to determine.
Proper configuration of slf4j backend. Since slf4j is only a wrapper it does not deal with configuration at all - it is specific for log4j, logback or java.util.logging (or maybe some custom backend - I have worked heavily with the custom "java commons logging" configurator, so really anything really can be used)
Even without LoggingHandler you should see two debug messages from static initializer of org.jboss.netty.channel.socket.nio.SelectorUtil (with Netty version 3.6.0.Final):
11:54:00.959 [main] DEBUG o.j.n.c.socket.nio.SelectorUtil - Using select timeout of 500
11:54:00.962 [main] DEBUG o.j.n.c.socket.nio.SelectorUtil - Epoll-bug workaround enabled = false

Comment: You need to use `InternalLoggerFactory.setDefaultFactory(Slf4JLoggerFactory.INSTANCE);` instead.
Comment: Netty however is not using my root logger, I have the following: 10:36:40,447 |-WARN in Logger[io.netty.channel.MultithreadEventLoopGroup] - No appenders present in context [default] for logger [io.netty.channel.MultithreadEventLoopGroup].
Comment: Slf4JLoggerFactory seems to be  deprecated
Comment: Note that adding the `LoggingHandler` like `LoggingHandler(InternalLogLevel.DEBUG)` as shown in the gist will set the logger name to the FQN of the `LoggingHandler`, which is almost always never desirable. To set the logger name, pass a `Class` or `String` as the first argument.


DHCP starting before network is ready

Question: I am having a problem with my DHCP server. When it restarts the isc-dhcp-server does not get ready because the network (it uses NetworkManager) is not ready.
I put a sleep command in the isc-dhcp-server start script but when the server restarted the script erased the line with the sleep command.
How can I delay the DHCP start or restart when the network is ready?
Here is some information:
Linux Version
PRETTY_NAME="Debian GNU/Linux 11 (bullseye)"
NAME="Debian GNU/Linux"
VERSION_ID="11"
VERSION="11 (bullseye)"

Journalctl
jan 09 07:50:22 server systemd[1]: Starting LSB: DHCP server...
jan 09 07:50:28 server isc-dhcp-server[579]: Launching IPv4 server only.
jan 09 07:50:30 server dhcpd[622]: WARNING: Host declarations are global.  They are not limited to the scope you declared them in.
jan 09 07:50:30 server dhcpd[632]: WARNING: Host declarations are global.  They are not limited to the scope you declared them in.
jan 09 07:50:31 server dhcpd[632]: Wrote 0 deleted host decls to leases file.
jan 09 07:50:31 server dhcpd[632]: Wrote 0 new dynamic host decls to leases file.
jan 09 07:50:31 server dhcpd[632]: Wrote 79 leases to leases file.
jan 09 07:50:31 server dhcpd[632]:
jan 09 07:50:31 server dhcpd[632]: No subnet declaration for enp32s0 (no IPv4 addresses).
jan 09 07:50:31 server dhcpd[632]: ** Ignoring requests on enp32s0.  If this is not what
jan 09 07:50:31 server dhcpd[632]:    you want, please write a subnet declaration
jan 09 07:50:31 server dhcpd[632]:    in your dhcpd.conf file for the network segment
jan 09 07:50:31 server dhcpd[632]:    to which interface enp32s0 is attached. **
jan 09 07:50:31 server dhcpd[632]:
jan 09 07:50:31 server dhcpd[632]:
jan 09 07:50:31 server dhcpd[632]: Not configured to listen on any interfaces!
jan 09 07:50:31 server dhcpd[632]:
jan 09 07:50:31 server dhcpd[632]: If you think you have received this message due to a bug rather
jan 09 07:50:31 server dhcpd[632]: than a configuration issue please read the section on submitting
jan 09 07:50:31 server dhcpd[632]: bugs on either our web page at www.isc.org or in the README file
jan 09 07:50:31 server dhcpd[632]: before submitting a bug.  These pages explain the proper
jan 09 07:50:31 server dhcpd[632]: process and the information we find helpful for debugging.
jan 09 07:50:31 server dhcpd[632]:
jan 09 07:50:31 server dhcpd[632]: exiting.
jan 09 07:50:33 server isc-dhcp-server[579]: Starting ISC DHCPv4 server: dhcpdcheck syslog for diagnostics. ...
jan 09 07:50:33 server isc-dhcp-server[640]:  failed!
jan 09 07:50:33 server isc-dhcp-server[641]:  failed!
jan 09 07:50:33 server systemd[1]: isc-dhcp-server.service: Control process exited, code=exited, status=1/FAILURE
jan 09 07:50:33 server systemd[1]: isc-dhcp-server.service: Failed with result 'exit-code'.
jan 09 07:50:33 server systemd[1]: Failed to start LSB: DHCP server.

#> cat /etc/network/interfaces

# This file describes the network interfaces available on your system
# and how to activate them. For more information, see interfaces(5).

source /etc/network/interfaces.d/*

# The loopback network interface
auto lo
iface lo inet loopback

#> cat /etc/dhcp/dhcpd.conf

# dhcpd.conf
#
# Sample configuration file for ISC dhcpd
#

option domain-name "server.local";
option domain-name-servers 22.214.171.124, 18.104.22.168;

default-lease-time 600;
max-lease-time 7200;

ddns-update-style none;

authoritative;

subnet 192.168.1.0 netmask 255.255.255.0 {
        # — default gateway
        option routers 192.168.1.3;
        option subnet-mask 255.255.255.0;
        #option nis-domain "SERVER";
        option domain-name "SERVER";
        # Cloudflare
        option domain-name-servers 220.127.116.11, 18.104.22.168;
        option time-offset -18000;
        option ntp-servers 192.168.1.3;
        #option tftp-server-name "192.168.1.10";
        option broadcast-address 192.168.1.255;
        range 192.168.1.11 192.168.1.90;
        default-lease-time 21600;
        max-lease-time 43200;
        # Fixed IP addresses can also be specified for hosts.
    [...]

Thank you guys.
Comment: Have you tried adding `After=NetworkManager` to the service that starts the DHCP server?
Comment: Not yet. To be honest I did not find where I can make this modification. But I am thinking of making a timer to restart the service after 20 seconds the server starts. I don't know if the right way, but it can resolve my problem.
Comment: If you want to try it, you can just add `After=NetworkManager.service` to the `[Unit]` section of the `.service` file
Comment: Oh, right. But the problem is that I did not find where is the isc-dhcp-server.service file. using the `systemctl status isc-dhcp-server.service` it gives me the path `/system.slice/isc-dhcp-server.service` but I don't know how I can access it.
Comment: It looks like systemd slices are a whole other can of worms, I know nothing about how that works
Answer: To order a service start after network is up, set After=network-online.target in the systemd service file.
Don't use After=NetworkManager-wait-online.service, because that is an implementation detail. NetworkManager-wait-online.service orders itself Before=network-online.target, so you get that ordering implicitly.
For example, do so via systemctl edit isc-dhcp-server.service.
Read the manual page, in particular about ipv4.may-fail=no and ipv4.required-timeout about how to tell NetworkManager that the interface is only ready with an IPv4 address.
A better, more robust solution may be to convince the DHCP server to dynamically cope with being started when the addresses are not there yet.
Answer: What you can try to do is
systemctl enable systemd-networkd.service systemd-networkd-wait-online.service
And then
[Unit]
After=systemd-networkd-wait-online.service
Wants=systemd-networkd-wait-online.service

Source
https://stackoverflow.com/questions/35805354/systemd-start-service-at-boot-time-after-network-is-really-up-for-wol-purpose
I usually edit the file directly in /etc/systemd/system/ with vi or nano
And then a systemctl daemon-reload and a restart if the service comes up properly
Comment: This does not provide an answer to the question. Once you have sufficient [reputation](https://serverfault.com/help/whats-reputation) you will be able to [comment on any post](https://serverfault.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/577366)

DHCP starting before network is ready


Como obter o último dia do mês?

Question: Estou tentando fixar uma data de vencimento para o final do mês porém não tenho ideia de como poderia ser o código. Atualmente está assim:
  from datetime import date
  from datetime import datetime
  from datetime import timedelta

  data_atual = date.today()
  print(data_atual)
  last_date = data_atual + timedelta(13)
  print(last_date)

Eu tentei fazer com timedelta porém tenho que ficar alterando o número para poder pegar o último dia do mês. Como faço para não ter que ficar alterando esse número?
Answer: Uma forma de fazer é usar calendar.monthrange, que retorna uma tupla contendo o dia da semana referente ao primeiro dia do mês, e a quantidade de dias daquele mês. Ou seja, basta pegar o segundo valor da tupla e setar este dia na data:
from datetime import date
from calendar import monthrange

data_atual = date.today()
# monthrange retorna o último dia do mês, basta setá-lo na data e pronto
last_date = data_atual.replace(day=monthrange(data_atual.year, data_atual.month)[1])
print(last_date) # 2022-05-31

Outra alternativa (um pouco mais complicada) é primeiro setar o dia para 1, depois somar a quantidade de dias do mês menos 1 (assim, se um mês tem 31 dias, por exemplo, eu seto o dia para 1 e somo 30, resultando no dia 31):
from datetime import date, timedelta
from calendar import monthrange

data_atual = date.today()
# seta o dia para 1, e soma a quantidade de dias do mês menos 1
last_date = data_atual.replace(day=1) + timedelta(monthrange(data_atual.year, data_atual.month)[1] - 1)
print(last_date) # 2022-05-31

Se bem que esta solução é desnecessarimente mais complicada, pois se eu já sei a quantidade de dias do mês (obtida por monthrange), setar este valor diretamente é bem mais simples.

Outra forma igualmente mais trabalhosa é instalar o pacote dateutil e usar um relativedelta para somar um mês. Depois, seta-se o dia para 1 e subtrai-se um dia. O resultado é o último dia do mês atual:
from datetime import date, timedelta
from dateutil.relativedelta import relativedelta

data_atual = date.today()
# soma 1 mês, seta o dia para 1 e subtrai 1 dia
last_date = (data_atual + relativedelta(months=1)).replace(day=1) - timedelta(days=1)
print(last_date) # 2022-05-31

É uma ideia parecida com a segunda solução acima, e também me parece desnecessariamente mais complicada. A primeira solução me parece bem mais "direto ao ponto".
Comment: +1 pela excelência presente na explicação!!
Comment: Obrigado, me ajudou muito!!!

Como obter o último dia do mês?


Multicollinearity: does if matter which variable I remove?

Question: Say I'm running a multiple linear regression. I have 4 explanatory variables: A, B, C and D.
Pearsons correlation coefficient for A and B is 0.90. I decide to remove either A or B prior to running the multiple linear regression.
Will A and B both have exactly the same correlation coefficient with C and D, in which it doesn't matter which one of A or B I remove?
Or could A and B both have different correlation coefficients with C and D, in which I should remove the least correlated explanatory variable, A or B, prior to running the multiple linear regression?
Answer:

Q : Will A and B both have exactly the same correlation coefficient with C
  and D, in which it doesn't matter which one of A or B I remove?

A and B don't necessarily have the same correlation coefficient with C and D. Think of $X=[A,B,C]\sim N_3(0,\Sigma)$ where $\Sigma= \left( \begin{array}{ccc}
1 & 0.9 & 0.1 \\
0.9 & 1 & 0.3 \\
0.1 & 0.3 & 1
\end{array} \right)$.
For sample version, check it through experiment.
library(mvtnorm)
set.seed(123)
Sigma <- c(1, 0.9, 0.1, 0.9, 1, 0.3, 0.1, 0.3, 1)
Sigma <- matrix(Sigma, nrow = 3)
X <- rmvnorm(n = 100, mean = rep(0,3), sigma = Sigma)
cor(X)

Q : could A and B both have different correlation coefficients with C and
  D, in which I should remove the least correlated explanatory variable,
  A or B

This is not a good question. Suppose cor(A,C)=0.40, cor(A,D)=0.67, cor(B,C)=0.56, and cor(B,D)=0.27. B is more correlated to C than A, but A is more correlated to D than B. How do you define "the least correlated explanatory variable"? Should it be A or B? This situation is possible. Please try the following R code.
set.seed(123)
data <- matrix(rnorm(40), nrow=10)
data[,3] <- -data[,3]
colnames(data) <- c("A","B","C","D")
cor(data)

If removing one variable between A and B is the only option, then the solutions I can think of are

drop the variable which is less correlated with the response
drop the variable which has larger Variance Inflation Factor (VIF)
fit 2 new models : one removing A and one removing B, and to see which new model suffers less multicollinearity. To measure multicollinearity, you can look at the VIF of each present variable or the Condition Number of $X'X$ where $X$ is the present design matrix
use variable selection method like stepwise regression and lasso regression to (hopefully) remove one variable

I am not sure which are valid solutions or which is the best one, so any comment is appreciated.
Comment: Your response to Q1. doesn't work, because A and B are not correlated with each other
Comment: @luciano The answer is updated. You don't specify the type of the correlation coefficient : is it a population version or sample version? Sample correlation coefficient can be non-zero even if the population correlation coefficient is 0. When talking about multicollinearity in regression, we usually mean the sample correlation coefficient, because the population version is unknown. It is possible that population version is high but sample version is low. In this case, you can not even detect multicollinearity, as all methods are with respect to the sample.


Use intents to either open file in browser or share it

Question: I'm creating an android application that deals with texts files. I want my users to be able to share their files using email, dropbox, ... but I also want them to be able to open them in the browser if they happen to be html files.
I'm having no problem in doing both codes separately. These is the one to share a file:
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + path));
startActivity(Intent.createChooser(intent, "Send File"));

and this is the one to open the file in the browser:
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setClassName("com.android.browser", "com.android.browser.BrowserActivity");
intent.setData(Uri.parse("file://" + path);
startActivity(Intent);

My problem is that I don't want to ask the user which option he wants beforehand. I want the intent chooser to list both type of operations. I tried using text/html instead of text/plain but the browser only listens to intents when the URI starts with http.
Any ideas on how to accomplish this?
Comment: My current solution is to rip the code of ChooserActivity and implement my own MULTI_ACTION_CHOOSER intent.
Answer: In terms of merging the two rosters, you have no choice but to do that yourself.
However, both of your current implementations have issues:

The text/plain one will fail for apps that do not handle EXTRA_STREAM -- you should consider using a Uri, perhaps pointing to a ContentProvider by which you make the file available, as support for the data Uri is going to be more common.
Your second one will crash on devices where this browser does not exist. Moreover, you also assume that this browser will be able to consistently load from file:// Uri values in all versions of Android, which is not a safe assumption. If the browser authors wanted it to load a local file, they would have added support for it in the manifest. Use a WebView widget if you do not have an HTTP URL. No professional-grade code should reference com.android anywhere.


Always deleting last row of table in MVC View

Question: I have 2 forms in same razor view.
1.First form is used to populate 2 dropdownlist's in ajax add model popup.
2.Second form is used to populate the added values from first form in the same view.
I can't able to use @model IEnumerable so i am getting it as viewbag collection and populating datatable.
Final task is need to add delete button in each button in datatable and remove the row accordingly.
But i can't able to get the id of each row of button click on http post.
Please look into the complete code. I am struck up for past 2 days. Please help me soon...
Controller:
 public class MappingK360Controller : Controller
{
    private readonly K360ECommerceSContext _context;
    public MappingK360Controller(K360ECommerceSContext context)
    {
        _context = context;
    }

    public IActionResult Index()
    {
        GetMappedDataDt();
        Get3PProductCatalogJson();
        GetK360ProductCatalogDB();
        return View();
    }
    public void GetMappedDataDt()
    {
        var resultMappedData = _context.K360Masters.FromSqlRaw("SELECT * FROM K360_Master WHERE ClientCatalog is NOT NULL").ToList();
        ViewBag.K360MappedData = resultMappedData;
    }
    public void Get3PProductCatalogJson()
    {
        string strAPIUrl = "https://raw.githubusercontent.com/wedeploy-examples/supermarket-web-example/master/products.json";
        string jsonUrlProducts;
        using (WebClient client = new WebClient())
        {
            jsonUrlProducts = client.DownloadString(strAPIUrl);
        }
        Dictionary<string, object> Jsondictresults = new Dictionary<string, object>();
        var objResponseB = JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(jsonUrlProducts);
        foreach (Dictionary<string, object> DictMainKV in objResponseB)
        {
            foreach (KeyValuePair<string, object> item in DictMainKV)
            {
                Jsondictresults.Add(item.Key, item.Key);
            }
            break;
        }
        ViewBag.TPartyJsonCtgls = Jsondictresults.Keys;
        ViewData["JsonCatalogs"] = Jsondictresults;
    }
    public void GetK360ProductCatalogDB()
    {
        PropertyInfo[] propertyInfosSM = typeof(CatalogProduct).GetProperties();
        Dictionary<string, object> K360dictresults = new Dictionary<string, object>();
        foreach (PropertyInfo propertyInfoDB in propertyInfosSM)
        {
            K360dictresults.Add(propertyInfoDB.Name, propertyInfoDB.Name);
        }
        ViewBag.K360dbCtgls = K360dictresults.Keys;
        ViewData["K360Catalogs"] = K360dictresults;
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public IActionResult Index(K360Master K360LevelAMap)
    {
        try
        {
            List<K360Master> K360MasterList = _context.K360Masters.Where
              (x => x.ClientCatalog == K360LevelAMap.ClientCatalog).ToList();
            if (K360MasterList.Count > 0)
            {
                GetMappedDataDt();
                Get3PProductCatalogJson();
                GetK360ProductCatalogDB();
                ViewBag.Message = "Selected Catalog is already Mapped!";
            }
            else
            {
                _context.K360Masters.Add(K360LevelAMap);
                _context.SaveChanges();
                int id = K360LevelAMap.Id;
                ViewBag.Message = "Inserted Mapped ID: " + id;
                GetMappedDataDt();
                Get3PProductCatalogJson();
                GetK360ProductCatalogDB();
            }

        }
        catch (Exception)
        {

        }

        return View(K360LevelAMap);
    }

    [HttpPost("DeleteK360Data")]
    [ValidateAntiForgeryToken]
    public IActionResult DeleteK360Data()
    {
        int intDeleteid = Convert.ToInt32(TempData["KDataId"]);
        _context.Database.ExecuteSqlRaw($"DELETE FROM K360_Master WHERE ID = {intDeleteid}");
        GetMappedDataDt();
        Get3PProductCatalogJson();
        GetK360ProductCatalogDB();
        return View("Index");
    }

}}

View: @model SimplCommerce.WebHost.Models.K360Master @using SimplCommerce.WebHost.Models;

                    <fieldset class="border p-2">
                        <legend class="w-auto">Catalog Mapping:</legend>

                                        @foreach (var smctgls in ViewBag.TPartyJsonCtgls)
                                        {

@smctgls

                                        }

                                        @foreach (var dbctgls in ViewBag.K360dbCtgls)
                                        {

                                                @dbctgls

                                        }

                                    <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">Catalog Mapping</button>

                                    <form method="post" asp-action="Index" asp-controller="MappingK360">

K360 Mapping Form

                                                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                                            ×
                                                        </button>

                                                            Client Catalog:
                                                            @{var Jsonlist = new SelectList((System.Collections.IEnumerable)ViewData["JsonCatalogs"], "Value", "Key");}
                                                            <select asp-items="Jsonlist" asp-for="ClientCatalog" class="form-control"></select>

                                                            K360 Catalog:
                                                            @{var K360list = new SelectList((System.Collections.IEnumerable)ViewData["K360Catalogs"], "Value", "Key");}
                                                            <select asp-items="K360list" asp-for="K360catalog" class="form-control"></select>

                                                            <button type="submit" class="btn btn-primary">Save changes</button>
                                                            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>

                                    </form>

                                    @if (ViewBag.Message != null)
                                    {

                                    }

                    </fieldset>

                    <fieldset class="border p-2">
                        <legend class="w-auto">Mapped Data:</legend>

                        @using (Html.BeginForm("DeleteK360Data", "MappingK360", FormMethod.Post))
                        {
                            @*@Html.AntiForgeryToken()*@

                                        Client Catalog
                                        K360 Catalog
                                        ID
                                        Action

                                        @foreach (K360Master Mappeddata in ViewBag.K360MappedData)
                                        {

                                            @Mappeddata.Id
                                            @Mappeddata.ClientCatalog
                                            @Mappeddata.K360catalog

                                                    @{TempData["KDataId"] = @Mappeddata.Id;}
                                                    <input type="submit" class="btn btn-danger" value="Delete" />

                                    }

                            }

                    </fieldset>

public class K360Master
{
    public int Id { get; set; }
    public string ClientCatalog { get; set; }
    public string K360catalog { get; set; }

Comment: If I had to guess I would bet one of the things is using 0 based indexing and the other is using 1 based indexing which is always leaving the last row missing.
Comment: It's just that TempData["KDataId"] set current ID and gets overwritten every loop until TempData["KDataId"] set last ID before loop ends. So the TempData["KDataId"] is always last ID.
Comment: @asherguru, ya i observe that. so in foreach loop tempdata is not worth
Answer: in the foreach() loop you are overriding the value for TempData['KDataId'] at each itaration.
So, it will always be the id of the last K360Master object.
Instead you should send the desired id as a parameter, refactoring your controller method :
public IActionResult DeleteK360Data(int id)
{
    ...
}

And in your view :
@Html.ActionLink("Delete", "DeleteK360Data", new { id = @Mappeddata.Id})

(adapt it to generate the desired html tag such as button or whatever you want).
And don't forget to use [ValidateAntiForgeryToken] attribute on your controller's methods (not related to your question, but good practice).
Comment: public IActionResult DeleteK360Data(int id) .Id value is 0 always so that i try to sent through tempdata
Comment: You really have to do it like that. You should determine why the 'id' value is always 0 ; can you share your code of this version (controller) ? Maybe the route or some attribute is missing.
Comment: You did not modified the code as I suggested
Comment: i have modified as you suggest but id value is o so i revert back it
Comment: Ok but you are running a king of X-Y problem
Your goal now is to determine why id is 0, don't revert the code, it's the right way to to
Maybe try to modify he HttpPost attribute to include the id parameter.
Answer: View. Remove your Html.BeginForm.

   Delete

Javascript

Controller
[HttpPost]
public IActionResult DeleteK360Data(id) {
    // delete your data
}

EDITED
Download sample https://gofile.io/d/b4ZEs6.
UPDATED
<form method="post">

             ..

         @{
              foreach (var item in Model)
              {

                    <button asp-action="DeleteK360Data" asp-route-Id="@item.Id">Delete</button>
                    ..

              }
          }

</form>

Comment: sorry i am not good in javascript function
Comment: forgot to add [HttpPost]. Please see 'Controller' post.
Comment: If you don't have jquery.js, please use it.
Comment: @ asherguru,DeleteK360Data(id) >> id showing error
Comment: this code is common and working fine. other answer is also common and working too. you need to debug why it shows error. Like breakpoint in javascript in F12 developer console in chrome, etc.
Comment: you can download sample i made for you - https://gofile.io/d/b4ZEs6  you go check. i added 2 buttons using  and jquery.
Comment: ,thanks a lot.Will look into it and get back to you soon
Comment: btw, if use jquery, don't need to use .  is for button or input type=submit only.
Comment: ,When i replace model Models.K360Master to model List
Comment: If look into my code, i have Select html helper in ajax model popup and it shows error
Comment: List does not definition for ClientCatalog and no accessbile method
Comment: .. asp-for="ClientCatalog" shows error
Comment: no need to copy all K360Master etc. you just use  + button or jquery button into your existing project. that's all.
Comment: ya tried first jquery  $.post('@Url.Action("DeleteAjax")', { id: id }) not firing
Comment: then you use  + button one. it should work.
Comment: Delete form working like a gem!. Thanks a lot from my bottom of heart for your kind effort
Comment: Glad to hear. I updated post for working code (in your case). Please mark this as solved. Thanks.
Comment: i am new to stack overflow. Don't know to mark as solved. Now i did that. Sorry for delay.
Comment: ,again post one more question in the same task. If possible please look it ino it
Comment: now one immediate task for me. i have created new question.please look into your free time
Comment: https://stackoverflow.com/questions/66227012/dynamic-controls-creation-based-on-json-url-in-dotnet-core-mvc


Deploy firebase cloud functions - Invalid function service account

Question: I am trying to deploy my firebase cloud functions they work fine on local host but when I try to deploy them I get the following error:
{"@type":"type.googleapis.com/google.cloud.audit.AuditLog","status":{"code":3,"message":"Invalid function service account requested: default. Please visit https://cloud.google.com/functions/docs/troubleshooting for in-depth troubleshooting documentation."},"authenticationInfo":
I tried to play with roles but nothing works any help
Comment: I'm having the same error and I don't know why. Although it was working correctly earlier!
Comment: I think i've found some kind of a temporary solution for this. You can check this https://github.com/firebase/firebase-tools/issues/4697#issuecomment-1172733975
Answer: Okay so the main problem is in the 11.2.0 version of firebase-tools.
The steps i did to reproduce was simply downgrading to the 11.1.0 version and it worked perfectly!
This is the issue on github and this is the solution suggested by mhotan:
npm install -g firstname.lastname@example.com

Comment: Thank you, downgrading to 11.1.0 version worked for me too.
Comment: Same problem here with 11.2.0
Downgrading to 11.1.0 worked for me


How to create a view printing the latest 3 nodes with unique entity reference values

Question: I have two content types, CAR and DRIVER. The DRIVER content type contains a CAR entity reference field. So each DRIVER node creation page can reference a specific CAR.
The goal is to build a view to print out 3 of the most recent unique CARs referenced from a DRIVER node (created by the logged-in user).
Example... here are 6 of the most recently created DRIVERS by a particular user.

Driver 1 - BMW
Driver 2 - BMW
Driver 3 - Mercedes
Driver 4 - BMW
Driver 5 - Audi
Driver 6 - Mercedes

The goal is to display 3 of most recent unique CARS referenced, like so...

Driver 1 - BMW
Driver 3 - Mercedes
Driver 5 - Audi

The closest solution I've found is using Aggregation in views, but the sort order by Created Date doesn't actually sort them correctly.
I'm open to building this outside of views also. Any suggestions? Thanks!
Comment: How is the 'Cars' reference defined? Taxonomy? Entity reference? Also, the logged-in user can have multiple drivers? Is this correct? I'm trying to figure out how a relation between Driver and Car can be established. Is the car a defined value (like a taxonomy term) or is it a value the user can type in? If it's the latter, this will be harder to do because there wouldn't be a unique ID that can be used. Once this gets figured out, you can sort by # of results and filter down to the top 3.
Comment: 'Cars' and 'Drivers' are both Content Types, and Cars are referenced via entity reference field on the Driver node add form. Yes, the logged-in user can create multiple drivers. Yes, Cars are predefined values (has it's own unique ID) as it's a previously created node. Still, the issue remains... narrowing down the latest 3 Drivers with unique Cars (not duplicating the Car value). Thanks!
Comment: Are you able to pull in 3 car/driver combinations? Even if they aren't unique?
Comment: Yes, I can via Views. And I can make them unique using aggregation. But trying to sorting by DATE breaks the aggregation.
Comment: try sorting by NID
Comment: Tried it, but since it's being aggregated/grouped by CAR, and I need it sorted by the created date of DRIVER... setting sort to the DRIVER's NID breaks aggregation.
Answer:
Create a view for Car content type
Add a relationship to Driver content referencing this content
Sort by created date using the Driver relationship
Use aggregation to show distinct values
Use pager settings to only show specific amount of items
Comment: Doesn't work... the "sort by created date" with aggregation doesn't display results as you suggest.


Preferred way to combine PHP and HTML?

Question: I learned PHP by hacking away at phpBB2, even submitting a few mods to their database, which others downloaded and used. (I don't believe phpBB2 is supported any more with phpBB3 out so long now, so the v2 mods database is no more.)
One of my favorite things about phpBB was their templates system, which let the editor completely separate the HTML and the PHP. PHP files contained PHP: logic, database queries, and activating the templates. TPL files contained templates: HTML, template variables, and specialized HTML comments to allow for conditional or repeating blocks.
However, any time I see someone's PHP code online, it's either a small snippet working with a single function or such, or the PHP is full of strings containing HTML (or worse, HTML with PHP interspersed). phpBB is the only PHP I've looked at which actually separates the language and the markup language, suggesting to me that few, if any, other PHP codebases do such a thing.
I'm looking to start working with some PHP again, but this time it won't be a phpBB forum, and it will be on a team. Based on my experience, separation of PHP and HTML is uncommon (please correct me if I'm wrong on this!). However, I'm so used to that dividing line, I hate reading mixed PHP and HTML.
In the "real world" of PHP programming, what's the preferred method:

PHP files with strings of HTML
HTML files broken up with PHP blocks
PHP and HTML completely separate (I wish?)
Something else?
Answer: If you want to separate the PHP from the HTML you can use a template engine (Like smarty http://www.smarty.net/).
Comment: I think this exactly the sort of thing I'm looking for to develop in PHP without piggybacking off of phpBB.
Answer: Personally, I see no reason to add a template system/language into the mix, when PHP is already a prefectly good solution.
My preferred approach is to separate the display from the logic of the application.  This could take the form of a full blown MVC framework.  However, it could also be a simple matter of how you go about writing your code.
Expansion:
Ever since making the mistake of interspersing my HTML with copious amounts of ASP code, I have tried to separate page logic from display.  Within a single page, this means placing all of the page logic at the top, storing the information to be displayed in variables and then echoing them out within the HTML at the bottom of the PHP file.  The only logic which appears in the HTML portion is display logic.  In other words, simple error handling, ifs, loops, etc.  Basically, the same stuff that you'll find in most templating languages.
My reason for avoiding templating languages is that it's yet another form of syntax that I need to worry about.  What's the point? PHP provides more than I need for this purpose.
Meanwhile, you can take a simple MVC approach by separating things:
controller.php
<?php
// some application logic
$data['message'] = 'Hello, World.';

include 'view.php';

exit;
?>

view.php:

<title>
A simple 'MVC' view
</title>

<?php

echo $data['message'];

?>

This isn't without its drawbacks and issues.  However, if you think you can have complete, clean separation between application logic and display, you're mistaken.
Comment: Could you expand on this? How exactly is PHP a solution to separating PHP and HTML? And what about an example of your MVC approach? I understand the concept of MVC, but my weekend brain (only turned on halfway!) doesn't have a concept of PHP MVC for separating the logic and the presentation.
Comment: Thanks for the expanded answer. It looks like your recommendation is similar to the recommendation from [bobince](http://stackoverflow.com/questions/3220655/preferred-way-to-combine-php-and-html/3220993#3220993)?
Comment: @bobince Yes, pretty much.  The motivation for my answer was to warn against using a templating system.  There are situations where they can be useful.  Say, if you have a separate team dedicated to the front-end.  However, if you know PHP and you're responsible for the HTML (or the back-end devs have to touch it a lot), I think templating systems are generally overkill.  Good coding practices can achieve the same thing without an extra layer of processing.
Comment: Ok, I understand. The motivation for my question was mostly because I became so used to phpBB's templating, that I simply don't like reading files with mixed PHP and HTML. I think I could handle this level of mixture, though; I think the only significant difference between what I'm used to and your MVC example would be presentation logic, and this route would even be superior (at least to phpBB2) if the presentation logic started to get particularly complicated.
Comment: @Brian S  Note, if you remove the calls to include and exit, this can be done in one file.  That's the approach I typically use for relatively simple pages.
Answer: We use a customized code igniter base for MVC and just have logic and layout separated. that doesn't necessarily mean there's no php in our html, just that its not used for logic. It's perfectly okay to loop through a recordset with php code in a template imho, just don't try to talk to business objects and actually do stuff in the layout templates. You could ofcourse also look into something like tal or a million others for the templates if you really want to get rid of all php code there. I'm kinda thinking that's mostly overkill though, unless "insert special circumstance here"
edit fixed typo
Answer: In my experience, a lot of PHP development, whether for better or worse, ends up being php files connected to each other through includes that print out snippets of HTML as needed.
Mind though, most of my PHP experience is for more of a "we just need something that works" solution than a "we need the most elegant and efficient solution"
Comment: This makes a lot of sense, and it explains all the code I see lying around which I hate looking at.
Answer:
any time I see someone's PHP code online, it's either a small snippet working with a single function or such, or the PHP is full of strings containing HTML (or worse, HTML with PHP interspersed).

Yeah, the general quality of code out there is embarrassing.
Whilst you can go to a full-blown templating engine of your own, that may be overkill and in many cases the limited domain-specific-languages they provide will get in your way, when you could just be writing presentation logic in PHP.
If you want to still be writing normal PHP, but without the spaghetti:

Keep action code at the top of the file or in a different file. Put only application logic here, not any kind of HTML or templating. Any information generated in this stage that needs to be displayed by the template needs to go in a variable to be passed to the templating part, not printed out in the middle of a load of business logic.
Take your knowledge of tag-based templating and apply it to PHP. Have a single, correctly-indented hierarchy of code for both HTML and PHP presentation logic, as if you were writing 'well-formed' XML (whether or not you're actually using XHTML). Avoid putting HTML in strings at all costs.
Define an easier way of calling htmlspecialchars(), because otherwise typing that all the time is going to be a real pain, and if you aren't typing it all the time you're going to have potentially security-sensitive errors.

To summarise, eg.:
<?php
    // active code here
    // do things
    // put any errors in a $errors array

    // this trivial function would presumably be in an include
    //
    function h($s) {
        echo htmlspecialchars($s, ENT_QUOTES);
    }
?>

    <?php if (count($errors)!=0) { ?>

            <?php foreach ($errors as $error) { ?>
                <?php h($error); ?>
            <?php } ?>

    <?php } ?>
    ...

In the "real world" of PHP programming, what's the preferred method:

Oh, in the real world of PHP programming, the average project has a mishmash of approaches thrown together without any thought. In the real world the code is unmaintainable, bug-ridden, and insecure. You don't want to look at the Industry Standard, because the Industry Standard is to be broken in every way.
Comment: No, I can't. I have yet to meet a publically-available PHP project whose templating isn't a maze of twisty little echo-HTMLs, all alike.
Comment: Can you point me to source code for a non-trivial project formatted this way? I like the concept but I would like to see how readable it is on a larger scale, and how a lot of specific circumstances are handled.
Answer: I prefer to use a template system to minimize the amount of PHP code contained in the HTML files. I really don't see any way to entirely separate PHP from HTML, but I feel that it is sufficient to separate business logic (database) from presentation logic.
My template system is home-baked, but I'm sure you can find a variety that would work by preforming a google search.
Answer:
Based on my experience, separation of PHP and HTML is uncommon

True. But lot of PHP code is written by inexperienced developers. Further, PHP does not encourage, but rather discourage writing good code, and the ability to mix HTML with programming code is one of the examples of this.
If you expect to do high quality code, to be able to easily maintain and extend it, I highly recommend using template engine or something similar. Mixing both has a huge impact on the readability of your code, and will result in something becoming worse and worse over time. Refactoring will be painful, if not impossible.
Now, you have a large choice of the way to separate HTML from PHP

The most obvious one is to use an existing layout engine. There are plenty of them, some very well done and with a very low performance impact.
You can also write your own engine. It may not be a good idea on a big project (why reinvent the wheel?), but can be a solution either on a tiny project or when you need something very specific.
The last way I use in most projects is to build XML from business layer (XML serialization is quite easy in PHP), then to use XSLT to transform this to HTML page. It enables to do websites which are much easier to maintain and more easy to understand, and, by the way, enables to access the website data programmatically (loading XML instead of HTML page) when need. On the other hand, it decreases performance hugely, so is not intended for large websites with thousands of queries per second.
Answer: Most code starts with PHP and HTML strings, then evolves into a templating system during a big rewrite. Separating content from logic up front requires design, planning and communication among the team. Using XML or JSON instead of PHP arrays as the data format makes this easier.
Answer: you can mix up PHP inside HTML or vice versa simply by adding opening <?php and closing ?> PHP tags between your HTML.
<!DOCTYPE html>

<title>Hello world as text</title>

        <?php
            echo "
Hello world
";
        ?>

For more details : https://stackhowto.com/how-to-combine-html-and-php/

Preferred way to combine PHP and HTML?


why I have to re-declare type when implement interface in typescript

Question: why typescript throw error when I already declare type in interface.

Playgroud:
http://www.typescriptlang.org/play/#code/JYOwLgpgTgZghgYwgAgILIN4Chm+QDwC5kQBXAWwCNpkAfE0gG0YG4c8BnCMADQAoAbnEbEyVaAEpiAgPbAAJmwC+WLAkZwOHZACFkwcgAdGEchHDb02PMgD0tgsgC8DZi1z3kAHgC0f5GAAFsDaAO7AzCQyYMjkcADWKAAGXLxJAYFQMqHI0FlQ7LhEDOJQdK6MzhVshcip-EIiJdRQEpi1NkEhAHT4VY1sNipKQA
Answer: You have to define implementation of x in the class. Interface definition only defines "shape" of an object.
TypeScript cannot know how you want to implement the x. For example, instead of using field, you could have valid implementation of A interface using getter, setter and backing field:
class B implements A {
    private _x: number | null = null;

    get x(): number | null {
        return this._x;
    };

    set x(value: number | null) {
        this._x = value;
    }

    setX(val: number) {
        this.x = val;
    }
}

Typescript playground link.
Answer: When your class is implementing interface then it doesn't mean that properties from an interface have been already declared in a class. All that interface is doing here for you it's just checking your types in class:
Ok:
class B implements A {
    x: number | null = null;
    ...
}

Not ok:
class B implements A {
    x: number | string= "";
    ...
}

But you can't use 'x' without declaring it in class and you have declared it in class as null which matches the type number | null. An interface is only to check types used in class, not further implementation.


Como encontrar todos os lugares onde estão sendo utilizados métodos depreciados no Netbeans?

Question: Há alguma ferramenta no Netbeans que permita gerar um arquivo, um relatório, um log, ou algo do gênero, para encontrar todos os métodos que estão depreciados em uma Classe ou Projeto?
Tentei encontrar na Internet, e no próprio Stack, porém, só achei algo para o Eclipse, onde eram apresentados junto aos warnings do projeto.
Utilizo o Netbeans 8.0.
Comment: Iria responder mas se você não se importar em traduzir, a resposta está no stackoverflow em inglês: https://stackoverflow.com/questions/2583138/how-do-i-detect-the-deprecated-methods-in-a-program
Comment: Obrigado, talvez tenha sido a forma como pesquisei, dando maior foco em "Netbeans" do que em Java que fez eu não encontrar.
Comment: Alguma resposta ajudou a resolver o problema e pode sanar dúvidas similares de outros usuários? Caso positivo não esqueça de marcar a resposta como aceita. Pra fazer isso é só clicar no ✓ do lado esquerdo da mesma (abaixo do indicador de up e down votes).
Answer: Abra as propriedades do seu projeto, vá até a opção Compilação dentro da opção Construir na árvore do lado esquerdo. No campo Opções Adicionais do Compilador insira -deprecation. Depois disso os métodos depreciados serão mostrados como warning no output do projeto quando compilado.

-deprecation
Show a description of each use or override of a deprecated member or class.

Em tradução livre:

Mostra a descrição de cada uso ou sobrecarga de membros ou classes depreciados.


Extending a class that has been instantiated without 'new'

Question: I am using a library from Github that I am adding to my project via Composer. In my code, I want to extend the library classes. I would normally be able to do this with a simple extend and new e.g.
class myNewClasses extends classesFromTheLibrary
{
// add my custom methods here
}

// instantiate with new
$allClasses = new myNewClasses; // $allClasses can access methods in myNewClasses and classesFromTheLibrary

But, this library is instantiated as follows:
$document = \Sokil\Vast\Document::create('2.0');

So the new technique can't be used. Also, some of the classes I would like to extend are in different namespaces, such as \Sokil\Vast\Ad\Inline.
How do I extend classes when the instantiated this way and with different namespaces?
For reference, the library I'm trying to use is here
... and I've tried the decorator technique discussed here, but that doesn't seem to work either.
** EDIT **
Perhaps I am barking up the wrong tree here with extends: The ::create('2.0') may be a distraction.
What I am trying to do is add a method to a class in a different namespace to the parent.
The first instantiation happens at the top level: \Sokil\Vast\Document, but the class I want to extend is \Sokil\Vast\Ad\Inline ... but if I extend that class, I can't instantiate it, because it is instantiated within \Sokil\Vast\Document that I don't have access to. Hope that makes sense. Any ideas?
Comment: Does `myNewClasses::create("2.0")` not work? The author of that class did not intend it to be easily extended (if he had then he would have used the constructor, not a static method). Complain to the author.
Comment: That looks like it is instantiated via a [static method](http://php.net/manual/en/language.oop5.paamayim-nekudotayim.php). I'm not sure but maybe [this](http://stackoverflow.com/questions/1280492/extending-php-static-classes) is relevant.
Comment: @SverriM.Olsen, No - because [`create()`](https://github.com/sokil/php-vast/blob/master/src/Sokil/Vast/Document.php#L29) will always return an instance of the superclass without additional changes from the subclass.
Comment: @SverriM.Olsen and @HPierce, it seems you are both right: `myNewClasses::create("2.0")` does work (when using `extends \Sokil\Vast\Document`), but the additional classes in myNewClasses don't extend to the different namespaces (such as `\Sokil\Vast\Ad\Inline`).
Answer: Perhaps this would do:
class myDocClass extends \Sokil\Vast\Document {
    private $parentObj;
    public function __construct() {
        $this->parentObj = parent::create('2.0');
    }
}

$myDoc = new myDocClass();

You can't assign to $this, so I've created a property linking to the parent obj, which is instantiated in the create() static method of the parent.
Comment: This seems to instantiate the class but then errors further down the code where it uses $this saying that it is null.
Comment: What method did you try to call ? All methods from the parent class aren't in `$this`, but they're in `$this->parentObj` (`$this->parentObj->method()` for instance).
Answer: Since version 0.6 added ability to override element classes, so any custom element or element's attribute may be added.
First let's create class for MediaFile and add some custom attribute:
<?php

namespace Acme\Vast\ElementBuilder\Element;

use Sokil\Vast\Creative\InLine\Linear\MediaFile;

class AcmeMediaFile extends MediaFile
{
    public function setMinDiration($seconds)
    {
        $seconds = (int)$seconds;
        if ($seconds <= 0) {
            thow new \InvalidArgumentException('Invalid min duration specified, must be positive int')
        }

        $this->domElement->setAttribute('minDuration', $seconds);

        return $this;
    }
}

Now we need to override default element builder and create own MediaFile factory method:
<?php

namespace Acme\Vast\ElementBuilder;

use Sokil\Vast\ElementBuilder;
use Acme\Vast\ElementBuilder\Element\AcmeMediaFile;

class AcmeElementBuilder extends ElementBuilder
{
    /**
     * <Ad><InLine><Creatives><Creative><Linear><MediaFile>
     *
     * @param \DOMElement $mediaFileDomElement
     *
     * @return AcmeMediaFile
     */
    public function createInLineAdLinearCreativeMediaFile(\DOMElement $mediaFileDomElement)
    {
        return new AcmeMediaFile($mediaFileDomElement);
    }
}

Now we need to confugure VAST factory to use overridden element builder:
<?php

use Acme\Vast\ElementBuilder\AcmeElementBuilder;
use Sokil\Vast\Factory;

$elementBuilder = new AcmeElementBuilder();
$factory = new Factory($elementBuilder);

$document = $factory->create('4.1');

$ad = $document->createInLineAdSection();
$creative = $ad->createLinearCreative();
$mediaFile = $creative->createMediaFile();

$mediaFile->setMinDiration(10);

See https://github.com/sokil/php-vast#custom-specification-support for more details.


conditional probability density of arrival times

Question: I am trying to figure out how to solve problem:
Let $N(t)$ be a Poisson process of rate $λ$. Given that $N(t) = 3$, determine the conditional probability density functions of each of the three arrival times $S_1$, $S_2$, $S_3$.
I know that $S_1$ and $S_2$ are uniformly distributed at $[0,1]$ and $S_3$ seems to be independent of them, so I can find its pdf from joint density of $S_1$, $S_2$ and $S_3$ which is equal to $3!/t^3$. Then the pdfs of $S_1$ and $S_2$ are $1/t$ and pdf of $S_3 = 6/t$. Or maybe they are all the same $(2/t)$?
Answer: $S_1$ and $S_2$ are not uniformly distributed, and just where you  get $[0,1]$ you don't tell us.  The support of the distribution of each of the three random variables $S_1$, $S_2$, $S_3$ is $[0,t]$, not $[0,1]$.
In fact $S_1,S_2,S_3$ have the same distribution as the order statistics from an i.i.d. sample of size $3$ from a uniform distribution.  That implies that none of them is uniformly distributed.
Unconditionally, or marginally (if you prefer that word), we have $\Pr(S_1<s) = 1 - e^{-\lambda s}$ for $s>0.$  We want $\Pr(S_1<s\mid N(t)=3)$.
\begin{align}
& \Pr(S_1<s \mid N(t) = 3) = \frac{\Pr(S_1<s\ \&\ N(t)=3)}{\Pr(N(t)=3)} \\[10pt]
= {} & \Pr(N(s)\ge 1 \mid N(t)= 3) \\[10pt]
= {} & \frac{\Pr\left( \begin{array}{r} \big(N(s)=1\ \&\ N(t)-N(s) = 2\big) \\
\text{ or } \big( N(s)=2\ \&\ N(t)-N(s)=1 \big) \\
\text{ or } \big( N(s)=3\ \&\ N(t)-N(s)=0 \big) \end{array} \right)}{\dfrac{\lambda^3 e^{-\lambda t}}{3!}} \\[10pt]
= {} & \frac{ \left( \begin{array}{r} \dfrac{(\lambda s)^1 e^{-\lambda s}}{1!} \cdot\dfrac{(\lambda(t-s))^2 e^{-\lambda (t-s)}}{2!} \\[10pt]
{} + \dfrac{(\lambda s)^2 e^{-\lambda s}}{2!} \cdot \dfrac{(\lambda(t-s))^1 e^{-\lambda (t-s)}}{1!} \\[10pt]
{} + \dfrac{(\lambda s)^3 e^{-\lambda s}}{3!} \cdot\dfrac{(\lambda(t-s))^0 e^{-\lambda (t-s)}}{0!} \end{array} \right) }{\dfrac{\lambda^3 e^{-\lambda t}}{3!}} \\[10pt]
= {} & \frac{\dfrac{s^1 (t-s)^2}{1!2!} + \dfrac{s^2(t-s)}{2!1!} + \dfrac{s^3}{3!}}{1/(3!)} \\[10pt]
= {} & \binom 3 1 s^1 (t-s)^2 + \binom 3 2 s^2 (t-s)^1 + \binom 3 3 s^3.
\end{align}
This is the c.d.f. on the interval $[0,t]$.  Differentiating it with respect to $s$ gives you the p.d.f. on that interval. If you differentiate this with respect to $s$, using the product rule, you'll get five terms, and all but one of them will cancel.
$S_2$ and $S_3$ can be handled similarly.
Comment: Any idea how to solve this?
 https://math.stackexchange.com/questions/2253101/conditional-inter-arrival-times-for-poisson-and-renewal-process