autoload psr-4 gets lost during install

Question: this is the composer.json of my bundle (shortened)
{
    "name": "acme/my-bundle",
    "type": "library",
    "version": "0.5.0",
    "autoload": {
        "psr-4": {
            "Acme\\MyBundle\\": ""
        }
    }
}

and in my project:
"require": {
    "acme/my-bundle": "dev-master"
},

then i run composer install resulting in a installed.json like
[
    {
        "name": "acme/my-bundle",
        "version": "dev-master",
        "version_normalized": "9999999-dev",

        "type": "library",
        "installation-source": "source"
        //
        // here must be this:
        // "autoload": {
        //    "psr-4": {
        //        "Acme\\MyBundle\\": ""
        //    }
        // },
        // but these lines are missing!
        //
    }
]

and a autoload-psr4.php:
<?php

// autoload_psr4.php @generated by Composer

$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);

return array(
    /* here must be this:
     * 'Acme\\MyBundle\\' => array($vendorDir . '/acme/my-bundle'),
     * but this line is missing!
     */
);

the autoload is gone, and also other keys like require
what am i missing?
i also tried psr-0, but no success. autoload_namespaces.php is just an empty array.
Comment: If that line is missing, then Composer installs a commit that has these lines missing in your repository. You probably messed up the Composer version detection because you are obviously using Git for version control, but did explicitly specify a version in the composer.json. I don't have a clear picture yet of what else is wrong, but here is my statement: Don't ever specify a version in composer.json when using version control systems where you can actually tag the version. You should probably delete the vendor folder and the composer.lock file and run `composer update` to try fix this.
Comment: @Sven: I completely deleted composer.lock and vendors folder after every attempt. Solution is already found.
Answer: I did not mention, that I wanted to fetch a package from a private repo! This will make the difference!
So I had to re-specify the autoload
"require": {
    "acme/my-bundle": "dev-master"
},
"repositories": [
    {
        "type": "package",
        "package": {
            "version": "dev-master",
            "name": "acme/my-bundle",
            "source": {
                "url": "ssh://email@example.com/acme/my-bundle",
                "type": "git",
                "reference": "test"
            },
            //    THIS IS      |
            //    ADDITIONAL   V
            "autoload": {
                "psr-4": {
                    "Acme\\MyBundle\\": ""
                }
            }
        }
    }
]

see https://stackoverflow.com/a/24193122/816362
Thanks @zacharydanger
Comment: Well, you are probably doing it wrong then. Composer will be able to autodetect the `composer.json` of a project if you specify it as a "vcs" repository: `"type": "vcs", "url":"ssh://email@example.com/acme/my-bundle"`. Then Composer will use the definitions of autoloading of this project. If however you use the package type, you have to specify everything there and maintain it independently from the other library. This is a bad idea for maintenance.

autoload psr-4 gets lost during install


Criação de Array em kotlin : No value passed for parameter array [init]

Question: kotlin array
Converti um código de java para kotlin, porém está com um erro que não consigo resolver

Aqui está o código em java
public class IntroActivity extends AppCompatActivity {

    private ViewPager viewPager;
    private Button btnNext;
    private ImageView[] vectorImage;
    private LinearLayout containerDots;
    private Drawable active;
    private Drawable inactive;
    private SliderFragmentAdapter adapterFragment;
    private int lengthSlide;
    private Button btnSkip;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_intro);
        initViews();
        configSlideAdapter();
        configNextSlideButton();
        configVetorImgSlid();
        configSkipOnboardingButton();
    }

    private void configSkipOnboardingButton() {
        btnSkip.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finishOnboardin();
            }
        });
    }

    private void finishOnboardin() {
        finish();
        Intent intent = new Intent(getApplicationContext(), MapsActivity.class);
        startActivity(intent);
    }

    private void configVetorImgSlid() {
        lengthSlide = adapterFragment.getCount();
        vectorImage = new ImageView[lengthSlide];
        prepareDots();
    }

    private void prepareDots() {
        for (int i = 0; i < lengthSlide; i++) {
            vectorImage[i] = new ImageView(this);
            vectorImage[i].setImageDrawable(inactive);

            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
            layoutParams.setMargins(16, 0, 16, 0);
            containerDots.addView(vectorImage[i], layoutParams);
        }
        vectorImage[0].setImageDrawable(active);
    }

    private void configSlideAdapter() {
        adapterFragment = new SliderFragmentAdapter(getSupportFragmentManager(), 4);
        viewPager.setAdapter(adapterFragment);
        viewPager.addOnPageChangeListener(new OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
            @Override
            public void onPageSelected(int position) {
                for (int i = 0; i < lengthSlide; i++) {
                    vectorImage[i].setImageDrawable(inactive);
                }
                vectorImage[position].setImageDrawable(active);
            }
            @Override
            public void onPageScrollStateChanged(int state) {}
        });
    }

    private void initViews() {
        viewPager = findViewById(R.id.viewPage);
        btnNext = findViewById(R.id.btn_next);
        containerDots = findViewById(R.id.container_dots);
        active = ContextCompat.getDrawable(this, R.drawable.active_dot);
        inactive = ContextCompat.getDrawable(this, R.drawable.inactive_dots);
        btnSkip = findViewById(R.id.btn_skip);
    }
    private void configNextSlideButton() {
        btnNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int currentSlide = viewPager.getCurrentItem();
                viewPager.setCurrentItem(currentSlide + 1);
                if (currentSlide == (lengthSlide - 1)) {
                    finishOnboardin();
                }
            }
        });
    }

}

Código em Kotlin
Convertido fica desta forma
import android.content.Intent
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.appcompat.app.AppCompatActivity
import androidx.viewpager.widget.ViewPager
import androidx.viewpager.widget.ViewPager.OnPageChangeListener
import br.com.brq.brqmotors.onboarding.Adapter.ViewPagerAdapter

class OnboardingActivity : AppCompatActivity() {

    private var viewPager: ViewPager? = null
    private var btnNext: Button? = null
    private var vectorImage: Array<ImageView>? = null
    private var containerDots: LinearLayout? = null
    private var active: Drawable? = null
    private var inactive: Drawable? = null
    private var adapterFragment: ViewPagerAdapter? = null
    private var lengthSlide: Int = 0
    private var btnSkip: Button? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(br.com.brq.brqmotors.R.layout.activity_onboarding)
        initViews()
        configSlideAdapter()
        configNextSlideButton()
        configVetorImgSlid()
        configSkipOnboardingButton()
    }

    private fun configSkipOnboardingButton() {
        btnSkip!!.setOnClickListener { finishOnboarding() }
    }

    private fun finishOnboarding() {
        finish()
        val intent = Intent(applicationContext, javaClass::class.java)
        startActivity(intent)
    }

private fun configVetorImgSlid() {
    lengthSlide = adapterFragment.getCount()
    vectorImage = arrayOfNulls<ImageView>(lengthSlide)
    prepareDots()
}

private fun prepareDots() {
        for (i in 0 until lengthSlide) {
            vectorImage?.set(i, ImageView(this))
            vectorImage!![i].setImageDrawable(inactive)

            val layoutParams = LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
            )
            layoutParams.setMargins(16, 0, 16, 0)
            containerDots!!.addView(vectorImage!![i], layoutParams)
        }
        vectorImage!![0].setImageDrawable(active)
    }

    private fun configSlideAdapter() {
        adapterFragment = ViewPagerAdapter(supportFragmentManager, 4)
        viewPager!!.adapter = adapterFragment
        viewPager!!.addOnPageChangeListener(object : OnPageChangeListener {
            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {
            }

            override fun onPageSelected(position: Int) {
                for (i in 0 until lengthSlide) {
                    vectorImage!![i].setImageDrawable(inactive)
                }
                vectorImage!![position].setImageDrawable(active)
            }

            override fun onPageScrollStateChanged(state: Int) {}
        })
    }

    private fun initViews() {
        viewPager = findViewById(br.com.brq.brqmotors.R.id.viewPagerPrincipal)
        btnNext = findViewById(br.com.brq.brqmotors.R.id.btn_proximo)
        containerDots = findViewById(br.com.brq.brqmotors.R.id.container_pontos)
        btnSkip = findViewById(br.com.brq.brqmotors.R.id.btn_pular)
    }

    private fun configNextSlideButton() {
        btnNext!!.setOnClickListener(View.OnClickListener {
            val currentSlide = viewPager!!.currentItem
            viewPager!!.currentItem = currentSlide + 1
            if (currentSlide == lengthSlide - 1) {
                finishOnboarding()
            }
        })
    }

}

O erro se encontra aqui

 private fun configVetorImgSlid() {
    lengthSlide = adapterFragment.getCount()
    vectorImage = arrayOfNulls<ImageView>(lengthSlide)
    prepareDots()
}

Answer: O trecho está com erro porque vectorImage foi declarado como Array<ImageView>?, que significa que o valor da variável pode ser nulo (por exemplo, pode ter ou não uma array ali) mas o conteúdo da array não pode conter nulo, logo, se uma array estiver na varável, nenhum deles poderá ser nulo e quando você tenta atribuir arrayOfNulls<ImageView>(lengthSlide) a ela, você está passando uma array de tamanho lengthSlide que aceita nulo no conteúdo e está totalmente preenchida com nulo.
Algumas possíveis declarações, não são todas as possibilidades mas já dá uma ideia:
var vectorImage: Array<ImageView>? = null // Pode ser nula mas o conteúdo não. Iniciada nula
var vectorImage: Array<ImageView?>? = null // Pode ser nula e o conteúdo também. Iniciada nula
var vectorImage: Array<ImageView> // Não pode ser nula e nem seu conteúdo. Tem que iniciar no init
var vectorImage: Array<ImageView?> // Não pode ser nula mas seu conteúdo pode. Tem que iniciar no init
var vectorImage = emptyArray<ImageView>() // Não pode ser nula e nem seu conteúdo. Iniciada vazia
var vectorImage = emptyArray<ImageView?>() // Não pode ser nula mas seu conteúdo pode. Iniciada vazia

Você também pode marcar a variável como lateinit para dizer ao kotlin que ela vai iniciar nula mas depois vai receber um valor não-nulo e nunca mais será nula. Se algo tentar acessar ela antes dela ser iniciada, será disparado uma exception (apesar de iniciar nula, ela nunca vai retornar null)
// Não pode ser nula mas seu conteúdo pode. Iniciada quando quiser.
lateinit var vectorImage: Array<ImageView?>


Show that the sum $\sum_{k = 0}^n 2^k \binom{n}{k}$ is equal to $3^n$

Question: How can I show that the sum
$$ \sum_{k = 0}^n 2^k \binom{n}{k}$$
is equal to $3^n$?
Comment: Because it's $(1 + 2)^n$.
Comment: T. Bongers means "binomial theorem".  Maybe Fourier wants a combinatorial interpretation.
Comment: Yea that's what I thought, but how do I get there?
Comment: This is like early calculus, but I've forgotten most of it, so need someone to refresh my memory :l
Answer: For a combinatorial interpretation: suppose you have $n$ distinguishable eggs, and you want to paint some of them red, some of them blue, and leave some of them unpainted. Show that both sides of your desired equation count the number of ways to do this.
Comment: Great thanks! Made me remember that I could just add 1^(n-k), and then get (1+2)^n


