JavaScript map containing arrays turns into map containing maps

Question: I am creating a map containing arrays.
I'm sending this map as parameter to a method in a popup window.
This map of arrays is turning into a map of maps in the popup window!!
Im using IE8.
I'm creating a map like this:
var mapDetails = new Object();
mapDetails.fields = ['A','B'];
mapDetails.optSampleData = ['X','Y'];

JSON of map Im sending:
{'fields':['A','B'],'optSampleData':['X','Y']}

JSON of map Im receiving:
{'fields':{'0':'A','1':'B'},'optSampleData':{'0':'X','1':'Y'}}

This wouldnt be a problem in JS as the data can still be accessed as fields[0]. But, I'm sending it to server-side where I'm using GSON to parse the JSON. GSON turns it into a map.
Comment: How exactly you are "sending this map as parameter to a method in a popup window"? Do you use JSON serialization to string? If "yes" then what exactly is used?
Comment: I pass this object as a parameter to a function in the popup window. And then forward the same to server-side using JQuery ajax (to servlet). If sent from the main window the data gets converted to Map containing Lists by GSON. From the popup window it gets converted to a Map containing Maps by GSON. So, I tried to trace step by step using JSON.stringify. In the main page (before method call) stringify shows map containing arrays and in the popup window (on receiving method parameter) it shows map containing maps.
Answer: Try this function
function myParser(str) {

    str = str.replace(/'/g, '"');
    var obj = JSON.parse(str);

    for(var item in obj) {
        if(obj.hasOwnProperty(item)) {
            var array = [];
            for(var arrItem in obj[item]) {
                if(obj[item].hasOwnProperty(arrItem)) {
                    array.push(obj[item][arrItem]);
                }
            }
            obj[item] = array;
        }
    }

    return obj;
}

You can pass the received string into this function and receive your desired map containing arrays
Also you can reform your received string into your desired string format by this function:
var str = "{'fields':{'0':'A','1':'B'},'optSampleData':{'0':'X','1':'Y'}}";
var obj = myParser(str);
var desiredFormat = JSON.stringify(obj);
/* The result would be: */
/* "{"fields":["A","B"],"optSampleData":["X","Y"]}" */

Hope it helps you :)
Comment: I want to know the root cause because I intend to use JSON/GSON heavily and I dont want any surprises. Thanks anyway.
Comment: @Teddy Can you provide more codes? for example codes for how you pass the object from main window to popup window, Or create a fiddle!


What are some other basic forms besides ABA and ABACA?

Question: Edit: I took a look at the related question. The first answer illuminated me to free form ABCD... (let's not forget about free form!) and a good structure definition of Sonata. The other answers apparently did not have any ABC lettering description of forms (maybe I'm using a strict definition of "form"?). In any case, my question remains if any more basic forms exist (are well-established in baroque/classical/early romantic periods). I edited the title to include the word basic.
I only know 5 official forms:

ABCD... for Free Form
AA'A'' for Variations on a theme
ABA for the Minuet and Trio
ABACA for the Rondo (sometimes called ABA'B'A'')
ABABC(AB)' for Sonata

Surely there must be more? I could make up something like ABBA or any random combination of letters but I'd rather investigate the official forms first.
I wrote a Rondo and M&T years ago for the piano. I've wrote variations on a theme for a long time (they seem to be the easiest). Now I'm looking for other forms to try my hand, or I'll just make one up and consider it an exercise.
I'm partial to piano music, but official forms that are traditional for other types are okay too.
Edit: The baroque, classical, and early romantic periods are very long times with many, many works. I would be very surprised if only 5 basic forms existed there.
Comment: Any decent music encyclopedia or composition textbook will tell you all this.
Comment: I would just like to clarify that Sonata form is NOT at all ABABC(AB)'. It's more like AB(Development)A'B'(Ending).
Answer: This is a huge question, because, as you say, form can be anything: ABACAAAABADAAACDBAAACD. Obviously I'm being ridiculous, but forms is that sense are literally infinite.
With that said, there are a few other standard forms that you should know about, and I'll mix in some further information about what you currently have:

Binary form is an especially important one, often labeled as AB. Within binary form, there are two broad types: simple and rounded. Simple binary forms are simply an A section (repeated) followed by a B section (also repeated); though it is technically AABB, we abbreviate it to AB. Since you're a keyboardist, check out basically any suite movement by Bach---I'm partial to the C minor French Suite---to get a sense of simply binary movements. Rounded binary, however, is labeled ABA', because the A section returns to "round" out the form. Minuet string quartet movements---I recommend Haydn's Op. 76---are very often rounded binary forms.
As history progressed, these rounded binary forms became larger and larger, and eventually ABA' evolved into Exposition -- Development -- Recapitulation, what we call sonata form. This is much too complex a topic to fully discuss here (as evidenced by a very famous 700-page book), but the first movement of Beethoven's Op. 49, no. 1 is a very clear example.
You mentioned the minuet and trio form an ABA form; you're correct, and we call this ternary form. Sometimes it's difficult to distinguish ternary (ABA) from rounded binary (ABA'), but there are a few ways. First, rounded binary forms often create higher-level ternary forms. Minuets, as mentioned above, are often rounded binary forms; trios are, as well. But then these individual rounded binary forms create larger ternary forms. In other words, in your ABA ternary form, the first A is itself a rounded binary (aba'), and the B is also a rounded binary (let's call it cdc'), the final A is a return to the initial aba'. Thus the complete "minuet and trio" package is something like aba'|cdc'|aba', which we simplify as ABA. Note also that ternary forms are often more harmonically separate from rounded binary forms, with full cadences separating the large sections (but not always!). Key areas and motive are also often more distinct in ternary forms than in rounded binary forms. Nineteenth-century character pieces (like Chopin nocturnes!) are good examples of ternary forms.
Comment: 2 things: Does the non-rounded "Binary Form" belong to a specific kind of work, like sonata/rondo/prelude/ballad? And the bigger question: All your examples are limited to AB or some kind of ABA. I'm hunting for something a bit more intriguing like maybe ABCA or ABCB? If it helps, I'm **not** looking to analyze all the **parts taken together in a work**. Like a symphony has 4 parts, but I'm only interested in the ABwhatever form of **an individual part.** Comparing all the parts forms and then all the parts together would be too complex (for now).
Answer: Multiple "forms" as the question defines them can get named the same thing in classical music. For example, both ABACA and ABACABA are rondos, as is ABACADA. (In rare cases, a scherzo and double trio fits ABACA--or ABABA.)
There's also sonata-rondo form. Depending on which work you're listening to, it can be ABACB'A or ABACAB'AD.
For smaller forms within a work (e.g. the minuet in a minuet and trio), AABB or AB is binary form (either symmetrical binary or asymmetrical binary depending on how long A is compared to B), and AABA'BA' or ABA' is rounded binary form.
ABA is more commonly referred to as ternary form.
Arch form, which is ABCBA or ABCDCBA (etc.), also exists.
Sonata(-allegro) form with the recapitulation having its first theme group shorn off is best labelled as ABCB' (e.g. the first movement of Chopin's Piano Sonata No. 2 in B Flat Minor), while sonata(-allegro) form without the development is best labelled as ABAB' (e.g. the overture to Mozart's "The Marriage of Figaro").
March forms can get a wee bit complex--Sousa's marches often fit AABBCDCDC best.


Tag/Trunk Cisco 350x

Question: I am pretty new on the networking and cisco world.
As far as I learned, tagging is just assigning a port to a vlan, and, as per definition, trunking is assigning a port to more than one vlan
I am trying to trunk a port on a couple of vlans and that is what's happening on a 350x-48P:
<code>#configure terminal
(config)#interface GigabitEthernet1/0/48
(config-if)#switchport mode trunk
(config-if)#switchport trunk allowed vlan add 1,8
(config-if)#no shut
(config-if)#end

#show vlan
Created by: D-Default, S-Static, G-GVRP, R-Radius Assigned VLAN, V-Voice VLAN

Vlan       Name           Tagged Ports      UnTagged Ports      Created by
---- ----------------- ------------------ ------------------ ----------------
 1                                      gi1/0/3-10,               DV
                                          gi1/0/12-15,
                                          gi1/0/17-24,
                                          gi1/0/26-32,
                                          gi1/0/34-48,
                                          te1/0/2-3,
                                          gi2/0/1-48,
                                          te2/0/1-4,
                                          gi3/0/1-48,
                                          te3/0/1-4,
                                          gi4/0/1-48,
                                          te4/0/1-4,Po1-8
 2                        gi1/0/48                                S
 3                        gi1/0/48                                S
 5                         gi1/0/48                                S
 6                         gi1/0/48                                S
 7                         gi1/0/48                                S
 8                         gi1/0/48                                S
 10                        gi1/0/48                                S
 40                        gi1/0/48                                S
</code>
If I try only with a single port on a single vlan:
<code>#configure terminal
(config)#interface GigabitEthernet1/0/16
(config-if)#switchport mode trunk
(config-if)#switchport trunk allowed vlan add 1
(config-if)#no shut
(config-if)#end

#show vlan
Created by: D-Default, S-Static, G-GVRP, R-Radius Assigned VLAN, V-Voice VLAN

Vlan       Name           Tagged Ports      UnTagged Ports      Created by
---- ----------------- ------------------ ------------------ ----------------
 1                                      gi1/0/3-10,               DV
                                          gi1/0/12-15,
                                          gi1/0/17-24,
                                          gi1/0/26-32,
                                          gi1/0/34-48,
                                          te1/0/2-3,
                                          gi2/0/1-48,
                                          te2/0/1-4,
                                          gi3/0/1-48,
                                          te3/0/1-4,
                                          gi4/0/1-48,
                                          te4/0/1-4,Po1-8
 2                        gi1/0/16,gi1/0/48                                S
 3                        gi1/0/16,gi1/0/48                                S
 5                         gi1/0/16,gi1/0/48                                S
 6                         gi1/0/16,gi1/0/48                                S
 7                         gi1/0/16,gi1/0/48                                S
 8                         gi1/0/16,gi1/0/48                                S
 10                        gi1/0/16,gi1/0/48                                S
 40                        gi1/0/16,gi1/0/48                                S
</code>
Apparently it's just the right procedure, as per manual:
https://www.cisco.com/c/en/us/support/docs/smb/switches/cisco-small-business-300-series-managed-switches/smb4986-vlan-configuration-via-cli-on-300-500-series-managed-switche.html
Thanks for any help
J.
Comment: I do not see a problem. As far as adding VLANs to a trunk, it defaults to all VLANs, so adding them does not really do anything.
Answer: I don't see mistake on your side / command. It seems to me like you (or somebody else) have it added already before running this commands (adding it).
Try to remove the others or remove all and add just what you need. Be aware in case you are do configuration remotely to not remove VLAN which is used for the connection ;-).
VLAN 1 is default native VLAN and it is used also for e.g. spanning tree stuff. You will not be able to completely remove it but you don't need to use it for own traffic...
<code>#configure terminal
(config)#interface GigabitEthernet1/0/48
(config-if)#switchport trunk allowed vlan remove 2-7,9-40
(config-if)#end
</code>
It is good to check "starting state" before doing this kind of changes to not be surprise with the result.
Don't forgot to save the config to make it persistent over the reboot.
Answer: There is a mistake in the manual. You can read the following:
Note: In trunk mode, all VLANs are allowed by default. Using the switchport trunk allowed vlan add command lets you configure the VLANs allowed on the trunk.
When you trunk an interface all VLANs are allowed by default <- This is right.
switchport trunk allowed vlan add command <- there is the mistake
This command is used to add a vlan to the trunk, but the trunk allows all VLAN by default.
You have to use the same command without "add".
(config-if)# switchport trunk allowed vlan 1,8 -> This command will allow only VLAN 1 and 8.

Tag/Trunk Cisco 350x


JSON Objeto de Objetos

Question: Necessito de criar um objeto json a partir do zero em que cada key tem vários valores/values exemplo:
 '{"name":["daniel","dias"],"morada":["joao","allen"]}'

