How MPFR Library Calculation Accuracy Works

Question: I confess that I am having trouble understanding the MPFR library, I am trying to calculate the square root of a large number but I am not sure how to define the precision of the mpft_t root variable or what is the best way of rounding.
my code is as follows:

#include <stdio.h>
#include <stdlib.h>
#include <mpfr.h>

int main(){

    mpfr_t bigNumber, bigNumber2, root2;

    unsigned long int size = 1000000;

    mpfr_init2(bigNumber, size);
    mpfr_init2(bigNumber2, size);
    mpfr_init2(root2, size);

    mpfr_ui_pow_ui(bigNumber, 8, 20000, MPFR_RNDZ);

    mpfr_sqrt(root2, bigNumber, MPFR_RNDA);

    mpfr_pow_ui(bigNumber2, root2, 2, MPFR_RNDA);

    return 0;
}

But regardless of the precision set for mpz_t root, the result is often not satisfactory.
The result of  mpfr_pow_ui (bigNumber2, root, 2, MPFR_RNDA)  is most often different than mpfr_t bigNumber, and I don't mean the floating value, but the entire part.
How to find out the precision needed to perform a certain calculation?
what is the best form of rounding for this calculation?
why does this inaccuracy happen?
Comment: We'll need an [mre], please.
Comment: right, I corrected the question.
Comment: It has been a while since I worked with MPFR, so I am not sure exactly what your code is requesting of it in precision, but I suspect you are using the same precision for `bigNumber2` and `root2`. In this case, consider that, for some precision such that the ULP is approximately one part in P relative to the number, if we have some y with square root x, the calculated square root may be around x+1/(2p), due to the required rounding, and then the square of that is x^2+2x/(2p) + 1/(4p^2), which is approximately y + x/p. So it is not unexpected that calculating `sqrt(y)^2` will differ from `y`.
Comment: In other words, a small relative error in the square root leads to a large relative error in the square of that square root. You would have to calculate the square root with much more precision than the square in order to recover the original number most of the time, and, even then, I suspect there may be some cases that fail. Why are you trying to get the square of a square root to equal the original number anyway? Floating-point arithmetic is generally intended to be an approximation; you should not expect results identical to real-number mathematics.
Comment: This is for study only. In that case, I was just studying the accuracy of the library. Thank you for your explanation.
Comment: MPFR just rounds each operation correctly, regarding each input as exact. It does not track the accuracy in a sequence of operations. You have other tools for that.
Comment: In the case of a slightly modified version of the code in the post, the result is apparently exact. (The modification is to print the difference.)
Answer: The code works fine (on GCC 9.3.0 and MPFR 4.1.0) and gives back the original number.
#include <stdio.h>
#include <stdlib.h>
#include <mpfr.h>

int main()
{
    mpfr_t bigNumber, bigNumber2, root2;
    unsigned long int size = 100000;
    mpfr_init2(bigNumber, size);
    mpfr_init2(bigNumber2, size);
    mpfr_init2(root2, size);
    mpfr_ui_pow_ui(bigNumber, 8, 20000, MPFR_RNDD);
    mpfr_out_str (stdout, 10, 0, bigNumber, MPFR_RNDD);
    putchar ('\n');
    putchar ('\n');
    putchar ('\n');
    mpfr_sqrt(root2, bigNumber, MPFR_RNDD);
    mpfr_out_str (stdout, 10, 0, root2, MPFR_RNDD);
    putchar ('\n');
    putchar ('\n');
    putchar ('\n');
    mpfr_pow_ui(bigNumber2, root2, 2, MPFR_RNDD);
    mpfr_out_str (stdout, 10, 0, bigNumber2, MPFR_RNDD);
    putchar ('\n');
    putchar ('\n');
    putchar ('\n');
    putchar ('\n');
    return 0;
}


Pandas: How to combine two dataframes by closest index match?

Question: I've got two dataframes df1, df2 with indexes of the same type, but with few, if any, identical matches. Indexes may also have duplicaes. Columns A and B will consist of internally unique values. All indexes and columns are ordered, but not in the same direction. df1.index is descdending and df1['A'] is ascdending. df2.index is ascending and df2['B'] is descending.
df1: (numbers to the left are the unnamed indexes of the dataframes)
            A
80 -13.545215
76 -12.270691
73 -11.274724
65  -8.280187
38  -7.965972
13  -7.788130
10  -6.690969
6   -5.273063

df2:
            B
8  -13.827641
10 -12.283885
14 -11.459951
62 -11.067622
64 -10.745988
87 -10.661594
95  -9.816053
97  -7.740810

I'd like to combine the dataframes such that the values in df2['B'] are placed to the nearest corresponding index from df2 in df1, so that the desired output takes the form:
            B         A
8  -13.827641 -6.690969
10 -12.283885 -6.690969
14 -11.459951 -7.965972
62 -11.067622 -8.280187
64 -10.745988 -8.280187
87 -10.661594  NaN
95  -9.816053  NaN
97  -7.740810  NaN

If the closest index A in absolute terms is lower than index B, then the upper value of index A is the correct match. If index B has no corresponding match in index A that is higher, then NaN is the correct match.
So far, I've used pd.merge() and fillna() to make necessary analyses. But some may find it "unnatural" to make analyses on interpolated / synthetic data. Anyway, whis is how I've been doing it:
Partial code sample for pd.merge() and dropna():
# outer merge
df3 = pd.merge(df1,df2, how = 'outer', left_index = True, right_index = True)
#df4 = df3.interpolate(method = 'linear')[1:]
df4 = df3.interpolate(method = 'linear').dropna()
df4

Output:
            A          B
8   -5.982016 -13.827641
10  -6.690969 -12.283885
13  -7.788130 -11.871918
14  -7.877051 -11.459951
38  -7.965972 -11.263787
62  -8.070710 -11.067622
64  -8.175448 -10.745988
65  -8.280187 -10.729109
73 -11.274724 -10.712230
76 -12.270691 -10.695352
80 -13.545215 -10.678473
87 -13.545215 -10.661594
95 -13.545215  -9.816053
97 -13.545215  -7.740810

Plot:

Complete data and code sample
#imports
import numpy as np
import pandas as pd

# Some sample data
np.random.seed(1)
df1_index = sorted(np.random.randint(1,101,8), reverse = True)
df1info = {'A':sorted((np.random.normal(10, 2, 8))*-1)}

df2_index = sorted(np.random.randint(1,101,8))
df2info = {'B':sorted(np.random.normal(10, 2, 8)*-1)}

# Two dataframes
df1 = pd.DataFrame(df1info, index = df1_index)
df2 = pd.DataFrame(df2info, index = df2_index)

# outer merge
df3 = pd.merge(df1,df2, how = 'outer', left_index = True, right_index = True)

# interpolate missing values
df4 = df3.interpolate(method = 'linear').dropna()

# plot
df4.plot()

Thank you for any suggestions!
Edit 1: Duplicate scenario 1:
If df2.index has an exact match in df1.index, and df1.index has a duplicate, then the correct match is the lowest df1.index. I hope that makes sense. If it turns out to be nonsensical for some reason, I'm open to other suggestions!
Comment: [There's a built-in method for nearest index merge](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.merge_asof.html#pandas.merge_asof)
Comment: @G.Anderson `pd.merge_asof` is 1:1, which might not work here because of duplication.
Comment: What happens with the index is duplicated? Should it match to all exact duplicates/nearest duplicates?
Comment: @ALollz I'm thinking real hard about that right now. Will give feedback ASAP.
Comment: @ALollz I've edited the question with a scenario for duplicates. I hope it makes sense and really appreciate the effort so far!
Comment: @ALollz forgot about that :/
Comment: @Thanks to everyone taking a look at this. I'm gonna add some edits as well as scenarios for duplicates to make it all a bit more clear. Working on it right now.
Comment: @vestland can you give an example for Duplicate scenario 1
Answer: Not "Pythonic" but a O(n) solution
df2_index.sort()
df1_index.sort()

a = 0
b = 0
mapping = [[],[]]
while b < len(df2_index) and a < len(df1_index):
    if df1_index[a] == df2_index[b]:
        mapping[0].append(df2_index[b])
        mapping[1].append(df1.loc[df1_index[a], "A"])
        b += 1
        a += 1
    elif df1_index[a] > df2_index[b]:
        mapping[0].append(df2_index[b])
        mapping[1].append(df1.loc[df1_index[a], "A"])
        b += 1
    else:
        a += 1

df = pd.DataFrame({'A': mapping[1]}, index = mapping[0])
df2.merge(df, left_index=True, right_index=True, how='outer')

Output
     B              A
8   -13.827641  -6.690969
10  -12.283885  -6.690969
14  -11.459951  -7.965972
62  -11.067622  -8.280187
64  -10.745988  -8.280187
87  -10.661594  NaN
95  -9.816053   NaN
97  -7.740810   NaN

Both the indices are sorted in ascending order
b points to B's and a points to A's index
At any point of time give a b we find the next maximum a and save it when we find it
if b == a then we are done with those records so we move ahead
if a > b then we fond the value of b so we move b. We dont move a because this can also be a candidate for next b
if a < b we move a because the candidate for b will be somewhere after current a because it is sorted.
Comment: Thank you for answering! I would also be very interested in other variations of the same setup. Would you mind a follow-up question, or would you rather handle that in a new question?
Comment: @vestland Followup question is fine
Comment: Your suggestion answers my question before the edit. I'm also very curious as to how one would proceed to solve this with columns only and no index. So I believe the fair thing to do is accept your answer as it is, and post a new question with columns only and more properly explained duplicate scenarios.
Comment: sure :) But how will you frame the question without index when your condition of matching is on the index. Also I am eager to see pythonic solution to it.
Comment: I'm struggling with an array of real world variations of the same problem. I may also hva mis-specified this question just a tiny bit to match the exact thing I'm looking for right now =) I only realized that when I started digging even deeper as a response to the requests from Alollz. So a classic case of getting what you ask for, and not what you need... But I'll leave the question open to draw the attention of some pure pythonistas if you prefer....
Comment: Agreed. If you *would* like a follow-up question, how could you have included df1.index.values in the output (as a column)?


Elegant way of stripping string of currency characters?

Question: Currently Im receiving a string from a service that contains currency characters (Ex. "$123.44", "123,44 €"). I would like to strip these stings of their currency characters in order to perform some calculations on these prices (adding money, subtracting money...etc).
I know I could replace occurrences of certain characters and then re-add them later after the calculations, but I get the impression that there might be a better solution out there.
Any ideas?
Answer: You can use NSNumberFormatter to convert a formatted price into a Double value
func getNumber(formattedPrice: String, localeID: String) -> Double? {
    let formatter = NSNumberFormatter()
    formatter.numberStyle = .CurrencyStyle
    formatter.locale = NSLocale(localeIdentifier: localeID)
    return formatter.numberFromString(formattedPrice)?.doubleValue
}

but you'll need to specify the locale
getNumber("$123.44", localeID: "en_US") // 123.44
getNumber("123,44€", localeID: "it_IT") // 123.44
getNumber("£123.44", localeID: "en_UK") // 123.44

Answer: You can use an NSCharacterSet to root out those characters, like this:
var dollarStr = "$1.50"
var yuanStr = "¥18.25"
var euroStr = "20.75 €"

let strArray = [dollarStr, yuanStr, euroStr]

