How is static variable initialization implemented by the compiler?

Question: I'm curious about the underlying implementation of static variables within a function.
If I declare a static variable of a fundamental type (char, int, double, etc.), and give it an initial value, I imagine that the compiler simply sets the value of that variable at the very beginning of the program before main() is called:
void SomeFunction();

int main(int argCount, char ** argList)
{
    // at this point, the memory reserved for 'answer'
    // already contains the value of 42
    SomeFunction();
}

void SomeFunction()
{
    static int answer = 42;
}

However, if the static variable is an instance of a class:
class MyClass
{
    //...
};

void SomeFunction();

int main(int argCount, char ** argList)
{
    SomeFunction();
}

void SomeFunction()
{
    static MyClass myVar;
}

I know that it will not be initialized until the first time that the function is called. Since the compiler has no way of knowing when the function will be called for the first time, how does it produce this behavior? Does it essentially introduce an if-block into the function body?
static bool initialized = 0;
if (!initialized)
{
    // construct myVar
    initialized = 1;
}

Answer: This question covered similar ground, but thread safety wasn't mentioned. For what it's worth, C++0x will make function static initialisation thread safe.
(see the C++0x FCD, 6.7/4 on function statics: "If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for
completion of the initialization.")
One other thing that hasn't been mentioned is that function statics are destructed in reverse order of their construction, so the compiler maintains a list of destructors to call on shutdown (this may or may not be the same list that atexit uses).
Comment: Can you give a reference/citation to its being thread safe in C++0x? I haven't found one.
Answer: In the compiler output I have seen, function local static variables are initialized exactly as you imagine.
(Caveat: This paragraph applies to C++ versions older than C++11. See the comments for changes since C++11.) Note that in general this is not done in a thread-safe manner. So if you have functions with static locals like that that might be called from multiple threads, you should take this into account. Calling the function once in the main thread before any  others are called will usually do the trick.
I should add that if the initialization of the local static is by a simple constant like in your example, the compiler doesn't need to go through these gyrations - it can just initialize the variable in the image or before main() like a regular static initialization (because your program wouldn't be able to tell the difference). But if you initialize it with a function's return value, then the compiler pretty much has to test a flag indicating if the initialization has been done or something equivalent.
Comment: I suggest you to edit your answer since it is accepted as answer and has 10 votes. Also this question is most viewable with the topic of initialization of static variables.
Comment: Did something change? I've heard that after c++11 each initialization of static is thread-safe.
Comment: @VictorPolevoy: Yes - when this answer was written, C++11 didn't exist.  In C++11, the standard included thread support, and this was added to the description of initialization of block-scope static variables (6.7/4): "If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization".
Comment: Thanks for the part about initialization by a simple constant versus a function's return value!  Good point!
Comment: @VictorPolevoy: gcc/clang use an acquire load of a guard variable to check that static locals have been initialized, if they don't have compile-time-constant initializers.  e.g. https://godbolt.org/z/do89eqdMP  If the guard variable is false, then they pick one thread to do the initializing, and have other threads wait for it if they also see a false guard variable.  They've been doing this for a long time, since before C++11 required it.  (e.g. as old as GCC4.1 on Godbolt, from May 2006.)
Answer: You're right about everything, including the initialized flag as a common implementation. This is basically why initialization of static locals is not thread-safe, and why pthread_once exists.
One slight caveat: the compiler must emit code which "behaves as if" the static local variable is constructed the first time it is used. Since integer initialization has no side effects (and calls no user code), it's up to the compiler when it initializes the int. User code cannot "legitimately" find out what it does.
Obviously you can look at the assembly code, or provoke undefined behaviour and make deductions from what actually happens. But the C++ standard doesn't count that as valid grounds to claim that the behaviour is not "as if" it did what the spec says.
Answer:
I know that it will not be initialized until  the first time that the function is called. Since the compiler has no way of knowing when the function will be called for the first time, how does it produce this behavior? Does it essentially introduce an if-block into the function body?

Yes, that's right: and, FWIW, it's not necessarily thread-safe (if the function is called "for the first time" by two threads simultaneously).
For that reason you might prefer to define the variable at global scope (although maybe in a class or namespace, or static without external linkage) instead of inside a function, so that it's initialized before the program starts without any run-time "if".
Answer: Another twist is in embedded code, where the run-before-main() code (cinit/whatever) may copy pre-initialized data (both statics and non-statics) into ram from a const data segment, perhaps residing in ROM.  This is useful where the code may not be running from some sort of backing store (disk) where it can be re-loaded from.  Again, this doesn't violate the requirements of the language, since this is done before main().
Slight tangent: While I've not seen it done much (outside of Emacs), a program or compiler could basically run your code in a process and instantiate/initialize objects, then freeze and dump the process.  Emacs does something similar to this to load up large amounts of elisp (i.e. chew on it), then dump the running state as the working executable, to avoid the cost of parsing on each invocation.
Answer: The relevant thing isn't being a class type or not, it's compile-time evaluation of the initializer (at the current optimization level).  And of course the constructor not having any side-effects, if it's non-trivial.
If it's not possible to simply put a constant value in .data, gcc/clang use an acquire load of a guard variable to check that static locals have been initialized.  If the guard variable is false, then they pick one thread to do the initializing, and have other threads wait for it if they also see a false guard variable.  They've been doing this for a long time, since before C++11 required it.  (e.g. as old as GCC4.1 on Godbolt, from May 2006.)

Does a function local static variable automatically incur a branch? shows what GCC does.

Cost of thread-safe local static variable initialization in C++11? same

Why does initialization of local static objects use hidden guard flags? same

The most simple artificial example, snapshotting the arg from the first call and ignoring later args:
int foo(int a){
    static int x = a;
    return x;
}

Compiles for x86-64 with GCC11.3 -O3 (Godbolt), with the exact same asm generated for -std=gnu++03 mode.  GCC4.1 also makes about the same asm, but doesn't keep the push/pop off the fast path (i.e. missing shrink-wrap optimization).  GCC4.1 only supported AT&T syntax output, so it visually looks different unless you flip modern GCC to AT&T mode as well, but this is Intel syntax (destination on the left).
# demangled asm from g++ -O3
foo(int):
        movzx   eax, BYTE PTR guard variable for foo(int)::x[rip]  # guard.load(acquire)
        test    al, al
        je      .L13
        mov     eax, DWORD PTR foo(int)::x[rip]    # normal load of the static local
        ret              # fast path through the function is the already-initialized case

.L13:            # jumps here on guard == 0, on the first call (and any that race with it)
                 # It would be sensible for GCC to put this code in .text.cold
        push    rbx
        mov     ebx, edi             # save function arg in a call-preserved reg
        mov     edi, OFFSET FLAT:guard variable for foo(int)::x  # address
        call    __cxa_guard_acquire          # guard_acquire(&guard_x) presumably a normal mutex or spinlock
        test    eax, eax
        jne     .L14                         # if (we won the race to do the init work) goto .L14
        mov     eax, DWORD PTR foo(int)::x[rip]  # else it's done now by another thread
        pop     rbx
        ret
.L14:
        mov     edi, OFFSET FLAT:guard variable for foo(int)::x
        mov     DWORD PTR foo(int)::x[rip], ebx       # init static x (from a saved in RBX)
        call    __cxa_guard_release
        mov     eax, DWORD PTR foo(int)::x[rip]       # missed optimization:  mov eax, ebx
                # This thread is the one that just initialized it, our function arg is the value.
                # It's not atomic (or volatile), so another thread can't have set it, too.
        pop     rbx
        ret

If compiling for AArch64, the load of the guard variable is ldarb  w8, [x8], a load with acquire semantics.  Other ISAs might need a plain load and then a barrier to give at least LoadLoad ordering, to make sure they load the payload x no earlier than when they saw the guard variable being non-zero.

If the static variable has a constant initializer, no guard is needed
int bar(int a){
    static int x = 1;
    return ++x + a;
}

bar(int):
        mov     eax, DWORD PTR bar(int)::x[rip]
        add     eax, 1
        mov     DWORD PTR bar(int)::x[rip], eax   # store the updated value
        add     eax, edi                          # and add it to the function arg
        ret

.section .data

bar(int)::x:
        .long   1


A problem from Finite Dimensional vector spaces

Question: Problem : If $ M  $ and $N$ are two subspaces of the vector space $V$ such that $\forall v \in V  $ , $ v \in M $ or
$ v \in  $ (or both) . Prove that at least one of the is equal to $  V $
My Approach
Assume that $ M \neq V  $ , we are required to prove $ N = V    $  .
Assume contrary, let $\dim N < \dim V$.
We assume that $ M \cap N = \phi $ , in case the intersection is not null, we delete the elements from $ N  $ .
Now, $$\dim(M+N) + \dim (M\cap N) = \dim M + \dim N$$
Since $ \dim(M\cap N) = 0  $ and $M+N = V$.
Let $\dim M =m , \dim N = n . \dim V = v$.
Therefore  we get $n+m = v$
We know there is an isomorphism between $V$ and $\mathbb F^v$.
Consider the vectors in $\mathbb V$ corresponding to $(1,0,0,\dots) , (0,1,0,0,\dots), \dots$ in $\mathbb F^v$.
Exactly  $n$ of these belong to $N$ (which form a basis) and exactly m of these belong to $M$ (which again form a basis).WLOG we can assume that
$(1,0,0,\dots) , (0,1,0,\dots) , \dots , (0,0,\dots,1, 0,\dots) $ are the vectors present in $N $ ...$(*)$
Now consider the vector corresponding to $(1,1,1,\dots)$. It must belong to either $ N $ or $ M$ . WLOG assume it belongs to $N$ . Then we can get a set of $n+1$ linearly independent vectors in $N$.
$n$ vectors as described at $(*)$ and one of the form $(0,0,0,\dots , 1,1,1,\dots)$ But since we know that number of elements in basis is greater or equal to the number of elements in an independent set, we arrive at a contradiction since $n+1 > n$
My proof inherently assumes that the vector space given is a finite dimensional vector space. And also I feel that my proof is really clumsy. Is there a better way to prove it ?
Answer: How about the following? It does not require the vector spaces to be finite dimensional.
If $M, N \neq V$, then pick $v_1 \in V \setminus M$ and $v_2 \in V \setminus N$. Since $v_1 \notin M$, $v_1 \in N$ by assumption. Similarly $v_2 \in M$. Let $v = v_1 + v_2$. Then $v \notin M$ for otherwise $v_1 = v + (-v_2) \in M$. Similarly $v \notin N$. Contradiction to the assumption.
Added: I would like to emphasize $V \setminus M$ is NOT a subspace. It may be easier if you look at a picture: removing the $x$-axis from the $x-y$ plane does not give you a subspace. In fact, $V \setminus M$ could never be a subspace since it does not contain the zero vector of $V$. In the context of vector spaces, disjoint union $M$ and $V \setminus M$ is not the way we are interested in decomposing a vector space $V$. Instead we are more interested in (direct) sums of vector spaces.
Comment: That was really slick :D thanks!


Dropdown com JQuery/Ajax só envia dado no primeiro registro

Question: Estou aplicando um dropdown dinamicamente para cada item de uma lista retornada em PHP. Ao selecionar algum dos itens do dropdown, este valor é enviado a um arquivo Update.php, através de JQuery e Ajax.
O Dropdown:
//Aqui tenho um while em PHP para criar um Dropdown para cada registro no Banco de dados
<select id="tipoSel">
   <option value="">Selecione o tipo:</option>
   <option value="Cívil">Cívil</option>
   <option value="Criminal">Criminal</option>
   <option value="Trabalhista">Trabalhista</option>
   <option value="Família">Família</option>
   <option value="Comercial">Comercial</option>
   <option value="Administrativo">Administrativo</option>
 </select>
 <input type="hidden" name="id" value="<?php echo $p->current()->id;?>" />

