How to cycle a list infinitely and lazily in Kotlin?

Question: I have a list of directions and want to find the next direction when I take a right or left turn. Here is the working code I have:
enum class Turn { R, L }
enum class Direction { N, E, S, W }
val directionsInRightTurnOrder = listOf(Direction.N, Direction.E, Direction.S, Direction.W)

private fun calculateNextHeading(heading: Direction, turn: Turn): Direction {
    val currentIndex = directionsInRightTurnOrder.indexOf(heading)
    var nextIndex = currentIndex + if (turn == Turn.R) 1 else -1
    if (nextIndex >= directionsInRightTurnOrder.size)
        nextIndex = directionsInRightTurnOrder.size - nextIndex
    if (nextIndex < 0)
        nextIndex += directionsInRightTurnOrder.size

    return directionsInRightTurnOrder.get(nextIndex)
}

However, this would be so much simpler and easier to read if I could take the directionsInRightTurnOrder list and cycle through it infinitely (and lazily). In Clojure, I can do that, using clojure.core/cycle:

(take 5 (cycle ["a" "b"]))
# ("a" "b" "a" "b" "a")

Another thing that would help is if I could look up in a list using a negative index, like in Ruby or Python:

http://rubyquicktips.com/post/996814716/use-negative-array-indices
Negative index to Python list

Question:

Can I do cycle through a list/collection in Kotlin?
Is there an idiomatic way to do a negative-index-lookup in Kotlin?
Answer: Here's cycle:
fun <T : Any> cycle(vararg xs: T): Sequence<T> {
    var i = 0
    return generateSequence { xs[i++ % xs.size] }
}

cycle("a", "b").take(5).toList() // ["a", "b", "a", "b", "a"]

Here's how you could implement turn application:
enum class Turn(val step: Int) { L(-1), R(1) }

enum class Direction {
    N, E, S, W;

    fun turned(turn: Turn): Direction {
        val mod: (Int, Int) -> Int = { n, d -> ((n % d) + d) % d }
        return values()[mod(values().indexOf(this) + turn.step, values().size)]
    }
}

Sounds like modulo is what you're looking for -- negative index wrap-around. Couldn't find it in Kotlin's stdlib so I brought my own.
Direction.N
    .turned(Turn.R) // E
    .turned(Turn.R) // S
    .turned(Turn.R) // W
    .turned(Turn.R) // N
    .turned(Turn.L) // W

Enum#values() and Enum#valueOf(_) are what let you access an enum's members programmatically.
Comment: I think the best answer should be this https://stackoverflow.com/questions/40938716/how-to-cycle-a-list-infinitely-and-lazily-in-kotlin/40940840#40940840 remove the last `toList()` call, that should be lazy
Comment: Well, the .toList() is only for demonstration purposes. Without it, my example would print "kotlin.sequences.TakeSequence@1fb3ebeb". It's not part of the solution. Also, my solution indexes into a single collection which I preferred over the flatten() solution. The benefit of the flatten() solution is that it's nice to inline.
Comment: Note that since Kotlin 1.5 there is a [mod](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/mod.html) function in stdlib.
Answer: Custom sequence, which repeats indefinitely the given sequence or list can be written quite easily in terms of flatten:
fun <T> Sequence<T>.repeatIndefinitely(): Sequence<T> =
    generateSequence(this) { this }.flatten()

fun <T> List<T>.repeatIndefinitely(): Sequence<T> =
    this.asSequence().repeatIndefinitely()

Comment: @arekolek `generateSequence` without a seed is constrained to be iterated only once. If there is a seed, then the sequence can be iterated multiple times, each time starting with seed.

https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.sequences/generate-sequence.html
Comment: That looks simple! Thanks, I will try it out.
Comment: Why not just `generateSequence { this }.flatten()`? Do you need the seed?
Answer:
You can cycle through a list/collection in Kotlin by generating a sequence that returns the list/collection repeatedly and then flattening it. e.g.:
generateSequence { listOf("a", "b") }.flatten().take(5).toList()
// [a, b, a, b, a]

You can define your own modulo function for coercing both negative and positive numbers to valid indices to access elements in a list (see also Google Guava's IntMath.mod(int, int)):
infix fun Int.modulo(modulus: Int): Int {
    if (modulus <= 0) throw ArithmeticException("modulus $modulus must be > 0")
    val remainder = this % modulus
    return if (remainder >= 0) remainder else remainder + modulus
}

val list = listOf("a", "b", "c", "d")
list[-1 modulo list.size] // last element
list[-2 modulo list.size] // second to last element
list[+9 modulo list.size] // second element
list[-12 modulo list.size] // first element

Comment: Note that since Kotlin 1.5 there is a [mod](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/mod.html) function in stdlib.
Answer: Paraphrasing the discussion on kotlin Slack:

using List#modulo would make this simpler, but not as elegant as cycle still, since negative indexes will still need to be handled.
One option to implement a cyclical list is a Sequence. However, a custom Sequence will need to be written, or generated using generateSequence.  We thought it's an overkill for this situation.

Eventually I went with:

Making Direction aware of next and previous:

enum class Direction {
    N, E, S, W;

    private val order by lazy { listOf(N, E, S, W) }

    fun add(turns: Int): Direction {
        val currentIndex = order.indexOf(this)

        var nextIndex = (currentIndex + turns) % order.size
        return order.possiblyNegativeLookup(nextIndex)
    }

    fun subtract(turns: Int) = add(-1 * turns)
    fun next(): Direction = add(1)
    fun previous(): Direction = subtract(1)
}

Extending List with possiblyNegativeLookup:

fun <E> List<E>.possiblyNegativeLookup(i: Int): E {
    return if (i < 0) this[this.size + i] else this[i]
}

So the final code turns into:
val nextHeading = if (move.turn == Turn.R) heading.next() else heading.previous()


Can I use "box-sizing: border-box;" in universal selector (*) every time?

Question: I just learned html css and currently I'm trying to improve my skills by practicing. Everytime I open a new html page I'm using *{box sizing: border-box;}. Is it okay to use it like this every time or should I use it in the codes that I need?
Comment: That completely depends on one to one code implementation some uses and some don't. technically there is no restriction on use the `box-sizing` on the `(*)` selector which basically better than setting on individual elements.
Comment: This is a great question and should be reopened IMO.
Answer: If you start a new project it might be ok and clean to add * { box-sizing: border-box; } at the beginning so you can use it on the entire project and everyone else developing on the project will see it.
BUT if you work on an existing project and then just add * { box-sizing: border-box; } somewhere could mess up the entire layout! So there it might be "safer" to only add it to the containers you are working on with something like .border-boxed-container * { box-sizing: border-box; }. Or have an extra class like "border-boxed" which you can add to every element accordingly the CSS .border-boxed { box-sizing: border-box; }
Answer: It's not a right or wrong sort of thing. Depending on the situation, there's good reasons for using either border-box or content-box.
When creating something that needs precision in terms of size relative to others on the same row (e.g. a grid system that needs to total 100% per row), using border-box will simplify things and reduce surprises.
But if you need precision with the sizing of an element relative to its interior (ex. a perfect fit around a fixed-size image), content-box makes more sense.


Is JavaScript/NodeJS truly parallel?

Question: Recently in school, I've been taught C++/OpenMPI in a parallel computing class. I don't really like to program in C++ as its low level and harder to program, easier to make mistakes etc.
So I've been thinking, is JavaScript/NodeJS (something I've started to like) actually truly parallel? Or is it simply using non-blocking operations to simulate parallel execution (which I think it is)? There are libraries like async which gives similar functions to what I've used in OpenMPI: gather, scatter even "parallel". But I've got a feeling its just simulating parallelism using non-blocking IO?
Perhaps only node-webcl is truly parallel?
UPDATE: Seems possible via web workers (~31 min): watching http://www.infoq.com/presentations/Parallel-Programming-with-Nodejs
Comment: The reason for the popularity of things like Node.js or Python's twisted framework is that it turns out that for the kinds of loads experienced by webservers (multiple connections per client, small packets, responses in under 5 seconds etc.) multi-threading and multi-processing has proven (in the real world) to be significantly slower than multiplexed, non-blocking I/O. Especially once you have more threads than CPU cores (which is typical for a busy website).
Comment: See this for a historical perspective of the problem of web servers: http://stackoverflow.com/questions/3759683/how-node-js-server-is-better-than-thread-based-server/3759991#3759991
Comment: possible duplicate of [Is javascript guaranteed to be single-threaded?](http://stackoverflow.com/questions/2734025/is-javascript-guaranteed-to-be-single-threaded)
Answer: In deed, JavaScript is single-threaded by it's design. But you're not the first person who wants some parallelism in it, so there're some things that can work truly parallel:

WebWorkers - run in threads, which means that they quite cheap to create. They limited in data interchange abilities. At first, you could only send messages between workers, but now they are a lot better, you can even use SharedArrayBuffer for concurrent memory access. Not supported in NodeJs, only in browsers.
WebGL/WebCL - utilize graphic subsystems for parallel computing. Very fast, but effective for a limited set of problems. Not all tasks can be computed effectively on GPU-like subsystem. It also requires additional data transformations for presenting you data in pixel-like format. Has decent browsers support as WebGL, but as you've already mentioned has only experimental implementations for NodeJs.
SIMD - parallelism over data. It was a promising thing, but it is no longer on the roadmap for JavaScript and it will be a part of the WebAssembly standard.
Cluster - a NodeJs solution for parallelism. Allows to run multiple processes (not threads) and even supports SharedArrayBuffer for communication since 9th version.

That's pretty much it. There's also the WebAssembly threads proposal, but, firstly, it is a proposal and, secondly, WebAssembly is not JavaScript.
In general, JavaScript is by far not the best tool for low level parallel computing. There're a lot of other tools that suit better for this: Java, C#, Go...
Comment: "*multiple processes (not threads)*" - well, each of those processes has its own thread(s)
Answer: With Node.js, your JavaScript runs in a single thread. IO is non blocking.
Comment: Hmm, NodeJS is single threaded, so its NOT *truly* parallel? Meaning it doesn't benefit from multicore? But I suppose I can still use distributed systems (like the cloud)?
Comment: Not parallel in any sense of the word, is what I think he's saying.
Comment: That is correct. Node.js manages some threads under the hood for IO and other async operations (and if you write a C++ extension, you can get access to them), but to take advantage of multiple cores in your JavaScript code you'll either need to run multiple processes, or use a module that creates threads for you (via C++).

Is JavaScript/NodeJS truly parallel?


php date() not receiving year, month, day: NSDate to php

Question: I have a php web service and am sending an NSDate from an iOS app to the web service.  This is my php for receiving the date:
echo 'formatted T/S '.$u_timestamp = date('Y-m-d H:i:s', trim(strip_tags($_REQUEST['timestamp'])));

This is the date that I am sending with my url:
timestamp=2015-09-03%2013:52:09%20+0000

I am receiving it fine, but my output is this:
1970-01-01 00:33:35

Does someone know what is wrong with my php that I am not receiving the NSDate correctly?
Answer: The date function takes a Unix timestamp as the second parameter (i.e. the number of seconds since 1970-01-01 00:00:00)
Try this:
date('Y-m-d H:i:s', strtotime(trim(strip_tags($_REQUEST['timestamp']))));

Comment: Great, that works perfect, except my year equals 0000.  example: (0000-09-03 13:52:09)  What can I do to get correct year?
Comment: I'm guessing that the `+0000` is confusing `strtotime`
Comment: so I should send the 'timestamp' as a string without the milliseconds and that would work.. I took the '%20+0000' off the end of my answer and it updated my database with the correct timestamp.  Thanks!
Comment: yeah, try that. `strtotime` is relatively resilient, and will accept most common formats (as well as strings like `today`, or `yesterday`, or `+3 months`). My own local tests don'e seem to be confused by the milliseconds, but that doesn't mean that the exact format that your copy is receiving isn't confusing it.
Comment: Works like a charm, sending an NSString same format as NSDate without milliseconds and no problems.


Existence of positive linear functionals such that $\varphi(a^*a)>0$

Question: Let $A$ be a $C^*$-algebra, $0\neq a\in A$. I want to show that there exists a positive linear functional $\varphi:A\to\mathbb{C}$ such that $\varphi(a^*a)>0$.
My definitions: positive means $\varphi(b^*b)\geq 0$ for all $b\in A$.
Comment: And what if a=0?
Answer: One can also do this without using a faithful representation (say, if you want to use the result to prove Gelfand-Naimark):
By Hahn-Banach, there exists a bounded linear functional on $A$ such that $\phi(a^\ast a)=\lVert \phi\rVert \lVert a\rVert^2$. We can assume $\lVert \phi\rVert=\lVert a\rVert=1$. Moreover, it is not hard to reduce the problem to the case of unital $C^*$-algebras, so I'll assume that $A$ has a unit.
Since $0\leq a^\ast a\leq 1$, we have $-1\leq 1-2a^\ast a\leq 1$, hence $\lVert 1-2a^\ast a\rVert\leq 1$. Let $\phi(1)=\alpha+i\beta$ with $\alpha,\beta\in \mathbb R$. On the one hand, $\lvert \phi(1)\rvert\leq 1$ implies $\alpha^2+\beta^2\leq 1$. On the other hand, $\lvert \phi(1)-2\phi(a^\ast a)\rvert\leq 1$ implies $(\alpha-2)^2+\beta^2\leq 1$. Then one can check that this is only satisfied for $\alpha=1$ and $\beta=0$, that is, $\phi(1)=1$.
To conclude, use that every unital functional of norm $1$ on a $C^\ast$-algebra is positive, hence a state.
Comment: Are you showing that every functional $\phi\in A^*$ with $\|\phi\|=\|a\|=1$ satisfying $\phi(a^*a)=1$ is automatically positive?
Comment: @alepopoulo110 Yes.
Comment: Even though your proof looks perfectly fine, I find the statement in my previous comment a bit strange; it looks like the condition $\phi(1)=1$ can be replaced by $\phi(x)=1$ for any $x\ge0$ with $\|x\|=1$
Comment: But it is true. Maybe it becomes more plausible if you prove it for hermitian $\phi$ first. In this case you have $\phi=\phi_1-\phi_2$ with positive $\phi$, and the assumption implies $\lVert \phi_1\rVert\geq \phi_1(x)-\phi_2(x)=\lVert \phi_1\rVert+\lVert\phi_2\rVert$, hence $\phi_2=0$.
Comment: @alepopoulo110 You can find a proof here https://math.stackexchange.com/questions/3223632/bounded-linear-functional-on-a-c-algebra?rq=1


How do I enclose all numeric substrings of a string in braces?

Question: I would like to convert a string so that all numeric subsequences are enclosed in a {...} pair.
For instance:
input_string = "APPL[E]5XXXX"

output_string = "APPL[E]{5}XXXX"

Each string may contain one or more digits, for instance BASIC76XXXXX98ZZZZ and output should be BASIC{76}XXXXX{98}zzzz
Not sure if this possible to achieve. Any help will be very much appreciated.
Comment: You should really try something yourself before coming here for help. This isn't a "write my code for me" site.
Answer: I think you are looking for something like this:
$string =~ s/(\d+)/{$1}/g;

That will match any consecutive digits and replace them with the first captured substring ($1 - which coincides with the entire match) surrounded by curly brackets. The g is to make sure that all occurrences are replaced.
Comment: For a long time is has been bad practice to use `$&` - a capture and `$1` etc. should be used instead. For instance `$string =~ s/(\d+)/{$1}/g`
Comment: @user1844052 if you have parentheses in your regex, and count them from left to right, you can also access what was matched *inside* those subpatterns with `$1`, `$2`, `$3` and so on. Google "regex capturing groups" for more information.
Comment: @Borodin thanks for letting me know. I'm not really up to speed when it comes to Perl best practices ;).
Answer: This is for sure possible.
You want a regex that matches on digits, captures the digits, then substitutes the match with a wrapped set of curly braces.
my $input = 'APPL[E]5XXXX';
$input =~ s/(\d+)/{$1}/g;

The \d+ matches digits.
The () captures and stores in $1.
The s/// is a substitution regex.
And finally, the /g at the end means 'global', aka, do this for all matches.


Pegar parâmetros da URL

Question: Pessoal tenho a seguinte url:
http://localhost:27903/detalhes.aspx?id=3014953&stars=70
Preciso pegar os parametros separados, id e stars, alguma dica ai já tentei de tudo, segue meu código:
$('tbody#corpo2').append(
'
' + location.search.substring(4) + '	'
+ '' + "teste" + '	'
+ '' + location.search.substring(17).replace("s=", "").replace("=","") + ' 	' + '
');
});

