Good examples of mathematical writing (structural organization, style, typesetting, and so on)

Question: A very famous question on MathOveflow asks for examples of good mathematical writing. Here, I'd like to narrow down the topic and ask:

$\color{#c00}{\text{Question:}}$

Could you point out some examples of good mathematical writing
organization: that is, can you give reference to papers that distinguish themselves for a particularly good exposition, structural
    organization, style, typesetting, formatting, references organization, organization of the table of content, organization of the index (if there is any), acknowledgement section, dedication or epigraph, name and affiliation of the authors, etc?

In other words, I would like you to point out papers where the "details" mentioned above (that are often overlooked in the process of writing a paper by mathematicians who focus only on the results of a paper rather than on the presentation) are particularly well-crafted.
Note that I would prefer references to preprints that are available on the ArXiv, because published papers tend to reflect the choices of the journal when it comes to matters of style.
Comment: Check out the small booklet (about 100 pages) "Mathematical Writing" (Mathematical Association of America Notes) by Knuth (ISBN 10: 088385063X). It is (of course) not an actual paper.
Comment: It would be nice if the phrase "A very famous question" was a link to the said question. Were you referring to http://mathoverflow.net/q/358 ?
Comment: You want to see well crafted documents be it articles or something else?
Comment: @dustin, yes, research articles.
Comment: None of the answers appeal to you? I think Nick's answer along with mine are good enough...considering we seem to have actually put in some effort to answer. I also wonder why every answer has been downvoted here.
Comment: @Kugelblitz Actually, it wasn't me who downvoted; and, for the record, I like your answers. I hope that other interesting suggestions will be made. So, $+1$. :)
Answer: While I was trying to get pdfs of books written by Polya, I came across an award named after him here:
http://www.maa.org/programs/maa-awards/writing-awards
Looks like there are a whole slew of awards given to outstanding articles/papers/books:

http://www.maa.org/programs/maa-awards/writing-awards/carl-b-allendoerfer-awards
http://www.maa.org/programs/maa-awards/writing-awards/chauvenet-prizes
http://www.maa.org/programs/maa-awards/writing-awards/hasse-prizes
http://www.maa.org/programs/maa-awards/writing-awards/trevor-evans-awards
http://www.maa.org/programs/maa-awards/writing-awards/george-polya-awards
http://www.maa.org/programs/maa-awards/writing-awards/paul-halmos-lester-ford-awards
http://www.maa.org/programs/maa-awards/writing-awards/robbins-prizes-0

These links link you to various awards given for good quality research and writing; you can see past winners and encounter good papers.
But you've specifically asked for papers with good organised writing structure, so these links below are the awards given specifically, for outstanding articles and expository papers:-

Levi Covenant award: http://www.ams.org/profession/prizes-awards/ams-prizes/conant-prize
George Polya award: http://www.maa.org/programs/maa-awards/writing-awards/george-polya-awards
Paul R. Halmos - Lester R. Ford Awards: http://www.maa.org/programs/maa-awards/writing-awards/paul-halmos-lester-ford-awards
David P. Robbins Prize: http://www.ams.org/profession/prizes-awards/pabrowse?purl=robbins-prize

Being a tenth grader, I obviously haven't had much exposure to papers (Mainly because the vast array of contemporary papers are in journals which require you to subscribe to them by providing verification that you're a professional in some field of math/science; I'm not).
But, coincidentally, I had come across a paper I thought was excellent and saved it. Looks like it was the recipient of the fourth award I've mentioned in the aforementioned list; the David P. Robbins Prize. It's written by Thomas C. Hale.
http://annals.math.princeton.edu/wp-content/uploads/annals-v162-n3-p01.pdf
I think it's really good and is really clear. Very organised as well, providing contents as well as a useful Index.
If I come across better ones, I shall update this post.
Answer: Here's a couple review papers that (in my opinion) are written and organized excellently with respect to the categories mentioned:

Boyd, Stephen, et al. "Distributed optimization and statistical learning via the alternating direction method of multipliers." Foundations and Trends® in Machine Learning 3.1 (2011): 1-122.
https://web.stanford.edu/~boyd/papers/pdf/admm_distr_stats.pdf
Kolda, Tamara G., and Brett W. Bader. "Tensor decompositions and applications." SIAM review 51.3 (2009): 455-500.
http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.153.2059&rep=rep1&type=pdf


conditional expectation for Poisson

Question: Suppose that $X_t$ is a Poisson process with parameter  $\lambda= 3$. Find $E(X_2 + X_4 | X_3)$?
I do not know how to approach this problem. Thanks.
Comment: You could start with $E(X_2+X_4|X_3) = E(X_2|X_3) +E(X_4|X_3)$. Next note that $X_4 = X_3+U$ where $U$ is the increment. This solves half of your problem.
Answer: To begin with, you can determine the conditional distribution of $X_2$ given $X_3$ as follows: if $n \geq m$, then
\begin{align}
& P[X_2 = m | X_3 = n]  \\
= & \frac{P(X_2 = m, X_3 = n)}{P(X_3 = n)} \\
= & \frac{P(X_2 = m, X_3 - X_2 = n - m)}{P(X_3 = n)} \\
= & \frac{P(X_2 = m)P(X_3 - X_2 = n - m)}{P(X_3 = n)} \quad \text{(by incremental independence)}\\
= & \frac{e^{-6}\frac{6^m}{m!} \times e^{-3}\frac{3^{n - m}}{(n - m)!}}{e^{-9}\frac{9^n}{n!}} \quad \text{(by } X_t - X_s \sim \text{ Poisson}(\lambda(t - s)))\\
= & \binom{n}{m}\left(\frac{2}{3}\right)^m\left(\frac{1}{3}\right)^{n - m} , \quad m = 0, 1, \ldots, n.
\end{align}
If $n < m$, the conditional probability is $0$. Therefore,
$$X_2 | X_3 \sim \text{Binomial}(X_3, 2/3),$$
which leads to $E[X_2 | X_3] = \frac{2}{3}X_3$. $E[X_4 | X_3]$ can be handled similarly.

conditional expectation for Poisson


How to create a dynamic-width arrow in CSS?

Question: I need to write a page that has a full-width arrow on the bottom of the page. Thus, I use the following HTML:

the relevant CSS being:
#footer_wrap{
width: 100%;
}

#footer_left{
background: url('../img/arrow_bg1.png') repeat-x;
width: 100%;
height: 183px;
position: absolute;
left: 0;
}

#footer_right{
display: inline-block;
background: url('../img/arrow_bg2.png') no-repeat;
width: 250px;
height: 183px;
position: absolute;
right: 0;
}

In theory, this should work - and indeed, it did, when I used images with fixed background colors. However, my client required them to be transparent, which unfortunately revealed the ugly truth behind my hack - the arrow's "shaft" peeks out of the arrow head. What can I do about it?
The images comprising the arrow are a 1x183px "shaft" texture that is repeated for the entire length of the arrow (or, in this case, the entire page [width: 100%]), and the arrowhead is a 250x183px rectangle.
The arrow needs to take up the entire page and it needs to use transparent images, so these solutions are out of the window immediately. I suppose something like width: 100%-250px would be acceptable, but these shenanigans aren't supported in CSS.
Comment: Do you need crossbrowser-support, or can you use something like `box-sizing: border-box; padding-right: 250px;` on the footer_left?
Answer: You're already using position:absolute; so instead of width:100%, you can set left and right:
#footer_left{
position: absolute;
left: 0;
right:250px;
/* etc */
}

There are many other workarounds, but for your specific case i think it's the easiest.
Comment: Way neater solution. Again though, make sure the "width" is the same with the "right". My experience says is good practice to put a comment by both values.
Answer: I think this method might work: http://jsfiddle.net/27p4e/

left

right

.footer {
width:100%;
height:183px;
overflow:auto;
background:#ccc;
display:table;
}

.footer-left {
display:table-cell;
background:red;
height:183px;
}
.footer-right {
display:table-cell;
width:250px;
height:183px;
background:blue;
}


How to interchange the key value output of app.url_map.iter_rules function

Question: I have this python code which gives me all the api routes along with details in a JSON format when I hit the API GET request on http://localhost:9985/api/help
from flask import Flask, jsonify
app = Flask(__name__)

@app.route('/myapi', methods = ['GET'])
def this_func():
    """ /read"""
    return jsonify({})

@app.route('/api/help', methods = ['GET'])
def help():
    """ /write"""
    func_list = {}
    for rule in app.url_map.iter_rules():
        if rule.endpoint != 'static':
            func_list[rule.rule] = app.view_functions[rule.endpoint].__doc__
    return jsonify(func_list)

if __name__ == '__main__':
   app.run(host='localhost', port=9985)

Output of this gives me:
{
  "/api/help": "/write",
  "/myapi": "/read"
}

I want to have the position of key and value interchanged which means I want the output to look like:
{
  "/write": "/api/help",
  "/read": "/myapi"
}

How can I achieve this?
Comment: I am sorry I did not get the question
Comment: Does `func_list[app.view_functions[rule.endpoint].__doc__] = rule.rule` fix the problem?
Comment: @lord63.j no it gave me error TypeError: unorderable types: str() < NoneType()
Comment: @lovesoftlayeraj: then please post the full traceback for that error. You don't have any `<` comparisons in your posted code.
Comment: http://flask.pocoo.org/snippets/129/ This is exactly what I have in my application
Answer: Just swap the key and the value then; make rule.rule the value for each __doc__ key:
if rule.endpoint != 'static':
    docstring = app.view_functions[rule.endpoint].__doc__
    if docstring is not None and docstring.strip():
        func_list[docstring.strip()] = rule.rule

It may be that not all your routes have a docstring, so do test for that. I also used the str.strip() method to remove the extra whitespace you have in your docstrings. You may also want to limit this to the first line only:
if docstring is not None and docstring.strip():
    func_list[docstring.partition('\n')[0].strip()] = rule.rule

Note that func_list is a misleading name for a dictionary.
Comment: this worked perfectly but I still have those extra spaces. The strip command doesn't work. This is my stack trace          File "/root/Python-3.5.0/venv/lib/python3.5/site-packages/flask/app.py", line 1461, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/root//app-develop/test.py", line 18, in help
    if docstring.strip():                                                                                AttributeError: 'NoneType' object has no attribute 'strip'