O JQuery:
$(document).ready(function(){
        $(function() {
            $("#tipoSel").bind("change", function(event) {
                var $this = $( this );

                var tipo = $this.val();
                var id = $this.next('input').val();

                $.ajax({
                    type: "POST",
                    url: "Update.php",
                    data: 'tipo='+tipo+'&id='+id,
                    success: function(data) {
                        alert(tipo+' : '+id);
                    }
                });
            });

        });
    });

Porém, apesar de ter vários registros, e todos estarem exibindo seu respectivo Dropdown, a função do JQuery só funciona para o primeiro registro da página! Os demais nem exibem o alert...
O que deve estar errado? Como solucionar?
Answer: São todos os Dropdowns criados com o id de tipoSel? O id de um elemento deve ser único no DOM enteiro.
usaria uma classe, criando um Dropdown assim:
<select class="tipoSel">
   <option value="">Selecione o tipo:</option>
   <option value="Cívil">Cívil</option>
   <option value="Criminal">Criminal</option>
   <option value="Trabalhista">Trabalhista</option>
   <option value="Família">Família</option>
   <option value="Comercial">Comercial</option>
   <option value="Administrativo">Administrativo</option>
 </select>
 <input type="hidden" name="id" value="<?php echo $p->current()->id;?>" />

E depois no seu jQuery, selecione-as assim:
$('.tipoSel').on( ... );

Comment: É exatamente isso! Nem havia prestado atenção... Valeu!
Comment: Que bom que deu certo :D


22 fields limit in Scala 2.11 + Play Framework 2.3 Case classes and functions

Question: Scala 2.11 is out and the 22 fields limit for case classes seems to be fixed (Scala Issue, Release Notes).
This has been an issue for me for a while because I use case classes to model database entities that have more than 22 fields in Play + Postgres Async. My solution in Scala 2.10 was to break the models into multiple case classes, but I find this solution hard to maintain and extend, and I was hoping I could implement something as described below after switching to Play 2.3.0-RC1 + Scala 2.11.0:
package entities

case class MyDbEntity(
  id: String,
  field1: String,
  field2: Boolean,
  field3: String,
  field4: String,
  field5: String,
  field6: String,
  field7: String,
  field8: String,
  field9: String,
  field10: String,
  field11: String,
  field12: String,
  field13: String,
  field14: String,
  field15: String,
  field16: String,
  field17: String,
  field18: String,
  field19: String,
  field20: String,
  field21: String,
  field22: String,
  field23: String,
)

object MyDbEntity {
  import play.api.libs.json.Json
  import play.api.data._
  import play.api.data.Forms._

  implicit val entityReads = Json.reads[MyDbEntity]
  implicit val entityWrites = Json.writes[MyDbEntity]
}

The code above fails to compile with the following message for both the "Reads" and the "Writes":
No unapply function found
Updating the "Reads" and "Writes" to:
  implicit val entityReads: Reads[MyDbEntity] = (
    (__ \ "id").read[Long] and
    (__ \ "field_1").read[String]
    ........
  )(MyDbEntity.apply _)

  implicit val postWrites: Writes[MyDbEntity] = (
    (__ \ "id").write[Long] and
    (__ \ "user").write[String]
    ........
  )(unlift(MyDbEntity.unapply))

Also doesn't work:
  implementation restricts functions to 22 parameters

  value unapply is not a member of object models.MyDbEntity