let charSet = NSCharacterSet(charactersInString: "$¥€ ")

for str in strArray {
    let trimmedStr = str.stringByTrimmingCharactersInSet(charSet)
    print(trimmedStr)
}

prints out :
1.50
18.25
20.75


Join Mysql statement issue

Question: I have two form drop-downs that capture two IDs, which relate to PKs from a table named nodes.
I want to delete those two nodes from within another table, named relationships.
So after I gather the 2 node IDs, I'm trying to delete the one node that is in a relationship with the other node.
In my relationship I have the id and goingto both as nodes, however only id is an FK and the other one isn't.
So how do I delete that if it is in a relationship?
Here is my attempt
$goingto = $_POST['id_one']; //get from form both from id in nodes
$id = $_POST['idtwo']; //get from form both from id in nodes

mysql> DELETE from relationships where $id = $goingto;

Here is my table structure:
nodes                 relationships
-----                 -------------
id int(11),           id int(11),
name varchar(35),     goingto int(11), //this is the destinationnode from the id relation
color varchar(7),     data varchar(0) null
type varchar (12),    Foreign key (id) references nodes(id)
Primary key (id)

engine = innodb

Comment: 1. Are `id_one` and `id_two` guaranteed to relate to each other via the `relationships` table?  2. If so, do we know if it is `id_one` `goingto` `id_two`, or will it be `id_two` `goingto` `id_one`?  Or will there be _two_ relationship records for this - ie one in each direction?  3. Do you want to delete the `nodes` themselves (along with all associated `relationships` for those nodes), or just the `relationships` that exist _between_ them? 4. Perhaps it'd just be easier to post the assignment/exam question in full, rather than stripping out the pertinent details.
Answer: Do you think this is what you mean:
DELETE from relationships where id = $id and goingto = $goingto;
Comment: yeah thats what I exactly what I mean.

Join Mysql statement issue


When is a sacrifice bunt a statistically "good" option?

Question: In the past several years the sacrifice bunt has come under fire as a "waste of an at bat" and "lowering your chance to score." No one denies that outs are very valuable in baseball, but is it ever a good idea to intentionally give up an out to advance a runner (or runners)?
I am more interested in cases where the pitcher is not at bat.
Comment: first person to quote "the book" wins a gold star :)
Comment: Just ordered "The Book" on amazon, can't wait for it to arrive!
Answer: According to the calculations done in this James Click article titled "Taking One for the Team: When Does it Make Sense to Sacrifice? Part 1", he concludes:

Thus, we can conclude that, in this simple case, no matter who is
  coming up next, any batter hitting below .075 should always sacrifice,
  while any batter hitting better than .243 should never sacrifice. If
  nothing else, this conclusion lends further credibility to the idea
  that pitchers should almost always sacrifice if given the opportunity.

In the second part of his series, he notes:

Finally, we need to consider that sacrificing is a strategy often
  employed when getting one run is more important to winning than
  scoring many.

and

The values in Situation 3 immediately stand out. Virtually every major
  leaguer is under those numbers; so, according to this model, it is
  almost ALWAYS a good idea to sacrifice in that situation if only one
  run is needed. This conclusion flies in the face of many of the
  conventions usually espoused by performance analysts, but it is
  supported by the raw numbers from the run probability table. Notice
  that the probability of scoring at least one run increases from .635
  to .693 when sacrificing in Situation 3.

Note: Situation 3 is a man on 2nd with no outs.
He concludes in part 3 of the series:

Therefore, in the broadest conclusion possible, we can say that
  sacrificing is a good idea when pitchers are batting and, for most of
  the hitters in the league, when there is a man on second, no one out,
  and a single run is the goal. Even then, there is a set of the
  league's best hitters who should never lay down a bunt; which is too
  bad, because it would be fun to see Bonds square around, just once.

So the final conclusion that he draws is that a sacrifice bunt makes sense only in one situation: man on second, no one out, and a single run is the goal.


preg_match_all JS equivalent?

Question: Is there an equivalent of PHP's preg_match_all in Javascript? If not, what would be the best way to get all matches of a regular expression into an array? I'm willing to use any JS library to make it easier.
Answer: You can use match with the global modifier:
>>> '1 2 3 4'.match(/\d/g);
["1", "2", "3", "4"]

