Why is a minor 3rd consonant but an augmented 2nd dissonant?

Question: I am currently reading the Jazzology and on the chapter per the consonant and dissonant intervals I came across this statement:

while a minor 3rd is consonant, an augmented 2nd is dissonant.
   (page 6)

So my question is this:
Why is a minor 3rd consonant but an augmented 2nd dissonant, since they --technically-- are the same note?
Comment: Just to keep as reference, the complete quote is: `Enharmonically equivalent intervals usually appear in different contexts and thus should not be considered the same as their counterparts, i.e. while a minor 3rd is consonant, an augmented 2nd is dissonant.`
Comment: They're only actually the same note if you're tuning system is equal temperament. Jazz often isn't.
Comment: @OrangeDog can you expand your comment in an answer? It seems interesting
Comment: Someone else can take the rep, but here are some links.
http://en.wikipedia.org/wiki/Musical_tuning
http://en.wikipedia.org/wiki/Musical_temperament
http://en.wikipedia.org/wiki/Interval_%28music%29#Size_of_intervals_used_in_different_tuning_systems
Comment: And as @Dave mentions, the "same" note can be 40 cents different depending which direction you're coming from in his example.
Comment: Aw drat, missed my grammar error due to re-writing comment half-way though.
Comment: An A2 is **augmented**, which makes it dissonant.
Answer: Well, without any further context there is no possible distinction between a minor third and an augmented second as they are indeed the same note, technically.
However, the phrases minor third and augmented second make reference not only to that space of three semitones, but also to the relationship that this interval plays within a given chord or scale. Since almost every scale known to the Western world has some form of third, a scale or chord with an augmented second would most probably have another kind of third as well, making the augmented second seem like an added dissonance in context.
Consider this chord: C7#9. (The #9 can be considered equivalent to an augmented second). The naming convention of the chord assumes there will be a major third. So the chord is 1, 3, 5, 7 and #9. The last note is not an essential part of the chord's structure, and will sound dissonant.
If you just have a C and a D#/Eb, it doesn't really matter whether you call it a D# or an Eb. But when you're talking about the role that note plays within another structure, then there are reasons for naming it an augmented second (to make clear it is not a minor third).
Hope this helps!
Comment: Good point and well said. I would only add that the augmented 2nd shows up as often or even more often as a *melodic* interval, and it is always a melodic dissonance in common practice music while a melodic minor third is usually consonant (barring some sort of chromaticism)
Comment: @PatMuchmore Good point, I think it can be reasoned both from a common practice perspective as well as the perspective of contemporary jazz theory. I think it would add clarity if someone could give an example of how a note used in a melodic context might be an augmented second escaping from the implied harmony and thus dissonant, or a minor third in keeping with the harmony. But I don't feel like firing up Finale! Maybe later.
Answer: A key thing to keep in mind is that technically a minor 3rd and an augmented 2nd are different pitches (have different notional fundamental frequencies), at least in anything other than equal temperament.  In just intonation, these two pitches differ by approximately 40 cents (list of intervals), enough to make a perceptable difference in the degree of consonance. (Also note that some types of mean-tone temperament can also represent this difference).  Thus these different notes are different and have different harmonic behaviour in the context of a chord.
Even in the context of music intended for performance in ET, notating the enharmonic notes in particular ways can provide the performer with information on the composer's intent.
Comment: @JCPedroza 1) they behave different harmonically because they are (in JI and some other tuning systems) different pitches 2) 40 cents in a harmonic context is pretty discernible (added to answer in edit) 3) the composer is indicating whether the given given interval is intended to be consonant or dissonant, and how it's intonation should be if performed by an instrument with fine pitch control.
Comment: Good point, Dave. Unfortunately, the distinction between them is now lost on most of us because hundreds of years ago a bunch of barbers and blacksmiths conspired to ruin music by cursing it with only 12 notes. :(
Comment: @Grey - true to a degree, but it doesn't half make changing key a doddle...
Comment: 1) I don't think this answers the question. 2) Would that small frequency difference (measured in commas) influence the argument? Would that difference make a difference in consonance or dissonance? 3) Given the predominance of equal temperament, one would assume that the author is taking it into consideration.
Comment: 3) The author is talking about context and not frequency difference, and he is explicit about it. The complete quote (page 6) is: `Enharmonically equivalent intervals usually appear in different contexts and thus should not be considered the same as their counterparts, i.e. while a minor 3rd is consonant, an augmented 2nd is dissonant.`
Comment: Could those be considered different kinds/types of dissonances? One contextual, where the frequency doesn't change (like in the example, using ET) and one based on actual frequency relationships and differences (the one you present with JI)?
Answer: One reason is that if you're specifying an augmented 2, its probably because you have an augmented second and a major third in the chord. These notes are only a half step apart, and that is very dissonant.
Since we don't have, for example, a "minor fourth" interval, the third will always be major if an augmented 2 is involved. I guess there could be exceptions, but if there isn't also major third in the chord, it would just be written as a minor third interval.
Comment: Sorry, yes #9 is basically what I meant but as far as a scalar representation of the chord I used a #2 as the example.
Comment: There's not going to be a #2 and a maj3 in a particular chord. The clash is too great. There is a #9, which could be argued amounts to the same thing, but since it's an octave away from the note it would have clashed with, it's sonically not a problem. Close to the 'Hendrix chord'.
Comment: It could also be an augmented 3rd which is the same as a perfect 4th. Then it is less dissonant because of the major 2nd interval in the chord and you could augment that augmented 3rd to get a doubly augmented 3rd or augmented 4th and this gives you a diminished chord which is very commonly used in music
Answer: It seems to stem not from the meaning that we attach to the words now, but the past. Consonant meant it sat well in the key, dissonant, the opposite. So, when WRITTEN in music, a minor 3rd belongs in a given set of notes, whereas a #2 is not found.It appears to be more of a technicality than a reflection of what it actually sounds like.
Turn a minor 3 upside down, and it's a major 6th.Supposedly consonant. Turn a #2 upside down, and it's a diminished 7th. Both augmented and diminished intervals were labelled dissonant.
Answer: A sound example would make it much easier. Try this experiment:
Play a Cmajor scale and some I-IV-V-I in this key, then suddenly play the harmonic interval C-D#. It will sound dissonant in this context, the D# sounds like a leading tone to E (your brain will ask for solving it to E). You don't need to have the C-E in the same chord. It is enough to have the key context in your mind-ear.
Then play a Cminor scale and some cadences in this key, suddenly play the C-Eb (actually same piano keys as C-D#). In this context they will sound consonant, that is the reason for different name.
So they are different both in the writing and in the sound, in a tonal context. They only sound the same in atonal music. You would never find Beethoven mistaken D# for Eb in his written scores, but I wouldn't say the same for some common chord charts you find around.


Why is boolean toggling to "true" but not back to false?

Question: In my listView adapter class I have a delegate to assign a function to each button in my listview. This button should toggle a boolean called cupboard inside my "Spices" object. It works upon the first click and changes it to "true". But it won't go back to false again. Any idea what is causing it to not set back to false again? This is my first post here so apologies if it's a duplicate.
I've tried changing the default value of "false" to having a getter and setter and tried different if/else statements to toggle the bool values as well.
This is from the custom listView adapter inside the GetView() function:
Button AddToCupboard = row.FindViewById<Button>(Resource.Id.AddToCupboard);
//Adds onclick event for "Add to cupboard"

AddToCupboard.Click += delegate
{
    var item = mItems[position].cupboard;
     item = !item;
    Console.WriteLine(item);
};

My Spice class:
class Spice
{
    public string name { get; set; }
    public string flavour { get; set; }
    public string picture { get; set; }
    public string substitute { get; set; }
    public string description { get; set; }
    public string uses { get; set; }

    public bool cupboard { get; set; }
    public bool list { get; set; }
}

I expected console to output True then False when the same button is pressed twice, but it just stays at true.
Answer: That happens because you are not actually changing the cupboard value from the Spice object.
AddToCupboard.Click += delegate
{
    var mItem = mItems[position];
    mItem.cupboard = !mItem.cupboard;
}

In your example, you would copy the cupboard value into a local variable, toggled it from T to F and that was all. The mItems array would stay unmodified because all the operations were done on a copy of the interested variable.
Comment: Thank you! worked like a charm. Can you explain why declaring "mItems[position].cupboard" doesn't change the cupboard value? Im quite new and want to learn from mistakes.
Comment: So I was changing the value of "item" not the value of "cupboard"?
Comment: Yes. I was just writing a longer response. You copied the value of cupboard into another variable that is no more linked to the mItems[position].cupboard. That means if you change the value of the item, it does not automatically change the value of the mItems[position].cupboard.
Comment: In my example, from your mItems array, I got a reference to one of the object and I am changing a property of the object. This is where things are different. An object is a reference type while an integer/boolean/decimal is a value type. I recommend you to read about Value Types (https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/value-types) and Reference Types (https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/reference-types).


Solve recurrence relation: $a_n=3a_{n−1}+5a_{n−2}−7a_{n−3}$

Question: I hope can you help me, I want to solve this recurrence relation:
$a_n=3a_{n−1}+5a_{n−2}−7a_{n−3}$ with initial values $a_1=4, a_2=8, a_3=2$
Using synthetic division I get the roots: $1, 1-2\sqrt{2}$ and $1-2\sqrt{2}$
What are the characteristic equation for three different roots? I guess that:
$ a_n = c_1(r_1)^n + c_2(r_2)^n + c_3(r_3)^n$ where $r_1, r_2, r_3$ are the roots.
Can you help me solve this problem?
Comment: Note that you have a typo: the two irrational roots have to be 'conjugate' to each other (they should be $1\pm2\sqrt2$, presumably.)
Comment: http://nms.lu.lv/wp-content/uploads/2016/04/21-linear-recurrences.pdf
Comment: You are on the right lines: you need to put in $n=1$, $2$ and $3$ to get linear equations for the $c_i$.
Comment: The characteristic equation is different for irrational roots?
Answer: Recurrence $a_n=3a_{n−1}+5a_{n−2}−7a_{n−3}$ has characteristic polynomial $x^3 - 3x^2 - 5x + 7 = 0$ which has roots $x=1$, $x=1 - 2\sqrt{2}$, and $x=1 +2\sqrt{2}$.
That means your recurrence has form $a_n = \alpha \cdot 1^n + \beta \cdot (1-2\sqrt{2})^n + \gamma  \cdot  (1+2\sqrt{2})^n$.
Substitute in the values you know:
$4 = \alpha \cdot 1^1 + \beta \cdot (1-2\sqrt{2})^1 + \gamma  \cdot  (1+2\sqrt{2})^1$
$8 = \alpha \cdot 1^2 + \beta \cdot (1-2\sqrt{2})^2 + \gamma  \cdot  (1+2\sqrt{2})^2$
$2 = \alpha \cdot 1^3 + \beta \cdot (1-2\sqrt{2})^3 + \gamma  \cdot  (1+2\sqrt{2})^3$
This leads to solution $\alpha = \frac{21}{4}$, $\beta = \frac{3}{8} + \frac{1}{2\sqrt{2}}$, and $\gamma = \frac{3}{8} - \frac{1}{2\sqrt{2}}$.
$a_n = \frac{21}{4}+ (\frac{3}{8} + \frac{1}{2\sqrt{2}})\cdot (1-2\sqrt{2})^n + (\frac{3}{8} - \frac{1}{2\sqrt{2}})\cdot  (1+2\sqrt{2})^n$
This can be flattened down a little:
$a_n = \frac{1}{8} ((3 - 2\sqrt{2}) (1 + 2 \sqrt{2})^n + (3 + 2 \sqrt{2}) (1 - 2 \sqrt{2})^n + 42)$
Comment: (+1) Mathematica agrees with this answer.
Answer: an small tip :D if you make the ansatz $ a_n  =r^{n} $
the recurrence equation becomes
$ r^{n}=3r^{n-1}+5r^{n-2}-7r^{n-3} $
multiply all by $ r^{3} $ you get
$ r^{n+3}=3r^{n+2}+5r^{n+1}-7r^{n} $
divide all by $ r^{n} $ you get the polynomial
$ r^3 =3r^2+5r-7 $
get the roots of this polynomial and you get the solution
Comment: Thanks for your answer, I did that to get my roots. The problem is that I am lost with the equations to get the constants @.@


Generalization with imbalanced classes

Question: I have a generic question about learning (binary classification) with imbalanced classes and generalization. One recipe for learning with imbalanced classes is to downsample the negatives to a ratio where the model can actually learn something. But what happens when the model is deployed on the actual, very imbalanced data? To put some numbers around this, if the positives represent 1% of the actual data, we can train the binary classifier with all the positives and an equal number of downsampled negatives. But then the model is released on data that has the actual 1:100 positive to negative ratio. Will the model still be able to find the positives? Isn't it like it was not trained on the same problem as it is used for?
Comment: It's almost as if lying to the model leads to problems! $//$ My profile has a number of links about class imbalance, and my Data Science account recently awarded a large bounty to my question about class imbalance. It turns out to be a lot less of a problem than some people think.
Comment: Do you have two accounts? There's a way to merge them. $//$ I'd start with the bountied answer to [my question on Data Science](https://datascience.stackexchange.com/q/126337/73930).
Comment: I stand by the first part of my first comment: `It's almost as if lying to the model leads to problems!`
Comment: Do you mean that it is not a problem in a sense that the models can be created on unbalanced datasets, or it it not a problem to have a model trained on balanced data, that is later used for use-cases with unbalanced data?
Comment: I kind of want to keep it a surprise for when you read the reference material, but statistics sees minimal problem with training on imbalanced data (except for a few edge cases, also discussed in those links).
Comment: @dave What link/doc would you recommend first?
Comment: Dave, I knew it! :) Maybe I will read, indeed. Thank you for the insight though. I myself often train on unbalanced datasets, and what I observe is that when you balance the sets, the performance does not change (improve) drastically. So I guess that the differences in data distributions either are in the data, or they are not there, and unless the imbalance is extreme, the imbalance as such is not that much of an issue, I agree.
Answer: An amazing amount has been written about this on this site.  It is so unfortunate that you have started a new topic on this.  The matter has been completely settled.  Class imbalance is only a problem if you use invalid analytical methods, and any attempt to change the balance represented in validly sampled data will result in a complete mess that does not apply to future non-molested samples.
One of the most important statistical principles to understand is that if the proportion of positive responses is not close to 0.5, classification can be a bad idea and what should be analyzed is tendencies, i.e., one should be estimating probabilities of responses.
Comment: To be clear, the reason I asked this question is precisely because I never liked the idea of learning a model on data that doesn't have the same distribution as the "real" data. I am not a statistician myself, but the practice of "molesting" the data is widespread in the ML community.
Comment: Frank - it looks like the link to *this site* is not quite set up. I'd love to be able to access it. Can you fix the link?
Comment: I clicked on the link and it's working for me.
Answer: If you calculate the sensitivity, and especially the specificity, you will able to detect the bias you're interested in.  For example, consider a classifier that's a shoe-box which does nothing.  Also, assume a sample size of $n=100$, and a truth table involving 5 positives and 95 negatives.  Even though the classifier does nothing, its accuracy will be 95% all the time, since it only misclassifies 5% of the positive data.  Now, as soon as you calculate the sensitivity and specificity, the resulting values will be low.
Thus, applying "diagnostic screening" using sens & spec directly sidesteps this issue.
Answer: You can always run a validation/simulation: take your dataset, split it, use part of it that has balanced classes for training, and in the second part, if there is balance, random sample one of the classes, then perform validation. This way you will find out whether metrics (e.g., true positive rate, or false positive rate) will be the same for training as for the validation. I would guess that they will be different, but I am not a data science theoretician, so I would simply do an experiment and find out.

Generalization with imbalanced classes


Cloudflare and mod_proxy

Question: I'm already using mod_proxy to redirect from example-domain.com to example-domain.com:8080, well without CloudFlare (reserve proxy) it works... but with CloudFlare it just response an error 1000 DNS points to prohibited IP. Any chances to get trough this and still use CloudFlare to protect myself? I don't want that the address show something like this with mod_rewrite http://example-domain.com:8080, that's why I'm redirecting, hosting on port 80 is impossible so no changes there.
My vhost config:
    <Directory /var/www/example-domain.com>
            AllowOverride None
            Require all denied
            </Directory>

    <VirtualHost *:80>
            DocumentRoot /var/www/example-domain.com/web

            ServerName example-domain.com
            ServerAlias www.example-domain.com
            ServerAlias alias.example-domain.com
            ServerAdmin email@example.com
            ProxyPreserveHost On
            ProxyRequests Off

            <Proxy *>
              Order deny,allow
              Allow from all
            </Proxy>

            ProxyPass / http://example-domain.com:8080/
            ProxyPassReverse / http://example-domain.com:8080/

    </VirtualHost>

Answer: Regardless of what port you are accessing CloudFlare through, CloudFlare has a tendency to try port 80/443 first. If it can connect to these ports during it's own proxying it stops there and then does not try the port you actually wanted (in your case 8080).
Therefore this looks like a cyclic loop, you are pointing your requests from CloudFlare to proxy to point back through CloudFlare to the server at port 8080. CloudFlare is then stripping the port 8080 and connecting via a plain connection.
The best way to fix this is to simply to set your ProxyPass to go through a URL that doesn't run through the CloudFlare network or simply through localhost.
So either change the ProxyPass in your VirtualHost to:
        ProxyPass / http://direct.example-domain.com:8080/
        ProxyPassReverse / http://direct.example-domain.com:8080/

Where direct.example-domain.com does not route through the CloudFlare network (a grey cloud in your CloudFlare DNS, providing you're doing a full-host CloudFlare set-up).
Alternatively change your proxy pass to go via the localhost:
        ProxyPass / http://127.0.0.1:8080/
        ProxyPassReverse / http://127.0.0.1:8080/

Have fun!

Cloudflare and mod_proxy


Linear programming with many constraints and few unknown variables

Question: Vectors $x, y \in \mathbb{R}^{n\times 1}$ satisfy
$$
\forall_{i,j}\; x_i + y_j \leq a_{i,j}
$$
where $a\in \mathbb{R}^{n\times n}$ is a given matrix. The question is to find the maximum value of $\sum_i x_i + \sum_j y_j$.
My idea
Suppose $t$ is a bijection defined on $\{1,..,n\}\mapsto \{1,..,n\}$, then we have
$$
\sum_i x_i + \sum_j y_j \leq \sum_k a_{k\,t(k)}
$$
which further introduce
$$
\sum_i x_i + \sum_j y_j \leq \min_t \sum_k a_{k\,t(k)}
$$
What's left is to prove that $\min_t \sum_k a_{k\,t(k)}$ can be reached. That is to say, prove there exist vectors $x, y$ such that
$$
\begin{cases}
x_i + y_j \leq a_{i,j},\;\;\forall_{i,j}\\
\sum_i x_i + \sum_j y_j = \min_t \sum_k a_{k\,t(k)}
\end{cases}
$$
Comment: @mfl $\sum_k a_{k\,t(k)}$ will iterate through all rows and columns. It won't be $a_{11} + a_{12}$
Comment: Ups. I see. But is not $\sum_k a_{kt(k)}=\sum_{ij}a_{ij}$?
Comment: @mfl Suppose $t=[3\,1\,2]$ (we represent permutation as a vector), then $\sum_k a_{kt(k)} = a_{13} + a_{21} + a_{32}$
Comment: Thank you very much for your clarifications.
Comment: In $\sum_i x_i + \sum_j y_j \leq \sum_k a_{k\,t(k)}$ is  $t$ any bijection? The question is motivated in the fact that later you consider $\min_t.$
Comment: @mfl Yes, $t$ can be any bijection defined on $\{1,..,n\}$. The answer given by Michael provides a similar point of view from doubly stochastic matrix.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/81931/discussion-between-useprxf-and-mfl).
Answer: Your upper bound is good and corresponds to finding a min weight match over permutation matrices. Or you can prove a related upper bound directly:
Related (in fact, identical) upper bound
Let $P=(p_{ij})$ be a "doubly stochastic" $n \times n$ matrix so that
\begin{align}
\sum_{j=1}^n p_{ij} &= 1 \quad \forall i \in \{1, ..., n\} \\
\sum_{i=1}^n p_{ij} &=1 \quad \forall j \in \{1, ..., n\} \\
p_{ij} &\geq 0 \quad \forall i, j
\end{align}
Then if $(x_i), (y_j)$ are values that satisfy $x_i + y_j \leq a_{ij}$ for all $i,j \in \{1, ..., n\}$,  then you can show (using methods similar to your existing upper bound) that:
$$\sum_{i=1}^n x_i + \sum_{j=1}^n y_j \leq \sum_{ij} p_{ij} a_{ij} $$
So the best upper bound of this type is solved by the following linear program
\begin{align}
\mbox{Minimize:} & \quad \sum_{ij} p_{ij}a_{ij} \\
\mbox{Subject to:} & \sum_{j=1}^n p_{ij} = 1 \quad \forall i \in \{1, ..., n\} \\
&\sum_{i=1}^n p_{ij} =1 \quad \forall j \in \{1, ..., n\} \\
&p_{ij} \geq 0 \quad \forall i, j
\end{align}
It turns out that this upper bound is identical to your upper bound of the min-weight match over the matrix $(a_{ij})$ because every doubly stochastic matrix $(p_{ij})$ can be expressed as a convex combination of permutation matrices (which is sometimes called the Birkhoff-von Neumann theorem), and so minimizing a linear function over doubly stochastic matrices can be reduced to minimizing the same function over permutation matrices (since permutation matrices are the "extreme points" of the set of doubly stochastic matrices).
Matching lower bound
Try using linear program duality to take the dual of the above linear program with $p_{ij}$ variables to convert to a linear program with dual variables $x_i,y_j$.
Comment: In other words, swap the ordering of $\inf_{p\geq 0}[\cdot]$ and $\sup_{x,y \in \mathbb{R}^n} [\cdot]$ for the expression $$\left[\sum_{ij}p_{ij}a_{ij} +\sum_{i=1}^nx_i\left(1-\sum_{j=1}^n p_{ij}\right) +\sum_{j=1}^ny_j\left(1-\sum_{i=1}^n p_{ij}\right)\right]$$ [Alternatively, you could start with your linear program in $x_i,y_j$ variables and use duality _on that_ to transform to dual variables $p_{ij}$].
Comment: How do you construct the optimal $x,y$ according to $p_{ij}$?
Comment: Your question says "That is to say, prove _there exist_ vectors $x,y$ such that..." You can prove existence by completing the "matching lower bound" step in my above answer, which means you will need to construct the dual linear program (with $x,y$ variables as "Lagrange multipliers") from the linear program with $p_{ij}$ variables in my answer.  The key step is swapping the ordering of $\inf$ and $\sup$ as in my above comment. Are you familiar with duality theory? It does not give us an answer for $(x,y)$ in terms of $p_{ij}$, rather, it tells us a new linear program to solve.
Comment: This seems to be a homework problem about  duality. I don't see how it can be solved without duality theory or saddle point theory.  The type of linear program duality I am referring to is in equations (13)-(14) in these notes: https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=3&ved=2ahUKEwiK7YHd7_vcAhUPWa0KHRuYCnMQFjACegQIABAC&url=http%3A%2F%2Fweb.mit.edu%2F15.053%2Fwww%2FAMP-Chapter-04.pdf&usg=AOvVaw2ca3zfM8SvZTYusmYmFYC5
Comment: Genius, now I got it. It's actually a programming problem. I tried to find a determinitic and discretic approach to construct the optimal $(x,y)$ but failed. You method indeed proves the existence of the optimal $(x,y)$.
Answer: Since this seems to not be a homework, it may be useful to have the following "appendix" to my answer (although this may also be a spoiler to the do-it-yourself flavor of my prior answer).  I give this because some treatments of duality theory assume a particular structure that is not convenient for this problem.

You have the (primal) LP:
\begin{align}
\mbox{Minimize:} &\quad -\left(\sum_{i=1}^n x_i + \sum_{i=1}^n y_i\right) \\
\mbox{Subject to:} &\quad x_i + y_j \leq a_{ij} \quad \forall i,j  \in \{1, ..., n\}
\end{align}
The optimal objective value is the same as:
\begin{align}
&\inf_{x,y\in \mathbb{R}^n} \sup_{p\geq 0}\left[-\left(\sum_{i=1}^n x_i + \sum_{j=1}^n y_j\right) + \sum_{ij}p_{ij}\left(x_i+y_j-a_{ij}\right)  \right]\\
&\overset{(a)}{=}\inf_{x,y\in \mathbb{R}^n}\sup_{p\geq 0}\left[-\sum_{ij}p_{ij}a_{ij} + \sum_{i=1}^nx_i\left(-1+\sum_{j=1}^np_{ij}\right)+\sum_{j=1}^ny_j\left(-1+\sum_{i=1}^np_{ij}\right) \right]\\
&\overset{(b)}{=}\sup_{p\geq 0}\inf_{x,y\in \mathbb{R}^n} \left[-\sum_{ij}p_{ij}a_{ij} + \sum_{i=1}^nx_i\left(-1+\sum_{j=1}^np_{ij}\right)+\sum_{j=1}^ny_j\left(-1+\sum_{i=1}^np_{ij}\right) \right]\\
\end{align}
where (a) follows by switching the summation order; (b) follows by switching the order of $\inf$ and $\sup$ which can be justified in this case by saddle point theory.  The last problem has optimal value the same as that of the (dual) LP:
\begin{align}
\mbox{Maximize:} & \quad -\sum_{ij} p_{ij} a_{ij} \\
\mbox{Subject to:} & \quad \sum_{j=1}^n p_{ij} = 1 \quad \forall i \in \{1, ..., n\} \\
& \quad \sum_{i=1}^n p_{ij} = 1 \quad \forall j \in \{1, ..., n\} \\
&\quad p_{ij} \geq 0 \quad \forall i,j \in \{1, ..., n\}
\end{align}

Why is the primal problem equivalent to the following "2-player game"?
$$\inf_{x,y\in \mathbb{R}^n} \sup_{p\geq 0}\underbrace{\left[-\left(\sum_{i=1}^n x_i + \sum_{j=1}^n y_j\right) + \sum_{ij}p_{ij}\left(x_i+y_j-a_{ij}\right)  \right]}_{L(x,y,p)}$$
The reason is that player 1 wants to choose $x,y\in\mathbb{R}^n$ to minimize $\sup_{p\geq 0}L(x,y,p)$.  If it chooses in a way that violates the constraint $x_i+y_j\leq a_{ij}$ for at least one $(i,j)$ pair, then player 2 can "win" by choosing $p_{ij}\rightarrow \infty$ for that same $(i,j)$ pair, making  $L(x,y,p)\rightarrow\infty$. So player 1 must choose $x,y$ to satisfy  $x_i + y_j \leq a_{ij}$ for all $(i,j)$. Player 1 can further optimize its choice of $x,y$ as long as these constraints are satisfied, which corresponds to the primal LP.
Since $L(x,y,p)$ is linear in $(x,y)$ for fixed $p$, and linear in $p$ for fixed $(x,y)$, saddle point theory ensures we can switch the $\inf$ and $\sup$ ordering as we did above.


Getting started with docker swarm using a bare metal server

Question: So I have already images in my dockerhub which are ready to use as I have already setup a kubernetes cluster on a server. My next step is to achieve something similar using docker swarm. I do not really know how to get started so I am asking in here.
The kubernetes cluster is running on a bare metal ubuntu VPS server and looks like this:

My question is:

How to set up a single node cluster (one master only, no workers) on a bare metal ubuntu VPS? I did not found much out there, are there any significant changes I need to take care about (similar to the metalLB in the kubernetes cluster)?
Answer:
How to set up a single node cluster (one master only, no workers) on a bare metal ubuntu VPS? I did not found much out there, are there any significant changes I need to take care about (similar to the metalLB in the kubernetes cluster)?

There's not much to do. You simply:

Install the OS on your server. That may be from install media, or perhaps a network based scripted install. That's typically out of scope from docker and handled by the OS vendor or 3rd party tools.
Install docker. That's well documented from docker, just select your OS from the list: https://docs.docker.com/install/
Enable swarm with docker swarm init and you're done. If you have more than one network interface, you may need to specify an  --advertise-addr option. https://docs.docker.com/engine/reference/commandline/swarm_init/

That's it, one command and you have a single node cluster. The lack of guides is more that there's little to do to get up and running.


Checar se 'Permitir locais fictícios' está habilitado

Question: Tenho um aplicativo que necessita da opção "Permitir locais fictícios" do aplicativo padrão de Galeria habilitada para que funcione.
Como verificar se ela está habilitada?
Como enviar o usuário para este item de meu caso esteja desabilitado?
Essa opção fica no menu Programador, é um menu escondido... Como ativar esse menu e enviar a pessoa até la?
Answer: Resolvi...
Para verificar se a opção está habilitada:
private boolean isMockSettingsON() {
        return !Settings.Secure.getString(getContentResolver(),
                Settings.Secure.ALLOW_MOCK_LOCATION).equals("0");
}

Para enviar o usuário até o menu de dev:
Intent intent = new Intent(Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS);
startActivity(intent);

Answer: Complementando a resposta, o objeto Location possui uma propriedade de informa se ela foi gerada por mock, isFromMockProvider.
Esta está disponível a partir da API 18.
Exemplo:
if(!location.isFromMockProvider()){
 // Esta localização não foi gerada por um simulador
}


Poker Game(best hand so far)

Question: Hi everyone im having trouble with this poker game code I need to figure out how to display the best hand so far "Best hand so far: AH, AD, 2H, 7S, KC". For example, if i have a pair on the first game, then on the second game its two pairs or flush replace the last hand only if it is a higher hand.
<code>'
import java.util.*;
//****main****
 public class Player
 {
     private Scanner  input;
     Bankroll bankroll;
     PokerGame pokerGame;
     Bet bet;
     Hand hand;

 Player()
 {
      input = new Scanner(System.in);
 }

 void getInitialBankroll()
 {
      int numCoins;
      do
      {
           System.out.print("How many coins do you wish to insert into the      machine: ");
           numCoins = input.nextInt();
      }while (numCoins <= 0);
      System.out.println();
      bankroll = new Bankroll(numCoins);
 }

 void addCoins()
 {
      int numCoins;
      do
      {
           System.out.print("How many coins do you wish to insert into the machine: ");
           numCoins = input.nextInt();
      } while (numCoins <= 0);

      bankroll.alterBankroll(numCoins);
      System.out.println("Currently you have "+ bankroll.getBankroll()+ "   coins");
      System.out.println();
 }

 public void betAndPlay()
 {
      int coins;
      do
      {
           System.out.print("Enter a bet: 1 to 5 coins: ");
           coins = input.nextInt();
      } while (coins <=0 || coins > 5 || coins > bankroll.getBankroll());

      bet = new Bet(coins);
      pokerGame = new PokerGame(bet, bankroll, this);
      pokerGame.viewInitialHand();
      pokerGame.discardOrHoldCards();

 }

 public void displayHand(String[] handString)
 {
      System.out.println("********** Your Hand **********");
      for(int i = 0; i < 5; i++)
           System.out.println((i+1) +".  "+handString[i]);
      System.out.println("*******************************");
      System.out.println();
 }

 public void getDiscard(boolean[] x)
 {
      String ans;
      System.out.println("Hold or discard? ");
      for (int i = 0; i < 5; i++)
      {
           do
           {
                System.out.print("Hold (h) or Discard (d) card number "+(i+1)+": ");
                ans = input.next();
                if (ans.equals("h") )
                     x[i] = true; // hold
                else if (ans.equals("h") )
                     x[i] = false; // discard
           }while (!(ans.equals("h") || ans.equals("d")));
      }
      System.out.println();
 }

 public void displayResults(int payoff, int winnings)
 {
      String nameOfHand = "Lose";
      if (payoff == 250)
           nameOfHand = "Royal Flush";
      else if (payoff == 50)
           nameOfHand = "Straight Flush";
      else if (payoff == 25)
           nameOfHand = "Four of a Kind";
      else if (payoff == 9)
           nameOfHand = "Full House";
      else if (payoff == 6)
           nameOfHand = " Flush";
      else if (payoff == 4)
           nameOfHand = "Straight ";
      else if (payoff == 3)
           nameOfHand = "Three of a Kind";
      else if (payoff == 2)
           nameOfHand = "Two Pair";
      else if (payoff == 1)
           nameOfHand  = " Pair of Jacks or Better";

      if (winnings >0 )
      {
           System.out.println("Winner: "+ nameOfHand);
           System.out.println("Payoff is "+ winnings + " coins.");

      }
      else
           System.out.println("You lost your bet of  "+ bet.getBet());
           System.out.println("Current Bankroll is " +   bankroll.getBankroll());
           System.out.println();

 }

 public void quit()
 {
      int br = bankroll.getBankroll();
      System.out.println("\n******Game Over****** \n");
      if (br > 0)
           System.out.println("Returned: "+br+" coin(s)");
      else
           System.out.println("No coins remain");
      System.out.println("\n*********************");
 }

 public void menu()
 {
      String choice;
      do
      {
       //System.out.println("Best Hand: " + something); //Best Hand so far

       System.out.println("Choose");
           System.out.println("1: Make a bet and play poker");
           System.out.println("2: Add coins to the machine ");
           System.out.println("3: Cash out and quit");
           System.out.print("Your choice: ");
           choice = input.next();
           if (choice.equals("1"))
                betAndPlay();
           else if (choice.equals("2"))
                addCoins();
      }while ((!(choice.equals("3") ) && bankroll.getBankroll() >0));
 }

 public static void main(String[] args)
 {
      Player player= new Player();
      player.getInitialBankroll();
      player.menu();
      player.quit();
 }
</code>
}
    `
<code>public class PokerGame
 {
 private Bankroll bankroll;
 private Bet bet;
 private Hand hand;
 private Player player;
 private boolean[] holdCards;
 private static Hand bestHand;

 public PokerGame(Bet coinsBet, Bankroll br, Player pl)
 {
      bankroll = br;
      bet = coinsBet;
      player = pl;
      hand = new Hand();
      holdCards = new boolean[5];

 }

 int updateBankroll(int payoff)
 {
      int winnings = payoff*(bet.getBet());   // negative for a loss
      bankroll.alterBankroll(winnings);
      return winnings;
 }

 public void viewInitialHand()
  {
      hand.newHand();
      player.displayHand(hand.getHand());
   }
   public void discardOrHoldCards()
   {
      player.getDiscard(holdCards);
      hand.updateHand(holdCards);
      player.displayHand(hand.getHand());
  bestHand = player.evaluateHand();
    if(bestHand > count ){
        bestHand =
    }
      int payoff = hand.evaluateHand();
      int winnings = updateBankroll(payoff);
      player.displayResults(payoff, winnings); // the hand & the number of   coins won(lost)
      }
 }

  ///////////////////Hand.java///////////////////

 public class Hand
 {
 private Card[] cards;
 private Deck deck;
 private int suits[];  // holds the number of each suit in a hand
 private int values[]; // holds the number of each type card (A,2,3,4,...K)

 public Hand()
 {
      cards = new Card[5];
      suits = new int[5];      // uses indices 1..4
      values = new int[14];   // uses indices 1..13
      deck = new Deck();
 }

 public void newHand()
 {
      deck.shuffle();
      for (int i = 0; i < 5; i++)
      {
           cards[i] = deck.deal();
           suits[cards[i].getSuit()]++ ;
           values[cards[i].getValue()]++;
           }
           sort();
 }

 public void  updateHand(boolean[] x)
 {
      for (int i = 0; i < 5; i++)
      if ( !x[i])
      {
           // remove card data for card i
           suits[cards[i].getSuit()]-- ;
           values[cards[i].getValue()]--;
           // get a new card
           cards[i] = deck.deal();
           // update data for card i
           suits[cards[i].getSuit()]++ ;
           values[cards[i].getValue()]++;
      }
      sort();
 }

 public String[] getHand()
 {

      String[] cardsInHand = new String[5];
      for (int i = 0; i < 5; i++)
           cardsInHand[i] = cards[i].getName();
      return cardsInHand;
 }

 private void sort()  // orders cards by value field; a helper function
 {
      int max; // holds the position of the highest valued card
      for (int place = 4; place > 0; place--)
      {
           max = 0;
           // find the position of the highest valued card between 0 ans place
           // the position of the high card is stored in max
           for (int i = 1; i <= place; i++)
           if ( cards[i].getValue() > cards[max].getValue())
                max = i;
           // swap the highest wlaued card with the card in position place
           Card temp = cards[place];
           cards[place] = cards[max];
           cards[max] = temp;
      }
 }

 public int  evaluateHand()
 {
      if (royalFlush())  // royal flush pays 250:1
           return 250;
      else if (straightFlush()) // straight flush pays 50:1
           return 50;
      else if (fourOfAKind()) // four of a kind
           return 25; // four of a kind pays 25:1
      else if (fullHouse()) // full house
           return 9;
      else if (flush())
           return 6;
      else if (straight())
           return 4;
      else if (threeOfAKind()) // three of a kind
           return 3;
      else if (twoPair())
           return 2;
      else if (pair())  // Jacks or better
           return 1;
      return -1;   // losing hand
 }

 private boolean royalFlush()
 {
      //10, J,Q,K,A of the same suit
      boolean sameSuit= false;  // true if all same suit
      boolean isRoyalty= false; //  true if cards are 10,J,K,Q,A
      for(int i = 1; i <=4; i++)
           if (suits[i] == 5)  // all five cards of one suit?
                sameSuit = true;
      isRoyalty = (values[1] == 1 &&
                          values[10] ==1 &&
                          values[11] ==1 &&
                          values[12] == 1 &&
                          values[13] == 1); //one Ace && one 10 && one J &&one Q&&one K
      return (sameSuit && isRoyalty); // true if both conditions are true
 }

 private boolean straightFlush()
 {
      boolean sameSuit = false;
      boolean ranksInOrder = false;
      for(int i = 1; i <=4; i++)
           if (suits[i] == 5)
                sameSuit = true;  // same suit?
      // cards in sequence?
      ranksInOrder =
      cards[1].getValue() == (cards[0].getValue() + 1) &&
      cards[2].getValue() == (cards[0].getValue() + 2) &&
      cards[3].getValue() == (cards[0].getValue() + 3) &&
      cards[4].getValue() == (cards[0].getValue() + 4);
      return (sameSuit && ranksInOrder);
 }

 private boolean flush()
 {
      for(int i = 1; i <=4; i++)
           if (suits[i] == 5)  // all the same suit?
                return true;
      return false;
 }

 private boolean fourOfAKind()
 {
      for(int i =1 ; i <= 13; i++)
           if (values[i] == 4)
                return true;
      return false;
 }

 private boolean fullHouse()
 {
      boolean three= false;
      boolean two= false;
      for(int i =1 ; i <= 13; i++)
           if (values[i] == 3)  // three of one kind
                three= true;
           else if (values[i] ==2) // two of another kind
                two = true;
      return  two && three; // both conditions
 }

 private boolean straight()
 {
      // cards in sequence?
      return
      // Ace precedes 2
       (cards[1].getValue() == (cards[0].getValue() + 1) &&
      cards[2].getValue() == (cards[0].getValue() + 2) &&
      cards[3].getValue() == (cards[0].getValue() + 3) &&
      cards[4].getValue() == (cards[0].getValue() + 4))  ||
      //Ace follows King
       (values[1] == 1 && //Ace
      values[10] ==1 &&  //Ten
      values[11]==1 &&  //Jack
      values[12] == 1 && //Queen
      values[13] == 1); //King
 }

 private boolean threeOfAKind()
 {
      for(int i =1 ; i <= 13; i++)
           if (values[i] == 3)
                return true;
      return false;
 }

 private boolean twoPair()
 {
      int count = 0;
      for( int i = 1; i <= 13; i++)
           if(values[i] == 2)   // count the number of pairs
                count++;
      return (count == 2);
 }

 private boolean pair() // Jacks or Higher
 {
      if (values[1] == 2) //pair of aces
           return true;
      for( int i = 11; i <= 13; i++) // pair of Jacks or higher
           if(values[i] ==2)
                return true;
      return false;
      }
 }
</code>
Comment: Solution: 1) Work out which is best hand, 2) Display it.  OR ... 3) reword your Question to ask the questions that you >>really<< need answers to.
Comment: (I'm not trying to be unhelpful here.  The way to solve a problem like this >>is<< to break it down into subproblems.  If you do that yourself, then you can either solve the entire problem for yourself, or at least only ask about the subproblems that >>you<< can't solve.)
Comment: im trying to say that the best hand so far is going to be the winning hand so if the first hand you win with two pairs then the next game you play will display "best hand so far: two pairs..."  and if in that game you have two higher pairs than the previous then replace them. basically i need help saving the bestHand, holding it until a higher winning hand is dealt, then replacing the previous best hand with the new one
Comment: So ... how do you break all of that down into solvable sub-problems?
Answer: Hint: You need a method to compare two hands and work out which of those two hands is better.  Given that method, the rest of the problem is pretty straightforward.

Poker Game(best hand so far)


How can 2TB drive give protection for 12TB of data in a SHR (Synology Hybrid RAID)?

Question: I used the Synology RAID calculator to model a scenario of a mix of a bunch of 1TB and 2TB drives.
Could someone explain to me how is it possible that 2TBs of redundant space give protection for 12TBs of data?
Comment: That's completely normal for RAID 5. n disks of m gigabytes gives (n-1)*m gigabytes useable capacity. [Synology's documentation on *shr*](https://kb.synology.com/en-us/DSM/tutorial/What_is_Synology_Hybrid_RAID_SHR) may be worth reading as well; it's basically a buzzword for using non-equal devices in an array.
Comment: What is the concrete business problem you are trying to solve?
Comment: Thanks, analogy to RAID 5 seems to be the answer.
Answer: My guess? Synology uses a variation of RAID5.
Normally your data is stored in blocks along with its parity data.
The order of where the blocks and parity is located is rotated, so parity blocks is spread evenly across all drives in the array.
The idea is that if a drive fails, data can be restored by using information from the remaining drives and parity data.
In SHR I suspect Synology is pairing the 1 TB drives, so  for every 2 x 1 TB drives they behave like a 2 TB drive - effectively mimicking some kind of RAID 0.
In essence it would be the same as populating the drive with 9 x 2 TB drives and do ordinary RAID5 on the lot.
.... and as attached picture shows: There are no difference between RAID5 and SHR when you have 9 x 2 TB drives
Comment: SHR only gives some "advantage" when used in scenario with disks of *different* size. That's the whole goal of its existence: to maximize the available redundant space at all costs. If all disks are of the same size, it just produces usual RAID. So your example simply does not make sense.
Comment: Agreed. As far as I see it is basically just the same as making a JBOD array - except with a little bit of redundancy built-in.
Comment: Thanks, the proposed answer through RAID 5 proves (mathematically) that it's possible to protect 16TB with only 2TB overhead. I guess it's worth mentioning from what I read in the links from the comments above that it's a "protection" in double quotes since a single bit of read error after a full drive failure discards the entire array - which is pretty much an issue. I'm not sure if I should accept this answer BTW because it says "I suspect", anybody can confirm whether the assumptions in the proposed answer are correct?
Comment: Well I put my emphasis on "I suspect" due to the largest array I have ever done with Synology was 4 drives, hence only scratching the bare surface of RAID systems. :-)


Is xmlns="" a valid xml namespace?

Question: Is "empty" a valid value for XML namespace? If yes what does it mean?
I have the following XML code but I'm not sure to which namespace Field1 and Field2 elements belong to.
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
  <soapenv:Header />
  <soap:Body>
    <Root xmlns="uri">
      <Field1 xmlns="">147079737</Field1>
      <Field2 xmlns="">POL</Field2>
    </Root>
  </soap:Body>
</soapenv:Envelope>

Comment: @skaffman: It is legal, and this is the way to bring an element into the global namespace.
Comment: I concur with @Frerich Raabe: Without that, you would have no way of getting rid of an inherited namespace in a descendant node.
Comment: An interesting question. If it's not legal, then how does one specify "no namespace" for an element whose parent *is* in a namespace?
Comment: As I understood from XML spec this doesn't set namespace to global namespace but instead it to scope namespace. Am I wrong?
Answer: Yes, it is valid. Section 6.2 in the Namespaces in XML 1.0 Recommendation specifically says:

The attribute value in a default namespace declaration MAY be empty. This has the same effect, within the scope of the declaration, of there being no default namespace.

Quoted from comment:

It is legal, and this is the way to bring an element into the global namespace.
Comment: But is the above a *default* namespace declaration ?
Comment: @Brian: Yes; see Definition 3 in Section 3 in the 'Namespace in XML 1.0 Recommendation' I linked in my answer. It says '[Definition: If the attribute name matches DefaultAttName, then the namespace name in the attribute value is that of the default namespace in the scope of the element to which the declaration is attached.]'. DefaultAttName is defined to be 'xmlns'.
Comment: In my case if it's the same as having no namespace then what namespace is it? Does XML have a predefined default namespace, the one that is used then there is no default namespace provided by user like in my case?
Comment: No. No NS means no NS. Please check [Namespace Myths Exploded](http://www.rpbourret.com/xml/NamespaceMyths.htm) by Ronald Bourret.
Comment: @Brian And it is not a default NS. It is a default NS un-declaration because as the rec writes it : "This has the same effect, within the scope of the declaration, of there being no default namespace."
Answer: It is not a valid XML NS. It is not a valid XML NS declaration. Please check section 2.2 of Namespaces in XML 1.0 :

The empty string, though it is a legal URI reference, cannot be used as a namespace name.

It is however the only way to undeclare a default NS declaration if there is one in effect, or it has no effect. See Namespaces in XML 1.0 and 1.1, section 6.2. The 1.1 NS rec added a way to also undeclare a NS declaration with a prefix.
Thus it is a valid value for the xmlns special attribute, but it is not "a valid XML namespace" like the OP wrote it.
Comment: @lkuty I think you are answering the question whether the empty string is a valid namespace name. The OP however seems to ask whether the empty string is a valid value for the `xmlns` attribute. Maybe this disconnect is why there are two contradicting answers.
Comment: It seems you are confusing namespace prefixes with the actual namespaces (namespace URIs). The empty string is not a valid namespace prefix, but a valid namespace URI.
Comment: I don't think I am confusing anything. I know the difference. BTW I can't see where my answer might suggest that.
Comment: OK, that explains things. In the original question, the OP is mixing and confusing declaration and NS name, and I focused on NS name instead of declaration.

Is xmlns="" a valid xml namespace?


How to dynamically create named classes in Coffeescript without using eval?

Question: I want to be able to write:
generate 'Cat', 'meow'
and define the generate function in such a way that it produces:
class Cat
  meow: ->
    @.__proto__.constructor.name + ' says meow.'

so that I can write:
garfield = new Cat
garfield.meow() # "Cat says meow"

Comment: I'm confused by your example. You want `generate 'Cat', 'meow'` to generate code that incorporates neither `"Cat"` nor `"meow"`?
Comment: I'm sorry, I've corrected the example.
Answer: If you don't mind polluting your global namespace, I actually got this snippet running in the 'try coffeescript' runner at the CoffeeScript site:
root = exports ? window
alert = alert or console.log

gen = (clsname, val) ->
  root[clsname] = class
    meow: => "#{clsname} says #{val}"

gen 'Cat', 'meow'
g = new root.Cat
alert g.meow()

gen 'Dog', 'woff'
d = new root.Dog
alert d.meow()

Not 100% what you asked for, but it's almost what you wanted, isn't it?
Edit: Actually, the first script only worked in the browser, not the (Node.js-based) CLI, corrected the script.
If you know you'll only live in the browser, you can loose root.Cat and only say Cat, but if you want Node.js and browser compat, you'll have to live with root.*
Edit 2: It's generally a better idea to return the class from the generating function rather than magically putting it in a namespace. It's also possible to make the method names dynamic. With some inspiration from @Loren, the asker (notice how it doesn't need to refer the global object anymore):
alert = alert or console.log

gen = (clsname, val) ->
  C = class
  C.prototype[val] = -> "#{clsname} says #{val}"
  C

Cat = gen 'Cat', 'meow'
console.log Cat
g = new Cat
alert g.meow()

Dog = gen 'Dog', 'woff'
d = new Dog
alert d.woff()

Comment: The most recent version (Cat = gen ...) now doesn't run in the coffeescript test page. I'm getting "Uncaught TypeError: Illegal invocation." Any ideas?
Answer: If by "named class" you mean "a class with a named function," what you're asking for isn't possible—in CoffeeScript or JavaScript. Without eval, there's no way to create the equivalent of function FuncName() {...}. You can only use the __proto__.constructor.name property on functions defined with that syntax.
The class syntax is the only way of creating named functions in CoffeeScript, for reasons explained in the FAQ.


Alternatives to Exec and Eval when Importing a file path as string in Python

Question: I have to use a config-file cfg.yml:
---
paths:
    reldir : ../my/dir

In Python, I run:
with open('cfg.yml', 'r') as config_file:
    cfg = yaml.load(config_file)

and my goal is to do something with some files in the directory reldir, via the Python file. The above works well.

However, this Python program must be able to run on Windows and Linux. If I am not mistaken, they use different path delimiters, / and \\. Thus, I want to make the reldir in the config file more robust:
---
paths:
    reldir : os.path.join('..','my','dir').

If my understanding is correct, this will combine these folder names with the correct delimiter, depending on where the Python program is executed.
However, this doesn't work, and print(reldir) outputs os.path.join('..','my','dir') instead of ../my/dir. I.e., it is taking the string literally without evaluating the os.path.join function.
I experimented with exec() and eval(), but first, I could not get it to run anyway; and second, I read here that I shouldn't use these.
How should I best proceed?
Comment: Note `yaml.load` is just as bad as `exec` and `eval`.  Use `yaml.safe_load`.
Answer: Usually "/" works for Windows as well. You can just try "../my/dir"


Is it possible to set a PTR record for Github Pages hosting?

Question: Icelandic domains (.is) require that their domains support reverse DNS, which means configuring PTR records on the hosting server.
Is it possible to set up a PTR record for GitHub Pages site hosting?

Background:
I have an Icelandic top-level domain - petejones.is - and am using CloudFlare for DNS and GitHub Pages for hosting.  Icelandic domains are a little unusual in that .is domains must be registered through the national registrar ISNIC, and they have some tougher (it seems) requirements that the registered domains must comply with.
Apparently my setup is not quite up to snuff, as I've just gotten a notice from them that my DNS is not configured correctly.  Here's the key bit:

Test results for "DREW.NS.CLOUDFLARE.COM": The IP address
  2400:cb00:2049:########## of nameserver jasmine.ns.cloudflare.com
  is missing its PTR record or has an incorrect PTR record. The IP
  address 2400:cb00:2049:########## of nameserver
  drew.ns.cloudflare.com is missing its PTR record or has an incorrect
  PTR record. Test results for "JASMINE.NS.CLOUDFLARE.COM":

My sophisticated research (quick googling) indicates that ISNIC is testing to make sure the domain supports reverse DNS - you can resolve the IP from the domain name and vice versa - which seems to be a way of discouraging spam email domains.
Apparently this is configured on the host, rather than the DNS, which makes sense given that the goal is to find the domain from the host.
Is this possible on GitHub Pages?  I've seen plenty of info on adding A or CNAME records but nothing about PTR records.  I suspect GitHub doesn't get a lot of requests for this because they aren't concerned with email delivery.
Answer: The warning that you're seeing there isn't actually about GitHub or GitHub pages at all, but about CloudFlare's name servers.
Personally, I'd argue that accurate PTR on a name server's IPv6 address really isn't a problem, per se - email is going to care about reverse resolution for the mail server, not the DNS server.  We know the DNS server is valid for the domain because it's been delegated to; ensuring the owner of the IP space has named it identically is a pointless exercise.
However, CloudFlare would probably be interested in being compatible with the <code>.is</code> registrar's desires; you should drop them a note and they might happily fix.
Comment: Thanks!  Do you believe [this CloudFlare article](https://support.cloudflare.com/hc/en-us/articles/200168596-How-do-I-add-a-PTR-record-to-CloudFlare-) is incorrect (or misleading), then?
Comment: @peteorpeter That's not applicable - it's talking about hosted DNS, this situation is for the name servers themselves which belong to cloudflare.
Comment: What is the distinction between "hosted DNS" and "name servers themselves which belong to cloudflare"?  Isn't the former _composed_ of the latter?  Obviously you aren't dealing with a pro network/systadmin here - your patience is appreciated ;)  In related news I've opened a ticket with CloudFlare - will update if I hear back.  Thanks again.
Comment: @peteorpeter Hosted DNS is for zones of yours that are running on their infrastructure - the configuration for their own infrastructure is separate from that.
Comment: Did you get anywhere with this @peteorpeter?
Comment: I received a note from CloudFlare support that they were already investigating the issue and would add my domain to the list of affected domains.  I haven't received a warning from ISNIC since, so _I assume_ they fixed it.


Does multiplying a constant to a summation only apply to the first term?

Question: I used Symbolab to confirm one of my solutions and realized something strange when solving this summation:
image of question
Symbolab factors out the unneeded constant out of the equation, which is normal but then once the summation is solved, it only multiplies the first term in the summation's solution by the constant it factors out: Symbolab doing as described above I thought it was supposed to multiply every term like so: What i expected
How come in this question, only the first term is multiplied?
Answer: Symbolab has made an error.
The line
$$  \frac{1}{n^2 -1} \cdot \frac{1}{3}n^3 + \frac{3}{2}n^2 + \frac{13}{6}n  $$
should be
$$  \frac{1}{n^2 -1} \cdot \left( \frac{1}{3}n^3 + \frac{3}{2}n^2 + \frac{13}{6}n \right)  \text{,}  $$
as you correctly noticed.


Can I argue like this to prove that the determinant is positive?

Question: Let $X$ be a smooth $n$-manifold with an oriented atlas $\mathcal U = (U_\alpha, (x_1^\alpha, \dots, x_n^\alpha))$. Let $g$ be a Riemannian metric on $X$.
Let $g_{ij} = g\left ( {\partial \over \partial x_i^\alpha }, {\partial \over \partial x_j^\alpha}\right )$ for some $\alpha$.

If I want to show that $\det g_{ij} >0$ can I argue like this?

(1) By definiton a Riemannian metric is a positive definite quadratic form.
(2) Let $Q$ denote the matrix of the quadratic form. Since the form is positive definite, so is its matrix. Note that the eigenvalues of a positive definite matrix are positive.
(3) Pick a basis in which $Q$ is diagonal. Then the diagonal consists of the eigenvalues and
$$ \det Q = \prod_i \lambda_i > 0$$
since $\lambda_i > 0$.
Answer: Yes, more or less. It's worth remembering that the determinant is defined for a linear map $ T: V \rightarrow V $. Strictly speaking, there is no definition for a quadratic form $ V \otimes V \rightarrow \mathbb{R}$.
What you are doing is, choosing a coordinate basis, which induces a non-canonical identification of $ V $ and $ V^* $. With this identification, you can think of $ \tilde{g}: V \rightarrow V $, and then take determinant of $ \tilde{g} $. However the sign of this is a well defined quantity, and independent of the choice of basis.


Is it possible to sum on webform

Question: I'm newbie and made web form to fill with some values.
I want to sum all values on Column to make it has a total of column Value, like in excel to do sum of several values into one grand total.
Anyone experienced this ?
Thanks in advanced.
Answer: There is a tab titled "Analysis" for this. Alternatively you can use the "Download" option. See the example in the screenshot below.
Answer: You can try Webform Calculator

Provides a formula webform component for computed values, where you
  can enter a mathematical calculation based on the other fields. E.g.,
  create a formula field with value formkey1 * 0.1 * formkey2.
Answer: You can try Webform Calculation Components.

This module provides AJAX functionality to perform basic arithmetic operations on webform components.
With this module the user can have calculated fields, e.g. the total amount, calculated percentage etc.

It works with Webform 7.x-4.x
Answer: If you would like to sum the webform submission data, you can use Views Aggregator Plus
https://www.drupal.org/project/views_aggregator
You can put sum function in the columns you want to sum. You can put the results in end of the row.
Comment: I am not sure on how Views Aggregator works with forms.

Is it possible to sum on webform


VC++ error C2065 in debug build

Question: I am porting a C++ project to VS2008.
Piece of the code has a variable declared in the for loop statement as below:
for(bmpMapType::const_iterator it = bitmaps.begin(); it != bitmaps.end(); ++it)
{
}
"it" is later used as an index in another for loop statement as below:
for(it = bitmaps.begin(); it != bitmaps.end(); ++it)
{
}
It generates error c2065 in debug build wit hthe below project settings where as release build was successful.
I have set the C\C++ > Language> For Conformance In For loop Scope to No (/Zc:forscope- ) and built the project with release configuration mode.
Code was built succesfully.
The same code with the same settings fail to build in debug mode.
Can anyone help me to resolve the issue.
Any help is appreciated.
Thanks,
Lakshmi
Answer: The it variable is declared within the for loop initializer list, which means its scope ends along with the for loop scope. Setting /Zc:forscope- option enables the MS specific extension which keeps the it declaration alive until the end of the enclosing scope in which your for loop is defined (for example, whatever function body your code snippet exists in). IMHO, you shouldn't be using the /Zc:forscope- flag since it compiles non-standard code without errors. To fix your problem you can do one of two things:
bmpMapType::const_iterator it;
//first loop
for( it = bitmaps.begin(); it != bitmaps.end(); ++it ) { ... }
...
//second loop
for( it = bitmaps.begin(); it != bitmaps.end(); ++it ) { ... }

OR
//first loop
for( bmpMapType::const_iterator it = bitmaps.begin(); it != bitmaps.end(); ++it ) { ... }
...
//second loop
for( bmpMapType::const_iterator it = bitmaps.begin(); it != bitmaps.end(); ++it ) { ... }

Comment: Thankyou. That works fine. I have a question why it works in release mode without declaring it again as mentioned
Comment: Make sure the `/Zc:forscope` flag has the same setting in both Debug and Release modes, as far as I know it should either build or fail in both build configurations if that flag is set consistently.
Answer: A simple fix may be just to modify the second loop to match the first - declaring its own copy of it as per
for(bmpMapType::const_iterator it = bitmaps.begin(); it != bitmaps.end(); ++it) {

}

unless there is some place in between the loops where the first it is used.  If usage of each is entirely local to their respective loops then just do this and get on with your port.

VC++ error C2065 in debug build


df reports zfs used space as 128K, not the actual used space

Question: I have a ZFS mirror pool in my Proxmox instance. I am trying to get it to mount to an LXC container read-only (preferably not giving full filesystem access) so I can have Homepage detect the used and free space properly for monitoring purposes.
Other serverfault questions and answers have reported that df -hT should be able to report used space of zfs filesystems properly (minus parity data, possibly compression or dedupe data, but I'm not looking for 100% accuracy here)
But for me, df -hT reports the total space as what's available, and the used space as 128K.
root@pve:~# df -hT /nvme
Filesystem     Type  Size  Used Avail Use% Mounted on
nvme           zfs   590G  128K  590G   1% /nvme

/nvme is the toplevel zfs dataset is it not? Why does the space seem to be oddly calculated across these datasets?
root@pve:~# zfs list
NAME                     USED  AVAIL  REFER  MOUNTPOINT
nvme                     309G   590G   128K  /nvme
nvme/base-103-disk-0    43.4G   631G  2.19G  -
nvme/nvmecheck            96K   590G    96K  /mnt/nvmecheck
nvme/subvol-102-disk-0   554M  1.46G   554M  /nvme/subvol-102-disk-0
nvme/subvol-105-disk-0  1.71G  2.29G  1.71G  /nvme/subvol-105-disk-0
nvme/subvol-106-disk-0   625M  1.39G   625M  /nvme/subvol-106-disk-0
nvme/subvol-107-disk-0  3.37G  11.6G  3.37G  /nvme/subvol-107-disk-0
nvme/subvol-108-disk-0  1.18G  1.82G  1.18G  /nvme/subvol-108-disk-0
nvme/subvol-109-disk-0   533M  1.48G   533M  /nvme/subvol-109-disk-0
nvme/vm-100-disk-0      43.3G   624G  8.96G  -
nvme/vm-101-disk-0       132G   607G   115G  -
nvme/vm-104-disk-0      82.5G   661G  11.6G  -

FYI, nvme/nvmecheck is a dataset I made to see how child datasets would be calculated. It's even stranger with its reference.
Can anyone tell me what is going on? Maybe it's Debian's zfs implementation? Or something wrong with df?
zpool status is warning me that there are missing features with my zpool that I can run zpool upgrade, but I'm unsure if this is safe. My Proxmox is using the new boot tool, not legacy, so that should not be a concern.
zfs's USEDDS property may be related, but unsure:
root@pve:~# zfs list -o space nvme
NAME  AVAIL   USED  USEDSNAP  USEDDS  USEDREFRESERV  USEDCHILD
nvme   590G   309G        0B    128K             0B       309G

As you can see below, ZFS has a few properties where this 128K may derive from also.
root@pve:~# zfs get all nvme
NAME  PROPERTY              VALUE                  SOURCE
nvme  type                  filesystem             -
nvme  creation              Sat Jul 22 20:53 2023  -
nvme  used                  309G                   -
nvme  available             590G                   -
nvme  referenced            128K                   -
nvme  compressratio         1.13x                  -
nvme  mounted               yes                    -
nvme  quota                 none                   default
nvme  reservation           none                   default
nvme  recordsize            128K                   default
nvme  mountpoint            /nvme                  default
nvme  sharenfs              off                    default
nvme  checksum              on                     default
nvme  compression           on                     local
nvme  atime                 off                    local
nvme  devices               on                     default
nvme  exec                  on                     default
nvme  setuid                on                     default
nvme  readonly              off                    default
nvme  zoned                 off                    default
nvme  snapdir               hidden                 default
nvme  aclmode               discard                default
nvme  aclinherit            restricted             default
nvme  createtxg             1                      -
nvme  canmount              on                     default
nvme  xattr                 on                     default
nvme  copies                1                      default
nvme  version               5                      -
nvme  utf8only              off                    -
nvme  normalization         none                   -
nvme  casesensitivity       sensitive              -
nvme  vscan                 off                    default
nvme  nbmand                off                    default
nvme  sharesmb              off                    default
nvme  refquota              none                   default
nvme  refreservation        none                   default
nvme  guid                  [redacted]             -
nvme  primarycache          all                    local
nvme  secondarycache        all                    default
nvme  usedbysnapshots       0B                     -
nvme  usedbydataset         128K                   -
nvme  usedbychildren        309G                   -
nvme  usedbyrefreservation  0B                     -
nvme  logbias               latency                default
nvme  objsetid              54                     -
nvme  dedup                 off                    default
nvme  mlslabel              none                   default
nvme  sync                  standard               default
nvme  dnodesize             legacy                 default
nvme  refcompressratio      1.00x                  -
nvme  written               128K                   -
nvme  logicalused           164G                   -
nvme  logicalreferenced     54.5K                  -
nvme  volmode               default                default
nvme  filesystem_limit      none                   default
nvme  snapshot_limit        none                   default
nvme  filesystem_count      none                   default
nvme  snapshot_count        none                   default
nvme  snapdev               hidden                 default
nvme  acltype               off                    default
nvme  context               none                   default
nvme  fscontext             none                   default
nvme  defcontext            none                   default
nvme  rootcontext           none                   default
nvme  relatime              on                     default
nvme  redundant_metadata    all                    default
nvme  overlay               on                     default
nvme  encryption            off                    default
nvme  keylocation           none                   default
nvme  keyformat             none                   default
nvme  pbkdf2iters           0                      default
nvme  special_small_blocks  0                      default

My zpool properties:
root@pve:~# zpool get all nvme
NAME  PROPERTY                       VALUE                          SOURCE
nvme  size                           928G                           -
nvme  capacity                       15%                            -
nvme  altroot                        -                              default
nvme  health                         ONLINE                         -
nvme  guid                           [redacted]                     -
nvme  version                        -                              default
nvme  bootfs                         -                              default
nvme  delegation                     on                             default
nvme  autoreplace                    off                            default
nvme  cachefile                      -                              default
nvme  failmode                       wait                           default
nvme  listsnapshots                  off                            default
nvme  autoexpand                     off                            default
nvme  dedupratio                     1.00x                          -
nvme  free                           782G                           -
nvme  allocated                      146G                           -
nvme  readonly                       off                            -
nvme  ashift                         12                             local
nvme  comment                        -                              default
nvme  expandsize                     -                              -
nvme  freeing                        0                              -
nvme  fragmentation                  12%                            -
nvme  leaked                         0                              -
nvme  multihost                      off                            default
nvme  checkpoint                     -                              -
nvme  load_guid                      [redacted]                     -
nvme  autotrim                       off                            default
nvme  compatibility                  off                            default
nvme  bcloneused                     0                              -
nvme  bclonesaved                    0                              -
nvme  bcloneratio                    1.00x                          -
nvme  feature@async_destroy          enabled                        local
nvme  feature@empty_bpobj            active                         local
nvme  feature@lz4_compress           active                         local
nvme  feature@multi_vdev_crash_dump  enabled                        local
nvme  feature@spacemap_histogram     active                         local
nvme  feature@enabled_txg            active                         local
nvme  feature@hole_birth             active                         local
nvme  feature@extensible_dataset     active                         local
nvme  feature@embedded_data          active                         local
nvme  feature@bookmarks              enabled                        local
nvme  feature@filesystem_limits      enabled                        local
nvme  feature@large_blocks           enabled                        local
nvme  feature@large_dnode            enabled                        local
nvme  feature@sha512                 enabled                        local
nvme  feature@skein                  enabled                        local
nvme  feature@edonr                  enabled                        local
nvme  feature@userobj_accounting     active                         local
nvme  feature@encryption             enabled                        local
nvme  feature@project_quota          active                         local
nvme  feature@device_removal         enabled                        local
nvme  feature@obsolete_counts        enabled                        local
nvme  feature@zpool_checkpoint       enabled                        local
nvme  feature@spacemap_v2            active                         local
nvme  feature@allocation_classes     enabled                        local
nvme  feature@resilver_defer         enabled                        local
nvme  feature@bookmark_v2            enabled                        local
nvme  feature@redaction_bookmarks    enabled                        local
nvme  feature@redacted_datasets      enabled                        local
nvme  feature@bookmark_written       enabled                        local
nvme  feature@log_spacemap           active                         local
nvme  feature@livelist               enabled                        local
nvme  feature@device_rebuild         enabled                        local
nvme  feature@zstd_compress          enabled                        local
nvme  feature@draid                  enabled                        local
nvme  feature@zilsaxattr             disabled                       local
nvme  feature@head_errlog            disabled                       local
nvme  feature@blake3                 disabled                       local
nvme  feature@block_cloning          disabled                       local
nvme  feature@vdev_zaps_v2           disabled                       local

Answer: df will report how much storage is used by that mountpoint itself, e.g. files that are currently stored directly in /nvme (not considering neither snapshots nor reservations). It seems there are just some subfolders for the other mountpoints in there, hence the little usage of 128K.
The USED column of zfs list however shows the usage of the whole sub-tree, including children (and snapshots).
zpool upgrade is generally safe to run; the only drawback is that the pool then can only be used on systems that support all of the activated features, e.g. you might not be able to open it using a previous snapshot of the system or a rescue image.
Comment: Hmm... do you care about how much is currently used, or how much would be available for consumption?
Comment: Anyways, you can't get useful monitoring information about a whole ZFS pool just by looking at `du/df` output of a single zfs volume.
Comment: Thank you. I found similar info. The frustration is Homepage does its space checks with df and my zfs pool is on the host, so the zfs command is inaccessible from the lxc container. I'll have to look into alternative methods, I guess.


Problem when downloading large files using Storage module

Question: I'm using the Storage module to managed uploads on my website. I'm hosted on EC2, some content is sent to S3, and some stays on EC2.
Logged in users are able to transfer files to each other. One user uploads the file, and the other goes to download it.
The files that are causing problems are stocked on EC2.
A user is able to upload a large file (4 gb for example), to the server, but when someone tries to download the file, they get a file of 0b.
I checked via FTP and the file is there and complete (i downloaded it and opened it).
When moving the file to another directory (/default/files/file.zip), it works. If it is in the "/system/storage/serve/359/file.zip" it doesn't work.
--- EDIT ---
Forgot to mention that it DOES NOT happen with small files.
--- EDIT ---
Does anyone has any suggestion?
Thanks !
Answer: I would have preferred to put this into a comment, but I don't have enough rep points yet. :/
First, a few questions: What version of PHP are you using?  Does the same thing happen with small files?  Are you using symlinks?  Do your server logs show anything suspicious?
I am trying to fix a similar problem on one of my sites.  PHP 5.4 works fine, but 5.5 is choking when trying to interact with the file, which happens to be linked into a mounted filesystem.  They are on different versions of Ubuntu as well, so I am currently trying to figure out if it is a Linux kernel bug, a PHP bug, or a PEBKAC error.
Comment: It is not happening on small files for me. We are under php 5.3, Ubuntu.
Comment: It sounds like PHP is croaking... perhaps it is running out of memory.  I know that you said you are using Storage API, but am I correct in assuming that a direct link to the file (the actual location on the server) works, but the Drupal URL does not?  If that is the case, then your answer will probably either be in your PHP logs or webserver logs.


Imagens estão repetindo nos ImageViews

Question: Eu tenho 54 imagens preciso mostrar apenas 8, mas tem que ter uma seleção aleatória e não podem se repetir, estou programando na plataforma do Android Studio.
Eu uso esse código ele funciona tranquilo,Mostra os resultado em 8 ImagemView ,Mais.... ele repete os resultados da imagem ;(
insira o código aqui

public void Button2(View view) {

        final int[] imageViews = {
                R.id.imageView, R.id.imageView4, R.id.imageView7,
                R.id.imageView2, R.id.imageView5, R.id.imageView8,
                R.id.imageView3, R.id.imageView6,};

        final int[] images = {

                R.drawable.1,
                R.drawable.2,
                R.drawable.3,
                R.drawable.4,
                ...... vai até o 54

        };

        final Button shuffle = (Button) findViewById(R.id.Button2);
        shuffle.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                Random generator = new Random();
                int n = 9;
                n = generator.nextInt(n);
                Random random = new Random(System.currentTimeMillis());
                for (int v : imageViews) {
                    ImageView iv = (ImageView) findViewById(v);
                    iv.setImageResource(images[generator.nextInt(images.length - 1)]);
                }
            }
        });
    }

insira o código aqui

Usei este Código abaixo resolveu o problema.
};
final Button shuffle = (Button) findViewById(R.id.Button4);
shuffle.setOnClickListener(new View.OnClickListener() {
    public void onClick(View view) {

        Random rng = new Random();
        List<Integer> generated = new ArrayList<Integer>();
        for (int i = 0; i < 8; i++)
        {
            while(true)
            {
                Integer next = rng.nextInt(54) ;
                if (!generated.contains(next))
                {
                    generated.add(next);
                    ImageView iv = (ImageView)findViewById(imageViews[i]);
                    iv.setImageResource(images[next]);
                    break;
                }
            }
        }
    }
});}}
insira o código aqui

Fonte:https://stackoverflow.com/questions/7470509/how-to-set-random-images-to-imageviews
Comment: Wallace este site funciona de forma diferente de um fórum, logo, você não precisa adicionar que foi resolvido no titulo. ao inves disso, você pode aceitar uma resposta como aceita, clicando no `v` ao lado da resposta. Dessa forma, é como se a pergunta ficasse marcada como "resolvida".
Comment: Engraçado, você respondeu sua pergunta na sua própria pergunta, que por ventura está bem parecido com minha resposta.
Answer: Você pode fazer desta forma, comparando se o número gerado já existe no ArrayList:
int totalImagens = 54;
int totalEscolher = 10;
ArrayList<Integer> numbers = new ArrayList<Integer>();
Random randomGenerator = new Random();
while(numbers.size() < totalEscolher)
    {
        int random = randomGenerator.nextInt(totalImagens);
        if (!numbers.contains(random)) {
            numbers.add(random);
        }
}

Pensando desta forma, seu setOnClickListener ficaria assim:
final Button shuffle = (Button) findViewById(R.id.Button2);
        shuffle.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {

                int totalImagens = images.length;
                int totalEscolher = 10;
                final ArrayList<Integer> numbers = new ArrayList<Integer>();
                Random randomGenerator = new Random();
                while(numbers.size() < totalEscolher)
                {
                    int random = randomGenerator.nextInt(totalImagens);
                    if (!numbers.contains(random)) {
                        numbers.add(random);
                    }
                }

                for (int v : numbers) {
                    imageViews[v] = images[numbers.get(v)];
                    ImageView iv = (ImageView) findViewById(v);
                    iv.setImageResource(imageViews[v]);
                }
            }
        });

Comment: Ok, obrigado pela ajuda, mais como eu posso integrar esse código no meu projeto, desculpe mais não intendo muito. aguardo resposta, enquanto isso vou tentar implementar ele aqui.
Comment: @WallaceRoberto editei a resposta. Tente fazer desta maneira para ver se funciona.
Comment: Ta, e como eu faço agora na parte de cima, to pesquisando aqui sobre ArrayList mais sem sucesso, se você ver la em cima estou usando Imagens (R.drawable.exemplo) e a segunda linha ("final int[] imageViews = {")   ela continua?
Comment: @WallaceRoberto blz! Editei novamente para você. Agora pegando a imagem que está no seu images. Em cima você pode deixar da mesma forma inserindo as imagens.
Comment: Está dando erro, logo após apertar o botão.                                                  09-14 17:47:22.890 343-425/system_process W/NetworkManagementSocketTagger: setKernelCountSet(10054, 0) failed with errno -1

Imagens estão repetindo nos ImageViews


Dereference a rvalue shared_ptr

Question: I'm using a library which export a function like:
// there is some type T
std::shared_ptr<T> foo(params);

and while the following code works fine:
auto p = foo(params);
auto & v0 = *p;
// use v0 as a T's reference

the below crashes:
auto & v1 = *foo(params);
// use v1 as a T's reference

So what is the difference between v0 and v1? Many thanks for any help.
Answer: The object pointed at by a shared_ptr exists only as long as there is at least one shared pointer alive that still points at it.
In your example there is likely only one such pointer, and it's returned by foo.
For v0, p becomes the shared_ptr keeping the object alive.
For v1, there is only a temporary shared pointer that exists only for the duration of v1's initialization. The pointer and object being pointed at are gone by the time you use the reference, making it a dangling one at the point of use.
Comment: Thanks a lot, short and precise answer. I've though that the dereference may help "pin" the `T`'s object from shared pointer instances, but it's not.
Comment: @TaThanhDinh - Nah, the pointer pins the object, not the other way around. A reference to the object is still a "dumb" reference.
Answer: The statement
auto & v1 = *foo(params);

is a potential undefined behavior.
The function foo probably construct a std::shared_ptr inside and returns it to the caller as a temporary object (technically a prvalue) which is supposed to be assigned to some variable.
You don't assign the smart pointer of your expression to any variable. However, you grab the object pointed by (using the * operator) and assign it to the reference v1.
At the end of the expression evaluation the temporary std::shared_ptr will be destroyed and (being a smart pointer) the object pointed as well.
Therefore, auto & v1 is referring to a destroyed object and accessing to it is an undefined behavior (producing a segmentation fault in the majority of cases).
Comment: Thanks for pointing out that accessing a destroyed object is an undefined behavior.
Answer: In your first example, p remains in scope, holding a reference to the object and thereby keeping it alive. In your second example, the shared_ptr is destroyed after v1 is created, which destroys the object (assuming it was the only reference) and leaving v1 pointing to unallocated memory.

Dereference a rvalue shared_ptr


Facebook's l.php

Question: So recently i gave my friend a URL on facebook chat while we were discussing on how much further we have to go on a booking system, my friend says he cant open the link, when i tried clicking it worked but what caught my eye was the referring URL by facebook:

https://www.facebook.com/l.php?u=https%3A%2F%2F192.168.42.149%2FIS314%2Freservations.php

I was intrigued by the l.php (L.PHP), what actually does l.php do? I googled and a author speculated something on privacy at this page http://www.codehesive.com/index.php/archive/facebook-privacy-and-the-mystery-of-l-php/ but nothing too certain. So i was wondering if anyone has a clear idea of what l.php could be, i find this interesting (weird i know). Thanks!
Comment: This question can really only be answered by someone at Facebook that has knowledge of the actual code behind these redirects.
Comment: While this is an interesting question, I don't think it's a good fit for the [so] format as most answers here will be speculation without the ability to give a concrete answer.
Answer: No one can know what exactly that script does but the developers at Facebook.
I presume they track all outgoing links from Facebook to get some statistics on them and on the users. After that it just sends you to the external page.
Comment: What a dystopian prediction!
Comment: This might also be used for content moderation?
Answer: Please check out the following article Facebook, privacy and the mystery of l.php which says:

Unless it's from a public page, all you're bound to see is one simple
  referring URL: http://www.facebook.com/l.php. Facebook 'wraps' all
  links on Facebook within this simple file — once you click on a link
  in Facebook, l.php will 'redirect' you to the actual URL. Why Facebook
  does this is unclear.

So now you have more questions to answer.
Update: Sorry, I just realised that you posted actually the same link.

Facebook's l.php


Google Sheets - Find all occurrences of target over 2d RANGE, select other value in row when found

Question: Please see the attached example: Sheets Example
For this example, assume we receive the first tab (Awards List) as data. Column A is names of awards, Columns C through E represent up to 3 possible winners per awards.
Assume we also have Column A in the second tab, (awards per person), where the column is a list of all award titles.
I would like to write a formula for the data you see in Column C. This formula would at the names in Column A in "Awards Per Person" tab, search for all occurrences of the names through columns C through E in tab "Awards List" and produce a single cell listing of all awards won by the names in Column A in "Awards Per Person" as demonstrated in the link above.
Thanks!
I have been tinkering with vlookup, index/match, textjoin etc. and am having zero luck - I think because the search area is 2D instead of a single column or row. Any way I can do this without a macro/code?
Answer: You can use MAP to go through each name, FILTER to find the awards and inside of it BYROW to see if there's a match with the name in each row. Then TEXTJOIN will concatenate the values:
<code>=MAP(A3:A, LAMBDA(name,IF(name="","",TEXTJOIN(", ",1,IFNA(FILTER('Awards List'!A3:A,BYROW('Awards List'!C3:E, LAMBDA(r,IFNA(MATCH(name, r,0),0)>0)))),))))
</code>

The use of BYROW allows you to create a column with TRUE or FALSE if the name is met in each row. This way, column A of awards will be filtered according to it
Answer: You may give a try to the following formula-
<code>=MAP(TOCOL(A3:A,1),LAMBDA(x,
TEXTJOIN(", ",1,FILTER('Awards List'!A3:A,MMULT(INDEX(--('Awards List'!C3:E=x)),SEQUENCE(COLUMNS('Awards List'!C3:E3),1,1,0))))))
</code>
Answer: You may try:
<code>=map(A3:A,lambda(Σ,if(Σ="",,textjoin(", ",1,index(if('Awards List'!C3:E=Σ,'Awards List'!A3:A,))))))
</code>


Java print last name in arraylist

Question: i have this
ArrayList<String> players = new ArrayList<String>();

players.add("Albert Pujols");
players.add("Jim Edmonds");
players.add("Josh Hamilton");
players.add("Mike Trout");
players.add("Adrian Gonzalez");
players.add("Price Fielder");
players.add("Steven Strasburg");
players.add("Jose Bautista");
players.add("Bryce Harper");
players.add("Mike Trout");

how would i make a method to print out only the last name:
Pujols
Edmonds
Hamilton
Trout
Gonzalez
Fielder
Strasburg
Bautista

I have something like this but im stuck:
public static void printLastName(ArrayList<String> players) {
    for (int i = 0; i < players.size(); i++)
        System.out.println(players.get(i));
}

Comment: Why don't you create a class Player with attributes `firstName` and `lastName`? Then you would have a `List` and your loop would be simply `for(Player p : players) System.out.println(p.getLastName());` Java is an OO language, so make use of it.
Comment: As @AlexisC. mentionned you can create class called "Player", with the firstname and lastname as an attributes, after that you can decalare an ArrayList players = new ArrayList(); ,, greetings.
Answer: I guess, all names are single space separated.So, just split and print last part
System.out.println(players.get(i).split(" ")[1]);

As, Alexis C mentioned, you should create a model class with firstName and lastName and store the class instances in List
Answer: You could just introduce a Player class....
    public class Player {

        final String firstName;
        final String lastName;

        public Player(final String firstName, final String lastName) {
            this.firstName = firstName;
            this.lastName = lastName;
        }

        @Override
        public String toString() {
            return this.lastName;
        }

        @Override
        public boolean equals(final Object o) {
            if (this == o) {
                 return true;
            }
            if (!(o instanceof Player)) {
                return false;
            }

            final Player player = (Player) o;

            if (firstName != null ? !firstName.equals(player.firstName) : player.firstName != null) {
                return false;
            }
            return !(lastName != null ? !lastName.equals(player.lastName) : player.lastName != null);
        }

        @Override
        public int hashCode() {
            int result = firstName != null ? firstName.hashCode() : 0;
            result = 31 * result + (lastName != null ? lastName.hashCode() : 0);
            return result;
        }
    }

Answer: You should change your code to
public static void printLastName(ArrayList<String> players) {
for (int i = 0; i < players.size(); i++)
    System.out.println(players.get(i).split(" ")[1]);
}

Answer: just split it space of String function split() using \\s because "  "  will not work in java
here is the example
 String lastname = players.get(i).Split("\\s+")[1]; //even split("\\s"); will also work

if you want do it with Pattern class use below code
private static final Pattern SPACE = Pattern.compile(" ");//outside for loop
String lastname = SPACE.split(players.get(i))[1]; // inside for loop

Comment: I m the first to split it with regex :P
Answer: You may want to let Arraylist hold a String array, such as
ArrayList<String[]> players = new ArrayList<String[]>();
String[] player1 = {"Albert", "Pujols"};
players.add(player1);
System.out.println(players.get(0)[1]);

Java print last name in arraylist