What's difference between UI level testing and API level testing?

Question: I got this question while interviewing some companies. I don't think I answer the question well. However, based on my understanding:
The UI level testing is more about the what end user will see and would be better to use for acceptance testing.
The API level test is good for performance testing, since it's easier to simulate multiple users to access the resource at the same time. And, it's easier to look at where the problem will be.
Can anyone give me more detail about that? And when should we choose to use which type of testing?? Thanks a lot.
Comment: You may go through my article in which this topic is discussed in detail
https://www.codingular.com/2017/07/ui-automation-vs-api-automation/
Answer: UI stands for User Interface.  UI allows the user to interact with the application.
UI testing refers to testing graphical user interfaces, such as how user interacts with the application, testing application elements like fonts, layouts, buttons, images, colors, etc.  Basically, UI testing concentrates on the look-and-feel of an application.
For more details on API testing, see:
<code>http://www.guru99.com/gui-testing.html
</code>

API is an acronym for Application Programming Interface.  API enables communication between two separate software systems. A software system implementing an API contains functions/sub-routines which can be executed by another software system.
API testing is checking API of a Software System.  In order to check the API , it needs to be called from the calling software . Necessary test environment, database, server, application setup needs to be prepared before doing API Testing.
API testing is focused on the functionality of the business logic (such as a calculating total price) and it is entirely different from UI testing. It mainly concentrates on the business logic layer of the software architecture. This testing won't concentrate on the look and feel of an application.
For more details on API testing, see:
http://www.guru99.com/api-testing.html
Eric
Answer: In few words:
UI testing is testing between users (humans in most cases) and front end or client side (aka presentation logic) of the application such as a browser.
API testing is testing between backend or server side of the application (aka business logic) and backend of another application.
Comment: Best and simplest answer.
Answer: Instead of going into a long explanation, where you can find volumes written on the Internet, let me give you a couple of additional keywords.
For UI testing, also look at FUNCTIONAL and EXPLORATORY testing.
For API, also look at UNIT and AUTOMATED testing.
I find this resource useful http://www.stickyminds.com/testandevaluation.asp?Function=FEATUREDETAIL&ObjectId=17275
Pick the one your boss will give you a promotion for.
Comment: Thanks Walter. But, you can also do the automated testing on UI testing, right?
Comment: If you want to talk terms, UI is _user_ interface and API is what programmers are interested in. APIs are more likely to yield themselves to UNIT testing, which is pretty universally automated. You can use the following article as a starting point for learning abut automated UI testing http://stackoverflow.com/questions/606550/watir-vs-selenium-vs-sahi
Comment: Thanks Walter, I like your point about EXPLORATORY testing on UI. I am more interested in "Whether we can classify UI level testing to Blackbox and API level testing to whitebox?" If so, then, the question could be simplify to "Blackbox testing vs Whitebox testing". UI level testing will be Blackbox testing, no doubt. But, when it comes to API level testing, it doesn't mean you know the implementation of the API you are using. You may just did a API call from the library and don't know the source code.  So, it's kind of vague to determine whether API level testing is whitebox or blackbox.
Comment: In my mind the distinction between black and whitebox is whether the tester has an idea about the implementation, on top of expected input/output behavior.  This is orthogonal to whether it's UI or API. Switching to the human side of things, going in detail through functionality of typical use cases is one area where 'blackbox' is the right attitude, something that actual implementers and those with programming background often have trouble with, but an actual end-user does by default. P.S. You may consider starting to 'accept' some of the answers to your questions - 3 out of 8 is not great.
Answer: Testing at the API layer enables the robust, low-noise regression tests that are essential for continuous testing.  It also helps you zero in on problems that might not be evident from the UI level — for example, an error in writing the expected values to the database.
Answer: GUI Testing--testing on visible elements in pages or screens called as Gui testing.some other names to GUI are Sites testing/ front end testing/ screens testing.
API testing--Testing on invisible services functionalities called as API testing. other names to API are Services testing/ middleware Testing/SOA testing.
End-to-End Testing--testing related to integration of a site and a service is called as End-to-End testing. other names are Inter System testing/ interoperability testing.
Answer: In everyday testing, basicly there are three uses for API testing from the testers' point of view.

When an application is brand new, and the backend is ready/being developed, and there is no GUI yet, that is when API is tested. Also when the new functionality is newly developed, and is not yet deployed to the GUI ready code base. This is usually the phase of the project that most, and highest priority business requirements are implemented in the code.
When you encounter a API call error in your browser's DevTools, it could be usefull to test different API resources.
When the tester reports a defect, in the defect ticket, the developers post in the result of new fix, or operations the result of the fix/configuration in the environment, as a quick check of the isolated functionality.

But in general, once a GUI is ready, usually API testing in not needed, at least for testers. Of course for developers, it is useful to test new functionalities, as a higher level testing (integration testing) after unit tests.


Calculating the probability of the Nth sample in the birthday problem w/o knowing the previous samples

Question: If we draw two random variates from a discrete uniform distribution $[1, D]$, the probability that the samples are distinct is $(D-1)/D$. Explanations of the birthday problem state that if we sample a third time, the probability that this third sample is distinct from the first two is $(D-1)(D-2)/D^2$. Doesn't this assume that the first two samples were distinct? If they are not distinct, then the probability that the third sample is distinct is $(D-1)/D$. The solution to the birthday problem requires us to know the probability that the $n^\textrm{th}$ random variate is distinct from the previous samples. How can we calculate the probability that the $n^\textrm{th}$ sample is distinct from the previous samples without knowing the values of these previous samples?
Comment: @gung This is not homework, it is for my own edification. I saw the problem in David Mackay's textbook on information theory and was not satisfied with his explanation (or other similar explanations on the net).
Comment: Welcome to the site, @Dan. Is this homework? If it is, you need to add the 'homework' tag.
Answer: The probability all $3$ are distinct is $\frac{(D-1)(D-2)}{D^2}$.
The probability the third is not equal to the first two is $\frac{(D-1)^2}{D^2}$. Imagine choosing $C$ first. Then there are $D-1$ choices for $A$ so that $A\ne C$, and $D-1$ choices for $B$ so that $B\ne C$.
If you are given that the first two are distinct, the conditional probability that the third is different from both is $\frac{D-2}{D}$.
You are correct that if you are given the first two are equal, the conditional probability that the third is different is $\frac{D-1}{D}$.
If $D=10$, these are $72\%, 81\%, 80\%,$ and $90\%,$ respectively. The $81\%$ is naturally a weighted average between $80\%$ and $90\%$, weighted by the probabilities that the first two are distinct or not. The $72\%$ can also be viewed as a weighted average between $81\%$ and $0$, weighted by the conditional probability that the first two are distinct from each other given that they are distinct from the third.
Comment: Because this post has been upvoted, SE construes its deletion as removing potentially useful information; I have therefore undeleted it.
Answer: In the usual context of the birthday problem, if the first two values are not distinct the problem is solved and the third and subsequent values are irrelevant. What is confusing here is that you have written

Explanations of the birthday problem state that if we sample a third
  time, the probability that this third sample is distinct from the
  first two

What is really meant here (and is a big part of the unintuitive nature of the birthday problem), is "the probability that this third sample is distinct from the first two, given that they are distinct from each other".


Uniqueness submodule of cyclic module

Question: I'm having some problems with an exercise from Hungerford's Book of Algebra.
It states:

Let $R$ be a PID, and $A$ a unitary $R$-module such that $A$ is cyclic of order $r$.
a) Prove that every submodule of $A$ is cyclic of order dividing $r$.
b) Prove that for each $s\mid r$, there exists exactly one submodule of $A$ of order $s$.

I was able to prove a), and the existence part of b) but I can't manage to prove the uniqueness.
In a) what I did was basically noting that by the structure theorem, $A\cong R/(r)$, and every submodule of $R/(r)$ has the form $(s)/(r)$ where $s\mid r$, and is indeed cyclic.
In b) the idea for the existence was noting that if $r=sx$, then the submodule $Rb$ with $b=ax$ ($a$ is the generator of $A$), then $Rb$ is a cyclic submodule whose order is $\mathcal{O}_b = (s)$.
Comment: Sorry, I know that this is an old question. Probably is this a duplicate of https://math.stackexchange.com/questions/314677/is-there-a-unique-cyclic-submodule-for-every-factor-dividing-the-order-of-a-cycl?rq=1?. At least I think in the link there is an answer to (b).
Answer: The submodules of $R/(r)$ correspond by second isomorphism theorem to submodules of $R$ containing $(r)$. But the submodules of $R$ are just left ideals, or just ideals since $ R$ is commutative. Since $R$ is a PID, these are generated by a single element $t$, say, and $(r) \subset (t) $, so $r \in (t)$ and $r=ts$ for some $s$. Thus any submodule of $ R/(r)$ is cyclic (generated by $t+(r)$), of the form $(t)/(r)$. Map $R \rightarrow (t)/(r) $, by $\lambda \mapsto \lambda (t+(r))= \lambda t + (r)$. Now, $st \in (r)$ and if $ \lambda t \in (r)=(st) $ then $st |\lambda t$. This implies $s| \lambda$ since $R$ is an ID. Hence the kernel of this map is $ (s)$, so the module $(t)/(r) \cong R/(s) $ and is cyclic of order $s$, where $s|r$ since $r=ts$
Conversly if $s|r$ then $r=ts$ for some $t$. The submodule generated by $t+(r) $ is cyclic of order $s$ as required.

Uniqueness submodule of cyclic module


Combine gtk3 in C with gtkmm in C++

Question: I was looking at converting an existing project slowly from C written in gtk3 to C++. Originally, I started to build up classes and was using extern "C" to move one function over at a time. However, gtk has it's whole GObject system with special things to instantiate and dispose. (With tons of magic macros created on the fly.)
I started to make a wrapper for Gtk in C++ but it occurs to me that gtkmm already exists for that. Can gtk code be combined with gtkmm? Will signals and slots work across the two, and will it play nicely with the c++ gtkmm objects and c gtk "objects"?
Worst case is I could mirror the objects and cast them back and forth... And handle the creation and deletion in C with gtk so it doesn't break anything, but eventually I want to pull them out of C completely and I think that last bit will be a pain.
Answer: All Gtkmm widgets have a method named gobj() to give you the C pointer of your widget so you can call your C functions on it.
https://developer.gnome.org/gtkmm-tutorial/stable/sec-basics-gobj-and-wrap.html.en
https://developer.gnome.org/gtkmm/stable/classGtk_1_1Widget.html
I guess gtk C callbacks are compatible with the gtkmm callbacks:
https://developer.gnome.org/gtkmm-tutorial/stable/sec-connecting-signal-handlers.html.en

Combine gtk3 in C with gtkmm in C++


Como colocar autoria usando licença MIT

Question: Segundo a licença MIT tenho que colocar o direitos do autor e onde? Ou não preciso de colocar?
Licença MIT

The MIT License (MIT)
Copyright (c) 2014-2015 almasaeed2010
Permission is hereby granted, free of charge, to any person obtaining
  a copy of this software and associated documentation files (the
  "Software"), to deal in the Software without restriction, including
  without limitation the rights to use, copy, modify, merge, publish,
  distribute, sublicense, and/or sell copies of the Software, and to
  permit persons to whom the Software is furnished to do so, subject to
  the following conditions:
The above copyright notice and this permission notice shall be
  included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Answer: Já ressalto que eu não sou advogado. Se você tem maiores preocupações, consulte um. O risco é seu de confiar em pessoas aleatórias te informando sobre leis e licenças.