SWIG with C++ templates: undefined symbol

Question: C++ Templates and SWIG aren't playing nicely together for me.
When I try to import my module I get the error
ImportError: ./_simple.so: undefined symbol: _Z9double_itIiET_S0_

I am using SWIG 1.3.
Here is a simple example showing the problem:
//file: simple.h
template <typename T>
T double_it (T a);

//file: simple.cc
template <typename T>
T double_it (T a) {
  return (2 * a);
}

//file: simple.i
%module "simple"

%{
  #include "simple.h"
%}

%include "simple.h"

%template(int_double_it) double_it <int>;
%template(float_double_it) double_it <float>;

#file: setup.py
from distutils.core import setup, Extension
simple_module = Extension('_simple',
                          sources=['simple.i', 'simple.cc'],
                          swig_opts=['-c++'],
                          )
setup (name = 'simple',
       ext_modules = [simple_module],
       py_modules = ["simple"],
       )

Then build in with:
python setup.py build

If I include the contents of simple.cc into simple.i and remove the reference to simple.cc from the setup.py then everything works fine, but that isn't really a solution when things get more complex.
Next I'll give a counter example of something that is similar but doesn't use templates and works fine.
//file: simple.h
int double_it (int a);

//file: simple.cc
int double_it (int a) {
  return (2 * a);
}

//file: simple.i
//Same as before but with %template statements removed.
%module "simple"

%{
  #include "simple.h"
%}

%include "simple.h"

#file: setup.py
#Identical to previous example.

Answer: Typically templates are defined in a header file instead of in a cc file. With the setup you have, the compiler cannot find / compile the implementation of the template.
You will need to change the organization of the code so that the template implementation is available:
//file: simple.hh
template <typename T>
T double_it (T a) {
  return (2 * a);
}

//file: simple.i
%module "simple"

%{
  #include "simple.hh"
%}

%include "simple.hh" // include it directly into here

%template(int_double_it) double_it <int>;
%template(float_double_it) double_it <float>;

#file: setup.py
from distutils.core import setup, Extension
simple_module = Extension('_simple',
                          sources=['simple.i', 'simple.hh'],
                          swig_opts=['-c++'],
                         )
setup (name = 'simple',
       ext_modules = [simple_module],
       py_modules = ["simple"],
       )

I appreciate that your example is simplified, but it illustrates the point. You do not have to %include the implementation directly (but you do need to #include it), but you do have to provide some implementation to the SWIG compiler, even if it is a simplified version.
The above should get you going.
Comment: I left the header file out to make things a bit shorter.  Probably I should have left this in to make it look more normal. If you replace the two places where I have "template  T double_it (T a);" with include header statements you'll get something similar to yours. The main difference is that you are now including the implementation of double_it in the interface file so no linking is required.  I can also get it to work if I do that, but I am having trouble if the implementation is in a separate .cc file.
Comment: I added in a header file into my example so it look more normal.
Comment: You really have to put the implementation in the header file for the compiler to be able to find it and generate the version you need. The only alternative is to explicitly instantiate the template in your .cc file to make sure the instantiation you need exists (to make sure the compiler generates the version you need and it is available at link time).

"template class double_it;
template class double_it;" What you are running into is really a general question about C++ and template instantiation and less about SWIG specifically


Functional derivatives of metric tensor

Question: What is wrong in the following?
\begin{equation*}
g_{\mu\nu}(x)g^{\mu\nu}(x)=D \\
\frac{\delta}{\delta g_{\alpha\beta}(x)}D=0 \\
\frac{\delta}{\delta g_{\alpha\beta}(x)}(g_{\mu\nu}g^{\mu\nu})=2g^{\alpha\beta}(x)=0
\end{equation*}
The above equations are clearly inconsistent.
I am just trying to figure out what is the correct way of defining the correct functional derivative of $g_{\mu\nu}g^{\mu\nu}$ with respect to the components of $g$ itself.
Comment: What's your question?
Comment: I am just trying to figure out what is the correct way of defining the correct functional derivative of gμνgμν with respect to the components of g itself.
Answer: Your question is posed rather weirdly...
And I am quite sure you cannot really differentiate it like that. Instead of attempting to calculate a Fréchet-derivative directly in a wrong way, try calculating a Gateux-derivative along an arbitrary curve in the space of possible metrics, eg. take $$ \left.\frac{d}{d\varepsilon}(g_{\mu\nu}(\varepsilon)g^{\mu\nu}(\varepsilon))\right|_{\varepsilon=0}, $$ where $g_{\mu\nu}(0)=g_{\mu\nu}$, with a bit of abuse of notation.
Edit: You seem to be rather confused about functional derivation.
First of all, the map $g_{\mu\nu}\mapsto g_{\mu\nu}g^{\mu\nu}$ is not really a functional in the sense that these type of maps lead into $C^\infty(M)$, not $\mathbb{R}$. However in this case it maps into a constant function, which can be viewed as an element of $\mathbb{R}$, thus it is a functional. It is also obvious that since $g^{\mu\nu}$ is not independent from $g_{\mu\nu}$, such expression for any sort of metric will always result in the same number, thus, the derivative must be zero, since the "functional" is constant.
Secondly, the way you tried to use chain rule here is just wrong, which is why you got nonzero result. In general, you cannot calculate a functional derivative "directly".
Most of the time in physics, these functionals will take the form $$ F[\phi]=\int L(\phi,\partial\phi,...,\partial^k\phi)\ \Omega ,$$ where $\Omega$ is some volume element. In this case, the functional derivative always exists (provided $L$ is a well behaved function), and a directional derivative at $\phi$ in the direction of some arbitrary function $\delta\phi$ (which we usually define as a tangent vector to some curve in the function space, eg. $\delta\phi=d\phi/d\varepsilon$) will always take the form $$ \frac{dF}{d\varepsilon}=\int\frac{\delta F}{\delta\phi}\delta\phi\ \Omega .$$ In this case we call $\delta F/\delta\phi$ the functional derivative of $F$, and obviously the above expression is linear in $\delta\phi$.
If the functional is NOT in this integral form, then we cannot really a define a functional derivative like that, rather, if the functional is differentiable, then there must exist some linear map from the space of functions to the reals, for which the directional derivative in the direction of an arbitrary function always equals the action of that linear map on the function.
Therefore, what you are really interested in is actually the expression $$ \left.\frac{d}{d\varepsilon}(g_{\mu\nu}(\varepsilon)g^{\mu\nu}(\varepsilon))\right|_{\varepsilon=0}, $$ where $g_{\mu\nu}(\varepsilon)$ is a family of metrics indexed by a real parameter in a smooth way, and the metric at the 0 parameter is the metric you want to perturb.
Can you take it from here?
Comment: the problem seems to come from the constraint $g_{\mu\nu}g^{\mu\nu}=D$. As to the weird, these functional derivatives are quite common in theoretical physics. Only, I never thought of this one involving the metric tensor. The case with the electromagnetic tensor is simpler (no constraint).
Comment: No, I mean, you asked the question weirdly. There is no problem, however, since the derivative is identically zero. Also the Einstein-Hilbert action involves functional derivatives involving the metric tensor. The problem comes from the fact that you cannot calculate a functional derivative the way you tried.
Comment: OK, I probably need to think some more on the subject :-)
Comment: I am editing my answer
Comment: Ok, thanks!!! I was giving too much stuff for granted.

Functional derivatives of metric tensor


What does the line on top of variables in deferential equations mean?

Question: For example,
equation
What does the horizontal line on top of f mean?
Comment: It is a *differential* equation. "Deferential" means showing respect, deference
Comment: And A) That is not a differential equation B) $\overline{f}$ has many meanings dependent on context - since the author used $\mathrm{Var}$ it is clearly the case that $\overline{f}$ is the expected value
Comment: Before asking such a question, you can give context, often if you read the context you can find your answer, and for a second remark you can paste pictures directly into the question body. f with the bar often means the conjugate of f, f being a complex function
Answer: In that context, being $g$ a set $g=\{g_1,g_2,...,g_n\},$ it means
$$\overline{g}=\sum_{i=1}^n g_i x_i.$$
It is a weighted expected value, where each element $g_i$ has a weight $x_i$.


cutting bits in C++

Question: Suppose we have a binary file, that contains 32 bit numbers. Each 32bit number represents an instruction. My question: is it possible to cut this bits into chunks of 6+5+5+16 directly. Something like:
typedef struct _instruction
{
    int op_code : 6;
    int reg_dest : 5;
    int reg_s1 : 5;
    int offset : 16;
} INST, *PINST;

int read_32_bits = read_next_instr();

INST i = (INST)read_32_bit; /* this would cut the bits into chunks*/

Comment: Possible, yes. Portable, no! The relationship between bits in a word and bitfields in a structure varies.
Comment: C or C++? Pick one. The code you've written suggests the former, not the latter.
Comment: I prefer C++. But I will settle for either one!
Comment: I gave you an answer that's more portable than the one you selected and won't invoke undefined behavior.
Answer: Why not create a bit structure like you have but then place it inside a union?  I dropped the typedef so it uses C++ style definitions.
struct instruction
{
    int op_code  : 6;
    int reg_dest : 5;
    int reg_s1   : 5;
    int offset   :16;
};

union INST
{
    instruction  a;
    uint32_t     b;
};

You could store/load the 32-bit values using network functions:
INST  i;
i.b = ntohl(value);

And now you can reference the bit fields without typecasting.
if (i.a.op_code == XXX)

Comment: Just make sure the endianness and bit order is correct, depending on the compiler and target CPU.
Comment: Also C++ prohibits writing to one member of a union and then reading from a different member. It invokes undefined behavior. I believe C99 allows it but before that C prohibited it as well.
Comment: @bames53 I'm looking through the C spec (ISO/IEC 9899:TC3) now and I can't find what you are referring to. Footnote 82 on page 73 (126.96.36.199) refers to it as type punning.  This might be a trap representation. So I don't believe it is prohibited otherwise wouldn't the `reinterpret_cast` also be prohibited?
Comment: @bames53: Yes, I believe you are incorrect. In fact, I believe this is one of the very few valid ways of changing the types of certain things **without** invoking UB.
Comment: @JamieRoyer I think there's more to it than that footnote, but I can't find it at the moment. As for reinterpret_cast, the result can't be used for anything except casting back to the original type, except in some specific circumstances. So `int i = 1; float f = *reinterpret_cast(&i);` _is_ UB. My understanding is that to do such conversions legally (with implementation defined behavior) you have to do something like use memcpy. I.e. `int i; float f; memcpy(&i,&f,sizeof(i));`
Comment: @Omnifarious Reading from a non-active member of a union is definitely undefined behavior in C++. It's possible to play some tricks with pointers to union members, but then you'll run into strict aliasing rules.
Comment: @bames53: Well, IMHO, that's a standard bug then. It should be unspecified what values you will get out, but not undefined behavior. There are some low-level things you can only accomplish by doing stuff like that.
Comment: @Omnifarious I can't think of anything that absolutely requires it and for which there's no alternative. Anyway C++ and even C disallow a lot of things that one might do in assembly. There's some good info on the benefits of undefined behavior here: http://blog.llvm.org/2011/05/what-every-c-programmer-should-know.html
Comment: @bames53: I've read that. :-) I think unions are an interested and uncommon case in which it's useful to narrow the scope of undefined behavior in certain ways. A hardware register that has a different structure on read than on write is an example I can think of. Other examples are simply very convenient. Being able to overlay a struct on type of a byte string, for example, as a message decoding technique. Or what this guy wants to do.
Answer: You can just cast your struct as a pointer to the address of your 32-bit data.
INST* i = (INST*)&read_32_bit;

