If $f$ increasing, analytic on $\mathbb{R}$ and $\lim_{x\to +\infty}f(x)=1$, does it follows that $\lim_{x\to +\infty}f'(x)=0$?

Question: Question:

If $f$ strictly increasing, analytic on $\mathbb{R}$ and $\lim_{x\to +\infty}f(x)=1$, does it follows that $\lim_{x\to +\infty}f'(x)=0$?

If we drop the assumption that the function is increasing, an easy counterexample is $a(x)=\frac{\sin(x^2)}{x}+1$.
If we drop the analyticity requirement (but keep $C^{\infty}$) a counterexample can be constructed from
$$h(x)=\begin{cases}0&x\le 0\\\exp\left(\frac{-\exp(-1/{(x-1)^2})}{x^2}\right)&x\in (0,1)\\
1&x\ge 1\end{cases}$$
by setting
$$b(x):=\text{sign}(x)\sum_{n=0}^{+\infty}\frac{h(2^n(|x|-n))}{2^{n+1}}$$
It is clear that, if $\lim_{x\to +\infty} f'$ exists, it must be $0$:
In fact, since $0=\lim_{x\to +\infty}\frac{f(x)-1}{x}=\lim_{x\to +\infty}f'(x)$.
Otherwise one can prove it by noting that, since $f'\ge 0$ and $1=\int_0^\infty f'(x)dx$ it is impossible to have $\lim_{x\to +\infty}f'(x)>0$.
However, I do not see how to prove the existence of the limit of how to construct a counterexample (as $b$ is not analytic)
Comment: Are you sure it is wrong ?
Answer: $$ f(x) = \int_0^x \exp(-t^4 \sin^2(t))\, dt $$
is a counterexample, after normalizing by a suitable constant so that $ \lim_{x \to \infty} f(x) = 1 $ instead of $ 1.17195 \ldots $
The idea is that the factor $ t^4 $ suppresses the contribution of the integrand at all points too far from the zeroes of $ \sin(t) $ as $ t $ gets large, and $ \sin^2(t) $ is only within $ O(1/N^4) $ of $ 0 $ for $ t $ that's $ O(1/N^2) $ from an integer multiple of $ \pi $. Since $ 1/N^2 $ is a fast enough decaying sequence, the integral converges. It's obviously an analytic function.
Edit: Here is a more formal argument. Consider the integral
$$ \int_{N \pi}^{(N+1) \pi} \exp(-t^4 \sin^2(t)) \, dt \leq \int_0^{\pi} \exp(-\pi^4 N^4 \sin^2(t))$$
Split the interval $ [0, \pi] $ into two pieces, $ [1/N^{5/4}, \pi - 1/N^{5/4}] $ and its complement. Over this interval,
$$ \sin^2(t) \geq \sin^2(1/N^{5/4}) = 1/N^{5/2} + O(1/N^5) $$
so that $ \exp(-\pi^4 N^4 \sin^2(t)) \leq \exp(-\pi^4 N^{3/2} + O(N^{-1})) $, which is obviously summable by comparison to the geometric series, say. So the contribution to the integral from this part is $ L^1 $. The other part of the integral is over a set of measure $ 2/N^{5/4} $, and since the integrand is bounded from above by $ 1 $, this part only contributes a term of order $ O(1/N^{5/4}) $, which is also $ L^1 $. We conclude therefore that $ f $ is well-defined by monotonicity and has a finite limit at infinity.
Comment: Why is it an analytic function?
Comment: Just need to be a bit more formal for the conclusion I think, but this is brilliant
Comment: So in this case, the limit $f'(x)$ does not exist.  Suppose the original post had made the assumption that $f'(x)$ existed.
Comment: @ClementYung because the integrand is analytic.
Comment: @user2379888 They didn't actually ;)
Comment: @EDX, I know, but I"m curious if, in that case, there is still some clever counterexample.
Comment: @user2379888 Yes indeed I'm curious too to see if there are some !
Comment: @user2379888 If the limit exists it must be $0$, as you easily see from $f(x)=\int_0^xf'(t)dt$
Comment: @Caffeine actually not everytime, look at Fresnel integrals.
Comment: @EDX In this case, since $f'\ge 0$, the conclusion holds.
Comment: @Caffeine Could summon the theorem you're using ?
Comment: @Caffeine It doesn't help to restrict to entire functions, because the function I gave is entire as well. You can expand it in a power series around $ x = 0 $ with infinite radius of convergence.
Answer: I was thinking we could write the limit as $$\lim_{x \to \infty}\frac{e^xf(x)}{e^x}=1$$
Since this is an indeterminate form, we can apply L'Hopital's Rule,
$$\therefore \lim_{x \to \infty}\frac{e^xf(x)}{e^x}=\lim_{x \to \infty}\frac{e^xf(x)+e^xf'(x)}{e^x}=1$$
$$\therefore \lim_{x \to \infty}(f(x)+f'(x))=1 \implies \lim_{x \to \infty}f'(x) = 0$$
If I have made some error, please feel free to correct me.
Comment: Ahhh, I missed that. I thought when you said that the function is analytic, it will have a derivative and its limit will exist :)
Comment: L'hopital works only if the limit of the derivative exists, which is the hard part to prove here


Which instrument allows for more natural improvisation of melodies?

Question: For example, when there is a song playing, it is relatively easy to hum or whistle an improvised melody over it, while on a piano you would have to know which keys to press. A kazoo kinda allows the same simplicity because it is directly connected to our voice, and maybe a fretless instrument allows for more natural feedback. Some other instrument that requires more special technique would be then "less natural" in this sense.
Comment: I don't believe, there is a strong dependency on the type of the instrument, as long as the degree of mastery of that instrument is sufficient. If you are struggling to find the note you imagine on whatever instrument, this level is clearly not reached.
Comment: It is true that [continuous pitch instruments](https://music.stackexchange.com/questions/103798/what-is-the-general-term-for-instruments-without-fixed-pitches-like-fretless/103799#103799) especially the theremin where the change of tone always goes the same way than the motion, would feel more "natural", the problem then is to play in tune!
Answer: This kind of question is like asking whether red is better than green :-)
Instead of ranking what is "natural" I suggest looking at the qualities of the instruments and trying to understand how someone tries to exploit those qualities to perform.
Piano cannot bend pitch or sustain long notes or crescendo after a key is struck, but it can play chords and has a huge range. You don't need to worry about intonation as long as it's tuned. A lot of figures are probably easier to play fast on keyboard compared to wind instruments.
I sort of see your point about the voice being "natural." Singing is so fundamental. But... singing well is another story. A lot depends on the improv style. Humming a simple folk-like tune would be pretty direct with voice. But doing some jazz enclosures to decorate a chord arpeggio would be a challenge without lots and lots of practice.
About fretless instruments I think it's very much the opposite of what you suggest. To me they are harder to play, because it's hard to control the intonation. I think a strong case can be made that frets and keyboards were developed because they actually make it easier to play without a lot of training.
Having said all that, my personal feeling is wind instruments are well suited for expressive melody over piano and guitar. The voice-like qualities of winds seems directly expressive. Piano and guitar have weak tone and sustain by comparison. It doesn't mean they aren't expressive. It think they are just less directly (naturally if you like) expressive. Everyone has a voice so I think we respond more immediately to voice-like sounds. But that is largely an observation from the perspective of the listener not the performer. It shouldn't misconstrued as one instrument type over another is easier for improvisation.
Comment: Re: fretless instruments -- OMG yes! First time I tried to play lap steel in front of others, my ear was SO off, and I don't recall getting nearly that level of shame in my life.
Comment: I've only played lapsteel with a nut adapter which raises the action up high on my cheapo steel string acoustic. You're right. It's a real intonation shocker. I think that's why a lot of blues players use that wide vibrato shake. Vibrato is supposed to help find/maintain pitch. But that wide shaking seems a bit disguising accurate pitch.
Answer: If you mean to say that singing is the "best" way to improvise melodies, I'll present a different point of view. Being able to play instruments provides structured ways to reason about music that you most probably don't have if you cannot play any instrument. And being able to read and write musical notation provides another such framework, or instrument.
Each instrument is like a new language - it lets you "say" different things, naturally lending itself to certain musical expressions that might not arise so easily from other instruments. For example the guitar makes it easier to play open chord voicings, and more difficult or even impossible to play very tight close voicings that are possible on the piano. If you "speak guitar" and use the naturally arising chord patterns for playing melodic notes, you tend to produce certain melodies that you would not have thought of if you could only sing. Or if you know the half-whole diminished scale on an instrument, and use it to create melodies, you'll create things that practically nobody would come up with otherwise. And if you learn to play chords and melodies on the piano (why not guitar as well), you might develop a certain sense for emphasizing chord tones. Or at least you can make more informed choices about chord tones vs. non-chord tones, if you know where they are on a visual reference scale.
So, go and learn to play instruments. It will expand your melodic ideas and make you a better musician.
Answer: The piano I believe to be the easiest because the notes are labeled and easy to figure out. The guitar is up there it's just you have to memorize the note names making that aspect a little hard.
The nice thing about guitar is you can play melody (with expression)and harmony.
Where the piano you can play melody (but not too much expression) and harmony on the piano.
The most expressive melody instruments are horns and the voice but they limited to single lines.
And instruments which allow you to play harmony are slightly less expressive in playing melody.
Comment: I'm not sure this is a useful discussion; in any case, I have [moved it to chat](https://chat.stackexchange.com/rooms/115673/discussion-on-answer-by-mmj2020-which-instrument-allows-for-more-natural-improvi).


Is it possible to detect when an user closes the console in C?

Question: I would like to know if it is possible to detect when a user closes the console and then execute a function that frees the memory allocated by previous malloc calls.
I know that the main OS like Windows/Linux/MacOS are supposed to free this memory when the console closes, but I think it is better to make a program to rely on the OS as few as possible.
Comment: This is going to be OS-specific, and isn't part of the C standard.
Comment: In unix, when the terminal is closed, the process is sent SIGHUP. This kills your process by default, though you could hook it (and other signals such as SIGINT and SIGTERM) to perform some cleanup. Freeing up memory is not needed, though. The OS automatically frees all memory associated with processes that exit (incl killed).
Comment: @TomKarzes I see, so the program should either rely on the OS or use tools provided by the OS (if there are some).  Then in this case the OS is more to blame for bad memory management than the program lol.
Comment: There is no bad memory management. Your program _got_ all its memory from the OS, and the OS cleans it up. That is good memory management.
Comment: @Wheatley You just need to make sure the process exits when the console closes.  When the process exits, all memory will be freed.  You just need to make sure it doesn't continue running in background.
Answer: Re:

it is possible to detect when a user closes the console and then
execute a function that frees the memory allocated by previous malloc
calls?

Yes, it's possible to catch the signal.
On POSIX-compliant¹ systems, the process is sent SIGHUP.
Macro: int SIGHUP

The SIGHUP ("hang-up") signal is used to report that
the user's terminal is disconnected, perhaps because a network or
telephone connection was broken. For more information about this, see
Control Modes.
This signal is also used to report the termination of the controlling
process on a terminal to jobs associated with that session; this
termination effectively disconnects all processes in the session from
the controlling terminal.

The OS will automatically free() the memory when the process exits. But you can use signal()/sigaction()² to change the default handling and free up resources.

The sigaction() system call is used to change the action taken by
a process on receipt of a specific signal.

NB that signal()'s behaviour varies across UNIX systems and is not portable. Avoid it's use.
The only portable use of signal() is to change the disposition to SIG_IGN/SIG_IGN.
Also note that neither the C standard, nor the POSIX standard specifies free() to be async-signal-safe, i.e. it is not safe to call it in a signal handler.
[1] — For Windows, see: Windows console signal handling for subprocess c++
[2] — sigaction() is defined in the POSIX standard, not in the C standard.


AJAX requisição com dominio diferente

Question: minha Requisição
url="http://algumip:algumaporta/dowPDFNF?cChave="+chave

 $.ajax({
    url: url,
    dataType: 'jsonp',
    success: function (data) {
        console.log(JSON.stringify(data));
    },
    type: 'POST'
});

erro que retorna:
Uncaught SyntaxError: Unexpected token :

No entanto, quando eu passo a url (gerada pela variavel url) direto no navagador, eu consigo o retorno certo. Veja imagem o retorno:

O que eu preciso é pegar esse retorno para ter o download do pdf
{"pdf":"http:\\\\algumip\\download\\6a423e04e2c2dfd4a59f0001ec8bbf44b9a6a6d-nfe.pdf"}

Comment: Acredito que não é o caso, pois eu consigo chegar no outro dominio, problema está em ler o retorno "data" em success
Comment: O problema deve ser esse JSON.stringify, dá um console.log pra ver como está chegando o data.
Comment: Coloca um debugger dentro da função success.

    success: function (data) {
        debugger
        console.log(JSON.stringify(data));
    }
Pra ver se está entrando no success.
Comment: @DanielleArrudatorres Fato, altere o título porque nesse caso não existe nenhuma relação com CORS e com o fato da requisção ser para outro domínio.
Comment: @DanielleArrudatorres você não pode fazer um post com o jsonp para outro domínio, a requisição não pode ser get?
Comment: @MayconF.Castro o  debugger me retorna "Uncaught SyntaxError: Unexpected identifier"
Comment: @LeandroAngelo vou alterar pra Get e testar
Comment: Não informa qual é o callback.
Comment: O tratamento do retorno também é diferente, implemente o jsonpCallback para analisar o retorno.
Comment: Mesmo com jsonp: "jsonpcallback",  dataType: "jsonp". Ainda tenho o retorno do erro : Uncaught SyntaxError: Unexpected token :
Comment: Vamos [continuar esta discussão no chat](https://chat.stackexchange.com/rooms/77320/discussion-between-danielle-arruda-torres-and-leandro-angelo).
Answer: Tente acrescentar o item  async: false, pois segundo a documentação, pedidos de jsonp a servidores remotos não funcionam se o modo asynchronous estiver ativo.

Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation.

$.ajax({
    async: false,
    method: 'GET',
    url: url,
    contentType: "application/json",
    jsonpCallback: minhafuncaocallback,
    dataType: 'jsonp',
    success: function (json) {
        console.log(json);
    },
    error: function (jqXHR, textStatus, errorThrown) {
        console.log("AJAX ERRO" + jqXHR + textStatus + errorThrown);
    }
});

É bom que esse pedido seja feito após a página ter sido totalmente carregada porque um pedido synchronous impede que o carregamento da página continue até que a resposta seja recebida daquele pedido o que pode diminuir a qualidade da experiência do usuário no seu site, se for o caso.

AJAX requisição com dominio diferente


scrollTop animations choppy

Question: Sorry, my JavaScript skills are limited, but I'm trying to learn.
I am trying to make a smooth scrolling animation with scrollTop calculations where divs placed absolute on top of each other start with zero width and grow behind each other.
Have set up a fiddle to try to explain:
http://jsfiddle.net/vsP4e/1/
The problem is that the animation is really choppy and simply wrong at certain points.
Also, it I refresh the browser my divs start up at totally wrong places and jumps back in place when I start scrolling.
In firebug the calculations are often wrong and seem to never stop going even when I am not scrolling.
<code>    $(document).ready(function() {

        doStuff();

      $(document).scroll(function() {

        var levelScroll = $(document).scrollTop();

        doStuff();

          var show1 = $("#shaddow1").width();
          var c1w = $("#circle1").width();
          var div1W = $("#div1").width();

                    //div1
                    if(levelScroll>=0 && levelScroll<=200){
                      $("#div1").css("width", "0px");
                      $('#div1').css("margin-left", (-(div1W)/2));
                      $('#div1').css("margin-top", (-(div1W)/2));
                    }
                    else if(levelScroll>=200 && levelScroll<=500){
                      $("#div1").css("width", (levelScroll-200)+"px");
                      $('#div1').css("margin-left", (-(div1W)/2));
                      $('#div1').css("margin-top", (-(div1W)/2));

                    }
                    else if(levelScroll>=500){
                      $("#div1").css("width", "188px");
                      $("#div1").css("margin-left", "-94px");
                      $("#div1").css("margin-top", "-94px");
                    }

                    //circle1
                    if(levelScroll>=0 && levelScroll<=350){
                      $("#circle1").css("width", "0px");
                      $('#circle1').css("margin-left", (-(c1w)/2));
                      $('#circle1').css("margin-top", (-(c1w)/2));
                      $("#shaddow1").css("width", "0px");
                      $('#shaddow1').css("margin-left", (-(show1)/2));
                      $('#shaddow1').css("margin-top", (-(show1)/2));
                    }
                    else if(levelScroll>=350 && levelScroll<=650){
                      $("#circle1").css("width", (levelScroll-350)+"px");
                      $('#circle1').css("margin-left", (-(c1w)/2));
                      $('#circle1').css("margin-top", (-(c1w)/2));
                      $("#shaddow1").css("width", (levelScroll-300)+"px");
                      $('#shaddow1').css("margin-left", (-(show1)/2));
                      $('#shaddow1').css("margin-top", (-(show1)/2));

                    }
                    else if(levelScroll>=600){
                      $("#circle1").css("width", "232px");
                      $("#circle1").css("margin-left", "-116px");
                      $("#circle1").css("margin-top", "-116px");
                      $("#shaddow1").css("width", "232px");
                      $("#shaddow1").css("margin-left", "-116px");
                      $("#shaddow1").css("margin-top", "-116px");
                    }

                  });

    });

    function doStuff(){
            var show1 = $("#shaddow1").width();
            var c1w = $("#circle1").width();
            var div1W = $("#div1").width();

            $('#shaddow1').css("margin-left", (-(show1)/2));
            $('#shaddow1').css("margin-top", (-(show1)/2));

            $('#circle1').css("margin-left", (-(c1w)/2));
            $('#circle1').css("margin-top", (-(c1w)/2));

            $('#div1').css("margin-left", (-(div1W)/2));
            $('#div1').css("margin-top", (-(div1W)/2));
        }
</code>
Answer: If you use same values on different layers of a condition, it'll create conflict. Here is an example from your function:
<code>if(levelScroll>=0 && levelScroll<=200){ ... }
else if(levelScroll>=200 && levelScroll<=500){ ... }
//this will create a conflict when levelScroll value came to 200

else if(levelScroll>350 && levelScroll<=650){ ... }
else if(levelScroll>=600){ ... }
//this equation also will create bigger problem
</code>
Here is working jsFiddle.
Note: I won't suggest to use different (in your example you've got 2) conditions on scrolling, it raises mistake possibilty and most browser's still can't handle these advanced jQuery animations.
Comment: Thank you so much for you're help!
Animation is still a bit choppy but now the divs does not just fly off – they keep in place :)