Comment: Obs: o location.search.substring(4) pega tudo até o final da URL, teria como limitar pra ele pegar até o &?
Answer: Desta forma é possível pegar os parâmetros enviados via GET.
var query = location.search.slice(1);
var partes = query.split('&');
var data = {};
partes.forEach(function (parte) {
    var chaveValor = parte.split('=');
    var chave = chaveValor[0];
    var valor = chaveValor[1];
    data[chave] = valor;
});

console.log(data);

Comment: Valeu meu bruxo, deu certo, abraço!
Answer: Aqui está como pegar todos os parâmetros e colocar num objeto:
//Array de parametros 'chave=valor'
var params = window.location.search.substring(1).split('&');

//Criar objeto que vai conter os parametros
var paramArray = {};

//Passar por todos os parametros
for(var i=0; i<params.length; i++) {
    //Dividir os parametros chave e valor
    var param = params[i].split('=');

    //Adicionar ao objeto criado antes
    paramArray[param[0]] = param[1];
}

Para pegar um valor: paramArray['chave']
Answer: Pode pegar parametros da url  utilizando javascript.
     Utilizando a Url :http://localhost:27903/detalhes.aspx?id=3014953&stars=70  como exemplo  :

Answer: var url_string = window.location.href;
var url = new URL(url_string);
var data = url.searchParams.get("stars"); //pega o value

Answer: Eu pego via PHP e transmito ao JavaScript

Pegar parâmetros da URL


The reason that the larger gradient flowing through an ReLU neuron can cause it to die

Question: In this link about different neuron types, there is an introduction on the disadvantage of ReLU,

(-) Unfortunately, ReLU units can be fragile during training and can
  "die". For example, a large gradient flowing through a ReLU neuron could cause the weights to update in such a way that the neuron will never activate on any datapoint again. If this happens, then the gradient flowing through the unit will forever be zero from that point on. That is, the ReLU units can irreversibly die during training since they can get knocked off the data manifold. For example, you may find that as much as 40% of your network can be "dead" (i.e. neurons that never activate across the entire training dataset) if the learning rate is set too high. With a proper setting of the learning rate this is less frequently an issue.

I am not clear why large gradient flowing through a ReLU neuron could cause the neuron to die.
Please see the following ReLU picture for reference.
Answer: A big update can move the coefficient and bias by such a large amount that for all incoming values to the neuron, the ReLU returns 0 for all inputs. Thus the gradient becomes 0 for all subsequent updates.
Comment: I added a picture in my original post. Looks like when incoming values become quite big, then the returned value will increase linearly as well, instead of approaching zero.
Comment: Incoming **function** values are different from **gradient updates**.


Como passar parâmetros de um Fragment para outro Fragment no mesmo FrameLayout?

Question: Tenho uma Activity principal que tem UM frameLayout. O frameLayout inicia com o FragmentA.
FragmentA tem um botão que chama FragmentB abrindo no mesmo frameLayout, substituindo o FragmentA.
Como passar parâmetros do FragmentA para o FragmentB no mesmo framelayout e assim sucessivamente, caso tenha FragmentC, passando A para o B e B para o C?
Código
MainActivity:
public class MainActivity extends AppCompatActivity  {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final FragmentTransaction ft = getFragmentManager().beginTransaction();
        ft.add(R.id.frameInicial, new FragmentA(), "NewFragmentTag");
        ft.commit();
    }
}

FragmentA:
public class FragmentA extends Fragment  {

    public FragmentA() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_a, container, false);

        Button btChamaFragmentB = view.findViewById(R.id.btChamaFragmentB);

        btChamaFragmentB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                final FragmentTransaction ft = getFragmentManager().beginTransaction();
                ft.replace(R.id.frameInicial, new FragmentB(), "NewFragmentTag");
                ft.commit();

            }
        });

        return view;
    }
}

FragmentB
public class FragmentB extends Fragment {

    public FragmentB() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_b, container, false);
        return view;
    }
}

XML - Layout da MainActivity
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="aig.example.com.comunicacaofragment.MainActivity">

    <FrameLayout
        android:id="@+id/frameInicial"
        android:name="aig.example.com.menudeslizante.Fragment1"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>

Answer: conseguir resolver o problema e irei compartilhar com vocês.
Para chamar outra fragment passando parâmetro utilize o código abaixo:
FragmentB fragmentB = new FragmentB();
                Bundle bundle = new Bundle();
                FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
                bundle.putString("ano", "2018");
                fragmentB.setArguments(bundle);
                fragmentTransaction.replace(R.id.frameInicial, fragmentB ,"NewFragmentTag");
                fragmentTransaction.commit();
Para receber o parâmetro na nova fragment utilize o código abaixo:
   ` Bundle mBundle = new Bundle();
    if(mBundle != null){
        mBundle = getArguments();
        ano = mBundle.getString("ano");`

    }


