Limiting number of input values in an array/list in Python

Question: I'm obtaining input values in a list using the following statement:
ar = map(int, raw_input().split())

However, I would want to limit the number of inputs a user can give at a time. For instance, if the limit is specified by a number n, the array should only capture the first n values entered during the program.
e.g: if n = 6,
Input:
1 2 3 4 5 6 7 8 9 10

On performing 'print ar', it should display the following without any error messages:
[1, 2, 3, 4, 5, 6]

Comment: And it should ignore the rest of the input?
Answer: If you want to ignore the rest of the input, then you can use slicing to take only the first n input. Example -
n = 6
ar = map(int, raw_input().split(None, n)[:n])

We are also using the maxsplit option for str.split so that it only splits 6 times , and then takes the first 6 elements and converts them to int.
This is for a bit more performance. We can also do the simple - ar = map(int, raw_input().split())[:n] but it would be less performant than the above solution.
Demo -
>>> n = 6
>>> ar = map(int, raw_input().split(None, n)[:n])
1 2 3 4 5 6 7 8 9 0 1 2 3 4 6
>>> print ar
[1, 2, 3, 4, 5, 6]

Comment: Bravo! Thanks, that's a quite elegant solution, just what I wanted. I'm quite new to python, and slicing is quite a fresh concept for me.
Comment: Actually I found that using the statement: 'ar = map(int, raw_input().split())[:n] ' works as well. Arguments don't have to be provided for the split() function call.
Comment: Yes, I have explained that in my answer. My first solution was that. But then for a bit more performance I gave the current solution.
Comment: With simple slicing like that you would be taking all the numbers in the input , splitting them all, and then converting them all to int before slicing and getting the first `n` results.
Comment: Ah ok, can't see how I missed that!
Answer: How about indexing ar to just the 6th element? Technically, it's to the 7th element, as newarray will slice up to, but not including nth element
ar = map(int, raw_input().split())
print ar
#[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

newarray=ar[0:6]
print newarray
#[1, 2, 3, 4, 5, 6]

This should allow for unlimited input
Answer: I was looking for a solution to the same question.
I figured out what I can do below is my solution.
bookid = []
M = int(input())
S = input().split()
for i in range(M):
    books.append(S[i])
print(booksid)

But I think it's definitely not the most effective way to do it but easy.


ffmpeg: programmatically use libavcodec and encode and decode raw bitmap, all in just few milliseconds and small compressed size on Raspberry Pi 4

Question: We need to compress the size of the 1024x2048 image we produce, to size of about jpeg (200-500kb) from raw 32bits RGBA (8Mb) on Raspberry Pi 4. All in c/c++ program.
The compression needs to be just in few milliseconds, otherwise it is pointless to us.
We decided to try supported encoding using ffmpeg dev library and c/c++ code.
The problem we are facing is that when we edited example of the encoding, provided by ffmpeg developers, the times we are dealing are unacceptable.
Here you can see the edited code where the frames are created:
for (i = 0; i < 25; i++)
{
#ifdef MEASURE_TIME
        auto start_time = std::chrono::high_resolution_clock::now();
        std::cout << "START Encoding frame...\n";
#endif
    fflush(stdout);

    ret = av_frame_make_writable(frame);
    if (ret < 0)
        exit(1);

    //I try here, to convert our 32 bits RGBA image to YUV pixel format:

    for (y = 0; y < c->height; y++)
    {
        for (x = 0; x < c->width; x++)
        {
            int imageIndexY = y * frame->linesize[0] + x;

            uint32_t rgbPixel = ((uint32_t*)OutputDataImage)[imageIndexY];

            double Y, U, V;
            uint8_t R = rgbPixel << 24;
            uint8_t G = rgbPixel << 16;
            uint8_t B = rgbPixel << 8;

            YUVfromRGB(Y, U, V, (double)R, (double)G, (double)B);
            frame->data[0][imageIndexY] = (uint8_t)Y;

            if (y % 2 == 0 && x % 2 == 0)
            {
                int imageIndexU = (y / 2) * frame->linesize[1] + (x / 2);
                int imageIndexV = (y / 2) * frame->linesize[2] + (x / 2);

                frame->data[1][imageIndexU] = (uint8_t)U;
                frame->data[2][imageIndexV] = (uint8_t)Y;
            }
        }
    }

    frame->pts = i;

    /* encode the image */
    encode(c, frame, pkt, f);

#ifdef MEASURE_TIME
        auto end_time = std::chrono::high_resolution_clock::now();
        auto time = end_time - start_time;
        std::cout << "FINISHED Encoding frame in: " << time / std::chrono::milliseconds(1) << "ms.\n";

#endif
    }

Here are some important parts of the previous parts of that function:
codec_name = "mpeg4";

codec = avcodec_find_encoder_by_name(codec_name);

c = avcodec_alloc_context3(codec);

c->bit_rate = 1000000;
c->width = IMAGE_WIDTH;
c->height = IMAGE_HEIGHT;
c->gop_size = 1;
c->max_b_frames = 1;
c->pix_fmt = AV_PIX_FMT_YUV420P;

IMAGE_WIDTH and IMAGE_HEIGHT are 1024 and 2048 corresponding.
The result I have ran on Raspberry Pi 4 look like this:
START Encoding frame...
Send frame   0
FINISHED Encoding frame in: 40ms.
START Encoding frame...
Send frame   1
Write packet   0 (size=11329)
FINISHED Encoding frame in: 60ms.
START Encoding frame...
Send frame   2
Write packet   1 (size=11329)
FINISHED Encoding frame in: 58ms.

Since I am completely green in encoding and using codecs, my question will be how to do it the best way and correct way, meaning the way which would reduce timing to few ms, and I am not sure the codec was chosen the best for the job, or the pixel format.
The rest of the meaningful code you can see here (the encode() function you can find in the ffmpeg developer example I gave link to above):
void RGBfromYUV(double& R, double& G, double& B, double Y, double U, double V)
{
    Y -= 16;
    U -= 128;
    V -= 128;
    R = 1.164 * Y + 1.596 * V;
    G = 1.164 * Y - 0.392 * U - 0.813 * V;
    B = 1.164 * Y + 2.017 * U;
}

Answer: I used this :
int RgbToYuv(uint8_t *rgb, AVCodecContext *pCodecCtx, AVFrame * pFrame)
{
enum AVPixelFormat yuv420p_pix_fmt = AV_PIX_FMT_YUV420P, bgra_pix_fmt = AV_PIX_FMT_BGRA;
// Allocate video frame
//pFrame=av_frame_alloc();
// Allocate an AVFrame structure
AVFrame * pFrameRGB = av_frame_alloc();
if(pFrameRGB==NULL) return 0;
// Assign appropriate parts of buffer to image planes in pFrameRGB
// Note that pFrameRGB is an AVFrame, but AVFrame is a superset
// of AVPicture
avpicture_fill((AVPicture *)pFrameRGB, rgb, bgra_pix_fmt, pCodecCtx->width, pCodecCtx->height);
// initialize SWS context for software scaling
SwsContext *sws_ctx = sws_getContext(pCodecCtx->width,
pCodecCtx->height,
bgra_pix_fmt,
pCodecCtx->width,
pCodecCtx->height,
yuv420p_pix_fmt,
SWS_BILINEAR,
NULL,
NULL,
NULL
);
// Convert the image from its native format to RGB
sws_scale(sws_ctx, (uint8_t const * const *)pFrameRGB->data, pFrameRGB->linesize, 0, pCodecCtx->height, pFrame->data, pFrame->linesize);
//  konvertering går mot høyre

av_frame_free(&pFrameRGB);

return 1;

}
Not super fast but it worked


Confused by apparently confusing question on limit...

Question: Question: Let $f: R \rightarrow R$ be defined by
$$
f(x) = \begin{cases}
x & \text{if $x$ is an integer} \\[6px]
0 & \text{if $x$ is not an integer}
\end{cases}
$$
Find $\lim_{x \rightarrow 1} f(x)$.
My answer:
$\lim_{x \rightarrow 1^{-}}f(x)$ here we approach $f(x)$ from left and encounter fractions (decimals), $\{0.9,0.99,0.99,\dotsc\}$ so, the $\lim_{x \rightarrow 1^{-}}f(x)=0$
Similar logic for right hand limit and it also gives $0$.
My confusion:
But, while calculating limit, is it not that we can simply put $x=1$ in to the appropriate function provided in the question?
So, $\lim_{x \rightarrow 1}f(x)$ here, can't we put $x=1$ and get the result of limit as $1$?
As in the following photo, we chose appropriate function and put $x=1$.
Comment: "But, while calculating limit, is it not that we can simply put $=1$...". NO!
Comment: I edited a piece of the text, please modify the rest by yourself. It's an exercize to learn the basis of latex
Comment: okay, egreg you beat me on time ahah
Answer:
My confusion: But, while calculating limit, is it not that we can simply put $=1$ in to the appropriate function provided in the question?

What you're asking is whether $\lim_{x\to a} f(x) = f(a)$ is always true.  The answer is no.  In fact, this exercise is designed to highlight that difference.  And you might consider why we would need limits at all if this were true.
Your first answer, using the heuristic notion of evaluating $f$ at points closer and closer to $1$, but not equal to $1$, is the correct one.
It is true that $\lim_{x\to a} f(x) = f(a)$ for certain functions, the ones we call continuous functions.  Linear functions and polynomials are continuous functions.  That property is the one being invoked in the example photo you added.  But the original function you provided is not such a nice function, and is definitely not continuous.
Comment: I overcame confusion, for x<1, x>1(very near values to 1 towards right and left) we have f(x)=0 function. after choosing the function, (as the function is a constant function f(x)=0) whatever we input, it gives 0. Thank you for the help.


Por que consigo alterar arrays sem referência fora do escopo em C#?

Question: Quando quero que uma função altere o valor da variável fora da função, eu uso a palavra-chave ref, como no exemplo:
public void Alterar(ref string input) {
    input += "mundo!";
}

string olamundo = "Olá, ";
Alterar(ref olamundo);

Na função acima o valor de olamundo será Olá, mundo!, pois Alterar(string) alterou sua propriedade passada com referência. Veja funcionando no .NET Fiddle.
Se remover ambos ref no código acima, ele funcionará, mas o resultado final será apenas Olá, .
O que ocorre é que, quando o tipo do parâmetro é um array, a palavra-chave ref não é mais necessária. Seu valor é passado como referência automaticamente. Veja um exemplo:
public static void AlterarArray(int[] input) {
    input[1] = 10;
}

int[] teste = new int[] {1, 2, 3, 4, 5};
AlterarArray(teste);
Console.WriteLine(string.Join('\n', teste));

// 1
// 10
// 3
// 4
// 5

Veja funcionando o código acima no .NET Fiddle.
Por que é naturalmente desnecessário usar ref quando usando arrays como parâmetros? E como evitar que essa coleção seja alterada ao passar como parâmetro, garantindo que será a mesma que entrou?
Answer: Na verdade a melhor pergunta seria:

Por que a string se comporta assim?

E já foi respondido em Como passar string por referência?.
Um array é um tipo por referência, então o comportamento normal é o dele, como passa a referência em vez de passar o objeto, qualquer alteração feita no novo contexto acontece no objeto original e não em um novo objeto. Tudo simples e fácil de entender se entende como funciona tipos por referência: Qual a diferença entre Struct e Class?.
Também pode ser útil: Alocação de memória em C# - Tipos valor e tipos referência.
A questão é justamente a exceção da string que é explicada pela imutabilidade. Este tipo é por referência por otimização, mas a semântica ele é por valor, então ele se comporta como um int ou outro tipo por valor. Se quer usar a referência real tem que fazer igual em um tipo por valor, usar o ref.
O array em si não tem como proteger. Tem como não aceitar um array e aí sim proteger, por exemplo usar ReadOnlyCollection. Tente:
using System;
using System.Collections.ObjectModel;

