before pseudoelement appearing different on chrome and firefox

Question: So I'm experiencing this weird bug where Chrome doesn't display the pseudoelement inside my div with class "to_top", it works perfectly on Chrome but Firefox doesn't display the horizontal line outside the square, instead it appears inside and enlarges the container div instead, this is just sad. Any way to fix this?
Here is my code (sorry for inline styling but taht's not the problem here):

.to_top::before{content:""; position:absolute; width:100%; height:1px;  border-top:1px solid red; left:0px; top:-5px;}

      MENU
   LOCALIZACIÓN
   HORARIO
   CONTACTO
   OPINIONES

     COMIDA TRADICIONAL HECHA CON  EN MÁLAGA

      Copyright © 2018 Nombre del Restaurante

   DISEÑO WEB POR GGB

Comment: (`1px solid red` is not a height, btw.)
Comment: Well since you are using `top: -5px`, how did you determine that it wasn't Firefox actually doing things wrong here to begin with …? And what is it that you are actually trying to achieve here? At least with this example I can't see why you might be trying to use a pseudo element to achieve what simply making the element's top border one pixel thicker could achieve as well.
Comment: It's not possible to do with borders, what I want is to have that little line a bit over the square container, kind of like a "hat" if you get me
Comment: @CBroe true, I fixed it but still not working
Comment: Looks like it is the combination of `display: flex` and `position: absolute`, that makes Firefox handle things wrong(?) here. Guess adding an additional container element could perhaps fix this.
Comment: I tried using a span element instead of a pseudo element and still looks wrong, removed flex too...
Comment: I was talking about the properties of the element itself, not the pseudo element. Try and toggle flex in dev tools, then you'll see what effect it has in Firefox. Chrome doesn't care either way.
Comment: Possible duplicate of [Firefox CSS outline bug?](https://stackoverflow.com/questions/28009963/firefox-css-outline-bug)
Answer: Use border instead of outline for the sqare.


Symmetries and invariants.

Question: I would like someone to give me an example of application of the following paragraph from an introductory book on Lie groups theory:
The paragraph states the following:
Symmetry transformations, if they exist, play an important role in the construction of solutions of differential equations.
Indeed, they make it possible to find differential invariants directly under the action of a group of symmetry  ( Lie group ).
These differential invariants decrease the order or degree of the differential equation in question.
Thus, the discovery of more symmetries leads to more differential invariants, resulting in a decrease in the order or degree of the equation, which finally allows to find its solutions.
Thanks in advance for your help.
Answer: This is used a lot in physics; see Noether's theorem and constant of motion, in particular integral of motion.
An example is afforded by the conserved energy of a physical system. For instance, the equation of motion for a system consisting of a mass and spring is
$$
m\ddot x+kx=0\;,
$$
a second-order differential equation. Multiplying both sides by $\dot x$ and integrating over time yields
$$
\frac12m\dot x^2+\frac12kx^2=E\;,
$$
where the free additive constant $E$, the energy, consisting of the kinetic energy (the first term) and the potential energy (the second term), is a first integral of the motion, and we now have a first-order differential equation. We've introduced an additional constant and reduced the order of the differential equation by one.
The symmetry related to this constant of the motion is the invariance of the system (and thus of the equation of motion) under time translations. Similarly, invariance under spatial translations leads to conservation of linear momentum, and invariance under rotations leads to conservation of angular momentum.
Answer: Suppose you have the ODE $$y^{\prime\prime}(x) = f(x,y(x),y^\prime(x))$$ and suppose that someone told you that the Lie group $\bar y = y+\epsilon$ is a symmetry of the ODE. That means that $$ \bar y^{\prime\prime}(x) = f(x,\bar y(x)-\epsilon,\bar y^\prime(x)) = f(x,\bar y(x),\bar y^\prime(x)).$$ But this means that $f(x,y,z) = f(x,z)$, that is the ODE has the form $$y^{\prime\prime}(x) = f(x,y^\prime(x)).$$ Now by saying that $y^\prime(x)=p(x)$ we get the reduced ODE $$p^\prime(x) = f(x,p(x)).$$

Symmetries and invariants.


digital piano has plastic clunking sound

Question: I've had the Yamaha Digital Piano P-45 (~$500) for about seven years now - and it's fine, except that while playing (and recording with an iPhone nearby), I can prominently hear the plastic keys plunking - almost as loud as the speaker.
Do all entry-level digital pianos have such an audible plastic plunking sound? If so, how can it be mitigated?
Example recording
Comment: Hammer mechanisms tend to be loud. In an acoustic piano you don't hear it because the sound from string overwhelms it but I doubt it is possible to make a completely silent hammer mechanism that feels good to touch.
Comment: Good edit. But the upvote is for using "Beth" for the sample. :-)
Comment: Even entry level Yamaha digital pianos are better than decent. Have you tried to find the exact source of the clicking? Perhaps it is something external, like some felts or cushioning that has worn down where the key hits the key bed. Maybe you can add some cushioning to mute the clicking sound.
Comment: I guess a nice question you could make from this would be something along the lines "This dp makes these noises, is this usual for a dp in this price range, is this a problem of this model or is this indicative of a problem of this unit?"
Comment: I've an old Clavinova with a similar issue.   Essentially only really usable via MIDI or some other method outside of directly recording it with a mic or what not.
Comment: The only thing more important than how much a microphone costs is where it's placed.
Answer: All digital pianos will have some kind of mechanical extraneous sound, but the clicking from your digital piano is exceptionally loud.  (Either that, or you recorded your example with the volume very low.)
One way to get around this extra noise while recording is to record the line out signal from the piano.  You should be doing this anyway, unless you particularly like the sound through a certain keyboard amp.  If your piano does not have line outputs, but does have a headphone output, you can use a splitter cable to plug both headphones and a digital recorder or PC to your piano.  Specifically, you will need a "3.5mm headphone splitter" or "3.5mm TRS Y splitter, 1 male to 2 female".
For practice, you can use headphones to isolate you from the clicking sounds coming from the piano, if they bother you.  If you're playing with other people, headphones may not be an option, but you're probably playing loudly enough (with a keyboard amp) that the clicking is not an issue.
As far as physically solving the problem at the source, solutions available will depend on the construction of your keyboard.  Many keyboards will have a strip of felt that the keys touch when depressed all the way, which could be replaced, either with fresh replacement felt, or maybe some slightly thicker felt.  I believe this is the replacement for the model mentioned in the question.  I am not endorsing this seller.  For weighted models, there may also be cushion strips for the hammers.  Example Example If your keyboard has those cheap plastic-shell type keys, where the underside is accessible, then maybe you could try sticking some type of adhesive-backed gel or rubber pads in there to damp the keys.
Comment: Thanks for the "solving the problem" suggestions. (and yes I'm trying to solve the problem without using headphones or recording via MIDI interface to Apple laptop...) I plan to check mine, to see if perhaps the felt has worn out and just needs to be replaced.
Comment: I tried a few digital pianos at a local music store today. I tried two Yamahas there: One had the same clunky sound, so must use the same plastic key mechanism as the P-45. The other Yamaha seemed to have a much better mechanism. Will Yamaha tech support be willing to tell me which of their digital pianos use which mechanism? So far, I see this:

P-45: clunky plastic key mechanism (mine)
P-125: sounds/feels like same mechanism as P-45
YPD-165: totally different sounding/feeling mechanism

The "hinges" in the P-45 mechanism are just plastic bending - i've repaired broken keys twice.
Comment: Probably- [ask Yamaha](https://usa.yamaha.com/support/contacts/index.html)
Comment: So far, what I see from scouring the Yamaha website, is (mostly just) two kinds of "keyboard action":

GHS (Graded Hammer Standard) Keyboard Action with Matte Black Key Tops (on most of the P- models ("P" = Portables?)

GH3 (Graded Hammer 3) Keyboard Action with Synthetic Ebony and Ivory Key Tops (on about half the "YDP"(Yamaha Digital Piano?) models.

And my P-45 is "GHS", and the much-better sounding/feeling YDP-165 I played today is "GH3".


Are Skewness and Kurtosis Sufficient Statistics?

Question: I would like to prove that Skewness and Kurtosis are sufficient statistics for gaussian distribution.
Later on I will try to prove on loglogistic distribution.
Do you have any idea how to do that?
Comment: You are going to fail --- you cannot prove what is not true
Comment: You obtain absolutely no information about the location of a Gaussian from the skewness or kurtosis.  Proof: they are the same for a Normal$(\mu,\sigma)$ and Normal$(\mu^\prime,\sigma)$ distribution, for any $\mu$ or $\mu^\prime$. Indeed, skewness is worthless, because it's always zero.
Comment: Why would you think they are? What theorems exist that relate to sufficiency?
Comment: Can you give some detail? What is the reason?
Comment: Thanks a lot. That's right. How can I prove these two are sufficient statistic  on Loglogistic distribution? Any idea?
Answer: You are going to fail --- you cannot prove what is not true!
More details:  You obtain absolutely no information about the location of a Gaussian from the skewness or kurtosis. Proof: they are the same for a $\text{Normal}(\mu,\sigma)$ and $\text{Normal}(\mu′,\sigma)$ distribution, for any μ or μ′. Indeed, skewness is worthless, because it's always zero. (stated in comments by whuber).
As for the same question for loglogistic distribution, you would have to tell us why you expect skewness and kurtosis to be sufficient in that case (it is not).
Comment: This answer is presently flawed.  *Sample* skewness is not always zero.  In fact, it is non-zero with probability one (though it has a distribution that does not depend on $\mu$).


Can AWS lambda calls be Synchronous?

Question: Having some trouble using lambda functions in AWS. I would like to know if I can call AWS Lambda functions synchronously
rather than asynchronously. Right now the AWS Lambda functions seem to be continously running and I would like for a way to stop them
as they are using my credits. Any help would be appreciated.
Thanks,
heres these code:
<code>Client.GetObjectAsync(BucketName, FileName, (responseObj) =>
        {
        //print("about to get json");

            if (responseObj.Exception == null) print("exception not null"); else print(responseObj.Exception.Message);
            string data = null;
            var resp = responseObj.Response;
            if (resp == null)
            {
            //print("null");
            }
            else
            {
            //print("not null");
            }
        //print(resp.ContentLength);

            if (resp.ResponseStream != null)
            {
                print("before StreamReader");

                using (StreamReader reader = new StreamReader(resp.ResponseStream))
                {
                //print("In StreamReader");
                data = reader.ReadToEnd();
                //print("got json");
                }

            /**
            string fp = Application.dataPath + "\\unitydata.txt";
            using (var fs = System.IO.File.Create(@fp))
            {
                byte[] buffer = new byte[81920];
                int count;
                while ((count = resp.ResponseStream.Read(buffer, 0, buffer.Length)) != 0)
                    fs.Write(buffer, 0, count);
                fs.Flush();
            }
            **/

           // }
           // else
           // {
           //     print("response is null");
           // }
           // print("JSON CONTENT: " + data);
           // float[] fres = parseVectors(data);
           // for (int i = 0; i < fres.Length; i++) print(fres[i] + " ");
           // responseObj.ToString();
       // });
</code>
Comment: A good portion of your code is commented out, if it is not needed for the understanding of this question, I would advise you remove it instead so it doesn't clutter up the question.
Comment: This also looks like S3 fetching code rather than Lambda?
Answer: AWS Lambda function has a time out of 5 min. Since you stated that your Lambda function is continuously running, is it possible that your client code is doing this invocations behind the scenes?
Secondly, Please post details of your application technology stack. I see that you are using C# and AWS SDK for .NET. Are you writing a console application and trying to do few operations on S3?
Answer: I would like to know if I can call AWS Lambda functions synchronously rather than asynchronously.

Making a call to AWS Lambda is always synchronous. Inside Lambda you
  make asynchronous calls, but a call to Lambda is synchronous and upon
  calling it will return a result or will fail in the maximum configured
  time.

Right now the AWS Lambda functions seem to be continously running and I would like for a way to stop them as they are using my credits.

You will be billed only for the time you use it. If you don't use it,
  you will not be charged.

Can AWS lambda calls be Synchronous?


How do I disable caching of a custom token?

Question: I have created a custom token which reads values from the Apache Request Headers.  It seems to work fine for my testing, but then when another user subsequently accesses the token, it uses my values.  It seems that the token value is being cached.  How do I disable caching on custom token values?  NOTE: because of the use situation, I need to disable caching on the token value (or whole page), not just add a context.
I have searched for this and not found an answer. There are no cache related settings in hook_token_info nor hook_tokens. I have seen references to using bubbleable metadata in caching (https://www.drupal.org/node/2528662), but I am not clear on what I need to put there to disable caching.
/**
 * Implements hook_token_info().
 */
function fred_token_info() {
  $info = [
    'types' => [
      'fred_type' => [
        'name' => t('fred type'),
      ],
    ],
    'tokens' => [
      'fred_type' => [
        'APACHE_HEADERS' => [
          'name' => 'apache_request_headers()',
          'description' => t('Request headers as sent through Apache...not strictly a superglobal, but useful. Works in the Apache, FastCGI, CLI, and FPM webservers.'),
          'dynamic' => TRUE,
        ],
      ],
    ],
  ];
  return $info;
}

/**
 * Implements hook_tokens().
 */
function fred_tokens($type, $tokens, array $data, array $options, \Drupal\Core\Render\BubbleableMetadata $bubbleable_metadata) {
  $replacements = [];
  if ($type == 'fred_type') {
    foreach ($tokens as $name => $original) {
      $tokenParts = explode(':',$name);
      if (count($tokenParts) >= 2) {
        switch ($tokenParts[0]) {
          case 'APACHE_HEADERS':
            $fredType =& $_SERVER;
            break;
        }
        $FredKey = $tokenParts[1];
      }
      else {
        return;
      }

      if (!isset($tokenParts[2]) || $tokenParts[2]!=='raw') {
        $replacements[$original] = filter_var($superglobalType[$superglobalKey], FILTER_SANITIZE_STRING, FILTER_FLAG_NO_ENCODE_QUOTES|FILTER_FLAG_STRIP_LOW);
      }
    }
  }

  return $replacements;
}

Comment: You more likely want to vary caching, rather than disabling it. Have a read of https://www.drupal.org/docs/drupal-apis/cache-api/cache-contexts
Comment: Show your implementation.
Comment: Since this is a question about code, we need to see the code you wrote. Otherwise, the answer can just say it is necessary to set a cache context. We cannot say more because, without context, we cannot say what cache context must be set.
Comment: Edited to add code as requested.
Comment: You don't have access to this superglobal in Drupal. You could access \Drupal::request()->headers->get('X-foo') and add the cache context `headers:X-Foo`, but it would be not a good idea to put this token in random places depending on how much the header value is varying from request to request. Also, this doesn't work with anonymous page caching.
Answer: You need to provide a cache context with your token. It's essentially a way to tell Drupal to 1) still cache your value but 2) cache a value per context. Drupal has some built-in context values, the one you want is the "user" context (i.e. cache a value per user).
In order to provide the context, hook_tokens() provides a $bubbleable_metadata object as the fifth parameter. This object is passed down as Drupal recurses through the token segments. Use this object to attach the cache context using addCacheContexts().
Comment: Perhaps not the `user` context, but only because the OP did not specify exactly which headers, but otherwise, the above is always the answer to "why is this cached?".
Answer: I eventually found an answer.  Modify hook_tokens to add the following line so that it executes prior to the computation of the tokens (I put it as the first line of the function):
\Drupal::service('page_cache_kill_switch')->trigger();

Be aware that this prevents anything on the affected page from being cached, whether the end user is logged in or not, but this is perfect for our use case.
Comment: If you are going to downvote, please give a reason.   This solution matched my use and need case perfectly and I included the warnings of why it might not be a solution for everyone.


hook function not deleting nodes when calling node_delete

Question: I have a cron job where I need to do a node_delete().
From what I can tell the delete occurs okay if I run the cron job manually from the status report page, but if I try to run the cron from inside a call to a module_cron function it looks like the delete fails.
Is there some way to give the cron the access to delete nodes with node_delete?
Comment: As a note, I (we?) would recommend that you accept answers where such questions are answered sufficiently. This will benefit both you and the community.
Answer: A scheduled cron runs as uid 0, the anonymous user, and therefore probably can't delete anything.  When you run cron from the admin menu, it uses your current session, so you can delete things.
If you google for "drupal run cron as uid 1" you will see some workarounds.  Most involve switching users inside your hook_cron and then restoring the session when you are done.
What should be possible is to invoke drush -u XXX cron from your crontab instead of the the typical wget method.  Some searching will dig up the proper way to call it (you need to get the environment and Drupal basedir set right).  I would not run as uid 1, though.  Pick (or create) a user with sufficient permissions to do what you need.
What would also be possible is to create a script that bootstraps, loads the proper user, and then does your task.  Lock this down in your .htaccess and call it from your crontab.
Answer: For deletion of a node by using hook_delete, it is necessary that the author(user) of that node is present in the db. To achieve consistency, one should delete nodes first and then its user. If you donot want to delete node but only want to delete a user you should use hook_user and in delete case, set uid of the node to 1, as uid = 1 is for super admin. So we will not face orphaned nodes in the database. Hope so, it will help you.


Difference between anti-derivative and indefinite integral

Question: My teacher gave me the following integral to evaluate:
$$\int \frac{x^2}{(x\sin(x)+\cos(x))^2}dx$$
After half an hour of uselessly fumbling around with trig identities I gave up and plugged it into an integral calculator: https://www.integral-calculator.com/. However I am confused: it displayed ANTIDERIVATIVE COMPUTED BY MAXIMA as $$-\dfrac{\left(2x^2-2\right)\sin\left(2x\right)+4x\cos\left(2x\right)}{\left(x^2+1\right)\sin^2\left(2x\right)+4x\sin\left(2x\right)+\left(x^2+1\right)\cos^2\left(2x\right)+\left(2-2x^2\right)\cos\left(2x\right)+x^2+1}+C$$ and I pressed the simplify button to obtain $$-\dfrac{\left(x^2-1\right)\cos\left(x\right)\sin\left(x\right)+2x\cos^2\left(x\right)-x}{\left(x^2-1\right)\sin^2\left(x\right)+2x\cos\left(x\right)\sin\left(x\right)+1}+C$$ However the "MANUALLY" COMPUTED ANTIDERIVATIVE displayed the following $$\dfrac{\sin\left(x\right)-x\cos\left(x\right)}{x\sin\left(x\right)+\cos\left(x\right)}+C$$ Which was computed by the following method:
$$\int \frac{x^2}{(x\sin(x)+\cos(x))^2}dx= \int \Bigg(\frac{x\sin(x)}{x\sin(x)+cos(x)}-\frac{x\cos(x)(\sin(x)-x\cos(x))}{(x\sin(x)+\cos(x))^2}\Bigg) dx$$
Using integration by parts
$$ \int \frac{x\cos(x)(\sin(x)-x\cos(x))}{(x\sin(x)+\cos(x))^2} dx= \dfrac{\sin\left(x\right)-x\cos\left(x\right)}{x\sin\left(x\right)+\cos\left(x\right)}+ \int\frac{x\sin(x)}{x\sin(x)+cos(x)}dx$$
$$\Rightarrow \int \frac{x^2}{(x\sin(x)+\cos(x))^2}dx=\dfrac{\sin\left(x\right)-x\cos\left(x\right)}{x\sin\left(x\right)+\cos\left(x\right)}+ \int\frac{x\sin(x)}{x\sin(x)+cos(x)}dx-\int\frac{x\sin(x)}{x\sin(x)+cos(x)}dx=\dfrac{\sin\left(x\right)-x\cos\left(x\right)}{x\sin\left(x\right)+\cos\left(x\right)}+C $$
My question is: why do I get different results from computing the anti-derivative and the indefinite integral? I simplified the anti-derivative so shouldn't it be simplified to the indefinite integral above? Are these two equations equal? Are functions for anti-derivatives and indefinite integrals vastly different? Any help will be appreciated
Comment: Why do you distinguish anti-derivative and indefinite integral ? They are perfect synonyms.
Comment: I don't see what you mean. The calculator announces two antiderivatives, you can't distinguish them with synonyms. "Are functions for anti-derivatives and indefinite integrals vastly different?" does not make sense.
Comment: @YvesDaoust I distinguish them because each was differently computed on the site.
Comment: If you don't know if two functions are the same, [plot both of them](https://www.desmos.com/calculator/ezshqfn93t) and see what you get.  It's not a mathematical proof, but it does give you some strong evidence whether or not the functions are the same.
Comment: I think the point of confusion is that the tool itself uses two different tools to compute the anti-derivative.  One uses a tool called "Maxima" to do so.  The other uses its own methodology which also provides steps.  My guess is that Maxima covers a larger number of cases, but doesn't always tell you how you could do it yourself.
Answer: For example, because $$\begin{align*}&(x^2-1)\sin^2x+2x\sin{x}\cos{x}+1\\&=(x^2-1)\sin^2x+2x\sin{x}\cos{x}+\sin^2x+\cos^2x\\&=x^2\sin^2x+2x\sin{x}\cos{x}+\cos^2x\\&=(x\sin{x}+\cos{x})^2.\end{align*}$$
Now, what does happen in the numerator?
We have the following:
$$\begin{align*}&(x^2-1)\cos{x}\sin{x}+2x\cos^2x-x\\&=(x^2-1)\cos{x}\sin{x}+2x\cos^2x-x\sin^2x-x\cos^2x\\&=x\cos^2x+(x^2-1)\cos{x}\sin{x}-x\sin^2x\\&=(x\sin{x}+\cos{x})(x\cos{x}-\sin{x}).\end{align*}$$
I hope now it's clear.
Answer: Computing the Indefinite Integral
$$
\begin{align}
&\int\frac{x^2}{(x\sin(x)+\cos(x))^2}\,\mathrm{d}x\\
&=\int\frac{x^2}{(x\sin(x)+\cos(x))^2}\frac{\mathrm{d}(x\sin(x)+\cos(x))}{x\cos(x)}\tag1\\
&=-\int\frac{x}{\cos(x)}\,\mathrm{d}\frac1{x\sin(x)+\cos(x)}\tag2\\
&=-\frac{x}{\cos(x)}\frac1{x\sin(x)+\cos(x)}+\int\frac1{x\sin(x)+\cos(x)}\,\mathrm{d}\frac{x}{\cos(x)}\tag3\\
&=-\frac{x}{\cos(x)}\frac1{x\sin(x)+\cos(x)}+\int\frac1{x\sin(x)+\cos(x)}\frac{\cos(x)+x\sin(x)}{\cos^2(x)}\,\mathrm{d}x\tag4\\[1pt]
&=\tan(x)-\frac{x}{\cos(x)}\frac1{x\sin(x)+\cos(x)}+C\tag5\\[2pt]
&=\frac{\sin(x)-x\cos(x)}{x\sin(x)+\cos(x)}+C\tag6
\end{align}
$$
Explanation:
$(1)$: $\mathrm{d}(x\sin(x)+\cos(x))=x\cos(x)\,\mathrm{d}x$
$(2)$: $\frac1{u^2}\mathrm{d}u=-\mathrm{d}\frac1u$
$(3)$: integrate by parts
$(4)$: $\mathrm{d}\frac{x}{\cos(x)}=\frac{\cos(x)+x\sin(x)}{\cos^2(x)}\,\mathrm{d}x$
$(5)$: $\sec^2(x)=\frac{\mathrm{d}}{\mathrm{d}x}\tan(x)$
$(6)$: $\tan(x)=\frac{\sin(x)}{\cos(x)}$ and simplify

The Integrals are the Same
$$
\begin{align}
&-\frac{\left(x^2-1\right)\cos(x)\sin(x)+2x\cos^2(x)-x}{\left(x^2-1\right)\sin^2(x)+2x\cos(x)\sin(x)+1}+C\\
&=-\frac{(x\sin(x)+\cos(x))(x\cos(x)-\sin(x))}{(x\sin(x)+\cos(x))^2}+C\tag7\\
&=\frac{\sin(x)-x\cos(x)}{x\sin(x)+\cos(x)}+C\tag8
\end{align}
$$
Explanation:
$(7)$: multiply and use $\cos^2(x)-\sin^2(x)=2\cos^2(x)-1$
$(8)$: cancel common factors


Does escaping output prevent SQL Injections in any way?

Question: I'm preparing for Zend PHP 5.5 Certification and I found a question in study guide which seems to have a wrong answer.
I just don't understand - is there a mistake in their question or answer or does escaping output prevent SQL Injection in any manner?
I searched on the net but I can't find any information to prove this.
If escaping output really protects from SQL Injection, can anybody explain how exactly?
It would be great if you could bring an example.
Thank you very much.

Edit:
My question is not about how to prevent SQL Injection, but is if output escaping prevents SQL Injection in any way, so please don't mark my question as duplicate.
Duplicate Questions don't give me any answer to this one.
Comment: I think there is a typo in the question (Zend mistake), and they meant 'Input' instead of output, that is :)
Comment: Output is something that is leaving a certain system/process/component. If you build SQL and pass it to your database server, I'd also considered that output.
Comment: **It's all about XSS.** *No idea how it could affect SQL.* I think it all depends on what one defines as `output` *(maybe a typo)*.
Comment: @SveatoslavCircel whatever they meant, input or output - it wouldn't help.
Comment: You must not understand output as data sent to the user only.
Comment: Gumbo, what do you exactly mean?
Comment: @vascowhite, the question is about how to prevent SQL Injection, but nobody says that escaping output helps in any way, while Zend affirms that is does.
Comment: Well, it seems that @Gumbo's comment is the answer.
Comment: Quite unfair to say that output needs to be escaped to prevent sQL injection, the context in the question is clearly the response to the client. Not a request of any kind. Atleast I can understand the OP's confusion on this subject. It would have been easy to make the context clear.
Comment: @Gumbo I encountered same question and puzzled me. Post that as an answer pls. I think that is the one (don't see anything else that makes sense).
Answer:
My question is not about how to prevent SQL Injection, but is if output escaping prevents SQL Injection in any way, so please don't mark my question as duplicate. Duplicate Questions don't give me any answer to this one.

Okay, the answer to your question is "No". See also:

Blind SQL injection
Creating Backdoors with SQL Injection

It doesn't matter if you're escaping output after processing the injected query or not, if I can just write malware to your filesystem and access it directly.
The study guide is wrong.
Answer: I think it's all a matter of interpretation: If you interpret the term output as 'data that leaves a certain system/process/component/function' and escaping in regard of SQL as 'applying <code>*_escape_string</code> or similar functions to values that are put into SQL code', then, yes, output escaping may help protect you from SQL injections.
Note that it says "may help" as there are cases in which such functions won't help, most notably when escaped values are not used in a string literal.


Taylor Big Baby vs Koa Limited Edition Taylor 324ce-k-FLTD

Question: What are the differences between an extremely expensive guitar such as the 324ce-K and a very cheap / affordable acoustic like the Big Baby? Could somebody enlighten me as to why one is worth so much more? Specs, wood, playability, electronics, tone, longevity etc.
Answer: There are many, many reasons for differing price. I'm not going to refer to your two specific guitars in the question, as that makes it far too localised and close-worthy, so instead I'm going for the wider view:

Wood - some woods are more expensive due to their rarity. Some are more resistant to warping, temperature or humidity changes etc.
Sustain/Tone - linked to wood, but also construction, tone and sustain are key to how a guitar sounds, and can impact the price dramatically
Appearance - linked to wood, build quality and finishing. A lacquered book matched burl finish is likely to be a lot more expensive than a painted pine slab of wood
Electronics - these can have a major effect on the quality of sound. Good quality electronics can cost a lot
Neck - for playability and tone, a well made neck is worth a lot more than a cheap one
Setup - the combination of bridge, neck, fretboard, nut and strings affects playability, comfort and tone

At the end of the day, play them - see what one you prefer. Then work out if that is worth the money you are willing to spend.
Answer: This goes for all the cheap  vs expensive instruments, not just for acoustic guitars:

A cheap guitar isn't always a bad guitar. It's just made using cheaper materials. Using lower quality woods, strings and hardware. This equals to lower quality of sound the guitar produces. Note that this doesn't necessarily mean that the sound will be bad. It can be good up to a point, but you won't get any marvelous sounds.
A cheap wood that is used on a guitar might not be that durable. A good guitar might last many many years, but a cheap one probably won't.
Usually, cheap guitars get out of tune easier. This means that you'll have to tune it more often, in contrast with an expensive guitar.
A good guitar is easier to play. I had an old-cheap acoustic guitar and had to press real hard on the strings to play. This isn't the case on expensive guitars.
Answer: I own a Baby Taylor and they have crappy tuners. My Epiphone LP has one sharp-edged fret...
In general cheap guitars mean cheap material and no luthier ever touches your guitar while being fabricated. Which also means a cheap guitar's setup mostly is not really good.
But still cheap guitars are the ones you want to buy until being at least an intermediate player...


Tracking how many times a file has been opened/run on network drive

Question: I have a file on a network drive that is frequently used by many in our environment. How can I use Java to track how many times the file has been opened/run. I did some research into file watchers http://docs.oracle.com/javase/tutorial/essential/io/notification.html however these seem only to apply to creation, deletion, modification, and overflow. Before I go off on a file watching tangent, is this possible and what is the best way to do it?
Comment: so I think there are some application exist to doing so, and the question is, are you allowed to run the application at the server?!
Comment: Lets assume I do have access... could you recommend anything in particular?
Comment: so this is going to easy, just follow the link you have provided, you just need to listen/monitor the file(s) you are trying to monitor, but if you ask me, and this is possible, I suggest you do not let user in the network access the file directly, in-other word give the file to users with a proxy module, like ftp or http protocol, and doing so for manipulating, this ensures you to manage and monitor the file(s) you want dynamically and with more flexible and reliable approach.
Answer: I sincerely hope you have found a solution by now.
But assuming that the file in question is some kind of executable you could modify the example from this question: How to get a list of current open windows/process with Java?. And use JNA:
import com.sun.jna.Native;
import com.sun.jna.platform.win32.*;
import com.sun.jna.win32.W32APIOptions;

public class ProcessList {

    public static void main(String[] args) {
        WinNT winNT = (WinNT) Native.loadLibrary(WinNT.class, W32APIOptions.UNICODE_OPTIONS);

        WinNT.HANDLE snapshot = winNT.CreateToolhelp32Snapshot(Tlhelp32.TH32CS_SNAPPROCESS, new WinDef.DWORD(0));

        Tlhelp32.PROCESSENTRY32.ByReference processEntry = new Tlhelp32.PROCESSENTRY32.ByReference();

        while (winNT.Process32Next(snapshot, processEntry)) {
            //see if your process is open and update your counter
        }

        winNT.CloseHandle(snapshot);
    }
}

and poll the system with a Timer object.


Compare two unbalanced contingency tables in r

Question: I have two df that I convert to contingency tables, each df identifies two sets of survey questions results in two different months.
The number of rows of the dfs is different, meaning that surveys got different amounts of responses.
Each dataframe contains the same unique values (4 different unique values per column) - appearing with different frequencies.
I want to make two mosaic plots to compare the two different months - but I assume the two contingency tables are not comparable.
Here how I calculate my contingency tables:
<code># df month 1
df_1 <- structure(list(body = structure(c(3L, 2L, 4L, 1L, 2L), .Label =c("athletic ", "chubby ", "normal", "slim"), class = "factor"), hair = structure(c(2L, 3L, 1L, 4L, 2L), .Label = c("black", "blonde", "brunette","red"), class = "factor")), .Names = c("body", "hair"), class ="data.frame",     row.names = c(NA, -5L))

#compute contingency table
cont_table_1 <- xtabs(~df_1$body + df_1$hair, drop.unused.levels = TRUE)

# df month 2
df_2 <- structure(list(body = structure(c(3L, 2L, 4L, 1L, 2L, 1L), .Label =    c("athletic ","chubby ", "normal", "slim"), class = "factor"), hair = structure(c(2L, 3L, 1L, 4L, 2L, 4L), .Label = c("black", "blonde", "brunette", "red"), class = "factor")), .Names = c("body", "hair"), class = "data.frame", row.names = c(NA, -6L))

#compute contingency table
cont_table_2 <- xtabs(~df_2$body + df_2$hair, drop.unused.levels = TRUE)
</code>
How to approach this problem?
Comment: It appears you have a survey with two items (hair type and body type), with 5 responders in the first month and 6 responders in the second month. Is this correct? What is your research question or null hypothesis?
Comment: My request question is: is there any correlation between hair colour and body type (within the same month)? is this correlation changing month by month? My methodology is to use a mosaic plot of the different contingency tables for each month. Given that the number of responders varies per month, I ask : do I need to somehow balance those contingency tables?
Comment: But do you have a total of only 11 observations or do you have much more data than that?
Comment: This is just a small example. I have 287, 3916 and 1589 observations for three consecutive months.
Answer: There is a very old technique to standardize a contingency table, see e.g. Yule 1912. You could use that technique to standardize your counts and feed those to your favorite graphics program to make the graph you like.
Yule, U. (1912) On the methods of measuring association between two attributes, Journal of the Royal Statistical Society, 75(6): 579-652.
link


Populating a Recycleview giving null in JsonArrayRequest

Question: I have this Code, I am trying to get a JSON code from a PHP script with Android Studio, and after that, getting the image url and name to draw a RecycleView with some Lists, and populate it...I am always receiving NullPointerException from a JsonArrayRequest in JSON_DATA_WEB_CALL() method, and my head is going to explode, i dont find the solution. PHP has been tested too and it works, it displays a JSON correctly...any help would be great. Thx in advance. Here is the code:
getData.php
<?php

    //importing Config file
    include 'include/Config.php';

    // Create connection
    $conn = new mysqli(DB_HOST,DB_USER,DB_PASSWORD,DB_DATABASE);

    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    $sql ="SELECT * FROM imageplums";
    $result = $conn->query($sql);

    if ($result->num_rows >0) {
        // output data of each row
        while($row[] = $result->fetch_assoc()) {
            $tem = $row;
            $json = json_encode($tem);
        }
    } else {
        echo "0 results";
    }

    echo $json;
    $conn->close();
?>

MainActivity.Java
public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {
    public TextView text;
    public static String MAIL_KEY;
    RecyclerView recyclerView;
    RecyclerView.Adapter pAdapter;
    RecyclerView.LayoutManager recyclerViewlayoutManager;
    List<PlumImage> plumList;

    String GET_JSON_DATA_HTTP_URL = "http://192.168.1.39:8080/plumster/getdata.php";
    String JSON_IMAGE_TITLE_NAME = "image_title";
    String JSON_IMAGE_URL = "image_url";

    JsonArrayRequest jsonArrayRequest ;
    RequestQueue requestQueue ;

    private SessionManager session;
    private SQLiteHandler db;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    plumList=new ArrayList<>();

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            addPlum();
        }
    });

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); //Creamos Navigationview que corresponde a nav_header_main.xml
    navigationView.setNavigationItemSelectedListener(this);
    View header=navigationView.getHeaderView(0);
    text=(TextView)header.findViewById(R.id.textViewEmail);

    // SqLite database handler
    db = new SQLiteHandler(getApplicationContext());

    // session manager
    session = new SessionManager(getApplicationContext());

    // Fetching user details from sqlite
    HashMap<String, String> user = db.getUserDetails();

    MAIL_KEY = user.get("email");

    recyclerView=(RecyclerView) findViewById(R.id.recyclerview);
    recyclerView.setHasFixedSize(true);
    recyclerViewlayoutManager = new LinearLayoutManager(this);

    recyclerView.setLayoutManager(recyclerViewlayoutManager);
    //recyclerView.setLayoutManager(new GridLayoutManager(this,2));
    JSON_DATA_WEB_CALL();

}

public void JSON_DATA_WEB_CALL() {
    //Showing a progress dialog
    //final ProgressDialog loading = ProgressDialog.show(this, "Loading data", "Please wait...", false, false);

    JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(GET_JSON_DATA_HTTP_URL,

            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {

                    JSON_PARSE_DATA_AFTER_WEBCALL(response);
                    //loading.dismiss();
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                    Toast.makeText(getApplicationContext(),
                            error.networkResponse.toString(), Toast.LENGTH_LONG)
                            .show();
                }
            });

    requestQueue = Volley.newRequestQueue(this);

    requestQueue.add(jsonArrayRequest);
}

//This method will parse json data
public void JSON_PARSE_DATA_AFTER_WEBCALL(JSONArray array){

    for(int i = 0; i<array.length(); i++) {

       PlumImage plumImage = new PlumImage();

        JSONObject json = null;
        try {

            json = array.getJSONObject(i);

            plumImage.setName(json.getString(JSON_IMAGE_TITLE_NAME));

            plumImage.setPhoto(json.getString(JSON_IMAGE_URL));

        } catch (JSONException e) {

            e.printStackTrace();
        }
        plumList.add(plumImage);
    }

    pAdapter = new PlumAdapter(plumList, this);

    recyclerView.setAdapter(pAdapter);
}

Comment: Can you specify where in the code you are getting the NPE?
Comment: In JSON DATA WEB CALL method, when i create jsonarrayrequest variable, It returns null always, and i have two records un MySQL Db so It shouldnt be null...
Comment: Please **[edit]** your question and post the stack trace.
Answer: It has been solved, it was a problem with the PHP code which was returning null answer. Anyway, thank you.
Comment: Glad you got it working. BTW, when asking questions, please provide as much information as possible. You never specified the exact location you were getting the NPE. You mentioned a method, but a stacktrace will show you the exact location. We would need that to know that in order to help out since the method you mentioned is 19 lines of code. I would also recommend checking out Retrofit2. I find it better to work with than Volley.


Note in Rudin's Real and Complex Analysis, Theorem 3.3

Question: I understood the whole proof, but I can't understand the underlined part. Rudin says that if $\varphi \circ f$ is not in $L^1(\mu)$ then the integral of $\varphi \circ f$ is $+ \infty$ in the sense of Section 1.31 as the proof shows. But I can't see how the proof implies this part.
The integral in Section 1.31 is defined as follows:
For a measurable function $f: X\to [-\infty,\infty]$, we define $\int _X f d\mu= \int _X f^+ d\mu-\int _X f^- d\mu$, provided that at least one of the integrals on the right-hand-side is finite, where $f^+, f^-$ are the positive and the negative parts of $f$, respectively.
Thanks in advance.
Answer: The proof shows that $g(x)=\varphi(f(x))-\varphi(t)-\beta(f(x)-t)$ is a positive measurable function on $\Omega$. Hence, $\varphi\circ f=g+\varphi(t)+\beta(f-t)$ is the sum of a positive measurable function $g$ and an element of $L^1(\mu)$, hence the integral of $\varphi\circ f$ exists in the extended sense. Its integral, if not finite, can only be $+\infty$ as again, $\varphi\circ f$ is the sum of a positive measurable function and a function in $L^1(\mu)$.


OrientDB Javascript Server Side Functions

Question: I want to implement the whole server logic of the OrientDB with the server side Javascript functions but I can´t find a documentation of the server side JS implemantation. The best tutorial that I found is this one:
http://pizzaconnections.net/2015/04/02/orientdb-functions-by-samples-1/
But thats not enough, for example I want to know, how I can traverse to the graph with JS or if I have a vertex saved in a JS variable how to see which edges are going out from this vertex?
Can someone give me few links with good tutorials or maybe a good documentation for Javascript server side functions?
Comment: Hi @Jonny Right, would you like two examples (also only with the `command` OrientDB function) related to your requests ?
Comment: Hi LucaS, thanks for responding. Michela Bonizzi´s examples solved my problems. More examples are not necessary atm.
Answer: This is the examples that I made in according with your request:
I have this schema:

JS function to traverse the graph:

and the output(just a piece):

JS function to see which edges are going out from a specific vertex:

and the output:

Hope it helps,
Regards.
Comment: Thank you very much, this helps me alot. Exactly where I was looking for.


Number of ways to deal $5$ cards to $5$ players from a $52$ card deck.

Question: The question is:

In a game of poker, five players are each dealt $5$ cards from a $52$-card deck. How many ways are there to deal the cards?

The answer is $\frac{52P5}{(5!)^5}$ or $\frac{52!}{47!5!}$ I understand the reason after seeing the answer: $25$ ordered cards are picked from the deck of $52$, then divided by the number of ways each hand can be ordered, because the order of a hand does not matter.
However, before seeing the answer I came up with this attempt:
You choose $5$ cards from $52$, the order doesn't matter so we have $52\choose{5}$. Then you're left with $47$ cards and for the next hand we have $47\choose{5}$. The final sum is ${{52}\choose{5}} + {{47}\choose{5}} + {{42}\choose{5}} + {{37}\choose{5}} + {{32}\choose{5}}$.
This sum is considerably larger, but while I understand the reason $\frac{52!}{47!5!}$ is the correct, I can't find the mistake in my first attempt.
Comment: Why are you adding?  The universal principle of counting states the count of ways to do a series of tasks is the *product* of counts for each task.
Answer: There are $52!$ ways to shuffle the deck.   Dealing 5 cards to each player, every hand is one of $5!$ arrangements, and there are $27$ cards remaining, whose order we also don't mind.
Thus there are $\frac{52!}{27!~5!^5}$ ways to deal distinct hands to the five players.
Your attempt was adequate except that you need to multiply rather than add.
$$\binom{52}{5}\binom{47}{5}\binom{42}{5}\binom{37}{5}\binom{32}{5}\binom{27}{0} = \dfrac{52!}{5!^5~27!}$$

PS: $\frac{52!}{47!~5!}$ counts the ways to deal distinct hands to one player; $\frac{47!}{42!~5!}$ counts ways to deal to the next player, et cetera...
Comment: Thank you! It all makes sense now.


Apply branch locally only on Git

Question: Let's say I cloned a repository. My local files are "clean", I will call it "Version A".
But now I need perform some config changes (connection strings, etc). That changes never need back to server. So I thought about create a new branch with my config changes ONLY. I will call it "Version B".
Finally, I will do some local work, bug fixes, etc. I will call it "Version C".
Now, I want send my changes to server. My idea is send to server "Version A" + "Version C", removing added the changes (or ignoring?) on "Version B".
I wonder if this is possible, and how I do it?
EDIT:
If possible, tell me a ELI5 step by step...
Comment: Did you create separate branches for B and C?
Comment: @mkrieger1 Yes and No... I dont know what the best pratice here! This is my question!
Comment: You need to reorder the commits `A-B-C` -> `A-C-B`, then push `C`. If you don't know how to do that, see e.g. https://stackoverflow.com/questions/4981061/how-to-re-order-commits-in-git-non-interactively or https://git-scm.com/book/en/v2/Git-Tools-Rewriting-History.
Answer: You can use git rebase -i HEAD~2 to remove the Version B in your history.
After git rebase -i HEAD~2, your EDITOR will open.  Just remove the FIRST LINE of the content, then save & exit EDITOR.  Then your Version B will be removed.

Apply branch locally only on Git


fscanf vs ifstream speed

Question: I conjectured that ifstream would be faster than fscanf because fscanf has to parse the format string every time it runs, whereas, with ifstream, we know at compile time what kind of "thing" we want to read.
But when I ran this quick and dirty benchmark
#include <ctime>
#include <cstdio>
#include <iostream>
#include <fstream>
using namespace std;

#define NUMBER_OF_NUMBERS 100000000

int nums[NUMBER_OF_NUMBERS];

int main(int argc, char** argv) {

    FILE * fp = fopen("nums.txt","r");
    auto start = clock();
    for (int i = 0; i < NUMBER_OF_NUMBERS; i++)
        fscanf(fp,"%d",nums+i);
    auto end = clock();
    fclose(fp);

    auto first = end - start;

    ifstream fin("nums.txt");
    start = clock();
    for (int i = 0; i < NUMBER_OF_NUMBERS; i++)
        fin >> nums[i];
    end = clock();
    fin.close();

    auto second = end - start;

    cout << "CLOCKS_PER_SEC : " << CLOCKS_PER_SEC << endl;
    cout << "first          : " << first << endl;
    cout << "first (sec)    : " << first / CLOCKS_PER_SEC << " seconds" << endl;
    cout << "second         : " << second << endl;
    cout << "second (sec)   : " << second / CLOCKS_PER_SEC << " seconds" << endl;
    cout << "diff           : " << second - first << endl;
    cout << "diff (sec)     : " << (second - first) / CLOCKS_PER_SEC << " seconds" << endl;

    return 0;
}

I got as output the following:
CLOCKS_PER_SEC : 1000000
first          : 12336249
first (sec)    : 12 seconds
second         : 25738587
second (sec)   : 25 seconds
diff           : 13402338
diff (sec)     : 13 seconds

ifstream is more than twice as slow as fscanf. Where does fscanf get all this speed?
EDIT:
I'm on a reasonably modern 64-bit intel mac, using command line tools that come with xcode, in case it is relevant at all.
Comment: The marked duplicate has almost nothing to do with this question, since the other post is about the standard streams, rather than `fstream`s. Nor is it the best post about the standard streams.
Comment: Are you running an optimized build? \
Comment: @PaulMcKenzie `g++ -Wall --std=c++11 test.cpp && ./a.out` is what i did originally, but I just tried again with `g++ -O3 -Wall --std=c++11 test.cpp && ./a.out` with similar results
Comment: Short answer: http://stackoverflow.com/questions/5166263/how-to-get-iostream-to-perform-better
Comment: @GregHewgill At least from a cursory look at that post, the accepted answer talks about console input. I would have imagined that the argument that "console speeds don't really matter" might not exactly apply when implementing file io. At the very least, I'm pretty sure `fscanf` above isn't using the `stdin` device
Comment: With constant formats, I've come across compilers that analyze the format at _compile_ time.  The basic `fscanf(fp,"%d",nums+i)` could be simplified then into some sort of `nums[i] = getint(fp)`.  Not saying that is what happened here - would need to inspect the assembly.
Comment: What happens if you swap the order of the two tests?
Answer: fscanf does not need to parse the format string at all.  It uses a greedy algorithm that looks for the '%' character and then uses a simple switch statement to generate the input.  ifstream on the other hand, needs to perform lookups on its vtable to determine how each minute detail of the input is used.
All this being said, fscanf cannot be extended without altering the C library, while ifstream is as easy as sub-classing it.
EDIT:
All of this is also part of the fact that C's fscanf library routine has had far more time/work put into it and more opportunities for optimization.  The C++ library is only arbitrary consequence of the C++ standard and thus has not had the same scrutiny applied to it.
Comment: @randomusername: Just because you are wrong is not a good reason to call me names
Comment: `It uses a greedy algorithm that looks for the '%' character and then uses a simple switch statement to generate the input.` If that's not "parsing" then I don't know what is. And I don't see where a virtual table comes into it; streams deal with their insertion operands through basic function overloading.
Comment: Does `ifstream` still need to consult its vtable even if I have instantiated on the stack? I thought virtual methods were only relevant when I was accessing through pointers, where the exact underlying type is unknown at compile time
Comment: Not the vtable of the things being printed, but the `ifstream`'s own vtable.  Because `ifstream` can be sub-classed (and thus a different set of vtable entries) it has to perform the lookup.
Comment: @randomusername: That's.. nonsense. This is implementation-defined but at least in libstdc++ `ifstream` isn't even polymorphic: it doesn't _have_ a virtual table (though its member `basic_filebuf` instantiation does). [Here's the source if you don't believe me](http://gcc.gnu.org/onlinedocs/gcc-4.6.2/libstdc++/api/a00881_source.html) (and this is why typical advice is _not_ to derive from standard containers or stream types)
Comment: @LightnessRacesinOrbit Please, sir high and mighty, grace us with the true answer then...

fscanf vs ifstream speed


How do I know if I am on Amazon EC2 account free plan

Question: How do I know if I am on Amazon EC2 account free plan? I just opened a new account yesterday and Amazon talks about a free plan for micro instances. But I don't see an indication in the console user interface that I am on a free plan.
Comment: Because we're systems administrators, not the EC2 support desk.
Comment: can someone care to post, why there is a down vote on the question.
Comment: Kindly don't get me wrong. I thought this was a forum to get help and I feel this is a genuine question, this has nothing to do with other participants being system administrators or developers. I would probably abstain, if I think the question is genuine. Just my 2 cents.
Comment: In that case you are mistaken. Firstly, this site is not a forum (see the [FAQ](http://serverfault.com/faq)). Secondly, we are very strict about the questions that people ask here. We only permit questions that are applicable to a wider audience that will be of use to people far into the future. Thirdly, we don't permit questions that have a very, very narrow scope (such as this one).
Comment: AWS offers a free plan and as a new user I would definitely want to know if I am on that plan and I truly believe it is applicable for all new users of EC2. If I can post in either in stackoverflow or serverfault where am I supposed to pose these questions?
Answer: IF you're a new signup and only running a micro instance, you're a free user. The console itself doesn't indicate; but if you go to 'account activity' and expand the EC2 section, it'll indicate your current expenses under the free tier.


Codeigniter: when to use a model vs library?

Question: I've starting using Codeigniter for a project recently (few months ago) but its getting a little out of hand with a bunch of models that need to interact with each other and I was wondering if I should be creating a library instead?
In my case, I have a user action that happens when you win a game and it would get logged in  my user_model but I also want it to get put in my events_model?
Should something like this that affects multiple models become a library?
I know it should NOT be in the controller because I'd have to reuse this trigger in multiple controllers (might not make sense for the provided example but does for my application).
Answer: Libraries are meant to provide reusable functionality for your application, while models in the MVC architecture represent the data logic in or the actual data used by your application.
So to answer your question, you can implement a library that handles updating of multiple models. Just ensure that things like database inserts are handled by your models themselves, as that is business logic more than application logic.
Answer: You could leave your models modularised as they are and write your logic in libraries, this way you can access mutilple models though a single function in a library, without making your controllers untidy by loading multiple models and having none-interface orientated logic mingled in with interface logic.


How to evaluate $\lim _{x\to \:0^+}\frac{\left(e^x+e^{2x}\right)^2-4}{\sqrt{9+sinx}-3}$?

Question: $$\lim _{x\to \:0^+}\frac{\left(e^x+e^{2x}\right)^2-4}{\sqrt{9+\sin x}-3}$$
I have tried with Taylor:
$$\lim _{x\to \:0^+}\frac{\left(1+x+\frac{x^2}{2}+1+2x+2x^2\right)^2-4}{\sqrt{9+x-\frac{x^3}{6}+\frac{x^5}{120}}-3}=\lim _{x\to \:0^+}\frac{\frac{25x^4}{4}+15x^3+19x^2+12x}{\sqrt{9+x-\frac{x^3}{6}+\frac{x^5}{120}}-3}$$
But now I dont know how to move forward.
I tried with Hopital and it was found to be so:
$$\lim _{x\to \:0+}\left(\frac{\left(e^x+e^{2x}\right)^2-4}{\sqrt{9+\sin \left(x\right)}-3}\right)=\lim _{x\to \:0+}\left(\frac{2e^{2x}\left(e^x+1\right)\left(2e^x+1\right)}{\frac{\cos \left(x\right)}{2\sqrt{\sin \left(x\right)+9}}}\right)$$
$$=\lim _{x\to \:0+}\left(\frac{4e^{2x}\left(e^x+1\right)\left(2e^x+1\right)\sqrt{\sin \left(x\right)+9}}{\cos \left(x\right)}\right)=\frac{4e^{2\cdot \:0}\left(e^0+1\right)\left(2e^0+1\right)\sqrt{\sin \left(0\right)+9}}{\cos \left(0\right)}=\color{red}{72}$$
But I wanted to know if you could get the same result even with Taylor? Thanks
Comment: How about first removing square root in the denominator?
Answer: $$\lim _{x\to \:0^+}\frac{\left(e^x+e^{2x}\right)^2-4}{\sqrt{9+\sin x}-3}$$
$$=\lim _{x\to \:0^+}\frac{\left(e^x+e^{2x}\right)^2-4}{\sin x}\cdot\lim _{x\to \:0^+}(\sqrt{9+\sin x}+3)$$
$$=\left(\lim _{x\to0^+}\frac{e^{2x}-1}x+\lim _{x\to0^+}\frac{e^{4x}-1}x+2\lim _{x\to0^+}\cdot\frac{e^{3x}-1}x\right)\cdot\dfrac1{\lim _{x\to0^+}\dfrac{\sin x}x}\cdot\lim _{x\to0^+}(\sqrt{9+\sin x}+3)$$
Now use $\lim_{h\to0}\dfrac{e^{mh}-1}h=m$ to get $$(2+4+2\cdot3)\cdot(\sqrt9+3)=72$$
Comment: Why becomes so $$\left(\lim _{x\to0^+}\frac{e^{2x}-1}x+\lim _{x\to0^+}\frac{e^{4x}-1}x+2\lim _{x\to0^+}\cdot\frac{e^{3x}-1}x\right)$$
Comment: @AmarildoAliaj, What is $$(e^x+e^{2x})^2?$$
Comment: $$\left(e^x+e^{2x}\right)\left(e^x+e^{2x}\right)$$
Comment: @AmarildoAliaj, Why don't you expand using $(a+b)^2$
Comment: I dont understand. Can you show me how? Thanks
Comment: @AmarildoAliaj, $$(e^x+e^{2x})^2-4=e^{4x}-1+e^{2x}-1+2(e^{3x}-1)$$
Comment: oh yeah, I forgot $-4$ thanks
Comment: @AmarildoAliaj: its even better to factor the numerator.
Answer: To simplify, let us first factor $(e^x+e^{2x})^2-4=(e^x+e^{2x}-2)(e^x+e^{2x}+2)$ and get rid of the square root with $(\sqrt{9+\sin x}-3)(\sqrt{9+\sin x}+3)=\sin x$.
Then
$$\frac{e^x+e^{2x}-2}{\sin x}=\frac{1+x+\frac12x^2\cdots+1+2x+2x^2\cdots-2}{x-\frac16x^3\cdots}=\frac{3x+\frac52x^2\cdots}{x-\frac16x^3\cdots}$$tends to $3$.
The final answer is
$$(1+1+2)(\sqrt9+3)\,3=72.$$

The fully painful way, with development up to second order yields
$$\frac{(1+x+\frac12x^2\cdots+1+2x+2x^2\cdots)^2-4}{\sqrt{9+x-\frac16x^3\cdots}-3}\\
=\frac{4+12x+19x^2\cdots-4}{\sqrt9+\frac1{2\sqrt9}(x-\frac16x^3\cdots)-\frac1{2\cdot2\cdot9\sqrt9\cdot2}(x-\frac16x^3\cdots)^2\cdots-3}=\frac{12x+19x^2\cdots}{\frac16x-\frac1{216}x^2\cdots}$$ which tends to $12\cdot6=72$.
[We used $\sqrt{a+x}=\sqrt a+\frac1{2\sqrt a}x-\frac1{2\cdot2\cdot a\sqrt a\cdot2}x^2\cdots$]


Conditional expectation of gaussian random variables

Question: Guys I'm stuck on a question in my textbook. Let me first tell you about the question before I explain what I don't understand.
Let $x:\Omega \to \mathbb{R}^n$, $x\in G(0,Q_x)$, $w:\Omega\to\mathbb{R}^k$,$w\in G(0,Q_w)$, $Q_w = Q^T_w > 0$, $C\in\mathbb{R}^{k \times n}$ (where G means Gaussian random variable with mean and variance as specified). Assume that $x,w$ are independent random variables. Define $y:\Omega\to\mathbb{R}^k$ by
$y = Cx+w$.
Determine an expression for $E\left[x|\mathcal{F}^y\right]$, and for $E\left[e^{iu^T x}|\mathcal{F^y}\right]$.
By two different prepositions from my textbook I found that:
$y\in G\left(0,CQ_x C^T+Q_w\right)$. So let's call $Q_y = CQ_x C^T+Q_w$. Now I don't understand how to calculate the cross covariance matrix $Q_{xy}$. Because once I find $Q_{xy}$ then I know that:
$E\left[x|\mathcal{F^y}\right] = m_x + Q_{xy}Q_y^{-1} \left( y-m_y \right) = Q_{xy}Q_y^{-1}y = Q_{xy}Q_y^{-1}\left(Cx+w\right)$
and
$E\left[e^{iu^T x}|\mathcal{F^y}\right] = e^{iu^T E\left[x|\mathcal{F^y}\right] - \frac{1}{2} u^T \tilde{Q}u}$, where $\tilde{Q} = Q_x-Q_{xy}Q_y^{-1}Q_{xy}^T$
(given by $E\left[\left(x-E\left[x|\mathcal{F^y}\right]\right)\left(x-E\left[x|\mathcal{F^y}\right]\right)^T\right] = \tilde{Q}$)
Answer: Note that since all involved Gaussians have "unconditional" mean zero, the covariance matrix of $x$ and $y$ is given by
$$\mathbf{E}[yx']=C \mathbf{E}[xx']+ \mathbf{E}[wx'] = C \mathbf{E}[xx']=CQ_{xx}$$ where I used that $x$ and $w$ are independent. The apastrophe ' denotes the transpose operator.


.REMOTE and .Local results are reversed

Question: I am using SourceTree for performing/managing my file commits, pushes, pulls and merges.
I use BeyondCompare as the external Merge/Diff tool and have it set in the options. While managing one of the merge conflicts, I launched the Bcomp; this brings up 3 panes ending with .LOCAL, .REMOTE and .MERGED in their file names and the order is same as I mentioned in the Source Tree command line.
Here is the confusion and the issue -
    I notice that the .LOCAL file has the content of the .REMOTE and .REMOTE has my local changes as if it's trying to understand it in exactly opposite way. Just don't get this at all. Do I have a bad setting/config in Bcomp or SourceTree that is resulting in opposite content?
My understanding is :

Local : meaning the file I have made my changes locally and have got the conflict upon while pulling others
Remote : Is the file/content that has been pushed to pushed to the master ahead of me and is something I am pulling or merging with.

Sometimes I see this in the merged files
<<<>>>>

Can someone tell what when exactly do we get it, and will it ever happen if I use external merge tool like Bcomp. Does GIT put these to indicate something, and we need to manually remove it and save the file to avoid compilation errors
Comment: If you are rebasing LOCAL and REMOTE and reversed from what you expect.
Answer: See "git rebase, keeping track of 'local' and 'remote'", where I explained a rebase switches ours (current branch before rebase starts) and theirs (the upstream branch on top you want to rebase).
As torek expained in "What is the precise meaning of "ours" and "theirs" in git?"

The reason the "ours" and "theirs" notions get swapped around during rebase is that rebase works by doing a series of cherry-picks, into an anonymous branch (detached HEAD mode).
  The target branch is the anonymous branch, and the merge-from branch is your original (pre-rebase) branch:
  so "--ours" means the anonymous one rebase is building while "--theirs" means "our branch being rebased".

In that context:
+--------------------------------+
| LOCAL  |     BASE     | REMOTE |
+--------------------------------+
|             MERGED             |
+--------------------------------+

local references the partially rebased commits: "ours" (the upstream branch)
remote refers to the incoming changes: "theirs" - the current branch before the rebase.

.REMOTE and .Local results are reversed


What is the intuition behind matrix splitting methods (Jacobi, Gauss-Seidel)?

Question: Descent Methods, like Gradient and Conjugate Gradient ones, have a nice geometric interpretation and I really love them. What about Jacobi, Gauss-Seidel or other matrix splitting methods? I can't see any intuition behind the formulas.
A posteriori I know that these methods works because of Banach Fixed Point theorem but I still need a more stimulant picture.
Any ideas?
Answer: I'm not really sure what do you mean by intuition behind the methods, but all classical iterations for solving $Ax=b$ are based on splitting
$$
A=M-N,
$$
where

$M$ is nonsingular and easy to invert,
$M\approx A$ in some sense.

The equation $Ax=b$ is then equivalent to
$$Mx=Nx+b=Mx+(b-Ax),$$
which "naturally" defines a fixed-point iteration
$$
x_k=M^{-1}Nx_{k-1}+M^{-1}b=x_{k-1}+M^{-1}(b-Ax_{k-1}).
$$
Note that the second expression is more suitable in practice as it does not involve the "residual" matrix $N=M-A$.
There are many ways how to choose $M$ (assume $A=D-L-U$ is a splitting of $A$ to diagonal and lower and upper triangular parts):

$M=\alpha I$: Richardson method,
$M=D$: Jacobi method,
$M=D+L$ or $M=D+U$: forward and backward Gauss-Seidel method,
$M=(D+L)D^{-1}(D+U)$: symmetric Gauss-Siedel method,
etc. like SOR, SSOR, HSS, block splittings; you can also realize $M$, e.g., by incomplete factorizations or approximate inverses. There are literally tons of possibilities.

Splitting methods have a property that the errors are transformed in the same way independently of the iteration:
$$
x-x_k=(I-M^{-1}A)(x-x_{k-1})=(I-M^{-1}A)^k(x-x_0).
$$
From the spectral point of view, this has an advantage that (in contrast with CG or steepest descent) the spectral components of the initial error are damped with (asymptotically) the same rate from iteration to iteration. This has an important application, e.g., in multigrid methods, where methods like Jacobi and Gauss-Seidel are often used as smoothers since they efficiently damp (for PDE-related problems) the oscilatory error components associated with large eigenvalues.
Another particular motivation for Jacobi and Gauss-Seidel methods is that they zero out certain components of the residual vector $b-Ax$. Given an approximation $x_k$, the $i$th component of $x_{k+1}$ of the Jacobi iterate is computed simply by solving the $i$th equation of $Ax=b$:
$$\tag{$*$}
(x_{k+1})_i=\frac{1}{a_{ii}}\left(b_i-\sum_{j\neq i}a_{ij}(x_k)_j\right).
$$
If $z_i=[(x_k)_1,\ldots,(x_k)_{i-1},(x_{k+1})_i,(x_k)_{i+1},\ldots,(x_k)_n]^T$, we have $(b-Az_i)_i=0$. If the Jacobi update is executed in a loop for $i=1,\ldots,n$, the components $(x_{k+1})_j$, $j=1,\ldots,i-1$, can be already used on the right-hand side of ($*$), which leads to the update
$$\tag{$**$}
(x_{k+1})_i=\frac{1}{a_{ii}}\left(b_i-\sum_{j<i}a_{ij}(x_{k+1})_j-\sum_{j>i}a_{ij}(x_k)_j\right).
$$
This leads to the (forward) Gauss-Seidel iteration. Switching the loop order and the indices $k$ and $k+1$ on the right-hand side in ($**$) gives the backward Gauss-Seidel iteration. Again, we can interpret it as zeroing out a certain component of the residual vector.
Comment: Are backward Gauss - Siedel method and Jacobi method just the same ?
Comment: @PriyadarshiPaul Only if $A$ is lower triangular (then $U=0$ and $M=D$ for both methods).
Answer: These methods are highly intuitive and natural, but the idea isn't always explained clearly.  Jacobi and Gauss-Seidel are the simplest things you would try if you were going to invent your own iterative method for solving $Ax = b$.
The first equation in $Ax = b$ is
\begin{equation}
A_{11} x_1 + A_{12} x_2 + \cdots + A_{1n} x_n = b_1.
\end{equation}
This equation suggests a way to update our estimate of $x_1$:
\begin{equation}
x_1^{k+1} = \frac{b_1 - A_{12} x_2^k - \cdots - A_{1n} x_n^k}{A_{11}}.
\end{equation}
Our estimates of $x_2,\ldots,x_n$ are updated in the same way, all updates performed in parallel.  Then we've got the full vector $x^{k+1}$, and we're ready for the next iteration.  That's the Jacobi method.
The Gauss-Seidel method is just like the Jacobi method, except that you update the variables one at a time (rather than in parallel), and during each update you use the most recent value for each variable.
As an afterthought you can express these methods as splitting methods using matrix notation.  But that obscures how obvious they are to invent.
Comment: Summary of the thought process for Gauss-Seidel: Suppose we have an estimate of a solution to $Ax= b$. We can see that the first equation in $Ax = b$ is not quite satisfied though. Ok, so we just change the value of the first component of our vector so that the first equation in $Ax = b$ is satisfied. But then the second equation in $Ax=b$ is not satisfied. Ok, so we change the value of the second component of our vector to make the second equation in $Ax = b$ be satisfied. And so on. This is like the dumbest thing that someone would try doing, but it turns out to actually work.
Comment: @minhNghia You might be able to convince yourself that if the iteration converges at all, then the vector $x^*$ that it converges to must satisfy $Ax^* = b$. ( Think about what it would mean for example if $x^{k+1} = x^k$ in the equation I wrote above.) Now, as to why we would expect the iteration to converge at all, I don't have a good intuitive way to see that, but it is certainly something you can hope will happen. (And it is certainly something that you can try, to see if it happens in practice.)
Comment: I still don't understand the intuition after all iterative methods. How can you move one variable to the LHS, calculate it based on the other variables, and *expect* it to converge to the fixed point/solution?
Answer: In order to see the idea of how the Jacobi Method works, the straightforward approach is to use the very useful Contraction Mapping principle, which is roughly,
if there is a constant $0\le c<1$ such that $\|F(x_{k+1}) − F(x_{k}) \|\le c\|x_{k+1} – x_{k}\|$, then you can see with a little thought, that the iteration $x_{k+1} = F(x_{k})$ will converge to a fixed point.
Now would be a good time to review the Contraction Mapping principle, since iterative methods are an easy downhill slide from there.
Thus we need to convert $Ax=b$ into a form $x_{k+1} = F(x_{k})$. The most apparent conversion is to extract the diagonal elements of $A$, because a diagonal matrix has a simple inverse,  \begin{align*}
Ax &= b,  \\
(A - D + D)x &= b,   \\
(A - D)x + Dx &= b,   \\
Dx &= b - (A - D)x,   \\
x &= D^{-1}b - D^{-1} (A - D)x,
\end{align*}
and iterate as,
$$x_{k+1}  = D^{-1}b - D^{-1}(A - D) x_k$$
This is the Jacobi iterative method.
Importantly, notice above, that if you have a value for x that satisfies the relation Dx = b - (A - D)x, then x also satisfies Ax = b.
Now there is no guarantee that this will be a contraction mapping, but often it is.  And it will contract when the diagonal elements are dominant.
What would motivate you to do this? An easy-peasy motivation starts with the rudimentary relaxation method. First assume that the diagonal elements of A are much larger than the off-diagonal elements of A.  In this case the inverse of A is approximately the inverse of D, which is simple to calculate.
Compute a residual:
$$r = b - Ax_k$$
Compute an approximate correction:
$$Correction  = D^{-1}r$$
Then,
\begin{align*}
x_{k+1} &= correction + x_k,  \\
x_{k+1} &= D^{-1}r + x_k,  \\
x_{k+1} &= D^{-1}(b - Ax_k) + x_k  \\
x_{k+1} &= D^{-1}b - D^{-1}(A - D)x_k,  \\
\end{align*}
And this is the Jacobi method from the relaxation method.
There you have it.
Comment: This is such a wonderful answer from exactly 2 years ago to the day. Thank you.
Answer: The idea is that you assign to each equation a dominant variable and solve the equation for this variable. The assignment should result in a bijective relation between equations and variables
Then use these partial solutions in some kind of fixed point scheme, the dominant ones are the Gauß-Seidel and Jacobi schemes. This works especially well if the original system matrix is a small perturbation of a diagonal matrix.
Closely related are sparse reordering methods for sparse matrices, these often also start with the formulation of an assignment problem equations to variables, and solving it with, e.g., the Hungarian algorithm.
Answer: A good approach for an intuitive understanding of the Jacobi method is to pretend that you are presented with a system of linear equations to solve, and you need to invent a way to solve them. The exercise below shows how you would naturally invent the general idea of using iterative solutions of linear equations, including the Jacobi method.
P.S. First recall the general concept of any iterative relaxation:
Step 1: Calculate a residual value that measures a difference between a current approximate solution and the true solution.
Step2: Perform an operation on the input variables that will reduce the residual value of a new approximate solution.
Step 3: Perform these steps until the residual is small enough.
A system of linear equations L1, L2, L3… has variables x1, x2, x3…, and is expressed in matrix form as Ax=b. The core idea developed below is solving a system of linear equations by inventing an iterative relaxation method of shrinking the length of a residual error vector toward zero (residual vector = Ax-b). Then the method is modified to perform a group of iterations in parallel in order to produce essentially  the Jacobi method.  The Jacobi method to solve linear equations is evolved by starting from a well-known, hill-climbing, multidimensional, gradient-free minimization method that shrinks the length of a residual error vector (residual vector = Ax-b) to zero, at which point the x vector then solves the linear equations.
For teaching purposes, we assume that the linear equations have strict diagonal dominance in order to ensure convergence below. Each linear equation L1, L2, L3… defines a "plane" (in 2D, 3D, 4D…) and is associated with the corresponding variable x1, x2, x3…. First, a trial point x1, x2, x3… is guessed. At each iteration, the method then cyclically adjusts each x1, x2, x3… in turn along the corresponding axis direction until the length of the residual vector is minimized in that direction, which needs numerous calculations of the length of the residual vector. Next, and importantly, you notice that when each x1, x2, x3… is adjusted, that the minimum value of the length of the residual vector always occurs when the trial point is adjusted to lie in the "plane" of the linear equation corresponding to the variable x1, x2, x3…. Because the equations are linear, this adjustment can be directly calculated. Thus the residual vector no longer needs to be calculated, and the calculation is removed, leaving only the iterative algorithm. This method of cyclically adjusting the trial point is seen to converge because it reduces the length of the residual vector at each iteration.
At this point, you essentially have the Gauss-Seidel method. Finally you notice that the adjustments above to x1, x2, x3… can be made independently and simultaneously, which is essentially the Jacobi method. When the algorithm is expressed algebraically in an iterative matrix form, it becomes $x^{k+1} = x^{k} - D^{-1}(Ax^k - b)$, where D is the diagonal matrix.
Backing up a bit, you see that changing x1 may reduce the residual element of the first equation L1, but also changes the residuals of the other equations L2, L3, L4…, sometimes increasing the individual residual element length and sometimes decreasing the individual residual element length, but we easily notice that the total decreases are always more than the total increases: the sum of the lengths (i.e., absolute value) of all the residual elements (the L1 metric) always decreases, and we realize that this means that eventually the residual vector will be reduced to zero. This is ensured because of diagonal dominance, as assumed above.  Thus we will use the L1 metric for the length of the residual vector.  In other words, you are adjusting x1 in order to reduce the total residual vector, not specifically to reduce the residual of the first equation L1, but because of diagonal dominance, it happens that the residual of the first linear equation will shrink the most. Similarly, adjusting x2 will reduce the residual of the second liner equation the most.  It is old and well-known to use the L1 metric in minimization methods, as discussed in many references on minimization.
We see that $D^{-1}$ is used as an approximate inverse matrix by using the diagonal terms of A as an approximation of the original matrix. You can see that this is not  a bad idea when the diagonal terms are strongly dominant. In other words, when the diagonal terms are dominant, then the system of linear equations is approximated by setting the off-diagonal terms to zero; that is, each linear equation is approximated by the single largest term. The idea of an approximate inverse matrix is another valuable idea from the Jacobi method.
This iterative process motivates the use of general iterative methods to solve linear equations.
For a more detailed discussion of an intuitive  explanation of the Jacobi method, see the document at  https://doi.org/10.6084/m9.figshare.5969263.v1
Answer: Let me assume that $A$ is symmetric and invertible. Solving the linear system $Ax = b$ is equivalent to minimizing quadratic function $\frac{1}{2}x^T A x - b x$. Classical splitting methods such as Jacobi, Gauss-Seidel etc. define an invertible matrix $P$ and use the trivial identity $A = P + (A - P)$ to rewrite the linear system $Ax = b$ like this:
$$
Px = (P-A)x + b \\
x = x + P^{-1}(b - Ax) \\
x^{k+1} := x^{k} + P^{-1}(b - Ax^{k}) \\
$$
where the last line is an update rule for the iterative method. This iterative method becomes gradient descent if you set $P$ to be the identity (or scaled identity for if you want to adjust the step size). For Jacobi, you set $P$ to the diagonal of $A$ and so on for other methods. Any setting of $P$ can be seen as a Quasi-Newton method -- the idea of Quasi-Newton methods being that we try to transform the gradient in attempt to get better convergence. Intuitively, $P$ should be an approximation of $A$ that is easily invertible. The gradient descent's $P = I$ is one extreme. The opposite extreme is full (i.e., non-Quasi) Newton's method, which corresponds to setting $P$ to $A$. The update rule then ends up saying: "if you can directly compute $A^{-1} b$ then you don't need to iterate at all."


Problem by creating nodes in loop

Question: i am new to drupal and trying to migrate same pages to drupal. I am able to create one node via druapals API, but when trying to create more nodes in a loop it doesn't work...
This is the working code:
    define('DRUPAL_ROOT','/var/www');
    require '/var/www/includes/bootstrap.inc';
    drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

    #construct the new node object
    $node = new stdClass();

    #specify node properties
    $node->uid = 1;
    $node->title = "new node";
    $node->log ="";
    $node->status = 1;
    $node->comment = 1;
    $node->promote = 0;
    $node->sticky = 0;
    $node->type = 'veranstaltung';
    $node->language = 'und';
    $node->created = time();
    $node->changed = $node->created;
    $node->tnid=0;
    $node->translate=0;
    $node->body['und'][0]['value']="
content
";
    $node->body['und'][0]['format']="filtered_html";
    $node->body['und'][0]['safe_value']="
content
";

    #save node
    node_save($node)

If i put this in a for-loop and change the body and title each iteration it doesn't work.. The code is inside an external php script. Even copy the code and paste behind it again with other body and title does not work.
Thanks a lot
Comment: Objects are passed by reference in PHP; therefore `$node->nid` is being set after your first go around the for loop.  If `$node->nid` is set, no new node is created, so, I'd `unset($node->nid)` after each `node_save()` and give it another try.
Comment: Better run this script using Drush. It's very easy to use it for running scripts. It'll automaticaaly bootstrap Drupal.
Answer: Objects are passed by reference in PHP; therefore $node->nid is being set after your first go around the for loop. If $node->nid is set, no new node is created, so, I'd unset($node->nid) after each node_save() and give it another try.
Answer: Try function node_object_prepare()
$node = new stdClass();
$node->type = 'thing';
node_object_prepare($node);
$node->title = 'Test thing';
// ...more node properties...
node_save($node);
$nid = $node->nid;
print 'nid of the node I just created: ' . $nid;

You can also include your code in a custom module in a hook_init() or a hook_cron(), you'll not need to boostrap drupal

Problem by creating nodes in loop


Hyper-parameter turning using cross validation in random forest----test set AUC higher than cross validated AUC

Question: I am training a random forest model to predict a certain outcome.
I split my data into an 80% training and 20% test set.  In the training data, I used a grid-search to select optimal hyperparameters based on which hyper-parameters yielded the highest 5-fold cross AUC in this training set.
I then trained the model using these hyperparameters on the training set and determined the AUC on the test set.
I have a second external validation set which I also determined the AUC on.
Here are my results:
80% Training set AUC: 89 (95% CI: 85-92)
5-fold cross validation AUC in 80% training set: 64
20% Test set AUC: 80 (95% CI: 71-89)
External test set AUC:  70 (95% CI: 54-85)
My concern is that the 5 fold cross validation in the training set is so much lower than the other AUCs.  I looked across several resources all of which suggested that the cross-validation AUC should only be used for selecting hyper-parameters and not for model evaluation.
Should I be concerned/distrustful of these results?
Answer: The difference is indeed significant, but it is hard to say without knowing the size of the dataset.
I can think of two possible reasons why you might have such a big difference:

Your dataset is not particularly big, and therefore when running on a 5-Fold validation you are only using 4/5 of the 80% of your dataset (which is 64%) which might be insufficient for your RF to perform well

and/or

Your dataset is not shuffled (idk how you are performing the train/test split nor the CV), and therefore issues very different performance based on the set it is training on

Finally, I would suggest you try using the Out Of Bag error of Random Forests instead of the 5 fold CV.
Basically this gives you an estimate of your TEST error (equivalent to a Cross Validation) by using the forecasts that your trees make on the data they were not trained on (because of the bootstrapping).
This is easier to do than a 5 fold CV, it does not reduce the size of the sample, and does not take any extra time. This will give you an extra estimate that you can compare to your test and then validation set results.
EDIT:
I am also adding an extra information on how to cross-validate using the AUC, as it can be misleading:
Appropriate way to get Cross Validated AUC
Comment: Thank you so much and sorry for the late reply.  I have 1020 datapoints in my training set.  only 10% of the datapoints contains the variable that I am trying to predict for (this is a patient dataset and I am predicting cancer patient survival--only 10% of patients died, creating an unbalanced dataset)
Comment: Additionally, my oob error is ~40%....which is really really high.....any tips on how to improve this in a random forest survival model?  I'm using the randomForestSRC package.


How to align separated equations in LaTeX?

Question: I can use the align environment to properly align non-separated equations like this:
begin{align}
a^2 + b^2 &= c^2\\
          &= d
\end{align}

but how can I align separated equations with text inbetween? For example:
\documentclass[12pt, a4paper]{article}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}

\begin{document}

My first equation:

\begin{equation}
a^2 + b^2 &= c^2
\end{equation}

My second equation:

\begin{equation}
1 = 3 - 2
\end{equation}
\end{document}

I would like the two equations to be aligned at the equality sign.
Answer: You could place both equations in an align environment and add the text in between with \intertext{...}:
\documentclass[12pt, a4paper]{article}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}

\begin{document}

My first equation:

\begin{align}
a^2 + b^2 &= c^2\\
\intertext{My second equation:}
          &= d
\end{align}
\end{document}

Comment: In this case, it seems `\shortintertext` (from [`mathtools`](//ctan.org/pkg/mathtools)) seems equally appropriate.


Find the minimum of $|z+\frac{1}{z}|$ for $|z|\ge2$

Question: Find the least value assumed by the function $w=|z+\frac{1}{z}|$ where $,|z|\ge2$

Attempt
By triangular inequality,$|z+\frac{1}{z}|\ge ||z|-|\frac{1}{z}||$
$|z|\ge2......................(1)$
$|\frac{1}{z}|\le\frac{1}{2}$
$-|\frac{1}{z}|\ge\frac{-1}{2}.........(2)$
$|z|-|\frac{1}{z}|\ge2-\frac{1}{2}$
$|z|-|\frac{1}{z}|\ge\frac{3}{2}$
so $|z+\frac{1}{z}|\ge \frac{3}{2}$
But the answer given in my book is $-\frac{1}{8}$
Comment: $-\frac 18$ or $+\frac 18$? Absolute value cannot be negative.
Comment: A negative answer must be wrong, and I find your calculations persuasive:  $z=\pm2i$ will give $\frac32$
Answer: Let $r = |z| \ge 2$ then
$w=|z+\frac{1}{z}| = |r e^{i \phi}+\frac{1}{r} e^{-i \phi}|= r |1 +\frac{1}{r^2} e^{-2 i \phi}|$.
Now the minimum w.r.t. $\phi$ is obtained for $\phi = \pi/2$ and we get
$w \ge r |1 -\frac{1}{r^2}| = r - 1/r$.
Now for $r \ge 2$, the last expression takes its lowest value at the boundary, i.e. at $r=2$, which gives $3/2$.  This is tight, since $z = 2 i $ gives exactly that result.


Trying to understand a proof for the limit points of $\cup_{n=0}^{\infty}K_n, K_n = \{(1/n) + (1/m)\mid m=n,n+1,\dots\}$

Question: While reviewing my answer to the exercise of 13 of chapter 2 of Baby Rudin I happened to stumble across a detailed solution manual by Kit-Wing Yu, A Complete Solution Guide to Principles of Mathematical Analysis. In this guide Yu's answer is illustrative, yet I am stuck at understanding why a neighborhood of a point $p \in [0, 1]\setminus K_0, K_0 = \{0, 1, 1/2,\dots\}$ can only contain finitely many elements of the set $K$. Below a paraphrasing of the solution:

We define $K_0 = \{0, 1, 1/2,\dots\}, K_n = \left\{\frac{1}{n} + \frac{1}{m}\mid m=n,n+1,\dots\right\}, n = 1,2,\dots$, and $K = \cup_{n=1}^{\infty}K_n$. By definition $K_0$ and $K_n$ have limit point 0 and $\frac{1}{n}$ respectively. Therefore we have $\{0, 1, 1/2,\dots\}\subseteq K'$. We claim that $K' = K_0$. pause

Yu next shows that necessarily $K' \subseteq [0, 1]$. This is clear to me and it is not used in rest of the proof, so I am going to skip it.

continue Next, suppose that $p \in [0, 1]\setminus K_0$. By this assumption there exits a positive integer $k$ such that $\frac{1}{k+1} < p < \frac{1}{k}$. Since $\frac{1}{n} + \frac{1}{n}\geq \frac{1}{n} + \frac{1}{m}$ and $\frac{1}{n} + \frac{1}{n}\geq \frac{1}{m} + \frac{1}{m}$ for all $m\geq n$, $\frac{2}{k+m}$ is the maximum of the set $K_{k+m}\cup K_{k+m+1}\cup\dots$. Define $\delta = \frac{1}{2}\min\{ p - \frac{1}{k+1}, \frac{1}{k}-p\}$, so $(p - \delta, p + \delta) \subset (\frac{1}{k+1}, \frac{1}{k}).$ If $\delta = \frac{1}{2}(\frac{1}{k} - p)$, then we have $p - \delta = \frac{3p}{2} - \frac{1}{2k} > \frac{1}{2}(\frac{3}{k+1} - \frac{1}{k}) = \frac{2k - 1}{2(k+1)^2} > \frac{2}{k+m}$ for all $m > \frac{4(k+1)^2}{2k - 1}$. In this case, the interval $(p - \delta, p + \delta)$ contains only finitely many elements of the set $K_1 \cup K_2\cup \dots \cup K_{m-1}$. [paraphrasing ends]

I am stuck at understanding what relation does the maximum element of $K_{k + m}\cup K_{k + m + 1} \cup \dots$ have with the elements of the set $K_1\cup K_2 \cup \dots \cup K_{m-1}$, i.e. why are there only finite number of elements of $K$ in the interval $(p - \delta, p + \delta)$. Namely I think the idea is that the lower bound $p - \delta$ is less than the maximum element $\frac{2}{k + m}$ when $m$ is in a certain range of values, so that necessarily some elements of some $K_m$s reside in the interval $(p - \delta, p + \delta)$.  But I can't say for sure.
Comment: FYI, that $K' \subseteq [0,1]$ is used in the rest of the proof. If it were not true, then choosing $p \in [0,1] \setminus K_0$ would not be sufficient to show that $K$ had no limit points outside of $[0,1]$.
Comment: Perhaps this helps: https://math.stackexchange.com/q/3121709
Answer: Sometimes it is too easy to get caught up in minute details and miss the big picture.
All you need for this is a neighborhood $U$ of $p$ whose closure misses every $\frac 1n$. Since $\frac 1{k+1} < p < \frac 1k$, such a neighborhood must exist. $\left(\frac 1{k+1}, \frac 1k\right)$ works for every $\frac 1n$ except $n = k$ or $n = k+1$, and by shrinking it a bit, those two values are missed as well.
Now the maximum shows that for high enough $n, K_n$ does not intersect $\left(\frac 1{k+1}, \frac 1k\right)$ at all, much less the smaller neighborhood of $p$. So there are only a finite number of $K_n$ that intersect with $U$.
Also, in each $K_n$ there is only one limit point, $\frac 1n$. And if you choose any neighborhood of $\frac 1n$, only a finite number of points in $K_n$ lie outside that neighborhood. This is because there will be $\epsilon > 0$ such that $\left(\frac 1n - \epsilon, \frac 1n + \epsilon\right)$ is within the neighborhood, and for all $m > \frac 1\epsilon, \frac1n + \frac 1m$ is within $\epsilon$ of $\frac 1n$.
But $U$ was chosen so that $\Bbb R \setminus \overline U$ is a neighborhood of every $\frac1n, n \ge 1$. Hence each $K_n$ only has a finite number of points in  $U$, and only a finite number of the $K_n$ intersect $U$ at all. And the union of a finite collection of finite sets is finite. Since finite sets do not have limit points, $K' \cap U$ is empty, and $p \notin K'$.
Comment: While this approach might not be as "pretty", could the proof be finished by first setting $m > k(k + 1)$, so that $\frac{1}{k+1} + \frac{1}{m} < \frac{1}{k}$, then taking a center $p$ such that $\frac{1}{k+1} < \frac{1}{k+1} + \frac{1}{m+1} < p < \frac{1}{k+1} + \frac{1}{m} < \frac{1}{k}$, and finally choosing $\epsilon = \frac{1}{2}\min\left\{\left|p - \frac{1}{k+1} - \frac{1}{m+1}\right|, \left|\frac{1}{k+1} + \frac{1}{m} - p\right|\right\}$, so that no point of $K$ resides in the neighborhood $N_\epsilon(p)$?
Comment: You don't get to choose $p$. The object is to prove for any $p \in [0,1]\setminus K_0$ that $p \notin K'$. So $p$ is an arbitrary point of the indicated set. You then have to make the things you can choose work for that $p$.


In a class, there are 15 boys and 10 girls. Three students are selected at random. The probability that 1 girl and 2 boys are selected, is:

Question:
Then, n(S) = Number ways of selecting 3 students out of 25 = 25C3 =
  2300.
n(E)= (10C1 x 15C2) = 1050
P(E) = n(E)/n(s) = 1050/2300 = 21/46

I know the above method of obtaining answer using formula.

But without applying the formula, trying to solve it , gives
  me a different answer.

Probability of selecting girl = 10/25
Next, Probability of selecting 1 boy = 15/24
(24 because 1 girl is already selected)
Next, Probability of selecting another boy = 14/23
(23 because 1 boy and 1 girl were already selected)
(14 because 1 boy was already selected before)
So,

P(E) = n(E)/n(s) = (10x15x14)/(25x24x23)=2100/13800=21/138=7/46

why am i getting 7/46 ?
Comment: Your second method is the probability of very specifically picking in sequence a girl followed by a boy followed by another boy.  If you were to pick in sequence though, for the original problem you could also have picked a boy then a girl then a boy or also picked two boys and then a girl, each scenario being just as likely to occur as the one you calculated, making your answer off by a factor of three.
Comment: Multiply your answer of $\frac{7}{46}$ by three to account for the three different orders that you could arrange the genders of the people you selected so that the overall outcome totals two boys and one girl.
Comment: so, what should i do to get 21/46 ?
Answer: Since we are selecting $2$ of $15$ boys, $1$ of $10$ girls, and $3$ of $25$ total people, the probability is $${{15\choose{2}} {10\choose{1}}}\over{{25\choose{3}}}$$ $$= \frac{21}{46}$$
Your second method is incorrect because you are assuming we select a girl, a boy, and then another boy in that particular order. In reality, it can be any order $gbb$, $bgb$, $bbg$, giving $3$$7\over{46}$ $=$ $21\over46$


Input text validation while input?

Question: In my html page i want user to add a string in specific order in input type=text.
if i use pattern in input tag then the error will pop while submiting form and i want it while typing.
The required pattern is 4Letters and then 4Numbers No white Space No Special Character Allowed
The Pattern i used in my backend is ^[A-Z]{4}[0-9]{4}$
How can i achieve this ?
Edit
To The Moderators :
I Never said that the error was because of typo. Where did i mentioned it ? Closing question did not provides solution whoever it was you should have read the thread.
I haven't accepted answers as they are not working as intended.
Working on the solution.
Need this thread to opened again. Thank you
Comment: You swapped the letters and numbers in the pattern, try `pattern="\d{4}[A-Za-z]{4}"`
Comment: I want to disallow while tying if the pattern is not matched how can i do that ?
Comment: @ChandraShekharAazad what do you want to disallow ? A button ?
Comment: No, let me try to explain: the user in text input is typing the string, (the format/pattern of string is mentioned in the main question), after uer enters 4letter now user needs to enter 4number but if the user enter a letter the input text should not allow that letter. and all this i want while typing.
Comment: @ChandraShekharAazad Then you should implement javascript that removes the letter if it's in position 4 or later
Answer: I tried by adding a function call on input changes, so when the user will be typing it will test if the user input matches the pattern or not.
Note

Pattern : ^[0-9]{4}[A-Z]{4}$ matches the string like this 1234ABCD
For changing the Pattern, we require to do 3 changes

In HTML input field, we need to update the pattern
In JS the testText we need to update the string

testText contains, sample string that fully matches the pattern

(Optional) According to the requirement we can update the textElem.innerHTML value.

const textElem = document.querySelector(".text__error");

function checkText(event) {
    let testText = "1234ABCD"; // sample string that fully matches the pattern
    const { target } = event;
    if (!target.checkValidity()) {
        const { value } = target;
        testText = value + testText.slice(value.length);
        const re = new RegExp(event.target.pattern);
        if (!re.test(testText)) {
            target.value = value.substr(0, value.length - 1);
            if (!target.checkValidity()) {
                textElem.innerHTML = "Invalid, e.g. 1234ABCD ";
            } else {
                textElem.innerHTML = "Valid";
            }
        } else {
            textElem.innerHTML = "";
        }
    } else {
        textElem.innerHTML = "Valid";
    }
}
<form action="">

Text :
        <input type="text" pattern="^[0-9]{4}[A-Z]{4}$" required oninput="checkText(event)">

        <input type="submit" value="Submit">

</form>
Answer: there is risk of getting downvoted :) but still here is my solution. I tried to solve it using one regex but that didn't work so i used two regex to check the pattern and i am removing the last element from string if it is invalid.

$(document).ready(function() {
  $('#typehere').keyup(function(el) {
    let valid = true;
    let regex = /^\d{0,4}$/;
    let regex1 = /^\d{0,4}[a-zA-Z]{0,4}$/;
    if (this.value.length < 5) {
      valid = regex.test(this.value)
    } else {
      valid = regex1.test(this.value)
    }
    if (!valid) {
      console.log(valid)
      this.value = this.value.substr(0, this.value.length - 1);
    }

  })
})

<input type="text" id="typehere" />

Input text validation while input?


Why do Dense layers perform better than a mix of Conv Layers, Recurrent Layers on Sentiment Analysis with BERT emebddings?

Question: I have used BERT to make embeddings out of the imdb review dataset and I am trying out some models to check their perfomance on sentiment analysis (0 for the bad reviews and 1 for the good ones). I have seen that models with just dense Layers do work better than models which are a mixture of Convolutional with MaxPooling Layers and recurrent units such as LSTM or BiLSTM.I want to know why is this happening since BERT do captures of semantics and time dependencies so second models should perform better.
I am speaking about orders from 85% accuracy with dense layers to 75% with the mix of Layers.
Thanks in adavance
Answer: I would think that the problem of doing this kind of simple sentiment analysis is "pointwise enough" on words that even a simple logit or probit model trained purely on frequency analysis of words (so neglecting all of the sentence structure, ordering, et cetera) should be able to get good enough results. The additional power of an LSTM can end up leading it astray if a simpler model would've been sufficient to get a good fit, just because of the problems of gradient descent.
Moreover, it's not true that in limited dimensions, convolutional nets or dense layers are incapable of learning global information if it's "simple enough". The power of an LSTM really only becomes apparent when you have long sentences and you need to gain insight into some complex dependencies between different parts of the sentence - for instance, parsing tasks are well suited to be tackled by LSTM. Notice that you don't need to parse a sentence to determine the sentiment of the person who wrote it!
Still, if your accuracy with a more complex network remains low even on your training dataset, that's a sign that something is wrong with the training procedure. I'd advise you to check your code to make sure there are no mistakes in it. If you get good results on the training set but not out of sample, that just means the LSTM is learning garbage features and you need to correct for overfitting.
Comment: But, what kind of mistakes could I be making? I just download the dataset, decode into text, encode into numbers using BERT an using that as train/ validation data. I was afraid you might be right but I do not see where the problem could be. Besides, most sentences are long enough, and they contain usually more than 400 characters.