Comment: Thank you so much! This worked awesome!  One last question - In my original application I have all my routes tagged as                        api.route('/read/', methods=['GET'])
In this test script I have app.route('/read/', methods=['GET'])                                                      How can I modify this script to work with api.route instead of app.route where app = Flask(___name___)
 and api is an import I have in my original application.
Comment: I can't answer that as that depends entirely on the type of object of `api`.
Comment: http://flask.pocoo.org/snippets/129/ This is exactly what I have and I want to iterate over urls map for several such APIs and save into a json structure
Comment: That uses Flask Restful, and the API object is then an instance of `flask_restful.Api`.
Comment: app = Flask(__name__)
from .api_1 import api as api_blueprint
app.register_blueprint(api_blueprint) this is my api object its a blueprint and not a restful api object
Comment: @lovesoftlayeraj: blueprints collect all `route()` calls into a deferred state, then when you use `app.register_blueprint(api_blueprint)` all `api.route()` calls are 'replayed' to the `Flask` object. Other than that, all that happens is that the routes are prefixed with the blueprint prefix; they are regular routes just like `app.route()` calls give you. My code in my answer works for those just as well.
Comment: So do you mean I should simple copy this code with app.route in my apiroutes.py file where all my APIs are defined with api.route annotation? Which means my Python file will have all APIs annotated as api.route except this one with app.route annotation? If yes how to initialise app in my Python file ? I don't have any app object there ..Thanks a ton!
Comment: @lovesoftlayeraj: because your `help` route can only be called after your `api` blueprint has been properly registered, it should just work, yes.
Comment: I got this                                                                                File "/root/python/api/apiroutes.py",                                                                       line 26, in
    @app.route('/api/help', methods = ['GET'])
NameError: name 'app' is not defined
Comment: @lovesoftlayeraj: yes, you still need to import `app` to get to the name.
Comment: I imported app and then the added api with app.route('/api/help', methods = ['GET']). I got 404 error. Looks like will have to register this in blueprint? If I change to api.route I get  a blank json response as all my other APIs have api,route as annotation and not app.route so that means this function only reads apis defined with app.route tag.
Comment: @lovesoftlayeraj: we are really stretching the comments to breaking point here. Perhaps it is time to post a new question instead?
Comment: Sure I have another thread. Also invited you to a chat http://stackoverflow.com/questions/36516408/how-to-iterate-over-api-routes-in-a-different-file-than-the-app-initialization-f


Google gtag_report_conversion: how can I use it without reloading my page?

Question: I have the form in the popup. I need to use this script:
function gtag_report_conversion(url) {
  var callback = function () {
    if (typeof(url) != 'undefined') {
        window.location = url;
    }
  };
  gtag('event', 'conversion', {
    'send_to': 'id_of_analytics',
    'event_callback': callback
  });
  return false;
}

And on submit I use:
onclick="return gtag_report_conversion('my_page_url')"

But when I click submit-button, my page get reloaded and popup with form get closed. And no error- or success-messages are displayed.
How can I use this script without reloading my page?
Answer: Change this line
  window.location = url;
to
// window.location = url;

Answer: Basically the callback function will forward you to the url you call with the gtag_report_conversion function. So if you just don't pass the url, then this check
if (typeof(url) != 'undefined') {
        window.location = url;
    }

will evaluate to false and the forwarding won't be triggered.


Rationale for MCEM

Question: From what I've read, the main advantage of the EM algorithm is that the expectation step can be expressed in closed form giving a deterministic answer and thus 0 variance.
What's the rationale then behind MCEM (Monte Carlo EM) methods [1] which use sampling to calculate the E-step? Specifically, is there a theoretical/empirical evidence that MCEM gives lower variance than just doing sampling on the full likelihood or are there some other advantages of the EM algorithm that come into play here?
[1] http://www.biostat.jhsph.edu/~rpeng/biostat778/papers/wei-tanner-1990.pdf
Edit: To clarify, I mean that if you have the likelihood $\log \sum_z p(y|x)$, $z$ being latent, then one option is to use EM (or MCEM if your approximating distribution cannot give you a closed form). The other way I can see is to estimate the sum directly via sampling. So my question is if you're using sampling anyway, why use MCEM over directly integrating the likelihood.
Edit 2: Replaced MCMC with sampling which is what I had in mind -- got the names confused, sorry.
Answer: To answer you question very literally, MCEM and MCMC are algorithms used to solve different problems. MCEM maximizes a likelihood function (or posterior probability in the case of MAP estimates), while MCMC integrates over a posterior distribution.
When you talk about variance, you are talking about the estimators, not algorithms. So your question should be rephrased as "which has lower variances, posterior means or MLE estimates?". That, of course, is a very vague question.
Comment: Hmm I don't think I follow :- if you have the likelihood log \sum_z p(y|x), z being latent, then one option is to use EM (or MCEM if your approximating distribution cannot give you a closed form). The other way I can see is to estimate the sum directly via MCMC. So my question is if you're using sampling anyway, why use MCEM over MCMC.
Comment: perhaps sampling is what I meant instead of MCMC
Comment: I think the best way to phrase this is if you are going to using sampling (required for MCEM), is there an advantage to maximizing (MLE or MAP) rather than integrating (posterior mean)?
Comment: This question is very broad and hard to answer in general. But I think an answer for why one might prefer the MLE even though sampling is needed for the MCEM algorithm is that you are still integrating over a *subset* of the parameters, and maximizing over the rest. Given that it is often (but not always) faster to maximize than to integrate, you may chose the MCEM algorithm for speed if it is expected that the posterior means will be close the MLE, as is typically the case.

Rationale for MCEM


array of pointers - how to store from one array of pointers to another

Question: #include<stdio.h>
int main(){
 char *p[2];
 char *q[2];
 char *a = "Hello";
 char *b = "world";
 p[0] = a;
 p[1] = b;
 *q = *p;
 printf("\n %s \n",q[0]);
 printf("\n %s \n",q[1]);
 return 0;
}

I wanted to store the pointers stored in the p to q. when tried to print q[1], i'm getting a junk value. But q[0] prints "Hello" correctly.
Answer: *q = *p is the same thing as q[0] = p[0]. That's why printing q[0] works but printing q[1] doesn't. If you want to copy all the pointers you'll need either a for loop or memcpy().
memcpy(q, p, sizeof(p))

Comment: `sizeof(p)` will return the size of `2`character pointers which will be `8`. If you wish to write both the strings to a file, you will have write them in a loop.
Comment: @Angus: Why would you want to write a *pointer* to a file? That's a serious mistake, because the pointer is meaningless to the file, and to future programs (including this program). Which book are you reading?
Comment: But I want to write the *p[2] into a file write(fd,p,size) is not possible;
Comment: @modifiablelvalue I understand my statement is specific to a particular platform where `sizeof` of a character pointer is `4` which can't be guaranteed. I don't understand why you say my comment was wrong. Your point of `sizeof(char *)` being more than 4 is valid, but is very specific to certain systems.
Comment: @Ganesh: You don't even have to sit at a different computer, or a different OS to get different pointer sizes. In the past, `sizeof (char *)` has also been two, and can quite easily be all over again if you download one of those old compilers. At the current point in time, most 64-bit implementations will use 64-bit pointers. A 32-bit implementation will also run on 64-bit hardware. In which day and age are you programming where `sizeof (char *)` isn't more commonly 8?
Comment: @modifiablelvalue well i work on ARM which powers most of the latest handhelds and I have seen `sizeof(char *)` to be `4`. In my limited view, `64-bit` implementations are not very common and `32-bit` continues to be the norm. Even on my PC, where I am running MinGW,`gcc 4.6.2` whose default mode is `32-bit`. I feel unless someone is explicitly programming for `64-bit`, I feel the more commonly used mode is `32-bit`. Maybe my view of the world is limited :-)
Comment: @Ganesh Write programs to work today and in [the future](http://www.arm.com/about/newsroom/arm-launches-cortex-a50-series-the-worlds-most-energy-efficient-64-bit-processors.php), not just today, and you'll enjoy the benefit of not having to painfully adapt fidgety code in the future. I would suggest that your view of the world is out-dated. 64-bit implementations are all I have worked with on PCs for the last two years, and I have spent enough time ensuring programs are built to take full advantage of the hardware it runs on to be certain of this.
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/26683/discussion-between-ganesh-and-modifiable-lvalue)
Comment: @Ganesh I have a better idea... If the resource I mentioned earlier along side [this resource](http://clc-wiki.net/wiki/C_community:comp.lang.c:Portability_attitude) doesn't convince you to change your ways, then perhaps you could continue this discussion with comp.lang.c or ##C on freenode.
Comment: @modifiablelvalue thanks.. My ways are decided based on the real world as seen by my eyes. If required, I will take it up with comp.lang.c. While you ask other to mend their ways, probably you can also try to look at the world from a different perspective. Who knows you might see an entirely new picture
Answer: The problem here like Kevin mentioned is that what you have is an array of pointers... so in order to accomplish what you want you need to memcpy the pointers over into the other array. This is because (these are example values mind you :)
p[0] = 0xaaa
p[1] = 0xbbb

*q == 0xaaa

so
q[0] = 0xaaa

q[1] is junk
So you are not copying the array, only a single value :)
Hope this helps!
Answer: I understand what you want to do. You think you use " *q = *p; " to assign all pointers in p to q. But did you know that just assign p[0] to q[0], p and q are not pointers. They are just a array, you can't use this syntax to copy a whole array to another, but you can use memcpy or assign its elements one by one.
Answer: If I understand what you're trying to accomplish correctly, declare q as a double pointer **q, and assign it like this: q = p.


P(a < X < b) < 1 for any a,b ∈ R with a < b.

