Bind DNSSEC inline-signing loadkeys fail because zone in multiple views

Question: I'm trying to implement DNSSEC with the bind>=9.9 option inline-sgning.
I've previously successfully manually signed the same zone by generating a .signed file with dnssec-signzone. But I don't want to manually sign the zone each time so I want to use inline-signing to let bind do the stuff.
So I modified the options statement with key-directory "/etc/bind/keys"; dnssec-validation auto; dnssec-enable yes; and in the zone statement I've added auto-dnssec maintain; inline-signing yes;. But the server was still not answering
$ dig DNSKEY @<domain_ns>

So I ended up finding this command that gives me an error.
# rndc loadkeys <domain>
rndc: 'loadkeys' failed: multiple
zone '<domain>' was found in multiple views

A little bit of context : I'm using an "internal view" for people on my network and an "external view" for others. I need to keep those and the zone I want to sign is available to both views.
And then I don't know how to solve this, I've tryed using auto-dnssec and inline-siging options in both or in only one of the views. Doesn't seems to help. So i'm asking here if anyone knows a solution
Answer: When you have the same zone in multiple views, you need to tell rndc which view to operate on. It should be the view where the zone was defined as "type master", not the one where it was referenced with "in-view".
So, assuming you defined the zone for example.com in a view called "external", you'd have to type:
# rndc loadkeys example.com IN external

Same for the other rndc commands, just put "IN external" after the domain name and it should work.


add dimension to an xarray DataArray

Question: I need to add a dimension to a DataArray, filling the values across the new dimension. Here's the original array.
a_size = 10
a_coords = np.linspace(0, 1, a_size)

b_size = 5
b_coords = np.linspace(0, 1, b_size)

# original 1-dimensional array
x = xr.DataArray(
    np.random.random(a_size),
    coords=[('a', a coords)])