My understanding is that Scala 2.11 still has some limitations on functions and that something like what I described above is not possible yet. This seems weird to me as I don't see the benefit of lifting the restrictions on case classes if one it's major users cases is still not supported, so I'm wondering if I'm missing something.
Pointers to issues or implementation details are more than welcome! Thanks!
Comment: A case class with >22 params cannot have `unapply`, since it would have to convert to a `TupleX` with X>22, and tuples are still limited to 22. The sad part is that `Json.format[MyCaseClass]` (the macro-based solution) doesn't need to have this limitation (it could realize it is a case class and just extract the fields directly, without unapply, like pattern matching does), but it currently looks for `unapply` and fails...
Comment: Take a look at [relevant pull request description](https://github.com/scala/scala/pull/2305): the very first thing mentioned as limitation is lack of `unapply` for >22 classes and this was done for a reason (AFAIR, there would be an exponential blowup in classfiles size)
Comment: For those interested, here is a ticket tracking removing this limitation: https://github.com/playframework/playframework/issues/3174
Comment: The ticket is still open. Is there still a problem with >22 in 2.3 with Scala 2.11.1? Researching different stacks for a new project & wondering if this will be a problem. Thx
Answer: This is not possible, out of the box, for several reasons:

First, as gourlaysama pointed it out, play-json library used scala macro to avoid bolierplate code, and the current code relies of the unapply  and apply methods to retrieve fields. This explains the first error message in your question.
Secondly play-json library relies of a functional library which currently works only with a fixed number of parameters corresponding to previous case class fields arity limit. This explains the second error message in your question.

However it is possible to bypass the second point by either:

using shapeless Automatic Typeclass Derivation feature. Naveen Gattu has written an excellent gist doing exaclty so.
overridding default functiunal builder

First, creating the missing FunctionalBuilder:
class CustomFunctionalBuilder[M[_]](canBuild: FunctionalCanBuild[M]) extends FunctionalBuilder {

    class CustomCanBuild22[A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18, A19, A20, A21, A22](m1: M[A1 ~ A2 ~ A3 ~ A4 ~ A5 ~ A6 ~ A7 ~ A8 ~ A9 ~ A10 ~ A11 ~ A12 ~ A13 ~ A14 ~ A15 ~ A16 ~ A17 ~ A18 ~ A19 ~ A20 ~ A21], m2: M[A22]) {
def ~[A23](m3: M[A23]) = new CustomCanBuild23[A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18, A19, A20, A21, A22, A23](canBuild(m1, m2), m3)

  def and[A23](m3: M[A23]) = this.~(m3)

  def apply[B](f: (A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18, A19, A20, A21, A22) => B)(implicit fu: Functor[M]): M[B] =
  fu.fmap[A1 ~ A2 ~ A3 ~ A4 ~ A5 ~ A6 ~ A7 ~ A8 ~ A9 ~ A10 ~ A11 ~ A12 ~ A13 ~ A14 ~ A15 ~ A16 ~ A17 ~ A18 ~ A19 ~ A20 ~ A21 ~ A22, B](canBuild(m1, m2), { case a1 ~ a2 ~ a3 ~ a4 ~ a5 ~ a6 ~ a7 ~ a8 ~ a9 ~ a10 ~ a11 ~ a12 ~ a13 ~ a14 ~ a15 ~ a16 ~ a17 ~ a18 ~ a19 ~ a20 ~ a21 ~ a22 => f(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22) })

  def apply[B](f: B => (A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18, A19, A20, A21, A22))(implicit fu: ContravariantFunctor[M]): M[B] =
  fu.contramap(canBuild(m1, m2), (b: B) => { val (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22) = f(b); new ~(new ~(new ~(new ~(new ~(new ~(new ~(new ~(new ~(new ~(new ~(new ~(new ~(new ~(new ~(new ~(new ~(new ~(new ~(new ~(new ~(a1, a2), a3), a4), a5), a6), a7), a8), a9), a10), a11), a12), a13), a14), a15), a16), a17), a18), a19), a20), a21), a22) })

  def apply[B](f1: (A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18, A19, A20, A21, A22) => B, f2: B => (A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18, A19, A20, A21, A22))(implicit fu: InvariantFunctor[M]): M[B] =
  fu.inmap[A1 ~ A2 ~ A3 ~ A4 ~ A5 ~ A6 ~ A7 ~ A8 ~ A9 ~ A10 ~ A11 ~ A12 ~ A13 ~ A14 ~ A15 ~ A16 ~ A17 ~ A18 ~ A19 ~ A20 ~ A21 ~ A22, B](
    canBuild(m1, m2), { case a1 ~ a2 ~ a3 ~ a4 ~ a5 ~ a6 ~ a7 ~ a8 ~ a9 ~ a10 ~ a11 ~ a12 ~ a13 ~ a14 ~ a15 ~ a16 ~ a17 ~ a18 ~ a19 ~ a20 ~ a21 ~ a22 => f1(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22) },
    (b: B) => { val (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22) = f2(b); new ~(new ~(new ~(new ~(new ~(new ~(new ~(new ~(new ~(new ~(new ~(new ~(new ~(new ~(new ~(new ~(new ~(new ~(new ~(new ~(new ~(a1, a2), a3), a4), a5), a6), a7), a8), a9), a10), a11), a12), a13), a14), a15), a16), a17), a18), a19), a20), a21), a22) }
  )

  def join[A >: A1](implicit witness1: <:<[A, A1], witness2: <:<[A, A2], witness3: <:<[A, A3], witness4: <:<[A, A4], witness5: <:<[A, A5], witness6: <:<[A, A6], witness7: <:<[A, A7], witness8: <:<[A, A8], witness9: <:<[A, A9], witness10: <:<[A, A10], witness11: <:<[A, A11], witness12: <:<[A, A12], witness13: <:<[A, A13], witness14: <:<[A, A14], witness15: <:<[A, A15], witness16: <:<[A, A16], witness17: <:<[A, A17], witness18: <:<[A, A18], witness19: <:<[A, A19], witness20: <:<[A, A20], witness21: <:<[A, A21], witness22: <:<[A, A22], fu: ContravariantFunctor[M]): M[A] =
  apply[A]((a: A) => (a: A1, a: A2, a: A3, a: A4, a: A5, a: A6, a: A7, a: A8, a: A9, a: A10, a: A11, a: A12, a: A13, a: A14, a: A15, a: A16, a: A17, a: A18, a: A19, a: A20, a: A21, a: A22))(fu)

  def reduce[A >: A1, B](implicit witness1: <:<[A1, A], witness2: <:<[A2, A], witness3: <:<[A3, A], witness4: <:<[A4, A], witness5: <:<[A5, A], witness6: <:<[A6, A], witness7: <:<[A7, A], witness8: <:<[A8, A], witness9: <:<[A9, A], witness10: <:<[A10, A], witness11: <:<[A11, A], witness12: <:<[A12, A], witness13: <:<[A13, A], witness14: <:<[A14, A], witness15: <:<[A15, A], witness16: <:<[A16, A], witness17: <:<[A17, A], witness18: <:<[A18, A], witness19: <:<[A19, A], witness20: <:<[A20, A], witness21: <:<[A21, A], witness22: <:<[A22, A], fu: Functor[M], reducer: Reducer[A, B]): M[B] =
  apply[B]((a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7, a8: A8, a9: A9, a10: A10, a11: A11, a12: A12, a13: A13, a14: A14, a15: A15, a16: A16, a17: A17, a18: A18, a19: A19, a20: A20, a21: A21, a22: A22) =>  reducer.append(reducer.append(reducer.append(reducer.append(reducer.append(reducer.append(reducer.append(reducer.append(reducer.append(reducer.append(reducer.append(reducer.append(reducer.append(reducer.append(reducer.append(reducer.append(reducer.append(reducer.append(reducer.append(reducer.append(reducer.append(reducer.unit(a1: A), a2: A), a3: A), a4: A), a5: A), a6: A), a7: A), a8: A), a9: A), a10: A), a11: A), a12: A), a13: A), a14: A), a15: A), a16: A), a17: A), a18: A), a19: A), a20: A), a21: A), a22: A))(fu)

  def tupled(implicit v: VariantExtractor[M]): M[(A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18, A19, A20, A21, A22)] =
  v match {
    case FunctorExtractor(fu) => apply { (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7, a8: A8, a9: A9, a10: A10, a11: A11, a12: A12, a13: A13, a14: A14, a15: A15, a16: A16, a17: A17, a18: A18, a19: A19, a20: A20, a21: A21, a22: A22) => (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22) }(fu)
    case ContravariantFunctorExtractor(fu) => apply[(A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18, A19, A20, A21, A22)] { (a: (A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18, A19, A20, A21, A22)) => (a._1, a._2, a._3, a._4, a._5, a._6, a._7, a._8, a._9, a._10, a._11, a._12, a._13, a._14, a._15, a._16, a._17, a._18, a._19, a._20, a._21, a._22) }(fu)
    case InvariantFunctorExtractor(fu) => apply[(A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18, A19, A20, A21, A22)]({ (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7, a8: A8, a9: A9, a10: A10, a11: A11, a12: A12, a13: A13, a14: A14, a15: A15, a16: A16, a17: A17, a18: A18, a19: A19, a20: A20, a21: A21, a22: A22) => (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22) }, { (a: (A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18, A19, A20, A21, A22)) => (a._1, a._2, a._3, a._4, a._5, a._6, a._7, a._8, a._9, a._10, a._11, a._12, a._13, a._14, a._15, a._16, a._17, a._18, a._19, a._20, a._21, a._22) })(fu)
    }

  }

  class CustomCanBuild23[A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18, A19, A20, A21, A22, A23](m1: M[A1 ~ A2 ~ A3 ~ A4 ~ A5 ~ A6 ~ A7 ~ A8 ~ A9 ~ A10 ~ A11 ~ A12 ~ A13 ~ A14 ~ A15 ~ A16 ~ A17 ~ A18 ~ A19 ~ A20 ~ A21 ~ A22], m2: M[A23]) {
  }

}

and then by providing your own FunctionalBuilderOps instance:
implicit def customToFunctionalBuilderOps[M[_], A](a: M[A])(implicit fcb: FunctionalCanBuild[M]) = new CustomFunctionalBuilderOps[M, A](a)(fcb)

Finally, regarding the first point, I have sent a pull request to try to simplify the current implementation.
Comment: For Naveen's gist, I got come compile errors. For future reference, you can see the fix here. https://gist.github.com/angeloh/5fa10d8d5321bf650dd9
Comment: Getting stack overflow when using that Shapeless wrapper.
Comment: See my answer below, re https://github.com/xdotai/play-json-extensions, it seems there is a simple fix for play.  Will be testing next week.
Answer: We were also breaking our models into multiple case classes, but this was quickly becoming unmanageable.  We use Slick as our object relational mapper, and Slick 2.0 comes with a code generator that we use to generate classes (which come with apply methods and copy constructors to mimic case classes) along with methods to instantiate models from Json (we do not automatically generate methods to convert models into Json because we have too many special cases to deal with).  Using the Slick code generator does not require you to use Slick as your object relational mapper.
This is part of the input to the code generator - this method takes a JsObject and uses it to either instantiate a new model or update an existing model.
private def getItem(original: Option[${name}], json: JsObject, trackingData: TrackingData)(implicit session: scala.slick.session.Session): Try[${name}] = {
  preProcess("$name", columnSet, json, trackingData).flatMap(updatedJson => {
    ${indent(indent(indent(entityColumnsSansId.map(c => s"""val ${c.name}_Parsed = parseJsonField[${c.exposedType}](original.map(_.${c.name}), "${c.name}", updatedJson, "${c.exposedType}")""").mkString("\n"))))}
    val errs = Seq(${indent(indent(indent(indent(entityColumnsSansId.map(c => s"${c.name}_Parsed.map(_ => ())").mkString(", ")))))}).condenseUnit
    for {
      _ <- errs
      ${indent(indent(indent(indent(entityColumnsSansId.map(c => s"${c.name}_Val <- ${c.name}_Parsed").mkString("\n")))))}
    } yield {
      original.map(_.copy(${entityColumnsSansId.map(c => s"${c.name} = ${c.name}_Val").mkString(", ")}))
        .getOrElse(${name}.apply(id = None, ${entityColumnsSansId.map(c => s"${c.name} = ${c.name}_Val").mkString(", ")}))
    }
  })
}

For example, with our ActivityLog model this produces the following code.  If "original" is None then this is being called from a "createFromJson" method and we instantiate a new model; if "original" is Some(activityLog) then this is being called from an "updateFromJson" method and we update the existing model.  The "condenseUnit" method being called on the "val errs = ..." line takes a Seq[Try[Unit]] and produces a Try[Unit]; if the Seq has any errors then the Try[Unit] concatenates the exception messages.  The parseJsonField and parseField methods are not generated - they're just referenced from the generated code.
private def parseField[T](name: String, json: JsObject, tpe: String)(implicit r: Reads[T]): Try[T] = {
  Try((json \ name).as[T]).recoverWith {
    case e: Exception => Failure(new IllegalArgumentException("Failed to parse " + Json.stringify(json \ name) + " as " + name + " : " + tpe))
  }
}

def parseJsonField[T](default: Option[T], name: String, json: JsObject, tpe: String)(implicit r: Reads[T]): Try[T] = {
  default match {
    case Some(t) => if(json.keys.contains(name)) parseField(name, json, tpe)(r) else Try(t)
    case _ => parseField(name, json, tpe)(r)
  }
}

private def getItem(original: Option[ActivityLog], json: JsObject, trackingData: TrackingData)(implicit session: scala.slick.session.Session): Try[ActivityLog] = {
  preProcess("ActivityLog", columnSet, json, trackingData).flatMap(updatedJson => {
    val user_id_Parsed = parseJsonField[Option[Int]](original.map(_.user_id), "user_id", updatedJson, "Option[Int]")
    val user_name_Parsed = parseJsonField[Option[String]](original.map(_.user_name), "user_name", updatedJson, "Option[String]")
    val item_id_Parsed = parseJsonField[Option[String]](original.map(_.item_id), "item_id", updatedJson, "Option[String]")
    val item_item_type_Parsed = parseJsonField[Option[String]](original.map(_.item_item_type), "item_item_type", updatedJson, "Option[String]")
    val item_name_Parsed = parseJsonField[Option[String]](original.map(_.item_name), "item_name", updatedJson, "Option[String]")
    val modified_Parsed = parseJsonField[Option[String]](original.map(_.modified), "modified", updatedJson, "Option[String]")
    val action_name_Parsed = parseJsonField[Option[String]](original.map(_.action_name), "action_name", updatedJson, "Option[String]")
    val remote_ip_Parsed = parseJsonField[Option[String]](original.map(_.remote_ip), "remote_ip", updatedJson, "Option[String]")
    val item_key_Parsed = parseJsonField[Option[String]](original.map(_.item_key), "item_key", updatedJson, "Option[String]")
    val created_at_Parsed = parseJsonField[Option[java.sql.Timestamp]](original.map(_.created_at), "created_at", updatedJson, "Option[java.sql.Timestamp]")
    val as_of_date_Parsed = parseJsonField[Option[java.sql.Timestamp]](original.map(_.as_of_date), "as_of_date", updatedJson, "Option[java.sql.Timestamp]")
    val errs = Seq(user_id_Parsed.map(_ => ()), user_name_Parsed.map(_ => ()), item_id_Parsed.map(_ => ()), item_item_type_Parsed.map(_ => ()), item_name_Parsed.map(_ => ()), modified_Parsed.map(_ => ()), action_name_Parsed.map(_ => ()), remote_ip_Parsed.map(_ => ()), item_key_Parsed.map(_ => ()), created_at_Parsed.map(_ => ()), as_of_date_Parsed.map(_ => ())).condenseUnit
    for {
      _ <- errs
      user_id_Val <- user_id_Parsed
      user_name_Val <- user_name_Parsed
      item_id_Val <- item_id_Parsed
      item_item_type_Val <- item_item_type_Parsed
      item_name_Val <- item_name_Parsed
      modified_Val <- modified_Parsed
      action_name_Val <- action_name_Parsed
      remote_ip_Val <- remote_ip_Parsed
      item_key_Val <- item_key_Parsed
      created_at_Val <- created_at_Parsed
      as_of_date_Val <- as_of_date_Parsed
    } yield {
      original.map(_.copy(user_id = user_id_Val, user_name = user_name_Val, item_id = item_id_Val, item_item_type = item_item_type_Val, item_name = item_name_Val, modified = modified_Val, action_name = action_name_Val, remote_ip = remote_ip_Val, item_key = item_key_Val, created_at = created_at_Val, as_of_date = as_of_date_Val))
        .getOrElse(ActivityLog.apply(id = None, user_id = user_id_Val, user_name = user_name_Val, item_id = item_id_Val, item_item_type = item_item_type_Val, item_name = item_name_Val, modified = modified_Val, action_name = action_name_Val, remote_ip = remote_ip_Val, item_key = item_key_Val, created_at = created_at_Val, as_of_date = as_of_date_Val))
    }
  })
}

Answer: You can use Jackson's Scala module. Play's json feature is built upon Jackson scala . I don't know why they put a 22 field limit here while jackson supports more than 22 fields. It may make sense that a function call can never use more than 22 parameters, but we can have hundreds of columns inside a DB entity, so this restriction here is ridiculous and makes Play a less productive toy.
check this out:
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.scala.experimental.ScalaObjectMapper
import com.fasterxml.jackson.module.scala.DefaultScalaModule

object JacksonUtil extends App {
  val mapper = new ObjectMapper with ScalaObjectMapper
  mapper.registerModule(DefaultScalaModule)

  val t23 = T23("a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w")

  println(mapper.writeValueAsString(t23))
 }
case class T23(f1:String,f2:String,f3:String,f4:String,f5:String,f6:String,f7:String,
    f8:String,f9:String,f10:String,f11:String,f12:String,f13:String,f14:String,f15:String,
    f16:String,f17:String,f18:String,f19:String,f20:String,f21:String,f22:String,f23:String)

Answer: It seems this handles it all nicely.
+22 field case class formatter and more for play-json
https://github.com/xdotai/play-json-extensions
Supports Scala 2.11.x, 2.12.x, and 2.13.x and play 2.3, 2.4, 2.5 and 2.7
And is referenced in the play-json issue as the preferred solution (but not yet merged)
Answer: I'm making a library. please try this https://github.com/xuwei-k/play-twenty-three
Comment: "640K should be enough for everyone"
Comment: Didn't read all the code, but I've seen at least a reference to 252 fields!!! LOL :)
Answer: cases where case classes might not work; one of these cases is that the case classes cannot take more than 22 fields. Another case can be that you do not know about schema beforehand. In this approach, the data is loaded as an RDD of the row  objects. Schema is created separately using the StructType and StructField  objects, which represent a table and a field respectively. Schema is applied to the row RDD to create DataFrame in Spark.
Answer: I tried Shapeless "Automatic Typeclass Derivation" based solution proposed in another answer, and it didn't work for our models - was throwing StackOverflow exceptions (case class with ~30 fields and 4 nested collections of case classes with 4-10 fields).
So, we've adopted this solution and it worked flawlessly. Confirmed that by writing ScalaCheck test. Notice, that it requires Play Json 2.4.
Answer: In dotty (Scala 3) now you can use more than 22 fields in Case class.


Cyclotomic Polynomial $\Phi_p(x)$ Expansion

Question: On page 310 of Dummit & Foote, the following expansion is given for prime $p$.
$$\Phi_p(x)=\frac{x^p-1}{x-1}=x^{p-1}+x^{p-2}+\cdots+x+1.$$
This is a very basic question, but how does the expansion come about?
Comment: "cyclomatic". : ⟩ It's [cyclotomic](https://en.wiktionary.org/wiki/cyclotomic), meaning "circle cutting". (Compare "tomography" meaning "cut drawing".)
Comment: Haha, thank you, fixed it.
Comment: we have the inductive relationship $$\frac{x^p-1}{x-1} = \frac{x^p-x^{p-1}+x^{p-1}-1}{x-1} = x^{p-1} +\frac{x_{p-1}-1}{x-1}$$
Answer: It actually has nothing to do with p being a prime number. If you multiply by $(x-1)$ the right hand side you get :
$$ (x-1)\sum_{k=0}^{p-1} x^k = \sum_{k=0}^{p-1} x^{k+1} - x^k = x^p -1$$
Notice that 1 is a root of the polynomial $x^p-1$ so it is natural to try and find a polynomial P such that $P = \dfrac{x^p-1}{x-1}$. One can also notice that it is simply a geometric sum (the proof of the geometric sum is actually the same as the one I provided!)