Question: I am having the following question in an assignment:
"Let X be a random variable. Assume that the cumulative distribution function FX is continuous and strictly increasing on R.
Show that P(a < X < b) < 1 for any a,b ∈ R with a < b"
I am confused because I know that if X is continuous the following holds:
P(a < X < b)= P(a ≤ X < b)= P(a < X ≤ B)= P(a ≤ X ≤ b). I am helpful for tips on how to think about this and solve it.
Comment: Suppose there were some $a$ and $b$, $ab,$ so it isn't strictly increasing.
Answer: The approach given in the comment by @RideTheWavelet works. That is to prove  this by contradiction. If the probability between $a$ and $b$ is  equal  to 1, then the cumulative distribution function will be flat (height = 1) from that point $b$ onwards, contradicting/violating the condition that it is strictly increasing.
Let's take this question to understand behaviors of cumulative distribution functions (CDF's) in a bit more generality.
For a discrete random variable (which takes on point masses on finite or countably infinite points), the CDF has to have jump discontinuities. Further, in that case, the CDF cannot be strictly increasing.
For a continuous random variable, the CDF strictly increasing implies a few things. First, from the gist of the present question, a strictly increasing CDF must have 1 as a horizontal asymptote (as $x \rightarrow \infty $ CDF $\rightarrow 1$). Similarly as  $x \rightarrow -\infty $ CDF $\rightarrow 0$. For the corresponding probability density function (PDF), it means that it has to be strictly above the $x$-axis. That is, if the CDF is strictly increasing, the corresponding PDF must have $f(x) > 0$ for all $x$.


Rsync : execute permission required

Question: I'm using rsync between two servers to transfer files.
The problem is some files are not transferred.
I get this error : rsync: readlink "/var/www/index.html" failed: Permission denied (13)
So I check permissions on the server and after make tests, I notice a file is transferred only if it has these permissions : R-W !
If the file have these permissions : R--, Rsync can't download it !?
Command:
/usr/bin/rsync -avzr -e "/usr/bin/ssh -i /home/replication/thishost-rsync-key" firstname.lastname@example.com:/var/www/index.html ./

Is it a bug with Rsync ? I find any information about this problem.
Thanks for your help
Debian Etch 2.6.30
Rsync 2.6.9 protocol version 29
Comment: whats the output of
ls -al /var/www/index.html
Answer: rsync needs to be able to read the files you are trying to copy, so my guess is that the user running rsync does not have read permission on the file in question.
If that's the case, you can either grant read access on the file to that user, or use a different account that already has read access on all the files you are trying to copy.
If that's not the problem, please post the output of ls -l /var/www/index.html
Answer: To verify it's a permission thing as rsync tells, try:
ssh firstname.lastname@example.com "ls -al /var/www/index.html"
or
ssh email@example.com "ls -al /var/www/"

Take a look if some files that do not get transferred are symlinks that point outside the tree; if so, take a look at the --safe-links or --copy-links arguments.
Either change the permissions or change the user.
You could give more "verbosity" to rsync like with rsync -avvv [...] to see even more error messages.
The "r" parameter is not needed as "a" defaults to "-rlptgoD". And as you copy recursively, leave out the "index.html", just write "/var/www/" with the trailing slash.

Rsync : execute permission required


Como criar um botão na API do google maps para adicionar marcador?

Question: A dúvida é a seguinte...
Dei uma pesquisada por uns dias antes de vir aqui, mas só acho como adicionar o marcador de forma manual igual ao exemplo do google:
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(-34, 151);
Map.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));

Map.moveCamera(CameraUpdateFactory.newLatLng(Sydney));

mas gostaria de criar um botão na API do maps, que quando clicado adiciona o marcador na minha posição atual, e caso eu mude de lugar e clique novamente nesse botão adiciona outro marcador e assim por diante.
Answer: Basicamente, o que você quer então é como obter sua localização atual e mantê-la sempre atualiza, já que a forma de adicionar o marcador você já tem, certo?
A recomendação é utilizar o FusedLocationProviderApi, do Google Play Service. Então o primeiro passo é adicioná-lo ao seu arquivo build.gradle, caso ainda não tenha nas dependências do seu projeto:
compile 'com.google.android.gms:play-services:8.4.0'

Em sua Activity, precisamos iniciar o GoogleApiClient e ficar "escutando" as atualizações de localização do usuário. Primeiro, implemente o seguinte:
public class MapaActivity extends AppCompatActivity implements
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        LocationListener {

Declare o objeto nas propriedades de sua Activity:
protected GoogleApiClient mGoogleApiClient;

E este método abaixo você pode iniciá-lo no onCreate:
private void startTracking() {
    if (GooglePlayServicesUtil.isGooglePlayServicesAvailable(this) == ConnectionResult.SUCCESS) {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();

        if (!mGoogleApiClient.isConnected() || !mGoogleApiClient.isConnecting())
            mGoogleApiClient.connect();
    } else {
        Log.e(TAG, "Unable to connect to Google Play Services.");
    }
}

Aqui você está iniciando o GoogleApiClient, e com o sucesso, aí sim você solicita a atualização das coordenadas do usuário. Abaixo os métodos que precisam ser implementados de acordo com as interfaces que incluímos na assinatura da Activity:
@Override
public void onConnected(Bundle bundle) {
    LocationRequest mLocationRequest = LocationRequest.create();
    mLocationRequest.setInterval(10000);
    mLocationRequest.setFastestInterval(5000);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}

@Override
public void onConnectionSuspended(int i) {
    mGoogleApiClient.connect();
}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
    stopLocationUpdates();
}

Aqui quando a latitude e longitude do usuário é obtida, você pode guardá-la para utilizar quando o botão de adicionar marcador for acionado.
@Override
public void onLocationChanged(Location location) {
    if (location != null) {
        // Localização atual obtida
    }
}

Esse método você aciona quando finalizar a Activity, para encerrar o processo de atualização da localização e desconectar o client.
private void stopLocationUpdates() {
    if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
        mGoogleApiClient.disconnect();
    }
}

Nesta implementação, enquanto sua Activity estiver ativa, a localização sempre será requisitada de acordo com o intervalo definido. Outra opção é você somente solicitar a localização atual quando o botão for acionado, chamando o requestLocationUpdates e parando logo quando for obtida.
Basta você definir qual das duas opção se encaixa melhor de implementar da melhor forma. Um exemplo mais completo você pode ver aqui, do próprio Google.
Comment: Creio que minha pergunta não ficou muito clara, o que tenho duvida é em como criar um botão que toda vez seja clicado adicione um marcador na sua posição atual
Comment: Ficou claro sim, mas isso envolve todo esse processo de buscar a localização, que como você não mencionou, imagino que também faça parte da sua dúvida. Enfim, o botão propriamente dito, nada mais é do que implementar o método `setOnClickListener` e assim executar o processo do início. Ou através do `android:onClick` do seu layout. O que mais além disso?
Comment: Bom, fiz o botão dessa forma

`public void adicionarMarker(View view) {

        mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {

            @Override
            public void onMyLocationChange(Location location) {
                LatLng posicao = new LatLng(location.getLatitude(), location.getLongitude());
                MarkerOptions options = new MarkerOptions();
                options.position(posicao);
                marker = mMap.addMarker(options);
            }
        });
    }`

porem ele não ta encerrando, criar um marcador sem eu clicar nele


What do the letters above the piano staff represent?

Question: I am a beginner trying to understand the music notation for a song I want to try. Can someone kindly tell me what are the letters above the treble clef in the following figure:

I've read that they represent the triads but I am not sure how, for example there is an F written on top of the A note, etc. Any help would be really appreciated.
Thanks
Comment: Those are chord symbols. Look up http://en.wikipedia.org/wiki/Chord_names_and_symbols_%28popular_music%29 and read the first section.
Answer: The letters above mean the implied/intended harmony. There are 2 possibilities I see here as to why an F and C7 are listed.
If you are playing solo
There are certain common chord progressions in music.  The go-to example always seems to be I-V-I, and what this means is that the chords move from the first/tonic chord of the scale(in this case F, to the fifth/dominant chord of the scale (in this case C or C7) then back to The First.
You'll notice that there's no C present in the C7 either, but it does have other notes of the C7 chord.  This is an example of an implied harmony, because the function of the chord is to be a dominant so it can lead back to the root in the next chord(the F in the bass).
It's much more common to think of a chord progression as V - I - V (as it is in the first bar here) than it is to say V-iii-ii(as it would be if we take the bass to be the root notes) so what the transcriber has done is to write the V-I-V chords instead of the V-iii-ii chords(which would be C Am Gm).  As you can see, C Am G has a different harmony and feel to C F C7, but C F C7(or V I V) is the intended harmony underneath.
If you are playing as part of a group
the chords listed here are what the overall chord progression will be when everybody is playing. A C consists of CEG. An F major consists of FAC, and C7 is CEGBb.  While you are playing the A, another part will perhaps be playing F or C, or both!
Thanks for that.  When I first looked I thought it seemed simple, but there are a number of added little complexities in there that can throw you, for example you're not beginning on the root.  If anything is unclear let me know in the comments and I'll update :)
Answer: Mainly they have been written in for guitarists. The R.H. and L.H. for the piano player are there in place, so the tune will sound good as is. However, as Alexander  points out, there are often more notes available for each part of a tune, as in a C7 is made from C-E-G-Bb, but not all of them are used by the composer all the time. Guitarists sometimes (often!) strum full chords to accompany songs. The letters above tell them the appropriate chords to play.


Infinitely many primes that are the sum of a power of 2 and a perfect square

Question: Are there infinitely many primes $p$, for which there exist positive integers $m$ and $n$, such that
$2^m+n^2=p$?
Answer: Not an answer, but my link didn't work in a comment :(
Have you considered the easier question of whether or not there are infinitely many primes of the form $2+n^2$? Note that $$2+1^2=3, 2+3^2=11, 2+9^2=83,2+15^2=227, 21^2+2=443,33^2+2=1091,39^2+2=1523,45^2+2=2027,57^2+2=3251,81^2+2=6563$$ are primes, I can imagine there are infinitely many of those already.
Typically these are open problems. I refer you to this question and it's answer for more on that.
Comment: Also, if you fix n=1, then it becomes the Fermat conjecture about primes of the form 2^q+1
Comment: Well, Fermat conjectured that all number of the form 2^(2^t)+1 are primes which was proven wrong but the question if there are infinite primes is still open.
Comment: @ypercubeᵀᴹ : You're absolutely right! (how did I miss that - facepalm -) Goes to show how ridiculously easy it is to ponder these type of questions and run into open problems! I guess one could also wonder whether there are infinitely many primes $p$ such that $p!-1$ (or $p!+1$) is also prime. I bet that's an open problem too.


How to use Google Cloud Run as a singleton application service?

