Complex manifold with no divisors

Question: I read in Griffith Harris P132 that a complex manifold of dimension greater than one can have no divisors on it at all. I want to find examples. Is there an example? Does the Hopf manifolds $S^1\times S^{2n-1}$ have such properties?
Answer: For $n=2$ there is a nontrivial picard group. There are a few decent references about this listed on the wikipedia page for Hopf surfaces.
Comment: Thanks, but I still cannot understand why a complex manifold can havd no divisors. Does the non-trival picard group in the answer imply it?
Comment: I think this is the source you want for the Hopf Manifolds: http://www.pnas.org/content/55/2/240.full.pdf+html   (see theorem 2)
Comment: This one shows that there is a curve on it.
Comment: On the other hand, there are things called inuoue surfaces which apparently have no closed complex subvarieties. See this overflow question http://mathoverflow.net/questions/88996/non-compact-complex-surfaces-which-are-not-kahler and the comment to the first response there
Answer: The example you want, as mentioned in the comments, is that of an Inoue surface. Since they have no curves, they cannot have any divisors. On the other hand, consider the Hopf surface $S$ given by $(\mathbb{C}^2-{0})/\sim$ where $(x,y) \sim (2^nx,2^ny)$ for all $n\in\mathbb{Z}$, and the morphism $\varphi:S\to\mathbb{P}^{1}$ given by $[(x,y)] \mapsto [x:y]$. The pull back of a point $y\in\mathbb{P}^1$ will be a divisor on $S$. In fact, since $\varphi$ induces an elliptic fibration,  the divisors are just elliptic curves. To finish, one can show that these are all the divisors on $S$, which establishes $\text{Cl}(S) \cong \mathbb{Z}$.

Complex manifold with no divisors


Why Interrupts not generates by C code but easy generates by assembly instructions?

Question: I am programming a little kernel, and implement idt and interrupts.
This C code in my little kernel not generate any interrupt:
int x = 5/0;

int f[4];
f[5] = 8;

But this Assembly code can generate any interrupt:
asm("int $0");

(and handlers work right).
Help me to understand why this situation can happens.
I also tried this:
    int a = 3;
    int b = 3;
    int c = a-b;
    int x = a/c;

Nothing I try in c code can generate exception for me.
Even this not worked:
int div_by_0(int a, int b){return a/b;}

int x = div_by_0(5, 0);

Comment: As any decent book, tutorial or class should have mentioned, C doesn't have any bounds-checking. If you index an array out of bounds it leads to [*undefined behavior*](https://en.wikipedia.org/wiki/Undefined_behavior) which *could* lead to a crash (but not an "interrupt" the way you can in assembly).
Comment: The `idiv` instruction would generate the interrupt, however the compiler is not obliged to use it and typically will not use it for division by a constant (especially zero). If you hide the fact that you're dividing by zero from the compiler, then it may work.
Comment: If you just want to test your kernels exception handling, then perhaps write small assembly functions that perform these operations instead?
Comment: Hey in your `int x = 5/0;` the division by 0 is made by the preprocessor! It will never reach the compiler... I suggest to look at the generated assembly code...
Comment: `int $0` is triggering an interrupt in your computer's kernel via the operating system. And because C has no boundary checking, you will need to look elsewhere. You could use `asm()` to create an interrupt in assembly though.
Comment: but as i understand x =5/0 C must generate division by zero interurpt exception at least.
Comment: For the division, try using variables whose values are set at run-time instead of constant literals. And *use* the result to make sure the compiler doesn't optimize it away. Also note you can get different *exceptions* (the common term for such "interrupts") for integer and floating point division by zero.
Comment: @Someprogrammerdude Interestingly, on GCC 10.1 x86-64, `-O3`, the compiler generates an undefined opcode. ([Godbolt](https://godbolt.org/z/j54Q1R))
Comment: Divide by 0 don't trigger a fault on every platform. ARM Cortex-m doesn't not generate any fault by default (must be enabled) otherwise the division just return 0. And check assembly for compiler optimization when you make these tries.
Comment: Read [this blog about undefined behavior](http://blog.llvm.org/2011/05/what-every-c-programmer-should-know.html)
Comment: @ThomasJager Heh, well that's UB in action! :)
Comment: `but as i understand x =5/0 C must generate division by zero interurpt exception at least` No: it is an initialiser, not an assignment. Initialisers are evaluated at compile time.
Comment: The error, division by zero, is surely detected by the compiler in optimization phase, **because is constant**, simply rising the signal for division by zero exception, without invoking the interrupt. About the assembler instruction, you're using a **software interrupt** instruction, the compiler can't optimize it out, the instruction invokes the interrupt. Try `int div_by_0(int a, int b){return a/b;}`, then call it with 5 and 0 as parameters.
Answer: void fun ( void )
{
    int a = 3;
    int b = 3;
    int c = a-b;
    int x = a/c;
}

Disassembly of section .text:

0000000000000000 <fun>:
   0:   f3 c3                   repz retq

there is no divide to trigger a divide by zero.  It is all dead code.
And none of this has anything to do with the int instruction, these are completely separate topics.
As mentioned in the comments test it without using dead code.
int fun0 ( int x )
{
    return(5/x);
}
int fun1 ( void )
{
    return(fun0(0));
}

but understand that it still may not have the desired effect:
Disassembly of section .text:

0000000000000000 <fun0>:
   0:   b8 05 00 00 00          mov    $0x5,%eax
   5:   99                      cltd
   6:   f7 ff                   idiv   %edi
   8:   c3                      retq
   9:   0f 1f 80 00 00 00 00    nopl   0x0(%rax)

0000000000000010 <fun1>:
  10:   0f 0b                   ud2

because the optimizer for fun1 could see the fun0 function.  You want to have the code under test in a separate optimization domain.  In this case above then the idiv would generate the divide by zero.  And then it is becomes an operating system issue as to how that is handled and if it is visible to you.
Comment: `volatile` my friend.
Comment: @Joshua   volatile creates other issues, leaves a bad taste, once in a blue moon starts an argument on SO.  Certainly include it in your answer though.
Comment: point being is the OP is probably not generating a divide instruction thus no divide by zero.
Answer: The problem you are seeing is because division by 0 is undefined behaviour in C/C++. The compiler has managed to do enough optimization at compile time to realize you are dividing by zero. The compiler is free to do anything from things like halting and catching fire to making the result 0. Some compilers will emit a ud2 instruction to raise a CPU exception. The result is undefined.
You have a couple of options. Write your division in assembly and call that function from C/C++. Since you are using GCC (works for CLANG as well) You can also use inline assembly to generate a division by zero with something like:
#include <stdint.h>  /* or replace uint16_t with unsigned short int */

void div_by_0 (void)
{
    asm ("div %b0" :: "a"((uint16_t)0));
    return;
}

This sets AX to 0 then divides AX by AL with the DIV instruction. 0/0 is undefined and will raise a Division Exception (#DE). This inline assembly should work with 16, 32, and 64-bit code.

In protected mode or long mode using int $# (Where # is the vector number) to trigger an exception is not always the same as getting a CPU generated exception. Some exceptions generated by the CPU push an error code on the stack after the return address that needs to be cleaned up by an interrupt handler. If you were to use int $0x0d from ring 0 to cause a #GP exception the interrupt handler would likely fault as it returns from the interrupt because using int to generate an exception never places an error code on the stack. This isn't a problem with int $0 because #DE doesn't have an error code placed on the stack by the CPU.
Answer: It turned out to be due to optimization flags. Due to a bit of confusion at Makefiles, the -O2 flag worked. If you enable the -O0 flag, exceptions work directly from C. And even this simple code throws an exceptions:
int x = 5/0;


Android - dispatchTouchEvent gives me a StackOverflowError

Question: Here I have a ViewFlipper with a setOnTouchListener that works fine. Then I inflate ReLayNewsItem and later I add it to ViewFlipper.
Now I want WebView (web) to listen for touch events and pass them on to the ViewFlipper.
    final ViewFlipper VFnewsFeed = new ViewFlipper(this);

    VFnewsFeed.setOnTouchListener(new OnTouchListener(){
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (gestureDetectorLR.onTouchEvent(event)) { return true; }
            else { return true; }
        }});

    ///////////////////

    LayoutInflater inflater = (LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    RelativeLayout ReLayNewsItem = (RelativeLayout) inflater.inflate(R.layout.newsitem, null);

    final WebView web = (WebView)ReLayNewsItem.findViewById(R.id.NewsItemWv);

    web.setOnTouchListener(new OnTouchListener(){
        @Override
        public boolean onTouch(View v, MotionEvent event) {

            VFnewsFeed.dispatchTouchEvent(event); /// ERROR HERE!
            return false;
        }});

Yet it gives me this -
07-14 21:12:43.600: E/AndroidRuntime(14048): FATAL EXCEPTION: main
07-14 21:12:43.600: E/AndroidRuntime(14048): java.lang.StackOverflowError
07-14 21:12:43.600: E/AndroidRuntime(14048):    at life.iface.main$11.onTouch(main.java:1289)
07-14 21:12:43.600: E/AndroidRuntime(14048):    at android.view.View.dispatchTouchEvent(View.java:4605)
07-14 21:12:43.600: E/AndroidRuntime(14048):    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:1518)
07-14 21:12:43.600: E/AndroidRuntime(14048):    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1320)
...

Any ideas? Thanks! ;)
Comment: "StackOverflow" errors are the best ;-)
Answer: If you return false it means that the event is unhandled.
Depending on your needs try to return true or VFnewsFeed.dispatchTouchEvent(event) in onTouch method instead of false.
Reference to documentatnion
Comment: http://stackoverflow.com/questions/6374592/passing-touch-events-to-the-parent-view
Comment: tried both true and VFnewsFeed.dispatchTouchEvent(event), same error. :(
Comment: didn't really get it. you think it should be done with onInterceptTouchEvent ?


Writing an equation with integer coefficients

Question: An algebraic number is any complex number that is a root of a non-zero polynomial in one variable with rational coefficients. for example write an equation which $\sqrt2 +1$ is  one of its root ,with integer coefficients .
$$x=\sqrt 2+1 \to x-1=\sqrt 2\\(x-1=\sqrt 2)^2\to \\x^2+1-2x=2\\x^2-2x-1=0$$
other example :write an eq. with integer coefficients which $x=\sqrt2 +\sqrt3$ is a root.
$$x=\sqrt2 +\sqrt3 \\x^2=2+3+2\sqrt6\\(x^2-5)=(2\sqrt6)\\(x^2-5)^2=(2\sqrt6)^2\\x^4+25-10x^2=24\\x^4-10x^2-1=0$$
or$$x-\sqrt2=\sqrt3\\x^2+2-2\sqrt2x=3\\x^2-1=2\sqrt2x\\(x^2-1)^2=(2\sqrt2x)^2\\x^4+1-2x^2=8x^2\\x^4-6x^2+1=0$$
Now: my question is about :an equation which one's root is $x=\sqrt2+\sqrt3+\sqrt 5$ and coefficients are integer .
How many equation we can write for it ? w.r.t "coefficients are integer"
How can write this equation easily ?
Thanks in advance.
Comment: A polynomial with rational coefficients will have the exact same solutions as the polynomial where every coefficient is multiplied by a non-zero constant.  If you let the non-zero constant but the least common multiple of the denominators, this polynomial will have all integer coefficients.  Hence rational vs. integer coefficients isn't relevant and the process is the same for either.
Answer: One way is :$$x=\sqrt2+\sqrt3+\sqrt 5\\x-\sqrt5=\sqrt2+\sqrt3\\(x-9\sqrt5=\sqrt2+\sqrt3)^2\\x^2+5-2\sqrt5x=2+3+2\sqrt6\\x^2-2\sqrt5x=2\sqrt6\\(x^2-2\sqrt5x=2\sqrt6)^2\\x^4+20x^2-4\sqrt5x^3=24\\(x^4+20x^2-24)^2=(4\sqrt5x^3)^2$$ Is there an easier way  ?
Comment: Don't know that it's easier (or that it counts as an answer) but if using a CAS one convenient way is using polynomial resultants, for example [`resultant[ resultant[ resultant[ x-u-v-w, u^2-2, u ], v^2-3, v], w^2-5, w]`](http://www.wolframalpha.com/input/?i=resultant%5B+resultant%5B+resultant%5B+x-u-v-w,+u%5E2-2,+u+%5D,+v%5E2-3,+v%5D,+w%5E2-5,+w%5D) $\;=x^8 - 40 x^6 + 352 x^4 - 960 x^2 + 576\,$ which is the same polynomial as yours.


Regularizing conditionally convergent integrals

Question: For functions $f:\mathbb{R}\to \mathbb{R}$ the definition of a convergent improper integral is straightforward: the integral $\int_\mathbb{R} f(x)dx$ converges iff $$\lim_{(a,b)\to (-\infty, \infty)}\int_a^b f(x) dx $$
exists. However, already in dimension 2 things get trickier. For example, if $f(x,y)=\sin (x^2+y^2)$ and we take $$\int_{-a\leq x,y\leq a}f(x,y) dxdy$$ the limit as $a\to\infty$ exists and is equal $\pi$.
On the other hand, if we replace the square $\{(x,y)\mid -a\leq x,y\leq a\}$ by the disk of radius $a$ centered at the origin as the integration domain, the limit $$\lim_{a\to+\infty}\int_{x^2+y^2\leq a^2}f(x,y) dxdy$$ will no longer exist. In fact, the
value will oscillate around $\pi$. Also, it is clear that for any $A\in\mathbb{R}$ one can find a continuous family $\mathbb{R}\ni t\mapsto X_t$ of compact connected polygons in $\mathbb{R}^2$ such that
$$\lim_{t\to\infty} \int_{X_t}f(x,y) dxdy=A.$$

Here is my first question: is it possible to find a continous family $(X_t)$ of compact and convex polygons in $\mathbb{R}^2$ such that $$\lim_{t\to\infty} \int_{X_t}f(x,y) dxdy$$ would exist but
would be $\neq \pi$? If not, then is there a smooth function $g:\mathbb{R}^2\to \mathbb{R}$ and two continous families $(X_t),(Y_t)$ as above (i.e., $X_t,Y_t$ are compact and convex), such that $$\lim_{t\to\infty} \int_{X_t}g(x,y) dxdy,\lim_{t\to\infty} \int_{Y_t}g(x,y) dxdy$$
would both exist but would be different?
More generally, is there a standard way to regularize integrals such as $\int_{\mathbb{R}^2}f(x,y) dxdy$? One possible way would be to replace $f(x,y)$ by $f(x,y)h(tx,ty)$ where $h:\mathbb{R}^2\to\mathbb{R}$ is absolutely integrable
and then take the limit as $t\to 0$. But it is not quite clear whether this procedure will be independent of $h$, even if one takes $h=e^{-q(x,y)}$ with $q$ a positive definite quadratic polynomial
(not necessarily homogeneous).
Answer: The answer to the modified version of question 1 is yes. Let $g_0:\mathbb{R}\to\mathbb{R}$ be given by $x\mapsto x/(1+x^4)$ (basically we need an odd function which would be take positive values on the positive half-axis and whose integral would converge absolutely). Set $g(x,y)=g_0(x)$. Let $A$ be a real number $\geq 0$. For $t\geq 0$ set
 $\epsilon(t)=\int_t^{2t}g_0(t) dt$ and take $$X^A_t=\{(x,y)\in\mathbb{R}^2\mid -t\leq x\leq 2t,\frac{-A}{2\epsilon(t)}\leq y\leq\frac{A}{2\epsilon(t)}\}.$$  Then $\int_{X^A_t}g(x,y)dxdy =A$ for all $t$. Similarly, if one takes $$Y^A_t=\{(x,y)\in\mathbb{R}^2\mid -2t\leq x\leq t,\frac{-A}{2\epsilon(t)}\leq y\leq\frac{A}{2\epsilon(t)}\},$$ then $\int_{Y^A_t}g(x,y)dxdy =-A$ for all $t$


Prove range of f',$\{f'(x),x\in X\}$ dense in $X^*$

Question: Let $X$ be a Banach Space and let $f: X\rightarrow \Bbb R$ be a Fre'chet differentiable function. Suppose that $f$ is bounded from below on any bounded set and satisfies
$lim_{||x||\rightarrow \infty}\dfrac{f(x)}{||x||}=\infty$.
Then the range of $f'$,$\{f'(x),x\in X\}$ is dense in $X^*$.
I try to apply Ekeland's variational principle a s below:
Put $g(x)= f(x)+ \langle x^*, x\rangle$. Since $lim_{||x||\rightarrow \infty}\dfrac{f(x)}{||x||}=\infty$, we have $f(x) \ge M||x||, \forall M>0$. Combine with  $f$ is bounded from below on any bounded set, we have $f$ bounded from below. So we easily prove that $g(x)$ is lower semicontinuous and bounded from below. But I don't know how to use Ekeland's variational principle to continue this prove.
Could you help me? Thank you so much.
Answer: First, we apply Ekelands principle to $g$. Take $\varepsilon>0$ and any point $u \in X$ with $g(u) \le \inf g + \varepsilon$ (which exists by definition of $\inf g$). Then, we find $v \in X$, such that $\| u - v \| \le 1$ and
$$g(w) > g(v) - \varepsilon \, \|v-w\|$$
for all $w \in X$.
Using this inequality, what can you say about $g'(v)$?
Comment: Sorry for late response, because this problem appears in the section about Ekeland's principle, but I don't get the way to use Ekeland's Principle to solve it!
Comment: If have sketched the solution in my answer: Ekeland's principle could be used on $g$.
Comment: Could you please post detail your solution for this problem. THank you so much.
Comment: Do you mean details on the application of Ekeland or on the consequences of the inequality in my answer?
Comment: Application Ekeland for this problem. Could you post solution for this problem?
Comment: I have added some (trivial) details concerning the application of Ekeland.