Se você está só usando não tem que fazer qualquer coisa. Se está modificando também não tem muito o que fazer.
MIT é uma licença bem permissiva. Essencialmente ela só proíbe você dizer que o código é seu, você não pode alegar autoria se não foi você que fez. Ninguém sequer precisa saber se você está usando algum software com licença MIT em um produto ou serviço seu. Você pode distribuir seus softwares contendo código MIT sem falar para ninguém. Não tem nenhum requisito. Internamente se você até disser que foi você que escreveu aquele código não vai acontecer nada, você só não pode trocar o nome do autor pelo seu e publicar o código.
Se for publicar os fontes de sua própria versão, mesmo que dentro de outro projeto seu, você pode se adicionar como coautor se adicionou algo expressivo na sua versão. Aí você coloca no lugar mais apropriado, no cabeçalho do arquivo, indicando com clareza onde você contribuiu, ou no cabeçalho da função alterada. Só tome o cuidado de deixar claro que você não é o autor original.
MIT é próxima do domínio público, exceto que ela não abre mão da autoria. Mas abre mão de todos os direitos de cópia, uso e distribuição.
Esta licença existe mais para liberar os autores de garantias e responsabilidades e não permitir que você "roube" a autoria e processe outras pessoas alegando que elas estão usando algo que você não tenha direitos. Na prática ela serve só para isto. Ela pode ser melhor que domínio público que dá margem à interpretação da autoria.
MIT é a verdadeira licença de software livre. Não é um livre esquizofrênico onde você tem um monte de obrigação.
Coloquei no GitHub para referência futura.

Como colocar autoria usando licença MIT


How create a method who submit a form with parameters

Question: I have a page
On this page is the form with two selects year and month. I want to create something like that
getTable($year, $month)
{
}

After execute this method it get access to specific table. If I'll choose 2013 and kwiecien in method then I get specify page with tables.
I don't know how to send data to form using a code, what have I use? I use Symfony2
Edit:
SOLUTION
   $urltopost = "http://nbp.pl/transfer.aspx?c=
   /ascx/listaabch.ascx&Typ=a&p=rok;mies&navid=archa";
            $datatopost = array (
            "mies" => "05",
            "rok" => "12"
            );

            $ch = curl_init ($urltopost);
            curl_setopt ($ch, CURLOPT_POST, true);
            curl_setopt ($ch, CURLOPT_POSTFIELDS, $datatopost);
            curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
            $returndata = curl_exec ($ch);
            curl_close($ch);
            // var_dump($returndata);
            print_r($returndata);

It's solved my problem,
Comment: php or aspx?, your webpage uses aspx not php...if php, then ill create you an example about it
Answer: let me assume that your website is based on PHP language..
let say that your web domain was "www.example.com" and we need to pass using GET process "/home.php?year=2013" or "/home.php?year=2013&month=12"
lets initialized the home.php with year is equal to 2013 and month=12 is December
Inside your php code:
<?php
    function getTable($year,$month)
    {
        //Initializing global var
        $year = 0;
        $month = 0;
        $result = "";
        //check if GET process "year" is set, and must not empty
        if(isset($year) && $year != "")
        {
            //anti sql injection, and passing $_GET process to variables
            $year = mysql_real_escape_string($year);
            $result = mysql_query("SELECT * FROM data WHERE year=$year & month=$month") or die(mysql_error());

            //check if GET process "month" is set as well, and must not empty
            if(isset($month) && $month != "")
            {
                //anti sql injection, and passing $_GET process to variables
                $month = mysql_real_escape_string($month);
                $result = mysql_query("SELECT * FROM data WHERE year=$year") or die(mysql_error());
            }
        }

        //check if $result doesnt have an error,security purposes
        if($result) {
            //loop the datas
            while($row = mysql_fetch_array($result))
            {
                if($month == 0) {
                    echo $row['year'];
                }else {
                    echo $row['year']." ".$row['month'];
                }
            }
        }
    }

    getTable($_GET['year'], $_GET['month']);
?>

This is just an example, and it depends on you on how you use it...The Selection statement are just examples and needed to change...without any examples of your needs you must change the getTable functions prior to your needs...


Is it "safe" to use a capo on every string but the E?

Question: I've tried playing in drop D to play a song with a lower D chord that the one you can do with standard tuning, and it has pros and cons.
One of the cons is that the E string take some time to stay in tune after the drop D when it's back to E. To avoid this, I tried something weird: a partial capo holding every string but the E string. In standard tuning, it simulates a drop D but transposed +2.
It's actually more practical than a drop D because you can still do G chords and any barred chord just the way you would in standard tuning. (Playing a F# is a little harder in drop D than normal)
I don't think I've seen this anywhere, can it be damaging for the guitar? It's really helpful and I'm suspecting the reason I've never seen it  before is because I shouldn't be doing it at all. I'm guessing the pressure might be uneven on the neck or something.
Answer: In principle, this is fine. You can even get purpose-made partial capos to do this job, such as those here.
The only issue you're likely to have is if the capo isn't sitting evenly on the back of the
neck, causing it to slip or to exert particularly uneven pressure on the 5 strings it is stopping. If this isn't happening, then you're fine. If it is, you might want to look for a more forgiving capo... or one of those purpose made ones, though even that linked site states:

"On most guitars, you can capo 5 strings with just a normal capo slid over"

So it seems you're not the only one to have ever done this!


views alter query

Question: I have content type event that has date field
and i created view "events" to this content type and added contextual filter "Date".
The problem is in the database the field date value is stored with this format
2007-01-17T00:00:00
and I want to filter like this events/2007.  Unfortunately, I get no results because the URL should be like this events/2007-01-17T00:00:00.
So what is the solution for making it work with this events/2007 by altering
the query using views_views_query_alter() instead of creating field that hold the value like this 2007. I believe that altering the query by this way should solve it but it didn't
function views_views_query_alter(&$view, &$query) {
  if ($view->name == 'events' && is_numeric(arg(1)) ) {
    $view->query->where[0]['conditions'][3]['field']=" YEAR('field_data_field_date.field_date_value')";
  }
}

Comment: Mohamad, the edit was to improve the readability of the question, which in turn will get you a better answer. Formatted as-is, some people won't even bother reading the question or will edit it
Comment: hello mohamad salama, also I suggest to try to give format your question, for example for your code. is just add some spaces before each line in your code.
Comment: Mohamad, remember to use functions to test/debug your functions, for example, if you have Devel module, you can use **dsm()** to output values that are you working (or you can use the very helpful **print_r** or the **echo**).
Comment: i already debug the query & the results
and when i add 'YEAR' sql function to the field
'field_date_value' by doing so
 $view->query->where[0]['conditions'][3]['field']=" YEAR('field_data_field_date.field_date_value')";
it doing something wrong to the query
is gota be some way else for doing that.
Answer: Which Drupal and Views versions? From what I can see on my test site when creating:
A Filter Criteria you can specify granularity to year; same thing goes for a Contextual filter. (D7, latest Views).
Comment: yes its D 7.7 & View 7.x-3.0
all i want to do something that hook the criteria field
to make it YEAR('field_date_value') instead of just 'field_date_value3'

views alter query


How to set up a general domain in htaccess

Question: This is my htaccess file and I want to replace "yourdomain.com" with something general. I tried %{SERVER_NAME} but it doesnt work as expected.
RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?yourdomain.com [NC]
RewriteRule \.(jpg|jpeg|png|gif)$ - [NC,F,L]

I want allow only requests when HTTP_REFERER will match with SERVER_NAME or HTTP_HOST.
Answer: Use:

In the below example, -strmatch is used to compare the REFERER against
  the site hostname, to block unwanted hotlinking.
RewriteCond expr "! %{HTTP_REFERER} -strmatch '*://%{HTTP_HOST}/*'"
RewriteRule "^/images" "-" [F]

Reference: http://httpd.apache.org/docs/2.4/mod/mod_rewrite.html#rewritecond


Geometrical interpretation of why can't ridge regression shrink coefficients to 0?

Question: To explain the difference between Ridge and Lasso regression, following diagram is used as it is claimed that Ridge regression cannot shrink the regression coefficients to 0:

But my question is, if my equation of cost function is like the one on in the following image, Ridge can also reduce the coefficient to 0:

Please correct if I am wrong.
EDITS:
According to this answer(https://stats.stackexchange.com/a/30530/35989)

And now follows an interesting thing that greatly explains to me the difference between ridge regression and LASSO: in case of LASSO two contour plots will probably meet where the corner of regularizer is (1=0 or 2=0). In case of ridge regression that is almost never the case.

But it does not explain, why it can "ALMOST NEVER" be the case for ridge regression.
Comment: As you could learn from my answer to [your other question](https://stats.stackexchange.com/a/587031/35989) nobody claims that the parameter won't be zero.  It is just not the point of this regularization. The same, you could have parameters equal to zeros without using any regularization. You'll find good explanation of the geometry here https://stats.stackexchange.com/a/30530/35989
Comment: Edited the question. Now I request the people to focus on the problem and not on the other unnecessary stuff
Answer: Let's look at the image you used once again. Notice that it shows the same ovals of the cost function of linear regression $\hat \beta$ and the two different penalties: the lasso (square) and ridge regression (circle). We are interested in the first intersection point. With the ridge $\ell_1$ penalty, the closest intersection point is some point at the edge of the circle. With the lasso, it's the corner at zero.

Let's also look at one more example taken from here. You may notice that for different points it is the case that for lasso the intersection often happens on the corners, while for ridge at different locations.

Next, let's go one step further and consider not only $\ell_2$ and $\ell_1$ penalties, but also $\ell_p$ with $0 < p < 1$. As you can see in the image below, it's even more "spiky" and has a concave shape. In such a case, the "spike" is something that the linear regression ovals will touch almost always because it's the most sticking out point. With $\ell_1$ it's less extreme, but the same logic applies.

In the end, let's go back to geometry. The circle is a geometric shape such that all the points on its boundary are equidistant from the center. In the case of squares, the corners are the most distant points from the center. If something approaches the shapes from the outside, it is likely to first touch the most external point, that would be the corners for the square and any point on the boundary for the circle.
Finally, this is visible even if we use your picture but for linear regression cost, we draw a perfect oval. Notice that it touches the non-zero point faster than the zero.
Answer: It is not shrinking to zero
When estimated coefficients are zero in Ridge regression, then it is only because a parameter value crossed the value of 0. It is not because it shrank to zero, when the penalty is further increased the coefficient won't remain zero.
Below is an example image for showing that the difference between Lasso (shrinking to zero) and Ridge regression (crossing zero).

In the Lasso regression on the left you see that, as we increase the level of regularisation (reduce the $\ell_1$ norm) more and more coefficients will be zero and they remain zero when we increase the level of regularisation further.
In the Ridge regression on the right, the coefficient related to the green curve is shortly equal to zero when the $\ell_1$ norm of the coefficients is around 0.55. But the coefficient only passes zero and for stronger regularisation levels it is non-zero again.
The reason that coefficients can be zero with ridge regression is because the ridge regression follows a curved path. See Intuition for nonmonotonicity of coefficient paths in ridge regression
The probability of a zero coefficient
The above is more like a semantic comment about the terminology and meaning of 'shrinking'. If we ignore that, then you might still wonder why a zero coefficient is almost surely not occuring (it can occur but the probability is just zero).
This is similar to your other question Why in the Ridge regression, the coefficients cannot be 0? and is similar to $P[X=x]=0$ when $X$ is a continuous variable But here you are looking for a geometric interpretation, based on your drawing.
If we look at the case of Lasso, then we see that there are many circles that touch the square in the points/corners where one of the coefficients is zero. There is a range values for which this occurs and that range has a non-zero probability.
In the case of ridge there are only four possible single points such that the circles touch a circle in a points/corners where one of the coefficients is zero. For these single points there is zero probability that you have these as the OLS solution.
Comment: Your first 2 sentences are very insightful.


Checking if checkboxes in PHP are checked using javascript

Question: echo '
' . "

       Document No
       AWB NO
       Order Id
       Forms
       Extras

";
foreach ($cancel as $key => $value)
{
    echo "
";
    echo "" . "<input type='checkbox' name='name1' id='checkit$checkitCounter' />" . "	";
    echo "" . $value[$d] . "	";
    echo "" . $value[$a] . "	";
    echo "" . $value[$o] . "	";
    echo "" . $value[$f] . "	";
    echo "" . $value[$e] . "	";
    echo "
";
}
echo "

";

This above table is generated using php echo with checkbox generated every iteration.

    Continue..

The above button is supposed to run a javascript function given below:
function checkit {
    var x = document.getElementById("checkit").checked;
    if (x == false) {
        alert('All items are not removed,pls remove and continue');
    }
    else {
        window.location = "tst.php";
    }
}

The above JavaScript doesn't seem to be functioning properly as even though i have checked none of the boxes it just stays on the same page.
Comment: You can't have multiple ids on page, id must be unique, use class instead.
Comment: You should check out this answer http://stackoverflow.com/questions/3808808/how-to-get-element-by-class-in-javascript as it describes how to get and loop through elements using a class instead of an ID
Comment: @nevermind show an example?
Comment: @Machavity i don't think that is a valid solution for this situation.
Comment: @Pramod S, yes, please just post your rendered HTML, not php, or setup fiddle.
Comment: possible duplicate of [Check/Uncheck checkbox with javascript?](http://stackoverflow.com/questions/8206565/check-uncheck-checkbox-with-javascript)
Comment: @nevermind Its mainly just php, i have posted the important html there is in the code,how should i use classes instead? Can u show me an example of what u were saying
Comment: @SachinKanungo I have tried that,it isn't working.
Comment: http://stackoverflow.com/questions/1045845/how-to-call-a-javascript-function-from-php this might help
Comment: is your id same for all the checkboxes? u have used checkitcounter , whats the value of checkitcounter in php
Comment: I have solved your question and is posting an answer shortly
Comment: @maytham-ɯɐɥıλɐɯ Alright,thank you
Comment: @Gautam Depends on the number of rows.
Answer: Example:

 Continue..

<input type='checkbox' name='name1' class='checkit' />
<input type='checkbox' name='name1' class='checkit' />
<input type='checkbox' name='name1' class='checkit' />
<input type='checkbox' name='name1' class='checkit' />
<input type='checkbox' name='name1' class='checkit' />
<input type='checkbox' name='name1' class='checkit' />

And js:
function checkit() {
    var boxes = document.querySelectorAll(".checkit");
    arr = [];
    for (i = 0; i < boxes.length; i++) {
        arr.push(boxes[i]);
    }

    console.log(arr);

    function is_checked(val) {
        return val.checked == true;
    }

    checked = arr.filter(is_checked);

    console.log(checked);

    if (checked.length != boxes.length) {
        alert('All items are not removed,pls remove and continue');
    } else {
        window.location = "tst.php";
    }

}

Demo: https://jsbin.com/cukuzeweza/edit?html,js,output
Answer: I have made a light version of your code and the rest is left to your development logic.
You have had a lot small problems in your code, like function in JavaScript needed (), the usage of single and double quotes, missing call the JavaScript function etc.
I have created a dummy array for test, but again you could do what you like to achieve your code.
Here is the working solution:
<?php
$cancel = ["checkBox1", "checkBox2", "checkBox3"];

echo "

            Document No

";

foreach ($cancel as $value)
{
    echo "
";
    echo "<input type='checkbox' name='name1' id='$value' onchange='checkIt(\"$value\");' />	";
    echo "" . $value . "	";
    echo "
";
}
echo "

";
?>

You can see in your console the results of your checkbox.


Which of the answer is correct? Combination vs Binomial Distribution

Question: A class of 400 students having 220 women and 180 men. The class is divided into study groups of 10 students each. What is the probability that a certain group will have exactly 4 men?
I have used the following two approaches:

Combination question: Choose 4 men of 180 and choose 6 women of 220 divided by the total ways of choosing 10 people from 400.
Answer = 180C4 * 220C6 / 400C10 = 0.24102549843

Binomial distribution: Total trials (n) = 10, number of success (x) = 4 and probability of success (p) = 180/400 = 0.45. Note: Here success = picking a man.
So, P(4) = 10C4 * 0.45^4 * (1-0.45)^(10-4) = 0.23836664662

Why are these two outputs not the same? If one of my approach is incorrect, then which approach have I made mistake in? Also, how to rectify that mistake if any?
Comment: The binomial distribution is only exact if the trials are independent, which isn't the case here.  If the first selection is male, the second has a somewhat smaller chance of being male.  $\frac {180}{400}=.45$ but $\frac {179}{399}=0.448621554$.  Of course, as an approximation, it's not bad.
Comment: Since the objects are drawn without replacement, the [hypergeometric distribution](https://en.wikipedia.org/wiki/Hypergeometric_distribution) should be used.
Answer: Answer given by @lulu in the comments.
The combination answer is correct. The binomial distribution assumes that all the trials are independent of each other but that is not the case in this question.
Once a man is picked in the first trial, the probability of picking the second man becomes 179/399.
So the probability of picking the first man = 180/400.
Probability of pickign the second man = 179/399.
This implies that the next trial is dependent on the past trials.
Thanks to @N. F. Taussig for pointing out the hypergeometric distribution to be used in such a case and not the Binomial distribution.


Android layout folders: layout, layout-port, layout-land

Question: I'm not sure to have understood well the role played by the several Android /res/layout folders.
layout: general layouts
layout-port: layout for widget that must change for portrait orientation
layout-land: layout for widget that must change for landscape orientation
For example in the Home sample application, under layout-port and layout-land folders there is only one home.xml file.
Have I understood right?
Comment: Some developers might not realize how important it is to master this concept, so thanks for putting this on SO.
Comment: My theory HTML5 will replace this stuff in the future.
Comment: Update: the Home sample application does not exist anymore. I don't know what replaced it.
Answer: If you are in landscape or portrait Android looks for the layout file in either the -port or -land directory first, if it's not found then it falls back to the default layout directory.
You can read about providing alternative resources here. There are many more options than just land and port.
Comment: In this case, the other layouts do not change depending on orientation so they are just in the layout folder, whereas home is specific to portrait or landscape
Comment: I'm surprised there isn't some sort of orientation specifier for each property, to indicate different values for each. I understand that in the case of resolutions that could get messy, but since there's only two possible orientations (and always will be), it might be nice to not have to maintain two separate files for a layout if, for example, only one property needs to differ between orientations.
Answer: If you put home.xml in layout-port folder, when your device is in portrait orientation it will use the file: layout-port/home.xml.
If you put home.xml in layout-land folder, when your device in landscape orientation it will use the file: layout-land/home.xml.
Meaning for different orientation modes like portrait and landscape... we use two home.xml files; one in layout-port and the other in layout-land. If on the other hand you want to use the same layout file for both, you can just put home.xml in the layout folder and remove it from layout-land and layout-port.
Comment: if you have two layout files in -port and -land and they don't switch when you change the device orientation, you probably specified android:configChanges="orientation" in the AndroidManifest.xml. In that case specify again setContentView() in the onConfigurationChanged() or remove that AndroidManifest.xml directive.
Comment: I've made seprate layout xml files for both layout and layout-land. But when I change the orientation to landscape, its layout-land file is not getting displayed by the android. What is the problem?
Answer: Create folder in res layout-land or layout-port
layout-port: layout for widget that must change for portrait orientation
layout-land: layout for widget that must change for landscape orientation


How to compose a new song when inspired by existing song?

Question: Sometimes when I listen to a song, especially in foreign language, I get inspired by its atmosphere, and write some great lyrics.
Question:
Are there any tips or techniques on how to compose a new, original song, based on a certain atmosphere?
I guess using the same chords would be a start, but how to create a new singing melody as awesome as original, yet different?
Comment: While I don't have an answer, you may be interested to know that *"It's the Same Old Song"* by the Four Tops, and written by Holland-Dozier-Holland was based on another song written by them, *"I Can't Help Myself (Sugar Pie Honey Bunch)"* - https://en.wikipedia.org/wiki/It%27s_the_Same_Old_Song.

Listening to those 2 songs and the (same) chord progressions may provide some insight.
Answer: One might start with the chords though with so many pieces using common chord sequences (12 bar blues, passamezzo modern, cycle of fifths, etc.) that may not provide enough information. Most of these have been used for centuries. The rhythmic structure often contributes to a song's feel.
One thing to do is listen that song and other similar songs to see what they have in common that provides the feel you like. Then try imitating parts of one with parts of others until you get something you like.
I'll give a trivial example. When trying to figure out how to write a rumba (for American or International) ballroom dancing, I examined the following songs: "Siboney" Nina Mouskouri, "Beautiful Maria of my Soul" Antonio Banderas, "Te Quiero" Mestizzo. "Harlem Nocturne" Mantovani, and "Miami Beach Rumba" Irving Fields. These cover about 70 years of composing and with different styles. I also checked other songs by the same singers (and composers) to see how what I was interested in related to other pieces.
It helps to copy out the score to the songs you like because then you see the structure from a different point of view fro just listening.
Answer: It's easier to compose a song based on another song, set of songs, or in the style of a specific composer/album/etc. Listen to the music you want to compose in the style of (many examples if you can) so you figure out their typical chord progressions, rhythmic patterns, accompaniment patterns, instrumentation, etc. Then, use those in your new composition (well, the instrumentation is optional). Make sure that you do not use their melodies or you'll either need to point out the use of those melodies every time you publish the composition or be accused of plagiarism. Even worse, if their melody isn't in the public domain and people are not allowed to publish derivative works from it (hint: assume that any melody published after 1923 meets those dire requirements, according to US copyright law, unless the melody explicitly says otherwise), your published piece may be removed from the public eye anyway regardless of how many times you admit the origin of the melody. Rule of thumb: if you recognize the melody fragment from any piece of music you've ever listened to, don't use it.
For composing to fit a certain atmosphere, I recommend writing music--and listening to the music you compose--until your music evokes the atmosphere you desire. It's definitely more by feel than composing in a certain style.


Variável fora do while fica a zero

Question: Faço a soma total  da seguinte forma no while:
$TotalSIva6 = 0;
$TotalSIva7 = 0;
$TotalCIva6 = 0;
$TotalCIva7 = 0;
while($rows_cursos3 = mysqli_fetch_array($result3)) {

    $teste24 = $rows_cursos3['Valor'];
    $teste25 = $rows_cursos3['Valor1'];

    $TotalSIva6 = $TotalSIva6 + $teste24;

    $TotalSIva7 = $TotalSIva7 + $teste25;

    $TotalCIva6 = $TotalCIva6 + $TotalSIva6;

    $TotalCIva7 = $TotalCIva7 + $TotalSIva7;

    $tabela4 .= '
';

    $tabela4 .= ''.$rows_cursos3['Bolacha M DI'].'	';

    $tabela4 .= ''.$rows_cursos3['Quantidade Bolacha'].'	';

    $tabela4 .= ''.$rows_cursos3['Valor'].'	';

    $tabela4 .= '
';

    $tabela4 .= '
';

    $tabela4 .= ''.$rows_cursos3['Bolacha AS D'].'	';

    $tabela4 .= ''.$rows_cursos3['Total Bolacha AS'].'	';

    $tabela4 .= ''.$rows_cursos3['Valor1'].'	';

    $tabela4 .= '
';

    $TotalSIva8 = 0;
    $TotalCIva8 = 0;
    while($rows_cursos5 = mysqli_fetch_array($result5)) {

        $teste26 = $rows_cursos5['Valor'];
        $teste27 = $rows_cursos5['Iva'];

        $TotalSIva8 = $TotalSIva8 + $teste26;

        $TotalCIva8 = $TotalCIva8 + $teste27;

        $tabela4 .= '
';

        $tabela4 .= '
';

        $tabela4 .= ''.$rows_cursos5['ProdExtras'].'	';

        $tabela4 .= ''.$rows_cursos5['Total'].'	';

        $tabela4 .= ''.$rows_cursos5['Valor'].'	';

        $tabela4 .= '
';

        $tabela4 .= '
';

        $TotalSIva9 = 0;
        $TotalCIva9 = 0;
        while($rows_cursos4 = mysqli_fetch_array($result4)) {

            $teste28 = $rows_cursos4['Valor'];
            $teste29 = $rows_cursos4['Iva'];

            $TotalSIva9 = $TotalSIva9 + $teste28;

            $TotalCIva9 = $TotalCIva9 + $teste29;

            $tabela5 .= '
';

            $tabela5 .= ''.$rows_cursos4['ProdExtras'].'	';

            $tabela5 .= ''.$rows_cursos4['Total'].'	';

            $tabela5 .= ''.$rows_cursos4['Valor'].'	';

            $tabela5 .= '
';

            $tabela5 .= '
';

        }
    }

$TotalSIva8 = $TotalSIva8 + $TotalSIva6 + $TotalSIva7;

$TotalCIva6 = $TotalCIva6*1.06;
$TotalCIva7 = $TotalCIva7*1.13;

$TotalCIva8 = $TotalCIva8 + $TotalCIva6 + $TotalCIva7;

$tabela4 .= '
';
$tabela4 .= '';
$tabela4 .= 'Total S/Iva: '. $TotalSIva8 .'€';
$tabela4 .= '	';
$tabela4 .= '
';

$tabela4 .= '
';
$tabela4 .= '';
$tabela4 .= 'Total C/Iva: '. number_format($TotalCIva8, 2 , ',', ' ') .'€';
$tabela4 .= '	';

$tabela4 .= '
';

$tabela4 .='
';

$tabela4 .= '
';

$tabela4 .= '
';
$tabela5 .= '
';
$tabela5 .= '';
$tabela5 .= 'Total S/Iva: '. $TotalSIva9 .'€';
$tabela5 .= '	';
$tabela5 .= '
';

$tabela5 .= '
';
$tabela5 .= '';
$tabela5 .= 'Total C/Iva: '. number_format($TotalCIva9, 2 , ',', ' ') .'€';
$tabela5 .= '	';

$tabela5 .= '
';

$tabela5 .='
';

$tabela5 .= '
';

$tabela5 .= '
';

echo $tabela5;

Na $tabela5 dentro do while antes da linha $tabela5 .= '
'; se fizer:
var_dump ($TotalSIva9);
var_dump ($TotalCIva9);
Ele retorna os valores corretos:
(float(1) float(1.06) float(136.84) float(154.5592))
Se fizer os var_dump(); das variáveis fora do while. Ele retorna:
(int(0) int(0)).
Qual será a razão?
Comment: Os valores `Valor` e `Iva` coletados do BD são sempre do tipo número?
Comment: As variáveis `$TotalSIva9`e `$TotalCIva9` conterão apenas a soma dos valores de `$teste28` e  `$teste29` relativos à última iteração do `while` mais externo (`$rows_cursos5`) porque as duas variáveis estão recebendo o valor zero antes de começar o segundo `while`. Talvez quando ocorre a última iteração do `while`mais externo, os valores do `while` mais interno estão nulos.
Answer: mysqli_fetch_array é uma função do php, isso que dizer que as variaveis usadas dentro de uma função são declaradas na primeira utilização, o que falta no seu código é voce fazer uma referencia usando & pro compilador saber que a variavel dentro da função é a mesma que voce declarou antes.
Tente fazer o seguinte:
mysqli_fetch_array($result4, &$TotalCIva9)
{....}

você pode estudar mais em:
http://php.net/manual/pt_BR/language.references.whatare.php
Comment: Não funcionou...
Comment: faça a referencia direto no corpo da função use & em todas as $TotalSIva9.
Comment: Sempre que faço a referência ao actualizar a página dá error 500.
Comment: @Jean Freitas O segundo parâmetro de `mysqli_fetch_array` é uma constante para indicar o tipo de estrutura que será usada para guardar os dados coletados do BD, como indicado pela sua documentação em http://php.net/manual/pt_BR/mysqli-result.fetch-array.php   Possivelmente você se confundiu com outra função.

Variável fora do while fica a zero


jquery .on('input') doesn't get fired in ie8 alone

Question: I'm having this issue specific to IE8. This event doesn't fire in IE8 alone, but is working fine in IE9 and other browsers like Firefox and Chrome.
$('#myId').on('input', function () {
   //do something.
}

Please let me know if there is any work around for the same in IE8.
Thanks!
Comment: I don't recognize "input" as an event trigger, myself. Maybe I've just never seen it?
Comment: On a side note make sure you aren't using jquery 2.0+ it doesn't support old IE versions.
Comment: Try using `change` or `keyup` instead, `input` isn't supported in older browsers.
Comment: The `input` event is a new event, is't not supported in IE8
Comment: @VoidKing and everyone that upvoted your comment: Learn about it: [MDN oninput](https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers.oninput)
Comment: keyup works fine. change works only the textbox looses focus. thanks
Comment: oninput fire for more than just key events.
Comment: possible duplicate of [How to detect when a text input changes with ie8](http://stackoverflow.com/questions/11791855/how-to-detect-when-a-text-input-changes-with-ie8)
Answer: Older versions of IE have an event called propertychange that you can use. You can check for the propertychange event and the input event at the same time:
$('#myId').on("propertychange input",function(ev){
    doAwesomeThing();
});

Comment: Works but fires property change event twice in IE8 ... used `'keyup input'` instead and it worked!
Comment: Confirmed, Justin's solution above works like a charm. Thanks!
Answer: oninput is IE9+, that is why it does not work in IE8
MDN oninput
Feature         Chrome    Firefox    Internet Explorer    Opera    Safari
Basic support   (Yes)     2          9                    10       (Yes)

Comment: Note that IE9 also doesn't support `oninput` well, see https://stackoverflow.com/questions/6382389/oninput-in-ie9-doesnt-fire-when-we-hit-backspace-del-do-cut
Answer: AaronBaker's answer: Works for both IE8 and IE10(html5) as well as modern browsers... without double post of event
I would have used comment or upvote but rep too low.
$('#myId').on("propertychange input",function(ev){
    doAwesomeThing();
});

Answer: It looks like the input event is a part of the HTML5 specification, something I wouldn't expect IE8 to handle.  You may need to use the change event instead.
Answer: This slight optimization will prevent the listener from firing twice in modern browsers (kind of a hack, but prob the best solution)
$('selector').on(!window.eventListener ? 'keyup' : 'input', function () {}
Answer: I tried using propertychange as suggested by the top answer, but I noticed that sometimes it doesn't fire in IE8. For example after a page refresh with a prefilled input if I delete only one character.
My solution is to use keyup cut paste events instead of propertychange:
$('#myId').on('input keyup cut paste', function(e) {
    setTimeout(function() {
        doAwesomeThing();
    }, 0);
});

I used setTimeout with 0 delay because otherwise I would get the old input value on cut and paste events, see https://stackoverflow.com/a/9364812/2324685 for details.
You should note that this code might fire twice in some cases.


Setting up a subdomain which points to another IP (Apache2)

Question: I'm using Apache, and I'm trying to set up a subdomain for a virtual host, which then points to a server on a different IP address.
So the virtual host is www.example.com, I'd like to set up images.example.com, and point it to 127.0.0.1.
I've consulted some of the answered questions on SO and other sites, but I'm a bit overwhelmed and I don't want to risk wrecking a production site.
Comment: you do this with DNS, not at the webserver level
Comment: also, spend some time creating a test environment. It is time extremely well spent.
Comment: You are absolutely right. I don't know where my head was at.
Answer: The best way to do this is using DNS (an A record), however if you really want to do it with apache you could define the virtual host then use mod_proxy to pass the request to the other server.
Have a look at http://httpd.apache.org/docs/current/mod/mod_proxy.html for some example
Answer: If you really do want to have images.example.com resolve to 127.0.0.1 then the only sensible place to do this is in the hosts file on the server. This is either /etc/host (unix like systems) or %SystemRoot%\system32\drivers\etc\hosts for windows systems e.g.
127.0.0.1    localhost images.example.com

Be aware though that 127.0.0.1 is the loopback address and is only accessible from the host on which it is defined.
Comment: I'm sorry, you are absolutely right. As Sam pointed out in a remark to my question, what I was trying to achieve should of course be done on the DNS level. I wasn't thinking. Thanks for answering.


I need to force a refresh of custom.css in the Thesis Framework

Question: Does anyone know the best way to refresh custom.css in Thesis? I'm running into a problem where some of my css isn't getting implemented due to browser caching of custom.css. I tried adding a variable to the filename like "custom.css?v=1" and while this works, it gives me an error every time I load the page. Any help would be appreciated. Thanks in advance.
Answer: You can disable CSS caching by adding this filter to the custom_functions.php file.
<code>function cache_customcss()
{
return true;
}

add_filter('thesis_cache_query','cache_customcss');
</code>


Decide whether a discrete random variable is usual or unusual using Probability distribution?

Question: We know that in frequency distribution we decide whether a value is usual or unusual depending on how many standard deviations it's away from mean.
Moving forward to Probability distribution my teacher explained that we calculate the mean using the following formula ' ∑ [x.P(x)] ', later he said that we can decide whether the discrete random variable 'x' is usual or unusual by calculating how many standard deviations is the 'x' away from 'mean.
This doesn't make sense to me since we calculated the mean by multiplying 'the value of the discrete variable' by 'the probability of that variable', so the probability is involved in this formula, as well as the standard deviation formula, shouldn't we decide whether the 'x' is usual or unusual by looking at its probability?
Comment: Consider a variable that takes on values in ${1, 2, \dots, 1000}$, each with probability $1/1000$.   Is $x = 500$ unusual?  Are there any values of $x$ that *aren't* unusual, using probability as a criterion?   If all values are unusual, does the word "unusual" have any useful meaning?
Comment: What is needed is a definition of 'unusual'. @jbowman points out that a "probability" definition doesn't work well for discrete uniform distributions. For $\mathsf{Binom}(n=64, p=1/2),$ the smallest individual values also lie $\pm 2\sigma$ away from $\mu,$ so both definitions make sense.  But there are discrete distributions in which the smallest probabilities are near the mean.
Answer: Many things are usually skipped in classes, for a teacher and students. Outlier is a very vague concept and there are many different ways to determine.
So, back to your question,

shouldn't we decide whether the 'x' is usual or unusual by looking at its probability?

Yes, if you know the probability. However, we don't know the density in practice. Thus, we calculate the "sample" mean, $\frac{1}{n}\sum_i^n x_i$, not the population mean. If we assume that the distribution is unimodal, has a heavy probability around a mean (or median) like a normal distribution, then if a value is far from the mean, we would say that is unusual.

This doesn't make sense to me since we calculated the mean by multiplying 'the value of the discrete variable' by 'the probability of that variable', so the probability is involved in this formula, as well as the standard deviation formula

Probability never involves in the method. Only sample mean and sample standard deviation are used.
Apart from the method you are struggling with, we usually draw histograms or can use another criterion.
Comment: The example he used in probability distribution was a "weighted die" and he calculated the mean in this formula ' ∑ [x.P(x)]'
x values: 1,2,3,4,5,6
p(x): 0.05, 0.15, 0.35, 0.30, 0,10, 0.05
later on he calculated the variance using a formula that I couldn't find on the internet: ' ∑[x^2. p(x)] - mean ^ 2
Comment: @Karim Ok. So, you know all about the population and you never sampled from it. To calculate the variance, he just used a basic equation $Var(X)=E(X^2)-E^2(X)$. In that case, to determine whether x=1 is unusual or not, you can directly see the probability, 0.05. Some would say yes, and some no.


Time of intersection between a Celestial body in an orbit following Kepler's laws and a rocket

Question: In this example we have a celestial body following Keplar's laws of planetary motion, this is done as a function of time, an example of this can be found here on Wikipedia. (Calculations are done in 2 dimensions so we can ignore the z axis.) With this we also have all the data needed to calculate the orbit, (epi/perihelion distance, mass, etc.) in addition we also have an initial position at time t0.
The rocket is traveling at a constant velocity, we know the velocity, but not the vector in which it travels. The purpose of finding the time of intersection is to find this out. Like with the celestial body we also know its initial position at time t0. We also know t0
Is it possible to find either the time at which the rocket and the celestial body would intersect (the ideal scenario), or the velocity vector itself for the rocket to travel the shortest possible distance, and if so, how could this be calculated?
Comment: If the body is orbiting a primary the rocket will not travel with constant velocity.  If it is not thrusting it will also follow a conic section.  Unless the conditions are very special this is something you do numerically.  You can find a range of starting velocities that will intercept the body and choose your favorite.  I don't know what software is used.  Kerbal might be able to do it.
Answer: A Kepler orbit in the plane with greater axis has the orbit form
$$r(\phi) = \frac{a(1-\varepsilon^2)}{1+ \varepsilon \cos( \phi-\alpha)}$$
$\alpha$ is the angle of orientation of all orbits of the same excenticity $\varepsilon$ and axis parameter $a$.
The orbit is an ellipse for $\varepsilon<1$.
Since a rocket will follow an elliptic orbit too, that typically starts nearly tangential to the earth orbit, because fast rockets on hyperbolic orbits need velocities high enough to leave the solar system, are to heavy and too expensive.
The ballistic rockets start below 8km/s, the earth bound satelites below 11 km/s and the cosmic velocity for a hyperbolic orbit to leave the solar system is about 17 km/s
With three parameters $\alpha, a, \varepsilon$  its easy find the set of second ellipses between an arbitrary point on the first ellipse and an arbitrary starting point with an variing arbitrary tangent vector. The numerical or algebraic integration of time against radius is simple.
As always in mechanics, high energy motion is free and connects two points by a straigth line in no seconds as the limiting orbit of hyperbolas.
By energy and angular momentum conservation the time integral derives from energy  by
$$\frac{r'^2}{2}+ \frac{L^2}{2 r^2} - \frac{GM}{r} =- E_{tot}$$
$$ dt = \frac{dr}{\sqrt{\frac{2 GM}{r}-\frac{L^2}{r^2} - 2 E_{tot} }}$$
The indefinite integal has a  closed algebraic useless form, that could be used for mononotone invertible parts, but its complex form makes its use as a definite integral difficult.
$$t=\frac{-8 P+\sqrt{2} \text{gM} \left(i \log \left(8 \text{En} \text{gM} r-8 \text{En} \left(4 \text{En} r^2+L^2-2 \sqrt{2} P r\right)+\text{gM}^2\right)+2 \tan ^{-1}\left(\frac{2 \sqrt{2} P-4 i \text{En} r}{\text{gM}}\right)\right)}{8 \text{En}^{3/2}}$$
with
$P = \sqrt{ En ( gM r -L^2 - 2 En r^2)}$


Is it possible for a function to equal its Taylor series on a half interval

Question: $\def\R{\mathbf{R}}$
Let $f:(-1,1)\to\R$ be infinitely differentiable.
Then it has a taylor series expansion $T(x)=\sum_{n=0}^{\infty}{a_nx^n}$ where $a_n=f^{(n)}(0)/n!$.
Let's say we're given that $T$ converges pointwise to $f$ on the interval $[0,1)$.
What can we then say about its converge elsewhere?
We can deduce that $T$ converges to something on $(-1,1)$ absolutely, and uniformly on any compact subset of $(-1,1)$. But the lingering question is, must $T$ necessarily converge to $f$ on all of $(-1,1)$? In other words, is $f$ real analytic?
Answer: Not necessarily. Take the function$$\begin{array}{rccc}f\colon&\Bbb R&\longrightarrow&\Bbb R\\&x&\mapsto&\begin{cases}e^{-1/x^2}&\text{ if }x<0\\0&\text{ otherwise.}\end{cases}\end{array}$$Then the Taylor series of $f$ at $0$ is the null series, which converges to $f(x)$ for every $x\in[0,\infty)$, but which converges to $0\ne f(x)$ for every $x<0$.
Comment: Man! Infinitely differentiable functions are so frustratingly poorly behaved. I love this.


Como sortear números aleatórios repetidamente de modo que não seja sorteado o mesmo número?

Question: from random import randint

# Dados
lista_tentativas = list()
quantidade_tentativas  = 0

# Entrada de dados
x = int(input('Informe um numero entre 0 e 10:'))

# Tentativas
while True:
    y = randint(0,10)
    quantidade_tentativas += 1
    lista_tentativas.append(y)
    if y == x:
        print('O numero digitado foi {}')
        print(f'Essas foram todas as minhas tentativas: {lista_tentativas}')
        print(f'Essa foi a quantidade total de tentativas: {quantidade_tentativas} tentativas')
        break

Da forma que estou fazendo existe a possibilidade de tentativa do mesmo número. Quero remover essa possibilidade. Mas como?
Answer: Verifique se o número digitado está na lista de tentativas. Se estiver, peça/sorteie outro número, antes de incrementar a quantidade de tentativas:
while True:
    y = randint(0,10)
    if y in lista_tentativas:
        continue # ja existe, tenta outro numero
    quantidade_tentativas += 1
    lista_tentativas.append(y)
    if y == x:
        print('O numero digitado foi {}')
        print(f'Essas foram todas as minhas tentativas: {lista_tentativas}')
        print(f'Essa foi a quantidade total de tentativas: {quantidade_tentativas} tentativas')
        break

Comment: Como sua resposta já contempla o que o AP pede, eu apenas vou deixar a dica de que `lista_tentativas` seja um `set()` pois é uma estrutura de dados otimizada para casos como este. ;D
Comment: @fernandosavio concordo, mas estou achando mais didático deixar o código da resposta o mais parecido possível com o da pergunta, para facilitar o entendimento
Comment: Não foi uma sugestão de mudança, a resposta está boa. Deixei o comentário para que as pessoas leiam depois de ler sua resposta, como um complemento. :)


Keras LSTM - Validation Loss Increasing From Epoch #1

Question: I'm currently undertaking my first 'real' DL project of (surprise) predicting stock movements. I know that I'm 1000:1 to make anything useful but I'm enjoying it and want to see it through, I've learnt more in my few weeks of attempting this than I have in the prior 6 months of completing MOOC's.
I'm building an LSTM using Keras to currently predict the next 1 step forward and have attempted the task as both classification (up/down/steady) and now as a regression problem. Both result in a similar roadblock in that my validation loss never improves from epoch #1.
I can get the model to overfit such that training loss approaches zero with MSE (or 100% accuracy if classification), but at no stage does the validation loss decrease. This screams overfitting to my untrained eye so I added varying amounts of dropout but all that does is stifle the learning of the model/training accuracy and shows no improvements on the validation accuracy.
I have attempted to change a significant number of hyperparameters - learning rate, optimiser, batchsize, lookback window, #layers, #units, dropout, #samples, etc, also tried with subset of data and subset of features but I just can't get it to work so I'm very thankful for any help.

Code Below (it's not pretty I know):
# Import saved full dataframe ~ 200 features
import feather
df = feather.read_dataframe('df_feathered')
df.set_index('time', inplace=True)

# Difference the dataset to make stationary
df = df.diff(periods=1, axis=0)

# MAKE LARGE SAMPLE FOR TESTING
df_train = df.loc['2017-3-1':'2017-6-30']
df_val = df.loc['2017-7-1':'2017-8-31']
df_test = df.loc['2017-9-1':'2017-9-30']

# Make x_train, x_val sets by dropping target variable
x_train = df_train.drop('close+1', axis=1)
x_val = df_val.drop('close+1', axis=1)

# Scale the training data first then fit the transform to the test set
scaler = StandardScaler()
x_train = scaler.fit_transform(x_train)
x_test = scaler.transform(x_val)

# scaler = MinMaxScaler(feature_range=(0,1))
# x_train = scaler.fit_transform(df_train1)
# x_test = scaler.transform(df_val1)

# Create y_train, y_test, simply target variable for regression
y_train = df_train['close+1']
y_test = df_val['close+1']

# Define Lookback window for LSTM input
sliding_window = 15

# Convert x_train, x_test, y_train, y_test into 3d array (samples,
timesteps, features) for LSTM input
dataXtrain = []
for i in range(len(x_train)-sliding_window-1):
        a = x_train[i:(i+sliding_window), 0:(x_train.shape[1])]
        dataXtrain.append(a)

dataXtest = []
for i in range(len(x_test)-sliding_window-1):
        a = x_test[i:(i+sliding_window), 0:(x_test.shape[1])]
        dataXtest.append(a)

dataYtrain = []
for i in range(len(y_train)-sliding_window-1):
        dataYtrain.append(y_train[i + sliding_window])

dataYtest = []
for i in range(len(y_test)-sliding_window-1):
        dataYtest.append(y_test[i + sliding_window])

# Make data the divisible by a variety of batch_sizes for training
# Started at 1000 to not include replaced NaN values
dataXtrain = np.array(dataXtrain[1000:172008])
dataYtrain = np.array(dataYtrain[1000:172008])
dataXtest = np.array(dataXtest[1000:83944])
dataYtest = np.array(dataYtest[1000:83944])

# Checking input shapes
print('dataXtrain size is: {}'.format((dataXtrain).shape))
print('dataXtest size is: {}'.format((dataXtest).shape))
print('dataYtrain size is: {}'.format((dataYtrain).shape))
print('dataYtest size is: {}'.format((dataYtest).shape))

### ACTUAL LSTM MODEL

batch_size = 256
timesteps = dataXtrain.shape[1]
features = dataXtrain.shape[2]

# Model set-up, stacked 4 layer stateful LSTM
model = Sequential()
model.add(LSTM(512, return_sequences=True, stateful=True,
               batch_input_shape=(batch_size, timesteps, features)))
model.add(LSTM(256,stateful=True, return_sequences=True))
model.add(LSTM(256,stateful=True, return_sequences=True))
model.add(LSTM(128,stateful=True))
model.add(Dense(1, activation='linear'))

model.summary()

reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.9, patience=5, min_lr=0.000001, verbose=1)

def coeff_determination(y_true, y_pred):
    from keras import backend as K
    SS_res =  K.sum(K.square( y_true-y_pred ))
    SS_tot = K.sum(K.square( y_true - K.mean(y_true) ) )
    return ( 1 - SS_res/(SS_tot + K.epsilon()) )

model.compile(loss='mse',
              optimizer='nadam',
              metrics=[coeff_determination,'mse','mae','mape'])

history = model.fit(dataXtrain, dataYtrain,validation_data=(dataXtest, dataYtest),
          epochs=100,batch_size=batch_size, shuffle=False, verbose=1, callbacks=[reduce_lr])

score = model.evaluate(dataXtest, dataYtest,batch_size=batch_size, verbose=1)
print(score)

predictions = model.predict(dataXtest, batch_size=batch_size)
print(predictions)

import matplotlib.pyplot as plt
%matplotlib inline
#plt.plot(history.history['mean_squared_error'])
#plt.plot(history.history['val_mean_squared_error'])
plt.plot(history.history['coeff_determination'])
plt.plot(history.history['val_coeff_determination'])
#plt.plot(history.history['mean_absolute_error'])
#plt.plot(history.history['mean_absolute_percentage_error'])
#plt.plot(history.history['val_mean_absolute_percentage_error'])
#plt.title("MSE")
plt.ylabel("R2")
plt.xlabel("epoch")
plt.legend(["train", "val"], loc="best")
plt.show()

plt.plot(history.history["loss"][5:])
plt.plot(history.history["val_loss"][5:])
plt.title("model loss")
plt.ylabel("loss")
plt.xlabel("epoch")
plt.legend(["train", "val"], loc="best")
plt.show()

plt.figure(figsize=(20,8))
plt.plot(dataYtest)
plt.plot(predictions)
plt.title("Prediction")
plt.ylabel("Price")
plt.xlabel("Time")
plt.legend(["Truth", "Prediction"], loc="best")
plt.show()

Comment: Such a symptom normally means that you are overfitting. You model works better and better for your training timeframe and worse and worse for everything else. This is a good start. Now you need to regularize. Try to add dropout to each of your LSTM layers and check result.
Comment: Thanks for the reply Manngo - that was my initial thought too. However after trying a ton of different dropout parameters most of the graphs look like this: https://imgur.com/yQyjs5Y Validation loss just will not go down :(
Comment: Ah ok, val loss doesn't ever decrease though (as in the graph). I did have an early stopping callback but it just gets triggered at whatever the patience level is. Is it possible that there is just no discernible relationship in the data so that it will never generalize? Sounds like I might need to work on more features?
Comment: Well, MSE goes down to 1.8 in the first epoch and no longer decreases. It is possible that the network learned everything it could already in epoch 1. At the beginning your validation loss is much better than the training loss so there's something to learn for sure. What is the min-max range of y_train and y_test? What is the MSE with random weights? I'm not sure that you normalize y while I see that you normalize x to range (0,1). If y is something like 2800 (S&P 500) and your input is in range (0,1) then your weights will be extreme.
Comment: Yeah, this pattern is much better. I would stop training when validation loss doesn't decrease anymore after n epochs. Try early_stopping as a callback. The only other options are to redesign your model and/or to engineer more features.
Answer: Maybe you should remember you are predicting sock returns, which it's very likely to predict nothing. So val_loss increasing is not overfitting at all. Instead of adding more dropouts, maybe you should think about adding more layers to increase it's power.
Answer: Try Changing the Optimizer and Learning Rates. Regularizations Works a lot in the case of overfitting.


zeros of a multi-valued function

Question: Consider the equation below
$$ z -1 - \left( \frac{1}{\sqrt{z^2+z + 1}} - \frac{2}{\sqrt{z^2 + 4}} \right) = 0. $$
The function on the lhs is a four-valued function. To get its zeros, we can convert it into a 12th order polynomial equation by squaring.
Then we will get 12 zeros.
The question is then, are all these zeros indeed zeros of the original equation? More precisely, for each of them, is it always possible to make the function on the lhs vanish by taking the signs of the square roots correctly?
Is there any general theory for such kind of problem?
Comment: No. In this case, the $12$ roots will not be distinct, they will be repeated roots, because the only solution of $(f(x))^n = 0$ is $f(x) = 0$ for $n \in \mathbb{N}$, so the extra roots will come in groups of equal roots. You can check this either by yourself, or in Wolfram Alpha. By the way, what does this question immediately have to do with Riemann surfaces?
Comment: @астонвіллаолофмэллбэрг It has to do somehow because the two-branched square root function gives rise to a Riemann surface, "wrapping" both sheets one over the other. There's a nice explanation in pages 4-6 here: http://scipp.ucsc.edu/~haber/ph116A/ComplexFunBranchTheory.pdf
Comment: @DonAntonio Thank you for the reference.
Answer: Yes. Let $u = \sqrt {z^2+z+1}$ and $v = \sqrt {z^2+4}$, so that we have $u^2 = z^2+z+1$ and $v^2=z^2+4$.
Your equation $z-1-1/u+2/v = 0$ is equivalent to $(z-1)uv-v+2u = 0$.
Now if you want to get an equation that only talks about $z$ from this, you have to multiply $(z-1)uv-v+2u$ with its conjugates.
In terms of Galois theory, $\Bbb C(z)[u,v]$ is a Galois extension of $\Bbb C(z)$, its Galois group is isomorphic to $(\Bbb Z/2\Bbb Z)^2$ and is generated by $(u,v) \mapsto (-u,v)$ and $(u,v) \mapsto (u,-v)$.
Taking the norm of $(z-1)uv-v+2u$ will give you the expression
$((z-1)uv-v+2u)(-(z-1)uv-v-2u)(-(z-1)uv+v+2u)((z-1)uv+v-2u)$
This is invariant when you replace $u$ with $-u$ or $v$ with $-v$, so when you expand it and simplify, it is a polynomial expression in $z,u^2,v^2$.
Now you can replace $u^2,v^2$ with the corresponding polynomials in $z$, and you get that this product is actually a degree $12$ polynomial in $z$ (probably the same one that you've got).
Now, if $z$ is a root of the degree $12$ polynomial, and if you pick for $u$ and $v$ any of their two corresponding values and plug everything into the product, since the product evaluates to $0$, you must have that at least one of its factors also evaluates to zero. This means that there must be a choice for $u$ and $v$ that makes the original expression evaluate to $0$.
Comment: amazing! I encountered this problem in some quantum mechanics problem. I never expected that it has something to do with the Galois theory. So, is there any reference on this kind of problem? I mean not the Galois theory.

zeros of a multi-valued function


Find the limit : $\lim_{x \to \frac{\pi}{4}^-}\frac{\sin^2x-\cos 2x-\frac{1}{2}}{x-\frac{\pi}{4}}$

Question:
Find the limit :
  $$\lim_{x \to \frac{\pi}{4}^-}\frac{\sin^2x-\cos 2x-\frac{1}{2}}{x-\frac{\pi}{4}}$$

My work.
$$x-\frac{\pi}{4}=u \to x=\frac{\pi}{4}+u$$
$$\cos 2(\frac{\pi}{4}+u)=\cos (\frac{\pi}{2}+2u)=-\sin 2u $$
So we have :
$$\lim_{x \to \frac{\pi}{4}^-}\frac{\sin^2(\frac{\pi}{4}+u)+\sin 2u-\frac{1}{2}}{u}.$$
Now what?
Comment: Use L'Hospital's rule
Answer: Hint:
Using $\cos2x=1-2\sin^2x,$
$$\dfrac{2\sin^2x-2\cos2x-1}{2x-\dfrac\pi2}=\dfrac{-3\cos2x}{2x-\dfrac\pi2}$$
Set $2x-\dfrac\pi2=y$
Comment: let $f(x)=\sin^2x-\cos2 x$  then $$\lim_{x \to \frac{\pi}{4}^-}\frac{\sin^2x-\cos 2x-\frac{1}{2}}{x-\frac{\pi}{4}}= f'_{-}(\frac{\pi}{4})$$
So :
$$f'(x)=2\sin x\cos x +2\sin 2x$$
thus :
$$f'(\frac{\pi}{4}) =3$$
it is right ?
Comment: @Almot1960, Right u r
Answer: Following your approach,
\begin{align}\lim_{x \to \frac{\pi}{4}^-}\frac{\sin^2x-\cos 2x-\frac{1}{2}}{x-\frac{\pi}{4}}&=\lim_{u \to 0^-}\frac{\sin^2(u+\pi/4)-\cos 2(u+\pi/4)-\frac{1}{2}}{u}\\
&=\lim_{u \to 0^-}\frac{\left(\frac{\sin(u)+\cos(u)}{\sqrt{2}}\right)^2+\sin(2u)-\frac{1}{2}}{u}\\
&=\lim_{u \to 0^-}\frac{\frac{1}{2}\left(1+u+o(u)\right)^2+2u+o(u)-\frac{1}{2}}{u}\\
&=\lim_{u \to 0^-}\frac{u+2u+o(u)}{u}=3
\end{align}
where we used the fact that $\sin(au)=au+o(u)$ as $u \to 0$.


Implicit space partitiong in neural networks vs space partitioning in tree-based methods

Question: Tree-based methods, e.g., random forests or GBRT use trees to construct most informative space partitioning. Given a single tree, in each partition, the value of the regression function (or a class) is computed using a simple model. For example, it can be a constant or a single label. Catboost's regression trees AFAIK can fit a linear regression.
In contrast, even simple 1-2 hidden layer neural networks (with non-linear activation) can beat GBRTs or random forests although it is not clear how a couple of matrix multiplications can apparently create region-specific regression or classification functions. Region-specific is a bit of a misnomer, but the point is that neural networks can apparently identify regions of interest and behave differently in different regions.
Is there a simple explanation of how this happens? Is there a complicated one (e.g., some theory)?
Many thanks!
Comment: OP Posted this link, since deleted: http://searchivarius.org/blog/adversarial-examples-and-space-partitioning-capabilities-neural-networks
Answer: In fact, the decision tree is equivalent with the deep neural network with the ReLU activation function.
See the paper Oblique Decision Trees from Derivatives of ReLU Networks
or the or discussion on decision tree and neural networks.
Comment: Thank you for the link. I've largely figured it out. Turns out there are number of papers that explain how these piecewise linear approximations work. In particular, you can always cut out a bounded polygon like shape by intersecting relu-defined planes. I put some of my thoughts in a blog (referencing some of the recent at that moment paper): http://searchivarius.org/blog/adversarial-examples-and-space-partitioning-capabilities-neural-networks


Passar o data-id="@milestones.Codigo" para uma modal

Question: O meu sistema deve funcionar da seguinte maneira:
Ao clicar no botão destacado a vermelho na imagem abaixo

Ele abre esse modal aqui:

Isso já acontece, porém agora preciso que ao clicar na primeira imagem, ele pegue o data-id="@milestones.Codigo" e salve no campo CodigoMilestone.
Botão que chama a modal Atividade:
<button class="btn btn-default AddAtividade" data-id="@milestones.Codigo"></button>

Script que abre o modal:
$(document).ready(function () {

$(".AddAtividade").click(function () {
    $("#modal").load("AddAtividade", function () {
        $(".modal").modal();
    })
});
})

Como é que posso fazer isso?
Comment: Deve ser alguma coisa parecida com isso:
`var id = $(this).attr("data-id");`
Answer: Poderia fazer algo assim.
$(document).ready(function () {

$(".AddAtividade").click(function () {

    var codigoMilestone = $(this).attr("data-id");

    $("#modal").load("AddAtividade", function () {

        $("#meuInputId").val(codigoMilestone);

        $(".modal").modal();
    })
});
})

Comment: Obrigado, funcionou.


If running webpack programmatically he doesn't find module

Question: I want to use webpack-api at my electron app for build external web project.
I decide using webpack API in my app, but webpack can't found the babel-loader.
I created simple repository to reproduce the error: repository
Abstract presentation of the project (A - electron app, B - web project for build)
Error msg:
main.js:1 Uncaught Error: Module build failed (from ./node_modules/babel-loader/lib/index.js):
Error: Cannot find module 'D:\User\B\node_modules\babel-loader\lib\index.js'
    at eval (webpack:///./node_modules/loader-runner/lib_lazy_namespace_object?:5)
    at eval (main.js:1)

Base structure of both project:
Project A:
- main.js
- node_modules/
- webpack.config.js

Project B:
- main.js
- node_modules/
- webpack.config.js

Every project is independent and has all tool for development(like webpack)
My webpack config in project A for run webpack (if I using '/' in path I get API Schema error at webpack):
module.exports = {
    mode: "development",
    target: "web",
    entry: "D:\\User\\B\\src\\main.js",
    context: "D:\\User\\B\\",
    output: {
        path: "D:\\A",
        filename: 'bundle.js',
    },
    module: {
        rules: [
            {
                test: /\.(js)$/i,
                exclude: /node_modules/,
                use: {
                    loader: 'babel-loader',
                },
            },
        ],
    },
    resolve: {
        modules: [
        'D:\\User\\B\\node_modules',   //the same error if remove this line
        ],
    },

    stats: {
        errorDetails: true
    },
}

Run webpack:
const webpack = require('webpack');
const config = require('./webpack.config');
const compiler = webpack(config);

compiler.run((err, stats) => {
   //output errors...
});

Important:

If to try build project B using webpack cli (through npm), no
errors.
Project A based on Electron.
Using library version on both project: babel-loader^8.1.0, @babel/core^7.9.0, webpack^4.42.1, electron^8.2.1(electron only at A project)
Bundle file is created
Bundle js file is using in HTML file
Answer: Looks like this server already has other webpack wich running in watch mode and constanlty removing packages. Try to reload the server


Which is better to use "==" or "-eq" for comparing the integers in bash shell ?

Question: I can see some article like  this where it is mentioned that "-eq" is used to compare the integers, but this doesn't say that we can't use "==" for comparing the integers.
I verified this on bash shell locally and "==" is working fine.
So can anyone let me help to understand which is better option to use, if "-eq" then why ?
Comment: Even for strings, `==` is not best practice inside `[ ]`; the POSIX sh standard specifies only `=`. Bash supports `==`, but this is an extension, and scripts using it may not be compatible with all other POSIX shells.
Comment: @CharlesDuffy so is `==` a "bashism" ?
Answer: To compare integers, use -eq.  The difference is that == compares string value while -eq compares numeric value.  Here is an example where they yield different results:
$ [ 03 = 3 ] ; echo $?
1
$ [ 03 -eq 3 ] ; echo $?
0

It is the same using [[:
$ [[ 03 == 3 ]] ; echo $?
1
$ [[ 03 -eq 3 ]] ; echo $?
0

As a number, 03 is equal to 3.  But, as a string 03 and 3 are different.
Summary:  To compare numeric values for equality, use -eq
Comment: BTW -- I found it necessary to add my own answer for only a few reasons: Lack of mention of math contexts (in which case `==` is correct), and the implication that `==` is best practice in `[[ ]]` even for strings (whereas it leads to POSIX-incompliant habits when using `[ ]`).
Answer: It depends on the context. In a math context (which is preferable if you're writing your scripts specifically for bash), use ==.
(( foo == 3 ))     ## foo = 3 would be an assignment here, and foo -eq 3 an error

A math context is also present in other situations -- for instance, indexing into a non-associative array, making == preferred but -eq illegal in the below contrieved example:
foo=( yes no )
bar=3
echo "${foo[bar == 3 ? 0 : 1]}" # echoes "yes"

In [[ ]], use -eq.
[[ $foo -eq 3 ]]   ## $foo = 3 would be a string comparison here; $foo == 3 is a synonym,
                   ## but bad finger-memory to have if one wants to write POSIX code
                   ## elsewhere.

In [ ], use -eq -- and also quote:
[ "$foo" -eq 3 ]   ## = would be a valid string comparison here; == would be a
                   ## POSIX-incompatible string comparison here; -eq is correct.


How do I alter image field code without hacking core?

Question: I need to change the style of the title in image field to be a text area rather than a text field. I can achieve this by hacking core in the following way:
image.field.inc line 410
$element['title'] = array(
    '#type' => 'textarea',
    '#title' => t('Title'),
    '#default_value' => isset($item['title']) ? $item['title'] : '',
    '#description' => t('The title is used as a tool tip when the user hovers the mouse over the image.'),
    '#maxlength' => variable_get('image_title_length', 500),
    '#weight' => -1,
    '#access' => (bool) $item['fid'] && $settings['title_field'],
  );

// Change '#type' => 'textarea'  to '#type' => 'textfield'

I don't though, want to hack core.
How can I create a preprocess function to allow me to do this via my template.php.
Answer: You won't (easily) be able to use a preprocess function to do this as the element is generated by a form.
You could use a non-generic hook_form_alter() implementation to do this on a single form, but the best way would be to write a small custom module and implementhook_field_widget_form_alter() to override the element.
The alt and title fields (along with some others) are only added in a #process function of each image element (image_field_widget_process()), so you'll need to add your own #process function to run after that one, and alter the field type in there.
The following code is tested and seems to work well (including playing nicely with the AJAX functionality on the image field):
function MYMODULE_field_widget_form_alter(&$element, &$form_state, $context) {
  // If this is an image field type
  if ($context['field']['type'] == 'image') {
    // Loop through the element children (there will always be at least one).
    foreach (element_children($element) as $key => $child) {
      // Add the new process function to the element
      $element[$key]['#process'][] = 'MYMODULE_image_field_widget_process';
    }
  }
}

function MYMODULE_image_field_widget_process($element, &$form_state, $form) {
  // Change the title field to a textarea
  $element['title']['#type'] = 'textarea';

  // Return the altered element
  return $element;
}

It produces results like this:

It might be worth bearing in mind that the maximum size of the title column is set in the database, so you won't be able to go any higher than 1024 characters.
Comment: Nice! and what to do if I would like to add additional css class to an image in the same way? I'm looking for a solution to be able to add class and it may be different in different cases. As I understand this could be achieved in some similar way, right?
Comment: Unfortunately not - the alt and title columns are already part of the image field, this method is just replacing the textfield with a textarea on the widget form. It's not adding any extra data to the field at all. To add another column, which takes a class, you'd be looking at implementing a custom field which is a lot more work
Comment: Could you give me a hint on where to start reading - as I understand now, for this I need to write a small module (I guess) ?


Why did I convert the outer integral from $ \int_0^\infty $ into $ \int _0^\frac{\pi}{2} $ not any other value of theta?

Question: QUESTION
$$I =\int_0^\infty e^{-x^2}\mathrm{d}x$$
such that $$ \int_0^\infty   \int _0^\infty e^{-(x^2+y^2)} \mathrm{d}x \ \mathrm{d}y = I^2 $$
Change the variable to polar coordinates in order to evaluate $$ \int_0^\infty   \int _0^\infty e^{-(x^2+y^2)} \mathrm{d}x \mathrm{d}y = I^2 $$
SOLUTION:
Here is where my question lies in these steps
$$\int _0^\frac{\pi}{2} \int_0^\infty\ e^{-r^2} r \mathrm{d}r\mathrm{d}\theta$$
Why $\frac{\pi}{2}$ not any other $\theta$ value in the integral? That's  a solution I found in a textbook, regardless the following steps, (conducting a non proper integral and computing the definte integral's value), this is the point where I don't understand.

And why do we consider the $e^{-a^2} =0$  in:

$$\frac{-1}{2} \left( \lim\limits_{a \to \infty}\ e^{-a^2}-1 \right)\int_0^\infty \mathrm{d}\theta=\frac{\pi}{4}$$
Answer: You're only interested in the first quadrant of $\Bbb R^2$ in the double integral. That is, the double integral is integrating over the region $(0,\infty)\times(0,\infty)$, which is precisely the first quadrant. If you think about the unit circle values for $\theta$ and determine which angles lie in the first quadrant, you'll see that the first quadrant corresponds to $\theta\in(0,\pi/2)$.
For the values of $r$, well, you want to cover the entire first quadrant. This means that along any ray with an angle of $\theta$ (as measured from the positive $x$-axis), you'll need to take $r$ from $0$ to $\infty$. Since you do this for every value of $\theta$, you end up with a double integral: one that integrates with respect to $\theta$ and another that integrates with respect to $r$.
Comment: @Mayar: You'd have to explain further what you mean. Here, the region is $(0,\infty)\times(0,\infty)$ which corresponds to the first quadrant; in other words, it's the same region as $(0,\pi/2)\times(0,\infty)$ in polar coordinates. If our region were $(-\infty,\infty)\times(0,\infty)\subset\Bbb R^2$, then $\theta$ would range between $0$ and $\pi$ since this would encompass the upper half plane.
Comment: and why am I concerned with just the first integeral ?
Comment: sorry I mean why am I concerned with just the first quadrat and not the rest ?  and does this apply to for the triple integeral too?
Comment: @Mayar: I've edited my answer. Does it make sense now why you're only concerned with the first quadrant?
Comment: The triple integral is going to have a similar trick, too. There you'll convert to spherical coordinates, if I recall correctly, though, so some of the constants will look a little different.
Comment: but in other polar forms questions but not improper double integeral was defined as $\theta$ from zero to 180 or 360 , I am confused


How to alter Core's user login final function

Question: In user.module, I need to alter the message that is displayed if the username/password is not recognized. I'm using the email registration module so I don't use usernames at all. I want the last form error message in the code below to show email/password instead, as well as add a custom redirect to it.
I've googled for quite some time, but cannot find how to hook onto this function. Any help would be appreciated!
function user_login_final_validate($form, &$form_state) {
  if (empty($form_state['uid'])) {
  // Always register an IP-based failed login event.
  flood_register_event('failed_login_attempt_ip', variable_get('user_failed_login_ip_window', 3600));
  // Register a per-user failed login event.
  if (isset($form_state['flood_control_user_identifier'])) {
  flood_register_event('failed_login_attempt_user', variable_get('user_failed_login_user_window', 21600), $form_state['flood_control_user_identifier']);
}

if (isset($form_state['flood_control_triggered'])) {
  if ($form_state['flood_control_triggered'] == 'user') {
    form_set_error('name', format_plural(variable_get('user_failed_login_user_limit', 5), 'Sorry, there has been more than one failed login attempt for this account. It is temporarily blocked. Try again later or request a new password.', 'Sorry, there have been more than @count failed login attempts for this account. It is temporarily blocked. Try again later or request a new password.', array('@url' => url('user/password'))));
  }
  else {
    // We did not find a uid, so the limit is IP-based.
    form_set_error('name', t('Sorry, too many failed login attempts from your IP address. This IP address is temporarily blocked. Try again later or request a new password.', array('@url' => url('user/password'))));
  }
}
else {
  // Fix password reset messages
  form_set_error('name', t('Sorry, unrecognized username or password. Have you forgotten your password?', array('@password' => url('user/password', array('query' => array('name' => $form_state['values']['name']))))));
  watchdog('user', 'Login attempt failed for %user.', array('%user' => $form_state['values']['name']));
}

}
Answer: Override login form with hook_form_alter()
You need to replace validation function with your custom function.
Answer: To change the validation function then you need to add it to the #validate part of the form array in hook_form_alter:
function MYMODULE_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'user_login') {
    $form['#validate'][] = 'MY_user_login_final_validate';
  }
}

You will need to examine the $form['#validate'] array to remove the current user module validation and possibly adjust the weight of the module in the system table.
To redirect you add something like the following to hook_form_alter:
$form['#submit'][] = 'my_redirect_node_form_submit';

Again bearing in mind you might need to alter/re-order the current contents of $form['#submit'] and the system table weight.
OR if you want to simply change the string then you could do it in a number of ways.

The string overrides module: https://www.drupal.org/project/stringoverrides
Put the overrides in the settings.php file:
$conf['locale_custom_strings_en'][''] = array(
  'Sorry, unrecognized username or password. Have you forgotten your password?' => 'YOUR MESSAGE HERE',
);

Put this in hook_boot() :
global $conf;
$conf['locale_custom_strings_en'][''] = array(
  'Sorry, unrecognized username or password. Have you forgotten your password?' => 'YOUR MESSAGE HERE',
);

The trick is to replicate exactly what is in the string surrounded by `t('') in the user module (currently this is line 2228).
      form_set_error('name', t('Sorry, unrecognized username or password. Have you forgotten your password?', array('@password' => url('user/password', array('query' => array('name' => $form_state['values']['name']))))));

Then you can let the Drupal string translation system take care of it for you.  See here for a reference on Drupal.org
Comment: Great thanks for detailed resposne, I will try it today.
Comment: Thanks for your suggestion, I was able to hook into that validation process but the user.module validation still is called last. I changed the user.module weight to 9018 (my module weight is 9001) in the system table, cleared caches several times but user.module's validation is still winning... I also tried pushing my hook's weight to the top as described in [http://drupal.stackexchange.com/questions/21685/hook-module-implements-alter-not-working-for-me-what-am-i-doing-wrong](http://drupal.stackexchange.com/questions/21685/hook-module-implements-alter-not-working-for-me-what-am-i-doing-wrong)
Comment: I can't check today but I thought that the heavier weighted modules were called later, so is just that you need to make your module weight greater than the user module's?
Comment: You were right. I changed the user.module weight to 7018, and now it's working well! I was having another issue that was confusing since both the user.module and my module were throwing a form_set_error on the same element, therefore I would only see the user.module error. I had to use drupal_get_messages('error'); to clear the user's error, and then only my module's error was showing. Thanks again!


Create open close delimiters in XML created with Excel

Question: I'm exporting an XML file from excel, and for empty elements, excel creates the field like this:
<my_empty_element/>

However, my application needs it to be like this:
<my_empty_element></my_empty_element>

Is there any way to have excel to do this, I'm trying to avoid workarounds like search/replace text on the XMl file?
Comment: Also, how are you parsing the file? Most SAX/DOM parsing libraries should be able to handle this case. If you wrote your own parser you may want to add support for this fairly common case or use an established XML parsing library.
Comment: I'm using this function ActiveWorkbook.XmlMaps("CertificadoEnergetico_Map").Export in my vba code
Comment: To edit, the XML after exported, I'm using MSXML2.DOMDocument to load the XML and insert some data on elements I cannot map in the excel sheet. I believe this is the parsing library, on references I have "Microsoft XML, v3.0"
Comment: like others have said - from XML / DOM parsing perspective it makes no difference how the empty element is encoded - in fact it's quite correct for excel to export like this.
Comment: If you're later parsing this with MS tools it should handle such elements like any other - for example you can append children elements to such empty elements and will show up correctly when you serialize again to text/XML
Comment: Correcting my post to avoid misinterpretation, the problem exists because the application/service which receives the XML doesn't accept the empty element encoded on the single open/close "/>". Probably a poor XML implementation, but it's a public service not under my control, so I'll have to do it like that anyway.. guess I'll end up doing the find/replace.
Answer: Why does your application need it to be that way?
Instead of fixing Excel's correct behavior, why not fix the application that doesn't understand sole-tags?


Tem como transferir os dados do MySQL direto pra uma tabela no Excel?

Question: Tem alguma forma de transferir toda informação do banco de dados para uma tabela no Excel? Pode ser com qualquer linguagem.
Comment: Verifica a ver se te ajuda https://blogs.oracle.com/MySqlOnWindows/entry/how_to_guide_to_importing
Comment: Você precisa exatamente de que? Uma função em um possível sistema que faça a importação para excel?
Comment: Bom dia amigo, o proprio excel tem a opção de exportar para CSV. Após abrir voce pode salvar com xls.
Answer: Você pode exportar para CSV (dados separados com virgula), que o Excel abre normalmente. Se estiver usando PHPMyAdmin, ele tem uma opção exclusiva para esta exportação.
Se estiver usando a ferramenta MySQL Workbench, neste link ensina passo-a-passo como exportar por ele.
Ou por linha de comando ficaria assim:
<code>SELECT * FROM bancodedados.tabela
INTO OUTFILE 'arquivo.csv'
FIELDS TERMINATED BY '|'
ENCLOSED BY '"'
LINES TERMINATED BY '\n';
</code>
Answer: Fácil amigo, Instale essa versão ou superior do MySQL certifique-se de instalar MySQL For Excel e prontinho, dentro do Excel 2007 ou superior no fim da aba DADOS você encontrara um novo botão MySQL For Excel basta configurar a conexão e desfrutar dos benefícios!


Delete items from ComboBox

Question: I want to delete items from comboBox on java, if items exist in data table's column.
For example comboBox items: 09:00, 10:00, 11:00 and Data table value: 10:00  on this example, it must delete "10:00" on Combobox.
Answer: You can use DefaultComboBoxModel which has public void removeElementAt(int index) method.
Or just recreate the model when necessary and set the new model to already existing combobox.
Answer: You can use the removeItemAt(int itemIndex) method of JComboBox.
Comment: Requires a mutable data model.
Comment: @trashgod true - but that's the default except when explicitly setting a custom immutable model :-)

Delete items from ComboBox


If we consider $f\neq 0$, can we infer that $\int_{-1}^1 f(t)dt=0$ iff $f$ is odd?

Question: I am considering continuous functions $f\in C[-1,1]$. We know tha the area under an even function over a symmetric interval can be calculated by doubling the area over the positive  x -axis. For an odd function, instead, the integral over a symmetric interval equals zero, because half the area is negative. So, for odd functions $f\in C[-1,1]$ we have that
$$\int_{-1}^1 f(t)dt=0$$
The question is the following. If we consider $f\neq 0$, can we infer that $\int_{-1}^1 f(t)dt=0$ iff $f$ is odd?
Comment: Surely not. You can easily construct (continuous, not identially zero, not odd) functions with $\int_{-1}^0 f(t)dt = -1$ and $\int_{0}^1 f(t)dt = 1$.
Comment: However, if $\int_{-x}^x f(t)\,\mathrm d t=0$ for all $x$, then indeed $f$ is odd.
Answer: No, we cannot infer that. For instance,$$\int_{-1}^13x^2-1\,\mathrm dx=0,$$but $3x^2-1$ is an even function.
Comment: @bb_823 The question was "If we consider $f\neq 0$, can we infer that $\int_{-1}^1 f(t)dt=0$ iff $f$ is odd?" I don't see what is it that you mean when you say that the question is about the odd function. Which odd function?
Comment: The question was about the odd function. I'm fairly sure that the statement in the question is in fact true, but correct me if I'm wrong
Answer: No just take for example $f(x) = 1$ for $|x|\leq 1/2$ and $f(x) = -1$ for $|x|>1/2$
Answer: No, you can't. An example may be a continuous function $f$ which is $x$ if $0\leq x\leq 1$ and $\frac{3}{2}x^2$ if $-1\leq x\leq 0$.
Indeed
$$\int_{-1}^1 f(t)dt=\int_{-1}^0 f(t)dt+\int_{0}^1 f(t)dt=\frac{1}{2}-\frac{1}{3}\frac{3}{2}=0$$


Add allowed file extensions in Views Send file field

Question: Using the Views Send module to send mass email.
On the email creation page I want to set my custom validation extensions for the file field provided by Views Send in combination with MimeMail (r# 267 in views_send.module).
For the file field I am trying to set the only allowed extension to be of type .docx by using the following function:
function my_module_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == "views_form_views_send_page") {
    if ($form_state['step'] == 'views_send_config_form') {

      $form['mail']['views_send_attachments'] = array(
        '#type' => 'file',
        '#title' => t('Attachment'),
        '#upload_validators' => array(
          'file_validate_extensions' => array('docx'),
        ),
     );
  }
}

Unfortuanetely this is not working. What am I doing wrong here?
Answer: Turns out the file behavior you're looking for is not defined for file elements, but for managed_files. It's as easy as:
/**
 * Implements hook_form_FORM_ID_alter().
 */
function my_module_form_views_form_send_page_alter(&$form, &$form_state) {
  if ($form_state['step'] == 'views_send_config_form') {
    $form['mail']['views_send_attachments']['#type'] = 'managed_file';
    $form['mail']['views_send_attachments']['#upload_validators']['file_validate_extensions'][] = 'docx';
  }
}

But views_send will have to be patched to support managed_files. This still needs work in the issue queue.

Yet, as I mention in the issue, you can hack it directly in the module. It's not recommended, but we don't have a hook here and the issue above might take a while to be solved. So just change the line
$file = file_save_upload('views_send_attachments', array(), $dir);

to
$file = file_save_upload('views_send_attachments', array('file_validate_extensions' => array('docx')), $dir);

Comment: When I make it a managed file Views Send is complaining: Warning: Invalid argument supplied for foreach() in views_send_confirm_form() (regel 483 van /var/www/example.com/sites/all/modules/contrib/views_send/views_send.module)
Comment: To clarify better, I want to set my custom validation extensions for the file field provided by Views Send in combination with MimeMail (r# 267 in views_send.module)
Comment: Hm, I was just being naive. If you want to use `managed_file` then you'll have to patch views_send. It's an easy patch, though. I'll see you in the issue queue.
Comment: Thanks, I opened up an issue there as well https://drupal.org/node/2076659
Comment: Thanks, I tried that myself already but this is exactly what I am trying to avoid so I was hoping for another solution. I was thinking about creating a patch to add another textfield to the admin page where you can set your allowed extensions and then do a simple check with variable_get in file_save_upload