scrollTop animations choppy


Problem encrypting/encoding URL variable

Question: I have a class that takes a string in this format:

000067000000000012620060324b38e2cab3353

, encrypts the string then appends it as a get variable in a URL.
The class that does the encryption has a function that looks like this:
private function _code_encryption($enc_type,$a_string){
    $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC);
    $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);

    if($enc_type == self::ENCRYPT_STRING){
       //encrypt then return base64 encoded
       $encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, self::AUTH_ENCRYPTION_KEY, $a_string, MCRYPT_MODE_CBC, $iv);
       return base64_encode($encrypted);
    }elseif($enc_type == self::DECRYPT_STRING){
       $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, self::AUTH_ENCRYPTION_KEY, base64_decode($a_string), MCRYPT_MODE_CBC, $iv);
        return trim($decrypted);
    }
}

When the string is encrypted I urlencode the value and add it to the url like the url looks like "https://secure.mysite.com/index.php?action=someaction&transfer_code=XXXXX where XXXX is the urlencoded encrypted string.
Now, when the url is parsed and processed the value of $_GET['transfer_code'] is getting passed into the above _code_encryption function but is not returning the correctly decrypted value and instead returns garbled characters my browser doesn't render. Is there a requirement for the length of the key I use for encryption/decryption? I tried something like
$key = hash('sha256',self::AUTH_ENCRYPTION_KEY,true);

but that didn't work either...
Also, I am not urldecoding the $_GET['transfer_code'] variable because the php man pages state that get vars are already urlencoded...
Should I be UTF-8 encoding the alphanumeric string BEFORE encryption/base64_encoding, or will that even make any difference?
Answer: You use a random IV to encrypt, and the a different random IV to decrypt. The decrypted string will never ever match the original. To properly decrypt the original string you must use the same IV that was used during encryption. Usually this is achieved by prepending the IV used to the encrypted string. At decryption time you must first extract the IV from the value, initialize the key with this value, then decrypt the rest usign the properly initialized key.
I don't have a parser to validate this but it should be something like:
private function _code_encryption($enc_type,$a_string){
 $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC);
 if($enc_type == self::ENCRYPT_STRING){
  //encrypt then return base64 encoded
  $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
  $encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, self::AUTH_ENCRYPTION_KEY, $a_string, MCRYPT_MODE_CBC, $iv);
  return base64_encode($iv.$encrypted);
 } elseif ($enc_type == self::DECRYPT_STRING){
  $decoded = base64_decode($a_string);
  $iv = substr($decoded,0,$iv_size);
  $cipher = substr($decoded,$iv_size);
  $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, self::AUTH_ENCRYPTION_KEY, $cipher, MCRYPT_MODE_CBC, $iv);
  return trim($decrypted);
 }
}

Comment: Turns out the urlencoding was preserving the "=" signs fine but spaces were being converted to %2B, rather than "+". Problem solved.
Comment: Are you intentially skipping the 1st char of the iv ( substr($decoded,1,$iv_size) )?

I thought everything was working correctly (extracting the IV from char 0, not 1) but I'm getting mixed results. For example encrypting/encoding this string "67:1262031751:4b38e2cab2353" works great but this one "24:1262031777:4b38e2cab2353" never works at all and returns a 64 char string of bogus characters.
Comment: No, id did not skip 1st char intentionally. I just didn't rember if is 0 based or 1 based.
Comment: If some strings work some don't make sure your base64 encode/decode is correct. base64 pads the output with '=' and if the urlencode/decode strips the '=' then the base64 encode/decode is corrupted and the result is the cipher is corrupted. you're going to take this one by one and verify at each step that the reverse operation works (decrypt the output after encrypting and verify, decode after encoding, and verify etc).
Comment: I might have this same problem.  How did you solve the issue of the pluses and spaces?  I tried using both realurlencode and urlencode and neither worked.


How to declare copy constructor in derived class, without default construcor in base?