Generating the Nth combination of a binomial coefficient

Question: I'm designing a protocol, and need a bit of help. I am able to neatly condense the problem I am having into a allegory, I hope it doesn't sound too contrived.

Alice has flipped a coin t times, and has told me it has landed on heads k times.
From this, I am able to figure out how many different possible combinations of ways that Alice could have got this result:

function binom(t, k) {
    var coeff = 1;
    for (var i = t-k+1; i <= t; i++) coeff *= i;
    for (var i = 1;     i <= k; i++) coeff /= i;
    return coeff;
}

but now Alice wants to tell me the precise combination of heads-and-tails to she got, however she is restricted to only telling me a single number, the Nth possible way of generating the results she flipped.
So describe an algorithm that turns t (total coin flips), k (amount of heads) and n into a sequence of heads-and-tails.
There are multiple ways of ordering all possible combinations, so there are multiple answer. But in my case, it doesn't matter how Alice orders the combinations (and thus the N she gives me) as long as I have a procedure to efficiently decode it.
Answer: I've tested the following and it seems to work. It's in SQL as opposed to C but I hope you can follow the syntax. I'm not sure how much explanation you need but let me know if you have questions. The dbo.Choose() function is the same as your binom() function.
    -- Parameters
declare @t int; set @t = 8
declare @k int; set @k = 3
declare @n int; set @n = 7
    -- Variables
declare @seq varchar(8000); set @seq = ''
declare @m int; set @m = @n
declare @NumberOfCombinations int; set @NumberOfCombinations = dbo.Choose(@t, @k)
declare @HeadsRemaining int; set @HeadsRemaining = @k
declare @FlipsRemaining int; set @FlipsRemaining = @t
    -- .
    -- Work left-to-right: in each iteration, decide if the char is H or T, then
    -- set up the variables for the next iteration.
while @FlipsRemaining > 0 begin
    if @m <= @NumberOfCombinations * @HeadsRemaining / @FlipsRemaining begin
        -- Since C(t-1,k-1) / C(t,k) = k/t is the proportion of entries starting with H
        -- and same rule then applies at each subsequent level.
        set @seq = @seq + 'H'
        set @NumberOfCombinations = @NumberOfCombinations * @HeadsRemaining / @FlipsRemaining
        set @HeadsRemaining = @HeadsRemaining - 1
    end
    else begin
        set @seq = @seq + 'T'
        set @m = @m - @NumberOfCombinations * @HeadsRemaining / @FlipsRemaining
        set @NumberOfCombinations = @NumberOfCombinations * (@FlipsRemaining - @HeadsRemaining) / @FlipsRemaining
    end
    set @FlipsRemaining = @FlipsRemaining - 1
end
select @seq

This works on the following style of ordering, starting the H's leftmost and ending with H's rightmost. ($t=5, k=3$):
\begin{eqnarray*}
1 && HHHTT \\
2 && HHTHT \\
3 && HHTTH \\
4 && HTHHT \\
5 && HTHTH \\
6 && HTTHH \\
7 && THHHT \\
8 && THHTH \\
9 && THTHH \\
10 && TTHHH.
\end{eqnarray*}
So, $t=5,k=3,n=5$ results in HTHTH.


How to pass a 2-dimensional Vector to a function in rust?

Question: I'm trying to pass a 2-d array to a function but I cant figure out how to specify the expected type of the function.
My code looks like this
fn main() {
    let ker = vec![[-1, -1, -1], [-1, 8, -1], [-1, -1, -1]];

    do_schtuff(ker);
}

fn do_schtuff(k: Vec<Vec<i32>>) {
    println!("{:?}", k);
}

P.S.: I'm new to rust so any advice would be really appreciated! Thanks!
Comment: Isn't this a vector of arrays, a.k.a. `Vector<[i32; 3]>`?
Comment: FYI, the better way to have a two dimensional vector is to have a 1-dimensional vector with an API that let it use as a 2-dimensional one. I'm pretty sure that some crates exist to do that.
Answer: You don't actually have a two dimensional vector there. You have a vector of integer arrays. You need to change your code to actually use a vector with integer vectors in it:
fn main() {
    let ker = vec![vec![-1, -1, -1], vec![-1, 8, -1], vec![-1, -1, -1]];
    do_schtuff(ker);
}

fn do_schtuff(k: Vec<Vec<i32>>) {
    println!("{:?}", k);
}

Though it almost certainly would be better to not move the vector and give ownership to the do_schtuff function, but instead to pass the vector as a reference to a slice:
fn main() {
    let ker = vec![vec![-1, -1, -1], vec![-1, 8, -1], vec![-1, -1, -1]];
    do_schtuff(&ker[..]);
}

fn do_schtuff(k: &[Vec<i32>]) {  // Note it is more idiomatic to use a slice.
    println!("{:?}", k);
}


Kubernates assing multiple endpoints

Question: i have the following configurations on kubernates:
apiVersion: apps/v1beta2
kind: Deployment
metadata:
  name: {{ include "e-lucene-eva.fullname" . }}
  labels:
    app.kubernetes.io/name: {{ include "e-lucene-eva.name" . }}
    helm.sh/chart: {{ include "e-lucene-eva.chart" . }}
    app.kubernetes.io/instance: {{ .Release.Name }}
    app.kubernetes.io/managed-by: {{ .Release.Service }}