How to approximate the xth percentile for a large unknown quantity of number

Question: Recently came across this question on how to find the xth percentile for a given stream of numbers. I have a basic understanding of how this could be achieved if the stream was relatively small (can be stored into memory, sorted and the xth value can be found) but I was wondering how the percentile could be approximated if the stream of numbers is fairly large and the number of numbers is unknown.
Comment: I don't think you can do this without storing the numbers (not necessarily in memory though).
Comment: Do you know the rough distribution of the values? Or hard limits?
Comment: No, there is no clear indication of the distribution of the values apart from from the range in which the numbers will appear from. These values are essentially server response times and hence have been stated that some of the response times may appear slightly out of order (but responses that are too out of order can be discarded).
Answer: I think you could use Reservoir sampling to select uniformly k elements from the stream S and then approximate xth percentile of S with the xth percentile of these k numbers. k depends on how much memory do you have and how precise the approximation should be.

EDIT
Here is a code example to test the solution:
// create random stream of numbers
Random random = new Random(0);
List<Integer> stream = new ArrayList<Integer>();
for (int i = 0; i < 100000; ++i) {
    stream.add((int) (random.nextGaussian() * 100 + 30));
}
// get approximate percentile
int k = 1000; // sample size
int x = 50; // percentile
// init priority queue for sampling
TreeMap<Double, Integer> queue = new TreeMap<Double, Integer>();
// sample k elements from stream
for (int val : stream) {
    queue.put(random.nextDouble(), val);
    if (queue.size() > k) {
        queue.pollFirstEntry();
    }
}
// get xth percentile from k samples
List<Integer> sample = new ArrayList<Integer>(queue.values());
Collections.sort(sample);
int approxPercent = sample.get(sample.size() * x / 100);
System.out.println("Approximate percentile: " + approxPercent);
// get real value of the xth percentile
Collections.sort(stream);
int percent = stream.get(stream.size() * x / 100);
System.out.println("Real percentile: " + percent);

The result is:

Approximate percentile: 29
Real percentile: 29

I got a pretty good approximation for every x i used and currently i don't see why it can't be suitable for your case.
Comment: So I am currently attempting reservoir sampling with the selected elements being stored into a arraylist. But, it seems that the approximation is still far off from the desired xth percentile. So, I was wondering if a change in data structure would perhaps optimize this further in anyway? Also, the stream elements are response times and so, although some of the response times may appear out of order; they generally are in a somewhat sorted order and responses that are too out of order can be discarded. Knowing this, is there a different sampling algorithm that would be better given this?
Comment: @Bruce , i've added a code sample to the answer. Currently i can't see why this approximation is not working for you. Maybe you can provide an example of the stream?


Why is $ 2\binom nm^2<n^{2m}$?

Question: $\forall n\geq2 \forall m\geq2,$ $$ 2\binom nm^2<n^{2m}.$$
Why is the above inequality, which is equivalent to $ \binom nm<\frac{n^m}{\sqrt 2}$, true?
Answer: $$\binom nm =\frac {n (n-1) ... (n-m+1)}{m!} < \frac{n^m}{m!}$$
Thus, if $m \geq 2$
$$\binom nm^2 < \frac{n^{2m}}{m!^2} < \frac{n^{2m}}{2}$$
But your bound is very crude!

Why is $ 2\binom nm^2<n^{2m}$?


Why do combat sports use weight classes, but not other sports?

Question: It seems obvious why there are weight classes in combat sports - bigger fighters have an advantage over smaller ones.
But it also seems obvious that some physical attributes confer an advantage in other sports. For example, tall players have an advantage in basketball. Why aren't there "height classes" in basketball then?
Comment: Rowing comes to my mind where there is a light weight class: https://en.wikipedia.org/wiki/Lightweight_rowing
Comment: Some would argue that is what the gender divisions are.
Answer: Safety, mostly
A basketball team that loses very badly is humiliated. A boxer (or wrestler, mixed martial artist, etc.) who loses very badly might be severely hurt or even killed. Per Wikipedia, weight classes were originally established in boxing because "size mismatches were dangerous for the smaller boxer and unsatisfying for the spectators".
Answer: To have more champions.
It would be boring to have only one UFC champion, but in basketball there are 15 people on an NBA champion team.  Now the UFC can have 4-5 champions per gender.  Otherwise the best fighter from the heaviest class would most likely be lone champion.
Comment: Is tennis therefore boring because it has only one champion (per gender category)? The same applies to many other individual sports where physical size is an advantage.
Comment: The whole point of arts like Judo is that it enables smaller people to defeat larger people.  Ask any judo player. Your argument is grossly inaccurate.
Comment: There is no competitive edge from being bigger in tennis I believe that is the first requirement of having weight classes.
Comment: Medvedev: 1.98m, Zverev: 1.98m, Nadal: 1.85m, Tsitsipas: 1.93m, Alcaraz: 1.85m, Ruud: 1.83m, Djokovic: 1.88m, Rublev: 1.88m, Auger-Aliassime: 1.93m, Sinner: 1.88m (all heights from Wikipedia). The country with the tallest males in the world is the Netherlands at 1.825m. **Every single one of the world's top ten players is taller than average of males in the tallest country in the world**. I submit that your statement is false.
Comment: There are many female champions in tennis that are short and some of the greatest.  Rodger federer and nadal are also pretty average height.  This is not a sport like judo where the bigger person would slaughter the smaller one.


CheckMyProof: $f$ is bounded, uniformly continuous $\implies e^{f}$ is bounded, uniformly cts.

Question:
Let $~f: \mathbb{R} \to \mathbb{R}$ be bounded and uniformly continuous.
  Show that $e^f$ is also bounded and uniformly continuous.

My approach (with 5xum's extensive help) goes as follows:

$f$ bounded $\implies$ $e^f$ bounded

Since there exists an $M \in \mathbb{R}_{>0}$ so that $|f(x)| \leq M$ for all $x \in \mathbb{R}$, by the continuity and monotonicity of $e^x: \mathbb{R} \to \mathbb{R}$, we can see that $|e^{f(x)}| = e^{f(x)} \leq e^M ~\forall x \in \mathbb{R}$.

$f$ uniformly continouos. $\implies$ $e^f$ uniformly continuous.

We want to show that
$$
\forall \varepsilon' > 0 ~\exists \delta' > 0 ~\forall x,y \in \mathbb{R}: (|x-y| < \delta' \implies |e^{f(x)} - e^{f(y)}| < \varepsilon')
$$
Let $\varepsilon' > 0$ be fixed and set $\varepsilon :=  \frac{\varepsilon'}{2 M} > 0$, where $M$ is the bound of $\max\{e^{f(x)},e^{f(y)}\}$, meaning $|e^{f(x)}|, |e^{f(y)}| \leq M ~\forall x,y \in \mathbb{R}~~(*_2)$.
Since $f$ is uniformly continuous, the following holds
$$
\forall \varepsilon > 0 ~\exists \delta > 0 ~\forall x,y \in \mathbb{R}: |x - y| < \delta \implies |f(x) - f(y)| < \varepsilon ~~(*_1)
$$
Now, let $\delta > 0$ be so that $|x - y| < \delta$ and without loss of generality let $f(y) \geq f(x) ~\forall x,y\in\mathbb{R}$. Then we obtain
$$
\begin{align*}
|e^{f(x)} - e^{f(y)}| = |e^{f(x)}| |1 - e^{f(y) - f(x)}|
&= e^{f(x)} |e^{|f(y) - f(x)|} - 1| \\
&\overset{(*)}{<} 2 e^{f(x)} |f(x) - f(y)| \\
&\overset{(*_1)}{<} 2 e^{f(x)} \varepsilon \\
&\overset{(*_2)}{\leq} 2 \varepsilon M \\
&=\varepsilon'
\end{align*}
$$
Where $(*)$ can be done because $|e^u - 1| < 2u ~~\forall u \in (0,1]$.
Answer:

$f$ bounded $\implies$ $e^f$ bounded

trivial because of the monotonicity of $e^x$ ??

My professor had a favourite saying: "Dear colleague, 'trivial' and 'obvious' are my words. They are not yours to use."
If what you wrote is so trivial, then you should be able to prove it in $3$ lines, and if you are able to prove in $3$ lines, then just do it.
Beside, $f(x)=\frac1{x-1}$ is a monotonic function on $(0,1)$, but it is not bounded, so your argument obviously needs work.

$f$ uniformly cts. $\implies$ $e^f$ uniformly cts.

We want to show that $$ \forall \varepsilon' > 0 ~\exists \delta' > 0
> \forall x,y \in \mathbb{R}: (|x-y| < \delta' \implies |f(x) - f(y)| <
> \varepsilon') $$

No. We assume that what you wrote is true. What we need to prove is the following:
$$\forall\epsilon >0 \exists \delta > 0 \forall x,y\in\mathbb R:(|x-y|<\delta\implies |e^{f(x)} - e^{f(y)}| < \epsilon)$$
You need to prove the uniform continuity of $e^f$, while assuming that $f$ is uniformly continuous and bounded.

After your edit:
Part 1 is ok now.
Part 2 is still strange.
First problem:

Let $\varepsilon > 0$ be fixed and $\varepsilon' > 2 M \varepsilon >0$

This is very strange. Your proof should start with "Let $\varepsilon' > 0$", not "$\varepsilon > 0$." I think this is only a consequence of sloppy writing, though, so you should write, instead of the above,

Let $\varepsilon' > 0$ be fixed and set $\varepsilon = \frac{\varepsilon'}{2M}$

And then the proof should work out.
Second problem:

From $|x - y| < \delta$ follows that $|f(x) - f(y)| < \varepsilon$ because $f$ is uniformly cts.

This is very sloppy writing. What is $\delta$ equal to here? You haven't defined $\delta$, it just appeared out of the blue. This is another example of sloppy writing that must be fixed.
Third problem:

$$|e^{f(x)} - e^{f(y)}| =
|e^{f(x)}| |e^{|f(x) - f(y)|} - 1|$$

This is false if $f(x)<f(y)$. For example, if $f(x)=0$ and $f(y)=1$, then the left side of the equation equals $|e^0-e^1|=e$, while the right side equals $|e^0||e^{|0-1|} - 1| = 1\cdot |e-1|=e-1$
Fourth problem:

$$|e^{f(x)}| |e^{|f(x) - f(y)|} - 1| <
e^{f(x)} |e^{\varepsilon} - 1|$$

How do you know this inequality is true? If I were you, I would first use the knowledge you write in $*$ before going for the estimate with $\delta$...

After your second edit:
Slight problem:
Don't say "let $\delta$ be fixed", better to just say "let $\delta$ be such that if $|x-y|<\delta$, then $|f(x)-f(y)|<\epsilon$. That way, it's clear you only fix one number ($\epsilon$) and then "calculate" what $\delta$ is.
Bigger mistake:
You still wrote

$$|e^{f(x)}| |1 - e^{f(y) - f(x)}| =
e^{f(x)} |e^{|f(y) - f(x)|} - 1|$$