I guess I could create an empty DataArray with the new dimension and copy the existing data in.
y = xr.DataArray(
    np.empty((b_size, a_size),
    coords=([('b', b_coords), ('a', a_coords)])
y[:] = x

A better idea might be to be to use concat. It took me a while to figure out how to specify both the dims and the coords for the concat dimension, and none of these options seem great. Is there something I'm missing that can makes this version cleaner?
# specify the dimension name, then set the coordinates
y = xr.concat([x for _ in b_coords], 'b')
y['b'] = b_coords

# specify the coordinates, then rename the dimension
y = xr.concat([x for _ in b_coords], b_coords)
y.rename({'concat_dim': 'b'})

# use a DataArray as the concat dimension
y = xr.concat(
    [x for _ in b_coords],
    xr.DataArray(b_coords, name='b', dims=['b']))

Still, is there a better way to do this than either of the two above options?
Answer: If DA is your data array with length DimLen, you can now use expand_dims:
DA.expand_dims({'NewDim':DimLen})

Answer: Because of the way that math is applied over new dimensions I like to multiply in order to add new dimensions.
identityb = xr.DataArray(np.ones_like(b_coords), coords=[('b', b_coords)])
y = x * identityb

Comment: Quick solution although it leads to lose the available attributes in x
Answer: Using .assign_coords method will do it. However you can't assign coordinates to a non-existant dimension, the way to do as a one liner is:
y = x.expand_dims({b_coords.name: b_size}).assign_coords({b_coords.name: b_coords})

Answer: With reference to the syntax of the question:
y = x.expand_dims({"b": b_coords})

add dimension to an xarray DataArray


Is there a way to fast forward using audioPlayers FLUTTER

Question: I was wondering if audiopayers package has 30Sec fast forward.
I am using this flutter package to play audio but I did not find any fast forward
so can u guide me where is the fast forward?
Thanks for guiding me :)
Answer: As I can see in the document there is a function call seek() that let u fast forward.
Try calling this:
<code>await audioPlayer.pause();
await audioPlayer.seek(Duration(seconds: 30));
await audioPlayer.resume();
</code>
Comment: Thanks a million. u know I was in a hurry because the deadline of my project arrived and I had some bugs so I didn't read the documentation carefully. thanks
Comment: And one more thing, how can we speed up the audio?
Comment: i have used seek and its not working when i set to seek for 30 seconds it again start


Asymptotic distribution of $X_{(n)}$

Question:
Let $X_1,X_2,\dots,X_n \sim U(0,1)$. They are iid. Let $X_{(n)}=\max\{X_1,X_2,\dots,X_n\}$, then what is the asymptotic distribution of  $X_{(n)}$.

I know the method for finding the asymptotic distribution by Delta Method but I'm unable to find the derivative here.
As delta method says that $$ \sqrt{n}\Big(g(X_n)-g(\theta)\Big)\sim N\big(0,\sigma^2[g^\prime(\theta)]^2\big) $$ But here how to compute $[g^\prime(\theta)]^2$?
Comment: $$ \text{right: } \sqrt{n}\Big(g(\,\overline X_n)-g(\theta)\Big) \sim N\big(0, \sigma^2 [g^\prime(\theta)]^2\big) $$ $$\text{wrong: } \sqrt{n}\Big(g(X_n)-g(\theta)\Big) \sim N\big(0, \sigma^2 [g^\prime(\theta)]^2\big) $$ The first page of the pdf file to which you link, on the delta method, is about the distribution of $\bar X_n$, not about that of $X_n$ or of $X_{(n)} = \max\{ X_1, \ldots, X_n \}. \qquad$
Comment: https://math.stackexchange.com/questions/2950994/evaluating-lim-n-to-infty-frac1-theta-1-fracz-thetann-1
Comment: I don't actually understand your comment.
Answer: The CDF of $X_{(n)}$ is
$$F_{X_{(n)}}(t) = \mathbb P(X_{(n)} \le t) = t^n \ \text{for}\ 0 < t < 1$$
To have a nontrivial limit as $n \to \infty$, we'll want $t \sim 1 - \text{const} / n$.  Thus for $0 < s < n$,
$$F_{X_{(n)}}(1 - s/n) = (1-s/n)^n \to \exp(-s) $$
Since the left side can be written as $\mathbb P(n(1-X_{(n)}) \ge s$, this says $n(1-X_{(n)})$ converges in distribution to an exponential distribution with parameter $1$.
Answer: For $0<t<1$:
$$F_{X_n}(t)=P(\max\{X_1,...X_n\}\le t)=P(X_1\le t,\ldots,X_n\le t)=P(X_1\le t)\cdots P(X_n\le t)=t^n$$
So
$$F_{X_n}(t)=
\begin{cases}
0 & \text{ if } t\le 0\\
t^n & \text{ if } 0<t<1\\
1 & \text{ if } t\ge 1
\end{cases}
$$
From the equation above it is clear that $X_{(n)}\xrightarrow{P} 1$ (and in distribution). However, this limit statement to a degenerate distribution does not fully reveal the asymptotic distribution of $X_{(n)}$. So we search for sequences $k_n$ and $a_n$ such that $k_n(X_{(n)}-a_n)$ has a non-degenerate limiting distribution.
Computing the distribution function of $k_n(X_{(n)}-a_n)$ directly we have:
$$F(u)=P(k_n(X_{(n)}-a_n)\le u)=P\left(X_{(n)}\le\frac{u}{k_n}+a_n\right)$$
as long as $k_n>0$. Therefore:
$$F(u)=\left(\frac{u}{k_n}+a_n\right)^n\text{ for }0<\frac{u}{k_n}+a_n<1$$
We would like this expression to tend to a limit involving only $u$ as $n\rightarrow\infty$.
We observe that if we take $a_n=1$ and $k_n=n$ so that $F(u)=\left(1+\frac{u}{n}\right)^n$ which tends to $e^u$
We further observe that the values of $u$ which make the above limit valid are $0<a_n+\frac{u}{k_n}<1$ which in this case becomes $-1<\frac{u}{n}<0$. So $u$ may be any negative real number, since for any $u<0$, $-1<\frac{u}{n}<0$ for all $n>|u|$. We conclude that the random variable $U$ has the distribution function:
$$F(u)=
\begin{cases}
e^u & \text{ if }u\le 0\\
1 & \text{ if }u > 0
\end{cases}
$$
then $n(X_{(n)}-1)\xrightarrow{d} U$. Since $-U$ is a standard exponential random variable, we may also write:
$$n(1-X_{(n)})\xrightarrow{d} \text{Exponential}(1)$$
Comment: It doesn't converge to 1, but to Exponential(1), which is non-degenerate.
Comment: This answer is wrong.  See my answer.
Comment: @MichaelHardy why is this wrong?
Comment: Because it doesn't address the question. It shows correctly that $n(1-X_{(n)}$ converges in distribution to $1$, but "asymptotic distribution" has to do with the sort of thing you see in the central limit theorem, where you multiply by $\sqrt n$. Except in this case you multiply by $n+1$. $\qquad$
Answer: \begin{align}
\text{right: } \sqrt{n}\Big(g(\,\overline X_n)-g(\theta)\Big) & \sim N\big(0, \sigma^2 [g^\prime(\theta)]^2\big) \\
\text{wrong: } \sqrt{n}\Big(g(X_n)-g(\theta)\Big) & \sim N\big(0, \sigma^2 [g^\prime(\theta)]^2\big)
\end{align}
The first page of the pdf file to which you link, on the delta method, is about the distribution of $\bar X_n$, not about that of $X_n$ or of $X_{(n)} = \max\{ X_1, \ldots, X_n \}.$
I must dispute the answer by "Momo". Note that the weak law of large numbers tells us that in the limit, the distribution of $\overline X_n$ puts probability $1$ at the expected value, often denoted $\mu$. But the two lines displayed above speak of the distribution of $\sqrt n\left(\,\overline X_n - \mu\right)$, which is given by the central limit theorem as a normal distribution. The difference between these results is that we are scaling by multiplying by $\sqrt n$. Just as the C.L.T. gives us a normally distributed sample mean, we will get an exponentially distributed sample maximum.
We have
\begin{align}
\operatorname{E}(\,X_{(n)} ) & = \frac n {n+1}, \\[10pt]
\operatorname{var}(\,X_{(n)}) & = \frac n {(n+2)(n+1)^2} \sim \frac 1 {(n+1)^2}
\end{align}
where $A\sim B$ means $A/B\to 1$ as $n\to\infty$. So the standard deviation of $X_{(n)}$ is asymptotically $1/(n+1)$.
Now we have
\begin{align}
\text{for } x>0, & \quad \Pr\left( \frac{1-X_{(n)}}{\sqrt{\operatorname{var}(X_{(n)})}} > x \right) = \Pr\Big( (n+1)(1 - X_{(n)}) > x\Big) \\[10pt]
= {} & \Pr \left( X_{(n)} < 1 - \frac x {n+1} \right) = \left( 1 - \frac x {n+1} \right)^n \to e^{-x} \text{ as } n\to\infty.
\end{align}
Thus asymptotically, $(n+1) ( 1-X_{(n)} )$ is exponentially distributed with expected value $1$.
The multiplication by $(n+1)$ plays the same kind of role as the multiplication by $\sqrt n$ in the central limit theorem.
None of this alters the fact that the limiting distribution of $X_{(n)}$ concentrates probability $1$ at $1$ (as shown in "Momo"'s answer), just as the sample mean from a distribution with finite variance concentrates probability $1$ at the population mean. But "asymptotic distribution" involves the rescaling by multiplying by $\sqrt n$ in the first two lines of this answer and in the central limit theorem, and by $n+1$ in the result shown here.

Asymptotic distribution of $X_{(n)}$


Can anyone explain how line-$4$ follows from line-$3$?

Question: I don't know how line-$4$ follows from line-$3$.
Comment: Please use MathJax.
Comment: I'm not sure which line is "line $4$."  Is it the first line without "$\lim$"?
Comment: line 4 is "ln(abc)/3"
Answer: If $$L=\lim_{x\to a} f(a)^{g(x)}
\to 1^\infty \implies L=\exp[\lim_{x\to a} g(x)(f(x)-1)]$$
So $$L=\lim_{n\to \infty} \left(\frac{a^{1/n}+b^{1/n}+c^{1/n}}{3}\right)^{n}
=\lim_{n\to \infty} \exp[n\left(\frac{a^{1/n}+b^{1/n}+c^{1/n}}{3}-1\right). $$
$$\implies L=\exp\left(\frac{1}{3}\left[\lim_{m\to 0}\left(\frac{a^m-1}{m}\right)+\lim_{m\to 0}\left(\frac{b^m-1}{m}\right)+\lim_{m\to 0}\left(\frac{c^m-1}{m}\right)\right]\right).$$
$$\implies L=\exp[{\frac{1}{3}(\ln a+\ln b+\ln c})]=\exp(\ln (abc)^{1/3})=(abc)^{1/3}.$$
Here we have used $\lim_{x\to 0} \frac{a^x-1}{x}=\ln a.$
Answer: I'm guessing this is your issue:  Let's take the derivative of $f(x) = \ln \left( \frac{5^{1/x}}{7}\right).$
The derivative is the reciprocal of the argument of $\ln$ times the derivative of the argument:
$$f'(x) = \frac{7}{5^{1/x}} \frac{d}{dx}\left(\frac{5^{1/x}}{7}\right).$$
The $7$'s cancel:
$$f'(x) = 5^{-1/x} \frac{d}{dx}\left(5^{1/x}\right).$$
Using the rule $d/dx(a^x) = \ln(a) a^x$ and the chain rule we have:
$$f'(x) = 5^{-1/x}\ln(5) 5^{1/x}\frac{-1}{x^2}. $$
Comment: Thank you for your help!!!
Answer: To go from Line 3 to Line 4, you use that as $n$ approaches infinity, $a^{1/n}$ approaches $a^0=1$ (and similarly for the other variables - as long as they're not zero), as well as log rules.
The $3/(a^{1/n}+b^{1/n}+c^{1/n})$ approaches $3/(1+1+1)=3/3=1$.
The $-a^{1/n}\ln(a)/3-b^{1/n}\ln(b)/3-c^{1/n}\ln(c)/3$ approaches $-(\ln(a)+\ln(b)+\ln(c))/3=-\ln(abc)/3$ using log rules.
Finally, the negative cancels with the negative in the denominator.
Comment: Oh I understood! Thanks!!!!
Comment: @김태준 If this answer helped you, you are expected to vote it up or mark it as a solution.


Finding non-instantiated templates in C++ code

Question: What is the best way to find uninstantiated templates in C++ Code?
I have a code base that heavily uses templates.
Of course, we want to make sure that the test coverage is high.
For all used code, this works very well using gcov.
However, unused templates are reported as non-executable by gcov.
After some googling, it appears that there is no way to force g++ to emit code for these templates (which is only logical, how should the compiler guess any types?)
It also appears that there is no way to make gcov recognize the uninstantiated template code as runnable code.
Is there anything "out of the box" that allows me to augment the files generated by the GCC -ftest-coverage -fprofile-arcs instrumentation? By the gcov option documentation of GCC, it would probably be enough to mark the whole template function body as one block since execution will never end up there.
EDIT (background information): I'm working on a header-only template library.
My aim here is to find unused/untested functions.
I know that code coverage is flawed but finding uninstantiated code is a very important step towards better tested code.
Currently, we are putting checkpoint macros at the beginning of each function.
In testing mode, they expand to code that inserts a pair of (file, line) into a global set of passed checkpoints.
After running the tests, we manually read all files and compare the reached checkpoints with the set of all available checkpoints.
Finding uninstantiated code is important, for example, because of unintuitive C++ template precedence behaviour, there might be dead code somewhere that the reader or even the author would expect to be used.
Comment: I'm not sure what you're asking makes sense to me. The compiler only instantiates the template for the types used. If some given type is never used for that template then that particular instantiation won't exist at the object code level.
Comment: You mean template classes/structs/functions that are never instantiated for any type?
Comment: @Xeo: Yes, this is what I mean.
Comment: @Victor: Could be to eliminate dead code to ease maintenance.
Answer: I think our C++ Test Coverage tool (not GCC-based) does this correctly from your point of view.
It instruments the source code before the compiler sees it; code inside templates get "coverage probes" regardless of whether the template gets used or not.  The test coverage display portion of the tool knows where all the probes are; if the template code isn't instantiated, it clearly can't be executed that's what will get reported.  You don't have to do any "custom" macro insertion or other, er, BS.
The downside is that if you have a template parameterized by several different types, and template method m1 and m2 are executed for different instantiated types, your coverage for m1 and m2 will be 100% (after all, you executed the instrumented template).  It isn't clear this is bad; just that it is how this is interpreted.
Answer: Okay, since I'm not very versed with GCC, here's a tedious and very time-taking solution, but atleast it works! :)
This test relies on the fact, that some errors in template code aren't detected until actual instantiation, i.e. when dependant names don't actually exist in the template parameter:
template<class T>
struct Example{
  typedef typename T::_123344_non_existent_type instantiation_test;
};

Add such a typedef to every template you have, then compile. Remove it from every struct/class/function the compiler displays an error for and every template that still contains such a typedef when the code finally compiles never gets instantiated. Or you're unlucky and some types do define such a _123344_non_existent_type, though I'd lynch the coworker that is responsible for that. ;)
Comment: While workable, this is similarly work-intensive as maintaining the checkpoint macro approach I described above in my edit.
Comment: @Manuel: Yeah, I said so in the first sentence. ;) Sorry, but I wasn't online when you edited your question. ^^
Comment: @Manuel: actually it's worse, if you rework your test-suite, you need to start from scratch, since you had previously removed the `typedef` from those cases who worked.
Answer: I was having this same problem, so I wrote a program that modifies code coverage reports to show uninstantiated templates. It's not the most elegant, but it works.
There are two phases:

Before compilation, you use a C++ program written using Clang's Libtooling to find all of the templates in your code and insert comments before and after them.
After you've generated a test coverage report, you run a python script which goes through the report and modifies the lines enclosed by the comments from step 1.

So basically it takes advantage of the fact that even though a lot of your code is left out of the binary it pretty much all ends up in the final coverage report. The macros described in this question were the inspiration for this approach (it's basically an automated version of them that doesn't clutter the source code).
I've only used it on my own code so far, but it should generalize. Issues and pull requests welcome!


Qual é a diferença entre Object.assign e spread operator?

Question: Qual é a diferença detalhada de se usar Object.assign e o spread operator (...) para o espalhamento de propriedades de objetos?
Por exemplo, ao editar um objeto para novos valores, é a mesma saída:

const cursoNaDB = {
  abreviacao: "ES5",
  nome: "EcmaScript5",
  ano: "2009",
  categoria: "INICIANTE"
}

const cursoParaAlterarNaDB = {
  abreviacao: "ES6",
  nome: "EcmaScript6",
  ano: "2015",
  categoria: "AVANÇADO"
}

console.log(Object.assign(cursoNaDB, cursoParaAlterarNaDB));

console.log({ ...cursoNaDB, ...cursoParaAlterarNaDB });
Answer: Existem algumas diferenças sutis:
Diferença na definição de propriedades
A primeira delas é que Object.assign utiliza a operação interna [[Set]] para definir as propriedades. A notação de espalhamento (spread operator) simplesmente irá definir as propriedades. Assim, Object.assign chamará os setters, mas o spread operator não. Veja um exemplo:

const target = {
  set foo(val) {
    console.log('Chamou o set:', val);
  }
};
const other = { foo: 123 };

// Object.assign chama o setter:
console.log(
  Object.assign(target, other)
);

console.log('---');

// Spread operador não chama o setter:
console.log(
  { ...target, ...other }
);

Note, no exemplo acima, que como o spread operator nem sequer chamou o setter, a propriedade foo foi definida como 123 no objeto resultante. Contudo, ao utilizarmos Object.assign, o valor que definimos para foo não fica persistido no objeto resultante, já que o setter não faz nada com ele (além de imprimi-lo no console).
Assim, pode-se afirmar que o Object.assign funciona de forma similar ao operador de atribuição (=), que também executa a operação interna [[Set]] (o que invoca os setters, se existirem). O spread operator funciona de modo mais similar ao Object.defineProperty, que não executa setters:

const obj = {
  set foo(val) {
    console.log('Chamou o setter: ', val);
  }
};

// Object.assign se assemelha a isto:
obj.foo = 123;
console.log(obj); // { foo: undefined }

console.log('---');

// Spread operator se assemelha a isto:
Object.defineProperty(obj, 'foo', {
  value: 123
});
console.log(obj); // { foo: 123 }

Possível diferença no construtor do objeto resultante
Uma outra diferença é que o protótipo e construtor do objeto resultante poderá ser diferente de Object ao utilizar Object.assign. Ao utilizarmos o spread operator, o construtor do objeto resultante é, sempre, Object:

class DifferentThanObject {
  a = 1;
  b = 2;
}

const instance = new DifferentThanObject();
const other = { c: 3, d: 4 };

const obj1 = Object.assign(instance, other);
console.log(obj1.constructor.name); // DifferentThanObject

const obj2 = { ...instance, ...other };
console.log(obj2.constructor.name); // Object

Para entender, precisamos estar cientes da assinatura de Object.assign:

Object.assign(target, ...sources)

A diferença de construtores se dá, então, já que Object.assign "copia" todas as propriedades enumeráveis de cada um dos objetos source (passados do segundo argumento para frente) para o destino (target, o primeiro argumento). Assim, o construtor do objeto resultante será sempre o mesmo do objeto target.
Conforme vimos no exemplo acima, como instance (passado como target para o Object.assign) é uma instância de DifferentThanObject, a saída também será uma instância de DifferentThanObject.
A especificação da linguagem para Object.assign deixa isso excepcionalmente claro (referir ao link para o algoritmo completo):

Perform ? Set(to, nextKey, propValue, true).

Sendo to o objeto que foi passado como target, nextKey a chave da propriedade a ser definida e propValue o valor desta.
Isso evidencia que um novo objeto nem chega a ser criado. Para cada propriedade dos objetos source, será executada a operação [[Set]] no target. Ou seja, o mesmo objeto que entra como target é aquele que sai, só que com propriedades setadas a mais.
No entanto, sempre que utilizarmos o spread operator para fazer essa "transferência" de propriedades, o construtor do objeto resultante será Object. Isso acontece porque sempre criamos um novo objeto literal (que é, por definição, construído por Object):

const literal = {};
console.log(literal.constructor.name); // Object

A diferença pode ser melhor entendida se tentarmos imitar o comportamento de Object.assign e do spread operator explicitamente:

class DifferentThanObject {
  a = 1;
  b = 2;
}

const instance = new DifferentThanObject();
const other = { c: 3, d: 4 };

// ------- "Imitando" `Object.assign`:
// Object.assign(instance, other);

const resulting1 = instance;
resulting1.c = other.c;
resulting1.d = other.d;

console.log(resulting1);

// ------- "Imitando" spread operator:
// { ...instance, ...other };

const resulting2 = {};
Object.defineProperty(resulting2, 'a', { value: instance.a, enumerable: true });
Object.defineProperty(resulting2, 'b', { value: instance.b, enumerable: true });
Object.defineProperty(resulting2, 'c', { value: other.c, enumerable: true });
Object.defineProperty(resulting2, 'd', { value: other.d, enumerable: true });

console.log(resulting2);

Note que, ao utilizarmos o spread operator, somos "obrigados" a criar um novo objeto literal (com a notação {}) para que, sobre ele, as propriedades sejam espalhadas. O Object.assign irá simplesmente setar as propriedades a qualquer valor passado ao seu primeiro argumento.
Você pode passar um objeto vazio como target no Object.assign se quiser garantir que somente as propriedades próprias e enumeráveis serão transferidas, deixando de "transferir" o construtor e propriedades do protótipo do objeto target:

class DifferentThanObject {
  // Métodos são anexados ao protótipo:
  method() {
    // noop
  }

  // Propriedades da instância:
  a = 1;
}

const instance = new DifferentThanObject();
const other = { b: 2 };

const resulting1 = { ...instance, ...other };
console.log(resulting1.constructor.name); // Object
console.log(typeof resulting1.method); // undefined //=> Métodos do protótipo NÃO são "transferidos".
console.log(resulting1); // { a: 1, b: 2 }

console.log('---');

const resulting2 = Object.assign(instance, other);
console.log(resulting2.constructor.name); // DifferentThanObject
console.log(typeof resulting2.method); // function //=> Métodos do protótipo são "transferidos".
console.log(resulting2); // { a: 1, b: 2 }

console.log('---');

//        Objeto literal "vazio" ↓↓
const resulting3 = Object.assign({}, instance, other);
console.log(resulting3.constructor.name); // Object
console.log(typeof resulting3.method); // undefined //=> Métodos do protótipo NÃO são "transferidos".
console.log(resulting3); // { a: 1, b: 2 }

Isso acontece porque, nesse último exemplo, target é um objeto literal (cujo construtor é Object) e, como vimos, o Object.assign resulta no próprio target, só que com as propriedades dos outros objetos (sources) setadas.
Vale a pena ler Qual é a diferença entre criar um objeto a partir da forma literal ou a partir de uma função construtora? para entender melhor.
Conclusão
No seu caso, como você não está lidando com setters e os objetos têm o mesmo construtor (Object, já que ambos foram criados de forma literal), não há nenhuma diferença real.
A única ressalva é que Object.assign é um pouco mais suportado que o spread operator para o espalhamento de propriedades de objetos. Isso porque Object.assign foi introduzido no ECMAScript 2015 (ES6), enquanto o spread operator só ganhou a habilidade de espalhar propriedades de objetos no ECMAScript 2018.
Comment: Legal, por isso que o `Object.assign` funciona bem com o Vue.
Comment: Ótima resposta! perfeitamente descrita a questão da instância do objeto e sobre o acionamento do setter. Me ajudou muito


jenkins pipeline - start a pipeline job with input parameter via url

Question: In the old freestyle project days we could simply start a build which had parameters like this:
    curl -X POST JENKINS_URL/job/JOB_NAME/build \
  --data token=TOKEN \
  --data-urlencode json='{"parameter": [{"name":"id", "value":"123"}]}'

This does not seem to work with pipeline input plugins
With pipelines i can accomplish this with two steps:
Submit a new job:
curl -X POST JENKINS_URL/job/JOB_NAME/build

And then submit the input parameter:
curl -X POST -d json='{"parameter": {"name": "id", "value": "123"}}'
JENKINS_URL/job/JOB_NAME/build/BUILD_NUMBER/input/INPUT_NAME/submit

But this looks cumbersome, plus i have to somehow retrieve the build_number after start, wait until job kicks in (pending time) and only then submit. And if there is a timeout on input, this complicates things even more.
Can i somehow do this via single API call?
Answer: You can have parameterized pipeline jobs. It works just like parameterized freestyle jobs.
Just configure your job to be parameterized.
https://issues.jenkins-ci.org/secure/attachment/21424/PARAMETERIZED%20BUILD.png
Comment: Yes, but i would like to have this purely through pipeline input (e.g. i cannot have a timeout with this parametrized parameter)
Comment: Not sure what you mean.
It works exactly like freestyle jobs. Is that not what you wanted?
Answer: As Timmy mentionned, parameterized pipelines jobs work just like parameterized freestyle jobs.
To trigger it you can execute the following command :
curl -X POST JENKINS_URL/job/JOB_NAME/buildWithParameters?id=123 --data token=TOKEN

This is from Parameterized Build documentation.


Example of the set of absolute value on number fields.

Question: Let $k$ be a number field and $M_k$ be the set of standard absolute value on $k$, which means for $v \in M_k$, $v$ is an absolute value on $k$ whose restriction to $\mathbb{Q}$ is $|\cdot|_p$ where $p$ is a prime number or $\infty$.
I want to know any non-trivial example of $M_k$ or those elements. For example, let $k=\mathbb{Q}(i)$, I know that the standard absolute value on $\mathbb{C}$ is in $M_k$ but I can't imagine what absolute value satisfies that whose restriction to $\mathbb{Q}$ is $|\cdot|_p$ for a prime number $p$.
Does there exists? Could you give me any example?
Comment: I think that I found at least one  example.
Answer: Taking your example $k=\Bbb Q(i)$, then there

is one absolute value $|\cdot|_{\tilde p}$ on $k$ extending $|\cdot|_p$ if $p \equiv 3$ mod $4$, or $p=2$: it is given explicitly by $$|a+bi|_{\tilde p} = \sqrt{|a^2+b^2|_p}$$
are two absolute values $|\cdot|_{\pi_1}$, $|\cdot|_{\pi_2}$ on $k$ extending $|\cdot|_p$ if $p \equiv 1$ mod 4. Namely, in this case, $(p) = I_1\cdot I_2$ as ideals where $I_i$ are two different prime ideals in $\Bbb Z[i]$; choosing as $\pi_i$ any generator of $I_i$, the $\pi$-adic value first on $\Bbb Z[i]$ and then on its quotient field $k$ is defined completely analogously to $p$-adic values on $\Bbb Q$. (As examples, for $p=5$ one can choose $\pi_1 = 2+i, \pi_2=2-i$; for $p=13$ e.g. $\pi_1=2+3i, \pi_2 = 2-3i$ for $p=13$).

All this is related (and from a certain perspective, nearly equivalent) to the decomposition/ramification of the prime $p$ in the number field $k$. For your specific example, compare e.g. What's are all the prime elements in Gaussian integers $\mathbb{Z}[i]$, Primes in Gaussian Integers, Classification of prime ideals in $\mathbb{Z}[i]$, Are there any elegant methods to classify of the Gaussian primes?.
Comment: Oh,I read other source so I know that example and in fact now I can describe all the absolute values but your answer is very nice and easy. I think that this helps many people who ask the same one I asked. Thank you.


How to set type="email" attribute on a Drupal form textfield

Question: I'm doing some mobile forms with Drupal and have an email address textfield that currently has type="text" in the resulting HTML. I'd like this to be type="email" instead so that iOS shows a more useful keyboard when entering the email address.
I tried adding:
"#attributes" => array("type" => "email")

to my field but it seems to just get ignored by Drupal. Is there a correct and/or supported way to achieve this?
Answer: Elements which are input[type=email] are a builtin as of Drupal 8. They can be added (along with other HTML5 elements and markup) to Drupal 6 or 7 via the Elements module.
As of writing this answer, I found the Element-module docs quite scant; they don't explain that the method for getting an e-mail input-element is slightly different than how it's done in D8. For Drupal 7:
/**
 * Implements hook_form().
 * "For long-lasting relief you can count on!"
 *
 * hook_form() functions are passed a form-node,
 * plus extra state-info if present.
 *
 * At the end of the function, the form-node should
 * be returned to the caller.
 *
 */
function mymodule_form($node,&$form_state) {

    $node['primary_email'] = array(
        '#type' => 'emailfield',
        '#title' => t('Submitter'),
    ); // in Drupal 8, it's '#type' => 'email'

    return $node;
}

Be sure to have the Elements module enabled before you expect the above to work. Also, if you haven't already, you'll also want to make the form accessible by doing something like:
/**
 * Implements hook_menu().
 * "Money back guarantee!"
 */
function mymodule_menu() {

    // create primary menu-entry for module:
    $items['mymodule'] = array(
        'title' => 'My Very Own Module',
        'page callback' => 'mymodule_description',
        'access callback' => TRUE,
        'expanded' => TRUE,
    );

    // create menu-entry for form:
    $items['mymodule/myform'] = array(
        'title' => 'My Very Own Form',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('mymodule_form'),
        'access arguments' => array('Behold, the form.'),
        'file' => 'mymodule.module',
    );

    // ...[maybe add more stuff here]...

    return $items;

The other elements made available by Element are listed at cgit.drupalcode.org/elements/tree/elements.module#n7.
Answer: As it stands, Drupal core doesn't support all HTML5 form elements.  The Elements module will add some support though, so check that out.

HTML5 elements (url, email, search, tel, number, range)
Comment: I think you're misreading things.  The OP asked for the ability to put in an `email` field.  The Elements module does that.  Why would you downvote it?
Comment: I'm not sure about that to be honest.  It'd work, but it seems kinda *hacky*.
Comment: Doesn't work for Drupal 7.x
Comment: @cept0 You'll have to be a bit clearer - what doesn't work?
Comment: **The elements module does support `#attributes` though.** Unfortunately, I can't vote your answer down atm. But I will do so asap
Answer: Instead of adding a form validation handler to the form, you can add a validation handler to the form element that needs to be validated:
$form['email'] = array(
  '#type' => 'textfield',
  '#title' => 'Email',
  '#required' => TRUE,
  '#element_validate' => array('myelement_email_validate')
);

The validation handler receives three arguments: The form element being validated, the $form_state and the $form array for the form containing the form element.
function myelement_email_validate($element, &$form_state, $form) {
  $value = $element['#value'];
  if (!valid_email_address($value)) {
    form_error($element, t('Please enter a valid email address.'));
  }
}

Answer: this is how i have done it:
 $form ['group_coordonnees'] ['field_candid_email'] = array (
        '#type' => 'textfield',
        '#title' => t ( 'E-mail' ),
        '#default_value' => '',
        '#required' => TRUE

);

$node->field_candid_email ['und'] [0] ['email'] = $form_state ['values'] ['field_candid_email'];

The field type of field_candid_email being selected in the back office as email
Answer: on Drupal 7 you can:
 $form['msg'] = array(
   '#type' => 'text',
   '#attributes' =>array(
     'placeholder' =>  'some text' ,
     'required' => "" ,  //required field
     'type' => "email" ,
   ),);

Comment: There is no "type=text" in Drupal core form API. This solution won't work without an extra module.


OHS + weblogic - Customize error 500

Question: and sorry if the question looks stupid (it may be ^^), I'm a newbie in HTTP server.
We use OBIEE 11g, that means we have Weblogic and we chose to use an Oracle HTTP Server (OHS, built on Apache) in front. OHS uses mod_wl_ohs to interact with Weblogic, here is the mod_wl_ohs.conf file:
## Fusion Applications Name Based Virtual Host Configuration

RedirectMatch 301 ^/analytics$ /analytics/
RedirectMatch 301 ^/AdminService$ /AdminService/

LoadModule weblogic_module   "${ORACLE_HOME}/ohs/modules/mod_wl_ohs.so"

# global plugin-options
WLForwardUriUnparsed ON
KeepAliveEnabled ON
KeepAliveSecs 20
DynamicServerList OFF
WLProxySSL ON

## Context roots for BI EE
<Location /analytics >
 SetHandler weblogic-handler
 WebLogicCluster miaibv194.mia.michelin.com:9704
</Location>
## Context roots for AdminService
<Location /AdminService >
 SetHandler weblogic-handler
 WebLogicCluster miaibv194.mia.michelin.com:7001
</Location>

If I understand well, the RedirectMatch and corresponding Location directives (even if I don't get exactly the responsibilities of the 2) are used to pass URLs like /analytics and /AdminService to Weblogic.
I'd like to know how I could redirect HTTP errors 500 from URLs like /analytics to a custom page: is this possible ? I had a look at the ErrorDocument directive, but from what I could see it appeared it could only be used for physical path (i.e. under the Directory directive for instance), did I miss something ?
Thanks for your help, and do not hesitate to ask me for clarifications (I'll try to answer the best as I can) !
Comment: See answer on [same subject opened on Stack Overflow][1].

  [1]: http://stackoverflow.com/questions/11525534/can-custom-http-error-500-be-specified-under-location-directive/12635587#12635587
Answer: Well, what I was originally trying to achieve was to customize HTTP errors 500 in OBIEE 11g (which uses WebLogic, and an OHS in our case). I opened a SR to try to achieve that with OHS, but it failed (Oracle guy told me I had to do it at application level), so I opened a new one to do it with WebLogic itself and here is what it gives:
• Locate the analytics.ear in your Oracle BI Home directory. This will be /Oracle_BI1 (or whatever you chose to name your Oracle BI Home on install)/bifoundation/analytics.ear. So in our example scenario, this would be located at: C:\OBI\Oracle_BI1\bifoundation\jee\analytics.ear • Make a backup copy of the ear file so that you have a restore point to refer back to (and revert to) if needed Note that we do not support updating the analytics.ear file, you must stop, remove the previous analytics.ear file before deploying the new one.
• Unpack the analytics.ear file to a temporary location, using the Java jar tool. Use the command line options xvf to extract the contents to the current working directory (e.g. C:\OBI\jdk160\bin\jar –xvf C:\OBI\Oracle_BI1\bifoundation\jee\analytics.ear), so you will probably want to create a temporary directory to hold the unpacked contents and change into that directory before running the command.
The ear contains a META-INF directory and two war files, analytics.war and analytics-ws.war
• In the META-INF directory, there is a MANIFEST.MF file, add the following line to the end of the file: Weblogic-Application-Version: 11.1.1 Note that it has been reported that when re-applying these steps following the application of BI 126.96.36.199.0 BP2 patches, this step to update MANIFEST.MF should be ignored as the new analytics.ear file is not versioned.
• Unpack the analytics.war file to a second temporary location; it contains a default.jsp file and five top-level directories, one of which is called WEB-INF.
• in the WEB-INF directory, you will find an existing file called web.xml. Edit web.xml, for example by adding:
<error-page>
<error-code>500</error-code>
<location>/500error.jsp</location>
</error-page>

Make sure there are no hidden characters and check the quotes are correct for your platform.
• Once you have edited the web.xml , repackage the analytics.war file, again using the jar tool, and, in turn, repackage that back into the analytics.ear file. Next we need to redeploy the analytics.ear file to Weblogic
• Log into Weblogic Admin Console and click on Deployments
• In the Change Centre at the top left, click "Lock and Edit"
• Find the analytics app and click the tickbox next to it, then click on the Update button
• In the Update Application Assistant screen, make sure the deployment path is the same as the ear file you just updated, if not change the path
• Click Next, then Finish
• In the Change Centre at the top left, click "Activate Changes" to save your changes. If you have not already done so, restart the Weblogic Admin Server and all Managed Servers

OHS + weblogic - Customize error 500


Mac fullscreen non-one visible application window

Question: I have a cocoa fullscreen application and I also need to show on the same screen another's application window. Is it possible to run from my app a separate process with visible window on fullscreen? May be special tricks/hooks?
Comment: What does this question have to do with XWindows?
Comment: I meant possibility of low-lever tricks to grab window content from some running app and draw it in the fullscreen app manually. May be XWindows experts know such ways
Comment: Any such ways would only work on XWindows apps, though, not on normal Mac apps.
Answer: In the fullscreen mode, you can only show a single window of a single application. This system is very strict.
Comment: But may be we have a way to draw another window inside of ours?
Comment: I don't think so. Are you sure there isn't another way to do what you want to do, without having to have two windows on the same fullscreen window?


Question about how to convert a line image to a circle image

Question: First of all, I'm sorry I can not speak English well.
I ask for your understanding even if there are some awkward parts of my words.
I am a beginner to get into Opencv.
I want to translate a picture of a horizontal line into a picture of a circle.
I tried to recommend linearPolar, logPolar, and warpPolar in several articles, but I did not get the desired result.
Result Image:

Here is the image I want to put and the desired result.
Input Image:

Output Image:

What function should I use to get this result?
If you have any examples or explanations for reference, please let me know.
If you let me know just the keywords, I will search Google and this site hard.
Thank you for reading my question.
Answer: linearPolar or warpPolar are exactly what you are looking for
You just need to pass it the WARP_INVERSE_MAP flag to make it transform the direction you're looking for.
modified example from samples/cpp/polar_transforms.cpp
Would be something like this:
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>

int main(int argc, const char** argv)
{
    using namespace cv;
    using namespace std;

    int flags = INTER_LINEAR + WARP_FILL_OUTLIERS;

    Mat src = imread(R"(C:\temp\IPpzR.png)");
    Mat lin_polar_img;
    rotate(src, lin_polar_img, cv::ROTATE_90_COUNTERCLOCKWISE);
    imshow("Loaded",src);
    Mat recovered_lin_polar_img;
    Point2f center( (float)src.cols / 2, (float)src.rows / 2 );
    double maxRadius = min(center.y, center.x);

    cv::linearPolar(lin_polar_img, recovered_lin_polar_img, center, maxRadius, flags + WARP_INVERSE_MAP);
    cv::imshow("Modified",recovered_lin_polar_img);
    cv::waitKey();

    return 0;
}

which gives the following result:
Comment: Thank you very much for solving your anxiety.

I tried to solve all day, but I am glad to have you solve it.

I will also study the code you have provided for each line. Thank you again.
Comment: Mat src = imread("./IPpzR.png"); for ubuntu
Answer: Peter's answer is great (+1).
I had a play with it and just wanted to post a Python version of his approach with some sliders:
#!/usr/bin/env python

import numpy as np
import cv2
# main window
WINDOW_NAME = "carToPol"
cv2.namedWindow(WINDOW_NAME)
# read input
src  = cv2.imread("iPpzR.png")
# get dimenions and compute half (for center/radius)
dims = src.shape[:-1]
cols,rows = dims
half = cols // 2

def carToPol(src,center,maxRadius,interpolation,rotate90=True):
    # rotate 90 degrees (cv2.warpAffine seems to mess up a column)
    if(rotate90):
        src = np.rot90(src)
    # cartesian to polar (WARP_INVERSE_MAP)
    return cv2.linearPolar(src,(centerX,centerY),maxRadius,interpolation + cv2.WARP_FILL_OUTLIERS + cv2.WARP_INVERSE_MAP)

# interpolation names: just for debugging
interpolations = ["NEAREST","LINEAR","CUBIC","AREA","LANCZOS4"]

# slider callbacks: just for debugging
def printCenterX(x):
    print("center",x)
def printCenterY(x):
    print("centerY",x)
def printMaxRadius(x):
    print("maxRadius",x)
def printInterpolation(x):
    global interpolations
    print("interpolation",interpolations[x])
# create sliders
cv2.createTrackbar("centerX"  ,WINDOW_NAME,half,cols,printCenterX)
cv2.createTrackbar("centerY"  ,WINDOW_NAME,half,cols,printCenterY)
cv2.createTrackbar("maxRadius",WINDOW_NAME,half,cols * 4,printMaxRadius)
cv2.createTrackbar("interpolation",WINDOW_NAME,cv2.INTER_CUBIC,cv2.INTER_LANCZOS4,printInterpolation)

# continously process for quick feedback
while 1:
    # exit on ESC key
    k = cv2.waitKey(1) & 0xFF
    if k == 27:
        break

    # read slider values
    centerX   = cv2.getTrackbarPos("centerX",WINDOW_NAME)
    centerY   = cv2.getTrackbarPos("centerY",WINDOW_NAME)
    maxRadius = cv2.getTrackbarPos("maxRadius",WINDOW_NAME)
    interpolation = cv2.getTrackbarPos("interpolation",WINDOW_NAME)

    dst = carToPol(src,(centerX,centerY),maxRadius,interpolation,True)
    # show result
    cv2.imshow(WINDOW_NAME,dst)
    # save image with 's' key
    if k == ord('s'):
        cv2.imwrite("output.png",dst)

# exit
cv2.destroyAllWindows()

Comment: You are really kind as well as the person who wrote above.
Thank you very much!


Running Corda -CordaDemoBench without local admin access rights

Question: I would like to run Corda Demo Bench on a windows machine without admin rights.
Is there anyway to do that ?
https://www.corda.net/develop/resources.html
The installer doesnt fail, but it requests for admin user/password, which I dont have since my user is a non privileged user
Comment: At what point does this fail? During installation or while running DemoBench?
Comment: No failure, the installer asks for admin user/pass.
Answer: Based on your special case, I would suggest you to try to use the node-explorer (link: https://github.com/corda/node-explorer/releases) instead of the Demo bench.
The Corda DemoBench is used to demo Corda-finance app only, whereas the recent released node-explorer is capable of running whatever CorDapp of your choice.
It not only is a replacement of DemoBench, but also is a good tool to show case your PoC and not worry about developing a front end UI.
Video walkthrough at: https://www.youtube.com/watch?v=cn2lhS8pjRs&t=841s


Derivation of the mean and variance of the logit transform of a Beta random variable

Question: I'm interested in the distribution of the logit transform of a $Beta(\alpha, \beta)$ random variable; that is, the distribution of $X$ where $Y\sim Beta(\alpha, \beta)$ and $X = {\rm logit}(Y)$.  I've derived the PDF of this distribution as
$$p_X(x;\alpha,\beta) = \frac{1}{B(\alpha,\beta)} \left(\frac{1}{1 + e^{-x}}\right)^\alpha \left(1 - \frac{1}{1 + e^{-x}}\right)^\beta,$$
where $B(\alpha, \beta)$ is the complete beta function.  To get the expected value of this distribution, I use the Wikipedia derivation of the geometric mean of the beta distribution, recognizing that
$${\rm logit}(x) = \log(x) - \log(1-x).$$
This gives me $E[X;\alpha,\beta] = \psi(\alpha) - \psi(\beta)$, where $\psi$ is the digamma function.  In reviewing the Wikipedia derivation, I notice a peculiar substitution:
$$\int_0^1 \log x\  x^{\alpha-1} (1-x)^{\beta-1} dx = \frac{\partial}{\partial\alpha}\int_0^1 x^{\alpha-1} (1-x)^{\beta-1} dx.$$
This step has no citation in the article.  Can anyone point me to a resource which shows the derivation of this identity?
It should go without saying that when the identity is established, computing the mean and variance becomes straightforward.
Answer: I just realized this shortly after posting: the missing step outlined in the question depends on the identity
$$\frac{\partial}{\partial\alpha} x^{\alpha-1} = \log(x) x^{\alpha-1},$$
which is easily proven.


How to create a RAM Drive (RAM Disk) in Windows 2008 R2?

Question: There are lots of tools for creating RAM drives. None of them seem to work for windows 2008 R2. Does anyone know if this is possible and if so how. Does anyone know of a tool that does work?
I've tried the gavotte ram disk. It doesn't work. When i try to install it it just sais "Failed". I don't see log files anywhere. I've tried a couple of other ones (forgot the names) to no avail.
Any ideas?
Thanks
Answer: We've got an old version of the StarWind iSCSI Target software that works in 2008 R2 and can create RAM disks. It's not free, and it comes with an iSCSI wrapper, but it still works.
Answer: ImDisk is a virtual disk driver for Windows NT/2000/XP/Vista/7/8 or Windows Server 2003/2008/2012
http://www.ltr-data.se/opencode.html/#ImDisk
Current version 1.8.0 built 01 May 2014
Answer: Wikipedia seems to have a pretty complete list:
http://en.wikipedia.org/wiki/List_of_RAM_drive_software#Microsoft_Windows
There are a lot of others in addition to ImDisk and StarWind.


Is it possible that an Administrator do not have read/write access to a certain drive?

Question: I am in the process of writing some scripts to check a newly create windows server machine for certain conditions, like if user have admin rights, a particular drive exists, user have read/write access to that drive etc.
I was struggling a bit with checking of read/write permissions when I started thinking - Is it possible for an Admin to not have permissions on a certain drive?
I tested this by trying to create folders in user directories of other admins and i was able to do so. If it is impossible not to have write access as admin, i will drop this check. But if it is possible, then how can i check if i do not have the write permissions ?
Comment: `Is it possible for an Admin to not have permissions on a certain drive?` - Yes, it is possible.
Answer: Yes, it is possible.
I have created the user "Test" and added it to the local administrators group:

I have created a folder "ServerFault" on my desktop and removed "Administrators" permissions:

I start a shell as my "Test" user, and try to access this directory:

So even though the user is an Administrator, the individual folder permissions block the access.
How to check programmatically if you have write permissions largely depends on what language you are writing in, and would rather be a question for StackOverflow.
Edit 1:.. but hey, I can give you pointers.
In C++ for example, you could use the OpenFile function to open a file for writing.
If the function fails, you can call GetLastError(), if this error value is 5, you have no write access as the user that's running your program.
Edit 2: Since you're using Powershell, you could use the CACLS command and parse the outputs.

PS C:\Users\csa> cacls C:\temp | findstr "Administrator"
C:\Temp BUILTIN\Administrators:(ID)F
        BUILTIN\Administrators:(OI)(CI)(IO)(ID)F

From the "help":

 Perm can be: R  Read
              W  Write
              C  Change (write)
              F  Full control

and

 Abbreviations:
    CI - Container Inherit.
         The ACE will be inherited by directories.
    OI - Object Inherit.
         The ACE will be inherited by files.
    IO - Inherit Only.
         The ACE does not apply to the current file/directory.
    ID - Inherited.
         The ACE was inherited from the parent directory's ACL.

So in this case, the users from the builtin Administrators group have Full control because they Inherited it from the permissions set on the C:\ directory.
Comment: I've updated my answer :-) You still have to parse the outputs tho, I suck at powershell!
Comment: Thanks. This proves i was wrong to assume that. I am looking for some command in CMD or powershell to check if current user have write access or not. If you have some nice way of doing that (no .bat or .ps1) then it would be great.


Modulate from A minor to D major

Question: Can you recommend a smooth way to modulate from A minor to D major? I know a way to modulate down a fifth between major/major, but cannot really apply it here.
My ideas would be modulating to C major first and then to D major, or dominanticize a minor. Do you have practical examples?
Comment: I'm not sure whether it's "smooth" enough, but personally I'd just turn Am into AM and you've got your dominant! (Or maybe that's what you meant by "dominanticize.")
Comment: I've voted to close as a duplicate, but in addition there are two problems here: 1) the question just calls for a list of answers of equal value, and 2) it's borderline opinion-based.
Comment: Can you say a bit more about the context?  If you edit the question to frame it in terms of prior harmonies and the musical idiom, it might be made less opinion-based.
Comment: Hi @AndyBonner, yes.
Answer: Max Reger ("Supplement to Modulation") suggests a-d-Eb/G-A-D or i-iv=i-N63-V-I.
I had thought of a-d/F-F7-Bb7b5-D/A-A(7)-D; or extended a-d7-G7-F7-Bb7b5-D/A-A7-D.
Answer: There are thousands of ways of doing this. You could for example simply go
am - F - G - A(7) - D
which shortly modulates to C major, but resolves in an altered deceptive cadence, which gives us the dominant for D.
You could do something like
am - B7 - E7 - A7 - D
Or
am - f#ø - B - em - A7 - D
If you want you can do some altered mediants like
am - dm - F - Bb - Gb - D
Answer: Many ways! Simple straightforward, just go Dm>D.
Or use the dominant of both to get from Dm>D.
Or tts:E♭7>D.
Too many to mention, really.

Modulate from A minor to D major


CSS correto Div > li > span

Question: Tem uma parte no meu código que não estou conseguindo alterar o css.

Nome - Endereço Site

Nome - Endereço Site

Nome - Endereço Site

Tentei alterar assim:
.AlterarCSS > li > span{
    background: yellow;
}

Agradeço ajuda
Comment: na div que contem o `ul`
Answer: O simbolo > em um seletor CSS garante que o próximo elemento será um filho imediato, e, no seu caso, o filho imediato é o ul.
Para obter o resultado esperado, utilize o seguinte seletor:

.AlterarCSS > ul > li > span {
    background: yellow;
}

Nome - Endereço Site

Nome - Endereço Site

Nome - Endereço Site

Para mais informações sobre seletores CSS, utilize o guia de referência  CSS
Answer: Seletor filho
Um seletor filho tem como alvo um filho imediato de um elemento. O seletor filho consiste de um ou mais seletores simples separados por um sinal de maior ">". O elemento pai fica à esquerda do sinal ">", e é permitido deixar espaço em branco entre o elemento de combinação e os seletores.
A regra a seguir aplica-se a todos os elementos strong que sejam filhos de um elemento div:
div > strong { color:#f00; }

Somente elementos strong que sejam descendentes diretos do elemento div serão afetados por esta regra. Se houver qualquer outro elemento entre o elemento div e o elemento strong na árvore do documento, o seletor não se aplicará. No exemplo a seguir, somente "Texto um " será afetado pela regra:

    Texto um

Texto dois

Veja Mais sobre Seletores

Logo, seu código deverá ficar assim:

.AlterarCSS > ul > li > span{
    background: yellow;
}

Nome - Endereço Site

Nome - Endereço Site

Nome - Endereço Site

Answer: Retire o ">" do CSS tente assim:
.AlterarCSS li span{
    background: yellow;
}

Ou faça dessa forma que define os filhos corretamente:
.AlterarCSS > ul > li > span{
    background: yellow;
}

Answer: Experimente assim:
.AlterarCSS ul li span {
    background: yellow;
}

CSS correto Div > li > span


How should i make infinte ground ?

Question: I'm trying to make a simplified version of crazy taxi . For the first step i need to make an infinite ground . I'VE searched online but couldn't find any examples .
Can i find any example of how to do this ?
Comment: What you are looking for is called chunks. You divide visible portion of terrain into chunks and load them depending on players position. Basically what @ThomasCook described.
Comment: Let's assume - Draw distance of 1,000 units. So, you'll only ever need to draw 2,000 square units of ground at any given time (assuming player in center). So, you could have a 2,000 square unit "tile". You would only ever need to have 9 of these in the scene at any time (with the player in the center tile). As the player moves across the center tile to an edge tile, you would remove the tiles from the farthest edge from the player and add them to the edge ahead of the player.
Comment: If you don't have repeating terrain (i.e. you can't just keep 9 tile references in memory because you have 100's of different tiles - image Skyrim)then you could look into LoadAsync (which lets you load resources on a background thread).

https://docs.unity3d.com/ScriptReference/Resources.LoadAsync.html

Also, this question is probably more suitable for GameDevExchange.
Answer: This is a very broad question I try to give a very simplified answer to get you going.
To create endless road you need some sort of procedural function that generates corners for your track. If you do not need to backtrack you can cook something up yourself like (in X distance turn X degrees to the right). If you do need to backtrack you need something like perlin/simplex noise that always generates the same value based on 1 or more other values. You could use total distance to get the curve in the road.
You simply keep generating the world on the fly and unload pieces of the world you don't need any more. If the player can alter the world like destroying street furniture or leaving skitmarks you need to implement a chunk system. When you backtrack and generate a cerain part of the world with your procedural function you can have permanent changes the player made in that specific part by saving and loading to the chunk. Much like Minecraft does it actually.
Answer: https://www.youtube.com/watch?v=rhTPxrJICVg&list=PLLH3mUGkfFCXQcNBz_FZDpqJfQlupTznd
N3K makes an infinite runner in Subway Surfers style, meaning ground coming from the back and going towards the camera.
The above link is to his tutorial series.

How should i make infinte ground ?


How to boost input velocity of a "weak" digital piano used as a MIDI controller in Bitwig?

Question: In my studio setup, I have a Yamaha P-115 digital piano and a M-Audio CTRL49 keyboard controller. Both are bulky, therefore I have one out at a time only. I use Bitwig under Windows as my audio workstation.
The digital piano is convenient to record ideas when I "hit the walls" of the 49 keys. But it has a problem. When I strike the keys as hard as I can on it, the recorded velocity is really weak. Significantly weaker than if I press the M-Audio keys with a reasonable force. I tried changing the curves from the keyboard using the available settings from the manual; this did not help at all.
Pushing up the track volume can be a makeshift solution but not viable in the long run, especially with instruments that have varying timbres depending on velocity.
The other solution would be to put a "velocity boost" on the software side. Something that would remap the velocity ranges from the input. The following possibilities came to my mind:

Adding a Note Velocity effect before the instrument in every track. It helps a bit, but I need to disable it in all tracks when I switch to the other controller for mixing and arranging.

Writing an input script from scratch that boosts note velocities before sending them to the workstation. Still requires some learning.

Would you have another possible solution? The ideal would be to have the velocity boost set up per MIDI controller rather than per track.
Comment: You need to tell us what your DAW is. This type of thing can easily be done in the Logical Editor* in Cubase. [They may have changed its name over the years, I've lost track, but it's been there since the late 90's] *(just for Tim, if you read this - there's another book chapter in that)*
Comment: My DAW is Bitwig Studio - I mentioned "audio workstation" perhaps it is not clear.
Comment: Ah, I missed it in the title. Sorry, I'd never even heard of it, so I've no idea of its capabilities. It's probably time for a dig through the manual.
Answer: You don't mention whether you suspect it to be a mechanical problem with the Yamaha's keybed (where all the rubber membranes and PCB contacts are).  If so, it might be worth dismantling and giving it a clean with Isopropyl alcohol.  You should be able to find a teardown video on YouTube.
If not mechanical, have you tried a factory reset on the Yamaha keyboard?  It might seem obvious, but perhaps you've accidently input a key combination that's messed things up.  Also, the manual states that:

Touch Sensitivity cannot be used for jazz organ,
pipe organ, rock organ, or harpsichord voices.

Again, plain enough, but it might be a quirk of the keyboard's routine.  I'd also check whether there's a local MIDI setting, and if so, perhaps try disabling or enabling it.
Another option is to use a VST plugin to modify the incoming velocity.  Here's a freeware one:
https://www.codefn42.com/veloscaler/index.html
HTH


Cartesian Product of Borel Sets is Borel Again

Question:
Let $E$ and $F$ be Borel measurable subsets of $\mathbb R^{d_1}$ and $\mathbb R^{d_2}$, respectively. Then $E \times F$ is also Borel measurable in $\mathbb R^{d_1 + d_2}$.

I suppose it is necessary to show that elements of a generator of Borel $\sigma$-algebra on $\mathbb R^{d_1 + d_2}$ is Borel. That is, show that rectangles, i.e., Cartesian product of intervals, are Borel. It seems that I need to use Fubini' theorem. But I do not know how. Any help, please? Thank you!
Answer: Hint: Let $A = \left\{ E \subseteq \mathbb{R}^{d_1} \mid \text{$E \times \mathbb{R}^{d_2}$ is Borel in $\mathbb{R}^{d_1 + d_2}$} \right\}$. Show that $A$ is a $\sigma$-algebra containing all open sets of $\mathbb{R}^{d_1}$, hence all Borel sets. Then make a similar argument for $F$.
Comment: Why can I say $E^c \times \mathbb R^{d_2}$ is Borel if $E \times \mathbb R^{d_2}$ is Borel? Also how to proceed after showing $A$ is a sigma algebra?
Comment: Could you add a bit more detail, please? I do not see why $A$ is a $\sigma$-algebra and also do not know how to proceed after that.
Comment: Can you check the defining properties of a $\sigma$-algebra?
Comment: It's the complement in $\mathbb{R}^{d_1 + d_2}$. What can you say about a $\sigma$-algebra of subsets of $\mathbb{R}^{d_1}$ that contains all open sets?
Comment: It contains the Borel sigma algebra on $\mathbb R^{d_1}$. Then the similar argument shows that, say $B$, contains all the Borel sigma algebra on $\mathbb R^{d_2}$. Then $A\times B$ will contain the Borel sigma algebra of $\mathbb R^{d_1+d_2}$.
Comment: What does that say about $E$?
Comment: I edited my comments. It seems that you did not follow my suggestion to start with a rectangle here.
Comment: Well, instead of open sets in $\mathbb{R}^{d_1}$, you can use rectangles in $\mathbb{R}^{d_1}$.
Comment: No, I don't think what you wrote in your comments is right. What is $B$?
Comment: $B$ is corresponding sigma algebra contain $F$ defined similarly as for $A$.
Comment: $A \times B$ has nothing to do with this. What does it tell you that $E \in A$?
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/18785/discussion-between-user156460-and-mike).
Comment: Sorry, I'm not registered, so I can't chat.
Comment: $E \in A$ by definition means that $E\times \mathbb R^{d_2}$ is Borel in $\mathbb R^{d_1 + d_2}$. Right?
Comment: Okay, and for $F$?
Comment: $F \subset \mathbb R^{d_2}$ is Borel and $\mathbb R^{d_1}\times F$ is Borel in $\mathbb R^{d_1+d_2}.$
Comment: How can you conclude that $E \times F$ is Borel?
Comment: OK. Take intersection of $E\times \mathbb R^{d_2}$ and $\mathbb R^{d_1} \times F$.
Comment: Right. You've got it.
Answer: I don't see the meaning of constructing the $\sigma$-algebra $A$ in Mike's answer. Well, I think actually we can avoid that redundant construction.
What we need to prove is just: If $E$ is a Borel set in $\mathbb R^{d_1}$, then $E\times \mathbb R^{d_2}$ is a Borel set in $\mathbb R^{d_1+d_2}$.
Proof: This is simple. Because the set in the second position of the Cartesian product is the whole space $\mathbb R^{d_2}$, we can interchange the operations of taking Cartesian product and taking union/intersection. We can prove a similar result for $F$ in the same way. And therefore, if $E$ is a Borel set in $\mathbb R^{d_1}$ and $F$ is a Borel set in $\mathbb R^{d_2}$, then $E\times F(=[E\times \mathbb R^{d_2} ]\cap [\mathbb R^{d_1}\times F]\,)$ is a Borel set in $\mathbb R^{d_1+d_2}$.
$\tag*{$\square$}$
Comment: And how do you know that $E\times \Bbb{R}^{d_2}$ is a Borel set? Btw typo in last line it should be $d_1+d_2$.
Comment: @peek-a-boo I have proved it by words that *Because the set in the second position of the Cartesian product is the whole space $\mathbb R^{d_2}$, we can interchange the operations of taking Cartesian product and taking union/intersection.* $\textbf{Mathematical Proof:}$ Since $E$ is Borel in $\mathbb R^{d_1}$, we may write $E$ as a countable union/intersection of open sets in $\mathbb R^{d_1}$, where there may be finite number of set operations involved but the reasoning is the same. Therefore, $E=\cup_i A_i$ for some $A_i$ open in $\mathbb R^{d_1}$, where the union is a countable union.
Comment: (cont') Thus, $E\times \mathbb R^{d_2}=(\cup_i A_i)\times \mathbb R^{d_2} = \cup_i [A_i \times \mathbb R^{d_2}]$, where $A_i \times \mathbb R^{d_2}$ is open in $\mathbb R^{d_1} \times \mathbb R^{d_2}$, because $A_i$ and $\mathbb R^{d_2}$ are open in $\mathbb R^{d_1}$ and $\mathbb R^{d_2}$, respectively. So $E\times \mathbb R^{d_2}$ is a Borel set. $\blacksquare$ Definitely, $E$ can be something like $\cup_i \cap_j \cup_k A_{i,j,k}$, but the reasoning is pretty much the same.
Comment: I doubt that's true about Borel sets. Im no set theory wiz but a brief search about Borel hierarchy and the like already suggests that even if what you said is true (which I highly doubt) it is very non-trivial. The other approach of simply showing something is a $\sigma$-algebra containing the basic things you want is the much simpler option (and also this idea is used in several proofs).
Comment: Sigma algebras are typically very huge beasts, and I don't think they usually come with "simple explicit descriptions". Working with the general abstract definition of a generated sigma-algebra often suffices (atleast I've gotten by without delving into any further set theory).
Comment: @peek-a-boo Borel sigma algebra is generated by open sets by definition. I was working on the generated elements, which is a general approach as well. I actually proved that the Cartesian product of a countable union generated elements (i.e. open sets in $\mathbb R^{d_1}$) and the set $\mathbb R^{d_2}$ equals to the countable union of the Cartesian product of the generated elements and the set $\mathbb R^{d_2}$. We can similarly prove that Cartesian product can be swapped with a countable intersection or set complement. A Borel set must be formed by generated elements with these 3 operations.
Comment: @peek-a-boo Therefore, we rigorously proved that $E\times \mathbb R^{d_2}$ is Borel. $\blacksquare$ I was just too lazy to write down everything, but every step in my reasoning can be written out with the set-theoretic language such that it is as rigorous as you want.
Comment: Im not disputing the stuff about cartesian products and interchanging with countable unions/intersections. That's all trivial stuff. What i am disputing is your very first claim about Borel sets. Yes, by definition the Borel sigma algebra is generated by the open sets, and yes these include all countable intersections and unions of open sets. But how can you be sure these are all? I doubt it. See [here](https://math.stackexchange.com/a/1614718/568204). In general I doubt the generated sigma algebra has a nice description.
Comment: @peek-a-boo We don't care what a specific Borel set looks like. It must be formed by countable union, countable intersection, and set complement. You can perform finitely many set operations from these three. All these 3 operations can be swapped with the operation of taking Cartesian product. So, $E \times \mathbb R^{d_2}$ is Borel as well.
Comment: If you don't care what a specific Borel set looks like, and you're only using that unions, intersections comlements play nicely with cartesian products then this proof is essentially the same as the other one. The other answer is pretty direct and tells us to show something is a sigma algebra which contains open sets, and hence contains all Borel sets.


Queue realisation C++

Question: My realization of queue works in a strange way: when I enqueue new elements - all is right, but when I start to dequeue - it removes the last added element despite the fact that at this moment my head is 1 and tail is bigger. What are the pecularities of indexing in C++? Why does it behave like this?
Here is my full code:
https://hastebin.com/odibusacuk.cpp
class Queue{
public:
int head=1;
int tail=1;
int q[MAX];

int Queue::enqueue(int x){
    if (isFull()){
        return 0;}
    else {
        q[tail]=x;
       cout << tail << " here is a tail\n";
        if (tail==sizeof(q)){
            cout << tail << " this is tail\n" ;
            tail=1;}
        else {
            tail=tail+1;
            }
        return x;
        }
}
int Queue::dequeue(){
if(isEmpty()){
    cout << " the queue is empty\n";
    return 0;}
else {
    int x=q[head];
    if (head==sizeof(q)){
        head=1;}
    else {
        head=head++;
return x;}
    }
return 0;
}

Comment: Please include a [mcve].
Comment: You need to show us what you have done so that we could correct it.
Comment: my output is:
4 9 6 3 enqueued
1-head and tail-5
3 dequeued
Comment: *What should I change?* -- Bad ask here.  Debugging your own code is part of learning how to write programs.  What debugging have you done?
Comment: i printed head and tail indices and elements but i can't understand why it works in this way. I mean, when I print I see that q[1] = 4 q[2] =9 etc but when i remove - the last element with(as i suppose) the last(tail) index is  removed
Comment: I can not reproduced it: http://coliru.stacked-crooked.com/a/6140f1fd138bc8b4
Comment: it's strange. it works different in codeblocks..
Comment: @SamOsterman -- `sizeof(q)` -- If you expected this to give you the number of elements in the array `q`, this does not give you the number of elements in the array.
Answer: The problem you are having is because when you do something like
cout << k.enqueue(4) << " " << k.enqueue(9)  << ' ' << k.enqueue(6) << " " << k.enqueue(3) << " enqueued\n ";

it is not specified in what order these functions will be called.
In your example, they are being called from right to left.
This means your queue is actually
{ 0, 3, 6, 9, 4 }

0 is there since your are skipping element 0 and going directly to element 1.
Your head is pointing to 1, thus you will dequeue 3.
You can read more here.

Queue realisation C++


Dúvida sobre $.getJSON e history.pushState

Question: Estou estudando sobre history.pushState e pretendo desenvolver um site como forma de estudo como este http://html5.gingerhost.com/
Em relação ao jQuery (função para carregar o novo conteúdo) eu entendi perfeitamente, mas me surgiram algumas dúvidas:

Existe diferença entre window.history.pushState ou somente history.pushState?
Qual a função do primeiro atributo (nesse caso "null") window.history.pushState(null, "titulo", "novaurl")?
O segundo atributo, responsável pelo novo título, não funciona. Proceder com document.title = "novoTitulo" é a forma correta?
No caso do cite citado como exemplo, utiliza-se $.getJSON para retornar os dados solicitados, e essa parte eu até entendi como retornar os dados do PHP, mas, minha grande dúvida é: se eu possuo um site grande, como vou retornar todos os dados sendo que eu utilizo Templates para auxílio do PHP e HTML (incluindo consultas ao banco, e etc), isso é possível ou terei que mudar minha estrutura? Pois, pelo que percebi os dados retornados são de acordo com a variável cid passada através do jQuery, e os dados são retornados com um echo json_encode()...?
Há mesmo incompatibilidade da função window.history.pushState() com o IE?
Já vi no Github uma biblioteca chamada History.js. Pra que ela serve já que a função history já é nativa dos navegadores (estou perguntando porque realmente não consegui entender)?

Obrigado!
Comment: Igor, o assunto do getJSON é totalmente independente da questão do histórico. Sugiro você tirar isso da pergunta e postar como uma pergunta separada.
Comment: Sim, eu sei, acontece que como no exemplo que citei essa função é utilizada, gostaria de saber se a mesma poderia ser utilizada em sites grandes, como citei na pergunta...
Answer: Vou responder ponto a ponto sobre a parte do histórico. Quanto ao getJSON, acho que é caso para uma pergunta separada, como eu já disse no comentário acima (não leve a mal, somos malucos por organização aqui no site, e o ideal é que as perguntas sejam focadas, para que possam ajudar a outras pessoas).

Existe diferença entre window.history.pushState ou somente history.pushState?

Não. Nos browsers, window é o objeto global. Tudo o que está pendurado em window pode ser acessado com ou sem o window..

Qual a função do primeiro atributo (nesse caso "null") window.history.pushState(null, "titulo", "novaurl")?

Isso é uma das coisas mais interessantes da API de histórico. Você pode passar um objeto que representa o estado da aplicação naquele dado momento. Quando a pessoa retorna àquele ponto (via botão "voltar" do browser, por exemplo), é disparado um evento popstate, e o listener desse evento recebe o objeto de estado correspondente. Assim você pode restaurar o estado da aplicação sem precisar buscar dados no servidor.
O objeto a ser passado deve ser um objeto simples que possa ser serializado (ou seja, sem funções/métodos, e eu também evitaria conteúdo herdado via protótipo). O objeto serializado deve ocupar no máximo 640k caracteres.

O segundo atributo, responsável pelo novo título, não funciona. Proceder com document.title = "novoTitulo" é a forma correta?

O objetivo do segundo argumento para pushState não é alterar o título da página, e sim gravar um título no histórico. Se quer alterar o título atual, de fato precisa usar document.title = "novoTitulo".

Há mesmo incompatibilidade da função `window.history.pushState() com o IE?

Sim, pelo que sei só está disponível a partir do IE10.

Já vi no Github uma biblioteca chamada History.js. Pra que ela serve já que a função history já é nativa dos navegadores (estou perguntando porque realmente não consegui entender)?

O objetivo é justamente oferecer algo próximo à API oficial em browser onde ela não é suportada, como versões do IE anteriores à 10. A biblioteca usa mecanismos de fallback como hashes para lidar com os estados e trocas de URL.
Documentação relevante:

Guia de uso da History API, MDN
Especificação
Comment: Obrigado por responder. Somente mais uma pequena dúvida. Então vale a pena utilizar da biblioteca History.js?


The longest word in Weyl group and positive roots.

Question: How to write down a reduced decomposition of the longest word in a Weyl group? For example, how to write down a reduced decomposition of the longest word in type B3 Weyl group? For a decomposition of the longest word, how can we write down an ordering of positive roots? I am asking these questions because I am trying to understand Section 2.4 of http://arxiv.org/abs/math/0202148. Thank you very much.
Comment: To address the ordering question: One common way of ordering the positive roots (independent of a reduced decomposition) is to scale the roots so that the sum of their coefficients is 1, and then use the lexicographic order. Given a reduced decomposition $s_1 \cdots s_{\ell}$, a natural ordering of the roots associated to that particular decomposition $\alpha_1 < s_1(\alpha_2) < s_1s_2(\alpha_3) < \cdots < s_1\cdots s_{\ell - 1}(\alpha_{\ell})$, where $\alpha_i$ is the simple root associated to the $i$-th generator of the word.
Comment: It occurs to me that I was mixing orders a bit: Given any reduced decomposition for $w$, we can order the positive roots sent negative by $w$ in the order in which the reflections sent them to a negative root. The longest element maps all positive roots to negative roots. The order of the < in my comment is such that there exists a reflection ordering equal to it. (Hence the conflation of these two orders in my first comment.)
Comment: @user9791: I added my current *best guess* to the meaning of order. Can you comment?
Comment: The ordering described by @HughDenoncourt is related to the one I had in mind (but not quite the same). May be I should scratch that part, and let him describe that in an answer?
Comment: @JyrkiLahtonen: There are variations - my construction is recovered from your construction applied to $w^{-1} = s_{\ell} \cdots s_1$. (I succumbed to the order given in Bjorner and Brenti, though they order reflections instead of roots. I prefer your order because of the nice interpretation regarding when a positive root is sent negative.) I don't think I can say it better than you just did, so I favor leaving your answer in!
Comment: @HughDenoncourt Can you give me the references of ordering roots in your first comment?
Comment: Section 5.2 of Bjorner and Brenti's "Combinatorics of Coxeter Groups". The order is described within the proof of Proposition 5.2.1 on page 137.
Comment: @HughDenoncourt Thank you. In your first comment, by $"<"$ you meant "reflection ordering" that defined in Bjorner and Brenti's textbook? Isn't it the usual lexicographic order that $\alpha \le \beta \iff \beta -\alpha$ is a linear combination of simple roots with non-negative coefficients?
Comment: For two vectors in $\mathbb{R}^n$ relative to a fixed ordered basis $(a_1,\ldots,a_n) \leq_{lex} (b_1,\ldots,b_n)$ if $a_1 < b_1$ or if $a_1 = b_1, \ldots a_i = b_i$, but $a_{i+1} < b_{i+1}$. Precedence of comparison goes to the initial coordinate where the coordinates differ. (It is similar to alphabetical order, hence the name.) I believe what you are referring to is "height". Among simple roots $\alpha_1,\alpha_2$, $\alpha_1 < \alpha_2$ in lex order but are incomparable in the order you mention. The $<$ I was using is decomposition-based, but can be made to match lex order on roots.
Comment: Yes, you're correct by saying that I'm mentioning "height" of positive roots. My recently question is exact what you say if given reduced expression $w=s_{1}s_{2}\cdots s_{r}$ ($s_{i}$ simple reflection w.r.t simple $\alpha_i$) then $\beta_i:=s_rs_{r-1}\ldots s_{i+1}(\alpha_i), \beta_r:=\alpha_r$ are positive roots sent negative by $w$. I wanted to know that can we order them as $\beta_r<\beta_{r-1}<\ldots<\beta_1$ with $<$ I mean the order I defined previously?
Comment: I was asking a similar question in here http://math.stackexchange.com/questions/1513075/a-chain-between-two-positive-roots-having-same-length. If you have time plz take a look.
Answer: Here's an algorithm for finding such a reduced word decomposition.

Start with $w=e$ (=the empty word) and $\lambda=-\rho=-\sum_i\lambda_i$, where the $\lambda_i$ are the fundamental dominant weights determined by
$\langle \lambda_i,\check{\alpha_j}\rangle=\delta_{ij}$. Here $\alpha_1,\ldots,\alpha_n$ are simple positive roots.
If there exists an index $i$ such that $\langle\lambda,\alpha_i\rangle <0$, let $i_0$ be one of those (for example the smallest index, so you don't need to check too many). If no such $i$ exists, then exit with output $w$.
Replace $w$ with $s_{i_0}w$ and $\lambda$ with $s_{i_0}(\lambda)$. Go back to step 2.

Here initially $\lambda$ is in the negative of the dominant Weyl chamber. Each iteration brings it one simple reflection closer to the dominant chamber, and in the end it will reach it. The number of simple reflections will be equal to the number of positive roots, so you can use that as a stopping condition as well.

Let's do an example run with $B_3$. Here $\alpha_3$ is the short simple root.
$$
\begin{array}{c|l}
\lambda& w\\
\hline
(-1,-1,-1) &e\\
(1,-2,-1) &s_1\\
(-1,2,-5) &s_2s_1\\
(1,1,-5) &s_1s_2s_1\\
(1,-4,5) &s_3s_1s_2s_1\\
(-3,4,-3) &s_2s_3s_1s_2s_1\\
(3,1,-3) &s_1s_2s_3s_1s_2s_1\\
(3,-2,3) &s_3s_1s_2s_3s_1s_2s_1\\
(1,2,-1) &s_2s_3s_1s_2s_3s_1s_2s_1\\
(1,1,1) &s_3s_2s_3s_1s_2s_3s_1s_2s_1
\end{array}
$$
We knew in advance that the root system of type $B_3$ has nine positive roots, so predictably we get a weight in the fundamental Weyl chamber after nine simple reflections.
This presentation as a product of simple reflections is not unique (we could have used another simple reflection at multiple points). Undoubtedly you knew about that already.

I am not positive about the meaning of ordering of positive roots. I suspect (an educated guess based on the context) that it is the order in which the partial words building up the longest element map the positive roots to negative ones.  Let $w_i$ be the element of the Weyl group that is the product of $i$ first simple reflections in our decomposition of the longest element. To such an element of the Weyl group we can associate the set $\Phi_i$ of those positive roots $\beta$ such that $w_i(\beta)$ is a negative root.
It is known that $|\Phi_i|=i$. It is also known that if $w_{i+1}=s_{i+1}w_i$, then
$\Phi_i\subset \Phi_{i+1}$ and that the positive root in $\Phi_{i+1}$ "missing" from
$\Phi_i$ is then $\beta_{i+1}:=w_i^{-1}(\alpha_{i+1})$. Thus we get a vaguely natural ordering related to the decomposition: $\beta_1<\beta_2<\beta_3<\cdots$. With 2-dimensional
root systems you then get all the positive roots "in a rotational order" (which is why I am guessing that this is what it means). For example in type $A_2$ you get first one of the simple roots, then the highest root (=the one between the simple roots), and the other simple root is the last to join in.
I am not too confident about this, because it is also possible to use partial words clipped from the other end of the decomposition, and build a slightly different interpretation but analogous ordering. If the paper you cited has worked out examples, then it should be possible to reverse engineer this. I don't have the time to delve deeper into this today. Does this fit at all?


Starting my react project using npm start gives error

Question: Was able to do a npm install but everytime during npm start command this error is displayed.
Is there any missing node modules or what?
Already tried deleting node modules , package.lock files, tried clearing cache but nothing works.
<code>      throw er; // Unhandled 'error' event
      ^

Error: spawn cmd ENOENT
    at Process.ChildProcess._handle.onexit (internal/child_process.js:269:19)
    at onErrorNT (internal/child_process.js:465:16)
    at processTicksAndRejections (internal/process/task_queues.js:80:21)
Emitted 'error' event on ChildProcess instance at:
    at Process.ChildProcess._handle.onexit (internal/child_process.js:275:12)
    at onErrorNT (internal/child_process.js:465:16)
    at processTicksAndRejections (internal/process/task_queues.js:80:21) {
  errno: -4058,
  code: 'ENOENT',
  syscall: 'spawn cmd',
  path: 'cmd',
  spawnargs: [ '/c', 'start', '""', '/b', 'http://localhost:3000/' ]
}
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! firstname.lastname@example.com watch:js: `react-scripts start`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the firstname.lastname@example.com watch:js script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Cedz ThinkPad 1\AppData\Roaming\npm-cache\_logs\2021-03-14T09_27_08_677Z-debug.log
events.js:292
      throw er; // Unhandled 'error' event
      ^

Error: spawn taskkill ENOENT
    at notFoundError (C:\Users\Cedz ThinkPad 1\Documents\FrontEnd\node_modules\npm-run-all\node_modules\cross-spawn\lib\enoent.js:6:26)
    at verifyENOENT (C:\Users\Cedz ThinkPad 1\Documents\FrontEnd\node_modules\npm-run-all\node_modules\cross-spawn\lib\enoent.js:40:16)
    at ChildProcess.cp.emit (C:\Users\Cedz ThinkPad 1\Documents\FrontEnd\node_modules\npm-run-all\node_modules\cross-spawn\lib\enoent.js:27:25)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:277:12)
Emitted 'error' event on ChildProcess instance at:
    at ChildProcess.cp.emit (C:\Users\Cedz ThinkPad 1\Documents\FrontEnd\node_modules\npm-run-all\node_modules\cross-spawn\lib\enoent.js:30:37)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:277:12) {
  code: 'ENOENT',
  errno: 'ENOENT',
  syscall: 'spawn taskkill',
  path: 'taskkill',
  spawnargs: [ '/F', '/T', '/PID', 35492 ]
}
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! email@example.com start: `npm-run-all -p build:css watch:*`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the email@example.com start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Cedz ThinkPad 1\AppData\Roaming\npm-cache\_logs\2021-03-14T09_27_08_781Z-debug.log
r.com/l2Q0M.png```
</code>
Comment: Can you share your package.json script?
Comment: I figure it out that you are using a very old version of react-spark (1.0.0) but the latest is 4.1.1. Try to update it and try again: https://www.npmjs.com/package/@sparkdesignsystem/spark-react
Answer: okay check your node version and if it is latest try to install the node version 10 or something not the latest. it works for me , i hope it will help


How to write to a JSON file in the correct format

Question: I am creating a hash in Ruby and want to write it to a JSON file, in the correct format.
Here is my code:
tempHash = {
    "key_a" => "val_a",
    "key_b" => "val_b"
}
fJson = File.open("public/temp.json","w")
fJson.write(tempHash)
fJson.close

And here is the contents of the resulting file:
key_aval_akey_bval_b

I'm using Sinatra (don't know what version) and Ruby v 1.8.7.
How can I write this to the file in the correct JSON format?
Comment: What you're doing is actually something I use a lot to document the JSON and YAML structures I use. I'll write a small piece of code to save the YAML/JSON to a file, then build same structures showing what the data should look like before and/or after dumping and reloading. So, though your code isn't working quite right, stick with this process as it makes life easier in the long run.
Comment: Have a look at this SO answer: http://stackoverflow.com/questions/1684588/how-to-do-ruby-object-serialization-using-json
Answer: Require the JSON library, and use to_json.
require 'json'

d = {
  "a": 1,
  "b": 2,
}

File.open('out.json', 'w') do |f|
  f.write(d.to_json)
end

Your temp.json file now looks like:
{"a": 1, "b": 2}

Comment: `JSON.pretty_generate(tempHash)` is also rad http://www.ruby-doc.org/stdlib-1.9.3/libdoc/json/rdoc/JSON.html#method-i-pretty_generate
Comment: Minor improvement: I suggest the block form: `File.open(...){ |f| f << h.to_json }`
Comment: Is there any version now which does not generate the memory overhead of building the string in memory first?  This is a larger memory fragmentation problem if the json is getting into the megabytes range. 10 years later somebody should have optimized it
Comment: This answer is now **well** out of date (for Ruby 1.8). See https://stackoverflow.com/a/46829359/1852005 for a much simpler solution using `File.write`.
Answer: With formatting
require 'json'
tempHash = {
    "key_a" => "val_a",
    "key_b" => "val_b"
}
File.open("public/temp.json","w") do |f|
  f.write(JSON.pretty_generate(tempHash))
end

Output
{
    "key_a":"val_a",
    "key_b":"val_b"
}

Comment: @boulder_ruby appending may only make sense if the file format is JSONlines (one JSON object per line) and that hardly ever combines well with `pretty_generate`, unless the consumer of the output is a human. Even then, it's better to generate JSONlines and use something like `jq` to see the output.
Comment: I like the "a+" option. Doesn't clobber existing data.
Answer: This question is for ruby 1.8 but it still comes on top when googling.
in ruby >= 1.9 you can use
File.write("public/temp.json",tempHash.to_json)

other than what mentioned in other answers, in ruby 1.8 you can also use one liner form
File.open("public/temp.json","w"){ |f| f.write tempHash.to_json }

Comment: Use `File.write("public/temp.json", JSON.pretty_generate(tempHash))` (as per other answers) to get pretty JSON formatting in the output.
Answer: To make this work on Ubuntu Linux:

I installed the Ubuntu package ruby-json:
apt-get install ruby-json

I wrote the script in ${HOME}/rubybin/jsonDEMO
$HOME/.bashrc included:
${HOME}/rubybin:${PATH}

(On this occasion I also typed the above on the bash command line.)
Then it worked when I entered on the command line:
jsonDemo


CloudKit. Is it possible to clear Caches\CloudKit\Assets?

Question: I store images in CKRecord as CKAsset. Because of this, used a lot of disk space. Is it possible after fetch images from CKAsset, do the cleaning in at App\Library\Cashes\CloudKit\Assets?
Answer: It's not possible to clean up those files via the CloudKit API.
CloudKit will manage that space for you and should clean up downloaded assets periodically or if a low disk space notification happens. Your application shouldn't need to worry about it.
Answer: I was having the same problem and I actually found a work around:
<code>    let fileManager = NSFileManager.defaultManager()
    let cachePath = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true) as [String]
    let filePath = "\(cachePath[0])/CloudKit/Assets"
    do {
        let contents = try fileManager.contentsOfDirectoryAtPath(filePath)
        for file in contents {
            try fileManager.removeItemAtPath("\(filePath)/\(file)")
            print("Deleted: \(filePath)/\(file)") //Optional
        }
    } catch {
        print("Errors!")
    }
</code>
In essence, I manually navigated to the CloudKit/Asset folder, and retrieved all the CKAssets stored in there, then deleted them one by one.
Answer: Thank you!  This works.  Although the caches directory is now located inside a directory with a UID.
I tried removing the whole cloudkit directory and this worked with seemingly no side effects.  iOS immediately rebuilt it, but reduced the payload of my app from 20Gb+ to 700Mb.
Although iOS takes care of this and ostensibly there's no reason to do it manually, the huge size of my data container was making it impossible to download locally for testing purposes.
Code updated for swift 5.x
<code>let fileManager = FileManager.default
        let cachePath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true) as [String]
        let filePath = "\(cachePath[0])/CloudKit"
        do {
            let contents = try fileManager.contentsOfDirectory(atPath: filePath)
            for file in contents {
                try fileManager.removeItem(atPath: "\(filePath)/\(file)")
                print("Deleted: \(filePath)/\(file)") //Optional
            }
        } catch {
            print("Errors!")
        }
</code>


Exported MySQL database without procedures by mistake

Question: I've exported a database via SSH and I didn't add <code>--routine</code> command to export the routines.
Now I don't have any access to this database, and I have only one .sql file. is there any way to restore and find the routines through PHP code or database structures?
Answer: No, sorry, in this case I think you're out of luck. Looking at the database structure, you won't be able to figure out what a routine might have done. Likewise, looking at the PHP code is probably not going to help. If you know what the routines did (for instance, manipulate data on insert, maintenance by deleting some rows, or some such) you can work through recreating it, but that's basically reverse engineering it based on what breaks when you try to run your application.


How to modify the query that the views integration with the chart API module provides?

Question: I am using Google Charts API module to generate a pie chart of a content type with the fields Blood-group and count representing the sectors.
For this I need to completely alter the query (= select from a different table) that the views integration provides.
My question: Can I use hook_views_query_alter?
Comment: Yes you can. Post the code which you are trying..
Comment: Hmmm. Found it easier to write my own custom module. Greater flexibility. Charting with views on 7 hasn't been really good to me.
Comment: I havent tried with query_alter. In my chart_views module, I added the function chart_views_views_pre_execute() {
  if($view->name=="charts")
   {
       $view->build_info['query']="select field_blood_group_value,count(*) from field_data_field_blood_group group by field_blood_group_value";
   }
}                                                     However, this gave me an Ajax 500 error                                               Thank you
Answer: To create charts in Drupal, there are plenty of modules available. Refer to the comparison of charting modules for an overview. After doing so, it should be clear that the names (and namespaces) of various charting modules are pretty confusing. Therefor I suggest you add a link to the exact 'Google Charts API' module this question is about.
Moreover, if I correctly understand the question, it seems to me that this is a rather straight forward requirement that can be easily addressed with (at least) the Charts module, i.e. the views integration of it (provides a new views style plugin to transform tabular view results into a chart). I recently created quite a lot of new Charts documentation that should help to get started with it.
The Charts module ships with out-of-the-box samples which are straight forward to adapt to fit your needs, e.g. by cloning these samples in a new views display or a new view. Of course there are other alternatives in that comparison that might be a better fit for this specific case.
Be aware: I'm a new (co-) maintainer of both Chart and Charts (confusing module names, I didn't invent them), and the author of the comparison of charting modules.


$K[X]$ module and characteristic polynomial

Question: Let $(V, \phi)$ a $K[X]$-module with $V$ a finite-dimensional vector space.
Do you think that $ V \cong \dfrac{K[X]}{(\chi_{\phi})}$ with $\chi_{\phi}$ characteristic polynomial of $\phi$?
How to prove it? (I know the invariant factor decomposition if needed).
Thanks and regards.
Answer: Presumably, $K$ is a field, $\phi\in \operatorname{End}_K(V)$, and the action of $K[X]$ on $V$ is given by
$$f(X)\cdot v=f(\phi)(v)$$
for all $f(X)\in K[X]$ and $v\in V$.  The answer is no.  Take $V=K^2$ and $\phi=0$.  Then
$$\chi_\phi(X)=X^2$$
so
$$\frac{K[X]}{\big(\chi_\phi(X)\big)}=\frac{K[X]}{(X^2)}$$
is a $2$-dimensional indecomposable $K[X]$-module, but
$$V\cong K\oplus K$$
is decomposable (where each copy of $K$ is the $K[X]$-module on which $X$ acts by $0$).
However, if each irreducible factor of $\chi_\phi(X)$ occurs with multiplicity $1$, then the claim is true.  More generally, let $\Sigma$ be the set of all monic irreducible polynomials in $K[X]$.  For each $p(X)\in \Sigma$, let
$$V^p=\big\{v\in V\big|\exists k\in\Bbb N,\ \big(p(X)\big)^k\cdot v=0\big\}.$$
Then, $V^p$ is a $K[X]$-submodule of $V$ and
$$V=\bigoplus_{p(X)\in \Sigma}V^p.$$
It follows that $V\cong \frac{K[X]}{\big(\chi_\phi(X)\big)}$ if and only if $V^p$ is an indecomposable $K[X]$-module for every irreducible factor $p(X)$ of $\chi_\phi(X)$, or equivalently, the minimal polynomial $\mu_\phi(X)$ of $\phi$ satisfies $$\mu_\phi=\chi_\phi.$$


Unable to Install Microsoft Azure Backup Server

Question: I've been having a problem for the past two days trying install Microsoft Azure Backup Server... I'm very close.
The installation always fails to install the SQL server as shown in the image.
The error logs state:
On a domain controller, you cannot use the built-in Windows service accounts (Local Service or Network Service) as service accounts for Reporting Services
Comment: are you installing on a domain controller?
Comment: Hi Sven, thanks for responding. Yes, I am installing on a domain controller
Answer: Installation of Azure Backup Server on a domain controller is not supported - see this article.

I imagine this is primarily due to the reason you encountered, that installing SQL on a domain controller is also not supported. You will need to use another machine.
Comment: Sam, I didn't realise it wasn't possible to install on a domain controller Thanks


Android widgets not showing on screen

Question: I am trying to make a simple widget but when I want to put it in the screen it just disappear.
I tried this on Api : 23,26 and 30 ,it's all give me the same result.
Manifest.xml
<receiver android:name=".mAppWidgetProvider">

        <intent-filter>
            <action android:name="android.appwidget.action.APPWIDGET_UPDATE"/>
        </intent-filter>

        <meta-data android:name="android.appwidget.provider"
            android:resource="@xml/widget_info"/>

    </receiver>

widget_info.xml
<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:configure="com.app24.test.mAppWidgetProvider"
android:initialLayout="@layout/my_widget"
android:minWidth="250dp"
android:minHeight="70dp"
android:resizeMode="horizontal|vertical"
android:updatePeriodMillis="10000"
android:widgetCategory="home_screen">
</appwidget-provider>

mAppWidgetProvider
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;

public class mAppWidgetProvider extends AppWidgetProvider {

}

my_widget (the layout)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:background="@color/white"
android:padding="8dp">

<TextView
    android:text="Hello world"
    android:textSize="24sp"
    android:layout_weight="1"
    android:gravity="center"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

<Button
    android:text="Click me!"
    android:layout_weight="1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

<Button
    android:text="Click me!"
    android:layout_weight="1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

</LinearLayout>

and I have tried the other solutions but no thing.
Answer: check out logcat and look for some Exception. App widgets are crashing "silently" without any dialog, just doesn't appear. But you should be able to find cause of problem in logs
in your code I see one wrong line:
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
    ...
    android:configure="com.app24.test.mAppWidgetProvider"
    ...

android:configure should point on some Activity, which will be started when your widget will be added to home screen. your line points wrongly on your custom AppWidgetProvider, which isn't an Acticity - system probably tries to start this class as Activity or maybe checks instanceof and as this class isn't Activity then crash occurs. try to remove this line for start (or point on proper class)
Comment: I removed that line and it worked finally !,thank you so much...

Android widgets not showing on screen


Relation between areas of two non-similar triangles with individual proportional sides

Question: Triangle $ABC$ has area $k$ and $D$ is the middle point of $BC$.
We have $AP = 2 \cdot AB$, $AQ = 3 \cdot AD$ and $AR = 4 \cdot AC$. What's the area of triangle $PQR$?
I know that the answer is $k$, but I don't know how to prove it.
Thank you all in advance!
Answer:
Let $\angle PAQ = \alpha$ and $\angle RAQ = \beta$.
$$A_{PQR} = A_{APQ} + A_{AQR}- A_{APR}$$
$$=\frac12 AP\cdot AQ\sin\alpha + \frac12 AR\cdot AQ\sin\beta - \frac12 AP\cdot AR\sin(\alpha+\beta)$$
$$=\frac12 ( 2AB \cdot 3AD\sin\alpha )+ \frac12 ( 3AD \cdot 4AC\sin\beta)
- \frac12 ( 2AB \cdot4AC\sin(\alpha+\beta))$$
$$= 6 A_{ABD}+ 12 A_{ACD} - 8A_{ABC}
=6\cdot\frac k2+12\cdot\frac k2-8k=k$$