Para isso estou a executar este codigo várias vezes, mas o resultado é apresentado com keys geradas numéricas:
facetaPush - nome da key
response - array com os valores pretendidos
valuesFacetas - guardar objecto json final
var json_string = "";

json_string +='{\"'+facetaPush+'\":[' ;
for (var i = 0; i < response.length-1; i++) {
    json_string +='\"'+response[i]+'\",';
}
json_string +='\"'+response[response.length-1]+'\"]}';

var json_obj = JSON.parse( json_string );
valuesFacetas[facetaPush].push(json_obj);
alert("valores facetas: "+valuesFacetas[facetaPush][facetaPush]);

Comment: Qual é a razão de montares o JSON numa string? o que queres dizer com _"a key é dinamica por isso criar o objeto estaticamente"_? podes dar um exemplo?
Comment: editada pergunta
Answer: Uma maneira rápida de resolver isso é utilizando o JSON.stringfy ele aceita como argumento qualquer valor e o serializa em JSON.
Veja o seguinte exemplo:
var obj = {
    name: ["daniel","dias"],
    morada: ["joao","allen"]
}

JSON.stringify(obj)
// Resultado: "{"name":["daniel","dias"],"morada":["joao","allen"]}"

Comment: a key é dinamica por isso criar o objeto estaticamente não sei se é possivel
Answer: Acredito que seja algo parecido com isso que você quer:
function createMyObject(myKey, myCollection) {
   var myObj = new Object();
       myObj[myKey] = myCollection;
   return myObj;
}
var objName = createMyObject("name", ["daniel","dias"]);
var objMorada = createMyObject("morada", ["joao", "allen"]);

var all = createMyObject("myObjects", [objName, objMorada]);

console.log(objName, objMorada, all)

Answer: Se este for o seu padrão Objeto -> Array  você pode fazer um for para pegar as chaves e outro for para percorrer os valores deste array.

var json = {
  "name": ["daniel", "dias"],
  "morada": ["joao", "allen"]
};

console.log(json);

for (key in json) {
  console.log(key); // Pega chaves [name,morada]
  for (i = 0; i < json[key].length; i++) {
    console.log(json[key][i]); // [pega valores dos arrays dentro de name,morada]
  }
}
Answer: O JSON é a representação String do Objeto Javascript.
É mais fácil manipulá-lo como objeto.
Você pode acessar uma propriedade do objeto de diversas formas:
objeto.chave

ou
objeto['chave']

agora podemos trocar por uma variável
var varChave = 'chave';
objeto[varChave]

Fiz alguns exemplos para ver se você encontra o melhor caminho no seu caso:
// suas variáveis
var facetaPush = 'name';
var response = ['daniel', 'dias'];

var objeto = {};
objeto[facetaPush] = response; // exemplo com variáveis
objeto['morada'] = ['joao', 'allen']; // exemplo estático
objeto.morada = ['joao', 'allen']; // exemplo estático

Veja como o JSON ficaria:
var json = JSON.stringify(objeto);
// Resultado: "{"name":["daniel","dias"],"morada":["joao","allen"]}"

JSON Objeto de Objetos


How to write this to a linear programming problem?

Question: A procedure of animal feed makes two food products: F1 and F2. The products contain three major ingredients: M1, M2, and M3. Each ton of F1 requires 200 pounds of M1, 100 pounds of M2, and 100 pounds of M3. Each ton of F2 requires 100 pounds of M1, 200 pounds of M2, and 400 pounds of M3. There are at least 5000 pounds of M1 available, at least 7000 pounds of M2 available, and at least 10000 pounds of M3 available. Each ton of F1 costs $450 to make, and each ton of F2 costs $300 to make. How many tons of each food product should the producer make to minimize cost? What is the minimum cost?
Can I still use simplex method for this problem?
Answer: This problem looks like, that it is a good idea to apply the simplex algorithm. Just try it. I do some groundwork for you.
Defining the variables:
$x_1:=\texttt{amount of $F_1$ (in tons)}$
$x_2:=\texttt{amount of $F_2$ (in tons)}$
$y_1:=\texttt{amount of $M_1$ (in pounds)}$
$y_2:=\texttt{amount of $M_2$ (in pounds)}$
$y_3:=\texttt{amount of $M_3$ (in pounds)}$
The objective function is:
$\texttt{min} \ \ 450x_1+300x_2$
And the constraints are:
$x_1=200y_1$
$x_1=100y_2$
$x_1=100y_3$
$x_2=100y_1$
$x_2=200y_2$
$x_2=400y_3$
$y_1 \leq 5,000$
$y_2 \leq 7,000$
$y_3 \leq 10,000$
$y_1,y_2,y_3 \geq 0$
Every single equation requiress an artificial variable. And every single $\leq$-equation requiress a slack variable. Thus the simplex tableau is
$\begin{array}{|c|c|c|c|c|c|c|c|c|c|} \hline x_1&x_2&y_1&y_2&y_3 &a_1&a_2&a_3&a_4&a_5&a_6&s_1&s_2&s_3&RHS \\ \hline 450&300&0&0&0&0&0&0&0&0&0&0&0&0&0 \\ \hline 1&0&-200&0&0&1&0&0&0&0&0&0&0&0&0 \\ \hline 1&0&0&-100&0&0&1&0&0&0&0&0&0&0&0 \\ \hline 1&0&0&0&-100&0&0&1&0&0&0&0&0&0&0 \\ \hline 0&1&-100&0&0&0&0&0&1&0&0&0&0&0&0 \\ \hline 0&1&0&-200&0&0&0&0&0&1&0&0&0&0&0 \\ \hline 0&1&0&0&-400&0&0&0&0&0&1&0&0&0&0 \\ \hline 0&0&1&0&0&0&0&0&0&0&0&1&0&0&5,000 \\ \hline 0&0&0&1&0&0&0&0&0&0&0&0&1&0&7,000 \\ \hline 0&0&0&0&1&0&0&0&0&0&0&0&0&1&10,000 \\ \hline \end{array}$
The coefficients of the first row should be all non-positive at the end.


reduced relative homology

Question: In example 2.18 page 118 of Hatcher's Algebraic topology we read :

Applying the long exact sequence of reduced homology groups to a
  pair $(X,x_0)$ with $x_0\in  X$ yields isomorphisms $H_n(X,x_0)=\tilde H_n
(X)$ for all $n$ since $\tilde H_n (x_0)=0$ for all $n$.

Actually the long exact sequence gives that $\tilde H_n(X,x_0)=\tilde H_n
(X)$ for all $n$, i think it remains to show that $\tilde H_n(X,x_0)=H_n(X,x_0)$ for all $n$ which is equivalent to show that $\tilde H_0(X,x_0)=H_0(X,x_0)$ but how to do it? and is it true more generally that  $\tilde H_0(X,A)=H_0(X,A)$ for all non empty $A$?
Answer: Right before Example 2.17 on the same page, Hatcher says

In particular this means that $\tilde{H}_n(X, A)$ is the same as
  $H_n(X, A)$ for all $n$, when $A \neq \emptyset$.
Comment: The idea is explained in that paragraph of the text: essentially, relative chain complexes are already augmented.
Comment: thank you for pointing that out!! why is this true? what is the idea behind that?

reduced relative homology


A square is cut into three equal area regions by two parallel lines find area of square.

