Passagem de parâmetro usando o " String[] args" declarado na main

Question: Estive procurando na documentação da Oracle, exemplos de cópias de arquivos, com seus atributos de diversas formas... Dentro dessa pesquisa me deparei com uma coisa estranha que foi a passagem de parâmetro que estava sendo feita, que era a variável "args" declarada como string na main
Segue o código para mostrar... Gostaria de saber o que está acontecendo e por que foi usado.
import java.nio.file.*;
import static java.nio.file.StandardCopyOption.*;
import java.nio.file.attribute.*;
import static java.nio.file.FileVisitResult.*;
import java.io.IOException;
import java.util.*;

/**
 * Sample code that copies files in a similar manner to the cp(1) program.
 */

public class Copy {

/**
 * Returns {@code true} if okay to overwrite a  file ("cp -i")
 */
static boolean okayToOverwrite(Path file) {
    String answer = System.console().readLine("overwrite %s (yes/no)? ", file);
    return (answer.equalsIgnoreCase("y") || answer.equalsIgnoreCase("yes"));
}

/**
 * Copy source file to target location. If {@code prompt} is true then
 * prompt user to overwrite target if it exists. The {@code preserve}
 * parameter determines if file attributes should be copied/preserved.
 */
static void copyFile(Path source, Path target, boolean prompt, boolean preserve) {
    CopyOption[] options = (preserve) ?
        new CopyOption[] { COPY_ATTRIBUTES, REPLACE_EXISTING } :
        new CopyOption[] { REPLACE_EXISTING };
    if (!prompt || Files.notExists(target) || okayToOverwrite(target)) {
        try {
            Files.copy(source, target, options);
        } catch (IOException x) {
            System.err.format("Unable to copy: %s: %s%n", source, x);
        }
    }
}

/**
 * A {@code FileVisitor} that copies a file-tree ("cp -r")
 */
static class TreeCopier implements FileVisitor<Path> {
    private final Path source;
    private final Path target;
    private final boolean prompt;
    private final boolean preserve;

    TreeCopier(Path source, Path target, boolean prompt, boolean preserve) {
        this.source = source;
        this.target = target;
        this.prompt = prompt;
        this.preserve = preserve;
    }

    @Override
    public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
        // before visiting entries in a directory we copy the directory
        // (okay if directory already exists).
        CopyOption[] options = (preserve) ?
            new CopyOption[] { COPY_ATTRIBUTES } : new CopyOption[0];

        Path newdir = target.resolve(source.relativize(dir));
        try {
            Files.copy(dir, newdir, options);
        } catch (FileAlreadyExistsException x) {
            // ignore
        } catch (IOException x) {
            System.err.format("Unable to create: %s: %s%n", newdir, x);
            return SKIP_SUBTREE;
        }
        return CONTINUE;
    }

    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
        copyFile(file, target.resolve(source.relativize(file)),
                 prompt, preserve);
        return CONTINUE;
    }

    @Override
    public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
        // fix up modification time of directory when done
        if (exc == null && preserve) {
            Path newdir = target.resolve(source.relativize(dir));
            try {
                FileTime time = Files.getLastModifiedTime(dir);
                Files.setLastModifiedTime(newdir, time);
            } catch (IOException x) {
                System.err.format("Unable to copy all attributes to: %s: %s%n", newdir, x);
            }
        }
        return CONTINUE;
    }

    @Override
    public FileVisitResult visitFileFailed(Path file, IOException exc) {
        if (exc instanceof FileSystemLoopException) {
            System.err.println("cycle detected: " + file);
        } else {
            System.err.format("Unable to copy: %s: %s%n", file, exc);
        }
        return CONTINUE;
    }
}

static void usage() {
    System.err.println("java Copy [-ip] source... target");
    System.err.println("java Copy -r [-ip] source-dir... target");
    System.exit(-1);
}

public static void main(String[] args) throws IOException {
    boolean recursive = false;
    boolean prompt = false;
    boolean preserve = false;

    // process options
    int argi = 0;
    while (argi < args.length) {
        String arg = args[argi];
        if (!arg.startsWith("-"))
            break;
        if (arg.length() < 2)
            usage();
        for (int i=1; i<arg.length(); i++) {
            char c = arg.charAt(i);
            switch (c) {
                case 'r' : recursive = true; break;
                case 'i' : prompt = true; break;
                case 'p' : preserve = true; break;
                default : usage();
            }
        }
        argi++;
    }

    // remaining arguments are the source files(s) and the target location
    int remaining = args.length - argi;
    if (remaining < 2)
        usage();
    Path[] source = new Path[remaining-1];
    int i=0;
    while (remaining > 1) {
        source[i++] = Paths.get(args[argi++]);
        remaining--;
    }
    Path target = Paths.get(args[argi]);

    // check if target is a directory
    boolean isDir = Files.isDirectory(target);

    // copy each source file/directory to target
    for (i=0; i<source.length; i++) {
        Path dest = (isDir) ? target.resolve(source[i].getFileName()) : target;

        if (recursive) {
            // follow links when copying files
            EnumSet<FileVisitOption> opts = EnumSet.of(FileVisitOption.FOLLOW_LINKS);
            TreeCopier tc = new TreeCopier(source[i], dest, prompt, preserve);
            Files.walkFileTree(source[i], opts, Integer.MAX_VALUE, tc);
        } else {
            // not recursive so source must not be a directory
            if (Files.isDirectory(source[i])) {
                System.err.format("%s: is a directory%n", source[i]);
                continue;
            }
            copyFile(source[i], dest, prompt, preserve);
        }
    }
}
}

Se notarem no trecho abaixo mostra a passagem, que estou falando, como é a primeira vez que vejo isso, gostaria de uma ajuda pra entender.
 public static void main(String[] args) throws IOException {
    boolean recursive = false;
    boolean prompt = false;
    boolean preserve = false;

    // process options
    int argi = 0;
    while (argi < args.length) {
        String arg = args[argi];
        if (!arg.startsWith("-"))
            break;
        if (arg.length() < 2)
            usage();
        for (int i=1; i<arg.length(); i++) {
            char c = arg.charAt(i);
            switch (c) {
                case 'r' : recursive = true; break;
                case 'i' : prompt = true; break;
                case 'p' : preserve = true; break;
                default : usage();
            }
        }
        argi++;
    }

Obrigado
Answer: Uma detalhe, String[] não é String, este simbolo [] significa que isto é uma "array" do tipo string. Ou seja ele carrega consigo um ou strings.
Por exemplo este código:
public class Exemplo {
    public static void main (String[] args) {
        for (String s: args) {
            System.out.println(s);
        }
    }
}

Se você chama-lo assim:

java Exemplo Foo Bar Ola Mundo

Ele irá retornar isto:

Foo
Bar
Ola
Mundo

Pois a cada espaço ele adicionou um item na "array", ou seja:

String a = "ola mundo"; é uma String.
String a[] = {"ola", "mundo"}; é um vetor de string, ou seja neste exemplo são dois arrays em um vetor.

Note que também existem arrays com outros tipos, como int[] que é um vetor (array) de números inteiros.
Veja que na documentação do java tem este trecho:

When an application is launched, the runtime system passes the command-line arguments to the application's main method via an array of Strings
Quando uma aplicação é executada, o sistema em tempo de execução passa os argumentos da linha de comando para o método main usando um array de Strings.
Comment: É esqueci de mencionar que se trata de um vetor de String não de apenas uma... Porém como se trata de um exemplo de cópia de arquivos e diretórios, foi aqui que veio a dúvida da comparação com o vetor de Strings ?
Comment: Então, é uma dúvida... Onde quero chegar é. Se este código faria a cópia de um determinado diretórios, subdiretórios e arquivos o que foi passado como parâmetro fica impossível de compilar... Tentei executar aqui e ele sempre cai no
metodo static void usage() {
    System.err.println("java Copy [-ip] source... target");
    System.err.println("java Copy -r [-ip] source-dir... target");
    System.exit(-1);
}

Mas não pega nem um diretório pra copiar...
Comment: @Valdecir Como você passou os argumentos? Vejo que a sua duvida não é sobre `string` ou `string[]`, por favor se puder editar a pergunta e explicar nela isto que acabou de me dizer pra deixar ela mais clara :) vou tentar compilar aqui.
Comment: @Valdecir Como você executou o java? `java Exemplo -r ...`?
Comment: OK... é que este exemplo é do javadoc, vai me ajudar muito entender o que se passa em cada método.

Vou editar aqui
Answer: Bom pessoal encontrei a resposta para essa pergunta... Na verdade esse vetor de String declarado na main quando passado como parâmetro, o "valor" tem que estar pré determinado antes da execução do programa, como se fosse apenas um .jar e seria compilado por linha de comando, então os parâmetro tem que ser apresentados junto com a execuão. Para conseguir usar no NetBeans eu segui os passos abaixo.

Após clicar em Personalizar...

Passei os parâmetros necessários pra meu programa funcionar.
OBS: Aumentei a memória do java para que fique um pouco mais rápida a cópia dos arquivos, e com isso ele copiou 26.2GB em 15 minutos 30 segundos.
Espero ter ajudado
Comment: Desculpe Valdecir, mas você realmente era o único que poderia encontrar a resposta, já que isto não é mencionado na pergunta, em nenhum momento na pergunta seria possível entender que o problema era com o copiar dos arquivos, recomendo que leia este link:  http://pt.stackoverflow.com/help/how-to-ask
Comment: Acredito que não... A verdade era que eu precisava de ajuda para fazer este código funcionar, e não estava entendendo o por que estava sendo passado o parâmetro "Caminho/Origem de cópia"... Como pode notar a cópia de arquivos já estava pronta apenas precisava executar o código.
Comment: Então amigo, foi justamente o que eu disse, você escreveu a "pergunta" de uma maneira que só você mesmo poderia responder, não de proposito, mas quem tenta lhe ajuda ao ler a sua pergunta fica sem entender ou entende outra coisa.


Makefile for kernel module

Question: Hi I am trying to write a 'Hello World' kernel module.
I wrote the following C code:
Module514.c
#include<linux/module.h>
#include<linux/kernel.h>
#include<linux/init.h>

MODULE_LICENSE("GPL");
MODULE_AUTHOR("BMC")
MODULE_DESCRIPTION(" My module]")

static int __init module514(void){
    printk(KERN_INFO"Hello World");
    return 0;
    }

static void __exit module514_cleanup(void){
    printk(KERN_INFO"unloaded")
    }

  module_init(module514);
  module_exit(module514_cleanup);

Then created the following Makefile
obj-m += Module514.o

all:
    make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules

clean:
    make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean

But when I give make I get the following message.
make: Nothing to be done for `all'.

What am I doing wrong.
Comment: Can you post output "make -n"?. Also you code will not compile, semi-colon ;  is missing
Comment: @Sasi Response for 'make -n' is the same "make: Nothing to be done for `all'.". Thanks corrected the code.
Answer: The problem here seems to have been caused by my Vim configuration. When I used TAB to indent the makefile spaces were getting inserted instead of TAB. Once I corrected this using a different editor all is going file.
PS: Also makefile need to be named with capital M = Makefile
Comment: http://stackoverflow.com/questions/24709389/error-in-generating-ko-file-for-simple-hello-world-module-for-linux-kernel/31968848#31968848

it's good to start with reading the kernel build process as given above

Makefile for kernel module


something errors were thrown out when I was testing the scikit-learn with nosetests

