Minimizing numbers along diagonal

Question: Please forgive my ignorance if this isn't the appropriate place to ask this question, I'm by no means an expert in statistics.
I'll omit most of the esoteric linguistic details here, but I've run up against a roadblock using Excel, where I am trying to minimize the values along the diagonal, (top left to bottom right.) I would prefer smallest numbers to be near the diagonal, and larger numbers to be farthest away from it.
There are only two constraints;
(1) Individual cells may not move, only rows and columns; i.e. the relationship between all values along the a row or column must be maintained with any move.
(2) For every shift in a row there has to be a symmetric movement in columns. e.g. if row 3 is moved down three, column C must be moved right by three as well.
I'm open to using any kind of software and reformatting my data in any way, I'll post some photos below to give some clues as to what kind of operations I am hoping to perform. It is possible that the minum values are already closest to the diagonal in the second photo, but I want to be able to statistically prove that the numbers cannot be any lower.
Thanks in advance

The first graph is a screenshot of the raw data; it shows the similarity (lower numbers are more similar) between letters in the pre-classical Arabic language. The data is in alphabetical order, but for my purpose this order is arbitrary.

The second is my attempt at organizing based on some educated guesses at how the phonology could have been; in this design the letters that are closest to each other are more similar to each other, and thus have lower numbers.
Comment: There are some algorithms discussed [here](http://webhome.weizmann.ac.il/home/fedomany/Bioinfo05/lecture4.pdf) that may be of some use to you.
Answer: Your second example looks to me like you did a pretty good job (so I wouldn't expect to improve upon it much). Your constraint 1 is pretty typically, but I've never seen constraint 2 before, so you may need a novel solution. See the references for some examples of ordering tables, it may be possible to estimate the hierarchical clustering solutions for the rows and columns and then cut the dendrogram in an arbitrary way to suit your needs. (Or there may be other heuristic solutions based on PCA that will work for your example.) Although those don't focus specifically on the diagonal.
A simple technique is to order by row and/or column sums, so just see for your example if there are any rows/columns that stick out. That is easy enough to do in excel ;)
Also I would avoid the red-green color scale. Stephen Few has some applicable suggestions here. With only 5 values you may ditch the numbers all together and use a sequential color ramp.
References

Pilhofer, Alexander, Alexander Gribov, Antony Unwin (2012) Comparing clustering using Bertin's idea. IEEE Transactions on Visualization and Computer Graphics 18(12):2506-2515. PDF here.
Wilkinson, Leland and Michael Friendly (2009). The history of the cluster heat map. The American Statistician 63(2): 179-184. Pre-print PDF here.
Comment: (+1) Constraints (1) and (2) together merely ask for a permutation of the letters.  An *ordering* is sought which places groups of similar letters near each other. Thus, you certainly *have* seen this situation before: it can be considered a clustering problem or a one-dimensional MDS.
Comment: Sorry did not mean to make it too complicated @CayetanoGonçalves. Learning a stats package is generally helpful. Checking the row and column sums is easy in Excel, every other suggestion would likely be annoying in Excel although probably possible with a little elbow grease. Whuber's suggestion just takes changing the data from a contingency table to a set of pairs, e.g. `46,88` in one row, `84,86` in the next etc.
Comment: Ah yes - good call @whuber. Makes evaluating the potential permutations and defining the "best" solution (however you want to define best) a much simpler task!
Comment: Thanks for the information, I am trying to digest it. Would you two recommend sticking with Excel, or is there some sort of software package that would be easier?

Minimizing numbers along diagonal


setting up cake on hostgator

Question: So i have been reading forum after forum and my bakery is still not functional.
Here is my folder tree:
/home/jja/public_html/
there i have: app, cake, index.php and one .htaccess that looks like:

RewriteEngine on
RewriteBase /
RewriteRule    ^$ app/webroot/    [L]
RewriteRule    (.*) app/webroot/$1 [L]

I get no log errors and a 404 Error.
Answer: This article might help you
Installing CakePHP on shared hosting
I am also hosting my website on hostgator without any problems.
Dont keep your app and cake folders in public_html folder.
Move the app and cake folder to the main root i.e /home/username
Move all the folders inside the webroot to public_html
Your folder structure should look like this:
<code>/home/username
  /app
  /cake
  /public_html
      /css
      /img
      /js
      index.php
</code>
You will also have to make changes to the index.php file found in the webroot. This has been explained in the above mentioned link.

setting up cake on hostgator


Finding the minimal polynomial of $w+w^{-1}$ with $w$ is a primitive nth root of unity

Question: Let $w$ be primitive nth root of unity over $\mathbb{Q}$. Find the minimal polynomial of $w+w^{-1}$ over $\mathbb{Q}$
Comment: Note that $w+w^{-1} = 2 \cos(2\pi/n)$. A minimal polynomial can be recursively found using trigonometric identities: $1=\cos(2\pi) = \cos(n \cdot 2\pi/n) = \dotsc$
Answer: What happens here is similar to what happens with the polynomial $M_w$
of $w$ : there is no general formula, the answers depends on the prime
factorization of $n$ (for example, its degree is $\phi(n)$). In general, we only know
that $M_w$ divides $X^{n-1}+X^{n-2}+\ldots +1$, and $M_w$ coincides with
this polynomial when $n$ is prime.
Similarly, if $n$ is odd say $n=2m+1$, we may define
$$
T_m=\Bigg(\sum_{j=0}^{\lfloor \frac{m}{2} \rfloor}
\binom{m-j}{j} (-1)^j x^{m-2j}\Bigg) +
\Bigg(\sum_{j=0}^{\lfloor \frac{m-1}{2} \rfloor}
\binom{m-1-j}{j} (-1)^j x^{m-1-2j}\Bigg) \tag{1}
$$
Then, we have the algebraic identity
$$
T_m\bigg(w+\frac{1}{w}\bigg)=\frac{1}{w^m}\sum_{i=0}^{2m} w^i \tag{2}
$$
which shows that $T_m$ annihilates $v=w+\frac{1}{w}$, so the minimal
polynomial $M_v$ of $v$ divides $T_m$. When $n$ is an odd
prime we have $M_v=T_m$.
Comment: @LeVanTu This degree is $\frac{\phi(n)}{2}$ since the degree $[{\mathbb Q}(w):{\mathbb Q}(v)]$ is equal to $2$ ; indeed $w$ satisfies $w^2-vw+1=0$
Comment: furthermore, how can i calculate the degree of following extension [$\mathbb{Q}(w+w^{-1}):\mathbb{Q}$]
Comment: thank you.But i wonder how can you determine polynomial  $T_m$?
Answer: The minimum polynomial satisfied by $w$ is palindromic. Making the substitution $z=w+w^{-1}$ is a standard method of treating such polynomials, since it divides the degree of the polynomial by half. Look up palindromic polynomials.


How to create a dev environment with FireStore & Cloud functions

Question: I've been using FireStore together with Cloud functions extensively and so far everything has been great.
As my Swift app nears production launch, I would like to build a separate dev environment. Based on the documentation I was able to:

Create two separate projects
Link these two projects to my 2 targets using the various GoogleService p-list
I was also able to declare 2 service accounts for my Firebase Function environments and create two separate aliases.

It all seemed to work, except that my new Dev Cloud Function environment is not fully linked with my Dev FireStore DB but appears instead still linked to my initial FireStore DB instance - the cloud function is correctly triggered when I write something on it, but all the data retrieval function return empty (as if the .get() commands where targeting my "old" prod DB).
Could you let me know how I can "force" my Dev Cloud Functions environment to link with my Dev FireStore DB instance? I must have missed a step - for ex., I didn't re-initialize the CLI/ re-logged-in, etc. but only created a 2nd alias.
I am also getting this message: "Billing account not configured. External network is not accessible and quotas are severely limited. Configure billing account to remove these restrictions". It's weird as I am not using an external account (it's Firestore/ Cloud Functions/ FCM only).
Any documentation/ step-by-step guide you can point to would be super helpful!
Here is how I initialize my 2 apps:
const functions = require('firebase-functions');

const admin = require('firebase-admin');

var serviceAccount = require("./adminKey.json");
var serviceAccountDev = require("./adminKey-dev.json");

var secondEnvironment = admin.initializeApp({
  credential: admin.credential.cert(serviceAccountDev),
  databaseURL: "https://<app name>-dev.firebaseio.com"
}, 'dev instance');

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "https://<app name>.firebaseio.com"
});

var db = admin.firestore();

Thanks again,
Francois
Answer: Update based on the comments below and the update to your post with the part of the Cloud Function code where you initialize the App:
By doing the following:
var secondEnvironment = admin.initializeApp({
  credential: admin.credential.cert(serviceAccountDev),
  databaseURL: "https://<app name>-dev.firebaseio.com"
}, 'dev instance');

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "https://<app name>.firebaseio.com"
});

you are initializing the App with the Prod environment parameters for the two environments.
You should do as explained at the bottom of this documentation item: https://firebase.google.com/docs/functions/config-env#automatically_populated_environment_variables
which is:

If you need to initialize the Admin SDK with the default project configuration using service account credentials, you can load the credentials from a file and add them to FIREBASE_CONFIG like this:
serviceAccount = require('./serviceAccount.json');
const adminConfig = JSON.parse(process.env.FIREBASE_CONFIG);
adminConfig.credential = admin.credential.cert(serviceAccount);
admin.initializeApp(adminConfig);

process.env.FIREBASE_CONFIG is an environment variable that is automatically populated in the function runtime.

(Initial answer, not fully relevant to your exact problem anymore...)
If I understand well, you just have to use the use command, in the CLI, to switch to the target Project for which you want to deploy your Cloud Function(s). This is in case the user you are logged in with is managing the two projects (dev and prod).
In case two different users manage the two projects, you have to use the logout command followed by a login command in order to login with the correct user (and possibly subsequently use the use command if the user manages several projects).
See the documentation here: https://firebase.google.com/docs/cli/#administrative_commands
Comment: Thanks Renaud! Yes that's what I did - I basically use the use command to decide in which environment to deploy my code. This works fine, however my cloud functions in my new Dev environment are not being triggered by my Dev Firestore DB...
Comment: @Franc Do you see anything in the Cloud Functions log of the Dev env?
Comment: Sorry for the delay in getting back, I tried to test things deeper. The cloud function get correctly triggered, where it fails is in reading value on my firestore DB when I ask it (e.g., using the .get()). The code is the same as on my prod environment so I know it's not a coding issue. It also gives me this weird message: "Billing account not configured. External network is not accessible and quotas are severely limited. Configure billing account to remove these restrictions". Any clue what that could be?
I'll edit my original post to reflect what I found.
Comment: The billing message is normally when your function needs to contact an external service (but you explained that you are just using internal services....). Do you initialize (admin.initializeApp()) with specific options? Maybe if you add your Function code to your post one would be able to find a reason....
Comment: Thanks Renaud! Yes, at closer inspection I feel like I must do something wrong when initializing my two apps. I think what I am missing is a flag to let cloud function know which of my two environment it should initialize based on which alias I am using. I added my initialization code above. Would be great if you could help me with a quick review... Thanks a ton!


Prove the approximation of the identity function on $\mathbb{\bar{R}}_+$ by an increasing sequence of simple functions.