Question: A square is cut into three equal area regions by two parallel lines that are 1 cm apart, each one passing through exactly one of two diagonally opposed vertices. What is the area of the square ?
Comment: @amirbahadory: You must show your own efforts to get answer(s).
Comment: What did you try?
Comment: Please read [How to ask a good question](https://math.meta.stackexchange.com/questions/9959/how-to-ask-a-good-question?r=SearchResults&s=1|129.5144), amir.
Comment: Is this a stock image or did you change the problem from 1cm to 6in?
Comment: @DavidPeterson. No "1 cm " is true.i edited.
Comment: @DavidG.Stork . I think we can draw this in $\mathbb{R^2} $ and use integral.  But I can't find a square with this property.
Comment: HINT. Draw a diagonal of the square and consider the four triangles thus obtained.
Answer:
Let $AE=x$. By symmetry (equal area etc.) $FC=x$. Let the side of square be $a$. Then $DE=BF=\sqrt{a^2+x^2}$.
Area of the parallelogram $FBED$ = $\sqrt{a^2+x^2} \cdot 1=\sqrt{a^2+x^2}$.
Area of $\triangle DAE$ = Area of $\triangle FCB$ = $\frac{ax}{2}$.
$$\frac{ax}{2}=\sqrt{a^2+x^2} \implies \color{red}{x^2=\frac{4a^2}{a^2-4}}.$$
And area of square is thrice the area of the triangle gives us
$$a^2=\frac{3ax}{2} \implies 2a=3x.$$
Solve these to get $a^2=13$ (area of the square).


Red card during substitution in Football

Question: Can a player in football be given a red card during substitution because of entering the field long before the player being substituted exits? I'm curious to know this because in most of the matches that I've watched, the new player only enters after the substituted player exits
Comment: @Nij, this is not a duplicate as OP asks about a red card given to the *replacing* player (not the replaced one).
Comment: This is not a duplicate. The suggested duplicate is about *player*s who are leaving being cautioned/sent-off, not *substitute*s who are entering.
Comment: A dismissal for a second caution is still a dismissal and carries identical weight in the laws. Red cards are red cards, regardless of why they were given. @Don_Biglia
Comment: Yellow can be given, red? No.
Comment: A second yellow card and therefore red card can be given to a substitute or to a player about to be substituted. Likely it would not be, but you're making a blanket statement which is not correct. @Don_Biglia
Comment: The question has the same answer: any player can get their first or second card of either colour, regardless of whether they could be, have been, will be, are about to be, or are currently being substituted on or off. @Bebs
Comment: @Nij,please don't beat about the bushes
Comment: @Nij, in fact a yellow/red card can be given for many reasons so most answers of these kind of questions would be "Yes, it could happen". Answering "No, it never happened." to this question would very hard to prove. My guess is that OP was also asking for a reference of this situation, he probably could find references of red card given to the player going out, but not to the entering player.
Comment: The question is quite clearly "can it be done?" not "has it ever been done?". The answer is trivially that yes, the referee is empowered to give cards correct in law to any player or substitute or substituted player between the time they enter the ground until the time they leave it after the match, but as a practical matter, it is extremely unlikely that this exact precise combination of events has occurred in a context where it will be accessible to the community here. @Bebs
Comment: ... Therefore, the question as written is a duplicate as voted; any supposed additional question about actual events should be be separate from both.
Comment: @Nij A second yellow card leading to a red card is still a yellow card. There is a distinction (for me at least).The act of entering the pitch too early would never be seen as such a violence to give an immediate red card for it. I read the question as such.
Comment: @Don_Biglia, the substitute could have received a yellow earlier on the bench. Then the second yellow for entering too soon.
Comment: @Bebs I was not disputing that it wasn't possible. Just saying that this infriction alone would not trigger a direct red card on its own because the punishment for it would only be a yellow. Nij, I knew something like that would come, kinda why I added the for me bit. If a referee gives a second yellow resulting in red I view it differently. And so did the referee, if he deemed it grave enough he would give straight red regardless of him being booked already. And in game yes, but for further actions/suspensions a direct red card could not carry the same weight in the laws. But thats anthr dis
Answer: The answer is no, but they may be cautioned (which may indirectly result in a send-off for a second caution).
However, this question demonstrates why it is important to get the terminology used in the Laws of the Game correct so that there is no ambiguity.
As defined throughout Law 3 - The Players:

A player is one of the (up to) 11 active participants in the match.
A substitute is one of the potential replacements for a player, who must be named before the match.
A substituted player is a participant who was previously a player and was replaced by a substitute and may not take any further part in the match.

As defined in 3.3 - Substitution Procedure, when a substitution occurs - a player becomes a substituted player and a substitute becomes a player. If return substitutions are in use for the match, the player instead becomes a substitute (that is, they may be used again).
Now to answer the question, which appears to be about a substitute entering the field too early (not a player), the substitution procedure also states:

The substitute only enters:

during a stoppage in play
at the halfway line
after the player being replaced has left
after receiving a signal from the referee

The infringements and sanctions section of Law 3 - The Players (section 3.5) states:

For any other infringements of this Law:

the players1 are cautioned
play is restarted with an indirect free kick, from the position of the ball when play was stopped2

1 - I've just gone on a tirade about using the correct terminology, and here we have an example of the Laws themselves being incorrect. This sanction does not just apply to players, but also to substitutes and substituted players.
2 - This is only if the offence happened while the ball was still in play and isn't one punished by a direct free kick. If the ball was still in play, and as in this specific example, the substitute has entered the field incorrectly, the restart is a direct free kick [3.7]. If the ball is out of play, play restarts with the previous restart [12.4].
Therefore in practice, if substitutes are entering the field before the other player has left during the substitution procedure, in practice:

If the offence is only minor, the referee will use their discretion granted by Law 5, Section 2, Paragraph 1 to either ignore the offence or warn the team to adhere to the correct substitution procedure.
If the offence is blatant or the procedure continues being flouted by a team after having been warned, the referee will ask the substitute to leave the field, caution them for entering or re-entering the field of play without the referee's permission, and have them then re-enter the field correctly (provided by that point the player being substituted has left) to complete the substitution procedure correctly and become a valid player.
If this is the substitute's second caution, they are sent off for receiving a second caution in the same match and instead do not re-enter the field as a player after being sanctioned. Since they never became a player (and the player leaving never became a substitute / substituted player), the team does not play short. They may either opt for the player that was being replaced to continue, or use another substitute (if there are any eligible substitutes remaining).


Tricky problem with ASP.NET web forms resources and localization

Question: I've got the following nonstandard setup (VS2008, .NET 3.5 SP1):
There is a main web project called MainSite and There are several "plugin" web projects with different names.
When building these plugins I have a custom build step that calls aspnet_compiler.exe and aspnet_merge.exe. This results in two .DLL files - plugin_name.dll and plugin_name_deploy.dll. The first one contains the codebehind classes, the second one contains code generated from .ascx files.
These plugin .DLL's are then copied to /MainSite/bin/Plugins/ folder. At runtime (application startup) MainSite application looks in this folder and dynamically loads all the .DLL files there.
All my forms are in the plugins, in .ascx files. The main application is just a skeleton which loads these .ascx usercontrols as needed.
And now comes the need for localization. Ideally I would like to have the following:

When making the resources in Visual Studio, there should be a separate resource file for every form (.ascx file) so that it is easier for people to localize the forms in parallel.
The nice meta:resourcekey method in .ascx files is very comfortable for localizing controls;
The automatic resource language/culture fallback mechanism in .NET should be useable;
The result of compilation should be such that the files from all the plugins can be copied to the /MainSite/bin/Plugins/ folder. If there is a .DLL file for every language/culture and they hav to be put in some specific subfolders - that's fine as long as the .DLLs from different plugins don't have colliding names.

Any ideas on how to achieve this?
Answer: Apparently it is possible to implement custom resource providers in .NET. Here is an article that contains links to various other articles that explain the whole process. In effect, you take the value from meta:resourcekey and get the value from wherever you want. The article above, for example, stores all localization information in a DB.


Why can I pick out any singer's voice from a choir when I look at them?

Question: Our choir often practises in sections e.g. the sopranos sing their bit while the rest of us wait their turn. I discovered by accident that as I look at any particular singer, I can very clearly hear their individual voice, even if they are quite quiet and there's a dozen singers. I cannot do it if I don't look at them.
Does this phenomenon have a name? Is it common and why does it work this way? How can I expand on this useful skill?
Comment: Not certain so just a comment, but one factor could be that you can correlate their particular timing variations by seeing their mouths and matching that to their vocal contribution. There's probably all kinds of interesting cognitive research that could be (or has been?) done on this question.
Comment: I'm having trouble answering because I'm skeptical. When you look at a person, do you turn your head to face directly toward them? Does it work if you merely give them side-eye? If the latter, then this is about some kind of cognitive association; if the former, it's about acoustics. I'm skeptical, too, that this skill would work in rooms of other sizes and reverberance (in an echoey cathedral?). If it *does*, I'd have to wonder whether it's just confirmation bias (how do you *know* you're hearing that one person's voiceprint, not just imagining it?)
Comment: Other scientific-method ways to zero in: Does this work when watching another choir in concert, or only with the singers whose voices you've grown used to over frequent rehearsals?
Comment: I am not sure I understand the skepticism. Our choir-master can tell "Sarah is flat on this note" when we are all singing together in harmony so why is this hard to believe?
Comment: (Well, actually, maybe I do harbor a bit of doubt; if we wanted to be super-scientific about it, we definitely would have to rule out the possibility that we *think* we hear a particular person. And frequently as a conductor I'd make lucky/educated guesses to preserve the "ears in the back of his head" aura.
Comment: Another important aspect to consider is that with "lower" levels of performers, it's easier to have visual/acoustic clues of the player how's wrong: their "mistakes" are often much more clear, and the group is also often less "homogeneous" (there are many more differences in precision of tuning, rhythm/tempo and dynamics). Also, it's easier to associate a voice with a person as soon as there's any way to achieve that association (including small visual/acoustic clues), especially if you already know that voice; if the ambient is small (or the listener is close to the singer) and acoustics ->
Comment: @AndyBonner I agree with Mr. Boy. I taught guitar to a room full of third graders once, and I could hear clearly who was playing well and who wasn't, and who was in tune and who wasn't, even when they were all playing at once.
Comment: @ToddWilcox And indeed, as an orchestra director, I can do the same with violins. I can even identify the offending instrument by familiarity with its individual timbre. But 1) I consciously co-ordinate visual cues ("*Somebody's* flat! I'll look for bow movement that matches the start of the flat notes"), and 2) I of course could only recognize an instrument by its individual sound if I was very familiar with it. To be clear, Mr. Boy, I don't doubt that you can do what you describe, I'm just not sure it's anything other than a phenomenon of acoustics and observation.
Comment: -> allows it, our hearing and focusing on voices naturally allows us to focus more on a specific person. This is also related to the capacity of [attention](//en.wikipedia.org/wiki/Attention#Selective_and_visual), specifically the [selective auditory attention](https://en.wikipedia.org/wiki/Selective_auditory_attention). This is similar to the way we can often be able to focus on a conversation in a large crowd as soon as someone says our name or talks about a very specific subject that is somehow important for us.
Comment: @AndyBonner also, especially if it is an amateur choir, you might know that Sarah is flat because, well, of course it's Sarah who's flat.  Amateur singers tend to be consistent in their faults, whether being flat or sharp, dragging or rushing, and so on.
Comment: There are additional cues specific to the voice, too: vowel quality, volume/quality/timing of consonants, vibrato level/rate, variations in timbre between the different registers — most of which have visual as well as audible effects. (And, as phoog suggests, while in a good professional choir you'd hope that many of those things would be controlled and moderated and fairly homogeneous, in an amateur choir they're often unfortunately not.)
Answer: That's known as the cocktail party effect (being able to focus on particular speakers in a noisy environment), in this case aided by crossmodal sensory integration and attention.  It's one of those things where it is hard to get anywhere close to human performance with computing because it is a core tenet of visual and auditory processing that tends to be continually exercised.
Comment: This specific part sounded particularly relevant: https://en.m.wikipedia.org/wiki/Cocktail_party_effect#Visual_correlates


Configuring dhcp module in FreeRadius (3.0.2 - Centos 6.5)

Question: I am using the REST module to authorise a DHCP request.  I would like to send an explicit DHCP NAK if the authorisation fails, however the DHCP module seems to return immediately if there is a failure and just ignores the DHCP request without any response.
Here is my DHCP module configuration - if rest.authorize is successful, the if (ok) control block is hit, but if rest.authorize fails the if (fail) is never hit.
  dhcp DHCP-Discover {
    rest.authorize

    if (fail) {
            update reply {
                    DHCP-Message-Type = DHCP-Nak
            }
    }

    if (ok) {
        update reply {
           DHCP-Message-Type = DHCP-Offer
        }

        update reply {
            DHCP-Domain-Name-Server = x.x.x.x
            DHCP-Domain-Name-Server = x.x.x.x
            DHCP-Subnet-Mask = 255.255.255.0
            DHCP-Router-Address = x.x.x.x
            DHCP-IP-Address-Lease-Time = 3600
            DHCP-DHCP-Server-Identifier = x.x.x.x
        }
        mac2ip
    }
 }

Below is the output after a 401 Unauthorized is received.  I am wanting to achieve a temporary block on DHCP for a specified (small) period of time.  However the FreeRADIUS behaviour is to ignore duplicate requests for same DHCP transaction, meaning DHCP on client is blocked until it begins a new transaction.  If a DHCP NAK can be sent, the DHCP client will initiate a new transaction after each NAK (i.e. DHCP Discover), meaning FreeRADIUS will process each DHCP Discover from the client, and the block will be removed much closer to the desired block time.
Tue Jun  3 03:00:57 2014 : Debug: (3) rest : Sending HTTP GET to

"http://xxxxxx//api/v1/dhcp/80%3Aea%3A96%3A2a%3Ab6%3Aaa"
Tue Jun  3 03:00:57 2014 : Debug: (3) rest : Processing response header
Tue Jun  3 03:00:57 2014 : Debug: (3) rest :    Status : 401 (Unauthorized)
Tue Jun  3 03:00:57 2014 : Debug: (3) rest : Skipping attribute processing, no body data received
Tue Jun  3 03:00:57 2014 : Debug: rlm_rest (rest): Released connection (4)
Tue Jun  3 03:00:57 2014 : Debug: (3)   modsingle[authorize]: returned from rest (rlm_rest) for request 3
Tue Jun  3 03:00:57 2014 : Debug: (3)   [rest.authorize] = fail
Tue Jun  3 03:00:57 2014 : Debug: (3)  } # dhcp DHCP-Discover = fail
Tue Jun  3 03:00:57 2014 : Debug: (3) Finished request 3.
Tue Jun  3 03:00:57 2014 : Debug: Waking up in 0.2 seconds.
Tue Jun  3 03:00:58 2014 : Debug: Waking up in 4.6 seconds.
Received DHCP-Discover of id 7b0fb2de from 172.19.0.9:67 to 172.19.0.12:67
Tue Jun  3 03:00:59 2014 : Debug: (3) No reply.  Ignoring retransmit.
Tue Jun  3 03:00:59 2014 : Debug: Waking up in 2.9 seconds.
Received DHCP-Discover of id 7b0fb2de from 172.19.0.9:67 to 172.19.0.12:67
Tue Jun  3 03:01:02 2014 : Debug: (3) No reply.  Ignoring retransmit.
Tue Jun  3 03:01:02 2014 : Debug: Waking up in 0.4 seconds.
Tue Jun  3 03:01:02 2014 : Debug: (2) Cleaning up request packet ID 2064626397 with timestamp +56
Tue Jun  3 03:01:02 2014 : Debug: Waking up in 1999991.0 seconds.
Received DHCP-Discover of id 7b0fb2de from 172.19.0.9:67 to 172.19.0.12:67
Tue Jun  3 03:01:06 2014 : Debug: (3) No reply.  Ignoring retransmit.
Tue Jun  3 03:01:06 2014 : Debug: Waking up in 3999983.1 seconds.
Received DHCP-Discover of id 7b0fb2de from 172.19.0.9:67 to 172.19.0.12:67
Tue Jun  3 03:01:15 2014 : Debug: (3) No reply.  Ignoring retransmit.
Tue Jun  3 03:01:15 2014 : Debug: Waking up in 7999966.3 seconds.
Received DHCP-Discover of id 7b0fb2de from 172.19.0.9:67 to 172.19.0.12:67
Tue Jun  3 03:01:23 2014 : Debug: (3) No reply.  Ignoring retransmit.
Tue Jun  3 03:01:23 2014 : Debug: Waking up in 15999942.1 seconds.