Question: I want to use gcp cloud run as a background service with CPU always allocated with a minimum and maximum of 1 instance running at any given time.
The problem is when I deploy a new revision, the old revision continues to run for some time until it is eventually terminated by cloud run. This time is not configurable. During this period there are 2 revisions running my background service which is what I want to avoid due to my application limitations. I want the old revision to be terminated automatically as soon as the new container is deployed and in the ready stage.
I found that manually deleting the old revision will quickly terminate the container. I could update my deploy script to delete the old revision. But this is undesirable because I cannot revert to the old revision in case of a bug.
Is there a way to tell cloud run to automatically terminate an old revision as soon as the new revision is ready?
Answer: Running a service as a singleton is not a good pattern because you can have disruption at any time. Remember that Cloud Run is a serverless service and the platform can stop and restart your container at any time (underlying infrastructure outage, maintenance, relocation,...)
If you run something in background of Cloud Run service, like a scheduler or something like that, you can understand that it's not safe and reliable.
I think your issue come from there: If you have 2 versions running in the same time (on 2 difference instances), you could trigger 2 times the same schedule and duplicate your jobs.
Because Cloud Run is serverless, you don't have the capacity to manage the instance lifecycle. I can only help you to understand the Cloud Run behavior and optimize your design to fit the constraints and your requirements!
Comment: Websockets are not great for backend updates I'm realizing. The service I am listening to has a webhook version of this same data which would work better with the serverless quality of cloud run. I will look into that. Thanks for the help.
Comment: My service is indeed a sort of scheduler that listens to events coming in from an external source on a websocket and queues them to process. It is safe to duplicate tasks occasionally and also tolerates restarts at any time. Because GCP doesn't have a FIFO queue managed service, I have to manually develop this pattern in my application. If I did use Task Queues and find another way to order jobs than an in memory queue, I still need a background process that listens to the websocket and enqueues jobs which brings me back to the original problem of a singleton cloud run service.
Comment: Why do you need a single one websocket to listen the event? You could have several instance in parallel with the websocket deployed on them. The client will be connected to one of them. Why the singleton in that case? But you still have your issue: the connected user on the websocket will continue to communicate with the previous instance when you deploy a new revision. You can do nothing for that., maybe to limit the request time out, to for the client to reconnect more frequently and mitigate the duration with a new revision is deployed.


How to make views slideshow, shows more items per page than one

Question: I made a slideshow using views slideshow in drupal 7 to show bunch of logos, but it only shows one item per page, what I want is to show for example 6 logos per page when the visitor hit next, it slides to next 6 items and etc.. I checked views slideshow field setting, but couldnt find anywhere that I can set how many items to show per page.
thanks.
Answer: In Views Slideshow 7.x-3.0, you can find this option by selecting slideshow as your format and then clicking on settings. From there, you need to find the Action section and check "View Action Advanced Options", there you can choose how many items to display.
Comment: The "Items per slide" option has been removed from Views Slideshow 7.x-3.1.
Comment: in drupal 8 with slideshow module it is possible to show multiple items in option described above but is there a setting to show 4 items and slide only by one? Lets say i have 10 items and i want to show 4 at the beginning and slide by 1 item (node). If we show 4 items per slide it will slide by 4 items... that is a problem for me. could use any help.
Answer: From your explanation, you would require a module called jCarousal. It has built-in views support too. You can configure its settings change the number of items to show per page.
Comment: thanks, I actually found an option in slideshow itself which allows me to do this.
Comment: Where did you find that option? I know where it is in views slideshow 2.x, but I can't find it in 3.x


Live template shortcut for == intellij?

Question: My plain question is, whether by default is there a live template which can be used for == in intellij?
If yes, what?
Comment: What exactly do you want to achieve? Type something else to get `==`? Or press a key combo to insert it?
Comment: @Koyasha yes, i want to know whether its possible to use a '.' based operation (ex. myObject.E and press Enter upon suggestion, hope you get what i mean ) which would generate == for me, so that I don't need to manually type a space and two equal signs and another space.
Answer: There is no default postfix template for it, but you can add a custom one in the File | Settings | Editor | General | Postfix Completion dialog.
You can also type myObject==<value> and hit Ctrl+Alt+L right after that to auto-fix the format of your code, which means spaces will be added automatically to make it myObject == <value>. It'll save you extra trouble.

Live template shortcut for == intellij?


Which DB type (relational / NoSQL and which type) to choose for a complex case

Question: For one of our SaaS services we're investigating which DB to use as we're re-designing it from scratch.
Our current solution uses MySQL and creates a seperate DB for each new customer. The current (global) structure is:
- globaldb.globaltable
    => some global data shared with all customers
    => big
    => it would be an option to flatten this data in the customerdb.tablewithreportlines, but this increases the size quite a bit

- customerdb.tablewithstaticdata
    => joins with `globaltable`
    => searched on several columns
    => no group by
    => writes throughout the day, in the thousands
    => reads on request by the customer via the application, so not continuesly
    => can be big per customer, serveral GBs

- customerdb.tablewithreports
    => searched on several columns
    => writes throughout the day, but only in the tens
    => reads on request by the customer via the application, so not continuesly
    => quite small

- customerdb.tablewithreportlines
    => joins with `tablewithreports`
    => joins with `globaltable`
    => most columns are 'searchable'
    => most columns are 'groupable'
    => writes throughout the day, in the thousands but only when processing the `tablewithreports` lines
    => reads on request by the customer via the application, so not continuesly
    => can be big per customer, serveral GBs

The customerdb data is never UPDATEd, but only INSERTed (and DELETEd occasionally).
We are preparing for rapid growth and need a structure which is ready for this. It is acceptable to have new instances (if needed) added manually.
We've earlier had a MySQL setup with a very large amount of tables (and databases) for a test project. That project failed as the server was exceeding its maximum file handlers for the MySQL tables. This was at around +-500.000 tables. This new project will definately need to be able to handle 500.000 customers and therefore 1.5 million tables (with this current structure).
The average size per customer database is +- 7,5Mb. No to much, but it is quite spreaded as serveral customers have multiple GBs in their DB.
I've searched SO and Google to find a matching situation, but weren't able to find it.
At this point we're open to any suggestion, both relational, NoSQL or a combination as we're doing a full re-design.
Question what is the best suited database for this use-case?
PS: this is my first post so forgive my I'm incomplete
Answer: I would suggest to consider using a common database for all the customers. This radically reduces the number of tables.
Database management systems were not designed for this large about of databases or tables.
Usually a table is one entity representing a collection of the objects of the same kind. So all the objects of the same kind (like customers in your case) should be placed in one table rather having a separate table for every customer.


(JavaScript) Find the Area of a Circle From User Input Box

Question: Alright, so I am trying to figure out what I am doing wrong here and would love for someone to help me in the right direction.
I will have all the code below. As well as on CodePen if that helps here
I am looking to make a simple HTML page, where:

Function finds the area of a circle
The formula should be π (pi) r squared, right? or is it Math.PI?
Use π as the constant
The user will enter their first name in a textbox
The user will enter the radius from the second textbox
Calculate the area of a circle.
Concatenate the user's first name, a message, and the area of the circle and output all of that into the document.
Thank you so much for anyone who can help me with this, I have been stuck on this all day, and could use some help. Even if not the answer, just someone who could point me in the right direction, or what I am doing wrong? Thank you all.

function changeText() {
             var firstName = document.getElementById("fNameBox").value;
             var message = ", The area of your circle \"is\"";
             const radius1 = circleRadius + " " + Math.PI;
             var result = firstName.toUpperCase() + message + radius1;
        document.getElementById("message").innerHTML = (result);
      }

      function clearText() {
        document.getElementById("message").innerHTML = "
";
        document.getElementById("fNameBox").value = "";
        document.getElementById("wageBox").value = "";
      }
body {
        background-color: antiquewhite;
        font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
        text-align: center;
      }

      h1,
      h2,
      h3,
      h4,
      h5,
      h6 {
        text-decoration: underline;
      }

      span {
        margin-top: 0.5em;
        margin-bottom: 0.5em;
        font-style: italic;
      }

    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Program 4</title>

Program 4

        An Expression using a Constant

      <form id="myForm">
        First Name: <input type="text" id="fNameBox" />

        Radius (Of Circle): <input type="text" id="circleRadius" />

Output:

      </form>

      <button type="button" onClick="changeText()">Submit</button>
      <button type="button" onClick="clearText()">Clear</button>

Comment: You could get the area of a circle like so `Math.PI * circleRadius.value ** 2`.
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Comment: I cannot find where to mark it as the answer sorry I am here for an issue deploying my React web app portfolio and it will not deploy or even work locally now.
Answer: You need to get the radius input value first because the radiusOutput  variable you were trying to use is undefined. Also, you need to use parseInt() to convert input value of type String to type Number.
const radius1 = parseInt(document.getElementById("circleRadius").value) * Math.PI;

Also, I recommend using <input type="number" for radius instead of text.

function changeText() {
             var firstName = document.getElementById("fNameBox").value;
             var message = ", The area of your circle is: ";
             const radius1 = parseInt(document.getElementById("circleRadius").value) * Math.PI;
             var result = firstName.toUpperCase() + message + radius1;
        document.getElementById("message").innerHTML = (result);
      }

      function clearText() {
        document.getElementById("message").innerHTML = "
";
        document.getElementById("fNameBox").value = "";
        document.getElementById("wageBox").value = "";
      }
body {
        background-color: antiquewhite;
        font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
        text-align: center;
      }

      h1,
      h2,
      h3,
      h4,
      h5,
      h6 {
        text-decoration: underline;
      }

      span {
        margin-top: 0.5em;
        margin-bottom: 0.5em;
        font-style: italic;
      }

    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Program 4</title>

Program 4

        An Expression using a Constant

      <form id="myForm">
        First Name: <input type="text" id="fNameBox" />

        Radius (Of Circle): <input type="number" id="circleRadius" />

Output:

      </form>

      <button type="button" onClick="changeText()">Submit</button>
      <button type="button" onClick="clearText()">Clear</button>

Comment: Wow! Thank you so much! I even fixed it before this and was editing the code snippet where I was getting the radius. However, it kept saying HTML Object, etc. so forth, so I was still banging my head against the keyboard and about to start smoking cigarettes or walking around clearing my head of this simple stuff I know I know, it's been so long inside Kali Linux doing my OSCP, returning to this I got rusty, but thank you, good sir (or ma'am)!!!!!
This is the answer. Should I close it now? Or leave it up? How can I thank you, buy you a coffee or something?
Comment: No worries, please just upvote the answer and mark it as accepted if it helped, cheers!


Mathematica - Using Manipulate[] with physical units