Question:
For each $n$ in $\mathbb{N}^*$, let  $$d_n(r) = \sum_{k=1}^{n2^n}
 \frac{k-1}{2^n} 1_{[\frac{k-1}{2^n}, \frac{k}{2^n})} (r)+ n 1_{[n,
 \infty]}(r), r\in \mathbb{\bar{R}}_+,$$
Then, each $d_n$ is an increasing right-continuous simple function on
  $\mathbb{\bar{R}}_+$ and $d_n(r)$ increases to $r$ for each $r$ in
  $\mathbb{\bar{R}}_+$ as $n \rightarrow \infty$.

This is given as an lemma in my textbook without proof. It doesn't look obvious to me at all. Even understanding the function itself is hard for me.
Can someone kindly explain to me the function, how to interpret and understand it and prove the lemma?
It seems to be that $1_{[\frac{k-1}{2^n}, \frac{k}{2^n})}(r)$ is satisfied only when $k = n2^n$ which is the last case of the summation. Why do we need the summation then, instead of taking the last term only?
Answer: In terms of the greatest integer $[x]$ not exceeding $x$ you can write $d_n (r)=\frac {[2^{n}r]} {2^{n}}$ if $r \leq n$ and $d_n(r)=n$ if $r>n$.  Proof of the fact that $\frac {[2^{n} x]} {2^{n}} $ increases to $x$ as $ n$ increases to $\infty $ for every $x\geq 0$: we have $x-\frac 1 {2^{n}} =\frac {2^{n} x-1} {2^{n}} <\frac {[2^{n} x]} {2^{n}} \leq \frac {2^{n} x} {2^{n}}=x $. By the Squeeze Theorem $\frac {[2^{n} x]} {2^{n}}  \to x$. Next we prove that $2[y] \leq [2y]$ for all $y \geq 0$: if $n \leq y <n+1$ then $2n \leq 2y <2n+2$ so either $2n \leq 2y <2n+1$  or $2n+ \leq 2y <2n+2$. Hence $[y]=n$ and $[2y] =2n$ or $[2y]=2n+1$. It follows that $[2y] \geq 2n =2[y]$ in both cases. Taking $y=2^{n}x$ we get $\frac {[2^{n} x]} {2^{n}} \leq \frac {[2^{n+1} x]} {2^{n+1}} $. This completes the proof.
Comment: It is interesting to note that $\frac {[nr]} {n}$ is not increasing in $n$ for $r \geq 0$ but it becomes increasing if you restrict $n$ to powers of 2.
Comment: I don't quite understand how this helps
Comment: @user136266 I hope you can understand the proof now. I will be happy to help if you need some clarification.
Answer: The idea behind this is that you split the interval $[0,n)$ into $2^n$ equally sized intervals and on each interval you set the value equal to the value at the left point and on the interval $[n, \infty)$ you have to set $n$ (I think you have a typo)
Letting $n \rightarrow \infty$ the partition gets smaller and smaller and you can see that the function $d_n(r)$ increases to $r$ simply because the mesh of the partition converges to $0$.
Right continuity follows from the fact that we are using $[,)$ type of intervals for the approximation.
Comment: I am not understanding you. I am not seeing the link between the equation and what you say. Which part relates to what?
Comment: why $2^n$ and not any other number of intervals?
Comment: To add a bit to the answer regarding the question: the indicator function $1_A(x)$ equals $1$ if $x \in A$ and $0$ if $x \notin A$. So basically you split the the interval in $2^n$ parts and since you want to consider each part differently - you put an indicator function on it so that the disjoint intervals don't affect eachother. Finally, since you've split the interval, you want to sum up those indicator functions. $2^n$ suffices since we want the mesh to go to $0$ as $n \rightarrow \infty$, i.e. $\frac{n}{2^n}\rightarrow 0$ as $n \rightarrow \infty$


air coming out of nose when playing

Question: I've been playing the clarinet for 1 year. I used to have a problem with air coming out of my nose when playing.  It went away for a bunch of months and is now coming back a little.  If anyone has any advice I would appriciate it.
Thanks
Comment: Practice breathing exercises and air control, you might be blowing too hard if air is also coming out your nose.
Comment: You can practice and train to close the way that the air searches to pass through your nose by pressing and forming in your mouth a strong **nnggkkhh**
Comment: Do you have a teacher? Hard to see what is happening here. Do you have the feeling that you are blowing very hard? It should not be a big physical effort.
Answer: You're not alone!
I play the clarinet since I'm 7, and while being young, I was playing at least once or twice every week.
But during my studies, I was unable to play with my orchestra, and the more I could do was once avery 2 months.
After one year, while I was about 21, I started to have the same problem you describe.
At the beginning, it occurred at the end of rehearsals, when I was tired. I didn't pay attention.
But things became embarrassing when it occurred during a concert, while I was playing a solo.
At the end of my studies, I played again regularly, and the problem was there during the first rehearsals, but progressively went away.
So, I think this is a "muscle" that has to be trained to "close" correctly.
Also, try using easy-to-play mouthpiece and reeds, it can help, specially at the beginning.

air coming out of nose when playing


Calcular quantidade pelo número inteiro

Question: Eu tenho que inserir um registro no banco de dados de acordo com um número inteiro. Por exemplo, 20, 21, 22, 23...29 Eu pego o primeiro número (no caso 2) e insiro 2 registros. Se for 10, 11, 12, 13...19 (no caso 1) eu insiro 1 registro. 0,1,2,3,4...9 eu insiro nenhum...
Só preciso saber se é de 0 a 9, 10 a 11, 20 a 22 e assim por diante. De acordo qual número for eu pego o primeiro número. O problema de fazer por exemplo com substr é se o número for 100 então ele "pensará" que é valores entre 10 e 19.
Answer: Divida por 10, pegue a parte inteira, e utilize o resultado nas suas verificações. Por exemplo:
$dezenas = floor($num / 10);
if ($dezenas == 1) {

} else if ($dezenas == 2) {

} // etc.

Calcular quantidade pelo número inteiro


Proper javascript notation

Question: The following code creates navigation links for a Twitter Bootstrap carousel. The script runs perfectly when saved on my local machine as well as hosted as its own document. When placed into a Drupal page, however, the javascript is modified. I understand that Drupal requires a special Javascript structure. Is that the case with my code below? Any suggestions would be helpful. Thanks!
--- You can see how Drupal closes tags on Line 10
Original Code - working:
$(document).ready(function() {
    $('#headerCarousel.carousel[id]').each(function() {
        var html = '

';
        for(var i = 0; i != $(this).find('.item').size(); i ++) {
            html += '
'  + $(item).attr('data-title') + '
';
        }
        html += '

';
        $('.btn-navbar').after(html);
        $('.carousel-control.left[href="#' + $(this).attr('id') + '"]').hide();

    }).bind('slid', function(e) {
        var nav = $('.nav-collapse[data-target="' + $(this).attr('id') + '"] ul');
        var index = $(this).find('.item.active').index();
        var item = nav.find('li').get(index);
        nav.find('li.active').removeClass('active');
        $(item).addClass('active');

        if(index == 0) {
           $('.carousel-control.left[href="#' + $(this).attr('id') + '"]').fadeOut();
        } else {
           $('.carousel-control.left[href="#' + $(this).attr('id') + '"]').fadeIn();
        }
        if(index == nav.find('li').size() - 1) {
           $('.carousel-control.right[href="#' + $(this).attr('id') + '"]').fadeOut();
        } else {
           $('.carousel-control.right[href="#' + $(this).attr('id') + '"]').fadeIn();
        }
    });

   $('.bootstrap .nav a').bind('click', function(e) {
       var index = $(this).parent().index();
       var carousel = $('#' + $(this).closest('.nav-collapse').attr('data-target'));
       carousel.carousel(index);
       e.preventDefault();
   });
});

Generated code after placing in Drupal - broken:
$(document).ready(function() {
    $('#headerCarousel.carousel[id]').each(function() {
        var html = '

';
        for(var i = 0; i != $(this).find('.item').size(); i ++) {
            var item = $(this).find('.item').get(i);
            html += '
'  + $(item).attr('data-title') + '

';
        }
        $('.btn-navbar').after(html);
        $('.carousel-control.left[href="#' + $(this).attr('id') + '"]').hide();

    }).bind('slid', function(e) {
        var nav = $('.nav-collapse[data-target="' + $(this).attr('id') + '"] ul');
        var index = $(this).find('.item.active').index();
        var item = nav.find('li').get(index);
        nav.find('li.active').removeClass('active');
        $(item).addClass('active');

        if(index == 0) {
           $('.carousel-control.left[href="#' + $(this).attr('id') + '"]').fadeOut();
        } else {
           $('.carousel-control.left[href="#' + $(this).attr('id') + '"]').fadeIn();
        }
        if(index == nav.find('li').size() - 1) {
           $('.carousel-control.right[href="#' + $(this).attr('id') + '"]').fadeOut();
        } else {
           $('.carousel-control.right[href="#' + $(this).attr('id') + '"]').fadeIn();
        }
    });

   $('.bootstrap .nav a').bind('click', function(e) {
       var index = $(this).parent().index();
       var carousel = $('#' + $(this).closest('.nav-collapse').attr('data-target'));
       carousel.carousel(index);
       e.preventDefault();
   });
});

Comment: See https://coderwall.com/p/kd-4cg for guidance on how to write JavaScript code for Drupal.
Answer: Behavior handling has changed again in Drupal 7, with modules now required to explicitly define their attach handler, and optionally specify a detach handler. add code like this way.
(function ($) {

  Drupal.behaviors.exampleModule = {
    attach: function (context, settings) {
    $('#headerCarousel.carousel[id]').each(function() {
        var html = '

';
        for(var i = 0; i != $(this).find('.item').size(); i ++) {
            var item = $(this).find('.item').get(i);
            html += '
'  + $(item).attr('data-title') + '

';
        }
        $('.btn-navbar').after(html);
        $('.carousel-control.left[href="#' + $(this).attr('id') + '"]').hide();

    }).bind('slid', function(e) {
        var nav = $('.nav-collapse[data-target="' + $(this).attr('id') + '"] ul');
        var index = $(this).find('.item.active').index();
        var item = nav.find('li').get(index);
        nav.find('li.active').removeClass('active');
        $(item).addClass('active');

        if(index == 0) {
           $('.carousel-control.left[href="#' + $(this).attr('id') + '"]').fadeOut();
        } else {
           $('.carousel-control.left[href="#' + $(this).attr('id') + '"]').fadeIn();
        }
        if(index == nav.find('li').size() - 1) {
           $('.carousel-control.right[href="#' + $(this).attr('id') + '"]').fadeOut();
        } else {
           $('.carousel-control.right[href="#' + $(this).attr('id') + '"]').fadeIn();
        }
    });

   $('.bootstrap .nav a').bind('click', function(e) {
       var index = $(this).parent().index();
       var carousel = $('#' + $(this).closest('.nav-collapse').attr('data-target'));
       carousel.carousel(index);
       e.preventDefault();
   });

    }
  };

})(jQuery);

Comment: Thank you for your response! I actually do not know what version of Drupal I am working with since I only publish work and do not have access to the backend.. I tried implementing the code you suggested with no success. Last night, after a few more hours of researching, I realized that Drupal was automatically closing the tags in my string for var `html`. The developers of the CMS I'm using probably added in an HTML sanitizer like HTMLtidy. To work around this, I just hosted the javascript externally and linked to it in the HTML body and everything worked as it should.