Then you could access your fields, like this:
printf("opcode = %x", i->op_code);

Comment: If portability is important, you just declare multiple versions of your struct with #ifdefs based on platform to select the correct bit ordering
Comment: This is actually the norm in embedded systems. I have seen way worse things than this. +1.
Comment: +1: useful. True, this is theoretically "undefined behavior", and in practice it won't be portable: it will depend on whether integers are 32 bits, whether they're stored as little-endian or big-endian integers, and so on. Nonetheless, it's likely to work, and if it *doesn't*, due to endianness issues, it will show the OP exactly why it's completely impossible on his/her system (due to the bits in the integer not being laid out the same way as the bit-fields).
Comment: @BoPersson, that is a fair point.  If you want to be a purist, don't do this.  But on any particular real platform/compiler there will be a mapping you can use, and it can be pretty practical to do so.
Comment: +1 The guarantees of the standard are just that, guarantees, but just because it isn't guaranteed that every conforming implementation supports something doesn't mean that it isn't supported in practice, or that it isn't supported on the target platform. The OP should be aware of the limitations, but the information should not be denigrated with absurd and uninformative nonsense about "naive myths and lies".
Comment: as Jerry mentioned, the struct order can be platform dependent
Comment: @TomalakGeret'kal, what is your problem?  It is tagged with C, this code is correct unless you care to point out a problem
Comment: I can't see a problem with this either - portability is important, but we are assuming, we don't know the OP's predicament. It may be fine in his scenario to use bit fields, and in the past I've found this approach to be more efficient than a bunch of shifts...
Comment: @TJD - The standard only guarantees that the bitfields get the number of bits indicated. It doesn't say anything about how they are stored inside the struct, like their order or padding.
Comment: TJD you cannot use ifdef for platforms of different endianness, as those bit-fields are crossing byte boundaries, and in diiferent endiannes parts of bit-fields will be misaligned.
Comment: Thanks moderators for deleting the very valid reason that I downvoted this answer. @TJD: Jerry explains the problem; did you not see it?
Answer: Here is an answer that will work, be portable, not invoke undefined behavior on any compiler, and be optimized fairly effectively:
struct instruction {
   typedef unsigned int uint_t;

   explicit instruction(uint_t val) : val_(val) {}
   instruction(uint_t op_code, uint_t reg_dest, uint_t reg_s1, uint_t offset)
     : val_((op_code & 0x3fu << 26) | (reg_dest & 0x1fu << 21) |
            (reg_s1 & 0x1fu << 16) | (offset & 0xffffu))
   {
   }

   uint_t op_code() const { return (val_ >> 26) & 0x3fu; }
   void op_code(uint_t newval) { val_ = (newval & 0x3fu << 26) | (val_ & 0x3ffffffu); }

   uint_t reg_dest() const { return (val_ >> 21) & 0x1fu; }
   void reg_dest(uint_t newval) { val_ = (newval & 0x1fu << 21) | (val_ & 0xfc1fffffu); }

   uint_t reg_s1() const { return (val_ >> 16) & 0x1fu; }
   void reg_s1(uint_t newval) { val_ = (newval & 0x1fu) << 16) | (val_ & 0xffe0ffffu); }

   uint_t offset() const { return (val_ >> 16) & 0xffffu; }
   void offset(uint_t newval) const { val_ = (newval & 0xffffu) | (val & 0xffff0000u); }

   uint_t &int_ref() { return val_; }
   uint_t int_ref() const { return val_; }

 private:
   uint_t val_;
};

This lets you access all of the bitfields with a very convenient notation. I think it's also a POD, which lets you use it in a few interesting ways. And a good compiler will do a fairly decent job of optimizing the bit munging operations, especially if you have several calls to the convenience functions in a row.
It's almost as nice as having an overlay bit field. It's just a bit more work to define in the first place.
Also, I changed the type to unsigned int because if you're fiddling around with the bits, you really want a simply represented number without a sign bit or anything funky like that. Ideally you'd be including the <cstdint> header and using ::std::uint32_t or something in the typedef at the top.

cutting bits in C++


How to transcribe a score without a rigid tempo?

Question: How do you notate a score that doesn't have a continuous tempo, but ebbs and flows? How can you communicate the rhythmic intentions of the composer to future players? What I was lectured that you need to feel the beat. I feel that there's a change in the beat structure mathematically it's still stays on the tempo but the feeling is different.
Comment: Tempo fluctuation has nothing whatsoever to do with being "a capella". That simply means "without accompaniment".
Comment: How do you know it "ebbs and flows"?
Comment: I have the recording. But if I write the music and somebody else picks it up how would he know to play as intended?
Comment: Hmmm... I guess you don't. Perhaps clever use of fermatas? On the other hand, how do you know the recording is the "correct" interpretation of the piece? Your question is kind of unclear.
Comment: The recording is a demo from the composer. I'm asking it now in general since I transcribed the piece, how would someone else know how to play it exactly as the composer intended?
Comment: @Kilian Foth your right. The question is in general, music that doesn't have a constant tempo. I wrote the question because this is what I was busy with.
Comment: @Nachmen - I took a crack at editing your question to make it more clear. It's still too broad IMO; if you give a specific example (something like "It seems to slow down at the end of each phrase", or an example of what you've notated) it will make it easier to narrow down the possibilities. Feel free to roll back the edit if I didn't catch what you were going for.
Comment: Are you sure you aren't talking about syncopation? Especially in pop and rock, syncopated singing lines, when written out, can look very complicated for a beginner. It would be an interesting question to know how to transcribe such a heavily syncopated singing line.
Comment: To be clear: The question as it stands now isn't clear enough. But if you would include syncopation in the question I would vote to reopen.
Comment: Provide the recording for reference.  Even when notation can be relatively unambiguous, don't be afraid to do this.  We have the facility, use it!
Comment: If I could just send you that audio. Maybe I cant express myself with the right words.
Comment: I made a youtube account. I'm trying now to convert the mp3 to a codex that runs on youtube it's for me something  new. It will take some time untill I get everything straight and in place.
Answer: Without more information, I would guess that at least four things could be going on:

Rubato: An intentional fluctuation of tempo, with an expressive goal, used in music since Romanticism. This would feel most as 'ebbs and flows' to me. Because rubato is supposed to be only a temporary deviation of the original tempo.
Changing meter: The number of beats in a measure can temporarily change. For example, a piece or a song can go from a 3/4 meter to a 2/4 meter for just one measure and then return to 3/4. It can also be more structural: every 4/4 measure is followed by a 3/4 measure, for example.
Syncopation: There are many kinds of syncopation, see the Wikipedia article for that, but often it feels like a missed beat or a note that is suspended over the bar line. Most popular, jazz and rock music is syncopated which can make it difficult to transcribe rhytmically for an untrained ear, especially if there isn't a clear beat played underneath it.
Triplets or tuplets: three or more notes are played or sung in the space of one beat. Sometimes this can give a feeling of a temporary temposwitch.

It's difficult to know what you are dealing with but I would read up on those three and see if one of them qualifies.
Comment: Possible cause #5: ritardando/tempo primo or accelerando/tempo primo.
Comment: With luck I got it right the youtube link is https://youtu.be/rkkouhdO1a8
Comment: The audio clip is a new production with accompaniment, it's  also much clearer then the audio I had from 1948. It is around measures 15 that were my question was.
Comment: @guido This how I wrote it down. I have also by measure 24 the six eights that  repeat four times in the next part. between the beats the sentence with the six eights, the feel changes I left it in 3/4 because mathematically it fits. Put in a rubato sign then piú mosso, then back rubato and back piú mosso. For me it could be 6/8 only for a measure than back this the hard part for me.


Android, pegar id de um item de uma listView através do clique longo