spec:
  replicas: {{ .Values.replicaCount }}
  selector:
    matchLabels:
      app.kubernetes.io/name: {{ include "e-lucene-eva.name" . }}
      app.kubernetes.io/instance: {{ .Release.Name }}
  template:
    metadata:
      labels:
        app.kubernetes.io/name: {{ include "e-lucene-eva.name" . }}
        app.kubernetes.io/instance: {{ .Release.Name }}
    spec:
      containers:
        - name: {{ .Chart.Name }}
          image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
          imagePullPolicy: {{ .Values.image.pullPolicy }}
          ports:
            - name: evaptr
              containerPort: 8089
          resources:
            resources:
            limits:
              cpu: 150m
              memory: 1528Mi
            requests:
              cpu: 100m
              memory: 664Mi

apiVersion: v1
kind: Service
metadata:
  name: st-evabot-adm-backend-service
  namespace: st-evabot
spec:
  ports:
    - targetPort: bck-port
      port: 80
      protocol: TCP
  selector:
    app: evabot
    tier: backend

but when i run kubectl get endpoints:
NAME                                       ENDPOINTS                                                    AGE
evabot-db-service                          126.96.36.199:27017                                         19h
evabot-lucene-service                      188.8.131.52:8089,22.214.171.124:8089,22.214.171.124:8089   13h

why i have 3 ip ? and other has just 1?
Another question is .. these ips are for the connections with other pods ?
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  annotations:
    deployment.kubernetes.io/revision: "1"
  creationTimestamp: null
  generation: 1
  labels:
    app.kubernetes.io/instance: st-evabot-evabot-lucene
    app.kubernetes.io/managed-by: Tiller
    app.kubernetes.io/name: e-lucene-eva
    helm.sh/chart: e-lucene-eva-0.1.1
  name: st-evabot-evabot-lucene-e-lucene-eva
  selfLink: /apis/extensions/v1beta1/namespaces/st-evabot/deployments/st-evabot-evabot-lucene-e-lucene-eva
spec:
  progressDeadlineSeconds: 600
  replicas: 1
  revisionHistoryLimit: 10
  selector:
    matchLabels:
      app.kubernetes.io/instance: st-evabot-evabot-lucene
      app.kubernetes.io/name: e-lucene-eva
  strategy:
    rollingUpdate:
      maxSurge: 25%
      maxUnavailable: 25%
    type: RollingUpdate
  template:
    metadata:
      creationTimestamp: null
      labels:
        app.kubernetes.io/instance: st-evabot-evabot-lucene
        app.kubernetes.io/name: e-lucene-eva
    spec:
      containers:
      - image: registry-dgt.eni.com/eni/evabot-lucene:1.0.4
        imagePullPolicy: IfNotPresent
        name: e-lucene-eva
        ports:
        - containerPort: 8089
          name: evaptr
          protocol: TCP
        resources:
          limits:
            cpu: 150m
            memory: 1528Mi
          requests:
            cpu: 100m
            memory: 664Mi
        terminationMessagePath: /dev/termination-log
        terminationMessagePolicy: File
      dnsPolicy: ClusterFirst
      restartPolicy: Always
      schedulerName: default-scheduler
      securityContext: {}
      terminationGracePeriodSeconds: 30
status: {}

evabot-adm-ui-service                      ClusterIP   126.96.36.199   <none>        3031/TCP       21h       app=evabot,tier=frontend
evabot-lucene-service                      ClusterIP   220.127.116.11    <none>        8089/TCP       2h        app=evabot
st-evabot-adm-backend-service              NodePort    188.8.131.52   <none>        80:31971/TCP   8m        app=evabot,tier=backend
st-evabot-db-service                       ClusterIP   220.127.116.11   <none>        27017/TCP      31m       app=mongo-proxy
st-evabot-evabot-db-mongodb-replicaset     ClusterIP   None             <none>        27017/TCP      3d        app=mongodb-replicaset,release=st-evabot-evabot-db
st-evabot-fe-evabot-web-apache-webserver   ClusterIP   220.127.116.11    <none>        80/TCP         1d        app=apache-webserver,release=st-evabot-fe-evabot-web
tiller-deploy                              ClusterIP   22.214.171.124    <none>        44134/TCP      6d        app=helm,name=tiller

Comment: sorry i m a noob in kubernates can you just provide me an answer for help? or to undestand what is happening?
Comment: Can you share information about deployment with actual values data: `kubectl get deployment  -o yaml --export` and services running in the cluster: `kubectl get svc -o wide` ?
Comment: i updated the question
Comment: @mk_sta check it
Answer: I was not able to find neither app=evabot nor tier=frontend labels through the provided deployment manifest file, therefore the services evabot-db-service and evabot-lucene-service are exposing a different deployments(Pods).
However, you can easily retrieve information from your cluster about all components which are related to the labels app=evabot or tier=frontend:
kubectl get all -l app=evabot
kubectl get all -l tier=frontend
In general, Endpoint is the final point of your request where the Service will route network traffic to when a connection has been established to the Pods IP address. They can be auto discovered by Kubernetes with selectors or manually managed.
I assume that for evabot-lucene-service service in your example, possibly three Pods have been created by ReplicaSet, that are finally serving requests by their Endpoints:

evabot-lucene-service
  18.104.22.168:8089,18.104.22.168:8089,18.104.22.168:8089

For evabot-db-service service, only one Pod represents the Endpoint.

evabot-db-service                          184.108.40.206:27017

In case of any doubt or question, write a comment below this answer.

Kubernates assing multiple endpoints


Mvc Ajax call to controller not returning statusText

Question: I am using jquery 3.2.1 with .NET framework 4.5.2 MVC.
I have an jquery ajax call to an mvc controller. If the action is successful, the return is
return new HttpStatusCodeResult(200, "success message");

and when it fails,
return new HttpStatusCodeResult(400, "failure message");

and here is my javascript call:
var promise = $.ajax({
    method: 'POST',
    url: '/Home/TestAjaxAsync',
    // ...
});

promise.done(function(results) {
    console.log("got success: ");
    console.log(results);
});

promise.fail(function(err) {
    console.log("got error: ");
    console.log(err);
});

all of this is working perfectly on local machine in visual studio IIS express, and when hosted locally. I can send the request and get "success message" and "failure message" in statusText property with status code.
But when hosted in production server remotely, this stops working. I am able to send the request successfully and receive the response successfully and get "success message" for 200 OK. But for 400, 401, 403 or any other error codes, the statusText is always "error". Sometimes, the custom message is shown in responseText as a YSOD with full html markup.
I have tried the following also but could not get it to working on production server at all.
return new HttpStatusCodeResult(HttpStatusCode.BadRequest, "failure message");

Comment: sounds like a server setting for _friendly error messages_ (or similar, custom errors off perhaps) is overriding your status codes. Check settings.
Answer: As by jQuery Documentation

jqXHR.done(function( data, textStatus, jqXHR ) {});
An alternative construct to the success callback option, refer to deferred.done() for implementation details.
jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
An alternative construct to the error callback option, the .fail() method replaces the deprecated .error() method. Refer to deferred.fail() for implementation details.

The first argument of done(function(...)) is data, but the first argument of fail(function(...)) is jqXHR, which..

is a superset of the browser's native XMLHttpRequest object

You should try
promise.fail(function (jqXHR) {
    console.log("got error: ");
    console.log(jqXHR.responseText);
});

or
promise.fail(function (jqXHR, textStatus) {
    console.log("got error: ");
    console.log(textStatus);
});

or
promise.fail(function (jqXHR, textStatus, errorThrown) {
    console.log("got error: ");
    console.log(errorThrown);
});

Depending on what works best for you.
Comment: i tried all the above implementations. I am not getting "failure message". instead i always get statusText: "error"
Comment: @HuSen That's.. unfortunate.
Comment: thing is i have been using this practice in almost all of my applications and never failed... until now... very strange indeed
Answer:
Add baseurl with your Ajax url parameter.

var geturl = window.location;
var baseurl = geturl.protocol + "//" +geturl.host + "//" + geturl.pathname.split('/')[1];

url : baseurl + 'controller/action'
Answer: try this when it fails:
throw new HttpException(400, "bad request");


Optimization of linear objective with quadratic integer constraint

Question: Is there any way to solve an linear optimization problem with quadratic integer constraint?
E.g.
$\max a^Tx$, $x=\langle x_1,x_2,\cdots,x_n \rangle$
s.t. $x_ix_j<b_{ij}$, $\forall x_i,x_j \in x$
$x_i \in \{0,1\}, \forall x_i \in x$
Answer: Since $x$ is binary and the product only can be $0$ or $1$, your model is a bit odd with the strict inequality. If $b_{ij} >1$ then $x_i$ and $x_j$ are arbitrary, and if $b_{ij} \leq 1$ then you must model the fact that one of the terms has to be zero, which you can do by $x_i + x_j \leq 1$.
Comment: No, for $b_{ij}=1$ one of them has to be zero, since the product has to be $0$ in that case
Comment: ...for $0 < b_{ij} < 1$ the product has to be $0$. For $b\leq 0$ the problem is infeasible. You seem to fail to appreciate that you have a strict inequality (which I commented upon in my answer)
Comment: I see what you mean… I also realized my model looks weird with the 0 or 1 value for $x_i$… But if $b_{ij}=1$ then $x_i$ and $x_j$ can be 1 at the same time
Comment: For $b_{ij}=1$, $x_i$ and $x_j$ can also be arbitrary. So is there any way to mathematically specify the constraint to $b_{ij}<1$?


Significantly more sightings over the years?

Question: This is probably something very easy for many of you, but I am not sure if I am doing this right. I am a biologist and have been looking at the occurrence (per year) of a certain species in a certain area from 2001 to 2016. As this is a rare species, in two years we saw none, in the other years we saw 1-10 individuals. It seems like the animals are being seen more in recent years and I think there is a significant increase of them over the years. But how do I test this? I have simplified my dataset to just years and a number of sightings in that year (of different individuals, so no double counts):

If I run a linear regression in SPSS my p-value is significant. But is this the right way to do it?
Comment: Yes, sure! Is it better like this?
Comment: It looks like time series analysis would be better.,
Comment: Rare count can be modelled by Poisson distribution, so a poisson regression might do ... or time series, but with a few sightings of a rare animal I doubt if time correlation is important. More sightings might be because of more effort, are you sure the effort was approximately constant? (effort might be used as an ofset in a poisson model, so if you have data about effort, post that also)
Comment: @kjetilbhalvorsen Unfortunately I do not have effort data, but I do think effort was fairly constant. Do you think this dataset is too small for a statistical conclusion?
Answer: Small counts like with a few sightings of a rare animal are usually well modelled by a Poisson distribution, so Poisson regression is indicated.  Variability in number of sightings of a rare animal could well be caused by a varying level of effort, below I assume this is not the case, that is, effort is approximately constant over time. (If you have effort data, it could be included as an offset via the argument  offset=log(effort) in the glm command below).
I show below an analysis of your data using Poisson regression in R, which I think is more appropriate than the analysis you presents in the question. R code is:
year      <-  2001:2016
sighting  <-  c(1,0,3,2,0,4,2,2,5,4,4,10,8,3,6,5)
dat  <-  data.frame(year,sighting)
# Poisson regression model:
mod.0  <-  glm(sighting ~ year, family=poisson, data=dat)
summary(mod.0)
confint(mod.0)
plot(mod.0)

Which produces the following output:
> mod.0  <-  glm(sighting ~ year, family=poisson, data=dat)
> summary(mod.0)

Call:
glm(formula = sighting ~ year, family = poisson, data = dat)

Deviance Residuals:
    Min       1Q   Median       3Q      Max
-2.0802  -0.7293  -0.2194   0.8220   2.0665

Coefficients:
              Estimate Std. Error z value Pr(>|z|)
(Intercept) -227.69850   61.49336  -3.703 0.000213 ***
year           0.11395    0.03058   3.726 0.000194 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for poisson family taken to be 1)

    Null deviance: 33.801  on 15  degrees of freedom
Residual deviance: 18.770  on 14  degrees of freedom
AIC: 67.106