Proper javascript notation


Python3 numpy.fft.fft() vs Python2 numpy.fft.fft()

Question: After running the following code on my MacBook Pro, I find that the python3 numpy.fft.fft is faster than python2:
import random
import time
# import matplotlib
import numpy as np
from scipy.fftpack import fft
# import cv2

coordinate = np.ndarray((1920, 1080, 2))
print(coordinate.shape)

for i in range(1920):
    for j in range(1080):
      coordinate[i][j] = (random.randint(0, 1920), random.randint(0, 1080))

print(coordinate[0][0])
# test = ([2.+4.j, 3.+3.j, 4.+4.j, 5.+3.j, 4.+2.j, 3.+1.j, 2.+2.j, 1.+3.j])
start_time = time.time();
res = np.fft.fft(coordinate)
end_time = time.time();
print("spend time: ", (end_time - start_time));

the result is:
% python2 ./test.py
(1920, 1080, 2)
[ 1022.   435.]
('spend time: ', 0.06316184997558594)
% python3 ./test.py
(1920, 1080, 2)
[1143.  678.]
spend time:  0.18218493461608887

The pythons' numpy version are both 1.19.1
Python2: 2.7.16
Python3: 3.7.3
Why the python2 is faster than the python3?
Answer: I modified your test a bit which I think changes the conclusion a bit. Here is the modified code:
import random
import time
# import matplotlib
import numpy as np
from scipy.fftpack import fft
# import cv2

np.random.seed(1234)

first = np.random.randint(0, 1920, (1920, 1080))
second = np.random.randint(0, 1080, (1920, 1080))

coordinate = np.dstack((first, second))
print(coordinate.shape)

print(coordinate[0][0])

start_time = time.time();
for i in range(100):
  res = np.fft.fft(coordinate)
end_time = time.time();
print("spend time: ", (end_time - start_time)/100);

First of all I let the ftt function run in a loop for 100 iterations to give a better average. Second I used the same seed for all tests, therefore the resulting array coordinate is the same for all tests.
The third change doesn't affect the test, it's only a faster way to create the coordinate array.
I let the test run several times using python2 and python3 (not on my machine, but I used repl.it) and my conclusion is that there isn't really much of a difference. On my end, testing with python3 more often than not was faster than python2.
Comment: I run your code on my Mac but it still has the issue. I try your code and my code on Alibaba Cloud Computing, and the python3 does run faster than python2.I think it's maybe the problem of python numpy on mac and I plan to post an issue on python github page. Thanks for your answer!
Answer: I had post this question on GitHub as an issue: https://github.com/numpy/numpy/issues/17130


NFL the playoff race tie breakers regarding common games record

Question: Based on the rankings explanation provided by CBS regarding the NFL playoff situation; CBS provides something regarding a common record:

Seattle is ahead of Detroit based on common games record (4-0 to the
  Lions' 2-2).

What is a common games record?
Comment: Teams in the same division play each other twice each season. One of the common games in this scenario are the Cardinals. If Seattle loses to Arizona next week they will have a 1-1 record versus the Cardinals, how does that figure into the equation?
Comment: @alamoot The Cardinals have everything to do with the question as the Seahawks and Lions have them as a common opponent and the question asks about common games. The Seahawks play the Cardinals twice this season as compared to once for the Lions.
Comment: WOOW I definitely didn't understand that question properly. My bad, you're right Cards are def a factor.
Comment: The question asking about the relationship between the Seahawks and the Lions has nothing to do with the Cardinals.
Answer: Common games in the NFL tie breaking rules are games that teams have with common opponents. For example, let's say that Team A and Team B are tied and are both in the running for a wildcard spot in the playoffs. Looking at each of their 16-game schedules, they have each played Teams C, D, E, and F at some point during the season. These are the common games. Team A beat teams C and D, but lost to E and F, for a common games record of 2-2. Team B beat D, but lost to C, E, and F, giving them a record of 1-3. Team A wins the tie breaker and goes into the playoffs, and team B is finished.
In order for this particular tie breaker to be enforced, there needs to be a minimum of 4 games with common opponents between the two teams. If they don't have at least 4 common games, this tie breaker gets skipped.
For this tiebreaker, what is compared is the percentage record. For example, let's say two teams in different divisions are tied for a wildcard spot. When looking at games against common opponents, one team has a record of 3-1, and the other team has a record of 3-2, having played one of the common teams twice. The 3-1 team would win the tiebreaker, having a better percentage.
Answer: http://www.nfl.com/standings/tiebreakingprocedures
common games would probably be their records against common opponents

packers
panthers
cardinals
giants

seahawks are 4-0 and lions are 3-1 vs the four teams they have both played.
Answer: "Best won-lost-tied percentage in common games, minimum of four."
See: http://www.nfl.com/standings/tiebreakingprocedures
The confusion often surrounds the term "common games, minimum of four." Does it mean 4 opponents or 4 games?
All games against opponents played by both the tied teams are taken into consideration. There need only be four such "common games," which can occur with less than four common opponents.


Mysql - PhpMyAdmin erro ao executar trigger

Question: Olá, quando tento executar a seguinte trigger, obtenho este erro:

#1064 - Você tem um erro de sintaxe no seu SQL próximo a linha 11

Segue a trigger:
CREATE TRIGGER atualizacao
after update ON cliente
FOR EACH ROW
BEGIN
    DECLARE VERX VARCHAR(10);
    SET VERX=(SELECT DESCRICAO FROM versao WHERE id=NEW.id_versao);
    if(OLD.id_versao<NEW.id_versao)then
    begin
        INSERT INTO tarefa (id_cliente,id_servico,dt_cadastro,dt_inicio,dt_final,hora_inicio,hora_final,situacao,descricao,solucao,prioridade,id_projeto,tipo) VALUES(NEW.id_cliente,10,now(),now(),now(),now(),now(),2,'Atualização',CONCAT('Sistema atualizado para versão ',VERX),1,1,0);
    end;
END$$

Gostaria de saber o que poderia ser...
Comment: Qual a linha 11? Seria a linha "END$$"?
Comment: Seu select não está faltando **JOIN** ? de onde vem o campo WHERE id=NEW.id_versao ?
Comment: @EdvaldoLucena o `NEW.id_versao` é o último id alterado, não precisa de join
Comment: @RicardoPontual isso mesmo, a linha 11 é a última
Comment: a última linha não seria `END;$$`?
Comment: @RicardoPontual já tentei, acontece a mesma coisa..
Comment: Acredito que ali ao invés de `end;` seja `end if;` já que você não fechou o `IF`
Comment: Na real acredito que ali antes do `INSERT` nem é necessário abrir um novo `begin`
Comment: @EvaldoRc sua trigger faz o quê? Você não detalhou o que ela faz.
Comment: Aham, fiz as alterações (removendo o begin e colocando end if) e funcionou, muito obrigado!!
Answer: O que está ocasionando o erro de fato é a ausência do DELIMITER$$ no início do código mas há também alguns outros erros na TRIGGER descrita.
Primeiro que você acabou não fechando o IF e também não há necessidade de abrir um segundo BEGIN antes do INSERT. Tente dessa forma:
DELIMITER$$
CREATE TRIGGER atualizacao
after update ON cliente
FOR EACH ROW
BEGIN
    DECLARE VERX VARCHAR(10);
    SET VERX=(SELECT DESCRICAO FROM versao WHERE id=NEW.id_versao);
    if(OLD.id_versao<NEW.id_versao)then
        INSERT INTO tarefa (id_cliente,id_servico,dt_cadastro,dt_inicio,dt_final,hora_inicio,hora_final,situacao,descricao,solucao,prioridade,id_projeto,tipo) VALUES(NEW.id_cliente,10,now(),now(),now(),now(),now(),2,'Atualização',CONCAT('Sistema atualizado para versão ',VERX),1,1,0);
    end if;
END$$

Comment: muito obrigado, realmente funcionou agora!!


Set cookie from CodeIgniter and get the value with javascript

Question: I'm trying to get some data from a cookie. I set the cookie with CodeIgniter and here is my code
$c = array('name' => 'total', 'value' => $total, 'path' => '/');
$this->input->set_cookie($c);

Then, I want to take the data with javascript. This is what i've tried
function getCookie(c_name) {
  var i,x,y,ARRcookies=document.cookie.split(";");
  for (i=0; i<ARRcookies.length; i++) {
    x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
    y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
    x=x.replace(/^\s+|\s+$/g,"");
    if (x==c_name) {
      return unescape(y);
    }
  }
}

console.log(getCookie('total'))

I got the function from here but it doesn't work to my code. Is there anyway to achieve this ?
Answer: There's nothing wrong with your javascript codes. Maybe it happens because the cookie is not yet set. You just have to add expire value to your cookie, set it to any number (in seconds) or 0 to set it to disable immediately.
$c = array('name' => 'total', 'value' => $total, 'path' => '/', 'expire' => 0);
$this->input->set_cookie($c);

Answer: To read the cookie you can use this
function readCookie(name) {
let nameEQ = encodeURIComponent(name) + '=';
let ca = document.cookie.split(';');
for (let i = 0; i < ca.length; i++) {
    let c = ca[i];
    while (c.charAt(0) === ' ')
        c = c.substring(1, c.length);
    if (c.indexOf(nameEQ) === 0)
        return decodeURIComponent(c.substring(nameEQ.length, c.length));
}
return null;

}
readCookie('total');

This has worked for me multiple times, Hope it works for you as well.
Comment: There is no error, the function is working properly for other cookie


Contradiction on an Inequality

Question: The problem on which I have a problem is this-

Let a, b, c be non-negative real numbers. Prove that $$ \sum_{cyc} {a^2-bc \over 2a^2+b^2+c^2} \ge 0 $$

While solving and after some resolution, we get $$ \sum_{cyc} {(a+b)^2 \over a^2+b^2+2c^2} \le 3 $$
And by C-S, we have,
$$ \sum_{cyc} {(a+b)^2 \over a^2+b^2+2c^2} \le \sum_{cyc} {2(a^2+b^2) \over a^2+b^2+2c^2} $$
It rests to prove that
$$ \sum_{cyc} {a^2+b^2 \over a^2+b^2+2c^2} \le {3 \over 2} $$
By cyclic substitutions of $x$ for $b^2+c^2$, we get,
$$ \sum_{cyc} {a^2+b^2 \over a^2+b^2+2c^2} = \sum_{cyc} {(a^2+b^2) \over (c^2+a^2)+(b^2+c^2)} = \sum_{cyc} {z \over x+y} \le {3 \over 2} $$
But by the Nesbitt's Inequality,
$$ \sum_{cyc} {z \over x+y} \ge {3 \over 2} !$$
Can anybody explain me where's the mistake and the correction?
Thanks!
Comment: Your original approach seems to loose too much i.e. the inequalities are not sharp enough
Answer: Your first step was not so strong, which gave a wrong inequality.
SOS helps here:
We need to prove that $$\sum_{cyc}\frac{(a-b)(a+c)-(c-a)(a+b)}{2a^2+b^2+c^2}\geq0$$ or
$$\sum_{cyc}(a-b)\left(\frac{a+c}{2a^2+b^2+c^2}-\frac{b+c}{2b^2+a^2+c^2}\right)\geq0$$ or
$$\sum_{cyc}(a-b)^2(c^2-(a+b)c+a^2-ab+b^2)(2c^2+a^2+b^2)\geq0,$$ which is true because $$c^2-(a+b)c+a^2-ab+b^2\geq c^2-(a+b)c+\frac{1}{4}(a+b)^2=\frac{1}{4}(2c-a-b)^2\geq0.$$
Comment: Is there an easier proof? And what is SOS?
Comment: @Book Of Flames I see also five ways to the proof. This way is an easiest. SOS it's Sum Of Squares method. How it works, you saw already.
Comment: Anyways I have an easier proof in my book. Thanks!
Comment: @Book Of Flames If you know a proof of this inequality, why do you ask the question?
Comment: I was thinking to get a for a way out through my approach. But I know that it is wrong, so I was asking for an improvement/correction. But Thanks a lot.
Answer: Another solution.
By your work we need to prove that:
$$\sum_{cyc}\frac{(a+b)^2}{a^2+b^2+2c^2}\leq3,$$ which is true by C-S:
$$\sum_{cyc}\frac{(a+b)^2}{a^2+b^2+2c^2}\leq\sum_{cyc}\left(\frac{a^2}{a^2+c^2}+\frac{b^2}{b^2+c^2}\right)=\sum_{cyc}\left(\frac{a^2}{a^2+c^2}+\frac{c^2}{c^2+a^2}\right)=3.$$

Contradiction on an Inequality


Not receiving broadcast from k9 email

Question: I am listening for the email received broadcast from k9 and I cannot seem to get it to work.
I have registered a receiver for the following:
com.fsck.k9.intent.action.EMAIL_RECEIVED

I'm wondering if I need to add a permission - I can't seem to receive this broadcast.
I know my receiver is working as I can receive broadcasts for SMS and the phone. Has anyone else used this that can maybe shed some light on the subject?
Here's my filter:
IntentFilter fltr = new IntentFilter();
fltr.addAction("android.provider.Telephony.SMS_RECEIVED");
fltr.addAction("com.fsck.k9.intent.action.EMAIL_RECEIVED");
fltr.addAction("android.intent.action.PHONE_STATE");
registerReceiver(mRcv, fltr);

In my BroadcastReceiver:
private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
private static final String EMAIL_RECEIVED = "com.fsck.k9.intent.action.EMAIL_RECEIVED";
private static final String CALL_RECEIVED = "android.intent.action.PHONE_STATE";

public void onReceive( Context context, Intent intent ) {
            Log.d(TAG, "Inside Broadcast Reciever");
            Log.d(TAG, "Action: " + intent.getAction());
            if(intent.getAction().equals(SMS_RECEIVED)) {
                StartAct("SMS Received", context);
            }else if(intent.getAction().equals(EMAIL_RECEIVED)){
                StartAct("Email received", context);
            }else if(intent.getAction().equals(CALL_RECEIVED)){
                if(intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(TelephonyManager.EXTRA_STATE_RINGING))
                    StartAct("Incoming Phone Call", context);
            }

        }

Comment: Do you need permission? I've not done K9 receivers, but I know for the SMS and phone you need permission, does the K9 say anything about needing to declare a permission?
Comment: I'm not sure about the permissions - that is what I would like to find out. I'm not sure where to look to see if it is needed. The wiki page about the broadcast intent doesn't state anything about permissions.
Answer: I have it working - finally....
You have to add a data scheme to the intent filter. This will allow you to receive the broadcast. BUT it will break the other actions that I had in the filter, so I had to break them into separate receivers - one for SMS and phone and another for the k9 email broadcast.
Here's the one for k9 email:
IntentFilter fltr = new IntentFilter();
fltr.addAction("com.fsck.k9.intent.action.EMAIL_RECEIVED");
fltr.addDataScheme("email"); //This is needed to even receive the broadcast
registerReceiver(mRcv, fltr);

Answer: Try looking at the actual K9 source code. The AndroidManifest shows several Permissions that they have. Try compiling your program with it hooked up to eclipse and check LogCat, it'll usually show in it's error section if there is a missing permission. I only see 4 declared permissions that they have created, so READ_MESSAGE would be my guess, but check the logcat and see what it says.
Unfortunately it looks like their documentation is lacking quite a bit, which is a damn shame.

Not receiving broadcast from k9 email


Wp Rest Api Custom End point

Question: Im trying to add a custom end point to my wp-rest api the latest version. I have this already but the one with the slug param at the end does not work.. Does any one know why.. would be great if anyone could help..
     register_rest_route( 'wp/v2', '/guestmix', array(
        array(
            'methods'         => WP_REST_Server::READABLE,
            'callback'        => array( $this, 'get_guestmixes' )
        ),
        'schema' => array( $this, 'get_public_item_schema' )
    ) );

    register_rest_route( 'wp/v2', '/guestmix/(?P<slug>\d+)', array(
        'methods' => 'GET',
        'callback' => 'get_guestmix'
    ) );

Answer: i guess it because you used d metacharacter for regex (?P<slug>\d+) that's mean for digit, please try use S instead.
The code should look like this
register_rest_route( 'wp/v2', '/guestmix/(?P<slug>\S+)', array(
    'methods' => 'GET',
    'callback' => 'get_guestmix'
) );

this is cheat sheet for reference http://www.phpliveregex.com/
Comment: If only Wordpress documentation cared to explain which metacharacters we can use.
Comment: I have been looking for  cheat sheet for WP rest routes for some time now and by chance came across this page (it may be because I used edge to sear h instead of chrome) but finally I have  chance at finding the solution to my url regex, I hate regex enough (despite the 'wow thats impressive' thoughts I get now and then)  my problem was that my url needed to be url encoded and had 19 sections - yes I know...
Answer: The above answer works for me, though I implemented the regular expression slightly differently, following a 2019 gist, that covers different url/slug-structure scenarios.
register_rest_route( 'wp/v2', '/guestmix/(?P<slug>[a-zA-Z0-9-]+)', array(
    'methods' => 'GET',
    'callback' => 'get_guestmix'
) );

Hope this helps

Wp Rest Api Custom End point


Using measurement errors in cross validation to test error hypothesis?

Question: A response $y$ has been measured using 25 electronic devices.
For 8 of them, the response was heavily flawed. It was usually equal to a third of the response measured from the other devices.
So, I removed them and did my main analysis. I then thought, could I use the data from the other 8 responses (i.e., the covariates), and use them to predict new data, and then I would take a third of that data, and compare with the responses from the 8 devices I actually got?
If that's a good fit, then that would seem to confirm the hypothesis that the 8 devices give responses equal to a third of the "actual" response (assuming our model is correct)?
Is this a good idea?
Answer: In order to find a sensible answer to your question, "is it a good idea?", I would want to know what we are talking about. Imagine your $y$ is the result of function that is carried out, defined by a number of characteristics. The answer to "what is $y$?", is therefore not only defined by the attribute it is supposed to represent, but also by a number of characteristics describing the context:

what object(s) are the measurements taken from? E.g. water samples, some rat's brain, some people in a company's customers panel, a piece of aluminum foil put in a microwave that is running at 700W.
what instruments were used?
when were the measurements taken?
given the time of measurement, should the measurements have the same result and why?
who was pushing the buttons?
etc.

If 8 of the measurements show different outcomes (bias?), in a consistent pattern, I would say that your measurement theory is incomplete or incorrect.
It's generally not a good idea to assume that any model is correct. Remember, it's a model!


Diferença entre os metacaracteres \b e \B

Question: Os metacaracteres \b e \B são âncoras que marcam os limites de uma string (onde ela começa, termina ou ambos). Funciona segundo o padrão ASCII, contendo apenas [A-Za-z0-9_]. Isto é, só serão identificados as partes da string que contenham este padrão.
Tenho esta variável:
x <- c('melodia', 'bom-dia!', 'bom_dia!', 'radial', 'dia', 'diafragma')
x

E os seguintes códigos com uso de \b:
library(tidyverse)

\bdia marca o início (tudo que começa com dia, segundo o padrão ASCII):
str_subset(string = x, regex(pattern = '\\bdia'))
[1] "bom-dia!"  "dia"       "diafragma"

dia\b marca o final (tudo que termina com dia, segundo o padrão ASCII):
str_subset(string = x, regex(pattern = 'dia\\b'))
[1] "melodia"  "bom-dia!" "bom_dia!" "dia"

\bdia\b marca o intervalo (tudo que começa e termina com dia, segundo o padrão ASCII):
str_subset(string = x, regex(pattern = '\\bdia\\b'))
[1] "bom-dia!" "dia"

bom-dia é retornado pois o - não está contido no padrão ASCII informado.
Agora com uso de \B:
str_subset(string = x, regex(pattern = '\\Bdia'))
[1] "melodia"  "bom_dia!" "radial"

str_subset(string = x, regex(pattern = 'dia\\B'))
[1] "radial"    "diafragma"

str_subset(string = x, regex(pattern = '\\Bdia\\B'))
[1] "radial"

Como \B é o inverso de \b (assim como ocorre com \w e \W, \s e \S e assim por diante), o retorno foi o esperado, mas por conta de ser um exemplo simples.
Considere a situação a seguir. Tenho a variável:
y <- c('5203. ._2302', '4243424', '52033.23021', '5201w2211', '53210ggsd3333')

E o código:
str_subset(string = y, regex(pattern = '\\b5\\d{3}\\w'))
[1] "52033.23021"   "5201w2211"     "53210ggsd3333"

Que retorna tudo que comece com 5 seguido de 3 digitos com qualquer caracter \\w ([A-Za-z0-9_) em seguida. Ok.
O que não entendo são os códigos abaixo:
str_subset(string = y, regex(pattern = '\\b5\\d{3}\\w\\b'))
[1] "52033.23021"

str_subset(string = y, regex(pattern = '\\b5\\d{3}\\w\\B'))
[1] "5201w2211"     "53210ggsd3333"

Enquanto o primeiro código casa tudo aquilo que termina com \w, deveria casar tudo, não? E, o segundo, ao invés de casar, deveria negar tudo.
Isso é que não entendi.
Portanto,

qual a diferença, referente à aplicação e ocasião de uso, de \b e \B?
Answer: Antes de mais nada, vale esclarecer que o atalho \b (também conhecido como word boundary, algo como "fronteira entre palavras") é um zero-length match (ou um match de tamanho zero): ele não corresponde a um caractere, e sim a uma posição da string (mais detalhes aqui). No caso, é uma posição que possui um caractere alfanumérico antes e não possui um caractere alfanumérico depois (ou vice versa).
Tanto que a regex a\b encontra um match na string "a" (pois o final da string também é uma posição que tem um caractere alfanumérico antes e não tem um depois, veja).
Já o \B é qualquer posição da string que não seja um \b, ou seja, uma posição em que ambos os caracteres - antes e depois desta posição - são alfanuméricos (ou que ambos são não-alfanuméricos).

Inclusive, este é um padrão comum em regex: muitos atalhos como o \w, \d e \s possuem suas "contrapartes negativas", que é basicamente a mesma letra, só que maiúscula: \W é "qualquer caractere que não seja \w", \D é "qualquer caractere que não seja \d",  etc. Sendo assim, \B é qualquer posição da string que não corresponde a \b.

Sendo assim, nos seus exemplos ambas as regex começam com \\b5\\d{3}\\w: temos um \b antes do dígito 5, e como 5 é alfanumérico, então este \b só encontra um match se antes do 5 não há um caractere alfanumérico (ou seja, antes do 5 pode ter um caractere não-alfanumérico, ou o 5 pode estar no início da string). Depois do 5 temos 3 dígitos (\d{3}), seguido de \w (que é um atalho que considera letras, números ou _).
O que muda é o que tem depois do \w. No primeiro caso, temos \b. Como \w representa um caractere alfanumérico, então o \b verifica se o que tem depois é não-alfanumérico. Por isso ele só pega o "52033.23021". Veja como esta string corresponde à regex:
   5  203    3     .23021
\b 5  \d{3}  \w  \b

O segundo \b corresponde à posição entre o 3 e o .: de fato é uma posição que possui um caractere alfanumérico antes e não tem um alfanumérico depois.
As demais strings não dão match pelos seguintes motivos:

'5203. ._2302': depois do 5 e dos 3 dígitos, há um ponto, que não corresponde a \w
'4243424': não tem o 5
'5201w2211': tem o 5, os 3 dígitos e a letra w, que corresponde a \w. Mas depois da letra w há o dígito 2, então a posição entre a letra w e o dígito 2 não corresponde a \b.
'53210ggsd3333': tem o 5, os 3 dígitos e o dígito 0, que corresponde a \w. Mas depois do 0 há a letra g, então a posição entre o dígito 0 e a letra g não corresponde a \b.

Já a regex '\\b5\\d{3}\\w\\B' tem um \B no final, ou seja, é uma posição na qual antes e depois tem dois caracteres alfanuméricos (ou dois não-alfanuméricos). Por isso ela pega as strings "5201w2211" e "53210ggsd3333":
   5  201    w     2211
\b 5  \d{3}  \w  \B

   5  321    0     ggsd3333
\b 5  \d{3}  \w  \B

O \w pega um caractere alfanumérico, e nesse caso o \B só vai dar match caso o caractere seguinte também seja alfanumérico. Repare acima que na primeira string deu certo porque o \B corresponde à posição entre a letra w e o dígito 2, e na segunda string é a posição entre o dígito 0 e a letra g. E por isso ele não pega as demais strings:

'5203. ._2302': depois do 5 e dos 3 dígitos, há um ponto, que não corresponde a \w
'4243424': não tem o 5
'52033.23021': tem o 5, os 3 dígitos e o dígito 3, que corresponde a \w. Mas depois do dígito 3 há um ponto, que não é alfanumérico. Sendo assim, a posição entre o 3 e o ponto não corresponde a \B.

Por fim, vale esclarecer uma confusão que você fez. \b não corresponde somente ao início ou final da string, e sim a qualquer posição da string que tenha um caractere alfanumérico antes e não tenha um depois (ou vice-versa). Ex:
x <- c('ele podia ter feito isso', 'que dia feliz', 'o diabo que te carregue', 'foi adiado para amanhã')

str_subset(string = x, regex(pattern = '\\bdia'))
[1] "que dia feliz"           "o diabo que te carregue"

str_subset(string = x, regex(pattern = 'dia\\b'))
[1] "ele podia ter feito isso" "que dia feliz"

str_subset(string = x, regex(pattern = '\\bdia\\b'))
[1] "que dia feliz"

O primeiro caso (\\bdia) pega qualquer palavra que comece com "dia", o segundo caso (dia\\b) pega qualquer palavra que termine com "dia", e o terceiro caso (\\bdia\\b) pega exatamente a palavra "dia". Repare que essas palavras não precisam estar no início ou final da string.
Veja também que nenhuma das regex pega a palavra "adiado", pois as posições antes e depois de "dia" também são alfanuméricos e portanto não correspondem a \b.
Por fim, se quer marcar especificamente o início ou final da string, use os marcadores ^ e $.


How linear map transform the unit ball?

Question: Let $f:\mathbb{R}^n \to \mathbb{R^n}$ be a linear application, we suppose that $f$ is symmetric ($\langle f(x),y\rangle=\langle x, f(y)\rangle$), without using spectral theorem how we can see that $f$ maps the unit ball into an ellipsoid ?
Or how can we prove spectral theorem geometrically (intrinsically) ?
Can expand this reasoning to see why not any square matrix is diagonalizable ?
Comment: "Ellipse" is probably "ellipsoid".
Comment: i don't see how you have do such calculation @BranimirĆaćić because for $f(x,y)=1/2(y,x)$
$$f(\cos(a)e_1+\sin(a)e_2)=1/2(\sin(a)e_1+\cos(a)e_2)$$ so the set will be the circle of center $0$ and of radius 1/2
Comment: Oh, I'm stupid, you're absolutely right.
Answer: $\newcommand{\Reals}{\mathbf{R}}\newcommand{\Brak}[1]{\left\langle #1\right\rangle}$An invertible linear operator $f$ on $\Reals^{n}$ maps the unit ball to an ellipsoid whether or not $f$ is symmetric (or even diagonalizable): One strategy is to write the unit ball as the locus of a quadratic inequality and perform a linear change of variables, concluding the image is compact and defined by a quadratic inequality, hence an ellipsoid (for some value of "hence").
In other words, knowing the image of the unit ball is an ellipsoid does not imply the spectral theorem, so if I understand what you're asking, the answer to your third question is "no".
As for proving the spectral theorem geometrically, one approach is to maximize the quadratic function
$$
F(x) = \Brak{x, f(x)}
$$
restricted to the unit sphere, i.e., subject to the constraint $g(x) = \|x\|^{2} = 1$. By Heine-Borel and the extreme value theorem, $F$ has an absolute maximum, $x_{0}$; Lagrange multipliers and symmetry of $f$ show that
$$
2f(x_{0}) = \nabla F(x_{0}) = \lambda \nabla g(x_{0}) = 2\lambda x_{0};
$$
that is, $x_{0}$ is an eigenvector of $f$, with eigenvalue equal to the maximum value of $F$. Now induct, restricting everything to the orthogonal complement of $x_{0}$, and iteratively constructing (for some value of "construct") an orthonormal $f$-eigenbasis of $\Reals^{n}$.
Comment: can explicit the calculus for example in 3 or 4 dimension space ?
Comment: Doing the calculation explicitly in any dimension amounts to orthogonally diagonalizing a symmetric matrix; that is, it's hard to be explicit unless, say the matrix of $f$ is diagonal. I'm guessing you want to see how the inductive step works. The key point is, if $f$ is symmetric, and if $f(x) = \lambda x$ and $\Brak{x, y} = 0$, then$$\Brak{x, f(y)} = \Brak{f(x), y} = \lambda\Brak{x, y} = 0,$$i.e., $f(y) \perp x$. In other words, $f$ induces a symmetric operator on the hyperplane $x^{\perp}$.
Comment: yeah this is what we do to prove the spectral theorem, $f$ stabilizes the orthogonal complaiment of any space stabilized by $f$, this proof in particular that eigenvector are orthogonal (the axes of our ellipsoid are orthogonal)

How linear map transform the unit ball?


Which Microservices architecture can we use to drill down a huge monolithic application that uses a no SQL DB?

Question: We have a huge monolithic backend application built on Java-Spring that deals with the Checkout functionalities of an e-commerce retail client. The application exposes multiple REST APIs to deliver the functionalities and  uses a No SQL DB to store the data.
What type of Microservices design/architecture can we go for, if we want to break this down into granular micro services so that the code maintainability and deployments can be made much easier? Could anyone please suggest the best suitable options that we could try out?
Comment: @user1237244 https://softwareengineering.stackexchange.com/
Answer: An incremental migration from monolith to micro-services is a safer path, you would find something called strangler pattern, which is a famous approach. Following is a good article I came across.
https://dzone.com/articles/monolith-to-microservices-using-the-strangler-patt
Firstly, you should be able to decompose your system in various aspects in terms of functionally and technically. You would need to find more information of what strategy to go forward, following research paper is a good start.
http://domainlanguage.com/wp-content/uploads/2016/04/GettingStartedWithDDDWhenSurroundedByLegacySystemsV1.pdf
Comment: in an ideal situation it cannot use same database, each service should be Highly maintainable and testable, Loosely coupled, Independently deployable and
Organized around business capabilities.
Comment: Thanks for the links. I'll check that out. One other concern here is that this might require the services to use a common database. But, I guess micro services is not built for that purpose.


How to warm-up Twig?

Question: I would like to warm-up Twig templates after cache rebuild or when needed. By warming-up I mean to process each twig template into php file.
Is this possible without rendering the content first?
Comment: Ok, let's stop the edit nonsense here. "warm-up" is a technical term applied to cache, there is no reason to remove it from the question, title or otherwise. This question is both clear and answerable in its original form
Answer: You can warm up the twig cache with drush:
twig-compile (twigc)  Compile all Twig template(s).

The twig cache is located in
/sites/default/files/php/twig

Here you can check the compiled php files.
Answer: The question sounds like coming from a Drupal 7 background :)
If I understand it correctly, you are looking for a way to execute some PHP logic before rendering the content. Just like what we were used to do in the *.tpl.php files.
However, PHPTemplate was removed and replaced by Twig for a reason. For truly separating business and presentation layers - on of the major reason.
This does not mean that you loose on to the control which you had with PHPTemplate files. This only means that you are now forced to follow the best standard practices ;-)
Ideally, in both Drupal 7 and 8 the template functions the rendering should be broken in two steps:

Business logic - The function which is responsible for initializing the data (to be returned to page). This could be a function which calls the theme() function, like the page callback of your hook_menu implementation where you pass the variables into it. These could also be the preprocess functions which could be used to add new and or change existing $variables to the theme element being called.
Presentation logic - These are nothing but the functions or template file responsible for printing the values that it gets from the Business layer into appropriate markup. In D7 we used *.tpl.php, whereas in D8 we use *.twig.

To deal with the issue at hand, you will need to the template_preprocess() function. The *.twig file is responsible to only print the variables, with minimum logical checks.
Comment: @IvanJaros This is a community site, so it is expected to show respect towards people trying to help! The person who edited the question might be at mistake. No one is perfect. If someone is wrong, you have to point it out respectfully. That is how as a community we grow.
Comment: Hi, sorry for the misunderstanding. I have rolled back the question to what I have originally wrote before some **** changed it to something completely different. Feel free to update or remove your question.
Comment: And as per the edited question, the answer still stands unchanged. preprocess is the way to get it done.

How to warm-up Twig?


React executes CATCH statement of PROMISE even after SUCCESS

Question: I am usually an angular developer and am working in react. Please excuse if this question seems simple.
I have a simple PROMISE
    return axios(`team/${this.state.teamId}/player`, this.state)
        .then((response) => {
            console.log('formSubmit success');

            this.store.dispatch({
                type:       constants.PLAYER_UPDATE,
                payload:    response.data.user,
            });
            return false;

        })
        .catch((error) => {
            console.error('Error', error.response.data);
            this.setState({
                saveStatus: error.response.data.message
            });
            return Promise.reject(error)
        });

In the network tab I can see that URL fetched fine.
Also store.dispatch is called as it is printed in console.
But at same time it is calling code in the catch statement.
My console output is
formSubmit success                    Player.js:127
Store BEFORE | PLAYER_UPDATE          Store.js:76

Uncaught (in promise) TypeError: Cannot read property 'data' of undefined
at Player.js:135

Why is it going after CATCH() when everything is success? I even added return statement at the end of this.store.dispatch
Please help.
Answer: The catch function will catch any error which will come in the then, if you want to just catch the error in promise, you probably want to use the second callback in then function. You should do something like this:
return axios.get(`endpoint`)
   .then(successCallback, errorCallback);

OR, in your case,
return axios(`team/${this.state.teamId}/player`, this.state)
        .then((response) => {
            console.log('formSubmit success');

            this.store.dispatch({
                type:       constants.PLAYER_UPDATE,
                payload:    response.data.user,
            });
            return false;

        }, (error) => {
            console.error('Error', error.response.data);
            this.setState({
                saveStatus: error.response.data.message
            });
            return Promise.reject(error)
        });

Comment: May be my brackets got messed up and i didnt notice. But that was my intention. Thanks for replying. Let me change code and try.
Comment: how to achieve success and failure callbacks with await ? I want to handle 401 and 403


Sight reading ("two hands") for one non-performers?

Question: For a long time I have wanted to learn to sight-read piano music, and made a few a ttempts, but failed.
The most important reason for these failures, I think, is that I have no interest whatsoever in performing music1, whereas all the resources I have found for learning how to sight read (particularly teachers) are entirely focused around performance, and relegate sight-reading as a secondary aspect and/or by-product of learning to perform.
For example, I have attempted a couple of times to take lessons from piano teachers, with the express purpose of learning how to sight-read, but these teachers have not known how to address this aim without putting me through the standard sequence of learning a little repertoire, etc.  As a result, I learn no sight-reading at all.  (I guess I have too good finger-memory and/or too good an intuition for the music, so after a couple of rounds I no longer require the score.)
My goal to be able to play a piano piece, however intricate, at first sight, even if my lack of dexterity forces me to play it at an uneven/halting tempo, and/or in an utterly mechanical way.
How can I achieve this goal without embarking in training whose primary aim is performance (for an audience, however modest)?
Is there any learning method for sight-reading specially designed for the non-performer?
May there be a subpopulation of piano teachers (maybe subscribing to a particular philosophy of teaching the piano, or catering to a particular type of student) that may be more responsive than the norm to this non-standard objective?
1I want to sight-read for the same reason a non-actor who loves theater may want to learn to read: to have another way to approach and appreciate theater.  My interest in sight-reading is as a tool, a "scope" to direct at music, to, literally, see it in a different way.  Maybe even to compose.
Comment: Find some sort of graded curriculum or anthology that you haven't yet played, and try sight-reading a few pieces to figure out what level of music you can currently sight-read to your own satisfaction. Work on sight-reading at that level for a while, then move up when you're ready. Once you get a sense of what scores at your level look like, you can download a lot more for free at imslp.org if you need extra material at a given level (which you will, since you can only sight-read a piece once). By the way, a good teacher should be willing to address a student's individual goals!
Comment: Very difficult question ! I went, years ago, to several teachers who obviously couldn't answer it, and now I teach, I'm searching for ways that mostly elude me.Hope someone answers succinctly
Answer: You probably do need to commit some pieces to memory, and here's why.
As a fluent reader of English, when you see the word "penguin", you don't process each individual letter in your head. You see the whole shape of the word, and immediately get a mental image of a black-and-white bird.
When you were a child, learning to read, you did process each individual letter one-by-one, and it was by doing that over and over again that you eventually built up the short cut of recognising the whole word.
As an adult, if you encounter a brand new word, you might process it letter by letter. You might break it into recognisable chunks. But you'd use your experience to quickly add it to your vocabulary, and from then on you'd recognise it instantly.
The principles are similar for reading music.
As a beginner, you might look at a bar of score, and think "OK, the first note is three lines up, so that's E,G,B ... B! Then the next one's two up, so that's a D. B D. Then down three... um, A... B D A.
Now, if you learn that piece my memory, but always play it with the notation in front of you, you'll learn to instantly associate the shape those three notes make on the stave, with the corresponding notes on the keyboard (you will, of course, have to adjust for key signatures).
The key here is that when that pattern appears in other pieces which you are attempting to sight-read, you will still recognise them and be able to play them.
The same goes for rhythm. At first it's quite a struggle to work out how a written rhythm will sound, and you'll have to spend some time tapping out the beats and trying to fit the written notes and rests around them. But the same patterns of rhythm come up over and over again, so once you know how a particular rhythm sounds, you won't have to work it out from scratch again.
Most music is made up of a lot of familiar patterns, along with occasional unfamiliar snatches. Like reading a novel containing the occasional difficult word. To sight read reliably, you need that vocabulary of patterns.
Answer: The first step in learning to sight-read is to read music, a lot.  If you feel like you don't need the music anymore after a few playthroughs, test that assumption by writing out the whole piece from memory.  I would encourage you to continue to look at the music while playing even if you do have it memorized though.
Having a deep knowledge of theory will help because you will see harmonic structures and patterns more easily and don't have to pick out notes.
Also important in sight-reading is knowing how to keep going when you make mistakes.  Our tendency is to stop and correct when making mistakes.  A good sight-reader won't let a missed note disrupt the pulse and flow of the piece.  The goal is uninterrupted playing from beginning to end.
I don't know of a way to divorce sight-reading from performance though, since obviously you have to play the piece while you're reading it.  If the goal isn't to play a piece even moderately well, then what is the goal?  I would also suggest that being able to sight-read well requires being fairly accomplished on the instrument.
Comment: This. Keeping going through mistakes, even botched mish-mashes, is the surest way to sight-reading proficiency. The music marches on, whether you can handle it or no. Eventually you learn to read ahead a measure or two and plot out your fingerings even while you're playing behind what you're looking at and digesting.
Comment: Agree with not stopping: play on, warts an' all.This is usually the reason people play the first part of a learnt piece better than the rest. Played it most.But when you've sightread a tune 2 or 3 times, after that it's not really sightreading.Suggest you leave it alone for a week and then try it again.Then it's not from memory.
Answer: In order to sight read music you need to build up a learned repertoire of common finger patterns.  The best way to start to do this is to practise playing scales and arpeggios, however you must read the scales and arpeggios off the music when you are playing them.  For sight reading it is very important to get a good eye to hand recognition, and if you play scales and arpeggios without reading them off the page you don't learn the instant pattern recognition that is needed for good sight reading.
Answer: I endorse Slim's answer. Knowing the main scales( major and natural minor,perhaps look at harmonic minor) will enable you to put the right hat on for each tune.When you see 3#,and they'll always be the same 3, you know it's in A maj. or F# minor.In A, for example, there'll be maybe more A notes and the tune will generally have F# C#and G# instead of F C and G.The chances of having to read Bb or Eb for example, are pretty small !Being aware of these sort of facts will hopefully cut down the number of errors in sightreading.
As a teacher, I find sightreading to be the hardest part to teach.How can it be practised at home ? When a pupil reads something new, he has no idea if what he's playing is correct, unless he knows it - then it's not sightreading! Much better done with another player present, to guide and confirm. Knowing chords and arpeggios will help immensely - if the same tune as above, in A, is looked at, it will usually reveal harmonies of A maj., D maj.,and E maj.Maybe F#m will appear etc., so if one knows the notes which form each chord,and which chords are in each 'key family', it'll help.
             Try to reference each next note to the last,e.g. C-D is right next door, a tiny move, whereas C-E, on adjacent spaces, will need a jump over the neighbouring D.This has to be better than saying "this is C, where's that on the keys, this is D,where's that.
Answer: The only useful tip I have ever received about sight-reading I got from a guy who is the best sight-reader I know. He said to learn to play without looking at the keyboard. Just look at the written music. He would even go so far as to put a blanket over the keyboard and play with his hands under the blanket to practice.
I have tried to do this and have gone from being a terrible sight-reader to a moderately adequate one.
Answer: I also have to secondate slim, but would like to add a bit. Im my opinion piano is the worst common instrument to learn sight-reading, since there are so many notes. (Harp would be similar and organ would be worse with the additional pedal voice.) So to come down to a managable amount of information you have to abstract significantly like, "oh we are modulating to the dominant chord here", otherwise you have to decode each note by itself, which is likely to take so much time, that the melody flow in your mind breaks down. Situation would be  easier for a wind instrument, where the is only one note at any given time.
Comment: Maybe it's got 88 keys/notes, but what's wrong with just using 2 octaves above and 2 below middle C? Or even less, the notes contained WITHIN the stave.That way, it's no better or worse than a guitar, clarinet, trumpet.......The bigger problem is that it expects you to play different things with each hand, using treble and bass clef dots to read.Most other instruments use ONE clef (and can't play chords),thus one note only at a time.
Answer: You're probably going to have to explain this in more detail:

My goal to be able to play a piano piece, however intricate, at first sight, even if my lack of dexterity forces me to play it at an uneven/halting tempo, and/or in an utterly mechanical way.

Playing it haltingly is not playing the rhythm and possibly wrecking the harmony.  Rhythm is often more important than the pitches used...
With music, you're either playing or composing.  So I assume you're interested in composing?  If so, split the song into melody, supporting chords and percussion.  Also look at the rhythms used.  To see how the components of the song make it "tick".
But, honestly, if you can't play SOME music (at least)...  You may not have a good "base" for composing.


Composite block from multiple other blocks + layout

Question: I would like to create a block consisting of multiple other blocks, combined with a layout or some other kind of wrapper html.
A typical example would be a footer with 4 columns containing a menu, some custom text, etc.
The entire thing should be configurable in the UI and then exportable to the CMI system.
Known solutions
I know that this is possible in Drupal 7 using renderkit + cfrblock. However this has not been ported to Drupal 8 (yet). I will get there eventually, but atm I would like to find out if another solution might already exist.
EDIT:
On D8 there is blockgroup, but it does not really work for me.
Related issues
How to group multiple blocks into one big block I think this is for D7.
Thanks!
Comment: Blockgroup will allow you to create groups of blocks. Other than that, all I can think of is Paragraphs in blocks.
Comment: I had tried blockgroup, but my mistake was to name the block group the same as the theme region :)
Answer: Use blockgroup. Add block_class if needed.
When creating the block groups, make sure that the machine name does not clash with existing theme region machine names! (from any theme, ideally)
After you created a block group, it will show up in two ways in the blocks UI:

As a new theme region (if you avoided the name clash)
As a block that can be placed.

Block class allows to add classes (e.g. bootstrap grid classes) to each block and block group.
This is not 100% what you would get with a layout, but it is getting close, and will be sufficient in many cases.


Bayes theorem in odds form - incorrect in Tetlock's 'Superforecasting' book?

Question: Page 170 in Philip Tetlock's  et al. Superforecasting book shows Bayes' theorem in odds form as:
$$\frac{P (H|D)}{P (\neg H|D)} = P (D|H) P (D|\neg H) \frac{ P (H)}{P (\neg H)}$$
Posterior Odds = Likelihood Ratio • Prior Odds
Shouldn't the Likelihood Ratio be $\frac{P (D|H)}{P (D|\neg H)}$, i.e. division instead of multiplication?
Comment: Quite right: this is a typo.
Answer: So this doesn't remain unanswered (except in comments) let's derive the odds ratio form from scratch:
We know
$P(A|B)=\frac{P(B|A)\cdot P(A)}{P(B)}$, so:
$$\frac{P(A|B)}{P(\bar{A}|B)}=\frac{\frac{P(B|A)\cdot P(A)}{P(B)}}{\frac{P(B|\bar{A})\cdot P(\bar{A})}{P(B)}}$$
$$=\frac{P(B|A)\cdot P(A)}{{P(B|\bar{A})\cdot P(\bar{A})}}$$
$$=\frac{P(B|A)}{{P(B|\bar{A})}}\cdot \frac{P(A)}{P(\bar{A})}$$
So yes, it's a typo as you suggest and should be divided rather than multiplied.