Comment: I didn't understand that syntax.
Comment: Note that this approach ignores captures. `'1a 2b 3c 4d'.match(/(\d)([a-z])/g)` outputs just `["1a", "2b", "3c", "4d"]`. If you need captures see [this answer](https://stackoverflow.com/a/1222072/2750743)
Comment: @erm3nda i think **/\d/g** is you didn't understand. Here [Creating a regular expression in Javascript](https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions).
Comment: If you need captures, matchAll fits much better. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/matchAll
Answer: John Resig has written about a great technique on his blog called 'Search and dont replace'
It works using javascript's replace function, which takes a callback function, and returns nothing to leave the original content unaltered.
This can be a neater than using a global match and iterating over an array of results, especially if you're capturing several groups.
Answer: A better equivalent of preg_match_all from PHP in JS would be to use the exec() function. This will allow you to capture groups as well, with match() you can not do that.
For example you want to capture all times and the number in brackets from the variable myString:
var myString = "10:30 am (15 left)11:00 am (15 left)11:30 am";
var pattern = /(\d{1,2}:\d{1,2}\s?[ap]m)\s\((\d+)/gi;
var match;
while (match = pattern.exec(myString)){
  console.log('Match: "' + match[0] + '" first group: -> "' + match[1] + '" second group -> ' + match[2]);
}

The output will be:
Match: "10:30 am (15" first group: -> "10:30 am" second group -> 15
Match: "11:00 am (15" first group: -> "11:00 am" second group -> 15

Answer: If you need the exactly return structure as in php.
Please check for yourself before usage)
Solution (on typescript):
function preg_match_all(regex: RegExp, str: string) {
  return [...str.matchAll(new RegExp(regex, 'g'))].reduce((acc, group) => {
    group.filter((element) => typeof element === 'string').forEach((element, i) => {
      if (!acc[i]) acc[i] = [];
      acc[i].push(element);
    });

    return acc;
  }, [] as string[][]);
}

Example (on javascript):

const str = ';9N;N1;CP-S2;EU;CP-S3;E;CP-S4;KRT;VH;;VL;CP-S2;CP-S3;CP-S4';
const regex = /CP-(S[\d*])/;
const result = preg_match_all(regex, str);

console.log(result);

function preg_match_all(regex, str) {
  return [...str.matchAll(new RegExp(regex, 'g'))].reduce((acc, group) => {
    group.filter((element) => typeof element === 'string').forEach((element, i) => {
      if (!acc[i]) acc[i] = [];
      acc[i].push(element);
    });

    return acc;
  }, []);
}
Answer: Use new RegExp().test()

function preg_match_all(regex, str) {
  return new RegExp(regex,'g').test(str)
}

preg_match_all JS equivalent?


Why is the 'line-element' non-integrable?

Question: I'm reading The Variational Principles of Mechanics by Cornelius Lanczos; here is the concerned excerpt:

A second landmark is the geometry of Riemann, which grew out of the ingenious investigations of Gauss concerning the intrinsic geometry of the curved surfaces. Riemann's geometry is based on one single differential quantity called the "line-element" $\bar{ds}^1\;.$ .... Let us consider for example the infinitesimal distance $\bar{ds}$ between two points $P$ and $P^1$ with the coordinates $x,y,z$ and $x+dx,y+dy,z+dz$. According to the Pythagorean theorem we have $$\bar{ds}^2= dx^2 + dy^2 + dz^2\,.$$ [...]

At the footnote

$^1$ Here we adopt the custom of denoting non-integrable differentials, which cannot be considered as the infinitesimal change of something, by putting a dash above the symbol.Thus $dq_k$ or $dt$ means the "$d$ of $q_k$" or the " $d$ of $t$", while $\bar{ds}$, for example, has to conceived as an infinitesimal expression and not as the "$d$ of $s$".

He further adds:

if $\bar{ds}$ were integrable, it would be impossible to find the shortest distance between two points because length of any curve between these two points - depending on the initial and end positions only - would be the same.

I couldn't get the point why "line-element" is non-integrable; he did add an explanation at the footnote, but I couldn't comprehend his reasoning: so according to him, a differential displacement between two points is non-integrable, is it so?
How could we integrate then using a differential displacement like $\mathrm dx$ in one-dimension or $\mathrm d\mathbf r$ in three dimensions or so?
Sorry, if I sound silly; but I'm a bit confused.
Can anyone please clarify to me why "line-element" is non-integrable?
Comment: I'm glad I'm not the only one thrown by the terminology.
Comment: On page 25, the term "not integrable" is used in exactly the same way in relation to non holonomic conditions (a ball rolling on a table can have different rotation states after rolling along a closed path).
Answer: "Non-integrable" is not the word I would use here, because it has other, non-related meanings.  I think that is the source of the confusion.
What he is  saying is that the result of integrating $ds$ along a curve is path-dependent, not just a function of the endpoints.
If $f$ is any smooth function defined on a simply-connected region (in particular the $x$ coordinate), integrating $df$ on any curve from $p$ to $q$ in this region will give you $f(q) - f(p)$, so that is not path-dependent.  So $dx$ is "integrable" in his sense, but $ds$ is not.


Two coins, one fair and one double headed

Question: Two coins: one fair (coin A) and one double headed (coin B). I toss one of the coins and get a head. What's the chance that I tossed coin A?
The answer is $1/3$, but how did they get this?
Comment: welcome to MSE, please try to add some of your own attempts.
Answer: $$
\Pr(A\mid H)=\frac{\Pr(H\mid A)\Pr(A)}{\Pr(H\mid A)\Pr(A)+\Pr(H\mid B)\Pr(B)}=\frac{\frac12\cdot\frac12}{\frac12\cdot\frac12+1\cdot\frac12}=\frac13.
$$
Answer: There are four equally likely outcomes of this experiment which can
be described as $H_A, T_A, H_{B,1}, H_{B,2}$. You have observed a Head.
Only one of the three
possible Heads that you might have observed is $H_A$ and so there is
one chance in three that the Head you actually observed in $H_A$.


Is $a$ < $b$ if $f(x)$ is differentiable on $(a,b)$ and continuous in $[a,b]$?

Question: $f(x)$ is differentiable on $(a,b)$ and continuous in $[a,b]$.
In theory $a$ can be equal to $b$. But then if $f(x)$ is defined on one point it's not differentiable because by definition derivative is the rate of change between 2 points on an interval.
By conventional notation we write the left-most coordinate of an interval adjacent to the left bracket and the right-most coordinate of the interval adjacent to the right bracket which in such case would mean that $a$ is before $b$.
So can we claim that $a<b$?
Or maybe if given $(a,b)$ the convention pre-supposes that $a \neq b$?
Comment: By definition, $(a,b) = \{x: a\lt x\lt b\}$. Therefore, if $(a,b)$ is not empty $a\lt b$.
Comment: @JohnDouma It's $a <b$ if $(a,b)$ is nonempty and $a = b$ if $(a,b)$ is empty. Thus, the final relation becomes $a \leq b$ since the statements still hold if $(a,b)$ are empty.
Answer: In my opinion (and these three words imply that this is just some very subjective thinking) it depends on how you define differentiability. If your definition of differentiability requires $f$ to be defined on an open interval (an interval of the form $(a,b)$ with $a<b$), then you are right, because then if $f$ is defined only on a set $[a,a]=\{a\}$ with one point, talking about differentiability of $f$ doesn't make any sense (because for this case it is not defined, and - as you have pointed out already - cannot tell anything about the rate of change, cause $f$ cannot change anyhow since there is only one value at which $f$ is defined).
However, it is sometimes convenient to define differentiability for those functions by just defining them to be differentiable (From a logical point of view this also makes sense and guides you sooner or later to the question how statements about the empty set are handled, see the comments above). This is, at first glance, pure convention. That way, one can replace a statement like "Let $f:[a,b]\to\mathbb R$ $\color{red}{\text{for }a<b}$ be continuous and differentiable in $(a,b)$ such that ..." by something like "Let $f:[a,b]\to\mathbb R$ be continuous and differentiable in $(a,b)$ such that ...". The second statement is easier to read because there are no redundant information. But as you can see, it is only a matter of taste.
Let's take a closer look at the definition of differentiability. What does
\begin{align*}
\lim_{x\to x_0}\frac{f(x)-f(x_0)}{x-x_0}\quad\text{exists}
\end{align*}
really mean? It means that for each sequence of numbers $(x_n)$ contained in the domain of definition of $f$ and so that $x_n\neq x_0$ for each $n$, the limit
\begin{align*}
\lim_{n\to\infty}\frac{f(x_n)-f(x_0)}{x_n-x_0}
\end{align*}
exists and is the same, no matter how the sequence $(x_n)$ actually looks like. Thus, $f$ is differentiable at $x_0$, if this works for each such sequence. But if there is no such sequence, then there is nothing to check, there is nothing that can go wrong, so, well, then we say, $f$ is indeed differentiable. But, again, this is our choice. We also could say, that $f$ is not differentiable in this case, and we are again talking about empty sets and how to treat them.
From a porgrammers point of view: Imagine that you would like to write a program that checks whether all elements of a set of objects (a list) $L$ satisfy a given property $P$, say. Thus, your function yields true, if all elements of $L$ satisfy $P$, otherwise false. You probably know that functions (depends on the language) have to return something, in any case! So we would probably write our function like this:
bool function check(List L, Property P) {
   for each (x in L) {
       if (!P(x))
           return false;
   }
   return true;
}

In your case, $P(x)=f$ is differentiable at $x$, and $L=(a,b)$. In case $L=\emptyset$, check(L, P) returns true. Try to rewrite this function so that it returns false if $L=\emptyset$. You would need a couple more lines. In summary, it is just handy to say that any property for elements of the empty set is true.
Again (see comments) from a logical point of view, this is the only reasonable way to go. If the statement "Each element of the empty set is red" was false, then its negation "There is one element of the empty set which is not red" had to be true, which is clearly impossible.
To avoid all those discussions, my former Analysis Prof. just defined intervals to contain at least two elements. But again, just definition/convention. To cite my former Algebra Prof.: "When it comes to mathematical definitions there is no true or false, just convenient or inconvenient."
Comment: You're welcome. For any further questions, don't hesitate to drop me an email.
Comment: Thanks for a really comprehensive answer! I guess I'd need to check with our calculus teacher so I know the convention for our class.
Answer: Note that if $a=b$ then $(a,b)$ is an empty set thus "f has a derivative on $(a,b)$" is a true statement.
Thus, by convention of noting lower bound first we can only claim $a \leq b$.
EDIT:
About the derivative on empty set.
In logic, a statement is either true or its logical negation is true (which is the same as saying that the statement is false).
Now, the logical negation of "f has a derivative $\forall x \in \emptyset$" is "for atleast one $x \in \emptyset$ $f(x)$ has no derivative".
Since there are no points in the empty set, one can't find a point for which $f(x)$ has no derivative.  Thus logical negation is false, making our statement true.
Conclusion: "f has a derivative $\forall x \in \emptyset$".
Comment: But from derivative definition: $f'(x) = lim_{h \to 0} \frac{f(x_0+h)-f(x_0)}{x_0+h-x_0}$ if $x_0+h=x_0$ then you get $0$ in the denominator? Or by definition $h \to 0$ but here it's $h=0$
Comment: For every point $x$ in the empty set the $\lim_{h \to 0} \frac{f(x+h) - f(x)}{h}$ exists. The trick is: there are no points in the empty set.
Comment: Indeed, every proposition of the form $\forall x \in \emptyset, P(x)$ is true.
Comment: I suppose you mean that $P(x)$ is the derivative of the function? From which area of math does this fact come from that the derivative exists on empty sets?
Comment: You are missing the point. We are saying something along the lines of "All pigs with wings speak english." which is true since you can't give a counter example. Logic is the area of mathematics.
Comment: I don't get it. I would think that giving an example in which there's division by zero proves my claim. Unless there's some other definition of derivative which we didn't learn in class.
Comment: I expanded my post a little, maybe this will help.
Comment: According to https://en.wikipedia.org/wiki/Interval_(mathematics) indeed $a$) on $a$ and $b$. It's purely convention that enforces $a \leq b$.
Comment: Because the convention for empty sets according to the article is $(a,a)$.
Comment: This here is a technical point: it's okay to use convention as long as it doesn't change the results. Noting $[1,2]$ instead of $[2,1]$ is fine if we can just exchange $a$ for $b$ in all our statements and still get true statements. (say you assumed $a<b$ and it turns out $b<a$ then you just rewrite your proof by exchanging $a$ and $b$ and its fine.) Now assuming $a<b$ also assumes $a \neq b$ which can still be the case.


How many selection ways are possible?

Question: There are 6 girls and 5 boys. You need to make a team of 4 persons. In how many ways can you form this team?
One way is to select 0,1,2,3,4 girls in team, but this is a very lengthy process. Is there any fast solution?
Comment: Please do not change questions after answers are posted.  It makes answers non-responsive.  I already answered the new one because it seemed the problem was because there were only two categories.  You might look at [stars and bars](http://en.wikipedia.org/wiki/Stars_and_bars_%28combinatorics%29) for a more general case.
Comment: In problems like this, it is often very helpful to give two or three specific examples of the different things being counted.  This clarifies what you're considering "different" and what you're considering "not different".
Comment: How is this different from the question "There are 11 kids and you need to make a team of 4 people"? Are there any requirements on the team having some members of each gender, etc.?
Comment: ok. got it. but i dnt get solution.
Answer: If the girls and boys are distinguishable, you really have eleven players to choose four from.  Writing using the binomial coefficient this is just ${11 \choose 4}$.  If they are not, you are just asking how many ways there are to split 4 into two ordered integers, and you have listed the five ways.
Added: Yes, as I explained, you can just find the maximum and minimum, the the count is $\max-\min+1$ where the $+1$ comes because you have both ends.  You don't have to think about the numbers in the middle.  For a more complicated case, suppose you have lots of red, blue, and yellow jelly beans and want the number of ways to select $10$ of them.  You can say that the number of red ones can range from $0$ to $10$.  Given $r$ reds, there are $11-r$ ways to choose the yellows and blues, so the total is $\sum_{r=0}^{10} (11-r)=11\cdot 11-\frac 12\cdot 11\cdot 12=121-66=55$
Comment: @ ross yes you are right if they are distinguishable 11c4 are possible ways..but here m js saying about gender.. so is there any fast method.. except making cases like having 0,1,2,3,4 girls in the team???
Comment: You can just say the minimum number of girls is $0,$ the maximum is $4,$ so the range is $4-0+1=5$.  Is that what you are looking for?
Comment: ross. m thinking about is there any  formula (simple).. except the method of making cases?

How many selection ways are possible?


Help I cant understand difference set and bijection

Question: I'm proving this problem and I have no idea to solve so, I looked solution on the book. But this makes me so confused.
Here is the problem.
For two sets $X$ and $Y$, If $(X-Y) \sim (Y-X)$ then $X \sim Y$.
(where $X \sim Y $ means there exist one-to-one correspondence for sets $X$ and $Y$)
and here is the solution.
Let $f$ : $X - Y \sim Y - X \quad $ and   $\quad g : X \to Y, \quad $
$g(x)=\begin{cases}
f(x),  & \text{if  $\quad x$ $\in$ X-Y} \\
x, & \text{if $\quad x$ $\in$ $X \cap Y$}
\end{cases}$
I can understand this definition of function $g$ shows bijection, but I cant understand why $\quad g(x)=x\quad$  where $x \in X \cap Y $.
Is there any guarantee that the function $g$ could be $g(x)=x$?
Let me know WHY THE FUNCTION $\quad g \quad$  has to have that appearance or any other solution of this problem.
Comment: "why the function $g$ has to have that appearance.." It does not have to. There are more possibilities. Finding one of them is enough to conclude that $X\sim Y$.
Comment: sorry not $x \in X \cup Y$ , $x \in X \cap Y$
Answer: What you want to find is a bijection from $X$ to $Y$.  The claim here is that $g$ is such a bijection.  It only needs to take values from $X$ (and return values from $Y$), it does not need to take values from $Y$.
The situation is symmetric and you could just as easily find a function from $Y$ to $X$ but you don't need to find one from $X \cup Y$ to anywhere.  (This comment is now unnecessary since the question has been edited from  "why $g(x)=x$  where $x \in X \cup Y $" to "$ g(x)=x$  where $x \in X \cap Y $".)
A concrete example might help.  Our universe consists of people with either black or white trousers and either black or white shirts.  Consider that $X$ is the set of people with black trousers and $Y$ is the set of people with black shirts.
$X - Y$ is the set of people with black trousers and white shirts.
$Y - X$ is the set of people with black shirts and white trousers.
We are told that there is a bijection between these two.  We don't know or need to know the details just that it exists.  We call this bijection $f$. It takes values in $X - Y$ but maybe not all of $X$ and gives values $Y - X$ but maybe not all of $Y$.
The bit of $X$ that $f$ might not be defined for is $X \cap Y$ and the bit of $Y$ that is not covered by $f$ is $Y \cap X$.  Conveniently, these are the same as $\cap$ is commutative.  So, we can use it to define our new function $g$ on this subset very simply.
So, back to our concrete example.
$X$ is the set of people of people with black trousers and either colour of shirt.
$Y$ is the set of people of people with black shirts and either colour of trousers.
We need map $X$ to $Y$.
$X$ splits into $X \cap Y$ (black trousers and black shirts) and $X - Y$ (black trousers and white shirts).
The first part are also in $Y$ so we can map them to themselves (second line of the definition of $g$).
The second is covered by the bijection that we are told exists.  Somehow, we can map $X - Y$ (black trousers and white shirts) to $Y - X$ (white trousers and black shirts).
Can you see that this is a bijection?
Why?
Sorry, I failed to answer the why at the end of your question.
We are asked to find a bijection between $X$ and $Y$, not the bijection.  The distinction I am making is that there is not necessarily just one.  In fact, it is very unlikely that there is a single bijection. That would happen only in the case that both $X$ and $Y$ had a single element.  Even if they are small finite sets (but more than one element) then there will be lots of bijections.  So, there is no claim that $g$ is the only answer.  It is just that  $g$ is an easy answer and one answer is enough.
This is a tough part of mathematics.  It is often easy to understand someone else's proof but it is still hard to understand how they thought of it. With practice, this type of example should become easy but many others will remain hard.  For example, when Andrew Wiles proved Fermat's Last Theorem, I don't think that anyone said: "that was obvious, why didn't I think of that".
Comment: The OP writes that he does understand that his $g$ is a bijection, but doesn't understand why it has been given the definition it has in the first place. That seems to hint of some deeper misunderstanding about the nature of mathematics.
Comment: @HenningMakholm Yes but I was hoping that my concrete example would help.
Comment: @HenningMakholm I added bit more.  I'll wait to see whether the OP responds.
Comment: My answer initially addressed "why $g(x)=x$  where $x \in X \cup Y $" but just as I started to suspect it was a typo, the OP changed it to "$ g(x)=x$  where $x \in X \cap Y $".  So, it was.
Answer: It's not clear that $g$ has to have this definition. However, that is not the initial question. The task is to provide a bijection $g:X\to Y$ and we've found one. There may be more, but that is irrelevant.
Comment: Thanks for your comment. But I have other question in your answer. You said "he task is to provide a bijection g:X→Y". Is it correct that I understand this as I can choose any type of bijection function to prove? I think this way is not general becuase I choose specific one to prove. Choose any type of bijection is guaranteed?
Comment: @SeunghwanShin it depends on how you define $\sim$. Usually it's said that $A\sim B$ iff there exists a bijection $A\to B$. Defining any bijection $A\to B$ is sufficient to prove.
Answer: Does there exist a function $h:X\cap Y\to Y$ that is prescribed by $x\mapsto x$?
Yes, because for every $x\in X\cap Y$ (i.e. for every $x$ in domain $X\cap Y$) we have $x\in Y$ (i.e. $x$ is an element of codomain $Y$).
Next to that from the fact that $X-Y\sim Y-X$ it follows that we have a function $k:X-Y\to Y$ such that $k$ is injective and its image is the set $Y-X$.
Based on these functions $h$ and $k$ we construct the function $g:X\to Y$.
It is prescribed by $x\mapsto k(x)$ if $x\in X-Y$ and $x\mapsto g(x)=x$ if $x\in X\cap Y$.
It is not difficult to prove that $g$ is a bijection justifying the conclusion that $X\sim Y$.
Comment: Oh God. you're so genius!
Answer: $g:x\mapsto x$ when $x\in X\cap Y$ is clearly a bijection, $X\cap Y\mapsto Y\cap X$.   So by choosing this, no further work needs to be done in that partition.
You are told that some $f$ exists where $x\mapsto f(x)$ is a bijection for $(X\smallsetminus Y) \mapsto (Y\smallsetminus X)$ too.
Thus by choosing such a $g$ that has those pieces over those partitions, you have constructed a bijection $g: X\mapsto Y$.


Why does this chromatic walkdown bassline work?

Question:

The above song (in F) has a bassline that walks down by half-steps from F to C# and includes C, B, and A#. Why does it work? What's the theory behind it? I know that E and B make good blue notes, but what about D# and C#? Is it switching between major and minor scale?
Comment: I really want that second F chord (after the Bbm/Db) to be an F/C instead of root-position F.  I mean, the bass line goes F-E-Eb-D-Db-**F**-B-C-F.  Doesn't that seem kind of bizarre?
Comment: @Brian Tung Yeah, F/C does seem like the natural way to play it. The whole game that this song is from was a one man project, and the creator had no knowledge of music theory. It's kind of inspiring.
Answer: In F the notes are F, E, Eb, D, Db. They reflect a note from each harmony. F goes with F chord; E goes with C chord; Eb goes with F7 - (or poss. Cm7, or Eb); D goes with Bb chord and Db goes with Bbm chord. Whilst the D#/Eb and B are good blues notes, E isn't.
Out of interest, that 3rd chord would contain D# (not called Eb) if the chord was B7, used in a tritone substitution, - but here it's not.
Comment: If there were a tritone substitution, then, depending on the context, it *might* be that Cb and Eb are better spellings than B and D#.
Comment: @RosieF - you're right, the chord could be called Cb7 working in certain keys, never worked out exactly which way the spelling would go. Probably reflecting the # or b in the original key.
Answer: It seems the composer was limited to three voices, and his voice doubling is somewhat poor, so the lines here do not exactly outline full harmonies.  There are probably a number of ways you could look at this.
That being said, it seems to me that we are hearing what is known as a sequence.  Sequences are patterns that repeat at different ranges, often used to harmonize a melodic line (e.g. the descending 5-6 sequence in the Pachelbel Canon).  The pattern in this piece is down a perfect fourth, up a minor third, and is used to harmonize a descending chromatic line by alternating between 53 and 63 inversions,  making this a form of a descending chromatic 5-6 syncope, if you want to be technical.
In the key of F it would look like this:
F
  C
  Ebmaj7
  Bb
  Dbmaj7
  F
  G7
  F
  C
When chords follow sequential patterns, the "rules" that govern progressional harmony get a lax hand.  Things that would otherwise sound strange end up sounding OK because everything else held together by melodic forces.
The sequence is followed by a modulation to the dominant.  Normally pretty standard.  In my opinion though that G major chord doesn't work so well, as it takes the pitch palette in a totally different direction (we've been doing flats so far, but now he throws in that sharp-- authentic vs. plagal motion on the circle of fifths) and isn't prepared in any way.  Then he jumps into what seems to me a rather premature 64-53 half cadence.  To me it just doesn't work, actually.
Comment: Reckon your Ebmaj7 is F7 , and Dbmaj7 is Bbm in this song. The sequence is nice, but ...
Comment: Well with the way he has things voiced I suppose there are many possibilities.  But if the third chord is an F7, he left out the third of the chord and he doubled the 7th, which would get you a big F in theory class.  Meanwhile the outer voices are outlining a major 7th, which is why I chose to interpret this the way I did.
Comment: I can't hear a D in that 3rd harmony, which is the maj7 part of Ebmaj7, and would pre-empt the major 3 of the next harmony.
Comment: The D (note) is contained in the top voice; it is sounded on the down beat.
Comment: You're right, it is a D, and I believe the other notes are Eb, C and F. So it *could* be F13, no A, which features all the 4 notes, but I still think Ebmaj7 is awkward - only 2 notes fit. I looked at various dots for it, and they're all really badly written. They should get the big F in theory class!  That modulation to V pretty well has to have the secondary dominant ,G, and yes, there's # involved. Can't be helped.
Answer: It works because harmony is the result of adding melodies, and a scale, diatonic or chromatic is a very strong melodic element. The opening of this tune, the bit with the descending chromatic scale, goes: F, C/E, F7, Bb/D, Bbm/Db, F/C.   Very similar to the end of "When the Saints Go Marching In" which has become a jazz cliche.  The only reason this might trouble your sense of theoretical propriety is if you had slipped into the error of thinking that anything beyond diatonic chords need special justification.   I7 and iv (F7 and Bbm) are very commonly used, and need no excuse of "temporary modulation" or "borrowing".  Other common chromatic chords in the key of F are Ab, Eb, D7, G7 etc. etc.  I suppose the most "way-out" harmony in F major might be a B major chord.  But even that gets used - functionally as a tritone substitution or the beginning of a "cycle of 5ths" journey back to F, or decoratively - sliding up to a C chord.


Log into a specific server in a Windows 2012 Remote Desktop Collection

Question: I have 4 Windows 2012 Remote Desktop servers in 1 collection. All 4 of the servers have the RD Session Host role. I've also put the collection into High Availability Mode, so all 4 servers also have the RD Connection Broker role as well. I created a DNS A record for each of the 4 servers using the same name.
The load balancing works great. When I log into the DNS name of the collection I get which ever server is best at that moment in time.
For administration purposes, how do I log into a specific server of my choosing? I tried using just the IP address of a specific server but the connection broker takes over and potentially passes me to a different server. I want to be able to specify exactly which server I'm logging in to.
Answer: Use /admin after the computer name in your RDP client.  Allows administrative login without consuming CAL, and bypasses connection broker.


Perfect 4th is dissonant?

Question: Why is the perfect fourth dissonant in some cases when it does not sound dissonant?  When I play it in close position, it does not sound dissonant at all.  When I play it as a compound interval, I would kind of agree an extremely excessively tiny bit.  Why is it considered a dissonance sometimes when it actually does not?
Comment: This might have the answer you want: https://music.stackexchange.com/questions/64984/the-intervals-considered-dissonant-have-changed-since-the-middle-ages-how-s/65263?r=SearchResults#65263
Comment: Highly related: https://music.stackexchange.com/questions/67061/consonance-dissonance-of-5th-according-to-the-explanation-of-4th
Comment: It will depend what instrument/tuning it gets played on. Give us a clue at least.
Comment: @Tim I think it's reasonable to assume 12-TET here, and I doubt the instrument would make a huge impact on its consonance.
Comment: @Tim: It doesn't depend on the instrument except in artificial circumstances (no musical context) and with untrained listeners. What it really depends on is musical context.
Comment: I'm thinking from the premise that different tuning systems will produce slightly different intervals. 12tet instruments will have only one P4, whereas unfretted instruments and voices may vary that P4 - even to sound less dissonant. Personally, I think P4 and P5 are as dissonant or as consonant as each other. After all, they're their own inversions.
Answer: Dissonance has no universal definition but depends on style and context.
For example, the perfect fourth is a dissonance in the context of species counterpoint. Whether it sounds pleasant, subjectively, is irrelevant: in that domain, it behaves as a dissonance, that must be resolved through falling by step. Again the everyday definition of dissonance is not involved here. In this context, the word dissonant indicates a tension function: the music cannot stop on this note, it must resolve according to the rules of the style.
Answer: The consonance of the Perfect Fourth, like all intervals, depends on context. In this video, there's a great example of perfect fourths sounding really dissonant.

Also, certain styles of music treat it different ways. Consonance and dissonance are largely context and culture related in nature, and though people have attempted to quantify them, they really can't be pinned down, other than the ubiquitous "it sounds like...".
Comment: The perceived dissonance of the fourth is, I believe, ultimately related to its nonexistence in the harmonic series upwards from the fundamental tone.  It's first iteration is of course 3 to 4, and we naturally hear 4, the fundamental tone, as wanting to be at the bottom of the interval.  But that's just my nerdy geometric opinion.
Comment: @ScottWallace Wow, I never considered that. I would upvote that as an answer!
Comment: Nice answer, 45266!  Compared to the tritone, m2, M2, m7, and M7, the P4 sounds **very** consonant to me.  Also, that girl in the thumbnail looks nice.

Perfect 4th is dissonant?


Are strictly increasing/decreasing sequences considered monotone?

Question: A sequence which is either non-decreasing or non-increasing  is said to be monotone, this is the definition we have been given. But if a sequence is strictly increasing or strictly decreasing then that doesn't mean it is monotone so monotone is only if it is non-decreasing or non-increasing. Am I correct or not?
Answer: Monotone in words means it can only increase or it can only decrease. And in that case for instance a strictly increasing sequence is monotone since it cannot decrease.
Answer: A sequence of real numbers $(s_n)$ is:

monotone if $s_n \leq s_{n+1}$ for all $n \in \mathbb{N}$ or $s_n \geq s_{n+1}$ for all $n \in \mathbb{N}$.
strictly increasing if $s_n < s_{n+1}$ for all $n \in \mathbb{N}$.
strictly decreasing if $s_n > s_{n+1}$ for all $n \in \mathbb{N}$.

As $s_n < s_{n+1}$ for all $n \in \mathbb{N}$ implies $s_n \leq s_{n+1}$ for all $n \in \mathbb{N}$, a strictly increasing sequence is monotone.
As $s_n > s_{n+1}$ for all $n \in \mathbb{N}$ implies $s_n \geq s_{n+1}$ for all $n \in \mathbb{N}$, a strictly decreasing sequence is monotone.
In summary, strictly increasing and strictly decreasing sequences are monotone.
Answer: A sequence is monotone if it is either non-increasing or non-decreasing.
That is, $(s_n)$ is monotone if either $\forall n \in \mathbb{N}$, $s_{n+1} \geq s_n$ or $\forall n \in \mathbb{N}$, $s_{n+1} \leq s_n$
Comment: @ Ryan Stiles : so if it is strictly increasing or strictly decreasing then it's not monotone?


Significado de ?: ?= ?! ?<= ?<! em uma regex

Question: Em várias regex notei alguns simbolos que não parecem ser parte da captura mas algum tipo de funcionalidade. Gostaria de saber o nome ou termo desses simbolos e qual é a funcionalidade de cada um.
?:
?=
?!
?<=
?<!

Comment: Depende da linguagem.
Answer: Se estiver se referindo a regexes do .Net, usando a classe Regex, esses símbolos podem ser usados ao iniciar um grupo com parenteses:
( + simbolos + ... + )
O que significam:

?: Grupo não capturado: indica um grupo que não constará na lista de grupos capturados... note que isso vai ser considerado normalmente dentro do match, só não será um grupo, por exemplo:
String analisada: abc. 123 xpto<fim>
   Regex: \w+(?:\.|<fim>)
   Matches: abc., xpto<fim>

Os outros são assertivas, sem captura, e tampouco avançam na leitura:

?= Lookahead positivo: isso é uma assertiva, que verifica se o grupo pode ser encontrado iniciando-se na posição que se encontra, mas sem capturar nem avançar na leitura da string que está sendo analisada, por exemplo:
Ler palavras que acontecem antes de um ponto (.)
   String analisada: 123. xpto.
   Regex: \b\w+\b(?=\.)
   Matches: 123, xpto
?! Lookahead negativo: isso é uma assertiva, que verifica se o grupo não pode ser encontrado iniciando-se na posição que se encontra, mas sem capturar nem avançar na leitura da string que está sendo analisada, por exemplo:
Ler palavras que não acontecem antes de um ponto (.)
   String analisada: 123 xpto abc.
   Regex: \b\w+\b(?!\.)
   Matches: 123, xpto
?<= Lookbehind positivo: isso é uma assertiva, que verifica se o grupo pode ser encontrado terminando-se na posição que se encontra, mas sem capturar nem avançar na leitura da string que está sendo analisada, por exemplo:
Ler palavras que acontecem após um ponto (.)
   String analisada: abc. 123 xpto.
   Regex: (?<=\.\s*)\b\w+\b
   Matches: 123
?<! Lookbehind negativo: isso é uma assertiva, que verifica se o grupo não pode ser encontrado terminando-se na posição que se encontra, mas sem capturar nem avançar na leitura da string que está sendo analisada, por exemplo:
Ler palavras que não acontecem após um ponto (.)
   String analisada: abc. 123 xpto.
   Regex: (?<!\.\s*)\b\w+\b
   Matches: acb, xpto

Se for do seu interesse, eu costumo usar essa ferramenta para trabalhar com regexes no C#:
http://rad-software-regular-expression-designer.software.informer.com/1.4/
Comment: +1 só gostaria de frisar que isso não é específico do .Net, mas algo padronizado, disponível num grande número de *engines* de regex. O suporte (principalmente a *lookbehind*) varia, mas a sintaxe é a mesma em todas elas.
Comment: Muito show de bola. +1. Sempre que esquecer, vou vir nessa pergunta
Answer: Lookahead é uma forma de procurar strings que tenham ou não um determinado final. É utilizado (?⁼..) para o positivo, ou seja, que terminem com; e (?!..) para o negativo, ou seja, que não termina com.
Lookbehind faz o mesmo que o lookahead, porém, como o próprio nome diz, não procura depois, mas sim antes, da string dita. (?<=..) para o positivo e (?<!..) para o negativo.
Exemplo, considere a sequência foobarbarfoo.
bar(?=bar)    encontra o primeiro bar.
bar(?!bar)    encontra o segundo bar.
(?<=foo)bar   encontra o primeiro bar.
(?<!foo)bar   encontra o segundo bar.

Você também pode combiná-los:
(?<=foo)bar(?=bar)   encontra o primeiro bar.

Veja essa ferramenta online(RegExr) ela o ajuda a criar expressões, tal como identificar tipos, há também exemplos.
Aqui explica mais detalhadamente sobre o assunto.
Em breve atualizarei a resposta com mais informações.
Comment: O breve momento chegou?


Next step on music theory as a guitar player

Question: I've been playing the guitar as a hobby since 2013 and have been gradually gaining familiarity with it by playing all kinds of songs.
At first, I simply tried to remember the fingerings by reading guitar tabs and spent tons of time practicing to build up muscle memory, so I can play my favorite songs to please myself. After some time I started to find it boring to play without understanding what I'm playing.
So I bought some guitar music theory books to learn. The theoretical ones of them mainly talked about scales, intervals, chords, modes, and so on, while the practical ones focused on fingerings and ways to easily find notes on the fretboard. I started to read staff instead of tabs and do the practices in the books.
I know those are important concepts in music, but I'm still kind of confused on how to use them to facilitate the understanding of the structure of songs. Also I'm not pretty sure to what extend should I practice them. How can I get over this?
Comment: Are you playing in any bands/ensembles? Much much music have you written yourself yet?
Comment: I'm not sure this question is on topic because I think the answers are somewhat subjective. If you want to understand guitar, learning as many songs from as many genres as possible is probably the single best focus. If you want to understand *music*, then studying music theory (without the word "guitar" in front) and learning a second instrument will have a huge impact. In terms of *your* next step, first you have to tell us what your ultimate goal is.
Comment: The rather haphazard and varied nature of the current answers has confirmed my concerns that this is on the subjective side. There are so many areas of music theory that there will never be a single answer to what to learn next. Adding on to my comment about music theory no centered on guitar, I suggest this resource: https://viva.pressbooks.pub/openmusictheory/
Comment: @leftaroundabout No, but I was in a band as a drummer when I was in college. I never write music, just playing songs
Comment: I'll warn that knowing your scales/intervals/chords/modes aren't that helpful when attempting to understand the **form** of the song you're practicing. Quite often, if the entire song stays in one key throughout and isn't all that uniform chord progression-wise, these won't help you locate the **verses**, **choruses**, **bridge(s)**, or sometimes any **solo(s)**. (The solo(s) may actually be the easiest to locate due to them generally being more florid, with shorter average note lengths, and more difficult to play than other sections.)
Comment: I'd like to thank all of you who left an answer here. I'm so moved by your willingness to help and appreciate it so much!!! I have to admit it is a somewhat subjective question, as @ToddWilcox said. It's hard to pick the best answer because I do more or less learn from each of your answer and they are in different aspects. So I give all of them a upvote.
Answer:
I know those are important concepts in music but I'm still kind of confused on how to use them to facilitate the understanding of the structure of songs.

A word of caution first: music is what sounds good. Music theory is similar to grammatics in that it describes how to create something that "sounds good" in certain rules like grammatics describes in rules how "correct language" is formed, but both, music theory and grammatics take what is actually the case - actually spoken language here, actually created music there - and try to explain what has happened with these rules post festum.
And, quite similar to language, what people think "sounds good" changes over time like the way people express themselves in language. Study those rules, there is wisdom in them, but ultimately "listen to your ear".
There are two main parts of music theory: harmonics and counterpoint. The first one deals with what (which tones) sounds good together. The second deals with how to create musical development. The emphasis of the first is on the static aspect (what do tones sounding together do to each other), the emphasis of the second is on the dynamic aspect of musical occurrence (how to go to there from here).
A small digression. Suppose you read a romance novel and it goes like this: man and woman meet, they fall in love and live happy ever after. This doesn't sound all too interesting, no? Now, how about this: man and woman meet, they fall in love, but they have to overcome a lot of obstacles, the chances for them seem almost zero, but finally they are successful and, having found each other at last, live happy ever after. Better, yes?
Art - and music is no exception - is generally like that: there are certain expectancies of the audience and if you always fulfil them it becomes boring. If you always betray them it becomes arbitrary. But there is a happy medium of sometimes adding tension and sometimes releasing it, that makes a piece of art interesting and pleasing to watch/hear.
In music the most basic development is "going away - coming home", "create tension - release it". Try it yourself: play a C-major chord on your guitar, then a G7. Your feeling will be that there is a tension and you "crave" for hearing another C-major chord to release it. Why this is the case (among many other things) is explained with rules in harmonics. (For this specific instance: see "leading tone".)
I hope i could interest you in the further study of music theory, best of luck in your endeavours.
Answer: You need to study harmony, not just theory. An analogy of sorts is that theory is the alphabet and grammar but harmony is literature.
With harmony you learn the functions and qualities of chords and how they relate to and interact with each other. You will learn about basic to advanced chord progressions. This knowledge can be used to study, analyze and better understand music you already know and why things either work or they don't. It will also help you make educated choices for creating your own music if you choose to take that path.
Comment: would also help you understand what notes two or more people can play *with you* - for instance a bass player. The bassist in ACDC often plays the thirds leaving root and fifths to the guitarists.
Comment: @bigbadmouse Yes, inversions and slash chords are an important part of knowing harmony.
Answer: An understanding of music theory is pretty much a must for any serious musician, even a guitar player! If you want to be the guitar player that can add something to pretty much any band in any setting, the guitar player that gets called to play live gigs, the guitar player other people love to play with, you should:

know what chords exist in every common key
know what notes are in common chords (major, minor, 7th, etc.)
know what notes make up every common key (its scale, accidentals)
know intervals, what they sound like and how to play them
be able to read a chord chart
be able to transpose a chord chart (in a few minutes or, better, on the fly)
know chord functions in common keys and how to notate them (I, vi, V or 1, 6, 5)

Yes, that's a lot. Just start with one step and work from there. I suggest starting with a common guitar key (G is a good one) and learn it inside-out. Learn the G major scale, and all the chords in the key. Know the chord functions in the key (C is the four chord, and D is the five [dominant] chord). Know common chord progressions in G: C D Em G = 4 5 6 1 = IV V vi I.
Reading music is a plus, but 99.9% of guitarists won't need that skill. You can go far with an understanding of chords and scales, and the ability to read a chord chart like a boss.
Answer:
...The theoratical ones of them mainly talked about scales, intervals, chords, modes, and so on...

I can just imagine it. Endless scales and modes. Charts for each one on different tonics. Charts for matching scales to chords, etc. etc.
I think you might find you beginning theory efforts easier if you think in terms of two principle broad realms: general first terminology and notation, and second relative relationships.
The first is things like time signatures and note values, key signatures, interval names and chord spelling. Basically objective stuff you need to know to talk about music with some precision.
The second part is about understanding musical movement in relative terms. So instead of specific chords like G7 Cm, F7 B♭m, etc. you think of V7 i the dominant and tonic chords of any key, root change by descending fifth, G7 adds a minor seventh to a G major triad, or that minor seventh is added by dropping the root a whole step, Cm is just a change to the third of a C major triad, etc. etc. You eventually think/see/hear/finger mostly as interval changes. Root changes by descending fifth, not G to 7, the seventh of the dominant seventh chord falls a step to the third of the tonic triad, etc. etc.

...I started to find it boring to play without understanding ... After some time I started to find it boring to play without understanding what I'm playing.

One of the most practical things you can do to alleviate that boredom and immediately start learning patterns through actual playing is transpose the songs you already know through all keys.
Guitar presents a particular conundrum when it comes to transposing. Some transpositions are trivially easy on guitar, because you can just slide up/down the neck one fret at a time. Don't transpose your songs that way. Instead transpose by fifths and fourths.
Obviously this will first seem like just learning new fingerings, but when transposing songs pay attention to the interval relationships and which notes/strings are which chord members/scale degrees. Eventually there will be a merging of interval knowledge on the fretboard and common musical patterns. Theory gives you terminology to talk about these relationships and significant patterns.
Transposing is a fast track to this knowledge, because instead of thinking specific chords like G7 Cm transposes to F7 B♭m, your theoretical understand of what that progression is in relative terms is more like this: take any bass tone (you don't even need to give it a pitch letter name), play a major third and minor third above that bass (you don't need to know what the letters are), now move the bass down a perfect fifth or up a perfect fourth, and move the third up a half step, move the seventh down a whole step, as a bonus if I want to change the mode of that progression from minor to major the seventh moves down a half step rather than whole step.
It's very, very wordy to say, but it should become second nature to play. When you can play it and can name all the parts, all the relative relationships, that's your performance "muscle memory" enlighten by theory so you will be "understanding what [you're] playing."
Answer: To me it sounds like you look for a broader context and stimuli. If so, I'd like to suggest two books for further reading. Though the topic is Jazz music, they provide a lot of things to try and think about in any genre, on any tonal instrument.
The first one is "How to Play from a Real Book, for all musicians", by Robert Rawlins. It's compact, goes through even more details than you've mentioned, like comming up with bass lines, or forms. I.e. all concepts and "tools" you need to understand and turn the (in)famous Fake Book notations (or your own song-fragments) into real, lovely songs.
The second one is "jazz theory, from basic to advanced study", by Dariusz Terefenko. It's a bit overwhelming, but good to read and try, whenever you're reday for a certain chapter. Having started with drums myself, trying the material presented in this book really made me understand and use harmonies on piano, keyboard, synth, Hammond organ clone.
The first one is a kind of bird-eye view with very practical emphasis, while the second one is very detailed, nerdish if you like. Both talk about what you can do with chords and scales, and how successful solutions to certain challenges looked like.


Date Range Picker in 24 hour format

Question: I am using the Date Range Picker plugin for bootstrap and I am trying to get the values in 24hour format. I have set the option timePicker24Hour: true but it still doesn't return it in 24 hour format.
This is my code:
$("#reportdatetime").daterangepicker({
    timePicker: true,
    timePicker24Hour: true,
    timePickerIncrement: 30,
    locale: {
        format: 'MM/DD/YYYY h:mm'
    }
});

Fiddle: https://jsfiddle.net/rdawkins/k67xfa1g/1/
Answer: Use the correct locale format.To display time in 24 hours format use the following -
$("#reportdatetime").daterangepicker({
    timePicker: true,
    timePicker24Hour: true,
    timePickerIncrement: 30,
    locale: {
        format: 'MM/DD/YYYY H:mm'
    }
});

working example : https://jsfiddle.net/Ly0jh5pz/2
Comment: `H:MM` is incorrect. It should be `H:mm`. `MM` is used for months.
Comment: Incorrect. Check your fiddle. `H:MM` is giving incorrect result by default in your minute field. Even though the minute input box shows 00, the value being set in the date field is that of the month.
Comment: you can use both H:mm and H:MM.
Comment: Perfect! Thank you so much Arvind
Answer:

Answer: you can set AM/PM format into it if you want: here is some examples.
Andhere is describing how to use moment formats.

Date Range Picker in 24 hour format


Proving that $s$ is a reflexive closure of $r$

Question: I have this problem that I cannot figure out. Could you please help me out with this?
Let $r$ be a relation on the set $X$ and let $$R:=\{t:t \text{ is a  reflexive relation on } X \text{ with } r\subseteq t \}.$$ For $x,y \in X$ we have $x \, s \, y$ iff for each $t\in R$ we have $x \, t \, y$. Show that $s$ is the reflexive closure of $r$.
My idea so far was as follows.
Suppose $x,y \in X$ and $x \ s \ y$. It follows that for all $t\in R$ we have $x \ t \ y$. Since $r\subseteq t$ for all $t\in R$, it follows $r \subseteq s$ and also $s \subseteq t$. Since each $t\in R$ is reflexive, $s$ is also reflexive.
Could you please verify my idea? I'm sure it has some mistakes.
Answer: Your reasoning makes no sense.
Start with an arbitary $x\in X$ and observe that $xtx$ is true for every $t\in R$.
This because every $t\in R$ is reflexive.
Then by definition we have $xsx$.
Proved is now that $s$ is reflexive.

For proving that $s$ is the reflexive closure of $r$ it is enough now to show that $r\subseteq s\subseteq t$ for every $t\in R$.
An interesting fact: the reflexive closure of $r$ is the set $r\cup\Delta$ where $\Delta:=\{\langle x,x\rangle\mid x\in X\}$.
This set $\Delta$ is the so-called diagonal of $X$.
Comment: I don't understand the point "for every $r \in R$". Shouldn't that be "every $t \in R$"?
Comment: @Javiator Slip of the pen. I repaired.
Comment: Could you show me how I can show that $r$ is a subset of $s$?
Comment: If $xry$ then for every $t\in R$ we have $xty$ so that $xsy$ by definition.
Comment: So for the entire proof then would: Suppose $x \in X$. Then by definition of $R$ we have $xtx$ for every $t \in R$. It follows that $xsx$. Hence $s$ is reflexive.
For proving that $s$ is the reflexive closure of $r$, we show that $r \subseteq s$. Let $xry$ for $x,y \in X$. Then it follows that for every $t \in R$ we have $xty$, from which $xsy$ follows by definition. Hence $r \subseteq s$. Is this correct?
Comment: Yes. Formally you should finish by stating that $s$ is a subset of every $r\in R$. Then you have proved 3 things for $s$: it is reflexive, it contains $r$ and it is contained in every reflexive $t$ that contains $r$. These 3 things are characteristic for reflexive closure of $r$.
Comment: How can I show that $s$ is a subset of every $t \in R$?
Comment: Let $t\in R$ and have a look at the definition of $s$ to observe that $\neg xty\implies\neg xsy$. This is exactly the same statement as $xsy\implies xty$.
Comment: I was thinking exactly the same but how can we say that $\neg xty$? I need to show that $\neg xry \implies \neg xsy$ but for that I need to show $\neg xty$.
Comment: You don't have to show that $\neg xty$. But only that $\neg xty\implies\neg xsy$. The statement "if you go under the shower then you get wet" is simply true. No matter if you go under the shower or not.
Answer: The reflexive closure of $r$ is the least relation $r'$ such that whenever $x \, r \, y$  and $x, y \in X$, we have $x \, r' \, x$ and $y \, r' y$ and $x \, r' \, y$. (From this definition, we immediately see that $r'$ is reflexive.)
We first show that $r' \subseteq s$ and then show that $s \subseteq r'$.
Suppose $x \, r' \, y$ and $x,y \in X$.
There are now two cases. If $x = y$, then note that for every reflexive $t$ with $r \subseteq t$ we must have $x \, t \, x$. So $x \, s \, x$. If $x \neq y$, then we again have that $x \, t \, y$ for every reflexive $t$ with $r \subseteq t$. Again, $x \, s \, y$.
Next, suppose $x \, s \, y$. Again, there are two cases. If $x = y$, then by definition, we have $x \, r' \, y$. If $x \neq y$, then for every reflexive $t$ with $r \subseteq t$ we must have $x \, t \, y$. But this then means that $x \, r \, y$.
Answer: Yeah, this has some problems.

Since $r\subseteq t$ for all $t\in R$, it follows $r \subseteq s$ and also $s \subseteq t$.

How does it follow that $r \subseteq s$? That's not clear.
Fortunately, to show that $s$ is reflexive we don't need it ... yes, we need that $s$ is reflexive, but given its definition that's the easy part.
The harder part is that at some point you  need to show that $s$ is the closure of $r$, i.e. that $s$ is the smallest reflexive relation for which $r \subseteq s$. That part you haven't addressed at all yet.
Comment: Is the rest except the part you mentioned correct? Just to be sure about my reasoning.
Comment: @Javiator Well, there really isn't much more to your argument ... If you mean is your *setup* ok .. well, that's a little weird too. If you want to show reflexivity, you have to show $x \  s \ x$ for any $x$, so you wouldn't start with $x$ and $y$.
Comment: Thank you, I'll correct that. For the harder part: Can I say that since for $x,y \in X$ and $xry$ it follows that $xty$ for every $t \in R$, because by definition $r \subseteq t$, and thus $xsy$ and $r \subseteq s$?
Comment: No, that last part does not follow.  You have for any $t$ that $r \subseteq t$ and $s \subseteq t$, but from that you can't get $r \subseteq s$.  Here's what I would do: being the reflexive closure of $r$, $s$ is adding to $r$ any $$ that weren't already in $r$ (again, that just means $s$ is reflexive), but $s$ is not adding other new pairs to $r$. In other words, you need to show that for any $x$ and $y$ with $x \not = y$: if $ \in r$, then $ \in s$ (it doesn't remove any existing ones from $r$ either) and if $ \not \in r$, then $ \not \in s$
Comment: But with my comment I do show that every $ \in r$ is also $ \in s$ right? But not if $ \not \in r$ is also $ \not \in s$?


React classNames override className added by Javascript

Question: I have a problem that is When I adding class by JS method: divElement.classList.add('className'), but when I have state or props updated -> I decorate my component with a class just like below:

Then, classes which I added by JS method disappeared.
That is a problem of react or I do something wrong?
Anyone can explain why? Thanks a lot.
Answer: The value of the components is recalculated/reevaluated on each re-render unless its memoized (ie. useMemo, useCallback) or is using React state/hooks like useState or useEffect.
Therefore, although you were able to modify the class name with javascript that doesn't cause a re-render, the clsx() will be reevaluated in the next render, so whatever you did with the class name via vanilla Javascript code won't be relevant.
I would recommend keeping using clsx to add/remove any class names, and moving the logic into a useEffect or storing the value into a useState.


Refatorar o código usando o factory pattern sem o uso da condição if-elseif

Question: Tenho o seguinte Factory. Nele eu instancio uma classe responsavel por dar parse no arquivo em questão. Para que seja instanciado esse parser, primeiramente é verificado nas condições se aquele parser é o correto para realizar o processamento.
public class InvoiceParserFactory
{
    public static InvoiceParser getParser(InvoicePdfReader reader)
    {
        String invoiceText = reader.getText();

        if (isXxxParser(invoiceText)) {
            return new XXX_PARSER(invoiceText);
        }
        else if (isYyyParser(invoiceText)) {
            return new YYY_PARSER(invoiceText);
        }
        else {
            throw new InvoiceException("Can't find parser.");
        }
    }

    private static boolean is_XXX_PARSER(String invoiceText) {
        Pattern p = Pattern.compile("xxx_regex");
        Matcher m = p.matcher(invoiceText);

        //as condições aqui são diferentes, portanto não da pra simplificar esses métodos
    }

    private static boolean is_YYY_PARSER(String invoiceText) {
        Pattern p = Pattern.compile("yyy_regex");
        Matcher m = p.matcher(invoiceText);

        //as condições aqui são diferentes, portanto não da pra simplificar esses métodos
    }
}

Aqui um exemplo de um PARSER:
public final class XXX_PARSER extends InvoiceParser
{
    @Override
    protected void parseSomeText() {
        //implementação
    }
}

Essa lógica não escala nesse design pattern, já que terei centenas ou até milhares de PARSERS. Vi em alguns exemplos que seria interessante colocar todos os PARSERS em uma collection e implementar um método estatico em cada PARSER para verificar se o PARSER em questão é o que precisa ser instanciado. Só que ai me depararia com a necessidade de instanciar o PARSER antes mesmo de usa-lo, pois teria que usar talvez Set<InvoiceParser> e depois set.add(new XXX_PARSER) e assim em diante, só que se eu instanciar dessa maneira em uma collection eu quebro todo meu algoritmo que está baseado no construtor da classe InvoiceParser, que é pai de todos os PARSERS.
Qual seria a melhor forma de refatorar esse Factory para que atenda minha necessidade?
Comment: Se guardar um set do tipo `Class` não precisa de instanciar de antemão os vários parsers. Pode ate guardar um map com a class e respetiva regex, e se algum dos elementos jogar, instancia o parser por reflexão.
Comment: Qual versão do Java você está utilizando?
Comment: Estou utilizando Java 8
Answer: Você poderia utilizar uma enum com um elemento para cada tipo de parser. Nela você teria a forma como o parser é criado e o pattern correspondente. Exemplo:
Classe InvoiceParser:
private abstract class InvoiceParser {/*métodos da classe*/}

Duas implementações como exemplo:
private class XxxParser extends InvoiceParser {
    public XxxParser(String text) {}
}

E:
private class YyyParser extends InvoiceParser {
    public YyyParser(String text) {}
}

A enum com um factory method que encontra o parser adequado:
public enum Parser {
    //O primeiro parâmetro é a regex
    //o segundo é a forma como se cria o parser
    XXX_PARSER("xxx_regex", XxxParser::new),

    YYY_PARSER("yyy_regex", YyyParser::new);

    //interface com um método para criar o parser
    //permite o uso de lambda e method references
    @FunctionalInterface
    private static interface ParseCreator {
        InvoiceParser create(String text);
    }

    //cache interno
    private static final Parser[] VALUES = Parser.values();

    private final Pattern pattern;

    private final ParseCreator creator;

    private Parser(String regex, ParseCreator creator) {
        this.pattern = Pattern.compile(regex);
        this.creator = creator;
    }

    //factory method que encontra o parser adequado ao reader
    public static final InvoiceParser forReader(InvoicePdfReader reader) {
        for(Parser parser : VALUES) {
            if(parser.pattern.matcher(reader.getText()).find()) {
                return parser.creator.create(reader.getText());
            }
        }
        throw new IllegalArgumentException();
    }
}

Caso a regex não seja o único critério utilizado para identificar o parser adequado, você poderia adicionar a enum um objeto responsável por verificar esses critérios adicionais específicos de cada parser, nesse caso a enum ficaria dessa forma:
public enum Parser {
    //o primeiro parâmetro é a regex
    //o segundo é a forma como se cria o parser
    //o terceiro são os critérios adicionais
    XXX_PARSER("xxx_regex", XxxParser::new, reader -> {
        //suas condições adicionais
        return true;
    }),

    YYY_PARSER("yyy_regex", YyyParser::new, reader-> {
        //suas condições adicionais
        return true;
    });

    //interface com um método para criar o parser
    //permite o uso de lambda e method references
    @FunctionalInterface
    private static interface ParseCreator {
        InvoiceParser create(String text);
    }

    //interface com um método para verificar se o parser é o adequado
    //permite o uso de lambda e method references
    @FunctionalInterface
    private static interface Parseable {
        boolean canParse(InvoicePdfReader reader);
    }

    //cache interno
    private static final Parser[] VALUES = Parser.values();

    private final Pattern pattern;

    private final ParseCreator creator;

    private final Parseable parseable;

    private Parser(String regex, ParseCreator creator, Parseable parseable) {
        this.pattern = Pattern.compile(regex);
        this.creator = creator;
        this.parseable = parseable;
    }

    //factory method que encontra o parser adequado ao reader
    public static final InvoiceParser forReader(InvoicePdfReader reader) {
        for(Parser parser : VALUES) {
            if(!parser.pattern.matcher(reader.getText()).find()) {
                continue;
            }
            //verifica os critérios específicos do parser
            if(parser.parseable.canParse(reader)) {
                return parser.creator.create(reader.getText());
            }
        }
        throw new IllegalArgumentException();
    }
}

Para encontrar o parser adequado bastaria fazer:
InvoiceParser parser = Parser.forReader(reader);

Comment: @GustavoPiucco Não. Cada vez que você evoca o método `create` na linha `return parser.creator.create(reader.getText());` ele vai criar um novo *parser*.
Comment: @GustavoPiucco Não acho que exista uma "melhor prática" para esse caso. É simplesmente uma questão de utilizar a melhor solução para o problema. Se você acha que utilizar um `Map` vai ser a melhor, seja por um aumento de performance, melhora na legibilidade ou mesmo manter certa consistência no código (caso, por exemplo, você tenha solucionado problemas parecidos com um `Map`) vá em frente e use, não há problema algum.
Comment: @GustavoPiucco Só seriam necessárias algumas adaptações (a criação de uma nova classe para agrupar algum dos valores), visto que, na segunda `enum`, são utilizados 3 parâmetros no construtor, enquanto um `Map` só aceita 2 valores (chave e valor).
Comment: Quando se usa o XxxParser::new é instanciado de imediato o parser? Ou seja, todos os parsers colocados no enum são pré-instanciados? Se sim, isso seria um problema pois eu teria que tirar lógicas do construtor dos parsers
Comment: Não seria uma "melhor prática" usar um Map estático com todos os parsers ao invés de Enum?
Answer: Você pode usar um ServiceLoader. Esse é o mecanismo que foi introduzido no Java 6 para resolver problemas exatamente desse tipo que você tem. No seu caso, o InvoiceParserFactory corresponde a um serviço. As implementações desse serviço estão espalhadas no classpath/modulepath em um monte de lugares. A função do ServiceLoader é encontrar todas as implementações, instanciá-las e dar o resultado.
Primeiro, vamos dar uma mexida na sua classe InvoiceParserFactory (que se tornou uma interface):
package com.example.invoice;

import java.util.ServiceLoader;

public interface InvoiceParserFactory {
    public boolean acceptsText(String text);

    public default boolean acceptsText(InvoicePdfReader reader) {
        return acceptsText(reader.getText());
    }

    public InvoiceParser newParser(String text);

    public default InvoiceParser newParser(InvoicePdfReader reader) {
        return newParser(reader.getText());
    }

    public static InvoiceParser getParser(InvoicePdfReader reader) {
        ServiceLoader<InvoiceParserFactory> loader =
                ServiceLoader.load(InvoiceParserFactory.class);

        for (InvoiceParserFactory factory : loader) {
            if (factory.acceptsText(reader)) {
                return factory.newParser(reader);
            }
        }

        throw new InvoiceException("Can't find parser.");
    }
}

Essa interface aproveita-se do fato de que a partir do Java 8, interfaces podem ter métodos estáticos ou com implementações default. A partir do Java 9, métodos privados também são permitidos em interfaces.
Vamos supor que essa interface está dentro do JAR invoice-api.jar.
Então, no arquivo xxx.jar, você põe essa classe:
package com.example.xxx.invoice;

import com.example.invoice.InvoiceParserFactory;

public class XxxInvoiceParserFactory implements InvoiceParserFactory {
    // ...

    public XxxInvoiceParserFactory() {
    }

    @Override
    public boolean acceptsText(String text) {
        Pattern p = Pattern.compile("xxx_regex");
        Matcher m = p.matcher(invoiceText);
        // ...
    }

    @Override
    public InvoiceParser newParser(String text) {
        return new XxxParser(text);
    }
}

Dentro do xxx.jar, você põe um arquivo com o mesmo nome da classe/interface do serviço oferecido (não da implementação) dentro de uma pasta chamada services dentro da pasta META-INF. Por exemplo, no caso acima, o arquivo se chamaria META-INF/services/com.example.invoice.InvoiceParser. Dentro desse arquivo você põe o nome completo da classe implementadora:
com.example.xxx.invoice.XxxInvoiceParserFactory

Vamos supor que o JAR yyy.jar tenha duas implementações distintas de InvoiceParser, uma chamada YyyBlueInvoiceParser e a outra YyyRedInvoiceParser. Nesse caso no arquivo META-INF/services/com.example.invoice.InvoiceParser dentro desse outro JAR você põe isso:
com.example.yyy.invoice.YyyBlueInvoiceParserFactory
com.example.yyy.invoice.YyyRedInvoiceParserFactory

Ou seja, o que acontece é que cada JAR tem dentro da pasta META-INF/services, arquivos com os nomes dos serviços oferecidos, dentro de cada um desses arquivos, está o nome das implementações existentesa par esses serviços.
Uma aplicação que tenha xxx.jar, yyy.jar e invoice-api.jar no classpath conseguirá enxergar essas três implementações. Para alterar as implementações é fácil, basta que cada JAR que contenha alguma(s) implementação(ões) do seu serviço a(s) declare dentro do META-INF/services/com.example.invoice.InvoiceParser dentro do próprio JAR e então é só adicionar o JAR ao classpath e o ServiceLoader o encontrará.
Entretanto, há um porém. Para que o ServiceLoader possa localizar e instanciar os serviços, eles devem estar em classes públicas, ter um construtor público sem parâmetros e a classe correspondente tem que ser uma implementação ou subclasse do serviço oferecido.
Idealmente você deveria ter as subclasses de InvoiceParser como serviço ao invés das implementações de InvoiceParserFactory. Entretanto, para conseguir isso, você precisa refatorar as suas subclasses de InvoiceParser de uma forma que consiga se livrar da necessidade de ter o PDF como parâmetro para poder ter um construtor sem parâmetros.
Há uma outra forma de oferecer serviços em JARs modulares (Java 9+) que estejam no modulepath ao invés do classpath, mas isso é um pouco mais complicado. O javadoc da classe ServiceLoader descreve isso com detalhes.
Também já falei um pouco sobre o ServiceLoader nessa outra resposta minha.
Comment: Não seria o ServiceLoader que preciso, acredito que é muito mais simples do que você acabou imaginando. O regex serve para identificar o formato/tipo da fatura, e após identificar esse formato, instanciar o parser responsavel de extração de dados dessa fatura. Meu problema era só resolver a quantidade enorme de if-elseif para instanciar esses parsers que se encontram no mesmo JAR. Pois para cada parser, tem um regex que identifica que aquele parser é o que deve ser utilizado, entende? De qualquer forma essa resposta me ajudou pra resolver um problema futuro.
Answer: Você pode utilizar a biblioteca Reflections e então fazer isso:
public class InvoiceParserFactory {

    private static final Set<Class<? extends InvoiceParser>> SUB_TYPES;

    static {
        Reflections reflections = new Reflections("com.example.meupacote");
        SUB_TYPES = reflections.getSubTypesOf(InvoiceParser.class);
    }

    public static InvoiceParser getParser(InvoicePdfReader reader) {
        String invoiceText = reader.getText();

        for (Class<? extends InvoiceParser> k : SUB_TYPES) {
            try {
                return k.getDeclaredConstructor(String.class).newInstance(invoiceText);
            } catch (Exception e) {
                // Engole e pula.
            }
        }
        throw new InvoiceException("Can't find parser.");
    }
}

Em cada implementação de InvoiceParser, você deve colocar um construtor que lança uma exceção se a String passada não for compatível com ele:
public class XxxInvoiceParser extends InvoiceParser {

    // implementação...

    public XxxInvoiceParser(String invoiceText) {
        if (!isXxx(invoiceText)) throw new IllegalArgumentException();
        // implementação...
    }

    @Override
    protected void parseSomeText() {
        // implementação...
    }

    private static boolean isXxx(String invoiceText) {
        Pattern p = Pattern.compile("xxx_regex");
        Matcher m = p.matcher(invoiceText);

        // implementação...
    }
}

Comment: Sim. Nos pacotes e em quaisquer subpacotes. Não sei acerca da performance, mas uma das finalidades de haver o pacote especificado é exatamente essa. No entanto, eliminar esse custo de desempenho é fácil (alterei a resposta para isso), pois o conjunto de classes só precisa ser pesquisado uma vez.
Comment: @GustavoPiucco Ainda existe um gargalo de que ele tem que testar todas as implementações uma por uma até achar aquela que é adequada. Se esses testes forem pesados, encontrar a implementação correta é complicado. Entretanto, tanto o código da sua pergunta como todas as respostas aqui descritas tem esse mesmo problema. A solução é que as implementações rejeitem um PDF que não lhes pertençam o mais rápido possível por meio de testes muito simples e óbvios e com isso, mesmo com milhares de implementações distintas, o impacto seja pequeno.
Comment: Esse código vai pegar todas as implementações de InvoiceParser dentro do pacote com.example.meupacote automaticamente? Reflection comparado ao exemplo do @Felipe Marinho, perde em performance? Em escala(muitas implementações de InvoiceParser) seria um problema?


how to solve Fatal error: Cannot use [] for reading

Question: i kept  getting error : Fatal error: Cannot use [] for reading
for($m=1; $m<=12; ++$m){
    $monthName=strtolower(date('F', mktime(0, 0, 0, $m, 1)));
<input style='text-align:center' class='form-control ".$monthName."' type='text' size='60' id='".$monthName."' name='".$monthName[]."' value='".$$monthName."'>
}

i want to use array [] for input name..how do i fix this
Comment: Put the square brackets outside of the quotes
Comment: I'm hoping this isn't the whole code block, because your syntax is completely off.
Answer: You combined the square brackets with the php variable, you should add your square brackets externally with the variable as
for($m=1; $m<=12; ++$m){
    $monthName=strtolower(date('F', mktime(0, 0, 0, $m, 1)));
    <input style='text-align:center' class='form-control ".$monthName."' type='text' size='60' id='".$monthName."' name='".$monthName."[]' value='".$$monthName."'>
}

Answer: for($m=1; $m<=12; ++$m){
    $monthName=strtolower(date('F', mktime(0, 0, 0, $m, 1)));
<input style='text-align:center' class='form-control ".$monthName."' type='text' size='60' id='".$monthName."' name='".$monthName."[]' value='".$$monthName."'>
}

Comment: Thank you for this code snippet, which may provide some immediate help.  A proper explanation [would greatly improve](//meta.stackexchange.com/q/114762) its educational value by showing *why* this is a good solution to the problem, and would make it more useful to future readers with similar, but not identical, questions.  Please [edit] your answer to add explanation, and give an indication of what limitations and assumptions apply.


Erro ao retornar objeto em array - Javascript

Question: Olá, estou com um erro ao retornar objeto em array, objeto não retorna.
    let myArray = [{
        "name": [{
            id: 0,
            name: "Jhon"
        }, {
            id: 1,
            name: "Sara"
        }]
    }],

    objIndex = myArray.findIndex((obj => obj.id == 1));

    console.log(myArray[objIndex])

Comment: Em vez de `findIndex`, pode simplesmente fazer `result = myArray[0].name.find(obj => obj.id == 1)` e `result` será o objeto que vc procura (`findIndex` só faz sentido se vc quer saber o índice, mas se quer somente o objeto, usar `find` é mais "direto ao ponto"). Outro ponto é rever essa estrutura, precisa mesmo que seja um array com um único elemento, que por usa vez é um objeto, que contém outro array com outros objetos? A estrutura indicada na resposta abaixo (apenas um array que contém os objetos, sem precisar do "name") é mais simples
Comment: E qual é o erro?
Comment: @JéfBueno Alterei o post, objeto não retorna.
Comment: @hkotsubo myArray[0].name, ta ai a resposta hahahaha, valeuuu!!
Answer: O problema é bem claro, não existe id nos itens de myArray. É fácil ver isso apenas fazendo um log no primeiro (e único item do array).

let myArray = [{
  "name": [{
    id: 0,
    name: "Jhon"
  }, {
    id: 1,
    name: "Sara"
  }]
}];

console.log(myArray[0]);

É mais fácil ver o problema lendo o código em partes.
let myArray =
[
  // ^ Inicia um array
  {
    // ^ Inicia um objeto
    "name":
      // ^ Propriedade "name" do objeto
    [
      // ^ Inicia um array (name então é um array)
      {
        // ^ Inicia um objeto (name é um array de objetos)
        id: 0,
        name: "Jhon"
        // ^ Propriedades do objeto
      }, {
        // ^ Outro objeto dentro do array (que está em name)
        id: 1,
        name: "Sara"
      }
    ]
  }
]

Aparentemente você apenas digitou de forma errada a inicialização dos objetos. Neste caso, é só corrigir isso.

let myArray = [{
  id: 0,
  name: "Jhon"
}, {
  id: 1,
  name: "Sara"
}]

const objIndex = myArray.findIndex((obj => obj.id == 1));
console.log(myArray[objIndex])
Comment: No caso precisaria acessar o name primeiro, dessa forma consegui rodar já.
Comment: @Josimara Não entendi seu comentário
Comment: Você não deveria ter modificado o myArray, e sim usado o meu.
Comment: @Josimara Você deveria ter especificado isso na pergunta...


Do the eigenvalues of the product of a positive diagonal matrix and a skew-symmetric matrix still have zero real part?

Question: Let $A$ be a $n\times n$ diagonal matrix with real, positive entries on the diagonal. Further, let $B$ be a $n\times n$ invertible, skew-symmetric and real matrix. Now let $n$ be even. Then it is known that the eigenvalues of $B$ all have zero real part.

Is this also true of the product $AB$?

I tried doing some simulations in Matlab: The real parts were not zero, but always $\sim 10^{15}$ times smaller than the imaginary parts, so I suspect this is a rounding error on Matlabs part. But how to prove it?
Answer: Let $R$ be the (symmetric) root of $A$. Then, $AB$ and $RBR$ are similar and we have
$$ (RBR)^T = RB^T R = -RBR. $$
That is, $RBR$ is skew-symmetric too. In particular the eigenvalues of $RBR$ are imaginary (including zero) and the same as $AB$.
Comment: "Symmetric root"? It's diagonal with positive entries, just call it a square root...
Comment: @J.M.isn'tamathematician square root for matrices is ambiguous. Symmetric root not
Comment: Hmm, I thought I had it, but what can I say about the eigenvalues of $RBR$? I know $B$ and $RBR$ are congruent, but when $B$ is not symmetric, I don't know how to proceed (if it was I could use Sylvester's law of inertia). I feel like I'm missing something very obvious.
Comment: @Lovsovs, the terminology is admittedly muddled here. To be explicit: try performing a similarity transformation. with $\mathbf A^{-1/2}$, which is equivalent to taking the inverse square root of the diagonal entries of $\mathbf A$.
Comment: @Lovsovs I expanded the answer. Hope it helps.
Comment: @user251257 Indeed it did, thank you for your time!


Can't connect to vsftpd on Ubuntu 10.04

Question: I started the vsftpd on Ubuntu 10.04, but can't connect to it.
The error says(FTP Client):
Status: Connecting to 124.205.xx.xx:21...
Error:  Connection timed out
Error:  Could not connect to server

I've checked the server status, and vsftpd is running:
$ ps ax | grep vsftpd
23646 ?        Ss     0:00 /usr/sbin/vsftpd
23650 pts/1    S+     0:00 grep --color=auto vsftpd

port 21 is under listening as well:
$ netstat -tlnp | grep 21
(No info could be read for "-p": geteuid()=1000 but you should be root.)
tcp        0      0 0.0.0.0:21              0.0.0.0:*               LISTEN      -

I can connect to localhost:
$ ftp localhost
Connected to localhost.
220 (vsFTPd 2.2.2)
Name (localhost:jlee):
331 Please specify the password.
Password:
230 Login successful.
Remote system type is UNIX.
Using binary mode to transfer files.
ftp>

Here is iptables output
$ sudo iptables -vL
Chain INPUT (policy ACCEPT 191 packets, 144K bytes)
 pkts bytes target     prot opt in     out     source               destination

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

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

What's the problem here?
Comment: Is 124.205.xx.xx a static or dynamic IP?
Comment: What does netstat -tlnp report? You just tried to list all the open udp ports with your netstat command, that can't be right... :-)
Comment: Can you post tcpdump outputs from both client and server side?
Answer: Check if your ftp client is on activ or passiv mode.
If it's on passiv mode, you have to add some parameters. Something like this :
pasv_enable=YES
pasv_promiscuous=NO
pasv_min_port=40000 as you want
pasv_max_port=41000
pasv_address=xxx.xxx.xxx.xxx (your ip)
port_promiscuous=NO
Answer: I just installed vsftpd with apt-get install vsftpd on my Ubuntu 10.04 laptop, and the daemon worked out of the box.
Have you modified the vsftpd configuration files?
Does ftp localhost work for you if you try to do that on your server?
Do you have iptables enabled? Does iptables -vL list some rules?
Comment: Thanks for the answer. I've updated the output of `ftp localhost` and `iptables -vL`, please take a look at it. I used apt-get install vsftpd too, and it worked. But after a server sudden down, it doesn't work now
Answer: It's not your server firewall, it's not your vsftp configuration, it's something between you and your server =P
Can you connect from your pc to any other ftp server? Can you connect to your ftp from another host?
Answer: I am not sure but it might be apparmor daemon which might be denying you to connect it to your
FTP server , disable apparmor and see if it helps
 service apparmor stop

Can't connect to vsftpd on Ubuntu 10.04