Question: Please take a look on the following example:
class Base
{
protected:
    int m_nValue;

public:
    Base(int nValue)
        : m_nValue(nValue)
    {
    }

    const char* GetName() { return "Base"; }
    int GetValue() { return m_nValue; }
};

class Derived: public Base
{
public:
    Derived(int nValue)
        : Base(nValue)
    {
    }
    Derived( const Base &d ){
        std::cout << "copy constructor\n";
    }

    const char* GetName() { return "Derived"; }
    int GetValueDoubled() { return m_nValue * 2; }
};

This code keeps throwing me an error that there are no default contructor for base class. When I declare it everything is ok. But when i dont, code does not work.
How can I declare a copy constructor in derived class without declaring default contructor in base class?
Thnaks.
Comment: Compiler doesn't supply the default constructor for the class once we have any parameterized constructor..
Answer: Call the copy-constructor (which is generated by the compiler) of the base:
Derived( const Derived &d ) : Base(d)
{            //^^^^^^^ change this to Derived. Your code is using Base
    std::cout << "copy constructor\n";
}

And ideally, you should call the compiler generated copy-constructor of the base. Don't think of calling the other constructor. I think that would be a bad idea.
Comment: @amit: `Base(Base const&)` will be generated by the compiler!
Comment: @amit: of course it is. unless you define a copy ctor yourself, the compiler will synthesize one for you.
Answer: You can (and should) call the copy ctor of the base class, like:
Derived( const Derived &d ) :
        Base(d)
{
    std::cout << "copy constructor\n";
}

Note that I turned the Base parameter into a Derived parameter, since only that is called a copy ctor. But maybe you didn't really wanted a copy ctor...
Comment: `Base(Base const&)` is.  By the compiler.
Comment: @amit: of course it is. unless you define a copy ctor yourself, the compiler will synthesize one for you.
Comment: @PlasmaHH: You should explicitly mention it in your answer, I totally forgot about it :\
Comment: @amit: there is a whole lot of other basic things that are not explicitly mentioned in the answer, because they do not relate to the question, and either I explain all of them, or none. I think none is more useful here.
Answer: If no user-declared constructors of any kind are provided for a class type (struct, class, or union), the compiler will always declare a default constructor and a copy constructor as a non-explicit inline public member of its class.
If some user-declared constructors are present, the user may still force the automatic generation of a default constructor by the compiler that would be implicitly-declared otherwise with the keyword default.
In the base constructor, you have user-declared constructors so you must declare otherwise with the keyword default.
class Base
{
protected:
    int m_nValue;

public:
    Base(const Base&) = default;    // since cpp11

    Base(int nValue)
        : m_nValue(nValue)
    {
    }

    const char* GetName() { return "Base"; }
    int GetValue() { return m_nValue; }
};

In the derived constructor, you must construct base constructor like:
Derived(const Base &d)
: Base(d)
{
    std::cout << "copy constructor\n";
}

Comment: This doesn't appear to add anything to the existing eight-year-old answers; it also doesn't correct the copy ctor param


Importing npm linked React JSX project/modules into AngularJS TypeScript module not working

Question: I am working on a proof-of-concept sample React framework/library that could be used in React applications, as well as an AngularJS framework wrapper around it so that it can be used as an AngularJS framework/library as well.
There are 2 projects:
sample-react-framework
sample-react-framework-wrapper (the AngularJS project)
Right now I have an npm link to the sample-react-framework project from the sample-react-framework-wrapper project.
sample-react-framework has 3 components - a navigation bar, banner, and side menu. These components are .jsx files.
sample-react-framework-wrapper has 3 components as well - the same 3 - which are just .ts wrappers that render the React elements.
I'm trying to import my React JSX modules into the TypeScript modules, and it appears to be working but is then throwing an error at the end anyway:
webpack result is served from http://localhost:8090/assets
content is served from C:\workspaces\UI\sample-react-framework-wrapper
10% 0/1 build modulests-loader: Using email@example.com
Hash: c4f0160d96f95001f727
Version: webpack 1.12.2
Time: 3233ms
              Asset     Size  Chunks             Chunk Names
sample.framework.js  42.5 kB       0  [emitted]  main
chunk    {0} sample.framework.js (main) 39.6 kB [rendered]
    [0] ./src/components/index.ts 112 bytes {0} [built]
    [1] ./src/components/banner/banner.ts 2.44 kB {0} [built] [1 error]
    [3] ../sample-react-framework/src/index.js 862 bytes {0} [built]
    [4] ../sample-react-framework/src/components/banner/banner.jsx 8.64 kB {0} [built]
    [5] ../sample-react-framework/~/classnames/index.js 1.12 kB {0} [built]
    [6] ../sample-react-framework/src/components/side-menu/side-menu.jsx 11.7 kB {0} [built]
    [7] ../sample-react-framework/src/components/navigation/navigation.jsx 9.81 kB {0} [built]
    [8] ./src/components/navigation/navigation.ts 2.37 kB {0} [built] [1 error]
   [10] ./src/components/side-menu/side-menu.ts 2.44 kB {0} [built] [1 error]
     + 2 hidden modules

ERROR in ./src/components/side-menu/side-menu.ts
(7,26): error TS2307: Cannot find module 'sample-react-framework'.

ERROR in ./src/components/navigation/navigation.ts
(7,28): error TS2307: Cannot find module 'sample-react-framework'.

ERROR in ./src/components/banner/banner.ts
(6,24): error TS2307: Cannot find module 'sample-react-framework'.

If you look above you can see it was able to get into and build the JSX files fine - but still throws errors that it can't find my framework in the end.
I've tried different things from Googling around, such as setting a resolve.fallback to be my path.join(__dirname, 'node_modules') - but that also failed (tried things from this issue: https://github.com/webpack/webpack/issues/784)
Unfortunately I'm really not sure what else to try at this point :(
Here's an example of how I am defining the JSX classes:
import React from 'react';
import classNames from 'classnames';

import SideMenu from '../side-menu/side-menu';

class Banner extends React.Component {

}

module.exports = Banner;

And the TS module:
/// <reference path="../../../typings/angularjs/angular.d.ts" />
/// <reference path="../../../typings/react/react.d.ts" />

import * as React from 'react';

import { Banner } from 'sample-react-framework';

angular
    .module('sampleFramework.banner', [])
    .directive('bannerComponent', bannerComponent);

function bannerComponent() {
    return {
        restrict: 'E',
        scope: {
            banner: '=',
            links: '='
        },
        replace: true,
        ...
    }
}

Does anyone have any idea what could be causing this?
Answer: I also posted an issue looking for help on the ts-loader project's GitHub issues: https://github.com/TypeStrong/ts-loader/issues/72
jbrantly got back to me quickly and informed me that the issue was I needed to define a typings file for my react framework in order for TypeScript to understand it - oops!

From your SO question:
import { Banner } from 'sample-react-framework';

The error here is that TypeScript is saying it doesn't understand sample-react-framework. TypeScript doesn't understand plain JS modules. It only understands TS modules or declaration files that describe the API of the JS module. Assuming you want to keep sample-react-framework as pure JS and not TypeScript, you'll need to create a definition file for it. For example...
// index.d.ts
import React from 'react';
export class Banner extends React.Component { }

Then in the package.json of sample-react-framework you could put:
"typings": "index.d.ts"

TypeScript should then be able to resolve the definition file and understand what you mean when you say import { Banner } from 'sample-react-framework';.

I've tested it out and defined the following index.d.ts in sample-react-framework:
import * as React from 'react';

interface Props { }
interface State { }

export class Banner extends React.Component<Props, State> { }
export class SideMenu extends React.Component<Props, State> { }
export class Navigation extends React.Component<Props, State> { }

The TS compiler was complaining about React.Component not matching the definition (and the React import not being '* as React') - but other than those minor tweaks his solution was exactly what I needed to fix my problem.
Answer: I've had the same problem. And I've located the problem in both ts-loader and typescript-loader (not in webpack itself) - as both were unable to resolve npm linked modules.
Also I was able to compile same code base with raw TypeScript compiler - which I am using as solution (also because other reasons).
But I think pointing resolve.falback to original/linked source did help.
Comment: My problem actually didn't end up being an issue with resolving the module but instead that I didn't have a typings file defined! I probably should have realized I needed that sooner! See my answer for more details.


How to render node content according to site theme after hook_node_insert/update?

Question: How can I get the actual HTML of the node when i am in hook_node_insert/update?
I would like to get the rendered HTML as it should appear in the site and save it somewhere else ...
I am working in drupal 7.
Answer: So first as the hook_node_update doc says:

Note that when this hook is invoked, the changes have not yet been
  written to the database, because a database transaction is still in
  progress. The transaction is not finalized until the save operation is
  entirely completed and node_save() goes out of scope. You should not
  rely on data in the database at this time as it is not updated yet.
  You should also note that any write/update database queries executed
  from this hook are also not committed immediately. Check node_save()
  and db_transaction() for more info.

Solutions:
There's a module for that: hook_post_action
There's also a short article about drupal_register_shutdown_function


What languages does Google Cloud Speech Automatic Punctuation Support?