Specifying windows account for SSIS SourceConnectionOLEDB

Question: I'm starting an SSIS package from an .aspx using sp_start_job on the SQL-server.
This package is an import-job, where the destination database is on the same server as the job, so the DestinationConnectionOLEDB uses the same SQL-credentials as for running the job.
However, the source is on another server, and the SourceConnectionOLEDB requires a windows domain account for logon. (The package runs fine from Visual Studio, using my windows account).
I seem to have two possible solutions for the account in the SourceConnectionOLEDB.

either to pass the account of the user who is running the .aspx
or specify a fixed windows account and password in the package.

The last seems not possible to do in Visual Studio, as soon as I select Windows Authentication, the UserID and password field is disabled. Or is there a way of saving this info in the SSIS?
And if not, how do I pass the users windows credentials to the sp_start_job?
Answer: If I got it right, you have a SQL Server Agent job that runs an SSIS package, with a step of type "SQL Server Integration Services Package".
You cannot save AD user login info in SSIS (afaik), but you can specify which user runs the job step in SQL Server by setting up credentials and proxy to be used in that specific job step.
When you run the job, it gets executed as the SQL Server Agent Account by default, but you can change that by using credentials and proxy.

The credentials (Security - Credentials) allows you to specify a username and pw (even an AD user), to be used later by a proxy
The proxy (SQL Server Agent - Proxies) allows you to specify which credentials are available to different job step types.

Summary:

Create the credentials object (Security - Credentials) for your AD user
Create the proxy object (SQL Server Agent - Proxies)

use the credentials defined in point 1
enable the subsystem "SQL Server Integration Services Package"

Configure the job step

in the "run as" dropdown you should see the proxy you just created

Of course in your package you must have set Windows authentication for the data source


Unattended WinDbg script for breakpoints and delays

Question: I want to debug an application running on Windows by setting a breakpoint on a certain address, waiting till the breakpoint is hit, keeping the application paused for a certain period of time and then continuing. All of this should be done in an unattended fashion (e.g. a script).
To do this, I chose to use WinDbg since the scripting support seems promising.
Starting WinDbg and attaching to the process by process name can e.g. be done by invoking the following command:
"C:\Program Files (x86)\Windows Kits\10\Debuggers\x64\windbg.exe" -pn my-executable.exe

Setting the breakpoint is done with the bu command:
bu 0x1337

Continuing works with the g command.
Delaying can be done with the .sleep command:
.sleep milliseconds

For writing WinDbg scripts this PDF might be helpful.
How can I piece it all together? I didn't figure out how delaying after hitting a breakpoint can be done nor do I know how to perform all of those actions (including attaching) from the command line alone without loading up the WinDbg GUI at all.
Answer: what for you need to sleep
you can embed the script commands and pass it to and instance of windbg
with -c  switch  the command below lists the modules and quits the session
windbg -c "lm;q" calc.exe
you can put it inside a batfile and run the batfile
like
cdb -c "bu %2 \".sleep 5000;g\";g" %1.exe

a gif showing how i broke on winmain slept for 5 seconds before allowing the exe to run below
Comment: I need the sleep to write into the process memory with another application in the meantime and then continue the execution to avoid concurrency/bad timing issues.


I'm almost 100% sure that the answer is 60 and yet I got the question wrong.

Question: For context here's the typed-out question: Consider rectangle PQRS (not shown) with PQ=24 and PS=10. If A and B are the midpoints of sides PQ and QR respectively, find AB.
I'm really not sure what I could be doing wrong and in all probability I'm most likely overlooking one very small and crucial detail or definition that's embedded in the question. Half of 24 and 10 is 12 and 5 respectively and when multiplied together 12 times 5 will equal 60. Is that not the question, find A and B, midpoints, and then multiply them together?
I've just now gotten the idea that maybe PQ=24 means that they're variables that when multiplied together equal 24 but that doesn't make sense because then it mentions line PQ's midpoint, ie P and Q are not variables. It's a simple question but I can't seem to get past it, please help me.
Comment: Please write an informative title... one that relates to the content of the question.
Comment: It should be a geometry problem, but you understand it as algebra... (A and B are the midpoints, not two numbers)
Comment: AB is the length of the line segment between A and B
Answer: $AB$ in this case means the length from point $A$ to point $B$. It doesn't mean the area of something like a sub-rectangle of the main rectangle, $A\times B=60$.
To get the length from $A$ to $B$ you need to use Pythagoras' theorem. 12 and 5 is a well-known combination. You need to solve for $\sqrt{12^2+5^2}$.
Comment: While your intent is correct, "$A \times B = 60$" is not true. $A$ and $B$ are points, not numbers. There is no such concept as "$A \times B$".
Comment: Yes, we can be fairly sure that AB doesn't mean $A\times B$ in this case, since $A$ and $B$ are points. I think you've parsed the first sentence wrongly. What I have written is that AB probably means "the length from point A to point B" rather than "the area of a sub-rectangle, which is A×B=60". You seem to have taken that to mean that I think that such a subrectangle exists, but I am actually stating that it doesn't, and that that is a misinterpretation of what $AB$ means.
Comment: I didn't misinterpret your post. I started out by saying your intent was correct. But still, your writing that "$A \times B = 60$" is the area of a subrectangle confuses the matter, rather than clarifying it. The subrectangle exists (though it is not what the question asks for) and its area is $60$, but its area is not expressible as "$A \times B$".
Comment: @PaulSinclair OK I have rewritten it, although I think that it is very unlikely that anyone was actually confused by the previous version. Hopefully this discussion can be ended. Thank you for your input and I hope to see you on some more interesting discussions again.
Comment: You wouldn't be confused and I wouldn't be confused. But the idea that $A$ and $B$ were lengths instead of points was the key mistake that led to the OP asking this question. And way you had originally phrased that paragraph reinforced this error even though you were trying to correct it. Now it is better.


MaxKeepAliveRequests for IIS7 (with NLB)

Question: We have an IIS7 running on several nodes in an NLB cluster. The NLB nodes are set to Affinity:None so that new connections are spread across them. We want KeepAlive switched on so that we can get better performance but we are finding that when one of the nodes in the cluster goes away all its traffic moves on to other nodes but never moves back.
Although we are running web services we only have a few clients that do CPU intensive tasks so we are finding that one server will be being battered to death while the other sits there doing nothing!
We would like something like Apache's MaxKeepAliveRequests which limits the number of requests on a given connection so that IIS will periodically force clients to re-connect and therefore balance the cluster.
Is this something IIS7 supports? Is this what "normal" people do?
Answer: If it's a truly stateless session, you can disable KeepAlive altogether in IIS7 with:
<code>appcmd set config /section:httpProtocol /allowKeepAlive:false
</code>
This shouldn't add a significant amount of overhead if most of the work is done by only a few clients. Be sure to test it first, though.
Comment: Thanks, but we want KeepAlive switched on. Connections are made from vast distances over potentially slow links so the connection time overhead could be significant. Fresh connections could be a buffering problem when streaming our media.
Answer: I couldn't find a suitable solution, so wrote my own. I've documented the configuration settings in IIS and NLB. The article provides the HTTP module code you need in order to implement a MaxKeepAliveRequests setting to make sure no client remains glued to the same node in the NLB cluster.
Connection balancing across NLB using IIS and MaxKeepAliveRequests
http://www.bigsoft.co.uk/blog/index.php/2011/09/21/connection-balancing-across-nlb-using-iis-and-maxkeepaliverequests


vue 3 composition api & typescript object keys

Question: Currently digging into Vue-3 composition api and wondering how to use types in detail (using TypeScript on top of vue).
The documentation isn't very accurate on this, since there is only a short description about how to do Strings. Of course according to that I could simply use type Object, but I wonder how to declare object properties, to tell TypeScript what keys belong to a related object - in class style api this could be done the TypeScript way ... is there any extended source about how to do properties in detail in composition api?
Comment: Maybe provide a little code snippet demonstrating what you're trying to achieve. An example can often illustrate a problem better than a long description.
Comment: In class style api I'd do it this way:

@Prop() somePropertyName: { foo, bar };