On Option #4 solution below, although this works in terms of DHCP NAK, the DHCP module "remembers" the REST authorisation result for the DHCP transaction.  Only when the device attempts a new transaction does the DHCP module make the REST authorisation call again:
Received DHCP-Discover of id 7b0fb322 from 172.19.0.9:67 to 172.19.0.12:67
Sending DHCP-NAK of id 7b0fb322 from 172.19.0.12:67 to 172.19.0.9:67
Wed Jun  4 00:31:32 2014 : Debug: Waking up in 3.5 seconds.
Received DHCP-Discover of id 7b0fb322 from 172.19.0.9:67 to 172.19.0.12:67
Sending DHCP-NAK of id 7b0fb322 from 172.19.0.12:67 to 172.19.0.9:67
Wed Jun  4 00:31:35 2014 : Debug: Waking up in 0.6 seconds.
Wed Jun  4 00:31:36 2014 : Debug: (4) Cleaning up request packet ID 2064626465 with timestamp +138
Wed Jun  4 00:31:36 2014 : Debug: Waking up in 1999991.0 seconds.
Received DHCP-Discover of id 7b0fb322 from 172.19.0.9:67 to 172.19.0.12:67
Sending DHCP-NAK of id 7b0fb322 from 172.19.0.12:67 to 172.19.0.9:67
Wed Jun  4 00:31:40 2014 : Debug: Waking up in 3999982.8 seconds.

Comment: This is really neat, it's nice to see using the flexibility of the server to do interesting things.
Answer: rest.authorize {
    fail = 1
}
if (reject || fail) {
    update reply {
        DHCP-Message-Type = DHCP-NAK
    }
}

OK. So you have four options:

Return a 401 with a JSON content-type and just a set of empty braces {} (that may work)
Use the v3.0.x HEAD commit where i've just altered the behaviour to allow empty bodies. It's odd it's actually calling the body data callback for an empty body. I didn't expect that, which is why it errors out. This will appear in released version 3.0.4.
Edit the return statement just below RDEBUG2("Skipping....") in src/modules/rlm_rest/rest.c to be return 0.
Edit your rest call to match the snippet I added above (because putting it after this bulleted list screwed with the formatting).
Comment: I am returning an empty 401 Unauthorized - see added debug output in OP and explanation of the FreeRADIUS DHCP behaviour I am trying to overcome.
Comment: I recommend option 4 :) It's actually the correct configuration anyway if you want to NAK requests if your REST API is unavailable.
Comment: I found that if I use your suggested solution above ONLY for DHCP Request (not for DHCP Discover), at least on Apple iOS the DHCP behaviour is to create a new DHCP transaction much faster (within 10 seconds) in response to DHCP NAK than if this happens on the DHCP Discover message.


Are there any other instances of a coach's challenge backfiring?

Question: My title just refers to "coach's challenge" so it will be shorter. I intend to also include other non-neutrally-initiated replay review, such as for example manager's challenges .
The one instance I am aware of is from the 2017 Nov 12 NFL game Packers vs Bears,
in which the original ruling was  Bears ball at the 3 yard line,
the Bears coach challenged hoping for a ruling of  touchdown by the Bears,
and the challenge resulted in a ruling of turnover, Packers ball.
Are there any other instances of a non-neutrally-initiated replay review backfiring?
Answer: Jim Schwartz's attempted challenge against the Texans in 2012 probably counts here. What happened:

Texans running back Justin Forsett was knocked down, but got up and continued to run. The play was called a touchdown.
As this was a scoring play, it was subject to automatic review.
Jim Schwartz threw his challenge flag. Because the play was already subject to review, this was an illegal challenge.
As the rules stood at the time, an illegal challenge prevented all review of the play, so the automatic review was cancelled.
Therefore the touchdown stood, whereas it was highly likely that the automatic review would have called the touchdown back if Schwartz had not thrown his flag.

which was frankly a bit bonkers. For a less extreme example, see Mike McCarthy's attempted challenge against the Vikings in 2012. That was a similar situation, except that McCarthy threw his flag after the official replay had begun, so the replay happened and gave the Packers a touchdown. The Packers still got a a 15 yard penalty on the kickoff though.
In the 2013 offseason, the NFL got rid of the rule that hammered the Lions because everybody agreed it was a bit silly.


Kivy apps not starting in from systemd

Question: Failed to start Kivy apps in systemd on Raspberry4 (Buster) with Kivy 11.1.1.
I wrote an app using Kivy framework 11.1 running on Raspberry4 (buster). The application is working fine when I start it from cli
However, I got an error when starting this same app within systemd. Looks like environnement variable are not set properly.
Below is an illustration - fyi, I added os.system('env') in my program before importing kivy.
LANGUAGE=fr_FR.UTF-8
USER=asysclay
SHLVL=0
HOME=/home/asysclay
OLDPWD=/
PS1=(ENV)
LOGNAME=asysclay
JOURNAL_STREAM=8:52735
_=/home/asysclay/ASYSClay/ENV/bin/python
PATH=/home/asysclay/ASYSClay/ENV/bin:/home/asysclay/ASYSClay/ENV/bin:/home/asysclay/ASYSClay/asysclayscores/sbin:/bin:/usr/sbin:/usr/bin
INVOCATION_ID=f86a4183f7b840ff88e9aac0fe41c9ef
KIVY_WINDOW=sdl2
LANG=fr_FR.UTF-8
SHELL=/bin/bash
VIRTUAL_ENV=/home/asysclay/ASYSClay/ENV
PWD=/home/asysclay/ASYSClay/asysclayscores

[INFO   ] [Logger      ] Record log in /home/asysclay/.kivy/logs/kivy_19-09-06_79.txt
[INFO   ] [Kivy        ] v1.11.1
[INFO   ] [Kivy        ] Installed at "/home/asysclay/ASYSClay/ENV/local/lib/python2.7/site-packages/kivy/__init__.pyc"
[INFO   ] [Python      ] v2.7.16 (default, Apr  6 2019, 01:42:57)
[GCC 8.2.0]
[INFO   ] [Python      ] Interpreter at "/home/asysclay/ASYSClay/ENV/bin/python"
[WARNING] [Deprecated  ] Python 2 Kivy support has been deprecated. The Kivy release after 1.11.0 will not support Python 2 anymore
[INFO   ] [Factory     ] 184 symbols loaded
[INFO   ] [Image       ] Providers: img_tex, img_dds, img_sdl2, img_pil, img_gif (img_ffpyplayer ignored)
[INFO   ] [Text        ] Provider: sdl2
[INFO   ] [Window      ] Provider: sdl2(['window_egl_rpi'] ignored)
error: XDG_RUNTIME_DIR not set in the environment.
[CRITICAL] [Window      ] Unable to find any valuable Window provider. Please enable debug logging (e.g. add -d if running from the command line, or change the log level in the config) and re-run your app to identify pot
ential causes
sdl2 - RuntimeError: Could not initialize EGL
  File "/home/asysclay/ASYSClay/ENV/local/lib/python2.7/site-packages/kivy/core/__init__.py", line 71, in core_select_lib
    cls = cls()
  File "/home/asysclay/ASYSClay/ENV/local/lib/python2.7/site-packages/kivy/core/window/window_sdl2.py", line 152, in __init__
    super(WindowSDL, self).__init__()
  File "/home/asysclay/ASYSClay/ENV/local/lib/python2.7/site-packages/kivy/core/window/__init__.py", line 981, in __init__
    self.create_window()
  File "/home/asysclay/ASYSClay/ENV/local/lib/python2.7/site-packages/kivy/core/window/window_sdl2.py", line 290, in create_window
    self.get_gl_backend_name())
  File "kivy/core/window/_window_sdl2.pyx", line 224, in kivy.core.window._window_sdl2._WindowSDL2Storage.setup_window
  File "kivy/core/window/_window_sdl2.pyx", line 74, in kivy.core.window._window_sdl2._WindowSDL2Storage.die

Comment: I'm looking for guidance for setting up env properly
Comment: I think you need to set the DISPLAY, at least - your problem is probably that Kivy is being started outside of a graphical environment. This is a specific issue that you can search for, there's probably a standard solution.
Answer: I came across the same problem when trying to start a Kivy application automatically with a systemd service file. The error I was getting was
Loaded: loaded (/etc/systemd/system/wfpiconsole.service; enabled; vendor preset: enabled)
Active: failed (Result: exit-code) since Sun 2019-09-22 15:11:26 BST; 1min 34s ago
Process: 448 ExecStart=/usr/bin/python3 -u main.py (code=exited, status=1/FAILURE)
Main PID: 448 (code=exited, status=1/FAILURE)

Sep 22 15:11:24 raspberrypi python3[448]:     self.create_window()
Sep 22 15:11:24 raspberrypi python3[448]:   File "/usr/local/lib/python3.7/dist-packages/kivy/core/window/window_sdl2.py", lin
Sep 22 15:11:24 raspberrypi python3[448]:     self.get_gl_backend_name())
Sep 22 15:11:24 raspberrypi python3[448]:   File "kivy/core/window/_window_sdl2.pyx", line 224, in kivy.core.window._window_sd
Sep 22 15:11:24 raspberrypi python3[448]:   File "kivy/core/window/_window_sdl2.pyx", line 74, in kivy.core.window._window_sdl
Sep 22 15:11:25 raspberrypi python3[448]: [INFO   ] [Text        ] Provider: sdl2
Sep 22 15:11:25 raspberrypi python3[448]: 2019-09-22 15:11:25+0100 [-] Log opened.
Sep 22 15:11:26 raspberrypi python3[448]: [CRITICAL] [App         ] Unable to get a Window, abort.
Sep 22 15:11:26 raspberrypi systemd[1]: wfpiconsole.service: Main process exited, code=exited, status=1/FAILURE
Sep 22 15:11:26 raspberrypi systemd[1]: wfpiconsole.service: Failed with result 'exit-code'.

I solved the problem by adding Environment=DISPLAY=:0 to the [Service] section of the systemd file.

Kivy apps not starting in from systemd


How to read and write to a text file in C++?