Question: I have been playing around with Cloud Speech API and noticed that it returns punctuation for English but not for Japanese when enableAutomaticPunctuation is set to true.
Does anybody know What languages does Google Cloud Speech Automatic Punctuation Support?
Answer: Speech-to-Text can provide punctuation in audio transcription text for 'en-US' language only.
EDIT MAY 2020: Now, Speech-To-Text supports more languages
Comment: Note that this answer is now out of date; please [see my answer below](https://stackoverflow.com/a/61574211/6952495)
Answer: Update: as of May 2020, several languages have punctuation supported, including Japanese. They have a full list of languages they support and features that are supported for each language listed here.


How to reference xml data C#

Question: I have this xml file...
<xmlheufthdc src="http://172.16.7.50:8990/xml/heuft/hdc" version="1.0" time="2016-11-23T09:23:43.172Z">
<device name="2NG012550">
<entry name="count_total" status="valid">80849</entry>
</device>
</xmlheufthdc>

I have used c# and been able to access the data under entry name and entry status but i how do i make reference to the number 80849. ie what would i call it rather than name or status.
The code is as follows
public partial class Form1 : Form
{
    Form2 form2 = new Form2();

    public Form1()
    {
        InitializeComponent();
    }

    public string add1;
    public string read1;
    public string att11;
    public string att21;

    private void button1_Click(object sender, EventArgs e)
    {

    }

    public void configureToolStripMenuItem_Click(object sender, EventArgs e)
    {
      form2.Show();

    }

    private void button2_Click(object sender, EventArgs e)
    {
        string text1 = "";
        string text2;
        add1 = form2.add;
        read1 = form2.read;
        att11 = form2.att1;
        att21 = form2.att2;

        XmlReader xmlReader = XmlReader.Create(add1);
        while (xmlReader.Read())
        {
            if ((xmlReader.NodeType == XmlNodeType.Element) && (xmlReader.Name == read1))
            {
                if (xmlReader.HasAttributes)
                    text1=(xmlReader.GetAttribute(att11) + ": " + xmlReader.GetAttribute(att21));
                textBox1.Text = text1;
            }

        }
    }
}

The att items are entred in another form and this is where i would enter.
read1 being "entry" and att1 being "name" and att21 being "status".
Sorry im new to this any information would be much appreciated.
Thanks Alistair
Comment: Share the code you're using to "access" the xml. Are you using XmlDocument? XDocument? XPath syntax?
Comment: Hey, The code is as follows
Answer: The number can be accessed by using the InnerText property of XmlNode class.
Comment: Hey, Can you expand a little on this please i have added my code above.
Comment: XmlNodeList CNodes = xn.SelectNodes("xmlheufthdc/device/entry");
        foreach (XmlNode node in CNodes)
        {
            string na = example["Name"].InnerText;
Comment: Try this
XmlNodeList CNodes = xn.SelectNodes("xmlheufthdc/device/entry"); foreach (XmlNode node in CNodes) { string number = node.InnerText};
Comment: Thanks I'll give that a try :)
Comment: Do I replace the existing XMLReader I have?
Comment: Can you please try ReadInnerXml() of the XmlReader class inside the if loop like this xmlReader.ReadInnerXml()

How to reference xml data C#


Extracting an array from a dataframe column that contains an array

Question: I am using thorns and cochlea to generate a spiketrain. The result is in the form of a pandas.DataFrame in the form, that the column 'spikes' contains the array of spiketimes that I need.
DataFrame generated by thorns
When I try to extract it with
a = df.as_matrix(['spikes'])

the resulting matrix will always look like this:
a = [[array([1,2,3])][array([4,5,6])]]

to further use the data, i need the form:
a= [[1,2,3][4,5,6]]

how can I delete the array() part?
This is the code I use:
import cochlea

import thorns.waves as wv

#generating the spiketrain

sound = wv.ramped_tone(fs=100e3,freq=500,duration=0.3,dbspl=60)
spiketrain=cochlea.run_zilany2014(sound,fs=100e3,anf_num=(2,0,0),cf=500,seed=0,species='human')
print spiketrain

#trying to extrakt spiketime information
a = spiketrain.as_matrix(['spikes'])
print 'a='
print a

Comment: What is the actual shape of a?
Comment: If I use a.shape in my example a  is an array of the shape (2,1) the problem is the shape of the stored Data, which does not only contain the values but also the datatype in the form array([1,2,3])
Comment: Oh, if the shape is (2,1) then reshaping will not work. I started from a different initial array. I will try to look at it afterwards.
Comment: What is the output you get using `spiketrain['spikes'].values`? Is it the desired shape, if not, what is the shape?
Comment: With values it is still the shape array([1,2,3])
Comment: But then the individual entrys a[0] look normal at least
Answer: This is one way:
import pandas as pd, numpy as np

df = pd.DataFrame({'A': [np.array([1,2,3]), np.array([4,5,6]), np.array([7,8,9])]})

res = np.array(df['A'].values.tolist())

# array([[1, 2, 3],
#        [4, 5, 6],
#        [7, 8, 9]])

res2 = list(map(list, df['A']))

# [[1, 2, 3],
#  [4, 5, 6],
#  [7, 8, 9]]

Comment: It still looks the same, but I think I can use it now in the later model. Thanks
Comment: @Eli.K, sure - I added an alternative which may help you.
Comment: Yes, that is better, the second one generates the normal array form


Include insignificant predictor with low variance?

Question: In my regression, I have a predictor (measured in proportions) with very low variance (.002). It had no significant effect on the outcome due to a very high standard error of the regression coefficient.
When reporting on the effect in a paper, is it right to say there was no effect of my predictor in my study? Even though I know the lack of effect is most likely due to the low variance, and I add that thought in the paper? It feels like I might mislead the non-attentive readers, or I am reporting useless stuff.
Maybe it is best practice to discard this predictor from the model, and note in the paper that it was impossible to test this effect due to the data limitations?
And as extra I wanted to ask if it is possible to get a lower variance when taking the log of the values? I observed this with my variable.
Comment: The decision to exclude the variable should have been made before looking at the statistical significance of the variable.  Otherwise, biased standard errors of all the coefficients will result.
Comment: In general, excluding variables because of observed $\hat{\beta}$ or $P$-values leads to multiple biases in the model.  Including the variable does not lead to a bias.  If on the other hand you excluded a variable without unblinding yourself to $Y$, the standard errors will not be biased low.
Comment: Whether .002 is "low" depends on the scaling of the regressor. If you measure something in meters, its variance may be 2000, while if you recode the exact same data to kilometers, the variance will suddenly be .0002. There is really no good answer to your question without knowing the context and how your regressor could have an effect.
Comment: @StephanKolassa is right about the scaling issue, but if the variance really is very low in sensible terms, then I think you should delete it from the model because it can't make a difference. The ultimate would be a variance of 0 (that is, all subjects have the same value) and then the coefficient is really meaningless.
Comment: You are right! I edited, stating the used scale is a proportion.
Comment: @PeterFlom, you might give your comment as an answer, and I can approve? Otherwise this question stays unanswered.
Comment: True, I am working hopelessly disorderly. And I would not have wasted time focusing on the literature on this variable. But I have learned!
And apart from that, @FrankHarrell you mean including it will bias all the SE's? Because how can leaving it out afterwards give other SE's than excluding it immediately?
Comment: The observation that the standard error of the estimate was high (How high?) can be a sign of numerical instability as might occur with complete separation. You may need to use tabular investigation to identify and characterize the impact of the predictor on the outcome.
Answer: @StephanKolassa is right about the scaling issue, but if the variance really is very low in sensible terms, then I think you should delete it from the model because it can't make a difference. The ultimate would be a variance of 0 (that is, all subjects have the same value) and then the coefficient is really meaningless.


ABEM adding modifiers directly to an element?

Question: I'm beginning to learn more about CSS formatting and now I've picked up ABEM to use along with SCSS to develop a WordPress site.
Is it then valid to add a modifier directly to let's say an h1 block? Like this:
HTML

To make the text green.

CSS
.-green {
 color: green;
}

Or do I need to add a block or an element before to modify it instead?
Like this:
HTML

To make the text green.

CSS
.a-heading_text.-green {
 color: green;
}

Comment: Ah no, the modifier floats on its own. This is so you don't need to write out the block element before, and then just use the modifier on its own. Like to centre stuff instead of saying ```a-heading_text-green``` you can just use the modifier ```-green``` on it. But yeah I think I just answered my own question.
Answer: ABEM is a BEM variant and a lonely modifier wouldn't be BEM-compliant. Your second option is the right one: you "need to add a block or an element before to modify it instead".
If you want to create a standalone helper for a simple purpose, then it is not a modifier but a block:

To make the text green.

With the CSS:
.green {
  color: green;
}

This helper block can of course be mixed with other blocks or elements. The following code is valid:

To make the heading text green.

Comment: Ah okay so if it has no other block or element in front of it and I need it to turn ex. green then It becomes a block, because a modifier can't be on its own in an elements class right?


Connecting to a python socket behind a router

Question: I have a Python script on my server which opens a socket that can be connected to from anywhere.
It works on my digitalocean test server that has a public IP as shown by ifconfig.
It does not work on my work server which is behind a router and perhaps a firewall (ifconfig shows a private IP)
Do I need to mess with the router settings and allow port forwarding?
I have installed apache as my understanding is that it's needed to do anything with web (like sockets), although I am not hosting any webpages or browser based stuff, just the socket.
Thanks
Answer: You have a couple of options for allowing external access to your server with private IP:

Forwarding a port from the router/firewall, which protects this server. How to do it depends on the type of the router/firewall.
Using ngrok to circumvent the firewall.
Build yourself VPN connection into the server's LAN - again on the router/firewall. Again, depends on the type of the router/firewall.
Run some king of proxy on the router/firewall, which proxies the incoming connections to the internal IP of your server. Which proxy depends on the protocol you are running, for HTTP i suggest haproxy or nginx.

Depends on what do you need to achieve.
If you want permanent, worldwide access to the service you are running, i suggest number 1 or 4.
If you want to just do some temporary tests, number 2 or 3.


How to use the Features API to enable a feature?

Question: So I looked at the features API, and in order to enable a feature, they use this code:
function hook_pre_features_enable_feature($component){
};

So I go in and add this:
function mysite_pre_features_enable_feature($component){
    $component = 'roles';
};

My Feature is already there, but it never gets enabled. Why is this?
Answer:
in order to enable a feature, they use this code

That's not accurate. The hook function is actually:

Invoked on a Feature module before that module is enabled.

It's not involved with the action of enabling the feature, it's just a listener to enable it to run some code just before something else enables it.
Features are just modules, and to enable one you use the same method as if you were just enabling a module:
module_enable(['foo']);


Como é possível um mesmo endereço de memória ter 2 valores diferentes ao mesmo tempo?

Question: Me surgiu uma dúvida sobre o comportamento do qualificador de tipo const do C++.
Eu estava testando o quanto uma variável declarada como constante está protegida de alterações. Para isso eu tentei alterar o seu valor usando um ponteiro não constante.
E aí surgiu um comportamento estranho pra mim. Eu consigo alterar e printar o valor apontado pelo ponteiro, mas a variável original continua com o valor constante. É como se o mesmo endereço de memória tivesse 2 valores... Como isso é possível?
#include <iostream>

using namespace std;

int main()
{
    const int a = 1;
    int *p1 = (int*) &a;

    (*p1) = 42;

    cout << p1 << " " << (int) *p1 << endl;
    cout << &a << " " << (int) a << endl;

    return 0;
}

Output:
0x7fff46c6b00c 42
0x7fff46c6b00c 1

Comment: Você ta modificando uma constante escrevendo num endereço de memória reservado para tal. Acredito que esteja caindo num Undefined Behavior, já que você "enganou" o compilador.
Comment: Nem sempre o que você escreve e a mesma saída linha por linha no compilador, ele faz diversas otimizações pra seu código rodar teoricamente da melhor maneira possível. inclusive em alguns compiladores tem como desativar essas funções de otimização
Answer:
É como se o mesmo endereço de memória tivesse 2 valores... Como isso é possível?

A resposta curta é: Isso não é possível. Acontece que quando você mandou imprimir o valor da variável a seu programa não leu novamente na memória qual valor guardado lá, ele retornou o valor direto.
Esse resultado é devido a uma otimização que o compilador fez. Quando você usa const há possibilidades de otimização de desempenho que podem ser exploradas porque o compilador sabe que você não vai mudar o valor dessa variável. Mas aí você foi lá e deu uma rasteira no compilador.

Vamos a Investigar
Testei compilar com o clang e o sanitizer para detectar undefined behaviour, mas ele não viu problemas. Mesmo assim não sei se podemos afirmar que não é undefined behaviour.
Eu testei compilar com gcc++ e com o clang++, ambos passando as opções -g -O0, e mesmo assim o resultado foi o mesmo. Ou seja, é uma otimização tão "básica" (por que não fazer?) que o compilador está fazendo mesmo quando você pode o mínimo possível de otimizações com a opção -O0.
Vamos olhar o assembly gerado pelo compilador para confirmar. Para isso eu usei o código abaixo para evitar carregar a biblioteca iostream (mais linhas no assembly). Note que agora estamos interessados no valor de retorno da main.
int main() {
  const int a = 5;
  int *p1 = (int *)&a;

  (*p1) = 9;

  return a;
}

Com o const esse programa tem um valor de retorno de 5 (errado) e sem o const de 9 (correto). Agora vamos ver o assembly (você pode passar a opção -S na hora de compilar para ele parar no passo de assembly).
Com o const o g++ gerou o seguinte assembly na minha máquina (compilado com g++ -O0 -S main.cpp.
    .file   "main.cpp"
    .text
    .globl  main
    .type   main, @function
main:
.LFB0:
    .cfi_startproc
    pushq   %rbp
    .cfi_def_cfa_offset 16
    .cfi_offset 6, -16
    movq    %rsp, %rbp
    .cfi_def_cfa_register 6
    subq    $32, %rsp
    movq    %fs:40, %rax
    movq    %rax, -8(%rbp)
    xorl    %eax, %eax
    movl    $5, -20(%rbp)
    leaq    -20(%rbp), %rax
    movq    %rax, -16(%rbp)
    movq    -16(%rbp), %rax
    movl    $9, (%rax)
    movl    $5, %eax
    movq    -8(%rbp), %rdx
    xorq    %fs:40, %rdx
    je  .L3
    call    __stack_chk_fail@PLT
.L3:
    leave
    .cfi_def_cfa 7, 8
    ret
    .cfi_endproc
.LFE0:
    .size   main, .-main
    .ident  "GCC: (Arch Linux 9.3.0-1) 9.3.0"
    .section    .note.GNU-stack,"",@progbits

Agora vamos remover o const e ver o assembly gerado.
    .file   "main.cpp"
    .text
    .globl  main
    .type   main, @function
main:
.LFB0:
    .cfi_startproc
    pushq   %rbp
    .cfi_def_cfa_offset 16
    .cfi_offset 6, -16
    movq    %rsp, %rbp
    .cfi_def_cfa_register 6
    subq    $32, %rsp
    movq    %fs:40, %rax
    movq    %rax, -8(%rbp)
    xorl    %eax, %eax
    movl    $5, -20(%rbp)
    leaq    -20(%rbp), %rax
    movq    %rax, -16(%rbp)
    movq    -16(%rbp), %rax
    movl    $9, (%rax)
    movl    -20(%rbp), %eax
    movq    -8(%rbp), %rdx
    xorq    %fs:40, %rdx
    je  .L3
    call    __stack_chk_fail@PLT
.L3:
    leave
    .cfi_def_cfa 7, 8
    ret
    .cfi_endproc
.LFE0:
    .size   main, .-main
    .ident  "GCC: (Arch Linux 9.3.0-1) 9.3.0"
    .section    .note.GNU-stack,"",@progbits

Bom, eu não entendo quase nada de assembly, mas se olharmos o diff desses dois códigos a única diferença é em uma linha (22). Com o const a linha 22 é
movl    $5, %eax

e sem o const a linha 22 se torna
movl    -20(%rbp), %eax

Viu a diferença? Quando a variável a não é const o valor dela, como qualquer outra variável é lido da memória quando precisamos dele (-20(%rbp) (o -20 aqui é um ofsset em relação ao ponteiro, no caso rbp que é um ponteiro de frame indicando que essa variável esta na stack) que é onde a variável a foi armazenada), mas quando ela é const o assembly gerado possui o valor literal da variável a quando ela foi declarada, que é uma das maneiras de como o g++ trata constantes, com maiores otimizações o compilador simplesmente coloca o valor literal da constante sempre que ele for usando, assim nunca consultando a memoria, trazendo grandes benefícios enquanto a eficiência.
Para maiores informações você pode ler esse FAQ, também vale checar a documentação e essa pergunta no SO tem várias respostas interessantes.

Fato interessante: Recentemente encontrei essa pergunta no stackoverflow sobre o std::launder (eu não conhecia) que serve para você pegar o ponteiro de um objeto para o qual você passou o ponteiro. Resolvi testar com o código aqui e percebi que *std::launder(&a) ou simplesmente *(&a) vai ler o valor correto na variável a porque primeiro pega o endereço de a e depois ver o valor armazenado nesse endereço.
Comment: Tentar modificar o valor de um objeto que foi inicialmente declarado como constante é considerado comportamento indefinido pela standard. Então, mesmo usando `std::launder`, o programa ainda estaria errático. Aqui está o parágrafo relevante: http://eel.is/c++draft/dcl.type.cv#4
Comment: Muito interessante esse comportamento do compilador! Obrigado pela resposta!


Trouble With a  Not Rotating Where I Want It To

Question: I'm relatively new to html and css so I apologise in advance if my code is sloppy and/or redundant.
http://jsfiddle.net/t16uf9sv/1/
As can be seen in the linked fiddle, I'm in the middle of making an interactive menu button that will eventually expand to reveal prompts to navigate the site. For now though, I've just been trying to get the vertical bar of the plus to rotate 90 degrees to form a minus when clicked. [ + ] ---> [ - ].
When trying to perform this with the attached code, the element just doesn't go where I want it to.
I have a feeling that the problem may lie in how I went about centering the bar elements (.vertical, .horizontal) within the square (.menu).
HTML:

CSS:
* {
    margin: 0;
    padding: 0;
}

body {
    position: relative;
}

body {
    background: #212121;
}

.nav {
    position: fixed;
    margin-top: 326px;
    margin-right: 965px;
    margin-left: 250px;
}

.menu {
    height: 50px;
    width: 50px;
    border: 2.5px solid #ffffff;
    -o-transition:.2s;
    -ms-transition:.2s;
    -moz-transition:.2s;
    -webkit-transition:.2s;
    transition:.2s;
}

.plus {
    position: relative;
    padding: 25px;
}

.vertical {
    background: #ffffff;
    height: 25px;
    width: 2.5px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    -o-transition:.2s;
    -ms-transition:.2s;
    -moz-transition:.2s;
    -webkit-transition:.2s;
    transition:.2s;
}

.horizontal {
    background: #ffffff;
    height: 2.5px;
    width: 25px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    -o-transition:.2s;
    -ms-transition:.2s;
    -moz-transition:.2s;
    -webkit-transition:.2s;
    transition:.2s;
}

.menu:hover {
    background: #ffffff;
}

.menu:hover .vertical, .menu:hover .horizontal {
    background: #212121;
}

.menu:active .vertical {
    -webkit-transform: rotate(90deg);
    -moz-transform: rotate(90deg);
    -o-transform: rotate(90deg);
    -ms-transform: rotate(90deg);
    transform: rotate(90deg);
}

I'm starting to lose my mind trying to figure this out, so if anyone could help in any way I would greatly appreciate that.
Answer: The problem is that you're telling it to simply rotate 90degrees, which is what it's doing. When it rotates, it loses it's position of top:50% and left:50%, you need to redefine those in your :active snippet:
.menu:active .vertical {
    -webkit-transform: rotate(90deg);
    -moz-transform: rotate(90deg);
    -o-transform: rotate(90deg);
    -ms-transform: rotate(90deg);
    transform: rotate(90deg);
}

just add:
 top: 25%;
  left: 46%;

And it will do exactly what you need :)

Working Fiddle Here
 .menu:active .vertical {
        -webkit-transform: rotate(90deg);
        -moz-transform: rotate(90deg);
        -o-transform: rotate(90deg);
        -ms-transform: rotate(90deg);
        transform: rotate(90deg);
        top: 25%;
        left: 46%;
    }

Answer: One way to do this is just add opacity: 0, and change the top and left attributes in the css under menu:active .vertical:

* {
    margin: 0;
    padding: 0;
}

body {
    position: relative;
}

body {
    background: #212121;
}

.nav {
    position: fixed;
    margin-top: 10px;
    margin-right: 965px;
    margin-left: 250px;
}

.menu {
    height: 50px;
    width: 50px;
    border: 2.5px solid #ffffff;
    -o-transition:.2s;
    -ms-transition:.2s;
    -moz-transition:.2s;
    -webkit-transition:.2s;
    transition:.2s;
}

.plus {
    position: relative;
    padding: 25px;
}

.vertical {
    background: #ffffff;
    height: 25px;
    width: 2.5px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    -o-transition:.2s;
    -ms-transition:.2s;
    -moz-transition:.2s;
    -webkit-transition:.2s;
    transition:.2s;
}

.horizontal {
    background: #ffffff;
    height: 2.5px;
    width: 25px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    -o-transition:.2s;
    -ms-transition:.2s;
    -moz-transition:.2s;
    -webkit-transition:.2s;
    transition:.2s;
}

.menu:hover {
    background: #ffffff;
}

.menu:hover .vertical, .menu:hover .horizontal {
    background: #212121;
}

.menu:active .vertical {
    -webkit-transform: rotate(90deg);
    -moz-transform: rotate(90deg);
    -o-transform: rotate(90deg);
    -ms-transform: rotate(90deg);
    transform: rotate(90deg);
    top: 25%;
    left: 40%;
    opacity: 0;
}

Answer: The problem is that the rotate is relative to the position before the
transform:translate(-50%, -50%);
that you used to center it (if you remove this you will notice it rotates correctly but in the wrong place).
I would say the best thing to do here is not use translate in positioning, as the size is fixed. I only use it for variable size elements.
Instead just remove the transform, set the dimensions to fixed sizes, as so:
.vertical {
    background: #ffffff;
    height:50%;
    top:25%;
    position: absolute;
    width:5%;
    left:47.5%;
    -o-transition:.2s;
    -ms-transition:.2s;
    -moz-transition:.2s;
    -webkit-transition:.2s;
    transition:.2s;
}

I estimated this so it was about the same as yours. Also this way it is relative to the screen size (although it is small enough to not matter really).


Magento subpages give 404

Question: I just restored our Magento website on a different server running apache2 on ubuntu. The home page pulls up just fine but if I try to go to any other page, I get a 404.
Permissions

All files are 660
All directories are 770 All files and directories
All files and directories belong to the www-data group

Things I've Tried

check all the website and store ids
add /index.php/ between the domain and page path
clear temporary files

Nothing appears in the log files other than the standard 404 lines in the access.log and error.log.
apache2 .conf file
<VirtualHost *:80>
    ServerAdmin email@example.com
    ServerName mydomain.com

    DocumentRoot "/var/www/default/"
    <Directory />
        Options FollowSymLinks
        AllowOverride None
    </Directory>
    <Directory "/var/www/default/">
        Options Indexes FollowSymLinks MultiViews
        AllowOverride All
        Order allow,deny
        allow from all
        php_admin_flag engine on
        php_admin_value open_basedir none
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/error.log

    # Possible values include: debug, info, notice, warn, error, crit,
    # alert, emerg.
    LogLevel warn

    CustomLog ${APACHE_LOG_DIR}/access.log combined

</VirtualHost>

.htaccess
DirectoryIndex index.php

<IfModule mod_php5.c>
    php_value memory_limit 10G
    php_value max_execution_time 1800000
    php_flag magic_quotes_gpc off
    php_flag session.auto_start off
    php_flag suhosin.session.cryptua off
    php_flag zend.ze1_compatibility_mode Off
</IfModule>

<IfModule mod_security.c>
    SecFilterEngine Off
    SecFilterScanPOST Off
</IfModule>

<IfModule mod_deflate.c>
</IfModule>

<IfModule mod_ssl.c>
    SSLOptions StdEnvVars
</IfModule>

<IfModule mod_rewrite.c>
    Options +FollowSymLinks
    RewriteEngine on

    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
    RewriteCond %{REQUEST_URI} !^/(media|skin|js)/
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-l
    RewriteRule .* index.php [L]
</IfModule>

AddDefaultCharset Off

<IfModule mod_expires.c>
    ExpiresDefault "access plus 1 year"
</IfModule>

Order allow,deny
Allow from all

<Files RELEASE_NOTES.txt>
    order allow,deny
    deny from all
</Files>

Log File Output
==> /var/log/apache2/oem1-error.log <==
[Tue Oct 15 12:32:21 2013] [error] [client 192.168.0.4] File does not exist: /var/www/gearhead_oem1/admin

==> /var/log/apache2/oem1-access.log <==
192.168.0.4 - - [15/Oct/2013:12:32:21 -0600] "GET /admin HTTP/1.1" 404 507 "-" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.69 Safari/537.36"

Answer: Php requires different permissions. Magento recommends the following:
find . -type d -exec chmod 775 "{}" \;
find . -type f -exec chmod 664 "{}" \;

Comment: Thank you. Giving more permission to the public doesn't change anything. If it was a permissions issue, it would have been a permissions error. Just for kicks, I changed the permissions to 775 and 664. No go.
Answer: Sounds like a problem with rewrites. In Ubuntu:
Run:
a2enmod rewrite
apt-get install php5-curl

and then:
service apache2 restart

mod_rewrite and php-curl will now be enabled!
Comment: I also added php5-curl to your answer. a2enmod rewrite got me most of the way there but I was still getting some curl errors.

Magento subpages give 404


How to setup Backand real time communication is a Ionic2 app?

Question: I can't find any example on how to do this.
Thanks,
Guillaume
Answer: This one is for ionic, its broadcasting what the user sees on his device youtube app to a desktop browser


Diffrent settings for diffrent file types with one printer queue. Windows server 2012

Question: I have been tasked with doing the following:
Using only one printer queue, make sure .docx gets printed with "1-sided print" while .pdf gets printed with "2-sided print".
Is this possible without additional software? If so could i get some pointers...
Only requirement is that the end user only needs to have one queue selected at all time.
Software and hardware related to the printer:
Xerox colorqube 9302
Windows server 2012 R2
Safecom G4
Answer: @Jakodns, if a commercial solution is not a problem for you. (There is a 30-day trial)
Basic video tutorial: https://www.youtube.com/watch?v=wPKoTD-nRWs&list=PLDF2C2AD95B2B2FC2&index=27
The idea is that you simply create a profile with 2 printer channels, each time the same printer. We will configure channel 1 to print for .docx files and channel 2 for .pdf files.

Download and install the Ricoh Print&Share trial
Open the software and go to the [Change] button on the upper right corner
Click [New] to create a new Profile.
Give the profile a name and add 2 channels: Channel 1 -> Printer and Channel 2 -> Printer
Configure Printer Channel 1 for .docx (so simplex Printing should be enabled)
Do the same for Printer Channel 2 but configure it for .pdf files in Duplex.
Now in the [Profile] dialog where you added channels there is also a [Trigger points] button, click it.
There, for both channels, enable the option [Only execute when document is printed from the following application]. You can click the [...] button to change or add regular expressions.
Click OK to close all dialogs and at the [Profiles] dialog, select your newly created dialog, set it as [Default] and click [Use and Close].

And that's it. The only requirement is that if you print that there is something in the print job name that you know that .pdf or .docx files are being printed.
For example if you print from notepad you often see "Untitled - Notepad". This name "Notepad" is the name of the application and you could use it in your regular expression to detect that it was printed from "Notepad". So if you are lucky you will maybe see that printing a .docx file contains "Word" or ".docx" in the name to use for your detection. But that depends on how each application prints.
If you know for example that each pdf file is always starting with "My Report" as in "My Report 04545 - 2016 06 ABC" you could use "My Report" maybe for your detection. This is fully up to you, be creative :-)
If you are not familiar with regular expressions, it is basically a language to search terms in a text/string.
Hope this helps!
Comment: I'll look into this. Looks like something I could use.
Answer: Still doesn't seem possible to solve from the serverside, maybe possible with some additonal software.
Solved it by using Xeroxs printer settings for diffrent program (Single sided when printing from adobe acrobat and dubble sided when printing form word). Since it is only four clients this solution works, but would still like to find a real fix for it.


Volatility forecasting in presence vs. absence of ARCH effects

Question: Suppose I have a time series $x_t$ with no autocorrelation (consider for example log return of stock prices). If $x_t^2$ is autocorrelated, we can model the series with a GARCH model and provide a good forecast of the future volatility. But what if $x_t^2$ is not autocorrelated?

What can we say on the obtained volatility prediction?
Does it mean that the predicted volatility is completely random or that the volatility is simply the mean of the historical volatility?
Is the volatility forecast better in absence or in presence of autocorrelation in $x_t^2$?

EDIT:
My impression is that short time forecast is more reliable in presence of autocorrelation in $x_t^2$, while long term forecast is more reliable in absence of it.
Comment: You can say that one forecast is better than the other when the object being forecast is the same. However, when you have differently behaved processes (one with ARCH effects and one without), it is not straightforward to say that one forecast is better than the other.
Comment: I would say that a long term forecast should converge to the mean of the historical variability and this should be always true if the autocorrelation of the squared residual is 0. In real applications I think is unlikely for example that the volatility grows indefinitely
Answer:
What can we say on the obtained volatility prediction?

If the $x_t^2$ is non-autocorrelated, the estimated GARCH model (consider order (1,1) for simplicity)
$$ \sigma_t^2 = \omega + \alpha x_{t-1}^2 + \beta \sigma_{t-1}^2 $$
would have $\hat\omega \approx \hat\sigma^2$, $\hat\alpha \approx 0$, and $\hat\beta \approx 0$, where $\hat\sigma^2$ is the (unconditional) sample variance. Alternatively, you could probably get $\hat\omega \approx 0$, $\hat\alpha \approx 0$, $\hat\beta \approx 1$ with $\hat\sigma_t^2 \approx \hat\sigma^2$ for all $t$. In both cases the fitted values would be approximately constant and the GARCH model would have negligible effect as compared with the alternative of assuming constant variance. The predicted values would also be roughly constant and roughly equal to the fitted in-sample variance $\hat\sigma^2$.

Does it mean that the predicted volatility is completely random or that the volatility is simply the mean of the historical volatility?

It is the latter.

Is the volatility forecast better in absence or in presence of autocorrelation in $x_t^2$?

You can say that one forecast is better than another when the object being forecast is the same. However, when you have differently behaved processes (one with ARCH effects and one without), it is not straightforward to say whether one forecast is better than the other. For starters, you can ponder upon questions like:

Which of the two series is more predictable? (Then you need to define predictability.)
Which of the two series is likely to be predicted more accurately with a GARCH model? (Then you need to define how to compare predictive accuracy for two different targets.)

You could choose to compare absolute predictive accuracy across the cases based on some loss function, e.g. square loss. Then you would ask, on average, does one prediction yield a smaller squared loss than the other (for their respective targets)? (Checking this may be nontrivial because time-varying conditional variance is measured with a large error, unless you have data of higher frequency and can obtain a more accurate measure of realized variance.)
Now to address the question more directly, take a sample of fixed size and suppose you know the true model of the conditional variance (but you do not know its coefficient values which need to be estimated). The simpler the conditional variance model, the more precisely you will be able to estimate the model and the more precise your forecasts will be. That tells that a constant conditional variance should be easier to estimate and predict than, say, conditional variance of GARCH type. However, if you allow for stochastic conditional variance, estimation and forecast precision will also (inversely) depend on the error variance in the conditional variance equation. Moreover, when you do not have the true model the picture is less clear.

EDIT: My impression is that short time forecast is more reliable in presence of autocorrelation in $x_t^2$, while long term forecast is more reliable in absence of it.

As mentioned above, when you know the true model you would prefer a simple process to a more complicated one, and low error variance (in the conditional variance equation) to a high one. This should be true both for short- and long-term forecasts.


Adding a new field in SQLite in android

Question: As I said before, im very much new to android and now i faced a very troubling poblem.
I have a database and i need to add a new field in the table. I don't know much of android and java..
So please guys, a little help will be appreciated...
Here's my code for the database:
public class MySQLiteHelper extends SQLiteOpenHelper {

  public static final String TABLE_COMMENTS = "comments";
  public static final String COLUMN_ID = "_id";
  public static final String COLUMN_COMMENT = "comment";

  private static final String DATABASE_NAME = "commments.db";
  private static final int DATABASE_VERSION = 1;

  // Database creation sql statement
  private static final String DATABASE_CREATE = "create table "
      + TABLE_COMMENTS + "(" + COLUMN_ID
      + " integer primary key autoincrement, " + COLUMN_COMMENT
      + " text not null);";

  public MySQLiteHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
  }

  @Override
  public void onCreate(SQLiteDatabase database) {
    database.execSQL(DATABASE_CREATE);
  }

  @Override
  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    Log.w(MySQLiteHelper.class.getName(),
        "Upgrading database from version " + oldVersion + " to "
            + newVersion + ", which will destroy all old data");
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_COMMENTS);
    onCreate(db);
  }

}

