What is the name for a chord played by notes introduced in sequence?

Question: Is there a name for a chord that is introduced one note at a time?
You can hear an example in the first couple of seconds of "Lolly, Lolly, Lolly, Get Your Adverbs Here!" on Schoolhouse Rock:

It's different from an arpeggio; I don't know that much about music theory but from looking it up, it doesn't seem exactly the same as a rolled chord or broken chord.
Answer: This technique has a few different names, a pyramid, bell, or cascade chord. It can be considered a classification of arpeggio since sometimes when arpeggios are played the notes are sustained.
Here is an excerpt from the "Arpeggio" article in Wikipedia:

A bell chord, also known colloquially as "bells", is a musical arrangement technique in which a composition has separate instruments (or multiples of the same instrument) play single notes of a chord in sequence, sustaining individual notes to form the chord. It is, in effect, an arpeggio played by several instruments sequentially. This is also known as a pyramid or cascade. It is common in barbershop music. [End excerpt]

This technique can be used in vocal music, horn arrangements and even orchestral settings. Vocally it has been used in "Twist and Shout" and "Bohemian Rhapsody" just to name a few.
Comment: In that wiki article... "The technique originated with jazz big bands"...I doubt that! I'm sure there are examples from long, long before that.
Comment: @MichaelCurtis That caused a raised eyebrow for me Michael, part of the reason I didn't include it in my excerpt. It's hard to believe that in several centuries of western music no one had ever before sustained an arpeggio over several instruments, lol!
Comment: https://en.wikipedia.org/wiki/Arpeggio#Bell_chord -- thanks!
Comment: It's one of those comments that makes start looking in my score collection, but who has the time to fact check?
Comment: @MichaelCurtis Beethoven's 5th comes to mind, he staggers the opening phrases and let's the last notes sustain against the subsequent phrases. Not a perfect example but similar.
Answer: An arpeggio is a chord played with the notes in ascending or descending order.
A broken chord is a chord played such that not all pitches are sounded at the same time.
In this case, it's both an arpeggio and a broken chord — both terms are appropriate to describe the music — but it also happens that each note is sung by a different voice. The multiple voices don't disqualify it as an arpeggio or broken chord.
One tends to think of arpeggios and broken chords in the context of a single instrument, but they need not be. It's also common to think of the notes of arpeggios and broken chords as happening in relatively rapid succession, but this need not be the case either.
It could be considered a rolled chord as well. Rolled notes typically are performed more rapidly, but not by definition. There is music in which chords are rolled slowly — but a slow roll is rather the exception than the rule. Nevertheless, if a slowly rolled chord is going to appear, the beginning or end of a piece is the most likely place to find it.
Comment: Nice answer. For anyone who is interested: this is how the NES / Famicom emulated chord sounds. Look up "**nes chord arpeggio**" for details.
Answer: The term arpeggio gets used in two ways, as a type of embellishment of a chord represented by the ways line...

...and also to mean playing the tones of a chord separately in a line...

The second mean is often called arpeggiation - as a process, like in composition - and sometimes it's called broken chord.
The embellishment is normally played from bottom up, very fast, and sustaining all tones for the duration of the chord, whereas arpeggiation can order the chord tones freely into a line (tons of melodies are just the result of the arpeggiation process) so there is a clear aural difference.
The difference between the two meanings is usually understood in context. If someone were to say the opening theme to Eine kleine Nachtmusik is arpeggios, it's understood that they mean the broken chord/arpeggiation process not the wavy line embellishment.
The device at the beginning of Lolly, Lolly, Lolly, Get Your Adverbs Here! is arpeggiation, a broken chord. Even though the tones go from bottom up and are sustained it's performed fairly slow. You wouldn't notate it with a wavy line, but write out full durations with long note values.


Image Load From url getting slow system android

Question: Whenever I want to run my code on mobile, mobile is slow and image load is also slow I think there is size issue so please tell me about that how to get small size of image .
here is my code.
<code>public class TopRatedFragment extends Fragment {

    JSONParser jParser = new JSONParser();
    private static String url_all_products = "http://3ilogics.org/vid/get_all_products.php";

    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_PRODUCTS = "products";
    private static final String TAG_PID = "pid";
    private static final String TAG_NAME = "name";
    private static final String TAG_EMAIL = "price";
    private static final String TAG_IMG = "images_url";

    // products JSONArray
    JSONArray products = null;
    JSONArray products2 = null;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_top_rated, container,
                false);
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);

        try {
            products = json.getJSONArray(TAG_PRODUCTS);

            //sd=json.getJSONObject(TAG_PRODUCTS).length();
            for (int i = 0; i < products.length(); i++) {
                JSONObject c = products.getJSONObject(i);

                // Storing each json item in variable
                String id = c.getString(TAG_PID);
                String name = c.getString(TAG_NAME);

                // creating new HashMap
                HashMap<String, String> map = new HashMap<String, String>();

                // adding each child node to HashMap key => value
                map.put(TAG_PID, id);
                map.put(TAG_NAME, name);

            }

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        HorizontalListView listview = (HorizontalListView) rootView
                .findViewById(R.id.listview);
        listview.setAdapter(mAdapter);

        return rootView;

    }

    private static String[] dataObjects = new String[] { "Text #1", "Text #2",
            "Text #3", "Text #4", "Text #5", "Text #6", "Text #7", "Text #8",
            "Text #9", "Text #10" };

    private BaseAdapter mAdapter = new BaseAdapter() {

        @Override
        public int getCount() {
            return TopRatedFragment.this.products.length();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View retval = LayoutInflater.from(parent.getContext()).inflate(
                    R.layout.viewitem, null);
            TextView title = (TextView) retval.findViewById(R.id.title);
            ImageView title2 = (ImageView) retval.findViewById(R.id.image);
            String img=null;

            try {
                //Log.d("sda",products.getJSONObject(position).toString());
                title.setText(products.getJSONObject(position).getString(TAG_NAME));
                img=products.getJSONObject(position).getString(TAG_IMG);
                title2.setImageBitmap(getBitmapFromURL(img));
                System.gc();
            }

            catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            //Log.d("All Products: ", json.toString());
            return retval;
        }

    };
    public Bitmap getBitmapFromURL(String img) {
        try {

            URL url = new URL(img);
            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();

            Bitmap myBitmap = BitmapFactory.decodeStream(input);

            return myBitmap;

        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
            return null;
        }
    }

}
</code>
Comment: you should get exception while running this code as network calls can not execute in UI thread.
Answer: Use an async task for executing such operations, something like this: http://www.vogella.com/tutorials/AndroidBackgroundProcessing/article.html
Comment: How to use async task can you please explain it through any sample code
Comment: @user3345828 you should be able to find millions of samples/tutorials for AsyncTask if you simply search for it...


Definition of ring-homomorphism

Question: If we choose a ring $R$ with unit $1$ then for $r\in R$ the map $R\rightarrow R,s\mapsto rs$ is not a ring-homomorphism since $1$ is not mapped to $1$?
It seems false that this map is not a ring-homomoprhism...
Answer: For that reason and (most of the times) for the fact that $\phi(ab)=rab$, which is in general not equal to $\phi(a)\phi(b)=ra\cdot rb$. If $R$ is commutative, it is a homomorphism of $R$ as $R$-module. If $R$ is not commutative, it still is a homomorphism of $R$ as right $R$-module (but in general not as a left $R$-module).
Ring-homomorphisms are the functions $\phi:R\to S$ which satisfy:

$\phi(1)=1$
$\phi(a-b)=\phi(a)-\phi(b)$
$\phi(ab)=\phi(a)\phi(b)$

Condition (2) is often substituted with the equivalent condition "$\phi(a+b)=\phi(a)+\phi(b)\text{ and }\phi(-a)=-\phi(a)$"

Definition of ring-homomorphism


How do I determine if differences between medians are statistically significant when notches are very close (see "C" and "D")?

Question: Regarding "C" and "D":
Is there a way other than visually inspecting the notches from the boxplots? I know the range of values for "D" is lower than "C" and the median value appears to be lower for "D". I also think that box "D" has less variability. I'm not sure what else is worth mentioning when I compare the two boxplots.
Answer: There are several issues here.
First, I have always regarded notches in boxplots
to be a rough suggestion whether medians are equal.
Notches are calibrated for comparisons, at the 5% level, of two groups at a time.
Using boxplot notches as a graphical device, it is especially
important to show the boxplots in a way that
makes the notches easy to see. In this case, I
think it would be helpful to plot the boxplots horizontally, rather than vertically.
Also, the
notches may be easier to see if the interiors of boxes have
colors that contrast with the outlines.
Thus, I believe the righthand panel below shows the relative
locations of the notches better than does the
lefthand panel. [There are 500 observations in each plot.]
par(mfrow=c(1,2))
 boxplot(x1,x2, col="grey", notch=T)
 boxplot(x1,x2, notch=T, horizontal=T, col="skyblue2", pch=20)
par(mfrow=c(1,1))

Second, I think it is best to do a formal test
whether the locations of the samples differ.
If the distribution types of the populations
are unknown, one can use a nonparametric test.
Results for the Wilcoxon rank sum test are shown
below. There is no doubt about significance
at the 5% level.
wilcox.test(x1,x2)

        Wilcoxon rank sum test
        with continuity correction

data:  x1 and x2
W = 108000, p-value = 0.0001981
alternative hypothesis:
  true location shift is not equal to 0

Note: The following R code was used to
simulate my fictitious data. Because populations
are chi-squared, a parametric test might
be used instead.
set.seed(2022)
x1 = rchisq(500, 10)
x2 = rchisq(500, 11)


Como fazer deploy de uma aplicação vuejs (browserify) no heroku?

Question: Levantei o servidor com express, porém usando um esquema para o webpack pois não encontrei nada relacionado ao browserify, segue o código...
// server.js
var express = require('express');
var path = require('path');
var serveStatic = require('serve-static');
app = express();
app.use(serveStatic(__dirname + "/dist"));
var port = process.env.PORT || 5000;
app.listen(port);
console.log('server started '+ port);

já está tudo configurado corretamente, mas está aparecendo somente...

Cannot GET /

Alguém sabe como posso fazer isso?
package.json
"scripts": {
    "watchify": "watchify -vd -p browserify-hmr -e src/main.js -o dist/build.js",
    "serve": "http-server -o -s -c 1 -a localhost",
    "dev": "npm-run-all --parallel watchify serve",
    "build": "cross-env NODE_ENV=production browserify -g envify src/main.js | uglifyjs -c warnings=false -m > dist/build.js",
    "postinstall": "npm install express",
    "start" : "node server.js"
  },

Com o comando que está no start o servidor levanta, porém a aplicação não é encontrada.
Obs. para iniciá-la localmente é necessário um npm run dev que não foi possível executar em start no heroku.
Comment: Como está seu `package.json`? O Heroku logs pode ajudar, veja se tem algo estranho nele
Comment: Adicionei a parte relevante do package.json, também tentei verificar os logs, mas não me mostra nada.
Comment: Pode nos mostrar o server.js pf Felipe?
Comment: @LucasCosta, já está na pergunta
Comment: Ah sim, me atentei ao comentário. Experimente deixar o start dessa forma: `"start": "./node_modules/webpack/bin/webpack.js -p --progress && node server.js"`. E verifique se as dependencia do webpack estão no package.json corretamente tb
Comment: Perdão, tinha colocado o package.json errado, já editei, testei a solução acima e não deu certo...
Comment: Oi Felipe, tens esse projeto no github ou podes criar um `.zip` para podermos testar?
Comment: veja se esse tutorial serve https://medium.com/netscape/deploying-a-vue-js-2-x-app-to-heroku-in-5-steps-tutorial-a69845ace489
Answer: Como você está usando o http-server como servidor, uma opção é executar npm-run-all no start e para hospedar no Heroku omitir o host. Com esas alterações o app irá ser interpretado:
{
  "name": "teste",
  "description": "primeiro projeto em vue",
  "author": "teste",
  "private": true,
  "scripts": {
    "watchify": "watchify -vd -p browserify-hmr -e src/main.js -o dist/build.js",
    "serve": "http-server -o -s -c 1 -a",
    "dev": "npm-run-all --parallel watchify serve",
    "build": "cross-env NODE_ENV=production browserify -g envify src/main.js | uglifyjs -c warnings=false -m > dist/build.js",
    "postinstall": "npm install express",
    "start": "npm-run-all --parallel watchify serve"
  },
  "dependencies": {
    "express": "^4.16.2",
    "vue": "^2.0.1",
    "babel-core": "^6.0.0",
    "babel-preset-es2015": "^6.0.0",
    "babelify": "^7.2.0",
    "browserify": "^13.0.1",
    "browserify-hmr": "^0.3.1",
    "cross-env": "^1.0.6",
    "envify": "^3.4.1",
    "http-server": "^0.9.0",
    "npm-run-all": "^2.1.2",
    "uglify-js": "^2.5.0",
    "vueify": "^9.1.0",
    "watchify": "^3.4.0"
  },
  "browserify": {
    "transform": [
      "vueify",
      "babelify"
    ]
  },
  "browser": {
    "vue": "vue/dist/vue.common.js"
  }
}