Question: I'm a new user, and am trying to build a simple Boyle's law system in Mathematica. I want to include the units of the values, as I may need to perform some conversions later. If my quantities are a discrete list, they work fine. I cannot seem to get it to work for a slider.
I've searched for a while before posting this question. Here's my code:
    Manipulate[
     Text@Style[
       Grid[{
         {Row[{"Total fill volume is ", totalVolume}]},
         {Row[{"Delivery rate is ", deliveryRate}]},
         {Row[{"Product duration is ",
            duration[totalVolume, deliveryRate]}]},
         {Row[{}]},
         {Row[{"Initial pressure is ", initialPressureG}]},
         {Row[{"Drop in pressure is ", pressureDrop, "%"}]}
         }, Alignment -> Left]
       ]
     ,
     {{totalVolume, Quantity[30, "ml"], "Total fill volume"},
      Quantity[{30, 45, 60, 90}, "ml"]},
     {{deliveryRate, Quantity[1, "ml/day"], "Delivery rate"},
      Quantity[{0.5, 1, 2, 3}, "ml/day"]},
     {initialPressureG, 0, 100},
     {{pressureDrop, 40, "Pressure drop"}, 0, 100, 5}
     ]

Instead of initialPressureG being a slider from 0 to 100, I want it to be a slider from 0psi to 100psi. Am I doing something stupidly wrong?
Comment: Head over to http://mathematica.stackexchange.com with your question, you're likely to get a better class of answer there.
Answer: One possible solution is to keep the slider values purely numeric make the transformation to a full quantity separately. Example:
Manipulate[DynamicModule[{valueWithQuantity = Quantity[value, "A"]},
  valueWithQuantity],
  {value, 0, 100}
]

This approach can be used in your code too
Manipulate[
 DynamicModule[{pressureDrop = Quantity[pD, "psi"]},
  Text@Style[
    Grid[{{Row[{"Total fill volume is ",
         totalVolume}]}, {Row[{"Delivery rate is ",
         deliveryRate}]}, {Row[{"Product duration is ",
         duration[totalVolume,
          deliveryRate]}]}, {Row[{}]}, {Row[{"Initial pressure is ",
         initialPressureG}]}, {Row[{"Drop in pressure is ",
         pressureDrop, "%"}]}}, Alignment -> Left]]
  ], {{totalVolume, Quantity[30, "ml"], "Total fill volume"},
  Quantity[{30, 45, 60, 90}, "ml"]}, {{deliveryRate,
   Quantity[1, "ml/day"], "Delivery rate"},
  Quantity[{0.5, 1, 2, 3}, "ml/day"]},
 {initialPressureG, 0, 100},
 {{pD, 40, "Pressure Drop"}, 0, 100, 5}
 ]

and you get what you expected.


How to factor $n^4 + 2n^3 + n^2 -2n^2c -2nc +c^2$