This is for the functions for the database:
    public class CommentsDataSource {

  // Database fields
  private SQLiteDatabase database;
  private MySQLiteHelper dbHelper;
  private String[] allColumns = { MySQLiteHelper.COLUMN_ID,
      MySQLiteHelper.COLUMN_COMMENT };

  public CommentsDataSource(Context context) {
    dbHelper = new MySQLiteHelper(context);
  }

  public void open() throws SQLException {
    database = dbHelper.getWritableDatabase();
  }

  public void close() {
    dbHelper.close();
  }

  public Comment createComment(String comment) {
    ContentValues values = new ContentValues();
    values.put(MySQLiteHelper.COLUMN_COMMENT, comment);
    long insertId = database.insert(MySQLiteHelper.TABLE_COMMENTS, null,
        values);
    Cursor cursor = database.query(MySQLiteHelper.TABLE_COMMENTS,
        allColumns, MySQLiteHelper.COLUMN_ID + " = " + insertId, null,
        null, null, null);
    cursor.moveToFirst();
    Comment newComment = cursorToComment(cursor);
    cursor.close();
    return newComment;
  }

  public void deleteComment(Comment comment) {
    long id = comment.getId();
    System.out.println("Comment deleted with id: " + id);
    database.delete(MySQLiteHelper.TABLE_COMMENTS, MySQLiteHelper.COLUMN_ID
        + " = " + id, null);
  }

  public List<Comment> getAllComments() {
    List<Comment> comments = new ArrayList<Comment>();

    Cursor cursor = database.query(MySQLiteHelper.TABLE_COMMENTS,
        allColumns, null, null, null, null, null);

    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {
      Comment comment = cursorToComment(cursor);
      comments.add(comment);
      cursor.moveToNext();
    }
    // Make sure to close the cursor
    cursor.close();
    return comments;
  }

  private Comment cursorToComment(Cursor cursor) {
    Comment comment = new Comment();
    comment.setId(cursor.getLong(0));
    comment.setComment(cursor.getString(1));
    return comment;
  }
}