MSBuild /m:4 fails because it builds the same project twice

Question: My team has a large solution (~500 csproj's). We use VS2012, and build using TFS Build, which uses MSBuild 4. Currently we build serially, but we want to build in parallel (using msbuild /maxcpucount:4). However, when I try it on my 4-proc machine, I get a weird failure:
11:2>CSC : fatal error CS0042: Unexpected error creating debug information file 'C:\Common\obj\Debug\Common.PDB' -- 'C:\Common\obj\Debug\Common.pdb: The process cannot access the file because it is being used by another process. [C:\Common\Common.csproj]
Looking at the log, 2 msbuild nodes were trying to build that same csproj, and thus colliding on writing some output:
10>Project "C:\Utils\Utils.csproj" (10) is building "C:\Common\Common.csproj" (11) on node 4 (default targets).
46:2>Project "C:\Objects\Objects.csproj" (46:2) is building "C:\Common\Common.csproj" (11:2) on node 1 (default targets).
Why would MSBuild try to build the same project twice?
Answer: Cause: Someone was calling <MSBuild Projects="Common.csproj" Properties="..." />. Then, MSBuild thinks that it should build Common.csproj again with those different properties, and it happened to occur at the same time with the regular compilation of Common.csproj.
Fix: Call <MSBuild ... /> without those unneeded properties.
Test:
Common.targets
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Target Name="Build">
    <Message Importance="high" Text="Build in $(MSBuildThisFile)" />
  </Target>
  <Target Name="After" DependsOnTargets="Build">
    <Message Importance="high" Text="After in $(MSBuildThisFile)" />
  </Target>
</Project>

Other.targets
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Target Name="Build">
    <Message Importance="high" Text="Build in $(MSBuildThisFile)" />
    <MSBuild Projects="common.targets" Targets="Build" />
    <MSBuild Projects="common.targets"
             Targets="After"
             Properties="myprop=myvalue"
             />
  </Target>
</Project>

Run:
> msbuild other.targets /clp:verbosity=minimal
  Build in other.targets
  Build in common.targets
  Build in common.targets    <<<< Common.targets Build is invoked again
  After in common.targets

And indeed, removing Properties="myprop=myvalue" solves the issue.
Answer: I found someone had added two project references (from the same project) and that apparently caused msbuild to build twice also.. something to watch out for
Comment: This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/30587303)
Comment: Original asker here. This is actually a different and equally-valid answer, and is of value to future people encountering this issue. So upvote from me.


Truncated Dirichlet process vs Dirichlet distribution

Question: As the topic suggests I was wondering what the main differences are in using one over the other. Suppose for sake of simplicity the Dirichlet distribution has all parameters set to $\alpha$.
All I can think of is that considering that DPs use a stick breaking process the first few sticks tend to be larger. Since the last few sticks are smaller the clusters associated to them tend to be unoccupied. Thus the DP will limit the number of clusters available.
However it's conceivable for a given number of clusters $T$ both a truncated DP and a Dirichlet distribution will give the same realisation of $\pi$s.
For illustration of what I mean refer to the following two generative processes:
1. Dirichlet Distribution:
$$
\begin{align}
\theta_i&\sim\mathcal{N}(0,100) \quad i=1,\cdots,T\\
\mathbf{\pi}&\sim Dir(\alpha)\\
z_n&\sim\prod_{i=1}^T \pi_i^{1(z_n=i)}\\
x_n&\sim \mathcal{N}(\theta_i,1)
\end{align}
$$
2. Dirichlet Process:
$$
\begin{align}
\theta_i&\sim\mathcal{N}(0,100) \quad i=1,\cdots,T\\
v_i&\sim Be(1,\alpha) \quad i=1,\cdots,T\\
\pi_i & = v_i\prod_{j=1}^{i-1}(1-v_j)\\
z_n&\sim\prod_{i=1}^T \pi_i^{1(z_n=i)}\\
x_n&\sim \mathcal{N}(\theta_i,1)
\end{align}
$$
I understand that the same $\alpha$ may not derive the same $\pi_i$s but the point is in the case of the Dirichlet distribution,for an appropriate $\alpha$, won't (some of the $\pi_i$s be driven to zero) so that we get the same posterior on $\pi_i$?
Comment: Quite old question, but have you found an answer here?
Comment: @fsociety not a full answer but from experience (in using variational DPs) DPs tend to assign smaller number of clusters. Whereas normal Dirichlet distributions will tend to fill up the entire set.
Comment: Very old question, but a relevent link to a paper by Hemant Ishwaran, who did a lot of work on these models: http://biomet.oxfordjournals.org/content/87/2/371.full.pdf
Answer: You have two very different priors on $\pi$, so why would you expect the same posterior?
Let's think about the nature of $T$ in your presentation above:

In 1: Dirichlet Distribution, $T$ is a fundamental defining feature of the finite-dimensional Dirichlet prior distribution for $\mathbf{\pi}$. With $T$ fixed, you have complete flexibility (within the unit simplex constraint) to set the values of $\alpha$. Without any additional structure favoring some values of $\alpha$ over others, as $T$ increases, the expected value of each element of $\mathbf{\pi}$ will decrease.
In 2: Dirichlet Process, $T$ is a choice of truncation level, not a feature or parameter of the ideal Dirichlet Process. In this case, as $T$ gets large, the expected values for the individual elements of $\pi$ do not shrink, at least not for the portion of the process you're approximating well. As you noted above, the first few elements of $\pi$ are still large in expectation due to the stick-breaking construction. Your hope is that $T$ is large enough to provide an adequate approximation to the infinite-dimension process that you really wanted to sample from.


Why an array reference is passed in the method instead of its values?

Question: I am declaring an array myArray in main method and passed the same array in doIt(myArray) method.
When I took another array variable in doIt() method and assign myArray to it. And then I printed the myArray in main method.
But I am doing same thing with integer and String, the changes made in respective method do not affect the output.
My Code is
public class ChangeIt {

    public static void main(String[] args) {
        int[] myArray = {1,2,3,4,5};

        new ChangeIt().doIt(myArray);
        for (int i = 0; i < myArray.length; i++) {
            System.out.print(myArray[i] + " ");
        }

        String str= "Gaurav";
        new ChangeIt().printString(str);
        System.out.println("\n"+ str);

        int num = 5;
        new ChangeIt().printNum(num);
        System.out.println(num);
    }

    private void doIt(int[] z) {
        int[] A = z;
        A[0] = 99;

    }
    private void printString(String s){
        String s2 = s + "Kukade";
    }

    private void printNum(int x) {
        int y = x+1;
    }

}

The output is
99 2 3 4 5
Gaurav
5

So, what is happening? Why it is printing 99 instead of 1?
Comment: In the other two cases, you're creating new instance. In the `doIt()` method, you are just creating new variable, which points to the same instance of an array. Check this out: https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value?rq=1
Comment: There is a difference between *reasigning* new value and *modifying* existing value. If you want your wife to have blond hair you can either `wife = new Wife(HairColor.BLOND)` (divorce and remarry blonde) or `whife.hairColor(HairColor.BLOND);` (let your wife change her hair). Second approach (modification) also uses reassignment but it does it on object internal property (hair color) - which represents its state.
Comment: Thanks for your comment NeplatnyUdaj and Pshemo
Answer:
But I am doing same thing with integer and String, the changes made in respective method do not affect the output.

The fundamental difference is that with the int and String, you're not changing the state of the original int or String. In fact, you're not even assigning to the parameter (but if you did, it wouldn't be observable outside the function).
But with the array, you're changing the state of the array, not assigning a new array to a local.
This:
int[] A = z;

just points A at the same array z points to, it doesn't create a new array. Since they both point to the original array, assigning to one of its elements changes the state of the array.


Max # of threads per CPU

Question: I'm currently using Visual Studio Test Suite load tester to simulate a load against on of our web apps on a different server. (No, I'm not testing against production). I believe it is creating a thread per simulated user.
While I was doing this, I experienced a blue screen which may have been unrelated.
But that brought up the question.
How many threads can I use before my CPU can't handle GENERATING that many requests?
Specs:
Intel Core 2 Duo CPU T7700 @ 2.40 GHz 2.40 GHz (32 bit)
Is there any other information or context I need to provide?
Answer: It depends on the version of .NET you're running.  You can 250 worker thread for processor on .NET 3.5.
Check out this MSDN article.
Answer: You can monitor these performance counters while you're running this test.  It'll give you an idea of what your practical limits are as you increase the concurrency:

System \ "Processor Queue Length".

Processor Queue Length is the number
  of threads in the processor queue.
  Unlike the disk counters, this counter
  counters, this counter shows ready
  threads only, not threads that are
  running.  There is a single queue for
  processor time even on computers with
  multiple processors. Therefore, if a
  computer has multiple processors, you
  need to divide this value by the
  number of processors servicing the
  workload. A sustained processor queue
  of less than 10 threads per processor
  is normally acceptable, dependent of
  the workload.

This is similar to the Unix load average, in that it indicates threads waiting to execute.  This is not the same as CPU utilization %, which only tells you how much time is spent working vs. idling.

System \ "Context Switches/sec".

Context Switches/sec is the combined
  rate at which all processors on the
  computer are switched from one thread
  to another.  Context switches occur
  when a running thread voluntarily
  relinquishes the processor, is
  preempted by a higher priority ready
  thread, or switches between user-mode
  and privileged (kernel) mode to use an
  Executive or subsystem service.  It is
  the sum of Thread\Context
  Switches/sec for all threads running
  on all processors in the computer and
  is measured in numbers of switches.
  There are context switch counters on
  the System and Thread objects. This
  counter displays the difference
  between the values observed in the
  last two samples, divided by the
  duration of the sample interval.

This number is relative to each system.  But, with some benchmarking you can use this counter to correlate to the upper limits of your processing capacity.
Answer: Some limiting factors to consider:

Time spent context switching between threads can outweigh benefit of having multiple threads. Generally, unless your threads spend a lot of time waiting, the benefit of more threads per core is a degredation, not improvement, in performance - see next point:
Is there any point in having more than one thread? Unless each thread spends a lot of time waiting for something to happen - if you have one core - then you can only do one thing at once. Throwing more threads at it is not going to help. For 2 cores 2 threads...
Running out of stack memory is a possibility - as the os can no longer keep track of all your threads.
Comment: Well, because it is hitting an external web server, and then just waiting for a response, yeah, the thread is basically doing nothing for 95% of it's duration
Comment: How many threads did you create before the blue screen? At a guess you either ran out of memory, or the cpu was thrashing / context switching.

Max # of threads per CPU


Discriminant analysis for the validation of cluster analysis

