Regex to find multiple matches in between two strings

Question: Here is a link to the string I am trying to do regex from: http://pastebin.com/raw/TRKbqGxs
Yes, I know regex is not the best for parsing HTML, but I want to use it in this project. I don't want to use HTML Ability Pack at this moment.
My main interest are lines like these:
data-screen-name="thanhbach195" data-name="Mai Thanh Bách" data-protected="false">
data-screen-name="zeref980" data-name="Yan Naung Htet" data-protected="false">
I want to export the data between following chunks of text data-screen-name=" and " data-name=.
Basically, in this case thanhbach195 and zeref980.
I tried the following regex: string reg = "data-screen-name=\"(.*)\" data-name=\"";
But I didn't get the answer of the multiple matches for some reason. In fact, it doesn't seem to be extracting the string I want at all.
I would appreciate if someone can help me write a correct regex to extract all matches between those 2 strings in the string that I uploaded above.
private List<string> getUsers(string str)
        {
            List<string> users = new List<string>();
            string reg = "data-screen-name=\"(.*)\" data-name=\"";
            MatchCollection mc = Regex.Matches(str, reg);
            foreach(Match m in mc)
            {
                users.Add(m.Groups[1].Value);
            }
            return users;
        }

This code returns the same match every time (first one I believe it is).
Comment: I must add again and again: do not use dot matching patterns to parse delimited text. Use negated character classes, sometimes with alternations.
Comment: You should be using Html Agility Pack for this.  But you already know that.
Comment: But It works fine. (http://i.stack.imgur.com/PN5bJ.png). How are you accessing the value of the group? Are there more than one matches in your html?
Comment: Yes @MaximilianGerhardt there are more than 1 matches, which is my problem.
Comment: @RobertHarvey I agree but I'd like to use regex for this software I'm writing right now. Html Agility Pack definitely makes it a lot easier though.
Comment: `foreach(Match m in Regex.Matches(inputHTML, reg)) { Console.WriteLine( m.Groups[1].Value); }`.
Comment: @RobertHarvey Yes, I did. Suppose I have to use groups, how would I access all the groups of all matches? Right now, I am just getting the same output every time. I'll update my first post with an example.
Comment: @MaximilianGerhardt That is what I've been doing pretty much and I keep getting the same output every time.
Comment: Code looks good, go set a breakpoint on the `Add()` function and debug it. Take a look at what entries the list has and how the list is then further processed.
Comment: Thanks @MaximilianGerhardt for the time. I got it working! :)
Comment: Without using groups you may also try this one `/[^"]+?(?="\s*data-name=")/g`
Comment: And it works - http://ideone.com/wTJpM5
Answer: Disclaimer
You should really use an HTML parsing engine as there are many obscure edge cases that regex can't easily accommodate. But I'm not your mom, so I'm not going to tell you how to live your life.
Since it appears that you have some control over your source text, you'll probably be able to completely avoid the obscure edge cases.
Description
This regex will do the following:

find all the div tags
ensure each div tag found contains a class="user-actions with or without the quote
captures the values for data-screen-name, data-name, and data-protected into their own capture groups
allows attribute/value sets to appear in any order
allows the quotes around value to be optional, so you can use single quotes, double quotes, or no quotes
scrubs quotes from the values, so you get the raw value
avoids a lot of the messy edge cases the regex police cry about when matching HTML

The Regex