Number of Fisher Scoring iterations: 5

> confint(mod.0)
Waiting for profiling to be done...
                    2.5 %       97.5 %
(Intercept) -351.90183933 -109.9909922
year           0.05539646    0.1757022

(I do not show here the plots, which do not indicate any problems with the model)
Note that the confidence interval on the slope parameter is far away from zero, so some increase in abundance with time is indicated.  With so few data effective model criticism (based on residuals and such) is not really possible, so you need to believe in the model!
Comment: +1. The final discussion is especially important, since these data exhibit an interesting characteristic.  Because sightings are assigned to years, rather than specific dates, we might ask how sensitive the results are to slight changes in the dates.  The answer is that the most recent three years are noticeably more influential on the coefficient estimates than any of the previous years. Thus, if the purpose is to estimate rates of change over time, we should note that (1) this Poisson model posits exponential increase and (2) the last three years of data begin to challenge that assumption.
Comment: Thank you very much for the effort and explanation! I have to look at this again but it does make more sense than my SPSS try.
Answer: As kjetil writes, there is rather little data here - too little to draw truly firm conclusions.
My personal impulse in such a situation is to look at multiple models and see whether they agree in principle.
Let's first draw a graph.
year <- 2001:2016
sightings <- ts(c(1,0,3,2,0,4,2,2,5,4,4,10,8,3,6,5),start=2001)
plot(sightings,type="o",pch=19)

Well, the graph does look rather convincing, even if it is only 16 data points. I'd certainly rather bet on the 2017 observation to be larger than 4, rather than 4 or less.
Here is the R analogue to the linear regression you calculated in SPSS. Note that the p values match:
summary(lm(sightings~year))

Coefficients:
             Estimate Std. Error t value Pr(>|t|)
(Intercept) -796.7588   220.6300  -3.611  0.00283 **
year           0.3985     0.1098   3.628  0.00274 **

As kjetil suggested, a Poisson regression would also make sense:
summary(glm(sightings~year,family="poisson"))

Coefficients:
              Estimate Std. Error z value Pr(>|z|)
(Intercept) -227.69850   61.49336  -3.703 0.000213 ***
year           0.11395    0.03058   3.726 0.000194 ***

This model also finds a significant trend. However, the linear and the Poisson regression posit very specific trends: a linear one in the first case and an exponential one in the second case.
An alternative would be to test the correlation between sightings and year. The pearson correlation again calculates a linear trend:
cor.test(sightings,year,method="pearson")

t = 3.628, df = 14, p-value = 0.002742

Note how the p value is exactly the same as for the simple linear model.
Alternatives would be the spearman and the kendall correlations, which test for any kind of monotonous relationship between years and sightings, not only linear or exponential ones:
cor.test(sightings,year,method="kendall")

z = 2.9576, p-value = 0.0031

cor.test(sightings,year,method="spearman")

S = 156.75, p-value = 0.0004915

Although both tests output warnings, because they cannot calculate exact p values if ties are present, they again find significant trends.
Finally, as Michael Chernick notes, you actually have a time series, so a time series analysis might be useful. Your count data really call for an INAR model or similar, but there are really no common count data time series models that account for trend, so I'll just fit an ARIMA model and an ETS one:
library(forecast)
auto.arima(sightings)

Series: sightings
ARIMA(0,1,0)

sigma^2 estimated as 8:  log likelihood=-36.88
AIC=75.76   AICc=76.07   BIC=76.47

ets(sightings)

ETS(A,N,N)

Call:
 ets(y = sightings)

  Smoothing parameters:
    alpha = 0.3891

  Initial states:
    l = 1.3

  sigma:  2.3277

We note that auto.arima() models an ARIMA(0,1,0) process, which means that it believes that first differences are white noise. First differences again indicate a trend. Finally, ETS is the only one that does not find a trend, it only finds additive error (the first "A"), no trend ("N") and no seasonality ("N"). However, it finds a very large smoothing value of $\alpha = 0.39$, so it thinks your sightings might be a weak kind of a random walk. Note that these models are fitted using information criteria, so it doesn't make sense to assign a p value to the trends they find (or not).
In summary, most of these different models do find a trend, even if they are designed to look at different kinds of trends (linear, exponential, general monotone, first differences). This, together with the plot, would certainly be enough to convince me that there is indeed a trend in your data.
Comment: Thank you so much for your effort and explanation. That really helped a lot! I will have to look at all of this again in detail but it makes a lot more sense now.


"COPY_ERROR: Unable to copy" while using drush make with download type "copy"

Question: Here is my module structure:
.
|-- mymodule.make
|-- mymodule.info
|-- mymodule.module
|-- mymodule.install
`-- sub1
    |-- sub1.make
    |-- sub1.info
    |-- sub1.module
    `-- sub1.install

I would like that when using drush make the sub-module sub1 is also made (so I would like that sub1.make is called too).
In mymodule.make I declare:
api = "2"
core = "7.x"

projects[drupal][version] = "7.39"

; Modules
projects[sub1][type] = module
projects[sub1][download][type] = copy
projects[sub1][download][url] = "./sub1"

And here is the error that I have:
Found makefile: mymodule.make                                [ok]
COPY_ERROR: Unable to copy sub1 from ./sub1. -- build forced [warning]

However, the documentation tells

download[type] = copy Copies a project from a local folder.

so I think I'm using the correct [download][type]...
I've also tried with projects[sub1][download][url] = "file://./sub1" and have the same error.
Comment: Did you check is not simply a file permission issue?
Comment: Actually I've checked that and it's not the issue here, no file permission problems...
Answer: As a workaround, I used the includes[] directive instead.
Here is my working mymodule.make:
api = "2"
core = "7.x"

projects[drupal][version] = "7.39"

; Modules
includes[] = ./sub1/sub1.make


Using pipe when executing command in perl

Question: I am trying to use following command in perl but it giving me error
system("zcat myfile.gz | wc > abc.txt");