Question: Since I need to prove that this is square of natural number I tried to transfrom it into combinations of square of binomials,especially $2nc$ and $2n^2c$ with $n^4$ and $n^2$ have caught my eyes ,but I couldn't make it work.
I tried Bézout's identity to find n,c which $P(n)$ or $P(c)$  is zero but it wasnt straightforward.
Can you guys help me out.I am trying to improve my skills of factoring polynomials but sometimes I got stuck I dont know what to do.
I dont want to see only solution but what is going inside your head,how do you reason.what are the steps with which you approach the problem and what made you think towards the way that led to solution.
Comment: To clarify, what is it that you actually want to do? Do you want to show that the expression can never be a square (which could allow for difference approaches), or do you want to just factorize it?
Comment: Sure.Thank you for reply.I need to prove that this expression is square of natural number,c is also natural number
Comment: I also need to appologize.I made small mistake in expression that is now fixed in edit(2n^c instead of 2(n^2)c )
Comment: Hint: what are the perfect squares, and what are the doubled cross terms? And now see which combinations of signs will work.
Answer: HINT: Expand out $[n(n+1)-c]^2$. In particular, note that simple algebra gives $[n(n+1)-c]^2=n^4+2n^3+n^2-2n^2c -2nc +c^2$, so as the LHS is always the square of an integer if $n$ and $c$ are both integers, so must be the RHS $n^4+2n^3+n^2-2n^2c-2nc +c^2$.
ETA: As far as what led me to this, I did first note that $n^4+2n^3+n^2$ is $n^2(n+1)^2$, and so I figured that if the given polynomial $n^4+2n^3+n^2-2n^2c -2nc +c^2$ were square, the resulting square had to be "close to" $n^2(n+1)^2$ and perhaps the square of $n(n+1)$ "minus something" in $c$,  due to some minus signs in the polynomial, and that led me to the solution. I had also plugged in $c=1$ and $c=2$ and tried factoring both of the resulting polynomials to guide the way and see if there was a pattern. Then from there I tried $[n(n+1)-c]^2$ as my first guess. There is a certain amount of trial and error involved.
Comment: You can do it without trial and error by equating the coefficients, but it sometimes may be faster to do trial and error if one has experience with factoring polynomials.
Comment: Thanks I think I learned more from your explaining of how did you attack the problem than just solution.
Comment: @GreyCow thankyou, I am glad you found what I wrote helpful.
Answer: You are looking to get something in the form $(an^2+bn+d)^2$. (I can't use the variable $c$ as that is taken). Expanding that gives:
$$(an^2+bn+d)^2=(a^2)n^4+(2ab)n^3+(2ad+b^2)n^2+(2bd)n+(d^2)$$
Now it is a matter of equating the coefficients.
$$(a^2)n^4+(2ab)n^3+(2ad+b^2)n^2+(2bd)n+(d^2)=(1)n^4 + (2)n^3 + (1-2c)n^2 +(-2c)n+(c^2)$$
From this, we get that $$a^2=1\Rightarrow a=1$$
Note that I'm taking the $+1$ root just to find one answer. You'll get another answer if you take the negative root.
$2ab=2$, where $a=1$, so $2(1)b=2$ so $b=1$. To continue this process for the $n^2$ term, $2ad+b^2=1-2c$ where $a=1$ and $b=1$. This means that $2(1)d+(1)^2=1-2c$. Therefore, $d=-c$. For the linear coefficient, our values of $b$ and $d$ remain consistent. For the constant coefficient, note that the value we found is still consistent meaning we have no contradictions. Therefore, the values we found are correct!
So, $$[an^2+bn+d]^2=[(1)n^2+(1)n+-c]^2$$
$$\fbox{
    \(
(n^2+n-c)^2=(1)n^4 + (2)n^3 + (1-2c)n^2 +(-2c)n+(c^2)    \)
}$$

Since your polynomial can be expressed as a square, where the $n^2+n-c$ is always going to be an integer (for integer values of $n$ and $c$), you know that the polynomial is a square of that quadratic (which is always going to be an integer).
Comment: Thank you it helped enormoulsy,I don't really understand what are you talking about near the end of your answer :  " For the linear coefficient, our values of b
 and d
 remain consistent. For the constant coefficient, note that the value we found is still consistent meaning we have no contradictions. Therefore, the values we found are correct!"
Comment: I just meant that we had already found all the variables we needed to find, namely $a$, $b$, and $d$. Linear coefficient by the way just means the coefficient of $n$. Constant coefficient means the constant term. What I meant to describe was that if you continued with this process of equating coefficients, you wouldn't find any contradictions. It would be weird if you already got $2bd=-2c$ (for $n$ coefficient), but it didn't align with your already set definitions for $b$ and $d$. Here though, since $b=1$ and $d=-c$, the equation still works.
Comment: I get it now.Thank you very much.I learned a lot.My mind will be occupied with finding scenarios when it is possible to use method of equating coefficients to factor and when there is no solution.Thank you again,intresting method.


Can I use a Hazard Ratio to determine the absolute risk of a population?

Question: I am trying to convert the Hazard Ratio from this paper (Risk of Gastrointestinal Adverse Events Associated With Glucagon-Like Peptide-1 Receptor Agonists for Weight Loss) to determine the prevalence of gastroparesis in a given population.
The absolute risk of an individual developing gastroparesis is 50 per 100,000 individuals in the US according to the National Institute of Diabetes and Digestive Kidney Diseases.
The adjusted HR from the paper is 3.67 which indicates that an individual is 3.67x more likely to contract gastroparesis relative to bupropion-naltrexone which is not a GLP-1 agonist.
Is it reasonable to multiply 50 (absolute risk) by 3.67 and apply that to a population? So for 100,000 individuals using semgalutide we would expect 183.5 to be diagnosed with gastroparesis?
Comment: No, the risk and hazard are completely different measures.
Comment: @pzivich they are different measures, but not unrelated.
Answer: Hazard and risk are not directly related.
An extreme example, consider the risk of dying before 130 years old, and the hazard of dying due to smoking. If you smoke then you experience a higher hazard to die, but the risk of dying is eventually the same 100% for anybody.
The risk is an integral of the hazard $h(t)$
$$\text{Risk dying before time $t$} = P(T<t) = 1-e^{-\int_0^t h(t) dt } $$
See also this waiting time problem: What distribution to use to model time before a train arrives?

Approximation
If the risk is small, then we can use a Taylor series expansion like $e^x \approx 1-x$, and you get
$$\text{Risk dying}  \approx \int_0^t h(t) dt $$
and hazard ratio's transfer (approximately) to risk ratio's.

Your further computations with risk may work if not too many people are using using semgalutide. The risk of 50 per 100000 is probably for both users and non-users. Only if the users groups is very small, then you can use the 50 per 100000 of the entire population as estimate for the non-users population.
Otherwise you need to incorporate the relative fraction of users and non-users into the computation. A related question to this is How to account for the difference between the sexes in a mortality rate
Answer: The attempt is incorrect. Intuitively, if the prevalence were not 50/100,000 but 50%, it would exceed 100% if we multiply it by the hazard ratio 3.67.
The prevalence P is (# cases) / (# population) which does not have a time scope (i.e. age) in it and comes from a cross section. However, studies with hazard ratio model event occurrence with time, h(t) = f(t)/S(t), where f(t) is the derivative of event probability F(t) = Pr{event happens before t} at time t and S(t) = 1 - F(t) is the survival probability at time t. It must come from longitudinal data. Without reference to time t, the model does not stand. The probability or proportion that can be directly derived from a hazard ratio (HR) is a stochastic superiority: HR = Pr{S(t, X1) < S(t, X0)} / Pr{S(t, X1) >= S(t, X0)}. See https://en.wikipedia.org/wiki/Hazard_ratio#The_hazard_ratio_and_survival.
I would say that P is related to F(t), but I can find no source of mathematical expression relating these two, so I derive on my in own in the following. Comments and corrections are welcome. Assuming that the survival study has external validity so that it can be applied to the entire population, I believe that P = mean F(t) over t where t is age as distributed in the population, that is, event probability by age weighted according to the population age distribution. For example, if we estimate F(t) = 1 - S(t) = t/100 from the sample, so that the probability of event is 1% by age 1 and 99% by age 99. If we also find that age is uniformly distributed [0, 100] in the population (note that this information does not necessarily come from the study sample, and the age distribution in the study sample can be different from that in the population), then prevalence in the population cross section must be 50%. Therefore, to relate hazard ratio (or any survival analysis quantity) to prevalence, we must know the distribution of t (often the age) in a cross section so we can integrate it out.


Generate node edit link

Question: I'm attempting to dynamically generate a node edit link. I understand that I can manually create it by using
$editpath = '/node/'.$nid.'/edit';
but I have multiple sites that use subfolders like

/site1_subfolder/node/123/edit

and

/site2_subfolder/node/123/edit

I looked at the node class and I couldn't see any method that would generate this link for me. I did see that there's a NodeForm class but I didn't see any static methods I could take advantage of either.
Given a node or node id is there a way to generate an admin edit link to its edit form?
NOTE: If that's not possible I would be fine with using a function to get the subfolder names so I could do $editpath = '/'.$subfolder_name.'/node/'.$nid.'/edit';
But I'm not sure how to do that either.
UPDATE: I suppose I could do a $node->toUrl()->toString() to get the direct path and add edit at the end but this would only give me the alias, is there a way to not get the alias from this and get the direct link to the node instead?
Answer:
Given a node or node id is there a way to generate an admin edit link to its edit form?

Absolutely, the Url class has a fromRoute method:
$url = Url::fromRoute('entity.node.edit_form', ['node' => $nid]);
$link = Link::fromTextAndUrl('edit', $url);
$build = [
  ...
  'link' => $link->toRenderable(),
];

Answer:
Given a node or node id is there a way to generate an admin edit link to its edit form?

If you have the $node itself, then you can you can use the toUrl() method to get one of the defined links:
$url = $node->toUrl('edit-form');
$link = Link::fromTextAndUrl('Title', $url);
$build = [
  //...
  'link' => $link->toRenderable(),
];

The various link names for the entity are on the annotation for the Node class:
/**
 * Defines the node entity class.
 *
 * @ContentEntityType(
 *   id = "node",
 *   ...
 *   links = {
 *     "canonical" = "/node/{node}",
 *     "delete-form" = "/node/{node}/delete",
 *     "delete-multiple-form" = "/admin/content/node/delete",
 *     "edit-form" = "/node/{node}/edit",
 *     "version-history" = "/node/{node}/revisions",
 *     "revision" = "/node/{node}/revisions/{node_revision}/view",
 *     "create" = "/node",
 *   }
 * )
 */

Generate node edit link


What can a domain controller do?

Question: In short: I do not know where to start reading so that I can understand how to configure a DC.
The long question:
In the environment I work, we use an outdated domain controller and I have to create a new one. The problem is that I can not yet grasp the idea of the Domain Controller. The one we use is actually used just for authenticating users (single domain, no one else in the forest, no other forest).
The theory I (think) know in short is:

An active directory is a database that stores information about computers and users.
A domain controller is a server that holds the active directory and maybe other services such as DNS.
A windows server can be a domain controller if it has active directory.
I can restrict users from using a printer for example.
I can change the settings for a given user account (let's say desktop background?)

What I can not grasp is generally the big picture, but specifically:

Why are there users and computers and not just users, what can I do with each of them.
If I restrict a user from using a printer, what is it that prevents him from actually using it if he can reach it (by ip for instance).
Why would I put different types of users in different containers, instead of just putting them in "Users" and then making them members of different groups that have different rights. Is it just an aesthetic matter, everything being tidy and sorted?
The biggest problem: I do not know what else it can do (please give me some example situations where it could help)

What I guess I expected was that there would be more to this wonder, the Domain Controller, than just authenticating users.
Any help on any of the above matters would be greatly appreciated.
Thanks in advance!
Comment: @1.618 not sure where you've heard this, but it's not true in any sense. The term `domain controller` is not obsolete and applies **only** to AD. Essentially, everything in your comment is the exact opposite of what it should say. You may benefit from reading the question that this was closed as a duplicate of.
Comment: Again, this is not true at all. Some examples here: http://blogs.technet.com/b/kevinholman/archive/2013/09/25/upgrading-domain-controllers-to-windows-server-2012-r2.aspx http://blogs.technet.com/b/askpfeplat/archive/2012/09/03/introducing-the-first-windows-server-2012-domain-controller.aspx http://blogs.technet.com/b/keithmayer/archive/2012/08/06/safely-cloning-an-active-directory-domain-controller-with-windows-server-2012-step-by-step-ws2012-hyperv-itpro-vmware.aspx#.UwkKU5K9KSM there are plenty of other examples as well. Wherever you heard this info was incorrect.
Comment: It is also all over the AD DS design guide, which was last updated for Server 2012 here - http://technet.microsoft.com/en-us/library/cc754678(v=ws.10).aspx
Comment: @MDMarra Ok, actually I confused my terms a little here, and I was thinking of "PDC".  In AD, there is no "PDC" and "BDC".  Not claiming that as fact, that's just my recollection.  I have deleted my original comment.
Comment: Correct, the terms and concepts of a PDC and BDC were deprecated when Windows 2000 Server was released. The term "domain controller" or "DC" is still correct and widely used.
Answer: To answer just a piece of your question, which is kind of broad:
Here are a few reasons why computers appear in AD as accounts.

Policies can apply to computers as well as users.
Computers need credentials, too, even if it's only to execute policies applied to computers ("install this software from this share").  You cannot access this password.  It changes regularly.  (I sometimes see it change in my monitoring software--a second of credential mismatch that shows up in the SQL error log--but that's the only way you'd know.)
It's just the way Kerberos works in AD.  You need account credentials, a trusted machine, and a proper timestamp or else you can't log in.  (Untrusted machines fall back to NTLM.)

Also, you generally group users and computers into OUs in order to apply policies to them.
Check out the question and answers in the "duplicate" link.  It's good stuff.

What can a domain controller do?


Apache Flume with Flat Files Source

Question: I have the source directory with many log files coming in and I want to use the Apache Flume to consume this log files and transfer the data to HDFS. I am just wondering how does the Flume knows, the already processed log files? is there any configuration?
Answer: The kind of data ingestion you talk about, i.e. consuming files as they are put in a directory, is achieved through the Spooling Directory Source. If you have a look on the documentation your will see that:

This source lets you ingest data by placing files to be ingested into a "spooling" directory on disk. This source will watch the specified directory for new files, and will parse events out of new files as they appear. The event parsing logic is pluggable. After a given file has been fully read into the channel, it is renamed to indicate completion (or optionally deleted).

Apache Flume with Flat Files Source


Azure static web app custom domain, how to solve "The custom domain has not been resolving to your static web app and has expired"

Question: Our sites are hosting with Adobe AEM.  We use Azure traffic manager to manage DNS switching, so we can switch to a site down holding page which we host on Azure Static Apps.
The static web app has a validated custom domain which is our main sites domain.
This has worked really well for about a year. Now we just switched to the site down in traffic manager, and got SSL errors with the static hosting.  We see our custom domains have this error next to them:
<code>The custom domain has not been resolving to your static web app and has expired.
</code>
Presumably the only solution is to delete the custom domains, re add and re validate them.
This is a real same, as using traffic manager and static web apps is the perfect site down solution except for this show stopper.
Answer: Have you ever found a solution?
Looks like there is a autorenewal in place...
To get it working I found a issue on github: https://github.com/Azure/static-web-apps/issues/888
haven't tested it yet (not even sure if this helps in my specific case) but looks promising...


One sample permutation test on skewed data

Question: I have one sample of values, each of them is a z-score from mutually independent z-scored distributions. I aimed at testing that the mean value of the sample is larger than zero. Originally I wanted to test it using one-sample permutation test, however, the z-scored distributions turn out to be skewed, so the sign flipping seems to be invalid. The distributions are skewed in a way, where most of the datapoints are negative but close to zero, while some of the data are positive with higher absolute value.
Which test is appropriate in this situation?
Comment: Thanks for comment, I just want to clarify that I am not performing a test on z-scored distribution, but rather on a sample, where each of the values is a z-score, but from different distributions.
Comment: But you still haven't said what you mean by z-scored. And what do you mean by 'different distributions'? Not sure how to make sense of a test on a dataset that is not a sample from a particular definable distribution, population, or process.
Comment: The z-scores were obtained by the formula you are mentioning (substracting mean and dividing by std). The different distributions correspond to different measurments, where within within each measurment some conditions were shuffled to obtain random distribution and observed value is z-scored in respect to that distribution, This has been done for multiple experiments/measurments  which rendered z-score values constituing the tested sample.
Comment: You give me limited choices how to try to help. Options are (a) I just pick a skewed sample with some negative values and try to illustrate a permutation test for $0$ mean. (b) You give me some data: along a row, commas separating values. (c) You give me an idea how to simulate data that might be enough like yours to be helpful. What is sample size?
Comment: Thank you, would be grateful even for (a). I am meanwhile thinking of how to describe nature of my data in simple and meaningful way. The sample size to perform the test on is 26 values.
Comment: Indeed, it seems that the main problem is that z-values come from different, even thought rather similar distributions, thank you for putting this forward. The only thing I know that mean value of each distribution is zero, but not sure if I can use it for any inference regarding the resulting sample. I dont know what to do.
Comment: To state it formally, let N be a natural number. Then we have N samples, each of them consisting of 1000 values. Lets z-score values within each sample. For each of the N samples there is also a value that we call an observation and is tranformed to z-score with respect to N-th sample distribution. We want to test that mean of observations is significantly higher than it would be if we were randomly taking one value from each of the N samples instead.
Comment: It is tempting to basically perform randomization test with randomly taking one value from each of the samples and calculating the mean, however, I want to ensure to test 'group effect' accounting for contribution by individual values, not just very few very large outliers.
Comment: See my answer using option (a). Seemed to have no difficulty with it.
Comment: Thank you! Originally was afraid to do sign flipping around mean permutations, as in the case of skewed distribution I had feeeling it does not nonparametrically model the null hypothesis. Or it is not a problem?
Comment: Regarding permutation tests, here are discussions about 'exchangeability', which you should read. It depends on what the null hypothesis really is. // Another approach is to transform data, something like $y = x^{1/5}$ to get rid of some skewness, then do a test for mean = 0; permutation or maybe even t if transformed data nearly normal. The _medians_ of orig'l and transformed data are the same, but not the means. // Because you have no idea what the actual population is, trying to test whether its mean is $0$ is going to be subject to some discussion.
Comment: Thank you. It turns out that in some variation of a problem I have integer values data, again with skewed distribution, most of the values equal to zero and few values positive integers. What variant of permutation can be used here, since the data are strongly asymetric with respect to both mean and median (median equals to zero, but more than half values are equal to zero).
Comment: Maybe a simple sign test would work. How many observations overall> how many negative? and how many positive? For example, if 1000 altogether, 30 negative and 10 positive, then one-sided test rejects $0$ as true location of median. In R, code`pbinom(10,40,.5)` returns P-value $ 0.001110717.$
Answer: Data. Here is a right skewed sample that has some negative values, but a sample average $A$ somewhat above $0.$
set.seed(1234)
n = 200;  x = rexp(n, .1) - 8
a.obs = mean(x); a.obs
[1] 2.045604
stripchart(x, pch="|")
abline(v = mean(x), col="greens")

Permutation test. Now we use the sample mean as metric, permute signs of
the $n = 200$ observations, and find the average a.perm of the
sign-permuted data. With $10\,000$ such values
we can get a good idea of the permutation distribution sample averages.
The null hypothesis that the mean is $0$
for the distribution from which x was randomly sampled
is rejected. The P-value of the test is about $0.0035 < .05 = 5\%.$
set.seed(326)
a.prm = replicate(10^4,
                   mean(sample(c(-1,1),n,rep=T)*x))
mean(abs(a.prm)>=abs(a.obs))
[1] 0.0035   # P-value of permutation test

hist(a.prm, prob=T, br=30, col="skyblue2", main="Permutation Dist'n")
 abline(v = c(a.obs,-a.obs), lwd=2, col="red", lty="dotted")


How is rock founded from blues if they have different scales?

Question: I heard that rock was created from blues. But most of the scales in rock are either major or minor. But blues scales are created from adding chromatic notes to a pentatonic scale.
Isn't rock more similar to say classical or pop music since they both share the same regular major/minor scales?
Comment: Which rock are you talking about? Is Led Zeppelin not rock? What about John Mayer? There is a lot of rock and pop music that is based on classical music (like Billy Joel or Yngvie Malmsteen), and a lot based on jazz (some Beatles, some of everything really) and a lot based on delta and/or Chicago blues (Zep, Stones). Rock and pop take influences from all over, including African, Asian, and Latin music. Any source claiming that rock is primarily based on blues and nothing else is wrong. But some bands are primarily blues influenced.
Comment: I saw that your question was downvoted, then I saw the excellent answer written by @topo morto. So since your question can inspire such a great answer I upvoted your question, because without that question we wouldn't have that great answer. I upvoted the answer also of course.
Comment: The Blues scale is created by adding ONE chromatic note to the pentatonic. That's all. Except that real Blues also incorporates a myriad of other notes 'in the cracks', which cannot really be called chromatic in its proper term. I think your question is based on a false premise. And Blues/Rock is a very wide spectrum of music.
Comment: @LarsPeterSchultz I think you're being a little too generous - but at least I managed to get some Zappa in there...
Comment: I think the confusion here is that you don't know the history of "rock" and all its variants.  Perhaps it is not true that Blues made Rock.  The term Rock and Roll (I think) was first applied to Elvis Presley's music.  That is heavily blues oriented (more like copied).  From that point the meme evolved, infecting numerous people all over the globe.  The Brits were inspired by it but eventually created their own modern music that quotes these blues classics but also injects new ideas.  To say that Opeth, or Zappa, or Yes, etc is "Rock" is to call out the trunk of the family tree.
Answer: 'Rock' is an umbrella term referring to an area of music containing many sub-genres that has been evolving for nearly 70 years now. Even at its birth, it evolved from multiple genres such as Country, Blues, and Boogie-Woogie piano music. As time has moved on it has taken in more and more influcences such as folk, classical, jazz... and ultimately, every other genre out there. Accordingly, it has incorporated harmonic pallettes from all those styles - and in some ways, found ways to fuse them together.

most of the scales in rock are either major or minor

First, a question - where does that assertion come from? is it your impression or does it come from a statistical analysis of a corpus of work?
Doubtless there is a lot of rock music that is based on major and minor scales. There's also an awful lot that is based around the blues scale - I bet if you asked 10 guitarists to play a 'rock riff', more than half would play something based around a blues scale. There are a lot of modal influences in rock too. (I've sometimes thought that there seems to be a kind of 'Rock scale' or 'rock key' that incorporates aspects of Major, blues, minor, and perhaps the Mixolydian mode.)
As an illustration of something that exhibits a kind of bluesy rock tonality, Have a listen to Joe's Garage. The first part is fairly straightforward major - then pay attention to what happens at about 4 minutes, when they're making it sound more 'rocky'. They're certainly not sticking to straightforward major - or minor - at that point.

blues scales are created from adding chromatic notes to a pentatonic scale.

It's not as simple as that. The archetypal blues sound is all about bending notes through ranges of pitch (which you can hear a little of in the Joe's Garage vocal). There are simplified versions of the blues scale which could be described in the way you have, but that wouldn't qualify as a full description of classic blues tonality.

Isn't rock more similar to say classical or pop music

Maybe - but only in that rock, pop, and classical are all huge, sprawling families of genres that have adopted many different influences over the years, and include examples using many different types of scale.
Comment: I'm not sure it's fair to use Zappa as an example, because he is so good at defying genres.
Answer: This is a style question, not really a theory question.
Let's skip the discussion about blues scale versus blue notes, blues harmony, and what is rock tonality.
The question is...

...how is rock founded from blues

The easiest, most direct answer I can think of is: Joe Turner and Bib Mama Thornton.
Joe Tuner

Shake, Rattle, and Roll

Big Mama Thornton

Hound Dog

The Rock & Roll versions are:

Bill Haley
Elvis Presley

Initially rock was just blues (performed by whites) with a different performance style. Regarding scales and harmony there is no difference in the 'blues' and early 'rock and roll'.

...But most of the scales in rock are either major or minor...

Rock is too broad a label for this question. We can go from Slayer to Elvis under the rock umbrella! It's like lumping Turlough O'Carolan and J.S. Bach in the same category, because both used major scales and lived during the same time period. Try to differentiate what style of rock you are talking about.
This is "rock" when blues is removed...

Frankie Avalon, Venus

EDIT
You mention blues, rock, pop, & classical and are looking at similarities and differences. All of them share a commonality which is the diatonic scale (yes, it applies to blues.) In terms of history and evolution of styles you should consider how the hymn is a foundation. In America it becomes the spiritual. Also the waltz and late 19th century/early 20th century sheet music songs are the ancestor of pop. In both cases, hymns and waltzes, the diatonic scale is the foundation. Other styles evolved from them. Instead of make scale/style associates think about harmony and overlapping, evolving styles.
Comment: Carolan did not use a violin, he was a harpist :)
Comment: @JonKiparsky, where was my head! I'll correct that.
Answer: To be extremely unacademic, in my head I consider the blues scale to be the "cool" scale. Whenever I hear it used in a song, it just makes the song sound and feel "cool." It adds fun, with just a slight bit of edge (owing to that dissonant tritone). Be it the Contra Base theme or Black Dog by Zeppelin
For some basics, the blues scale is the pentatonic minor (5 notes from the 7 in a minor scale) with a few extra notes, the blues notes, added. (I don't know if that's the actual name, but I call it that since it's what makes the blues scale the blues scale; hearing them is what gives it that sound). They are 3 chromatic notes--the fourth, the augmented fourth/diminished fifth (aka tritone), and the fifth.
Obviously, this scale was originally used in, you guessed it, the blues. Chuck Berry is the father of rock 'n' roll, and some of his most famous riffs and licks became trademark staples of rock guitar. Listen to his legendary "Johnny B Goode" or the equally iconic "Tutti Frutti" by Little Richard. These songs are on the border where blues first became rock 'n' roll. Then listen to songs like Steppenwolf's "Born to Be Wild" and Sweet's Ballroom Blitz. You can hear the similar riffs used in these songs, the same Chuck Berry thing where the guitars play a power chord (fifth), then hammer on a sixth and augmented sixth. This sort of thing is still used way into the 90s you can hear it in Alice in Chains' Man in the Box (albeit it's more subtle there). One of the most common Chuck Berry licks used all the time in rock and metal is doing a unison bend on the root note and then hitting its fifth on the string above it. The most obvious example that comes to mind is the solo on KISS' "Rock 'N Roll All Nite"
Another trademark of rock music that comes from the blues is the 12 bar blues progression (i.e. 4 bars of I, then 4 bars of IV, 2 again of I, 2 bars of V, and then repeat.) E.g. Rock 'N Roll - Led Zeppelin
Historically speaking too, most of the great rock musicians of the 60s were inspired by the blues players of the 50s. Mick Jagger is the original rock frontman, and he modeled his style after the black American blues players. The Stones are, after all, a blues rock band. The Beatles too.
Of course, rock eventually diverged and began incorporating everything else--minor, harmonic minor, major, modes of major scale, exotic scales in metal, jazz, you name it. But it began in the blues, and at the very heart of a rock song is usually the blues scale somewhere in there, be it the main riff or at the very least some licks in the lead playing. Kirk Hammett and Dave Mustaine for e.g. use blues licks in their solos all the time. The solo for the Mechanix comes to mind, and I'm pretty sure nearly all the songs on Kill 'Em All are based around either pentatonic or blues riffs. It would be quite rare to find any modern rock or metal song without any influence from the blues. Historically and culturally too, it was the blues players that became and inspired the original generation of rock 'n' roll.
Answer: My take on this question is that it seems to me that the term "Blues" is rather loosely applied to a lot of music that has it's origins further back in history, such as "Negro Spiritual" and even further back than that in "Jungle rhythm". Both of these categories are often found in "Blues" and in early and even current "Rock" music.
When I hear someone say Rock came from "Blues" or Rock came from "Country", it always sounds to me like one genre is trying to steal the thunder from another genre, and I try to disregard it. I prefer to just appreciate each classification, whatever it may be, for the way it makes me feel when I listen or play it.
Also,  it occurs to me that the major scale or the blues scale is only a part of what makes rock a separate category, there's also the rhythm, the lyric, the "attitude", all often very similar in nature to Blues, and Country, and just about anything else we've ever heard. I understand that it's important to know the history, but in this case the history doesn't seem to be helping one to understand the music and may be confusing the issue. My impulse is to just accept it for what it is.