public class Program {
    public static void AlterarArray(ReadOnlyCollection<int> input) {
        input[1] = 10;
    }

    public static void Main() {
        int[] teste = new int[] {1, 2, 3, 4, 5};
        AlterarArray(Array.AsReadOnly(teste));
        Console.WriteLine(string.Join('\n', teste));
    }
}

Veja não funcionando no .NET Fiddle. Também coloquei no GitHub para referência futura.
Ainda é o possível usar uma coleção imutável desde o início, que vai se assemelhar ao tipo string, inclusive com os contras.
O array é um tipo que não deveria ser muito usado pensando no mais conceitualmente correto. Na prática o próprio .NET obriga fazer isto em alguns casos, mas não porque ele quer isso, é porque não valia o esforço de mudar tudo no .NET 2.0 quando pode fazer de uma forma melhor.
O array resolve bem várias situações, mas ele tem vários problemas. Mais uma vez a falta de tempo para lançar e ter copiado do Java fez o C# ter alguns defeitos.
Percebeu que para ter um tipo por referência imutável ou só de leitura teve que fazer um tipo mais abstrato? O normal da linguagem é o array. Uma pena.


Finding Lyapunov function for Lorenz system - what did I wrong?

Question:
For constants $a,b,c > 0 $
we're given the Lorenz-System:
$$\begin{cases}x'=a(y-x) \\ y'=bx -y - xz \\z'= xy -cz\end{cases}$$

I just want to find a Lyapunov function and don't know what I've done wrong:
Use $L(x,y,z)=x^2+ay^2+az^2$
We know that $$\dot L=\nabla L \cdot f= 2\begin{pmatrix}x \\ ay \\az\end{pmatrix}\cdot\begin{pmatrix}a(y-x) \\ -bx-y-xz \\xy-cz\end{pmatrix}$$
Edit:
As Robert mentioned :
$\dot L  =-4ax^2+(2ab+4a)xy-2ay^2-2acz^2 $
So
$2x+2ay+2az=-4ax^2+(2ab+4a)xy-2ay^2-2acz^2$
$x+ay+az=-2ax^2+(ab+2a)xy-ay^2-acz^2$
Comment: It should be $\dot{L} = -4\,{x}^{2}a+ \left( 2\,ab+4\,a \right) yx-2\,a{y}^{2}-2\,ac{z}^{2}$
Comment: @RobertIsrael: Thank you ! :D
Comment: @ Robert Israel: Would you check my edit, please ?
Answer: For a global Lyapunov function $L$ you want $\dot{L} \le 0$ for all $x,y,z$.  In this case, if $a > 0$ and $c > 0$ the quadratic form $−4ax^2+(2ab+4a)xy−2ay^2−2acz^2$ is negative semidefinite if and only if
$ b^2 + 4 b - 4 \le 0$, i.e. $ -2 - 2 \sqrt{2} \le b \le -2 + 2 \sqrt{2}$.


Are $h$-eigenspaces of infinite-dimensional $sl(2,\mathbb C)$-modules of dimension at most $1$?

Question: Let $(\pi,V)$ be an irreducible representation of the Lie algebra $sl(2,\mathbb C)$ on a possibly infinite-dimensional complex vector space $V$. Further let $h,e^+, e^-$ be the usual standard basis where $h$ is the semisimple matrix $\begin{pmatrix} 1 &0\\0&-1\end{pmatrix}$.
Now, if $V$ is finite-dimensional, the usual argument goes like this: the operator $\pi(h)$ has at least one eigenvector $v_0$ and from there one finds $h$-eigenvectors with distinct eigenvalues by applying $\pi(e^+)$ resp. $\pi(e^-)$ several times to $v_0$. (I am not very precise here)
Since $V$ is finite-dimensional one deduces that (because $\pi(h)$ can have only finitely many eigenvalues) this way one gets finitely many nonzero vectors which are $h$-eigenvectors and their span is an invariant subspace of $V$ which equals $V$ since $V$ is irreducible. In particular one sees that $V$ is $h$-semisimple and $h$-multiplicity free (in other words: $V$ is the direct sum of the nonzero $h$-eigenspaces and every nonzero eigenspace is one-dimensional).
My question: 1) I am now interested in $V$ an infinite-dimensional and irreducible representation of $sl(2,\mathbb C)$. Is it then also true that $V$ is $h$-semisimple and $h$-multiplicity free and is there a fairly elementary way to argument? Actually I guess in general a module will not be $h$-semisimple (we cannot even garantue the existence of one $h$-eigenvalue), so I guess I should ask if $h$-semisimplicity implies that in the decomposition of $V$ into $h$-eigenspaces any eigenspace is of dimension $1$?
'Add'-it: 2) Just to make sure my understanding is correct (it is probably not), but is it right that in general we cannot assume that the operator $\pi(h)$ is diagonalizable on $V$? So whenever in a text I read 'let $V = ..$' be the eigenspace decomposition of $V$ into eigenspaces of $\pi(h)$, the text is probably only treating the finite-dimensional case.
3) Assuming we have given one $h$-eigenvector $v_0$ with $h$-eigenvalue $\lambda$ and $V$ is infinite-dimensional, we can again deduce that the submodule $V_0$ generated by $v_0$ is $h$-semisimple and if $V$ is additionally irreducible, then of course $V$ itself is $h$-semisimple.
I have read that under the additional assumption that $v_0$ is also an eigenvector for the Casimir element $C$, then all eigenspaces in $V_0$ are one-dimensional, but I don't understand why. Also, when is it the case that $C$ acts as scalar multiple of the identity on $V$?
Comment: The keyword you want to look up is "category O."
Comment: @QiaochuYuan Irreducible objects of $\mathcal{O}$ for $\mathfrak{sl}_2$ are indeed multiplicity free, so the subtle part of the question has to do with weight modules that are not in $\mathcal{O}$.
Answer: 1) This is part of the classification problem of weight-$sl_2$-modules, whose solution is attributed to Gabriel and can be found in Dixmier's Algèbres enveloppantes (7.8.16). Britten and Lemire classified all simple multiplicity-free weight modules [Britten, D.J., Lemire, F.W. A classification of simple Lie modules having a 1-dimensional weight space, Trans.Am.Math.Soc. 299, 1987].
2) When a text writes "Let $V=\bigoplus_\lambda V_\lambda$" be the eigenspace decomposition of $V$, ..." then the text only and exactly assumes that $V$ has an eigenspace decomposition. By the way, $V$ is then called weight module.
If $V$ is irreducible, it is in particular indecomposable, which implies that all $\lambda$ lie in a single $\mathbb{Z}\alpha$-coset of $\mathfrak{h}^*$.
3) Yes, given one $h$-eigenvector $v_\lambda$, the universal enveloping algebra $\mathcal{U}(sl_2)$ generates a before mentioned weight module.
4) Let  $\{ e_+, e_-, h'\}$ be the dual basis of $\{e^+, e^-, h\}$ of $sl_2$ with respect to the Cartan-Killing form $B(x, y) = \mathrm{trace}(\mathrm{ad}(x)\mathrm{ad}(y))$. Then
$$C = hh'+ e_-e^- + e_+e^+$$
commutes with any $g\in sl_2$ and is called Casimir element. Thus the Casimir element $C$ is in the center $\mathcal{Z}(\mathfrak{g})$ of $\mathcal{U}(\mathfrak{g})$ and acts by diagonal matrices $\pi(c)$.
Actually, for semisimple $\mathfrak{g}$ the center $\mathcal{Z}(\mathfrak{g})$ of $\mathcal{U}(\mathfrak{g})$ is isomorphic to the polynomial ring over $\mathbb{C}$ in $\mathrm{rank}\,\mathfrak{g}$ variables [cf. Carter, Lie algebras of finite and affine type, Thm 11.32]. In our case of $sl_2$ this is just $\mathbb{C}[C]$.
The stated additional condition of $C$ acting by a scalar, say $Cv_0=\xi\cdot v_0$ implies now that on the generated module $V_0 = \mathcal{U}(sl_2)v_0$, the Casimir element $C$ will also act by scalars: $c(e_\pm v_0)=e_\pm cv_0= \xi\cdot (e_\pm v_0)$.
Next, let's equip the module $V_0$ with the action $hv_0 = \lambda v_0$, for some $\lambda\notin\mathbb{Z}$, and $e_-v_n := fv_n = (n+\varepsilon)v_{n+1}$ for $\varepsilon\in (0,1)$.
Lemma. If $n > 0$, then
$
(i)\; hv_n = (\lambda -2n)v_n\\
(ii)\, ev_n = (\lambda - n + 1)v_{n-1}\\
$
Proof.
(i) By induction on $n$:
$h\left(fv_n\right) = fhv_n + \left[h,f\right]v_n = f(\lambda -2n) v_n - 2fv_n = \left(\lambda -2(n+1)\right)\left(fv_n\right)$
(ii)
$$\left(n+\varepsilon\right)ev_{n+1} = efv_{n} = fev_n+\left[e,f\right]v_{n}\\
=\left(\lambda-n+1\right)fv_{n-1}+hv_{n}\\
=\left(\lambda-n+1\right)\left(n-1+\varepsilon\right)v_{n}+\left(\lambda-2n\right)v_{n}\\
=\left(\lambda-n\right)\left(n+\varepsilon\right)v_{n}$$
for $n\ge 0$. Now divide by $\left(n+\varepsilon\right)$.
q.e.d.
Now, we can extend the action of $e=e_+$ for $n \le 0$. This is consistent with the action of $h$, as demonstrated by
$h(ev_n)=ehv_n + [h,e]v_n = e(\lambda - 2n) v_n + 2ev_n  = (\lambda -2(n-1))(ev_n).$
Surely, these modules are infinite-dimensional for $0 < \varepsilon < 1$ and their weight-spaces are one-dimensional.
Since $V_0$ is generated by the vector $v_0$ with $h$-action $\lambda$, the Harish-Chandra homomorphism $\phi:\mathcal{U}(\mathfrak{g})_0 \to \mathcal{U}(\mathfrak{h})$ allows to determine the central character from the the h-action on $v_\lambda$: $\chi_\lambda: \mathcal{Z}(\mathfrak{g}) \to \mathbb{C}$ by $\chi_\lambda(z) = \lambda(\chi(z))$. This is due to the fact, that $\mathcal{U}(\mathfrak{h})$ is isomorphic to a polynomial ring, in the $sl_2$-case just $\mathbb C[h]$ where $\lambda: \mathbb C[h] \to \mathbb C$ is just the evaluation homomorphism.


Linux guest graceful shutdown in Hyper-V

Question: What mechanism Hyper-V use to signal a Linux guest to gracefully shut down?
Somehow CoreOS does gracefully shut down, but another Linux doesn't (it is just abruptly powered off)
Comment: Do you have the Hyper-V Guest Integration Services installed?
Comment: They are only kernel modules, and they all are already in the mainline kernel and loaded on my box. So yes, I have them installed and operating.
Answer: I figured it out. drivers/hv/hv_util.c calls orderly_poweroff() from kernel/reboot.c which subsequently fails to find /sbin/poweroff and does only a minimal cleanup.
Answer: If i am not mistaken, Hyper v integration is what causes this. I have not used CoreOS but usually this is what causes your virtual server to shutdown correctly.
In terminal, issue the command lsmod. On CoreOS you will (if i am right) see that it lists Hyperv services(hv_vmbus, hv_netvsc, etc) on the other it does not. Some Linux distros come with it built in and others you can add it.
If this is not it, comment below and i will delete this answer.
Comment: I have the modules loaded. They are in mainline kernel, so only distributions with very old kernels need backported modules from MS.
Answer: This does not answer your question as detailed, as you might want to know. I want to add this as an answer nonetheless, as the detailed technical answers comes close to be off-topic (non-supported environment).
You want to look at the documentation of Linux and FreeBSD Virtual Machines on Hyper-V on what distributions are supported. Check the section of the individual distribution and version and see, if the Core is supported.

Core
  Integrated shutdown:
  With this feature, an administrator can shut down virtual machines from the Hyper-V Manager. For more information, see Operating system shutdown.
Source: Feature Descriptions for Linux and FreeBSD virtual machines on Hyper-V

If the distribution is not supported, it is not advised to use them in production. Even if there are ways to implement support on a non-listed distribution.
Comment: I didn't say that you would not have a right to know.
Comment: It's all open source (including code from Microsoft), so I have the right to know. Whether it's supported it is ittelevant as I'm not seeking support and just educating myself. I run a non-production Linux anyway.


How to configure spotless google formatter to format braces

Question: How to configure spotless google formatter to format braces in 2 lines instead of a single line
-    void contextLoads() {}
+    void contextLoads() {
+    }

Answer: You can't. From google-java-format's README:

Note: There is no configurability as to the formatter's algorithm for formatting. This is a deliberate design decision to unify our code formatting on a single format.


Confirmation of Proof: For some $v\in\mathbb{Z}$, $12v^2 - 4v + 3$ is never a square.

Question: I am trying to prove that $\sqrt{3}$ is irrational. I can use modulo, and the Fundamental Theorem of Algebra (FTOA), but I decided to approach it a little bit differently this time: I decided to use some quadratics.
It is quite long, but it is unfinished, as there is this one part I need to prove:

That for some $v\in\mathbb{Z}$, namely the set of all integers, $12v^2 - 4v + 3$ is never a square.

I have no idea how to approach this. What are some useful skills or knowledge I should know about square numbers or similar (quadratic) problems? I would really appreciate a hint, but full answers are acceptable.
Thank you in advance.
Answer: $$12v^2-4v+3\equiv-1\pmod4$$
But for any integer $a,$ $$a^2\equiv0,1\pmod4$$
Comment: @user477343 If $a$ is even then $a=2n$ and $a^2=4n^2=0 \mod 4$. If $a$ is odd then $a=2n+1$ and $a^2=4n^2+4n+1=1 \mod 4$.
Comment: Why is this the case? Is this a well-known theorem?
Comment: @user477343, Sorry for being late. Hope you have understood the method now.
Comment: @gandalf61 thank you for telling me. I quite figured that out anyway, but if it was not for your comment, I would have forgotten to tick this answer, haha.
Comment: Very good answer. If you explained just a little bit more, it would have been ideal. Congratulations, nonetheless! $$(+1) \ \ \color{green}{\checkmark}$$
Comment: No problemo :) ${}$
Answer: $$
12v^2-4v+3=n^2\Rightarrow v = \frac{1}{24}\left(4\pm\sqrt{16-16 \times 3(3-n^2)}\right)
$$
but
$$
1-3(3-n^2) \ge 0\Rightarrow n^2 \le \frac{8}{3}\Rightarrow n^2\le 2\Rightarrow n \in \{0, \pm 1\}
$$
Comment: I like your approach, and in using the quadratic formula, we see that values $n=0$ and $n=\pm 1$ do not yield $v\in\mathbb{Z}$, proving that there are no integer solutions. However, I am not too familiar with inequalities (and I think it should be $n\in\{0,\pm 1\}$ as opposed to $n=\{0,\pm 1\}$) so that is why I did not tick this answer. But thank you anyway for stretching out my perspective :) $$(+1)$$
Comment: Your notation is more exact an I will change it. Thanks.
Comment: No problemo :) ${}$


