difference between python set and dict "internally"

Question: Can anybody tell me how the internal implementation of set and dict is different in python? Do they use the same data structure in the background?
++ In theory, one can use dict to achieve set functionality.
Answer: In CPython, sets and dicts use the same basic data structure. Sets tune it slightly differently, but it is basically a hash table just like dictionaries.
You can take a look at the implementation details in the C code: setobject.c and dictobject.c; the implementations are very close; the setobject.c implementation was started as a copy of dictobject.c originally. dictobject.c has more implementation notes and tracing calls, but the actual implementations of the core functions differs only in details.
The most obvious difference is that the keys in the hash table are not used to reference values, like in dictionaries, so a setentry struct only has a cached hash and key, the dictentry struct adds a value pointer.
Before we had the built-in set, we had the sets module, a pure-Python implementation that used dict objects to track the set values as keys. And in Python versions before the sets module was available, we did just that: use dict objects with keys as the set values, to track unique, unordered values.
Answer: These two are use the same datastructure in the backend. e.g in sets you cannot store duplicate values but in dict you can store multople same values and you can turn the dict to sets by changing the behavior of dict


Block Google Analytics during local testing for static site development without IP ranges (especially on Mobile devices)

Question: I've searched around on SO, and found a few questions that ask about this, but most of the answers that I've come across all seem to suggest either filtering via IP range or introducing conditional code to the engine powering the site; neither of these options are viable for me.  If this does turn out to be a duplicate where this an answer that fits in to my use case, then I apologize in advance, but I just can't seem to find anything.
My original method of filtering myself out from Google Analytics was to simply redirect requests to google-analytics.com and the https version of GA to localhost in my hosts file.  This works just fine on my desktop, but it is useless when testing on mobile devices like an iPhone (unless somebody knows how to finagle the iPhone's hosts file without jailbreaking).
My setup for local testing is to use pow with .dev domains for the local project directories, and then when I need to see the development version of sites on mobile devices I use Xip.io in conjunction with Adobe Shadow.
I can't filter by IP range because I frequently work from home, and my ISP doesn't provide static addresses for residential accounts.
I tried to set up a Custom exclude filter in my Google Analytics profile to filter out traffic originating from these domains, but they either don't work or I have a really bad misunderstanding of how the Exclude filters work (which is entirely possible).  I have Custom Filters set up to Exclude based on the Hostname, matching the patterns \.dev and .*xip\.io/.* but these filters do absolutely nothing.  I believe this is because this filter is, technically, looking for the hostname of the originating domain and not the hostname being requested, but I'm really not sure because the language is vague and differs depending on which help document you're looking at.
Short of manually removing the GA tracking codes from the site during local dev then going back and adding them back in, does anybody have any suggestions or can anybody tell me what I'm doing wrong with my Exclude filters?
Answer: I've been using a variation on the analytics tracking code to prevent page views from being tracked on our staging server -- something like:
if (!/\.dev|xip\.io/.test(window.location.hostname)) _gaq.push(['_trackPageview']);

Alternatively, you could apply this to the _setAccount call. If you do this and look at the tracking requests, the web property ID shows up as 'UA-XXXXX-X'
Comment: Very clever. I like that I don't have to futz around with cookies.
Answer: You could rely on
 window['ga-disable-UA-XXXXXX-Y'] = true;

where UA-XXXXXX-Y is the account ID. (details here).
Like creating a page or webserver directive that sets a cookie (page reserved to developers to be excluded from ga), and in your code that loads ga:
if (hasDeveloperCookie()) {
     window['ga-disable-UA-XXXXXX-Y'] = true;
}

Comment: This looks promising.  I'm assuming that due to the nature of cookies, I would have to implement this "landing page" individually for every site that I am testing locally, correct?  I haven't done much work with cookies yet so I'm just wanting to make sure I understand the principles behind your answer.
Comment: I think so, a cookie is valid for a domain (eventually domain/path) and has an expiration. You could set the cookie (maybe directly in javascript, or maybe with php for instance), and then show some visual indication on the page that cookie is loaded and GA is not loaded. Each desktop browser has function to delete cookies, I am not sure about mobile browsers. You should _include_ in some way the script containing GA code in your pages, in order to have just a single point on a website where to implement this modification.


Pandas combinations and merge

Question: If you have the following dataset,
BookStrategy    Trade   DV01    Maturity

STRAT1  Bond    1000    04/05/23

STRAT1  Swap    -200    04/05/23

STRAT1  Swap    -300    04/05/23

STRAT1  Swap    -500    04/05/23

And the ultimate aim is to get this
STRAT1  Bond    1000    04/05/23    STRAT1  Swap    -200    04/05/23    STRAT1  Swap    -300    04/05/23    STRAT1  Swap    -500    04/05/23

STRAT1  Swap    -200    04/05/23    STRAT1  Bond    1000    04/05/23    STRAT1  Swap    -300    04/05/23    STRAT1  Swap    -500    04/05/23

STRAT1  Swap    -300    04/05/23    STRAT1  Bond    1000    04/05/23
STRAT1  Swap    -200    04/05/23    STRAT1  Swap    -500    04/05/23

STRAT1  Swap    -500    04/05/23    STRAT1  Bond    1000    04/05/23    STRAT1  Swap    -200    04/05/23    STRAT1  Swap    -300    04/05/23

In short, if I have
row1
row2
row3
row4,
I want the combinations to be
row1 --> row1 row2 row3 row4

row2 --> row2 row1 row3 row4

row3 --> row3 row1 row2 row4

row4 --> row4 row1 row2 row3

The code that I have so far is this,
dataset = pd.read_csv('bla.csv')

print (dataset.head(1))

df = dataset.values

df1 = pd.DataFrame(df.reshape(1,-1))

This gives the output,
0   STRAT1  Bond    1000    04/05/23    STRAT1  Swap    -200    04/05/23    STRAT1  Swap    -300    04/05/23    STRAT1  Swap    -500    04/05/23

Comment: It's not very clear what you want. Are you trying to expand each column to have 4 columns? How are you obtaining the last 8 columns in your `ultimate  aim`?
Comment: what is the logic behind this ?
Comment: Yes, I am trying to expand it to contain all the possible rows.
So if I had 10 rows with 3 columns each, I would have 10*3 columns in each row (3 columns for itself and the other 27 columns for the 9 other rows)
Answer: You can using pop for moving the list
l=[]
for x in range(len(df)):
    s = df.apply(tuple, 1).values.tolist()
    s=[s.pop(x)]+s
    l.append(s)

pd.DataFrame(l).stack().apply(pd.Series).unstack().sort_index(level=1,axis=1)

Out[398]:
        0     1     2         3       0     1     2         3       0     1  \
        0     0     0         0       1     1     1         1       2     2
0  STRAT1  Bond  1000  04/05/23  STRAT1  Swap  -200  04/05/23  STRAT1  Swap
1  STRAT1  Swap  -200  04/05/23  STRAT1  Bond  1000  04/05/23  STRAT1  Swap
2  STRAT1  Swap  -300  04/05/23  STRAT1  Bond  1000  04/05/23  STRAT1  Swap
3  STRAT1  Swap  -500  04/05/23  STRAT1  Bond  1000  04/05/23  STRAT1  Swap
     2         3       0     1    2         3
     2         2       3     3    3         3
0 -300  04/05/23  STRAT1  Swap -500  04/05/23
1 -300  04/05/23  STRAT1  Swap -500  04/05/23
2 -200  04/05/23  STRAT1  Swap -500  04/05/23
3 -200  04/05/23  STRAT1  Swap -300  04/05/23

Pandas combinations and merge


Autenticação de usuário com $rootScope

Question: Estou desenvolvendo um sistema em que dependendo do nível do usuário ele é redirecionado para uma página
.run(function($rootScope, $location, $http, config) {
  $rootScope.$on('$locationChangeStart', function(event) {
    if ($location.path() != "/Login") {

      $http.get(config.BaseUrl + "/auth.php").success(function(inf) {
        if (typeof inf == "object") {
          if (inf.nivel > 0) {
            $location.path("/ContratosCorretor") ;
          }

Ou seja, se o nível do usuário for maior que 0, ele é corretor e será redirecionado para a página dele, porém ele vai poder acessar mais uma página
  $routeProvider.when("/NovoContratoCorretor", {
    templateUrl: "view/NovoContratoCorretor.html",
    controller: "NovoContratoCorretor",
  })

e dessa forma que está meu $rootscope e sempre sera redicerionado para  para /ContratosCorretor.. Alguém tem alguma solução pra esse problema?
Comment: Se entendi bem o que quer fazer, dependendo do nível de acesso o usuário é redirecionado para uma página é isso?
Comment: Isso, Dependendo do nivel dele, ele é redirecionado pra uma página, mas ele só consegue acessar aquela página... eu quero que ele possa acessar mais uma
Comment: O usuário só fica preso aquela página, mas eu quero que ele possa navegar por mais uma
Comment: Nesse caso, entendo que quando o usuário acessar a primeira vez será redirecionado para uma página default. Após ele poderá navegar entre páginas através de um menu acredito. É isso? Se sim o que você precisa é um menu dinâmico que seja compilado em tempo de execução conforme o nível do usuário. Certo?
Answer: Eu sugiro que você determine uma variável de nível antes de configurar as rotas dessa forma:
if (nivel == 1) {
    angularApp.config(
                ['$routeProvider',
                    function ($routeProvider) {
                    $routeProvider
                 .when("/NovoContratoCorretor", {
                        templateUrl: "view/NovoContratoCorretor.html",
                        controller: "NovoContratoCorretor",
                 })
                 .when("/OutraPagina", {
                        templateUrl: "view/OutraTemplate.html",
                        controller: "OutraController",
                 })

               ]);
               }
}

Ou se você preferir, você pode estabelecer um nível para cada rota, e fazer a verificação do nível no controller:
     $routeProvider
                .when("/NovoContratoCorretor", {
                     templateUrl: "view/NovoContratoCorretor.html",
                     controller: "NovoContratoCorretor",
                     niveis: [1,2]
                     })
                .when("/OutraPagina", {
                     templateUrl: "view/OutraTemplate.html",
                     controller: "OutraController",
                     niveis: [2,3]
                });

No controle você captura o nível:
.run(function($rootScope, $location, $http, config, $routeParams) {
  $rootScope.$on('$locationChangeStart', function(event) {
    if ($location.path() != "/Login") {

      $http.get(config.BaseUrl + "/auth.php").success(function(inf) {
        if (typeof inf == "object") {
          if (angular.isDefined($routeParams.niveis[inf.nivel])) {
               $location.path("/ContratosCorretor") ;
          }
       ...

Answer: Acredito que analisar em toda rota uma regra que só é válida após o login, é um desperdício de processamento.
Você pode registrar um listener específico para a variável de usuário e só redirecionar o mesmo quando ela mudar, da seguinte maneira:
$rootScope.$watch('nomeDaVariavelDeUsuario', function(novoUsuario) {
  if(novoUsuario.nivel > 0) {
    $location.path("/ContratosCorretor");
  }
});

Desta maneira, você só vai efetuar redirecionamento para página inicial quando o objeto for efetivamente alterado, seja por login ou algo do tipo. Em todas as outras rotas de navegação, vai funcionar corretamente.
Apenas como complemento, o seu código não funcionou pois você deu um binding no evento de troca de rota, então sempre que a rota era diferente da de login, você automaticamente redirecionava o usuário para a sua página inicial.

Autenticação de usuário com $rootScope


Problemas no carrinho PHP

Question: Segue o código do meu carrinho. Eu queria que ele não repetisse os produtos e sim soma-se a quantidade deles no carrinho. Estou com dificuldade nessa parte.
<?php
include 'conexao.php';
session_start();
$_SESSION['carrinho'][] = $_GET['produtoid'];
?>

        Nome

        Quantidade

        Subtotal

    <?php

         for($i = 0; $i < count($_SESSION['carrinho']); $i++){

        $consulta = "SELECT * FROM produto where id =".$_SESSION['carrinho'][$i]." ";

         $resultado = $PDO->query($consulta);

         $vetorResultado = $resultado->fetchAll(PDO::FETCH_ASSOC);

         foreach ($vetorResultado as $valor) {

            echo "
".$valor['nome']."	";
            echo "<input type='text' size='3' name='vetorResultado['id']' value='1'>	";
            echo "".$valor['preco']."
";
      }

    }

    ?>

Finalizar compra
Continuar comprando
Answer: Boa tarde Leonardo, como você está guardando esses dados no banco de dados você pode alterar um pouco sua query e retornar a quantidade de produtos agrupando os registros.
$consulta = "SELECT nome,preco,count(nome) as qtd FROM produto where id =".$_SESSION['carrinho'][$i]." group by nome,preco";

Essa query vai te retornar nome, preco e qtd (quantidade de linhas agrupadas). Ai então é só alterar seu loop.
foreach ($vetorResultado as $valor) {
    echo "
".$valor['nome']."	";
    echo "<input type='text' size='3' name='vetorResultado['id']' value='".$valor['qtd']."'>	";
    echo "".$valor['preco']."
";
}

Tenta isso.

Problemas no carrinho PHP


Number of solutions of a matrix equation(TIFR GS 2011).

Question: Let $A$ be a $2\times 2$ matrix with complex entries,The number of $2\times 2$ matrices with complex entries such that $A^3=A$ is infinite.
Proof: Let us consider matrices of the form,$A=\begin{bmatrix} 1 & z\\
                              0 & -1 \\
                              \end{bmatrix}$,where $z\in \mathbb C$.,this is an infinite collection each matrix having characteristic equation $x^2-1=0$.By Cayley-Hamilton theorem,each of these infinitely many matrices satisfy, $A^2-I=O$.So,$A^3=A$ is satisfied by all of these matrices,although I am not saying that this collection is complete.
Can someone help me find the complete collection?
Comment: https://math.stackexchange.com/questions/1406500/the-number-of-2-times-2-complex-matrices-satisfying-a3-a?rq=1
Answer: HINT
The eigenvalues can only be $0,1,$ or $-1$, so one can write down all possible Jordan canonical forms.  There are $6$ where the two eigenvalues are different, and another $6$ where they're equal.
Comment: @loupblanc Well, you're correct, but I only meant that all the possibilities were among these, so that every one would work.
Comment: Yes, I know that you know that.
Answer: Let $m(x)$ be minimal polynomial then we know $m(x)$ must divide $x^3-x$.
If $ \ deg(m)=1$ then $A\in \{ 0,I,-I\}$.
And if $deg(m)=2$ then $m(x)\in \{x^2-x,x^2+x,x^2-1\}$
And hence $m$ has distinct eigenvalues which implies $A$ is diagonalizabile.


Hot to free disk server when full ? (it empties auto after a reboot)

Question: Every N days, my services stop because server is full (especilally mysql service and so website is down)
df
Sys. de fich.        1K-blocs       Occupé Disponible Capacité Monté sur
/dev/md/1             10403064   9875912      2868 100% /
udev                  16421232       240  16420992   1% /dev
/dev/md/2            105366664  17734884  82321576  18% /home
shm                   16421232         0  16421232   0% /dev/shm

I clean everuthing I can (tmps files, logs etc...), it is still 100%
After I do a reboot,
df
Sys. de fich.        1K-blocs       Occupé Disponible Capacité Monté sur
/dev/md/1             10403064   3185652   6693128  33% /
udev                  16421232       240  16420992   1% /dev
/dev/md/2            105366664  17735408  82321052  18% /home
shm                   16421232         0  16421232   0% /dev/shm

Everything is OK
Is there a CRON table I can setup ? or safely move mysql server ? or clean some locked files ?
Comment: Is `/tmp` on root (`df -h /tmp`)?  That's a famous place for uncurated garbage to get dumped, and it can be addressed easily enough.
Comment: It's a 10G partition @MadHatter that's a lot of cruft for /tmp.
Comment: @Iain I'm not sure it counts as a lot, but I agree it's fairly high.  Depends on the (undsiclosed) value of N as to whether it's unreasonably high.  Until the OP finds where these files are, it's basically guesswork.  I totally applaud your prohibition on `kill -9`ing mysqld!
Answer: You need to identify what is filling your disks and take appropriate actions to resolve that issue.
Given that you delete log files etc and the problem remains and that rebooting solves the issue my guess would be;
You have a log file that has been deleted but the daemon that is writing to the file doesn't know that so it is continuing to write to the file descriptor (fd).
You should be able to find the file by using
lsof +L1

When you know the name of the file, you should be able to figure out the relevant daemon.
Once you know the daemon, you should be able to resolve the issue. Normally you would have logrotate manage a daemon's log files. It has a number of techniques for signaling a daemon to close/reopen or copy/truncating a log file
Answer: Files are not deleted (despite it looks so) if they are used by any active process(es). So try to delete files and restart your mysql server and web services.
Comment: NO NO NO NO NO - never kill -9 mysql  No No that's just wrong.
Comment: once raised 100% of disk, I cannot restart mysql any more !
Comment: try to kill it with `pkill -9 -f mysqld` and start again
Comment: sorry.. not very familiar with `mysql` but doubt that this may cause any harm if disk is already full


I am new to coding. if user give wrong input how can we ask to reenter input without exiting code?

Question: My question is that when user gives wrong input it throw exception msg "wrong input" and exits the code. I want to ask again to enter the input without exiting code. I tried while loop but I didn't do it right, so please help with my doubt.
import java.util.Scanner;

public class A{

    public static void main(String[] args) {
      Scanner sc=new Scanner(System.in);

      try {  System.out.println("enter");
      int a=sc.nextInt();
      int b=sc.nextInt();
           System.out.println(a+b);

      } catch (Exception e) {
          //TODO: handle exception
          System.out.println("wrong input");
          System.out.println("enter again");

      }
   }
}

Comment: Are you sure you understand what a while loop is? Your code sample doesn't seem to loop in any manner at all...
Comment: @sittsering please delete your comment then
Answer: Use while loop and break.
while (true)
{
    try {
        System.out.println("enter");
        int a = sc.nextInt();
        int b = sc.nextInt();
        System.out.println(a + b);
        break;
       } catch (Exception e) {
            System.out.println("wrong input");
            System.out.println("enter again");
            sc.nextLine();
       }
}

Only when both a and b values are entered correctly, then it'll break out of while loop, otherwise it'll keep looping.
Comment: thnks. I didnt add sc.nextLine(); while trying while loop


Animation e Transition no CSS Juntos Não Funcionam

Question: Estou escrevendo o código abaixo e não está funcionando a parte do transition.
A classe .menu-fixed eu aplico via javascript. A animação quando abre o site. A animação funciona, mas quando eu aplico a classe que contém o transition não funciona.
Eles não funcionam juntos num mesmo elemento ?
CSS
            &.fundo-menu{
                position: absolute;
                left: 0;
                right: 0;
                top: -500px;
                opacity: 0;
                margin: auto;
                width: auto;
                animation-name: LogoTorcaneDesce;
                animation-timing-function: ease;
                animation-duration: 2s;
                animation-delay: 0.2s;
                animation-fill-mode: forwards;
                transition: all 0.8s ease;
                &.menu-fixed{
                    width: 230px;
                }
            }

JS
    var MenuHeaderBox = $("header#header, nav.menu, .fundo-menu, .logo-menu");
    $(window).scroll(function(){
        if($(this).scrollTop() > 300){
            MenuHeaderBox.addClass('menu-fixed');
        }else{
            MenuHeaderBox.removeClass('menu-fixed');
        }
    });

Answer: Descobri o problema. A transição não funciona quando determino um valor auto na propriedade.
No meu caso tinha um width: auto. Troquei pelo valor real da imagem e o transition funcionou.
Acredito que isso é para todos os casos.


FPDF Código de Barras Code128 Erro

Question: Estou tentando gerar um arquivo PDF usando o FPDF e uma classe "Code 128 barcodes" (encontrei em fpdf.org > scripts > Code 128 barcodes).
O método Code128() está dentro do arquivo code128.php na classe class PDF_Code128 extends FPDF
Porém, quando tento usar meu código recebo erro na página de que já existe este método sendo usado e não consigo gerar o PDF.
Segue meu código até então:
require("../fpdf/fpdf.php");
require("../fpdf/code128.php");

$pdf=new PDF_Code128();
$pdf->AddPage("L", array(54,86));
$pdf->AddFont('Univers','','univers.php');
$pdf->SetAutoPageBreak(false);
$pdf->Image("../img/modeloArquivo.png", 0, 0, 86, 54);

$nome='Teste';
$pdf->SetFont('Univers', '', '6');
$pdf->SetXY(28.8,17);
$pdf->Write(6, $nome);

$local='Teste';
$pdf->SetFont('Univers', '', '6');
$pdf->SetXY(28.8,23);
$pdf->Write(6, $local);

Comment: Cheque os require do seu arquivo e as classes, parece que a classe do PDF_Code128 extende a classe do FPDF e pode ser que esteja chamando algum método duas vezes.
Answer: Chequei o que foi colocado ali nos comentários e foi isso mesmo que resolveu. Quando eu tirava o require("../fpdf/fpdf.php"); desde arquivo não funcionava também, mas porque eu não havia visto o require no arquivo code128.php.
Atualizei o require neste arquivo (por padrão vem: require("../fpdf.php"); e no meu site estou usando require("../fpdf/fpdf.php");) e removi do meu arquivo principal, deixando nele apenas o require("../fpdf/code128.php"); e parou de dar conflitos entre os métodos do Code128 e do FPDF.

FPDF Código de Barras Code128 Erro


Proving that the product of 2 samples, when sorted in order, converges to the variance of the population

Question: I have a question regarding the average value of the pairwise product of 2 ordered samples that are drawn from a random variable, $X$, which in this case is zero-mean Gaussian ($X \sim N(0,\sigma_x) $).
Let $x_1, x_2, ... x_n$ be $n$ samples drawn from the random variable $X$. Let us put these samples in ascending order, and call the result: $x_{(1)}, x_{(2)}, ... x_{(n)}$.
Let's go ahead and do the same for a second sample of $n$ elements drawn from $X$. We'll call these $x'_{(1)}, x'_{(2)}, ... x'_{(n)}$
(So the two sets of samples are each, separately, in ascending order)
Empirically, I've noticed that:
$$ \lim_{n \rightarrow \infty} \frac{1}{n} \sum_i^n x_{(i)}x'_{(i)} \rightarrow \sigma_x^2$$
I'm trying to prove this result. Does anyone have any suggestions? I've been looking at the literature for order statistics, but I can't seem to come up with an airtight proof.
(Note that if I hadn't sorted them in order, the pairwise product between the two samples would obviously converge to zero, since $X$ is zero-mean: $ \lim_{n \rightarrow \infty} \frac{1}{n} \sum_i^n x_{i}x'_{i} \rightarrow 0$)
(I asked this question math exchange, but I think it is more suited to this stackexchange).
Comment: Given zero mean, $\frac{1}{n}\sum_{i=1}^n x_i^2$ converges to the true variance as $n \rightarrow \infty$. It seems like the more samples you draw, the closer each sample in the first sorted list will become to its partner in the second sorted list: $|x_i - x_i'| \rightarrow 0$, so $x_i x_i' \rightarrow x_i^2$. Perhaps this could explain your observation. I haven't thought carefully enough about this to say whether your conjecture is true or not, but maybe this could be a place to start.
Comment: If true, one way to prove this might be to look at the distribution of the $k$th order statistic for $n$ iid samples from a zero-mean Gaussian. Proving (for all $k \in [1, n]$) that this distribution approaches a delta function (e.g. that its variance approaches 0) as $n \rightarrow \infty$ would imply that $|x_i - x_i'| \rightarrow 0$.
Comment: Thank you @user20160! This is very helpful. I'm looking at the distribution of the $k$th order statistic. It is: $f_{(k)}(x) = \frac{n!}{(k-1)!(n-k)!}f_X(x)(F(x))^{k-1}(1-F(x))^{n-k}$. I tried to integrate this to find the mean and variance, but I can't seem to find a closed way to carry out this integral. Do you have any suggestions for how to carry this out? Thanks.
Answer: It also holds that
$$\frac{1}{n} \sum_i^n x_{(i)}^2 \rightarrow_p \sigma_x^2,\;\;\; \frac{1}{n} \sum_i^n [x'_{(i)}]^2 \rightarrow_p \sigma_x^2$$
since the result holds for any permutation of the index and so also for the ordered one. Then
$$\frac{1}{n} \sum_i^n x_{(i)}^2 + \frac{1}{n} \sum_i^n [x'_{(i)}]^2 \rightarrow_p 2\sigma_x^2$$
$$\implies \frac{1}{n} \sum_i^n [x_{(i)}-x'_{(i)}]^2 + \frac{2}{n} \sum_i^n x_{(i)}x'_{(i)} \rightarrow_p 2\sigma_x^2$$
$$\implies \frac{1}{n} \sum_i^n x_{(i)}x'_{(i)}\rightarrow_p \sigma_x^2 - \frac{1}{2n} \sum_i^n [x_{(i)}-x'_{(i)}]^2$$
So in order for the result to hold we must show that
$$\frac{1}{2n} \sum_i^n [x_{(i)}-x'_{(i)}]^2 \rightarrow_p 0$$
which in turn requires to show that
$$x_{(i)}-x'_{(i)} \rightarrow_p 0 $$
and so also in distribution and therefore that $E\big[x_{(i)}-x'_{(i)}\big]^2 =0$
This is what a comment suggested, by the way. Can you take it from here?
Comment: Thank you so much! This is very clear reasoning. However, I am still having a hard time taking it from here. As I mentioned in response to the comments, I can't seem to find a closed way to carry out the integrals of the $k$th order distribution to find the mean and variance. Do you have any suggestions? Thanks
Comment: @AbubakarAbid No need to do that, which anyway is usually infeasible. What you need to show, as the comment suggested, is that the distribution function itself of an order statistic (not the density function) approaches a constant as $n$ goes to infinity. This is easily shown for $X_{(1)}$ and $X_{(n)}$ for example.
Comment: Thanks @Alecos, sorry I'm not sure I understand. Are you suggesting that I show that the CDF of $X_{(k)}$ approaches a step function (meaning that all of the probability density is concentrated at a single point)? That seems even harder than computing the variance. Could you please show me how you concluded that was the case for $X_{(1)}$ or $X_{(n)}$?
Comment: @AbubakarAbid In fact it it really simple. For the extremes, we have $F_{(1)}(x) = 1- [1-F(x)]^n$ and  $F_{(n)}(x) = [F(x)]^n$, where $F$ is the distribution function of the unordered variable. They obviously go to a constant when $n$ goes to infinity, don't they? For the intermediate order statistics, the distribution function is $$F_{(i)}(x) = \sum_{k=i}^n {n \choose   k} [F(x)]^k\cdot [1-F(x)]^{n-k}$$

and with a little fiddling around you can show that this sum too converges to a constant (in the sense that it does not depend on $x$ at the limit).
Comment: @AbubakarAbid By the way, your question makes for a very good textbook exercise.
Comment: OK, thank you for helping me see that. I see that clearly both $[F(x)]^n$ and $1-[1-F(x)]^n$ converge to $0$ and $1$, respectively, which would mean that the distributions of $F_{(1)}$ and $F_{(n)}$ approach a constant value. But I still don't think this necessarily proves that the variance of $F_{(1)}$ and $F_{(n)}$ are $0$. This just shows that all of the probability density becomes more negative and more positive, respectively. In other words, we haven't showed that probability density function converges to a delta function (or, equivalently, that the variance goes to zero)?
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/53788/discussion-between-abubakar-abid-and-alecos-papadopoulos).
Comment: @AbubakarAbid The mother here is the distribution function, no need to look at the density (which after all is the derivative of the cdf). Anyway, if you want to see it that way, if the cdf becomes a constant, its derivative becomes zero, and then the integral representing the variance has a zero integrand and so equals zero. I am pretty certain probabilists could come up with some pathological counterexamples, but this is what happens with "usual" random variables like a gaussian.


Dúvida de Conceito ao cadastrar parcelas no banco de Dados

Question: Pessoal caso eu tenha uma venda a ser cadastrada, com número de contrato, dados do clientes e entre outros e tenho campos de venda com parcelas... Ai que vem minha dúvida, devo criar uma tabela de parcelas interligada pelo número da venda e cada registro de uma venda gera vários registro de parcelas? Por exemplo realizo uma venda em 3x e cadastro 3 registros na minha tabela de parcelas interligados pelo mesmo ID da compra? Até porque preciso depois informar a data de pagamento de cada uma, se houve desconto e enfim.
Comment: Entendi. Considerando os requisitos que você descreveu, é feito assim mesmo como você sugeriu.
Comment: Quais são suas opções? Digo, se não numa outra tabela, como você armazenaria estas informações que você já sabe que precisa?
Comment: @Caffé nao tenho opção, pergunto pois esta é a única que pensei, queria saber o que é feito hoje no "mercado".
Comment: Ok! Muito obrigado @Caffé
Comment: @RafaelAssmann uma dica é lembrar de ter um controle também do valor devido. Pois muitas vezes ocorre da pessoa pagar apenas uma parte de uma parcela.
Comment: @GiovaniRaciPaganini sim! tenho o saldo no banco de dados, muito obrigado!
Answer: Sou desenvolvedor de sistema comerciais e sugiro o seguinte:
Como você precisa controlar o pagamento e desconto de cada uma, o ideal é criar a tabela da forma que você descreveu relacionando por ID. Sugiro ainda que você crie uma rotina para não excluir estas parcelas em caso de estorno, ou cancelamento da venda. Uma forma de fazer isto é colocar um campo "ativo" na tabela de parcelas, caso true a parcela está ativa.
Uma estrutura básica seria:
Id, ID da Venda, Data da Parcela, Data do Pagamento, VAlor da Parcela, Valor Pago, Ativa
Outros campos seriam: status: em_cobrança_tel, em_cobrança_juridica, acordo etc
Comment: entendi perfeitamente, muito obrigado!


Is there always $B\subseteq A$ with $f(B)=B$?

Question: Let $f:A\rightarrow A$ be a function between finite sets. Is there always a non-empty subset $B\subseteq A$ with $f(B)=B$ ?
I think there is, but I am not sure how to prove it.
Answer: The sequence $A,f(A),f(f(A)),\ldots$ is decreasing, but it cannot decrease strictly for more than $|A|$ steps, so for some $n$, $f^n(A)=f^{n+1}(A)=f(f^n(A))$.
Comment: Very nice ${}{}{}{}$ thanks.
Answer: If you want $B\neq A$, then no: Let $A=\{1,2\}$ and $f(1)=2$, $f(2)=1$. More generally, a cyclic permutation of $A$ will work.
Comment: yeah, any cyclic permutation works. But I am allowing $B=A$.
Comment: I'm pretty sure $B\subseteq A$ means B can be equal to A.
Answer: This seems to fall to strong induction. Suppose it is true for subsets of size $n$ or smaller.
Take $A$ of size $n$. If the function is bijective we are done (take $B=A$). Otherwise pick $x$ that is not in the image of $f$. Notice that the image of $f$ restricted to $A\setminus\{x\}$ is a subset of $A\setminus \{x\}$. So we apply the inductive hypothesis with the function $f$ restricted to $A\setminus \{x\}$ and find an appropriate "fixed" subset.


Getting "Cannot GET /" in browser with express router

Question: Working with express Router for getting for the first time.
This is my route.js
var express = require('express');
var router = express.Router();
router.get('/', function(req, res) {
  res.send('home page');
});
module.exports = router;

This is my index.js
var express = require('express');
var app = express();
var router=require('./route.js');
app.use('/route',router);
var server = app.listen(process.env.PORT ||8000, function () {
  var host = server.address().address;
  var port = server.address().port;
  console.log("Example app listening at http://%s:%s", host, port)
});

When I open run it in browser it shows:
    Cannot GET /
Comment: But you are calling `http://localhost:8000/route` ?
Comment: I was calling  http://localhost:8000
Comment: Okay than that's the problem. You registered your router for `/route`. Express basically concats the paths which in your case is `/route` (index.js) + `/`(route.js) = `/route`. So just change `/route` to `/` in index.js
Answer: The only URL the code you have written will respond to is:
www.example.com/route/

If you want it to respond to:
www.example.com

then change to the following in your index.js file:
app.use('/', router);

Comment: Thanks for the explanation.
Answer: You should replace
app.use('/route',router); with app.use('/', router);
Answer: As I may see you have created default route in app.use as /route
you must not have added that using app.use('/') would be enough instead of creating another route for that
Thanks.


Lines through the origin and Euler-Lagrange

Question: What form should  the minimal-length curve to $\int \sqrt{dr^2 +r^2d\theta^2\over{1-r^2}}$ take? I think I can use the Euler-Lagrange equations. So write the integral as $\int\sqrt{({dr\over d\theta})^2 +r^2\over{1-r^2}}d\theta$, then since the integrand is not explicitly dependent on $\theta$, we can say that $I-r'{\partial I\over \partial r'}=c$ for some (complex?) constant $c$. But I don't seem to be getting anything useful. The equation reduced to $r^2=c\sqrt{(r'^2+r^2)(1-r^2)}$ by my calculation. But I think I am expecting straight lines through the origin...
Comment: what are the boundary conditions? or are you looking for closed curves?
Comment: @WillieWong: The domain is the unit disc. I am wishing to show that the shortest path joining 2 points is along a diameter.
Comment: So you are looking for a curve that passes through $(1,0)$ and $(0,1)$ that minimises the integral? Or do you allow arbitrary endpoints on the unit disc? (Because it looks like you are looking for geodesics on the Poincare disc.)
Comment: @WillieWong: You are right, I am indeed looking for geodesics on the disc, but the metric is one $1\over (1-r^2)$ factor different
Answer: If you expect straight lines through the origin, it makes no sense to consider $r$ as a function of $\theta$, since your entire line is at a single $\theta$ value. (Note also that using the Beltrami identity instead of the Euler-Lagrange equation as you did introduces a spurious solution $r'=0$ that leads to circles that don't solve the Euler-Lagrange equation.)
You can consider $\theta$ as a function of $r$ instead. Then you have
$$\int\sqrt{\frac{1+r^2\theta'^2}{1-r^2}}\mathrm dr\;,$$
and since $\theta$ doesn't occur in the integrand, the Euler-Lagrange equation becomes
$$\frac{\partial\mathcal L}{\partial\theta'}=C\;,\\
r^2\theta'\sqrt{\frac{1-r^2}{1+r^2\theta'^2}}=C\;.
$$
This equation is indeed solved by $\theta=\text{const.}$, so lines through the origin are solutions, but it also has further solutions:
$$
r^4\theta'^2(1-r^2)=C(1+r^2\theta'^2)\;,\\
\theta'=\sqrt{\frac C{r^4-r^6-Cr^2}}\;.
$$
Wolfram|Alpha integrates this to a rather complicated function of $r$.
Comment: @Don: You're welcome!
Comment: @joriki, Any chance for assistance here: http://math.stackexchange.com/questions/1066495/minimization-of-variational-total-variation-tv-deblurring


Ordenar por data de upload após um readdir

Question: Eu tenho este código que funciona bem, mas gostaria que as últimas imagens a serem uploadadas aparecessem no topo da página, em vez de aparecerem por uma ordem aparentemente 'random'.
Não estão numa base de dados, estão só numa pasta para onde vão usando a função move_uploaded_file(pics/....).
$myDirectory = opendir("pics");
while($entryName = readdir($myDirectory)) {
    $dirArray[] = $entryName;
}

closedir($myDirectory);

$indexCount = count($dirArray);

for($index=0; $index < $indexCount; $index++) {
    $temp = explode('.', $dirArray[$index]);
    $extension = strtolower(end($temp));
    if ($extension == 'jpg' || $extension == 'png' || $extension == 'tif' || $extension == 'gif' || $extension == 'jpeg' || $extension == 'JPG'){
        echo '';
    }
}

Answer: Pode usar a função filemtime() para saber a data de gravação de cada imagem. Que pode ser usado como chave para ordenar as imagens, usando uksort(), antes de serem processadas.
Ver também:

fileatime() - data do último acesso da imagem;
filectime() - data da ultima alteração da imagem;

Exemplo:
<?php
    function mtimecmp($a, $b)
    {
        $mt_a = filemtime($a);
        $mt_b = filemtime($b);

        if ($mt_a == $mt_b)
            return 0;
        else if ($mt_a < $mt_b)
            return -1;
        else
            return 1;
    }

    $imagens = glob($myDirectory."*.jpg");
    usort($imagens, "mtimecmp");
    array_reverse($imagens);

    foreach ($imagens as $imagem)
    {
        echo '
';
    }
?>

Fonte SOEN
Answer: Com arsort, foi criado um dateint com o valor gerado pelo filemtime e com ele o arsort ordenar de forma simples o array que foi criado ($img), sendo a data maior primeiro.
<?php
     $path = "pics/";
     $dir  = opendir($path);
     $img  = array();
     $exts = array('jpg', 'png', 'tif','gif'); //extensões aceitas
     if ($dir){
         while($arq = readdir($dir)){
             $ins = explode('.', $arq);
             $out = strtolower(end($ins));
             if ($arq != '.' && $arq != '..' && in_array($out, $exts)){
                $dateint = filemtime($path.$arq);
                array_push($img, array(
                                 'dateint' => $dateint,
                                 'name' => $arq,
                                 'date' => date('d/m/Y H:m:s', $dateint)));
             }
         }
         if ($img && sizeof($img) > 0){
             arsort($img);
             foreach($img as $value){
                 echo '
';
                 echo '';
                 echo '';
                 echo '';
                 echo '
';
             }
         }
     }

Comment: Obgrigado é isto mesmo, mas queria que fizesse mesmo o display das imagens (ultima parte do meu codigo), sendo que a ultima a ser uploadada ficaria no topo da page
Comment: @Miguel, foi feita edição, com a alteração de visualizar as imagens
Comment: Obgado, era isto mesmo


Quotient space. Understanding and proving things

Question: Let $E$ be a vector space and $F$ a subspace of $E$. The quotient space $E/F$ is $\{x+F:x\in E\}.$ Prove that if $E/F$ has dimension $n$, then there exists a linearly independent set $\{l_1,\dots, l_n\}$ in the algebraic dual space $E^{\#}$ such that $F = \bigcap_{i=1}^{n} \ker(l_i)$.
The only thing I can think of is, if $a \in E/F$ then $a = x+f$ with $f \in F$ and $x \in E$. For example, if $a \in F$ then $x=0$.
Since $E/F$ has dimension $n$, there is a Hamel base $\{h_1,\dots,h_n\} \subset E/F$ such that $$a = c_1h_1+\dots+c_nh_n.$$ Also, $\ker(l_i) = \{x \in E: l_i(x) = 0\}$, so if $x \in \bigcap_{i=1}^{n} \ker(l_i)$ the $l_i(x) = 0$ for all $i=1,\dots,n$.
But I don't see how can I relate all of this to get the result. Any hints?
We don't know any big result on this topic. The only thing we have is the very definition of the quotient space.
Comment: It is helpful to think about what this means 3D. Let $F$ be a line passing through $0$, then $E/F$ is a set of lines, parallel to $F$. Naturally, this $E/F$ is isomorphic to a plane passing through $0$ and perpendicular to $F$. Take $n=2$ linearly independent vectors $e_1$ and $e_2$ in that plane, it's easy to see that $F = \{
x | (x, e_1) = 0 \;\text{and}\; (x, e_2) = 0 \}$.
Answer: It's helpful to think of the elements in $\{x + F: x \in E\}$ as equivalence classes mod F, i.e. for $y,y' \in E / F$ we say $ y =_{mod ~ F} y'$ if $y - y' \in F$.
In this context, we can define the application $\pi: E \to E / F$ given by $\pi x = \bar{x}$ where $\bar{x}$ is the set of all $x' \in E$ such that $x - x' \in F$. Observe that $\pi$ is linear, surjective and $\ker(\pi) = F$. This last sentence means that all $y \in F$ are in the zero class: $y \in \bar{0} \in E / F$. On the other hand if $x \in \bar{0}$ then $x = 0  + f$ for some $f \in F$, so the zero class is precisely $F$.
If $E / F$ has dimension $n$, then we can represent any class $\bar{x}$ as a linear combination of $n$ independent classes:
\begin{equation}
\bar{x} = \lambda_1 \bar{e}_1 + ... + \lambda_n \bar{e}_n
\end{equation}
Since the components for each $\bar{x}$ in this basis are unique, we can define the linear functionals $\bar{l}_i : E / F \to \mathbb{K}$, $\bar{l}_i(\bar{x}) = \lambda_i$. It's clear that $\bar{l}_i(\bar{x}) = 0 $ if the i-th component of $\bar{x}$ is zero. Over this construction, we define $l_i : E \to \mathbb{K}$ by $l_i(x) = \bar{l}_i(\pi(x)) = \lambda_i$. In this case we have, $\cap_{i =1,..,n} \ker(l_i) = \{x \in E : l_i(x) = 0 ~~\forall i = 1,...,n\} = \{x \in E: \pi(x) = \bar{0} \} = \{ x \in E : x \in F\} = F$.
Comment: $\bigcap_i \ker(l_i) = \{\overline0\} = \{F\} \neq F$.
Comment: I redefined $l_i$ based on your comment. Is it ok now?
Comment: It is ok now :)


python OpenCV(3.4.2) error: (-215:Assertion failed)

Question: I'm trying to use the SIFT descriptors for image matching. I am planning to match one image with another.
This is the code with which I am trying to make the match
sift = cv2.xfeatures2d.SIFT_create()

kp_1, desc_1 = sift.detectAndCompute(original, None)
kp_2, desc_2 = sift.detectAndCompute(image_to_compare, None)
index_params = dict(algorithm=0, trees=5)
search_params = dict()
flann = cv2.FlannBasedMatcher(index_params, search_params)
matches = flann.knnMatch(desc_1, desc_2, k=2)

but I get the following error:
<ipython-input-6-1f81512d446c> in AlgSift(imagen, imagentocompare, umbral)
   21     search_params = dict()
   22     flann = cv2.FlannBasedMatcher(index_params, search_params)
---> 23     matches = flann.knnMatch(desc_1, desc_2, k=2)
   24
   25

   error: OpenCV(3.4.2) /io/opencv/modules/flann/src/miniflann.cpp:487: error:
   (-215:Assertion failed) (size_t)knn <= index_->size() in function
   'runKnnSearch_'

Comment: You can check: if input parameters are NULL or there may be different function('runKnnSearch_') definition for specific opencv version.
Answer: An error such as Assertion failed occurred in my case because the position of the image to be loaded was not correct. Please check your storage location and code once.


Angular $scope.variable undefined

Question: I am having a problem that my $scope.todo list always returns a undefined when using the angular function ng-repeat. If I define the $scope.todo it works perfectly but when I use the solution below to fetch results and add it to the variable I get an undefined before it seems to have a chance to go and retrieve the correct values
I have now added a bit better code to explain my problem. After looking at some of the jsfiddles below and trying those solutions I'm starting to think its something to do with my callbacks.
function TodoCtrl($scope) {

   $scope.todos = [];

   buildInitialList(function (result){
       console.log(result); //Logs defined after the undefined below
       $scope.todos = result;
   });

   console.log($scope.todos); //Logs undefined before the defined log above
}

function buildInitialList(callback){
    //Simulates call to db
    setTimeout(function (){
    callback([{text: 'item 1', done: false},
        {text: 'item 2', done: false}]);
},2000);
}

function fetch(url, callback) {
    $.getJSON(url, function (data, status) {
        callback(data);
    });
}

Comment: There a few syntax errors are they typos or your actual code?
Comment: You are never actually assigning the result to your scope variable. http://jsfiddle.net/973nW/
Answer: Shouldn't this:
$scope.testList = buildInitialList(function (result){
     return result;
   }

Be like this:
$scope.testList = buildInitialList( function (result){return result;} );

And buildInitialList function is not returning any value. Based on your sample code it could something like this:
function buildInitialList(callback){
   var result = doWorkAndGetResult();
   callback(result);
  //missing return value...
   return result; /*maybe?*/
}

Here is a fully working jsfiddle demo:
http://jsfiddle.net/f9ee4/1/
Comment: sorry that doesn't work. If I do
$scope.testList = buildInitialList(function (result){
     console.log(result);
     return result;
});

I get the correct result logged to the console so both functions seem to working ok just not getting called at the correct time
Comment: @MartyCochrane it worked on my end. Your function had not return that is/was the issue.
Comment: @MartyCochrane, I added a JSFiddle.
Comment: thanks for your help. I have edited your fiddle to help explain my problem http://jsfiddle.net/f9ee4/2/
Comment: @MartyCochrane here is the answer...again a return is needed... http://jsfiddle.net/f9ee4/3/
Comment: @Dalorzo Your return in the global function negates the whole reason to use a callback.  If a callback isn't really need then he should just return the value.  If a callback is needed, for example, because there's an ajax call in there, then the callback needs to assign the scope variable.
Comment: @CraigSquire my point is not around the callback function but to highlight that the issue is that a function has not return and therefore the variable is undefined. Practices and best practices are responded when the question requires it.
Comment: @Dalorzo I have to disagree, answering a question in a way that isn't practical to use in a production application is not useful.
Comment: I have tried your solutions in your fiddles but still no joy I'm afraid. I'm wondering if its something to do with my callbacks. I've added more life like code above to explain better what I'm doing.
Do you see anything wrong with it?
Answer: You are never actually assigning your result to the scope variable.  Your callback is being called, but the return value of your callback is NOT what gets assigned to your scope property.
By using a callback, I'm assuming you have some sort of async call in that global function.  If you don't have an async call in there, then you should just return the value from buildInitialList, without using a callback.
Here's a fiddle that works:
http://jsfiddle.net/973nW/
function MyCtrl($scope) {
    buildInitialList(function (result){
        $scope.name = result;
    });
}

Side note: using a global function isn't a good idea, you may want to consider putting your function into a service.
Answer: After pulling my hair out and thinking something was wrong with my javascript it turns out the problem was actually within the ng-repeat I was using in the HTML
This is what my html looked like

            <input type="checkbox" ng-model="todo.done">
            {{todo.text}}

This worked fine when I had defined a list of ToDo's right from the start however when I had to go to the DB & retrieve that list the results never seemed to be applied to the original $scope.todos
I had to use the $scope.$apply function to make sure when my values were retrieved from the DB they were actually applied to the $scope afterwards
buildInitialList(function (result){
    $scope.$apply(function (){
        console.log(result);
        $scope.todos = result;
    });
});

Angular $scope.variable undefined


how to get XML content over HTTP request?

Question: I'm building a module and I need to  get XML content over HTTP request.
The idea is to create nodes programmatically with the retrieved data from the xml file.
Can I do this?
Comment: Are you looking for [`drupal_http_request()`](https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_http_request/7)?
Comment: @AdamBalsam I think so, should I add special parameters for requesting a xml file?
Comment: I don't think you'd need any parameters at all except for the first (`$url`) parameter: `$request = drupal_http_request('http://domain.com/xml_file.xml');`. The XML file would be in `$results->data`.
Comment: With just the $url parameter works but then there are rare characters in the texts. That's the reason I think I need the "header" parameter.
Answer: Its a little bit of a learning curve , but I would recommend using the feeds module for this
https://www.drupal.org/project/feeds
you can then load xml (or csv) to nodes, and map its contents to nodes.
This is preferable to writing your own custom functionality.
but if you do, drupal_http_request(), and then node_save() for constructing the nodes would be the way to do things.
If you do code it yourself, Id recommend getting comfortable with running scripts with drush, as that'll be easier than battling timeouts in the browser
Comment: With feeds, don't you also need the Feed XPath module for injest XML?
Comment: I used feeds before but I need to manipulate the data, then is not an option afaik.
Comment: You can integrate your own code with feeds using the API it supplies. The main advantage is being able to backout and re-run the import process which is very helpful while testing.
Comment: As @MPD mentions the Feed XPath module is needed. Here a very good video tutorial to use it: https://www.youtube.com/watch?v=n7LxjxwXtrc&feature=youtu.be
Comment: @chefnelone The Feeds Tamper module can be used to manipulate data w/o needing custom code agains the Feeds API.


Open a storyboard view with a stackview button in Swift 3 and Xcode

Question: I have three views in my storyboard: MainViewController, EditViewController and PatchViewController.
In my Main view I've added a Horizontal Stack View-object which has its own class (class FieldController: UIStackView) where I add three buttons programatically.
Depending on some dynamic values, clicking on one of these buttons should open either the Edit or Patch-view which also should have access to an id that corresponds to what button clicked.
How can I achieve this?
Comment: Hint: Use named segues combined with an IBAction
Answer: First, you need to create segues in your storyboard from main controller to your additional controllers and set different identifier for each segue. In my example I'm using EditSegueIdentifier and PatchSegueIdentifier
Then in your main controller:
//connect IBActions to each button, or your buttons may have one action to connect to, but have also different tags, like below:
@IBAction func buttonAction(_ sender: UIButton) {
    //You can send an ID as Int for example, to catch them in prepareForSegue method.
    //You can send any values or objects as sender,
    //also it can be a tag of clicked button, whatever you want.
    switch sender.tag{
        case 1:
          performSegue(withIdentifier: "EditSegueIdentifier", sender: YourIDForEDIT)
        case 2:
          performSegue(withIdentifier: "PatchSegueIdentifier", sender: YourIDForPATCH)
        default: break
    }

}

If you are using programatically created buttons, you can make same thing inside their selector method:
func setTargets(){
    let selector = #selector(buttonAction(_:))
    yourFirstButton.tag = 1
    yourFirstButton.addTarget(self, action: selector, for: .touchUpInside)

   yourSecondButton.tag = 2
   yourSecondButton.addTarget(self, action: selector, for: .touchUpInside)
}

func buttonAction(_ sender: UIButton){
     switch sender.tag{
            case 1:
              performSegue(withIdentifier: "EditSegueIdentifier", sender: YourIDForEDIT)
            case 2:
              performSegue(withIdentifier: "PatchSegueIdentifier", sender: YourIDForPATCH)
            default: break
        }
}

Then we need to prepare values to send to additional controllers
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        //check segue identifier for sending values to destination controller
        if segue.identifier == "EditSegueIdentifier", let editID = sender as? Int {

            let destination = segue.destination as? EditViewController
            destination?.id = editID
        }

        if segue.identifier == "PatchSegueIdentifier", let patchID = sender as? Int {

            let destination = segue.destination as? PatchViewController
            destination?.id = patchID
        }
}

==============EDIT==================
The protocol
protocol YourStackViewDelegate {
    func performButtonAction(with index: Int) //or you can send anything else (e.g. ID, objects)
}

Then in your StackViewClass
class YourStackViewClass {
   //make optional var for delegate instance
    var delegate: YourStackViewDelegate?

   func setTargets(){
        let selector = #selector(buttonAction(_:))
        yourFirstButton.tag = 1
        yourFirstButton.addTarget(self, action: selector, for: .touchUpInside)

       yourSecondButton.tag = 2
       yourSecondButton.addTarget(self, action: selector, for: .touchUpInside)
    }

    func buttonAction(_ sender: UIButton){
         //call the method from the protocol
         delegate?.performButtonAction(with: sender.tag)
    }
}

In your view controller
override func viewDidLoad() {
   super.viewDidLoad()

   yourStackView.delegate = self
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
            //check segue identifier for sending values to destination controller
         if segue.identifier == "EditSegueIdentifier", let editID = sender as? Int {

             let destination = segue.destination as? EditViewController
             destination?.id = editID
         }

         if segue.identifier == "PatchSegueIdentifier", let patchID = sender as? Int {

             let destination = segue.destination as? PatchViewController
             destination?.id = patchID
         }
  }

Then add an extension of you view controller with the delegate
extension YourViewController: YourStackViewDelegate {
    func performButtonAction(with index: Int) {
         switch index{
                case 1:
                  performSegue(withIdentifier: "EditSegueIdentifier", sender: YourIDForEDIT)
                case 2:
                  performSegue(withIdentifier: "PatchSegueIdentifier", sender: YourIDForPATCH)
                default: break
            }
    }
}

Comment: Thank you for the answer. I'm getting an error though: "Use of unresolved identifier 'performSegue'". This function doesnt seem to exist in a UIStackView(where my buttons are created)? I can call it if I run MainViewController().performSegue(), but then my created segue seems to be lost: "has no segue with identifier "PatchSegueIdentifier".
Comment: The performSegue method should be called in the view controller. You can use protocol to send any data or actions from your custom stack class to the view controller. Let me know if you need a code for it, I will edit my answer
Comment: If you could provide code for it it would be great. I've tried a few times my self now without success.
Comment: I've edited my answer, check it. Let me know if you need something
Comment: Edit: As soon as I wrote a question, I figured that "yourStackView" is a IBOutlet, correct?
Comment: Yes, it is. You need to connect it with your view controller
Comment: Thanks a lot Woof for tremendous help!


Chord progression in Brangane's warning

Question: I have been interested for quite some time in the harmonic progression in Brangane's warnings in the second act of Wagner's Tristan und Isolde. My question: how can one analyze the chord progression in this passage ?
Here's the link for the Brangane's first warning on Youtube. After a bit of time, here's what I have found:

From 0:00 to 0:34 in this link, I have difficulties identifying the chords. It does not seem to be triadic harmony, but instead tetrachords.
From 0:34 to 01:22, it seems easier. I have found the following chord progression: D, A, G, C#, Am, Em, C#m, Eb.

I am not used to analysis, and as such I don't know how to proceed with this progression, for which I see no apparent pattern. I have studied transformational music theory for some time, and I have written the transformations from one chord to the other using both the transformation/inversion (T/I) group, and the PLR group, but there does not seem to be any significant pattern here as well.
Any help would be appreciated...
Answer: OK, this is a tricky passage, but it's not impossible to analyze. The high level of dissonance is caused by a) the persistent Ab pedal; b) the long-held appoggiaturas. At the slow tempo Wagner is using, these two forces create sonorities that we try to hear as "chords," but which are not:  they are conglomerations of chord and non-chord tones.
roughly (discounting the pedal and removing the appoggiaturas):
bar 1:    Db7
bar 2-3:  Dbdim7 (= Vb9/Ab)
bar 4-5:  Ab7
bar 6-7:  Eb7
bar 8-9:  Db7
Comment: Thanks for the help... How would you go to analyze this progression, or the triadic one I indicated ? What should I be looking for ?
Answer: I would suggest looking up the score for the piece. (Here for example, starting at p. 361.) If you are having trouble hearing/transcribing the harmony why not go to the source? Unless your objective is to become a better transcriber there is no need to torture yourself...
Regarding the harmonic analysis I must confess I'm as much in the dark as you. One way of looking at it is this: how does it sound? It certainly does not sound like a simple "functional" harmonic progression (ie D -> T movement etc). Every time the ear expects a resolution something else happens. Perhaps there is something else that ties it all together, such as the melody.
Looking at the key signatures in the score the piece starts out in Ab and then moves to A natural. Since you seem familiar with neo-Riemannian theory why not take a look at the tonnetz and try to track the progression?

Chord progression in Brangane's warning


Not understanding the concept of "irreducibility" for quasi-projective varieties

Question: I am self-studying Shafarevich's "Basic Algebraic Geometry" and I am having some trouble understanding the decomposition of quasi-projective varieties into irreducible components. I work over an algebraically closed field.
Shafarevich claims that "The notion of irreducible variety and the theorem on decomposing a variety as a union of irreducible components carries over word-for-word from the case of affine sets." I am having difficulties understanding this (Shafarevich dedicates only half a page to the concept of quasi-projective variety, leaving a lot for the student to figure out by himself).

Let $X \subseteq \Bbb P ^n$ be an irreducible projective variety. Let $U = \{[x_0 : \dots : x_n] \in \Bbb P ^n \mid x_0 \ne 0\}$ be our usual affine chart. Let $X_0 = U \cap X$ be the affine part and $X_\infty = X \setminus X_0$ be the part at infinity. $X_0$ is the intersection of a Zariski closed subset of $\Bbb P^n$ and the open subset $U$, therefore a quasi-projective variety. $X_\infty$ is a closed subset of $X$, therefore closed in $\Bbb P^n$, therefore projective, therefore quasi-projective. Since $X = X_0 \cup X_\infty$, it follows that $X$ is reducible! Where am I wrong?
A concrete example: consider the affine line $L: x=0$ in $\Bbb A^2$ and let $\overline L$ be its projective closure. Then $\overline L$ will be the union of $L$ (the affine part) and $[0:1:0]$ (the point at infinity). How does this fit with the intuition that $\overline L$ should be irreducible?
Let $X,Y,Z$ be projective varieties such that $X = Y \cup Z$ with $Y \cap Z \ne \emptyset$. Let $W = Z \setminus Y$ - a quasi-projective variety. Since $X = Y \cup W$, how does this fit with the expected uniqueness of the decomposition in irreducible components?
If $X = Y \cup Z$ is reducible with $X,Y$ projective, does it follow that $Z$ must be projective too, or can it also be quasi-projective non-projective?
Answer: If $X$ is projective, it is irreducible if it cannot be written as a union of two closed subset. Here, all your decompositions are on the form $X = X \backslash Z \sqcup Z$ where $Z \subset X$ is closed. $X \backslash Z$ is not closed so there is no contradiction. For example, $[0,1] = \{0\} \cup (0,1]$ but it is connected because $\{0\}$ is not open.
The uniqueness of decomposition into irreducible component is only true if you take closed component. Else, you can again take $\mathbb A^1 = \mathbb A^1 \backslash \{pt\} \sqcup \{pt\}$ which would contradict the irreducibility of $\mathbb A^1$.
Here is some example of reducible variety : the variety $xy = 0$ in $\mathbb P^2$ (a union of two lines), the variety defined by $x(y^2 - xz)$ (a union of a line and a parabola), and any polynomial $f = gh$ is the union of the variety $g = 0$ and $h=0$. If $g,h$ are non-units and different polynomial you will get a reducible variety. Hope it helps a bit.
Finally, your answer to 3) is yes. If $X$ is projective it is given by equation $f = 0$. Assume for simplicity $Y,Z$ are irreducible : then $f = gh$ with $g = 0$ correspond to $Y$ and $h=0$ corresponds to $Y$. So just $X$ projective and $Y,Z$ closed implies that $Y,Z$ are projective.
Comment: Let me understand this clearly: is it possible to define a reducible *quasi*-projective variety as one that can be written as the union of two non-trivial *quasi*-projective varieties? Or does the usual definition of reducibility work only for affine and projective algebraic subsets, but not for quasi-projective ones?
Comment: A little remark : 3)  is false if $Y,Z$ are not assumed irreducible. Take $Y$ a union of a projective line and a point $p$. $Y$ is projective but reducible. Now let $Z$ to be a projective line minus the point $p$. $Y \cup Z$ is the union of two projective lines, so it's projective, and $Y$ is also projective but $Z$ is not projective. Anyway usually all varieties are assumed irreducible for avoid this kind of problem.
Comment: About your comment : no, because $A^1$ is quasi projective but you will get "fake decomposition" by writing it as $A^1 \backslash p \sqcup p$. So you define a reducible quasi-projective variety to be the reunion of two _closed_ subset of the quasi-projective variety (closed for the induced topology).
Comment: Irreducibility works for any type of variety.


Is it valid to assign observations partially to both test and train in n-fold cross validation?

Question: I'm looking to use n-fold cross validation for selecting meta-parameters for fitting a model to a dataset. However, dropping observations entirely from the learning-set while fitting the model to each of the folds may create problems for the model fitting.
I was wondering whether it would be valid to perform the cross-validation on a weighted basis, e.g. the observations selected for the fold would receive a weight of say 0.95 and the ones excluded from the fold would receive a weight of say 0.05. When assessing predictive performance one then would weight prediction errors according to the complement of these weights, e.g. (1-0.95) for those 'participating heavily' and (1-0.05) for those 'participating lightly'.
Is there any merit in this intuition?
Such a process is similar to Fay's Balanced Repeated Replication (Survey sampling variance estimation). I have never encountered it in relation to cross-validation. Any literature pointers are appreciated.
Answer: I doubt this is a good idea. The core idea behind CV is that it is a simulation of testing model on unseen data; any leak of information from local test sets to local trains will ruin the guarantee that the performance on local test is not a result of overfitting, thus making the result unreliable.
If your model has a problem with reduced train set, it is quite possible that you have caught some general instability and you should look for some better solution.
Comment: Some more intuition: Statistical learning theory leverages the fact that w.h.p your iid training and test sets will be representative of the distribution from which they were drawn. Hence low training error and high test error implies a poor classifier rather than some unlucky pick of the test points. Therefore, you should trust the data and not try to massage the test error.


It is true that, during the first years of professional football, teams used to play with only 2 defenders and 5 forwards?

Question: I've heard many times that, in the past (I don't know exactly when, but It may be around 1930 and 1950 decades) football teams used to align using 2-3-5 formation.
I know that tactics used to be less defensive at those times, and it used to be more goals, but I guess if this were completely true, an we interpreter 2-3-5 as 2 defenders, 3 midfields and 5 forwards in the same sense we refer to those positions today, it should have been dozens of goals per match.
I also rembember reading a quote from some old player saying that I was an exaggeration, and that just the idea of 5 forwards against 2 defenders is ridiculous.
Can anybody explain how football tactics worked at those times?
Comment: Keep in mind that before the 1930s, the offside rule was a lot different - you needed to be farther than the goal line than (or level with) the third last opponent, not the second last opponent. This made holding a line with less defenders much easier.
Answer: YES but it was not a rule
This site confirm that, in the early 1900s, tactics were more offensive than now.
Also this source and wikipedia confirm that the old off side rules permits to play with those tactics.
I think you can find a lot of exhaustive info on the posted links, so I prefer to do not add more.
Comment: Yes. That explains why those tactics were used before 1925, which is the year when the off-side rule changed. But there are famous later teams which used 5 forwards. I known some argentinian teams examples, like River Plate's La Máquina in the 40's https://en.wikipedia.org/wiki/La_M%C3%A1quina
Comment: Now that I read yout Football Bible source, I think that those 40's teams probably used the 3-2-2-3 MW tactic, which also has 5 forwards, but it's more balanced.
Comment: Some of those tactics numberings are confusing. For example, Victorio Pozzo's Il metodo is refered as 2-3-2-3, but two of the midfielders were responsible of mark the opponent's wingers! Makes much more sense to call them defenders instead of midfielders. That way it would be 4-1-2-3


Is there any way at all to tell if these measures are 6/4 vs. 3/2?

Question: It's once again time for everyone's favorite game, "why is this wrong on my test?"
This time, it's a "name that time signature" question that got marked wrong.

In short, the only other answer that I would consider is 3/2, but it could technically be either right? The first measure obviously is divided into 1+2+3, but the second measure looks distinctively 6/x ish, at least with the greater classical style as a pretext. To me, there's nothing to suggest one answer over the other.
If it is in fact 3/2, how can I distinguish them in the future? I see that there's already a similar question about 3/4 vs. 6/4, but to me this is different because of this specific instance where the second measure looks to my eye to be two beats divided into three. At the very least, there's no clear way to distinguish them, is there?
If there is, how can I tell?
Comment: Having written out the full thing, I have to say that it feels very much like 3/2. Although while taking the test my eye gravitated toward the second measure, I have to agree that given the context, there isn't anything very 6/4ish about this excerpt at all. I think the real answer to my question of how to tell is to get more experience with sight reading/audiation/rhythm.
Comment: I'm nominating to open this although the questions seem superficially the same, the particulars on the grouping that answers the question is different.
Comment: @replete As I mentioned in the question, I at least find this to be different because "of this specific instance where the second measure looks to my eye to be two beats divided into three." Basically, while the linked question explains *that* there's a difference, I'm asking "what's the best way to know for certain when in doubt?" I did check the linked question, and I haven't found what I consider to be a direct answer to my question. I'll check again later this evening when I have time to make sure I haven't missed something.
Comment: The second bar may be in either two or three, but the first and third bars cannot be in two.
Comment: @replete They can though, can't they? But given the context, I concede it seems unlikely.
Comment: @replete Forgive my density, but I don't see how that would be necessary. I tried recreating a 6/4 measure of a half note and a whole note in Musescore and it works fine. I don't actually know how I would write the same thing using triplets.
Comment: Indeed. Forcing the first and third bars into two dotted minim beats isn't the most natural approach. It sounds like you're drawing the right conclusion about not letting purely visual cues take precedence. +1
Comment: Seeing as I cannot answer this now, I will add a comment, the grouping of bar 3 gives it away. If it was 6/4 the grouping would dictate two crotchets tied, no ties is trying to indicate minim beats, hence 3/2.
Answer: I get 3/2 in that the first and third measures indicate a pulse of a half note. The second measure looks like a 6/4 measure though. Thus 3/2 wins the election. Many pieces do have some measures that do not follow the usual conventions of the time signature. Examples would be "America" from "West Side Story" which alternates 3/4 and 6/8 (though it's regular in a two-measure grouping.) Often waltzes in 3/4 will have a pair of measure with the melody (and accompaniment) being three half-notes in a row.
Comment: I don't agree that the second bar looks like 6/4 any more than 3/2. It could be either. I have some music in front of me right now - In dir ist Freude BWV 615 - which is in 3/2 with bars just like the second. The choice here depends on whether the bar is in two or three. 6/4 is used for two in the bar, 3/2 is used for three in the bar.
Comment: The first and third bar have no note crossing the quarter-note beat. The second does. (Weak, but there's not much to go on from the score.) The fourth measure is consistent with either time signature.
Comment: I see, you are not counting 6/4 in two dotted half notes. That's up to you...
Comment: In 3/2 the second bar may have been written with a minim tied to a crotchet to give the picture of 3, but it appears that these days, (almost) anything goes!
Comment: I do Know That 3/2 is Three Half notes counted to a measure/ and unless there is something missing in the example neither looks to have a measure of Three half notes


Using sample sizes when combining z-scores

Question: What is the theoretical justification for using the square root of the sample size as the weight when combining z-scores in a meta-analysis?
Is this because the variance of the z-score is proportional to 1/n, where n is the sample size, so the inverse variance is proportional to n?
Answer: Let's look at the CLT. Its main issue is convergence in distribution. Rather than writing $Z=\frac{\bar{X}-\mu}{\sigma/\sqrt{n}}\sim\mathcal{N}(0,1)$, we can write $\frac{\bar{X}-\mu}{\sigma/\sqrt{n}}\xrightarrow{d}\mathcal{N}(0,1)$. The CLT has some variants, the Lindeberg–Lévy variant  states it in a slightly different manner: $\sqrt{n}(\bar{X}-\mu)\xrightarrow{d}\mathcal{N}(0,\sigma^2)$. This means that the difference between the average and the mean converges to the normal distribution $\mathcal{N}(0,\sigma^2)$ with rate $\sqrt{n}$.
For our needs, we can re-write the Lindeberg–Lévy variant as $\sqrt{n}\left(\frac{\bar{X}-\mu}{\sigma}\right)\xrightarrow{d}\mathcal{N}(0,1)$. That is, the statistic $\frac{\bar{X}-\mu}{\sigma}$ converges to the standard normal distribution $\mathcal{N}(0,1)$ with rate $\sqrt{n}$.
Why is this important? One can think of the rate of convergence as the speed of approaching $\mu$. Upon combining different variables (which depends on some theory like continuity conditions, Slutsky's theorem and the LLN), we need to make sure they have the same rate of convergence or otherwise the convergence of the sum doesn't hold.
Consider $Z_1=\frac{\bar{X}-\mu_X}{\sigma_X}$ and $Z_2=\frac{\bar{Y}-\mu_Y}{\sigma_Y}$. If they have the same convergence rate (say $\sqrt{n}$) then we can write something like $\sqrt{n}(Z_1+Z_2)\xrightarrow{d}\mathcal{N}(0,2)$. If they have different convergence rates, we cannot discuss the convergence of a combination.
This issue of rate of convergence (which in CLT is $\sqrt{n}$) is the reason for writing the square root of the sample size in z-scores. The rate of convergence is an important and nontrivial topic, you can read some more here and here.
Comment: The letter d means convergence in distribution
Comment: What does the letter d means?
Comment: "If they have different convergence rates, we cannot discuss the convergence of a combination." Convergence rate = sqrt(n). Do you mean if there if a different sample size, we cannot discuss the convergence of a combination? But in meta analysis, sample size of individual studies often differs. They will combine by sqrt(n).
Comment: different sample sizes don't mean they can't converge. $\sqrt{n_1}$ and $\sqrt{n_2}$ are both rates of $\sqrt{n}$. The problem is, for example, when one converges with rate $\sqrt{n}$ and the other with rate $n$.
Comment: This has nothing to do with the CLT.
Answer: Z-scores are estimates scaled by the estimated standard error of those estimates. Say we have two estimates from two samples $$Z_1 = \frac{\bar{X}_1}{\sigma\sqrt{n_1}} = \frac{1}{\sigma\sqrt{n_1}} \sum_{k=1}^{n_1} X_{1k} \\
Z_2 = \frac{\bar{X}_2}{\sigma\sqrt{n_2}} = \frac{1}{\sigma\sqrt{n_2}} \sum_{k=1}^{n_2} X_{2k} $$
where $\sigma$ is the error in the individual observations $X_{ik}$ (which for simplicity we assume as the same in both groups) and $n_1$ and $n_2$ are the sample sizes.
Here you see that if you would simply add $Z_1$ and $Z_2$ together with equal weights then the individual observations $X_{ik}$ do not get equal weights which is less efficient.
$$\sqrt{0.5} Z_1 + \sqrt{0.5} Z_1 = \sum_{i \in [1,2]} \sum_{k=1}^{n_i} \left( \frac{\sqrt{0.5}}{\sigma\sqrt{n_i}} X_{ik} \right)$$

The justification is that a weighted mean will have a smaller standard error, in comparison to an unweighted arithmetic mean. (From a different perspective the justification is a larger mean z-score instead of smaller standard error, see at the end)
This relates a bit to generalized least squares, and weighted least squares, which have the task to compute an estimate when the observed data points do not have equal variance/error.
What you are doing is computing an average which is a linear estimator and generalized least squares, which will use a weighted mean based on the variance of the individual terms, is the best linear unbiased estimator.

Example of a weighted mean having lower variance:
Example: If you have two observations distributed as
$$\bar{x}_1 \sim N(\mu, \sigma_1^2)\\
\bar{x}_2 \sim N(\mu, \sigma_2^2)$$
then the weighted mean (with weights $a_1+a_2=1$) will be distributed as
$$a_1 z_1 +a_2 z_2 \sim N(\mu, \sigma^2)$$
with the variance a weighted sum $$\sigma^2 = a_1^2 \sigma_1^2 + a_2^2 \sigma_2^2 = \sigma_1^2 -2 a_2 \sigma_1^2 + a_2^2 (\sigma_2^2+\sigma_1^2)$$
which has a minimum in $a_2 = \frac{\sigma_1^2}{\sigma_1^2+\sigma_2^2}$.

Intuitively:
Imagine you have a study with sample size 1000 and a study with sample size 10. The estimate from the latter study has a very large error. When you would average the results of both fifty-fifty then the propagation of error from the inaccurate study will count fifty percent and will lead to a large error in the end result.
The unweighted average of two numbers, one with small error and one with large error, will not have a small error but a medium error. So the average makes the situation worse (because you already had a number with a small error).

Is this because the variance of the z-score is proportional to 1/n, where n is the sample size, so the inverse variance is proportional to n?

The z-scores have variance 1, because they are normalised, but they have different means.
The z-score is roughly distributed as $N(\mu/\sqrt{n},1)$. Where $\mu$ is the population mean. If $\mu$ is non-zero then larger samples will have larger z-scores and that is why you want to give them a stronger weight.
So the comparison with GLS above, which is about different variance instead of different means is a bit twisted, but superficially the principle is related. If you compute the z-scores back to means of the population, then the GLS comparison counts and the goal is to get a linear sum that estimates the population mean and has the lowest variance possible (smaller variance means a larger z-score).
Comment: This has nothing to do with least squares
Comment: @Spätzle this has to do with computing an average which is a linear estimator (and unbiased if the individual z-scores are unbiased) and GLS is the best linear unbiased estimator.
Comment: @Spätzle, OP's question is about https://en.wikipedia.org/wiki/Inverse-variance_weighting ... " to minimize the variance of the weighted average."


How to add/subtract date in log4j 2?

Question: <code>i have following configuration file in log4j 2

<RollingFile name="RollingFile" fileName="logs/test.log"
        filePattern="logs$${date:yyyyMM}/app-%d{MM-dd-yyyy}.log">
                    <PatternLayout pattern="%d %-5p [%t] %C{4} (%F:%L) - %m%n"/>
                    <Policies>
                        <OnStartupTriggeringPolicy />
                        <SizeBasedTriggeringPolicy size="20 MB"/>
                    </Policies>
                    <DefaultRolloverStrategy fileIndex="max" max="100"/>
                </RollingFile>
</code>
can I perform date addition and/or subtraction in the filePattern. ? as of now the files generated upon rollover has current date. I would like to subtract single day from it . how can it be done ?
Answer: This is currently not possible, but I believe someone requested something similar earlier. I believe filing your request on the Log4j-2.0 issue tracker ( https://issues.apache.org/jira/browse/LOG4J2 ) may be the best way to proceed.

How to add/subtract date in log4j 2?


Move from one Fragment inside Activity to another Fragment inside Activity

Question: So I have Activity A with Fragment A.1, and I also have Activity B with Fragment B.1.
What I want to ask is, how do I move directly from Fragment A.1 to Fragment B.1?
I know to move from Fragment A.1 to Activity B, is by:
Intent i = new Intent (getActivity (), MainActivity.class);
startActivity (i);
getActivity ().finish();

But how to move straight to Fragment B.1?
Each Activity A and Activity B has a different <FrameLayout> for Fragment replacement

UPDATE 1.0

I've tried my own way and also the way @cewaphi answered with code like this,
In Activity A:
Intent i = new Intent(TransactionDone.this, MainActivity.class);
i.putExtra("immediatelyTransactionToFragment", true);
startActivity(i);
finishAffinity();

In Activity B:
boolean shouldTransitionToFragment = getIntent().getBooleanExtra("immediatelyTransationToFragment", true);
if (shouldTransitionToFragment) {
Fragment fragment = new Wallet();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.mainFrameLayout, fragment);
transaction.commit();
Log.d("DEBUGGING REDIRECT", "Go to Fragment B.1");
}

The log "Go to Fragment B.1" was created but the transaction doesn't work
Comment: you can pass a variable with intent if intent has that extra in it just load the fragment in second activity
Comment: if you want it, you must call your activity B which holds your Fragment B.1. There is no way you can directly call fragment as standalone according to my knowledge. You can do call Activity B and make sure to do your Fragment B.1 transaction in ActivtyB in oncCreate() using fragment transactions. In your use case easy solution to use fragment transaction with single activity and replace fragment inside ActivityA.
Comment: Is it really necessary to have multiple activities here? What you want to do becomes much easier when using the single activity approach in your app and especially when you are using the convenience of the [navigation component](https://developer.android.com/guide/navigation/navigation-migrate)
Comment: for your current approach: why do you not put an extra boolean in your intent when starting activity B from fragment A. 1? Then on receiving this boolean inside your activity B you move to fragment B. 1 after your activity has been created.  If not for this boolean from Fragment A1 you only move from activity B with your button click.  Is this the intended behavior?
Comment: So here is the first thing. Do you want activity B to launch with fragment B.1 while moving from your Activity A? If so I do not sure how to achieve, because to display your fragment B.1 UI, you must launch it inside any activity. So for your question, I need little clarification, 1-> Does your priority to just launch fragment B.1 or launch it with inside Activity B1?
Comment: @KP I'm assuming I'm in Fragment A.1 in Activity A, and yes I want to be able to move to Fragment B.1 in Activity B. My reason isn't just launching Fragment B.1, because in Fragment B.1 there are a lot of operations So maybe I need to not just launch?
Comment: @KP But... Fragment B.1 is now only accessible by click trigger in Activity B, it doesn't trigger automatically
Comment: @kelvin so I have to make logic in Activity B, if there is a value of 'example-value' then load Fragment B.1?
Comment: Yes . also why dont you replace Fragment A1 with fragment B1 inside Activity A .
Comment: so I am assuming your Activity B does have some views and also fragment tag? Clicking on views you want to hide views and display fragments? If you want to Acess Fragment B 1 from Activity B, you must call Activity B from your Activity A.
Comment: @cewaphi Yes I think so. but because this project is being worked on together, my other team worked on using 2 activities because they couldn't load the Webview responsively.
Comment: This problem should be easier to solve, when I only use one Activity which is used by all the Fragments. Thank you friend
Comment: If I may ask, why does another activity make the loading more responsive?
Comment: @cewaphi Yeah right, that's the approach I want. Talking about other Activities makes loading more responsive, these are just words from my team. I just tried before and there was no problem
Answer: When using a single activity and e.g. using the navigation component is not an option.
Consider the following:

In your fragment A.1 when starting the activity store a Boolean
i.putExtra("immediatelyTransationToFragment", true);

In activity B
shouldTransitionToFragment = getIntent().getBooleanExtra("immediatelyTransationToFragment");
// after activity was created
if (shouldTransitionToFragment) {
    // Execute the transition action as you would when pressing the button
}

Update 2020/09/07
You are trying to transition to a Fragment from your Activity like this:
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.mainFrameLayout, fragment);
transaction.commit();

The documentation states that you should first add the fragment to the activity:
ExampleFragment fragment = new ExampleFragment();
fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.commit();

Apparently your transition works when you click your button. Are you doing it the same?
But I assume at that time the activity has already been created.
Try once to add your fragment instead of replace. I don't know how your container is initialised but adding might be the operation you want, I refer to this good answer for clarification.
Also consider to perform to call this transaction after your activity was created.
Comment: Can this directly trigger Begin Transaction to Fragment B.1? I have tried "If the value of the getStringExtra() result is not empty, then Begin Transaction to Fragment B.1." But it doesn't work. I've written it in onCreate ()
Comment: Can you post the code how you try to transition to the fragment? If you do not have your `if` statement, does the transition (generally) not work?
Comment: To be honest, I am usually not conducting Fragment transactions manually anymore since I have switched to the convenience of the Navigation Component. I will update my answer accordingly for what I have noticed.
Comment: Yeah I thought so too, it's just a matter of time when I actually have to migrate using a navigation component. migrating all that current code would be very painful
Comment: By the way replacing `transaction.replace(R.id.mainFrameLayout, fragment);` with `fragmentTransaction.add(R.id.fragment_container, fragment);` doesn't solve the problem :(
Comment: I already assumed it wouldn't make a difference. How do you do it when you click the button? Does it work when you move after creating the activity (and not during creating it)?


Como exibir o conteúdo de uma fila?

Question: Digo isso, pois já criei a Fila:
    Queue<string> Fila = new Queue<string>();

Mas não consigo exibi-la,
    string Pedido = (("Cliente:") + Cliente + (Environment.NewLine + "Produto:") + Produto + (Environment.NewLine + "Tamanho:") + Tamanho + (Environment.NewLine + "Quantidade") + Quantidade);
        //Adiciona o pedido a memória

As outras variáveis acima são como esta:
    Cliente = Console.ReadLine(); //Insere na memória o que foi digitado pelo usuário.

Na minha tentativa para exibir o conteúdo da Fila,
    if (resp == "S") //se a resposta for sim, exibe mensagem de sucesso e pergunta se deseja adicionar outro pedido
        {
            Fila.Enqueue(Pedido);
            Console.Write("Pedido Registrado! Deseja adicionar outro pedido? (S/N)");
            resp = Console.ReadLine();
            if (resp == "S")
            {
                Pedido = "";
                if (resp == "Verificar Fila")
                {
                    Console.Write("Fila: " + Fila);
                }

            }

O que é exibido é:
    Fila.Collections.Generic.Queue`1[System.String]

Answer: Se quiser um modo mais compacto:
Console.WriteLine(String.Join(Environment.NewLine, fila));

O método estático String.Join une os itens de uma coleção com um caractere (nesse caso quebra de linha).
Veja fucionando aqui.
Comment: É, provavelmente isso é mais próximo do que ele quer mesmo.
Answer: Como Queue implementa IEnumerable, você pode iterar todos os elementos com foreach:
Queue<string> fila = new Queue<string>();

fila.Enqueue("Teste 1");
fila.Enqueue("Teste 2");
fila.Enqueue("Teste 3");

foreach(string pedido in fila) {
    Console.WriteLine(pedido);
}

http://ideone.com/asyiVi
Comment: Mas nesse caso, não iria imprimir o pedido e não a fila de pedidos?
Comment: O que você quer dizer com "imprimir a fila"? A fila é o conjunto do que tem nela.
Comment: Pois eu quero poder imprimir a fila, então no caso de adicionar outro pedido a fila posteriormente, imprimiria a fila toda (Pedido 1 + Pedido 2, etc)
Comment: Então, o `foreach` que eu estou sugerindo varre a fila toda e imprime os itens, um por vez. Com isso você monta a saída que você quer.
Comment: Editei o exemplo colocando mais itens na fila, veja: http://ideone.com/asyiVi
Comment: Mas considere que no caso, meu pedido é: string Pedido = (("Cliente:") + Cliente + (Environment.NewLine + "Produto:") + Produto + (Environment.NewLine + "Tamanho:") + Tamanho + (Environment.NewLine + "Quantidade") + Quantidade);
        //Adiciona o pedido a memória
Comment: E as variáveis Cliente, Produto, Tamanho, etc seguem o padrão:  Cliente = Console.ReadLine(); //Insere na memória o que foi digitado pelo usuário.
Comment: Vamos [continuar esta discussão no bate-papo](http://chat.stackexchange.com/rooms/24244/discussion-between-harison-and-bfavaretto).
Comment: @Harison Não pude continuar a discussão naquele momento. Mas a resposta do MarcusVinicius não resolve o seu problema?

Como exibir o conteúdo de uma fila?


Same CSS file generates under different folder when I flush

Question: A question from a newbie:
I am using a theme in my site and I made some changes in the CSS file.
The CSS file I am modifyiing is Style.XcVzbo5GbrB4v7QVES377fts6uudS0o0YbaMpBamvPg1.css
and it is in the folder: /sites/default/files/less/1TKupTVXZyLFbxdskTDq5OyCMsRMsIZmPQc_nx40j0Y/sites/all/themes/XXXXXX/less
So when I flush the caches, a new folder named randomly like above appears in
/sites/default/files/less/

with the unmodified version of my CSS file Style.XcVzbo5GbrB4v7QVES377fts6uudS0o0YbaMpBamvPg1.css in it.
Where is the source of this Style.XcVzbo5GbrB4v7QVES377fts6uudS0o0YbaMpBamvPg1.css so I can modify it for ever?
Answer: It's in a theme, module, library, Drupal's misc folder, or basically anywhere that the web server can read; that's as much as can really be said without more info.
To get that info, turn off css aggregation in Configuration -> Development -> Performance, then try inspecting the page again. Now you should see the original, unaggregated source file of the rule.
Bear in mind that if you're compiling Sass/Less to CSS, the file you find might not necessarily be the last place you need to look - it depends how the compilation actually happens in your application. But it gives you a good starting point at least.
Also bear in mind the nature of Cascading Style Sheets - if you introduce an identical rule with new styles after the original, it will take precedence. So as an alternative to tracking down the original, you could just add a new css file to your theme and give it an appropriate weight so it loads last and your styles "win".
Don't forget to switch aggregation on again afterwards if you need it.
Comment: Thanks a lot! I did some reading on CSS and added an extra stylesheet into my theme folder and made my changes in it. Now it's perfect!


Event ID 566 - Deleted Objects - Exchange Server

Question: Getting alot of these on one of the DCs security log:
*Event Type: Failure Audit
Event Source: Security
Event Category: Directory Service Access
Event ID: 566
Date:  27/01/2010
Time:  10:12:41
User:  Domain\Exchangeserver$
Computer: DC
Description:
Object Operation:
  Object Server: DS
  Operation Type: Object Access
  Object Type: container
  Object Name: CN=Deleted Objects,CN=Configuration,DC=Domain,DC=local
  Handle ID: -
  Primary User Name: DC$
  Primary Domain: Domain
  Primary Logon ID: (0x0,0x3E7)
  Client User Name: Exchangeserver$
  Client Domain: Domain
  Client Logon ID: (0x0,0x55A0BA34)
  Accesses: Read Property
Properties:

Default property set
   uSNChanged
  Public Information
   objectClass
 container
  Additional Info:
  Additional Info2:
  Access Mask: 0x10*
The only thing I've noticed is there are some plain SIDs showing in mailbox rights (ADUC) for some of our users which I can only assume are old users accounts that have now been deleted (Sid to user will not resolve). Not sure if it's related.
Any ideas?
Thanks
Answer: Based on some Googling after I encountered this, I found that there was a change in Windows 2003 that allowed attributes to be marked as confidential. I'm not sure if this applied to "uSNChanged."
One example result (a top Google hit):
http://www.eventid.net/display.asp?eventid=566&eventno=4015&source=Security&phase=1
Assuming this applies to your situation, you appear to have two options (quoted from the article linked above):

Set Directory Service Access Auditing to no auditing to remove the audit entries from the security event log.
In ADSIEDIT go into the SCHEMA partition - UnixUserPassword - under the attributes of search flags change from 128 to 0 then Force replication.

I didn't come across anything obviously more specific when looking for "event id 566" along with "uSNChanged." Adapt the instructions for the attributes in your situation.
There are lots of mentions of this elsewhere. I haven't sorted it out myself, but hopefully this helps your situation.
Comment: I did stumble across something similar and ended up disabling the auditing for directory server access. I don't believe Google was that helpful at the time!


"unlayout" a child view in View#onLayout when reusing views

Question: I have an Android View where I'm overriding onLayout(boolean changed, int l, int t, int r, int b). This view is bound to items in a list view so the view tends to get reused. For certain items, I childViewA.layout(l, t, r, b) and for other items, I don't. That is, child view A is only visible in some items. However, when I use this logic, child view A simply retains its position from its layout in the previous item. It doesn't disappear as expected just because we're not calling layout(l, t, r, b) in the current view bind. It stays as-is from the earlier bind. Anyone know why it works this way? I would assume each view is laid out afresh in each layout call and not just repositioned from the earlier layout call. Is my only way out to call setVisibility?
Sample method:
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
  if (condition) {
    childViewA.layout(l1, t1, r1, b1);
  }
  childViewB.layout(l2, t2, r2, b2);
  childViewC.layout(l3, t3, r3, b3);
}

Answer: Try this:
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
  if (condition) {
    childViewA.layout(l1, t1, r1, b1);
  }
  else{
    childViewA.layout(0, 0, 0, 0);
  }
  childViewB.layout(l2, t2, r2, b2);
  childViewC.layout(l3, t3, r3, b3);
}

The problem is that you aren't calling layout to childViewA at all when you DON'T want it to be there - so it keeps the old layout.