Question: alguém sabe como faço para puxar um ID de um item da ListView através do SetOnItemLongClickListener e poderiam me dizer se esse método funcionaria com um item que esta sendo exibido do banco de dados??
O código do Adapter:
public class ObjetoAdapter extends BaseAdapter {

private List<Objeto> objeto;

private Context context;

public ObjetoAdapter(Context context, List<Objeto> objeto) {
    this.objeto = objeto;
    this.context = context;
}

@Override
public int getCount() {
    return objeto.size();
}

@Override
public Object getItem(int arg0) {
    return objeto.get(arg0);
}

@Override
public long getItemId(int position) {
    return objeto.get(position).getId();
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    View rootView = LayoutInflater.from(context).inflate(R.layout.lista_objetos, parent, false);

    TextView tvID = (TextView) rootView.findViewById(R.id.tvID);
    TextView tvNome = (TextView) rootView.findViewById(R.id.tvLvNome);
    TextView tvValor = (TextView) rootView.findViewById(R.id.tvLvValor);

    Objeto objetoDaVez = objeto.get(position);

    tvID.setText("ID: " + getItemId(position));
    tvNome.setText(" Nome" + objetoDaVez.getNome());
    tvValor.setText(" Valor: R$" + objetoDaVez.getValor());

    return rootView;
}

Answer: Ficou um pouco difícil de entender, mas se entendi bem, você quer pegar o id do seu objeto e não simplesmente a posição dele na listview, como é recebido no parâmetro do Listener. Então, vamos lá...
Na interface OnItemLongClickListener temos o método onItemLongClick que recebe como parâmetro uma instância de AdapterView. Através dessa instância podemos capturar do adapter usado na listview através do comando adapterView.getAdapter(). Tendo o adapter em mãos podemos invocar o método adapter.getItemId(int posicao), que geralmente sobrescrevemos quando o adapter é customizado. Se você sobrescrever esse método no seu adapter, poderá ter o id, seja ele qual for, do seu objeto referenciado pelo item da listview que foi clicado e não necessariamente a posição do item na lista.
listView.setOnItemLongClickListener(new OnItemLongClickListener() {

    @Override
    public boolean onItemLongClick(AdapterView<?> adapterView, View v, int pos, long id) {
        long codigoDoObjeto = adapterView.getAdapter().getItemId(pos);
        return true;
    }
});

Vou colocar aqui um exemplo do adapter customizado:
public class MeuObjetoListListViewAdapter extends BaseAdapter {

private Context context;
private List<MeuObjeto> meuObjetoList;

public SistemaListViewAdapter(Context context, List<MeuObjeto> meuObjetoList) {
    this.context = context;
    this.meuObjetoList= meuObjetoList;
}

@Override
public long getItemId(int position) {
    return meuObjetoList.get(position).getCodigoIdOuPKQualquer();
}

//Demais métodos ...

}

Se não for isso, peço desculpas, mas foi o que entendi =)
Comment: Talvez seja isso (Não posso testar no momento), pra ficar claro, o que quero, eu desejo pegar pegar o ID do objeto da LV no banco (através do clique longo), para poder, por exemplo, usar esse ID e exibir o nome e valor do objeto (que consta no banco) referente ao ID numa outra Activity em duas TextView, deu pra entender ou continua confuso??
Comment: Acredito então que o que citei seja o caminho certo.  Você quer pegar o id do objeto, que é a primary key no banco de dados, e não a posição dele na ListView. Qual adapter você está usando em sua ListView?
Comment: Depois de o método `getItemId` ter sido implementado passa a ser possível pegar directamente o valor do `id` através do parâmetro passado ao método `onItemLongClick`.
Comment: certo, Tássio, dei uma fuçada aqui no código e meu código está aparentemente identico ao seu, estou utilizando o BaseAdapter. Me parece que esse é o caminho mesmo, então nesse caso, como eu poderia fazer para que ao clique  longo, ele armazene o id em uma variável para que em uma outra Activity, ele possa ser passado como parametro para o meu método `buscarObjetoPorID(variavel)`?
Comment: Para ressaltar, fiz do jeito que você fez e ai no método setei o `Objeto.getId()` e ele me retornou o primeiro item independente de qual eu clique.
Comment: Sim, por esse caminho você pode pegar o id (primary key da tabela) do seu objeto. Sobre seu novo problema, precisaria ver parte do seu código do adapter para entender o que está acontecendo. Teria como mostrar?
Comment: Claro, após sua demonstração e o comentário do Ramaral, mudei o trecho do código do ID e coloquei aquele `getItemId(position)` pra ver se funcionava e na ListView, abaixo de cada objeto, aparece o ID referente, mas ainda não sei como pegar o ID, uma vez que tentei instanciar esse adapte e não deu certo.
Answer: Se o adaptar associado à sua ListView for um CursorAdaptar o parâmetro id passado ao método onItemLongClick(), da interface OnItemLongClickListener, representa o valor do campo _id do registo associado à linha clicada.
private long listItemPressedId;
minhaList.setOnItemLongClickListener(new OnItemLongClickListener() {

    @Override
    public boolean onItemLongClick(AdapterView<?> adapter, View v,
            int pos, long id) {
        listItemPressedId = id; //id do registo associado à linha clicada
        return false;
    }
});

Comment: Fala, Ramaral, agradeço a tentativa, mas não deu certo (A única opção que apareceu foi `ListItem` e nem assim deu certo), vamos ver se explicando você consegue ajudar. Cada linha da LV exibe dados de um banco de dados, aí queria que ao clicasse no item(certo dado), ele pegasse o ID do item, verificasse no banco de quem era esse ID e fosse para uma outra tela exibir apenas esse item. Nesse método de exibir na outra tela usei um ID já existente e funcionou, porém quero que ao longo clique, ele pegue o ID do selecionado, deu pra entender??
Comment: O que quer dizer com *"A única opção que apareceu foi ListItem..."*?
Comment: Quando fui fazer a sintaxe que você recomendou (com `ListItemPressedId`), o mais perto que apareceu foi `ListItem` e nada mais do gênero, compreendeu??
Comment: `listItemPressedId` é a variável que vai guardar o `id` do item da lista clicado. Você deve declará-la primeiro como `private long listItemPressedId`
Comment: Ah sim, entendi, mas no caso, essa variável do tipo long seria usada em um método que precisaria de um int (o ID do banco), teria de fazer uma conversão de long para int normalmente ou com long é diferente (Não conheço muito esse tipo)?
Comment: Não é preciso fazer conversão, o tipo `long` é um `int` com uma maior amplitude de valores(guarda números maiores). Tenha em atenção que o código postado parte do princípio que o seu *adapter* herda de *CursorAdpater* (ou *SimpleCursorAdapter*) o que é o aconselhado quando se trabalha com dados vindos do SQLite.
Comment: Ah sim, mas meu banco não é o SQlite e sim o MySql (Ele roda a partir da internet), tem algum problema ou funcionaria da mesma maneira?
Comment: Como é que você acede ao banco?
Comment: Utilizo uma WebService, o `strictmode.threadpolicy` para o app puxar remotamente os dados, um método para buscar todos os objetos de uma tabela do banco e adapto o ListView para cada linha aparecer um objeto e esse método que desejo executar seria um `SELECT nome, valor WHERE ID = X` (Se foi isso mesmo o que perguntou).
Comment: Como o seu *adapter* não é um *CursorAdapter* terá de implementar o método `getItemId()` no seu *adapter*. veja a resposta do Tássio Auad.


Ergodic: Show another implication

Question:

Let $(\Omega,\mathfrak{A},\mu,T)$ be a dynamic system in measure theory and $p\geq 1$. Show that the following statements are equivalent:
    $$
(1)~~~~~(\Omega,\mathfrak{A},\mu,T)\text{ is ergodic}\\(2)~~~~~\text{For any measurable function }f\colon\Omega\to\mathbb{R}\text{ it is: }f=f\circ T\text{ a.s }\implies f=\text{const. a.s.}\\(3)~~~~~\forall f\in L_{\mu}^p: f=f\circ T\implies f=\text{const.}
$$

Here Ergodic system, show an implication I have shown $(3)\implies (1)$.
Here Show: Ergodic implies $f=\text{const a.s.}$ I tried $(1)\implies (2)$ and $(2)\implies (1)$.
Now what remains is to show that $(1)\implies (3)$. And I have some problems to do so.
Consider a function $f\in L_{\mu}^p$ with $f=f\circ T$.
Now I have to show, that $f=\text{const}$:
How can I do that (using (1))?
I only can show that $f$ is constant almost surely: because $f$ is measurable and therefore from (1) it follows by (2) and the fact that $f=f\circ T$ even surely (i.e. especially almost surely) that $f$ is constant a.s.
But I do not manage it to show that $f$ is constant surely...
Can you please help me?
Comment: But I did not find it and maybe you can give me a hint?
Answer: In general, we may not have $f=f\circ T$ almost everywhere. Take indeed $N$ a non-empty invariant set of zero measure and replace $f$ by $g:=f\chi_N$, which satisfies $g=g\circ T$. Then when $f=c$ a.e. with $c\neq 0$, the function $g$ is not constant.

Ergodic: Show another implication


Inverse SNR: find the first point with a specified SNR ratio where noise and signal are simple normal distributions

Question: I have a pair of 2 simple normal distributions for noise and signal , specified by $\mu1,\sigma1$ and $\mu2,\sigma2$, so I know how to calculate CDF1, CDF2 for every point.
I would like to find $x$ = the leftmost point where $\frac{CDF1(x)}{CDF2(x)}=P$ where P is a constant desired SNR ratio, say P=3.
I have a file with some several thousands of such normal distribution pairs, so best would be if there could be some Excel formula I could use for each such pair, getting its relevant $x$.
Is there an anlytical solution I'm missing? If there's none, can you point me to some nice way to do it with R/python without resulting to some monstrous "goal seek" Excel simulation?
Thanks! (Math and signal processing novice, be patient)
Answer: Consider $$\frac{CDF_1(x)}{CDF_2(x)} = P.$$
We have $$CDF(x) = \frac{1}{2} \left[1 + erf\left(\frac{x-\mu}{\sigma\sqrt{2}}\right)\right]$$
and
$$\frac{d}{dx}CDF(x) = \frac{1}{\sigma 2\sqrt{2}} e^{\frac{-(x-\mu)^2}{2\sigma^2}}.$$
Using the above two equations, write
$$CDF_1(x) = P \times CDF_2(x)$$.
Differentiate on both sides with respect to $x$ and solve the ratio of exponentials using the log function. You should be getting a closed form expression for $x$.
Comment: cool! so what you're saying is that the derivative is the normal density function. So what I'm looking for is simply the point where the ratio between the 2 normal densities is P?
Comment: Precisely. And that is a linear function of $x$.
Comment: I'm sorry - I must be missing something because I checked it up on Excel and it is not true that in each point X the ratio between the CDFs is the same as the ratio between the densities... did I mess up with the derivation?
Comment: I have made a mistake in this answer. I am looking for where I have gone wrong. Sorry to have wasted your time.


How to customize drupal node using 'PANELS'

Question: I am trying to implement the "PANELS" module in drupal 7.31 to customize a page display.
Panels Module : 7.x-3.4
Drupal version : 7.31
I have created courses(as a product) using "COMMERCE" module. I am able to display the LIST Courses
using Panels. But I am also want to customize the course detail page(User click on course and then redirect to detail page).
You can see list of courses using Panels on here:

Now I want to customize the detail page where all details show from Database using Panels.
You can also see Course Detail page here:
Comment: Sorry, I don't know what you are asking. I tend to use View modes to customize content output, and then have Panels display that output. Does that help?
Answer: You can't customize the node detail page with panels. You will have to use display suite. DS allows you to do a lot of things, and one of them is "Display Suite allows you to take full control over how your content is displayed using a drag and drop interface."
Hope this helps


PayPal CreateRecurringPaymentProfile Error 11502 - Invalid Token

Question: I am setting up a Recurring Payment with PayPal's API.  First I send the following parameters to SetExpressCheckout:
Array
(
    [METHOD] => SetExpressCheckout
    [USER] => XXX
    [PWD] => XXX
    [SIGNATURE] => XXX
    [VERSION] => 98.0
    [AMT] => 0
    [MAXAMT] => 99.00
    [RETURNURL] => http://google.com
    [CANCELURL] => http://google.com
    [L_BILLINGTYPE0] => RecurringPayments
    [L_BILLINGAGREEMENTDESCRIPTION0] => 99.00 per month till stopped
)

This generates a response like the following:
Array
(
    [TOKEN] => EC-90P39652RF345525U
    [TIMESTAMP] => 2013-02-08T17:09:24Z
    [ACK] => Success
    [VERSION] => 98.0
)