and this is the other class which the above class uses:
public class Comment {
  private long id;
  private String comment;

  public long getId() {
    return id;
  }

  public void setId(long id) {
    this.id = id;
  }

  public String getComment() {
    return comment;
  }

  public void setComment(String comment) {
    this.comment = comment;
  }

  // Will be used by the ArrayAdapter in the ListView
  @Override
  public String toString() {
    return comment;
  }
}

All this code works fine when I'm working with only one field(i.e. the comment) but
I want to add three new fields named: "Address", "Age", "Gender" and if possible change the DB name and i just can't seem to be able to alter it in the right way to get what i want.
Please tell me the right alterations needed.
PLEASE Help me on this!
Thanks in advance,
Waiting for your reply...
Comment: Do you really need to update an existing database? I assume your app is not used yet, so can't you just create a new database that suits your needs? Or is that actually what you are asking?
Comment: I must UPDATE the database.
Comment: :( dont have any other choice
Comment: If i upgrade the database with the new settings will it work then?
Answer:
if possible change the DB name and i just can't seem to be able to
  alter it in the right way to get what i want. Please tell me the right
  alterations needed.

There are two ways:

implement correctly onUpgrade() method of SQLiteOpenHelper class (if you need update)
Just update your database class (modify DDL statement e.q. add new columns and change db
name if you want) and before install updated application to your device, delete
application's data (in device it's in settings under applications
manager). That will delete all data connected to your application
(databases, preferences, etc.)