Question: I did a discriminant analysis for the validation of my cluster analysis. The cluster analysis is based on a PCA, so I used the components as the independant variables in the discriminant analysis. My question is: is there a restriction considering the number of the independant variables (components) compared to the number of my (cluster) groups?
Thanks a lot!
Comment: How can DA validate the clusters? Please describe how you reason it in more details.
Comment: Because it is frequently used in literature.
Answer: You can use the discriminant analysis to predict the cluster using your principal components as independent variables, so your model would be:
$Cluster=Component_1+Component_2,...,Component_n$
And no, you don't have a restriction on the number of components you can use in regards to the number of clusters you have. I would use them all. By means of cross validation I would measure how well this model (linear discriminant) predicts the cluster and if the accuracy is good you would know that the clusters are separable, crisp, which could be interpreted as cluster health. Note that you could use any classifier to do this. You could also directly use separability measures for this same purpose like Jeffries-Matusita or divergence.


Update Cmdb_ci table of one instance with respect to update of another servicenow instance

Question: We have a requirement in which we want to update the cmdb_ci table of one instance of ServiceNow with respect to the create or update in the cmdb_ci of another instance.
If someone creates or updates the ci in instance 1 the same should get reflected in instance 2.
I tried it with a scheduled job but the requirement demands it on live basis.
Answer: Use a REST API instead.
REST documentation is available on developer.servicenow.com.
To make it instantaneous, you would want to do a push from the instance on which the change occurs rather than a pull from the instance that should receive the change.


Obtaining the expectation matrix of $SO(n)$ for $n \geq 2$

Question: I have to solve the following problem:
Obtain a matrix whose entries are the expectation values of a randomly chosen matrix belonging to $SO(n)$ for $n \geq 2$.
I could set up the expression that would give me the result, but I have trouble evaluating it. I feel lost.
Let $\mu$ be the Haar measure of $SO(n)$ and $e_i$ be the $i$th unit vector in $\mathbb{R}^n$. Then, we want the matrix
$$\mathbf{E} = (E)_{ij} = \frac{1}{\mu(SO(n))} \int_{SO(n)} (e_i \cdot U e_j) \mathrm{d}\mu(U)$$
where $U$ is an arbitrary randomly chosen matrix in $SO(n)$. Furthermore, we know also that $\mu(SO(n))<\infty$ since $SO(n)$ is compact.
After here, I am lost. Any help is appreciated!
Answer: Let $G$ be any compact, locally compact matrix group; let $\mu$ be its normalized Haar measure, i.e. $\mu(G)=1$. Let $E=\int\limits_Gg\, d\mu(g)$ be the expectation we are interested in. The key point is that $E$ is invariant under the action of $G$. Consider $g_1 \in G$. Then, $g_1 \cdot E = \int_G g_1 g \, d\mu(g) = \int_G h \,d\mu(g_1^{-1}h) = \int_Gh \, d\mu(h) = E$ (we made a substitution $h=g_1g$ and used invariance of Haar measure).
Now consider $SO(n)$. First, if $n=1$, this group is trivial, so the expectation is just the identity matrix. Now, suppose that $n \geq 2$. Let $g$ be a $180^\circ$ rotation in $ij$ coordinate plane (this is where we need $n \geq 2$). Multiplying a matrix $E$ by $g$ on the left has the effect of multiplying by $-1$ the $i$-th and $j$-th rows of $E$. Since $E$ is invariant, $gE=E$, meaning that any row in $E$ doesn't change if we multiply it by $-1$, meaning that any row of $E$ consists of zeros. Thus, $E=0$.

NB: I once answered a somewhat related question about finite groups; you may be interested in it.


Mockito error in Spring Boot tests after migrating to JDK 11

Question: I have just migrated to JDK 11 in order to use the latest Java LTS version. If I change the execution JRE in Eclipse from 10 to 11 (and only then), when I try to run my tests, I get the following exception stacktrace.
Please note that everything works as expected if I switch back to jdk-10. I use Spring Boot and my tests also use Mockito. My pom.xml is also shown here.
Is there a known incompatibility between Spring Boot and/or Mockito with jdk-11? Perhaps another reference missing in pom.xml?
pom.xml:
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.5.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.glassfish.jaxb</groupId>
            <artifactId>jaxb-runtime</artifactId>
            <version>22.214.171.124</version>
        </dependency>
        <dependency>
            <groupId>javax.activation</groupId>
            <artifactId>activation</artifactId>
            <version>1.1.1</version>
        </dependency>
        <dependency>
            <groupId>javax.transaction</groupId>
            <artifactId>jta</artifactId>
            <version>1.1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.maven</groupId>
            <artifactId>maven-model</artifactId>
            <version>3.5.4</version>
        </dependency>
        <dependency>
            <groupId>org.modelmapper</groupId>
            <artifactId>modelmapper</artifactId>
            <version>2.2.0</version>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>

            <groupId>org.javassist</groupId>
            <artifactId>javassist</artifactId>
            <version>3.23.1-GA</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <executable>true</executable>
                    <skipTests>true</skipTests>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>spring-releases</id>
            <url>https://repo.spring.io/libs-release</url>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>spring-releases</id>
            <url>https://repo.spring.io/libs-release</url>
        </pluginRepository>
    </pluginRepositories>

Stacktrace:
java.lang.IllegalStateException: Failed to load ApplicationContext
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:125)
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:108)
    at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:190)
    at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:132)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:246)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:227)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:246)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
    at org.junit.runners.Suite.runChild(Suite.java:128)
    at org.junit.runners.Suite.runChild(Suite.java:27)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:538)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:760)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:460)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:206)
Caused by: org.mockito.exceptions.base.MockitoException:
Mockito cannot mock this class: class org.foo.MockedClass.

Mockito can only mock non-private & non-final classes.
If you're not sure why you're getting this error, please report to the mailing list.

Java               : 11
JVM vendor name    : Oracle Corporation
JVM vendor version : 11+28
JVM name           : Java HotSpot(TM) 64-Bit Server VM
JVM version        : 11+28
JVM info           : mixed mode
OS name            : Linux
OS version         : 4.4.0-128-generic

Underlying exception : java.lang.UnsupportedOperationException: Cannot define class using reflection
    at org.springframework.boot.test.mock.mockito.MockDefinition.createMock(MockDefinition.java:157)
    at org.springframework.boot.test.mock.mockito.MockitoPostProcessor.createMock(MockitoPostProcessor.java:222)
    at org.springframework.boot.test.mock.mockito.MockitoPostProcessor.registerMock(MockitoPostProcessor.java:192)
    at org.springframework.boot.test.mock.mockito.MockitoPostProcessor.register(MockitoPostProcessor.java:174)
    at org.springframework.boot.test.mock.mockito.MockitoPostProcessor.postProcessBeanFactory(MockitoPostProcessor.java:144)
    at org.springframework.boot.test.mock.mockito.MockitoPostProcessor.postProcessBeanFactory(MockitoPostProcessor.java:131)
    at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:282)
    at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:170)
    at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:694)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:532)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:780)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:412)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:333)
    at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:139)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:99)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:117)
    ... 33 more
Caused by: java.lang.UnsupportedOperationException: Cannot define class using reflection
    at net.bytebuddy.dynamic.loading.ClassInjector$UsingReflection$Dispatcher$Unavailable.defineClass(ClassInjector.java:821)
    at net.bytebuddy.dynamic.loading.ClassInjector$UsingReflection.inject(ClassInjector.java:185)
    at net.bytebuddy.dynamic.loading.ClassLoadingStrategy$Default$InjectionDispatcher.load(ClassLoadingStrategy.java:187)
    at net.bytebuddy.dynamic.TypeResolutionStrategy$Passive.initialize(TypeResolutionStrategy.java:79)
    at net.bytebuddy.dynamic.DynamicType$Default$Unloaded.load(DynamicType.java:4457)
    at org.mockito.internal.creation.bytebuddy.SubclassBytecodeGenerator.mockClass(SubclassBytecodeGenerator.java:121)
    at org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator$1.call(TypeCachingBytecodeGenerator.java:37)
    at org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator$1.call(TypeCachingBytecodeGenerator.java:34)
    at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:138)
    at net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:346)
    at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:161)
    at net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:355)
    at org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator.mockClass(TypeCachingBytecodeGenerator.java:32)
    at org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.createMockType(SubclassByteBuddyMockMaker.java:71)
    at org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.createMock(SubclassByteBuddyMockMaker.java:42)
    at org.mockito.internal.creation.bytebuddy.ByteBuddyMockMaker.createMock(ByteBuddyMockMaker.java:25)
    at org.mockito.internal.util.MockUtil.createMock(MockUtil.java:35)
    at org.mockito.internal.MockitoCore.mock(MockitoCore.java:65)
    at org.mockito.Mockito.mock(Mockito.java:1855)
    ... 49 more
Caused by: java.lang.IllegalStateException: Could not find sun.misc.Unsafe
    at net.bytebuddy.dynamic.loading.ClassInjector$UsingUnsafe$Dispatcher$Disabled.initialize(ClassInjector.java:1366)
    at net.bytebuddy.dynamic.loading.ClassInjector$UsingUnsafe.inject(ClassInjector.java:1202)
    at net.bytebuddy.dynamic.loading.ClassLoadingStrategy$ForUnsafeInjection.load(ClassLoadingStrategy.java:458)
    at net.bytebuddy.dynamic.TypeResolutionStrategy$Passive.initialize(TypeResolutionStrategy.java:79)
    at net.bytebuddy.dynamic.DynamicType$Default$Unloaded.load(DynamicType.java:4457)
    at net.bytebuddy.dynamic.loading.ClassInjector$UsingReflection$Dispatcher$Indirect.make(ClassInjector.java:684)
    at net.bytebuddy.dynamic.loading.ClassInjector$UsingReflection$Dispatcher$CreationAction.run(ClassInjector.java:302)
    at net.bytebuddy.dynamic.loading.ClassInjector$UsingReflection$Dispatcher$CreationAction.run(ClassInjector.java:290)
    at java.base/java.security.AccessController.doPrivileged(Native Method)
    at net.bytebuddy.dynamic.loading.ClassInjector$UsingReflection.<clinit>(ClassInjector.java:70)
    at net.bytebuddy.dynamic.loading.ClassLoadingStrategy$Default$InjectionDispatcher.load(ClassLoadingStrategy.java:184)
    ... 65 more