Using the description and token from the created billing agreement, I send the following parameters to CreateRecurringPaymentsProfile:
Array
    (
    [METHOD] => CreateRecurringPaymentsProfile
    [USER] => XXX
    [PWD] => XXX
    [SIGNATURE] => XXX
    [TOKEN] => EC-90P39652RF345525U
    [PROFILESTARTDATE] => Feb 22 2013 17:09:24
    [DESC] => 99.00 per month till stopped
    [BILLINGPERIOD] => Month
    [BILLINGFREQUENCY] => 12
    [AMT] => 99.00
    [CURRENTCYCODE] => USD
    [CREDITCARDTYPE] => VISA
    [ACCT] => 1234123412341234
    [EXPDATE] => 012014
    [CVV2] => 123
    [EMAIL] => email@example.com
    [STREET] => 123 Main St
    [CITY] => New York City
    [STATE] => NY
    [COUNTRYCODE] => US
    [ZIP] => 12345
)

All looks well to me, but it fails:
Array
(
    [TIMESTAMP] => 2013-02-08T17:09:24Z
    [ACK] => Failure
    [VERSION] => 98.0
    [L_ERRORCODE0] => 11502
    [L_SHORTMESSAGE0] => Invalid Token
    [L_LONGMESSAGE0] => The token is invalid
    [L_SEVERITYCODE0] => Error
)

Any help is greatly appreciated!
Comment: Tried updating the `PROFILESTARTDATE` to `'2013-02-22T17:27:03'` (with the T found in PayPal examples).  No luck, not surprisingly.
Answer: You need to redirect the buyer to PayPal to approve the recurring payment before you call CreateRecurringPaymentsProfile.  The timestamps on both of your API responses are the same, which tells me that you called CreateRecurringPaymentsProfile as soon as you got your response from SetExpressCheckout.  You need to redirect the buyer to PayPal after you get your response back from SetExpressCheckout.
Comment: I literally just found this, not sure why it wasn't in the documentation.  A quick question..is there any way to initiate a recurring payment without having users go to PayPal and using their account? +1 for looking closely at the timestamps.
Comment: There's a couple of options.  1) PayPal Payments Pro with Recurring Billing.  This will only work for buyers using a credit card -- buyers using their PP account would still have to approve the recurring payment on the PP website.  It'll also run you about $60 a month.  2) Billing agreements (BAs).  With BAs, the buyer has to go to PP the first time to approve the BA, but they don't have to go back to the PayPal website after that -- you can just charge against the BA as needed.  Not automatic though -- you'd have to run an API call to process each charge.
Comment: Thank you very much.  Can you link me to any documentation/resources for PayPal Payments Pro w/Recurring Billing?  This is what I originally thought you could do with recurring payments, but it currently is forcing me to go through the PayPal BA.
Comment: I figured it out. You just have to go through CreateRecurringPaymentsProfile and don't use a token.  Wish the documentation was better so I didn't have to waste my time with that all.
Comment: For anyone looking, here is a link to the related classic api (not the new rest api) doc https://developer.paypal.com/webapps/developer/docs/classic/express-checkout/ht_ec-recurringPaymentProfile-curl-etc/ This explains that you must redirect the user to paypal before creating the recurring payments profile. I didn't realise this either, but it's quite clear when I didn't just skim read. If you're using PHP, download (composer) the SDK and try the examples. Worked for me.


What happens when a baseball player is "DFA'ed" and then signs with another team?