Testing Mac App Store app on real device - How to export?

Question: I have been developing Mac App Store and iOS apps for several years now. I don't event want to know how many hours, days or weeks (?) I spend by solving provisioning problems...
One of my Mac apps targets OS X 10.7+. While everything works fine in genereal, after the last update some users reported problems when using the app on 10.7. Other OS X version work fine.
In the past, I simply cloned the project from my developing computer (iMac) to my MacBook running the specific OS X version. I then opened the project in Xcode, ran it and check what the problem was. This is far to easy for Apple, since this not possible any more.
The project only compiles (due to several reasons) in Xcode 7+ only. Xcode 7 runs on 10.10+, thus testing on 10.7 is not possible.
I have been trying to build/export the app to test it on my MacBook the whole day without any success. The app simply does not start on 10.7 on my MacBook. Of course the MacBook is a registered devices, included in my provisioning profiles, etc.
This is my workflow:

Removed all App Store specific entitlements from the app in Xcode/Target/Capabilities
Created new wildcard certificates and provisioning profiles that does not include any App Store specific entitlements
Selected the new profiles in Xcode/Target/Build Settings/Code Signing
Run Product/Archive
In Organizer select the Archive and click on Export

Here I tried several different combination (signing, no signing, etc.). No matter if I choose Export a Developer-Signed Application or Export as a Mac Application the result is always the same.
When I copy the created App file to my MacBook und start it nothing happens. The icon flashes once and this is all. Only the Console gives I hint about the Problem:

killed com.mycompany.myapp because its use of the com.apple.developer.team-identifier entitlement is not allowed.

Great... As explained I removed all entitlement from the app and from the profiles. Where the hack does this entitlement come from and how do I get rid of it?
Is there no way to test the App with all its features (== all entitlement) on another device?
Answer: I should have answered my own question earlier. Back in January I was somehow able to get the app running on my other Mac. Now I had to solve the same problem and it took some time to dig out the correct solution again.
So, maybe this will help others to solve the same problem. At least it will help my future-me to remember what has to be done :-)

Archive the app just as you would prepare the app to be submitted to the App Store.
Switch to the Organizer and select the just created archive
Select Export... instead of Upload to App Store...
Select Export a Developer ID-signed Application(second option). DO NOT select Export a Development-signed Application (third option). Actually I have no idea what's the difference is, but only the first one works...)
Click Next and the Organzier will fetch provisioning information from your dev account. DO NOT select the fetched provisioning profile but select Use local signing assets from the dropdown box instead
Click Choose and Export in the next step.
Done

Good luck and happy app signing...


Can we output individual form items within a Layout?

Question: We are using Layouts (via mytheme.layouts.yml) to create regions for our Node Edit forms.  This looks something like...
edit_nodelayout:
  label: 'Edit Node Layout'
  category: edit
  path: templates/panels
  template: edit-nodelayout
  default_region: toplayout
  regions:
    toplayout:
      label: 'Top'
    details:
      label: 'Details'
    other:
      label: 'Other'