Look at

Android: upgrading DB version and adding new table
Comment: I started android programming just about a week ago so, i dont know its complete stucture yet... :(
Comment: @ShanzidSHaiham i added link in my origin answer.
Comment: Im really sorry for beign such a pain in the ass but can you please change my code and post it please..
Comment: and which one is the DDL statement?
Comment: @ShanzidSHaiham create table statement.
Answer: Create new columns in table like this:
String Comment_table = String.format("CREATE TABLE %s " +
                "(%s INTEGER PRIMARY KEY AUTOINCREMENT ," +
                " %s TEXT , %s TEXT , %s TEXT ," +
                " %s TEXT  )",

                Comment_Table,
                Comment_ID ,
                Comment , Address , Age ,
                Gender );

(Here, Column names are Static String Declared as Class Variables).
Comment: where do i put this? O.o
Comment: where in the helper class?!
Comment: Ooo Boy!! First go and check out your existing code and learn what's happening in it. where database is created and where table create statement executes and then try to change in DB.
Comment: you are a kid or 50 years old man that doesn't change anything. if you  want to learn something then you need to learn by your own. I have showed you the way. now its on you where you want it. see your code and do as they are doing with your own class. so that you can make it,
Comment: Thats good. As answer to your question if you want to create table when database is created then you can put this statement in onCreate() method of SQl Helper class. but you want to make it later than you can execute this statement in any method.
Comment: My problem is solved. I didnt know that if the database verson already existed in the device it would not execute the onCreate method again.
Comment: I didn't know that you needed to upgrade the database version to save new changes
Comment: ofcourse... or you can create new database every time to make changes.
Comment: ya..i didnt know that before...now i know

Adding a new field in SQLite in android


Can zero covariance and zero expectation imply zero conditional expectation?

Question: Let $x$ and $\epsilon$ are two random variables. If $$Cov(x, \epsilon)=0$$ and $$E[\epsilon]=0,$$ can that lead to $E[\epsilon|x]=0?$
Comment: it's not a homework. Some papers only check that if $Cov(x, \epsilon)$ is zero for OLS assumption which specifies that $E[\epsilon|x]=0$ in lots of formal literatures.
Comment: Related:  https://stats.stackexchange.com/questions/486169/random-sampling-weak-and-strong-exogenity/486253#486253
Comment: Welcome to CV. Since you're new here, you may want to take our tour, which has information for new users.  Since this looks like homework (apologies if it's not), please add the [self-study] tag and read its wiki. Then tell us what you understand thus far, what you've tried & where you're stuck. We'll provide hints to help you get unstuck. Please make these changes as just posting your homework & hoping someone will do it for you is grounds for closing. If this is self-study rather than homework, let us know, and... it's still a good idea to show us what you've tried.
Answer: This figure is a complete answer.

For those who would like a gloss on the figure though, notice that in this sample of 1,000 values of $(X,\varepsilon),$

"$\operatorname{Cov}(X,\varepsilon)=0$."  When $X$ and $\varepsilon$ are centered around zero, as they are here, the covariance is their average product.  The figure uses color to indicate the individual products: greens and blues for very negative values and oranges for slightly positive values.  On balance the many oranges cancel the few greens and blues, giving zero covariance.

"$E[\varepsilon]=0$." On average the value of $\varepsilon$ is zero.  This is clear from the symmetry: rotating the plot 180 degrees preserves its features (down to fairly fine detail) but negates the values of $\varepsilon.$  Thus the average must be close to zero (the only finite number equal to its own negative).

The conditional expectation $E[\varepsilon\mid X]$ is traced out by the thick black curve: at each value of $X$ it estimates the average height of the points lying above that value.  Clearly this is not always zero.  (All that matters in this example is that the curve is not constantly zero: the details of its shape are irrelevant.)

Even when $X$ and $\varepsilon$ have zero covariance and $\varepsilon$ has zero expectation, locally the values of $\varepsilon$ may fluctuate with $X,$ provided they average out to zero globally (on the whole).