Caused by: java.lang.NoSuchMethodException: sun.misc.Unsafe.defineClass(java.lang.String, [B, int, int, java.lang.ClassLoader, java.security.ProtectionDomain)
    at java.base/java.lang.Class.getMethod(Class.java:2109)
    at net.bytebuddy.dynamic.loading.ClassInjector$UsingUnsafe$Dispatcher$CreationAction.run(ClassInjector.java:1269)
    at net.bytebuddy.dynamic.loading.ClassInjector$UsingUnsafe$Dispatcher$CreationAction.run(ClassInjector.java:1257)
    at java.base/java.security.AccessController.doPrivileged(Native Method)
    at net.bytebuddy.dynamic.loading.ClassInjector$UsingUnsafe.<clinit>(ClassInjector.java:1136)
    ... 74 more

Comment: What is are the versions of mockito and bytebuddy ? I believe Bytebuddy introduced **preliminary** Java 11 support in 1.8.0, however I advise you to try with the latest bytebuddy version in this regard (as of today [1.8.22](https://github.com/raphw/byte-buddy/releases/latest))
Comment: Haven't spotted any issues so far with Spring Boot 2 and Java 11.
Comment: Spring Boot 2.0 (and related Spring 5.0) doesn't, officially, support JDK 11. So don't upgrade.
Comment: Doesn't JDK 11 reduce/change the operation of reflection quite significantly; which would have an impact on Spring (boot)?
Answer: Was the same problem.
Add Mockito 2.22.0 to dependencies. Everything seems to work.
compile group: 'org.mockito', name: 'mockito-core', version: '2.22.0'

Comment: this is totally weird, 2.22.0 works just fine. but the latest version doesn't seem to
Comment: Thank you very much for the answer. Everything works as expected now. Adding the link to the respective maven reference to facilitate others finding it: https://mvnrepository.com/artifact/org.mockito/mockito-core/2.22.0
Comment: This answer was helpful except I needed version Mockito version 3.1.0.
 I used sonatype's site to look for my spring boot's most recent compatible version, just click your version and find your dependency version: https://search.maven.org/artifact/org.springframework.boot/spring-boot-dependencies
Comment: FYI: 2.19.1 is the version in which this got fixed (of course 2.22.0 also works :)). Thanks!
Comment: I had thought the latest wasn't either, but after a good clean and rebuild, Mockito 2.23.4 worked
Comment: I had same problem with Java 11.  specifying  2.22.0 in mockito dependency solved  it. Found solution at https://dev.to/scottshipp/how-to-fix-a-mockito-cannot-mock-this-class-exception-in-a-spring-boot-app-457e
Comment: Thanks, I've checked different sources and nothing was working. I am currently with Java 13 and was using the latest version of Mockito. When I downgraded it to 2.22.0, it started working fine.


Forearm soreness while practicing the piano

Question: Recently I have had a bit of fore arm soreness, and I don't know what to do about it. The soreness isn't lasting though, It's more like, I play a phrase and by the end it my forearm is sore, and if I wait for a minute it goes away.
The piece I have been learning recently is Winter by Vivaldi movement one, but a piano arrangement (This guy creates piano arrangements for many songs and gives sheet music to his patreons, for five dollars a month I believe) I am learning it from the back to the front. Right now where I am currently at in the piece is 2:39 in the video.
Should I work on my technique or is there any part that would seem to cause this? I have a teacher to help with technique and fingerings if that is the issue, however what I have been doing is the fingerings the video shows.
Comment: Hi Solar, sorry to hear you are having discomfort. It's very tough (and potentially unwise) to answer questions about pain online. Is it simply muscle tiredness from practicing too much? Do you type a lot or do manual labor for work which exhausts your muscles? Or is there an underlying injury/medical condition? Your teacher may be able to help look at your posture, wrist position, etc., but if the pain continues or gets worse, you should really get a medical opinion. Unfortunately it is quite possible to injure yourself playing music.
Answer: Rule of thumb (and the other fingers I suppose): if you are getting sore quickly (or really much at all in most cases), you are doing something wrong. Piano is more about finesse and technique than physical strength (or else professional pianists would have massive forearms!) Sure, there is some strength and endurance to be built up over time, but this comes as a natural side effect of good technique. Pushing through soreness in hopes of "building strength" has the potential to actually do more harm than good.
When it comes to playing tremolos, like the ones you mentioned, the most common tendency is to find the hand shape for the chord, lock it in place and rotate the whole forearm at the elbow. This takes a lot of physical exertion and will make you sore very quickly. On the other hand (no pun intended), playing with your fingers only can be just as bad.
Rousseau is an excellent pianist, I am a big fan of his as well. Notice, in the video, how loose his fingers are, particularly the ones not actually playing a note. Also notice how the back of his hand is rotating slightly back and forth. The key here is to use both your fingers and your wrist/forearm, distributing the exertion between them. It may not be exactly 50/50, you'll have to figure out what proportions are most comfortable to you. Once you find the sweet spot it should not cause you any strain.
(One other neat trick to conserve just a little extra energy when playing the same note repeatedly is to not lift the key all the way up in between notes. Once the string has been struck the hammer falls back to its resting position and can be re-engaged by lifting the key only part way before depressing. This means your finger doesn't have to travel as far, reducing the speed at which you have to move it.)


Unrecognized name when joining 2 tables in Google Big Query

Question: I want to join two tables from different datasets. It is possible to INNER JOIN these two datasets but it does not work with a regular JOIN.
I want to join a Google Analytics 4 (GA4) item id on the item id of the datawarehouse.
In order to access the GA4 item id I need to UNNEST the GA4 items array.
When using the code below, I get the following error:
Unrecognized name: dwh_id; Did you mean dwh? at [9:79]

Here's the query I'm using now.
SELECT
  event_date as ga4_date,
  ga4_items.item_id AS ga4_id,
  ga4_items.item_name,
  ga4_items.price,
  dwh.Product_SKU__Google_Analytics as dwh_id,

FROM `ga4-data` as ga4
JOIN `datawarehouse-data` as dwh ON dwh_id = ga4_id,
  UNNEST(ga4.items) as ga4_items

Let me know if you have the answer :)
Comment: You can't use a column alias **dwh_id** at **ON** clause, so use a base column name **Product_SKU__Google_Analytics** instead.
Comment: **ga4_id** is also column alias, you can't use it at **ON** clause either.
Comment: Thanks for the reply! However, when I use the following code:

```
FROM `ga4-data` as ga4
JOIN `datawarehouse-data` as dwh ON dwh_id = ga4_id,
  UNNEST(ga4.items) as ga4_items
```

I get the following error:

```
Unrecognized name: ga4_id; Did you mean ga4? at [9:120]
```
Comment: Tried that. But then I come to another error that I thought I solved. item_id is nested within an array. Then I get the following:

Cannot access field item_id on a value with type ARRAY> at [9:117]

.

I use the following query: FROM `ga4-data` as ga4
JOIN `datawarehouse-data` as dwh ON Product_SKU__Google_Analytics = items.item_id,
  UNNEST(ga4.items) as ga4_items
Comment: Would you check my answer? **UNNEST** part should be put before **`datawarehouse-data`**.
Comment: I don't quite understand. Any chance you can write that UNNEST line by any chance? Where should I put it whitout getting any errors?
Answer: My best quess of what you're trying to do:
CREATE TEMP TABLE `ga4-data` AS
SELECT '2022-01-01' AS event_date,
       [STRUCT('item001' AS item_id, 'name1' AS item_name, 100 AS price),
        STRUCT('item002' AS item_id, 'name2' AS item_name, 200 AS price)] AS items
;

CREATE TEMP TABLE `datawarehouse-data` AS
SELECT 'item001' AS Product_SKU__Google_Analytics,
       'col1' AS col1;

SELECT event_date as ga4_date,
       ga4_items.item_id AS ga4_id,
       ga4_items.item_name,
       ga4_items.price,
       dwh.Product_SKU__Google_Analytics as dwh_id
  FROM `ga4-data` as ga4, UNNEST(ga4.items) as ga4_items
  JOIN `datawarehouse-data` as dwh
    ON dwh.Product_SKU__Google_Analytics = ga4_items.item_id;

Comment: does the `join` statement in general do `full outer join`?
Comment: @Arihant  no. it means **INNER JOIN**.
Comment: Ah, I see. Do I have to write a `STRUCT` statement for each item_id? Because this set I'm using has hunderds of items.
Comment: @JHorizon,  I just reorganize your tables based on your query.  your query is trying to do join 2 tables with join keys. one is a **item_id** in **items** which type is an **array of struct** in GA4 table and another is a product SKU code named **Product_SKU__Google_Analytics** in **datawarehouse-data** table.
Comment: Alright! Thank you so much for your help so far!

I can run the script but runs into the following error: Temporary tables may not be qualified at [1:19]
Comment: @JHorizon - can you try running only the `SELECT ..` statement and skip both the `CREATE TEMP TABLE ..` statements. (i.e: line no. 11 onwards)
Answer: Alright, I figured it out. It took a lot of trial and error but I got it:
WITH ga as
(
    SELECT  event_date as ga4_date,
            ga4_items.item_id as id,
            ga4_items.item_name,
            ga4_items.price
    FROM    `name-ga4-dataset` as ga4, UNNEST(ga4.items) as ga4_items
),

dwh as
(
    SELECT Product_SKU__Google_Analytics as dwh_id
    FROM `name-dwh-dataset` as dwh
)

SELECT * FROM ga
JOIN dwh
ON ga.id = dwh_id


Email php erro , n consigo de jeito nenhum

Question: Renovando perguntar , usei o PHPMailer em um arquivo meu php , como coloco ele no meu site(html), para as pessoas me mandarem msgs para o gmail...
Comment: Importante você `EDITAR` esta pergunta, explicando-a de forma clara, objetiva e direta, enfatizando a dificuldade encontrada. Além disso, nos forneça um [Exemplo mínimo, completo e verificável](https://pt.stackoverflow.com/help/minimal-reproducible-example) do problema, junto com sua tentativa de resolução. E mais, sugiro a leitura do [Guia de sobrevivência do Stack Overflow em Português](https://pt.meta.stackoverflow.com/questions/8045/guia-de-sobreviv%C3%AAncia-do-stack-overflow-em-portugu%C3%AAs) para entender melhor o funcionamento da plataforma, evitando maiores frustrações.
Comment: Bem-vindo ao [pt.so]! Você colocou uma imagem do código e/ou mensagem de erro. Apesar de parecer uma boa ideia, não é! Um dos motivos é que se alguém quiser responder a pergunta, não pode copiar o código e alterar algo dentro. Clique no link [edit] e **coloque o código/erro como texto**. Veja mais sobre isso nesses links - [Manual de como NÃO fazer perguntas](https://pt.meta.stackoverflow.com/a/5485/3774), [Postar mensagem de erro como imagem](https://pt.meta.stackoverflow.com/q/7816/3774)
Answer: Este erro acontece porque você está tentando usar o $this fora de uma classe, recomento você pesquisar sobre PHP e orientação a objetos para entender o uso do $this.
Além disso para usar a função mail no Windows você vai precisar configurar algumas coisas a mais no seu ambiente, por conta disso muitos usam a lib PHPMailer no lugar da função mail.
Comment: vou tentar usar o PHPMailer.. se funcionar dou o accept
Comment: Comentei sobre o PHPMailer, mas o erro no seu código é por conta de usar o $this fora de um contexto de classe. Você entendeu o significado de usar $this?
Comment: Estou em curso de html , sei o básico de php. Estou vendo muitos videos e sites sobre fazer email do site direto para o meu gmail. Sobre o $this estava dando um erro de porta 25 de email e acabei colocando la , mas não , eu nao entendi Jhonny.
Comment: Como você é bem iniciante, vou te recomendar esse vídeo aqui para você conseguir realizar o seu objetivo https://www.youtube.com/watch?v=seoweg-PfEM
Comment: Jhonny Freire fiz  youtube.com/watch?v=seoweg-PfEM , certinho ; e agora como faço para botar no meu site oq vai mandar para o email ?
Comment: https://ibb.co/8d7vRMD a foto do powershell a unica coisa q deu errado , ja mexi no path do windows e no powershell antes . talvez seja isso
Comment: "ibb.co/8d7vRMD a foto do powershell a unica coisa q deu errado , ja mexi no path do windows e no powershell antes . talvez seja isso" posso usar o xxamp ao invés.
Comment: não manjo nada de php :(
Comment: Isso certamente está relacionado a forma que você instalou o PHP no Windows, quase certo que seja configuração nas variáveis de ambiente feitas errado. Aconselho a abrir um novo tópico  aqui no atackoverflow para esse problema em específico, Outras pessoas com esse problema poderão encontrar sua pergunta e se beneficiar da solução.
Comment: vou abrir sobre o powershell , mas me tira uma duvida dps que ajeita o PHPmailer como faço meu codigo para enviar as info colocadas no meu 'site' ?
Comment: https://ibb.co/rk276V1 <<<<<<< POWERSHELL AJEITADO
Comment: youtube.com/watch?v=seoweg-PfEM  tudo que esse site falou de phpmailer e powershell eu fiz
Comment: ja to com os codigos PHP tudo arrumado e agora oq eu faço, para botar num formulario no site ?
Comment: foi mal pelo outro post ,apaguei sem dar o accept , mas nesse n vou cometer o erro


How do derive the cardinality of $Y=\{(x_1,x_2)\in X^2:x_1=x_2\}$?

Question: Suppose we have a finite set $X$ with $|X|=n$ elements. To determine how many elements the set $X^2$ has, we use the properties of cardinality, and thus we do the following $$|X^2|=|X\times X|=|X||X|=n^2.$$ But, I struggle to derive how many elements the set $Y=\{(x_1,x_2)\in X^2:x_1=x_2\}$.
My thinking was that the set $Y$ has $\frac{1}{2}n^2$ elements since $x_1=x_2$. But this is wrong. The correct answer is $n$. Although I don't know how to justify it.
So is there a general method for calculating the number of elements of a set?
Thank you.
Comment: Can you _list_ the elements of $Y$? What elements are there?
Comment: @johnny09 But you only want elements where both coordinates are the same. If $|X|=n$, you know $X$ has $n$ distinct elements, which you could name $a_1,\dots,a_n$. Then, for example, $(a_1,a_1) \in Y$ since $a_1=a_1$, but $(a_1,a_2)\notin Y$ since $a_1 \neq a_2$. Can you list all the ordered pairs that are in $Y$?
Comment: @johnny09 Yes, although I would not end with $\dots$ as that makes it look like $Y$ is infinite. I would instead write $Y=\{(a_1,a_1),(a_2,a_2),\dots,(a_n,a_n)\}$.
Comment: Something like this $Y=\{(0,0),(1,0),(0,1),(1,1),(1,2),(2,2)\ldots\}$?
Comment: @kccu Okay, so $Y=\{(a_1,a_1),(a_2,a_2),(a_3,a_3),\ldots\}$, right?
Comment: @kccu Yes, of course, you're right. And thus $|Y|=n$. Thank you.
Answer: Let $f: Y\to X$ be defined by $f(x_1,x_2)=x_1$ then $f$ is a bijection and $|Y|=n$:
For any $x \in X$ we have $(x,x) \in Y$ so $x \in f(Y)$. If $f(x_1,x_2) = f(y_1,y_2)$ then $x_2 = x_1 = y_1 = y_2$ since both $(x_1,x_2)$ and $(y_1,y_2)$ are in $Y$. Thus $f$ is bijective.
Comment: Do you use the pigeonhole principle?
Comment: @johnny09 No, see my edit.


MQTT - validation for incorrect IP and Port

Question: I want to validate that given IP and port are running in MQTT if not then i have to show exception to user. here is my code,
try {

                MqttMessage message2 = new MqttMessage();
                MQTT mqtt_connect = new MQTT();
                mqtt_connect.setHost(Host_Address, port);

                String topic = "/call/MQTT_Config";
                mqtt_connect.setClientId("MQTT_Config");
                mqtt_connect.setWillRetain(false);
                mqtt_connect.isWillRetain();
                mqtt_connect.setWillTopic(topic);
                BlockingConnection m_publisher = mqtt_connect.blockingConnection();

                m_publisher.connect();

                if(m_publisher.isConnected()){
                    System.out.println("connected");

                m_publisher.disconnect();
                }
                else
                {
                    System.out.println("not connected");
                    return "Port or IP may not running";
                }

            } catch (Exception e) {
                e.printStackTrace();
                return "failure";
            }

when i give correct IP and port then it goes to if(m_publisher.isConnected()) condition fine but when i give wrong IP or port then it comes till m_publisher.connect(); and then there is nothing happen, like loading console only.Is not going to next step. why?
i have to show some validation when user give unmatched IP or MQTT port. where am i doing wrong?
Answer: The problem here will depend on what the user enters.

If they enter an IP address for a machine that exists but is not listening on the port then the machine will respond quickly with a connection refused message
If they enter an IP address for a machine that doesn't exist then the code will wait for the TCP timeout (default is 15mins) before raising an error.
Comment: ok i understand. so what is solution for this? is there any possible to set TCP timeout 1 min?


How to render a reactjs component stored in a redux reducer?

Question: I have a redux reducer loaded with several reactjs components.
I want to load these inside other components through this.props
Like: this.props.components.MyReactComponent
class OtherComponent extends Component {
  render() {
    const Component = this.props.components.MyReactComponent
    return (

        <Component />

    )
  }
}

Is this possible? If so, how?
EDIT The component is a connected component. I am able to load it but it is broken. In this case, it is a counter, when you click to increment or decrement nothing happens. In the console, there is this error:
Uncaught ReferenceError: _classCallCheck is not defined

if I convert the component into a dumb component (without connecting it), the error is this:
Uncaught ReferenceError: _classCallCheck3 is not defined

EDIT 2
I found out why those errors show up. It is because the react component gets stripped out when stored in the reducer:
A react component would look something like this:
{ function:
   { [Function: Connect]
     displayName: 'Connect(Counter)',
     WrappedComponent: { [Function: Counter] propTypes: [Object] },
     contextTypes: { store: [Object] },
     propTypes: { store: [Object] } } }

However, after I store it inside a reducer, it loses its properties and ends up looking something like this:
{ function:
   { [Function: Connect] } }

After reading the comments below, I thought of an alternative. I can store in a reducer the path to each component, then make a new wrapper component that could render those other components from those paths.
I tried it but encoutered a different problem with the funcion require from nodejs that for some weird reason is not letting me user a variable as an argument. For example:
This works:
var SomeContent = require('../extensions/myContent/containers')

This does not:
var testpath = '../extensions/myContent/containers'
var SomeContent = require(testpath)

Giving me the following error:
Uncaught Error: Cannot find module '../extensions/myContent/containers'.

It is adding a period at the end of the path. How can I prevent require to add that period?
If you can think of any other alternative I can implement for what I am trying to do, I would greatly appreciate it.
EDIT 3 Following Thomas advice...
What I am trying to accomplish is this:
I want to be able to render react components inside other react components, I know how to do it the same way most us know how to; however, I want to be able to do it by importing a file that would contain all the components  without actually having to import and export each one of them:
OtherComponent.js
import React, { Component } from 'react'
import { SomeComponent } from '../allComponentes/index.js'

export default class OtherComponent extends Component {
  render() {
    return (
      <SomeComponent />
    )
  }
}

SomeComponent.js
import React, { Component } from 'react'

export default class SomeComponent extends Component {
  render() {
    return (

        Hello

    )
  }
}

allComponents/index.js
import SomeComponent from '../allComponents/SomeComponent/index.js'

export { SomeComponent }

What I am trying to do in allComponents/index.js is to avoid having import/export statements for each component by reading (with fs module) all the components inside the allComponents folder and export them.
allComponents/index.js (pseudocode)
get all folders inside allComponents folder
  loop through each folder and require the components
    store each component inside an object

export object

When I tried that, I encountered multiple issues, for one, export statements have to be in the top-level, and second, fs would work only on the server side.
So, that is why I thought of loading all the components in a reducer and then pass them as props. But as I found out, they got stripped out when stored them in a reducer.
Then, I thought of only storing the path to those components inside a reducer and have a wrapper component that would use that path to require the needed component. This method almost worked out but the nodejs function require wont allow me to pass a variable as an argument (as shown in EDIT 2)
Comment: Why are you loading/storing components in the reducer?
Comment: @Joe Because I am experimenting and want to load components stored in a reducer. By the way, I can get the component to display but it is broken, I will update my original question to explain this.
Comment: It's just that I had only come across plain json type data objects in stores (which are then operated on in the reducer function), so I was thrown by your question.  Is storing your react component itself in the store not overcomplicating things?
Comment: Agree w. Joe, this seems like overcomplicating it, and definitely not the common use case w. Redux. Here is a quote from the Redux docs (http://rackt.org/redux/docs/basics/Reducers.html): `Given the same arguments, it should calculate the next state and return it. No surprises. No side effects. No API calls. No mutations. Just a calculation`. I'd say it would be much easier for yourself and your app to listen to a value from the Redux store, and based on that render the given component(s).
Comment: @Joe I updated my question, is that the reason of why my components stored in a reducer get stripped out? I am scanning a folder full of components and try to avoid having an index to export each of them. So I want to be able to import them inside other components without the need to export them manually.
Comment: @Thomas I updated my question, could you please elaborate your answer. I am open to alternatives to solve my problem.
Comment: @ElPirru I need more  information about the app and the purpose (what should it be able to do) before I can help you. Forget storing components for this, but rather tell us what is the purpose of the counter and when/why/how should it add/remove/something else a new component (and what does this component do). That way I'd be able to better help you and understand the context. Also please enlighten us in terms of structure of the app (files, directories etc.).
Comment: @Thomas I did my best to explain what I am trying to do, please let me know if my explanation is not clear enough, I will try to improve it.
Comment: @ElPirru Helps a bunch. One question: What do are you trying to gain of not importing/exporting modules, and instead store them in a reducer? Also when you mention the use of `fs`, it seems to me that you're not following a common React setup, see https://github.com/vesparny/react-kickstart for an example. Usually what you would to, is to have a bunch of different components, import them in a wrapper and then render/display them according to different settings within your reducer and potentially add react-router to allow users to route between specific components.
Comment: @Thomas I am trying to do a drop in system that will allow me to drop some files in a folder and it will just work. I already did this for reducers in an universal app and it is working beautifully. I will make it open source so I can let you know when I release it.
Answer: I think your question is not really to do with redux but rather is (as you say):
What I am trying to do in allComponents/index.js is to avoid having import/export statements for each component by reading (with fs module) all the components inside the allComponents folder and export them.

By way of example, I have all of my (dumb) form components in a folder path components/form-components and the index.js looks something like:
export FieldSet from './FieldSet'
export Input from './Input'
export Label from './Label'
export Submit from './Submit'
export Select from './Select'
export Textarea from './Textarea'

Then when I want to import a component elsewhere, it is import { FieldSet, Label, Input, Submit } from '../../components/form-components/';


Azure B2C | Password Reset sending to wrong UserJourney

Question: I followed the following tutorial: Password reset custom policy
I followed each step and did not get any errors when uploading the files to the b2c.
What the policy does is add a password reset option in the SignUpSignIn Policy. The button appears and it's clickable, but when clicked I'm redirected to the SignUp part of the policy instead of the password reset.
At first I thought it might be a template for the password reset, but when trying to use it to "create" an account the "create" button won't do anything.
The code for the Journeys is the following:
SignUpSignIn Journey:
<UserJourney Id="SignUpOrSignIn">
      <OrchestrationSteps>

        <OrchestrationStep Order="1" Type="CombinedSignInAndSignUp" ContentDefinitionReferenceId="api.signuporsignin">
          <ClaimsProviderSelections>
            <ClaimsProviderSelection TargetClaimsExchangeId="ForgotPasswordExchange" />
            <ClaimsProviderSelection ValidationClaimsExchangeId="LocalAccountSigninEmailExchange" />
          </ClaimsProviderSelections>
          <ClaimsExchanges>
            <ClaimsExchange Id="ForgotPasswordExchange" TechnicalProfileReferenceId="ForgotPassword" />
            <ClaimsExchange Id="LocalAccountSigninEmailExchange" TechnicalProfileReferenceId="SelfAsserted-LocalAccountSignin-Email" />
          </ClaimsExchanges>
        </OrchestrationStep>

        <OrchestrationStep Order="2" Type="ClaimsExchange">
          <Preconditions>
            <Precondition Type="ClaimsExist" ExecuteActionsIf="true">
              <Value>objectId</Value>
              <Action>SkipThisOrchestrationStep</Action>
            </Precondition>
          </Preconditions>
          <ClaimsExchanges>
            <ClaimsExchange Id="SignUpWithLogonEmailExchange" TechnicalProfileReferenceId="LocalAccountSignUpWithLogonEmail" />
          </ClaimsExchanges>
        </OrchestrationStep>

        <OrchestrationStep Order="3" Type="InvokeSubJourney">
            <Preconditions>
              <Precondition Type="ClaimsExist" ExecuteActionsIf="false">
                <Value>isForgotPassword</Value>
                <Action>SkipThisOrchestrationStep</Action>
              </Precondition>
            </Preconditions>
            <JourneyList>
              <Candidate SubJourneyReferenceId="PasswordReset" />
            </JourneyList>
          </OrchestrationStep>

        <OrchestrationStep Order="4" Type="ClaimsExchange">
          <Preconditions>
            <Precondition Type="ClaimEquals" ExecuteActionsIf="true">
              <Value>authenticationSource</Value>
              <Value>localAccountAuthentication</Value>
              <Action>SkipThisOrchestrationStep</Action>
            </Precondition>
          </Preconditions>
          <ClaimsExchanges>
            <ClaimsExchange Id="AADUserReadUsingAlternativeSecurityId" TechnicalProfileReferenceId="AAD-UserReadUsingAlternativeSecurityId-NoError" />
          </ClaimsExchanges>
        </OrchestrationStep>

        <OrchestrationStep Order="5" Type="ClaimsExchange">
          <Preconditions>
            <Precondition Type="ClaimsExist" ExecuteActionsIf="true">
              <Value>objectId</Value>
              <Action>SkipThisOrchestrationStep</Action>
            </Precondition>
          </Preconditions>
          <ClaimsExchanges>
            <ClaimsExchange Id="SelfAsserted-Social" TechnicalProfileReferenceId="SelfAsserted-Social" />
          </ClaimsExchanges>
        </OrchestrationStep>

        <OrchestrationStep Order="6" Type="ClaimsExchange">
          <Preconditions>
            <Precondition Type="ClaimEquals" ExecuteActionsIf="true">
              <Value>authenticationSource</Value>
              <Value>socialIdpAuthentication</Value>
              <Action>SkipThisOrchestrationStep</Action>
            </Precondition>
          </Preconditions>
          <ClaimsExchanges>
            <ClaimsExchange Id="AADUserReadWithObjectId" TechnicalProfileReferenceId="AAD-UserReadUsingObjectId" />
          </ClaimsExchanges>
        </OrchestrationStep>

        <OrchestrationStep Order="7" Type="ClaimsExchange">
          <Preconditions>
            <Precondition Type="ClaimsExist" ExecuteActionsIf="true">
              <Value>objectId</Value>
              <Action>SkipThisOrchestrationStep</Action>
            </Precondition>
          </Preconditions>
          <ClaimsExchanges>
            <ClaimsExchange Id="AADUserWrite" TechnicalProfileReferenceId="AAD-UserWriteUsingAlternativeSecurityId" />
          </ClaimsExchanges>
        </OrchestrationStep>

        <OrchestrationStep Order="8" Type="SendClaims" CpimIssuerTechnicalProfileReferenceId="JwtIssuer" />

      </OrchestrationSteps>
      <ClientDefinition ReferenceId="DefaultWeb" />
    </UserJourney>

PasswordReset subjourney:
<SubJourneys>
    <SubJourney Id="PasswordReset" Type="Call">
      <OrchestrationSteps>

        <OrchestrationStep Order="1" Type="ClaimsExchange">
          <ClaimsExchanges>
            <ClaimsExchange Id="PasswordResetUsingEmailAddressExchange" TechnicalProfileReferenceId="LocalAccountDiscoveryUsingEmailAddress" />
          </ClaimsExchanges>
        </OrchestrationStep>

        <OrchestrationStep Order="2" Type="ClaimsExchange">
          <ClaimsExchanges>
            <ClaimsExchange Id="NewCredentials" TechnicalProfileReferenceId="LocalAccountWritePasswordUsingObjectId" />
          </ClaimsExchanges>
        </OrchestrationStep>

        <OrchestrationStep Order="3" Type="SendClaims" CpimIssuerTechnicalProfileReferenceId="JwtIssuer" />

      </OrchestrationSteps>
    </SubJourney>
  </SubJourneys>

Answer: The sub-journey takes you to "LocalAccountDiscoveryUsingEmailAddress".
""

So you have to verify before you get to the next step "LocalAccountWritePasswordUsingObjectId" where you can reset the password.
Comment: I have another UserJourney that it's password reset. And it works fine, and it's very similar to the sub journey: https://pastebin.com/ebN1X8yf


Understanding the Taylor Series

Question: I'll admit I've always had a few confusions about the Taylor Series, as it itself looks completely unintuitive to me.
$$f(x) = f(x_0)+f'(x_0)(x-x_0)+\frac{f''(x_0)(x-x_0)^2}{2!}+\frac{f'''(x_0)(x-x_0)^3}{3!}+ \ ...$$
This looks really weird to me for a couple reasons (just the general expansion of $f(x)$):

Why is a point $x_0$ required to expand the function?
Why is the term $(x-x_0)$ and not $(x+x_0)$? I know shifting a graph to the right involves taking $f(x)$ to $f(x-x_0)$ but I've never really understood why intuitively, and why this is needed to expand the series.

Taking the derivative of $f(x) = f'(x)$.
$$\therefore f'(x) =
\frac{d}{dx}\left(f(x_0)+f'(x_0)(x-x_0)+\frac{f''(x_0)(x-x_0)^2}{2!}+\frac{f'''(x_0)(x-x_0)^3}{3!}+ \ ...\right)$$
$$f'(x) = f'(x_0)+ f''(x_0)\frac{d}{dx}[(x-x_0)]+ f'''(x_0)/2!\frac{d}{dx}[(x-x_0)]^2 \ + \ ...$$
$$f'(x) = f'(x_0) - f''(x_0)+f'''(x_0)(x-x_0)\ + \ ...$$
Now there are two constant terms, and the term to first have the $(x-x_0)$ multiplied to it is now the third term. I don't see any intuitive pattern here or anything.
I suppose what I'm asking for is an explanation for the intuition going on here other than the expansion matches any function evaluated at a point for every derivative. I'm asking for the two bulleted points to be addressed, with an explanation. I've tried reading about it a bit now and it hasn't been coming nicely to me, but if someone instead thinks I should read about it somewhere they think is good with explaining it I welcome that as a comment too.
Comment: https://www.youtube.com/watch?v=3d6DsjIBzJ4 (3Blue1Brown needs no introduction)
Answer: One way to think of Taylor series is as a generalization of the tangent line to a curve. At the point $x_0$ the tangent line to the graph of $y = f(x)$ can be written as
$$y = f(x_0) + f'(x_0)(x - x_0)$$
which is also called the linearization of $f$ at $x_0$: approximating the function by a linear/degree $1$ polynomial. If you want to approximate the function with a tangent "parabola" add higher-order derivatives and powers:
$$y = f(x_0) + f'(x_0)(x - x_0) + \dfrac{f''(x_0)}{2!}(x - x_0)^2$$
approximates the function with a degree $2$ polynomial at $x_0$.
If you want to approximate the function with a tangent "cubic" then continue the pattern:
$$y = f(x_0) + f'(x_0)(x - x_0) + \dfrac{f''(x_0)}{2!}(x - x_0)^2 + \dfrac{f'''(x_0)}{3!}(x - x_0)^3$$
Taylor series allow you to continue this to a degree $n$ polynomial:
$$y = f(x_0) + f'(x_0)(x - x_0) + \dfrac{f''(x_0)}{2!}(x - x_0)^2 + \dots +\dfrac{f^{(n)}(x_0)}{n!}(x - x_0)^n$$
Comment: For the graph of $y = f(x)$ a point on the curve is $(x_0, f(x_0))$ and the slope of the tangent line comes from the derivative $f'(x_0)$. Plug this into point-slope form of a line, $y - y_1 = m(x - x_1)$, and you get $y - f(x_0) = f'(x_0)(x - x_0)$. Add $f(x_0)$ to the other side.
Comment: Can you elaborate on how the tangent line to the graph of $y=f(x)$ can be written as $y=f(x_0) + f'(x_0)(x-x_0)$?
Comment: Sir i am reading your answer you take derivative of f(x)" as f'(xo)(x-xo) sir from where the term x-xo come
Answer: There exists a polynomial $p(x)$ such that all of its derivatives at some point ($x_0$), will equal all of the derivatives of $f(x)$ at $x_0$
The Taylor formula tells us how to generate this polynomial, and this is why we need the $x_0$ in the polynomial expansion.
$p(x) = f(x_0) + f'(x_0)(x-x_0) + \cdots+ \frac {f^{(n)}}{n!} (x-x_0)^n\cdots\\
p(x_0) = f(x_0) + f'(x_0)(x_0-x_0) + \cdots+ \frac {f^{(n)}}{n!} (x_0-x_0)^n\cdots = f(x_0)\\
p'(x) = f'(x_0) + f''(x-x_0) + \cdots+ \frac {f^{(n)}}{(n-1)!} (x-x_0)^{n-1}\cdots\\
p'(x_0) = f'(x_0)\\
p^{(n)}(x_0) = f^{(n)}(x_0)\\
$
Furthermore, this polynomial will be arbitrarily close to the original function everywhere inside the radius of convergence.  That is for any finite polynomial the error is bounded, and the degree of the Taylor approximation increases the upper bound of the error term goes to $0.$
This implies that knowing all of the derivatives of a function as some point is sufficient information to know everything about that function.
Update:
The Taylor theorem says that there is a sequence of polynomials such that:
$p(x) = f(x_0) + f'(x_0)(x-x_0) + \cdots+ \frac {f^{(n)}}{n!} (x-x_0)^n\\
f(x) = p_n(x) + \epsilon(x)$
Where $\epsilon_n(x)$ is the error term.
If $f(x)$ is "smooth", i.e. all of its derivatives exists.
Over an interval
$|\epsilon_n(x)| < |\frac {f^{(n+1)}(\xi)}{(n+1)!} (x-x_0)^{n+1}|$
Where $\xi$ is chosen as the maximal value of  $f^{(n+1)}(x)$ in that interval.
This puts an upper bound on the size of the error.
If the Taylor series converges, then $\lim_\limits{n\to\infty} |\frac {f^{(n+1)}(\xi)}{(n+1)!} (x-x_0)^{n+1}| =0$
Comment: What do you mean by "upper bound of the error term", exactly?
Comment: @sangstar I have added an update.

Understanding the Taylor Series


How to block admin area unless username is X (not user role is) in WordPress?

Question: I have a site where I want some users to have the role type of admin but still not be able to access the admin area (don't ask!) This is more of a temporary fix whilst my new site is being built.
I am using this code at the moment which blocks everyone to the admin area unless role type is admin - but how can I block admin unless username is 'mack' for example.
add_action( 'init', 'blockusers_init' );
function blockusers_init() {
    if ( is_admin() && ! current_user_can( 'administrator' ) &&
        ! ( defined( 'DOING_AJAX' ) && DOING_AJAX ) ) {
      wp_redirect( home_url() );
      exit;
    }
}

Obviously the user still needs to access all other front end pages of the site, just not the admin area.
Answer: use wp_get_current_user():
$current_user = wp_get_current_user();
if ($current_user->user_login != 'mack') {
    //It's not mack...
}

Comment: Thanks for your help, really appreciate it! my php is still pretty rusty! How can I amend my existing code above to include your tweak! Thanks a lot
Answer: If you want a temporary fix without working in your code maybe can you disable user
https://srd.wordpress.org/plugins/disable-users/
Otherwise as @Eduardo say you can do something like this
add_action( 'init', 'blockusers_init' );
function blockusers_init() {
    $current_user = wp_get_current_user();
    if ( is_admin() && ! current_user_can( 'administrator' ) &&
        ! ( defined( 'DOING_AJAX' ) && DOING_AJAX ) && $current_user->user_login != 'mack' ) {
      wp_redirect( home_url() );
      exit;
    }
}

Comment: Just tested this, added new user, role type admin with a different username than mack and can still access admin area?


DDNS client for Windows

Question: I need to manually update BIND DNS from a Windows server. The network team has given my IP address permissions to write to DNS. I'm having trouble finding a good client. I see that nsupdate is a good client for Linux. Searching for "nsupdate for Windows" has a lot of hits, but the clients seem less than ideal and require copying lots of DLLs around.
Ideally I'd like something using the .NET, Windows API, or PowerShell to update BIND DNS. Is there a good client for doing this?
To be more clear, I'm trying to take a cluster's hostname and manually change its IP address to be on different subnets. This will be used in manual failover scenarios.
Comment: ipconfig /registerdns
Comment: Your question lacks some details. What do you mean that you need to update a BIND DNS server from a Windows server? The Windows DNS client is a dynamic DNS client. Are you talking about a Windows client updating its' own A record or are you talking about a Windows DNS server updating a zone on a BIND DNS server?
Comment: I'm asking for the former, "a Windows client updating its' own A record". How do I issue a command to the Windows DNS client to update a DNS record?
Comment: sorry, was just updating my comment to say that I need to take a virtual ip and move it around between different subnets. The reason I need to do that is because I'm looking for a manual workaround to this problem: http://dba.stackexchange.com/questions/40915/how-do-i-change-sql-server-2012-availability-group-dns-subdomain
Answer: ISC makes a binary distribution of BIND for Windows.  The installer has a "tools only" option which doesn't install the server.
I haven't checked, but I presume nsupdate is one of the tools; you'd also get dig, which is very handy for DNS troubleshooting.
Comment: Indeed, nsupdate.exe is included with the zip file that you download to install the server.

DDNS client for Windows


how do I get the depth of a MenuLinkContent?

Question: I'm using the sitemap module and i need to get the menu link depth in my preprocess function (template_sitemap_menu_link). I'm trying to do that by accessing the MenuLinkContent object with
<code>    $menu_link_obj = $variables['element']['#original_link'];
</code>
There is a getParent() method I can access to check if this is a level zero item, but no way to check for depth. I could always loop trough getParent() until I get NULL and count the number of iterations, but that seems like a bad practise to me. Is there an alternative?
Answer: Here is our approach:
<code>$menu_link = $variables['element']['#original_link'];

$depth = 0;
$parent = $menu_link->getParent();
if ($parent) {
  while ($parent) {
    $parent_parts = explode(':', $parent);

    $parent_entity = \Drupal::service('entity.repository')->loadEntityByUuid($parent_parts[0], $parent_parts[1]);
    $parent = $parent_entity->get('parent')->get(0)->value;
    $depth ++;
  }
}
</code>
Hope to help
Comment: Anyone coming across this, it will cause an error when trying to access the value for `$parent_entity`. Use `$parent = $parent_entity->get('parent')->get(0) ? $parent_entity->get('parent')->get(0)->value : NULL;` will solve this, that we check for the parent first.


Sorting an Array of objects given an ordered list of ids

Question: I have a collection of objects @users, each having its id attribute.
@users = [#<User id:1>, #<User id:2>]

I also have an ordered Array of ids.
ids = [2,1]

¿Is there a magical way to sort the collection using that list of ids? Without making another call to the database, if possible.
Thank you !!!
Answer: In fact you don't need to sort, build an intermediate indexed hash, it's O(n):
users_by_id = Hash[@users.map { |u| [u.id, u] }]
users_by_id.values_at(*ids)

If you still wanted to try a sort approach, the Schwartzian transform would be adequate:
@users.sort_by { |u| ids.index(u.id) }

However, using index within a loop is a red flag: O(n^2) time. We can build an intermediate hash to go back to O(n*log n):
indexes = Hash[ids.each_with_index.to_a]
@users.sort_by { |u| indexes[u.id] }

Comment: Awesome one-liner solution. Thanks for the link to Schwartzian transform.
Comment: How about the situation when some items may repeat ? For example the list of last viewed files.
Comment: @Artur79: Then you probably need `Enumerable#group_by`
Answer: Try this. First, build up a reverse mapping from id -> user.
ids_users = {}

@users.each {|user| ids_users[user.id] = user}

Then, use the ids order
ids.collect{ |id| ids_users[id] }

Comment: Alternative way to construct the hash: `id_users = Hash[ @users.map { |u| [u.id, u] } ]`
Answer: You certainly don't need to go to the DB since you already have the User objects, although since the users are in an array, you'd probably want to create a temporary map of id => User to get the end result.
Answer: If you can access the id of each user by calling user.id, you could sort the array like this:
@users.sort!{|a,b| a.id <=> b.id }

If you only have the ids in a separate array from the objects you could do the following:
Zip the two arrays together, sort the resulting array on the ids, then collect the sorted users from the result.
users_ids = @users.zip(ids) # creates an array of smaller arrays each holding [user, id]
users_ids.sort!{|a,b| a[1] <=> b[1]} # sorts on the id in each sub-array
sorted_users = users_ids.collect{|item| item[0]} #grabs the users, leaving the ids behind

Take a glance at this: http://ariejan.net/2007/01/28/ruby-sort-an-array-of-objects-by-an-attribute


send vs return effects

Question: I was reading an article about reverb effects, and it said in that article that if you want to have good reverb effect, you can EQ the send  and sometimes EQ the return sound.
Now, I only know a single method to do that. I just put an EQ as an insert, after my reverb plugin(in FX channel). Am I EQing the send or return? And how could I use the other method?
By the way, my DAW is Cubase.
Answer: Reverb usually is a "linear" effect as is EQ.  That means short of exceeding valid input levels, it doesn't matter whether you put EQ or reverb first.  If you are using analog devices, either of those effects would provide a more level input to the other, so you'd put the device with worse signal-to-noise ratio last.  Digitally, there should not be much of a difference.
Answer: This is Cubase-specific [anything since about v5 can do it this way]
To EQ the send [separately from the actual channel] you would send the channel to a new channel instead of Stereo Bus, & add EQ to your new channel, but don't assign it to an output, instead remove it from Stereo Bus - so in effect it just 'vanishes'.
You use a regular FX send from that to your reverb.
You can use this for example to make only S's spin into a long bright reverb, without all the mud sending to it as well [George Michael trick from late 80's, early 90's]
To EQ the return, you EQ the reverb return itself on your FX channel, as your original example.
Comment: first, thanks for your answer. i just did what you said, but there is a problem . you said : dont assign it to an output, instead remove it from stereo bus... when i did that , the reverb effect was also gone. no reverb sound at all. what did i do wrong? and what do you mean by making S spin? thanks again for your kind help

send vs return effects