We have placed each field for the content-type into the appropriate region via the admin UI.  At least one of our fields is a reference field to a Paragraph entity-type.
In our template, which is defined in the yml as /templates/panels/edit-nodelayout.html.yml, we are currently outputting all content as full regions.
{# some html here #}
{{ content.toplayout }}

{# some html here #}
{{ content.details }}

{# some html here #}
{{ content.other }}

How would we access individual items within a region?  For example, if within the content.details region, we have placed a field called "Foo", how do we output that individually?  We have tried this...

Please enter everything you know about Foo

{{ content.details.foo }}

This becomes interesting when the field called "Foo" is a reference to a Paragraph entity-type.  How would we then output individual fields within "Foo" entity?

Output the "bar" field within the "foo" Paragraph type

{{ content.details.foo.bar }}

Any help, pointers to documentation appreciated.
Answer: That is not how you're supposed to use layout templates as those should be for for placing content, just like normal Drupal regions, and then modify the output using field and node templates. The general idea being to be able to reuse the templates in other places and as such reducing the number of templates needed.
Of course you can output content directly in the layout template. I would recommend you install the Twig Tweak module. You can then use {{ dd() }} to see what is available to you. As an example you can display a field value like this:
{{ node.field_myfield.value }}

It depends on what you want to display, but that's the general idea, very similar to the node template.


APACHE httpd.conf error

Question: I have recently installed the latest Apache.
It is working fine through localhost:80 and through 10.0.0.51:80, but I can't connect through [External IP]:80.
I have forwarded ports correctly, but I don't know if it has something to do with the httpd.conf file.
So here is a link to my httpd.conf file.
Comment: Are you behind a firewall or a NAT device?
Comment: No. I just believe there is something to do with the http.conf file
Answer:
Ensure that your apache is listening on every address:

get this in your conf:
Listen 0.0.0.0:80

check it from console:
$ netstat -luntp | grep :80

I would change ServerName to the IP (I'm not an expert, but I think it gives better results with external IPs):
ServerName localhost:80

Then, visit the internal ip of the server 10.0.0.51:80 and ensure it's showing ok.
Now, ensure that you are redirecting the ports correctly, and check it visiting your external IP address outside your network (with a phone, o similar, so your router/firewall doesn't get in the way out) and

if the browser says connection interrupted, it's probably a firewall issue
if the browser is waiting too long, could be a firewall issue, or something in your apache configuration.

APACHE httpd.conf error


Why does default .gitignore suggest ignoring config directory?

Question: In Drupal 8, perhaps the most anticipated feature is separation of configuration from content. It achieves this by storing configuration changes in a sites/default/config_* folder.
Why then does the default .gitignore file suggest ignoring this directory?
If I make changes to the site, I want those changes to be tracked to push them to the live site, or merged with another developer's changes.
Comment: If you want to add an exception to include your site config folder in the main Drupal repo, I found adding this line works: `!sites/*/files/config_whateverrandomstring` (no trailing slash or asterisks)
Comment: Have no idea why Drupal even ships with a .gitignore - the choice of version control has nothing whatsoever to do with Drupal.  I had expected it to be removed in 8.
Comment: @Derrick your exception doesn't run if you don't add an asterisk to the main ignored folder:

This is OK:
> sites/default/files/*
> !sites/*/files/config_whateverrandomstring

This is NOT OK
> sites/default/files/
> !sites/*/files/config_whateverrandomstring
Answer: You are supposed to put that in a separate repository, I suppose. Note that the best practice workflow is to export the configuration and git the staging directory. You are not supposed to edit the active directory to the best of my understanding.
Edit: since writing this answer the default storage is now in the database and there's no more active directory.
Comment: See http://drupal.stackexchange.com/questions/85635/what-is-the-suggested-workflow-for-migrating-cmi-configuration-from-dev-sta
Comment: You *must* only add the staging directory and copy the files from active to it. The import process is required so systems can re-act to configuration changes (like creating the necessary field tables when you add a new field).
Comment: That makes sense!  Thanks.  Though for a small site, I'm not convinced the additional repo and export/staging step is worth the extra effort so I think I will just keep everything in one.  Change config? git add, git push, done.  New core updates?  Git pull/merge, done.  Though certainly not as clean as separating into two repositories - theoretically its a simpler and faster workflow.
Comment: That said, adding the staging directory to the same repository is IMHO fine. The .gitignore does not specifically mention the config directories at all, they're just excluded together with all other files, which is correct. It is now quite easy to move the config folder outside of files and only ignore the active directory.
Comment: Ohhhhh.... that bursts my bubble - was expecting/hoping that Drupal reacts to file changes in the active config folder in real-time, thus allowing a pure Git workflow to pull/merge from other developers.   Thx for clarifying Berdir.   I guess this workflow is almost achieved, just need to run a drush command to export config before a commit, and then again to import after pulling a commit.


How to make loadByProperties or entityQuery case sensitive for field value

Question: Neither loadByProperties or entityQuery are case sensitive. How to make it case sensitive? I'm using MySQL as a database but would rather have a portable solution if possible.
With LoadByProperty
$nodes = $this->entityTypeManager()
              ->getStorage('node')
              ->loadByProperties(['field_myfield' => $value]);

With entityQuery
    $entity_ids = \Drupal::entityQuery('node')
        ->condition('field_myfield',$value)
        ->execute();

You can, of course, build your own query as explained in this answer. But my question is specifically about using loadByProperties or entityQuery API.
Answer: It was this long issue thread, they add sensitive case support to entityQuery.
So instead of = operation you can use = BINARY or instead of LIKE you can use LIKE BINARY.
Try this:
$entity_ids = \Drupal::entityQuery('node')
  ->condition('field_myfield',$value, '= BINARY')
  ->execute();

Comment: Thanks! But no luck with loadByProperties? I don't understand why the API provide entityQuery AND loadByProperties to be honest. I like API when their is one obvious way to do things. I will strictly use entityQuery in the future.


How to run alter query to modify mysql database using hook_schema?

Question: I want to change data-type of a field in for a particular table in database. I  want to use hook_schema_alter() to do so.
The ALTER query is:
ALTER TABLE `abcd` CHANGE `session_number` `session_number` INT( 255 ) NOT NULL COMMENT 'Session number to get number.'

Is it possible to implement such query using hook ? If yes please guide me.
Tonnes of thanx in advance.
Comment: You shouldn't do that in `hook_schema_alter()`. `hook_schema_alter` is to alter the schema definition but it won't be able to modify the database for you. You need to implement that in `hook_enable()` which will invoke during enabling your custom module.
Comment: I have multiple instances for same code means same project running for 2 different places . Thats why am thinking to use hook_schema_alter(). Moreover, how to user hook_enable to implement db alteration ?
Answer: Changes to the schema are typically handled with hook_update_N and you will normally locate this file in the module.install file.
For example with the update from Drupal 6.x-7.x the some of the base permissions were rename:
/**
 * Rename blog and forum permissions to be consistent with other content types.
 */
function system_update_7000() {
  $result = db_query("SELECT rid, perm FROM {permission} ORDER BY rid");
  foreach ($result as $role) {
    $renamed_permission = $role->perm;
    $renamed_permission = preg_replace('/(?<=^|,\ )create\ blog\ entries(?=,|$)/', 'create blog content', $renamed_permission);
    $renamed_permission = preg_replace('/(?<=^|,\ )edit\ own\ blog\ entries(?=,|$)/', 'edit own blog content', $renamed_permission);
    $renamed_permission = preg_replace('/(?<=^|,\ )edit\ any\ blog\ entry(?=,|$)/', 'edit any blog content', $renamed_permission);
    $renamed_permission = preg_replace('/(?<=^|,\ )delete\ own\ blog\ entries(?=,|$)/', 'delete own blog content', $renamed_permission);
    $renamed_permission = preg_replace('/(?<=^|,\ )delete\ any\ blog\ entry(?=,|$)/', 'delete any blog content', $renamed_permission);

    $renamed_permission = preg_replace('/(?<=^|,\ )create\ forum\ topics(?=,|$)/', 'create forum content', $renamed_permission);
    $renamed_permission = preg_replace('/(?<=^|,\ )delete\ any\ forum\ topic(?=,|$)/', 'delete any forum content', $renamed_permission);
    $renamed_permission = preg_replace('/(?<=^|,\ )delete\ own\ forum\ topics(?=,|$)/', 'delete own forum content', $renamed_permission);
    $renamed_permission = preg_replace('/(?<=^|,\ )edit\ any\ forum\ topic(?=,|$)/', 'edit any forum content', $renamed_permission);
    $renamed_permission = preg_replace('/(?<=^|,\ )edit\ own\ forum\ topics(?=,|$)/', 'edit own forum content', $renamed_permission);

    if ($renamed_permission != $role->perm) {
      db_update('permission')
        ->fields(array('perm' => $renamed_permission))
        ->condition('rid', $role->rid)
        ->execute();
    }
  }
}

Comment: This is true for database tables the module itself defines. If a module wants to change the database tables defined from another module, it should implement `hook_schema_alter()`.
Comment: For my own knowledge going forward, would this hook also by best kept in the `module.instal`l file? and how many times will the `hook_schema_alter` hook run?
Comment: Drupal looks for `hook_schema_alter()` in the .install file of the module. It is called every time a module calls `drupal_get_schema()` and Drupal cache for that has been cleared, for example because a module was disabled or enabled.
Comment: I think you are correct with the use of `hook_schema_alter` to manage the changes in `$schema`, but the actual `db_change_field` call should be handled within `hook_install` or `hook_update_X` as these hooks allow for better deployment management. A module should not have be disabled/enabled for updates/changes take effect.
Answer: As you mentioned you are having single Drupal code base for multiple sites. I assume that you only want one of the sites having schema change. So you need a separate module for altering schema.
You need to implement hook_schema_alter() and hook_enable() in .install file of your custom module.
/**
 * Implements hook_enable().
 */
function mymodule_enable() {
  // other_module is the module name which define the schema of 'abcd' table.
  $schema = drupal_get_schema_unprocessed('other_module', 'abcd');
  db_change_field('abcd', 'session_number', 'session_number', $schema['fields']['session_number']);
}

/**
 * Implements hook_schema_alter().
 */
function mymodule_schema_alter(&$schema) {
  $schema['abcd']['fields']['session_number'] = array(
    'type' => 'int',
    'size' => 'tiny',
    'not null' => TRUE,
    'default' => 0,
    'description' => 'Session number to get number.',
  );
}

Please note that 'size' => 'tiny' means 1 byte size for integer type. More details can be found here.
Comment: Code is same for multiple sites. I want to run it on each site. Huge thankx...


Reading an Encrypt file

Question: I am writing an application that encrypts a list of Employee into a text file. I was able to encrypt the Employees list to a text file. When I try to decrypt it back, I am getting some error saying

java.lang.ClassCastException: com.reading.employee.blueprint.Employee cannot be cast to java.base/java.util.List

This is an example of the code I am working on.
private static byte[] encryptingAFile(List<Employee> list) {
    byte[] empList, textEncrypted = null;

    try {
        ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
        ObjectOutputStream object = new ObjectOutputStream(byteArray);

        KeyGenerator keygenerator = KeyGenerator.getInstance("AES");
        SecretKey myDesKey = keygenerator.generateKey();

        Cipher desCipher;
        desCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        String s;

        for (Employee employee: list) {
            object.writeObject(employee);
        }

        empList = byteArray.toByteArray();
        desCipher.init(Cipher.ENCRYPT_MODE, myDesKey, new IvParameterSpec(new byte[16]));
        textEncrypted = desCipher.doFinal(empList);

        Files.write(Paths.get("Encrypt.txt"), textEncrypted);

        desCipher.init(Cipher.DECRYPT_MODE, myDesKey, new IvParameterSpec(new byte[16]));
        byte[] textDecrypted = desCipher.doFinal(textEncrypted);

        ByteArrayInputStream bis = new ByteArrayInputStream(textDecrypted);
        ObjectInputStream ois = new ObjectInputStream(bis);
        List<Employee > result = (List<Employee>) ois.readObject();

        System.out.println(result.toString());

    }
    catch (InvalidKeyException in) {
        System.out.println(in);
    }
    catch (Exception e) {
        System.out.println(e);
    }
    return textEncrypted;
}

I was hoping that someone could help me.
Answer: When you write the objects to the ObjectOutputStream, you write each Employee one at a time, you don't write a single list object. So when you read them back in, you don't get a single list object back. Either you need to write the whole list to the stream in the first place, or you need to read the Employee objects back one at a time.
Comment: @William the point made is that while you are encrypting the `Employee`s one at a time, you're trying to decrypt the object as a `List` which is why you get a ClassCastException.
Comment: Is there an example you could show me how to read it back one at a time, please. I am little new to java, and this is actually my first time encrypting and decrypting a file.
Comment: Thank so much for hint. I did what your told me and it work!.

Reading an Encrypt file


Seemingly impossible square root solution

Question: How is this equation possible? Maybe its the fact that I'm $20$ hours into a $40$ hour cram session, but this just doesn't make sense to me.
It's a standard Arc Length equation, $c(t)= (4-2t)\hat{\textbf{i}} +\ln(4t)\hat{\textbf{j}}+(5+t^2)\hat{\textbf{k}}$
I'm down to the point of finding the magnitude of $C'$ for the integral, but I'm stuck at this point
$(4+(\frac{1}{t^2})+4t^2)^{\frac{1}{2}}$ My solution guide says this is equal to $\frac{2t^2 + 1}{t}$ but I just don't see it, please help.
Comment: $$4+ \frac{1}{t^2}+4t^2 = \frac{4t^2 + 1 + 4t^4}{t^2} = \frac{(2t^2)^2 + 2(2t^2)+1}{t^2} = \frac{(2t^2+1)^2}{t^2}$$
Answer: $$ 4 + \frac{1}{t^2} + 4t^2 = \frac{4t^2 + 1 + 4t^4}{t^2} = \frac{(2t^2 + 1)^2}{t^2} = \left(\frac{2t^2 + 1}{t}\right)^2$$
So the square root is as given.
Answer: The solutions given by George and Achille are very clear.
It's also beneficial to recognize your answer as a potential quadratic from the get go. Rearrange in order of descending powers to factor it more clearly:
$$\left(4t^2+4+\frac{1}{t^2}\right)^{\frac{1}{2}}$$
$$\left(\left(2t+\frac{1}{t}\right)^2\right)^{\frac{1}{2}}$$
Since $t>0$,
$$2t+\frac{1}{t}$$
$$\frac{2t^2 +1}{t}$$


The 'publish on' date must be in the future

Question: Is there a way to set the content to be published on future time instead of future date. I get the message "The 'publish on' date must be in the future" when trying to set publish date to today but late at night.
Comment: Bala, I think your edit to this question changes the question's meaning, and I'm not sure I agree with it.  I don't think the original author said that "Whenever the node is trying to publish during night time i get this message." I think they simply said they get this when they schedule it for later in the day TODAY.
Comment: @Boriana that's correct, as soon as we put the date and time, and try to save the content it comes up with that message.
Answer: Under

admin/config/content/scheduler

you can set your date format. What have you set here? Has the date format included time formatting?
The publish time has to be added after the date (that is today).
Comment: Can you provide us with a non-working example? Another source for the error could be another time-zone set up (Server, your drupal default time zone and user-specific time-zones).
Comment: yes I have configured the date and time to d-M-Y H:i:s, I and yes I did add time after the date
Comment: for some weird reasons the embargo is now working fine. Just tested now when trying to recreate the problem. Thanks
Comment: Fine. You may try to test towards the date that isn't working and see if there are discrepancies with your time-zones. (Another common mistake is to set the publish date to 0:00h and expect this to be midnight that day... which isn't ;o)


Is there compress option for exportListener in Marklogic Java Client API?

Question: I want export all the documents from my marklogic db using Data Movement SDK . I exported successfully as files but i want to compress them in zip file through DMSDK. I searched in the documentation regarding compress option but didn't find any.
Updated Code
public class Extract {
    static // replace with your MarkLogic Server connection information

    DatabaseClient client =
              DatabaseClientFactory.newClient("x", x,
                                              "x", "x",
                                              Authentication.DIGEST);

    private static String EX_DIR = "F:/JavaExtract";

    // Loading files into the database asynchronously
    public static void exportByQuery() {
         DataMovementManager dmm = client.newDataMovementManager();
        // Construct a directory query with which to drive the job.
        QueryManager qm = client.newQueryManager();
        StringQueryDefinition query = qm.newStringDefinition();
        query.setCollections("GOT");

        // Create and configure the batcher
        QueryBatcher batcher = dmm.newQueryBatcher(query);
        batcher.withBatchSize(1000)
        .withThreadCount(10)
        .onUrisReady(
            new ExportListener()
                .onDocumentReady(doc-> {
                    String uriParts[] = doc.getUri().split("/");
                    try {
                       FileOutputStream dest = new
                             FileOutputStream("F:/Json/file.zip");
                           ZipOutputStream out = new ZipOutputStream(new
                             BufferedOutputStream(dest));
                           ZipEntry e = new ZipEntry(uriParts[uriParts.length - 1]);
                           out.putNextEntry(e);

                           byte[] data = doc.getContent(
                                   new StringHandle()).toBuffer();
                           doc.getFormat();
                           out.write(data, 0, data.length);
                          out.closeEntry();

                          out.close();

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }))
               .onQueryFailure( exception -> exception.printStackTrace() );

        dmm.startJob(batcher);

        // Wait for the job to complete, and then stop it.
        batcher.awaitCompletion();
        dmm.stopJob(batcher);
    }

    public static void main(String[] args) {
        exportByQuery();
    }
}

When i am running it is taking only the last document in GOT collection and keeping in zip rather than taking all.
Any Help Is Appreciated
Thanks
Answer: You're really close.  Just use standard Java zip writing rather than Files.write.  The top two answers here look really good: How to create a zip file in Java
Another option is WriteToZipConsumer.  That would replace all your code in the onDocumentReady call.
[UPDATE based on updated question]
Your onDocumentReady listener is run for each document, so I'm guessing it doesn't make sense to create a new FileOutputStream("F:/Json/file.zip"); for each document.  That's why you're only seeing the last document when you're done.  Try moving these two lines to before you initialize your batcher:
                       final FileOutputStream dest = new
                         FileOutputStream("F:/Json/file.zip");
                       final ZipOutputStream out = new ZipOutputStream(new
                         BufferedOutputStream(dest));

That way they'll only run once.
Also, move this until after dmm.stopJob(batcher);:
                      out.close();

Also, surround your listener code in a synchronized(out) {...} block so the threads won't overwrite each other as they write to the stream.  Remember, your listener code is going to run in 10 threads in parallel, so your code in the listener needs to be thread-safe.
Comment: I can able to implement zip but it is taking only last file in collection. I kept my code in updated section.Any help is really helpful.


Regarding to the size() in setup() function

Question: Why I can use size(1920, 1080) in setup()
but If I use
setup()
  visualContext = new VisualContext(
    new Area(0, 0, 1920, 1080),
    new Area(158, 150, 1340, 950)
  );
  size(visualContext.getGlobalArea().getWidth(), visualContext.getGlobalArea().getHeight());

There will be an error
When not using the PDE, size() can only be used inside settings().
Remove the size() method from setup(), and add the following:
public void settings() {
  size(1920, 1080);
}

I can not find any doc about this topic.
Curious, can size only be initialized by constant but variable?
Answer: use settings if you want to invoke size with parameters.
VisualContext visualContext = new VisualContext(
    new Area(0, 0, 1920, 1080),
    new Area(158, 150, 1340, 950)
  );

void settings() {
  size(visualContext.getGlobalArea().getWidth(), visualContext.getGlobalArea().getHeight()); //<>//
}

https://processing.org/reference/settings_.html


Submartingale convergence (Durrett 5.3.1)

Question: Exercise 5.3.1 in Durrett's "Probability Theory and Examples" states
Let $X_n$, $n\ge 0$, be a submartingale with $\sup X_n < \infty$. Let $\xi_n=X_n-X_{n-1}$, and suppose $E(\sup \xi_n^+)<\infty$. Show that $X_n$ converges almost surely.
Here are my thoughts:
It looks like we need to use theorem 5.2.8 (Martingale convergence theorem), which states that $X_n$ converges almost surely if $\sup EX_n^+<\infty$. I am trying to understand why we can just do the following (or at least I'm guessing we can't):
Suppose $X_n > 0$ (edit: on some set with positive measure), then $0< \sup X_n < \infty$, and therefore $EX_n^+ \le \sup X_n < \infty$. So we're done.
Otherwise, if $X_n \le 0$ a.e., then $\sup X_n^+ = 0$ a.e. Once again, we're done.
Am I missing something? Since I didn't use all the information, I probably am.
Thanks for the help.
Comment: Actually I think you can, but I also think the point of the problem was to get you to try to use Theorem 5.3.1 and deduce that $P(D) = 0$.
Answer: You've stepped off a cliff in deducing that the expectation $E(X^+_n)$ is bounded above by the random variable $\sup_n X_n$.
Suggestion: Employ the argument used by Durrett in the proof of his Theorem 5.3.1. Fix a  positive real $K$, define the stopping time $T=T_K$ to be the first time $n$ that $X_n$ is larger than $K$, and observe that the stopped process satisfies
$$
X_{n\wedge T}\le K+\sup_m\xi_m^+,
$$
so that
$$
E(X_{n\wedge T})\le K+E(\sup_m\xi_m^+)<\infty,\qquad\forall n.
$$
Now apply the submartingale convergence theorem to the stopped process. This yields a.s. convergence of $X_n$ on the event $\{T_K=\infty\}=\{\sup_mX_m\le K\}$. Finally, vary $K$.
Comment: By this I simply meant use the fact that $\cup_{K=1}^\infty\{\sup_mX_m\le K\}=\{\sup_m X_m<\infty\}$ has probability 1. You've shown that $(X_n)$ converges a.s on each piece $\{\sup_mX_m\le K\}$, $K=1,2,\ldots$, so it converges on their union.
Comment: I'm probably 6 years late, but I cannot understand the part where K is varied ?
Comment: oh !! got it. thanks a lot.
Comment: The convergence theorem requires $\sup E(X_n^+)< \infty$. Could you explain how to get $\sup E(X_{n \wedge T}^+) < \infty$? Could it has both infinity positive part and negative part?
Comment: I could just as well have noted (and should have) that $X_{n\wedge T}^+\le K+\sup_m\xi_m^+$.


What good is a VHD backup if you can't boot the Machine in Virtual PC?

Question: I've read that you cannot boot from the VHD backups that Vista Ultimate / Server 2008 creates.  However you can mount them with vhdmount.
So if you can't boot it then what good is the VHD backup over a regular compressed file backup and system restore?
Answer: Microsoft uses a technology called Volume Shadow Copy to make these backups. It's a very clever approach because it allows full volume sector-by-sector backups (like a Ghost image) that can be stored incrementally. If you backup every day, each additional copy only consumes the space required to store the changes, yet still looks like a full stand-alone image.
The combination of VHD (a convenient pre-existing disk image format) and Volume Shadow Copy makes it trivial to restore to any point in time (that you have a backup of).
Why are these image (or sector-based) backups useful?
1) Sector-based backups are orders of magnitude faster than file-based ones. In a sector-based backup the disk heads are moving sequentially whereas in a file-based backup the heads are moving randomly. In many cases this means the difference between backups being able to complete overnight or not.
2) You can do a complete system restore simply by booting from the Vista/Windows 7 DVD and going through the option of recovering your system. This covers scenarios like failed hardware or malware damaging your OS.
3) They are very space-efficient. Think of a 100 MB database file. If you do incremental file-based backups, every new backup will consume 100 MB. On the other hand, a sector-based incremental backup will only consume the space necessary to store the changes to the 100 MB file, which could be as small as a single sector.
Microsoft's use of the VHD format was a logical choice that saved them creating a new format -- a laudable approach in my opinion (the less "standards" the better). Think about it; with VHDMount I can now mount full-disk backups AND Virtual PC/Hyper-V virtual disks -- what's not to like? Nowhere in all that is the implication that an image of a computer will boot on completely different hardware (which is what Virtual PC/Hyper-V are equivalent to).
Comment: Thanks for the explanation.  All of those are very solid reasons, I have to admit however that I was disappointed when I found that I couldn't simply run the VM from the VHD.  It seems at the least I ought to be able to do a system restore to VirtualPC or different hardware.  Is that possible?
Answer: I think the idea behind it is that if using Hyper-V, you can quickly move it to another Hyper-V server and mount it to another Virtual server.
Comment: I can see how that would make sense in a enterprise environment with Server 2008 machines but why on Vista?  Maybe it's just one of those things that Microsoft does that doesn't make sense.  But I was hoping for something more convenient for the non-enterprise user.
Comment: Looks like Windows 7 support booting these and mounting them.

http://en.wikipedia.org/wiki/VHD_(file_format)#Windows_7_support_for_native_VHD_boot
Comment: This works if you set it up that way from scratch but you cannot do this from a VHD produced from a backup of a physical machine.


Query not returning expected result

Question: I'm new to sql and I'm running the query below
<code> var Pprofile = "SELECT A.POLICY_PROFILE as POLICY_PROFILE,A.STATUS_CODE1,A.EFF_DT, A.END_EFF_DT,E.OTHER_STRING10,E.DISPLAY_EMPLOYEE FROM  EMPLOYEE E , ASGNMT A " +
    "WHERE E.DISPLAY_EMPLOYEE = A.LD1 AND " +
"POLICY_PROFILE = 'LOCAL_51' AND A.STATUS_CODE1 = 'A' " +
    " ORDER BY E.DISPLAY_EMPLOYEE, A.EFF_DT ASC";
</code>
The problem is that is returning all the different "effective dates records" for all the employees as shown in the picture. I only want to get the last  effective date record created for each different user. query result
Please I need help with my query which probably can be written much better, but at end I would like to just get the last effective date record, no all of them.
Thank You!
Comment: See https://meta.stackoverflow.com/questions/333952/why-should-i-provide-an-mcve-for-what-seems-to-me-to-be-a-very-simple-sql-query - and we don't need to see this java stuff or whatever that concatenation is.
Answer: Something like this
<code>drop table if exists t;
create table t(id int, eff_dt date);
insert into t values
(1,'2017-01-01'),(1,'2017-01-01'),(1,'2017-02-01'),
(2,'2017-01-01');

select t.*
from t
where t.eff_dt = (select max(t1.eff_dt) from t t1 where t1.id = t.id);
</code>

Query not returning expected result


Covering the plane with compact sets

Question: Let $X$ be a non-empty compact subset of the plane and $\{Y_{\alpha}\}$ a family of pairwise disjoint compact subsets of the plane each of which intersects $X$ in a singleton. Is it possible to choose $X$ and $\{Y_{\alpha}\}$ such that $X\cup\bigcup_{\alpha}Y_{\alpha}$ covers the plane?
If the compactness constraint on the sets $Y_{\alpha}$ were dropped then a solution would be to take $X$ as the closed unit disc and the sets $Y_{\alpha}$ as the spokes radiating from the boundary of the disc.
But in my case, the sets $\{Y_\alpha\}$ have to be compact. I suspect that I am asking the impossible of $X$ and $\{Y_{\alpha}\}$ but I have not been able to prove this.
Answer: Here's a construction for the special case where the compact set $X \subset \mathbb R^2$ has the same cardinality as $\mathbb R$, for example if $X$ contains an open ball. We can take the index set $\{\alpha\}$ to be $X$ itself (because your requirements yield one subset $Y_\alpha$ for each $\alpha \in X$).
Each $Y_\alpha$ will be a two point set, hence compact: the point $\alpha \in X$, and one other point $\beta(\alpha) \in \mathbb R^2 - X$ depending on $\alpha$.
I'll use the fact that the sets $X$ and $\mathbb R^2 - X$ are both in one-to-one correspondence with $\mathbb R$ and hence in one-to-one correspondence with each other. Choosing a bijection $\beta : X \to \mathbb R^2 - X$, as $\alpha \in X$ varies the sets $Y_\alpha = \{\alpha,\beta(\alpha)\}$ satisfy your requirements.
Comment: Thank you very much. You do surprise me!

Covering the plane with compact sets


If $K(\zeta,\beta)/K$ is the splitting field for $f$, what can we say about $K(\zeta,\beta)/K(\zeta)$?

Question: Problem setup:

Let $n\in\mathbb{N}$ and let $K$ be a field whose characteristic does not divide $n$. The splitting field of $f=x^n-c$ ($c\not=0$) over $K$ is $K(\zeta,\beta)$ where $\zeta$ is a primitive $n$-th root of unity. Put $E=K(\zeta,\beta)$. What can we say about $[E:K(\zeta)]$?

Overall goal: I am working on a problem (with the same assumptions) where we assume $n=2^k$, and show $[E:K]$ is a power of $2$. We take the following steps:

Step 1: Assume $\zeta\in K$ and show that all irreducible factors of $f$ have degree $[E:K]$. Conclude that $[E:K]$ divides $n$.

I was able to do this fairly easily: first let $g$ be an irreducible factor of $f$, then let $\beta$ be a root of $g$. Since $\zeta\in K$, we have $E=K(\beta)$. Since $g$ is irreducible, $[E:K]=[K(\beta):K]=\deg(g)$. Since the degree of $f$ is the sum of the degrees of its irreducible factors, we know $[E:K]$ divides $n$.

Step 2: Assume $\zeta\not\in K$, suppose $n=2^k$, and show $[K(\zeta):K]$ is a power of $2$.

There is a more general result that says $[K(\zeta):K]$ divides $\phi(n)$ where $\phi$ is Euler's totient function (see here). Applying this, we obtain $[K(\zeta):K]$ divides $\phi(n)=\phi(2^k)=2^{k-1}$, so $[K(\zeta):K]$ is a power of $2$.
Where I get stuck/main question:

Final step: Apply steps (1) and (2) to show that if $n=2^k$, then $[E:K]$ is a power of $2$.

From step (1), the result follows quickly if $\zeta\in K$, since $[E:K]$ will divide $n$, a power of $2$, and hence $[E:K]$ will also be a power of $2$. I am getting confused about the case when $\zeta\not\in K$. If this is the case, then step (2) says $[K(\zeta):K]=2^\ell$ for some $\ell\leq k-1$. From the Degree Formula for Field Extensions, we have (let $\beta$ be a root of $f$):
$$
[E:K]=[K(\zeta,\beta):K]=[K(\zeta,\beta):K(\zeta)][K(\zeta):K]=[K(\zeta,\beta):K(\zeta)]2^\ell.
$$
If $[K(\zeta,\beta):K(\zeta)]$ is a power of $2$, we will be done. This leads me to my main question of this whole post, what can we say about $d=[K(\zeta,\beta):K(\zeta)]$? I know that if $f$ were irreducible over $K(\zeta)$, then $d=n=2^k$ and we're done. But we don't know that $f$ is irreducible over $K(\zeta)$. My idea is, maybe we can do something similar to Step (1) as follows:

Claim: Regard $f$ as a polynomial over $K(\zeta)$. Let $g$ be an irreducible factor of $f$ over $K(\zeta)$. Let $\beta$ be a root of $g$. Then $[K(\zeta,\beta):K(\zeta)]=\deg(g)$, so (using a similar argument as in Step (1)), $[K(\zeta,\beta):K(\zeta)]$ must divide $n=2^k$, and hence will also be a power of $2$.

Is this claim true? Or am I missing something here? If it is true, then the result follows immediately. It feels like my claim might be a slightly special case of a more general result, but I am not sure. I'd appreciate any feedback.
Comment: Let $h$ be the $L=K(\zeta)$-minimal polynomial of $c^{1/n}$. It divides $x^n-c$ so $h = \prod_{j=1}^d (x-\zeta^{a_j}c^{1/n})$. Thus $h(0)= \prod_{j=1}^d (-\zeta^{a_j}c^{1/n})\in L$ ie. $c^{d/n}\in L$ which implies that $h = x^d-c^{d/n}$. From there $d=\deg(h)=[L(c^{1/n}):L]$ has to be the least integer such that $c^{d/n}\in L$. Since $c^{\gcd(n,d)/n}\in L$ then $d |n$.
Answer: There seems to be a mistake in Step 1 - I don't see how it follows that the degree of $g$ divides $n$ from what you've written.
In any case, you can use Galois theory to simplify both of your steps. In particular, $K(\zeta,\beta)/K(\zeta)$ is Galois and $K(\zeta)/K$ is Galois and it is easy to study these Galois groups.
Working with the first extension, we see that it is the splitting field of $x^n - c$ over $K(\zeta)$. In particular, if $\beta$ is some root of it, all the other roots are of the form $\zeta^i \beta$ and it splits after adjoining just $\beta$; the latter also means that the Galois group is determined by its action on $\beta$. If we take $\sigma$ in the Galois group, we see that it determines an element of $\mathbb Z/n\mathbb Z$ by $\sigma(\beta) = \zeta^i\beta$. One can check that this induces an injection of the Galois group into $\mathbb Z/n\mathbb Z$. Take $\sigma,\tau$ corresponding to $i,j$ and then:
$$\sigma\tau(\beta) = \sigma(\zeta^j \beta) = \zeta^j \sigma(\beta) = \sigma^{i+j}\beta$$
(note $\sigma$ fixes $\zeta$)
So the Galois group has order dividing $n$ by lagrange, and in this case it divides $2^k$ and hence has order some power of 2.
We can treat the latter extension in almost the same way. Again in this case the extension is obtained by adjoining $1$ primitive $n$th root of unity. Its conjugates are all of the form $\zeta^i$ for some $i$ coprime to $n$, and this gives rise to a natural embedding of the Galois group into $(\mathbb Z/n\mathbb Z)^\times $ by $\sigma\mapsto i$ when $\sigma(\zeta) = \zeta^i$. Just like above one can easily verify this is a homomorphism. Thus the Galois group has order dividing that of $(\mathbb Z/n\mathbb Z)^*$; the latter has order $\phi(n)$ which in this case is $2^{k-1}$ so again we get an extension of degree a power of $2$.
Finally, degrees multiply in towers and so the whole thing is degree a power of $2$.


Grouping with linq but leaving out certain items in the result

Question: I have the following code (you can copy paste and run the code if you have linqpad)
   void Main()
    {
        List<data_item> itemlist1= new List<data_item>();
        List<data_item> itemlist2= new List<data_item>();

        itemlist1.Add(new UserQuery.data_item
        {
         id=1,
         LeftHasdata=true

        })
        ;
        itemlist1.Add(new UserQuery.data_item
        {
         id=2,
         LeftHasdata=false

        })
        ;

        itemlist2.Add(new UserQuery.data_item
        {
         id=2,

          RightHasData=false
        })
        ;
        itemlist2.Add(new UserQuery.data_item
        {
         id=1,

          RightHasData=false
        })
        ;
        itemlist2.Add(new UserQuery.data_item
        {
         id=3,

          RightHasData=false
        })
        ;

        //var result= itemlist1.Concat(itemlist2).GroupBy(p=>p.id).Select(s  => new UserQuery.data_item {
        var result= itemlist1.Union(itemlist2).GroupBy(p=>p.id).Select(s  => new UserQuery.data_item {
          id=s.Key,
          LeftHasdata=s.Where(rd=>rd.LeftHasdata!=null).Select(d=>d.LeftHasdata).FirstOrDefault(),
           RightHasData=s.Where(rd=>rd.RightHasData!=null).Select(d=>d.RightHasData).FirstOrDefault(),
           })

           ;
        result.Dump();

    }

// Define other methods and classes here

 public class data_item
 {
     public int id {get;set;}
     public bool? LeftHasdata  { get; set; }
     public bool? RightHasData { get; set; }

}

I get the result below:
>id LeftHasdata RightHasData

>1 True False

>2 False False

>3 null  False

I only want to return results where group has more then one element. This means that the last result row should not be returned. How can i tweak my query to accomplish this.
many thanks in advance
B
Comment: You mean like `.Where(p => p.Count() > 1)`?
Comment: Well, this seems like it. I beleive to have tried to call the "where " extension method but my compiler would not allow it...
Answer: Just add a Where clause
var result = itemlist1.Union(itemlist2)
                      .GroupBy(p => p.id)
                      .Where(g => g.Count() > 1)
                      ...

Answer: The shortest answer is filter groups having only one element:
itemlist1.Union(itemlist2).GroupBy(p=>p.id).Where(g=>g.Count()==2).Select ...

Comment: This also does the job. Thanks


why are C7 and Cmaj7 different chords

Question: I'm relatively new to music theory, I was under the impression Cmaj7 was the same as C7 so i just added a minor third above the C triad (CEG) and got CEGBb.
As it turns out, C maj7 is actually a major third above the C triad - that is CEGB.
Then there's the Cminor variation, that is C Eb G, and Cminor7 C Eb G Bb.
If there is a discrepancy within the chords and the 7th why is there no discrepancy between regular C and C major?
Answer: Several sevenths exist. The most used is probably C7 made up from CEGBb. It is a dominant. Next is Cmaj7. C E  G B. Then Cm7. C Eb G Bb. And dont forget Cm maj7. C Eb G B. They are all in common usage but C7 is more used so has the simplest, if not most explanatory name.
Answer: The "maj" modifier is for the "7", not for the "C".  "major" is never indicated for the general mode of the chord (indicated by the third step): that's the default.  Only minor is indicated, with "m" or in the case of Jazz, "-".
There is really not much to be done here rather than learn all of the handful of exceptions and conventions.  There is not a lot of logic behind them.
Comment: Also I down voted due to your last paragraph.  There _is_ logic behind the conventions as dominant 7ths were dominant hence it make sense to refer to the most popular 7th as just 7.

why are C7 and Cmaj7 different chords


Strategy Pattern replacing if/else or case statments

Question: Why does it seem to me that using Strategy is just putting off the if/else to the Factory?
Using Strategy, doesn't a Factory need to figure out which concrete class to instantiate, and doesn't it do so by if/else?
Is another option to use a Map/List somehow, and have the keys be a name of the class to instantiate, and maybe have the class using the Factory pass in a name?
Answer: Map\List is an implemetation of Factory pattern.
Using Strategy patter is better than if\else because it's creates les coupled code.
With Factory+Startegy you can extend algorithms of processing without touch of client code, and have more ways to configure code dynamicaly (withot recompile).


App Crashes with: unrecognized selector sent to instance"

Question: The "Back" button in my app, when pressed, correctly takes me to the main view/screen, then the app crashes, Debug screen giving me this:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[RLMRealmNotificationToken invalidate]: unrecognized selector sent to instance 0x600003bd57e0

I stepped through the code with Debug and see the last line of code executed before it crashes.
In the code I see this error "Thread 1: signal SIGABRT" and have read here that this is likely related to the IBAction not working properly on my Back button but can't figure out where the issue is in the code.  My project does not show the Back button on the Storyboard, as it is coded.
Here is the code where my CustomBackButton is defined.
<code>#import "ViewControllerHelper.h"
#import "ProfileRealm.h"

@interface ViewControllerHelper ()

- (void)setCustomTitle;
- (void)setCustomBackButton;
- (void)profilesAction:(id)sender;

@end

@implementation ViewControllerHelper

- (id)initWithViewController:(UIViewController *)viewController       andProfile:(ProfileRealm *)profile {
    self = [super init];
    if(self) {
        _viewController = viewController;
        _profile = profile;

        [self setCustomTitle];
        [self setCustomBackButton];
    }
    return self;
}

- (void)setCustomTitle {
    if (_profile == nil)
        return;

    NSMutableAttributedString *string = [[NSMutableAttributedString     alloc] initWithString:_profile.name];

    UIFont *font1 = [UIFont boldSystemFontOfSize:15.0];
    [string addAttribute:NSFontAttributeName value:font1 range:NSMakeRange(0, string.length)];

    [string appendAttributedString:[[NSAttributedString alloc] initWithString:@"\n"]];

    NSUInteger start = string.length;

    [string appendAttributedString:[[NSMutableAttributedString alloc] initWithString:_profile.friendlyName]];
    UIFont *font = [UIFont boldSystemFontOfSize:15.0];
    [string addAttribute:NSFontAttributeName value:font range:NSMakeRange(start, string.length - start)];

    NSMutableParagraphStyle *paragrapStyle = [[NSMutableParagraphStyle alloc] init];
    paragrapStyle.alignment = NSTextAlignmentCenter;
    [string addAttribute:NSParagraphStyleAttributeName value:paragrapStyle range:NSMakeRange(0, string.length)];

    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0,0,44,44)];
    [titleLabel setAttributedText:string];
    [titleLabel setNumberOfLines:2];
    //    [titleLabel setTextColor:[UIColor whiteColor]];

    _viewController.navigationItem.titleView = titleLabel;
}