Question: Hey everyone, I have just started to learn C++ and I wanted to know how to read and write to a text file. I have seen many examples but they have all been hard to understand/follow and they have all varied. I was hoping that someone here could help. I am a total beginner so I need clear instructions. Here is an example of what i'm trying to do:
#include <iostream>
#include <fstream>
using namespace std;
string usreq, usr, yn, usrenter;
int start ()
{
    cout << "Welcome..."
int main ()
{
    cout << "Is this your first time using TEST" << endl;
    cin >> yn;
    if (yn == "y")
        {
            ofstream iusrfile;
            ofstream ousrfile;
            iusrfile.open("usrfile.txt", "w");
            iusrfile >> usr;
            cout << iusrfile;
            iusrfile.close();
            cout << "Please type your Username. \n";
            cin >> usrenter;
            if (usrenter == usr)
            {
            start ();
            }
        }
    else
        {
            cout << "THAT IS NOT A REGISTERED USERNAME.";
        }

    return 0;

}

Comment: Which C++ book are you learning from?
Answer: Header files needed:
#include <iostream>
#include <fstream>

declare input file stream:
ifstream in("in.txt");

declare output file stream:
ofstream out("out.txt");

if you want to use variable for a file name, instead of hardcoding it, use this:
string file_name = "my_file.txt";
ifstream in2(file_name.c_str());

reading from file into variables (assume file has 2 int variables in):
int num1,num2;
in >> num1 >> num2;

or, reading a line a time from file:
string line;
while(getline(in,line)){
//do something with the line
}

write variables back to the file:
out << num1 << num2;

close the files:
in.close();
out.close();

Answer: Default c++ mechanism for file IO is called streams.
Streams can be of three flavors: input, output and inputoutput.
Input streams act like sources of data. To read data from an input stream you use >> operator:
istream >> my_variable; //This code will read a value from stream into your variable.

Operator >> acts different for different types. If in the example above my_variable was an int, then a number will be read from the strem, if my_variable was a string, then a word would be read, etc.
You can read more then one value from the stream by writing istream >> a >> b >> c; where a, b and c would be your variables.
Output streams act like sink to which you can write your data. To write your data to a stream, use << operator.
ostream << my_variable; //This code will write a value from your variable into stream.

As with input streams, you can write several values to the stream by writing something like this:
ostream << a << b << c;

Obviously inputoutput streams can act as both.
In your code sample you use cout and cin stream objects.
cout stands for console-output and cin for console-input. Those are predefined streams for interacting with default console.
To interact with files, you need to use ifstream and ofstream types.
Similar to cin and cout, ifstream stands for input-file-stream and ofstream stands for output-file-stream.
Your code might look like this:
#include <iostream>
#include <fstream>

using namespace std;

int start()
{
    cout << "Welcome...";

    // do fancy stuff

    return 0;
}

int main ()
{
    string usreq, usr, yn, usrenter;

    cout << "Is this your first time using TEST" << endl;
    cin >> yn;
    if (yn == "y")
    {
        ifstream iusrfile;
        ofstream ousrfile;
        iusrfile.open("usrfile.txt");
        iusrfile >> usr;
        cout << iusrfile; // I'm not sure what are you trying to do here, perhaps print iusrfile contents?
        iusrfile.close();
        cout << "Please type your Username. \n";
        cin >> usrenter;
        if (usrenter == usr)
        {
            start ();
        }
    }
    else
    {
        cout << "THAT IS NOT A REGISTERED USERNAME.";
    }

    return 0;
}

For further reading you might want to look at c++ I/O reference
Answer: To read you should create an instance of ifsteam and not ofstream.
ifstream iusrfile;

You should open the file in read mode.
iusrfile.open("usrfile.txt", ifstream::in);

Also this statement is not correct.
cout<<iusrfile;

If you are trying to print the data you read from the file you should do:
cout<<usr;

You can read more about ifstream and its API here
Comment: ifstreams are always opened in input mode
Comment: I agree that there is no need to pass the mode as ifstream::in is default parameter to the ifstream::open, but I think its a good idea to explicitly mention it.
Comment: Oh yeah whoops, "ofstream iusrfile" was supposed to be "ifstream iusrfile". And thanks for the help on the cout statement.


What permissions do i need to read users email folder using Graph Api?

Question: I am logged in as email@example.com in Graph Explorer. I am trying to read the email folder structure and contents of a generic email where we send documents to . The email is firstname.lastname@example.com. Both emails are under the same tenant/organization in Azure.
So if im logged in as  firstname.lastname@example.com , i send the command
<code>https://firstname.lastname@example.com/mailFolders

It seems to give an error: "Forbidden - 403 - 226ms. You need to consent to the
permissions on the Modify permissions (Preview) tab"
</code>
Which permission do i need to give ?
Answer: As the message already stated, if you're using the MS Graph Explorer then there's a tab called "Modify permissions (preview)" which then displays all required permissions and also offers an option to consent to them.
Keep in mind that this is only a test environment. You still have to consent these permissions in your app later.
Comment: I have added the permissions from Graph Explorer , but am getting access denied error. So if i  have 2 users lets say firstname.lastname@example.com , firstname.lastname@example.com . Every email that email@example.com gets firstname.lastname@example.com should get , that requires a shared email access. Do i need to set up anything in Azure to give email@example.com access to email@example.com  ?
Comment: Could be some configuration problem for your app registration, sometimes app-permissions aren't enough or not available and you need delegated ones. Take a look [here](https://www.azure365pro.com/access-specific-office-365-mailbox-using-microsoft-graph/) for some more help.


How to find duration in year and months from date field in internal tables without API's in ABAP?

Question: So, I have 2 internal tables, with a date of joining field in the 1st table and a service years field in the other table; I have added the data to the tables manually.
I have used the following logic to find years but it seems incomplete:
    TYPES : BEGIN OF s_empdetails,
              empid       TYPE n,
              fname(20)       TYPE c,
              doj         TYPE dats,
             END OF s_empdetails.

    TYPES : BEGIN OF s_details,
              empid      TYPE n,
              serv_yrs   TYPE dats,
            END OF s_details.

    DATA : gt_header  TYPE TABLE OF s_empdetails WITH HEADER LINE,
           gwa_header TYPE s_empdetails.

    DATA :gt_result  TYPE TABLE OF s_details,
          gwa_result TYPE s_details.

DATA : gv_date     LIKE sy-datum.

gv_date = sy-datum.

    gwa_header-empid = 10002.
    gwa_header-name = 'Aditya'.
    gwa_header-doj = '20200205'.

    APPEND gwa_header TO gt_header.
    CLEAR gwa_header.

    gwa_header-empid = 10003.
    gwa_header-name = 'Sumit'.
    gwa_header-doj = '20170701'.

    APPEND gwa_header TO gt_header.
    CLEAR gwa_header.

    LOOP AT gt_header INTO gwa_header.
      gwa_result-empid = gwa_header-empid.
      gwa_result-name = gwa_header-name.

      APPEND gwa_result TO gt_result.
      ENDLOOP.

I used the following logic to get the number of years but it doesn't give accurate years, as a person joining in January will still get 1 year service on his name. So, how can I get years and months as well here.
LOOP AT gt_result ASSIGNING FIELD-SYMBOL(<gwa_result>).

  READ TABLE gt_header ASSIGNING <gwa_header> WITH KEY empid = <gwa_result>-empid.

  <gwa_result>-serv_yrs = gv_date+0(4) - <gwa_header>-doj+0(4).

ENDLOOP.

Comment: Well, you are completely ignoring the month and day of both the date in the data and the current date, so what did you expect? Although if year of joining and current year are identical, I would expect a result of 0 years from this code.
Answer: Working with dates and times is more difficult than they seem at first. So it's usually advisable to leave date-arithmetics to a library. Unfortunately I am not aware of any standard library for date and time handling which is available on every ABAP system. There are just some module-specific libraries like the class CL_RECA_DATE in the module RE-FX or the function module COMPUTE_YEARS_BETWEEN_DATES which is part of the HR module.
Unfortunately we don't know what modules you have installed on your system, so we don't know which of those are available to you. Which means we need a pure ABAP solution.
A solution which does not handle leap-years correctly but might be good enough for some situations might be this:
DATA(years_between) = ( gv_date - <gwa_header>-doj ) / '365.0'.

Subtracting one TYPE d variable from another gives you the number of days between those two dates. Dividing that by 365 would convert those to a number of years if every year had 365 days*. Not stating a type for this inline declaration of years_between results in type I being determined, which will result in the year being rounded to the nearest integer. If you need the exact fraction of years, you can get that by stating the type of years_between as a type which can handle more accuracy. Like a floating point value, for example:
DATA years_between TYPE f.
years_between = ( sy-datum - date1 ) / '365.0'.

Note that TYPE dats like in your code snippet above is not going to work. It will give you meaningless results. That type represents a specific date, not a timespan between two dates. So don't try to use it in that context.

*Unfortunately not all years have 365 days. If you need to handle leap-years at all and if so how you would handle them depends on the exact use-case for the numbers you are calculating here. So I am going to leave that as an exercise to the reader :)


WCF Service Impersonate One User But Still User Windows Authentication?

Question: I am using LinqToEntitiesDomainService to connect to a SQL Server Database.  This requires Windows Authentication, which I have working.
I wrote a web service that uses Activator.CreateInstance(...) to run an executable on the server.  I would like this to use Windows Authentication, as well.  However, I need the service to have the proper permissions to run the executable.
When I run the service right now, it works fine.  My account has the proper roles to authenticate.  I also have god-like permissions on the server, which allows me to have the Activator.CreateInstance(...) command work.
While other users who have the proper roles can authenticate, their account doesn't have permissions on the server, nor should it.
Is there some (preferably, easy) way to run the service as one user, but have all of the authentication done with windows authentication?  It would also be best if I could do it all in just one app pool...
Thank You!
Answer: Yes you can, take a look at this article. This shows some techniques for impersonating users.
using (WindowsImpersonationContext impersonationContext =
                                 ((WindowsIdentity)User.Identity).Impersonate())
{
    // do something as current user
}

Or in WCF you can also define this declaritively.
public class HelloService : IHelloService
{
    [OperationBehavior(Impersonation = ImpersonationOption.Required)]
    public string Hello(string message)
    {
        return "hello";
    }
}

Note these two techniques impersonate the client (caller).
To impersonate another user explicitly you need some P/Invoke. There's a project here that wraps it all up for you quite neatly. You can then do this:
using (new Impersonator("myUsername", "myDomainname", "myPassword"))
{
   // do something as myUsername
}


How to pass data from JsonResult to JQGrid in MVC?

