Compute the effect of $∆_∗$ on homology groups.

Question:
Let $∆ : S^n → S^n × S^n$ be the diagonal map $∆(x)=(x,x)$. Compute the effect of $∆_∗$ on homology groups.

My attempt :
I considered the CW chain complex of $S^n$ and let, $H_0(S^n)=\Bbb Z\{v\}$ and $H_n(S^n)=\Bbb Z\{e\}$ . Then    $S^n × S^n$ has it's non-zero homlogy groups $H_0(S^n \times S^n)=\Bbb Z\{v \otimes v\},H_n(S^n \times S^n)=\Bbb Z\{v \otimes e,e \otimes v\},$$ H_{2n}(S^n \times S^n)=\Bbb Z\{e \otimes e\}$ .
$H_{2n}(S^n)=0$ .
Looking at $H_0(S^n)$ , $\Delta_*  : H_0(S^n) \to H_0(S^n \times S^n)$ behaves like, $\Delta_*(v)=(v,v)$ which can we identify with $v \otimes v$ ? If it is true then it's identity on the 0th homology .
And then ,$\Delta_*  : H_n(S^n) \to H_n(S^n \times S^n), \Delta_*(e)=(e,e)$ how to understand the realtion with the generators  $v \otimes e,e \otimes v$ ?
Thanks in advance for help!
Comment: @Javi yeah, so it's identity on the 0th Homology group, right? What about the other cases?
Comment: Since you are using tensor products, I assume that you're relying on the Künneth formula. The image of $(v,v)$ by the natural map to the tensor product is precisely $v\otimes  v$.
Comment: In the second case, you are actually making some identifications. If the homology of the first sphere is generated by $v$ and you don't have any generator (or element) called $e$, then you cannot send $e\to (e,e)$, because the first coordinate doesn't make sense, so I think you're implicily calling $e$ to $v$.
Comment: @Javi Honeslty, I am totally new to this topic and am having difficulty in understanding the stuff clearly, so would you kindly help me to learn it better by posting an answer in details.
Comment: Hint : Consider $\pi_1, \pi_2 :S^n \times S^n \rightarrow S^n$ the projection maps
Answer: Example 3B.3 of Hatcher's Algebraic Topology can enlighten your problem a bit. I'm going to be using the Künneth formula all the time.
In the first case, as we mention, you have factorized $\Delta_*:H_0(S^n)\to H_0(S^n)\times H_0(S^n)\to H_0(S^n)\otimes H_0(S^n)\cong H_0(S^n\times S^n)$. The map between the cartesian product and the tensor product is the canonical one, sending $(x,y)\mapsto x\otimes y$. In particular, if you call $u$ the generator of the first $S^n$ of the product, $v$ the generator of the second $S^n$ of the product, and $e$ the $S^n$ of the source, it is clear by cellular homology that $e\mapsto (u,v)\mapsto u\otimes v$. You called $v$ both $u$ and $v$, which is not a problem, but I think that could have led you to a confusion.
In the second case, we have that $H_n(S^n\times S^n)\cong (H_n(S^n)\otimes H_0(S^n))\oplus (H_0(S^n)\otimes H_n(S^n))$. Then, you can choose generators $(u\otimes v)$ and $(v\otimes u)$, (I'm now identifying generators of both spheres, you can avoid it if you want). Then, the generator $a$ of $H_n(S^n)$ is mapped $(u\otimes v)\oplus (v\otimes u)$ (if you called the generators by a different name you just have to keep the naming here). You can even call $a$ to every generator of every $H_n(S^n)$, which simplifies the notation, giving you that $a\mapsto (a\otimes v)\oplus (v\otimes a)$, which is probably more clear. Now, $(u\otimes v)$ and $(v\otimes u)$ (or $(a\otimes v)$ and $(v\otimes a)$) are just the generators of the direct sum, so everything is known.
The important thing here, is that the generators are product of cells of dimension whose sum is the dimension of the homology.


Call to undefined method PDO::bindParam(), como resolvo?

Question: Estou iniciando os estudos de OO e decidi dar uma olhada no PDO, só que não está funcionando. Me ajudem, por favor:
<?php

class Cliente {
   private $nome;
   private $email;
   private $telefone;
   protected $cpf;
   protected $senha;
   private $pdo;

   public function __construct() {
       try{
       $this-> pdo = new PDO ("mysql:host=localhost; dbname=clientes;","root","");
       } catch (PDOException $erro){
           echo "Não Foi possivel conectar ao Banco: ".$erro->getMessage();
       }

   }
   public function cadastrar($nome, $email, $cpf, $data_nascimento, $telefone, $endereco){
               $this-> pdo -> prepare ("select CPF from cliente where CPF = ':cpf'");
               $this-> pdo -> bindParam (':cpf', $cpf);
               $this-> pdo -> execute();

               if ($this->pdo -> rowCount() >= 1){
                   echo "Cadastro já existente.";
               } else {
               try {
               $this->pdo->prepare("INSERT INTO clientes(nome, email, data_naschimento, telefone, endereco)
                  values (':nome',':endereco',':email',':data_nascimento', ':telefone', ':endereco')");
                  $this->pdo -> bindParam(':nome', $nome);
                  $this->pdo -> bindParam (':endereco', $email);
                  $this->pdo -> bindParam (':email', $data_nascimento);
                  $this->pdo -> bindParam (':data_nascimento', $telefone);
                  $this->pdo -> bindParam (':telefone', $endereco);
                  $this->pdo -> execute();
                  echo "Dados cadastrados com Sucesso";
               }
               catch (PDOException $erro){
                   echo "Não foi possivel inserir os dados no banco: ".$erro->getMessage();

               }

        }

   }

   public function apagarCadastro($cpf){
           //Executa uma query que apaga os dados o banco
    try{
           $this -> pdo -> prepare("DELETE FROM CLIENTE WHERE CPF = ':cpf' ");
           $this -> pdo -> bindParam (':cpf', $cpf);
           $this -> pdo -> execute();
    }
    catch (PDOException $erro) {
           echo "Não foi possivel apagar os dados: ". $erro->getMessage();
    }
    if ($this -> pdo -> rowcount() >=1 ){
           echo "Todos os dados foram apagados com Sucesso.";
       }
   }
   public function atualizarNome($newNome, $oldNome){
           //Executa uma query que atualiza o nome no banco
           try {
           $this -> pdo -> prepare ("UPDATE CLIENTES SET NOME = ':nome' WHERE NOME = ':nome2'");
           $this -> pdo -> bindParam (':nome', $newNome);
           $this -> pdo -> bindParam (':nome2', $oldNome);
           } catch (PDOException $erro){
               echo "Não foi possível atualizar os dados". $erro->getMessage();
           }
   }
   public function atualizarEmail(){
       //Executa uma query que atualiza o banco
   }
   public function atualizarSenha(){
       //Executa uma query que atualiza o banco
   }
   public function exibeDados(){
       //Executa uma query que da um select no banco

   }
   public function getPdo() {

   }

}

Answer: O metodo bindParam pertence à classe PDOStatement. O método prepare da classe PDO retorna um PDOStatement:
$stmt = $this->pdo->prepare("QUERY");
$stmt->bindParam(":param", $value);
$stmt->execute();

Quando usar o prepare, atribua seu retorno a uma variavel, e use-a para associar os parametros à query com o bindParam.
No seu caso, podemos mudar o seguinte trecho:
       try {
          $this->pdo->prepare("INSERT INTO clientes(nome, email, data_naschimento, telefone, endereco)
          values (':nome',':endereco',':email',':data_nascimento', ':telefone', ':endereco')");
          $this->pdo -> bindParam(':nome', $nome);
          $this->pdo -> bindParam (':endereco', $email);
          $this->pdo -> bindParam (':email', $data_nascimento);
          $this->pdo -> bindParam (':data_nascimento', $telefone);
          $this->pdo -> bindParam (':telefone', $endereco);
          $this->pdo -> execute();
          echo "Dados cadastrados com Sucesso";
       }
       catch (PDOException $erro){
           echo "Não foi possivel inserir os dados no banco: ".$erro->getMessage();

       }

Para:
       try {
          $stmt = $this->pdo->prepare("INSERT INTO clientes(nome, email, data_naschimento, telefone, endereco)
          values (':nome',':endereco',':email',':data_nascimento', ':telefone', ':endereco')");
          $stmt -> bindParam(':nome', $nome);
          $stmt -> bindParam (':endereco', $email);
          $stmt -> bindParam (':email', $data_nascimento);
          $stmt -> bindParam (':data_nascimento', $telefone);
          $stmt -> bindParam (':telefone', $endereco);
          $stmt -> execute();
          echo "Dados cadastrados com Sucesso";
       }
       catch (PDOException $erro){
           echo "Não foi possivel inserir os dados no banco: ".$erro->getMessage();

       }

Comment: Obrigado, assim que chegar em casa irei testar. E digo se funcionou, novamente,, obrigado pela atenção.
Comment: @TiagoSilveira Sem problemas. Se essa resposta foi realmente util, selecione-a como a resposta correta para a pergunta, assim outras pessoas que tiverem a mesma duvida que voce, possam encontrar mais facilmente a solucao. :)
Comment: Muito obrigado, resolveu meu problema. Obrigado mesmo.


Composer not respecting constraint defined in composer.json

Question: I have a build, with the following constraint on drupal/core, for some reason the constraint is not respected.
Upon running composer install this comes up:
 - Downloading drupal/core (9.5.0-rc1)

Composer show -i drupal/core:
name     : drupal/core
descrip. : Drupal is an open source content management platform powering millions of websites and applications.
keywords :
versions : * 9.5.0-rc1

I seriously would prefer having stable drupal/core.  I am able to "force the universe" by doing  composer require drupal/core --update-with-dependencies, and committing the generated .lock file.
Why, composer, why?!?
composer.json:
{
    "name": "acme/drupal",
    "description": "Acquia-compatible Drupal application based on the Drupal Recommended Project",
    "license": "GPL-2.0-or-later",
    "authors": [
        {
            "name": "Acquia Engineering",
            "homepage": "https://www.acquia.com",
            "role": "Maintainer"
        }
    ],
    "repositories": {
        "asset-packagist": {
            "type": "composer",
            "url": "https://asset-packagist.org"
        },
        "drupal": {
            "type": "composer",
            "url": "https://packages.drupal.org/8"
        }
    },
    "require": {
        "php": ">=8.1",
        "acquia/acquia-cms-starterkit": "^1",
        "acquia/blt": "^13.5",
        "acquia/drupal-environment-detector": "^1",
        "acquia/http-hmac-php": "6.0.0",
        "acquia/memcache-settings": "^1",
        "composer/installers": "^2.1",
        "cweagans/composer-patches": "^1.6",
        "drupal/address": "^1.11",
        "drupal/admin_toolbar": "^3.1",
        "drupal/coffee": "^1.2",
        "drupal/config_ignore": "^2.3",
        "drupal/config_readonly": "^1.0@beta",
        "drupal/config_split": "^1.9",
        "drupal/core": "~9.4",
        "drupal/core-composer-scaffold": "^9",
        "drupal/core-recommended": "~9.4",
        "drupal/drimage": "^2.0",
        "drupal/entity_browser": "^2.8",
        "drupal/entity_clone": "^1.0@beta",
        "drupal/field_group": "^3.2",
        "drupal/focal_point": "^1.5",
        "drupal/fpa": "^3.0",
        "drupal/gin": "^3.0@beta",
        "drupal/insert": "^1.0",
        "drupal/link_attributes": "^1.11",
        "drupal/module_filter": "^3.2",
        "drupal/paragraphs": "^1.15",
        "drupal/pathauto": "^1.11",
        "drupal/scheduler": "^1.4",
        "drupal/seckit": "^2.0",
        "drupal/section_library": "^1.0",
        "drupal/section_library_reusable": "^1.0@beta",
        "drupal/shield": "^1.6",
        "drupal/twig_tweak": "^3.1",
        "drupal/upgrade_status": "^3.13",
        "drupal/webprofiler": "^9.0",
        "drush/drush": "^10.6 || ^11",
        "oomphinc/composer-installers-extender": "^1.1 || ^2"
    },
    "require-dev": {
        "acquia/blt-phpcs": "^1.0",
        "acquia/coding-standards": "^1.0.0",
        "behat/behat": "^3.11",
        "behat/mink": "^1.10",
        "drupal/devel": "^4.1",
        "drupal/drupal-extension": "^4.2",
        "drupal/twig_vardumper": "^3.0",
        "mglaman/phpstan-drupal": "^1.1",
        "phpspec/prophecy-phpunit": "^2.0",
        "phpstan/extension-installer": "^1.1",
        "phpstan/phpstan": "^1.6",
        "phpstan/phpstan-deprecation-rules": "^1.0",
        "phpunit/phpunit": "^9.5",
        "squizlabs/php_codesniffer": "^3.6"
    },
    "config": {
        "allow-plugins": {
            "composer/installers": true,
            "cweagans/composer-patches": true,
            "dealerdirect/phpcodesniffer-composer-installer": true,
            "drupal/core-composer-scaffold": true,
            "ergebnis/composer-normalize": true,
            "oomphinc/composer-installers-extender": true,
            "phpstan/extension-installer": true,
            "acquia/blt": true,
            "acquia/blt-phpcs": true,
            "drupal/console-extend-plugin": true
        },
        "platform": {
            "php": "8.1"
        },
        "sort-packages": true
    },
    "extra": {
        "composer-exit-on-patch-failure": true,
        "drupal-scaffold": {
            "allowed-packages": [
                "acquia/acquia_cms"
            ],
            "file-mapping": {
                "[profile-root]/.editorconfig": false,
                "[profile-root]/.gitattributes": false,
                "[profile-root]/.travis.yml": false,
                "[profile-root]/acquia-pipelines.yml": false,
                "[web-root]/sites/default/default.services.yml": {
                    "mode": "replace",
                    "overwrite": false,
                    "path": "docroot/core/assets/scaffold/files/default.services.yml"
                },
                "[web-root]/sites/default/default.settings.php": {
                    "mode": "replace",
                    "overwrite": false,
                    "path": "docroot/core/assets/scaffold/files/default.settings.php"
                }
            },
            "gitignore": true,
            "locations": {
                "profile-root": "docroot/profiles/contrib/acquia_cms",
                "web-root": "docroot/"
            }
        },
        "enable-patching": true,
        "installer-paths": {
            "docroot/core": [
                "type:drupal-core"
            ],
            "docroot/libraries/{$name}": [
                "type:drupal-library",
                "type:bower-asset",
                "type:npm-asset"
            ],
            "docroot/modules/contrib/{$name}": [
                "type:drupal-module"
            ],
            "docroot/modules/custom/{$name}": [
                "type:drupal-custom-module"
            ],
            "docroot/profiles/contrib/{$name}": [
                "type:drupal-profile"
            ],
            "docroot/themes/contrib/{$name}": [
                "type:drupal-theme"
            ],
            "docroot/themes/custom/{$name}": [
                "type:drupal-custom-theme"
            ],
            "drush/Commands/contrib/{$name}": [
                "type:drupal-drush"
            ]
        },
        "installer-types": [
            "bower-asset",
            "npm-asset"
        ],
        "patchLevel": {
            "drupal/core": "-p2"
        },
        "patches": {
            "drupal/core": {
                "Break long text strings in layout edit": "https://www.drupal.org/files/issues/2020-12-22/3016507-50.patch",
                "Improve StringItem::generateSampleValue()": "https://www.drupal.org/files/issues/2020-06-24/3091478-15.patch",
                "Not all form elements can't use in vertical_tabs": "https://www.drupal.org/files/issues/2021-01-02/3122920_group_patch_5.patch",
                "PHP message: Error: Call to a member function getEntityTypeId() on null (Layout Builder)": "https://www.drupal.org/files/issues/2020-08-05/3049332-inline-35.patch",
                "Stream wrapper reference in JS library causes error in _locale_parse_js_file()": "https://www.drupal.org/files/issues/2020-05-08/2735717-28.patch",
                "New non translatable field on translatable content throws error": "https://www.drupal.org/files/issues/2021-02-10/3025039_42.patch"
            },
            "drupal/section_library": {
                "#3228163: Add create or update logic.": "https://git.drupalcode.org/project/section_library/-/merge_requests/3.patch"
            }
        }
    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "scripts": {
        "acms:install": [
            "./vendor/bin/acms acms:install"
        ],
        "nuke": [
            "rm -rf docroot vendor composer.lock"
        ]
    }
}

Comment: You have tilde constraints and "minimum-stability": "dev".
Comment: I'm voting to close this question because it is a question about Composer usage, and not truly specific to Drupal. I understand if others disagree.
Comment: @cilefen Thanks mate, I totally understand your point but this is a grey area... as the installation and setup of the app requires knowledge of this component.
Answer:
Set "minimum-stability": "stable".
Remove drupal/core from composer.json requirements section. It is superfluous.
composer require drupal/core-recommended:^9.4 drupal/core-composer-scaffold:^9.4 -W.

Once you do that you have more work to do because of things that don't make sense, like drupal/insert 1.0.0 requires drupal/core ^8. If that is removed you have:
 Root composer.json requires drupal/gin ^3.0@beta -> satisfiable by drupal/gin[3.0.0-beta1, ..., 3.0.0-beta5].
    - drupal/gin[3.0.0-beta1, ..., 3.0.0-beta5] require drupal/gin_toolbar ^1.0@beta -> found drupal/gin_toolbar[dev-1.x, 1.0.0-alpha1, ..., 1.x-dev (alias of dev-1.x)] but it does not match your minimum-stability.

When that happens you have to specify dev versions of the dependencies explicitly.


How to assign and access the id of the td of the table in JQuery

Question: I'm inserting the row dynamically. How can I assign the id to each td so I can access it and update it after time. I'm sticking in it
                       $(document).ready(function(){
            var rowNumber = 0;
            var myData=new Array(6);
            myData[0]="txt1";
            myData[1]="txt2";
            myData[2]="txt3";
            myData[3]="txt4";
            myData[4]="txt5";
            myData[5]="txt6";
            $('#display').click(function(){
                //Get the user input
                for(i=0; i<6; i++)
                {
                if(document.getElementById(myData[i]).value !=0)
                {
                var nameInput = document.getElementById(myData[i]).name;

                var Quan = document.getElementById(myData[i]).value;
                //Create a new row with an ID
                var newRow = $('
').attr('id', 'row' + rowNumber);
                //Add some HTML to the row

                newRow.html('' + nameInput + '	' + Quan + '	');

                //Append the new row to the body of the #myTable table
                $('#myTable tbody').append(newRow);

                //Iterate row number
                rowNumber++;

                }
                }
            });
        });

I'm inserting the row dynamically. How can I assign the id to each td so I can access it and update it after time. I'm sticking in it.
Answer: YOU DON'T NEED IT
var td = $('#myTable tr:eq(2) td:eq(1)'); // 3 row 2 col

SEE DEMO
BUT IF YOU WANT
Write something like:
for(i = 0; i < 6; i++) {
  ...
  newRow.append('' + nameInput + '	');
  newRow.append('' + nameInput + '	');
  ...
}

Then to access:
$('#2_1').css('background', '#ccc'); // make grey background in 2 row 1 col

Answer: You don't really need to.  You can use jQuery's nth() selector.
For example:
$('td:nth(2)').html()

Demo here: http://jsfiddle.net/Uz4Ze/
Alternatively, I would suggest assigning each  a class, instead of an id. This will give you the added benefit of being able to style each column differently.


Is there a way to create a Webform automatically via script using Drush or another method?

Question: I'm automating a base Drupal 8 install using a bash script with Composer and Drush commands that installs Drupal and uses Drush and other methods to set my basic site configurations.
I'd like to also create some other basic settings like creating a standard Webform contact form, including its URL, etc.
Is this possible to do somehow via a script? Perhaps have a Webform config export stored somewhere and import it via the script? Note, this would be a new site so its UUID would differ each time.
Answer: You can create a new site from an existing configuration using drush site:install --existing-config.  Create the config through exporting from an existing site and copy it over to the new project.
See https://www.drupal.org/node/2897299 and https://www.drupal.org/project/drupal/issues/2980670
The docs are a bit outdated though, you now need to use $settings['config_sync_directory'] instead of $config_directories['sync'], see https://www.drupal.org/node/3018145
Answer: You can exactly do what you touched on with config: put a placeholder into the yaml for the URL and remove the uuid completely. As you import into a new site, that will generate a new one for you.
Comment: Ah, I was not aware you could import a config with a blank UUID. I'll try that out. Thanks!


Kmeans function - Amap package - what nstart stands for

Question: I don't understand what the nstart changes in the algorithm.
If centers = 8, that means the function will cluster 8 groups. But, what nstart variates?
This is the explanation on the documentation:
centers:
Either the number of clusters or a set of initial cluster centers. If the first, a random set of rows in x are chosen as the initial centers.

nstart:
If centers is a number, how many random sets should be chosen?

Comment: I guess the algorithm tries several random starts (instead of just one) by drawing "number of centers" rows from the data sets, checks the cluster sum of squares, and proceeds with the best start, resulting in a more stable output?
Comment: hmmm both... :-> You can check the examples section of `?kmeans`, too, and look at the source code by entering `kmeans` in the console.
Comment: This question mask is because you are supposing or it is because you want to comment more friendly? Haha
Answer: Unfortunately, the ?kmeans doesn't exactly explain this (in both stats and the amap packages). But, one can get an idea by looking at the kmeans code.
If one uses more than one random starts (nstart greater than 1) for the kmeans, then the algorithm returns the partition that corresponds to the smallest total within-cluster sum of squares.
(The output contain the total within-cluster sum of squares value as tot.withinss).
Answer: Look further below in the details:

The algorithm of Hartigan and Wong (1979) is used by default. Note that some authors use k-means to refer to a specific algorithm rather than the general method: most commonly the algorithm given by MacQueen (1967) but sometimes that given by Lloyd (1957) and Forgy (1965). The Hartigan–Wong algorithm generally does a better job than either of those, but trying several random starts (nstart> 1) is often recommended. In rare cases, when some of the points (rows of x) are extremely close, the algorithm may not converge in the "Quick-Transfer" stage, signalling a warning (and returning ifault = 4). Slight rounding of the data may be advisable in that case.

nstart stand for the number of random starts. I can not explain the statistical details but in their example code, the authors of this function choose 25 random starts:
## random starts do help here with too many clusters
## (and are often recommended anyway!):
(cl <- kmeans(x, 5, nstart = 25))

Comment: When you mean the number of random starts, is the number of randoms start centroids, right? Isn't this supposed to be the same as the number of centroids, thus, the number in centers?
Comment: The idea is to start clustering from e.g. 5 random centroids. These could be anywhere in the set so theoretically they are close together which is not ideal for a clustering attempt. As far as I understand nstart, the random choice of centroids is made e.g. 25 times in consecutive iterations if you set it that way. See e.g. [this](https://stats.stackexchange.com/questions/58238/how-random-are-the-results-of-the-kmeans-algorithm).


Fiber product an difference of schemes

Question: Let $j:W\to X$ be a closed immersion of a schemes and $f:Y\to X$ a morphism. The basechange of $j$ along $f$ defines a closed immersion $W\times_X Y\to Y$.
The inclusion $k:X\setminus W\to X$ and the inclusion $l:Y\setminus (W\times_X Y)\to Y$ are both open immersions.
Is the fiber product
$$
(X\setminus W)\times_X Y
$$
isomorphic to $Y\setminus(W\times_X Y)$ in the canonical way, i.e. is $l$ the basechange of $k$ along $f$?
Answer: Let $U=X\setminus W$. The natural morphism $f^{-1}(U)\rightarrow U\times_XY$ is an isomorphism. The closed immersion $W\times_XY\rightarrow Y$ induces a homeomorphism onto $f^{-1}(W)$. So, $W\times_XY$ can be identified canonically with a closed subscheme of $Y$ with underlying topological space $f^{-1}(W)$, and thus its complement is $f^{-1}(X\setminus W)=f^{-1}(U)$.
The key fact being used about the underlying topological space of the pullback of a closed subscheme came up in this question:
Ideal of the pullback of a closed subscheme
Comment: Dear @Ronald, $f^{-1}(W)$, as a scheme, is $W\times_YX$. One has to prove that the underlying topological spaces match up, because in general, the underlying topological space of a fiber product of schemes is not the fiber product in the category of topological spaces.
Comment: Ah, you are right. Perhaps you can add http://math.stackexchange.com/questions/257850/ideal-of-the-pullback-of-a-closed-subscheme to your answer.
Comment: Yes. In general, the fiber of the continuous map $|X \times_S Y| \to |X| \times_{|Y|} |Z|$  at $(x,y,s)$ identifies with $\mathrm{Spec}(\kappa(x) \otimes_{\kappa(s)} \kappa(y))$.
Comment: Dear @Keenan Kidwell, then the statement follows from $$f^{-1}(X\setminus W)\cong f^{-1}(X)\setminus f^{-1}(W)\cong Y\setminus f^{-1}(W)\cong Y\setminus (W\times_X Y)$$ I see, thank you.
Comment: So how do you prove that $f^{-1}(W)$ identifies with $W \times_X Y$? This is nontrivial, I think. And my gut feeling is that it may be false in the nonreduced case. Also remember the well-known special case that $W$ is the spectrum of a field, there you also have to do something ..
Comment: Dear @MartinBrandenburg, what do you mean? The fact that there are different scheme structures on the closed subset $f^{-1}(W)$ of $Y$ (but only one reduced one)?
Comment: No. "The closed immersion $W \times_X Y \to Y$ induces a homeomorphism onto $f^{-1}(W)$" needs a proof (if it is correct after all).
Comment: Hm, for topological spaces this is true. What is your definiton of $f^{-1}(W)$ as a scheme (if not $W\times_X Y$ by definition)?
Comment: Dear @Martin, I believe this follows from Proposition 4.20 in Goertz-Wedhorn. And I think that once you asked a question about this on MSE and I gave this reference...unless I'm not remembering correctly.
Comment: Dear @KeenanKidwell, ah, I see, this is a very clear formulation of the problem.
Comment: Dear @MartinBrandenburg, but the positive answer of the question has then very much to do with $j$ being a closed immersion. If for example $X$ is terminal and $j$ is the morphism into the terminal object, the scheme-theoretic pullback $W\times Y$ has as its underlying topological space not the product of the topological spaces of $W$ and $Y$, i.e. $|W\times Y|\not\cong |W|\times|Y|$, right?
Comment: Dear @MartinBrandenburg, thank you very much. Do you perhaps know if the statement of the question remains true when ''closed immersion'' is replaced by ''open immersion'' and the reduced closed subscheme structures on $X\setminus W$ and $Y\setminus (W\times_X Y)$ are taken respectively?
Comment: Dear @Ronald, I would guess that this is false just because the base change of a reduced scheme need no longer be reduced (e.g. over a field). So maybe you would want to take the reduced induced structure on $Y\times_X(X/W)$ and then ask the question. But I don't know the answer in this case.

Fiber product an difference of schemes


Trying to compare elements of string with loops and indices, but indices do not increment

Question: I am trying to make a Su Doku solver for Euler Project.  I am having trouble comparing string elements.   My 2nd loop with index k occurs only once, rather than nine times. if I remove the code with my if statement, it loops through just fine.  Anyone know why?  Something about trying to access my strings makes it stop...
puzzle is a vector and reference_stringis a string ="123456789".
for (int i = 0; i != 9; i++){
    cout << "loop 1" << endl;
    for (int k = 0; k != 9; k++) {

        if (reference_string[i] == puzzle[row_index][k] ||
            reference_string[k] == puzzle[col_index][k] ||
             reference_string[i] == puzzle[box_index][k] ){
            possible_answers.push_back(0);
        }

        else if ( k = 8 ){
            possible_answers.push_back(1);
        }
    }
}

Answer: You need to change k = 8 to k == 8, or safer 8 == k.  You are not performing a comparison, you are performing an assignment that alters the loop counter so the loop condition is satisfied after just one iteration.
Comment: Oh, great thanks! I missed that.  I just spotted one other error now for the second line in the conditional.  That should be an i.  I guess I am tired because i have been searching for the mistake for a while now.  But it works just as I want it now.  :)
Comment: Did your compiler try to warn you about the erroneous assignment?  Some compilers do warn about a *suspicious* assignment if you perform an assignment inside of an `if` statement (there are legitimate cases for doing that, which is why it is only a warning and not an error, but I don't like code that relies on that).


docker compose linking container network

Question: I have two containers, one for the database (DynamoDBLocal) and the other for the web app written in Nodejs.  I use Docker compose to setup the two containers and this is what my compose file looks like.
version: '2'
services:
  DynamoDBLocal:
    container_name: DynamoDBLocal
    build:
      context: ./DynamoDBLocal
    image: tag/drive-sync/dynamodb:latest
    ports:
      - "8000:8000"
  SetupService:
    build:
      context: ./setup
    image: tag/drive-sync/setup_service:latest
    ports:
      - "3000:3000"

My Nodejs app speaks to the DynamoDBLocal container.  As I understand both the containers get created under the same network as per the new Docker and when I try to access the DynamoDBLocal DB from the Nodejs App using the following url
http://DynamoDBLocal:8000  I get the following error
"message": "Inaccessible host: dynamodblocal'. This service may not be available in theus-west-2' region.",
Answer: From what I understand in the docs when they say that the  "supports the --link option to provide name alias for the linked container" I assume that you should be using the links option in your compose file to get name aliasing.
SetupService:
build:
  context: ./setup
image: tag/drive-sync/setup_service:latest
ports:
  - "3000:3000"
links:
  - "DynamoDBLocal:dynamodb.us-west-2.amazonaws.com"


I am searching for an example in C for using pkcs#5

Question: AFAIK, PKCS#5 is used for hashing passwords. I could not find an example to explain how to use openssl to make a client for hashing the passwords.
Answer: i have made a blogpost siting how to hash using openssl in C. Here is the link. Let me know, if this is the one you are looking for?


Material design light mdl-select

Question: I'm trying to use the mdl-select component in an Angular app.
<form [formGroup]="form">
  <mdl-select formControlName="personId">
    <mdl-option *ngFor="let p of people" [value]="p.id">{{p.name}}</mdl-option>
  </mdl-select>
</form>

I installed using the instructions from here: https://github.com/mseemann/angular2-mdl-ext/tree/master/src/components/select
Getting this console error:
Unhandled Promise rejection: Template parse errors:
Can't bind to 'value' since it isn't a known property of 'mdl-option'.
1. If 'mdl-option' is an Angular component and it has 'value' input, then verify that it is part of this module.
2. If 'mdl-option' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.
3. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. ("tiple="true" placeholder="Select users">
        <mdl-option mdl-ripple *ngFor="let hero of heroes" [ERROR ->][value]="hero.name">{{hero.name}}</mdl-option>
      </mdl-select>

"): ng:///AppModule/NewEventComponent.html@19:59

Comment: What do your imports look like? Whenever I've run into this it's been an import or bootstrapping issue
Comment: Just like the instructions from here. https://github.com/mseemann/angular2-mdl-ext/tree/master/src/components/select. I used the `import { MdlSelectModule } from '@angular-mdl/select';` in the component where I need the select.
Comment: can you try `import { MdlOptionComponent } from '@angular-mdl/option';` as well?
Comment: Cannot find module '@angular-mdl/option'. I even tried installing it but got this `npm ERR! 404 Not found : @angular-mdl/option`. Even if I comment the `mdl-option` from the html, I get `mdl-select' is not a known element:`
Comment: Ahh I just looked at their code base again .. try this:

`import { MdlSelectModule, MdlOptionComponent } from '@angular-mdl/select';`
Comment: Nope ... still doesn't like mdl-option `Can't bind to 'value' since it isn't a known property of 'mdl-option'.
1. If 'mdl-option' is an Angular component and it has 'value' input, then verify that it is part of this module.` ... but I think I'm using this wrong.
Comment: Ok I've got one more idea.. Can you actually import these in your app.module.ts, and then include the `MdlOptionComponent` in your `declarations` array, and the `MdlSelectModule` into your `imports` array? After that you'd want to remove the imports from your component that is using the Components
Comment: Uncaught Error: Type MdlOptionComponent is part of the declarations of 2 modules: MdlSelectModule and AppModule! Please consider moving MdlOptionComponent to a higher module that imports MdlSelectModule and AppModule. You can also create a new NgModule that exports and includes MdlOptionComponent then import that NgModule in MdlSelectModule and AppModule.
Comment: Ahh that makes sense! OptionComponent is already imported by the Select. If you remove the import and declaration of Option in `app.module.ts` and leave the `MdlSelectModule`, you might be in luck
Comment: Yeah. That was it. Still have an error, but that's because I copy pasted the example from GitHub. Add an answer please!
Answer: Your issue is that you aren't importing the module property, as it needs to be bootstrapped in your root app.module.ts.
Take the import { MdlSelectModule } from '@angular-mdl/option' out of your custom component, and move it to app.module.ts. Additionally, add MdlSelectModule to your imports: [] array in app.module.ts

Material design light mdl-select


Generate data with a given covariance matrix and given non-normal distribution

Question: Question
I have a dataset of numbers, which I know to be correlated with a covariance matrix that I can reasonably estimate. This correlation has no (known) structure connected to time, space, clusters, or siimlar. Moreover, the values are not normally distributed.
For a sanity check (surrogate, resampling, or whatever you wish to call it), I want to generate artificial datasets with the following properties:

The data is correlated as per the given covariance matrix.
The values have the same distribution as the original data.

It probably suffices if those properties are only approximately preserved. You might call this a parametric bootstrap of correlated data.
What I found so far

Resampling correlated data using bootstrap asks for the case of data with a known correlation structure. The books recommended in the answer only seem to address the case of correlations that originate from temporal or spacial sampling or from clusters.
There are procedures for generating normally distributed data with a known correlation matrix, as addressed, e.g., in: Generating data with a given sample covariance matrix.
My best ad-hoc approach so far would be: Generate normally distributed data adhering to the correlation matrix, and then rank-transform it to the target distribution, hoping that the correlation structure will not be affected too strongly.
Comment: I think this is along the lines of what I described here: https://stats.stackexchange.com/a/423189/247274. You specify the correlations in the copula; then you give the marginal distributions parameters to turn those correlations into the covariances you want.
Comment: Check out elliptical distributions. If you're happy to take one of those the problem is not too bad ( and that you talk about ranks suggests you would like an elliptical distribution...)
Comment: @user1587692: I am aware of those (or rather, it is not surprising to me that I can generate data from them), but how are they going to help me beyond what I elaborated in the last point? Can you elaborate in an answer?
Answer: The question is very broad, with little specific information. The general answer is to use a copula. Since you specifically want to control the covariance matrix, a gaussian copula would be indicated, or more generally, an elliptical copula. The answer bt @DavidF is a link to a walk-through of such a solution. But if such a copula is a good fit to the data is another question entirely.
After simulating data from the copula model, transform the margins one by one. If you want a better answer, tell us some more, like number of variables, and what is your ultimate goal?
Answer: I think what you need is explained here, and without the use of copulas: https://www.r-bloggers.com/easily-generate-correlated-variables-from-any-distribution-without-copulas/
In the words of the author of the linked article (Francis Smart), the proposed method is:

Draw any number of variables from a joint normal distribution.
Apply the univariate normal CDF of variables to derive probabilities for each variable.
Finally, apply the inverse CDF of any distribution to simulate draws from that distribution.

The result is that the final variables are correlated in a similar
  manner to that of the original variables. This is because the rank
  order of the variables is maintained and thus correlations are
  approximately the same though not exact.

Hope it helps.
Comment: Welcome to Stats.SE. Can you please edit you answer to expand it, in order to include the main points of the link you provide? It will be more helpful both for people searching in this site and in case the link breaks. By the way, take the opportunity to take the [Tour], if you haven't done it already. See also some tips on [ask], on [formatting help](https://stats.stackexchange.com/help/formatting) and on writing down equations using [LaTeX / MathJax](https://math.meta.stackexchange.com/q/5020).


Node Call Export on Callback

Question: I'm banging my head for not learning from the basics and just jumping in.
I'm building an API that returns the SSL Certificate status of a domain.
It's working fine on console.log but the JSON output is empty, obviously because the exports get executed before the https request ends.
How do I incorporate the exports in response.on(end) function?
Thanks a lot!

function getSSL(domain) {

    var options = {
        host: 'www.'+domain+'.com',
        method: 'get',
        path: '/'
    };

    var isAuth = false;

    callback = function(response) {

        response.on('data', function () {
            isAuth = response.socket.authorized;
        });

        response.on('end', function () {
            console.log(isAuth);
        });

    }

  var req = https.request(options, callback).end();
}

exports.findByDomain = function (req, response) {
    var id = req.params.id;
    sslCheck = getSSL(id);
    response.send(sslCheck);
};
Comment: `getSSL` needs a callback as the second param to return the data. It'll look like: `getSSL(id, function(data) { response.send(data) });`
Comment: [Related/dupe](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call), whereby `isAuth` is the thing you want to be passing to an ultimate callback function, probably defined within your `findByDomain` function.
Answer: Yes, the response.send(sslCheck); gets executed before getSSL(id); has a chance to finish. You need to send in a callback so it can be executed after getSSL(id); finishes:
function getSSL(domain, callback) {

    var options = {
        host: 'www.'+domain+'.com',
        method: 'get',
        path: '/'
    };

    var isAuth = false;

    var httpCallback = function(response) {

        response.on('data', function () {
            isAuth = response.socket.authorized;
        });

        response.on('end', function () {
            console.log(isAuth);
            callback(isAuth);
        });

    }

  var req = https.request(options, httpCallback).end();
}

exports.findByDomain = function (req, response) {
    var id = req.params.id;
    getSSL(id, function(sslCheck) {
        response.send(sslCheck);
    });
};

Comment: Thanks a lot, worked fine!
Now I just need to investigate a better way of retrieving SSL information without the overhead of the whole firstpage html.

Node Call Export on Callback


How to restrict device join in Azure AD

Question: We are a team of remote workers trying to restrict access to 'corporate resources' to specific devices, which are virtual Desktop-as-a-Service machines hosted by a third party. Corporate resources are Office 365 applications, OneDrive and, eventually, services hosted on Azure. The right solution seems to be Azure AD Join. But I can't see how to limit Join to those VMs that are our 'corporate' workstations.
Answer: Azure AD join needs users input your credentials of Azure AD Account. If you want to limit Azure AD join devices, you can limit users who can join their devices to AzureAD:
Go to Azure Portal > Azure Acitve Directory > Devices > Add memebers who can join devices to Azure AD.

How to restrict device join in Azure AD


Material Date Picker text color

Question: I am trying to change the text color of my DatePicker
 <DatePicker
            android:id="@+id/start_date_text"
            android:layout_width="400dp"
            android:layout_height="190dp"
            android:datePickerMode="spinner"
            android:calendarViewShown="false"
            style="@style/MyDatePicker" />

This code just gives 3 pickers, month, day and year. How can I change this text color?

where Widget.Material.Light.DatePicker has been all the DatePicker options under Widget
Comment: For a DatePickerDialog check my answer on **Change DatePicker header text color** http://stackoverflow.com/a/42460022/5188159
Answer: As with most components, the DatePicker's text color is effected by textColorPrimary:
<item name="android:textColorPrimary">@color/Black</item>

Comment: This doesn't change the color of the text.
Comment: It only works if it is in your main app theme. It's somewhat difficult to change the font color directly because it is buried under several layout and ultimately the `EditText` itself will be styled as `?android:attr/textAppearanceMedium` which essentially only will refer to the `textColorPrimary` in your main theme. This question might help: http://stackoverflow.com/questions/22962075/change-the-text-color-of-numberpicker. If you want to change it for a `DatePicker`, it would require another outer loop to go though the `DatePicker`'s children to find the `NumberPicker`s.
Comment: Thanks, that is a very involved process to change something so simple. My app can get by with just using a consistent color throughout though.
Comment: adding this to the base app theme did the trick, Thanks!
one note : this does only change numbers color, but not days letters in the top
to change days letters as well you should override android:textColorSecondary.
Happy coding !
Answer: An updated version would be to use editTextColor instead of using textColorPrimary and time pickers as suggested by tachyonflux date.
try:

Answer: I don't know what your style have but you can do it this way:

Comment: I have tried that already and it doesn't work. I tried all the DatePickers under widget and no changes were seen with textColor
Comment: @JordanCarlyon Could you show us MyDatePicker style in your post ?
Comment: It's the name as yours but I did add it.

Material Date Picker text color


How to toggle browser_spellcheck dynamically in tinymce

Question: I've a custom toolbar button, which is used to toggle the browser's spell check. I've used
browser_spellcheck : true

in the initialization. Now if we press button, then i need to 'off' the spell check.
So, how can we set browser_spellcheck to false dynamically?
Answer: You cannot change the init settings of TinyMCE dynamically - it simply does not allow that to happen.  If you need to change a setting like this you would need to use the remove() and init() APIs to reload the editor with new settings.
Comment: thanks for your reply. But, i'm looking for the way other than reinitialize.


SFTP, ChrootDirectory and multiple users

Question: I need a setup where I can put the contents of several user folders to a DMZ server from where external clients can download it, protocol SFTP, Linux, OpenSSH. To ease administration we want to use one single user for the upload.
What does work is to define ChrootDirectory /home/sftp/ in sshd_config, set the according ownership and modes and define a home dir in passwd so that the working directory of the user fits. This is my structure:
/home/sftp/uploader/user1/file1.txt
                   /user2/file2.txt

The uploader user can write file1.txt and file2.txt to the corresponding folders and by having the user folders (user1, user2) set to the users' primary group + setting SETGUID on the folders the users are able to even delete the files (which is necessary).
Only problem: because /home/sftp/ is the chroot base dir the users can change updir and see other users' folders, though not being able to change into because of access rights.
Requirement: We want to prevent users to change to /home/sftp/uploader/ and see other users' folders. My requirements are to use SFTP, have one upload user and every user must have write access to his home dir.
Obviously it's not an option to use something like ChrootDirectory %h because every path component of the chroot path needs to have limited access rights, so as far as I understand this does not work.
Answer: I solved this by introducing another directory level:

/srv/sftp/user1/data/file1.txt
          ^^^^^ ^^^^
            |     +- user homedir
            +------- chroot target

OpenSSH is now configured to chroot to the directory "user1" preventing the user from breaking out of his own directory. The user homedir is set to "/data" so that the working directory of the user is this one right after the SFTP login.
"user1" has limited access rights as required by OpenSSH, the user has no write access to this directory.
"data" on the other hand belongs to the user and has his primary group along with SETGUID, so that the user can write in this directory and files that are written by the upload user belong to the correct group.
Answer: As I understand I should use
Match user for every user separately in sshd_config
Match user user1
ChrootDirectory /srv/sftp/user1
Match user user2
ChrootDirectory /srv/sftp/user2
AllowTCPForwarding no
X11Forwarding no
ForceCommand internal-sftp


Find pages from orders of a specific user

Question: I have the following associations:
User has_many Order
Order has_many Pages

How can I find all the pages that belongs to a specific User? Is not a directly association, but the table Order is between them. So, I can't do:
user.pages

I just can do user.orders
Comment: Hommer, did my answer help at all?
Answer: What you want is probably a different association. Try the has_many :through association.
User.rb
has_many :orders
has_many :pages, through: :orders

Order.rb
belongs_to :user
belongs_to :page

Page.rb
has_many :orders
has_many :users, through: :orders

Take a look at the Rails documentation for more information: http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association
If you don't really need more metadata on the joining model (in this case, Order.rb), you can simply also use a HABTM association.

Generate a table called users_pages

and then:
User.rb
has_and_belongs_to_many :pages

Pages.rb
has_and_belongs_to_many :users

For more information on this association read: http://guides.rubyonrails.org/association_basics.html#the-has-and-belongs-to-many-association
For more information on when to choose either, read: http://guides.rubyonrails.org/association_basics.html#choosing-between-has-many-through-and-has-and-belongs-to-many


Categorise hour into four different slots of 15 mins

Question: I am working on a dataframe and I want to group the data for an hour into 4 different slots of 15 mins,
0-15 - 1st slot
15-30 - 2nd slot
30-45 - 3rd slot
45-00(or 60) - 4th slot
I am not even able to think, how to go forward with this

I tried extracting hours, minutes and seconds from the time, but what to do now?
Answer: Use integer division by 15 and then add 1:
df = pd.DataFrame({'M': range(60)})

df['slot'] = df['M'] // 15 + 1

print (df)
     M  slot
0    0     1
1    1     1
2    2     1
3    3     1
4    4     1
5    5     1
6    6     1
7    7     1
8    8     1
9    9     1
10  10     1
11  11     1
12  12     1
13  13     1
14  14     1
15  15     2
16  16     2
17  17     2
18  18     2
19  19     2
20  20     2
21  21     2
22  22     2
23  23     2
24  24     2
25  25     2
26  26     2
27  27     2
28  28     2
29  29     2
30  30     3
31  31     3
32  32     3
33  33     3
34  34     3
35  35     3
36  36     3
37  37     3
38  38     3
39  39     3
40  40     3
41  41     3
42  42     3
43  43     3
44  44     3
45  45     4
46  46     4
47  47     4
48  48     4
49  49     4
50  50     4
51  51     4
52  52     4
53  53     4
54  54     4
55  55     4
56  56     4
57  57     4
58  58     4
59  59     4


É possível usar PHP num campo data-title?

Question: É possível usar PHP dentro de um campo data-title?
Eu tenho o seguinte código:

      <?
      $result = $connection -> query("SELECT * FROM portfolio") or die($connection -> error);
      while($row = $result -> fetch_array(MYSQLI_ASSOC)){
      ?>
          <div class="col-md-3 col-sm-4 col-xs-12 m-col-md-3 picture-item"
               data-groups='["<?=$row['portfolio_tipo']?>"]'
               data-date-created="<?=$row['portfolio_data']?>"
               data-title="<?=$row['portfolio_titulo']?>">

O problema é que todos os campo data-... não funciona com php lá dentro. Nenhum dos atributos funciona.
Este código em html estava a funcionar perfeitamente, depois de colocar com php deixou de funcionar.
Comment: Não funcionam em que sentido? Não mostram os valores? Pois a situação que você propôs não vejo nenhum problema em ser executada. Certifique-se de utilizar php > 5.4, pois o <?= (simplificação do echo) , acredito que é só dessa versão para cima, caso eu não esteja enganado.
Comment: @MárcioAndré  Você está com a configuração `short_open_tag` ativada para poder usar `<?=` ?
Comment: Complementando a informação sobre a short tag: http://programmers.stackexchange.com/questions/151661/is-it-bad-practice-to-use-tag-in-php
Comment: basta adicionar um `echo` antes da variável que "segura" o valor que você deseja imprimir
Comment: Testei localmente aqui e no Ideone com um array qualquer https://ideone.com/nINakE ... funcionou corretamente. Tem certeza que os dados não estão vazios?
Comment: Sim tenho a certeza que não estão vazias, estou a usar as mesmas variáveis noutro sitio e funciona, só esses atributos não estão a funcionar
Comment: sim uso sempre assim
Answer: O php funciona em qualquer parte do arquivo. Como você relatou o problema citando apenas o atributo data-title acredito que os outros atributos (data-date-created, ...) estejam funcionando. Se for isso mesmo, acredito que a sua variável $row['portfolio_titulo'] esteja vazia ou não exista.

Edit: você pode ter alguns problemas com aspas. Por exemplo, se tentar colocar uma string Meu título com "aspas" no atributo data-title ficaria assim:
data-title="Meu título com "aspas""

Para contornar este problema, você pode utilizar a função htmlspecialchars ou htmlentities:
data-title="<?= htmlentities($row['portfolio_titulo']) ?>"

Comment: O problema está em todos os atributos.
Comment: Execute um `var_dump` na variável `$row` em algum lugar da página em que você possa ver o resultado e verificar se a variável está correta e contém mesmo os valores que você está tentando utilizar. `var_dump($row);`
Comment: Sim as variáveis têm conteúdo, estou a usa-las noutros sítios e elas funcionam.
Comment: Mesmo que funcione em outro lugar, é interessante procurar o erro em qualquer lugar possível no script **atual**. Quando você menos espera, algo pequeno ao qual você não dá valor pode representar o problema que você está procurando.
Comment: Concordo plenamente @Oesli, mas não é de variáveis vazias, inspeccionei elemento e elas encontram-se cheias
Answer: 1 - Verifique se seu documento é .php
2 - Você não precisa por colchetes data-groups='["<?=$row['portfolio_tipo']?>"]'
...

    <?php
          $portfolio_tipo = $row['portfolio_tipo'];
          $portfolio_data = $row['portfolio_data'];
          $portfolio_titulo = $row['portfolio_titulo'];

    ?>

          <div class="col-md-3 col-sm-4 col-xs-12 m-col-md-3 picture-item"
                   data-groups="<?=$portfolio_tipo?>"
                   data-date-created="<?=$portfolio_data?>"
                   data-title="<?=$portfolio_titulo?>">

...

3 - Faça um teste antes de selecionar os valores com a query:
...

    <?php
          $portfolio_tipo = 'teste tipo';
          $portfolio_data = 'teste data';
          $portfolio_titulo = 'teste titulo';

    ?>

          <div class="col-md-3 col-sm-4 col-xs-12 m-col-md-3 picture-item"
                   data-groups="<?=$portfolio_tipo?>"
                   data-date-created="<?=$portfolio_data?>"
                   data-title="<?=$portfolio_titulo?>">

...

Comment: já testei, não funcionou
Comment: Que diferença faz esse código daquele que eu tenho?
Comment: Retire os colchetes.
Comment: E faça com essa organização.
Comment: Agora faça assim: $portfolio_tipo = "valore teste"; E TESTE! SE VIER ALGO, SEU SELECT NÃO PRESTA!
Comment: não funciona a mesma, só deixou de funcionar depois de eu colocar o php, quando estava só em html funcionava 100%
Comment: Meu caro, era pra está funcionando. Tem certeza que o seu documento é `.php` ??
Comment: Sim tenho a certeza que é um ficheiro `.php`. Obviamente era para estar a funcionar e por não estar a solucionar o problema vim aqui para tentar procurar ajuda.
Comment: "Since PHP 5.4.0, <?= is always available." O seu php é superior a 5.4?
Comment: Sim, não tenho problemas em usar isso. @Lollipop assim como você disse funciona, mas quando uso com query deixa de funcionar
Comment: A questão é.... SEU SELECT traz algum resultado?
Se sua consulta não trouxer nada, não vai aparecer nada ali, logicamente
Answer: Sim, é possível! Inclusive creio que essa foi a intenção inicial ao se criar esses atributos no HTML5. Criar um ambiente mais agradável ao usuário sem ter que se fazer diversas consultas ao banco... na primeira consulta já popular todos dados necessários do servidor nos campos data e deixar o resto em cargo do browser do usuário utilizando o front-end e tirando a responsabilidade do servidor de criar toda a dinâmica da página.
Tente fazer isso:
Fiz um teste aqui e funcionou normalmente os atributos data

  <?
$result = $connection -> query("SELECT * FROM portfolio") or die($connection -> error);
while($row = $result -> fetch_array(MYSQLI_ASSOC)){

    echo  '
'; ?>

Se mesmo assim continua não funcionando, verifique se sua consulta no banco traz algum resultado....
Comment: `<?=` já é um `echo`. Usar os dois em conjunto gerará um erro.
Comment: @AndréRibeiro fiz um teste aqui e funcionou normalmente, editei a resposta pra ficar mais dinâmico...
Answer: No PHP, quando não se dá um ECHO nas variáveis, ele não imprime o valor da mesma na página transformando ela em HTML. seu erro está nisso. tente colocar o ECHO que resolve.
Comment: `<?=` já é um `echo`.
Comment: não conheço ``.
Comment: @LeandroLUK http://php.net/manual/en/function.echo.php
Comment: no mesmo link que você me mandou @RafaelWithoeft tem a informação `Note: Because this is a language construct and not a function, it cannot be called using variable functions` creio que seja por isso que não esteja funcionando, portanto é melhor fazer com o echo mesmo.
Comment: @LeandroLUK Só quis demonstrar o uso da short tag, no caso `` funcionaria do mesmo jeito que ``, espero que não tenha interpretado errado o meu comentário, não quis julgar o certo ou errado, só demonstrar os dois lados... o conceito de `variable functions`, pode ser visto aqui: http://php.net/manual/en/functions.variable-functions.php


Como repetir HTTP requests várias vezes e simultaneamnte, sem delay?

Question: Preciso de uma maneira de enviar http request's várias vezes, sem alteração de nenhuma requisição.
Atualmente eu tenho utilizado Charles Proxy - pego a request de um app do iphone e assim posso repetí-la em meu computador. Charles Proxy repete quantas vezes for necessário, porém com certo delay entre as requests. Observei que o servidor não aceita a mesma request se for mandada após 200ms. Por isso, necessitava de um programa ou outro meio que pudesse enviar 30 requests, por exemplo, todas ao mesmo tempo, sem delay. Há alguma maneira de se realizar isso?
Não tenho controle sobre o servidor, que não é meu. Apenas pego requests prontas do iphone e repito no windows.
Comment: Que tipo de requisição? REST, HTTP simples? Existem várias ferramentas em várias linguagens que permitem você fazer isso. Não precisaria criar um programa específico, basta configurar a ferramenta com a quantidade de threads, a quantidade de requisições por threads ou o tempo de duração do teste.
Comment: http/1.1 POST. estou com a request aberta agora mesmo aqui.
Comment: Veja por exemplo [este exemplo](http://www.soapui.org/Getting-Started/load-testing.html) de como fazer teste de carga com a ferramenta SoapUI (que faz SOAP e RESP).
Comment: Outra ferramenta interessante para testes de carga é o [Proxy Sniffer](http://www.proxy-sniffer.com/). Com ele você pode gravar o teste e ele gera o código (em Java) para você adaptar da forma que quiser, além de ter um sistema para você faz a execução dos testes gravados de acordo com os parâmetros solicitados. Enfim, é isso que você procura?
Comment: vou utilizar o proxy sniffer. Mas queria um programa que simplesmente pudesse repetir POST https de um servidor ao mesmo tempo.
Answer: O Apache JMeter é capaz de realizar o teste de carga que você precisa. É free e open source.
Apenas lembre-se que enviar muitas requisições para um servidor pode derrubá-lo ou deixá-lo muito lento, podendo gerar algo que será considerado como um Ataque de Negação de Serviço, Denial of Service (DoS) em inglês. Isso é especialmente grave quando o servidor não é seu.


Grails won't retrieve single item from list using get(params.id)

Question: I have a table where you input information which is then displayed, when you click the name of it I want it to go to a new page where it only displays the item clicked and not everything.
Here is my controller...
class RecipeController {

def index() {
    def recipe = Recipes.list() //Recipes is the Grails Domain
    [recipe: recipe]
}

def newRecipeForm() {

}

def createRecipe()  {
    def r = new Recipes(name: params.name, course: params.course, diet: params.diet)
    r.save()
    redirect(action:"index")
}

def deleteRecipe()  {
    def r = Recipes.get(params.ID)
    r.delete()
    redirect(action:"index")
}

def showRecipe() {
   def rec = Recipes.get(params.ID)
    [recipe: rec]
}

}
My index.gsp where the recipe name is clickable which should redirect by ID to a new page where it just displays only that recipe info.
   <g:each var="Recipes" in="${recipe}">

            <g:link action="showRecipe" id="${Recipes.id}">${Recipes.name}</g:link>

   </g:each>

and finally my showRecipe.gsp where the recipe should be displayed by itself...but it keeps displaying all of them that i add
<g:each var="rec" in="${recipe}">

        ${rec.name}

</g:each>

any guidance would be awesome! thanks
Comment: why you are using   if you want only first value.
Comment: why you have params.ID? should be params.id. Also in createRecipe you can change to new Recipes(params).
Comment: first i would use  `` as the outter element, second, could you explain what is the core question on your part...
Comment: Please add println(params) in your show() action and tell me what you see.
Answer: I could say that your first error is in your index.
It is likely that the Recipe.id that you have is retrieving all the id´s and sending them in the link.  You should not use UpperCase in a property name, the compiler might think of the property as a Class. The code should be more like:

            <g:link action="showRecipe" id="${recipes.id}">${recipes.name}</g:link>

</g:each>

Add a println(params) or log.info(params) in your show() action to print all your params and see exactly what you are receiving from your view.
Also be careful with your naming conventions. You might want to change recipe for recipeList or something, and recipes to recipeInstance or simply recipe. It will make the code more readable, and make it easier for us to help you.
EDIT
As @Nitin Dhomse said you only need to access the data of a single recipe so you don´t need to do
<g:each var="rec" in="${recipe}">

in your show.gsp.
It would be more like

    ${recipe?.id}
    ${recipe?.name}
     ....

Also, you should either redirect in your show() action if you dont find the recipe Instance or access your properties like $(recipe?.name) in your show.gsp, otherwise you will get nullPointer Exceptions.


Proving $S_3$ is not a coproduct of cyclic groups

Question: Aluffi II.6.11 suggests proving the above.
Here's the sketch of my proof by contradiction.
Assume that $S_3$ is a coproduct of a family $\mathcal{C}$ of cyclic groups $C^i$. Using the universal property for coproducts (and considering morphisms $\sigma_i : S_3 \rightarrow C^i$ such that $\sigma_i \iota_i = 1$, where $\iota_i$ is the injection function) shows that each $C^i$ cannot be larger (as a set) than $S_3$.
Next, since $S_3$ has three elements of order 2 and two elements of order 3, it can be shown that any cyclic group that maps its generator onto one of those elements shall have order 2 or 3 respectively.
So we're down to a corpoduct of a certain number of $C_2$ and $C_3$.
Now, by considering both elements of order 3 in $S_3$, it can be shown that having two $C_3 \in \mathcal{C}$ with different injection functions leads to contradiction, so we have at most one $C_3$. We also have to have at least one $C_2$ mapping onto some element of order 2, otherwise there's a certain freedom in defining the behavior of some morphisms from $S_3$. Similarly, we also have to have at least one $C_3$.
Now, considering the group $C_2 \times C_3$ along with a pair of morphisms $\varphi_2 : C_2 \rightarrow C_2 \times C_3, \varphi_2([n]_2) = ([n]_2, [0]_3)$ and $\varphi_3 : C_3 \rightarrow C_2 \times C_3, \varphi_3([n]_3) = ([0]_2, [n]_3)$ it can be shown that there is no valid homomorphism $\sigma : S_3 \rightarrow C_2 \times C_3$ satisfying the corresponding universal property for coproducts, hence the contradiction with the original assumption.

Overall, this looks quite clunky. Does it look reasonable though? Is there a better way to prove the claim (perhaps limited to the little amount of algebra and category theory that might be expected by this point)?
Comment: I recommend against using the term "proof by contradiction". You are proving a negative statement, i.e. "it is not the case that $S_3$ is a coproduct of cyclic groups". To prove a negative statement, you assume it and show that this leads to a contradiction. Proof by contradiction proves a *positive* statement by assuming its *negation* and showing that the negation leads to a contradiction. https://ncatlab.org/nlab/show/proof+by+contradiction briefly describes the difference, and I highly recommend Bauer's post referenced there.
Comment: "Proof by contradiction" is probably misused more often than it's used correctly, and this leads to its meaning being ambiguous. "Indirect proof" would be much less ambiguous when you are actually using proof by contradiction which you aren't in this case. You could say that you are doing a "proof of a negation", but you can probably just omit mention of proof by contradiction.
Comment: Isn't the free product (which is the coproduct of groups) of (nontrivial) cyclic groups infinite? If $C_1$ and $C_2$ are generated by $a$ and $b$, respectively, then can't I just make words like $ababababa$?
Answer: Here is a maybe simpler proof, but which involves more concepts that may be unknown.
$\newcommand{\Z}{\mathbb{Z}}$Suppose that a group $G$ is the coproduct of cyclic groups:
$$G = \Z/n_1\Z * \dots * \Z/n_k\Z.$$
Then the abelianization of $G$, i.e. its quotient by its commutator subgroup, is isomorphic to the direct sum $G_{\mathrm{ab}} \cong \Z/n_1\Z \oplus \dots \oplus \Z/n_k\Z$. So if we know the abelianization, we know what cyclic groups must be involved.
Now it's well-known that the commutator subgroup of $S_3$ is the alternating group $A_3$, and the quotient $(S_3)_{\mathrm{ab}}$ is the cyclic group $\Z/2\Z$. Therefore, if $S_3$ were a coproduct of cyclic groups, then it would be isomorphic to $\Z/2\Z$. This is obviously false because $S_3$ has $6$ elements whereas $\Z/2\Z$ only has two. Therefore $S_3$ cannot be isomorphic to a coproduct of cyclic groups.
Answer: The problem states

"Since direct sums are coproducts in Ab, the classification theorem for abelian groups mentioned in the text says that every finitely generated abelian group is a coproduct of cyclic groups in Ab. The reader may be tempted to conjecture that every finitely generated group is a coproduct in Grp. Show this is not the case, by showing that $S_3$ is not a coproduct of cyclic groups."

I think that your approach is a reasonable way of going about it given what information you have available. Certainly if $C_n$ is a factor of the coproduct then $n\in\{2,3\}$ as you mentioned, since these are the only nontrivial orders of elements in $S_3$.
I think the simplest way to move forward from here is to note that there should be a map $f:S_3\to C_3$ such that
$$C_3 \xrightarrow{i} S_3 \xrightarrow{f} C_3$$
is the identity map, if we assume that $S_3$ is a coproduct with a $i:C_3\to S_3$ factor. You can then reach a contradiction by showing that no such $f$ exists.
Comment: I don't think we have the machinery yet to show that a coproduct of groups in $\mathbf{Grp}$ is abelian (and it's not really that obvious to me, given that we don't know what a coproduct in $\mathbf{Grp}$ is at all).
Comment: @0xd34df00d Yeah, I agree. I edited my answer to reflect further thoughts I have. This question would be much easier (though perhaps not giving much practice with coproducts) if you knew that coproducts in **Grp** are free products (and are thus infinite nonabelian groups).
Answer: I have a much simpler way of contemplating this, but as a beginner, it might be flawed, so please let me know if it's not reasonable:
By the universal property of coproduct, there is a unique homomorphism from the direct sum of cyclic groups to S3. Now if we prove that the homomorphism has a inverse (i.e. that the homomorphism is actually a isomorphism), we are done.
To establish isomorphism, we need same number of elements (6), which constrains that C2*C3 the only possibility, because 2*3=6. Then, comparing the order of the 6 elements in both groups, we found out they are not isomorphic to each other.
This seems too simple a solution, so I doubt my thoughts here. Much appreciated for any comments.
Edit:
This not the correct way to think, thanks to the comment.
Comment: @Yunhan, correct. It is a common mistake, though. You have two abelian groups $A$ and $B$ and you automatically think of their direct sum. The problem is that even though for any *abelian* group $C$, any pair of morphisms from the summands to $C$ factors through the direct sum. However, if $C$ is not abelian, then it is no longer true. The reason is that the direct sum contains relations that nonabelian $C$ won't permit in general, so you can't induce the morphism you want.
Comment: The direct sum is not the coproduct in the category of all groups.  It does not have the universal property you think it has. The coproduct in the category of groups is the free product.
Comment: Thanks, I see. Direct sum is the coproduct in the category of abelian groups though right?


Is it possible to train neural network to generate similar pictogram?

Question: Is it possible to give the neural network and pictogram and train him to generate variant of this picto?
I know there is some initiative to generate vectors drawings like https://github.com/tensorflow/magenta/blob/master/magenta/models/sketch_rnn/README.md or some logos generated by AI but it's not really qualitative…
Any idea/tips?
Answer: Most classes of generative models of images (with the notable exception of autoregressive models) have a "latent" space.
Typically, a property of a well trained and sufficiently powerful generative model is that traversing the latent space also smoothly traverses the image space in a coherent manner, yielding variants of the starting image.
So in short: train a generative model, then take nearby points in your latent space to obtain "variants"


How to "inherit" bindable properties in Aurelia?

Question: I am developing an Aurelia application using TypeScript. In this application I defined a set of custom elements each sharing a set of bindable properties that get translated to css settings as shown in the following simplified example:
import {computedFrom, bindable, autoinject} from 'aurelia-framework';

@autoinject
export class MyCustomElement {
    @bindable span: number;

    @computedFrom('span')
    get width() {
        return this.span? this.span* 26 : 0;
    }

    // Leaving out a whole bunch of other code for sake of readability
}

The HTML code for this element looks somehow like this:
<template>

        <svg xmlns="http://www.w3.org/2000/svg" css="width: ${width}px;">
        </svg>

</template>

So I need the value of the computed property several times throughout the HTML template of the custom element.
Now other elements also need the span and the width property. As I understood from reading github: Aurelia Issue #210 inheritance of bindable properties is not yet supported. As Rob Eisenberg stated the way to go would be using composition here.
But when using that I still would need to implement both the span and the width property but also import a component via dependency injection that just adds the functionality of actually calculating the left margin. So all in all this approach still results in a lot of copy and paste code.
Is there a better way to address this?
I was thinking about using custom attributes for this after a hint from @AureliaEffect on twitter, but that still won't prevent me from implementing each of the required properties on the element to be able to bind to it in the template of the element.
A short explanation on the business case behind this (a.k.a. "Why did I chose this approach"): Users of my application are able to build a track layout as you find it in electronic railway interlocking systems. This requires to specify the width of elements or their offset in some generic units, not in pixels. Also this properties need to be specified per element and not per element class.
(There is another question here a StackOverflow addressing a somewhat similar topic, but with an approach not working in my scenario: Using the @bindable attribute on child class in Aurelia)
Comment: Though this feature will be added in one of the upcoming releases of Aurelia, there is another way to save doubling the logic: By adding the bindable properties by means of a decorator. I have explained that over here: https://stackoverflow.com/a/45361429/1521227
Answer: Maybe you see it since that question, but there's an active discussion going on right now about this on github with eventually a PR coming in soon. You can follow the discussion right here :
https://github.com/aurelia/templating/pull/507#issuecomment-297163265
Comment: I will write an answer to this question once the issue has been solved.
Comment: Thanks for notifying me - though I am also the "Spontifixus" discussing in that thread ;)
Comment: Ah! That's funny, I didn't pay attention to the names of peoples participating in the discussion, ahaha. At least other people will now have a link directly to this :)


Erro ao utilizar o AutoMapper " Class Not Found"

Question: Estou estudando a utilização do AutoMapper, porém recebo um erro em meu projeto.

Versão do AutoMapper: v3.3.1

Adicionei o Config em meu Global.asax, ficando assim:
 protected void Application_Start()
        {
            AutoMapperConfig.RegisterMappings();
        }

O meu AutoMapperConfig está desta forma:
public class AutoMapperConfig
    {
        public static void RegisterMappings()
        {
            Mapper.Initialize(cfg =>
            {
                cfg.AddProfile<DomainToViewModelMappingProfile>();
                cfg.AddProfile<ViewModelToDomainMappingProfile>();
            });
        }
    }

Minha classe DomainToViewModelMappingProfile está desta forma:
public class DomainToViewModelMappingProfile : Profile
    {
        public override string ProfileName
        {
            get { return "DomainToViewModelMappings"; }
        }

        protected override void Configure()
        {
            Mapper.CreateMap<Pessoa, PessoaViewModel>();
            Mapper.CreateMap<Endereco, EnderecoViewModel>();
            Mapper.CreateMap<Pessoa, PessoaEnderecoViewModel>();
            Mapper.CreateMap<Endereco, PessoaEnderecoViewModel>();
        }
    }

e a ViewModelToDomainMappingProfile está assim:
public class ViewModelToDomainMappingProfile : Profile
    {
        public override string ProfileName
        {
            get { return "ViewModelToDomainMappings"; }
        }

        protected override void Configure()
        {
            Mapper.CreateMap<PessoaViewModel, Pessoa>();
            Mapper.CreateMap<EnderecoViewModel, Endereco>();
            Mapper.CreateMap<PessoaEnderecoViewModel, Pessoa>();
            Mapper.CreateMap<PessoaEnderecoViewModel, Endereco>();
        }
    }

Ao "mapear" a classe em meu AppService assim:
 public void Adicionar(PessoaEnderecoViewModel pessoaEnderecoViewModel)
    {

        var pessoa = Mapper.Map<PessoaEnderecoViewModel, Pessoa>(pessoaEnderecoViewModel);
        var endereco = Mapper.Map<PessoaEnderecoViewModel, Endereco>(pessoaEnderecoViewModel);

        pessoa.Enderecos.Add(endereco);
        _pessoaRepository.Add(pessoa);
    }

Ao debugar, quando chego nesta parte  var pessoa = Mapper.Map(pessoaEnderecoViewModel); recebo o seguinte erro:

Mapper.cs not found

Locating source for 'c:\dev\AutoMapper\src\AutoMapper\Mapper.cs'. Checksum: MD5 {28 13 88 2d fa c bf 90 0 c9 9c 25 64 11 3d 36}
The file 'c:\dev\AutoMapper\src\AutoMapper\Mapper.cs' does not exist.
Looking in script documents for 'c:\dev\AutoMapper\src\AutoMapper\Mapper.cs'...
Looking in the projects for 'c:\dev\AutoMapper\src\AutoMapper\Mapper.cs'.
The file was not found in a project.
Looking in directory 'C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\crt\src\'...
Looking in directory 'C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\crt\src\vccorlib\'...
Looking in directory 'C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\atlmfc\src\mfc\'...
Looking in directory 'C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\atlmfc\src\atl\'...
Looking in directory 'C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\atlmfc\include'...
The debug source files settings for the active solution indicate that the debugger will not ask the user to find the file: c:\dev\AutoMapper\src\AutoMapper\Mapper.cs.
The debugger could not locate the source file 'c:\dev\AutoMapper\src\AutoMapper\Mapper.cs'.

E aparece a opção para localizar o arquivo Mapper.cs.
Tentei seguir o exemplo do desta resposta, porém não ajudou.
Answer: Consegui aqui, estava verificando o erro no lugar errado.
O problema estava em minha classe  Pessoa. Eu possuo uma ICollection .
Ao iniciar ela no construtor, o mesmo funcionou perfeitamente.
public Pessoa()
        {
            Enderecos = new List<Endereco>();
        }


Solving Algebraic Riccati Equation by using Newton-Raphson's method?

Question: Assume that we have a function called $$F(X) = 0$$
That function can be written as the Algebraic Riccati Equation:
$$F(X) = A^T X + XA - XBR^{-1}B^TX + Q = 0$$
Where the solution to the equation is matrix $X$.
To do a Newton-Raphson solveing method. I need to use this equation:
$$X_{i+1} = X_{i} - F'(X_{i})^{-1}F(X_{i})$$
Where $F'(X)$ is the jacobian function of $F(X)$ and $X_{i+1}$ is going the be the solution to the Algebraic Riccati Equation.
My question is:
How can I find the derivative of $F(X)$ ? Can I just assume that the derivative is:
$$F'(X) = A^T + A - XBR^{-1}B^T$$ ?
Answer: $F'(X):H\in M_n\rightarrow A^TH+HA-HUX-XUH$ where $U=BR^{-1}B^T$.
Let $K=F'(X_i)^{-1}F(X_i)$.
At each step, you must solve in $K$ this linear equation:
$A^TK+KA-KUX_i-X_iUK=A^TX_i+X_iA-X_iUX_i+Q$, or
$(A^T-X_iU)K+K(A-UX_i)=A^TX_i+X_iA-X_iUX_i+Q$, which is a Sylvester equation.
EDIT 1. Answers to the first three comments.
I don't need any dot product or "fourth order tensor"!!! $F'(X)$ is a derivative and not a gradient. Stop to read the matrix cookbook; you don't understand that you do.
$F$ is a function from $M_n$ to $M_n$. Then, its derivative, in $X\in M_n$, $F'(X)$ is a LINEAR application from $M_n$ to $M_n$; we assume that it is a bijection in $X_i$ and, therefore $F'(X_i)(K)=F(X_i)$. One cannot do simpler!
Last point. A Sylvester equation in the unknown matrix $K$, is a linear equation in the form $AK+KB=C$.
cf.   https://en.wikipedia.org/wiki/Sylvester_equation
Matlab has a solver dedicated to this type of equation.
EDIT 2. Answer to Daniel Mårtensson . Your below comment: "but where do I update $K$ then?" shows that you did not understand one word of my post...
I rewrite. One iteration consists in that follows.
i) input. $X_i$
ii) Solve in $K$ (using Matlab): $(A^T-X_iU)K+K(A-UX_i)=A^TX_i+X_iA-X_iUX_i+Q$
The equation depends on $X_i$; then $K$ depends on $X_i$.
iii) output. $X_{i+1}=X_i-K$ (and not $X_i+K$).
Comment: I assume that $F'(X):H$ is referring to the double dot product between the fourth order tensor $F'(X)$ and second order tensor $H$? Since the [derivative of a matrix with respect to a matrix](https://en.wikipedia.org/wiki/Matrix_calculus#Other_matrix_derivatives) is a fourth order tensor.
Comment: It is also not immediately clear (at least not to me) where the final Sylvester equation came from. So maybe it would be worth adding that $F'(X_i):K=F(X_i)$. Now buy using the definition of that double dot product the final Sylvester equation can be obtained.
Comment: What is a sylvester equation ? Is it the derivative of the riccati equation?
Comment: So....the Sylvester equation is the derivative equation of the riccati equation?
Comment: So let me make this clear! I need to find $$K = F'(X)^{-1}F(X)$$ to find the new $X_{1+i}$ from $X_{1+i} = X_i + K$. I can find $K$ from $$AK + KB = C$$.......but where do I uptade $K$ then?
Answer: Let a lowercase letter stand for the corresponding vectorized matrix, e.g.
$$f={\rm vec}(F), \,\,\, x={\rm vec}(X)$$
Write the function and its differential
$$\eqalign{
 F &= A^TX + XA - XPX + Q \cr
dF &= A^T\,dX + dX\,A - dX\,PX -XP\,dX \cr
}$$
and vectorize
$$\eqalign{
df &= (I\otimes A^T+A^T\otimes I-I\otimes XP-X^TP^T\otimes I)\,dx \cr
J=\frac{\partial f}{\partial x}
 &= M - (I\otimes XP) - (PX\otimes I)^T \cr
}$$
Note that $$M=(I\otimes A^T+A^T\otimes I)$$ is constant between iterations and only needs to be calculated once.
Then we have the standard Newton iteration
$$\eqalign{
 Js &= f \cr
 x_+ &= x - s \cr
}$$
All of the Kronecker products are sparse, so by utilizing the sparse solvers from your matrix library, you can solve moderately-sized systems with this simple method.
Comment: How would it be if the Riccati Equation was discrete? It would be not possible to find the derivative of it? Maybe I should learn numerical jacobian insted ?
Comment: Can you not show this as a real example so I can mark this as an accepted answer?


Can the accessed website detect if i'm using a Virtualized like machine vmware, vbox, etc?

Question: If i access an website, it can detect if im using a virtual machine ?
More specifically an Vmware image?
And if the website is able to..
How can i prevent it?
Thankful, Chinchila
Comment: While I expect a _browser_ won't tell a website if you're running virtualized or not, a _flash_ or _activeX_ or (probably?) _silverlight_ plugin or (possibly?) _java_ applet can tell when you're running virtualized. So be careful with your plugins.
Answer: The accepted answer is not exactly correct.
This can sometimes be done even simply using JavaScript by detecting your screen resolution to detect a windowed operating system as explained here:
http://carnal0wnage.attackresearch.com/2009/04/detecting-vmware-with-javascript-or-how.html
or by detecting your MAC address (VMware uses fixed MAC ranges) as explained here:
http://jeremiahgrossman.blogspot.co.il/2009/08/web-pages-detecting-virtualized.html
To circumvent these problems, don't use re-sized windows and change your machine's MAC address. There are other ways to detect you are in a VM using JAVA applets maybe ActiveX plugins and probably other things as well...
Comment: Pretty interesting. But you usually must opt-in to running Java applets and ActiveX plugins (or those are disabled entirely), and the screen resolution is just a heuristic (although a clever one). Every VM I've dealt with in modern times (I realize this answer is 2.5 years old) will adapt to your physical monitor size, and there is a wide variety of screen dimensions. I stand by saying that there isn't an _easy_ way for a web server to detect if you're using a VM.
Comment: There are probably other detection methods that are based on timing (some tasks are slower on VM) or somehow detecting machine frequency (http://www.securitygalore.com/site3/vmd1-advisory)
Answer: There are few ways to determine whether you are on a Virtual Machine and  below are the most used

Through WebGL: WebGL is a Javascript API that comes with the browsers like Google Chrome, Firefox, etc. This will leak the GPU name and the Vendor name of the renderer. While using a Virtual Machine, It will leak different rendered data than while using the browser on a physical machine. For example, Google Chrome shows Renderer's name as "Google SwiftShader"(It is used on machines without 3D graphics hardware.), Firefox Shows the renderer's name as "llvmpipe"(This is also a software renderer). It will lead to understanding to the website that you are on a Virtualised Machine. For more information regarding WebGL Check this link.

Through WebRTC: It will leak the local IP address to the website(Tested on chrome) but firefox is not leaking somehow

Also, the Virtual box adds a string "VirtualBox" in the prefix to the webcam name. Suppose you are using a Virtual machine and gave webcam access to some website, it will be able to see the webcam name along with the prefix "VirtualBox". To prevent that you can check this solution once (https://askubuntu.com/a/1357986/699463)

If you want to know more about this kind of leaks, then definitely use this website https://browserleaks.com/ to perform leaking tests like webrtc, webgl, and more. It will also show the ways to avoid this kind of leaks.
Answer: Web servers can only tell details about the web browsers through their user agent string.  Unless you're using a special web browser (unlikely) that detects that it's running in a VM, then the web server shouldn't know.  In any case, UA strings are easy to change to whatever you'd like them to be, so you can always pretend to be something you're not.
Check out this useful Wikipedia article.
Comment: So if i use a normal browser without addons i cant be detected as using a virtual machine?
I already read on a website that they can see even my active username, computer name etc...
I was worried about it to, to let my pc name undetected too.
Comment: No, they shouldn't be able to see your username or computer name unless you have some evil plugins/extensions installed.  Typically, all the UA string will give is which web browser you're using, its version, and your OS version.  IE also sends your .NET version.


How to do multivariate analysis on data not normally distributed?

Question: I have a series of continuous measurements that are not normally distributed (multivariate Shapiro-Wilk test p-value = 0.003818, Anderson-Darling test p-value = 0.0178 or lower for each variable) that are then stratified by several other ordinal data (such as: death Y/N, sex M/F, fever Y/N).
I understand that multivariate analysis can be done only with normally distributed data. The question is: are there not-normal alternatives? As there is the Mann–Whitney U test for the t-test, is there a non-parametric MANOVA?
Alternatively, what would be the procedure to analyze not normally distributed data?
Comment: _How_ to do it depends on what hypotheses you want to test, but "multivariate analysis can be done only with normally distributed data" is definitely wrong.
Answer: The Kruskal-Wallis test can be used. It is the equivalent of MANOVA in non-parametric tests.


Javascript: Add label at beginning and end of axes

Question: I want to add to the beginning of the axes a label to indicate "not very important" and a label to the end of the axes "very important." I am using the following slider program: http://sujeetsr.github.io/d3.slider/.
As a beginner to JS, would appreciate your help on how it would be best to do that.
Answer: How about this:

<!DOCTYPE html>

  <link rel="stylesheet" type="text/css" href="https://rawgit.com/sujeetsr/d3.slider/master/d3.slider.css" media="screen" />


Transition from "old-school" neural network methods to deep learning?

Question: As far I know the current state of deep learning favours a rather simplistic setup -- in short: many layers to allow for representational learning, maxout or a similarly suited activation function to avoid the explaining-away phenomenon, and dropout as regularization. Correct me please if I'm wrong or outdated on this.
To me, having missed the early deep learning developement (RBMs, autoencoders, etc.) and still being stuck in the 90's neural network methods, this seems like a promising chance to step into the field of deep learning. It suggests I simply take my old neural network code, add maxout and dropout, use stochastic gradient descent aka backpropagation and start over (--maybe by disregarding the huge-data stuff requiring GPUs and specialized libraries). But, is it really that simple?
Questions:

Given I want to turn a running "old-school" neural network program into a basic -- but useful -- deep-learning implementation, what do I have to do? Is it really just dropout + maxout?
How to perform the learning? Just by stochastic backpropagation? Are there other methods used from the large set of training methods and tweaks (rprop, Levenberg-Marquart, momentum, simulated annealing, etc.)? Any preferences on the learning parameters?
What are good heuristics for the network architecture (in terms of number of layers, number of neurons, direct-links and/or not full connections, etc.)? Yes, I know, it always depends :-) ... still, are there any reasonable approaches?

Ok, I realize this became a very broad question, parts of which are most likely already covered here on Cross Validated -- so I'm thankful for links as well.
Answer: The nature publication described everything precisely about what deep learning really is, which I don't have to repeat here.
And to my observation, "old school" neural network don't go "deep" for many reasons. And nowadays, people found new ways to overcome headaches brought by "old school" neural network frameworks, e.g. using GPU to improve the computational efficiency, using dropout to solve over-fitting problem etc.

I think the answer is yes. It is those important heuristic tricks, along with the undisregardable GPU implementations that made deep learning really "deep".
Generally, the lecture slides here answered this question clearly enough, see the last slide for a summary of learning methods for different problems.
Recent research on deep recurrent attention models (DRAM) proved that using proper designed network models, which act more like a human brain, can improve computational efficiency (by decreasing number of parameters required to train with the help of recurrent networks), while increase recognition accuracy. This made the application of dropout less necessary for an implementation.

EDIT: The above answer may contain much opinion of my personal perspective, but truth is when we look back a few year later that how deep learning grow popular among machine learning algorithms, we would see that it is the inspiration of human brain that push the development of deep learning forward. That is to say, we are just trying to mimic how brain solve the complicated problems, while "old school" neural networks are brains like a rat, and "deep" networks are brains of a monkey.
Comment: Here's a non-paywall version of the article: https://www.cs.toronto.edu/~hinton/absps/NatureDeepReview.pdf
Comment: Welcome to the site, @blue. +1, however can you post full citations & a summary of the
information at the link?


5/7b in figured bass

Question: What does 5/7b mean in figured bass?
If it is just a 7th chord in root position, then why is it not just 7b?
In other places in the same score, 7 or 7b are used to denote a 7th chord.
Here is the example, from Vivaldi's "Filiae maestae Jerusalem" (source):
Answer: The 5 is not redundant, and it doesn't mean you have "a four note chord."
The point of the notation is that the 7b 5 intervals from the new bass note are the same notes as the 6b 4 intervals from the previous bass note.
In other words, since the continuo is for organ (which can sustain notes indefinitely), you simply hold those two notes down, and only the bass note moves.
That is exactly the same as what the violins are playing, of course.
What is more interesting about this example is that the second chord played by the strings is actually a 6b 4 2 chord, which then becomes a complete 7 5 3 dominant 7th. But Vivaldi wanted the D played only the viola, not by the organ continuo. Otherwise the figuring would have been 6b 4 2 followed by just 7b.
A typical organ continuo registration might have made the complete 6b 4 2 chord sound muddy, especially if a cloth-eared organist voiced it with the D in the tenor, a second above the bass C!
Re the edition, you can view an alternative professionally published edition here - though I don't agree with the continuo realization: https://www.prestomusic.com/sheet-music/works/52700--vivaldi-introduzione-al-miserere-rv-638-filiae-maestae-jerusalem/browse
Comment: Do you know why there are no lines connecting the two figures to show that the notes are held while the bass changes? Other than the lack of those lines it does make sense the figure means to not play the third of the chord.
Comment: Thank you for suggesting this edition! Checked it out and it was very helpful. There, figured bass is realised as follows. In bar 1: C3, G3, C4, Eb4. In bar 2: C3 is still held, the upper 3 notes are released, Ab3, D4, F4 are played instead. All notes are released in the middle of bar 3. In the middle of bar 3: Bb2, Ab3, D4, F4 are played - so, in the opinion of the editor, the common notes are repeated and not held from the previous chord. This edition will probably also be very helpful with understanding parts II and III, where the bass line was written without any numbers.
Answer: I wish the IMSLP had another source beside the Martin Straeten version. It could help confirm the meaning. I notice the key is C minor and this notation uses the modern three flats rather than two flats which was common in the Baroque era. Straeten may have modernized some things in the score. Perhaps too he changed bass figures?
Usually a modification of the numeric figure with b, #, + means an alteration from the key signature. In this case both the 6b and 7b refer to the A and that is already a flat from the key signature. So I think this may mean two things:

It simply confirms the flat of the key signature.
If the original score was for a key signature of two flats, it would have been Eb and Bb, in which case these figure would require the flat to mean Ab, because the flat wasn't in the key signature. (I suspect this is the actual case, but we would need to see the original score to confirm.)

EDIT
About the 5 figure.
As far as I can tell the 5 is redundant. Plain 7 means a root position seventh chord and 7/5 also means a root position seventh chord. The 5 doesn't seem necessary to clear up some possible confusion from the previous chord. Either way a Bb dominant seventh chord should be played.
Comment: @Liisi, I added an edit.Funny, the flat on 7 is what got my attention!
Comment: It does not solve my question about the difference between 7b and 5/7b. That was my question - not the flat.
Answer: In traditional figured bass pedagogy, a single figure indicates a non-chord tone or its resolution (e.g. 7-6 for a suspension). Thus to indicate a chord, at least two figures are required, and 7/5 is traditional for root-position 7th chords (6/5, 4/3, and 4/2 for the other inversions).
Answer: It means you have a four-note chord in root position.
It means you have what looks like Eb:V7 in root position, the notation is derived from the distance the root the third, fifth and seventh are from the root note. It also looks like the sevenths wants to be flatten for some reason.
In this case, 7/5/3, 7/5 and 7 all mean the same thing a four-note chord in root position.
You can find a thorough explanation of all the names for inversions and how the names where derived in my answer here.
How to memorize seventh chords and inversions on piano?
Comment: You gave the wrong key! More importantly you didn't really explain why the flat is on the figure which is the whole point of the question.
Comment: What does E:V7 mean? And why is the third omitted from the notation but the fifth is not?
Comment: the third is not omitted the violas are playing the D
Comment: please see the link in my answer to see a thorough explanation of the notation.
Comment: But why is 3 omitted from figured bass notation here and 5 is not? There has to be some difference between 7b and 5/7b (or only 7b would be used - why have two different notations for something exactly the same in one score).
Comment: It does not matter, sometimes it is notated just with a 7, sometimes it is notated 7/5 or sometimes the full name is given 7/5/3. It does not mean the third is not present in the chord it is just different shorthand for the same thing.
Comment: can downvoters please explain there vote with a comment.
Comment: It's not my downvote (I have too little reputation to downvote). However, your answer is not easy to read and has several grammatical errors.

5/7b in figured bass