Question: I cannot find how to solve the problem like below. The mac is OS 10.10.3 and python is 2.7.6(the original one in mac). All the way to get the scikit-learn is so smooth except testing. I cannot understand the error at all...
failure is listed below:
======================================================================
FAIL: sklearn.feature_extraction.tests.test_image.test_connect_regions
Traceback (most recent call last):
  File "/Library/Python/2.7/site-packages/nose-1.3.6-py2.7.egg/nose/case.py", line 197, in runTest
    self.test(*self.arg)
  File "/Library/Python/2.7/site-packages/sklearn/feature_extraction/tests/test_image.py", line 63, in test_connect_regions
    assert_equal(ndimage.label(mask)[1], connected_components(graph)[0])
AssertionError: 777 != 767
======================================================================
FAIL: sklearn.feature_extraction.tests.test_image.test_connect_regions_with_grid
Traceback (most recent call last):
  File "/Library/Python/2.7/site-packages/nose-1.3.6-py2.7.egg/nose/case.py", line 197, in runTest
    self.test(*self.arg)
  File "/Library/Python/2.7/site-packages/sklearn/feature_extraction/tests/test_image.py", line 70, in test_connect_regions_with_grid
    assert_equal(ndimage.label(mask)[1], connected_components(graph)[0])
AssertionError: 777 != 767
Answer: This is caused by a bug in scipy. Upgrade scipy and it'll go away.


Targeting specific property for transition delay

Question: I am using the following CSS to animate features of a div. .shrink gets added to .header through Java
 .brand, .brand:visited, .brand:hover {
    display: block;
    position: relative;
    height: 100px; width: 100px;
    margin-top: 25px;
    background: url('img/logo.png') no-repeat center center;
    background-size: contain;
    border: 1px solid #fff;
    border-radius: 50%;
    -webkit-transition: height 0.35s ease, width 0.35s ease, margin 0.35s ease, border-color 0.35s ease;
    -moz-transition: height 0.35s ease, width 0.35s ease, margin 0.35s ease, border-color 0.35s ease;
    -ms-transition: height 0.35s ease, width 0.35s ease, margin 0.35s ease, border-color 0.35s ease;
    -o-transition: height 0.35s ease, width 0.35s ease, margin 0.35s ease, border-color 0.35s ease;
    transition: height 0.35s ease, width 0.35s ease, margin 0.35s ease, border-color 0.35s ease;
}

header.shrink .brand {
   margin: 0; padding: 0;
   height: 80px; width: 80px;
   border-color: transparent;
}

I want to put a 0.35s delay on JUST the border-color transition. Not sure the proper notation so that it wont affect all values.
ALSO, is there a way to only have the delay applied in one direction? Meaning that I would like the delay to be applied when the border shows up, but no delay when it goes transparent.
Comment: Just add the delay to the last one alone (that is, like `..., border-color 0.35s 0.35s ease`).
Comment: oh cool I didn't think it was that easy, I added an addition to my question
Answer: Question 1 - How to add a delay of 0.35s only to border-color property transition?
It is very simple. Just add a delay in the last part of the comma separated values that is provided to the transition property (that is, the one for border-color) alone. In the shorthand when two time values are provided, the first would be considered as the duration and the second as the delay.
transition: height 0.35s ease,
            width 0.35s ease,
            margin 0.35s ease,
            border-color 0.35s 0.35s ease; /* notice how the delay is added here alone */

Question 2 - How to add a delay only when border shows up (on hover)?
Again very simple, add two transition settings - one for the default selector and one for the :hover selector. In the one that is within :hover selector, add the delay because it applies when the border shows up and in the transition within the default selector do not provide any delay.

.brand {
  display: block;
  position: relative;
  margin: 0;
  padding: 0;
  height: 80px;
  width: 80px;
  background: url('http://lorempixel.com/100/100') no-repeat center center;
  background-size: contain;
  border: 1px solid transparent;
  border-radius: 50%;
  transition: height 0.35s ease, width 0.35s ease, margin 0.35s ease, border-color 0.35s ease;
}
.brand:hover {
  height: 100px;
  width: 100px;
  margin-top: 25px;
  border: 1px solid #f00;
  transition: height 0.35s ease, width 0.35s ease, margin 0.35s ease, border-color 0.35s 0.35s ease;
}


Problems with 10G networking under Linux

Question: We are currently encountering problems with different 10G network cards under linux.
I know that it's difficult to "solve" problems / answer questions like this but we are a bit helpless. So please be kind :-)
First we tried Intel 10G adapter (X*710). They worked fine until we saw "tx hang" in the kernel message log.
We tried everything. Newest firmware, newest kernel (4.19, 4.14. 4.20, 5.x), we used the kernel i40e driver and the one from intel. We searched the net, tried all the steps like disabling TSO or LRO. Nothing helped. The "tx hang" occurred multiple times a day. All connections are lost until the kernel watchdog restarts the connection. It takes about 1-2 minutes.
So we tried Mellanox cards. They do almost the same. After some hours all network adapter went down and up again. Just the kernel log messages are not there, maybe because the driver does not log that.
We tried all cards (4 of each manufacturer) on 3 different machines to exclude other hardware errors or bugs. We tried different SPF+ modules (also 8) and cabling (9) and other switches (2 large HP procurve).
Does anyone have any idea what to look for else?
Maybe some kernel config options (we use vanilla kernel which worked perfectly under 1G equipment)?
Some other hardware issue?
Comment: Post your full adapter configuration, including any `ethtool` or similar settings.  Note that if you are disabling autonegotiation, you are breaking the 10G standard.  Autonegotiation is a **required** part of gigabit and faster networking.  See http://noahdavids.org/self_published/gigabit-AN.html for cites to the IEEE 802.3 standard (not freely available)  See also http://www.ieee802.org/3/an/public/jul04/lynskey_2_0704.pdf documenting the requirement of the standard.
Comment: I think it's a driver/kernel bug similar problems were reported [https://sourceforge.net/p/e1000/bugs/583/](https://sourceforge.net/p/e1000/bugs/583/)
Answer: Recently I was working as a network/system engineer in a company that was massively using 10G network infrastructure, and like most of the experienced network engineers that started their career in the early 00s, I was sticking to Intel-manufactured network adapters, but in the processs of deploying 10G network infrastructure I encountered lots of issues, and I can summarize them below. I should also say that this is my personal experience, someone's else experience may vary radically.

there are several Intel 10G/40G chipsets and some of them are troublesome and some are not. For instance EoL X520 chipset is decent and we saw no problems with it in the production environment. We were using X520-DA2 adapters.
when it comes to X*710, there are several factors to consider:
there's X710 and XL710 chipset. X710 is used in 10G adapters, and XL710 is used in 40G adapters.
there are several sub-manufacturers of network adapters that ship tampered X710 adapters under their name, for example Supermicro. Avoid using these, they are badly designed and poorly supported. Intel NVM firmwares are incompatible with these, and Supermicro NVM images are hard to obtain, delayed in time, and Intel technical support refuses to support such adapters, stating that "these are not manufactured by us".
in the same time original, Intel-manufactured X710 adapters are decent, stable and cool, my former employer still has dozens of servers running original Intel-manufactured network adapters. However, we had to replace all of the Supermicro-tampered X710 ones.
disclaimer: personal opinion. XL710 chipset, regardless of the submanufacturer, is a dead one. I saw several unanswered bugreports, all stating the problem you are facing: complains from kernel about timeouts, adapters stopping working as soon as some considerable traffic appears on the wire and so on. Regardless of the OS used: Linux, FreeBSD, etc. Intel techsupport failed to solve these (typical thread). I have seen a non-official feedback from network engineers working for large enterprises and the feedback was the same: don't ever use the XL710 chipset in production (you can google those using "malicious driver detection event" as one of the patterns); they were trying to, but it was futile: they were proposing to use theis "proper" DAC-cables instead of the "generic ones", "proper" SFP+ trancievers instead of general ones (and since there are only 3-5 original SPF+ tranciever manufacturers, I doubt there would be any real difference). I can say that we switched to Mellanox 40G cards (Connect-X based ones) and its was okay since that (and that was the advice that my colleagues gave me; same thing about older Connect-X 10G chipsets). We didn't replace a single thing in the rest of the infrastructure: DAC cables/SFP+ trancievers stayed the same. This isn't a Mellanox ad, there are several vendors shipping 40G adapters - Chelsio, Solarflare, you can stick to any of them, all are reported to be working. Reason why we switched to Mellanox was trivial: lots of used adapters on the aftermarket.

As a potential solution I can say that you should try running latest NVM image on your cards, but I am very pessimistic about these. From my experience - these updates solve nothing. I also still have several adapters that after update stopped being recognized as Intel adapter that can be burned with a new version (however, they continued to "fuction").
Follow-up: as far as I can see, there is still some hope: according to this (sic ! notice the date !), some Linux distributions now have the patches needed. But, considering the amount of time passed since the original discovery of the problem (several years, jeez !) and the fact that Intel took almost no action to investigate/solve this issue from their side for major networked OS, I would conclude that XL710 is one of the biggest failures in the history of network ICs production. Keep up the good work, Intel.
Comment: THANK YOU SO MUCH for your effort. You helped me a lot.
Comment: Can you confirm or not that Mellanox MT27500 works with you?
Comment: Unfortunately, I cannot confirm these are okay since we have more recent MT27700 and MT26448 cards from ConnectX-4 and ConnectX-2. But I think yours are worth trying, it's previous ConnectX-3 generation, and I really think they will be okay (cannot guarantee though).
Comment: We successfully testet MT27500 with kernel 4.14 and it works like a charm.


Multiple linear regression: am I interpreting the methodology right?