Prove that a bounded $f$ is integrable if $I_0 := \lim_{n\to\infty}L(f,P_n) = \lim_{n\to\infty}U(f,P_n)$

Question:
Prove that a bounded function $f$ is integrable on $[0,1]$ if
$$I_0 := \lim_{n\to\infty}L(f,P_n) = \lim_{n\to\infty}U(f,P_n),$$ in which case $\int_0^1f(x)dx$ equals $I_0$.

Refer here. I suspect that this is the same question with answers but I am not sure how to apply it to prove my particular case.
Furthermore, consider the definition that I was given below

Definition: $f : [a,b]\to \mathbb R$ is said to be (Riemann) integrable on $[a,b]$ if and only if $f$ is bounded on $[a,b]$, and for every $\epsilon > 0$ there is a partition $P$ of $[a,b]$ such that $U(f,P) - L(f,P) < \epsilon$.

With this definition in mind, why then did the linked post above need to show that
$$\overline{\int}_a^b f \leq U(f,P_N) \leq  L(f,P_N) \leq \underline{\int}_a^b f?$$
Would it not just follows from the definition (in my particular case) that if $U=L$ as $n\to \infty$ then there automatically is a partition $P$ such that $U(f,P) - L(f,P) < \epsilon$ is satisfied by definition?
Any clarification is helpful thank you!
Answer: Beccause the upper and lower integrals are the infimum and supremum, respectively, of upper and lower sums, it follows that for any $N$ and $M$
$$L(f,P_N) \leqslant \underline{\int}_a^b f \leqslant \overline{\int_a}^bf\leqslant U(f,P_M)$$
Since $I_0 = \lim_{n\to\infty}L(f,P_n) = \lim_{n\to\infty}U(f,P_n)$, for any $\epsilon > 0$ there exists $N$ and $M$ such that
$$I_0 - \epsilon < L(f,P_N) \leqslant U(f, P_M ) < I_0 +\epsilon$$
Thus,
$$I_0 - \epsilon < \underline{\int}_a^b f \leqslant \overline{\int_a}^bf< I_0 +\epsilon$$
Since $\epsilon$ can be arbitrarily close to $0$, it follows that
$$I_0= \underline{\int}_a^b f = \overline{\int_a}^bf$$
This proves both that $f$ is Riemann integrable and that $I_0$ is the value of the integral.
Comment: This also uses the fact that given any partitions $P$ and $Q$, we must have $L(f,P) \leqslant U(f,Q)$ which implies that $\underline{\int}_a^b f \leqslant \overline{\int_a}^bf$ (for any bounded $f$ even if it is not Riemann integrable).
Comment: Yes. The usual Riemann criterion is that if we can find a partition such that the the difference between corresponding upper and lower sums is less than $\epsilon$, and this works for any $\epsilon$, then the function is Riemann integrable. Again this is because the upper and lower integrals are squeezed and must differ by less than any $\epsilon$.  The proof here is similar except we don't use upper and lower sums for the same partition.
Comment: @schn: Thanks.  It is clearly not true for every partition sequence $(P_n)$ -- for example, a constant sequence. Do you mean prove there exists a sequence where the lower and upper sums converge to $I_0$?  Or perhaps with an added condition such as $\|P_n\| \to 0$.
Comment: @schn: That converse is true.  When I get a chance I'll show you how to proceed.
Comment: @schn: Pose this as a new question showing your work as you show here.  Comments are really not meant for extensive discussion and the posting of solutions. It is also better to not answer a second question from comments by appending into an existing answer from an earlier question.
Comment: @schn: I can help you then.
Comment: @schn:  I added an answer there.
Comment: I see, so Based on your first sentence, in other words, taking the $\inf(U) - \sup(L) < \epsilon$ is essentially equivalent to $U - L < \epsilon$ in proving that an $f$ is Riemann integrable? Forgive me if I am mistaken.
Comment: Dear @RRL, thank you for a nice proof. I would be extremely grateful if you could prove the converse statement in an edit, that is, if $f$ is integrable, then $I_0 = \lim_{n\to\infty}L(f,P_n) = \lim_{n\to\infty}U(f,P_n)$.
Comment: Yes. If I understood the OP's question correctly, you proved "if there is a $P_n$ such that $ I_0 = \lim_{n\to\infty}L(f,P_n) = \lim_{n\to\infty}U(f,P_n)$, then $f$ is integrable and $I_0$ is the value of the integral". So I was wondering if the converse also holds: "if $f$ is integrable and $I_0$ is the value of the integral, then there exists a $P_n$ such that $ I_0 = \lim_{n\to\infty}L(f,P_n) = \lim_{n\to\infty}U(f,P_n)$". I don't know if this statement holds, but I am trying to go from bottom to top in your post. I am stuck on how to obtain the second inequality from the third :-)
Comment: My attempt so far is the following: if $f$ is integrable and  $I_0= \underline{\int}_a^b f = \overline{\int_a}^bf,$ then, for $\epsilon>0$, clearly $I_0 - \epsilon < \underline{\int}_a^b f = \overline{\int_a}^bf< I_0 +\epsilon.$ Next I would like to somehow squeeze in an $L(f,P_n)$ such that $I_0 - \epsilon <L(f,P_n)\leq \underline{\int}_a^b f$ and similarly for $U(f,P_n)$. If such a sequence of partition exists, probably for large enough $n$, then we would be done. But I'm unsure which property justifies such a sequence and which conditions arise on the sequence.
Comment: Ok, I understand. I asked a [question](https://math.stackexchange.com/q/4684725/642262) about this implication the other day :-)


QCOW2 virtual size lowering

Question: I'm trying to get the virtual size of a qcow2 container down so that it can fit in a openstack flavor with 10GB disk.
root@node-10:~# qemu-img info zztop.qcow
image: zztop.qcow
file format: qcow2
virtual size: 80G (85899345920 bytes)
disk size: 2.6G
cluster_size: 65536
Format specific information:
compat: 1.1
lazy refcounts: false

I follow the guide here and fill the end of the disk with zeros then run qemu-img convert -O qcow2.
The resulting qcow2 however retains the same disk size and virtual size.
How do I lower the virtual size of a qcow2 so that it can fit in a openstack flavor smaller than 80GB?
Comment: you can boot from volume too, the openstack flavours only list the root ephemeral disk, boot from disk or snapshot.
Comment: I'm trying to ensure my images/snapshots templates don't continue growing every time I update them.
Comment: the second example in that link would work,     "mv original_image.qcow2 original_image.qcow2_backup"
qemu-img convert -O qcow2 original_image.qcow2_backup original_image.qcow2
Comment: Virtual size remains 80GB. `/dev/vtbd0p2     77G    2.3G     69G     3%    /`
Answer: If you want to shrink the virtual size, you need to use virt-resize
Comment: I did, Posting the actual code spares people following the link and skimming through all the documentation to find the important parts. It's recommended in the [answering guidelines](https://serverfault.com/help/how-to-answer) under _Provide context for links_ also for the case when that site goes down or becomes unavailable.
Comment: Would you mind posting the actual command?
Comment: Did you try following the link?
Answer:
You need to convert the qcow2 image to raw
qemu-img convert -O raw guest.img guest.raw
Then resize the raw file
qemu-img resize guest.raw 3G
Then convert it back to qcow2
qemu-img convert -O qcow2 -o compat=0.10 guest.raw guest.img
Then run the guest and resize your file system
Answer: Improved answer of @user370956
I was able to successfully shrink my image actual size from 5.9G to 3.5G and v. size, too.

Backup your image
cp guest.img quest.backup
You need to convert the qcow2 image to raw
qemu-img convert -O raw guest.img guest.raw
Boot up some live iso mounted as -cdrom and your guest.raw mounted as -drive
qemu-system-x86_64 -machine type=pc,accel=kvm -boot order=d -drive file=guest.raw,format=raw -cdrom ~/Downloads/debian-live-9.6.0-amd64-lxde.iso -m 2G
Use gparted (gui tool) to shrink the partition from inside the guest. Keep some free space so the system can still boot (100 MB is enough). Leave the remaining space unallocated. Check the filesystem.
fsck -a
Then resize the raw file
qemu-img resize guest.raw 3G
Then convert it back to qcow2
qemu-img convert -O qcow2 guest.raw guest.img
At this point you can resize the qcow2 virtual image size to add some space and this will not affect image file size. This may be needed to ensure the stability of the VM.
qemu-img resize guest.img +1G
Repeat steps 2,3 to allocate some more space to guest root partition if you did step 6.
Answer: Manipulating only from the host side, may leave your guest file system corrupted.
So to complete this answer, before any changes from the host you need to change the VM's storage partitions sizes with partitioning tools like gparted from inside of the VM. So that the total size of the virtual disk becomes less than desired size of the virtual storage. After that, you can do the first 3 steps.
Answer: 1 - Disable swap file in fstab if there is one
2 - Mount gparted to your VM cd-rom
3 - start VM, boot gparted and resize the partition to a smaller size
4 - Delete swap partition and recreate, or make sure all partitions are aligned next to each other at the beginning of the disk. I had issues with the swap being at the end of the disk after shrinking the partition so this was the fix.
5 - shut down VM
6 - Locate qcow2 file and in same directory, run
'qemu-img create -f qcow2 -o preallocation=metadata new-disk.qcow2 80G' (where 80G is the new disk size)
7 - use virt-resize - 'virt-resize old-disk.qcow2 new-disk.qcow2'
8 - copt new-disk to correct file name for VM, start VM and re-enable swap ie: 'swapon /dev/sda5'
9 - edit fstab to add swap ie: '/dev/sda5 swap swap defaults 0 0'
DONE.

QCOW2 virtual size lowering