- (void)setCustomBackButton {
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithImage:  [UIImage imageNamed:@"monkeys"]
                                                                     style:UIBarButtonItemStylePlain
                                                            target:self     action:@selector(profilesAction:)];
    _viewController.navigationItem.leftBarButtonItem = item;
}

- (void)profilesAction:(id)sender {
    //MARK - App Crashes after next line is executed
    [_viewController.tabBarController.navigationController  popViewControllerAnimated:YES];
}

@end

    //Post Crash, I get a SIGABRT error in the main file
    // Here is that code:

    #import <UIKit/UIKit.h>
    #import "AppDelegate.h"

    int main(int argc, char * argv[]) {
        @autoreleasepool {
            return UIApplicationMain(argc, argv, nil,      NSStringFromClass([AppDelegate class]));
        }
    }
</code>
Answer: Looks like this could be due to the "invalidate" method not being a recognized selector. Try using <code>[RLMRealmNotificationToken stop];</code> instead per their documentation
Comment: Thanks!  I inherited this project. Parts of the code had [RLMRealmNotificationToken stop];  but those lines threw an error to "use -invalidate instead"  . But I will read up on their documentation. Thanks again.
Comment: Is the selector it's looking for `invalidate` and `-invalidate`?
Comment: "invalidate" only, I believe. Apologies for the "-"
Comment: Did they throw an error, or did the compiler complain?
Comment: It was one of the red highlighted alerts to the right of the line of code, with an exclamation point.  Said -stop should be updated to be invalidate, instead.
Comment: Did you verify the the RLMRealmNotificationToken is still in memory, and that it was not yet deallocated?
Answer: If the compiler complains that you should use "invalidate" instead of "stop", and at runtime "invalidate" is not recognised, then I would suspect that you are using an old compiled library together with new incompatible header files.
Say version 1.0 of your library used "stop". You received 2.0 header files where the method changed to "invalidate" but you continue using the compiled 1.0 library.
But usually this is caused by a reference to an object being declared as one thing, while the actual object is another thing.
Comment: Thank you!  This makes sense. I will dig into it and let ou know what I find.  Thank you again for your wisdom and help!
Comment: Here is an example of where I get the stop vs invalidate error:
-(void)dealloc {
  [self.token stop];     //Error on this line is ->.  'stop' is unavailable: Renamed to -invalidate.
    self.token = nil;
}