Question: This is a follow-up question to 1 and 2. So we have the normal linear model
\begin{align*}
\textbf{Y} = \textbf{X}\beta + \epsilon
\end{align*}
where $\epsilon\sim\mathcal{N}(\textbf{0},\sigma^{2}\textbf{I})$, $\mu_{i} = \beta_{0} + \beta_{1}x_{i1} + \ldots + \beta_{p}x_{ip}$ and $\mu = \textbf{X}\beta$. As far as I have understood, we take $n$ observations
\begin{align*}
Y_{1} & = \beta_{0} + \beta_{1}x_{11} + \ldots + \beta_{p}x_{1p} + \epsilon_{1}\\
Y_{2} & = \beta_{0} + \beta_{1}x_{21} + \ldots + \beta_{p}x_{2p} + \epsilon_{2}\\
&\vdots\\
Y_{n} & = \beta_{0} + \beta_{1}x_{n1} + \ldots + \beta_{p}x_{np} + \epsilon_{n}\\
\end{align*}
and apply the least square method, for instance, to obtain $\hat{\beta} = (\textbf{X}^{T}\textbf{X})^{-1}\textbf{X}^{T}\textbf{Y}$.
The problem which concerns me is the interpretation of such process. Let us suppose, for example, that $Y$ represents the income, $x_{1}$ indicates the gender and $x_{2}$ stands for the age. Thus we draw someone from target population and obtain the first observation
\begin{align*}
Y_{1} = \beta_{0} + \beta_{1}x_{11} + \beta_{2}x_{12} + \epsilon_{1}
\end{align*}
After so, we draw another person (with replacement) from the target population and obtain the second observation
\begin{align*}
Y_{2} = \beta_{0} + \beta_{1}x_{21} + \beta_{2}x_{22} + \epsilon_{2}
\end{align*}
We repeat such process until $n$ observations are made. Once we have $\hat{\beta}$ at hand, we can estimate $\mu$ according to $\hat{\mu} = \textbf{X}\hat{\beta}$. Moreover, we can also estimate the variance $\sigma^{2}$ through the estimator
\begin{align*}
S^{2} = \frac{(\textbf{Y} - \textbf{X}\hat{\beta})^{T}(\textbf{Y} - \textbf{X}\hat{\beta})}{n-p-1}
\end{align*}
where it is assumed that $\operatorname{Rank}(\textbf{X}) = p+1$ and $\textbf{X}$ has full rank.
My first question is: am I describing the observation process rightly?
My second question is: how should we interpret the distribution $\textbf{Y} = \mathcal{N}(\textbf{X}\beta,\sigma^{2}\textbf{I})$?
The last question may be confusing me because, in the context of inference, we normally assume the sample consists in independent identically distributed random variables and in the multiple linear regression problem we just assume independence. In other words, the distribution of $\textbf{Y}$ corresponds to the distribution of the sample $(Y_{1},Y_{2},\ldots,Y_{n})$ and the means $\mu_{i}$ do not need to be the same. Is it correct?
Any help is appreciated. Thanks in advance!
Comment: The variance $\sigma^{2}$ refers to the distribution of $\textbf{Y}$, right? As to the hypothesis concerning the distribution of $\textbf{Y}$, each marginal is independent from the others, but they are not identically distributed. Am I reasoning correctly?
Comment: The variance is an *assumed, common* variance among all the $\epsilon_i.$  That's the only way you can justify the estimator $S^2.$
Comment: Thanks for the response but I am still concerned about my second question. What we are modeling is the sample distribution, where each $Y_{i}$ is independent from the others, but they are not equally distributed. At least that's the conclusion I've got.
Comment: That's correct: the $Y_i$ are not equally distributed.  Your account of that is very clear.  Their expectations vary, as given by $X\beta.$
Comment: Thank you very much! Just one more question: can we recover the distribution of $Y$ from the distribution of $\textbf{Y}$?
Comment: I cannot make sense of that question, because I understand your notation to mean $\mathbf{Y}$ is composed of the $Y_i$ as components.  What, then, could "$Y$" possibly mean?
Comment: In the inference context, if it is given a population whose distribution is given by $p(x|\theta)$, we make use of the likelihood function $$L(\textbf{x}|\theta) = \prod_{i=1}^{n}p(x_{i}|\theta)$$
in order to estimate the parameter $\theta$, from whence we get $\hat{\theta}(\textbf{x})$. Based on this, we can describe the population distribution using $\hat{\theta}$. I do not know if the analogy is valid, but here we have the population distribution $Y\sim\mathcal{N}(\mu,\sigma^{2})$, but what we determine is the distribution of the sample $\textbf{Y}$. Am I reasoning right?
Comment: You seem to be using "population distribution" in at least two different senses.  Moreover, "$Y\sim\mathcal{N}(\mu,\sigma^{2})$" does not describe the setting of your question.
Comment: I am just wondering. Maybe I am wrongly digressing. Anyway, I thought we could express the distribution of the income, as in the example I have proposed, based on the tools proposed by the multiple linear regression.
Comment: The first two-thirds of your post explicitly answers the second question.  The first question is almost tautological, but maybe what one could add is that this "observation process" is *one* of many ways where this multiple regression formulation is applicable.  For the last question, you have implicitly assumed more than you state at the point where you first refer to "the variance."  *What* is this the variance of?  Thinking about this ought to help you understand the answer.
Answer: Let us be explicit about what it is that you observe and what it is that you do not observe.
You observe $Y_i, x_{i1}, x_{i2}$ for $i=1,\ldots,n.$
You do not observe $\beta_0,$ $\beta_1,$ $\beta_2,$ or $\varepsilon_i.$
What you are calling $\widehat\mu_i$ is usually called $\widehat Y_i$ and is called the $i$th fitted value. It is the estimated expected value of a $Y$ value corresponding to the observed values of $x_{i1},x_{i2}.$ And as you say, the values of $\widehat Y_i$ for $i=1,\ldots,n$ in general differ from each other.
I don't understand what you mean by interpreting the distribution of $\textbf{Y} = \mathcal{N}(\textbf{X}\beta,\sigma^{2}\textbf{I}),$ but normally one writes
$$
\textbf{Y} \sim \mathcal{N}(\textbf{X}\beta,\sigma^{2}\textbf{I})
$$
rather than
$$
\textbf{Y} = \mathcal{N}(\textbf{X}\beta,\sigma^{2}\textbf{I}).
$$
One could say that for any measurable set $A\subseteq\mathbb R^n$ one has
\begin{align}
& \Pr(\textbf{Y}\in A) \\[10pt]
= {} & \frac 1 {\sqrt{(2\pi)^n\det(\sigma^2 \textbf{I})}} \\[8pt]
& {} \times \int\limits_A \exp\left( \frac{-1}2 (\textbf{y} - \textbf{X}\beta)^\top \left( \sigma^2 \textbf{I}\right)^{-1} ( \textbf{y} - \textbf{X}\beta) \right) \, d\textbf{y}
\end{align}
Comment: That's exactly my doubt: how do we interpret such integral?
Comment: @user1337 : I'm still not sure how to understand your last question. Maybe this will shed some light. One writes $\textbf{Y} \sim \operatorname N(\textbf{X}\beta, \sigma^2 I_n),$ but one could just as well write $\textbf{Y} = \textbf{X}\beta + \varepsilon$ and $\varepsilon \sim\operatorname N(0,\sigma^2 I_n).$ To say that $\varepsilon \sim\operatorname N(0,\sigma^2 I_n)$ means that the scalar components $\varepsilon_1,\ldots,\varepsilon_n$ are jointly normally distributed and each has expectation $0$ and variance $\sigma^2$ and the covariance between any two of them is $0. \qquad$
Comment: In the first place, thanks for the response. My question is: how should we interpret each marginal distribution? Does it give the distribution corresponding to each sampling?


Find series expansion of $f(x)=x^2\tan^{-1}(x^3)$

Question: I was requested  to find the power expansion of $f(x)=x^2\tan^{-1}(x^3)$ and, since I'm new to power series, was wondering if my procedure is correct. I explain it by parts.
$i)$ Consider the power expansion of $\frac{d}{dx} \tan^{-1}(x^3)$:
$$\frac{d}{dx}\tan^{-1}(x^3) = \frac{3x^2}{1+x^6} = 3x^2 \sum_{n=0}^\infty (-x^6)^n = \sum_{n=0}^\infty (-1)^n \space 3x^{6n+2}$$
$ii)$ Clearly,
$$f(x) = x^2\tan^{-1}(x^3) = x^2 \int \frac{d}{dx} \tan^{-1}(x^3) dx = x^2 \int \sum_{n=0}^\infty (-1)^n \space 3x^{6n+2}dx$$
due to step $i$.
$iii)$
$$f(x)=x^2\int\sum_{n=0}^\infty (-1)^n \space 3x^{6n+2}dx = x^2 \sum_{n=0}^\infty (-1)^n \space \frac{3x^{6n+3}}{6n+3} = \sum_{n=0}^\infty (-1)^n \space \frac{3x^{6n+5}}{6n+3} = \sum_{n=0}^\infty (-1)^n \space \frac{x^{6n+5}}{2n+1}$$
$$=\frac{x^{11}}{9}  - \frac{x^{17}}{15}  + \frac{x^{23}}{21}  - \frac{x^{29}}{27}  +...   $$
Note. The series convergence radius will be $|x^6| < 1 = (-1, 1)$
Is this solution correct? I tried checking with online series expansion calculators, but they seem incapable of handling the particular problem.
Comment: What level of rigor (in the sense of mathematical proof) are you required to use? If it's simply a matter of formal algebraic manipulation, then simply substitute $x^3$ for $x$ in the expansion for $\tan^{-1}x$ and then increase each of the resulting exponents of $x$ by $2.$ Regarding "I tried checking with online series expansion calculators", see [this WolframAlpha calculation](https://www.wolframalpha.com/input?i=series+%28x%5E2%29*%28arctan+%28x%5E3%29%29+at+x+%3D+0+to+order+20).
Comment: The **radius** of convergence is a number. The **region** of convergence is a set.
Comment: $-1^n$ is different from $(-1)^n$.
Comment: Also, you got the right series, but in the last step you miscalculated the first terms: $$\sum_{n=0}^\infty (-1)^n  \frac{x^{6n+5}}{2n+1}  \ne \frac{x^{11}}{9}  - \frac{x^{17}}{15}  + \frac{x^{23}}{21}  - \frac{x^{29}}{27}  +\cdots$$
Comment: It's not wrong but I feel that by differentiating $\tan^{-1} (x^3)$ instead of just $\tan^{-1}$ added complications. Instead you could substitute after you've integrated the series term by term in the same way you took care of the $x^2$ product after you expanded the series.
Answer: $$\tan^{-1} z= \sum_{k=0}^{\infty} (-1)^k \frac{z^{2k+1}}{2k+1}$$
So $$x^2\tan^{-1} x^3=\sum_{k=0}^{\infty} (-1)^k \frac{x^{6k+5}}{2k+1}.$$


How to render a Get Locations map programmatically?