Appendix
Below is the R code that generated the figure.  The (long) third line is the heart of it: to a curvilinear function $y = \sin(\pi x/\sqrt{3})$ it adds uniformly distributed errors runif(n, -1/2, 1/2) and then -- to assure the resulting response will have no correlation with $x$ -- removes the effect of $x$ on these values (using the sequence of calls scale(residuals(lm(...)))).
(If you are uncomfortable with this pre-processing, then add the errors after removing the effect of $x:$
eps <- runif(n, -1/2, 1/2) + residuals(lm(sin(pi*x/sqrt(3)) ~ x))

The result, because the errors are truly independent of $x,$ will not have a perfectly zero correlation, but only because of chance variation in the simulation.  This gives a better simulation but doesn't guarantee a good plot!)
#
# Create data.
#
n <- 1e3                     # Specify the size of the dataset
x <- scale(runif(n))         # Create explanatory variable values
eps <- scale(residuals(lm(runif(n, -1/2, 1/2) + sin(pi*x/sqrt(3)) ~ x)))
zapsmall(cor(cbind(x, eps))) # Confirm lack of correlation
#
# Create a data frame for plotting and plot it.
#
X <- data.frame(x=x, eps=eps, Product=x*eps)
library(ggplot2)
ggplot(X, aes(x, eps)) +
  geom_hline(yintercept=0) + geom_vline(xintercept=0) +        # Draw axes
  geom_point(aes(fill=Product), size=2, shape=21, alpha=1/4) + # Plot the points
  geom_smooth(color="Black", se=FALSE, size=1.1) +             # Plot the regression
  scale_fill_gradientn(colors=topo.colors(13)[1:12]) +         # Specify colors
  ylab(expression(epsilon))                                    # Label an axis

Comment: @financial Done.
Comment: would you mind sharing the equations needed to generate this simulation?
Answer: Let $x = \epsilon = 0$.  Now check the relevant moments.
Comment: This is more a comment/suggestion than an answer.
Comment: It depends what OP is trying to show here (which is a bit ambiguous).  The example shows that there are cases where all three conditions hold, so the first two conditions are compatible with the third.
Comment: The question seems me quite clear. In any case, comments (not answers) are for clarifications too.
Answer:
Let $x$ and $\epsilon$ are two random variables.
If $$Cov(x,\epsilon)=0$$ and $$E[\epsilon]=0,$$ can that lead to
$E[\epsilon|x]=0?$

No, those conditions are not enough.
Indeed it is possible that both hold but $Cov(x^2,\epsilon)\neq0$, therefore $E[\epsilon|x]\neq 0$
However if this stonger condition hold $Cov(f(x),\epsilon)=0$ fon any $f()$, then
$E[\epsilon|x] = 0$ hold
Note: sometimes $E[\epsilon|x] = 0$ is assumed but only $E[x \epsilon] = 0$ is checked/considered. This prassi can work if we assume (often implicitly) that only linear relations are permitted.
Answer: The following is wrong. Here is an counter example:
Here are my thoughts. Could some expert help check for me? thanks.
$Cov(x, \epsilon)=0\space\implies E[x\epsilon]-E[x]E[\epsilon]=0 \space \stackrel{E[\epsilon]=0}\implies E[x\epsilon]=0$
so we can say $x$ and $\epsilon$ are orthogonal. From the geometric perspective, $E[\epsilon|x]$ is the projection of $\epsilon$ onto the x's plane. Since $\epsilon$ is orthogonal to that plane, so the projection is zero. That is $E[\epsilon|x]=0$
Comment: Here is a counterexample: https://stats.stackexchange.com/questions/190703/non-linear-endogeneity/190800#190800
Comment: @ChristophHanck Thanks for pointing it out.

I guess $E[x]=0$ is needed for my implication to be correct.

in[this book]( https://drive.google.com/file/d/1VmkAAGOYCTORq1wxSQqy255qLJjTNvBI/view) section 9.4:

it defines $ = E[UV]$, where U, V are random variables. if $E[U]=0$ and $E[V]=0$ then it shows the interpretation:

U, V are orthogonal if and only if U an V are uncorrelated(Cov(U, V) = 0)
Comment: I am not sure - my counterexample also has $E(x)=0$. Also, in my understanding, orthogonal is something else than $E(\epsilon|x)=0$.
Comment: Hmm. then I guess when some literatures use $cov(x, \epsilon)=0$ to check the real consistent OLS assumption $E[\epsilon|x]=0$. there is an implicit assumption that $\epsilon$ is in normal distribution.
Comment: Zero covariance is enough for consistency, but zero conditional mean affords stronger results - again, I'd refer you to the link I posted for an example.
Comment: @LongBu; "then I guess when some literatures use $cov(x,ϵ)=0$ to check the real consistent OLS assumption $E[ϵ|x]=0$. there is an implicit assumption that ϵ is in normal distribution" this can be a reasonable explanation but it seems me not so common. Maybe my answer can help.


If volume of a sphere increases by 72.8%, what is change of its surface area?

Question: If the volume of a sphere is increased by 72.8% what would be the change in surface area?
I'm trying to solve the problem using application of derivatives. I noticed that on differentiating the formula for volume of a sphere we directly end up with that of the surface area. How to approach this link?
Comment: If you take the ratio of the "new" volume vs "old", you will find $R=r1.728^{1/3}$ where R is the new radius, r the old radius.
Comment: What has this to do with derivatives?
Comment: @copper.hat it was a question I found in a book that dealt with derivatives
Comment: Looking at Quanto's answer, you have $S = C \, V^{2/3}$ so that $dS = 2/3 \, C \, V^{-1/3} \, d V$ and $dS / S = 2/3 \, dV / V$.
Answer: Recall that

volume $V= \frac43 \pi r^3$
surface area $S= 4 \pi r^2$

then assume

$V+\Delta V=\frac43 \pi (r+\Delta r)^3 =1.728 V=1.728\cdot \frac43 \pi r^3$

and find $\Delta r$.
Answer: Use $V= \frac43 \pi r^3$ and $S= 4 \pi r^2$ to establish
$$S=(36\pi)^{1/3}V^{2/3}$$
With the new volume $V'=1.728V=1.2^3V$, the new surface is
$$S'=(36\pi)^{1/3}(1.2^3V)^{2/3}=(1.2)^2S=1.44S$$
Thus, the surface increases 44%, exactly.
Comment: Cute observation.  I guess  $M= 1.728 = \frac {1728}{1000}=\frac{12^3}{10^3}=\frac {12}{10}^3$ and so $M^{\frac 23} = \frac {12}{10}^2$.  And FWIW the radius has increased from $1$ to $1.2$ or $20$.
Comment: @fleablood - Yeah, the question is designed this way on purpose, anticipating that some would miss
Answer: Hint: A sphere of radius $r$ has volume $V=\frac43\pi r^3$ and surface area $A=4\pi r^2$. So $r=\sqrt[3]{\frac{3V}{4\pi}}=\sqrt{\frac A{4\pi}}$. If the volume changes from $V$ to $1.728V$, then the radius changes from $r$ to ... and in turn the area changes from $A$ to ...
Answer: Set up a formula that sets up Volume in terms of Area.
As Volume is determined by $V= \frac 43\pi r^3$  and Surface Area of a Sphere is $SA= 4 \pi r^2$ then $SA = 4\pi r^2 = 4\pi{\sqrt[3]{\frac {3V}{4\pi}}}^2$
So if volume is increased by $1.728$ then surface area is increased from $4\pi{\sqrt[3]{\frac {3r}{4\pi}}}^2$ to   $4\pi{\sqrt[3]{\frac {3*1.728r}{4\pi}}}^2$
And the proportional increase is $\frac{4\pi{\sqrt[3]{\frac {3*1.728r}{4\pi}}}^2}{4\pi{\sqrt[3]{\frac {3*1.728r}{4\pi}}}^2}=1.782^{\frac 23}$
And percentage increase is $100(1.782^{\frac 23}-1)$
The real question, I suppose, is how to get the formulas for volumes and surface areas in the first place.
If we look at cross section circles of  a sphere at points $x: -r\le x \le 4$ along the diameter of the sphere, these cross section circles have radii of $R = \sqrt{r^2 - x^2}$.
An area of one of these circles is $\pi R^2=\pi(r^2 - x^2)$   and the circumference of a circle is $2\pi R= 2\pi\sqrt{r^2 - x^2}$
So the volume of a sphere is $V= \int_{-r}^r \pi(r^2 - x^2)dx=\frac 43\pi r^3$ and the surface area of a sphere is $\int_{-r}^r2\pi\sqrt{r^2 - x^2}dx= 4\pi r^2$
.....
Well we are at it the area of circle is determine  by $A=\int_{-r}^4 2\sqrt{r^2 - x^2}dx = \pi r^2$
Answer: As @user170231 siad, $r$ increases by $1.728^{1/3}$ and then $A$ increases by $1.728^{2/3}$, So the final answer will be $100(1.728^{2/3}-1) \%$.


Taylor expansion for equation simplification

Question: What taylor approximation would be necessary to approximate the equation
$$
{1 \over 1 + \left(v/c\right)\cos\left(\,\theta\,\right)} \approx
1 - {v \over c}\,\cos\left(\,\theta\,\right)
$$
I saw Walter Lewin write down an equation like this, but I don't understand how he came to this conclusion. It comes from the equation$\ldots$
$\displaystyle f' = f\left[1 + {v \over c}\cos\left(\,\theta\,\right)\right]\quad   \text{where}\quad f = {c \over \lambda}$.
$\displaystyle λ'\left[1 + {v \over c}\,\cos\left(\,\theta\,\right)\right] = λ$.
This is then somehow changed to
$λ' = λ\left[1 - \left(v/c\right)\cos\left(\,\theta\,\right)\right]$. Any explanation ?. Thanks !.
Answer: I hope he didn't write down
$$\frac1{1+\cos\theta}\approx1-\cos\theta.$$
That's bad.
But in effect he wrote down
$$\frac1{1+(v/c)\cos\theta}\approx1-(v/c)\cos\theta.$$
If $v/c$ is small, this is OK. It is
$$\frac1{1+x}\approx1-x$$
for small $x$ which is fine: $1-x$ is the beginning of the geometric
series for $1/(1+x)$. The error is of the order of $x^2$, so that
is fine if you can afford to neglect errors of that size.
Answer: It could be a special case of
$$\frac{1}{1+u} \approx 1-u$$
when $u$ is small. In your case it would apply when $\frac{v}{c}\cos \theta$ is small.


How do I create an additional README %doc file in an RPM spec file?

Question: When creating a spec file, what is the proper procedure for creating an additional text doc file to be installed by the RPM, when that text file is not part of the original source?
For example, if the current %doc line includes the following files that are in the source:
<code>%doc FEATURES KNOWNBUGS LICENSE README RELEASE_NOTES
</code>
and I want the spec file to create a README_FOO that will be written in the same docs directory (which contains package-specific configuration instructions), what's the proper way to do it?
I know I can create a text file in the %install section of the spec file with:
<code>echo 'README_FOO contents go here
' > "$RPM_BUILD_ROOT"/README_FOO
</code>
but I'm not sure of the correct path to use after $RPM_BUILD_ROOT, or how to reference the new file in the existing %doc line or a new one.
Thanks in advance.
Answer: The easiest thing to do is to create a new %SOURCEx file and then copy it in during %prep. From there you can refer to it as normal in %doc.
Comment: Sorry - can you be a bit more specific with "copy it in"? I've created an additional source called readme.tar.gz (with three READMEs) and included it as Source2. Then in prep, I assume I untar it, but TO where? And then FROM where do I copy the untarred files? Thx.
Comment: Since it's a tarball you can just add it to `%setup` via `-a 2`. This will extract it into the same place as all the other files. Then from there you put them in %doc as you would any other file from there.


Gaussian Distribution + Hash Tables

Question: The original question I posted on StackOverflow. I think it's more mathematically inclined so I posted it here again. In terms of math.
There's a class of students. Each students has a score between 0 and 300 (gaussian, with some known average and standard deviation). I need to find classes of marks (like 0-100, 101-125, 126-140, 141-160, 161-175, 176-200, 201-300) such that:
The number of classes is minimumThe number of students in each class is minimum
How do I go about doing this? Is this a standard problem? Also, is it possible to prove that only this set of classes will have the above property.
Comment: I remember this book tackles the problem of choosing a binning optimally: [All of non-parametric statistics](http://www.amazon.com/All-Nonparametric-Statistics-Springer-Texts/dp/0387251456).
Comment: @Raskolnikov: Thanks! I'll try to get that book.
Answer: You question is a bit underdefined, but in general what you're looking for is index (order?) statistics. For example, if the number of classes is to be $2$, you need to cut them at the median. If it's $3$, you cut them at the $1/3$ and $2/3$ order statistics, and so on. The classes will be entirely evenly-spread.
The former paragraph assumed the classes can depend on the data. If the classes are not supposed to depend only on the distribution, then you just need to find the index statistics for the distribution. For example, the median of a Gaussian is equal to its mean, and for the other points you can consult a table (there is no closed form). You can then estimate how evenly spread the scores are going to be, e.g. the spread in the L2 spread is given by a $\chi^2$ distribution, whose mean you can look up in Wikipedia.
Answer: To have the minimum number of classes, take a class from 0 to 300.  To have the minimum number of students per class, take each different score to be a class.
More seriously, you generally need to define the number of classes you want, and whether you want all the classes to be about a given size.  You might want this when giving grades, say 50% A's, 40% B's and 10% C's.  For other applications you are just trying to group "things that are close enough together that we can treat them the same."  If the distribution is a true Gaussian, with no noise, there is no nice answer.  But with a reasonably small sample, you can just plot a histogram, look for scores that are relatively rare, and make the cut there.
In more than one dimension it gets harder.  You might look at cluster analysis
Answer: Statisticians would usually refer to your "classes" as "bins".
Your requirements for "minimum number of bind" and "minimum size of the bins" are in opposition, and you would have to clarify how the conflict should be resolved.  For instance, if one arrangement has 10 bins with 5 marks each, and another has 5 bins with 10 marks each, which is better?  Or, one arrangement has 10 bins with 10 marks each, and another has 10 bins total, 9 with 9 marks each, and the last one with 19 marks.  You have to specify a rule for how to identify which of any two arrangements is better.  Only then can you ask how to achieve the best one, and whether it is unique.
Comment: Yes, the two requirements are in opposition. That's what makes me believe that there will be one "optimal" size and number of students.  How about this rule: The summation of (product of size of a bin and the number of entries in it) should be minimum.

Gaussian Distribution + Hash Tables


Autoscaling with Google Compute Engine with Static IP pointing to domain name

Question: I am looking to add autoscaling to my Google Compute Engine via the instructions I have found here: https://cloud.google.com/compute/docs/autoscaler
My original Compute Engine instance has a static ip and I have the domain (example: domain.com) which points to this static ip (via Google Domains).  So when my users visit my domain.com site, they are pointed to the static ip original Compute Engine instance.  This works perfectly for now.  However, with autoscaling, I believe new instances may spin up with different ephemeral ips other than my original Compute Engine static ip.  Is this correct?
Therefore, my worry/confusion is that when there is enough traffic to spin up multiple servers coming into my domain.com address (which points to my static IP original Compute Engine instance), I am not sure how this traffic would then distributed to the additional instances that spin up since users are accessing my site through the domain (pointing at the static ip) and not the new ips for the instances that spin up.
My question is: how do I get my current instance and all the new ones that spin up to open/function through my domain.com address?  Is this automatic?  Or do I need to do something in either Google Domains, the Managed Instance Group, or elsewhere?
Comment: https://cloud.google.com/load-balancing
Comment: Okay, so it sounds like I have to set up the load balancer to get the static IP I need for the domain.  Then, the load balancer will distribute the traffic to the servers under the Managed Instance Group (MIG) when my domain points to my load balancer static ip.  But I am not able to do the MIG without the load balancer static IP.  Does this sound correct?
Answer: You may follow the below steps:
-Create a snapshot of your existing VM.
-Create a custom image using the snapshot.
-Create a MIG template using the custom image
-Create a MIG
-Configure a LB to get a static ip and the LB will distribute the traffic to the servers under the Managed Instance Group (MIG) when your domain points to your load balancer static ip.
Your understanding of the last comment is correct.
Comment: Thanks so much. This is very helpful.


How to plot inequalities $x^2+z^2\leq 4$, $2\leq y \leq 4$ on Maple

Question: I am trying to plot the graph of the region in 3D-space defined by $$x^2+z^2\leq 4, \quad \quad 2\leq y \leq 4.$$ This is a solid circular cylinder of radius $2$ with axis $y$-axis that lies between the planes $y=2$ and $y=4$.
I used implicitplot3d in Maple to try to do this:
implicitplot3d(x^2 + z^2 <= 4, x = -5 .. 5, y = -5 .. 5, z = -5 .. 5, style = surface)
This almost gives me what I am looking for, except that the cylinder is not solid for some reason. I just obtain the outer shell, excluding the "caps" (top and bottom) of the cylinder.
How do I obtain the solid? Thank you in advance.
Comment: Maybe you should also put your question to Maple Primes (https://www.mapleprimes.com/questions/) which specializes in Maple issues.
Comment: This is a programming question, not a math question, and hence should be closed or migrated.
Answer: There are several ways to construct the plot of such a cylinder.
As just one example,
P := plots:-display(
   plottools:-transform((x,y,z)->[x,z,y])(
     plottools:-cylinder([0,0,2], 2, 2, strips=200, style=surface))):
P;

plots:-display(P, labels=[x,y,z],
               view=[-5..5,-5..5,-5..5]);

Comment: Thank you for your help, this is perfect.