Question: I'm asking specifically about Pablo Sandoval, who signed a five year contract with Boston Red Sox, and is now owed $18 million each for 2018 and 2019, plus the balance of his 2017 salary. He was designated for assignment because 1) he had become a "replacement" player, and 2) he was being paid way too much for a level of performance that a "minimum wage" player called up from the minors could match or exceed.
The San Francisco Giants may now want Sandoval back, perhaps on a "trial" basis. Will they have to pick up his expensive contract to rehire him? Can they pay him what they think he's worth and have Boston pick up the difference? Or can they pick up the full contract and dump it back on Boston if they DFA Sandoval themselves?
Have others in the past elected to play again when (in Sandoval's case) they could collect over $40 million (or some lower amount) over several years while not playing?
What has happened in these types of situations?
Answer: A team that wants to hire a DFA'd player has to offer him at least the "minimum wage" for major league baseball (now a bit over $500,000). The team that originally DFA'd him will receive salary relief to the extent picked up by the new team (they owe the original contract amount minus his current salary.


Spring boot with i18n (internationalization) and thymeleaf

Question: I am trying to get i18n to work with my spring boot application, which uses thymeleaf as template engine.
I followed some tutorials, which showed me how to define message source and locale resolver, so I made this configuration class:
@Configuration
@EnableWebMvc
public class AppConfig extends WebMvcConfigurerAdapter {

    @Bean
    public MessageSource messageSource() {
        ReloadableResourceBundleMessageSource msgSrc = new ReloadableResourceBundleMessageSource();
        msgSrc.setBasename("i18n/messages");
        msgSrc.setDefaultEncoding("UTF-8");
        return msgSrc;
    }

    @Bean
    public LocaleResolver localeResolver() {
        CookieLocaleResolver resolver = new CookieLocaleResolver();
        resolver.setDefaultLocale(new Locale("en"));
        resolver.setCookieName("myI18N_cookie");
        return resolver;
    }

    @Override
    public void addInterceptors(InterceptorRegistry reg) {
        LocaleChangeInterceptor interceptor = new LocaleChangeInterceptor();
        interceptor.setParamName("locale");
        reg.addInterceptor(interceptor);
    }

}

Then, in my resource folder (src/main/resources) i made folder i18n and inside i put messages.properties and messages_sl.properties
inside there is defined first.greeting = Hello World!
And this is my thymeleaf template:
<!DOCTYPE html>

        <meta charset="UTF-8"/>

        English | Slovenian

My Controller is nothing special, it just forwards this view when I access it and in my properties file i have defined:
spring.thymeleaf.mode=LEGACYHTML5
spring.thymeleaf.cache=false

However, when I load page, instead of Hello World! I get ??first.greeting_en?? or ??first.greeting_sl??, depending on set locale.
Everywhere I looked I saw same configuration, so I am really lost as what am I missing.
And here is my project structure:
 src
   └───  main
       ├───  java
       │   └───  com
       │       └───  mjamsek
       │           └───  Simple_i18n
       │               ├───  conf
       │               └───  controller
       └───  resources
           ├───  i18n
           │   ├─── messages.properties
           │   └─── messages_sl.properties
           ├───  static
           └───  templates

Answer: Add the classpath: prefix to MessageSource's basename
msgSrc.setBasename("classpath:i18n/messages");


At what point in history did the relationship between pitch and frequency become well-known among musicians?

Question: I think I've read that even very ancient cultures were able to discern that an octave difference corresponded to a pipe of twice the length, and so on. But at what point were musicians and composers able to understand that each note in a scale of fixed notes represents a certain number of Hz?
(I'm interested in facts relating to various areas - if it was known earlier in Vanuatu than in Vienna, I'm interested in that level of detail!)
Comment: Just an insight: in a vibrating string, it's easier to see that higher pitches correspond to faster vibration
Comment: This is probably a book-length topic.  But I'm willing to bet there's not much information available.
Answer: If you have access to a good academic library, then the following article appears to be on point regarding the Western tradition:

S. Dostrovsky, Early Vibration Theory:  Physics and Music in the Seventeenth Century.  Archive for History of Exact Sciences, Vol. 14, No. 3 (5.XII.1975), pp. 169–218.

Here are a few pertinent pasages;  I have bolded the TL;DR quote:

That pitch can be identified with frequency was a major discovery of the seventeenth century, and this identification made possible very precise measurements of relative frequencies. ...
Following his father Vincenzo, Galileo was critical of the traditional use of the ratios based on string lengths to describe musical intervals.  He went on to connect pitch with frequency and to explain clearly that frequency ratios correspond to intervals.

After the above quote, Dostrovsky quotes extensively from Galileo's Discourse on Two New Sciences (1638).  In particular, Galileo describes scraping a sharp metal stylus across a metal plate so that it squeaks, and examining the spacing of the scratches left behind on the plate.  He found that higher-pitched squeaks corresponded to scratches that were closer together (and thus a higher frequency of scratches.)
Finally, other folks were thinking the same way around the same time:

A number of Galileo's contemporaries recognized the central importance of frequency even though they did not discuss it as clearly and as explicitly as he did.  Isaac Beeckman had associated pitch with frequency already by 1615, when he had tried to derive the inverse proportionality between frequency and length of a vibrating string.  Although Descartes had not emphasized frequency in his early Compendium Musicae, in L'Homme, written in 1632, he referred to it as the source of pitch:  "les petites secousses composeront un son que l'âme jugera... plus aigu ou plus grave, selon qu'elles seront plus promptes à s'entresuivre, ou plus tardives."  ...  Mersenne often dwelt on reasons for the musical ratios.  In Harmonie Universelle he gave a variety of possible ratios for the octave and a variety of reasons for the particular ratio 2:1.  Finally he wrote that it is "entirely necessary" to use this ratio: "sound being nothing other than the movement of the air, and this movement finding itself always double in the octave, and never quadruple or octuple, it follows that the two sounds of the octave are in the same ratio as these movements." ...
To summarize:  according to the picture that was around by the end of the first third of the seventeenth century, sound consisted of a succession of pulses (percosse for Galileo, secousses for Descartes, battemens for Mersenne and, later, Huygens.)  ...  The identification of pitch with frequency became categorically accepted, in spite of the fact that it was only possible to measure relative frequencies and these only by using the identification itself.  The problem of determining frequency absolutely was to challenge natural philosophers throughout the seventeenth century.

(Translation of the Descartes quote:  "The small jolts compose a sound that the soul will judge... higher or lower, according to whether they are quicker or slower to follow each other.")
Comment: (I'm not 100% happy with "jolt" as the translation for "secousse" in the quote above, BTW;  if anyone has a better translation I'm open to suggestions.)
Comment: This is fascinating, but of course it still doesn't really show (what would?) how widespread the knowledge of the math behind music was amongst musicians.  Remember what Leibniz said:  _Musica est exercitium arithmeticae occultum nescientis se numerare animi._  That is: Music is a hidden arithmetical exercise; the soul does not know it is counting.
Comment: @ScottWallace:  it did occur to me that this didn't really answer the question as asked;  it's just a necessary condition.  It'd be interesting to know how widespread the knowledge is *today* — if you asked 100 musicians what a sound actually is, how it travels, or what makes a higher pitch different from a lower pitch, how many of them would be able to answer correctly?  (Particularly those musicians without formal musical schooling.)
Comment: @MichaelSeifert - the story of the hammers and anvils, in addition to not being true physically, is apparently a medieval addition to Pythagoras.
Comment: I wonder that too.  I doubt that it's been formally studied, but who knows?
Comment: @ScottWallace and Michael Seifert: is there really no evidence that people understood that reducing the length of a string caused it to vibrate proportionally faster?  If that _was_ understood, then the knowledge of the relationship between frequency and pitch goes back at least to Pythagoras.
Comment: @phoog:  in the linked article, Dostrovsky discusses the ancients' writings on the relationships between physical characteristics of objects and the pitches they produce.  His general conclusion is that it's pretty muddled.  They said that halving the length of a taut string would raise its tone by an octave (which is true), but they also said that doubling its tension would raise its tone by an octave (which is false), and that hitting an anvil with a hammer of twice the weight would also raise its tone by an octave (which is also false).  ...
Comment: ... Dostrovsky also notes that later scientists who did understand how vibrations were related to sound were "horrified at the casual misrepresentation of the basic facts of vibration in the accounts of Pythagoras' discovery."  All in all, his conclusion is that the Pythagoreans were much more interested in the numerological relationships between varying pitches rather than the physical differences between the vibrations that produced them (such as the number of cycles per second in the vibration.)
Comment: (That said, it's entirely possible that there's other evidence out there that Dostrovsky didn't include!)


Prove $ \operatorname{erfi}(x) \in O(e^{x^2})$

Question: How can we prove:
$$
\operatorname{erfi}(x) \in O (e^{x^2})
$$
Samely we can prove:
$$
\lim_{ x \rightarrow \infty  } \frac {\int_0^x e^{t^2} \, dt} {e^{x^2}} = 0
$$
Also it is so awkward. The integral of a function should be greater than or equal to that function in growth rate but here it seems like it is the opposite.
By the answer here, we can observe this, but it's still vague that how that answer is achieved.
It's important to mention that the relations mentioned are all achieved via WolframAlpha.
Comment: "The integral of a function should be greater than or equal to that function but here it seems like it is the opposite" — I can see where intuition would lead you to this, but the point here is that $e^{x^2}$ grows _so_ quickly that it outpaces its accumulated integral 'up to' that point. The exponential function is (sometimes derfinitionally!) the balancing point there, in that its growth is exactly fast enough to keep up with its integral (up to the requisite constant); anything that grows faster than that will outgrow its integral.
Comment: Converted my comment into an answer!
Comment: @SassatelliGiulio It's easy to prove it that way.
Comment: @StevenStadnicki Great that's the intuition I needed.
An answer that sums up these to comment would be nice so I can select it as the solution.
Comment: @StevenStadnicki Don't you mind demonstrate it mathematically via Hopital as the first comment say? So it can be complete enough to be the solution.
Comment: Ahhh! Yes, point. I'll try and add that shortly.
Answer: You say that 'the integral of a function should be greater than or equal to that function but here it seems like it is the opposite'; the idea that an integral is bigger than the function itself is intuitive, but $e^{x^2}$ grows so quickly that it outpaces its accumulated integral up to whatever point of evaluation. The exponential function is (sometimes definitionally!) the balancing point with respect to rate of growth; it grows exactly fast enough to keep up with its integral, up to the requisite constant. Anything that grows faster than $e^x$ will outgrow its integral in the same way that $e^{x^2}$ does.


How to Sinon spy a Vue component method triggered by a Vue event?

Question: The basic setup that I've done in order to describe my problem:
Using vue-cli 2.8.2, I generated a new project based on webpack template (vue init webpack vue-test-sinon-spy) keeping all the defaults of vue-cli (with the irrelevant exception of disabling eslint).
Changes done in this vue-cli generated project:

I attached an event on h2 tag from Hello.vue:

Essential Links

I added a method in Hello component

I added a new test in Hello.spec.js

describe('Hello.vue', () => {
  // ...

  it('should handle click on h2 tag', () => {
    const Constructor = Vue.extend(Hello)
    const vm = new Constructor().$mount()
    sinon.spy(vm, 'sayHello')

    // [A] if I run the line below, vm.sayHello.callCount will be 0 - not as expected
    vm.$el.querySelector('h2').click()

    // [B] if I run the line below, vm.sayHello.callCount will be 1 - as expected
    // vm.sayHello()

    // vm.sayHello.callCount will be 0 or 1, depending on
    //    what line I execute ([A] or [B]),
    //    even if in both cases sayHello method is really executed
    console.log('###', vm.sayHello.callCount)
  })
})

When I programmatically click the html tag (using vm.$el.querySelector('h2').click()), spy won't capture the execution of the method sayHello, thus vm.sayHello.callCount will be 0. Not what I like.
But, if I directly call sayHello (using vm.sayHello()), vm.sayHello.callCount will be 1. As I expect.
How can I make spy capture the call of sayHello (so that vm.sayHello.callCount will be 1), if I want to simulate the click on the html tag (vm.$el.querySelector('h2').click()), and not directly calling sayHello (no vm.sayHello())?
Thanks
Comment: Wouldn't this make a better e2e test? I don't think unit tests should be concerned with UI interactions
Answer: The problem here is that callback is being bound to the event when the component is mounted. I'm not sure exactly how it works in the background but it's like its a copy of the sayHello method within the click event scope. You can't modify it after it has been bound.
You are creating the spy after that on the components method. They act the same but they are not. One is a spy and one is not.
wrapper.vm.sayHello() executes the method (spied on)
wrapper.find('h2').trigger('click') executes the callback (not spied on)
Create the spy on the component Class before mounting rather than the instance afterwards and it should work as expected.
it('should handle click on h2 tag - vue-test-utils + dummy click version', () =>     {
    const clickSpy = sinon.spy(Hello.methods, 'sayHello')
    const wrapper = mount(Hello)
    ...
})

Comment: can we do the same for data variable also? something like: sinon.spy(Hello.data, 'datavariable') ?
Comment: No. Spies are only used to monitor a function or an object method.
https://abdulapopoola.com/2016/04/11/how-function-spies-work-in-javascript/
Answer: (Note Phil's comment on this not being a valid use of unit tests.)
A workaround that I found is this:

Install vue-test-utils: yarn add --dev https://github.com/vuejs/vue-test-utils (afaiu, vue-test-utils is not officially released yet)
Trigger a dummy click event

Now, you can add a new test, which will run as expected:
describe('Hello.vue', () => {
  // ...
  it('should handle click on h2 tag - vue-test-utils + dummy click version', () => {
    const wrapper = mount(Hello)
    sinon.spy(wrapper.vm, 'sayHello')

    // trigger a dummy click event
    wrapper.find('h1').trigger('click')

    // [A] if I run the line below, vm.sayHello.callCount will be 1 - as expected
    wrapper.find('h2').trigger('click')

    // [B] if I run the line below, vm.sayHello.callCount will be 1 - as expected
    // wrapper.vm.sayHello()

    // vm.sayHello.callCount will be 1 in both [A] and [B] cases
    console.log('#####', wrapper.vm.sayHello.callCount)
  })
})

This behavior is so weird and make Vue looks more like a pet project than like a 2.x.x project, that maybe I misunderstood something.


Install Errors for SQL Server 2005 and 2008 on Vista x64

Question: I'm having very strange issues installing either SQL 2008 or 2005 on my local dev machine running Vista Business 64 SP1. It gets to the end of the installation process, then complains about not being able to connect to an RPC server. It immediately pop ups a vista error that the system is shutting down because of a critical error.
When the system comes back up, the same shut down notice appears and shuts down again. I have to boot into safe mode and turn off the SQL server services.
I've tried turning off Windows Firewall and Windows Defender thinking that there may have been a conflict, but the same error occurs without fail.
The event viewer tells me that lsass.exe failed with status code 255 and that it faulted in ncrypt.dll.
Has anyone encountered this issue before?
Answer: No, but I think installing SP2 on that Vista machine would be a really wise thing to do.


How to check if result from cache_get() is expired?

Question: cache_get always returns an object and I'm a bit confused by its values. There's probably a short generic function that can handle this for once and for all.
$cache = cache_get('key');
if ($cache) {
  // doesn't work, cache_get always returns an object
}

if (!$cache || ($cache->created < time() - $cache->expire)) {
  // cache is expired? I'm not sure
}

Just checking for the data member doesn't cut it.
I had seen the issue reported on d.o (in 2009) but that doesn't really help me fix it on any live site. So I'm looking for a function that will still make cache work for me without resorting to storing the cache myself in the database.
Comment: You know it's [already reported issue](https://drupal.org/node/534092)?
Answer: TL;DR Don't, unless you have to. Drupal has long history of optimization and even if it sometimes serves you outdated cache, it's not without a cause. It's to prevent overhead of constant cache wipes. If your application is time-critical for some reasons, read below.

As you can see in the code that does the actual work:
function getMultiple(&$cids) {
  try {
    // Garbage collection necessary when enforcing a minimum cache lifetime.
    $this->garbageCollection($this->bin);

    // When serving cached pages, the overhead of using db_select() was found
    // to add around 30% overhead to the request. Since $this->bin is a
    // variable, this means the call to db_query() here uses a concatenated
    // string. This is highly discouraged under any other circumstances, and
    // is used here only due to the performance overhead we would incur
    // otherwise. When serving an uncached page, the overhead of using
    // db_select() is a much smaller proportion of the request.
    $result = db_query('SELECT cid, data, created, expire, serialized FROM {' . db_escape_table($this->bin) . '} WHERE cid IN (:cids)', array(':cids' => $cids));
    $cache = array();
    foreach ($result as $item) {
      $item = $this->prepareItem($item);
      if ($item) {
        $cache[$item->cid] = $item;
      }
    }
    $cids = array_diff($cids, array_keys($cache));
    return $cache;
  }
  catch (Exception $e) {
    // If the database is never going to be available, cache requests should
    // return FALSE in order to allow exception handling to occur.
    return array();
  }
}

There is no test built in1, and no limit that makes Core return only unexpired nodes.

The way I prefer if I can, is to delete/hide table rows on database level, for example by creating a proxy view that never returns outdated records in the first place, but usually this is inconvenient. Don't try unless you know what you're doing.
The Drupal-only way would be to add comparison in PHP, like that:
if (isset($cache->data) and time() < $cache->expire) {

If your cache is relatively long, you can, and for performance reasons probably should omit testing their expire date on each call and leave it to Drupal's core. It will allow minimum cache lifetime to work with your data, for example. That's how core is doing it.1

1 There are some tests in prepareItem method, but for performance reasons they do not guarantee that outdated cache items will not be returned - see actual code for details.
Comment: I think the big takeaway is that the standard Drupal cache backend exforces a *minimum* lifetime for non-temporary and non-permanent entries, and not an *exact* one.  In fact, this is stated in the API docs for cache_set: "$expire: One of the following values: ... A Unix timestamp: Indicates that the item should be kept **at least until the given time**, after which it behaves like CACHE_TEMPORARY." (emphasis mine).  In addition, constant pruning of the cache tables will ruin the effectiveness of MySQL query caching, as writes/deletes to a table invalidate all entries in that table.
Comment: @MPD I agree with that. On the other hand there are situations when refreshing data at the exact moment is vital. Especially if it's a government project or other project that must comply with specific laws. Also in case of contests. Probably there are other reasons, too. I assumed that's the case here.
Comment: @MPD better now?


Additional twig suggestions for menus

Question: Unlike other elements, the base twig suggestions for menus are only "menu.html.twig" and "menu-[menu_name].html.twig".
I am aware that I can generate additional suggestions through the hook THEME_theme_suggestions_menu_alter, but the $variables array does not contain any useful data. Case in point, I want to retrieve the current region, is it possible?
Comment: If you want to get region, it is possible but not in that template. You have to use the block template for that menu and load the block object and get region from there. Or you can use hook_block_view_alter, depends on your use case.
Comment: The use case is to use the same twig template for all menus inside a given region (sidebar).
Comment: Hm, in that case I would use that aforementioned hook and add theme suggestion into the build array.
Answer: All steps described here work for me with some minor modifications.
GOAL: show main menu in both header and footer region, but use a different template file for both (based on their region).
PREMISE: your theme has regions (like header and footer) and you have used the drupal block system to place the main menu in both your header as in your footer.
I did this in mytheme.theme file:
Dont forget to add the Block use statement in the beginning of your .theme file:
use Drupal\block\Entity\Block;

Now here's the magic for region based menu templates. Also inside your .theme file:
/**
 * Implements hook_preprocess_HOOK().
 *
 * Pass block region value to content so this can be used in
 * MYTHEME_theme_suggestions_menu_alter.
 */
function MYTHEME_preprocess_block(&$variables) {
  if (isset($variables['elements']['#id'])) {
    $region = Block::load($variables['elements']['#id'])->getRegion();
    $variables['content']['#attributes']['region'] = $region;
  }
}

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 *
 * Provide region based menu suggestions.
 */
function MYTHEME_theme_suggestions_menu_alter(&$suggestions, array $variables) {
  if (isset($variables['attributes']['region'])) {
    $suggestions[] = 'menu__' . $variables['menu_name'] . '__' . $variables['attributes']['region'];
  }
}

RESULT when inspecting the main menu inside the header:

RESULT when inspecting the main menu inside the footer:

Comment: This worked for my situation. I just remove the `. $variables['menu_name'] . '__' ` portion of the code as I just wanted to theme all menus that were in specific regions.
Answer: There are a couple of functions that seem like they can help here:
function hook_theme_suggestions_HOOK_alter
function hook_theme_suggestions_alter
This blog post has a useful (if a little bit hacky) way of adding to the template suggestions based on block ID.
http://kristiankaa.dk/article/drupal8-region-specific-menu-theme-hook-suggestion
He suggests using hook_preprocess_block() to add the block ID to the variables array and then using hook_theme_suggestions_HOOK_alter() to add that ID to the theme suggestions for the menus.
/**
 * Implements hook_preprocess_block().
 */
function THEMENAME_preprocess_block(&$variables) {
  $variables['content']['#attributes']['block'] = $variables['attributes']['id'];
}

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function THEMENAME_theme_suggestions_menu_alter(array &$suggestions, array $variables) {
  // Remove the block and replace dashes with underscores in the block ID to
  // use for the hook name.
  if (isset($variables['attributes']['block'])) {
    $hook = str_replace(array('block-', '-'), array('', '_'), $variables['attributes']['block']);
    $suggestions[] = $variables['theme_hook_original'] . '__' . $hook;
  }
}

So you'll end up with an additional menu--MENU-NAME--BLOCK-NAME.html.twig template possibility. It's a neat trick and works well!
Comment: does not work for drupal 8.2.x
Comment: It does work... Currently using on a live production site running 8.2.4. You need to make sure you rebuild the twig cache... Or better still turn it off for development.

https://www.drupal.org/node/2598914
Comment: Getting Notice: Array to string conversion in THEMENAME_theme_suggestions_menu_alter() (line 16 of themes/custom/THEMENAME/THEMENAME.theme).
Comment: Do a web search for "Notice: Array to string conversion" this may help you fix this... There are loads of threads on SO. It means you are taking an array variable and using it like it is a string.
Answer: Confirming $variables['attributes'] is always empty in 8.2.x, so there's insufficient contextual info to form a new suggestion
I solved by installing the menu block module, which adds an field for Theme Hook Suggestion for the menu.html.twig into the edit screen for each menu block.
Answer: You can't get any extra info in suggestions alter, like context. But it's possible to inject suggestions when you render any thing in Drupal 8.
Normally you would do something like this:
$variables['menu'] = [
  '#theme' => 'menu',
  ...
];

Code like this, will probably be inside a menu block, but it could be anywhere.
What you can do to achieve your goal is to change the theme call:
$variables['menu'] = [
  '#theme' => 'menu__header',
  ...
];

Doing the above will add the header suggestion to menu template. I'm not sure how to best accomplish the above.

You should subclass the menu block and change the code a bit
I'm not sure that you can get the region the block is placed in on redner. Otherwise you can add the suggestion as a setting which is configured on the block along with the other menu settings.
Comment: I played a bit with your suggestion, any idea why in SystemMenuBlock there's no access to the machine name of the block currently being rendered? That would allow to load the entity and get the region...
Comment: You should be able to get with either from the configuration or some of the internal methods on the block
Answer: Basically the workaround suggested by featherbelly does work on a Drupal 8.2.7, but it's really hacky and the attributes possibly will also get rendered unless you explicitly unset them again. If they do get rendered this will cause invalid markup.
Using menu_block as suggested by user73304 is way the better option here and it gives you full control of which template is used for any menu via the UI, which is great and better than hacky code that might not work anymore in future versions.

Additional twig suggestions for menus


Java 5 - Bring Modal Dialog to Front on any click

Question: Setting: Java 5 - no upgrade possible.
I have a large application that has a number of modal dialog windows.  I have heard that hidden modal dialogs can result in uninformed users going so far as to restart their computer.  Even if a user knows how to ALT-TAB (in MS Windows, at least), it's a pain.  From what I understand, this was in part fixed in later versions of Java, but that's not an option here, unfortunately.
So, is there any way to force a modal dialog to be shown if any part of the running application is clicked on?  I was thinking it might have something to do with either MouseListeners, GlassPanes, or something else.  However, I've got a bunch of other stuff I'm supposed to be working on, so I don't have a lot of time to devote to hashing this out right now. Can anybody point me in the right direction?
Thanks so much!
Comment: `setModal(true)`.  ModalityType is not in Java5 (only 6 and later)
Comment: what type on Modality, 1) `setModal(true)` 2) `ModalityType(some from API)` but fo real help you have to post http://sscce.org/, because (maybe I wrong) I don't know another Focus issues in Java5 or Java6
Comment: If no one knows where I can start looking for a solution, I'll post an SSCCE tomorrow...gotta run off and do work now...
Comment: right you are added into Java6, then this method can't solve your issue, are you tried - what's happens, when you add/remove/change `setModal(true)` dynamically, set that to required JDialog, that would be easiest and simple way
Comment: SSCCE - create JFrame with two JDialogs that manage two JButtons
Comment: I'll work on an sscce, but it's a bit difficult to model the problem...I've got classes that contains a JTable inside a JPanel inside a JTabbedPane inside a JFrame.  lol
Comment: maybe you have issue with Concurency in Swing, because you can manage empty JDialogs without any issue, but you had problem with Container that loading data, then probably you'll the same problems in Java6 :-)
Answer:
So, is there any way to force a modal dialog to be shown if any part of the running application is clicked on?

When you create the dialog you need to specify the parent frame as the owner of the dialog. Then whenever you click on the frame any dialog that is a child will also be shown.
Comment: see: SwingUtilities.windowForComponent(...).
Comment: Unfortunately the dialog requires a Frame or Dialog parent, which in the context of the problem, is not available.  The dialog is being shown by a class containing a JPanel, which is added to a JTabbedPane, which is then put into a JFrame...
Comment: Unless there's a way to find the top frame of a JComponent, but I don't know of a way to do that...


What is the relationship between a quotient space and annihalator?

Question: If we have a vector space $V$ and subspace $W$, we have that
$$\dim(V/W) = \dim V - \dim W.$$
Similarly for the annihilator $W^{\circ}$ we have that
$$\dim W^{\circ} = \dim V - \dim W.$$
What is the isomorphism between these two spaces? Is there an intuitive way to relate the two ideas?
Comment: See the bottom of https://en.wikipedia.org/wiki/Dual_space#Quotient_spaces_and_annihilators.
Answer: The natural isomorphism is not between $W^0$ and $V/W$, but between $W^{\circ}$ and $(V/W)^*$. Consider the linear map
\begin{align*}
L : W^{\circ} &\to (V/W)^*\\
\varphi &\mapsto \hat{\varphi}
\end{align*}
where $\hat{\varphi}(v + W) := \varphi(v)$. Note, the map $\hat{\varphi}$ is well-defined because if  $v' + W = v + W$, then $v' = v + w$ for some $w \in W$ so
$$\hat{\varphi}(v' + W) = \varphi(v') = \varphi(v + w) = \varphi(v) + \varphi(w) = \varphi(v) = \hat{\varphi}(v + W).$$
Note that if $\hat{\varphi} = 0$, then for every $v \in V$, $0 = \hat{\varphi}(v + W) = \varphi(v)$, so $\varphi = 0$. Therefore $L$ is injective.
Let $\psi \in (V/W)^*$. Note that $\psi\circ\pi \in V^*$ where $\pi : V \to V/W$ is the natural projection, and $(\psi\circ\pi)(W) = \psi(\pi(W)) = \psi(0) = 0$, so $\psi\circ\pi \in W^{\circ}$. Furthermore
$$\widehat{\psi\circ\pi}(v + W) = (\psi\circ\pi)(v) = \psi(\pi(v)) = \psi(v + W),$$
so $L(\psi\circ\pi) = \psi$. Therefore, $L$ is surjective.
So the map $L : W^{\circ} \to (V/W)^*$, $\varphi \mapsto \hat{\varphi}$ is an isomorphism.
If $V$ (and hence $W$) is finite-dimensional, then we have
$$\dim W^{\circ} = \dim (V/W)^* = \dim V/W = \dim V - \dim W.$$


Unable to fetch a word containing spaces using to_tsvector and to_tsquery

Question: I want to fetch a word entered by a user in the database:
select name
from users
where to_tsvector(name) @@ to_tsquery('$word:*')

I mention word = alain john smith, when I run the query  I got this error:
syntax error in tsquery: "alain john smith"

The plainto_tsquery  cannot recognize Boolean operators, weight labels, or prefix-match labels in its input Parsing queries
How can I fix that?
Answer: A tsquery cannot contain alain john smith, since the parser will split this into three words.
If you have PostgreSQL 9.6 or later, you can use
to_tsquery('alain <-> john <-> smith')

which makes use of the "followed by" operator <->.
In older versions, the best you can do is
to_tsquery('alain & john & smith')

which will match strings containing all three words, but not necessarily adjacent or in this order.


Adding loading image into the  for live search

Question: I need to add a small loading image to my live search engine (as per the photo) to have it shown before the search results comes up as I'd have several images called from database which may need some time to load, and when the result is loaded the loading image fadeout

My Script code is:

And my HTML code is:

        <input name="Search" type="text" id="search" autocomplete="off" onfocus="if (this.value == 'Search by item name or number')
 {this.value = '';}" onblur="if (this.value == '')
 {this.value = 'Search by item name or number';}"
value="Search by item name or number">

Thanks in advance
Answer: Try this?
On keyup, append the loading image to ul, after the result, hide it again.
// Start Ready
$(document).ready(function() {

    // Icon Click Focus
    $('div.icon').click(function(){
        $('input#search').focus();
    });

    // Live Search
    // On Search Submit and Get Results
    function search() {
        var query_value = $('input#search').val();
        $('b#search-string').html(query_value);
        if(query_value !== ''){
            $.ajax({
                type: "POST",
                url: "search.php",
                data: { query: query_value },
                cache: false,
                success: function(html){
                    // remove loading gif
                    $("ul#results").html('');
                    $("ul#results").html(html);
                }
            });
        }return false;
    }

    $("input#search").live("keyup", function(e) {

        // show loading gif after keying 3 characters
        if($(this).val().length >= 3)
            $("ul#results").append('

');

        // Set Timeout
        clearTimeout($.data(this, 'timer'));

        // Set Search String
        var search_string = $(this).val();

        // Do Search
        if (search_string == '') {
            $("ul#results").fadeOut();
            $('h4#results-text').fadeOut();
        }
        if(search_string.length >= 3){
            $("ul#results").fadeIn();
            $('h4#results-text').fadeIn();
            $(this).data('timer', setTimeout(search, 100));
        }
    });

});

Comment: You are perfect, thanks a lot, one more thing, may you adjust this image to show up ONLY after typing three letters?!.... thanks again, I was searching it two days already.
Comment: check my update answer again, add this condition for showing image...if($(this).val().length >= 3) ...
Comment: if possible & I may be bothering, I wish to make the slide down window only fade in after writing three letters in the input box, I think it is little code in the //DO Search// place at the end of the code, thanks again.
Comment: nvm, check update answer again, try this? ... else if(search_string.length >= 3) ...
Comment: You are brilliant, it worked fine but the results stopped from coming up, it only shows the loading image and keep loading....
Comment: :) remove else? just ...if(search_string.length >= 3){}...coz I cannot test the script.


How is an ROC curve constructed for a set of data?

Question: I know that sensitivity and recall (and precision, and specificity, etc) can be computed for a set of data X with a binary label Y, but I'm not sure how there can be multiple values for both of those, for a single  set of data.
How is an ROC curve constructed for a set of data?  It must require an ordered set of data for both axes, so there must be an ordered set of pairs of recall and specificity values.  How is this order determined? and how are these values determined?
Comment: Maybe [this](http://stats.stackexchange.com/questions/105501/understanding-roc-curve/105577#105577) can be helpful?
Comment: A classifier is ranking if it can output some score instead of a hard classification prediction. For example, Logistic Regression typically outputs probability, which is a score you can use for ranking. You can use this information for building the ROC curve.
Comment: That was helpful, thank you @AlexeyGrigorev, but it is still unclear to me how the "rank" or "score" is determined.  That source doesn't explain that part at all.
Comment: Okay, so if I have, for example, a `random forest` which is a binary classifier.  The probability of success produced by the classifier would be the value used for ranking.  Correct?
Comment: yes, this is correct
Answer: Here's an example of calculating an ROC curve. There are many things that ROC curves are used for, but this will give an overall idea of how an ROC curve is created.
Lets say that we want to use white blood cell counts to diagnose appendicitis. We'd like to collect a white blood cell count from a patient and then tell them if they have appendicitis or not. We'll call it our "Appendicitis Test". (This is just an example, no guarantees that this makes medical sense.)
We'd like to make an ROC curve for our Appendicitis Test. We have 50 patients that we can use. We know two things about these patients: 1) whether or not the patient has appendicitis and 2) what the white blood cell count of the patient is.
With these two pieces of information, we can create an ROC curve.
Here's the fake data of our patients:
#White blood cell counts for our 50 patients (WBC)
WBC = c(10:59)
#Whether they have appendicitis (Append: 1=yes, 0=no)
Append=c(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,1,1,1,1,1,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1)
#Combine our data
dat = data.frame(cbind(WBC, Append))

We decide that a white blood cell count above 30 is a pretty good cutoff for deciding whether a patient has appendicitis. But we're not sure. So we try 5 possible white blood cell cutoffs that would indicate that a patient has appendicitis: 10, 20, 30, 40, and 50. Now, we need to find the sensitivity and specificity at each cutoff to see how well the test detects appendicitis at each cutoff.
#Create variables that equal 1 if the test detects
#appendicitis (whether it's correct or not) using our five cutoffs.
dat$yes10 = ifelse(dat$WBC > 10, 1, 0)
dat$yes20 = ifelse(dat$WBC > 20, 1, 0)
dat$yes30 = ifelse(dat$WBC > 30, 1, 0)
dat$yes40 = ifelse(dat$WBC > 40, 1, 0)
dat$yes50 = ifelse(dat$WBC > 50, 1, 0)

Now calculate the sensitivity and specificity at each cutoff:
 sensitivity <-c(sum(dat$yes10 == 1 & dat$Append == 1)/sum(dat$yes10 ==1),
            sum(dat$yes20 ==1 & dat$Append == 1)/sum(dat$yes20 ==1),
            sum(dat$yes30 ==1 & dat$Append == 1)/sum(dat$yes30 ==1),
            sum(dat$yes40 ==1 & dat$Append == 1)/sum(dat$yes40 ==1),
            sum(dat$yes50 ==1 & dat$Append == 1)/sum(dat$yes50 ==1))

 specificity <-c(sum(dat$yes10 == 0 & dat$Append == 0)/sum(dat$yes10 ==0),
                 sum(dat$yes20 ==0 & dat$Append == 0)/sum(dat$yes20 ==0),
                sum(dat$yes30 ==0 & dat$Append == 0)/sum(dat$yes30 ==0),
                sum(dat$yes40 ==0 & dat$Append == 0)/sum(dat$yes40 ==0),
                sum(dat$yes50 ==0 & dat$Append == 0)/sum(dat$yes50 ==0))

Then plot the True Positive Rate (sensitivity) by the False Positive Rate (1 - specificity) of each cutoff to get the ROC curve for the appendicitis test.
TruePositiveRate = sensitivity
FalsePositiveRate = 1 - specificity
ROCCurve = data.frame(cbind(FalsePositiveRate, TruePositiveRate))
plot(ROCCurve, main="ROC Curve for Appendicitis Test")
lines(ROCCurve, col="red")

Now we can see that our cutoff of 40 is our best choice, because there is a 100% true positive rate and only 20% false positive rate.
Comment: Good explanation.  So, these "cutoff" values - it seems to me that this is just one way to vary something over multiple pairs of TPR and FPR values, as @TH4454 is suggesting.  If I have multiple predictor variables, and the binary result of a machine learning algorithm, how do I incorporate all of these in devising  `"cutoff"` values?   You cited an example with just one variable as the cutoff, but it's more difficult for me to imagine if there were multiple variables.....?
Comment: Probabilistic/scoring classifiers, like logistic regression, trees, and neural networks, output a numeric value that needs a  threshold to become a binary value. You can use an ROC plot to see which threshold is the best for your chosen probabilistic/scoring classifier. You can also look at the TPR and FPR over all of the thresholds to get an overall look at the performance of your classifier. And then you can plot an ROC curve for each type of classifier (trees, logistic, etc.) on one plot to compare all of them together and choose the best one for your data.
Answer: A ROC curve is calculated from an independent risk prediction or risk score that has been merged to validation data containing observed binary outcome variables, e.g. life or death, recurrence or remission, guilty or innocent, etc..
The ranges of possible values for that risk prediction/score are sorted and enumerated from least to greatest as a range of possible cutpoints. For each cutpoint, the continuous risk variable is dichotomized producing a classification of the observed event. This binary value is compared to the observed outcomes and the sensitivity and specificity is calculated each time. Plotting sensitivity and specificity over the range of possible cutpoints produces a ROC.
Note that the linepath produced by these cutpoints does not convey what the actual cutpoint is. For that reason, it is often nice to annotate a ROC curve with example sens/spec combinations for a couple cutoff points.
Example R code here:
ROC<-function(T,D){
  DD <- table(-T,D)
  tpr <- cumsum(DD[,2])/sum(DD[,2])
  fpr <- cumsum(DD[,1])/sum(DD[,1])
  rval <- list(tpr=tpr, fpr=fpr,
  cutpoints=rev(sort(unique(T))),
  call=sys.call())
  class(rval)<-"ROC"
  rval
}

Answer: So say your model gives some % prediction between 0 and 100%.  Let's call that Y.  And your classifier is either A or B.
My understanding is that an ROC curve is built by ranging a variable, let's call it "K", for values between 0 and 100%.  For every value K and every estimate Y, you say something like ... if K is greater than Y, then it's an A, otherwise it's a B.
Then you build a confusion matrix for every K.  From each of those confusion matrices, you can determine the true positive (the Y value in the ROC curve) and false positive (X value in the ROC curve).
Hence, if you have perfect separation between A and B, your ROC curve will go straight up and to the left.
Answer: A ROC Curve is not constructed for a set of data, it is constructed for the results of a classification performed on a set of data.
There are models (or methods of implementing them) that produce multiple ROC curves for a single model and set- say, one for the results of the model applied to the training set itself and one for the results of the model applied to validation set. Multiple ROC curves for a single model and data set would most likely be of this variety.


Angular - Interceptor HTTP retornar o valor de uma promisse

Question: Tenho que aplicar uma descriptografia no body do retorno de uma requisição via Interceptor, porém o método de descriptografar é assíncrono e retorna uma promisse.
Segue um trecho da classe:

intercept(req: HttpRequest, next: HttpHandler): Observable> {

return next.handle(req).pipe(map((event: HttpEvent<any>) => {
  if (event instanceof HttpResponse) {
    let _body;

    this.cryptMethod.decrypt(event.body).this(res => _body = res); // Método assíncrono

    return event.clone({ body: JSON.parse(_body) });

  }
  return event;
}));
}`

Acontece que o this.cryptMethod.decrypt() é assíncrono, e por isto o return é alcançado antes do _body ser preenchido.
Há alguma solução para isto?
Answer: Tente usar uma async function, dessa forma você pode utilizar await dentro da função para esperar o retorno da promise.

intercept(req: HttpRequest, next: HttpHandler): Observable> {

return next.handle(req).pipe(map(async (event: HttpEvent<any>) => {
  if (event instanceof HttpResponse) {
    let _body;

    await this.cryptMethod.decrypt(event.body).then(res => _body = res); // Método assíncrono

    return event.clone({ body: JSON.parse(_body) });

  }
  return event;
}));
}`
Comment: Valeu cara, funcionou aqui!
obrigado!