Question: I'm using Get Locations module and the getlocations_fields submodule. I have a content type where I created a "Getlocations Fields" field, this way I can select locations when adding/editing content. I have multiple nodes which contain locations.
Now I would like to display one Get Locations map from given nodes (I have some node ids) programmatically. (I know there's Views integration, but I have a complicated task.)
What is the appropriate way to do this? I haven't found the right method yet, I don't know how Get Locations module's API works.

Hmm, maybe inspecting "A map in your own module" (https://drupal.org/node/2061951) and getlocations_fields_field_formatter_view() in getlocations_fields.module is a good start.
OK, I created a block output as per "A map in your own module". Now I need to collect the content of $latlons array. Do you know how to retrieve these data from entities with Get Locations API?
On admin/config/services/getlocations, you can configure different map markers for taxonomy terms if you "Enable Markers for Terms (Select Vocabularies enabled in a Term reference field)". I set a term reference field for my content type, and this way the NODE appears with the given marker. I would like to keep this behavior, "querying" the Get Locations field's data with markers for a given node, and display that appropriately. But I can't figure out how.
Answer: As per hutch's comment, and my experiments, I managed to solve it. I wrote it down here: https://drupal.org/node/2082137#comment-7832139.
I created a separate function for the task:
/**
 * Load a map from multiple node ids with the appropriate markers
 *
 * @param array $nids The node ids of the nodes you want to get displayed on the map.
 * @param array $getlocations_extra_settings Some extra settings you want to override the default values with.
 * @see https:// drupal.org/node/2082137
 * @todo Patch for getlocations_setlocations() to accept settings which override the defaults, or figure out an alternative solution.
 */
function getlocations_nodemap_multiple($nids = array(), $getlocations_extra_settings = array()) {

  $latlons = array();
  $minmaxes = array('minlat' => 0, 'minlon' => 0, 'maxlat' => 0, 'maxlon' => 0);
  $count_nids = 0;
  // override default settings
  $getlocations_settings = array_merge(getlocations_defaults(), $getlocations_extra_settings);
  $marker = $getlocations_settings['node_map_marker'];
  $typemarkers = getlocations_get_markertypes('node');

  foreach ($nids as $nid) {

    // maybe a less resource consuming method should be used
    // btw., what about entity_load()? (https://api.drupal.org/api/drupal/includes!common.inc/function/entity_load/7)
    $node = node_load($nid);
    $locations = getlocations_load_locations($node->vid);

    if (isset($typemarkers[$node->type]) && $typemarkers[$node->type]) {
      $marker = $typemarkers[$node->type];
    }

    if (count($locations)) {
      // we should loop over them and dump bummers with no lat/lon
      foreach ($locations AS $key => $location) {
        $latlon = getlocations_latlon_check($location['latitude'] . ',' . $location['longitude']);
        if ($latlon) {
          $minmaxes = getlocations_do_minmaxes($count_nids, $location, $minmaxes);

          if (!isset($location['key'])) {
            $location['key'] = '';
          }
          else {
            if ($location['key'] == 'nid') {
              $location['lid'] = $nid;
            }
            elseif ($location['key'] == 'vid') {
              // not vid?
              $location['lid'] = $nid;
            }
          }

          // term markers
          $marker = getlocations_get_term_marker($nid, $marker);

          // per location marker
          if (isset($location['marker']) && ! empty($location['marker'])) {
            $marker = $location['marker'];
          }

          $count_nids++;

          $name = htmlspecialchars_decode($location['name'] ? strip_tags($location['name']) : strip_tags($node->title), ENT_QUOTES);
          $latlons[] = array($location['latitude'], $location['longitude'], $location['lid'], $name, $marker, $location['key']);
        }
      }
    }
  }

  if ($count_nids < 2 ) {
    $minmaxes = NULL;
  }
  return getlocations_setlocations($latlons, $minmaxes);
}

And now I can call it like this:
function testmodule_any_custom_page_callback_you_want_to_use($blabla) {

  $output = '';

  $nids_array = array(41, 45, 52, 73, 219); // of course, this array is generated

  $getlocations_extra_settings = array();
  $getlocations_extra_settings['extcontrol'] = 'testmodule';
  $getlocations_extra_settings['fullscreen'] = 1;
  $getlocations_extra_settings['streetview_show'] = 1;
  $getlocations_extra_settings['maptype'] = 'Map';
  $getlocations_extra_settings['visual_refresh'] = 1;

  $output = getlocations_nodemap_multiple($nids_array, $getlocations_extra_settings);

  return $output;

}

This solution currently has its limitations, because unfortunately the default settings are hardcoded to getlocations_setlocations (the values of getlocations_defaults() are currently hardcoded). I hope hutch will develop this part further. :)


Sparse dot product in SQL

Question: Imagine I have a table which stores a series of sparse vectors.  A sparse vector means that it stores only the nonzero values explicitly in the data structure.  I could have a 1 million dimensional vector, but I only store the values for the dimensions which are nonzero.  So the size is proportional to the number of nonzero entries, not the dimensionality of the vector.
Table definition would be something like this:
vector_id : int
dimension : int
value : float
Now, in normal programming land I can compute the inner product or dot product of two vectors in O(|v1| + |v2|) time.  Basically the algorithm is to store the sparse vectors sorted by dimension and iterate through the dimensions in each until you find collisions between dimensions and multiply the values of the shared dimension and keep adding those up until you get to the end of either one of the vectors.
What's the fastest way to pull this off in SQL?
Answer: You should be able to replicate this algorithm in one query:
<code>select sum(v1.value * v2.value)
from vectors v1
inner join vectors v2
on v1.dimension = v2.dimension
where v1.vector_id = ...
and v2.vector_id = ...
</code>
Comment: So how would you index the table?  By (vector_id, dimension)?
Comment: Indexing by (vector_id, dimension) makes the most sense, since those should define a unique record in the table.
Comment: This is basically what I came up with -- until anyone else posts something faster I'll give it to you.  Thanks!

Sparse dot product in SQL


JQuery - Identificar texto automático

Question: Estou usando JQuery para identificar quando a caixa de texto há texto na caixa de texto, assim:
CSS:
.inputtext {
    border: 1px solid lightgrey;

    margin: 0;
    margin-top: 11pt;

    width: 100%;
}

.inputtext:focus {
    border: 1px solid green;
    box-shadow: 0 0 1px green;
}

.inputtext + span {
    font-size: 15pt;
    position: absolute;
    left: 15px;
    top: 18pt;
    color: grey;
    cursor: text;
    transition: all 200ms ease;
}

.inputtext:focus + span {
    font-size: 11pt;
    color: green;
    transform: translate(-10px,-18pt);
}

.inputtyped + span {
    font-size: 11pt;
    transform: translate(-10px,-18pt);
}

HTML:

    <input type="email" name="email" id="email" class="inputtext" required>
    Email

JQuery:
function typed() {
    var val = $(this).val();

    if (!val) {
        $(this).removeClass('inputtyped');
    } else {
        $(this).addClass('inputtyped');
    }
}

$(window).on('load', function () {
    $("input.inputtext").each(function (index, element) {
        $(element).change(typed);
        $(element).focus(typed);
        $(element).trigger('change');
    });
});

Funciona perfeitamente, assim:

Porém, quando o navegador preenche com o e-mail e senha salvos, o span não é ajustado:

Como posso resolver isso?
Comment: Cara vc pode resolver isso colocando no HTML autocomplete="off" no input, Nem sempre é a melhor solução, mas as vezes pode te atender... https://www.w3schools.com/tags/att_input_autocomplete.asp Faz um teste ai
Comment: @hugocsl pelo que eu entendi e olhei o exemplo, o `autocomplete="off"` irá desativar o autocomplete que acontece quando você começa a digitar, assim como as IDEs fazem. Não me ajuda nesse caso
Answer: Este problema do autocomplete é um pouco complicado de resolver pois varia de browser para browser e também nas diferentes versões destes.
O chrome por exemplo não dá indicação que está a preencher os campos quando lê a página
Uma possível solução será a seguinte:
$(window).on("load", function() {

    //Verifica alterações a cada 1 segundo (1000 millisegundos)
    var verificador = setInterval(function () {

        $("input.inputtext").each(function(index, element) {
        $(element).change(typed);
        $(element).focus(typed);
        $(element).trigger("change");
    });

    }, 1000);

});

Basicamente estamos a criar um temporizador que corre a cada 1 segundo (pode alterar o tempo a seu gosto) e verifica o campo.
Uma opção também é cancelar o temporizador depois alguns segundos para este não estar constantemente a executar:
clearInterval(verificador);

Ainda estou a investigar o assunto
Espero ter ajudado.
Cumprimentos
Answer: Não entendi o "põe o texto automaticamente". No mais, isso resolve?
function typed() {
  var val = $(this).val();

  if (! val) {
    $(this).removeClass('inputtyped');
  } else {
    $(this).addClass('inputtyped');
  }
}

$(window).on('load', function() {
  $('input.inputtext').each(function(index, element) {
    $(element).on('change', typed);
    $(element).on('focus', typed);

    typed.call(element);
  });
});

Comment: Não resolve pois o `typed()` usa o selector `$(this)`. "_põe o texto automaticamente_" se refere a quando o navegador salva o login, então ele preenche os campos de texto automaticamente.
Comment: Eu editei a minha resposta. Veja agora.
Comment: Ainda não funciona quando eu entro na página, mas se eu recarregá-la ou editar alguma coisa, funciona.
Comment: Isso é estranho. Sabe me dizer qual comportamento causa isso?
Comment: Não tenho ideia. É como se o `$(window).on('load')` só ocorresse quando há alguma alteração na tela

JQuery - Identificar texto automático


Is there any reason not to use 'protected' properties?

Question: Just wondering...
Is there any reasons not to use protected properties?
I mean instead of using this:
public abstract class Foo
{
    protected Bar { get; private set; }
}

to use this one:
public abstract class Foo
{
    private Bar _bar;

    protected Foo(Bar bar)
    {
        _bar = bar;
    }

    protected GetBar()
    {
        return _bar;
    }
}

Comment: The second one is perfectly valid Java; so if you see C# code like that, the most likely reason is that it has been written by a Java programmer who hasn't really accommodated to C# yet.
Comment: You use `protected` for accessibility, it has nothing to with properties.
Answer: I don't see any reason why you would use a GetXXX() method instead of a property regardless of it's modifiers.
Since you tagged this question with C# tag, I strictly recommend using the first approach. That is what properties are for.
Use a method only when value returned by it can be different every time you call it regardless of it's state. For example, DateTime.Now was a mistake and should have been a method.
For more details refer to Property Usage Guidelines on MSDN. On a side note, it's surprising how they haven't had a need to change it since Framework 1.1.
Comment: As mentioned above by ammoQ, this is probably either code ported from Java or a Java programmer's work - that's the standard in Java.
Comment: There is no requirement that a property should be idempotent. It should only be 'pure' with no side-effects.
Comment: @leppie: If you look at the guidelines, there is one in list when methods should be used that says `Calling the member twice in succession produces different results.`. Of course, it also mentions about having no side-effects.
Answer: A few more reasons to use properties instead of methods:

Data binding can only see properties
You can use read only or write only semantics.
Answer: Only if you have non-writable or non-readable Attributes inside the class
Answer: The question is not really about protected it has more with: why should I use properties?
Propeties are logically equivalent with Getter/Setter method pairs, whatever you can do with a with a Name {get{} \ set{}} you can do with a GetName() \ SetName() pair and vice versa, especially as C# has getter and setter accessors, so we can play with the accessibility too.
But, there are some folks that feel that public (or protected) properties are a bit like cheating from an OOP perspective, especially if all that the property does is just expose a backing field. After all person.Name = "SWeko" seems like it changes the state of the object externally, while person.SetName("SWeko") merely tells the object that it needs to change it's state. And from a purely theoretic standpoint I think that those objections have merit.
However, not all of us have the luxury of living in ivory towers, so the concept of properties is really usefull, as it's more readable, less error prone, and IMHO, closer to the real world model. It also provides us with a kind of dichotomy, when i write something like this:
person.Name = "SWeko";
person.Work();

I expect that the first line will a fast assignment, and will not have side-effects, while I expect that the second line will do something more, and probably affect the inner state of the object. When I use Getter and Setter method, no such distiction is immediately obvious:
person.SetName("SWeko");
person.Work();

Comment: IMHO, read-write properties should behave like variables.  If an object implements some read-write properties, writing them and then reading them in any order without any intervening *method calls* should cause them to read back the values written.  I have no problem with writable properties changing the values of read-only properties, or with method calls changing the values of any or all properties (read-only or read-write), but I dislike inter-connected read-write read-write properties. IMHO, something like StringBuilder.Length should be a read-only property, paired with a SetLength method.
Comment: @supercat This would get very tedious working with UI controls, as they tend to have lots and lots of properties that depend on each-other in a expected and logical way (e.g. AutoSize affects Width and Height properties).
Comment: @SWeko: A paradigm which I think is missing from parts of Forms, and which would help improve its utility, is the separation of "settings" properties from "current behavior".  For example, "Visible" should be split into "RequestedVisibility" and "IsShown".  "RequestedVisibility" should be a read-write property that would always return the value written; "IsShown" should be a read-only property indicating whether the control and all its parents have RequestedVisibility set.  For sizing, there should be requested-size and actual-size properties, the former read-write the latter read-only.
Comment: @SWeko: It could certainly be useful to have methods to copy the current state of an object to the "requested" state, and to have a means of invoking such methods from within the UI editor; I can accept that absent such a feature one may have to do somewhat ugly things with properties to make the UI editor work nicely.  Defining things as much as possible in terms of orthogonal properties, however, will help to avoid problems when serializing and unserializing objects.
Comment: @Supercat: Again, in theory, that approach has merit, as it will be a cleaner design, but does not match the expected (and quite real) human woldview. Not to mention that it would take a ton of code just to show your form.
Comment: @SWeko: Obviously the .net Forms class is what it is, but I would suggest that when designing a new class one should avoid having read-write properties that don't behave as orthogonal variables.  That doesn't mean one must absolutely reject any design in which read-write properties interact, but such designs should only be used in cases where an alternative form with orthogonal read-write properties would be demonstrably inferior.  As for "the expected world view"...
Comment: @SWeko: ...I would think it much less confusing for a control to have a read-write "RequestedSize" property (which would be unaffected by things like MultiLine) and a read-only "DisplayedSize" property, than to have a single "Size" property whose setter writes "RequestedSize" and whose reader fetches "DisplayedSize".  With such designs, the internal state of a control when a control or form is saved won't be accurately recreated when it's reloaded.  Whose "world view" is that supposed to match?


Pandas get percent value of groupby

Question: I have a pandas groupby that I've done
grouped = df.groupby(['name','type'])['count'].count().reset_index()

Looks like this:
name  type    count
x     a       32
x     b       1111
x     c       4214

What I need to do is take this and generate percentages, so i would get something like this (I realize the percentages are incorrect):
name  type  count
x     a     1%
x     b     49%
x     c     50%

I can think of some pseudocode that might make sense but I haven't been able to get anything that actually works...
something like
def getPercentage(df):
    for name in df:
        total = 0
        where df['name'] = name:
            total = total + df['count']
            type_percent = (df['type'] / total) * 100
            return type_percent

df.apply(getPercentage)

Is there a good way to do this with pandas?
Comment: Can you provide a short input sample and the output you'd expect given the sample?
Answer: Try:
df.loc[:,'grouped'] = df.groupby(['name','type'])['count'].count() / df.groupby(['name','type'])['count'].sum()

Answer: Any series can be normalized by just passing in an argument "normalize=False" as follows (it's cleaner than deviding by count):
Series.value_counts(normalize=True, sort=True, ascending=False)
So, it will be something like (which is a series, not a dataframe):
df['type'].value_counts(normalize=True) * 100

or, if you use groupby, you can simply do:
total = grouped['count'].sum()
grouped['count'] = grouped['count']/total * 100

Answer: Using crosstab + normalize
pd.crosstab(df.name,df.type,normalize='index').stack().reset_index()

Pandas get percent value of groupby


evaluate string with array php

Question: I have a string like
       "subscription link   :%list:subscription%
       unsubscription link :%list:unsubscription%
       ------- etc"

AND
I have an array like
    $variables['list']['subscription']='example.com/sub';
    $variables['list']['unsubscription']='example.com/unsub';
    ----------etc.

I need to replace %list:subscription% with $variables['list']['subscription'],And so on
here list is first index and  subscription is the second index from $variable
.Is possible to use eval() for this? I don't have any idea to do this,please help me
Answer: Str replace should work for most cases:
foreach($variables as $key_l1 => $value_l1)
    foreach($value_l1 as $key_l2 => $value_l2)
        $string = str_replace('%'.$key_l1.':'.$key_l2.'%', $value_l2, $string);

Eval forks a new PHP process which is resource intensive -- so unless you've got some serious work cut out for eval it's going to slow you down.
Besides the speed issue, evals can also be exploited if the origin of the code comes from the public users.
Answer: You could write the string to a file, enclosing the string in a function definition within the file, and give the file a .php extension.
Then you include the php file in your current module and call the function which will return the array.
Answer: I would use regular expression and do it like that:
$stringWithLinks = "";
$variables = array();

// your link pattern, in this case
// the i in the end makes it case insensitive
$pattern = '/%([a-z]+):([a-z]+)%/i';

$matches = array();

// https://www.php.net/manual/en/function.preg-replace-callback.php
$stringWithReplacedMarkers = preg_replace_callback(
    $pattern,
    function($mathces) {
        // important fact: $matches[0] contains the whole matched string
        return $variables[$mathces[1]][$mathces[2]];
    },
    $stringWithLinks);

You can obviously write the pattern right inside, I simply want to make it clearer. Check PHP manual for more regular expression possibilities. The method I used is here:
https://www.php.net/manual/en/function.preg-replace-callback.php

evaluate string with array php


Can we shift the diatonic scale "one fifth" to the left?

Question: The seven-note Pythagorean scale is obtain by completing the cycle of fifths until we get to the eighth fifth.
The diatonic scale is obtained by starting with the fourth and then running the cycle of fifths until we get to the eighth fifth. Contrary to the seven-note Pythagorean scale, the note corresponding to 1 is in second position in the cycle of fifths (whereas in the seven-note Pythagorean scale, it is in first position).
My question is, are there other seven-note musical scales, for example a seven-note musical scale that has the note corresponding to 1 in third position in the cycle of fifths?
Are they popular? Or do they exist just in theory but remain unused?
Comment: @niobium, I think you see that the series of P5 up from `C` ends on `F#` might seem to be in conflict with a `C` major scale. While that is not necessarily the case, you might be interested in George Russell and his Chromatic Lydian Concept. As I understand it, Russell felt that series made the lydian scale rather than the major scale the basis for harmony.
Comment: The definitions you give for the Pythagorean scale and for the diatonic scale are equivalent.  The question is therefore rather unclear.  Can you perhaps give an example of each kind of scale illustrating your understanding of the difference between them?  I mean, if you start on C and generate the Pythagorean scale using the procedure you describe, you get a scale with no F but an F sharp, so it's a G major scale, and we end up with the same scale that we would have gotten by using the "diatonic" procedure.
Comment: I am totally new to music theory, I may have misunderstood something. As far as I have understood, C D E F# G A B is one example of the seven-note Pythagorean scale (starting with C). C D E F G A B is one example of the diatonic scale starting with C.
Comment: Also, I think I understand your point. Thanks for the help
Answer: Your wording of the question is a little unclear.
You don't need to move by perfect fifths eight time to get seven tones, only six jumps by perfect fifth will give you seven tones. Also, I'm not sure what you mean by "shift". Probably you mean rotation of a scale, but it might also be understood to mean transpose.
Anyway, ascending perfect fifths, starting at C, and stopping at seven tones, will be...
C G D A E B F#
You can call that scale G major, C lydian, etc. depending on which tone you choose to be the tonic.
Depending on the meaning of shift we can do a number of things to that series of tones.
You can shift - extend a perfect fifth to the left, and the seven tones would become...
F C G D A E B
Or, if the tones are arranged by letter steps...
C D E F# G A B
...a diatonic shift to the left by fifth (diminished in this case) would be...
F# G A B C D E
On the other hand if you mean transpose a (perfect) fifth down, it would be...
F B A B C D E
You can do many procedure, but if the end result is seven tones that can be rearranged into a series of perfect fifths, then you will have a collection of diatonic tones, and the various way of ordering such a series by letter steps will have scale or mode names.
For details you can look up concepts like modes of the diatonic scale.


Measurable Subset of $(0,1)$

Question: Let $p$ be a prime number. If $x\in(0,1)$, we can write $x =\sum_{n=1}^{\infty} \dfrac{a_n}{p^n}$ with $a_i\in\{0,1,2,....,p-1\}$.
For each $k\in\mathbb{N}$,
define
$$E_k = \{ x \in (0,1) : x = \sum_{n=k+1}^{\infty} \dfrac{a_n}{p^n} , a_{k+1} \geq 1\}$$
I want to show that $E_k$ is measurable for each $k\in\mathbb{N}$.
I am stuck with this problem for quite some time now. Can anyone please help me with this? Thanks for any help.
Comment: $E_k=\left[\frac{a_{k+1}}{p^{k+1}},\frac{a_{k+1}+1}{p^{k+1}}\right) ?$
Comment: Tip: Make curly parentheses in MathJax by escaping them like so `\{1,2,3\}` (that produces $\{1,2,3\}$)
Comment: How are you getting this?
Answer: Hint:
$$\sum_{n=k+1}^{\infty}\frac{a_{k+1}}{p^n}$$ can be written as $$p^{-{k}}\sum_{j=1}^{\infty}\frac{b_j}{p^j} $$
(by just writing $b_j = a_{k+j}$).

Measurable Subset of $(0,1)$


How to switch rows in matrix L when decomposing matrix A into PA = LU?

Question:
Find the permutation matrix $P$, the lower triangular matrix $L$ and the upper triangular matrix $U$ such that $$ PA=LU $$
Given $$ A=  \begin{pmatrix} 1 & 2 & 3 & 4 & 5 & 6  \\ -2 & -3 & -4 & -5 & -6 & -7 \\ 3 & 7 & 11 & 16 & 21 & 27 \\ -4 & -5 & -5 & -5 & -5 & -5 \end{pmatrix}$$

I came this far
$$ U = \begin{pmatrix} 1 & 2 & 3 & 4 & 5 & 6  \\ 0 & 1 & 2 & 3 & 4 & 5 \\ 0 & 0 & 0 & 1 & 2 & 4 \\ 0 & 0 & 1 & 2 & 3 & 4 \end{pmatrix}$$
and
$$ L= \begin{pmatrix} 1 & 0 & 0 & 0   \\ -2 & 1 & 0 & 0  \\ 3 & 1 & 1 & 0  \\ -4 & 3 & 0 & 1 \end{pmatrix}$$
The last step I have to make is to change the fourth row with the third one but I do not know exactly how to change the entries in the lower triangular matrix L. Can anyone explain what exactly I have to switch in L?
Comment: @Moo If you think of the procedure as overwriting old variables, their $U$ isn't "finished" yet because it's not upper triangular, but the entry in the pivot position that they need to use to finish the elimination is zero, so an interchange is required. They're asking how to incorporate that interchange into $P$ and $L$.
Answer: Long answer: think of the result of forward elimination as being a matrix equation of the form $U=E_r P_r E_{r-1} P_{r-1} \dots E_1 P_1 A$ where $E_i$ are "elimination" matrices (clearing out the column below the $i$th pivot in the usual way) and $P_i$ are either permutation matrices that move the $i$th pivot into the $i$th row or else the identity (if you didn't do an exchange in that step). Elimination matrices are lower triangular, and stay that way when multiplied together. But when permutation matrices get included, they stop being lower triangular.
So now you generally want to invert that product of $E_i P_i$ to isolate $A$. If you keep them all together, the inverse won't be lower triangular, which in $PA=LU$ you want it to be. So what you do instead is you rewrite the product $E_r P_r \dots E_1 P_1$, so that all the permutation matrices are on the right and all elimination matrices are on the left. To do that, it suffices to figure out how to write $PE$ as $E' P'$.
This can be done with $P'=P$ and $E'=P E P^{-1} = P E P^T$, as is easy to check: $E' P'=P E P^{-1} P=PE$. This $E'$ taking this form is an instance of a common situation in algebra, where conjugation is used to apply an operation "in the context" of another, invertible operation having been applied already.
By doing that over and over again, you can move all the permutation matrices over to the right. The result looks like this:
$$U=E_r (P_r E_{r-1}^T P_r^T) \cdot  ((P_r P_{r-1}) E_{r-2} (P_r P_{r-1})^T) \cdot \dots \cdot ((P_r \dots P_2) E_1 (P_r \dots P_2)^T) \\
 \cdot P_r \cdot \dots \cdot P_1 \cdot A.$$
So now
$$L^{-1}=E_r (P_r E_{r-1} P_r^T) \cdot  ((P_r P_{r-1}) E_{r-2} (P_r P_{r-1})^T) \cdot \dots \cdot ((P_r \dots P_2) E_1 (P_r \dots P_2)^T)$$
What does this mean in a nutshell? It means that to get the correct $L^{-1}$, you have to move the nontrivial entries in your "computed $L^{-1}$" based on all the row exchanges that you did after those entries were computed. Inverting $L^{-1}$ at the end still works the same (you just flip the sign on the nontrivial entries).
Thus in your example, the effect of swapping rows $3$ and $4$ is that you update $L$ by exchanging the roles of indices $3$ and $4$, resulting in:
$$L=\begin{pmatrix}
1 & 0 & 0 & 0 \\
-2 & 1 & 0 & 0 \\
-4 & 3 & 1 & 0 \\
3 & 1 & 0 & 1
\end{pmatrix}.$$
Note that this is not the same as just exchanging row $3$ with row $4$.
After that you're done, in this particular example, but if you weren't, then you would not exchange $3$ with $4$ in subsequent steps.
Short answer: Your final matrix $P$ achieves all the row exchanges you did. To get $L$, each time you do a row exchange that would be achieved by multiplying on the left by a permutation matrix $P$, you replace your current $L$ with $P L P^T$, which means that you perform that permutation both on the rows and on the columns of your current $L$ (but not on the final $L$).
Comment: @Operator I don't really understand the question; are you talking about replacing row 2 by adding a multiple of row 4 to it? You can do that, but it would result in a $L_{2,4}$ entry, which wouldn't be allowed.
Comment: Thank you for the answer!
Comment: @Operator I actually summarized something incorrectly in the short answer (this is part of why I wanted to write the long answer in the first place, to make sure I had the logic straight). I've fixed it now.
Comment: I have a last question. I would like to know how the entry $L_{21}$ would look like if I did not use the following row operation $$ Row_2 + 2*Row_1 $$ instead if I used the following row operation $$ 2*Row_2  - Row_4$$ how would the entry $L_{21}$ look like now, if this row operation is legal regarding PA = LU?
Comment: Thank you for the answer!
Answer: Using row reduction, we arrived at
$$U = \begin{pmatrix} 1 & 2 & 3 & 4 & 5 & 6  \\ 0 & 1 & 2 & 3 & 4 & 5 \\ 0 & 0 & 0 & 1 & 2 & 4 \\ 0 & 0 & 1 & 2 & 3 & 4 \end{pmatrix}$$
As an alternate approach to the excellent write up by @Ian (+1), you could have reversed the row reduction steps, including the swap, as $$A = E_1^{-1}E_2^{-1}E_3^{-1}E_4^{-1}U$$
This results in
$$L = \begin{pmatrix} 1 & 0 & 0 & 0 \\ -2 & 1 & 0 & 0 \\ 3 & 1 &0 & 1 \\ -4 & 3 & 1 & 0 \end{pmatrix}$$
We see that $L$ is not lower triangular and we just need to swap row three and four, resulting in
$$L = \begin{pmatrix} 1 & 0 & 0 & 0 \\ -2 & 1 & 0 & 0  \\ -4 & 3 & 1 & 0 \\3 & 1 &0 & 1\end{pmatrix}$$
That swap requires a permutation matrix
$$P = \begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 &0 & 1 \\ 0 & 0 & 1 &0\end{pmatrix}$$
Now we can verify
$$PA = LU$$
You can also verify that $$A = PLU = P^T LU = P^{-1} LU$$
See, for example, How can LU factorization be used in non-square matrix?
Comment: Thank you for your answer as well!
Comment: I have a last question. I would like to know how the entry $L_{21}$ would look like if I did not use the following row operation $$ Row_2 + 2*Row_1 $$ instead if I used the following row operation $$ 2*Row_2  - Row_4$$ how would the entry $L_{21}$ look like now, if this row operation is legal regarding PA = LU?
Comment: Is that a legal row operation?


Site mult-lingua com expressões regulares

Question: Olá, pessoal, tudo bem?
Estou com um problema para fazer a identificação da página com a língua ao mesmo tempo. Só esta puxando o index com as línguas e as demais páginas não.
Esse é a expressão da url: main.php
$urlpatterns = array(
    '/' => 'index.php',
    '/(?P<lang>\S+)' => 'index.php',
    '/(?P<lang>\S+)/quem-somos' => 'quem-somos.php',
    '/(?P<lang>\S+)/contato' => 'contato.php'
);

E esse é a configuração do tradutor.php
if (isset($_GET['lang'])) {
    $lang = explode("/", $_GET['lang']);

    if ($lang[0] == "br") { $lang[0] = "br"; require_once ('br.php'); }
    if ($lang[0] == "en") { $lang[0] = "en"; require_once ('en.php'); }
    if ($lang[0] == "es") { $lang[0] = "es"; require_once ('es.php'); }

} elseif (!isset($_GET['lang'])) {
    require_once ('br.php');
}

Na URL fica dessa maneira:
meusite.com.br/br ou meusite.com.br/br/
Porém só busca a página inicial, quando busco por meusite.com.br/br/quem-somos ou meusite.com.br/en/quem-somos, não busca.
Alguém poderia me ajudar?
Se eu formatar tudo no tradutor.php, as expressões serão ignoradas no main.php?
Comment: Bom, sua expressão para o idioma é `(?P\S+)`, que basicamente é qualquer sequência com um ou mais caracteres que não são espaços em branco. A URL `/en/quem-somos` é uma sequência de mais de um caractere que não são espaços em branco, logo o arquivo exibido deve ser `index.php`?
Comment: @AndersonCarlosWoss Entendi. O que eu devo retirar dessa minha expressão para funcionar? Pra identificar o en separado de quem-somos: en**/**quem somos?
Comment: Indicando que `lang` não deve possuir `/` no valor, por exemplo, `(?P[^/]+)`. Isso definirá "lang" como qualquer sequência de um ou mais caracteres que não são a barra. Você pode editar a expressão para ignorar outros caracteres também se desejado.
Comment: Quando uso essa forma acaba dando erro aqui no meu código na linha do preg_match():

`
function url_response($urlpatterns) {
  foreach ($urlpatterns as $pcre => $app) {
    if(preg_match("@^{$pcre}$@", REQUEST_URI, $_GET)) {
      include(APPLICATION_DIR.'/'.$app);
      exit();
    } else {
      $erro = true;
    }
  }
  if(isset($erro) && $erro == true){
    include("app/404.php");
  }
  return;
}
`
Comment: Que erro seria esse?
Comment: Deu certo eu acabei tirando um parenteses na minha edição. Funcionou como esperei.
Obrigado pela ajuda!!!!!!
Answer: O problema está na expressão regular que está utilizando. Você definiu lang como (?P<lang>\S+), porém o \S casa com qualquer caractere diferente dos espaços em branco (' ', \n, \t, etc).
Assim, a URL /en/quem-somos acaba sendo interpretada inteiramente como lang e a página exibida será a index.php, pois você definiu isso:
'/(?P<lang>\S+)' => 'index.php'

Como está definindo que lang será um elemento do path, o ideal é que você delimite seu valor com o caractere delimitador do path: a barra, /. Para isso, uma forma de implementar seria definir que lang pode ser qualquer coisa exceto a barra:
(?P<lang>[^/]+)

E, desta forma, apenas en será considerado lang na URL /en/quem-somos.
Comment: Boa tarde!!! Funcionou perfeitamente!!!!!
Obrigado pela disposição e pela ajuda.


Suggest good UI framework for react-native app. I used expo to create project

Question: i need some good ui components library for react-native like react material ui for react web applications
Please suggest a library that you have used in you projects
Answer: React Native Elements
As a cross-platform UI Toolkit, you can now use RNE on the web & share your codebase between your React Native + React web apps.
View
Nativebase
Essential cross-platform UI components for React Native & Vue Native
View
React Native Material UI
Highly customizable material design components for React Native.
View
UI Kitten
React Native framework for creating stunning cross-platform mobile applications. Design system based brings your product from MVP to enterprise. Forever Open Source and free.
View
React Native UI Lib
View


How to get properties for multiple users using Get-ADUser

Question: I was trying to get info on multiple users using Get-ADUser but it doesn't like it. Can someone provide a tip on how to do this? Many Thanks
Get-ADUser -Identity jdoe, jsmith, adoe, bdoe, cdoe -Properties  CN, SamAccountName ,passwordlastset, passwordneverexpires | select  SamAccountName, passwordlastset, passwordneverexpires

Answer: As indicated by the cmdlet help, Identity does not accept an array of input:
Get-ADUser [-Identity] <ADUser> [-AuthType {Negotiate | Basic}] [-Credential <pscredential>]
   [-Partition <string>] [-Properties <string[]>] [-Server <string>]  [<CommonParameters>]

So, you can loop over an array of input:
'jdoe','jsmith','adoe','bdoe','cdoe' | ForEach-Object {
     Get-AdUser -Identity $_ -Properties PasswordLastSet,PasswordNeverExpires}

Or you can run against an entire OU:
Get-AdUser -Filter * -SearchBase "OU=Users,DC=ad,DC=domain,DC=com" -SearchScope Subtree

Or construct an appropriate LDAPFilter
Get-AdUser -LDAPFilter '(|(sAMAccountName=*doe)(sAMAccountName=jsmith))'

Or any number of other ways.  But your best bet is always the help.  If you don't have it downloaded, there's always:
 Get-Help Get-AdUser -Online

You should be able to find examples, if not, these should give you an idea of where to start: https://docs.microsoft.com/en-us/powershell/module/activedirectory/get-aduser?view=winserver2012-ps&redirectedfrom=MSDN#examples
Comment: Thanks for the tips, I appreciate it!
Answer: You can run it against multiple users by doing:
@('user1','user2','etc') | get-aduser | select-object Name

Answer: This command will get you all the properties of the user
Get-ADUser usernamehere -Properties * | Select-Object name,office

you can add the Select object to define the information you want to see
Get-ADUser usernamehere -Properties *  | Select-Object name,office

Comment: I used a poweshell script that users a CSVfile with the attributes I want to retrieve, $OU = "OU=ouname External Users,DC=corp,DC=name-group,DC=com"

$CSVname = "C:\Users\myaccount\Documents\UKOUusers.csv"
#Import-Module ActiveDirectory #Imports AD module

Get-ADUser -SearchBase $OU -Filter * -Properties GivenName,Surname,EmailAddress,Department,Manager,Office| Select GivenName,Surname,EmailAddress,Department,Manager,Office| Export-Csv $csvname


How to evaluate the definite integral $\int_0^{a/2 }x^2(a^2-x^2)^{-3/2}dx $

Question:
$$\int_0^{a/2}x^2(a^2-x^2)^{-3/2}dx $$

I've been having trouble with this question for a while now. When I attempted the question I substituted $x=a\sin\theta$ and $(a\cos\theta)^3=(a^2-x^2)^{-3/2}$.
When I solved with the substitutions what I get at the end is $\tan^2\theta$ in the integral sign. So I integrated $\sec^2\theta-1$ and got an answer which is different to the real answer. And when I checked an online integral calculator the top $x^2$ was split into $x^2-a^2+a^2$ to make two fractions. which didn't make sense to me at all because somewhere along that line the $x^2$ itself was completely removed. The online calculator is www.integral-calculator.com
I learned trigonometric substitution last night and I am not very good at it. So a detailed explanation would be very much appreciated.
Answer: Hint: Using substitution $x=a\sin t$ then
$$\int_0^{\frac{a}{2}}\dfrac{x^2}{\sqrt{a^2-x^2}^3}dx=\int_0^{\pi/6}\tan^2t\ dt$$
Comment: That's exactly what i did, I then expressed tan^2t as sec^2t-1 and got the answer X/(a^2-x^2)-arcsin(x/a)+c. but when i tried to solve it for a/2 and 0, it didn't work out.
Comment: I couldn't read your notes. It's better to write them with mathjax. anyway, $$\int \tan^2t+1-1\ dt=\tan t-t\Big|_0^{\pi/6}$$ it's a number!
Comment: I'll have to learn how to use mathjax, thanks. And also what i meant was that's exactly the answer i got, but when i re substitute the original values and calculate, The final answer is wrong.
Comment: What's te final answer ?
Comment: What I did was, after re-substituting, I used the same limits as were originally given a/2 and 0. The answer should be 1/sqrt3 - pi/6. but i couldn't get this.
Comment: It's the answer that you find in last integral: $$\tan t-t\Big|_0^{\pi/6}=\tan{\pi/6}-{\pi/6}-0=\dfrac{1}{\sqrt3}-\dfrac{\pi}{6}$$
Comment: and without bounds
$$\int\dfrac{x^2}{\sqrt{a^2-x^2}^3}dx=\int\tan^2t\ dt=\tan t-t=\dfrac{\sin t}{\cos t}-t=\dfrac{x/a}{\sqrt{1-(x/a)^2}}-\arcsin\dfrac{x}{a}=\dfrac{x}{\sqrt{a^2-x^2}}-\arcsin\dfrac{x}{a}+C$$
Comment: thank you so much, turns out my integration was correct, my substitution was wrong. But it's all good now :)
Comment: you are welcome.
Answer: Hint:
How about integration by parts
$$\int x\cdot\dfrac x{(a^2-x^2)^{3/2}}dx=x\int\dfrac x{(a^2-x^2)^{3/2}}dx-\int\left(\dfrac{dx}{dx}\int\dfrac x{(a^2-x^2)^{3/2}}dx\right)dx$$
Now choose $\sqrt{a^2-x^2}=y$


Restrict Menu Item Visibility by Permissions

Question: I have a module-generated menu (using yaml file) with 5 menu items. My requirements don't allow me to restrict menu item visibility by role because roles can be dynamically added. So I have to do this using permissions only.
What I've tried
(1) Restricting menu item access using route permissions - this shows a page forbidden but still allows the restricted menu item to be visible
Please see my actual files below:
portal_hrm_core.links.menu.yml
portal_hrm_core.hrm_link:
  title: 'HR Manager'
  route_name: portal_hrm_core.hrm_link
  menu_name: hcm
  expanded: TRUE

portal_hrm_core.routing.yml
portal_hrm_core. hrm_link:
path: '/admin/hrm'
defaults:
  _controller: '\Drupal... systemAdminMenuBlockPage'
  _title: 'HRM'
requirements:
  _permission: 'access hrm_core_job+access_hrm_core_employee'

(2) Contrib modules - Menu Item Visibility and Menu Item Per Role
Both of these are only role-based and can't support permissions
I know I can go really low-level and use something like hook_preprocess_menu but seems to heavy for such a simple requirement considering how many times that hook may be called.
So folks, please any further suggestions?
Thanks
Comment: AFAIK point (1) is correct and should also hide menu items (using that method in my own projects). Menus are heavily cached, have you cleared cache after adding route permissions?
Comment: Hudri - your quick reply has strongly encouraged me! Thanks. Please I've updated the original question with my source files for your review. And I cleared the cache using both ```devel menu ui``` and ```drush cr```. Still this menu item remains visible no matter the permissions, and I'm not logged in as admin.
Comment: This is almost exactly the same I'm doing, I just don't have that `expanded: true` key in my files, don't know that key. I also have an additional `options: _admin_route: TRUE` in my `routing.yml` files, because I only need that for pages with admin theme.
Answer: Works now. Thanks Hudri for pointing me in the right direction. I re-checked your suggestion about clearing the cache. In the process I discovered that the following line was commented out in my lazyBuilder() method (these menu items are in my toolbar and are generated in code)
$manipulators = [
  ['callable' => 'menu.default_tree_manipulators:checkAccess']
]

The absence of those lines were causing my menu to ignore access checks, apparently. Uncommenting them out solved the problem. Thanks.


Adding a Yes or No to delete option on a batch script

Question: I have wrote this script and I was wounder if I can have it do like Y for Delete and N for not deleting the files but I am not sure how to go about adding that.
@ECHO OFF
SETLOCAL EnableDelayedExpansion

REM Set variables
SET SOURCE=C:\My Recordings
SET DEST=\\XXXXXXXX\c$\VideoArchive
SET 7ZIP=C:\Program Files\7-Zip\7z.exe

REM Compress local files with 7zip
ECHO ---------------------------------------------------------
ECHO    BEGINNING VIDEO COMPRESSION OPERATIONS
ECHO ---------------------------------------------------------
CD /D "%SOURCE%"
FOR %%f in ("*.wrf") DO (
    SET FILENAME=%%~nf
    ECHO Compressing !FILENAME!
    "!7ZIP!" a -t7z -aoa "!FILENAME!.7z" "%%f"
)

REM Copy compressed files
ECHO ---------------------------------------------------------
ECHO    COMPRESSION COMPLETE - BEGINNING COPY OPERATIONS
ECHO ---------------------------------------------------------
for /F "usebackq delims=" %%a in (`dir /b "%SOURCE%\*.7z"`) do (
    SET CURRENT_FILE=%%a
    SET CURRENT_FILE_NO_EXTENSION=%%~na

    REM Extract the month.
    for /F "usebackq tokens=3 delims=-" %%i in ('!CURRENT_FILE!') do (
        SET CURRENT_FILE_DATE=%%i
        SET FILE_MONTH=!CURRENT_FILE_DATE:~5,2!
        SET MONTH_DEST=!DEST!\!FILE_MONTH!
    )

    XCOPY "%SOURCE%\!CURRENT_FILE!" "!MONTH_DEST!\" /Y /V /I /R

    REM Confirm successful copy, then delete original
    IF !ERRORLEVEL! EQU 0 (
        ECHO Copy Operation Successful. Removing Original...
        DEL /Q "%SOURCE%\!CURRENT_FILE_NO_EXTENSION!.wrf"
        DEL /Q "%SOURCE%\!CURRENT_FILE!"
    )ELSE (
        ECHO Error while copying "%SOURCE%\!CURRENT_FILE!.
    )
)

That is my code if anyone could help that would be great.
Answer: Use choice, and act on the response.
To offer the user the option "Delete files? yn", use
choice /c yn /n /m "Delete files?"

ERRORLEVEL will contain the index of the value selected (for instance, in the example above, 1 if Y was pressed, 2 for N'). Your batch file can then checkERRORLEVEL` and react accordingly.
While other answers mention the /y parameter to del, choice is generic and can be used with any batch file for any reason.
Answer: set /p DELETE=Delete [y/n]?
if !DELETE! == y (
    ...
)


Data set generator

Question: I'd like to ask if someone knows a good data set generator for multi-target/Multivariate regression
All the best
Richard
Comment: A starting point would be to try the $data()$ command in R.
Answer: An easy way to generate data that's appropriate for multivariate regression is to draw random variates from a multivariate distribution, such as the multivariate normal distribution. Just write the mean vector as a function of your covariates. Sampling from a multivariate normal distribution can be done with, for example, numpy.random.multivariate_normal in Python or MASS::mvrnorm in R.

Data set generator


mocking private variables in a function for testing Junit4

Question: I am writing a Junit4 test for a function which has Boolean variables which are set based on other functions. How can I mock these Boolean variable in my test case.
The function I am testing
private var operatorSigned = false
private var engineerSigned = false

override fun onValidationSucceeded() {
    if (operatorSigned && engineerSigned) {
        sendQualityControlCheck()
    } else {
        view.showToastMessage(app.getString(R.string.quality_control_signatures_not_complete))
    }
}

This is how the values are set
override fun signatureSigned(name: String, svgSignature: String, bitmapSignature: Bitmap, signatureType: SignatureType) {
    val svgSignatureGzipped = CompressionTools.gzipCompress(svgSignature)
    when (signatureType) {
        SignatureType.OPERATOR -> {
            operatorSignature = QualityControlSignature(svgSignatureGzipped, DateTime())
            operatorSigned = true
            view.operatorSignatureSigned()
        }
        SignatureType.ENGINEER -> {
            engineerSignature = QualityControlSignature(svgSignatureGzipped, DateTime())
            engineerSigned = true
            engineerName = name
            view.engineerSignatureSigned()
        }
    }
}

My test case
@Test
fun `must show toast message when onValidationSucceeded is called and operatorSigned is false`() {
    `when`(app.getString(R.string.quality_control_signatures_not_complete)).thenReturn("Operator and Engineer signature required")
    presenter.onValidationSucceeded()
    verify(view).showToastMessage("Operator and Engineer signature required")
}

I want to be able to change values on operatorSigned and engineerSigned how can I do that.
Comment: To me this seems like a class design problem. If you have you signature code as its own class and inject it in, it might be easier to test
Comment: How are they set? In the code you have posted they are always `false`. (i.e. if they are set in other functions, then call the other functions to set them).
Comment: but they are based on too many other parameters
Comment: updated my question
Comment: Don't try to test "the code". Unittests verify the *public observable* **desired behavior** of the code.
Answer: Let's pretend the OPERATOR path of your code sets these booleans to false:
@Test
fun `must show toast message when onValidationSucceeded is called and signature is Operator`() {
    // Given
    signatureSigned("unusedName", "unusedSig", null, SignatureType.OPERATOR)
`when`(app.getString(R.string.quality_control_signatures_not_complete)).thenReturn("Operator and Engineer signature required")
    // When
    presenter.onValidationSucceeded()
    // Then
    verify(view).showToastMessage("Operator and Engineer signature required")
}

(had to pretend because right now the code you shared only ever sets the booleans to true).
You are now unit testing the classes behaviour not testing how that behaviour is coded. For example, now if those booleans where refactored out for an Int value. This test would still pass without you having to touch it, that is a good thing!

Or if your code stays as is. You can test like this:
@Test
fun `must show toast message when onValidationSucceeded is called and has not been signature signed`() {
    // Given
    // We haven't signature signed (see verify)
   `when`(app.getString(R.string.quality_control_signatures_not_complete)).thenReturn("Operator and Engineer signature required")
    // When
    presenter.onValidationSucceeded()
    // Then
    verify(view).showToastMessage("Operator and Engineer signature required")
    verify(view, never()).operatorSignatureSigned()
    verify(view, never()).engineerSignatureSigned()
}

How to mock a static method (hint you don't, you move it to the edge of your system and worry about it later).
Your class right now:
class MyClass {

    override fun signatureSigned(name: String, svgSignature: String, bitmapSignature: Bitmap, signatureType: SignatureType) {
        val svgSignatureGzipped = CompressionTools.gzipCompress(svgSignature)
        ...
    }

}

So you need to remove the static call, for another class that can do the static call as a dependency.
interface SignatureCompressor {
    fun compress(signature: String)
}

class GZipSignatureCompressor : SignatureCompressor {
    override fun compress(signature: String) {
        return CompressionTools.gzipCompress(signature)
    }
}

Now your class becomes:
class MyClass(private val compressor: SignatureCompressor) {

    override fun signatureSigned(name: String, svgSignature: String, bitmapSignature: Bitmap, signatureType: SignatureType) {
        val svgSignatureGzipped = compressor.compress(svgSignature)
        ...
    }

}

and you can mock the compressor:
 val cut = MyClass(mockk())

You also don't need the interface if you only have one implementation of compressing
Comment: thank you that is a perfect Idea but one question, in signatureSigned function how can i mock val svgSignatureGzipped = CompressionTools.gzipCompress(svgSignature) it gives me an error that svgSignatureGzipped is null
Comment: Wrap the static method call into a Class `GZipCompressor` or something, then pass this as a dependency of the class.
Comment: did not understand how to do that sorry
Comment: I'll add it to the answer


Extended class calling function that should not be inherited

Question: i have following problem:
I've made a simple android app that adds 1 to an integer every 1000 ms using a handler, and then display this integer.
The problem is that when i start another activity the same thing happens, which would be fine, if that was intended. The mentioned function is not called in the new activity and yet it seems to be. Please look over my code and show me where it went wrong..
MainActivity:
public class MainActivity extends ActionBarActivity {

protected TextView text;
protected int position;
private Handler handler = new Handler();
private int i = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    text = (TextView) findViewById(R.id.text);
    position=0;
    SetButtonCLickListener();
    counter();
}

protected void SetButtonCLickListener() {
    Button btn = (Button) findViewById(R.id.button);
    btn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            SwitchActivity();
        }
    });
}

private void counter() {
    handler.removeCallbacks(count);
    handler.postDelayed(count, 1000);
}

private Runnable count = new Runnable() {
    public void run() {
        i++;
        text.setText("Count: " + i);
        handler.postDelayed(count, 1000);

    }
};

protected void SwitchActivity() {
    if (position == 1) {
            finish();

    } else {
        Intent intent = new Intent(this, MainActivity2.class);
        startActivity(intent);
    }

}
}

SecondActivity
public class MainActivity2 extends MainActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main_activity2);
    text = (TextView) findViewById(R.id.text);
    SetButtonCLickListener();
    position=1;
}
}

Answer: MainActivity2 has an onCreate() method. In the onCreate() method, you call super.onCreate(), which triggers the MainActivity implementation of onCreate(). The MainActivity implementation of onCreate() is where you are starting your counter thing, via its call to the counter() method. Hence, when MainActivity2 starts up, its onCreate() calls MainActivity's onCreate(), which calls counter().
My guess is that MainActivity2 should inherit from Activity, not from MainActivity.
Comment: You are right, though i had hoped it would be possible this way.


Is there any way to make this animation's height as tall as my text?

Question: I have a title in my page which the animation that slides out is only 1/2 of the height of the text, but in half-screen (phone or on split screen), it covers the entire text, this is because my title font-size is based on vw. Is there any way that the animation's height is always as tall as the text, not the entire element? Here is the website -->https://proking73.github.io/P.W.I.L-with_Sis/, and you could check the source code or inspect the page. My goal is that the animation covers the entire text.
Comment: Use your code here as minimum code needed to reproduce the same effect
Comment: What does that mean? (sorry) Could you maybe explain it in more detail?
Comment: The code needed to make the animation on the website you are sharing the link to
Comment: Yes, the animation was made, I need help making it the height the same as the text.
Comment: like this `html` is : `Practicing everything I learn,restarting /w Aarushi® edition` ; Javascipt : .....................
Comment: Never mind, I just used the same method for the font-size as the height of the animation. Problem solved.
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/238491/discussion-between-proking73questioneer-and-rana).
Answer: Nevermind, the answer was to just make the height the same as my font size height.


Is using your thumb for jazz barre chords 'bad technique'?

Question: When I play barre chords using jazz voicings such as in the following chord chart:

I often wrap my thumb around the neck to fret the E string. I prefer this, rather than using my first finger, as it makes it easier to play more complex chords since it frees up an extra finger. I want to know whether this is considered 'bad technique' and whether this has any negative long term effects on playing.
Comment: In the chord diagram, your thumb is on string 6, 5th fret, but where is the barre, and how to you mute strings 5 and 1?
Answer: Using your thumb isn't "bad technique" per se. It's either appropriate or it isn't, given the context in which you do it. For example, if this chord is sandwiched between two others which require the first finger barre, maybe it would be better to leave the finger down through those chords.
Bad technique is what I did when I started playing years ago, saw Jimi Hendrix using his thumb, and decided I didn't need to learn how to barre properly!
Answer: Who has the power to decide? Any technique that works for an individual cannot be a bad one. Yes, purists may disagree, but it's not them playing, it's you! As stated already, an extra digit is always an asset, particularly on extended guitar chords. I'm only jealous, having small hands...
Answer: The traditional arguments against wrapping the thumb around to fret the sixth string are that it slows the hand down when you need to change fingerings, and that it brings the other fingers closer to the strings so they are more likely to mute other strings unintentionally. This matches my experience; but if you can play quickly and cleanly with your thumb wrapped around, those reasons needn't bother you.
I find that when I try to fret with my thumb, or even just have my palm on the back of the neck, my wrist and fingers are flexed more, and there's more tension in my hand. Even when playing a barre, my hand feels much more relaxed if I have only my thumb on the back of the neck. This make it easier to play for a long time without getting sore.
Answer: It is unorthodox, but it's not bad per se. I'd definitely recommend learning to barré properly/use your first finger too, and then use whichever is appropriate based on the specific chord and its context.
A classical guitarist (or at least, a classically-trained guitarist) wouldn't really use their thumb like that at all, but plenty of top guitarists still do: Metheny, (Jeff) Beck, Emmanuel, Hendrix, SRV, Bonamassa, etc... Loads.
I find it does produce a slightly different sound - somewhat warmer and fluffier than using your first finger. This is because your thumb is going to be quite flat against the neck, whereas your first finger would be more pointed (i.e. you would be using your fingertip more).
There are no downsides to this technique if applied appropriately. However, if used as an excuse to not learn other fingerings, you might find it limiting when playing chords that demand a full barré or similar.
So yes, it's fine, but learn to play it both ways and then use whichever you feel.
Answer: I wouldn't say this is a bad technique. There are many guitarists that use this one, for the very same reason you mentioned. You have one extra finger, thus you can play one more note. Also, when I play a chord like this, it is more relaxing for my hand.
Answer: Not at all, it's a great technique! There are chords that you can only play by using your thumb, e.g. the following voicing of A13(b9) (from low E to high e):
5 X 5 6 7 6
where you play the E string with your thumb. If you used your first finger to play a barre chord it would be very difficult to mute the A string.
Answer: Some of the tricks used in country music where the guitar was for show more than anything else, the would wrap their thumb around the three base strings and the index fingers around the 123 in same fret to form a chord. Then moving it up and down the neck the singer could play along with the band. Some of those country singers playing was worse than their singing. I use my thumb watch some of Johny Cash videos he uses the thumb
Answer: Try playing F#dim with your thumb on the bass string to get the correct inversion, and then it's obvious that this one's a no-brainer. Yes, it does slow you down so it should be avoided, but in certain circumstances it really opens up the instrument's full potential by getting the correct inversion and using all 6 strings.
Answer: I play steel string acoustic guitar and I find that in many instances using the thumb to barre is actually more ergonomic than using the index finger.
Typical use case for using the thumb is when I want to play or mute the low EA strings while simultaneously playing or chording on the GBE strings on a steel string acoustic guitar.  In this case if I barre with the thumb, then I can keep my wrist straight much easier and with less finger pressure than if I use my index finger.
YMMV, of course.
Answer: For starters, the chord you have given as an example isn't technically a barre chord; the "standard" fingering uses your four non-thumb fingers with no need to form a barre at all.
However, this doesn't really matter for your main question, which is whether it's bad technique to use your thumb to play notes on the low E string. Any experienced musician will answer any "Is this bad technique?" question with it depends, because bodies and instruments come in all shapes and sizes and there is always the possibility that an unusual technique will work perfectly for someone.
That said, there are a few reasons why using the thumb for these sorts of chords is not the default choice:

As has been noted, it can slow down your chord changes. Practice switching rapidly between that A13 voicing and the Dmaj7 voicing right next door. I bet that in this context, you will find the standard fingering to be more economical.
Depending on the size of your arms and playing position, using the thumb can force your wrist into a nearly right-angle position. This limits the circulation to your fingers and hand, which limits your left-hand control and can quickly lead to muscle fatigue.

In real life, many guitarists (including many who are considered to have "good technique") do use the thumb fingering. But they are more likely to use it for chords lower on the neck, since this gives the elbow more wiggle room and allows to to maintain a relatively straight, relaxed wrist position. The further up on the neck you go, the stronger the recommendation becomes; where you choose to switch from thumb to fingers will depend on your personal geometry. I have relatively small arms, so I find it comfortable to use the thumb fingering as high as the 10th or 11th fret, but after that I do tend to switch to the standard fingering for the reasons given above.
Another way to make the thumb fingering more comfortable and enable a straight wrist position when playing with the thumb is to hold the guitar with its neck pointing slightly forward. There is an Adam Neely Q&A video where he suggests this idea; I will add a link if I can find it.
Answer: If using your thumb helps you to reach notes more effectively then it can't be bad technique. If it slows you down doing certain things, then it is not good technique at that moment. BTW, I think you'll find that a generally cooler way to play that A13th is to play it without that low A anyway.
Answer: I think it depends what sort of chords you are transitioning to/from. For example, the thumbed-barre F chord would be and easier transition to/from a traditional C or a G chord than the non-thumbed F barre chord.
On the other hand, the "proper" barre chord is easier to maintain and move around further down the neck, especially closer to the 12th fret.


How to download payload in NODE-RED?

Question: I am connecting to an oracle DB node and getting the payload through debug node.Is there a way to  download the payload in json format
Answer: The msg.payload will already be a JSON object, what you see in the debug node is just a representation that's formatted for display in the sidebar.
Comment: There are a bunch of standard nodes that would allow that, update the question with what you have already tried. Stackoverflow is not a free code writing service, you have to try first then people will help you fix it.
Comment: Thanks for your reply. I can view the payload in debug mode but can you suggest me on how to download the same so that I can save it in my local.

How to download payload in NODE-RED?


How to reference existing Paragraph entity?

Question: I'm trying to create an entity reference field for existing paragraph, but can't seem to figure it out.
I've tried creating a normal entity reference field (content) but that only gives me the options to select from content types.
I've tried creating a paragraph field and using a entity reference view to display the results. (this displays a list of paragraph entity ids but when referencing one in a node it comes up with There are no entities matching "(21)".
How do I reference existing paragraph entities in a node?
Answer: Re-using paragraphs is not supported/allowed. Each paragraph has a reference to the host entity it is being used in and only supports one such reference.
If you need re-usable content in paragraphs, you need to have another entity type or bundle that you reference from a paragraph type.
Comment: What if the use-case isn't to re-use paragraph item but instead to reference them. My usecase is to have an eform that displays on multiple paragraph items (eform to paragraph item is one to many). The submitted entity form needs a reference back to the paragraphs item that it was on when it was submitted. This isn't re-use but is a valid use-case for referencing paragraphs items.
Comment: @Berdir that wouldn't work for my use-case. The question is stored in the paragraph and the submission is stored in the eform submission. With your suggestion there would be no link between the question, answer, and the user that answered. But that is no matter, I have done this and it works. This wasn't an additional question, more of an argument that referencing a paragraphs item doesn't always mean reusing paragraphs content. Sometimes a reference is just a reference.
Comment: But surely a paragraph is just an entity? And we should be able to make reference to any entity?
Comment: Yes, it is a paragraph and yes a paragraph field is nothing but a reference to it. But as I said, a paragraph also has a reference back to the entity that uses it and it currently only supports exactly one such reference. The behavior when multiple entities reference it is undefined and unsupported.
Comment: @FrankRobertAnderson That sounds like referencing an eform *from* a paragraph, which I'd do as an eform paragraph type with a reference field. Knowing which paragraph, or node/host entity, the form was displayed on is something that neither paragraphs nor entity references can handle automatically, but it should be possible to do using a bit of form alter to remember the page you were on. If you need more info, ask a separate question
Comment: You can also use the paragraphs_library sub-module, right?