Fermata tie confusion

Question: Can someone help me understand what the circled notation is instructing in this simple piece by Markham Lee? Are the notes tied? I'm confused as how they can be tied and staccato at the same time.
Answer: The notes are not tied. This is relatively conventional notation for portato, which is rather like a "sticky" staccato with longer but still detached notes.
Comment: Strange that the treble notes aren't portato as well?
Comment: @Tim Perhaps because the treble pitch changes? That doesn't completely answer it, but that may have been the logic.
Comment: @Richard - possibly, but the fermata effect is more a sort of volume change, pulsing thing, rather than referencing musical pitches, where here it's almost a sus, hence the question.
Comment: Ah thank you very much! Learnt something new today :)
Comment: @Tim The composer is indicating that he wants the treble notes to sound long and legato, and the bass notes to sound as a soft staccato, shorter than the treble notes, but still sounding, given the fermata. It is a nice effect. It matches the diminuendo just before and the pp afterwards.
Answer: Although not all engravers make the distinction, it is common to place ties and slurs differently.  A tie should be placed between the note heads, while slurs should be placed conspicuously above or below them.  In this case, the curved marking is quite conspiciously above the note heads, implying that it is a slur even though the pitch doesn't change.
Additionally, as Todd Wilcox notes, when multiple notes are being tied simultaneously, there should be a separate tie marking for each one.
Comment: Also a tie for a chord should be a curve for each note of the chord - in this case two.
Comment: @ToddWilcox: That is definitely generally true, and I've added it to my answer.  I'm curious whether the rule is *always* true, or whether there might be exceptions if e.g. a keyboard piece has the outer two notes of an initially-suspended chord sustained for multiple bars, while the inner voice changes on beat 4 of one of the earlier bars.  Would one draw the ties through the stem of the changing note, or put a small gap in the tie for the step, or draw an ending-half-tie at the start of the continuation of the outer note that would have collided, or what?
Answer: Slurred and staccato rather than tied and staccatto. It's called 'portato'.  Makes sense for stringed instruments where a slur indicates continuous bow movement.  A little paradoxical on piano, I agree!   And further complicated by the fermatas.  Think 'sticky staccato'.  And think of the fermata as 'pause the count' rather than 'prolong the note'.