So TypeScript/my IDE knows that my Object should contain the keys foo and bar. I could not find any description about how to achieve that using composition api
Comment: ok you need to use `PropType`. I'll give you an example below.
Comment: @IrgendSonHansel Someone asked [similar question](https://stackoverflow.com/q/64831745/3634538) recently. My proposed solution there might help.
Answer: Use PropType to provide strong type definitions for your props. Here's an example ..
import { defineComponent, PropType } from 'vue';

export default defineComponent({
  props: {
    myProp: Object as PropType<{ foo: string, bar: number }>,
  },
  setup(props) {
    ...
  }
});

Comment: @IrgendSonHansel Same thing. See [Annotating Props](https://v3.vuejs.org/guide/typescript-support.html#annotating-props) in the official guide.
Comment: Can you tell where this information can be found? Now I know how to handle objects but what about arrays & functions ...?


Problem in drush configuration with wamp server 64 bit

Question: I am trying to enable drush for wamp server 64 bit.
I have configured all things with youtube videos and it seems it must be ok but when I run drush via cmd console, I see this error message :
PHP Warning:  PHP Startup: Unable to load dynamic library './php_gd2.dll' - The
specified module could not be found.
My operating system is windows 7 64 bit. so I have installed Wamp server 64 bit version. PHP version is 5.5.12 and apache version is 2.4.9
I don't know what is the reason of this problem. I checked my php.ini
extension path is ok. also I can see "php_gd2.dll" file inside extension folder.
so why I see this error that says specified module could not be found?
Answer: PHP for Apache and CLI have different configuration files, so check if you're using the right one.
To identify which php.ini is used by drush, run drush status:
$ drush status
PHP executable         :  /path/to/bin/php
PHP configuration      :  /path/to/php.ini

then edit that file and check if you've the right extensions specified.
Alternatively check using php command, for example:
$ php -i | grep php.ini

Note: In case grep command is not found, replace with the with find.
If you still have a problem, possibly that your DLL library was compiled for the wrong version of PHP. So either use the one included with WAMP, or download the right one specifically for that version of PHP.
Also double check that your command-line php points to the right place (WAMP folder):
$ where php
$ which php

which should give you C:\WAMP\PHP\bin-like path, if it's not, update your system PATH variable in advaned system settings.
Finally to check if your GD2 library is loaded, check by:
php -r "phpinfo();" | grep gd2

Note: The grep can be replaced with find on Windows if you don't have Linux command utilities installed.
Comment: I am using wamp on windows 7 64 bit. You mentioned run "drush status" but I have written drush command cause this error. indeed drush command doesn't work at all.
But I checked php.info. result is >> Configuration File (php.ini) Path : C:\Windows  and Loaded Configuration File  : C:\wamp\bin\apache\apache2.4.9\bin\php.ini. does this information help?
Comment: @Mehrdad201Missing `gd2` library normally shouldn't prevent from `drush` running, apart of the issue described in [here](https://github.com/drush-ops/drush/issues/1616), as I had similar issue with `memcached`.
Comment: @Mehrdad201The `php.ini` from `phpinfo();` should help, but your still points to Apache path, so make sure you run `phpinfo();` from the CLI (not Apache), or use `php -i` instead to find out the config file. Unless they're pointing to the same file, which is a bit weird.
Comment: Dear @kenorb, can you tell me how can I run phpinfo from CLI (not apache) ?
Comment: @Mehrdad201 Run PHP from the command-line (in `cmd.exe` console), not the web browser, e.g. `php -r "phpinfo();" | find "php.ini"`.
Comment: I did it. I went to php via cmd. it was located at C:\wamp\bin\php\php5.5.12  then I executed php -i command. The result has a lot of lines but I can't find any php.ini in output texts
Comment: Also I executed this command php --ini via cms when I was in C:\wamp\bin\php\php5.5.12   - the result is

Configuration File (php.ini) Path: C:\Windows
Loaded Configuration File:         C:\wamp\bin\php\php5.5.12\php.ini
Scan for additional .ini files in: (none)
Additional .ini files parsed:      (none)
Comment: @Mehrdad201 So `C:\wamp\bin\php\php5.5.12\php.ini` is the right file to change, comment out the loading of `gd2` extension, as you probably not need that for drush.
Comment: maybe drush doesn't need gd2 plugin. but if I disable it so drupal sites that work with gd2 plugin won't work correctly.
Comment: @Mehrdad201 Your question is about how to enable `drush` which is command-line only and PHP configuration for command-line and Apache are 2 different things. So anything you disable for PHP CLI, won't affect any of your sites, so I'm not sure what you're trying to do. If you're focusing on PHP CLI, edit that config for CLI only and remove that non-working plugin, it won't do anything with your sites.


nginx process turn to D state when high load on same static file

Question: I have some file hosting servers running nginx, serving static files which size average from 500MB to 6GB.
The servers use Lustre1.8 as cluster filesystem.
Files stay on some raid6 array with stripe size = 512KB.
At normal situation, nginx works very well.
_ The disk i/o :
Device: tps MB_read/s MB_wrtn/s MB_read MB_wrtn
sdc 727.00 136.23 5.75 136 5
sdd 627.00 124.36 0.01 124 0
_ Traffic out :
iface Rx Tx Total
eth2: 480.00 b/s 551.30 Mb/s 551.30 Mb/s
eth3: 480.00 b/s 481.72 Mb/s 481.72 Mb/s
eth4: 136.47 Mb/s 525.45 Mb/s 661.92 Mb/s
eth5: 480.00 b/s 497.82 Mb/s 497.82 Mb/s
bond0: 136.47 Mb/s 2.01 Gb/s 2.14 Gb/s
_ Number of files are serving :
lsof -u nginx -n | grep storagefile | wc -l
3982
But, when in hot situation (when a new hot file, may be a porn dvd or JAV recently uploaded), there are a lot of clients (more than 800) download that file at the same time, and nginx processes are going to D state.
At last, nearly all processes are D state ! This makes the download speed very slow :(
root 25821 0.0 0.0 33032 584 ? Ss Dec20 0:00 nginx: master process /usr/sbin/nginx -c /etc/nginx/nginx.conf
nginx 25823 0.8 1.5 158384 126396 ? S Dec20 23:53 nginx: worker process
nginx 25824 0.7 1.8 182276 150420 ? D Dec20 21:58 nginx: worker process
nginx 25825 0.7 2.1 207584 175728 ? D Dec20 22:01 nginx: worker process
nginx 25826 0.8 1.8 186052 154196 ? D Dec20 23:32 nginx: worker process
nginx 25827 0.7 1.9 191448 159464 ? D Dec20 23:03 nginx: worker process
nginx 25828 0.8 1.6 166044 134188 ? D Dec20 24:56 nginx: worker process
nginx 25829 0.7 1.3 139308 107452 ? S Dec20 23:00 nginx: worker process
nginx 25830 0.7 1.7 176652 144796 ? D Dec20 21:08 nginx: worker process
nginx 25832 0.7 1.2 136648 104788 ? D Dec20 20:25 nginx: worker process
nginx 25833 0.8 1.7 178948 146964 ? D Dec20 23:27 nginx: worker process
nginx 25834 0.7 2.0 195828 163968 ? D Dec20 21:45 nginx: worker process
nginx 25835 0.8 1.6 166200 134344 ? S Dec20 23:30 nginx: worker process
nginx 25836 0.8 1.3 144624 112640 ? D Dec20 23:50 nginx: worker process
nginx 25837 0.7 1.3 143644 111784 ? D Dec20 22:02 nginx: worker process
nginx 25838 0.7 1.3 141912 110056 ? D Dec20 21:17 nginx: worker process
nginx 25839 0.6 1.4 150580 118724 ? S Dec20 20:12 nginx: worker process
nginx 25840 0.8 1.5 158916 126928 ? D Dec20 23:48 nginx: worker process
...
I have tried many time tuning the number of process worker, but I didn't work !
How can I fix this ? I think when a lot off client access the same file, it suppose to be better because of caching ?!
Here is the config of nginx :

#

worker_processes 48;
worker_rlimit_nofile 800000;
events
{
worker_connections 51200;
use epoll;
}
http
{
sendfile off;
directio 1m;
output_buffers 1 512k;
tcp_nopush off;
tcp_nodelay on;
keepalive_timeout 5;
...
nginx -V
nginx: nginx version: nginx/1.0.0
nginx: built by gcc 4.1.2 20080704 (Red Hat 4.1.2-50)
uname -a
Linux OST 2.6.18-194.17.1.el5_lustre.1.8.5 #1 SMP Mon Nov 15 15:48:43 MST 20
If you need more info, tell me.
Answer: Your disk subsystem is unable to provide enough speed, that's why nginx is being locked on IO, because it's syncronous by default.
You may try to use aio: http://wiki.nginx.org/HttpCoreModule#aio - it would be solution to worker processes locking, so all other requests that are related to proxying or other asyncronus operations will work faster. But aio will not sightly speedup your downloads.
Consider adding more memory: increasing from 8 to 24 GB will improve linux vfs caching and it may give icredible results.
RAID6 is not good for static file serving. It shows good speed while single thread reading and performance is degraded on tens and hundreds concurent readings. There is nothing better than separate disks configured as JBOD. You may also try to use SSD for some "hot" content.
Comment: Thanks for replying.
In hot time, when most of process turn into D state, I have tried cp/rsync/dd that "hot file" to /dev/null or to another ftpserver to measure that if there's bottle neck at disk i/o ?!
But it was not disk i/o, cp/rsync/dd was done at very good speed (about 100~200Mbyte/s) => So I dont think the problem at disk i/o but nignx (directIO) not good at high concurent reading.
I also try AIO but the traffic out lower than directIO very much (about 10% compares to DirectIO).
Comment: http://www.remsys.com/nginx-on-1gbps
Comment: Try with "sendfile on;". Remove directio and output_buffers. DirectIO is not good if you have popular files with several readers. It forces nginx to read from disk instead of memory (vfs cache).


Como representar o tipo Real no C#?

Question: Tenho uma tabela já existente em um banco de um cliente meu e lá tem um atributo com o tipo de dado REAL. Como eu represento no C#? float ou decimal? Qual o melhor caminho?
Answer: Depende do conteúdo. Depende se deseja exatidão de valores.
Quase sempre eu vou de decimal que dá a exatidão, ele é útil para valores monetários ou outros típicos que a unidade exata é importante, isto vale para vários tipos de medidas. Mas o banco de dados precisaria estar com um tipo compatível.
Mas pode ir de double, eventualmente float. Se no banco de dados está como REAL, deve ser o mais adequado, a semântica do tipo real é de ponto flutuante como esses tipos do C#.
O que pode se perguntar é se o banco de dados está errado e já causando problema para o sistema.
Veja mais em Qual a forma correta de usar os tipos float, double e decimal?.
Coloquei no GitHub para referência futura.
Comment: O problema é que o banco de dados está errado, se é juros, esquece esse `real`, isto está errado, provavelmente todo o sistema está errado. Veja: https://pt.stackoverflow.com/q/38138/101 e https://pt.stackoverflow.com/questions/tagged/valor-monet%c3%a1rio?sort=votes&pageSize=50. Boa parte dos sistemas existentes estão causando prejuízos por aí, incluindo gerando multas de fiscalização porque os valores ficam errados.
Comment: Essa informação eu não tenho, o que passa que é para juros, comissões e eu achei mais adequado o uso do decimal, mas pode ser que aja alguma outra informação que eu não conheço.
Comment: Se é para isto o certo é `decimal`,m as precisa estar assim no banco de dados também.
Comment: Se é para juros está errado, está causando prejuízos para a empresa, seja de valores, seja de imagem.
Comment: Não entendi, big. Como assim prejuízo? Então qual tipo eu represento no C# o REAL do Sql Server?
Comment: Entendi agora, em realidade o banco deles é estranho, mas eu estou apenas criando um aplicativo mobile e essa etapa faz parte do rest que vai viabilizar o aplicativo. O campo hora e data deles é float, por exemplo, mas não tenho como alterar isso, já existe há uns 8 anos assim e quero só fazer meu App pra eles, vender, receber e negociar outras demandas. De qualquer forma, vou levar seu comentário pra eles e deixá-los tomarem suas próprias decisões. Vou usar o decimal, pois o C# não tem o Real, para campos monetários. Valeu.
Comment: É, está tudo com problemas, aprenda a fazer certo, mas este parece ser um caso perdido. Pelo menos sua parte ficará certa para outros bancos de dados.

Como representar o tipo Real no C#?


Como embaralhar caracteres de uma String em Delphi

Question: Teria alguma função para embaralhar em Delphi para embaralhar uma string.

Ex de String  := 'casa de madeira';
Ex de retorno := 'medr ci saedaaa';
Comment: Da uma olhada se te ajuda https://www.clubedohardware.com.br/forums/topic/567952-embaralhar-letras/
Comment: Isso mesmo. Para não ficar sem resposta posso por o código com a resposta? ou você coloca... vai que o site sai do ar...
Comment: Se resolveu pode pôr o código pra ajudar o pessoal.
Answer: Postando para não ficar sem resposta como sugestão do Autor da pergunta.
Fonte: Jefferson Rudolf (users/34982)
function EmbaralharString(const aString: string): string;
var
  i: integer;
  vPosicao: integer;
  vLista: TStrings;
begin
  Randomize;

  vLista := TStringList.Create;

  for i := 1 to aString.Length do
    vLista.Add(aString[i]);

  for i := 1 to aString.Length do
  begin
    vPosicao := Random(vLista.Count);
    Result := Result + vLista.Strings[vPosicao];
    vLista.Delete(vPosicao);
  end;

  FreeAndNil(vLista);
end;

Bem simples, primeiro ele desmonta a string em e cria uma lista de "char", depois randomicamente pega cada "char" e monta uma nova string.