which is not true, since, for $f(x)=1$ and $f(y)=0$, the left side equals $$|e^1|\cdot |1-e^{0-1}| = e\cdot (1-e^-1) = e-1$$
while the right side equals
$$|e^1|\cdot |e^{|0-1| -1} = e\cdot (e-1)=e^2-1$$
Comment: @ViktorGlombik Your proof is very very sloppy. You obviously have the correct idea, but if I was grading this, you would struggle to get half the points. There are at least 4 problems with your proof which I described in my edited answer.
Comment: I wasn't sure how to prove the boundness (hence the ? at the end), the 'trivial'-statement was a hint received from a friend. I now added a proof to my question, is it correct? And you're right about the "We want to show"-part. I misspelled and now edited my question.
Comment: I've tried to incorporate your suggestions. Is my proof satisfactory now?
Comment: @ViktorGlombik Unfortunatelly, no. It's much closer, but still sloppy.
Comment: but I said that log $f(y) \geq f(x)$, so that $f(y) - f(x) = |f(y) - f(x)|$. In your counterexample, you ignore that condition, or am I mistaken?
Comment: @ViktorGlombik Oh, you're right. But you still follow that up with $$e^{f(x)} |e^{|f(y) - f(x)|} - 1|
e^{f(x)} |e^{\varepsilon} - 1|$$ which is not well justified. Just because $|A|<\epsilon$, that doesn't necessarily mean that $|F(A)|<|F(\epsilon)|$, it depends on the function $F$, and in your case, the function is $F(X) = |e^X-1|$ for which the above is not always true. Instead, use the $*$ inequality **FIRST**, then use the $*_1$ inequality.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/75780/discussion-between-viktor-glombik-and-5xum).


Counting Multi-Sets for Donuts

Question: The problem is:
Suzy is selecting 20 donuts to bring to her club meeting. The donut store sells 7 varieties of donuts. Donuts of the same variety are all the same. There is a large supply of each variety of donuts, except for jelly donuts. There are only 5 jelly donuts available. How many ways are there for Suzy to select the donuts?
I was thinking that the answer was $5{20 + 6 - 1 \choose 6-1}$, since there is not an unlimited supply of jelly donuts. Would that logic be correct?
Comment: @Jon The proposed answer is incorrect.
Answer: Suzy can choose $j\in[0..5]$ jelly donuts and then $20-j$ donuts of the other six kinds. Therefore there are
$$\sum_{j=0}^5 {20-j+5\choose 5}=191\,470$$
ways to chose the donuts. The number ($265\,650$) proposed by you is wrong on two accounts: (i) There are six possible choices for $j$. (ii) When the $j$ jelly donuts have been chosen there are no longer $20$ donuts to be bought.
Answer: Christian Blatter has explained how to correct your approach and why your approach was incorrect.  Here is another method.
Let $x_j$ denote the number of jelly donuts.  Let $x_k$, $1 \leq k \leq 6$, be the number of donuts of type $k$ that Suzy purchases.  Then
$$x_1 + x_2 + x_3 + x_4 + x_5 + x_6 + x_j = 20 \tag{1}$$
is an equation in the nonnegative integers.  If we temporarily ignore the restriction that $x_j \leq 5$, a particular solution of equation 1 corresponds to the placement of six addition signs in a row of $20$ ones.  For instance,
$$1 1 1 + 1 1 + 1 1 1 1 + 1 1 + + 1 1 1 1 1 1 + 1 1 1$$
corresponds to the solution $x_1 = 3$, $x_2 = 2$, $x_3 = 4$, $x_4 = 2$, $x_5 = 0$, $x_6 = 6$, and $x_j = 3$.  There are
$$\binom{20 + 6}{6} = \binom{26}{6}$$
such solutions since we must choose which $6$ of the $26$ positions required for $20$ ones and $6$ addition signs will be filled with addition signs.
From these, we must subtract the number of cases in which the condition $x_j \leq 5$ is violated.  Suppose $x_j > 5$. Then $x_j' = x_j - 6$ is a nonnegative integer.  Substituting $x_j' + 6$ for $x_j$ in equation 1 yields
\begin{align*}
x_1 + x_2 + x_3 + x_4 + x_5 + x_6 + x_j' + 6 & = 20\\
x_1 + x_2 + x_3 + x_4 + x_5 + x_6 + x_j' & = 14 \tag{2}
\end{align*}
Equation 2 is an equation in the nonnegative integers with
$$\binom{14 + 6}{6} = \binom{20}{6}$$
solutions.  Since these are the cases that violate the restriction that $x_j \leq 5$, we conclude that the number of ways that Suzy can purchase $20$ donuts at the store without buying more than five jelly donuts is
$$\binom{26}{6} - \binom{20}{6}$$

Counting Multi-Sets for Donuts


The AMP module requires the PHP AMP library

Question: I installed Drupal 8 and amptheme. I downloaded the AMP module and the library files. When I tried to install the module, I got the following message:

The AMP module requires the PHP AMP library.

The library files are in libraries/amp-library. I think the library location is incorrect.
How do I fix the error?
Answer: This module requires the use of Composer to install its libraries. You can learn more about Drupal and Composer on drupal.org's documentation hand book Installing modules' Composer dependencies in Drupal 8. The AMP module project page also has a brief description of how to install on Drupal 8.0.5.
Comment: Thank you, I have installed Composer Manager module, but when i run username@locahost:/var/www/SITENAME$ composer drupal-update shows warning like **Warning: This development build of composer is over 30 days old. It is recommended to update it by running "/usr/local/bin/composer self-update" to get the latest version.**


Placing coloured pieces on graph edges such that every cycle has at least one piece of each colour

Question: Given a connected graph with N nodes, E edges, and Blue and Red pieces.
Any number (0, 1, 2, ...) of Blue and Red pieces can be placed on any edges.

What's the minimum number of pieces needed to ensure that all cycles include at least one Blue piece and one Red piece?

Can anything be concluded about the pieces placing strategy to get minimum number of pieces?

Can anything be concluded about Blue-to-Red pieces ratio in the minimum pieces configuration? E.g. equal number of red and blue pieces.
Comment: This reminds me of Ramsey numbers.
Comment: I am going to assume that by "loop" you mean "cycle", because your question doesn't make sense otherwise, but let me know if I misunderstand.
Comment: Hi Misha. Thanks for your answer. Correct, cycles..
Answer: If we deleted every edge with a blue piece on it, we would be left with an acyclic graph; therefore we can be left with at most $N-1$ edges. Therefore at least $E-N+1$ edges need to have a blue piece on them, and similarly at least $E-N+1$ edges need to have a red piece on them.
This lower bound can be achieved, and in general the method to do it is to:

Pick a spanning tree $T$, and put a blue piece on every edge not in $T$.
Pick a spanning tree $T'$ (possibly the same as $T)$, and put a red piece on every edge not in $T'$.


Is function P infinitely additive (countably or uncountably additive)?

Question:
Suppose our probability space $W$ is the set $\mathbb{N} = \{0,1,2,\dots\}$ of natural numbers, and $\mathcal{A}$ is the algebra of all subsets of $\mathbb{N}$.
  Suppose we define a function $P$ on $\mathcal{A}$ such that $P(X) = 0$ whenever $X\in\mathcal{A}$ is finite, and $P(X) = 1$ when $X$ is infinite.
  Is $P$ finitely additive?
  Either prove it is, or explain why it is not.

Where do I start with this proof? I'm new to probability, and could use a solid hint.
Answer: $$
1=P(\mathbb N) = P\left( \bigcup_{n\in\mathbb N} \{n\} \right) \overset{\Large\text{?}} = \sum_{n\,\in\,\mathbb N} P(\{n\}) = \sum_{n\,\in\,\mathbb N} 0 = 0. \\ \phantom{\frac11}
$$
\begin{align}
1 & = P(\mathbb N) = P( \text{set of all even members of } \mathbb N \cup \text{set of all odd members of } \mathbb N) \\[10pt]
& \overset{\Large\text{?}} = P( \text{set of all even members of } \mathbb N) + P(\text{set of all odd members of } \mathbb N) = 1+1
\end{align}
Comment: @PrasunBiswas: Do you agree w this: https://math.stackexchange.com/questions/705285/is-p-finitely-additive-when-pa-0-if-a-is-finite
Comment: Hi Michael, I am still stuck after many days. Can you explain above? So to prove that P is infinitely additive I only need to disprove that P is finitely additive? But I don't understand what you did above.
Comment: @floatingkrishna : You cannot prove that a set function is countably additive by proving only that it is finitely additive. But you can prove that it is _not_ countably additive by proving that it is _not_ finitely additive.
Answer: Hint: odd naturals, even naturals, naturals.
Comment: @tozhello I'm not sure what you mean, but try to *disprove* that P is finitely additive. Note that you only need to find *one* counterexample, instead of proving a property for an infinite number of cases.
Comment: Thanks Anonymous, let me think about this, am new to probability
Comment: @tozhello don't think about probability. Think about P as a generic function on sets. The property that it must have to be finitely additive is that if you take a finite number (in this case two suffices) of disjoint sets, the sum of the values of P on them equal the value of P on their union.
Comment: Thanks, let me think.
Comment: Just to clarify: By proving P is finitely additive it is sufficient to prove that P is infinitely additive?
Comment: So by using odd and even natural numbers and making them 1 + 1 = 2 this disproves that P is finitely additive & therefore proves that P is infinitely additive? I'm still lost with this question. Is there anyway you can explain this out a bit more?


Remote Ratchet Connection

Question: So I have been trying to set up ratchet for some time now. And have hit another snag. I have followed this tutorial http://socketo.me/docs/hello-world and everything seems to work on the local machine. however when I try to access them from a remote machine for testing purposes I cannot. Under the help and troubleshooting section it states to bind the chat-server program to 0.0.0.0 and I have done this to no avail. currently I have it running on port 9680 because 80 and 8080 are inuse on the system. (which is running an apache server) any help or suggestions on how to solve this connection issue would be much appreciated as I cannot continue with my project until I can access the Websockets remotely. I am fairly new to server administration so my knowledge of how to set this up is fairly slim. Thanks in advance!
Answer: You actually shouldn't bind your WebSocket server to 0.0.0.0 in production. In the context of servers, 0.0.0.0 means "all IPv4 addresses on the local machine". So say your server has a public IP address of 220.127.116.11 and a local/private IP address of 192.168.0.1, then this means an application bound to 0.0.0.0 will be reachable from both IPs (at least to whatever can route to those addresses). Which, typically, in a production setup, is not something you want. Normally, you want to bind to specific IP addresses on specific network interfaces, because you know exactly what your host will listen on.
Common gotchyas to look out for
The other gotchyas you want to look out for, is that binding to the public interface usually requires root privileges. Trying to do so without elevated privileges will usually result in an error opening the TCP socket. There's also the address is already in use problem, which can be solved by making sure you have SO_REUSEADDR set on the socketopt (though, I'm fairly certain Ratchet does this for you by default). Additionally, if you're running SELinux, there's always the possibility that you're policy won't allow listening on that port. Then there's the firewall network configuration issues where either your firewall or some part of your network hardware is blocking the port.
Ratchet and Apache over the same port
The other draw back to having a multi-tenancy server, is that if you want to serve HTTP traffic both from your Apache httpd webserver as well as your PHP WebSocket server, you can't bind both to the same port on the same IP without putting a reverse proxy in front of them. In fact, this is what Ratchet recommends for production in their documentation.
The general idea is to have a reverse proxy like HAProxy, bound to the public IP listening on port 80/443, and then configure it route specific traffic either to your PHP WebSocket server (which will probably be listening on the local loopback or local network interface) or to your Apache httpd webserver depending on say a specific set of routes or some cookie, for example.

Remote Ratchet Connection


String should get split on the right side of the page

Question: I have a path saved in string (datn1, datn2) and want to print the path on a page. So I have to look, if the string is too long for the width of the page and if it is too long, it should begin with a new line.
First of all I split the string and saved it in a string array:
String datn1 = dateiName1, datn2 = dateiName1;
char[] Trennzeichen = { '\\' };
String[] folders1 = datn1.Split(Trennzeichen);
String[] folders2 = datn2.Split(Trennzeichen);

I also have the margins of the page in variables:
float leftMargin, rightMargin, topMargin, bottomMargin, width, height;

Now I want to add a new string to parts of the string array and look, if it's on the page. When it reaches the right site it should make a new line... how can i do that?
my idea:
string path_new;
for (int i = 0; i <= folders1.Length; i++)
{
   If()//How can i say that he should look if the string is inside the margins?
   {
      path_new= folders1[i]+"//";
   }
   else
   {
      path_new= "\n" + folders1[i]+ "//";
   }
}