Deixei como dependencies e não devDependencies para que o Heroku possa usá-los, e alterei as propriedades start e serve.
Comment: Era isso mesmo, muito obrigado!


Any ideas on how to solve this? $\lim_{x\to \infty}x(\frac{1}{e}-(\frac{x}{x+1})^x)$

Question: Tried L'Hospital's rule, using logarithms and variable substitution. Guess I'm missing something or making mistakes. Thanks.
Comment: It's best that you show your work and give some meaningful context to your question. Just writing that you tried some approach and that didn't work does not constitute a meaningful context.
Answer: Observe that, for $x\to \infty$,
$$
\begin{split}
\left(\frac{x}{x+1}\right)^x
& = \exp\left[ -x \log\left(1+\frac{1}{x}\right)\right]
\\ &= \exp\left[-x\left(\frac{1}{x}-\frac{1}{2x^2} + o(1/x^2)\right)\right]
\\ & = \frac{1}{e}\exp\left(\frac{1}{2x} + o(1/x)\right)
\\ & = \frac{1}{e} + \frac{1}{2e x} + o(1/x).
\end{split}
$$
Comment: Yeah, taking -1 from logarithm is what I did miss. Thank you sir!


Diagonal entries of symmetric matrices and eigenvalues

Question: suppose I have a symmetric matrix $S$ with diagonal entries $s_{jj}$. I'm trying to prove that none of these diagonal entries $s_{jj}$ can be be smaller than all the eigenvalues of $S$. My textbook tells me that if one of these diagonal entries were small than all the eigenvalues, then $S-s_{jj}I$ would have wholly positive eigenvalues and be positive definite - however that couldn't be the case because $S-s_{jj}I$ would have a zero on the main diagonal.
What I don't understand is how one can skip straight to $S-s_{jj}I$ having wholly positive eigenvalues.
Help will be appreciated, thanks!
Answer: In general, the eigenvalues of $S - \mu I$ are $\lambda_1 - \mu, \lambda_2 - \mu, \ldots, \lambda_n - \mu$ where $\lambda_1,\ldots,\lambda_n$ are the eigenvalues of $S$. You can check this by noting that the eigenvectors of $S$ are eigenvectors of $S-\mu I$ and vice versa.
Comment: Yep - solves it. Thanks!
Answer: As $S$ is a symmetric matrix it is diagonalizable and we can write $D = U^{-1} S U$ with $D$ a diagonal matrix and $U$ an invertible matrix. Now you can transform
$$ S- s_{jj} I \to U^{-1} (S- s_{jj} I) U = D-s_{jj} I $$
which has the eigenvalues $\lambda_i$ of $S$ minus $s_{jj}$ which are positive per definition.


QHttpMultiPart to QByteArray

Question: Is there a way to convert a QHttpMultiPart to QByteArray or other similar binary data?
I found QHttpMultiPart very convenient to compose mail data formats but seems very dependand to QNetworkAccessManager framework and as as far as I searched there is no direct way to do that.
The closest that I has been is to append the QHttpMultiPart to a QNetworkReply object which is derived from QIODevice and then use QIODevice::readAll(), but QNetworkReply does not have public constructors.
Comment: Did you make any progress on this?
Comment: @jp36 No. I checked the source code of QHttpMultiPart and it's not possible because the QIODevice interfaces are private. So I have to build my own Multipart builder. :/
Comment: Thanks for the update. I found a Qt bug about this that hasn't gotten any traction. If you want to vote/watch it and maybe help move it along - https://bugreports.qt.io/browse/QTBUG-39396
Comment: Was your only problem that `QNetworkReply` does not have a public constructor? I believe you could have subclassed it and made the constructor public. How do you append `QHttpMultiPart` to the network reply though?
Comment: @georg-schölly It is not the only problem. Internally the QIODevice interface of QHttpMultiPart are private due PIMPL pattern. It should be useful to you to check the [source code](https://github.com/openwebos/qt/tree/master/src/network/access) of these classes, maybe you can see a workaround
Answer: You can subclass QNetworkAccessManager: its createRequest() method (which you have to implement) will receive a QIODevice containing all the data sent with a POST request; so you just have to call post(..., multiPart) on this fake network access manager of yours and you'll be able to read the data.
Here's a helper class I wrote:
multipart.h:
#include <QByteArray>
#include <QIODevice>
#include <QScopedPointer>

class QHttpMultiPart;

class MultipartPrivate;
class Multipart
{
public:
    Multipart();
    virtual ~Multipart();

    QByteArray toByteArray(QHttpMultiPart *multiPart);

private:
    QScopedPointer<MultipartPrivate> d_ptr;
    Q_DECLARE_PRIVATE(Multipart)
};

multipart.cpp:
#include "multipart.h"

#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>

class FakeReply: public QNetworkReply
{
    Q_OBJECT
public:
    FakeReply(const QNetworkRequest &req, QNetworkAccessManager *parent):
        QNetworkReply(parent)
    {
        Q_UNUSED(req);
        QNetworkReply::open(QIODevice::ReadOnly);
    }
    void abort() override {}
    qint64 readData(char *, qint64) override { return 0; }
};

class MultipartPrivate: public QNetworkAccessManager
{
    Q_OBJECT

    using QNetworkAccessManager::QNetworkAccessManager;

    QNetworkReply *createRequest(Operation op, const QNetworkRequest &req,
                                 QIODevice *outgoingData) override {
        Q_UNUSED(op);
        m_data = outgoingData->readAll();
        return new FakeReply(req, this);
    }

public:
    QByteArray m_data;
};

Multipart::Multipart():
    d_ptr(new MultipartPrivate)
{
}

Multipart::~Multipart()
{
}

QByteArray Multipart::toByteArray(QHttpMultiPart *multiPart)
{
    Q_D(Multipart);

    QNetworkRequest dummy(QUrl("http://multipart.test"));
    delete d->post(dummy, multiPart);
    return d->m_data;
}

#include "multipart.moc"

You can also find a couple of unit tests here:
https://gitlab.com/accounts-sso/libauthentication/commit/7d84cb417f756e663dca7362457b28bc53a1096a

QHttpMultiPart to QByteArray


How can I get names of the players who joined the game room?

Question: I am making a tic-tac-toe game using nodejs,socket.io and sql database to store the results. The problem is that I am unable to get the name of both the players that join the game room. How can I do that?
Comment: Without your code this questions is impossible to answer.
Answer: Your server has no notion of a "name" for a socket.io connection.  I can think of two ways to associate a name with a socket.io connection:

If the user is logged into your server via http and the server knows the name for that login, then you can access the login cookie from the socket.io connection and presumably use that to access the server-side session object and get the name that way.
You can have the client announce its name to the server by sending the server a socket.io message that tells it the name.  You server can then receive that message and set a custom property on the socket.io socket object to that name.  Note: this is not particularly secure since a client can announce any name it wants.  If that matters to you and you have a login name, then use the first option.


Can we determine the sign of this product of complex numbers?

Question: Let $$\Lambda=\prod_{n=1}^N(a_n+ib_n)\not=0$$
where $a_n,b_n$ are real. Can we determine $\mathrm{sign}(\Lambda)$ when $\mathrm{Im}(\Lambda)=0$ and $a_n<0\;\forall n$?
The result can depend on $N$, but not the individual $a_n$s and $b_n$s.

The context for this problem is that I have the matrix product $$A=BC$$ where $A$ and $C$ are square and (in general) nonsymmetric, so $$\mathrm{det}(A)=\mathrm{det}(BC)=\mathrm{det}(B)\mathrm{det}(C).$$ I know that $\mathrm{det}(B)$ is positive and real and that $\mathrm{det}(C)$ is real (since the matrix $C$ is real, its determinant can only be real). Now I write $\mathrm{det}(A)$ as the product of the (complex) eigenvalues of $A.$ Furthermore, I know that all eigenvalues of $A$ have negative real part.
Comment: $\omega$ has real part $-1/2$.
Comment: Sure we can determine the sign. Just compute the product and look at the number you get.
Comment: @Wojowu I don't know the eigenvalues of $A$, only that they must have a negative real part.
Comment: In that case, it's impossible to deduce the sign just by knowing that and $n$. For $n=3$, the product might be positive ($\omega\cdot\omega\cdot\omega=1$) as well as negative ($\omega\cdot\overline\omega\cdot -1=-1$) ($\omega$ is a primitive thrid root of $1$).
Comment: @Wojowu I don't think that that satisfies that all real parts of the complex numbers, here (here $\omega$), should be negative? Am I mistaken?
Answer: We can't know the sign. Assuming $a+b+c=abc$ we have that
$$(-1+ai)(-1+bi)(-1+ci)=ab+ac+bc-1.$$ Now, if $a=1,b=-1,c=0$ we get $-2<0$ and if $a=b=-2,c=-4/3$ we get $25/3>0.$
Comment: That's actually $a_1a_2(1+k^2)$ which is always positive. You won't find examples with two numbers, but three are enough as I illustrate in a comment above.
Comment: That was what I feared, thanks!


How to build a simple blog where content could be published securely to user groups?

Question: I am developing a PHP application and want to host a blog to communicate with my alpha, beta, and (hopefully) other users.  I have some experience with Drupal, so am planning to put it to use.
I installed Acquia Commons.  It was impressive, perhaps too impressive for my needs.  I started out by trying to remove some of the features, and I found that there's not much documentation freely available for it.  (I don't want a paid service - this startup has not made any money).
I am thinking that Drupal Core with Organic Groups added might be sufficient, but I'm not sure since I have not used Organic Groups before.  And of course, there could be other distributions or modules that I don't know about too.
So, the question is, if your Drupal skills were pretty basic, how would you go about building a simple blog where content could be published securely to user groups?
EDIT: Maybe my usage of the word 'groups' is confusing the issue.  Perhaps I could do this simply by creating different roles, such as Alpha User, Beta User, and assigning users to those roles.  In that case, how would I go about restricting access to content based on role?
Comment: Personally, if I were developing a PHP application, I would want to spend my time developing that, not messing around with blog configuration.  Setting up Organic Groups is pretty involved, so I would use Google Groups/Plus or one of the other freely available services.  If you really want a Drupal distribution, I would try Open Atrium, which does bug tracking too.
Comment: Read this link
https://www.lullabot.com/blog/articles/organic-groups-drupal-7 And watch this series of videos (signup is free)
http://modulesunraveled.com/organic-groups
Answer: As per your "... there could be other distributions or modules that I don't know about too." in your question: have a look at the Group module (commonly perceived as an alternative for Organic Groups).
Group allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections. It is available as of D7, and has a D8 version also. The Group module creates groups as entities, making them fully fieldable, extensible and exportable. Which also makes it integrate very well (out of the box) with commonly used modules such as Rules, Views, etc.
Some more questions you may want to look at for more details:

What are the various roles supported by the Group module?, which explains the various types of roles that can be used.
How to bulk assign existing content to a group created with the Group module?, a typical issue when adding this module to an existing site).
What are the features of the Group module versus Organic Group module?

Resources

Community documentation for the Group module.
Video tutorial "How to use the Group module in Drupal 8 to manage editorial access control to different areas of a web site".


Smooth path definition

Question: I keep getting confused with the definition of a smooth path. Here is a definition from William T. Shaw's Complex Analysis with Mathematica:
A path $\phi$ is a continuous mapping from a segment of the real axis into the complex numbers; i.e. $\phi:[a,b]\rightarrow C$.
A path $\phi$ is smooth if it is a differentiable path, and furthermore, the derivative map $\phi':[a,b]\rightarrow C$ is continuous.
OK, now here is my path: $\phi:[-2,2]\rightarrow C$ by $\phi(t) = t^2 + i t^3$. Now, I believe it is differentiable:
$$\phi'(t)=2t+i 3t^2$$
And I believe that $\phi'$ is continuous on $[-2,2]$. However, here is the image of the path:

See the sharp cusp at (0,0)? This is a smooth path?
I am obviously missing a subtle point.
D.
Comment: The curve's "speed" tends to zero as it reaches the cusp, so it is a sufficiently gentle turnaround that it remains continuous (and even continuously differentiable). Your intuition would probably be better captured with the term **regular curve** (where the tangent vector never jerks around suddenly or takes a rest stop).
Comment: Note, that is not the graph of the function in the same way that we talk about graphs from ordinary calculus. Think about it - the actual graph would be 3-dimensional. This is just the image of the function, and does not determine the function.
Comment: In many books, there is an extra condition on smooth curves, namely that $\phi'(t) \neq 0$ everywhere. (This would make your example non-smooth.)
Answer: It is smooth by the definition you gave. Smooth path are probably used to make integration along them... cusps are not a problem. The important thing is to find a tangent vector almost everywhere.
Comment: In the cusp (as in any point where the derivative is $0$) you don't have a tangent line.
Comment: Almost everywhere? The definition requires everywhere.
Comment: There is no *tangent line* at $0$, but there is a *tangent vector* (or perhaps velocity vector), namely the zero vector. Integration over a curve involves its tangent vector, not its tangent line.
Answer: In short, a smooth curve $\vec{c}: [a,b]\rightarrow C$ must:

map distinct points on $(a,b)$ to distinct values
have a $\vec{c}'(t)$ that exists, is continuous, and $\neq\vec{0}$ at any point in $(a,b)$

So no, the example you have given is not smooth, because at $(0,0)$, $\vec{c}'(t)=\vec{0}$ so that it can turn around, which violates condition 2.
(I was going to leave this as a comment for posterity's sake, but unfortunately do not have the reputation to :/)

Smooth path definition


Error 404 with Wordpress subdomain using nginx

Question: I'm in the process of setting up a subdomain with wordpress on it. I'm getting a 404 error with my nginx configuration. Currently using PHP Version: 7.0.22, not getting any errors in the php logs, but I am in nginx
/var/log/nginx/error.log
 *1 open() "/usr/share/nginx/html/50x.html" failed (2: No such file or directory), client: xxx.xxx.xxx.xxx, server: kb.workspire.io, request: "GET / HTTP/1.1", upstream: "fastcgi://unix:/var/run/php7-fpm.sock", host: "kb.workspire.io"

Here is my current server block
/etc/nginx/sites-available/kb.workspire.io
server {
    listen 80
    server_name kb.workspire.io;
    root /var/www/kb.workspire.io/wordpress;
    index index.php;

    location / {
            #try_files $uri $uri/ =404;
             try_files $uri $uri/ /index.php?q=$uri&$args;
    }

    listen 443 ssl;

    error_page 404 /404.html;

    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
            root /usr/share/nginx/html;
    }

    location ~ \.php$ {
            try_files $uri =404;
            fastcgi_split_path_info ^(.+\.php)(/.+)$;
            fastcgi_pass unix:/var/run/php7-fpm.sock;
            fastcgi_index index.php;
            include fastcgi_params;
    }

Comment: I think the error only says that the error document is not found..
Answer: The location block here:
location = /50x.html {
        root /usr/share/nginx/html;
}

is telling nginx to fetch a custom error page /usr/share/nginx/html/50x.html which is then throwing an error because it doesn't exist.
If you are using custom error pages, you'll want to fix your paths so they can be found. It certainly looks odd that the 50x.html page is expected to be in /usr/share/nginx/html but the 40x.html page is looking in /var/www/kb.workspire.io/wordpress.
If you are not using custom error pages, you can remove the error_page directives and the location = /50x.html block.
Comment: I used a server block config from another site I had and looking at it now, I believe it was the location block. It's working now, thank you
Comment: Glad to hear it's working. If my answer helped you, I'd appreciate it if you could mark it as accepted.


xkb: Correct way to interact with it on Mint 15/Ubuntu 13

Question: I would like to know what is the currently approved way to interact with the X11 xkb apparatus to effect changes in the keyboard layout. (For Mint 15 Cinnamon, though I suspect Ubuntu 13 would be a close match for this topic).
I studied up on xkb, especially using An Unreliable Guide to XKB Configuration (http://www.charvolant.org/~doug/xkb/).
OK, so I think I know how to specify what I want in xkb concepts, using keycodes, keysyms, compat and so forth. However, relative to "Unreliable":

The xkb-related files are in different directory locations. OK, but...
I can't figure out what top-level config file actually invokes the particular xkb components ("Unreliable" discusses XF86Config-4, which is obsolete.) There are many different files in each subdirectory of /usr/share/X11/xkb, but I don't see how particular ones are selected.
I am assuming there's supposed to be a way to add user-specific overrides via user-specific xkb config files in ~/, but I've found no evidence how to do.

I did notice that there's a /etc/default/keyboard file, which sets some variables like XKBMODEL and XKBLAYOUT etc that look promising, but I have no idea what substitutions and syntax can be used there, nor if and when that takes effect.
Looking forward to enlightenment!
Answer: Having the same problem here.
I used to be able to change the files in earlier ubuntu Versions in /usr/share/X11/xkb/symbols/
I just made a copy of the de file and changed what I wanted to in there. Used to be pretty easy, as the systems just overrides the included "latin4"-Layout.
Guides are also found here: http://hektor.umcs.lublin.pl/~mikosmul/computing/articles/custom-keyboard-layouts-xkb.html
It seems as though Mint 15 is not using these files anymore?
Update: found this: http://grahamwideman.wikispaces.com/linux+--+keyboard+configuration,+xkb
Update 2: After changes to the file in /usr/share/X11/xkb/symbols/ you have to manually delete the files in /var/lib/xkb to empty the system-cache for keymapings


What does a circle before/between notes mean?

Question: I have a score for a guitar music here, which has these strange hollow circles between notes; also before the first note:

They don't look like notes, and playing them makes the music ugly, so they have some other function.
What do they mean?
Answer: They indicate open-string notes (E,A,D,G,B,E); note that they are in the same position of the numbers that indicate which fingers to use to fret the notes.
Comment: Interestingly (or not :-) ), this "o" is placed above the note in stringed-instrument sheet music.  Looks like it wouldn't fit there in guitar scores.
Comment: Dave is correct, usually this is indicated by a the number 0 rather then a circle.
Comment: I actually thought about them as the letter "o" for "open"; so the circle style confused me.
Answer: This is a badly notated 'open string', this should be a zero instead of a circle because it makes it hard to differentiate between open strings and open harmonics.
Answer: On guitar, there are often several places to play the same note. For example, the top E could be fretted on the 3rd string, 9th fret, 2nd string, 5th fret or open top string.The circle, as stated in the previous answer, indicates that the composer wants that E played on an open top string.The circle by the bottom E says the same thing, although I can't think of another way to play that note! As it's probably a study for a beginner, the composer has just been helpful.As the font is different, think 'open' rather than 0 fret, but it's the same difference.
Comment: "I've told you once, just do them the same." I'd hold down an open Am for 1st bar, open E for second, and E7 for the third bar, same fingers for all the triplets in each bar.The 'simile' means use the same right hand digits, as in thumb(p),index(i) and middle(m).
Comment: Do these markings tell us anything about how to play the B in the second bar? Does the absence of "o" markings in e.g. second triplet mean "play it like earlier", "play it differently" or "I felt helpful for a while but now I feel lazy"? I think all the triplets should be played similarly; asking just in case I missed something obvious.
Answer: In writing for the violin family, a small circle also means harmonic, which is produced by lightly touching the string enough to stop it vibrating but not enough to play the note. Sometimes the string is stopped lower down as well, in order to play a different range of harmonics.


Convert PartialView to HTML

Question: I am just wondering if it is possible to convert
PartialView("_Product", model)

to html so we can send it back with JSON ?
return Json(result, JsonRequestBehavior.AllowGet);

Answer: Absolutely, put the following method in a shared controller or a helper class.  It will return the rendered view in HTML, the usage is self explainatory:
public static string RenderViewToString(ControllerContext context, string viewName, object model)
{
    if (string.IsNullOrEmpty(viewName))
        viewName = context.RouteData.GetRequiredString("action");

    var viewData = new ViewDataDictionary(model);

    using (var sw = new StringWriter())
    {
        var viewResult = ViewEngines.Engines.FindPartialView(context, viewName);
        var viewContext = new ViewContext(context, viewResult.View, viewData, new TempDataDictionary(), sw);
        viewResult.View.Render(viewContext, sw);

        return sw.GetStringBuilder().ToString();
    }
}

Comment: U are awesome genius man! :)
Comment: @Leo Nix How should I create the context argument? I tried to initialize an instance but I don't know the ControllerBase argument of its constructor.
Comment: you don't need to create one if you use it in the context a controller action: ControllerContext is a property of the controller so just pass it in.   https://goo.gl/pp5AkR
Comment: Say you're trying to render a partial view in HTML rather than calling it from the controller. Then what do you use as the context? e.g. `
Comment: Thanks mate, you saved my day :)
Answer: I don't know if it is best practice or not, but if you left it as it is
return PartialView("_Product", model)

Then you can call the method using AJAX:
$.ajax ({
  type: "POST",
        url: _url,
        data: _data,
        success: function (result) {
            // the result is the returned html from the partial view
        }
})

Convert PartialView to HTML


Getting results from two tables by using SELECT Query

Question: I have 2  MySQL tables:

I store the admin_vat_id in the Fac__Article table which is actually a reference to the id of the Fac__Admin_vat:

What I'm trying to do
I want to get all Fac__Article  table's entries, but at the admin_vat_id column, where it normally would display the integer value, I want to display the float value of the column rate of the table Fac__Admin_vat.
I guess I have to use the select and union keyword, but I don't know how to implement this select query. Please guide me with knowledge in solving this problem.
Comment: its a simple join query nothing more than that
Comment: I think you should use the `LEFT JOIN` instead of `UNION`.
Comment: can you show some sample output you require?
Answer: Try this (correct the table names if i misspelled): SELECT *, Fac__Admin_vat.rate FROM Fac__Article LEFT JOIN Fac__Admin_vat ON Fac__Admin_vat.id = Fac__Article.admin_vat_id
Comment: Although your answer didn't solve my problem it pointed me to the right direction. +1
Comment: Please do not edit my answer with your comment. Why isn't that good for you? You sad, you want everything from the `Fac__Article` table, and the `rate` related on Fac__Article.id to Fac__Article.admin_vat_id
Answer: All you need is a simple LEFT JOIN:
SELECT
    fa.id,
    fav.rate,
    fa.article_number,
    fa.name,
    fa.description,
    fa.unit,
    fa.price,
    fa.stock,
    fa.stock_warning,
    fa.visible
FROM `fac_article` fa
LEFT JOIN `fac_admin_vat` fav
    ON fa.admin_vat_id = fav.id