Fermata tie confusion


Vue.js Bootstrap table - pass data between Parent and Child component

Question: I have 2 components: Parent and Child. In both components, I'm using Bootstrap tables and their 'items' and 'fields' come from API. The Child component should pass data (true or false, for each table row) to the Parent component. I want to assign this data from the Child component to the Parent component bootstrap table row object. You can see my code below.
So, the problem is that the v-if statement doesn't work. It seems like the object 'state' is assigned before the component is created because on console.log I can see that the new 'state' object is there and filled correctly with true/false but in DOM the situation is different, the state is undefined.
Anyone who can help how can I set the 'state' object and make it works?
Parent component:
<template>

        <template v-slot:cell(config)="row">
            <child-component
              @onitembind='isSingleRow'>
            </child-component>
        </template>

</template>

<template v-slot:cell(labelCheckbox)="row">

</template>

Child component:

Comment: Does the `state` property exist prior to you setting it?
Comment: @Hiws no, actually I create it in the method isSingleRow
Answer: In Vue 2, adding properties to an existing object wont be reactive, as Vue wont be able to properly add a getter/setter for the property.
To get around this you should use the Vue.set/this.$set method.
this.$set(this.customItems[i], 'state', this.singleRow[i])
For more information see: https://v2.vuejs.org/v2/guide/reactivity.html#For-Objects


StoreAppLicense status "Inactive license" of UWP app

Question: Below is the code for a UWP app to get license info on the user's PC
<code> private static async Task<int> getLicenseState()
    {
        StoreAppLicense license = await appStoreContext.GetAppLicenseAsync();
        //string licenseMode;

        if (license.IsActive)
        {
            if (license.IsTrial)
            {
                //licenseMode = "Trial license";
                return 0;
            }
            else
            {
                //licenseMode = "Full license";
                return 1;
            }
        }
        else
        {
            //licenseMode = "Inactive license";
            return 2;
        }

    }
</code>
What I confused about is how to process the app when it detects "Inactive license"?
stop the app? or just display some warning info? or trigger a window to ask the user to buy the app?
Your comment welcome
Answer: If the current application license invalid, then you can use StoreContext.RequestPurchaseAsync to remind users to purchase the application.
<code>private StoreContext context = null;