Comment: Is site in your question referring to a website? What framework are you using to build the website in c#? If it's a website, what use is it to calculate the length of the string on the server? What if someone has a lower resolution or resizes the window?
Comment: no i suggested the right side of a page, which i want to print... pagesize --> a4
Comment: It's clearer now but I don't understand what you are trying to achieve. Are you writing the path to a file that you print out or by what means are you printing your output? Additional question: Won't this depend on the font and its size?
Comment: i want to print the path on a page and because it is to long i have to split it. yes it depends on the font and size. because of that i want a query if the string is inside the margins and if not it should begin with a new line. uptonow it looks like this: http://abload.de/img/problem2bkz6.png
Answer: now i found a solution:
 private void DrawGraphic(Graphics g)
{
    g.PageUnit = GraphicsUnit.Millimeter;
    String datn1 = dateiName1, datn2 = dateiName2;
                char[] Trennzeichen = { '\\' };
                String[] folders1, folders2;
                if (vergl.X == 1)
                   folders1 = datn1.Split(Trennzeichen);
                else
                   folders1 = new String[0];
                if (vergl.Y == 1)
                   folders2 = datn2.Split(Trennzeichen);
                else
                   folders2 = new String[0];

                if (pageSetupDialog1.PageSettings.Landscape == false)
                {
                  string path_new = "";
                  string path_new2 = "";

                for (int i = 0; i < folders1.Length; i++)
                {
                 string path_temp = path_new + folders1[i] + "//";
                 System.Drawing.Size size_path_temp = TextRenderer.MeasureText(path_temp, new Font("Verdana", 8f));  // get size of string path_temp (in pixel)
                 double size_path_temp_width = Convert.ToDouble(size_path_temp.Width);
                 double variable = Convert.ToDouble(rightMargin.ToString())*96/25.4d; //96 = dpi Anzahl

                if (size_path_temp_width < variable)
                 {
                  path_new += folders1[i] + "//";
                 }
                 else
                 {
                  path_new += System.Environment.NewLine + folders1[i] + "//";
                 }
                }

            for (int i = 0; i < folders2.Length; i++)
            {
              string path_temp = path_new2 + folders2[i] + "//";
              System.Drawing.Size size_path_temp = TextRenderer.MeasureText(path_temp, new Font("Verdana", 8f));  // get size of string path_temp (in pixel)
              double size_path_temp_width = Convert.ToDouble(size_path_temp.Width);
              double variable = Convert.ToDouble(rightMargin.ToString()) * 96 / 25.4d; //96 = dpi

         if (size_path_temp_width < variable)
         {
          path_new2 += folders2[i] + "//";
         }
         else
         {
          path_new2 += System.Environment.NewLine + folders2[i] + "//";
         }
        }
 g.DrawString(path_new, new Font("Verdana", 8f), new SolidBrush(Color.Black), leftMargin, topMargin+10);
 g.DrawString(path_new2, new Font("Verdana", 8f), new SolidBrush(Color.Black), 20, topMargin + 10 + bmp1.Height / 6 + 25);
}

dateiName1 and dateiName2 is a string in which the paths are saved.
vergl.X and vergl.Y checks if there is a path read in


How to config Apache to get error 502 Bad Gateway for testing?

Question: I'm developing a website with ajax allow many queries insert many many row to database in the same time. It's run ok on localhost, but when I deploy onto server (free Amazon server), it's often get error 502 Bad Gateway. Now, I also want get Error 502 on my Apache localhost for testing my code. So, how to config server? Thank for helps.
Answer: You can use mod_rewrite
RewriteEngine On
RewriteCond %{REQUEST_URI} ^/badurl
RewriteRule .* - [R=502]

All urls, matched pattern "^/badurl" will return 502 error.


How to modify and queue arrays with a function using .push and .shift

Question: Basically, I need to know how to move an array through a queue so that "1' gets knocked off and "6" gets added. I already know to do this I need to use the .push() and .shift() elements. I, however, am stumped on how to do so. Particularly how to structure the code and what to tell the .push() and .shift() to look at. Ex. "blank.push();". The farthest I got was to include "arr.push()" and "arr.shift()" within the function but all that did was knock off the "1". I also need to know why and what I need to change the "return item;" line to. Below is the code I was provided.

function nextInLine(arr, item) {
  // Your code here

  return item;  // Change this line
}

// Test Setup
var testArr = [1,2,3,4,5];

// Display Code
console.log("Before: " + JSON.stringify(testArr));
console.log(nextInLine(testArr, 6)); // Modify this line to test
console.log("After: " + JSON.stringify(testArr));

If all you want to do is provide a solution that works, I should be able to follow the bread crumbs of what goes where and figure out how and why it works but I would very much appreciate a detailed as possible explanation of what is happening in this code for everything above the "//Display Code" line. I have some working knowledge of JS but the less you assume I know the happier I will be. :)
BONUS ROUND: Just curious but if some could tell me why "arr.shift()" is acceptable code (regardless of it's function) but "item.push()" or "item.shift()" errors as "TypeError: item.push is not a function." To me, they are both just similar parameters of this function. Why does one error out while the other doesn't? Is there a programmed meaning to "arr" or trait I am unaware of?
Comment: `shift` and `push` are array methods. `item` has the value `6` in your code. `6` is a number, not an array, and doesn't have these methods.
Comment: Is this similar to what you are asking? http://stackoverflow.com/questions/1590247/how-do-you-implement-a-stack-and-a-queue-in-javascript
Comment: Possible duplicate of [How do you implement a Stack and a Queue in JavaScript?](http://stackoverflow.com/questions/1590247/how-do-you-implement-a-stack-and-a-queue-in-javascript)
Comment: i should add that you really need to look a bit at the documentation for the functions you use, it would have spared you time ;)
Answer: function nextInLine(arr, item) {
    var nextItem = arr.shift(); // This removes the first element of the array, being 1, and assigns it to the nextItem variable.
    // Now arr = [2,3,4,5]
    arr.push(item); // This adds the item 6 to the end of the queue
    // Now arr = [2,3,4,5,6]
    return nextItem;
}

Bonus Answer:

arr in this context is an array, which has push and shift methods.

and item is a number, which doesn't have such methods
Answer: function nextInLine(arr, item) {
    // Your code here
    arr.shift();
    arr.push(item);
    return item;  // Change this line
}


User gets instantly disconnected after connection successful on a chrooted SSH

Question: I configured a jail with Chroot in SSH following this tutorial.
I found another question on StackOverflow dealing with the same problem, however the answers didn't work for me either.
The auth.log file contains the following:
Mar 16 18:36:06 *** sshd[30509]: Accepted password for thenewone from x.x.x.x port 49583 ssh2
Mar 16 18:36:06 *** sshd[30509]: pam_unix(sshd:session): session opened for user thenewone by (uid=0)
Mar 16 18:36:07 *** sshd[30509]: lastlog_openseek: Couldn't stat /var/log/lastlog: No such file or directory
Mar 16 18:36:07 *** sshd[30509]: lastlog_openseek: Couldn't stat /var/log/lastlog: No such file or directory
Mar 16 18:36:07 *** sshd[30509]: pam_unix(sshd:session): session closed for user thenewone

My sshd_config file contains the following:
Match User thenewone
    ChrootDirectory         /home/thenewone
    AllowTcpForwarding      no
    X11Forwarding           no

My /home/thenewone directory is owned by root:root and contains the chrooted system (all files but /home/thenewone/home/thenewone owned by root:root)
I don't understand why the connection is successful then simply close.
Answer: Problem found: some binaries dependencies were missing, even for the shell associated with the chrooted account...
Shell failed to load --> disconnection!
If you are experiencing the same trouble as mine, use ldd <binary> to find all needed dependencies in the chroot jail


How do I stop gdb from continuously hitting breakpoints in gdb extended with Python?

Question: I extended gdb with Python, but when there are a large number of breakpoint hits, gdb only stops the first time and will not stop later. Additionally, I found that if gdb. execute ('continue ', to_string=True) is not used to automatically run, but rather manually execute continue, this problem does not exist.
my code as:
<code>def CmdCaptureBreaks(event):
    print("capture a event")
    if not isinstance(event, gdb.BreakpointEvent):
        return
    cur = event.breakpoints[0].location
    if cur is None:
        cur = event.breakpoints[0].expr
    o = gdb.execute('bt', to_string=True)
    print(o)
    BreakDispatch(cur)
    #time.sleep(3)
    gdb.execute('continue', to_string=True)

gdb.events.stop.connect(CmdCaptureBreaks)
</code>
the gdb infomations
<code>(gdb) b rte_flow_query
Breakpoint 1 at 0x56190d3ee190
(gdb) c
Continuing.
[Switching to Thread 0x7fd59effd400 (LWP 30636)]

Thread 17 "revalidator12" hit Breakpoint 1, 0x000056190d3ee190 in rte_flow_query ()  ##### first hit
capture a event
#0  0x000056190d3ee190 in rte_flow_query ()
#1  0x000056190d5ea00a in netdev_dpdk_rte_flow_query_count ()
#2  0x000056190d5ea56a in netdev_offload_dpdk_flow_get ()
#3  0x000056190d4b0e03 in dpif_netdev_get_flow_offload_status ()
#4  0x000056190d4b0f44 in get_dpif_flow_status ()
#5  0x000056190d4b1048 in dp_netdev_flow_to_dpif_flow ()
#6  0x000056190d4b2dd0 in dpif_netdev_flow_dump_next ()
#7  0x000056190d4c8301 in dpif_flow_dump_next ()
#8  0x000056190d46fcac in revalidate.isra ()
#9  0x000056190d471d30 in udpif_revalidator ()
#10 0x000056190d566fa0 in ovsthread_wrapper ()
#11 0x00007fd5d0dd9609 in start_thread (arg=<optimized out>) at pthread_create.c:477
#12 0x00007fd5d0acb293 in clone () at ../sysdeps/unix/sysv/linux/x86_64/clone.S:95

Thread 17 "revalidator12" hit Breakpoint 1, 0x000056190d3ee190 in rte_flow_query () #####no stop
Thread 17 "revalidator12" hit Breakpoint 1, 0x000056190d3ee190 in rte_flow_query () #####no stop
Thread 17 "revalidator12" hit Breakpoint 1, 0x000056190d3ee190 in rte_flow_query () #####no stop
Thread 17 "revalidator12" hit Breakpoint 1, 0x000056190d3ee190 in rte_flow_query ()  #####no stop
Aborted (core dumped)
When execute control+c may cause crash.
</code>
If I manually execute continue, there is no problem!!!
PS:root@localhost:~# gdb --version
GNU gdb (Ubuntu 9.2-0ubuntu1~20.04.1) 9.2
Any advice would be appreciate! Thanks in advance.
When I delete gdb.execute('continue', to_string=True), and manually execute continue in gdb , there is no problem!!!
`
<code>(gdb) b rte_flow_query
Breakpoint 1 at 0x5617df277190
(gdb) c
Continuing.
[Switching to Thread 0x7f1627fff400 (LWP 53739)]

Thread 17 "revalidator12" hit Breakpoint 1, 0x00005617df277190 in rte_flow_query ()
capture a event
#0  0x00005617df277190 in rte_flow_query ()
#1  0x00005617df47300a in netdev_dpdk_rte_flow_query_count ()
#2  0x00005617df47356a in netdev_offload_dpdk_flow_get ()
#3  0x00005617df339e03 in dpif_netdev_get_flow_offload_status ()
#4  0x00005617df339f44 in get_dpif_flow_status ()
#5  0x00005617df33a048 in dp_netdev_flow_to_dpif_flow ()
#6  0x00005617df33bdd0 in dpif_netdev_flow_dump_next ()
#7  0x00005617df351301 in dpif_flow_dump_next ()
#8  0x00005617df2f8cac in revalidate.isra ()
#9  0x00005617df2fad30 in udpif_revalidator ()
#10 0x00005617df3effa0 in ovsthread_wrapper ()
#11 0x00007f1669996609 in start_thread (arg=<optimized out>) at pthread_create.c:477
#12 0x00007f1669688293 in clone () at ../sysdeps/unix/sysv/linux/x86_64/clone.S:95

(gdb) continue   ####### manually execute

Thread 17 "revalidator12" hit Breakpoint 1, 0x00005617df277190 in rte_flow_query ()
capture a event
#0  0x00005617df277190 in rte_flow_query ()
#1  0x00005617df47300a in netdev_dpdk_rte_flow_query_count ()
#2  0x00005617df47356a in netdev_offload_dpdk_flow_get ()
#3  0x00005617df339e03 in dpif_netdev_get_flow_offload_status ()

#4  0x00005617df339f44 in get_dpif_flow_status ()
#5  0x00005617df346770 in dpif_netdev_operate ()
#6  0x00005617df352e80 in dpif_operate ()
#7  0x00005617df2f46a1 in push_dp_ops ()
#8  0x00005617df2f967d in revalidate.isra ()
#9  0x00005617df2fad30 in udpif_revalidator ()
#10 0x00005617df3effa0 in ovsthread_wrapper ()
#11 0x00007f1669996609 in start_thread (arg=<optimized out>) at pthread_create.c:477
#12 0x00007f1669688293 in clone () at ../sysdeps/unix/sysv/linux/x86_64/clone.S:95`
</code>
Answer: I don't know the answer to the Python question, but I can tell you how to do this specific thing in pure GDB.
<code>(gdb) b rte_flow_query
Breakpoint 1 at 0x56190d3ee190
(gdb) comm 1
>bt
>continue
>end
(gdb) continue
</code>
This attaches a GDB command script to breakpoint 1 which prints the backtrace and then continues. I do this sort of thing all the time, so I know it works. If you need something more complex you can probably embed or call some Python.
To disable the commands, simply define them again, but empty.
<code>(gdb) comm 1
>end
(gdb)
</code>


redirect the vtiger application to jsp application when user click logout link in vtiger

Question: I need to change the logout href into mysite jsp application url. where i get this line in vtiger folder .
I spent more than a hour not able to figure out can you please tell where should i get the file (view page source code).
Sign Out

To example:
Sign Out

why i need this mean because im redirecting jsp application to vtiger with sso lgoin that's no issue.so if user click logout i need redirect the user back to my jsp application  this is what i need exaclty.
Thanks advance.
Comment: please help me guys
Answer: You can achieve this functionality by changing one line from below file: root\modules\Users\actions\Logout.php
Existing code: header ('Location: index.php');
Update code: header ('Location: http://www.google.com/'); //Enter your jsp application url
Comment: Thank you. Cheers!
Comment: may i know vtiger developed using which framework ? @sAch


Creating a validation for a switchClass on hover so the animations are tied to when the mouse enters and leaves the div

Question: Using a hover function, I have some divs that switch classes when the mouse enters and leaves the parent div. The problem is that if the mouse leaves the webpage, the switchClass stays toggled in the state that I want to only happen when the mouse is hovering in the parent div.
So I have a series of rows. They're built out with a container, then two divs side by side, child1 and child2. When the mouse is not in the container, child1 is 100% width and child2 is hidden by overflow: hidden. When the mouse hovers over the container, child1 switches to the class child1-hover and child2 slides into view, and vice versa.
I have it working with hover(), but I would rather there be some sort of validation using mouseEnter and mouseLeave because if I scroll too fast over the rows or if my mouse leaves the webpage, the switch gets switched, so when I'm not hovering over the container the child has child1-hover applied and vice versa.
Here are my issues:

I don't like that when I scroll too fast or my mouse leaves the webpage, the hover state in my switchClass becomes the non-hover state. See this version: https://jsfiddle.net/sling/g7xLn1ut/6/
I have to use classes, not IDs because there's like 30 rows on this webpage, so then I have to use a $('.container').hover(function() { ->>>$(this).find<<<- just to make things a little more complex
Even when using mouseenter and mouseleave, I still have the same issue where when I use switchClass. See this version: https://jsfiddle.net/sling/d6x4sfLn/
I don't want this function to slow down my website, so I don't want it like refreshing the page every 10 seconds or anything... So, with that in mind, maybe it's better to have there be a scroll to height activator that makes the child1 switch to child1-hover? This is more of a design/opinion question/a fallback in case what I want to happen is impossible

please beware, this is just a truncated version of the fiddles linked above

        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed suscipit enim orci. Aenean vulputate scelerisque lorem sagittis lacinia. Nunc vitae massa felis.

        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed suscipit enim orci. Aenean vulputate scelerisque lorem sagittis lacinia. Nunc vitae massa felis.

        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed suscipit enim orci. Aenean vulputate scelerisque lorem sagittis lacinia. Nunc vitae massa felis.

Ok and here's version two:

        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed suscipit enim orci. Aenean vulputate scelerisque lorem sagittis lacinia. Nunc vitae massa felis.

        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed suscipit enim orci. Aenean vulputate scelerisque lorem sagittis lacinia. Nunc vitae massa felis.

        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed suscipit enim orci. Aenean vulputate scelerisque lorem sagittis lacinia. Nunc vitae massa felis.

In version 1, when your mouse leaves the web page or scrolls too fast, the classes get switched so that child1-hover is the active class when you're not hovering in the container div.
In version 2, child1-hover still gets stuck when your mouse leaves the webpage off of the container div, but at least the next time you hover over it the hover state rights itself.
Hopefully part of that makes sense...
Answer: This is a great opportunity for a CSS only solution. You can solving the problem and won't need relatively heavy jQuery methods or any JavaScript. We can also simplify the code a little bit.
So, I edited from your JSFiddle code. You just have to apply :hover on .container for the effects.
Let me show you (below is the entire SCSS):
.container {
  width: 100%;
  height: 50vh;
  min-height: 300px;
  display: block;
  overflow: hidden;

  .image-h2 {
    top: 50%;
    color: white;
    padding: 1px;
    margin: 0;
    text-align: center;
    position: absolute;
    width: 100%;
    display: block;
    transition: 0.3s;
  }

  &:hover .image-h2 {
    opacity: 0;
  }

  .image-card {
    background-image: url("http://www.steves-digicams.com/blog/wp-content/uploads/2017/10/Nikon_D850_Sample_13.jpg");
    background-size: cover;
    background-position: center;
    width: 100%;
    height: 100%;
    position: relative;
    display: inline-block;
    transition: 0.3s;
  }

  &:hover .image-card {
    width: 40%;
    height: 100%;
  }

  .text-card {
    display: inline-block;
    width: 55%;
    padding-left: 1em;
    height: 100%;
    padding-bottom: 20px;
    vertical-align: middle;
  }

}

Answer: So I was actually able to answer this question with help from someone at a dev get-together. Here is our solution:
    $(function() {
          $(".project-container").on('mouseenter', function() {
            $(this).find(".image-card").animate({width: "33.33333333%"}, 300);
          });
          $(".project-container").on('mouseleave', function() {
            $(this).find(".image-card").animate({width: "100%"}, 300);
          });
          $("div").on('mouseleave', function(){
           $(this).find(".image-card").clearQueue()
         });
        });

Here's the whole thing, but instead of doing a switchClass, we realized we could do an animation. The clearQueue makes sure there's no jitter!

$(function() {
          $(".project-container").on('mouseenter', function() {
            $(this).find(".image-card").animate({width: "33.33333333%"}, 300);
          });
          $(".project-container").on('mouseleave', function() {
            $(this).find(".image-card").animate({width: "100%"}, 300);
          });
          $("div").on('mouseleave', function(){
           $(this).find(".image-card").clearQueue()
         });
        });
@charset "UTF-8";
/* ‹›‹›‹›‹›‹›‹›‹›‹›‹›‹›‹› Variables ‹›‹›‹›‹›‹›‹›‹›‹›‹›‹›‹› */
/* and mixins */
/* —+—+—+—+—+—+—+—+— Overall Body Styles +—+—+—+—+—+—+—+—+ */
body p, body span, body div {
  font-family: "Work Sans", Times, serif;
  font-size: 16px;
}
body a, body strong {
  font-weight: 600;
}
body h1, body h2, body h3, body h4, body h5, body h6 {
  font-weight: 200;
}

/* =≠=≠=≠=≠=≠=≠=≠=≠ Header and Nav styles =≠=≠=≠=≠=≠=≠=≠=≠ */
header #navigation {
  position: fixed;
  width: 100%;
  top: 0;
  z-index: 100;
}