Question: I have used JQGrid to get the data from the controller which uses "GET". But, still I'm getting a blank table. I have also tried to apply breakpoints and check whether my variable "details" inside "Detail" Method getting value or not. It worked fine. I guess the problem is in returning the data in JSON format.
Controller
 [HttpGet]
        public JsonResult Detail()
        {

            IntegrationsProcessor db = new IntegrationsProcessor(new MCNIDbContext());
            DBModel.Integrations row = db.GetIntegrationRow();
            List<Integrations> details = new List<Integrations>
            {
                new Integrations
                {
                    IntegrationName = row.IntegrationName,
                    CompanyEmail = row.CompanyEmail
                }
            };

            return new JsonResult()
            {
                Data = details,
                JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                MaxJsonLength = Int32.MaxValue
            };

HTML file
@using MCNIDev.CustomControls
@model MCNIDev.Models.ViewModel.Integrations

@{
    ViewBag.Title = "Details";
}

<!DOCTYPE html>

    <meta name="viewport" content="width=devicexb c-width" />
    <title>Integrations</title>

@Styles.Render("~/Content/toasterCss")
@Styles.Render("~/Content/dataPickerCss")

    @using (Html.BeginForm("", "Integrations", FormMethod.Post, new { enctype = "multipart/form-data", @class = "form-horizontal", id = "frmManifestOrders" }))
    {

Integrations

                                    <input type="button" class="btn btn-secondary" onclick="document.location.href='/Dashboard/Dashboard';" value="Cancel" />

    }

@Scripts.Render("~/bundles/integrations")

JQGrid File
var Integrate = function() {
function GetValue() {
    $("#tblSelectIntegrations").jqGrid({
        type: "GET",
        url: "/Integrations/Detail",
        datatype: "json",
        async: false,
        colNames: [
            "First Name", "Email Address"
        ],
        colModel: [
            //{
            //    name: '',
            //    key: false,
            //    width: 30,
            //    editable: true,
            //    formatter: function () {
            //        return "<input type='checkbox' value='Select' class='fm-button ui-state-default ui-corner-all fm-button-icon-left noPrint'\>";
            //    }
            //},
            { key: false, name: 'IntegrationName', index: 'IntegrationName', editable: false, width: 200 },
            { key: false, name: 'CompanyEmail', index: 'CompanyEmail', editable: false, width: 200 },
         //   { key: false, name: 'Blank', index: 'Blank', editable: false, width: 200 }
        ],
        pager: jQuery("#divSelect"),
        rowNum: 1,
        scroll: 0,
        height: $(window).innerHeight() - 450,
        width: "100%",
        viewrecords: true,
        caption: "Product",
        emptyrecords: "No records to display",
        jsonReader: {
            root: "rows",
            page: "page",
            total: "total",
            records: "records",
            repeatitems: false
        },
        autowidth: true,
        multiselect: false,
        loadonce: false,
        ajaxGridOptions: { cache: false },
        gridComplete: function () {
        },

    }).navGrid("tblSelectIntegrations", { edit: false, add: false, del: false, search: false, refresh: false });
}
return {
        GetValue: GetValue
    };
}();

Answer: The issue lies in controller. I am trying to send data without telling JQGrid where to insert data.
var jsonData = new
            {
                rows = value
            };
            return Json(jsonData, JsonRequestBehavior.AllowGet);

Replace below code with above code
return new JsonResult()
            {
                Data = details,
                JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                MaxJsonLength = Int32.MaxValue
            };

In my first code I've mentioned that add my data in the rows.


Can anyone think of a way of preventing an XP client from performing DNS lookups for external domains?

Question: As usual, we're trying to tighten security even further in our organisation.  The current focus for me is the possibility of a compromised XP client from using DNS lookups as a command/control channel (Google "dns malware command control channel").
Of course, this presupposes that a client could be compromised in the first place; something that we believe very unlikely.  That said...
We're currently a Windows Server 2003 AD shop, with all DNS zones stored in AD.  The DNS servers are allowed to forward to our ISP's DNS serverz - something that is required by a number of servers, i.e.: we need to resolve external addresses for B2B stuff.
The XP clients and Windows servers are on the same domain, and therefore share the same DNS servers.  The clients can therefore perform external address lookups.
If a client were to be compromised, it could before a lookup of whatsmynextmove.hacker.com, and the SOA for that domain could return a crafted reply which holds the control instruction.
So, the question is, can anyone think of a way of preventing the XP clients from performing DNS lookups for domains other than the local DNS domain (the one for the AD forest).
My thoughts so far:
1) Get some kind of proxy man-in-the-middle DNS product that the XP clients use.  The proxy filter lookups for domains other than the internal domain.
2) Identify all the external domains that we need to resolve and configure conditional forwarders for each of them, e.g.: microsoft.com, verisign.com, redhat.com, Etc, Etc.  I'm not sure how many conditional forwarders can be configured.
Any thoughts.... anyone?
Comment: So you guys have been reading a bunch of security related books and white papers and are trying to secure your network from every possible exploit regardless of how farfetched, unlikely, or crippling to your network the remediation might be?
Answer: What I did was use my firewall to block all LAN to WAN port 53 (DNS) traffic.  Then I configure the firewall's DHCP to push out the DNS server of it's IP address (because it has a caching DNS proxy built in).  Then I modified the DNS records to block some ad and marketing/tracking companies.  Last I set the firewall to forward requests to OpenDNS and signed up for filtering and blocked content by group and added exceptions.
Actually when I said I blocked port 53, what I actually did to make bot's job a little harder is restrict out going traffic by port (i.e. 80, 443, ...) to only what I needed.  When I get the IP address for email nailed down (because they seem to change every now and then) I will restrict them by port and IP so no other email will be allowed in/out.
Configuring your DNS requests down to the proxy IP and port and blocking all others would probably help some.
Of course don't forget to review the logs so you know if something did crawl in to a machine or if you are blocking something that should be unblocked.
Hope this helps.
Answer: Ever heard the phrase "Breached by Design"?
The DOE should wake up and realize that if you're using Windows on a network with any kind of outside access - no matter how many layers of protection you add on - you're already breached. Microsoft spent a fortune making their software able to phone home, and those methods are designed to get past any kind of defense you could set up.
Every single leaky channel - from security updates, to the 9,999,999 auto-updating software packages, to the insane ability of IE to rewrite your OS on the fly, to the amazing number of secret squirrel backwards communications channels (like DNS and their own little backspin on windows time server) and so on until you realize how futile it all is... Well, every channel is a potential entry point into your network.
This problem - which is becoming an issue of national security (now that the foxes have been roaming the hen house as they like ever since Balmer's boys scrambled to get Internet Explorer integrated into the OS) is that the use of Windows - and now dot Net - has become a "best practice". The problem is that it simply cannot be secured without using an air gap - meaning a network that isn't connected to any WAN or internet source. But even the brightest minds at the various TLA outfits are content to pretend that it'll never happen to their network.
The sad thing is that this is the same kind of thinking that made the Antivirus business a multi-billion dollar industry. If the management at MS hadn't decided that attempting to run/execute/evaluate every byte of data encountered was a good idea when DOS 3 appeared, we wouldn't be suffering from the headaches of AVG/McAffee/Norton/Windows Defender/etc. If you had a two year old, would you teach it to put everything it found on the sidewalk into it's mouth? Microsoft didn't invent the trojan/virus, but they did more to spread them than anyone could have dreamed of. But I digress.
In spite of this, the fix is easy. Almost.
Put a linux or BSD unix box in. Disable all services except DNS and tell the DNS server it can only resolve for whatever you've put in the config, and maybe look upstream to the AD box for local or local domain addresses - using the linux box to filter out everything else. Then hard-code the DNS box in as the server for anything you want to lock down.
You'll pass your DOE audit with flying colors. The bad news is that the DOE audits are roughly as sophisticated and comprehensive as those other audit theatricals with catchy names like SAS-70. Like most security programs, they're more along the lines of security blankets than armed guards. If you run a windows network, and you have users using Internet Explorer, or Windows Search, or Chrome, or Google Desktop, or whatever else they managed to get installed - your security is entirely imaginary. Windows IS the primary vector - not because it's common, but because it's breached by design.
Comment: I think the same can be said for any large code-base O/S or application.  As soon as you connect a computer to a network, you expose its attack surface. I agree, the attack surface of some operating systems / applications is bordering on laughable, but at least the big(ger) vendors are now awake, not something that can be said about some of the small(er) vendors I deal with.
Interestingly, the perceived C&C threat that's been identified with DNS is not a leak, design flaw or vulnerability; it's just a very imaginative use of a core-infrastructure component.
Comment: Simon, the problem is that Windows - and most especially Internet Explorer and the new search functions - is actually far worse than "any large code-base O/S or application". The C&C threat is very, very real and has already been a problem for far too long.
Answer: You need to implement something like split-brain DNS. For your setup you may begin getting ideas here.
Answer: The fact that this page now shows up second in Google for your proposed search phrase suggests that this is not a significant attack vector.
Thus far the most significant use of DNS per se has been as a pseudo C&C channel by the Conficker worm.  In this case frequently changing domain names were however only used to permit the download of updates to the worm, and not to directly control it.  Hence blocking web access to the clients was sufficient to thwart that vector.
If you really must do this, you might find what you need in the local-zone features of the Unbound recursive resolver to forward your local domain to the AD server and reject everything else.  You'd need to configure your XP clients to use that server instead of your existing AD server.
Answer: joeqwerty - not quite.  We're an American owned company, and have recently been audited by the "U.S. Department of Energy's Office of Nuclear Energy".  This attack vector (Command and Control vector) is one of the "must fix" entries in the audit.  But thanks for the response.
Comment: Not sure where to put this - so here will do.  The solution I've settled on is to have a second triplet of non-AD DNS servers, which only forward to our 'real' DNS for our "mydomain.co.uk" and "in-addr.arpa".   Seems to work well.  Just need to get sign-off from the auditors.
Comment: I think option 2 in your question may be the only way to do it with W2K3 DNS servers without the use of additional products, tools, etc.


Which parts of the t-statistic depend on the other variables?

Question: When testing whether a variable is significant in a linear model, we perform the T test for the hypothese $H_0: \beta_j = 0$ vs $H_1: \beta_j \neq 0$:
$$ T = \frac{\beta_j}{\sqrt{\sigma^2[(X^TX)^{-1}]_{jj}}} $$
It's my understanding that when we interpret whether a variable is significant, based on the outcome of this test, it is in relation to the other variables being included in this model. Which part of this statistic takes the other variables into account? And is this test equivalent to performing an F-test between the model with $\beta_j$ and the model without it?
Answer: Indeed, the coefficients relate to the other variables being included in this model. Maybe being more precise with notation already clears up the confusion: it is better to write the t-statistics as
$$ T = \frac{\hat\beta_j}{\sqrt{\hat\sigma^2[(X^TX)^{-1}]_{jj}}}, $$
with $\hat\beta_j$ an estimate of the true coefficient $\beta_j$ about which we test some hypothesis. Now, if we include other variables into our regression model, the estimates will change. You can also observe it from the present formula via $X'X$ - with other specifications of the regression, other variables will be contained in $X$ and hence the standard error will change, too.
As to your second question, this thread may be relevant: Proof: Adding additional regressor and the influence on the adjusted R^2


Como faço um relacionamento OneToMany Unidirecional com joincolumn obrigatório?

Question: Como faço esse relacionamento ser obrigatório quando o em.persist() for executado?
Não quero mapear bidirecional.
<code>@OneToMany(cascade = {CascadeType.ALL})
@JoinColumn(name = "cliente_id",referencedColumnName="ID",insertable=true, nullable=false, columnDefinition="bigint DEFAULT 1 NOT NULL")
public List<Telefone> getTelefones() {
    return telefones;
}
</code>
Answer: Esta pergunta não contem as Entidades.
Bom, neste caso basta não não criar nenhum atributo na classe Telefone.
Conforme está no seu código, vc está dizendo que esta classe (não especificada na pergunta) possui vários telefones. Do jeito que está, já está unidirecional, caso vc não tenha declarado nenhum atributo desta classe (não especificada na pergunta) na classe Telefone.


Maximum principle for a nonlinear heat equation

Question: Suppose that $\Omega\in\mathbb{R}^n$ is bound and open with smooth boundary $\partial\Omega$. Consider the following initial-boundary value problem for a nonlinear heat equation:
$$
\begin{cases}
%\vspace{3mm}
u_t=\Delta u+u(1-u), \ \ &x\in\Omega,\ \ t>0,\\
%\vspace{3mm}
u(x,0)=u_0(x),\ \ &x\in\Omega,\\
u=0, \ \ &x\in\partial\Omega,\ \ t>0,
\end{cases}
$$
where $0\le u_0\le1$. Show that $0\le u(x,t)\le1$, $x\in\Omega$, $t>0$.
We prove $u(x,t)\le1$ by contradiction. Assume for some $(x_1,t_1)$ with $x_1\in\Omega$ and $T>t_1>0$, we have $u(x_1,t_1)>1$ and
$$
\displaystyle\max_{x\in\overline{\Omega}, T\ge t\ge0} u(x,t)=u(x_1,t_1).
$$
Then $u_t(x_1,t_1)=0\ge\Delta u(x_1,t_1)$, which leads to
$$
u_t-\Delta u-u(1-u)\Big|_{(x,t)=(x_1,t_1)}>0.
$$
Therefore $u(x,t)\le1$. On the other hand, however, I have no idea how to prove $u(x,t)\ge0$. A similar argument for proving $u(x,t)\le1$ seems not work for the proof of $u(x,t)\ge0$. Any suggestion for ideas or proofs is welcome, thanks!
Another related question: When the homogeneous Dirichlet boundary condition $u=0$ is replaced by the homogeneous Neumann boundary condition $\frac{\partial u}{\partial \nu}=0$, the same conclusion remains true?
Answer: Consider $\displaystyle v\left(x,t\right)=u\left(x,t\right)-\frac{t}{4}$. Then you can get  \begin{equation}v_t-\Delta v=u_t-\Delta u+u-u^2-\frac{1}{4}\leq0, \end{equation}which implies $v$ is subsolution of the heat equation. Hence we can apply the maximum principle to $v$ to obtain\begin{equation}\max_{\Omega}v\leq\max_{\Omega}u_0\left(x\right)\leq1.\end{equation} Thus, $u\leq1$.
On the other hand, we can set $\displaystyle w\left(x,t\right)=1-u\left(x,t\right)+\frac{t}{4}$ and $w_0\left(x\right)=1-u_0\left(x\right)$. Then we can get\begin{equation}w_t-\Delta w=w\left(w-1\right)+\frac{1}{4}\geq0,\end{equation}which means $w$ is the supersolution of the heat equation. Similarly, by using the minimum principle, we have shown\begin{equation}\min_{\Omega}w\leq\min_{\Omega}w_0\leq1.\end{equation}Thus, $u\geq0$.


Diagonalizing a matrix with complex numbers

Question: hope everyone is doing well.
I'm a bit stuck on the following problem:
$T: C^2 \rightarrow C^2$, where $T$ is defined by $T(x,y)=(2x + (3-3i)y, (3+3i)x + 5y$
So I perform the usual calculations to diagonalize the matrix, right up until I find that the roots of the characteristic polynomial are $\lambda_1 = -1, \lambda_2 = 8$
From here I am having a hard time performing the row operations to get my eigenvectors. I realize that the calculations are fairly trivial but they are confusing me.
If someone could help me with, for example, the matrix associated to $\lambda_1$ I would be grateful:
$$
    \begin{matrix}
    3 & 3+3i \\
    3-3i & 6 \\
    \end{matrix}
$$
Comment: What is confusing you? The two rows are proportional by a factor $1 - \mathrm i$.
Comment: So is the eigenvector associated to $\lambda_1$ $(1, 1+i)$?
Answer: We may write
$T(x,y)=(2x + (3-3i)y, (3+3i)x + 5y \tag 1$
as
$T \begin{pmatrix} x \\ y \end{pmatrix} = \begin{bmatrix} 2 & 3 - 3i \\ 3 + 3i & 5 \end{bmatrix} \begin{pmatrix} x \\ y \end{pmatrix}, \tag 2$
and then he characterisic polynomial of $T$ is
$\det (T - \lambda I) = \det \left ( \begin{bmatrix} 2 & 3 - 3i \\ 3 + 3i & 5 \end{bmatrix} - \lambda I \right ) = \det \left ( \begin{bmatrix} 2 - \lambda & 3 - 3i \\ 3 + 3i & 5 - \lambda \end{bmatrix} \right) = \lambda^2 - 7 \lambda - 8; \tag 3$
it is easy to see that the roots of
$\lambda^2 - 7 \lambda -  8 = 0 \tag 4$
are
$\lambda = -1, \; 8; \tag 5$
since I'm not too swift at row operations myself, I'll solve for the eigenvectors directly from
$\begin{bmatrix} 2 & 3 - 3i \\ 3 + 3i & 5 \end{bmatrix} \begin{pmatrix} x \\ y \end{pmatrix} = \lambda \begin{pmatrix} x \\ y \end{pmatrix}; \tag 6$
writing out the first row of this equation yields
$2x + (3 - 3i)y = \lambda x, \tag 7$
or
$(2 - \lambda)x + (3 - 3i) y = 0, \tag 8$
or
$y = -\dfrac{(2 - \lambda)x}{3 - 3i} = \dfrac{(\lambda - 2)x}{3 - 3i}; \tag 9$
since eigenvectors are are scalable, we may take $x = 1$; then the two eigenvectors are characteized by the two $y$-values
$y =  \dfrac{(-1 - 2)x}{3 - 3i} = \dfrac{-3}{3 - 3i} = \dfrac{-1}{1 - i} = \dfrac{-1 - i}{2}, \tag{10}$
$y =  \dfrac{(8 - 2)x}{3 - 3i} = \dfrac{6}{3 - 3i} = \dfrac{2}{1 - i} = \dfrac{2 + 2i}{2} = 1 + i; \tag{11}$
we may thus take the two eigenvectors to be
$v_{-1} = \begin{pmatrix} 1 \\ \dfrac{-1 - i}{2} \end{pmatrix}, \; v_8 = \begin{pmatrix} 1 \\ 1 + i \end{pmatrix}; \tag{12}$
we note that $v_{-1}$ and $v_8$ are in fact orthogonal with respect to the Hermitian inner product on $\Bbb C^2$ defined by
$\langle w, z \rangle = \bar w_1 z_1 + \bar w_2 z_2, \tag{13}$
where $w, z \in \Bbb C^2$:
$w = \begin{pmatrix} w_1 \\ w_2 \end{pmatrix}, \; z = \begin{pmatrix} z_1 \\ z_2 \end{pmatrix}; \tag{14}$
indeed,
$\langle v_{-1}, v_8 \rangle = 1 \cdot 1 + \dfrac{-1 + i}{2} \cdot (1 + i) = 1 - \dfrac{2}{2} = 0; \tag{15}$
the orthogonality of $v_{-1}$, $v_8$ should not surprise us since they belong to distinct eigenvalues of the matrix $T$, which is Hermitian:  $T^\dagger = (T^\ast)^T = T$.  $v_{-1}$ and $v_8$ form the columns of $V$, a diagonalizing matrix for $T$:
$V = \begin{bmatrix} v_{-1} & v_8 \end{bmatrix} = \begin{bmatrix} 1 & 1 \\ \dfrac{-1 - i}{2} & 1 + i \end{bmatrix}, \tag{16}$
the determinant of which is
$\det(V) = 1 + i + \dfrac{1 + i}{2} = \dfrac{3}{2}(1 + i); \tag{17}$
the inverse of $V$ is thus
$V^{-1} = \dfrac{2}{3(1 + i)}\begin{bmatrix} 1 + i & - 1 \\ \dfrac{1 + i}{2} & 1 \end{bmatrix} = \begin{bmatrix} \dfrac{2}{3} & -\dfrac{2}{3(1 + i)} \\ \dfrac{1}{3} & \dfrac{2}{3(1 + i)} \end{bmatrix}; \tag{18}$
finally, since
$TV = T\begin{bmatrix} v_{-1} & v_8 \end{bmatrix} = \begin{bmatrix} Tv_{-1} & Tv_8 \end{bmatrix} = \begin{bmatrix} -v_{-1} & 8v_8 \end{bmatrix}, \tag{19}$
we may write
$V^{-1}TV = V^{-1} \begin{bmatrix} -v_{-1} & 8v_8 \end{bmatrix} =  \begin{bmatrix} -V^{-1} v_{-1} & 8V^{-1} v_8 \end{bmatrix} = \begin{bmatrix} -1 & 0 \\ 0 & 8 \end{bmatrix}. \tag{20}$


Variance of change after $K$ steps in AR(1) model

Question: I am generating from a standard AR(1) process. Lets assume a decay time lag $\tau=100$ and unit time steps of $\Delta t=1$, so $\phi=\exp(-1 / (\tau/\Delta t))=0.99$. The predicted autovariance is $\sigma^2 = \frac{1}{1 - \phi^2}$.
Then the AR is defined as $y_{i+1} = \phi \times y_i + \epsilon$, where $\epsilon \sim \mathrm{Normal}(0,1)$.
Now I want to investigate the change after K steps: $$y_{i+K}-y_i$$
I find empirically that the distribution is normal with variance:
$$\sigma(K)^2 = (\tau/2 + 1) \times (1 - \exp(K/\tau)^2)$$
Can this be derived analytically?
I suspect that K steps incur $\tau$ standard deviations of variance $\sigma^2$, but why half of that, and why the offset?
More generally for Gaussian processes: How can this variance be derived from the integral over the power spectral density?
This question is different from autocorrelation/autocovariance, which looks at $y_{i+K} \times y_i$.

Here is my python code:
<code>import numpy as np
def generate_AR(N = 1000, sigma = 1.0, c=0, dt=1., tau=100):
    W = np.random.normal(0, sigma, size=N)

    # correlation: set to < 1, otherwise not stationary!
    phi = np.exp(-1. / (tau / dt))

    y = np.empty(N)
    y[0] = W[0]
    for i in range(1, N):
        y[i] = c + phi * y[i-1] + W[i]
    return y

tau = 100
for i, dN in enumerate([2, 4, 10, 40, 100]):
    dy = np.empty(10000)
    for i in range(10000):
        y = generate_AR(N=dN, tau=tau, dt=1)
        dy[i] = y[-1] - y[0]
    print('tau:', tau, 'steps:', (dN-1), 'variance:', np.var(dy))
</code>
Answer: Just using the following two facts:

$\operatorname{Var}(y_{i + K} - y_i) = \operatorname{Var}(y_{i + K}) + \operatorname{Var}(y_i) - 2\operatorname{Cov}(y_{i + k}, y_i) =
2\gamma(0) - 2\gamma(K)$, where $\gamma(h)$ is the autocovariance function of $\{y_t\}$.
For an AR(1) process with white noise variance $\sigma^2$, its autocovariance function is given by:
\begin{align}
\gamma(h) = \frac{\sigma^2\phi^h}{1 - \phi^2}.
\end{align}

In your case, $\sigma = 1$, hence $\operatorname{Var}(y_{i + K} - y_i) =
2\gamma(0) - 2\gamma(K) = \frac{2(1 - \phi^K)}{1 - \phi^2}$.
Answer: By repeated substitution, we obtain
$$
y_{i+K} = \phi y_{i+K-1} + \epsilon_{i+K} =  \phi^2 y_{i+K-2} + \phi \epsilon_{i+K-1} + \epsilon_{i+K} = \ldots
= \phi^K y_i + \sum_{j=0}^{K-1} \phi^j \epsilon_{i+K-j}
$$
We thus have
$$
\mathrm{Var}(y_{i+K}-y_i) = \mathrm{Var}\left((\phi^K -1) y_i + \sum_{j=0}^{K-1} \phi^j \epsilon_{i+K-j}\right)
$$
We know that $\mathrm{Var}(y_i)=\sigma^2$, $\mathrm{Var}(\epsilon_{i+K-j})=1$ for all $j$, and also that $y_i$ is uncorrelated with $\epsilon_{i+1},\ldots,\epsilon_{i+K}$. Putting everything together gives
$$
\mathrm{Var}(y_{i+K}-y_i) = (1-\phi^K)^2 \sigma^2 + \sum_{j=0}^{K-1} \phi^{2j} = (1-\phi^K)^2 \sigma^2 + \frac{1-\phi^{2K}}{1-\phi^2}
$$


Why does accessing an indexed item on an object work without noImplicitAny?

Question: Why does this code compile?
interface RotationDirection {
    polarity: number,
}

const d: RotationDirection = {
    polarity: 1,
}

console.log(d[0]);

If I add --noImplicitAny, it fails with PipeGenerator.ts:9:13 - error TS7053: Element implicitly has an 'any' type because expression of type '0' can't be used to index type '{ polarity: number; }'.
  Property '0' does not exist on type '{ polarity: number; }'.
I don't know how this could possibly be inferred to any. d clearly does not have a property 0, nor does the interface.
Comment: object fields work like an array, so you can iterate them or use with an indexer
Comment: Is that to say index expressions suppress property checking?
Answer: Historically it looks like bracket access was a "back door" to allow arbitrary property indexing when the compiler doesn't know if a property exists or not; see microsoft/TypeScript#7660 and microsoft/TypeScript#7733.
Note that in both dotted and bracketed access, the compiler infers that the type of the unknown property is any:
const any = d.notPresent; // unknown property error
// const any: any;
const alsoAny = d["notPresent"]; // implicitly any error
// const alsoAny: any;

That might be surprising.  The issue is that just because a property is not declared on an object type, it doesn't mean that the property is definitely absent; it just means that the compiler does not know about it, and it could be anything if it is present.  Another way of saying this is that object types in TypeScript are not exact.  In this case, an object of type RotationDirection may actually have a property with key "0":
const weirdDirection = {
    polarity: 100,
    "0": true
};

const cloakedWeirdness: RotationDirection = weirdDirection; // no error

So the compiler decides that the type of such undeclared properties is any.

As time goes on this back door access via brackets is less of an issue.  It is recommended that one enable the --strict flag to get the maximum type safety from the compiler.  And since --strict includes --noImplicitAny, you should get an error for both ways of accessing unknown properties (although the exact error message will differ, of course).
Okay, hope that helps.  Good luck!
Playground link to code


azure .vhd image capture/load

Question: I want to do the following:

In Azure, US East, capture current windows VM image (I know how to do that)
download .vhd image (I know how to do that)
Now, I want to load (that image I downloaded) in second(separate) Azure account in US West, how do I do that?

Can someone can help me out, thank you.
Comment: Off-Topic. SO is about programming questions, in a rather narrow sense. This question belongs to http://www.serverfault.com
Answer:
Create a storage in US West
Use Azcopy to copy the VHD image from US East Storage to US West Storage
Create a Virtual Machine using that copied VHD (may need to use powershell)

Getting Started with the AzCopy Command-Line Utility:
http://azure.microsoft.com/en-in/documentation/articles/storage-use-azcopy/
Comment: Hey Bruno, can you give me an actual command syntax? since in that AzCopy link there is way too much information. Thanks.
Answer: Also important make sure you generalize your VM using sysprep otherwise your VM will not be accessible on restart.  Been down that road.  There are ways to get it back but not fun.  So pause before you click that "capture" button. If you do on restart it will fail due to "vm has been generalized". Generalization essentially removes all your personal information as well as other things...
https://technet.microsoft.com/library/bb457073.aspx
https://learn.microsoft.com/en-us/azure/virtual-machines/windows/capture-image-resource
https://blogs.technet.microsoft.com/shwetanayak/2017/03/19/captured-the-virtual-machine-didnt-intend-to-generalize-it-now-what/

azure .vhd image capture/load


What is the difference between msExchangeHideFromAddressBook and msExchHideFromAddressLists?

Question: I'm trying to set up up AD attributes for some groups to hide them from the OCS/MOC address book. According to this article:
http://technet.microsoft.com/en-us/library/ee323528(office.13).aspx
There should be two attributes that control this visibility: msExchangeHideFromAddressBook and msExchHideFromAddressLists.
What are the differences between these attributes?
Answer: The Technet article is faulty, only the msExchHideFromAddressLists attribute exists in practice.


Is this function uniformly continuous on the given set?

Question: Let $S = [0,1]\times [0,1].$ For $(x,y) \in S,$ define $f(x,y) = x^2 + 3y.$ The problem is to show $f$ is uniformly continuous on $S.$
Let $s > 0$. Suppose $(x,y),(x_0,y_0) \in S$ and $\lvert x - x_0 \rvert < s, \lvert y - y_0 \rvert < s.$ Then
$$\begin{align}
  |f(x,y) - f(x_0,y_0)|
  &\leq \lvert x - x_0\rvert \lvert x + x_0\rvert + 3\lvert y - y_0\rvert \\
  &\leq (4 + 2\lvert x_0\rvert)s.
\end{align}$$
Let $e$ be epsilon in which I'm trying to create a neighbourhood around $f(x,y) - f(x_0,y_0) $ such that $f(x,y)$ is continuous. I know that since I found a variation or an upper bound for $f(x,y)$ in regards of $x_0$ and $s$ let me find epsilon $e$ by
\begin{align}
  4 + 2 \lvert x_0\rvert s \leq e,
\end{align}
so I end up with
\begin{align}
  s < \frac{e}{4 + 2\lvert x_0\rvert},
\end{align}
in which $s$ is dependent on both $e$ and $x_0$. It seems like it is not uniformly convergent, however I can choose a very very small $s$ so that it is satisfied for all $x_0$ (since as $x_0$ increases $s$ decreases from the equation obtained) Can we say that $f$ is uniformly continuous in this case?
Comment: Since $f$ is continuous and $S$ is compact, then we can show that $f$ is uniformly continuous on $S$. Alternatively, you could show that the derivative is bounded and use the mean value theorem.
Comment: The question is sloppily written. I still don't know which of the two $f$s you intend.
Comment: The first sentence makes no sense, which expression defines $f$?
Comment: Fixed sorry about that
Comment: It still makes no sense. Read the comment.
Comment: But can you please comment on my way of thinking instead.
Comment: Please, use $\epsilon,$ not $e.$
Comment: I edited the first part of your question. Feel free to keep it as it was if you want. I am just suggesting a simpler clearer way to start, but this is a matter of opinion.
Answer: You're definitely on the right track. But when you write
$$\begin{align}
  f(x,y) - f(x_0,y_0)
  &\leq \lvert x - x_0\rvert \lvert x + x_0\rvert + 3\lvert y - y_0\rvert \\
  &\leq (4 + 2\lvert x_0\rvert)s.
\end{align}$$
it's a little strange. First, you need absolute values on the left. We then have
$$ |f(x,y) - f(x_0,y_0)| \le |x+x_0||x-x_0|+ 3|y-y_0| \le (|x+x_0| + 3)s.$$
For some reason you must be thinking $|x+x_0|\le 1 + 2|x_0|.$ This is true, but weird. Why not just use $|x+x_0| \le 1 + 1 = 2?$ Then we get $|f(x,y) - f(x_0,y_0)| \le 5s.$ You're then ready to go. Let $\epsilon>0.$ Choose $s<\epsilon/5.$ With this $s$ you'll get $|f(x,y) - f(x_0,y_0)| < \epsilon$ as desired.
Your question needs some rewriting. You seem to have ignored @copper.hat's comment. When you do that, people get a bit frustrated and sometimes move on.
Answer: since $x\le1$
$$s<\frac e 6\le\frac{e}{4+2|x_0|}$$
So s doesn't really depend on $x_0$, meaning $f$ is uniformly continuous


Mobile Redirect from specific page / QR Code

Question: My client has created a QR Code that goes to a specific page on her non-mobile site.
She does have a mobile site, m.customersdomain.com
Question is, the QR Code has already been submitted to print for advertising and is going to a regular URL like:
http://www.customerdomain.com/specificpage
Is there a way to look for mobile devices that hit this one non-mobile page and redirect them to a mobile URL / page with the same content?
Answer: You must add some code to your customer's server in order to detect whether the hit comes from a mobile device and redirect accordingly.
Here you can get examples of how to make that detection on several programming languages:
http://detectmobilebrowsers.com/
Comment: Jorge,

Have this so far for JS:

if ((screen.width <= 700) &&
currentpage("http://customersite.com/gotopage")) {
 window.location = "http://m.customersite.com/gotopage";
 }

I just need to figure out how to look @ the current URL, and if it is in fact http://customersite.com/gotopage, then send them via window.location to http://m.customersite.com/gotopage
Comment: All,

This may do it:

if ((screen.width <= 700) &&
location.href("regularURL")) {
window.location = "mobileurl";
}

...maybe???

Any better way?

Thanks!


How to add ocx control which not supports wpf in wpf window?

Question: I'm new to wpf!
I want to add ocx control in wpf window. Is it possible?
The control I'm using does not support wpf.
Answer: This might help you!
Step by step guid to host ActiveX control in WPF.
https://msdn.microsoft.com/en-us/library/ms742735(v=vs.110).aspx


Angular Type '{ domain: string[]; }' is not assignable to type 'string | Color'

Question: I am using ngx-charts with Angular 12 and I'm getting this error message then I use this:
colorScheme = {
  domain: ['#5AA454', '#A10A28', '#C7B42C', '#AAAAAA']
};

The error message is:
Type '{ domain: string[]; }' is not assignable to type 'string | Color'.

How can I fix this?
Answer: ngx-charts version 19 or above accepts only types string or Color (from here), and to expand on another answer:

String examples include "cool", "natural", "vivid", etc from the preset color schemes in this file.
Color example to set your own custom scheme:

import { Color, ScaleType } from '@swimlane/ngx-charts';
export class foo {
  colorScheme: Color = {
    name: 'myScheme',
    selectable: true,
    group: ScaleType.Ordinal,
    domain: ['#f00', '#0f0', '#0ff'],
  };
}

<ngx-charts-area-chart
 ...
 [scheme]="colorScheme"
></ngx-charts-area-chart>

Comment: this is better solutoin, agrees?+1
Answer: Use the ngx-charts version 18 or below.
The scheme type [scheme]="colorScheme", is asking for a string but the type you are providing is an object.
The latest version 19 or above as scheme type is of string | color.
Comment: The code I provided I got from their own demos ...strange :( By string...do you mean an array of strings? Because I need to add multiple hex codes
Comment: String as in single string not an array. Before string was of type any so there was not any problem. But now it is declare as of type string | color.
Comment: please can you elaborate more on that I'm facing the same issue, with ngx-charts. how did you assign to it? when I just pass the string the chart doesn't load
Answer: This will work
import { Color, ScaleType } from '@swimlane/ngx-charts';

colorScheme: Color = {
    domain: ['#99CCE5', '#FF7F7F'],
    group: ScaleType.Ordinal,
    selectable: true,
    name: 'Customer Usage',
};

Github: Typing of Color is incorrect


Warning: Invalid argument supplied for foreach() in form_select_options() (line 2837 of includes/form.inc)

Question: I get the following erros on selecting the selectbox.
Here onchang of this field will populate another checkbox with city details id zipcode using ajax callback.
<code> $zipcode_options = get_all_zipcodes_ascending();

  // Populate Ort on auktion clone.
  $selected = isset($auktion->zip_code) ? $auktion->zip_code : NULL;
  $selected = isset($form_state['values']['zip_code']) ? $form_state['values']['zip_code'] : $selected;
  $ort_options = _ajax_city_dropdown_options($selected);

  $form['zip_code'] = [
    '#type' => 'select',
    '#title' => t('PLZ'),
    '#options' => $zipcode_options,
    '#default_value' => isset($auktion->zip_code) ? $auktion->zip_code : "",
    '#select2' => ['width' => '100%', 'placeholder' => t('Enter a zipcode'), 'allowClear' => TRUE],
    '#empty_option' => '',
    '#validated' => TRUE,
    '#required' => TRUE,
    '#ajax' => array(
      'event' => 'change',
      'callback' => 'ajax_example_dependent_dropdown_callback',
      'wrapper' => 'dropdown-second-replace',
    ),
  ];
</code>
Referenced many links but cannot find a solution to resolve this issue.
References:
https://www.drupal.org/node/586576
populate drop down from results using ajax
http://techqa.info/drupal/question/203725/help-understand/solve-this-warning:-invalid-argument-supplied-for-foreach%28%29-in-views-that-requires-class-registry-clean-to-mend
Answer: Looking on the code i suspect  that error lies in these lines-
<code>$selected = isset($auktion->zip_code) ? $auktion->zip_code : NULL;
 $selected = isset($form_state['values']['zip_code']) ? $form_state['values']['zip_code'] : $selected;
$ort_options = _ajax_city_dropdown_options($selected);</code>
And according to my understanding adding these lines will fix this warning-
<code> $selected = isset($auktion->zip_code) ? $auktion->zip_code : NULL;
$selected = isset($form_state['values']['zip_code']) ? $form_state['values']['zip_code'] : $selected;
$ort_options = _ajax_city_dropdown_options($selected);
if(!is_array($ort_options)){
    $ort_options=array();
}
</code>
Assuming that _ajax_city_dropdown_options($selected); returns options for second select list/ Check Boxes there can be some options in first Select List or there is none selected in first list for which there is no values available for second list. So returning an empty array will address this situation and prevent this error form appearing.


Windows 2003 guest customization in vmware

Question: I would like to use the "run once" feature in VMware's guest customization scripts to run an interactive script to further customize the guest OS (ie SNMP community, DNS suffix, add local user/pass). It must be an interactive prompt because the values can be different per VM. I am not joining these to a domain.
Has anyone tried this before or have a good resource for customizing W2k3 via script?
Answer: I do this on my Windows 2003 and 2008 guests.  Put the script in the c:\windows\system32\ folder on the template.  Within the customization settings you can add a onetime script to be run.  You'll also need to tell the system to automatically login once so that the script runs.
The last line of my script has a reboot command to reboot the guest after the script is complete.
(I'm assuming that you are using ESX for this.)
Comment: Do you have a good resource or examples of a script?
Comment: I'm just using a batch file to do what I need to.  In my case I'm running a vbs script using cscript to change the drive letter.  (I downloaded it from the net, not sure from where, I'll post it if you'd like.)  Then I force a reboot using shudown.exe with the /r /t 10 /c "rebooting" /d P:1:1 switches.

For adding users you can all NET USER, DNS changes should be able to be made using sh.  I'm not sure about SNMP settings.  Probably just load a registry file using regedit with the /q switch.