public async void PurchaseAddOn(string storeId)
{
    if (context == null)
    {
        context = StoreContext.GetDefault();
        // If your app is a desktop app that uses the Desktop Bridge, you
        // may need additional code to configure the StoreContext object.
        // For more info, see https://aka.ms/storecontext-for-desktop.
    }

    workingProgressRing.IsActive = true;
    StorePurchaseResult result = await context.RequestPurchaseAsync(storeId);
    workingProgressRing.IsActive = false;

    // Capture the error message for the operation, if any.
    string extendedError = string.Empty;
    if (result.ExtendedError != null)
    {
        extendedError = result.ExtendedError.Message;
    }

    switch (result.Status)
    {
        case StorePurchaseStatus.AlreadyPurchased:
            textBlock.Text = "The user has already purchased the product.";
            break;

        case StorePurchaseStatus.Succeeded:
            textBlock.Text = "The purchase was successful.";
            break;

        case StorePurchaseStatus.NotPurchased:
            textBlock.Text = "The purchase did not complete. " +
                "The user may have cancelled the purchase. ExtendedError: " + extendedError;
            break;

        case StorePurchaseStatus.NetworkError:
            textBlock.Text = "The purchase was unsuccessful due to a network error. " +
                "ExtendedError: " + extendedError;
            break;

        case StorePurchaseStatus.ServerError:
            textBlock.Text = "The purchase was unsuccessful due to a server error. " +
                "ExtendedError: " + extendedError;
            break;

        default:
            textBlock.Text = "The purchase was unsuccessful due to an unknown error. " +
                "ExtendedError: " + extendedError;
            break;
    }
}
</code>
Comment: does 'Inactive license' mean the current application license expires
Comment: Hello, you can use `StoreAppLicense.ExpirationDate` to determine whether the license has expired. I have revised the relevant description in the answer to avoid misunderstanding. According to the description in the [document](https://learn.microsoft.com/en-us/uwp/api/windows.services.store.storeapplicense.isactive?view=winrt-19041#Windows_Services_Store_StoreAppLicense_IsActive), when `StoreAppLicense.IsActive` is **False**, it means that the license is invalid and the user may need to purchase the application.
Comment: Can this (`StoreAppLicense.IsActive`) be used to detect sideloaded pirated instances of an app?


Do $\lim_{x \downarrow 0} f(x)$ and $\lim_{x \uparrow 1} f(x)$ exist if $f$ is concave over $[0, 1]$?

Question: Let $f: [0, 1] \rightarrow \mathbb{R}$ be a concave function. We know that $f$ is continuous over $(0, 1)$. Is it true that both $\lim_{x \downarrow 0} f(x)$ and $\lim_{x \uparrow 1} f(x)$ exist? Normal graphs of a concave function suggest these properties. But I have no idea how to prove them. Thanks.
Comment: A concave (or a convex) function on an open interval has simple monotonicity properties. Either it's monotonic on the whole interval, or there is a point $c$ in the interval such that it's monotonic (nondecreasing on one, nonincreasing on the other) on each of the two subintervals determined by $c$.
Comment: I'd suggest changing the title to match the actual question then.
Comment: Are you asking if $f(0)$ and $f(1)$ must necessarily be defined to be equal to their respective limits when $f$ is concave on $[0,1]$?  That's a different question than asking whether these limits exist.
Comment: @BrianBorchers No, I am just asking whether the limits exist. I know that even if the limits exist, $f$ may still be discountinuous at these two points.
Comment: Thank you! I did not realize I used the wrong title.
Comment: Do you allow for extended real valued functions?  e.g. can $f(0)$ be defined as $-\infty$?
Comment: No. Both $f(0)$ and $f(1)$ are just real numbers, not extended real.
Comment: Consider $f(x) = \ln x$  does this function meet your criteria?
Comment: @DougM This function is not concave on $[0, 1]$ though.
Comment: @Ovi Isn't it?  The second derivative is always less than 0, and  $f(\lambda x + (1-\lambda)y) \ge \lambda f(x) + (1-\lambda) f(y)$ for all $(x,y)\in (0,1)$ and $\lambda\in [0,1]$
Comment: @DougM $\ln(x)$ isn't defined at $x=0$.
Comment: Hint: Consider the set of values for $f(0)$ that keep the function concave and then take the least upper bound on that set.
Comment: @DanielFischer Beautiful! Thank you very much. I understand it now.
Answer: If $f$ is concave on $[0, 1]$ then
$$ \tag{*}
f(b) \ge \frac{c-b}{c-a} f(a) + \frac{b-a}{c-a} f(c)
$$
for $0 \le a < b < c \le 1$. This can be rewritten as
$$
\frac{c-b}{c-a} \bigl(f(b) - f(a)\bigr) \ge \frac{b-a}{c-a}\bigl(f(c) - f(b)\bigr) \, .
$$
In particular we have the following implication:
$$
\tag{**}
\bigl( 0 \le a < b < c \le 1 \text{ and } f(a) > f(b) \bigr)\implies f(b) > f(c) \, .
$$
Now consider two cases:

$f$ is increasing on $(0, 1)$. $(*)$ with $0 = a < b=1/2 < c < 1$ gives an upper bound for $f(c)$, so that $\lim_{x \to 1-} f(x)$ exists as a finite value.

Otherwise there is $0 < x_1 < x_2  < 1$ with $f(x_1) > f(x_2)$. Then $(**)$ implies that $f$ is decreasing on $[x_2, 1)$. $(*)$ with $a=0 < b < c=1$ gives a lower bound for $f(b)$, so that $\lim_{x \to 1-} f(x)$ exists as a finite value in this case as well.

A similar argument works for $\lim_{x \to 0+} f(x)$.
It follows from the concavity condition $(*)$ that
$$
\lim_{x \to 0+} f(x) \ge f(0) \\
\lim_{x \to 1-} f(x) \ge f(1)
$$
(i.e. $f$ is lower semi-continuous at the boundary points) but strict inequality can hold.
Comment: Yes, thank you very much. This is @DanielFischer hint. One thing I want to add is that the (*) inequality also provides upper and lower bounds that are used to guarantee the limits are not infinity.
Comment: @user295959: Yes that is exactly Daniel's hint. I found it still worthwhile to demonstrate how it follows directly from the concavity condition (and I am sure that Daniel would have posted an answer if he had wanted). It becomes a bit simpler if one already *knows* that a concave function has one-sided derivatives at every interior point, and these are decreasing. – Good catch about the finiteness of the limits, I have added that to the answer.
Comment: Perfect! Thank you!


Inequality using integrals

Question: Using that
$
u^{2}(x) - u^{2}(0) = \int_{0}^{x}(u^{2}(x))' dx$
and the Cauchy-schwarz inequality, show that if $u(0) = 0$, then exist a constant c such that
$\int_{0}^{b}u^{2}(x)dx < c\int_{0}^{b}(u'(x))^{2}dx $
Someone can give me a hint?
Comment: $u$ is a real function
Answer: Here's a solution. Don't read past the first 2 lines if you only want a hint.
We have
$$\begin{split}
\int_0^b u^2(x)dx &=\int_0^b \left(\int_0^x u^\prime(t) dt\right)^2dx \\
&= \int_0^b \left(\int_0^b 1_{[0, x]}(t)u^\prime(t) dt\right)^2dx\\
&\leq \int_0^b \left(\sqrt {\int_0^b (1_{[0, x]}(t))^2dt}\sqrt {\int_0^b (u^\prime(t))^2dt} \right)^2dx \mbox{ by CS}\\
&\leq \int_0^bb\int_0^b (u^\prime(t))^2dt dx\\
&\leq b^2 \int_0^b (u^\prime(t))^2dt
\end{split}$$
Comment: how can you say $\int_{0}^{b}(1_{[0, x]}(t))^{2}dt = b$
Comment: I'm saying the integral on the left is less than or equal to $b$.

Inequality using integrals


Probability of panel assignment

Question: I am trying to determine the probability of a "mixed panel" assignment (i.e., a panel of judges w/at least 1 woman).
Consider the following: A court has a total of 20 judges, 8 of whom are women. Panels of 5 judges are randomly drawn to decide any given case. What is the probability of drawing a panel on which at least 1 of the judges is female?
I realize this is a "simple" question, but it is beyond me. I would greatly appreciate a discussion of the steps required for its solution. Thank you in advance.
Comment: I previously had a [similar question](http://stats.stackexchange.com/q/3650/1036), and the [hypergeometric distribution](http://en.wikipedia.org/wiki/Hypergeometric_distribution) is applicable to your question as stated.
Answer: There is a large and rich branch of mathematics, combinatorics, devoted to solving such problems.  The most important step used here is to recognize that "at least one female" is more simply characterized as "not all males."  Details follow.

The name for the number of distinct 5-member panels from a pool of 20 judges is the "binomial coefficient," $\binom{20}{5}$.  We will worry later about how to compute this.  All probabilities involving 5-member panels of these judges will be fractions with this number in the denominator.  Computing a probability is a matter of counting which panels are described by an event; that will go in the numerator.
The all-male panels are drawn from a smaller pool of just 20-8 = 12 judges.  There are therefore $\binom{12}{5}$ of them.  The remainder of the possible panels, equal in number to $\binom{20}{5} - \binom{12}{5}$, have at least one female.  Therefore the desired probability is
$$\Pr(\text{Panel with a female judge}) = \frac{\binom{20}{5} - \binom{12}{5}}{\binom{20}{5}}.$$
To compute the binomial coefficients, consider that the number of ordered sequences of 5 people out of 20 equals $20 \cdot 19 \cdot 18 \cdot 17 \cdot 16$ because there are 20 ways to pick the first in the panel, 19 remaining people from whom to choose the second, and so on.  Any panel of 5 people determines $5! = 5\cdot 4 \cdots 2 \cdot 1$ such orderings.  Therefore $\binom{20}{5} = 20\cdots 16 / (5 \cdots 1) = 15504.$  Likewise $\binom{12}{5} = 792$.  The desired probability is
$$\frac{\binom{20}{5} - \binom{12}{5}}{\binom{20}{5}} = \frac{15504 - 792}{15504} = \frac{613}{646}.$$
Comment: "not all males" rather than "no males"?

Probability of panel assignment


failing to achive tunneling to fresh ubuntu 10.04 server

Question: I've just set up a new 10.04 server and can't get the tunneling to work.
local machine
ssh -L 9090:localhost:9090 firstname.lastname@example.com

login success, but thereafter trying tunnel from local browser, http://127.0.0.1:9090
echo at server terminal:
channel 3: open failed: connect failed: Connection refused

auth.log:
sshd[24502]: error: connect_to localhost port 9090: failed.

iptables -L
Chain INPUT (policy ACCEPT)
target     prot opt source               destination

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination

Trying 9090 at server (links http://xx.xxx.xx.xx:9090 works)
sshd_config is identical to previous 8.04 server, working fine.
What's going on?
Comment: Did you try `telnet localhost 9090`? Also, you mentioned iptables in your question. Did you have any NAT rules? You can paste the output of `iptables -L`.
Comment: telnet over tunnel gives: Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Connection closed by foreign host.
dump of iptables is in post above. Thanks for help, :-)
Comment: try executing your ssh command with -vvv to get more verbose output, it usually says where something went wrong
Comment: verbose output as answer, sorry for that.. new here...
Answer: Verbose output (-vvv).
Login success. Upon request of tunnel from local browser, at server terminal:
ebug1: Connection to port 9090 forwarding to localhost port 9090 requested.
debug2: fd 9 setting TCP_NODELAY
debug3: fd 9 is O_NONBLOCK
debug3: fd 9 is O_NONBLOCK
debug1: channel 3: new [direct-tcpip]
channel 3: open failed: connect failed: Connection refused
debug2: channel 3: zombie
debug2: channel 3: garbage collecting
debug1: channel 3: free: direct-tcpip: listening port 9090 for localhost port 9090,  connect from 127.0.0.1 port 57884, nchannels 4
debug3: channel 3: status: The following connections are open:
  #2 client-session (t4 r0 i0/0 o0/0 fd 6/7 cfd -1)

debug3: channel 3: close_fds r 9 w 9 e -1 c -1

Please note that port 9090 replies upon
# links 127.0.0.1:9090

ON WORKING MACHINE: (8.04)
at request:
debug1: Connection to port 9090 forwarding to localhost port 9090 requested.
debug2: fd 10 setting TCP_NODELAY
debug3: fd 10 is O_NONBLOCK
debug3: fd 10 is O_NONBLOCK
debug1: channel 3: new [direct-tcpip]
debug2: channel 3: open confirm rwindow 2097152 rmax 32768
debug2: channel 3: rcvd eof
debug2: channel 3: output open -> drain
debug2: channel 3: obuf empty
debug2: channel 3: close_write
debug2: channel 3: output drain -> closed

regards
//t
Comment: For future reference, this should be appended to your original question, not added as an answer.
Answer: Based on this thread I think the cause of your problem might be Apache, not sshd.
Try changing your Listen directive in your httpd.conf file to

Listen 127.0.0.1:9090

Restart httpd afterwards and see if that made any difference.
Answer: SOLVED:
It was a policy issue. At server terminal, requested service at 9090 didn't respond to
telnet localhost 9090

only at:
telnet 127.0.0.1 9090

Solution was to add this to /etc/hosts.
127.0.0.1 localhost localhost.localdomain


Scala, how to use functional programming to do a kind of join operation in between to complex sequences?

Question: Suppose I have a Seq[Seq[String]] sequence, like
val seq = for (i <- (1 to 50) toSeq) yield Seq(s"foo$i", s"bar$i")
, which is
List(List("foo1", "bar1"), List("foo2", "bar2"), ..., List("foo50", "bar50"))
I also had an index tuple, say
((5, 10), (13, 17), (25, 33), (42, 49))
What I want to get is filter the seq, get only those whose index is between the range in the second tuple and I want to add a new id in the last position.
The result should be:
List(List("foo5", "bar5", "0"), List("foo6", "bar6", "0")..., List("foo10", "bar10", "0"), List("foo13", "bar13", "1"), List("foo14", "bar14", "1")..., List("foo17", "bar17", "1"), List("foo25", "bar25", "2"), List("foo26", "bar26", "2")... List("foo33", "bar33", "2"), List("foo42", "bar42", "3"), List("foo43", "bar43", "3")..., List("foo48", "bar48", "3"), List("foo49", "bar49", "3"))
I can achieve this using procedural programming, but the code smell is ugly. How can this be done in a scala style functional way?
Comment: expandRanges, zipWith, filter
Comment: Something like `indexes.zipWithIndex.map { case ((start, end), idx) => seq.slice(start, end).map(_ + idx.toString) }` it may have some typos, I am on a cellphone. Also note this could be extremely inefficient if the underlying **Seqs** are **List** but if you have **Vectors** it would have a reasonable performance; also you may use an **Iterator** or a **View** to avoid allocating the `zip WithIndex` not sure if it would be a way to do the `slice` and the `map` also in one go.
Comment: @LuisMiguelMejíaSuárez `flatMap` not `map`?
Comment: @Bergi I guess `map` OP wants a nested **Seq**  but as I said I haven't compiled the code and my in mind compiler is not the best _(specially now that I am just going to bed)_ so maybe I am missing something. My idea is that if my snippet does helped OP I would post a proper answer tomorrow.
Answer: Generally speaking, join-type operations can easily be expressed using for comprehensions:
val ranges = Seq((5, 10), (13, 17), (25, 33), (42, 49))
for {
  i <- (1 to 50).toSeq
  ((lower, upper), j) <- ranges.zipWithIndex
  if i >= lower && i <= upper
} yield List(s"foo$i", s"bar$i", j.toString)

However be aware that this will require time proportional to the product of the lengths of the two lists. If these get sufficiently large, you'll need a more optimized solution.
Comment: Would you plz elaborate on how the time proportional gets increased to the product of the lengths of the two lists and how to make a more optimized solution, thanks