But when i run this I am getting error
syntax error near unexpected token `|'
Even if I remove >abc.txt I am still getting error.
Can we use pipe with system command?
Here are error details:
sh: -c: line 1: syntax error near unexpected token `|'
sh: -c: line 1: ` | wc '

Comment: Works for me. What are the actual filenames?
Comment: I am trying to give system("zcat myfile.gz | wc"); but its not working .
Comment: works for me too on solaris.
Comment: Actually its myfile*.gz and there is only one file matching it
Comment: hmmm but I am getting same error again..is there any way to debug this?
Comment: I suppose you have tried that exact command on the command line and it works?
Comment: yes it works prefect on command line :(
Comment: Note that this call uses `/bin/sh -c` for the shell, which might not be the same one you normally use.  Perhaps try it on that one?
Comment: @dan1111 can u explain a bit more what should I try?
Comment: run `/bin/sh` from the command line and then try the command. Is it the same?
Comment: @dan111 yes its same even after running /bin/sh
Answer: Next time, test your demo program to make sure it actually exhibits the behaviour you said it does. You actually ran something closer to
while (my $file_name = <>) {
   system("zcat $file_name | wc > abc.txt");
}

There are two errors in that:

You didn't remove the trailing newline, so the shell was trying to execute
zcat def.gz
 | wc >abc.txt

instead of
zcat def.gz | wc >abc.txt

You didn't transform the file name into a shell literal before emdedding it your command.
Consider what would happen if the file name contained a space. You would be executing
zcat def ghi.gz | wc >abc.txt

instead of
zcat 'def ghi.gz' | wc >abc.txt

Solution:
use String::ShellQuote qw( shell_quote );

while (my $file_name = <>) {
   chomp($file_name);
   system("zcat -- ".shell_quote($file_name)." | wc > abc.txt");
}

Comment: why you have used zcat -- in system call
Comment: In case the file names starts with a "`-`".
Answer: It is working as expected:
perl -lne 'system("cat *.java|wc");'

Something odd with your filename, maybe.
You could check the interpolation of your shell like this:
my @file = `ls -1 myfile*.gz`;chomp(@files);
print join("\n",@files);

There are other possibilites to execute in perl, like backtick, open with |, qx.
If you are trouble with filenames, you could get the filenames by yourself and call the system in a specific way to avoid executing shell: http://docstore.mik.ua/orelly/perl/cookbook/ch19_07.htm

If there is only one scalar argument, the argument is checked for shell metacharacters, and if there are any, the entire argument is passed to the system's command shell for parsing (this is /bin/sh -c on Unix platforms, but varies on other platforms). If there are no shell metacharacters in the argument, it is split into words and passed directly to execvp , which is more efficient.
Comment: what do u mean by checking  interpolation of your shell like this:
Comment: I am newbie in perl , can u provide me example how to achieve this using open or backtick or qx
Answer: I got this error message when trying to use backticks to execute a pipeline that included a cut -d \| command. Turns out I had to double escape the pipe character eg cut -d \\|


div height prob after jquery hide()

Question: after hiding some inner divs with jquery hide() function, the outer div height doesn't fit and its height is as long as it was before hiding.
i've this problem with IE, FF not with Chrome.
what's the solution !!
( i can give the page url if requested )
Comment: A minimal example on jsfiddle.net would be excellent.
Comment: @Douglas  would u check it here ? ( right sidebar click (+) sign to expand ) [click here](http://softkharid.com)
Answer: Are you saying the outer div's height did or didn't change?   Remeber when you do a hide() your setting the css to a "display:none".  This means the element will not take up anyspace in the DOM and if it was controlling the height of the outer div, then you will have to manually set the outer div height after it is hidden.
Another option would to be is to let the outer div control the height and then just hide() or show() its contents. that way it will maintain its dimensions.
Hope this helps
Comment: would u explain more ur second suggestion ;)

div height prob after jquery hide()


add a user and role programatically

Question: I am using the following code to add a user:
  $roles = user_roles();
  $userinfo = array(
  'name' => 'user2',
  'pass' => '123456',
  'init' => 'user2d',
  'status' => 1,
  'access' => REQUEST_TIME,
  // This is where we are different from the default function.
  'roles'        => array(array_search('student', $roles) => 6),

);
$account = user_save(drupal_anonymous_user(), $userinfo);

I am getting this error message:
PDOException: SQLSTATE[23000]: Integrity constraint violation: 19 column name is not        unique:
INSERT INTO {users} (uid, name, pass, created, access, status, init) VALUES (?, ?, ?, ?, ?, ?, ?); Array ( [0] => 15 [1] => user2 [2] => $S$DrkIg0KuBFO12eQ9nQ5ViSx4ydfcWS0nS1TMvaTjYyZyfmVniGgh [3] => 1333135061 [4] => 1333135061 [5] => 1 [6] => user2d ) in drupal_write_record()
(line 6975 of

I am wondering if someone can explain what is going wrong with me trying to add a role. ......
Answer: drupal_anonymous_user() gives you an object with a uid that is considered empty by PHP. This means, your call to user_save() will try to insert a new user into the database. The insert operation fails, because a user with the name user2 already exists in the database.
Comment: thank you that was a very clear and concise answer. I will remember when i see that error again what to look for.

add a user and role programatically


Properties of Euler's totient function

Question: I'm having some trouble understanding the following proposition:

Let $\phi$ be the Euler's totient function. If $p$ is a prime number and $n,m \in \mathbb N$, then:

$\phi(p)=p-1$
$\phi(p^n) = p^n - p^{n - 1}$
If $\gcd(m,n)  = 1$, then $\phi(mn)=\phi(m)\phi(n)$

I can understand and prove proposition number (1), but as for (2) and (3) I'm not understanding intuitively what they are saying and why they are true. Can someone explain to me the intuition behind proposition (2) and (3) and show me the proof?  Thanks
Comment: For (2), $\frac1p $ of the numbers from $1$ to $p^n$ are multiples of $p$ and hence not relatively prime to $p^n$
Comment: For (3), see the Addendum to [this](https://math.stackexchange.com/questions/3858851/number-of-positive-integers-le-n-which-are-a-multiple-of-p/3858930#3858930).
Answer: Why (3) is true intuitively:
For each $m_{i}$, $n_{j}$ respectively coprime and less than $m$, $n$, we can build one and only one $x_{ij}$ less than $m.n$ such that $x_{ij}$ has as remainder $m_{i}$ modulo $m$, and $n_{j}$ modulo $n$ (this is essentially the chinese remainder theorem). Such number $x_{ij}$ is coprime with $m$ and $n$, so coprime with $m.n$. The $x_{ij}$ are mutually different as they produce different remainders modulo $m$ and $n$. And their number is the number of couples $(m_i, n_j)$ so $ϕ(m).ϕ(n)$.
Answer: Let $(a,b)$ denote the gcd of $a$ and $b$, then
$$
\varphi(n)\triangleq\sum_{k\le n,(k,n)=1}1=\sum_{k\le n}\left\lfloor1\over(k,n)\right\rfloor
$$
where $k$ runs from 1 to $n$. By the property that
$$
\sum_{d|n}\mu(d)=\left\lfloor\frac1n\right\rfloor
$$
we obtain
$$
\begin{aligned}
\varphi(n)
&=\sum_{k\le n}\sum_{d|k,d|n}\mu(d)=\sum_{d|n}\mu(d)\sum_{k=jd\le n}1 \\
&=\sum_{d|n}\mu(d)\sum_{j\le n/d}1=\sum_{d|n}\mu(d)\cdot\frac nd \\
\end{aligned}
$$
Because the $n$ and Mobius function $\mu(n)$ are multiplicative, we deduce that $\varphi(n)$ is multiplicative as well due to the property of Dirichlet convolution.
For prime power $p^n$ ($n\ge1$), we have
$$
\varphi(p^n)=\sum_{k=0}^n\mu(p^k)p^{n-k}=\mu(1)p^n+\mu(p)p^{n-1}=p^n-p^{n-1}
$$

Properties of Euler's totient function


Display Data from Google Sheet into Google Forms

Question: I am creating a Quiz.
What I did first is to create data in google sheet and here it is
Link of Google Sheet
as you can see there I have 2 sheet and that is Questions and Answers
My Question is how can i display the Question and Answers in there respective position in Google Forms i am linking them by Question ID
TYSM
Comment: Check the [Quickstart: Managing Responses for Google Forms](https://developers.google.com/apps-script/quickstart/forms) as it demonstrates connecting Google Sheets to Google Form, which is the first step in your project.

Then there's the [HOW TO CREATE AN ENTIRE GOOGLE FORM FROM SCRATCH FROM A GOOGLE SPREADSHEET](https://www.youtube.com/watch?v=pXUsW6VRQak) video tutorial, which may offer additional insight.
Comment: Hello Sir Good Morning, Based on what you gave. It does help but it has an error when adding an Image.
Answer: I think the comments above will help you. This is also code (with help from here) which copies a multiple-choice question from one quiz to another.
If you combine this code with the stuff referred to in the comments about reading stuff from a sheet then you should be ok.
I see that you mention a problem copying images.  I'm stuck at that point too.
<code>function copyMultipleChoiceItem(item1, item2) {
//  copies MC question item1 to item2 - tested PDW 17/05/20
//  copy of feedback now working - tested PDW 17/05/30
//
    var item1MC = item1.asMultipleChoiceItem();
//  basic question items
    item2.setTitle(item1.getTitle());
    item2.setHelpText(item1.getHelpText());
    item2.setPoints(item1MC.getPoints());
    item2.setRequired(item1MC.isRequired());

//  the choices
    var choices = item1MC.getChoices();
    for (var i = 0; i < choices.length; i++) {
        item2.createChoice(choices[i].getValue(),choices[i].isCorrectAnswer());
    }
    item2.setChoices(choices);
//  the feedback
    var feedback1 = item1MC.getFeedbackForCorrect();
    item2.setFeedbackForCorrect(feedback1);
    var feedback1 = item1MC.getFeedbackForIncorrect();
    item2.setFeedbackForIncorrect(feedback1);
}
</code>
Answer: I'm not fully cleared about your question, but If you want an easy way to do a relationship between Google Sheets (columns) and Google Forms Drop-down lists and other Forms objects, you can try this add-on: formRange. Build your sheets then go to your Form and Addons. Chose formRange and install it. It's pretty easy to use and you have a little tutorial inside it.
formRanger: Google Form addon


Using recursion to display the same result in Binary Search and Insertion Sort (Python)

Question: I want to add in recursion in Binary Search and Insertion Sort to have them displayed the same output but while compiling, could not troubleshoot it. Where could have gone wrong? Getting unexpected indent errors for both of them.
Recursion using Binary Search
def binarySearch(alist, item):
    if len(alist) == 0:
        return False
    else:
        midpoint = len(alist)//2
    if alist[midpoint]==item:
        return True
    else if:
        if item<alist[midpoint]:
            return binarySearch(alist[:midpoint],item)
    else:
            return binarySearch(alist[midpoint+1:],item)

testlist = [0, 1, 2, 8, 13, 17, 19, 32, 42,]
print(binarySearch(testlist, 3))
print(binarySearch(testlist, 13))

Recursion using Insertion Sort (With a list)
def insertionSort(list):

  if i >= len(list):
    return list
  if list[i-1] > list[i]:
    temp = list[i]
    for a in range(0, i):
      if temp < list[a]:
        list.insert(a,temp)
        del list[i+1]
        break
  return insertionSort(list, i+1)

        while position > 0 and list[position - 1] > currentvalue:
            list[position] = list[position - 1]
            position = position - 1

        list[position] = currentvalue

list = [0, 1, 2, 8, 13, 17, 19, 32, 42,]
insertionSort(list)
print(list)

Comment: unexpected? in your binary search i already see you have an `else if :` without condition and in the else statement right below you have an indent error
Answer:
Code blocks are defined by their indentation. By "code block", I mean functions, if statements, for loops, while loops, and so forth. Indenting starts a block and unindenting ends it. There are no explicit braces, brackets, or keywords. This means that whitespace is significant, and must be consistent. In this example, the function code (including the doc string) is indented four spaces. It doesn't need to be four spaces, it just needs to be consistent. The first line that is not indented is outside the function.

by Dive into Python
Answer: you have to know how to use indentation. in your binary search code there are multipe indentation errors and here is the fix:
def binarySearch(alist, item):
    if len(alist) == 0:
        return False
    else:
        midpoint = len(alist)//2
    if alist[midpoint]==item:
        return True
    else:
        if item<alist[midpoint]:
            return binarySearch(alist[:midpoint],item)
        else:
            return binarySearch(alist[midpoint+1:],item)

testlist = [0, 1, 2, 8, 13, 17, 19, 32, 42,]
print(binarySearch(testlist, 3))
print(binarySearch(testlist, 13))

but your insertion sort is another story. you have undefined variables and etc. here is another implementation of insertion sort:
def insertionSort(list,i):
    if i<=1:
        return
    insertionSort(list, i - 1)
    currentvalue = list[i - 1]
    position = i - 2

    while (position >= 0 and list[position] > currentvalue):
        list[position + 1] = list[position]
        position = position - 1
    list[position + 1] = currentvalue

list = [0, 1, 2, 8, 13, 11, 19, 9, 42,]
insertionSort(list,len(list))
print(list)


Passing ViewModel from Presentation to Service - Is it Okay?

Question: In one of my views, I have a ViewModel which I populate from two tables, and then bind a List<ViewModel> to an editable GridView (ASP.NET Web Forms).
Now I need to send that edited List<ViewModel> back to the Services layer to update it in the database.
My question is - is it Okay to send the ViewModel back to Services, or should it stay in the Presentation? If not - should I better use a DTO? Many thanks.
Comment: I don't see any problems with that apporach
Comment: View-model is presentation layer.  You should use a DTO.
Comment: Although this is a good question, to be honest it does not quite fit the StackOverflow format, see the [faq](http://stackoverflow.com/faq#dontask): _there is no actual problem to be solved: "I'm curious if other people feel like I do."_
Answer: Nice question !
After several (hard) debates with my teammates + my experience with MVC applications, I would not recommend to pass viewmodel to your service / domain layer.

ViewModel belongs to presentation, no matter what.
Because viewModel can be a combination of different models (e.g : 1 viewModel built from 10 models), your service layer should only work with your domain entities.

Otherwise, your service layer will end up to be unusable because constrained by your viewModels which are specifics for one view.
Nice tools like https://github.com/AutoMapper/AutoMapper were made to make the mapping job.
Answer: I would not do it. My rule is: supply service methods with everything they need to do their job and nothing more.
Why?

Because it reduces coupling. More often than not service methods are addressed from several sources (consumers). It is much easier for a consumer to fulfil a simple method signature than having to build a relatively complex object like a view model that it otherwise may have nothing to do with. It may even need a reference to an assembly it wouldn't need otherwise.
It greatly reduces maintenance effort. I think an average developer spends more than 50% of his time inspecting and tracking existing code (maybe even much more). Now everybody knows that looking for something that is not there takes disproportionally much time: you must have been everywhere to be sure. If a method receives arguments (or object with properties) that are not used directly or further down the call stack you or others will walk this long road time and again.

So if there is anything in the view model that does not play a part in the service method, don't use it to call the method.
Comment: I have always leaned towards this (ie use its own models instead of VM) but what about the situation where the ViewModel would have the exact same properties as the Model? Wouldn't this be considered duplication?
Answer: Yes. I am pretty sure it is ok.
Try to use MS Entity Framework and it will help you allots.


React Query useMutation - "No overload matches this call"

Question: I'm using react-query in a typescript project, and am getting a hard to interpret type error when trying to use the useMutation() hook with a graphql query.
Example Code:
useMutation(
    async (
      parameter1: string,
      parameter2: string
    ) => {
      const response = await sdk.myMutation({
        parameter1: parameter1,
        parameter2: parameter2,
      });
      return response;
    },
    {
      onSettled: () => queryClient.invalidateQueries([CACHE_KEY]),
    }
);

Type Error:
  No overload matches this call.
  Overload 1 of 4, '(mutationFn: MutationFunction<{ __typename: "IdResponse"; id: string; }, string>, options?: Omit<UseMutationOptions<{ __typename: "IdResponse"; id: string; }, unknown, string, unknown>, "mutationFn"> | undefined): UseMutationResult<...>', gave the following error.
    Argument of type '(parameter1: string, parameter2: string) => Promise<{ __typename: "IdResponse"; id: string; }>' is not assignable to parameter of type 'MutationFunction<{ __typename: "IdResponse"; id: string; }, string>'.
  Overload 2 of 4, '(mutationKey: MutationKey, options?: Omit<UseMutationOptions<unknown, unknown, void, unknown>, "mutationKey"> | undefined): UseMutationResult<unknown, unknown, void, unknown>', gave the following error.
    Argument of type '(parameter1: string, parameter2: string) => Promise<{ __typename: "IdResponse"; id: string; }>' is not assignable to parameter of type 'MutationKey'.
  Overload 3 of 4, '(mutationKey: MutationKey, mutationFn?: MutationFunction<unknown, void> | undefined, options?: Omit<UseMutationOptions<unknown, unknown, void, unknown>, "mutationFn" | "mutationKey"> | undefined): UseMutationResult<...>', gave the following error.
    Argument of type '(parameter1: string, parameter2: string) => Promise<{ __typename: "IdResponse"; id: string; }>' is not assignable to parameter of type 'MutationKey'.

Answer: Although not obvious to me, the problem was that I tried to pass multiple parameters to the function used in useMutation.
The MutationFunction type only accepts a single parameter (confusingly called variables).
https://tanstack.com/query/v4/docs/reference/useMutation
To fix the problem I passed an object containing my parameters to the function like this:
useMutation(
    async ({
      parameter1,
      parameter2
    }:{
      parameter1: string,
      parameter2: string
      }
    ) => {
      const response = await sdk.myMutation({
        parameter1: parameter1,
        parameter2: parameter2,
      });
      return response;
    },
    {
      onSettled: () => queryClient.invalidateQueries([CACHE_KEY]),
    }
);

A cleaner idea might be to create a type to hold these parameters something like.
type myMutationParams ={
  parameter1: string;
  parameter2: string;
}

Then the useMutation hook looks something like this:
useMutation(
    async ({
      parameter1,
      parameter2
    }: myMutationParams
    ) => {
      const response = await sdk.myMutation({
        parameter1: parameter1,
        parameter2: parameter2,
      });
      return response;
    },
    {
      onSettled: () => queryClient.invalidateQueries([CACHE_KEY]),
    }
);

Comment: Many thanks for this example! Was dealing with the same issue
Answer: For me it usually happens when, I have any callback functions like onError, onSuccess or onSetteled.

Fix the typing, remove any types assigned in parameter.

For example:
// This is incorrect
onSettled: (_, err: CustomError) => {

},

// This is correct
onSettled: (_, err) => {
  const newErr = err as CustomError;
  // Now you can use the newErr
},

Check for types in mutationFn:
For example:
// This is incorrect
mutationFn: (accountId: string, accountDetails: Account) => {

},

// This is correct
type MutationParams = {
  accountId: string;
  accountDetails: Account;
};
mutationFn: (requestBody: MutationParams) => {
  // Now you can destructure param.
},

Be sure to only use one param, so just combine multiple params into object.


How do I find the visibleViewController in appdelegate?

Question: I currently instantiate the storyboards programmatically like so:
var iphone35StoryBoard:UIStoryboard = UIStoryboard(name: "iphone35", bundle: nil)

var initialViewController:UIViewController = iphone35StoryBoard.instantiateInitialViewController() as! UIViewController

self.window = UIWindow(frame: UIScreen.mainScreen().bounds)

self.window?.rootViewController = initialViewController

self.window?.makeKeyAndVisible()

This is my first time working with push notifications, so I'm unsure as the best practice, but what i'm trying to do is in didReceiveRemoteNotification and while the app is in an active state(foreground), I would like to be able to determine what view the user is currently on to determine if i should A) Call a local notificaiton or B) update the view if the push notification corresponds to the visible view.
Using various other SO related questions, I have tried to access the visibleviewcontroller using these variations of code:
let navigationController = application.windows[0].rootViewController as! UINavigationController

1)
let visibleController: AnyObject? = navigationController.visibleViewController

if visibleController is ProfileViewController {
    println("this works")
}

and
2)
let viewControllers: [UIViewController] = navigationController.viewControllers as! [UIViewController]

for vc in viewControllers {
    if vc is ProfileViewController {
        println("this works")
    }
}

3)
if let wd = self.window {
   var vc = wd.rootViewController
   if(vc is UINavigationController){
        vc = (vc as UINavigationController).visibleViewController
    }

    if(vc is ProfileViewController){
        println("this works")
    }
}

the problem i'm running into is that I can only obtain the rootviewcontroller and never the visible view controller. The rootviewcontroller in this case is a login screen, and despite me being on the profileViewController, i can only obtain the loginviewcontroller. Is this the best method for dealing with push notifications?
Answer: Move to destination view controller from storyboard when push notification will came
    let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main",bundle: nil)
    var destViewController : destVC
    destViewController = mainStoryboard.instantiateViewControllerWithIdentifier("destVC") as! destVC
    var navigationController =  UIApplication.sharedApplication().keyWindow!.rootViewController as! UINavigationController
    navigationController.pushViewController(destViewController, animated: true)

This is working for me from appdelegate.
Use notification center for more stuff :
NSNotificationCenter.defaultCenter().postNotificationName("name", object: nil, userInfo:nil)

NSNotificationCenter.defaultCenter().addObserver(self, selector: "method:", name: "name", object: nil)

func method(notification: NSNotification) {
    //Do your stuff.
}

Passing data with notification center
NSNotificationCenter.defaultCenter().postNotificationName("name", object:nil, userInfo:["message":"Unable to add \(homeName) Home"])

func method(notification: NSNotification) {
    //Do your stuff.
    println(notification.userInfo)
}

Comment: @Jay You can update your UI with the use of  `NSNotificationCenter`
Comment: thank you for answering! I'm going to edit my post, but what I was curious about was when the app is in the foreground. How do I update the UI / determine which view i'm on in order to properly update the UI?
Comment: You are right, I did not do my research properly. The question I should have been asking was, what is the best way to access the information that will update the UI? In the didReceiveRemoteNotification, how do I pass the userInfo to observer?


How do I get a dashboard like the one drupal.org is using?

Question: In search of making the dashboard for the user like drupal.org site I came to know there is a dashboard module in the drupal core. It is already enabled but I am not getting user interface like drupal.org site, not for admin and not for otehr users, How can I activate that so the user profile looks like what is on drupal.org site. I enabled the permission for user also. And where is the tab for the dashboard or how to enable it? Or am I missing something?
Comment: Combine [Views](https://www.drupal.org/project/views) with [Panels.](https://www.drupal.org/project/panels). Don't; know what is used on Drupal.org, but Panels will get you there.
Answer: The dashboard on drupal.org is made using Homebox module.

Homebox allows site administrators to create dashboards for their users, using blocks as widgets. Blocks in a Homebox page are resizeable, and reorderable by dragging.
Comment: Hmmm, yes that is true, it is made using the Homebox, later while doing search I  came to know that while reading that module's description. I tries also, and came to know it works as place holder only for blocks, various blocks we need to make using Views. Hence it does not provide predefined blocks with target of user profile, or user activity. Thanks for information though.


Nowhere differentiable Fourier transform

Question: Is there any $L_1$ function such that its fourier transform is in $L_1$ and the fourier transform is nowhere differentiable? Or every such Fourier transform must be differentiable a.e.?
Comment: If the function is continuous and compact supported, then is going to be bounded, so if it is also $L^1$ it will be also $L^2$, then its Fourier Transform is going to be an Analytic function (so a smooth transform), due to [Paley–Wiener theorem](https://en.wikipedia.org/wiki/Paley%E2%80%93Wiener_theorem#:~:text=In%20mathematics%2C%20a%20Paley%E2%80%93Wiener,Wiener%20(1894%E2%80%931964).). So your counter-example, or it will be a discontinuous function, or a continuous function in the whole line as domain.
Answer: Let $f$ be a bounded, nowhere differentiable function on $\mathbb{R}$. Let $g$ be a standard normal pdf. Then $gf$ is nowhere differentiable and in $L^2$. Also $\hat{(gf)} = \hat{g} * \hat{f} $. The fourier transform of a Gaussian is Gaussian, and convolving with a smooth function makes a smooth function, so $\hat{(gf)}$ is smooth and in $L^2$. So this exhibits a smooth function whose Fourier transform is nowhere differentiable. I think this is correct (?). Does it answer your question?
Comment: @user8268 I think the best I can do is argue that it is in $L^2$.
Comment: I guess you should still explain whether/when $\hat g * \hat f$ is $L^1$
Comment: I think $\hat{gf}$ may not be in $L^2$.
Comment: @Chaos My reasoning was that $g \in L^2$ (I think), so because $f$ is bounded, $gf \in L^2$. So the Fourier transform operator sends it to another element in $L^2$. (This latter Fourier transform is defined by extending the usual formula from the dense set of smooth compactly supported functions.) Oh but I see that its not clear the Fourier transform is in $L^1$... and perhaps that is not true?
Comment: @AreaMan Oh I see it's in $L^2$. But we can't say it's in $L^1$. There are some counterexamples .


How to simplify $\sin(n\frac{\pi}{2})$ as we do with $\cos(n\pi)$

Question: When calculating Fourier series we almost always get some expression that look like:
\begin{equation} ...\left[\cos(nx) \right]_0^\pi.
\end{equation}
Then we use $\cos(n\pi) = (-1)^n$.
However, lately I have come across expressions like this:
\begin{equation} ...\left[\sin(nx) \right]_0^{\pi/2}.
\end{equation}
Which is equal to:
\begin{array}{|c|c|c|c|}
\hline
n& 1 & 2 & 3 & 4 \\ \hline
\sin(nx)&\sin(\frac{\pi}{2}) & \sin(\pi) & \sin(\frac{3\pi}{2})& \sin(2\pi)\\ \hline
 val &1 &0 &-1 &0\\ \hline
\end{array}
How do we simplify this so that it looks like the $\cos(n\pi) = (-1)^n$.
Answer: You have
$$\sin\frac{n\pi}{2} = \frac{1-(-1)^n}{2}(-1)^{\lfloor n/2\rfloor}.$$
So that's one way.  But often, if there are no $\cos$'s messing things up, you can re-index your sum.  All the terms for even $n$ are zero, you can rewrite
$$\sum_{n=1}^{\infty}  \sin\frac{n\pi}{2}\mbox{crud} = \sum_{k=1}^{\infty} \sin\frac{(2k-1)\pi}{2}\mbox{crud}= \sum_{k=1}^{\infty}(-1)^k \mbox{crud}.$$
Whatever the crud is, replace all occurrences of $n$ with $2k-1.$
Comment: First formula is never $-1$
Comment: Your formula produces 0,1,0,1,0,1,...
Comment: @gist076923  I think I fixed it.
Answer: Note that $e^{\pm in\pi / 2} = \cos n\pi/2 \pm i\sin n\pi/2$, so
$$\sin n\pi/2 = \tfrac{1}{2i}(e^{in\pi / 2} - e^{-in\pi / 2})$$
$$= \tfrac{1}{2i}(i^n - i^{-n})$$
$$=\frac{i^{2n}-1}{2i^{n+1}}$$
$$= \frac{(-1)^n - 1}{2i^{n+1}}$$
$$= \boxed{\frac{1 - (-1)^n}{2i^{n-1}}}\tag{mult top/bottom by $i^{-2} = -1$}$$
This expression vanishes for even $n$, and for odd $n = 2k+1$ it becomes
$$\frac{1 - (-1)^{2k+1}}{2i^{2k+1-1}} = \frac{2}{2(-1)^k} = (-1)^k$$
as desired.
Answer: You have a sequence with period $4$ (specifically $0,1,0,-1,0,1,\cdots$), but $(-1)^n$ has period $2$, so it can't be used in this form.
However, $(-1)^{\binom n2}=(-1)^{n(n-1)/2}$ does have period $4$:
$$(-1)^0=1,\quad(-1)^1=-1,\quad(-1)^3=-1,\quad(-1)^6=1,$$
$$(-1)^{10}=1,\quad(-1)^{15}=-1,\quad(-1)^{21}=-1,\quad(-1)^{28}=1,$$
$$\cdots$$
To prove periodicity:
$$(-1)^{(n+4)(n+3)/2}=(-1)^{(n^2+7n+12)/2}=(-1)^{4n+6+(n^2-n)/2}\\=((-1)^2)^{2n+3}(-1)^{n(n-1)/2}=(-1)^{n(n-1)/2}$$
Now let's try shifting and combining these:
$$\begin{matrix}n&=&(0,&1,&2,&3,&\cdots) \\ (-1)^n&=&(1,&-1,&1,&-1,&\cdots) \\ (-1)^{n(n-1)/2}&=&(1,&1,&-1,&-1,&\cdots) \\ (-1)^{n(n+1)/2}&=&(1,&-1,&-1,&1,&\cdots) \\ (-1)^{n(n-1)/2}-(-1)^{n(n+1)/2}&=&(0,&2,&0,&-2,&\cdots)\end{matrix}$$
And there's your answer:
$$\sin(n\pi/2)=\frac{(-1)^{n(n-1)/2}-(-1)^{n(n+1)/2}}{2}$$
In fact any $4$-periodic sequence can be expressed in this way:
$$f_n=\frac{1+(-1)^n+(-1)^{n(n-1)/2}+(-1)^{n(n+1)/2}}{4}=(1,0,0,0,1,0,0,0,1,\cdots)$$
$$(a_0,a_1,a_2,a_3,a_0,a_1,a_2,a_3,a_0,\cdots)=a_0f_n+a_1f_{n-1}+a_2f_{n-2}+a_3f_{n-3}$$
$$=a_0\frac{1+(-1)^n+(-1)^{n(n-1)/2}+(-1)^{n(n+1)/2}}{4} \\ +a_1\frac{1-(-1)^n+(-1)^{n(n-1)/2}-(-1)^{n(n+1)/2}}{4} \\ +a_2\frac{1+(-1)^n-(-1)^{n(n-1)/2}-(-1)^{n(n+1)/2}}{4} \\ +a_3\frac{1-(-1)^n-(-1)^{n(n-1)/2}+(-1)^{n(n+1)/2}}{4}$$
See also What is a mathematical expression for the sequence $\{1,1,-1,-1,1,1,-1,-1,\dots\}$? and the linked posts.
Answer: If you are multiplying by that sin term, even terms fall out
$$
\sum_{n=1}^{2N} f(n)\sin \left(\frac{n\pi}{2}\right) = \sum_{k=1}^N (-1)^{k-1} f(2k-1)
$$


Correlation between musical knowledge and some measured variables

Question: I have this table:

The table shows the occurrences for each feature and separates whether one has or not musical knowledge.
I'd like to show in the test column a 'number' that could tell how strong a feature is correlated to the fact that one has musical knowledge. Which statistical test would you suggest?
I'm probably complicating things too much, but anyways.
Answer: It seems like, for each feature, you really have a contingency table ($2\times 2$ table.) For instance, for the first row, the table is
<code>          know genre total
W know            27    38
Wout know         24    31
</code>
(please comment if my interpretation is wrong). Usually (for chisquare test and other calculation ) we want a table with rows $(x, n-x)$ not as above $(x,n)$, that is:
<code>          genre don't
W know       27    11
Wout know    24     7
</code>
If this feature is meaningful, at least we should be able to reject the null of homogeneity. Using the chi-square test gives:
<code>    Pearson's Chi-squared test with Yates' continuity correction

data:  tab
X-squared = 0.10466, df = 1, p-value = 0.7463
</code>
In this case, we could not reject, so this feature is not helpful. Now you can repeat this for all features. In the reject cases, some measure of effect size, like the (log) odds ratio, can be helpful. Or you could bypass the chisquare test and calculate, say, odds ratios with confidence intervals at the outset. Odds ratios could be calculated either directly or via logistic regression, this is discussed widely, see for instance this blog or Computing Confidence Intervals for Odds Ratio Based on Fitted Values. There is even a dedicated package on CRAN.  See also Different ways to produce a confidence interval for odds ratio from logistic regression.
If you also have the original data your tables were calculated from, you could try to use logistic regression directly.
Comment: This really served me well. Thank you very much. :)


Custom field type - cardinality unlimited - multi column - radios to select default/primary

Question: I created a custom field for the CRM project to handle telephone numbers. It has multiple properties. I am having trouble getting primary to work; I want to be able to mark one of the telephone numbers as primary.
The CRMTelephoneWidget displays a radio as the primary property, and the value is saved. Still, more than one item can be primary because each has a different form name.
$element['primary'] = [
  '#type' => 'radios',
  '#options' => [$delta => $this->t('Primary')],
  '#title' => $this->t('Primary'),
  '#default_value' => $items[$delta]->primary ?? NULL,
];

I manually set the form name, as follows. Only one radio can be selected, but the value is not saved.
$element['primary'] = [
  '#type' => 'radios',
  '#options' => [$delta => $this->t('Primary')],
  '#title' => $this->t('Primary'),
  '#default_value' => $items[$delta]->primary ?? NULL,
  '#attributes' => ['name' => 'telephones[primary]'],
];

Any help or advice will be greatly appreciated!

Name
Type
Example

Phone
string
555-555-5555

Extension
string
123

Type
string
phone, fax, mobile (entity reference to config)

Location
string
home, work, billing (entity reference to config)

Primary
boolean

Mobile Provider
string
t_mobile
Comment: By grouping the radios the submitted data is no longer in the structure of the field deltas. Put the method `public function massageFormValues(array $values, array $form, FormStateInterface $form_state)` in the widget class and check $values for both cases. Then you know what to do. Please post the answer.
Answer: This is the interesting part of massageFormValues. I can pull the primary value from the user input.
/**
 * {@inheritdoc}
 */
public function massageFormValues(array $values, array $form, FormStateInterface $form_state) {
  $primary = 0;
  foreach($values as $delta => $value) {
    if (isset($value['primary'])) {
      $primary = $value['primary'];
    }
  }
  foreach ($values as $delta => $value) {
    $values[$delta]['primary'] = FALSE;
    if ($values[$delta]['_original_delta'] == $primary) {
      $values[$delta]['primary'] = TRUE;
    }
  }
  return $values;
}

    $field_name = $this->fieldDefinition->getName();
    $element['primary'] = [
      '#type' => 'radio',
      '#return_value' => $delta,
      '#title' => $this->t('Primary'),
      '#default_value' => $items[$delta]->primary ? $delta : NULL,
      '#attributes' => [
        'id' => $field_name . '-primary-' . $delta,
      ],
      '#parents' => [$field_name, 0, 'primary'],
    ];

Comment: Add something like `'#parents' => ['radios', $this->fieldDefinition->getName()],` to the radios so that the submitted data depends on the field name, if someone wants to add the field type multiple times to a content type. BTW you can get the submitted value of the radios element with getValue():  `$form_state->getValue(['radios', $this->fieldDefinition->getName()]);`
Comment: I don't think this works, the field doesn't accept `primary` submitted as field delta. The validation error is probably low-level Form API validation, the `radios` don't know about the other options. Try to use single `radio` elements which have as #return_value the field delta.
Comment: But you can submit it in the first field delta `0`. I've posted an answer with single radio elements
Comment: From @BinaryAlchemist: *There were problems when re-ordering the elements. I added a hidden element to track the original delta.* - Great, I think the version in your answer is the best solution. I can now delete my answer. BTW there is already an `_original_delta` in $values, you could try this instead of the hidden element.
Comment: "The submitted value 1 in the Primary element is not allowed." The does not work. Shouldn't it be [$this->fieldDefinition->getName(), 'primary'] ?
Comment: I was able to use `_original_delta`. I have also replicated this pattern in the CRMEmailWidget.


Finding the inverse of the arc length function

Question: I'm just a simple high school math student, so please don't eat me =)
In my calculus text, I have the formula:
$$L(x) = \int_{c}^{x} \sqrt{[f'(t)]^2 + 1}\,dt$$
Where $L(x)$ is the arc length of a curve $f(x)$ from $c$ to $x$.
How can I invert this function so that I can find valid values of $x$ to satisfy a given arc length? Something like $L^{-1}(x)$.
Answer: Nice idea!
As long as the function $g(x)$ is well-behaved, we have the following very important result. Let
$$G(x)=\int_c^x g(t)dt$$.
Then $G'(x)=g(x)$.
This result (and some related ones) is called the Fundamental Theorem of (Integral) Calculus.
Now let us apply that to your problem.  We obtain
$$L'(x)=\sqrt{1+(f'(x))^2}$$
Use the above equation to solve for $f'(x)$ in terms of $L'(x)$.  If you take $L(x)$ as known, you have found an explicit formula for $f'(x)$, and all you need to do is to integrate.
Now comes the unfortunate part.  For most pleasant functions $L(x)$, the resulting integration problem will be either difficult or more often impossible (in terms of standard functions).
I hope that this gives you something to play with.  You will find out why there is such a limited number of different arclength problems in calculus books!
Comment: @Gaebel: Indeed that is a different question! You can find an explicit formula for $L(x)$, and solve $L(x)=10$. Typically there should be two answers. And usually there will not be a pleasant formula for the inverse function, or indeed for $L(x)$, so you will need to use a numerical procedure.
Comment: I'm afraid I still don't understand. Now I have a function of $L'$, when what I need is a function of $L$. Can you show me an example with $f(x) = x^2$?
Comment: @Clark: $L'$ is a function of $L$. If you know $L(x)$, then you can compute $L'(x)$ from it.
Comment: In your post, you wrote "given arc length".  So I will take $L(x)=x^2$ as an example. Then, using the Fundamental Theorem of Calculus, we get $2x=\sqrt{1+(f'(x))^2}$. Solve for $f'(x)$. We get $f'(x)=\sqrt{4x^2-1}$ (I took the positive square root). To find $f(x)$, integrate.  The constant of integration can be found by using the fact that the arc length from $c$ to $c$ is $0$.  The integration in this case is slightly messy but doable.  If you have trouble with it, ask Wolfram Alpha.
Comment: Nono, what I meant was given a value for the arclength (let's say 10), a starting point (let's say 1), and a function $f(x) = x^2$, how do I find a value of $x$ such that $L(x) = 10$? Phrasing is difficult.
Comment: Then a numerical method it shall be! I already wrote it while waiting on an answer: http://goo.gl/uu7Z6 You can take a look if you fancy, but haskell might not be your cup of tea. If it is though, suggestions on speeding it up would be much appreciated!
Answer: You can do it by a differential equation without getting $L(x)$ explicitly.  If $\frac{dL}{dx} = \sqrt{1 + f'(x)^2}$, then
 $\frac{dx}{dL} = \frac{1}{\sqrt{1 + f'(x)^2}}$.  Numerical methods can be used to solve this differential equation.
Answer: You are basically asking how can one find the "arclenght parametrisation" for the graph of  a function (arclenght parametrisation is usually studied for parametric curves).
I might be wrong but from what I remember this Question is usually hard, the only way I know to solve it is by simply computing $L(x)$ and try to find its inverse function.


SharePoint 2013 KnockoutJS Lookup columns

Question: I have a basic knockoutjs project loading data from a SharePoint 2013 list scenario. Getting data and displaying data is easy, the problem that I'm running into is on the edit mode displaying the proper control. Everything should not be a textbox. This means the people picker control to dropdownmenus to calendar controls.
MSFT has some pretty good documentation on using the client side people picker control here"http://msdn.microsoft.com/en-us/library/office/jj713593.aspx
The problem that I have is calling this control inside my viewmodel.
Setting the value of the control doesn't look difficult courtesy of this blog post: http://www.sharepointcolumn.com/sp2013-setting-people-picker-value-in-newform-aspx/
I attempted to looking into computed values, but that doesn't seem to work. Does anyone have a blog post that I skipped over? The closest related post that I can find: http://yetanothersharepointblog.wordpress.com/2012/12/11/working-with-sharepoint-lookup-columns-in-knockout-js/
Lastly since it seems that I'm the only one doing this, does anyone think that I should not be reinventing the wheel with my forms and should just link each item to the appropriate SharePoint list item in edit or display view? I suppose that would be easier.
Answer: From a SharePoint Professional to another, I would highly recommend you to do that.
Just redirect the user to the item edit/display item page an let SharePoint take the leash of how to handle UI form elements.
Because, assume that you implement your custom form, what if the user decides to add one more site column to the list? Will you update your code to support another field?
From my personal experience with the beast I've come to the conclusion that structural implementation over already existent functionality tends to go wrong.
Also, if you have some kind of listing of items custom made and you want to provide editing, try to do something opening a pretty SP.UI.ModalDialog, its elegant and you use the sharepoint to do the work for you.
But it's just an advise.
Comment: I agree with your comments. I've come to the conclusion that in this use case, it doesn't make much sense to use angular or KO with SharePoint. The hassle of creating controls is just not worth it.


Valid VISA: 4222222222222 outputted as invalid

Question: When running my program through cs50's submit50 check, everything works besides validating 4222222222222 as VISA (instead of INVALID) is output. When I print out the count variable before, then sometimes VISA is output. Any solutions would be much appreciated as I cannot seem to properly fix this.

INSTRUCTIONS: Write a program that prompts the user for a credit card number and then reports (via printf) whether it is a valid American Express, MasterCard, or Visa card number, per the definitions of each's format herein. So that we can automate some tests of your code, we ask that your program's last line of output be AMEX\n or MASTERCARD\n or VISA\n or INVALID\n, nothing more, nothing less

#include <stdio.h>
#include <cs50.h>

int main(void)
{
    //get input from user
    long CardNum = get_long("Input credit card number:");

    bool nvalid = true;
    //count number of digits
    int count = 0;
    long temp1num = CardNum;
    while (temp1num > 0)
    {
        temp1num = temp1num / 10;
        count++;
    }

    //printf("%i\n", count);

    if (!(count == 13 || count == 15 || count == 16))
    {
        printf("INVALID\n");
    }

    else
    {
       .....

The problem arises in the beginning of the code so I only copied that part.
Answer: Mastercards always starts with either 5 or 2 and has a length of 16.
Visa cards always start with a 4 and can have a length of 13-16-19.
You are close. Try adding an additional condition for the supported lengths for VISA in your if statement it should solve your problem. Or, why not just check if the card length is either 13 - 19? It seems like it's failing because Visa supports different card lengths.
I have an awesome helper method that determines card types that's extremely handy but it's in C#.


Heteroskedastic time series outlier analysis using machine learning

Question: Is anyone aware of machine learning models that are able to deal with heteroskedasticity in time series, when trying to detect outliers? There are a lot of anomaly detection tools out there (like k-means, isolation forests, one-class SVMs,...) but they do not really have the ability to deal with changes in volatility. Ideally, I would like to have an algorithm that looks locally at the time series. Otherwise, if there are periods in the data where there is high volatility, all of these observations will be flagged as outliers. However, compared to their neighbours these high volatility point should not all count as outliers. This happens because the methods known to me look at the problem globally. Taking a local perspective, observations in high volatility should not necessarily count as outliers. Are there any neural network representations that are able to cope with that? I heard about convolutional approaches that have a sliding window that they use to take a local perspective.
I could also imagine having to transform the data so that some of the outliers appear much more strongly to the mentioned techniques. However, I'm also not aware of any such transformations.
Edit
Here is what I have been describing. The red ones should be outliers, while the green ones should not be. What I'm looking for is an ML approach that allows for volatility clustering and local outlier detection. Because of the multiplicative nature of the underlying process, large jumps are likely clustered.
Comment: That looks much better. What is the time resolution? Monthly/weekly/daily?
Comment: You are looking at daily data. Returns are calculated using the daily closing price of the asset.
Comment: are your time series multivariate?
Comment: Not necessarily. I would be glad to solve the univariate case first. So right now I'm only looking at a single time series.
Comment: Can you show some examples of your data (or similar data), marked with what you consider to be outliers? That will help to understand the problem and to propose a suitable method
Comment: Sorry for that, I added a figure. Just for reference, it's about financial time series data.
Answer: You want to take into consideration some local patterns in time to define your anomalies. This can be done with a relatively simple feature engineering procedure, and then using the standard anomaly detection methods on top.

Divide the time-series into sliding time-windows of a suitable length for the "context" you wish to have. In your example, this could be some months.
For each time-window, compute your desired metric for volatility. Should preferably be robust to outliers. Median Absolute Deviation is a candidate.
Scale the original data points by the volatility metric to "normalize" / "correct for" volatility.
Do anomaly detection on the new time series. If the feature engineering is strong, this might be as simple as applying a threshold
Comment: Oh yeah. Sorry, totally forgot. Have a good one
Comment: Thank you for your valuable input. What I did following this is to apply local volatility estimates, just as you suggested, to scale the series. In particular, I used the ```stochvol```package in R which gave me daily volatility estimates. In the end both the isolation forests and one-class SVM did pretty well.
Comment: Nice! Maybe mark this answer as accepted? Or if you wish to provide some more details, make an answer of your own and mark that?
Comment: Thanks, have a good week :)


How can double-stroke rolls be faster than single-strokes?

Question: How can double-stroke (RRLLRRLL) rolls be faster than single-strokes (RLRLRLRL)? If someone can hit 2 notes with the same hand, surely they'll get faster if they intertwine this with the other hand after the first note is played..?
I'm a beginner drummer, and I've just measured that I can do 16th note doubles at around 100 bpm, starting to lose track at around 110; while if I do alternating strokes (what I understand by "single") I can easily get to 160 bpm and slightly beyond. Obviously I haven't practised doubles much, but I just don't seem to grasp how with this huge bpm gap can doubles ever exceed singles :-O
For reference, for instance this guide seems to claim that doubles are faster:

The double stroke has a couple practical uses.
Playing faster than you can with a single stroke roll. Using the efficiency of the push-pull, you can use doubles to outperform your singles when the going gets too fast.

I'm not 100% sure I'm doing all the push-pull correctly, but my wrists feel relaxed, I'm definitely using the bounce of the stick from the drum / pad and it just seems impossible to go much faster for me right now, especially not being able to alternate the hands while striking.
What speeds can you guys get to with single and double strokes?
Comment: The double-stroke allows the stick to rebound on its own, rather like the spiccato or sautille for bowed instruments.
Answer: The double stroke is a different stroke from the single stroke. It's not played the same way as playing two single strokes in succession. It uses techniques to redirect the bounce of the stick off the drum back down to the drum.
Imagine playing a drag but instead of letting the stick bounce until it runs out of energy, you "grab" it after the second bounce. That's a double stroke.
One thing that should be happening as you increase the tempo of your double stroke roll is that you should change your grip. At the slowest speeds, the energy for the strokes comes from your wrists and maybe lower arm, and your grip is more relaxed. At the slowest tempos the technique is like playing two single strokes in a row.
As you speed up, your fingers get more involved, first with your ring and pinkie fingers "catching the bounce" and sending the stick back to the drum for the second stroke. Then at the highest speeds it's your first two fingers and your thumb gripping the stick more firmly but loosely enough so the stick can bounce. From the elbow or wrist you drive the stick down and it almost "vibrates" between your thumb and fingers to hit the head twice very quickly before you lift it away again to prepare for the next double stroke.
I would look for some videos on two-stroke rolls on YouTube to get a better idea of the proper techniques. At the time of this writing, Drumeo is a great YouTube channel for techniques. Even better would be to hire a drum teacher.
In short, generally a drummer can play a two stroke roll almost twice as fast as single stroke, because the motion of each stroke is the same between them, it's just that with each two-stroke stroke, the drum is struck twice instead of once.

it just seems impossible to go much faster for me right now, especially not being able to alternate the hands while stroking.

It takes a lot of practice. Again I suggest a teacher or Drumeo on YouTube. You'll want to learn to do double-strokes with each hand isolated before combining hands into the roll.
All of that said, there are some drummers who can do single stroke rolls very fast and might disagree about some points here. I'm just trying to give a basic understanding of the difference and why double-stroke rolls can be faster than single strokes. The main thing to keep in mind is that the technique is different, and it should feel different and sound different when you're playing them.
Answer:
If someone can hit 2 notes with the same hand, surely they'll get faster if they intertwine this with the other hand after the first note is played..?

Yes, but that's the point: you can hardly play more than two notes as fast as you can play the first two. While you can use the double stroke technique to play 4 very fast single strokes, you probably cannot do that for more than 5-6 strokes.
Consider that a rebound stroke takes advantage from the previous one: it's easier to make a second stroke after the first (and make them sound similar), than a third after the second, and so on.
The movements of the first and second stroke are not the same: when talking about standard single strokes, most of the movement involves the wrists, while the second stroke of doubles requires using your fingers.
All that's because the amount of energy you can put on the first is given by the fact that you have more time (and space) to "recover", since the other hand is playing in the meantime. The second stroke uses both the energy of the rebound and that of the hand (mostly, your fingers), but that energy is limited and your hand gets easily fatigued - meaning that it gets harder and harder the more strokes you try to do from rebounds only.
Also, sticks are heavy, and while fingers are faster than wrists, they don't have enough power to move sticks that fast at certain dynamics for a long period without some amount of recover.
Just to clarify, you can get pretty fast with single strokes, using a proper finger technique, that's how Guinness holders do that (see this old video of Mike Mangini that achieved about 300bpm playing sixteens) - but that technique cannot be holded for a long time at louder dynamic for the reason given before.
So, practically speaking, if you can play single strokes at speed X (mostly using wrists), you can theoretically play doubles at a speed close to 2X with the proper technique. Obviously, as soon as your single stroke speed gets higher, the difference between those maximum speeds increases.
Comment: > as soon as your single stroke speed gets higher, the difference between those maximum speeds increases.

Did you mean "decreases"? As in, if Mike Mangini did single-strokes at 300bpm, I doubt he could do doubles at 600?
Comment: @uukgoblin The difference between 2X and the actual speed you can reach with double strokes increases: if you can play singles at 120 you can probably play doubles close to 240, but if you can play singles at 180 you will hardly be able to play doubles as close to 360.


Puzzled over basic exponentiation problem with complex argument

Question: I can't figure out where is my erroneous thinking in the following elementary use of exponents. I have used Mathematica to verify that I don't know what I'm doing.
$$ a^{bc}=\left(a^{b}\right)^{c} $$
Mathematica says "True".
$$ e^{bc}=\left(e^{b}\right)^{c} $$
Mathematica says "True".
$$ e^{ibc}=\left(e^{ib}\right)^{c} $$
Mathematica says "True" ($i=\sqrt{-1}$).
$$ e^{i2\pi c}=\left(e^{i2\pi}\right)^{c} $$
Mathematica says "False".
FWIW I used PowerExpand[] on each of these expressions in Mathematica and put them inside a TrueQ[] function. I know that $ e^{i2\pi} = 1 $, that $ 1^{c}=1 $, and that $ e^{i2\pi c} $ is generally some point on the unit circle depending on the value of $c$ and thus a complex number with unit magnitude.
Please show me what is wrong.
Comment: In equation 3, I'm pretty sure I is being interpreted as a real variable and not imaginary complex unit.
Comment: @fleablood No, Mathematica uses a special symbol for the imaginary unit and I have been careful to use it.
Comment: @heropup Thank you for the Mathematica lesson; however, my question is not how to use Mathematica but why $e^{i2\pi c}\neq\left(e^{i2\pi}\right)^{c}$. For example, if c = 1/2, LHS = -1 but RHS = 1.
Answer: The documentation for PowerExpand clearly states:

The transformations made by PowerExpand are correct in general only if c is an integer or a and b are positive real numbers.

This is why you are getting erroneous results.  In the last expression, if $c$ is not an integer, $e^{2\pi i c} \ne (e^{2\pi i})^c$; e.g., try $c = 1/2$.
Do not use Mathematica commands without first understanding the documentation.


Add link to topic list after new topic or comment submission

Question: I would like that, when users submit a new topic or posts a reply in a forum, they would be redirected to the topics list.
How can I do this?
Answer: There's count of ways to do it, one of these: Rules module. Just add condition on node or comment adding, and add action for redirecting. For taking correct forum page of node or comment, I assume you should enable "php filter" and add php code that got forum taxonomy term and redirect to certain page.
Comment: The php part is my problem... would you be able to elaborate?