/* ∞8∞8∞8∞8∞8∞8∞8∞8∞8∞8∞ Home styles ∞8∞8∞8∞8∞8∞8∞8∞8∞8∞8∞ */
main .jumbotron {
  padding-top: 7em;
}
main .intro-container {
  height: 10px;
}
main .project-container {
  width: 100%;
  height: 50vh;
  min-height: 300px;
  max-height: 500px;
  display: block;
  overflow: hidden;
}
main .project-container .row {
  width: unset;
  height: 100%;
}
main .project-container .row .image-h2 {
  opacity: 1;
  color: white;
  padding: 1px;
  margin: 0;
  text-align: center;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translateX(-50%) translateY(-50%);
  width: 100%;
  display: block !important;
}
main .project-container .row .image-h2-hide {
  opacity: 0;
  position: absolute;
  transform: translateX(-50%) translateY(-50%);
  top: 50%;
  left: 50%;
  display: none;
}
main .project-container .row .image-card {
  background-image: url("http://www.steves-digicams.com/blog/wp-content/uploads/2017/10/Nikon_D850_Sample_13.jpg");
  background-size: cover;
  background-position: center;
  width: 100%;
  height: 100%;
  position: relative;
  display: inline-block;
}
main .project-container .row .image-card-hover {
  background-image: url("http://www.steves-digicams.com/blog/wp-content/uploads/2017/10/Nikon_D850_Sample_13.jpg");
  background-image: url("http://www.steves-digicams.com/blog/wp-content/uploads/2017/10/Nikon_D850_Sample_13.jpg");
  background-size: cover;
  background-position: center;
  width: 33.33333333%;
  height: 100%;
  position: relative;
  display: inline-block;
}
main .project-container .row .text-card {
  display: inline-block;
  width: 66.66666667%;
  padding: 1em 0 1em 2em;
  height: 100%;
}

/* ·•·•··•·•·•·•· ADDITIONAL MEDIA QUERIES ·•·•··•·•· */

      <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
      <link rel="stylesheet" href="css/style.css">
      <link href="https://fonts.googleapis.com/css?family=Work+Sans:200,400,600&display=swap" rel="stylesheet">

                This is the second project

                Title

                Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin posuere urna non magna imperdiet, non commodo magna finibus. Integer vel lacus sit amet augue imperdiet malesuada. Praesent hendrerit gravida ligula, ac tempor sapien pharetra eget. Maecenas hendrerit, odio quis eleifend vehicula, lacus dui pretium urna, quis facilisis tortor augue eget ipsum. Sed viverra massa vitae pretium tristique. Quisque nec felis mi.

This is literally copy and pasted from my .html doc, so the snippet isn't... reaaallly working so... sooorrryyy....
buuuuut i didn't want to leave this question unanswered!


Symfony2 : How do I render a resultset into HTML grouping records in the output

Question: I have a Doctrine query as follows...
$qb = $this->createQueryBuilder('s')
            ->select('s, csr, c')
            ->Join('s.classesreference', 'csr')
            ->Join('csr.Class', 'c')
            ->where('c.id = :id and csr.SpellLevel = :level')
            ->setParameter('level', $level)
            ->setParameter('id', $Class->getId())
            ->orderBy('s.Name','ASC')
            ->orderBy('csr.SpellLevel')
            ->getQuery();