SQL Fiddle
Comment: nope. that is an alias for the name of the table. fa is your Fac__Admin table, while fav is the Fac__admin_vat.
Comment: The `fa` and `fav` following the table names are assigning alias' to them for use elsewhere. See [here](http://dev.mysql.com/doc/refman/4.1/en/identifiers.html).
Comment: +1 for the example. But why are you using fa.columnname, and fav.column name? Will it work without it?
Answer: Try using left join, a rough example below.
SELECT *, Fac__Admin_vat.rate as admin_rate FROM Fac__Article LEFT JOIN Fac__Admin_vat ON Fac__Article.admin_vat_id = Fac__Admin_vat.id

This will allow you to use admin_rate in your code to get the data you want. Hope this helps.


How can I keybind opening a new terminal to the right of my current opened files?

Question: Currently I have the below snippet of code that doesn't really seem to do what I want it to do under my vim normal mode keybindings:
    {
        "before": ["<Leader>", "f", "t"],
        "commands": [
            "workbench.action.terminal.newInActiveWorkspace",
            "workbench.action.terminal.focus",
            "workbench.action.moveEditorToNextGroup"
        ],
        "when": "editorTextFocus && !terminalFocus && !quickInputVisible"
    },

I want it to open up a new terminal tab, and open it as a new tab of the files which are opened in the middle of VS Code (not on the bottom terminal part).
Answer: It sounds like you want one of these commands:
Terminal: Create New Terminal in Editor Area
workbench.action.createTerminalEditor

Terminal: Create New Terminal in Editor Area to the Side  (i.e., as a split/new group)
workbench.action.createTerminalEditorSide

Answer: I'm not aware of a VS Code command to change the location of a panel or open a panel in a specific location.
I do know that you can change the default location of all the panels by doing something like "workbench.panel.defaultLocation": "right". You might need to close and reopen VS Code after changing that setting for it to take effect.
In newer versions of VS Code, there's the secondary/auxillary sidebar, which you can drag panels and views into, so there's that.


Automated mails from a documentation on a closed network through adsl to user emails

Question: I have a closed network that has a documentation system that sends automated emails to users using smtp. The users are all on the same exchange server.  We have an adsl connection. Are there security issues if I open port 25 outgoing.? And if so can I limit it to communication with the specified exchange server?
Comment: There are a lot of details left out concerning network design and what is being used as a firewall, but I believe the question can be answered in general terms to your satisfaction.
Answer: If you limit SMTP to allow outbound only, then no, there are no security concerns as far as an unsolicited inbound connection exploiting an unpatched / vulnerable system.
Without knowing what your firewall is, I will go out on a fairly sturdy limb and say "yes", you can create a firewall rule that only allows port 25 inbound communication to go to the Exchange server. That is in fact a common thing to do to secure email communication and prevent inbound / outbound SMTP tomfoolery. In fact, if your systems are closed and predictable enough, you can create firewall rules that only allow outbound / inbound email to and from the two email server systems. Of course, this gets tricky depending on how email clients access the server and if they too are expected to communicate through email, but a deeper discussion of that kind of network design will require more information about your specific network.


Appropriate measure of dispersion for q-gaussian distribution data

Question: I have financial data (prices) which are believed to be q-Gaussian. I want to measure the dispersion for fixed periods in the dataset. Which tool is better, the mean absolute deviation, the coefficient of variation, the deviation from the center of gravity, or something like the fano factor?
The idea is to subtract price from the average of n periods, and then divide by the dispersion factor. I already tried the mean absolute deviation, but I don't like the outcome.
Comment: Why didn't you like the outcome? What happened & what would constitute a 'better' outcome?
Comment: the results didn't seem to add any value for analysis of change in behavior
Answer: The q-Gaussian distribution has undefined/infinite mean and variance for certain values of the parameters. So, dispersion measures that use the mean and variance are very sensitive to the presence of outliers, and perhaps inappropriate to describe data modeled with heavy tailed distributions. An alternative measure is the Median absolute deviation, which is less sensitive to the presence of outliers and does not assume the existence of any moments.


Find a Jordan Canonical Matrix Similar to a real matrix A