=]|='[^']*'|="[^"]*"|=[^'"][^\s>]*)*?class=['"]?user-actions)(?=(?:[^>=]|='[^']*'|="[^"]*"|=[^'"][^\s>]*)*?data-screen-name=(['"]?)(.*?)\1(?:\s|>))(?=(?:[^>=]|='[^']*'|="[^"]*"|=[^'"][^\s>]*)*?data-name=(['"]?)(.*?)\3(?:\s|>))(?=(?:[^>=]|='[^']*'|="[^"]*"|=[^'"][^\s>]*)*?data-protected=(['"]?)(.*?)\5(?:\s|>))(?:[^>=]|='(?:[^']|\\')*'|="(?:[^"]|\\")*"|=[^'"][^\s>]*)*\s*>
I recommend using the case insensitive flag.
Examples
Excerpt From Source Text
A tiny portion of your sample text

Live Example
Shows just a larger portion of your overall file because the online tool gets bogged down with huge strings of text.
https://regex101.com/r/bY1kH8/1
Capture Groups

Group 0 gets the entire opening div tag
Group 1 gets is assigned the quote if there was one around the data-screen-name value
Group 2 get the data-screen-name value, not including any quotes
Group 3 gets is assigned the quote if there was one around the data-name value
Group 4 get the data-name value, not including any quotes
Group 5 gets is assigned the quote if there was one around the data-protected value
Group 6 get the data-protected value, not including any quotes

Sample Matches
These were taken from your source text using the proposed regular expression.
[0][0] =

[0][1] = "
[0][2] = w33haa
[0][3] = "
[0][4] = Aliwi Omar
[0][5] = "
[0][6] = false

[1][0] =

[1][1] = "
[1][2] = Jamjomon
[1][3] = "
[1][4] = Jamchu :3
[1][5] = "
[1][6] = false

[2][0] =

[2][1] = "
[2][2] = dimakoza4enko
[2][3] = "
[2][4] = Дима Козаченко
[2][5] = "
[2][6] = false

[3][0] =

[3][1] = "
[3][2] = alupulipulipala
[3][3] = "
[3][4] = Wahid Arefin
[3][5] = "
[3][6] = false

[4][0] =

[4][1] = "
[4][2] = thanhbach195
[4][3] = "
[4][4] = Mai Thanh Bách
[4][5] = "
[4][6] = false

[5][0] =

[5][1] = "
[5][2] = zeref980
[5][3] = "
[5][4] = Yan Naung Htet
[5][5] = "
[5][6] = false

[6][0] =

[6][1] = "
[6][2] = Just__Kidding__
[6][3] = "
[6][4] = Chaw Chin Fong
[6][5] = "
[6][6] = true

[7][0] =

[7][1] = "
[7][2] = Fruitcentre
[7][3] = "
[7][4] = Fruit & Veg Centre
[7][5] = "
[7][6] = false

[8][0] =

[8][1] = "
[8][2] = aeronhalecastle
[8][3] = "
[8][4] = Eywon ツ
[8][5] = "
[8][6] = true

[9][0] =

[9][1] = "
[9][2] = Deheyb
[9][3] = "
[9][4] = 4k Scrub✌
[9][5] = "
[9][6] = false

[10][0] =

[10][1] = "
[10][2] = Ribbon2712
[10][3] = "
[10][4] = Даниил Демидов
[10][5] = "
[10][6] = false

[11][0] =

[11][1] = "
[11][2] = zayarmgmg95
[11][3] = "
[11][4] = Zayar Mg
[11][5] = "
[11][6] = false

[12][0] =

[12][1] = "
[12][2] = Ninderpy
[12][3] = "
[12][4] = Derpy
[12][5] = "
[12][6] = false

[13][0] =

[13][1] = "
[13][2] = ImJoehuff
[13][3] = "
[13][4] = JoeyT
[13][5] = "
[13][6] = false

[14][0] =

[14][1] = "
[14][2] = zxmir_
[14][3] = "
[14][4] = Zxmir_
[14][5] = "
[14][6] = false

[15][0] =

[15][1] = "
[15][2] = hienlequang
[15][3] = "
[15][4] = Hiền Lê Quang
[15][5] = "
[15][6] = false

[16][0] =

[16][1] = "
[16][2] = Najer14
[16][3] = "
[16][4] = Jan
[16][5] = "
[16][6] = false

[17][0] =

[17][1] = "
[17][2] = 7forOne
[17][3] = "
[17][4] = Abiel
[17][5] = "
[17][6] = false

[18][0] =

[18][1] = "
[18][2] = Th3uN1qu31
[18][3] = "
[18][4] = Th3_uN1Qu3
[18][5] = "
[18][6] = false

Explained

NODE                     EXPLANATION
----------------------------------------------------------------------
  <div                     '<div'
----------------------------------------------------------------------
  \b                       the boundary between a word char (\w) and
                           something that is not a word char
----------------------------------------------------------------------
  (?=                      look ahead to see if there is:
----------------------------------------------------------------------
    (?:                      group, but do not capture (0 or more
                             times (matching the least amount
                             possible)):
----------------------------------------------------------------------
      [^>=]                    any character except: '>', '='
----------------------------------------------------------------------
     |                        OR
----------------------------------------------------------------------
      ='                       '=\''
----------------------------------------------------------------------
      [^']*                    any character except: ''' (0 or more
                               times (matching the most amount
                               possible))
----------------------------------------------------------------------
      '                        '\''
----------------------------------------------------------------------
     |                        OR
----------------------------------------------------------------------
      ="                       '="'
----------------------------------------------------------------------
      [^"]*                    any character except: '"' (0 or more
                               times (matching the most amount
                               possible))
----------------------------------------------------------------------
      "                        '"'
----------------------------------------------------------------------
     |                        OR
----------------------------------------------------------------------
      =                        '='
----------------------------------------------------------------------
      [^'"]                    any character except: ''', '"'
----------------------------------------------------------------------
      [^\s>]*                  any character except: whitespace (\n,
                               \r, \t, \f, and " "), '>' (0 or more
                               times (matching the most amount
                               possible))
----------------------------------------------------------------------
    )*?                      end of grouping
----------------------------------------------------------------------
    class=                   'class='
----------------------------------------------------------------------
    ['"]?                    any character of: ''', '"' (optional
                             (matching the most amount possible))
----------------------------------------------------------------------
    user-actions             'user-actions'
----------------------------------------------------------------------
  )                        end of look-ahead
----------------------------------------------------------------------
  (?=                      look ahead to see if there is:
----------------------------------------------------------------------
    (?:                      group, but do not capture (0 or more
                             times (matching the least amount
                             possible)):
----------------------------------------------------------------------
      [^>=]                    any character except: '>', '='
----------------------------------------------------------------------
     |                        OR
----------------------------------------------------------------------
      ='                       '=\''
----------------------------------------------------------------------
      [^']*                    any character except: ''' (0 or more
                               times (matching the most amount
                               possible))
----------------------------------------------------------------------
      '                        '\''
----------------------------------------------------------------------
     |                        OR
----------------------------------------------------------------------
      ="                       '="'
----------------------------------------------------------------------
      [^"]*                    any character except: '"' (0 or more
                               times (matching the most amount
                               possible))
----------------------------------------------------------------------
      "                        '"'
----------------------------------------------------------------------
     |                        OR
----------------------------------------------------------------------
      =                        '='
----------------------------------------------------------------------
      [^'"]                    any character except: ''', '"'
----------------------------------------------------------------------
      [^\s>]*                  any character except: whitespace (\n,
                               \r, \t, \f, and " "), '>' (0 or more
                               times (matching the most amount
                               possible))
----------------------------------------------------------------------
    )*?                      end of grouping
----------------------------------------------------------------------
    data-screen-name=        'data-screen-name='
----------------------------------------------------------------------
    (                        group and capture to \1:
----------------------------------------------------------------------
      ['"]?                    any character of: ''', '"' (optional
                               (matching the most amount possible))
----------------------------------------------------------------------
    )                        end of \1
----------------------------------------------------------------------
    (                        group and capture to \2:
----------------------------------------------------------------------
      .*?                      any character (0 or more times
                               (matching the least amount possible))
----------------------------------------------------------------------
    )                        end of \2
----------------------------------------------------------------------
    \1                       what was matched by capture \1
----------------------------------------------------------------------
    (?:                      group, but do not capture:
----------------------------------------------------------------------
      \s                       whitespace (\n, \r, \t, \f, and " ")
----------------------------------------------------------------------
     |                        OR
----------------------------------------------------------------------
      >                        '>'
----------------------------------------------------------------------
    )                        end of grouping
----------------------------------------------------------------------
  )                        end of look-ahead
----------------------------------------------------------------------
  (?=                      look ahead to see if there is:
----------------------------------------------------------------------
    (?:                      group, but do not capture (0 or more
                             times (matching the least amount
                             possible)):
----------------------------------------------------------------------
      [^>=]                    any character except: '>', '='
----------------------------------------------------------------------
     |                        OR
----------------------------------------------------------------------
      ='                       '=\''
----------------------------------------------------------------------
      [^']*                    any character except: ''' (0 or more
                               times (matching the most amount
                               possible))
----------------------------------------------------------------------
      '                        '\''
----------------------------------------------------------------------
     |                        OR
----------------------------------------------------------------------
      ="                       '="'
----------------------------------------------------------------------
      [^"]*                    any character except: '"' (0 or more
                               times (matching the most amount
                               possible))
----------------------------------------------------------------------
      "                        '"'
----------------------------------------------------------------------
     |                        OR
----------------------------------------------------------------------
      =                        '='
----------------------------------------------------------------------
      [^'"]                    any character except: ''', '"'
----------------------------------------------------------------------
      [^\s>]*                  any character except: whitespace (\n,
                               \r, \t, \f, and " "), '>' (0 or more
                               times (matching the most amount
                               possible))
----------------------------------------------------------------------
    )*?                      end of grouping
----------------------------------------------------------------------
    data-name=               'data-name='
----------------------------------------------------------------------
    (                        group and capture to \3:
----------------------------------------------------------------------
      ['"]?                    any character of: ''', '"' (optional
                               (matching the most amount possible))
----------------------------------------------------------------------
    )                        end of \3
----------------------------------------------------------------------
    (                        group and capture to \4:
----------------------------------------------------------------------
      .*?                      any character (0 or more times
                               (matching the least amount possible))
----------------------------------------------------------------------
    )                        end of \4
----------------------------------------------------------------------
    \3                       what was matched by capture \3
----------------------------------------------------------------------
    (?:                      group, but do not capture:
----------------------------------------------------------------------
      \s                       whitespace (\n, \r, \t, \f, and " ")
----------------------------------------------------------------------
     |                        OR
----------------------------------------------------------------------
      >                        '>'
----------------------------------------------------------------------
    )                        end of grouping
----------------------------------------------------------------------
  )                        end of look-ahead
----------------------------------------------------------------------
  (?=                      look ahead to see if there is:
----------------------------------------------------------------------
    (?:                      group, but do not capture (0 or more
                             times (matching the least amount
                             possible)):
----------------------------------------------------------------------
      [^>=]                    any character except: '>', '='
----------------------------------------------------------------------
     |                        OR
----------------------------------------------------------------------
      ='                       '=\''
----------------------------------------------------------------------
      [^']*                    any character except: ''' (0 or more
                               times (matching the most amount
                               possible))
----------------------------------------------------------------------
      '                        '\''
----------------------------------------------------------------------
     |                        OR
----------------------------------------------------------------------
      ="                       '="'
----------------------------------------------------------------------
      [^"]*                    any character except: '"' (0 or more
                               times (matching the most amount
                               possible))
----------------------------------------------------------------------
      "                        '"'
----------------------------------------------------------------------
     |                        OR
----------------------------------------------------------------------
      =                        '='
----------------------------------------------------------------------
      [^'"]                    any character except: ''', '"'
----------------------------------------------------------------------
      [^\s>]*                  any character except: whitespace (\n,
                               \r, \t, \f, and " "), '>' (0 or more
                               times (matching the most amount
                               possible))
----------------------------------------------------------------------
    )*?                      end of grouping
----------------------------------------------------------------------
    data-protected=          'data-protected='
----------------------------------------------------------------------
    (                        group and capture to \5:
----------------------------------------------------------------------
      ['"]?                    any character of: ''', '"' (optional
                               (matching the most amount possible))
----------------------------------------------------------------------
    )                        end of \5
----------------------------------------------------------------------
    (                        group and capture to \6:
----------------------------------------------------------------------
      .*?                      any character (0 or more times
                               (matching the least amount possible))
----------------------------------------------------------------------
    )                        end of \6
----------------------------------------------------------------------
    \5                       what was matched by capture \5
----------------------------------------------------------------------
    (?:                      group, but do not capture:
----------------------------------------------------------------------
      \s                       whitespace (\n, \r, \t, \f, and " ")
----------------------------------------------------------------------
     |                        OR
----------------------------------------------------------------------
      >                        '>'
----------------------------------------------------------------------
    )                        end of grouping
----------------------------------------------------------------------
  )                        end of look-ahead
----------------------------------------------------------------------
  (?:                      group, but do not capture (0 or more times
                           (matching the most amount possible)):
----------------------------------------------------------------------
    [^>=]                    any character except: '>', '='
----------------------------------------------------------------------
   |                        OR
----------------------------------------------------------------------
    ='                       '=\''
----------------------------------------------------------------------
    (?:                      group, but do not capture (0 or more
                             times (matching the most amount
                             possible)):
----------------------------------------------------------------------
      [^']                     any character except: '''
----------------------------------------------------------------------
     |                        OR
----------------------------------------------------------------------
      \\                       '\'
----------------------------------------------------------------------
      '                        '\''
----------------------------------------------------------------------
    )*                       end of grouping
----------------------------------------------------------------------
    '                        '\''
----------------------------------------------------------------------
   |                        OR
----------------------------------------------------------------------
    ="                       '="'
----------------------------------------------------------------------
    (?:                      group, but do not capture (0 or more
                             times (matching the most amount
                             possible)):
----------------------------------------------------------------------
      [^"]                     any character except: '"'
----------------------------------------------------------------------
     |                        OR
----------------------------------------------------------------------
      \\                       '\'
----------------------------------------------------------------------
      "                        '"'
----------------------------------------------------------------------
    )*                       end of grouping
----------------------------------------------------------------------
    "                        '"'
----------------------------------------------------------------------
   |                        OR
----------------------------------------------------------------------
    =                        '='
----------------------------------------------------------------------
    [^'"]                    any character except: ''', '"'
----------------------------------------------------------------------
    [^\s>]*                  any character except: whitespace (\n,
                             \r, \t, \f, and " "), '>' (0 or more
                             times (matching the most amount
                             possible))
----------------------------------------------------------------------
  )*                       end of grouping
----------------------------------------------------------------------
  \s*                      whitespace (\n, \r, \t, \f, and " ") (0 or
                           more times (matching the most amount
                           possible))
----------------------------------------------------------------------
  >                        '>'

Answer: Try a non-greedy named regular expression of that terminates at the next double quote instead of a greedy match
string reg = "data-screen-name=\"(?<dataScreenName>[^\"]+)\" data-name=\"(?<dataName>[^\"]+\"";

this will allow you to use
foreach(Match m in mc)
{
    users.Add(m.Groups["dataScreenName"].Value);
}

Comment: Apparently, I missed something else. The regex was not the problem, as it works with the same I posted in the question.


Java class designing

Question: I want to do a simple program called "Ticketer", where you can:

add new event with number of tickets available
assign a ticket to customer.

I am not sure how to properly Design classes.
This is what I've got so far:
Class Event
----
Name
Date
QuantityOfTickets-which is how many tickets that event have

Class EventTicket extends Event
-----------
ticket[QuantityOfTickets]-after creatting any Event class create an array of tickets for
as many as  we set up in Event class.

TicketNumber
Object Customer
+3 fields from Event (Event.Name,Event.Date and Event.QuantityOfTickets)

Class Customer
-------------
Id
FistName
LastName

Can you please tell me in if that's a good approach and guide me, in general, step by step how to do this program ?
Thank You
Comment: "Proper" is subjective and depends on your requirements.  Your simple design might be fine for a simple demonstration, but you might find that it'll be hard to extend.  That's the curse all designers live with.
Comment: yes but is it doable ? i mean when i create Object Event can I automaticly create EventTicket objects for QuantityOfTickets times ?
Comment: Anything can be done.  Your requirements aren't clear.  Personally I think this is a naive design, but I'm not going to write one for you.  Try something, test it, learn from it, refactor to correct shortcomings.  That's all anyone can do.
Answer: I recomend another structure:
Class Event
Name
Date
QuantityOfTickets (can be removed and use instead of it length of array of tickets)
EventTicket tickets[QuantityOfTickets]

Class EventTicket
TicketNumber
(and if you will need additional fields (not from Event))

Class Customer
Id
FistName
LastName
EventTicket customerTickets[QuantityOfTicketsForThisCustomer]

any questions on it?
Comment: does EventTicket needs customer field ? so i could check which tickets are not assigned to anyone ? also i have a question about customerTickets[QuantityOfTicketsForThisCustomer]-is it really needed ? I dont see where is relationship between ticket and customer assigned to ticket. Thank You .
Comment: EventTicket (in my opinion) doesn't need customet field.
To find tickets are not assigned to anyone you can check that this tickets are not in included into list of tickets for all customers, but at this case, possible will be better to has additional field at Event class

"also i have a question about customerTickets[QuantityOfTicketsForThisCustomer]-is it really needed ? I dont see where is relationship between ticket and customer assigned to ticket."

In fact customer is owner of ticket and ticket object shouldn't know anything about it, but customer should know.

Java class designing


How to prove that $P(Z_1 = j| Z_0 = i) = P(Z_{n+1} = j| Z_n = i)?$

Question: Currently I am reading this Markov Chains' notes.
At page $112,$ section $4.2$ Transition matrix, I fail to understand how author obtains the following.

As seen above, the random evolution of a Markov chain $(Z_n)_{n\in \mathbb{N}}$ is determined
  by the data of
  $$P_{i,j} := P(Z_1 = j | Z_0 = i), i, j \in \mathbb{S},$$
  which coincides with the probability $P(Z_{n+1} = j | Z_n = i)$ which is independent of $n \in \mathbb{N}.$

I do not understand how author obtains the following equality
$$P(Z_1 = j| Z_0 = i) = P(Z_{n+1} = j| Z_n = i).$$
I think Markov property might be applied here, but I do not know how.
Any hint is appreciated.
Answer: You cannot prove this. Many books consider what are called homogeneous Markov chain. For these what you are trying to prove is part of the definition. There are non-homogeneous MC's so Markov property does not imply this property.


Program accepts non-numeric input, how do I get it to stop doing that?

Question: A particular talent competition has five judges, each of whom awards a score between 0 and 10 (both 0 and 10 are considered valid!) to each performer. Fractional scores, such as 8.3, are allowed. A performer's final score is determined by dropping the highest and lowest score received, then averaging the three remaining scores.
Write a program that uses these rules to calculate and display a contestant's score. It should include the following functions:
void getJudgeData() . This function should ask the user for a judge's score, store it in a reference parameter variable, and validate it. This function should be called by main once for each of the five judges.Make the following change to void getJudgeData( ).
The function should take in 2 parameters, not 1, as specified above
The first parameter should be a string that holds the values "Judge 1", "Judge 2".. and so on.
The second parameter should follow specifications shown above.
The getJudgeData function should ensure that:
score is numeric
score is >= 0
score is <= 10
double getHighest(). This function takes in 5 scores and returns the highest of the 5 parameters passed into it.
double getLowest(). This function takes in 5 scores and returns the lowest of the 5 parameters passed into it.
Here is my code
#include <iostream>
#include <iomanip>
#include <limits>

using namespace std;

//Function prototypes
void getJudgeData(string jname, double &score);
double getAverage(double score1, double score2, double score3, double score4, double score5);
double  findLowest(double score1, double score2, double score3, double score4, double score);
double  findHighest(double score1, double score2, double score3, double score4, double score5);

int main()
{
    //Variables
    double score1, score2, score3, score4, score5, average, lowest, highest;

    //Get input from five judges
    std::cout << "Enter the scores for the five judges." << endl;
    getJudgeData("Judge 1", score1);
    getJudgeData("Judge 2", score2);
    getJudgeData("Judge 3", score3);
    getJudgeData("Judge 4", score4);
    getJudgeData("Judge 5", score5);

    average = getAverage(score1, score2, score3, score4, score5);
    lowest = findLowest(score1, score2, score3, score4, score5);
    highest = findHighest(score1, score2, score3, score4, score5);

    system("pause");
    return 0;
}

/* getJudgeData
** Function should ask the user for a judge's score, store it in a reference parameter variable, and validate it.
This function should be called by main once for each of the five judges.
*/
void getJudgeData(string jname, double &score)
{
    do
    {
        cout << "Data entry for Judge. Score must be in the range 0 - 10: ";
        cin >> score;
        if (!cin)
        {
            cout << "Invalid. Input must be numeric. Please re-enter score." << std::endl;
            cin.clear();
            cin.ignore(numeric_limits<streamsize>::max(), '\n');
        }
        else
        {
            if (score < 0 || score > 10)
            {
                cout << "Invalid. Score must be between 0 and 10. Please re-enter score." << std::endl;
            }
        }
    } while (!cin || score < 0 || score > 10);

}

/* calcScore
Function should calculate and return the average of the three scores
that remain after dropping the highest and lowest scores.
*/
double getAverage(double score1, double score2, double score3, double score4, double score5)
{
    double lowest,
        highest,
        average;

    //Find lowest
    lowest = findLowest(score1, score2, score3, score4, score5);

    //Find highest
    highest = findHighest(score1, score2, score3, score4, score5);

    //Calculate average
    average = (score1 + score2 + score3 + score4 + score5 - highest - lowest) / 3;

    //std::cout << std::setprecision(3) << "Average: " << scoreAverage << std::endl;
    cout << setprecision(3) << "Average: " << average << endl;
    cout << setprecision(3) << "Lowest: " << lowest << endl;
    cout << setprecision(3) << "Highest: " << highest << endl;

    return average;
}

//findLowest
double findLowest(double score1, double score2, double score3, double score4, double score5)
{
    //Compare and return low score
    if (score1 < score2 && score1 < score3 && score1 < score4 && score1 < score5)
    {
        return score1;
    }
    else if (score2 < score1 && score2 < score3 && score2 < score4 && score2 < score5)
    {
        return score2;
    }
    else if (score3 < score2 && score3 < score1 && score3 < score4 && score3 < score5)
    {
        return score3;
    }
    else if (score4 < score2 && score4 < score3 && score4 < score1 && score4 < score5)
    {
        return score4;
    }
    else
    {
        return score5;
    }
}

//findHighest
double findHighest(double score1, double score2, double score3, double score4, double score5)
{
    //Compare and return low score
    if (score1 > score2 && score1 > score3 && score1 > score4 && score1 > score5)
    {
        return score1;
    }
    else if (score2 > score1 && score2 > score3 && score2 > score4 && score2 > score5)
    {
        return score2;
    }
    else if (score3 > score2 && score3 > score1 && score3 > score4 && score3 > score5)
    {
        return score3;
    }
    else if (score4 > score2 && score4 > score3 && score4 > score1 && score4 > score5)
    {
        return score4;
    }
    else
    {
        return score5;
    }
}

For some reason, the program accepts non-numeric input, how do I get it to stop doing that?
Answer: Your problem is that you reset error flag of std::cin, and then check for error again in. You might change to something like:
void getJudgeData(string jname, double &score)
{
    do
    {
        cout << "Data entry for Judge. Score must be in the range 0 - 10: ";
        cin >> score;
        if (!cin)
        {
            score = -1; // Invalid value to force the loop
            cout << "Invalid. Input must be numeric. Please re-enter score." << std::endl;
            cin.clear();
            cin.ignore(numeric_limits<streamsize>::max(), '\n');
        }
        else if (score < 0 || score > 10)
        {
            cout << "Invalid. Score must be between 0 and 10. Please re-enter score.\n";
        }
    } while (score < 0 || score > 10);
}

Demo
Comment: Thanks now it seems to be working. Also is there a way I can make it so you can see which judge it's asking for input from?
Comment: `std::cout << "Data entry for " << jname << ". Score must be in the range 0 - 10: ";`


Search for used columns in Crystal Reports

Question: Background:
We have two directories of Crystal Reports for both the web side of an application and Win32 side.  Both front-ends share the same database and for the most part, the same reports....it just so happens they are in different locations.
Question:
We have to change a column in many of the reports from one to another and want to know if there is an application, technique or way to search all the reports for the existence of this column so that we know how many reports we have to change?
Answer: You may be able to make use of this project: RptToXml.
Answer: We ended up getting the report definitions done for each report (which we needed to do anyway) and save them in one area.  We then used the program available at this website: http://www.ml-consult.co.uk which is called Crystal Reports Documentor which will build us a comma delimited file in which we can search for reports that use specific columns.


Why is Jetty serving css with text/html content type

Question: I'm using an embedded Jetty server in a Scalatra app. The issue is that it serves css files with text/html content type:
Here is the main method:
package yard.web

import org.eclipse.jetty.server.Server
import org.eclipse.jetty.webapp.WebAppContext
import org.scalatra.servlet.ScalatraListener

object JettyMain {
  def main(args: Array[String]) {
    val server = new Server(9080)
    val context: WebAppContext = new WebAppContext("src/main/webapp", "/")
    context.setServer(server)
    context.setInitParameter(ScalatraListener.LifeCycleKey, "yard.web.ScalatraBootstrap")
    context.addEventListener(new ScalatraListener())
    server.setHandler(context)

    server.start()

    println("Press ENTER to stop server")
    Console.readLine()
    server.stop()
    server.join()
  }
}

The file is located at src/main/webapp/libs/bootstrap/css/bootstrap.css, and served with:
$ curl --head http://localhost:9080/libs/bootstrap/css/bootstrap.css
HTTP/1.1 200 OK
Content-Type: text/html;charset=UTF-8
Last-Modified: Sat, 06 Apr 2013 14:30:35 GMT
Content-Length: 127247
Accept-Ranges: bytes
Server: Jetty(8.1.10.v20130312)

Why is Jetty thinking it's an html file?

Here is the ScalatraBootstrap class for completeness:
package yard.web

import org.scalatra.LifeCycle
import javax.servlet.ServletContext
import yard.Settings
import yard.db.Store

class ScalatraBootstrap extends LifeCycle {
  override def init(context: ServletContext) {

    val settings = Settings.default
    val db = Store(settings).db

    context mount (new MainServlet, "/")
  }
}

Update: Using a ResourceHandler causes the css to be served with correct content type. However, the app doesn't work :(
Comment: what versions of scala and scalatra are you using?
Comment: scala 2.10, scalatra 2.2
Comment: I made a simple app with your code, same versions, and a dummy controller. I can still see the correct content type returned, as well as get the requests routed to the main controller. It may be that the problem lies elsewhere.
Answer: The CSS file is typically served from the org.eclipse.jetty.servlet.DefaultServlet.
Which is declared in the etc/webdefault.xml file in the distribution.
Since you are using embedded mode, you'll want to provide this manually by calling WebAppContext.setDefaultsDescriptor(String) with the path to your etc/webdefault.xml file.
And finally, the mime types themselves are loaded by the DefaultServlet via the mime.properties file, which is loaded by Jetty via a call to Classloader.getResource("/org/eclipse/jetty/http/mime.properties").
Note: the mime.properties file is found in the jetty-http-8.1.10.v20130312.jar file.
Comment: Doesn't matter that you have a `web.xml` or not.  The [webdefault.xml](http://git.eclipse.org/c/jetty/org.eclipse.jetty.project.git/tree/jetty-webapp/src/main/config/etc/webdefault.xml?id=jetty-8.1.10.v20130312) is still required.  Grab yourself a copy of it, modify it to suit your needs (such as removing the jsp support), get a file reference to it, and set that file reference via `WebAppContext.setDefaultsDescriptor(String)`.  This is assuming that DefaultServlet is serving your CSS file.  It could be Scala itself serving the CSS, if so, you'll need to configure Scala.
Comment: `mime.properties` is there and has the correct css line. I'm using sbt to manage the deps, btw. Using `ResourceHandler` fixes the content type, but I can't find a way to combine it with the `WebAppContext`. Also, I'm not actually using any `web.xml` file.
Comment: you are correct. The problem was that Scala was serving the css. When I added a `web.xml` with the correct settings to have `default-servlet` serve them everything worked.


query data from database base on option value

Question: i want to fetch data from database into HTML table base on below option value
  <form method="POST">
        Status
        <select class="form-control" name="selection_list">
                <option value="">All</option>
                <option value="A">A: Not Processed</option>
                <option value="B">B: Partially Processed</option>
                <option value="C">C: Completely Processed</option>
         </select>
         <input name="submit" type="submit" class="btn btn-success btn-sm" value="Generate">
    </form>

if i select "All", php will select data from table where status = "All"
if i select "A: Not Processed", php will select data from table where status = "A"
...so on
how to writing code in HTML & PHP? please help....
Answer: use an id to select field:
   <form method="POST">
            Status
            <select class="form-control" name="selection_list" id="list_id">
                    <option value="">All</option>
                    <option value="A">A: Not Processed</option>
                    <option value="B">B: Partially Processed</option>
                    <option value="C">C: Completely Processed</option>
             </select>
             <input name="submit" type="submit" class="btn btn-success btn-sm" value="Generate">
        </form>
<?php

    if($_POST['submit'])
    {
    $list_id=$_POST['list_id'];

    //write the select query you need to process with WHERE status=$list_id;

    }
?>

Comment: how php know which option that i select cause in "list_id" have may option. i want to run query one by one, mean that if i select "All" = 1 query, if i select A: Not Processed = 1 query
Answer: This is pretty basic stuff.
Official already answered it, but instead of id, you'll have to use the name attribute.
Not to mention that there are security issues with this method.


Configuring iptables when operating KVM virtual machines over a VLAN bridge

Question: I am currently setting up a virtualized environment with KVM that spans across two physical host machines (Host1 and Host2). Both are connected to the same VLAN. The network interfaces on both machines are configured like this:
auto lo
iface lo inet loopback

auto enp4s0
iface enp4s0 inet static
    address <<public-IP>>
    netmask <<netmask>>
    gateway <<gateway>>

auto enp4s0.4000
iface enp4s0.4000 inet manual
    vlan-raw-device enp4s0
    mtu 1400

auto br0
iface br0 inet static
    address 192.168.100.<<1 or 2, depending on the host>>/24
    bridge_ports enp4s0.4000

The VMs are connected to the network like this:
<interface type='bridge'>
  <mac address='52:54:00:91:64:64'/>
  <source bridge='br0'/>
  <model type='virtio'/>
  <address type='pci' domain='0x0000' bus='0x00' slot='0x03' function='0x0'/>
</interface>

and:
auto ens3
iface ens3 inet static
    address 192.168.100.<<101 or 102, depending on the VM>>/24
    gateway 192.168.100.<<1 or 2, depending on the host>>

So far, everything works pretty well. From the VMs, I can ping both hosts as well as all other VMs across both machines. I can also access the internet, now that I have enabled NAT by adding the following iptables-rule:
iptables -t nat -A POSTROUTING -o enp4s0 -j MASQUERADE

But now comes the problem: even though I can ping all hosts on the VLAN from any machine on the VLAN, I cannot seem to connect to TCP services running inside the VMs properly. Here are my observations:

From Host1, I can access the web server in VM1 (running on Host1).
From Host2, I can access the web server in VM2 (running on Host2).
From VM1 (running on Host1), I CANNOT access the web server in VM2 (running on Host2) and vice versa (the connection seems to time out, I am not getting connection refused).
From Host1, I CANNOT access the web server in VM2 (running on Host2) and vice versa (again, the connection seems to time out).
Also, using netcat, I have figured out that I CANNOT access TCP services on Host1 from Host2 (again, the connection seems to time out).

What really surprises me is that ping works, but curl does not. To me (being not very experienced in networking), it seems like this is probably some sort of configuration problem with iptables. This is how iptables is set up currently on both hosts (running  and iptables -t nat -L -nv:
Output of iptables -L -nv:
Chain INPUT (policy ACCEPT 31 packets, 3143 bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain FORWARD (policy ACCEPT 5 packets, 520 bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain OUTPUT (policy ACCEPT 23 packets, 4089 bytes)
 pkts bytes target     prot opt in     out     source               destination

Output of iptables -t nat -L -nv:
Chain PREROUTING (policy ACCEPT 19 packets, 1313 bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain INPUT (policy ACCEPT 6 packets, 352 bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain POSTROUTING (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination
   13   961 MASQUERADE  all  --  *      enp4s0  0.0.0.0/0            0.0.0.0/0

Chain OUTPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination

I have even tried using tcpdump while attempting to establish a netcat connection between Host1 (nc -l 4444) and Host2 (nc 192.168.100.2 4444). There seems to be no traffic getting through.
This is how iptables is set up on the VMs:
Output of iptables -L -nv:
Chain INPUT (policy ACCEPT 31 packets, 3143 bytes)
 pkts bytes target     prot opt in     out     source               destination
    6   399 ACCEPT     tcp  --  *      *       0.0.0.0/0            0.0.0.0/0   tcp dpt:80 ctstate NEW,ESTABLISHED

Chain FORWARD (policy ACCEPT 5 packets, 520 bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain OUTPUT (policy ACCEPT 23 packets, 4089 bytes)
 pkts bytes target     prot opt in     out     source               destination
    4  1066 ACCEPT     tcp  --  *      *       0.0.0.0/0            0.0.0.0/0   tcp spt:80 ctstate ESTABLISHED

Output of iptables -t nat -L -nv:
Chain PREROUTING (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain POSTROUTING (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain OUTPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination

I have been working on this for two days now and I can't seem to figure it out. Any help would be greatly appreciated.
Comment: whats your target With the vlan? what Benefiz you think to gain if you use it?
Comment: I'm renting both host servers from an online provider that gives them one free public IP. If you want them together in an internal network (which i obviously need, because I'm running distributed internal services on the machines), they give you the option of putting them together in a VLAN for you. Both servers now have their public IPs, but they are also part of the virtual network ```192.168.100.0/24```and have private IP addresses in that network (```192.168.100.1``` and ```192.168.100.2```).
Comment: ok, now we get one point closer, however we still need that you update your question with the /etc/network/interfaces by seperated from the both servers used iptables rules because in my point of thinking both should use the same gateway but in my point of view, would it not be easier to create a pptp or openvpn s2s vpn?
Answer: I have just figured out the problem myself. While I was writing a support ticket to my hosting provider, I thought about the additional firewall they offer. I assumed it only covered the public IP and not the private subnet on the VLAN. However, after turning that firewall off, everything now works as expected!


What is standard tuning for twelve string guitar?

Question: I'm aware of a few different methods for tuning up a twelve string guitar.What is standard tuning for an acoustic twelve string guitar? Which pairs are tuned in unison and which pairs are tuned an octave apart?
Comment: [**_How do I ask a good question?_**](https://meta.stackexchange.com/help/how-to-ask) : _Search, and research

Have you thoroughly searched for an answer before asking your question? Sharing your research helps everyone. Tell us what you found and why it didn't meet your needs. This demonstrates that you've taken the time to try to help yourself, it saves us from reiterating obvious answers, and above all, it helps you get a more specific and relevant answer_
Comment: @Stinkfoot - said in such an erudite way! This question really should not appear here.
Comment: @Tim:  Thanks - but I didn't write it! The bold is a link to the subject in  SExchange's guidelines for Q & A. This question also qualifies as a "google it" question, also mentioned up there.
Comment: @Stinkfoot Remember that questions that can be answered with a quick web search are actually **not** discouraged on Stack Exchange. In fact, part of the purpose of Stack Exchange is to be one of the top hits on such a web search. There have been conversations on the SE meta about this.
Comment: @Stinkfoot See in particular https://meta.stackexchange.com/questions/8724/how-should-we-deal-with-google-questions and the linked questions. We are asked specifically not to criticize questions on the basis of how easy they may be to answer with a web search.
Comment: @ToddWilcox -  not exactly what it says up there. And note my citation in my first comment, which comes not from Meta QA's, but from the SO help center. Tnx
Comment: @Stinkfoot It's entirely possible I'm wrong in thinking that meta discussions refine and even override guidance in the help center. The top voted answer to the question I linked say "do not tell them to Google it". While you didn't write exactly that, your quote seems to me to imply that you are suggesting the asker should have done a web search rather than ask here. Further note this question is a duplicate of a question with a positive score.
Comment: @ToddWilcox : First words in the answer you cited: _Either answer nothing..._ . I answered nothing - simply cited the question guidelines in a comment. Whatever... more important things to worry about.
Comment: @ToddWilcox - given that this question is a duplicate, why hasn't that been noted with a close? It would also appear that several agree that it's not a good question for here, although I agree that in a google search this site should be a good place to find answers to questions such as this.
Comment: There is an old saying that goes" the only foolish question is the one that goes unasked". Makes good sense to me. And thanks for the answer to my question. I didn't mean to cause such a stink!
Answer: The E A D and G strings are tuned in octaves, the B and e strings are in unison.


How to avoid processing HTML outside of the template for Joomla components?

Question: I create my own component in Joomla 3.x
I have a functionnal Ajax call like this :
file.js
jQuery.ajax({
  type: 'post',
  data: 'topo_id=' + idTopo,
  url: 'index.php?option=com_mycomp&task=getMyData&format=json',
  datatype: "json",
  success: function(res) {
    console.log(res);
    jQuery('#resultDiv').html(res.data);
},
error: function (e) {
  console.log(e);
}})

controller.php
function getMyData(){
  $mydataSQL = $MyClass->getMyData($param); //
  $mydataHtml = $this->formatHtml($mydataSQL);  // to replace div content with ajax
  echo new JResponseJson($mydataHtml);
}
function formatHtml(MyClassFoo $foo) {
  $html ='
' . $foo->bar . '
';
  $html .= '
' . $foo->foo .'
';
  ...... and more html code here
  return $html
}

I'd like to use the result ($myData = result PDO::FETCH_CLASS) in a view. ($mydataSQL->name, $mydataSQL->address...) to avoid processing the html in the controller function.
I tryed without success a call like this : ...&format=raw&view=newview.
Comment: there is no variable like `$mydata` getting any valuue in the current function then why are you returning the same variable in `JResponseJson` ? Is it by mistake or what ? Could you please write in more detail what you want to do with returned value ?
Comment: @SudhirSapkal Sorry typo. I updated the question. I wan't to use the json response in a joomla view and not in my controller (function formatHtml)
Answer: What you want here is to use a layout.
https://docs.joomla.org/J3.x:Sharing_layouts_across_views_or_extensions_with_JLayout
in your controller
private function formatHtml(MyClassFoo $foo)
{
   $layout      = new JLayoutFile('path.to.layout');
   $data = array('foo' => $foo);

   return $layout->render($data);
}

and in layouts/path/to/layout.php (or templates/#current template#/html/layouts/path/to/layout.php)
<?php
defined('JPATH_BASE') or die;

$foo = $displayData['foo'];
?>

<?= $foo->bar ?>

<?= $foo->foo ?>

and more...

Comment: You are rather attentive to Joomla questions on StackOverflow.  I hope you will extend your volunteership to joomla.stackexchange too.  (good help can be hard to find)
Comment: sure, i'll check it out sometimes as well.


Prove that $2AK=BP+PC$ in isosceles triangle.

Question:
Let $ABC$ is isosceles triangle. $AB=AC$. Point $P$ such that $\angle BPC=2\angle BAC$. $PK$ is bisector of $\angle BPD$ and $AK \perp PK$. Prove that $$2AK=BP+PC$$

My attempts:
Let point $A'$ and $B'$ such that $AK=KA'$ and $PB=PB'$. Then need prove that $AA'=B'C$.
This is equivalent to proving that the $ACA'B'$ is an isosceles trapezoid.
I dont know how use that $\angle BPC=2\angle BAC$ and $AB=AC$
Answer: Because $∠BPC = 2∠BAC$ and $∠DPK = ∠FPK \Rightarrow ∠FDP = ∠DFP$, then $$∠FDP = ∠DFP = \frac{1}{2} ∠BPC = ∠BAC.$$
Therefore,\begin{gather*}
∠ABF = ∠DFP - ∠BAF = ∠BAC - ∠BAF = ∠CAD,\\
∠BAF = ∠BAC - ∠CAD = ∠FDP - ∠CAD = ∠ACD.
\end{gather*}
Since $BA = AC$, then$$
△ABF ≌ △CAD. \quad \text{(ASA)}
$$
Note that $DP = FP$ and $DK = KF$, thus$$
BP + PC = BF + CD = AD + AF = 2AK.
$$


Compare DateTime with milliseconds in LINQ

Question: I am building a windows service that fetches data from an SQL Database and stores them in a .txt file every 5 minutes. What I am trying to do is every 5 minutes when my service checks the database, it should check the last datetime record on the txt file and find it in the database. If it finds the same datetime, it should fetch all the newer records after that datetime. I am trying to be as precise as possible and not miss a records, so I thought it would be a good idea to compare the milliseconds of each date. This is what I have so far, but I know that x.Datetime, which is of type DateTime, does not fetch the milliseconds along with the date. "lastDate" is the date I fetch from the txt file with milliseconds added to it.
dbData = db.Table.Where(x => x.Datetime < lastDate).ToList();

Also, the column on the database has milliseconds stored with the datetime.
Comment: "does not fetch the milliseconds", what exactly do you mean by this? Fetch how, and from where? If the two DateTime values that are being compared have millisecond values, they will for sure be part of the comparison.
Comment: try to look [here](https://learn.microsoft.com/en-us/dotnet/standard/base-types/how-to-display-milliseconds-in-date-and-time-values)
Comment: Are  you sure this isn't just formatting?
Comment: DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss.fff tt")
Comment: I got my comment exactly where @Ben.S told you so :)
Comment: `dbData = db.Table.Where(x => x.Datetime < lastDate).ToList();` will get you all entries **before** (as in "older than") `lastDate`. Like "2020-06-01" < "2020-12-31"
Comment: Sorry, I wasn't clear enought. What I was trying to say is that eventhough the x.Datetime, which is fetched from the db, has milliseconds in its column on the database (here's an example "2020-12-10 12:08:00.200"), when I check the value of x.Datetime on the program x.Datetime only holds 14/12/2020 13:56:47 without the milliseconds.
Comment: A Tick is 100ns.  There is a constant TimeSpan.TicksPerSecond .  So 5 minutes is 300 seconds.  So if you divide the Tick value by 300 * TimeSpan.TicksPerSecond you will get dates to be in 5 minute groups.
Comment: @jdweng But then you are prone to miss singular or have duplicate rows due to rounding. I am with Gert's suspicion, OP is simply not _seeing_ millis because of default formatting in the IDE. _And_ OP is using the wrong operator.
Comment: @Fildor : I depends on the requirements.  Normally you will sample quicker than the 5 minutes and then average the values.  But you always can have the case where the data changes right on the edge of the 5 minute period.  that is why you normally sample in the middle of the 5 minute range.   so to be more robust you can add a 2 1/2 minute offset.
Comment: Is it an option to include a unique incremental id in the query, and also write it in the text file, so that you can keep the file in sync with the database, without the risk of missing any records?
Comment: @jdweng. Yes, "normally". But that doesn't seem to be what OP is doing.
Comment: @Fildor : It is what the OP wants.
Answer: So the rows in your table have a property Datetime. You only want to fetch rows that you haven't fetched before and you don't want to miss any rows.
The problem is, that as soon as your query returns, new rows might already be added. So before you process the fetched data at millisecond X, new data might already be added
It would be better to remember the DateTime of the last added row:
private DateTime lastFetchedDate = ...

Call the following procedure every few minutes:
private void FetchAndProcessNewData()
{
     var dbData = db.Table.Where(row => row.Datetime > lastFetchedDate)
                .OrderByDescenting(row => row.DateTime)
                .ToList();
    if (dbData.Any())
    {
        ProcessFetchedData(dbData);
        lastFetchedDate = dbData[0].DateTime;
    }
    // else: no new rows; nothing to process, no new lastFetchedDate needed
}

It is a bit of a waste to order all rows. A small optimization would be to not order the list, but calculate the max DateTime. This way you do'll only have to enumerate the fetched data once
lastFetchedDate = dbData.Select(row => row.DateTime).Max();

There is no Max for DateTimes, but the extension method is fairly easy to create. If you are not familiar with Extension methods, see extension methods demystified
public static DateTime Max(this IEnumerable<DateTime> source)
{
    // TODO: exception if source == null
    var enumerator = source.GetEnumerator();

    // initialize the first DateTime as the largest:
    if (enumerator.MoveNext()
    {
        var max = enumerator.Current;

        // enumerate the rest:
        while (enumerator.MoveNext())
        {
            if (enumerator.Current > max)
                max = enumerator.Current;
        }
        return max;
     }
     // else: empty source. Decide what to do: exception? return DateTime.MinValue;
}

Usage:
var dbData = db.Table.Where(row => row.Datetime > lastFetchedDate).ToList();
if (dbData.Any())
{
    ProcessDbData(dbData);
    this.lastFetchedData = dbData.Select(row => row.DateTime).Max();
}


Show any two matrices that commute with M also commute with eachother

Question: This is a proof where
$$M=\pmatrix{0&1\\-1&0}\;.$$
I've tried looking at it in terms of $A$ and $B$ like $AM=MA$ and $BM=MB$ but the snag is that I can't really get rid of $M$ to make $A=B$ so I'm not sure if I have the complete wrong idea or if there is a completely different way of doing it.
Comment: Hint: You're not trying to show $A=B$ just that $AB = BA$. Does that help?
Answer: HINT: Let
$$A=\pmatrix{a&b\\c&d}\;.$$
Then
$$AM=\pmatrix{a&b\\c&d}\pmatrix{0&1\\-1&0}=\pmatrix{-b&a\\-d&c}\;,$$
and
$$MA=\pmatrix{0&1\\-1&0}\pmatrix{a&b\\c&d}=\pmatrix{c&d\\-a&-b}\;.$$
If these are equal, what does that tell you about $a,b,c$, and $d$? The same argument applies to $B$. Knowing the general form that $A$ and $B$ must have, try to show by actual computation that they commute.


$A:X \to Y$- linear continuous function, $A\neq 0$ $H=\ker A\implies \exists z \in H^{\bot}: \|z\|=1$

Question: $A:X \to Y$- linear continuous function, $A\neq 0$ $H=\ker A, X=H\oplus H^{\bot}\implies \exists z \neq 0 \in H^{\bot}: \|z\|=1$
This implication is confusing to me, here in the book it says in brackets: Since $A$ is continuous $A^{-1}(0)$ is closed (this fact i understand), how this conclusion($\implies \exists z \neq 0 \in H^{\bot}: \|z\|=1$) I frankly do not understand.
Answer: I assume $X$ is a Hilbert space.
We only need $H^\perp\ne\{0\}$, as if it contains any nonzero $z_0$ vector, we can take $z:=\displaystyle\frac{z_0}{\|z_0\|}$.
And, in case of Hilbert spaces, $H^\perp\ne\{0\}\ \iff\ \bar H\ne X$ where $\bar H$ is the closure of $H$, and it happens to be $\bar H=H^{\perp\perp}$.
If $A$ was not continuous, still $A\ne 0$, then $H=\ker A$ might be dense, and then $H^\perp=\{0\}$.


nwjs app javascript protection?

Question: So nwjs is a neat little framework that enables node apps to run in desktop mode independent to platform. But the way I package my files is pretty raw.
I zip my node app directory into a .nw file, and I copy it to an existing nwjs app's content folder. Then this means that anyone with some knowledge of nwjs will be able to literally unzip the .nw file and dig through the app directory. WTF. Is there a way to protect my files in my nwjs app?
Comment: @jfriend00 um no this has nothing to do with web development or any of your proposals, you can compile JavaScript to binary and as Mike0 described in his answer, the downside of 30% perfermance degrees has to be accounted for. It's like compiling anything to binary that can be decompiled and as a _hacker_ (whoever you mean using that terminology) you only get a certain percentage of the original code which in the end, is pretty useless.
Answer: You can compile the javascript files with snapshot:
<code> nwjc source.js binary.bin
</code>
then load the compiled js in your app like this
<code> require('nw.gui').Window.get().evalNWBin(null, 'binary.bin');
</code>
for more info, check  this out.
Comment: performance issues resolved per https://nwjs.io/blog/js-src-protect-perf/

nwjs app javascript protection?


Why do I get #N/A's when using VLookup in VBA to reference another Excel file?

Question: I'm trying to program a VLookup in VBA that references another workbook. Basically I'm trying to vlookup across 2 workbooks.
Here is a simple outline of my goal:

Look up values in all rows in column A of workbook1
Pull the information in from column A (values that correspond to Column A in workbook1) and Column C (values to be copied) of workbook2 and place in column B of workbook1 in the corresponding cells (rows). Additional conditions: (1) if there are already values in the cells, overwrite and (2) if no value has been found for a cell, then keep cell unchanged. So also no #N/A.
Move on and repeat the process until there are no more entries left in column A of workbook1

Below is the code that I already have. I stumble upon the fact that the code does not work. I keep getting #N/As for each row in column B, while there should at least be some values found and pasted into some cells. For testing purposes, I copied the reference table in workbook2 to a worksheet in workbook1 and when I reference to that specific worksheet in the same workbook1 then the code seems to work.
Sub Import()

Dim rw As Long, x As Range
Dim extwbk As Workbook, twb As Workbook

Set twb = ThisWorkbook
Set extwbk = Workbooks.Open("C:\Documents\workbook2.csv")
Set x = twb.Worksheets("Sheet1").Range("A1:H100")

With twb.Sheets("Sheet1")

     For rw = 2 To .Cells(Rows.Count, 1).End(xlUp).Row
         .Cells(rw,2) = Application.Vlookup(.Cells(rw,1).Value2,x,3,False)
     Next rw

End With

End Sub

Do you see an error in my code? Or does anyone have a better way of accomplishing this task? Preferably, I also would like to open a selected file instead of referring to a full path.
Thanks in advance!
Comment: Please, try formatting both ranges which are compared **in the same way**. The best formatting, in such a case, would be to use TextToColumns (from Data)...
Comment: @FaneDuru while the extensions differ, the formatting is the same
Answer: Maybe try this:
    For ...
         on Error Resume Next
         .Cells(rw, 2).Value = WorksheetFunction.Vlookup(.Cells(rw,1).Value, x, 3, False))
    Next ...

But if I got you right "x" is the range where you search for a value AND it is defined as a range on the same sheet. So the ranges overlap!?
Comment: yes, but in your code it happens all in the same workbook. x is also defined as range in twb (= workbook1!?). than you should adjust the reference to "extwbk"
Comment: @stephie you are right! It now works as it supposed to do!
Comment: x is the range in which the vlookup should operate, right? So x includes column A to column H of workbook2. Column A of workbook2 contains the same values as column A of workbook1, and Column C (third column) contains the values which should be copied depending on the lookup.
Comment: This seems to work!  I now can get values pasted in the cells in which the vlookup finds matches. However, how can I get rid of the #N/A's whenever no match is found? I would like to keep the cells in which no match is found unchanged from being overwritten with #N/A
Comment: If this is working, then change `.Value2` to `.Value` in your original code and see what happens.
Comment: @Jonathan We *can't* reproduce this so please include some sample data.
Comment: You should no get a #N/A!? Maybe you didn't delete old values from previous runs? The code I wrote above will only write a new value if vlookup found something. so no entry if vlookup found nothing.
Answer: Possibly because this line:
Set x = twb.Worksheets("Sheet1").Range("A1:H100")

is referencing the wrong workbook. It should be:
Set x = extwbk.Worksheets("Sheet1").Range("A1:H100")

Handling N/A Values
Try code like this in your loop:
For rw = 2 To .Cells(Rows.Count, 1).End(xlUp).Row
        If Application.IsNA(Application.VLookup(.Cells(rw, 1).Value2, x, 3, False)) Then
            .Cells(rw, 2) = "NOT FOUND"
        Else
            .Cells(rw, 2) = Application.VLookup(.Cells(rw, 1).Value2, x, 3, False)
        End If

     Next rw

Replace "NOT FOUND" with whatever you want displayed, or just "" if you want an empty cell
Comment: ! I now can get values pasted in the cells in which the vlookup finds matches. However, how can I get rid of the #N/A's whenever no match is found? I would like to keep the cells in which no match is found unchanged from being overwritten with #N/A


When playing a bass part on piano do you play it in the right octave or one octave up as written?

Question: I am learning to play a song on the piano which shows the guitar chords, bass guitar notation as well as the piano notation. As usual, the bass guitar part is written one octave higher than what the bass guitar is playing. For example, the low E on a 4 string bass is notated just below the bass clef when actually that is the second E on the bass guitar (Low E string on a normal guitar)
If I am learning to play the song and want a real authentic understanding of the arrangement of the song, should I transpose the bass part to its proper octave or does it not matter?
Comment: Does it actually have a separate bass part on an extra stave or just a double stave piano part?
Comment: Bottom line (no pun intended) the bass is an octave transposing instrument as mentioned by @Tim. The other issue is: is this a rendition created for publication or is it the actual arrangement? Published lead sheets often have a "piano arrangement" in the grand staff that has nothing to do with what is on the recording.. When I arrange I sometimes write the bass in a specific octave because that's where I want it so if you want to understand this play it where it's supposed to be but consider the difference in timbre between a bass and a piano (or play the bass using a sampler).
Comment: there is a stave for each instrument in this case but my question applies to the grand staff too.
Answer: Notation for bass (and guitar) is written one octave higher than it sounds, due to the fact that most of the notes involved are more easily read on the stave lines and spaces than they would if written on mainly ledger lines. If the sheet is written using the grand clef, as in bass and treble for piano, then usually we play the actual notes.
If there's a small 8 attatched to the bass clef, so in fact it is written for bass guitar, it is intended that the notes are played an octave lower.
By listening to recordings, you'll have a better idea as to which octave was used in them, although just by playing both ways, you'll be the judge. Some pieces will benefit from playing the bass part in octaves, so you'll cover both options when playing that way.
The 'bottom line' is - use your ears, both to listen to what others do, and to what you play, and make the decision based on that. You may even mix and match.
Comment: Isn't the bass-clef-with-small-8-below technically a different clef from the normal bass clef, i.e. a suboctave bass clef with the dot marking F2 (instead of F3)?  So it's not just indicating an _intent_; the notes are actually _written_ an octave lower, due to the clef.
Comment: @gidds - won't the notes be *played* a octave lower, not *written* an octave lower?
Answer: I you are just trying to understand the arrangement it doesn't matter where you play the bass line. If you want it to sound in the same octave as the bass  then you need to play it an octave lower. But a piano low register doesn't have the weight of an electric bass, you might find it sounds better playing the bass line in octaves. It might sometimes sound better playing the bass line as written (i.e. sounding an octave too high)
Comment: @armani I wouldn't say "dissonant", I would say that the harmonic intervals sound more "muddy"
Comment: THank you. But won't some harmonic intervals become more dissonant the lower you go on the piano?
Comment: @armani If they sound too dissonant down low, play them an octave higher.


Should I rate-limit packets with iptables?

Question: I'm using iptables on Ubuntu Server. It's a web server on a VPS.
I'd like to know if I should rate-limit packets. If so, what should I rate-limit? And should I do so globally or per IP address?
Reference
I saw people suggesting this:
<code># Limit packet traffic on a TCP or UDP port:
iptables -A INPUT -p $proto --destination-port $port --syn -m state --state NEW -m limit --limit $lim/s --limit-burst $lb -j ACCEPT

# Limit established/related packet traffic:
iptables -A INPUT -m state --state RELATED,ESTABLISHED -m limit --limit $lim/s --limit-burst $lb -j ACCEPT
</code>
The above, a global rate-limit don't seem very useful, at least for the cases I can imagine. Is there any case where I should rate-limit globally?
I believe that a rate-limit per IP is usually better:
<code># Add the IP to the list:
iptables -A INPUT -p $proto --destination-port $port --syn -m state --state NEW -m recent --set --name RATELIMITED
# Drop if exceeded limit:
iptables -A INPUT -p $proto --destination-port $port --syn -m state --state NEW -m recent --update --seconds $sec --hitcount $hc --rttl --name RATELIMITED -j DROP
# Accept if inside limit:
iptables -A INPUT -p $proto --destination-port $port --syn -m state --state NEW -j ACCEPT
</code>
Additional question: Remote IPs may be spoofed. How to limit them properly?
Added another question for this:
https://serverfault.com/questions/340258/how-to-rate-limit-spoofed-ips-with-iptables
The goal
I'm trying to mitigate the risk of some D/DoS attacks and general abuse.
Related
How can I rate limit SSH connections with iptables?
PS: I have just opened a related question just for ICMP and it includes rate-limiting for this protocol: iptables | Types of ICMP: which ones are (potentially) harmful?
Answer: A rate limit is not a prevention but rather an invitation to DoS - especially in the flavor presented above where packets are going to be dropped if a certain rate of unauthenticated packets without state information has been exceeded. Since everybody can forge packets (including source IP addresses) at this connection state without greater effort, a new DoS attack vector leveraging your rate limit facility will arise.
A rate limit generally will only make sense if you have

either a predictable hard or a soft connection limit in your configuration
set the rate limit for general traffic below this limit in order to be able to set up connections for priority or administrative traffic regardless of the load

While 1. often is hard enough to determine to even bother, 2. will obviously only work if you are able to reliably differentiate "priority or administrative" traffic from the rest upon connection setup - e.g. if it is coming through a different network interface.
In other cases, it would rather reduce your system's resiliency than add to it.
Comment: Hi syneticon-dj. I undestand and agree that a misconfigured firewall is another tool for a DoS attack. Thanks for the heads up!
Comment: Per-ip or per-ip-port rate limiting also seems to make sense when defending from legitimate traffic that is too massive for one's server but whose originator isn't likely to exploit the problem you mention, say, abusive behaviour from the Bingbot or Facebook bots.
Answer: The problem with -m limit is the limitation of all TCP packets whatever the source IP addresses. So, if you have a low limitation for syn packets like
<code>-A INPUT -p tcp  --syn -m limit --limit 30/s --limit-burst 30 -j ACCEPT
-A INPUT -p tcp --syn -j DROP
</code>
only one client with the hping command line can take down your server by sending as many tcp packets with SYN flag because the limit rule will match and it will drop many packets whatever the sources IP addresses. limit does not make difference between good traffic and bad traffic. It will take the down the good incoming traffic too.
hping could be something like:
<code>hping thetargetedhostip -p 80 -S -c 1000 -i u20000
</code>
It is better to use hashlimit to limit incoming tcp connections per IP address. The following rule will match only if 30 packets per seconds will be received reducing the number of authorized packet per IP to 15 packets per second.
<code>-A INPUT -p tcp --syn -m hashlimit --hashlimit 15/s --hashlimit-burst 30 --hashlimit-mode srcip --hashlimit-srcmask 32 --hashlimit-name synattack -j ACCEPT
-A INPUT -p tcp --syn -j DROP
</code>
In Fact, I am CONVINCED that many servers that are taken down today aren't taken by being out of resources during an attack but because of the limit module dropping all the incoming traffic.
Answer: I typically limit rate limiting rules to servers that I expect to have:

low amounts of expected traffic
authentication services

For example, a hosting control panel's login page, POP3, IMAP, SSH, etc.  I usually leave HTTP services wide open and only block if there is an issue.
You do not want to drop good web traffic.  A link on slashdot could send you tons of traffic and with global rules, you may not realize an issue.
With regard to spoofed IPs, they cannot be blocked using this method and are typically not a concern since these rules mainly focus on limiting established TCP connections.  With a spoof IP the TCP connection can never be established.
Comment: Hi jeffatrackaid, thanks for your answer!
I'm inclined, too, to rate-limit (globally) these types of services (SSH etc).
Regarding HTTP traffic, that's why I don't intend to apply a global limit. In this question I expect to see whether there are cases when a limit per IP can be interesting.
Regarding spoofed IPs (I opened a separated question on that) although connections can't be established, there's the possibility of a DoS by using a SYN flood. I remain interested in hearing how this could be mitigated.


RSpec let method not generating variable

Question: I'm trying to create a test for my bill_total helper method. The let method isn't generating the bill1 and bill2 variable.
describe BillsHelper do
  let(:bill1) { Bill.create(name: 'Bill 1', amount: 1.00) }
  let(:bill2) { Bill.create(name: 'Bill 2', amount: 1.00) }

  describe "#bill_total" do
    bill1.amount = 1.00
    bill2.amount = 1.00

    expect(bills_helper.bill_total).to eq(2.00)
  end
end

Error:
    /Users/adrianleeelder/Documents/Developer_Resources/sites/bills_app/spec/helpers/bills_helper_spec.rb:18:in `block (2 levels) in <top (required)>': undefined local variable or method `bill1' for #<Class:0x007fb3c121b548> (NameError)
    from /Users/adrianleeelder/.rvm/gems/ruby-2.0.0-p0/gems/rspec-core-2.13.1/lib/rspec/core/example_group.rb:242:in `module_eval'
    from /Users/adrianleeelder/.rvm/gems/ruby-2.0.0-p0/gems/rspec-core-2.13.1/lib/rspec/core/example_group.rb:242:in `subclass'
    from /Users/adrianleeelder/.rvm/gems/ruby-2.0.0-p0/gems/rspec-core-2.13.1/lib/rspec/core/example_group.rb:228:in `describe'
    from /Users/adrianleeelder/Documents/Developer_Resources/sites/bills_app/spec/helpers/bills_helper_spec.rb:17:in `block in <top (required)>'
    from /Users/adrianleeelder/.rvm/gems/ruby-2.0.0-p0/gems/rspec-core-2.13.1/lib/rspec/core/example_group.rb:242:in `module_eval'
    from /Users/adrianleeelder/.rvm/gems/ruby-2.0.0-p0/gems/rspec-core-2.13.1/lib/rspec/core/example_group.rb:242:in `subclass'
    from /Users/adrianleeelder/.rvm/gems/ruby-2.0.0-p0/gems/rspec-core-2.13.1/lib/rspec/core/example_group.rb:228:in `describe'
    from /Users/adrianleeelder/.rvm/gems/ruby-2.0.0-p0/gems/rspec-core-2.13.1/lib/rspec/core/dsl.rb:18:in `describe'
    from /Users/adrianleeelder/Documents/Developer_Resources/sites/bills_app/spec/helpers/bills_helper_spec.rb:13:in `<top (required)>'
    from /Users/adrianleeelder/.rvm/gems/ruby-2.0.0-p0/gems/rspec-core-2.13.1/lib/rspec/core/configuration.rb:819:in `load'
    from /Users/adrianleeelder/.rvm/gems/ruby-2.0.0-p0/gems/rspec-core-2.13.1/lib/rspec/core/configuration.rb:819:in `block in load_spec_files'
    from /Users/adrianleeelder/.rvm/gems/ruby-2.0.0-p0/gems/rspec-core-2.13.1/lib/rspec/core/configuration.rb:819:in `each'
    from /Users/adrianleeelder/.rvm/gems/ruby-2.0.0-p0/gems/rspec-core-2.13.1/lib/rspec/core/configuration.rb:819:in `load_spec_files'
    from /Users/adrianleeelder/.rvm/gems/ruby-2.0.0-p0/gems/rspec-core-2.13.1/lib/rspec/core/command_line.rb:22:in `run'
    from /Users/adrianleeelder/.rvm/gems/ruby-2.0.0-p0/gems/rspec-core-2.13.1/lib/rspec/core/runner.rb:80:in `run'
    from /Users/adrianleeelder/.rvm/gems/ruby-2.0.0-p0/gems/rspec-core-2.13.1/lib/rspec/core/runner.rb:17:in `block in autorun'
[Finished in 2.4s with exit code 1]

Answer: The names defined in let statements are only available within before and it blocks, not within the outer level of the describe blocks.  If you replace your inner describe with it, the names will be accessible. Also, the names are not actually variables, but helper methods.
Answer: You need to write your examples inside it blocks, not describe blocks:
it "#bill_total" do
  bill1.amount = 1.00
  bill2.amount = 1.00

  expect(bills_helper.bill_total).to eq(2.00)
end


Under what conditions asymptotic equivalence can hold after composition?

Question: Let define the equivalence relation $$f\sim_\alpha g:\iff\lim_{x\to\alpha}\frac{f(x)}{g(x)}=1$$
Suppose we have two functions $f$ and $g$ and a continuous function $h$. Under what conditions we can says that $f\sim_\alpha g\implies(h\circ f)\sim_\alpha(h\circ g)$?
This question comes from this example: let $f(x):=\frac{\sqrt{x^2+x+1}}x$, then $f\sim_\infty g$ for $g(x):=1$ but $\ln f\not\sim_\infty \ln g$.
If there is some textbook or reference about this kind of questions related to the above equivalence relation I will be glad to know it.
Answer: First of all, your example is kind of silly since $\ln g$ is identically $0$ and so $\ln f/\ln g$ is simply never defined.  Obviously, if $h(x)$ can be $0$, you can get similar silly counterexamples by letting $g$ be such that $h(g(x))$ is always $0$.  However, you can get a less silly example for $h(x)=\ln x$ by choosing $g$ to approach $1$ very fast without actually being equal to $1$, so $\ln g$ will be much closer to $0$ than $\ln f$.
With this in mind, let me assume that $h(x)$ is always positive, or at least is always positive on the images of $f$ and $g$ in a neighborhood of $\alpha$.  I will also assume for convenience that $f$ and $g$ are positive in some neighborhood of $\alpha$, so we may consider $h$ as a function $A\to(0,\infty)$ for some $A\subseteq(0,\infty)$ containing the images of $f$ and $g$ near $\alpha$ (this is no real loss of generality, since if $f\sim_\alpha g$ then $f$ and $g$ have the same sign in some neighborhood of $\alpha$).  Define a function $h'$ by $h'(x)=\log(h(\exp x))$.  Then I claim $f\sim_\alpha g$ always implies $h\circ f\sim_\alpha h\circ g$ iff $h'$ is uniformly continuous on its domain $\{x:\exp x\in A\}$.
Indeed, suppose $h'$ is uniformly continuous.  Suppose $f\sim_\alpha g$, and fix $\epsilon>0$.  Choose $\delta_0>0$ such that if $|x|<\delta_0$, $|\exp(x)-1|<\epsilon$.  Choose $\delta_1>0$ such that if $|x-y|<\delta_1$, then $|h'(x)-h'(y)|<\delta_0$.  Choose $\delta_2>0$ such that if $|x-1|<\delta_2$, $|\log x|<\delta_1$.  Finally, let $U$ be a neighborhood of $\alpha$ such that if $x\in U$, then $\left|\frac{f(x)}{g(x)}-1\right|<\delta_2.$
Now if $x\in U$, we have $$\left|\frac{f(x)}{g(x)}-1\right|<\delta_2$$ which implies $$|\log f(x)-\log g(x)|=\left|\log\frac{f(x)}{g(x)}\right|<\delta_1$$ which implies $$|\log(h(f(x)))-\log(h(g(x)))|=|h'(\log f(x))-h'(\log g(x))|<\delta_0$$ which implies $$\left|\frac{h(f(x))}{h(g(x))}-1\right|=|\exp(\log(h(f(x)))-\log(h(g(x))))-1|<\epsilon.$$ Since $\epsilon>0$ was arbitrary, this means $h\circ f\sim_\alpha h\circ g$.
Conversely, suppose $h'$ is not uniformly continuous.  Then for some $\epsilon>0$, there exist sequences $(x_n)$ and $(y_n)$ such that $|x_n-y_n|\to 0$ but $|h'(x_n)-h'(y_n)|>\epsilon$ for all $n$.  Choosing $f$ and $g$ such that $\log f(x)=x_n$ and $\log g(x)=y_n$ when $1/n\leq |x-\alpha|<1/(n-1)$, we will then have $f\sim_\alpha g$ but $h\circ f\not\sim_\alpha h\circ g$.
Answer: Concerning the example you mention (composition on the left by the log), what is true is this:

If $f\sim_a g$ and if, in some neighbourhood of $a$, $g$ doesn't approach the value $1$, i.e. explicitly, if $\dfrac1{\ln\circ g}$ is bounded, then
  $$ \ln\circ f\sim_a\ln\circ g. $$


Uncaught TypeError: chart.addSingleSeriesAsDrilldown is not a function at Object.success - HighCharts

Question: I have a Highchartjs implementation that I am trying to implement, I am getting json data and trying to build a stacked bar chart drilldown. I have the data from the api and when I try to populate it,  I end up getting an error

Uncaught TypeError: chart.addSingleSeriesAsDrilldown is not a
function
at Object.success

This is my implementation so far
function loadProvinceStackedChart() {
            var dataSeries = [];
            var drill_level = 0;
            var chart = {
                type: 'column',
                marginBottom: 120,
                events: {
                    drilldown: function (e) {
                        var pointName = e.point.name;
                         $.ajax({
                                  url: 'api/getDistrictData/'+ e.point.name,
                                  type: 'GET',
                                  success: function (data) {
                                         //console.log('district data is', data);
                                          var labuploadedData = [];
                                          var labPndingData =[];
                                          $.each(data, function(key, item){
                                          //console.log('item q', item);
                                           var u = {
                                                     name: item.district_Name,
                                                     y: item.labUploaded,
                                                     drilldown: false

                                                     };
                                            var p = {
                                                       name: item.district_Name,
                                                       y: item.pending,
                                                       drilldown: false
                                                      };
                                            labuploadedData.push(u);
                                            labPndingData.push(p);
                                         });
                               // console.log('are of point', pointName);
                                  var chart = this;
                                  drilldowns4 = {
                                                  pointName: {
                                                             name: 'Uploaded',
                                                             color: '#228B22',
                                                             data: labuploadedData
                                                             }
                                                           },
                                  drilldowns6 = {
                                                  pointName: {
                                                            name: 'Pending',
                                                            color: '#FF0000',
                                                            data: labPndingData

                                                                }
                                                           },

                                series = drilldowns4[e.point.name],
                                series3 = drilldowns6[e.point.name];

                              chart.addSingleSeriesAsDrilldown(e.point, series);
                             chart.addSingleSeriesAsDrilldown(e.point, series3);

                              chart.applyDrilldown();

                                                    }

                                                });
                    }
                }
            };

I am trying to have the chart methods inside the success function ,but they keep throwing an error above. How can I display the stacked chart correctly from the data from the api?
Answer: The best way would be to implement the ajax query in the drilldown module like this.
events: {
  drilldown: function(e) {

    // The Endpoint URL
    let url = 'https://jsonplaceholder.typicode.com/posts/1';
    fetch(url)
      .then(function(response) {
        // Render the Response Status
        document.getElementById('result').innerHTML = response.status;
        // Parse the body as JSON
        return response.json();
      })
      .then(function(json) {
        // Render the parsed body
        document.getElementById('result_json').innerHTML = JSON.stringify(json);
      })
    }
}

At this forum post it's other example how to handle ajax query in the drilldown event.
https://www.highcharts.com/forum/viewtopic.php?t=40115#p138962


Controle de versão Rest com laravel

Question: Estou fazendo uma atualização em um aplicativo Android que tem como back-end uma api REST com php Laravel.
Gostaria de dicas de como fazer o controle de versão dessa api. Por exemplo, tive que fazer uma mudança em uma tabela no meu BD e com isso alterei o controler e o model correspondentes. Então ao fazer a atualização do aplicativo eu gostaria que os aplicativos de versões anteriores continuassem usando o mesmo controler e model antigos. Mas a versão atualizada do aplicativo eu gostaria que usasse a versão nova do controler e do model.
Comment: Crie um app para cada versão. Normalmente quando há uma mudança que compromete o funcionamento de uma versão anterior.
Comment: Tu pode usar o GIT pra facilitar sua vida: https://git-scm.com/doc
Answer: O que significa versionar uma APIRestful ?
Imagine a seguinte situação, você está desenvolvendo uma API que será consumida por um aplicativo desenvolvido para IOS/Android, um dos endpoints de sua API tem como objetivo retornar uma lista de usuários do sistema para mostrar na tela principal do App, a URL para consumir essa listagem de usuários é "GET https://www.meu-site-exemplo.com.br/api/usuarios" e o retorno desse endpoint é:
[{
    "nome": "Usuário de teste 1",
    "email": "Email de teste 1",
    "telefone": "+353832123323233"
},{
....
}]

O desenvolvedor responsável pelo App finaliza a integração e disponibiliza ele para download na AppStore e Google Play, depois disso, muitas pessoas fazem o download e estão usando-o em seus celulares. Um belo dia a sua empresa é vendida para uma empresa americana e por algum motivo eles querem remodelar o App e padronizar a API para retornar o nome dos campos em inglês, a primeira vista tudo isso parece muito simples, basta alterar o retorno da API e atualizar o App para ler esses novos campos:
[{
    "name": "Usuário de teste 1",
    "email": "Email de teste 1",
    "phone": "+353832123323233"
},{
....
}]

Todos que baixarem a nova versão do App seguirão usando perfeitamente, porém temos um grande problema, nem todos que já estavam usando ele antes irão atualiza-lo automaticamente. Quando eles tentarem usa-lo, o App fará um request para "GET https://www.meu-site-exemplo.com.br/api/usuarios" e retornará a lista de usuários com os campos em inglês, porém o App estará esperando campos em português, e é ai que teremos um grande problema.
Acredito que esse seja o problema mais comum de quem está desenvolvendo uma API que será consumida por Apps, também temos muitos outros exemplos. Em 2014 trabalhei em uma plataforma E-commerce na equipe de integrações, nosso papel era todos os dias integrar a plataforma com dezenas de diferentes APIs/WebServices, muitas vezes sofríamos por esse problema, os serviços externos simplesmente alteravam algo e tudo parava de funcionar, simplesmente o caos na terra.
A Solução:
O versionamento de APIs vem se tornando muito comum nos últimos anos, a ideia é nunca apagarmos o antigo código (lógica) quando precisamos fazer grandes alterações ou alterações que possam quebrar as integrações, adicionar novos campos talvez não seja um problema, mas sim alterar os que existem. Seguindo essa lógica, poderíamos criar endpoints desse tipo:
https://www.meu-site-exemplo.com.br/api/v1/usuarios
https://www.meu-site-exemplo.com.br/api/v2/usuarios

Repare que a diferença é o v1 e v2 que dizem respeito a versão que está sendo acessada. Dessa forma as antigas integrações poderiam seguir usando a primeira versão e as novas utilizariam a v2 ,construindo o código de uma forma organizada, nunca mais precisaríamos nos preocupar com isso.
Aplicando o versionamento aos diretórios
Nos exemplos a seguir vou demonstrar como eu costumo versionar minhas APIs, porém sei que existem diferentes approaches para fazer isso.
A primeira parte é organizarmos nossos diretórios, dentro da pasta app/Http/Controllers, crie uma pasta Api dentro e dentro dela crie duas pastas v1 e v2, desta forma teremos os seguintes diretórios:
app/Http/Controllers/Api/V1
app/Http/Controllers/Api/V2

também podemos criar essas pastas diretamente quando formos criar nossas controllers através do comando:
php artisan make:controller Api/V1/MinhaController

Dessa forma ele já criará os diretórios e a classe com o namespace correto.
Também podemos versionar nossos resources para termos retornos diferentes, basta executar na criação de um Resource ou uma Collection os seguintes comandos:
php artisan make:resource V1/UserResource

ou
php artisan make:resource V2/UserResource

e dentro de cada uma das controlles eu uso seu respectivo resource, conforme exemplo de uma controller utilizando a primeira versão de nossa API:
<?php

namespace App\Http\Controllers\Api\V1;

use App\Models\User;

class UserController
{
    public function getUser(int $idUser)
    {
        $user = User::find($idUser);

        return new \App\Http\Resources\V1\User($user);
    }
}

na controller da versão 2, basta utilizar um resource diferente. Esse mesmo modelo pode ser usado para Models, Views, Services, Repositories, ou qualquer outra estrutura que você estiver utilizando, inclusive para testes.
Porém ainda temos um problema, como Laravel redireciona quando se coloca v1 ou v2 na url? como ele chama a controller correta?
Carregando as controllers de acordo com a versão da URL
Para fazer isso utilizaremos os Middlewares do Laravel, primeiro acesse o arquivo config/app.php e adicione o seguinte código nas ultimas linhas:
/*
|-------------------------------------------
| Versão da API
|-------------------------------------------
|
| Essa é a ultima versão de sua API, caso não seja informado a       | versão desejada, essa será utilizada.
 */

'api_latest'  => '2',

Agora criaremos nosso middleware, execute o seguinte comando no seu terminal:
php artisan make:middleware APIVersion
Abra o arquivo criado (app\Http\Middleware\APIVersion.php) e insira o seguinte código:
<?php

namespace App\Http\Middleware;

use Closure;

/**
 * Class APIVersion
 * @package App\Http\Middleware
 */
class APIVersion
{
    /**
     * Handle an incoming request.
     *
     * @param  Request $request
     * @param  Closure $next
     *
     * @return mixed
     */
    public function handle($request, Closure $next, $guard)
    {
        config(['app.api.version' => $guard]);
        return $next($request);
    }
}

Esse middleware será responsável por interceptar o request e aplicar versão que estivermos chamando (caso não informarmos a versão). Acesse o arquivo ../app/Providers/RouteServiceProvider.php e adicione o seguinte atributo na classe:
/** @var string $apiNamespace */
protected $apiNamespace ='App\Http\Controllers\Api';

dentro do método mapApiRoutes insira o seguinte código:
/**
 * Define the "api" routes for the application.
 *
 * These routes are typically stateless.
 *
 * @return void
 */
protected function mapApiRoutes()
{
    Route::group([
        'middleware' => ['api', 'api_version:v1'],
        'namespace'  => "{$this->apiNamespace}\V1",
        'prefix'     => 'api/v1',
    ], function ($router) {
        require base_path('routes/api_v1.php');
    });
    Route::group([
        'middleware' => ['api', 'api_version:v2'],
        'namespace'  => "{$this->apiNamespace}\V2",
        'prefix'     => 'api/v2',
    ], function ($router) {
        require base_path('routes/api_v2.php');
    });
}

Desta forma estou separando os grupos de rotas por arquivos diferentes, repare que nos métodos require estou carregando:
routes/api_v1.php
routes/api_v2.php

será necessário criar esses dois arquivos manualmente e seguir a mesma lógicas do arquivo que já é criado pelo Laravel (routes/api.php), esse arquivo original não será mais usado. Prefiro essa separação pois mantém as coisas muito mais organizadas, depois disso é só criar as suas rotas apontando para cada controller.

Esta resposta foi retirada do artigo Versionando sua APIRestful com Laravel

Controle de versão Rest com laravel