In my Twig template I'd like to display the results of this query in a nested unordered list.

Level 0

Level 1

Level 2

Level 3

I just can't figure out how to do this in twig from the returned result set (essentially an array of Spell objects)
classesreference is a reference table between Spell and CharacterClass that also contains a field for the spell level when used by the referenced CharacterClass record.
Any help is appreciated.
Comment: If you group by spellLevel, you'll only have one result per level? So your first level will be in $result[0] and so on. Maybe you can add more information about your data structure.
Comment: I may be misuderstanding groupby ... I understood it to collect records with the same value together in the result set with the sortby then applying to these groups.  How would you suggest I achieve the results I want from the question?
Comment: Ok, after some reading I was misuderstanding GroupBy ... I still can't figure out how to do what I want to do though.. updated question to reflect my increase in understanding.
Comment: An easy way to get started is to simply iterate over the $spells array in your controller and generate 4 new arrays each containing just one level.  Pass these 4 arrays to your template.  There are of course better ways to accomplish this but this will get you going.
Comment: Unfortunately there are currently a lot more spell levels than 4 and possibly more to add in the future so I need a solution that will work for any number of spell levels.
Comment: Same approach only use an array of arrays.
Answer: Ok, after the misunderstanding of groupBy is fixed, let's dive into this one ;)
First, what you want to achieve is a two-dimensional array like this:
array(
    0 => array('Spell1', 'Spell4'),
    1 => array(),
    2 => array('Spell3'),
    3 => array('Spell2'),
);

The first array would contain every spell level and an array of spells.
This cannot be done with MySQL alone. MySQL returns rows, so there is no way to write a query which will give you the perfect array. So, what you want to do is write a query which gives you back all spells with their level. As I cannot fully grasp your table design, the following needs some work, but it might get you an idea:
$qb = $this->createQueryBuilder('s')
            ->select('s, csr, c')
            ->Join('s.classesreference', 'csr')
            ->Join('csr.Class', 'c')
            ->where('c.id = :id')
            ->setParameter('id', $Class->getId())
            ->orderBy('s.Name','ASC')
            ->orderBy('csr.SpellLevel')
            ->getQuery();
$resultArray = $qb->getArrayResult();

$spellLevelArray = array();
foreach($resultArray AS $result) {
    $spellLevel = $result['spelllevel'];
    $spellLevelArray[$spellLevel][] = $result['spell'];
}

As you can see, a foreach is used to iterate over each row (which is one spell) and add the spell to the inner array corresponding to the level. As said, you might need to change some stuff (like the spelllevel and what you store inside the array), but the overall idea should be clear.
Comment: Thanks for this... it is helpful ... is there no way with Doctrine2 to pull something like this out using DQL instead of writing the loop myself?
Comment: Well, the way you could do it with an ORM would be to add a method to your Class object, something like `getSpellsForLevel($level)` and then iterate over all spells and give back the spells for that level. Or you could query the classesreference class for the specific level and class and iterate over those.
Comment: Marked as the answer.  Thanks. I was hoping there would be a DQL statement that could bring the results back in the array format you describe above.  Thanks for the help anyway.


JointJS element containing HTML button onclick show form

Question: I am showing a form on addDetail buttton inside this element. How can I bind my data to this cell and send it to the server using the toJSon() method?
// Create a custom view for that element that displays an HTML div above it.
// -------------------------------------------------------------------------

joint.shapes.html.ElementView = joint.dia.ElementView.extend({

    template: [
        '
',
        '<button class="delete">x</button>',
        '',
        '', '
',
        '<input type="text" name="name"  placeholder="name"/>',
        '<button class="addDetail">+</button>',
        '
'

    ].join(''),

    initialize: function () {
        _.bindAll(this, 'updateBox');
        joint.dia.ElementView.prototype.initialize.apply(this, arguments);

        this.$box = $(_.template(this.template)());
        // Prevent paper from handling pointerdown.
        this.$box.find('input').on('mousedown click', function (evt) {
            evt.stopPropagation();
        });
        // This is an example of reacting on the input change and storing the input data in the cell model.
        this.$box.find('input').on('change', _.bind(function (evt) {
            alert($(evt.target).val());
            this.model.set('input', $(evt.target).val());
        }, this));

        this.$box.find('.delete').on('click', _.bind(this.model.remove, this.model));
        this.$box.find('.addDetail').on('click', _.bind(function (evt) {
             addActionDetail();

        })
        );

        // Update the box position whenever the underlying model changes.
        this.model.on('change', this.updateBox, this);

        // Remove the box when the model gets removed from the graph.
        this.model.on('remove', this.removeBox, this);

        this.updateBox();
    },
    render: function () {
        joint.dia.ElementView.prototype.render.apply(this, arguments);
        this.paper.$el.prepend(this.$box);
        this.updateBox();
        return this;
    },
    updateBox: function () {
        // Set the position and dimension of the box so that it covers the JointJS element.
        var bbox = this.model.getBBox();
        // Example of updating the HTML with a data stored in the cell model.

        this.$box.find('label').text(this.model.get('label'));
        this.$box.find('span').text(this.model.get('select'));
        this.$box.css({
            width: bbox.width,
            height: bbox.height,
            left: bbox.x,
            top: bbox.y,
            transform: 'rotate(' + (this.model.get('angle') || 0) + 'deg)'
        });
    },
    removeBox: function (evt) {
        this.$box.remove();
    }
});

}
Comment: how can i bind or send form data along with graph data
Comment: Inside the .addDetail.on('click', can you not post to the server the cell details which can you can get from  using                _.each(canvasGraph.getCells(), function(cell) {.....             })
Answer: In order to save some data on your element you must follow this steps:

Add some elementData propery to the shape model.
Each time the user click on addDetail inside your element you must have the element id, extract the elementData out of it, and then to render the form (you can achieve this by adding custom event listener to your paper)
When clicking the submit form, add add some custom trigger event.
Listen to that triggered event on your graph and try look for the specific cell by the ModelId and update it.

Here is the basic idea example:
1.your shape model:
joint.shapes.myShapes = joint.shapes.myShapes || {};

joint.shapes.myShapes.Element = joint.shapes.basic.Generic.extend({
    //basically the defaults function doesn't needed, because the set function adds that automatically.
    defaults: _.defaultsDeep({
        elementData: null,
    }, joint.shapes.basic.Generic.prototype.defaults),
    getElementData: function () {
        return this.get("elementData");
    },
    setElementData: function (elementData) {
        this.set("elementData", elementData);
    },
});

2.On your paper init, add your custom event listener function,
notice that you must have the ModelId to be remembered:
paper.on('addDetail:click', function (cell) {
    var elementData = cell.model.getElementData();
    elementData.ModelId = cell.model.id;

    formRender(elementData);
});

3.trigger some custom event on your submit and the object to be updated within the element model:
function formSubmit() {
    graph.trigger('custom:update', newElementData);
}

4.Add some custom event listener to your graph, add call the setElementData by the ModelId:
graph.on('custom:update', function (elementData) {
    var cell = graph.getCell(elementData.ModelId);
    cell.setElementData(elementData);
}, this);

Now you can send it to the server using the toJSon() method.


What makes a piece a fugue?

Question: Can anyone explain what a "fugue" is, in simple words?
After listening several times to Little Fugue in G minor by J. S. Bach, it seems that same "subject" is playing from start after an interval of time with a different instrument. But after listening to Toccata and Fugue in D minor, I am a bit confused and I believe fugue is not as simple as I thought.
So can anyone please explain fugue and explain its presence in these two contexts?
Comment: highly related: https://music.stackexchange.com/questions/25364/what-does-it-mean-to-be-able-to-write-a-fugue?rq=1
Comment: _fugue is not as simple as I thought_ The fugue is by no means simple. In fact, many consider it to be the ultimate challenge for a composer (also for performers). For that reason although it is a very old form, dating back at least to the Baroque period, it remains a popular form for modern composers, for example. [**_Ludus Tonalis-by Paul Hindemith_**](https://en.wikipedia.org/wiki/Ludus_Tonalis) : _...In between, there are twelve three-part fugues separated by eleven interludes, beginning in the tonality of the previous fugue and ending in the tonality of the next fugue_ .
Answer: (Note that Bach's "Toccata and Fugue" is two separate sections; if you're looking for fugal writing in the toccata portion, you'll have some trouble!)
Fugue is a type of polyphonic contrapuntal writing (the noun is "counterpoint," and "polyphonic" means "many voices"). "Counterpoint" basically just means the relationship among written notes; it stems from the Latin punctum contra punctum, or "note against note." (The connection is more obvious in the German Kontrapunkt.)
Fugues begin with an exposition where the subject (and possibly countersubject) are introduced in each voice. Once all voices have entered with the subject, the fugue enters into one or more episodes where they develop thematic material, move through extra keys, and so on.
Types of development include elongating the (counter)subject, shortening it, flipping it upside down, playing it backwards, using only a section of it, playing it in multiple voices at the same time (but slightly staggered), some combination of all of these, etc.
There's a famous statement that "fugue is not a form, it's a process." This is because the possibilities are really limitless in terms of keys visited, types of development employed, etc. Fugues can be remarkably different, which is why it can be so difficult to explain a fugue in one sentence.
Dom's answer here is really terrific and should definitely be consulted.
And, if you're interested, check out what I think is the single most impressive example of fugal writing of all time.
Lastly, two tongue-in-cheek references:

Gould's "So You Want to Write a Fugue"
Owen's "Fuguing by Doing"
Comment: @Stinkfoot I first read it in [Harold Owen's book](https://www.amazon.com/Modal-Tonal-Counterpoint-Josquin-Stravinsky/dp/0028721454), but he doesn't give a source, he just says that it's an oft-repeated phrase.
Comment: There is a piece, Bach, I think, that states a phrase, which is copied in the next bar, with another , then that second phrase goes into the next bar, and so on, like a game of tag. Seem to remember it as an ultimate fugue, but have searched and failed. Help!!
Comment: @Tim Definitely sounds like Bach! Is it maybe the famous [crab canon](https://www.youtube.com/watch?v=xUHQ2ybTejU)?
Comment: Sorry, that's not it. But that's so famous I've not come across it till now! Far too clever! Thanks, though.
Comment: _fugue is not a form, it's a process_ - Excellent! Source?
Answer: Let me try.
The point of a fugue is to gradually explore the hidden contrpauntal potentialities of a short, distinctive melody called "subject" in an artistically compelling way.
So, there are two layers of fugue-writing:

The technical layer: employing skilfully the contrapuntal devices;
The artistic layer: doing so in an considerate, purposeful way in order to achieve a particular artistic effect.

In other words: to succesfully walk your theme through a set of contrapuntal intricacies is not the end but the means; the point is to employ (a considered selection of) the contrapuntal devices to convey a specific artistic idea. The potentialities to be discovered in the subject are not merely of technical, but of artistic nature.
Also, often the composer focuses just on a single aspect of the subject's potentialities. For example, the point of the Fugue no. 1 of the Well Tempered Clavier is clearly to explore the (surprisingly many) possible different harmonizations of the subject - but not as an exercise in combinatorics, but artistically: the point is to use these different harmonizations of the subject as building blocks of a musically coherent whole in which each has its own structural function - and nothing else is allowed to distract from this goal.
The point of the E flat minor fugue, on the other hand, is purely contrapuntal: it is written in strict stillo antico and attempts to employ the widest array of contrapuntal devices such as inversion, augmentation, stretti of various sorts etc. - but all that in such a way as to achieve a seamless and "matter of course" musical texture without the least semblance of forcedness. It almost seems that the point is something like hide-and-seek: the composer does not attempt to expose the subject at each of its statements, but to hide it in the seamless texture in as many disguises as possible. Can you spot all the instances?
And so on: each successful fugue is original and unique, because the heart of the fugue as an art is the exploration of the uniqueness of a musical theme.

What makes a piece a fugue?