Question: If A is a matrix, Find a Jordan Canonical matrix similar to A:
$
c(x)=\text{det}(xI-A)=(x-3)^{5}(x-2)^{4}
$
The information given about A is:
$
\text{rank}(A-3I)=7
$
$
\text{rank}(A-3I)^{2}=5
$
$
\text{rank}(A-3I)^{3}=4
$
$
\text{rank}(A-3I)^{4}=4
$
$
\text{rank}(A-2I)=7
$
$
\text{rank}(A-2I)^{2}=5
$
$
\text{rank}(A-2I)^{3}=5
$
I cannot find an example that will show me how to apply the theorems in the textbook to help me answer this question.
:(
The textbook is: "Matrices and Linear Transformations" by Cullen.
I was googling, and came across something on wikipedia.  I'm not sure if this is correct or useful:
$
rank(A-3I)=7
\therefore \text{there are 7 Jordan blocks of size 2}
$
is this correct?
Comment: No, not correct.
Answer: The eigenvalues are $3$ (with multiplicity 5) and $2$ (with multiplicity 4).
The number of Jordan blocks associated to $3$ is equal to the dimension of the eigenspace of $3$, namely, to $\mathrm{nullity}(A-3I)$. By the Rank-Nullity Theorem, since $A$ is $9\times 9$ and the rank of $A-3I$ is $7$, the nullity is $2$, so there will be two Jordan blocks associated to $3$.
How many blocks are there of size at least 1? The nullity of $A-3I$. How many blocks are there of size at least 2? The initial vectors and second vectors of every block will be annihilated by $(A-3I)^2$; so you can figure out how many blocks have size at least $2$ by comparing the nullity of $A-3I$ and the nullity of $(A-3I)^2$. Every "extra" dimension you get in $(A-3I)^2$ gives you a block of size at least $2$. We have enough information to know that the nullity of $(A-3I)^2$ is 4; that means that there are 4 vectors in a Jordan canonical basis that are annihilated by $(A-3I)^2$. Two of them are the eigenvectors we already had, so that leaves $2$ vectors that correspond to blocks of size at least $2$. Continuing this way, we see that since the nullity of $(A-3I)^3$ is $5$, we get one more vector than before. That means that there is one block of size at least $3$ (four of the vectors were already accounted for, so you just add one more); the nullity of $(A-3I)^4$ is also $5$, so there are no new vectors added. There are no blocks of size at least $4$.
So we have two Jordan blocks associated with $3$: one block of size $2$, one block of size $3$.
Do something similar with $\lambda=2$.

This can all be visualized with the dot diagram of $A$ associated to $3$. This is an array of dots where there is a column for each block, and the number of rows in each column represents the length of the corresponding cycle.
If column $i$ has $p_i$ rows, then we will have $p_1\geq p_2\geq\cdots\geq p_k$ (where $k$ is the number of columns). Let $r_1\leq r_2\leq\cdots\leq r_{p_1}$ be the number of dots in each row. You can reconstruct the diagram on the basis of the $p_i$ or on the basis of the $r_j$. The following formulas give you the $r_i$:
$$\begin{align*}
r_1 &= \dim(V) - \mathrm{rank}(T-\lambda I)\\
r_j &= \mathrm{rank}((T-\lambda I)^{j-1}) - \mathrm{rank}((T-\lambda I)^j)\quad\text{if }j\gt 1.
\end{align*}$$
In your example, for $\lambda=3$, we would have
$$\begin{align*}
r_1 &= 9-7 = 2\\
r_2 &= 7-5 = 2\\
r_3 &= 5-4 = 1\\
r_4 &= 4-4 = 0.
\end{align*}$$
So the dot diagram associated to $\lambda=3$ is:
$$\begin{array}{ccc}
\bullet &\quad & \bullet\\
\bullet & \quad & \bullet\\
\bullet\\
\end{array}$$
The first column tells you there is a block of length $3$; the second column that there is a block of length $2$; the lack of a third column tells you there are only two blocks.
The $\bullet$ correspond to vectors in Jordan canonical basis. If $v_1$ and $v_2$ are the end vectors of the Jordan cycles associated to the two blocks, the dots correspond as follows:
$$\begin{array}{lcl}
\bullet\ (A-3 I)^{3-1}(v_1) &\quad&\bullet\ (A-3 I)^{2-1}(v_2)\\
\bullet\ (A-3 I)^{3-2}(v_1) &\quad&\bullet\ v_2\\
\bullet\ v_1
\end{array}$$
Answer: Modulo any conventions you may need to follow about the order of the Jordan blocks, The Jordan canonical form will be
$$J=\begin{pmatrix}
3 & p_1 \\ &
3 & p_2 \\ & &
3 & p_3 \\ & & &
3 & p_4 \\ & & & &
3       \\ & & & & &
2 & q_1 \\ & & & & & &
2 & q_2 \\ & & & & & & &
2 & q_3 \\ & & & & & & & &
2
\end{pmatrix} $$
for $p_1,\ldots,q_3\in\{0,1\}$.
Since you know that $A-3I$ has rank 7, $J-3I$ also has rank 7, so exactly one of the $p_i$s must be 0; without loss of generality it must be $p_1$ or $p_2$.
Similarly, $J-2I$ has rank 7, so exactly one of the $q_i$s must be 0; without loss of generality let it be $q_1$ or $q_2$.
This gives you four possibilities to check for which ones get the other ranks right. (There's a fairly simple principle to what works here, too, but it is better to discover it oneself).


How to aggregate the scores from different rows and return the maximum total scores in Python?

Question: My data set from a CSV file is as below:
csv_reader = [['Ali', '34'], ['Ali', '20'], ['Ali', '12.34'], ['Ben', '100.98'], ['Jack', '12.34'], ['Jack', '14.34'], ['Jack', '33'], ['Orlaith', '55.66'], ['Orlaith', '2']]

I want to sum up the scores of each person and to see who has the highest scores. So what I expect is as follow:
Ben has the highest total score of 100.98

Any of you know how to do this? I have tried a few codes, but they just didn't work.
Comment: Could you share the code that you've tried?
Answer: csv_reader = [['Ali', '34'], ['Ali', '20'], ['Ali', '12.34'], ['Ben', '100.98'], ['Jack', '12.34'], ['Jack', '14.34'], ['Jack', '33'], ['Orlaith', '55.66'], ['Orlaith', '2']]
cumulative = dict()
for person, score in csv_reader:
    cumulative[person] = cumulative.get(person, 0) + float(score)

max_score = max(cumulative.values())
max_score_persons = [person for person, score in cumulative.items() if score == max_score]

max_score_persons_string = ', '.join(max_score_persons)
print("{0} has the highest total score of {1}".format(max_score_persons_string, max_score))

Comment: So we are looping through `csv_reader` and unpacking every element into `person` and `score`.  Now we are making forming `cumulative` dict. `cumulative.get(person, 0)` this will check whether is there any entry already or not. If the entry is present it'll provide that value else provides `0`. then we are updating the `person` key with new value. you can print cummulative dict in loop. you'll get it.
Comment: But you can explain a little bit more about    `for person, score in csv_reader:
    cumulative[person] = cumulative.get(person, 0) + float(score)`    I couldn't quite get this.
Comment: Yeah I understand it now. Thanks a million.


Very challenging: max{floor,ceil}=?

Question: I spotted a pattern while trying to generalize a problem. (EDIT: said problem has been removed from this post to avoid confusion. EDIT(2): Here is the problem again: http://www.artofproblemsolving.com/Forum/viewtopic.php?p=367432&sid=356f2a2b519ab007bb648bf00e84934d#p367432 ) <--- That isnt the problem I want to solve, it is just where I got the pattern below from. I know how to solve the problem in the link already; I am only here trying to solve the problem below:
Here is the pattern I found, which I cannot prove. If you prove this, you win the bounty, and if there are multiple proofs, the most detailed (including extra information, etc) wins:
If $$\{k:k\in \mathbb{Z}^+,k\ne 4, k\ge 3\}$$,
$$\max\left\{\left(\frac{k}{\lfloor \frac{k}{\text{e}}\rfloor }\right)^{\lfloor \frac{k}{{\text{e}}}\rfloor},\left(\frac{k}{\lceil \frac{k}{\text{e}}\rceil }\right)^{\lceil \frac{k}{{\text{e}}}\rceil}\right\}=\begin{cases}\left(\frac{k}{\lfloor \frac{k}{\text{e}}\rfloor }\right)^{\lfloor \frac{k}{{\text{e}}}\rfloor}\quad\text{if}\ \{\frac{k}{\text{e}}\}<0.5\\ \\\left(\frac{k}{\lceil \frac{k}{\text{e}}\rceil }\right)^{\lceil \frac{k}{{\text{e}}}\rceil}\quad\text{if}\ \{\frac{k}{\text{e}}\}\ge 0.5\end{cases}$$.
I honestly don't know where to begin.
EDIT: Here $\{x\}$ denotes the fractional part of $x$, e.g. $\{5.4\}=0.4$.
Comment: What for? What is a possible use of that $\max$? Isn't it art for art's sake?
Answer: Your conjecture is correct for $k$ sufficiently large and, almost surely, the only counterexample is the case $k=4$ you have already noted.
This inequality is insanely tight: In the end, it comes down to the fact that $e/6 < 1/2$ and some very fortunate coincidences concerning the continued fraction of $e$.
We put $n = \lfloor k/e \rfloor$. We have
$$\left( \frac{k}{n} \right)^n < \left( \frac{k}{n+1} \right)^{n+1}$$
if and only if
$$(n+1)^{n+1}/n^n < k.$$
We'll set $c=(n+1)^{n+1}/n^n$.
On the other hand, $\{ k/e \} > 1/2$ is equivalent to $k/e>n+1/2$, or $k>e(n+1/2)$. So your conjecture is
$$k> c \Longleftrightarrow k > e(n+1/2).$$
In other words, if you had a counterexample to your conjecture, there would be an integer $k$ between $c$ and $e(n+1/2)$. We'll rule this out.
To this end, I need to replace $c$ by something more convenient.
I claim that $e(n+1/2) > c>e (n+1/2-1/(23.9 (n+1/2)))$ for $n \geq 4$.
This is definitely true for $n$ sufficiently large, as
$$c = n \exp\left((n+1) \log\left(1+\frac{1}{n}\right)\right) = n \exp\left((n+1) \left(\frac 1 n -\frac{1}{2n^2} + \frac{1}{3 n^3}+O\left(\frac{1}{n^4}\right)\right)\right)$$
$$= e(n+1/2-1/(24 n) + O(1/n^2))$$
I also checked it for $4 \leq n \leq 100$. I haven't done the careful work of figuring out the constant in the $O()$ to prove this for all $n$, but you could if you needed to and, if I am wrong, it only introduces finitely many errors. (Here and in the following, you should think of numbers like $23.9$ as "essentially $24$", but I have put in a little fudge to make the inequalities true inequalities rather than asymptotics.)
Our goal is to show that there are no solutions to
$$e(n+1/2-1/(23.9 (n+1/2))) < k < e(n+1/2)$$
in integers, except for $k=4$ and $n=1$ (as already noted).
We can already see that, if there are any solutions, they are rare: you need to get an interval of length $1/(24 n)$ to contain an integer. We will actually see that there aren't any.
Applying $x \mapsto e-x/(n+1/2)$ to each term, this equation is equivalent to:
$$\frac{e}{23.9 (n+1/2)^2} > e-\frac{2k}{2n+1} > 0$$
or
$$\frac{e}{5.975 (2n+1)^2} > e-\frac{2k}{2n+1} > 0 \quad (\ast).$$
We now remember a theorem about continued fractions (see, for example, Theorem 184 in Hardy and Wright): If $x$ is irrational and $p$ and $q$ are integers with
$$\left| x - \frac{p}{q} \right| < \frac{1}{2 q^2}$$
then $p/q$ is a convergent of $x$. Since $e/5.975 < 1/2$,  if we had a solution to $(\ast)$, then $(2k)/(2n+1)$ would be a convergent of $e$. (Since convergents grow exponentially fast, this already proves that solutions to $(\ast)$ are very rare.)
Roughly, the rest of the proof is as follows: If you look at the convergents $p_i/q_i$ of $e$ and compute $q_i^2 |e-p_i/q_i|$ you'll see that it is approaching $1/2$ for $i \equiv 1, 3 \bmod 3$ and going to zero for $i \equiv 2 \bmod 3$. Since $1/2 > e/5.975$, we don't expect any solutions in the first case. In the second case, it happens that $p_i/q_i$ is of the form $\mbox{odd}/\mbox{odd}$, not $(2k)/(2n+1)$. The rest of the argument is filling in the details of this.
We recall the basic formulas of the theory of continued fractions: If $x = a_0+1/(a_1+1/(a_2+1/(a_3 + \cdots))) =: [a_0, a_1, a_2, a_3, \cdots]$ and the convergents of $x$ are $p_1/q_1$, $p_2/q_2$, etcetera, than $p_{i+1} = a_i p_i +p_{i-1}$ and $q_{i+1} = a_i q_i + q_{i-1}$.
The continued fraction of $e$ is known:
$$e = [2,1,2,1,1,4,1,1,6,1,1,8,1,1,10,1,1,\cdots].$$
From now on, $a_i$ will denote the sequence $2$, $1$, $2$, $1$, $1$, $4$, etcetera and $p_i/q_i$ will denote the convergents, starting $p_1/q_1=2/1$, $p_2/q_2 = 3/1$, $p_3/q_3=8/3$, $p_4/q_4 = 11/4$,  etcetera. (Note that $8/3$ corresponds to $k=4$, $n=1$.)
From the relations $p_{i+1} = a_i p_i +p_{i-1}$ and $q_{i+1} = a_i q_i + q_{i-1}$, we check that the parity of $(p_i, q_i)$ repeats with period $6$. The terms of the form $(2k)/(2n+1)$ are appear in positions that are $1$ or $3$ modulo $6$, starting
$$2, \ 8/3,\ 106/39,\ 1264/465,\ 25946/9545,\ 517656/190435, \cdots$$
I checked the $4$ convergents after $8/3$ explicitly and they did not violate $(\ast)$, so I can assume that I am dealing with some quite large numbers if there are any counterexamples.
We have the alternating sum $\left| e-p_i/q_i \right| = 1/(q_i q_{i+1}) - 1/(q_{i+1} q_{i+2})+ \cdots$ and thus, in particular, $\left| e-p_i/q_i \right| > 1/(q_i q_{i+1}) - 1/(q_{i+1} q_{i+2})$. In the cases we care about, $e>p_i/q_i$ so we can drop the absolute value.
Case 1: $i=1 \bmod 6$, like $106/39$. Note that the denominators surrounding $39$ are $7$, $32$, $39$, $71$, $495$.
$$\frac{1}{q_i q_{i+1}} - \frac{1}{q_{i+1} q_{i+2}} = \frac{1}{q_i (2 q_{i} - q_{i-2})} - \frac{1}{q_{i+1} q_{i+2}}.$$
But $q_{i-2}/q_i$ and $q_i/q_{i+2} \to 0$ as $i \to \infty$ while $1 \bmod 6$ (these are $7/39$ and $39/495$ in the example), so
$$q_i^2 \left(  \frac{1}{q_i (2 q_{i} - q_{i-2})} - \frac{1} {q_{i+1} q_{i+2}} \right) \to 1/2.$$
Already $i=13$ gets you past $e/5.975$, so there are no solutions in this case.
Case 2: $i \equiv 3 \bmod 6$, like $1264/465$. Note that the denominators surrounding $465$ are $71$, $465$, $536$, $1001$. In this case, we have
$$\frac{1}{q_i q_{i+1}} - \frac{1}{q_{i+1} q_{i+2}} =\frac{1}{q_i q_{i+1}} - \frac{1}{q_{i+1}(q_i+ q_{i+1})} = \frac{1}{q_i (q_i+q_{i+1})} = \frac{1}{q_i (2 q_i + q_{i-1})}.$$
Again, $q_{i-1}/q_{i} \to 0$ (this is $71/465$ in the example) so
$$q_i^2 \frac{1}{q_i (2 q_i + q_{i-1})} \to 1/2.$$
Taking $i=9$ already gets you past $e/5.975$.
Comment: One point glossed in the above: The hypothetical $(2k)/(2n+1)$ obeying $(\ast)$ might not be in lowest terms; suppose $(2k)/(2n+1)=p/q$ with $GCD(p,q)=1$. But, if $|e-(2k)/(2n+1)|<e/(5.975 (2n+1)^2)$ then also $|e-p/q|<e/(5.975 q^2)$. And $GCD(2k, 2n+1)$ would be odd, so we would have $p$ even and $q$ odd. So we could replace $(2k,2n+1)$ by $(p,q)$ and then run the above argument.
Answer: Not an answer, just an observation - hence CW.
The plot of
$\text{max}
\begin{cases}
\dfrac{e}{k}\log\left(\dfrac{k}{\lfloor k/e\rfloor}^{\lfloor k/e\rfloor}\right)\\
\\
\dfrac{e}{k}\log\left(\dfrac{k}{\lceil k/e\rceil}^{\lceil k/e\rceil}\right)\\
\end{cases}$
against background $\mod \dfrac{e}{2}$

shows that what you conjecture is not strictly true, but it certainly approaches that limit (if I have understood the problem correctly).
Update
For $e\pm\frac{1}{2}$, fractional part $\pm\frac{1}{4}$:

<code>Manipulate[s = E + m; pr2 = 1.005; pr1 = 0.94; r1 = s; c = m/E;Show[Plot[{If[FractionalPart[k/s] < 0.5 - m/2, 1.1, 0], 1}, {k, r1, (r1 + 5 s)}, PlotStyle -> {{Opacity[0]}, {Opacity[0]}},Filling -> {1 -> {2}}, FillingStyle -> {Opacity[0.2]},Frame -> True, Axes -> False, GridLines -> {{}, {1}},GridLinesStyle -> {Gray, Dashing[0.01]},PlotRange -> {{r1, (r1 + 5 s)}, {pr1, pr2}}], Plot[{If[Log[(k/Floor[k/s])^Floor[k/s]]/(k/s) - c >Log[(k/Ceiling[k/s])^Ceiling[k/s]]/(k/s) - c,Log[(k/Floor[k/s])^Floor[k/s]]/(k/s) - c, I],If[Log[(k/Ceiling[k/s])^Ceiling[k/s]]/(k/s) - c >Log[(k/Floor[k/s])^Floor[k/s]]/(k/s) - c,Log[(k/Ceiling[k/s])^Ceiling[k/s]]/(k/s) - c, I]}, {k,r1, (r1 + 5 s)}, PlotStyle -> {{Red, Thick}, {Blue, Thick}}, Frame -> True,Axes -> False, PlotRange -> {{r1, (r1 + 5 s)}, {pr1, pr2}}]], {{m, 0}, -0.5, 0.5}]
</code>
Comment: No - $n\mod e/2-\epsilon $
Comment: ... look carefully at the plot - the stripes and the curves don't match up exactly.
Comment: ... which is probably why you said in the question $ k \neq 4$
Answer: Not an answer, but an approach: Fix a $k$ and let $K := \lceil \frac{k}{e} \rceil$. Suppose $\left\{ \frac{k}{e} \right\} \ge \frac12$. We want to show that
\begin{align*}
\left(\frac{k}{\lfloor \frac ke \rfloor}\right)^{\lfloor \frac ke \rfloor} \le \left(\frac{k}{\lceil \frac ke \rceil}\right)^{\lceil \frac ke \rceil}
\end{align*}
Basic transformations (and the fact that $K = \lceil \frac ke \rceil = \lfloor \frac ke \rfloor + 1$) yield the equivalent inequality
\begin{align*}
K^K \le k \cdot (K - 1)^{K - 1}
\end{align*}
Now our assumption $\left\{ \frac{k}{e} \right\} \ge \frac12$ means $\frac ke \ge \lfloor \frac ke \rfloor + \frac 12 = K - \frac 12$. Hence
\begin{align*}
k \cdot (K - 1)^{K - 1} \ge e \cdot \left(K - \frac12\right) \cdot (K - 1)^{K - 1}
\end{align*}
Plugging this in above and transforming, we see that it is sufficient to show that
\begin{align*}
\left(\frac{K}{K-1}\right)^K \le e \cdot \frac{K - \frac12}{K - 1}
\end{align*}
Taking the reciprocal and multiplying by $e$, we get the equivalent inequality
\begin{align*}
\left(1 - \frac1K\right)^K \cdot e \ge \frac{K - 2}{K - 1}
\end{align*}
Both sides converge to $1$ as $K \to \infty$ (here the role of the constant $e$ becomes apparent).
If we want to prove the other case, i. e., $\left\{ \frac ke \right\} < \frac12$, we analogously arrive at
\begin{align*}
\left(1 - \frac1K\right)^K \cdot e < \frac{K - 2}{K - 1}
\end{align*}
I could not proceed from here since I don't know enough about the convergence of $(1+\frac xn)^n$. I am not even sure whether this helps at all, but I wanted to post it since it explains where the $e$ comes from.

Very challenging: max{floor,ceil}=?


Crash when redirecting stdout to stderr for a second time

Question: The second run of foo() will crash without an error message. When I remove this unsafe line, it works ok.
use std::process::{Command, Stdio};
use std::os::unix::io::FromRawFd;

fn foo() {
    let mut p = Command::new("ls");
    unsafe { p.stdout(Stdio::from_raw_fd(2)) };
    let mut child = p.spawn().expect("spawn error");
    child.wait().expect("wait error");
    println!("process: {:?}", p);
}

fn main() {
    foo();
    foo();
}

It seems the unsafe code here has some issue. Maybe it's not releasing some resource?
Is there a way to do the stdout -> stderr redirection without using unsafe code?
Answer: Stdio::from_raw_fd(2) gives ownership of file descriptor 2 to the newly constructed Stdio object. Stdio's destructor will close the file descriptor. Stdio's destructor will run when the Command is dropped, because the Command owns the Stdio.
Of course, the reason you're not getting any output on the second call to foo is that standard error has been closed!
The simple solution would be to duplicate file descriptor 2 and pass the duplicate to Stdio::from_raw_fd.
Comment: @Francis thanks! `libc::dup()` works here! @Shepmaster thanks for pointing this out, you're right ;)
Comment: The ownership semantics of this `unsafe` code is [clearly documented](https://doc.rust-lang.org/std/os/unix/io/trait.FromRawFd.html#tymethod.from_raw_fd). OP would be well-served by **completely reading** the documentation for any `unsafe` code they use.


Is there a largest large cardinal?

Question: In ZFC,  a cardinal is an isomorphism class of sets. However ZFC doesn't explicitly have classes; NBG, which is a conservative extension of ZFC does.
There is no largest cardinal by Cantors Theorem
There is no set of all sets - it is in fact a class.
Classes do not have cardinalities, as these have been only defined for sets - but if one could define a cardinality for classes - wouldn't this, in some sense be a 'limit' of all cardinals in Set, including all large cardinal axioms?
Thus, is it possible to extend the notion of cardinality in any significant way to classes?
Apologies for the loose phrasing of this question. It was originally going to be a posting on Philosophy.SE, but I thought I would get better answers here.
Comment: This is a very mathematical question in my opinion... I haven't done much set theory, but the question seems legit. +1
Comment: You almost answer your own Question, to the extent it is well posed.  Since cardinality is an equivalence relation on sets, it cannot be extended to a similar notion on classes in ZFC or NBG.  In other set theoretic frameworks the cardinality of the universal set is a valid construction, and does give a largest cardinal, for example [Quine's NF](http://en.wikipedia.org/wiki/New_Foundations#How_NF.28U.29_avoids_the_set-theoretic_paradoxes) (or the second edition of Quine's *Mathematical Logic* for a version with proper classes, an inessential extension).
Comment: "Wouldn't this, in some sense be a 'limit' of all cardinals in Set, including all large cardinal axioms?" No. Unless you mean "limit" in a trivial way, it would be something else. Maybe it would be useful from a mathematical point of view, who knows? Work on it for a while, prove some theorems, show us that it is useful, or convince yourself that it isn't. It would certainly not be a "largest large cardinal".
Comment: @Caicedo: Well, there isn't much point in replicating work thats already done; and theres no harm in asking if such work has been done, suggested or thought about. 'It would be something else' - sure thats why I said in *some sense*.
Comment: You need to define things first before we can make sense of them. As it stands, this is unanswerable.
Comment: @caicedo: An answer along the lines of 'Its a legitimate question. There is no prior art on this question; and on the basis of what is *already* known, there is no clear strategy that would work' is a perfectly legitimate answer; and is how I interpret both your and Patricks comments.
Answer:
If one could define a cardinality for classes - wouldn't this, in some sense be a 'limit' of all cardinals in Set...

Sure, if you modify the definitions to allow this then the cardinalilty of any proper class would be considered the largest cardinal.  (Cantor's proof would then only apply to cardinals that are sets.)  However, this is not very interesting.

... including all large cardinal axioms?

No, large cardinal axioms are quite different objects from cardinals, and the relationship between largeness of cardinals and "largeness" (strength) of large cardinal axioms is not as straightforward as you might think.  (And anyway, there is no largest large cardinal axiom because there is no maximal consistent recursive extension of $\mathsf{ZFC}$.)
Many examples of large cardinal axioms take properties of the class of cardinals, e.g. infinitude, regularity (closure under limits of short sequences,) and closure under power sets, and posit that some (set-sized) cardinal already has these property.  Large cardinal axioms therefore provide a sense in which the set/class distinction is made relative, rather than absolute.
This is why I said that the possibility of considering the size of a proper class as a "largest cardinal" is not interesting; if your model of $\mathsf{ZFC}$ is realized as $V_\kappa$ where $\kappa$ is an inaccessible cardinal in my model of $\mathsf{ZFC}$, then a proper class in your model is a set in my model.  Moreover, I can go even farther and define $V_{\kappa+1}$, $V_{\kappa+2}$, etc. So the large cardinal axiom "there is an inaccessible cardinal" transcends the notion of cardinals in $\mathsf{ZFC}$ to a much greater extent than the "one-step" extension of the notion of cardinals that you get by allowing proper classes.
Comment: There's also no largest large cardinal axiom because I can always "one up" any given axiom. If it's an axiom asserting a proper class of something, then I can say that there is an inaccessible cardinal that in $V_\kappa$ there is a proper class of that something; and if not then I can always say that $\kappa$ is "one up for $\varphi$" if $\kappa$ is an inaccessible cardinal larger than a cardinal satisfying $\varphi$. :-)
Comment: @Asaf Sure, although I'm not sure how to rule out the possibility that someday we may find a large cardinal axiom for which this natural strengthening results in inconsistency.  (I admit that this seems very unlikely.)
Comment: Well, strictly speaking, if you assume choice, Reinhardt cardinals are an example! :-)
Comment: @AsafKaragila Can you allow all consistent-with-ZFC large cardinals to exist simultaneously?
Comment: @Wakem: Sure...
Answer: Yes, you can extend the notion of cardinality to classes, and it is consistent that there is only one cardinal for classes (e.g. $V=L$ implies that all classes have the same size), or it is consistent that there are classes which are incomparable (e.g. if you add two Cohen subsets to a proper class of cardinals, the class of the pairs cannot be definably well-ordered and it is incomparable in size with the class of ordinals). If you agree to violate the axiom of choices then there are even more options here (classes incomparable with sets).
But I don't think there is a lot written on this topic, and it's scattered throughout many papers. Some obvious consequences here, some minor mentioning there.
As for being a large cardinal, there are two type of properties to consider here. Small properties, which only affect the sets below the cardinal (e.g. inaccessible cardinals) and large properties, which affect sets which are not smaller than the cardinals (e.g. measurable cardinals).  There are also very large properties which affect pretty much everyone in the universe (e.g. supercompact cardinals).
Since $\sf ZFC$ has a very limited access to proper classes, having the class ordinals as a large cardinal of a large property is meaningless. But you can easily have small properties by taking $V_\kappa$ for some $\kappa$ satisfying the wanted property and considering it as a model on its own. If $\kappa$ is a Mahlo cardinal, then in $V_\kappa$ every closed and unbounded set of ordinals includes an inaccessible cardinal.
Note that requiring that every class of ordinals which is closed [and unbounded] has an inaccessible cardinal actually requires less than a Mahlo ordinals and cutting off the universe, because we have less classes to worry about.
Another peculiar example is a Woodin cardinal. Being a Woodin cardinal is having a small property, which itself is a very large property (if $\kappa$ is a Woodin cardinal, it might not even be weakly compact, but $V_\kappa$ is incredibly rich in internally large cardinals). So you can think of the similar case where the ordinals behave like a Woodin cardinal to some extent. Although, I'm not sure why you would do that.
Answer: Being a large cardinal isn't a question of mere size, is a question of complexity.
Consider $\lambda<\kappa$ with $\lambda$ measurable and $\kappa$ simply strongly inaccesible. Then, $V_\kappa$ is a model of $\mathsf{ZFC}$, $\lambda$ is measurable in this model and as $|V_\kappa|=\kappa$, $\kappa$ is the largest "cardinal" in your sense, but from the outside $\kappa$ isn't very big (isn't measurable).
Answer: Well, currently, I believe the "largest" large cardinal axiom is "there exists a limit club Berkeley cardinal" i.e. "there exists a regular cardinal $\kappa$  so that $S(\kappa)$ and $\kappa$ is a limit of regular cardinals $\lambda$ so that $S(\lambda)$". Here, $S(\mu)$ is an abbreviation for "$\forall M \ni \mu$ and $C \subseteq \mu$ ($C$ is closed unbounded), there is an elementary embedding $j: M \to M$ with critical point $C$". Of course, one could naively extend beyond this point, but, so far, no "original" large cardinals which have a higher consistency strength than this have been found.

Is there a largest large cardinal?


Functional Purpose of Flattened 7th Chord

Question: I am wondering how to use the "flattened seventh" chord when used in a major key (i.e. B-flat Major chord in key C Major).  I believe this would put a piece in the mixolydian mode.  For example . . . I know that a diminished 7th essentially serves the same purpose as a V7 chord, but where do you go from the flattened 7th . . . how do you go to it?
Thanks!
Answer: In classical functional harmony, non-diatonic chords are usually diatonic to a related tonal center, so the answer is that it depends on what the local tonal center is.  Normally, the ♭Ⅶ chord will be taken from the parallel minor or a related key.  For example, it can be Ⅴ/♭Ⅲ, where ♭Ⅲ is the relative major of the parallel minor.
The first example that comes to mind, however, is the ♭Ⅶ in Begin the Beguine, which itself is the tonal center of the first phrase of the bridge: ⅱ/♭Ⅶ → Ⅴ7/♭Ⅶ → ♭Ⅶ.  Overall, the bridge shifts the tonal center, roughly in the parallel minor, from ⅰ (the same as ⅱ/♭Ⅶ) to ♭Ⅶ to ♭Ⅵ to Ⅴ.  These shifts are achieved by lowering the major third that ended the preceding phrase to the minor third:

ⅰ (= ⅱ/♭Ⅶ) → Ⅴ7/♭Ⅶ → ♭Ⅶ
♭ⅶ (= ⅱ/♭Ⅵ) → Ⅴ7/♭Ⅵ → ♭Ⅵ7

The next chord is a diminished seventh achieved by raising the root of the preceding chord by a half step.  This leads to ⅶ°7/Ⅴ and then to a period of alternation between various minor subdominant functions and the dominant, where the bridge ends.  The last phrase definitively reestablishes the major key by starting with the tonic Ⅰ chord.
Comment: This answer is correct. I'll just add that this technique is usually referred to as "mode mixture," the chords taken from the related key are called "borrowed chords."


How to derive the five-segment axiom of Tarski's geometry from Hilbert's axioms?

Question: We are trying to prove that in an arbitrary Hilbert plane (assuming Hilbert's axioms of Group I:Incidence, II:Order and III:Congruence https://en.wikipedia.org/wiki/Hilbert%27s_axioms), Tarski's axioms A1-A9 (https://en.wikipedia.org/wiki/Tarski%27s_axioms) for 2D neutral geometry hold.
It seems to be a folklore theorem, but we couldn't find a proper reference to a synthetic proof. We could prove most axioms but we have a problem with the five-segment axiom.
The five-segment axiom says that:
$${(x \ne y  \land  Bxyz  \land  Bx'y'z'  \land xy \equiv x'y' \land yz \equiv y'z' \land xu \equiv x'u' \land yu \equiv y'u')} \rightarrow zu \equiv z'u'$$
Using Hilbert's Foundations of Geometry theorem 14 (congruence of supplementary angles) and theorem 18 (Side-Side-Side) we can obtain the five segment axiom when u is not on line xy.
Does anyone know a reference for the proof of  Tarski's five segment axiom in the degenerated case when u is on line xy ?
Answer: We have found a proof and formalized it using the Coq proof assistant, the details are here: https://hal.inria.fr/hal-01332044
Comment: The proof of Pythagorean theorem from Tarski's axioms can be found in  Chapter 15 of "Metamathematische Methoden in der Geometrie", by Schwabhäuser,  Szmielew and Tarski. The formalization in Coq is here: http://geocoq.github.io/GeoCoq/html/GeoCoq.Tarski_dev.Ch15_lengths.html#pythagoras
Comment: There is no paper which describe our formalization of Desargues' theorem from Tarski's axioms. The proof that we formalized in the well known proof by Hessenberg which is also presented in "Metamathematische Methoden in der Geometrie". The formalization is here: http://geocoq.github.io/GeoCoq/html/GeoCoq.Tarski_dev.Ch13_6_Desargues_Hessenberg.html If you are curious about this proof, you can also have a look at :  http://argo.matf.bg.ac.rs/downloads/HessenbergsTheorem/10.1.1.544.3402.pdf
Comment: The proof of Desargues' theorem can be found on pages 139-142. Remark 13.16 says that the versions of theorem proved are special cases of the projective version. We have to distinguish the case when the lines are parallel or not.
Comment: Do you have the reference for the proof of Pythagoras's theorem using Tarski's axioms? (the proof is mentioned in the link, hence why I ask)
Comment: This paper explains how you used Tarski's axioms to prove Pappus's theorem: https://hal.inria.fr/hal-01176508/file/Pappus.pdf  -- which one shows how you used Tarski's axioms to prove Desargues's Theorem? I thought it might have been this one: https://hal.archives-ouvertes.fr/hal-01282550/file/arithmetization.pdf but it doesn't mention a proof of Desargues's Theorem.
Comment: Isn't that for projective geometry though, not Euclidean geometry? Or does the distinction not matter? I can look it up in "Metamathematische Methoden in der Geometrie" -- do you happen to know the page number?


Erro com View retornando um arquivo txt

Question: Estou usando o seguinte código em meu Controller:
public ActionResult geraBpa()
{
    var caminho = System.Web.HttpContext.Current.Server.MapPath("~/Content");
    StreamWriter file = new StreamWriter($"{caminho}/BPA.txt");
    List<bpac> listaBpac = pegaBpac();

    int linhaTexto = 1;
    int linhaItem = 1;

    foreach (bpac linha in listaBpac)
    {
        file.WriteLine(
        "02" +
        linha.cnes +
        linha.cmp + //competencia
        linha.cbo +
        string.Format("{0:000}", linhaTexto) + string.Format("{0:00}", linhaItem) +
        linha.pa +
        "000" +
        string.Format("{0:000000}", linha.quant) +
        "EXT"
        );

        linhaItem++;
        if (linhaItem > 99)
        {
            linhaItem = 1;
            linhaTexto++;
        }
    }

    linhaTexto++;
    linhaItem = 1;

    byte[] fileBytes = System.IO.File.ReadAllBytes($"{caminho}/BPA.txt");
    string fileName = "myfile.ext";
    return File(fileBytes, MediaTypeNames.Application.Octet, fileName);
}

Estou recebendo erro nessa linha:

byte[] fileBytes = System.IO.File.ReadAllBytes($"{caminho}/BPA.txt");

O erro diz que o arquivo BPA.txt está aberto. Quando fui até a pasta, vi que o mesmo nem foi criado corretamente.
Alguma ajuda?
Comment: Possível duplicata de [Arquivo txt abre no navegador ao invés de ser efetuado o download](https://pt.stackoverflow.com/questions/231227/arquivo-txt-abre-no-navegador-ao-inv%c3%a9s-de-ser-efetuado-o-download)
Comment: Humm no seu código não estou vendo fechamento do arquivo após sua abertura, talvez seja isso
Comment: Porfavor, poderia postar o erro que está dando ?
Comment: O arquivo é muito grande? Essa resposta do SO em inglês sugere que existe uma limitação de leitura utilizando esse método: https://stackoverflow.com/questions/2030847/best-way-to-read-a-large-file-into-a-byte-array-in-c. Considere utilizar um FileStream.
Answer: É exatamente este o problema, o arquivo já está aberto quando é feita a tentativa de leitura.
Seu código abre um StreamWriter e não o fecha. Você pode usar o método Dispose ou colocar o código que usa a variável file dentro de um using. Você pode ler sobre o using em Qual a utilidade do using?
Eu seguiria pelo segundo caminho, o código ficaria assim
var caminho = System.Web.HttpContext.Current.Server.MapPath("~/Content");
using(StreamWriter file = new StreamWriter($"{caminho}/BPA.txt"))
{
    List<bpac> listaBpac = pegaBpac();

    int linhaTexto = 1;
    int linhaItem = 1;

    foreach (bpac linha in listaBpac)
    {
        file.WriteLine(
        "02" +
        linha.cnes +
        linha.cmp + //competencia
        linha.cbo +
        string.Format("{0:000}", linhaTexto) + string.Format("{0:00}", linhaItem) +
        linha.pa +
        "000" +
        string.Format("{0:000000}", linha.quant) +
        "EXT"
        );

        linhaItem++;
        if (linhaItem > 99)
        {
            linhaItem = 1;
            linhaTexto++;
        }
    }
}

linhaTexto++;
linhaItem = 1;

byte[] fileBytes = System.IO.File.ReadAllBytes($"{caminho}/BPA.txt");
string fileName = "myfile.ext";
return File(fileBytes, MediaTypeNames.Application.Octet, fileName);

Comment: Oi, o código funcionou, porém abre na tela ao invés de fazer o download. Alguma sugestão?
Comment: Sim. Algumas sugestões. Não acha melhor abrir outra pergunta? Pra ser sincero, acho importante até porque eu gostaria de ter esse assunto catalogado em algum lugar.
Comment: Blz, abrirei sim.
Comment: https://pt.stackoverflow.com/questions/231227/arquivo-txt-abre-no-navegador-ao-inv%c3%a9s-de-ser-efetuado-o-download

Erro com View retornando um arquivo txt


How to get the individual exit codes of all the shell scripts invoked by a parent shell script?

Question: I am new to shell scripting and I am trying to invoke several shell scripts from a single parent shell script. Is there a way for me to get the exit codes of all the individual shell scripts(trying to know if they were successful or there was an error and may be save the exit codes to a file, if that's possible) after all the scripts have completed execution?
Any help would be appreciated. Thank you.
Answer: After each script finishes you can check the $? variable for its status.  But, this only reports the exit status of the last command run, so you need to check it after each script and then (perhaps) set other varaibles to reference when the entire series is finished.
Comment: Yeah, I was iterating over a directory structure, invoking the scripts in each folder. So, I think I can do it after each invoke.


Show that $e^{f(x)}$ is Riemann Integrable

Question: Suppose that $f:\mathbb{R} \to \mathbb{R}$ is Riemann Integrable and $f = 0$  for $f \notin [a,b]$. Show that $e^{f(x)}*\chi_{[a,b]}$ is Riemann Integrable.
I think this means that:
$g(x) = e^{f(x)} = e^{f(x)} $for$ a \leq x \leq b$ and $0$ otherwise
I am trying to find two step functions for showing this is a Riemann Integrable, I am trying to use $e^{(f(x))^2}$ as my upper step function but with little success, does anyone have any suggestions? Thanks
Comment: I am confused (syntactically and logically) by that $f=0$ condition
Comment: Sorry I missed a part of the question will edit above
Comment: Have you ben asked to tak this approach to prove it?
Answer: Hint: To find step functions for $e^{f(x)}$, you may assume suitable step functions for $f(x)$ given.
Comment: So I assume $\phi(x)$ and $\psi(x)$ are upper and lower step functions of $f(x)$ respectively. I am trying to show the supremum of $\sum|e^{f(x)} -e^{f(y)}||I_j| < \epsilon$ (as this is a method I have used before to prove $f^2$ is Riemann Integrable) Is this the next step?
Answer: We can use the following the result:
If $f(x)$ is Riemann integrable on $[a, b]$ and range of $f(x)$ is $[A, B]$ and $g(x)$ is continuous on $[A, B]$ then $g(f(x))$ is Riemann integrable on $[a, b]$.
The result is false if we don't assume continuity of $g$. Clearly if we assume the continuity of $g$ then we can see that the points of discontinuity of $g(f(x))$ are same as those of $f(x)$. Since $f(x)$ is Riemann integrable the discontinuities of $f(x)$ form a set of measure zero and therefore the discontinuities of $g(f(x))$ form a set of measure zero. It follows that $g(f(x))$ is Riemann integrable on $[a, b]$.
Here in the current question we have $g(x) = e^{x}$ which is continuous on any finite interval so that $e^{f(x)}$ is Riemann integrable.


Keeping a delta sync between Azure Storage blob containers

Question: I have three different Azure Storage blob containers that are used to serve website content, one for production, one for staging and one for development.
My goal is to sync staging and development on a daily or weekly basis so they match production.
I put together something in PowerShell that works in principal but it's slow and heavy handed. It involves deleting the staging and dev containers, then copying the entire production container twice. For just 20k items, this whole process takes over an hour.
Considering only a couple hundred items may change in a week, a delta operation would likely be done much faster.
Has anyone seen a tool or method that can do a delta copy between Azure Storage blob containers? I'll likely end up writing my own tool but wanted to see if there are any out there currently.
Comment: We used a variant of this: http://toolheaven.net/post/How-to-do-a-fast-recursive-local-folder-tofrom-azure-blob-storage-synchronization.aspx
Comment: had the same demand before and end up scripting a PowerShell runbook for this just like you, but yea, the drawback is that it's pretty slow when working with many files. I couldn't find any solution to do the job, but if you do, please post the answer here.
Answer: Unfortunately there isn't a good way to do this. As you have already seen tools like AZCopy will move the files for you, but they won't do a delta copy or sync.
You could do something yourself in PowerShell that ran through the blobs and checked if they exist in the destination and then compare something like the modified date or file hash, but I can't imagine that will be particularly quick either unfortunately.
Answer: I revisited the AzCopy tool today and found it's come quite a long way and serves this purpose perfectly.  The flag is AzCopy Sync and there are a number of control options as well, such as deleting destination files which don't exist on the target.
Probably due to improvements in the Azure architecture or infrastructure, this transfer is also incredibly fast.  It did an initial sync of 10GB in less than 60 seconds. Previously this would take an hour or more.
Answer: I know it's a bit of an old post but I just came across it and thought I'd throw an idea into the pot, is there a reason it needs to run daily/weekly? You could use something like a Logic App with a blob storage trigger or a function with a blob trigger? That would trigger instantly so the storage accounts are always in sync.
The other option would be to use the triggers to insert a delta into a storage account/database and then process the changes en-mass daily/weekly


Memory game show result after match

Question: I am trying to show result after match, but it compares after the third click event:
<code>(this.aHracieTlactika[i] == e.getSource())
</code>
and I want to compare after the second click event.
<code>    private int aPocitadlo = 1;
</code>
This is my method to check match of two arrays:
<code>    public boolean zhoda() {
            if (this.aHodnotaTlac[0] == this.aHodnotaTlac[1]) {
                return true;
            }
            return false;
        }

    public void actionPerformed(ActionEvent e) {
    int pom = 0;
    for (int i = 0; i < this.aHracieTlactika.length; i++) {

                if (this.aHracieTlactika[i] == e.getSource()) {
                    this.aHracieTlactika[i].setText("" + this.aHodnoty.get(i));
                    this.aHracieTlactika[i].setEnabled(false);
                    this.aPocitadlo++;
                    this.aPocetTahov += 1;

                    if (this.aPocitadlo == 3) {

                        if (this.zhoda()) {

                            this.aHracieTlactika[this.aTlacitkoIden[0]].setEnabled(false);
                            this.aHracieTlactika[this.aTlacitkoIden[1]].setEnabled(false);
pom += 1;
  if (pom == 1) {
      System.out.println("You win");
                        }
                        } else {

                            this.aHracieTlactika[this.aTlacitkoIden[0]].setEnabled(true);
                            this.aHracieTlactika[this.aTlacitkoIden[0]].setText("");
                            this.aHracieTlactika[this.aTlacitkoIden[1]].setEnabled(true);
                            this.aHracieTlactika[this.aTlacitkoIden[1]].setText("");
                        }

                        this.aPocitadlo = 1;

                    }

                     if (this.aPocitadlo == 1) {
                        this.aTlacitkoIden[0] = i;
                        this.aHodnotaTlac[0] = this.aHodnoty.get(i);
                    }

                    if (this.aPocitadlo == 2) {
                        this.aTlacitkoIden[1] = i;
                        this.aHodnotaTlac[1] = this.aHodnoty.get(i);
                    }
            }
        }
</code>
Comment: May you please reformulate ?
Answer: Keep a global clickCount variable that you increment every time someone clicks the button. Then say if(clickCount % 2 == 0) which returns true when click count is divisible by 2.

Memory game show result after match


Apply dynamic ACL with spring security and JWT

Question: I have implemented authentication using SpringSecurity, JWT and OAuth2.
@Override
public void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
    .antMatchers(HttpMethod.POST,"/v1/register").permitAll()
    .antMatchers(HttpMethod.GET,"/v1/public").permitAll();
    List<String> permisos = roleService.findPermisos();
    for(String name: permisos) {
        String[] data = name.split(",");
        http.authorizeRequests().antMatchers(data[0], data[1]).hasRole(data[2]);
    }
    http.authorizeRequests()
    .anyRequest().authenticated()
    .and().cors().configurationSource(corsConfigurationSource());
}

Currently the configure(HttpSecurity http) method works on the OAuth2 side. In my database I have all the @RestController to which they are allowed or denied access for each Role, the problem is, it is applied only once the app is compiled and I need is for it to be applied when I modify the allowed or denied access without the need to recompile a dynamic acl shown in List<String> permisos = roleService.findPermisos().
Searching I read that I can use Filters with HttpSecurity, I have not been able to find examples, your help please.
Answer: Doing some research I modified my solution as follows:
@Override
public void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
    .antMatchers(HttpMethod.PUT,"/v1/menu").permitAll()
    .anyRequest().authenticated().and()
    .addFilterAfter(new CustomFilter(), AbstractPreAuthenticatedProcessingFilter.class)
    .cors().configurationSource(corsConfigurationSource());
}

I add a Filter addFilterAfter(new CustomFilter(), AbstractPreAuthenticatedProcessingFilter.class) and in CustomFilter() is:
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
        throws ServletException, IOException {
        ServletContext servletContext = request.getServletContext();
        if(usuarioService == null){
            WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
            usuarioService = webApplicationContext.getBean(IUsuarioService.class);
        }
        String[] path = request.getRequestURI().split("/");
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Usuario usuario = usuarioService.findByEmail(authentication.getName());
        if(usuarioService.existsPermission(request.getMethod(), path[2], authentication.getName())) {
            filterChain.doFilter(request, response);
        } else {
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
        }
}

So I changed my solution from a loop to a query through a filter, the problem is that all the Rest must be registered and validated, this would be a problem to allow access to resources that I do not want to be verified.
Please, if you have a better solution, I would really appreciate your help.


Beginning sweep picking exercises

Question: What are some recommended easy exercises to start developing the sweep picking technique in guitar? And what advice would you give to someone who's just starting with this technique? I mean, what is important for me to keep an eye on, what should I focus on when starting, etc. Thank you very much for any help.
Answer: The best training I can think of is to use arpeggios starting with simple two/three string swept arpeggios and build up from there.  Here are Some practical examples:
A Minor 2 - 3 string arpeggio shapes
<code>$1.12  $1.8  $2.10  $1.8  $1.12  |  $1.12  $1.8  $2.10  $3.9  $2.10  $1.8  $1.12
</code>
A Major 2 - 3 string arpeggio shapes
<code>$1.12  $1.9  $2.10  $1.9  $1.12  |  $1.12  $1.9  $2.10  $3.9  $2.10  $1.9  $1.12
</code>
A Dim 2 - 3 string arpeggios
<code>$1.11  $1.8  $2.10  $1.8  $1.11  |  $1.11  $1.8  $2.10  $3.8  $2.10  $1.8  $1.11
</code>
The above shapes are enough to play the scale in two or three string(or a mixture of), swept arpeggios.   You can start from the highest note or the lowest note as you see fit and you can start from any point (mode) of the scale.  So in A minor you would be playing:
Am  -  Bdim  -  CM  -  Dm  -  Em  -  FM  -  GM -  Am
When picking dont worry about speed, start slowly and build over a period of time, the most important thing to worry about is clarity of the notes and keeping the distance between them even (timewise).
From here you can add more intervals to extend the arpeggios onto more strings:
A Minor 4 - 5 string arpeggio shapes
<code>$1.12  $1.8  $2.10  $3.9  $4.10  $3.9  $2.10  $1.8  $1.12  |  $1.12  $1.8  $2.10  $3.9  $4.10  $5.12  $4.10  $3.9  $2.10  $1.8  $1.12
</code>
A Major 4 - 5 string arpeggio shapes
<code>$1.12  $1.9  $2.10  $3.9  $4.11  $3.9  $2.10  $1.9  $1.12  |  $1.12  $1.9  $2.10  $3.9  $4.11  $5.12  $4.11  $3.9  $2.10  $1.9  $1.12
</code>
A Dim 4 - 5 string arpeggios
<code>$1.11  $1.8  $2.10  $3.8  $4.10  $3.8  $2.10  $1.8  $1.11  |  $1.11  $1.8  $2.10  $3.8  $4.10  $5.12  $4.10  $3.8  $2.10  $1.8  $1.11
</code>
Remember that these examples are all triad arpeggios with A in the root, the shapes stay the same on the guitar no matter which chord your using, so if you want to move to another arpeggio simple move to the root note that you need on whatever string your starting from and apply the triad shape you need.
Its a good idea to try and play some songs you already know using these shapes instead of the chords you were using (don't worry about losing an extension or two for now).

Beginning sweep picking exercises


VS code debug - is replacing object values with ellipses. How to show object values in debug?

Question: How can I get the debug console to display the actual values of the sorted object?
The result in the VS Code debug console display as below and are non expandable:
[{…}, {…}, {…}, {…}, {…}, {…}]
No debugger available, can not send 'variables'

Here is a simple program outputting a sorted object that I have written in VS Code.
const items = [
    { name: 'Edward', value: 21 },
    { name: 'Sharpe', value: 37 },
    { name: 'And', value: 45 },
    { name: 'The', value: -12 },
    { name: 'Magnetic', value: 13 },
    { name: 'Zeros', value: 37 }
  ];

// sort by value
items.sort(function (a, b) {
    return a.value - b.value;
  });

// console.log(items);

Here is the launch.json file:
{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": []
}

Comment: They both work well (utils.inspect looks a lot neater!) thanks.
Comment: Use `JSON.stringify` or `utils.inspect` if it's NodeJS (the latter provides options for inspection depth).
Comment: Yup, I stumbled across it accidentally only recently and it's been super-helpful working w/ deeply-nested JSON :)
Comment: Does this answer your question? [VSCODE: No debug adapter, can not send 'variables'"](https://stackoverflow.com/questions/61817528/vscode-no-debug-adapter-can-not-send-variables)
Answer: Important: This solution only works if you are using Node.js.
If you are using Node.js, you can use the built-in util.inspect() function.
First, you have to import it using require().
const util = require("util");

Then, you can call the inspect function. You need to pass in your object as a parameter.
const inspected = util.inspect(obj);
console.log(inspected);

Then, you can easily see the object without it being condensed! For more information, see the util.inspect() documentation.

If you are not using Node.js, you can use JSON.stringify(). You can simply use it as so, passing the object as a parameter.

const obj = [
  { name: "Edward", value: 21 },
  { name: "Sharpe", value: 37 },
  { name: "And", value: 45 },
  { name: "The", value: -12 },
  { name: "Magnetic", value: 13 },
  { name: "Zeros", value: 37 }
];

console.log(JSON.stringify(obj));

This should allow you to inspect it properly.
Answer: Stringify worked but the output for mine is ugly AF! vscode really sucks in this regard!


How can System.out.printIn() accept integers?

Question: So I started learning java several days ago and got a question. For the next expression:
String foo=123;

is not allowed. However, in System.out.printIn(), we can use something like:
int x=5;
System.out.println(x);

Since implicitly assigning a integer to a string is not allowed, why the expression above works? Anyone can give a detailed explanation? I'm also wondering when can we use this kind of  implicit thing and when we cannot.
Answer: The reason you can call println with an integer is because the method is overloaded. Basically  there are more than one method called println and one of them accept an integer.
Take a look here: PrintStream
Comment: Why JDK 1.4.2 as reference? We are already in JDK 7 and 8 is soon to be released. Perhaps a reference to JDK 6 or 7 would be better.
Answer: There are so many overloaded methods of the PrintStream System.out:
println(boolean x)
println(char x)
println(int x)
println(long x)
println(float x)
println(double x)
println(char x[])
println(String x)
println(Object x)

Comment: @user1229490 It will use the `Object.toString()` method of whatever you pass to it.
Comment: What is (Object x)? A template of any kinds of objects?
Answer: The static member out of the class System is a PrintStream which has a method with the signature println(int).
Answer: Look at the API for PrintStream (System.out is a PrintStream). It has methods println(), println(boolean), println(char), println(char[]), println(double), println(float), println(int), println(long), println(Object) and println(String). This is called method overloading (scroll down to find the section on method overloading).
If you want to create a String from an integer literal, you can either put quotes around it  (String s = "123";) or use Integer.toString (String s = Integer.toString(123);) or String.valueOf (String s = String.valueOf(123);).
Answer: Im assuming you mean't println not printin , java has a println function for each datatype, so you can call println on booleans, ints, strings, ect and it will select the right function.
of course you cannot assign an integer to a string variable because they are different types.


Spring RestTemplate Equivalent

Question: I am using Spring Resttemplate and have an issue about generics: Generics with Spring RESTTemplate I want to look at other equivalent libraries that I can handle that situation.
Are there any other choices?
Answer: You can use the Jersey Framework (which has both client and server REST APIs): http://jersey.java.net/nonav/documentation/latest/client-api.html

Spring RestTemplate Equivalent