Good video lectures for studying Calculus?

Question: I am looking for a good online video resource to start studying Calculus. I am studying it alone, not part of any school or university. Trying to learn and enhance my mathematical skills.
Thanks!
Comment: [`Mathematica` is a software tool](http://www.wolfram.com/mathematica/)
Comment: This is not really a Mathematica question, or are you looking for a calculus video with Mathematica as tool?
Comment: I'm sorry if this is not the appropriate place. I wish to study mathematics. I was under the impression a math forum would be a good place to consult. I am not sure what it means 'a calculus video with Mathematica as tool'
Comment: Appreciate your effort, me too doing it alone, keep in touch.  I feel MIT lectures should be good, but nothing can replace books :)
Answer: I would suggest the following: http://ocw.mit.edu/courses/mathematics/18-01-single-variable-calculus-fall-2006/video-lectures/
I learned a lot from these lectures (not the ones in the link but the multivariable calculus ones) but these are just as good!
Comment: This link has better notes and designed for internet self learning.
https://ocw.mit.edu/courses/mathematics/18-01sc-single-variable-calculus-fall-2010/index.htm
Comment: The link in the Answer to ocw.mit.edu appears to be dead. The link in @vincentmathew is still good. Link rot; link rot and taxes.
Answer: The Kahn Academy has many mathematics video courses.
Answer: Gilbert Strang's Highlights of Calculus videos are probably good.
Comment: Having watched them, I can attest that they are *actually* good. Good recommendation.
Answer: In addition to the ones already mentioned by the other posters, I highly recommend you watch these excellent lectures by Selwyn Hollis.
As well, here are some hard to find videos corresponding to the 11th edition of Thomas Calculus that I enjoyed a long time ago. While the book links all appear to be dead, and not all of the videos work, most of the videos do work, and the deliverers are outstanding: Thomas.
I am surprised that the latter are still extant.
Answer: You may find Adrian Banner's Calculus Lifesaver course useful. The series of 24+ videos are available at http://press.princeton.edu/video/banner/ and are also provided on the iTunes Store as Podcasts. The quality of the videos is variable, but the exposition is thorough, and his style is engaging.
Answer: This tutorial should definitely be your starting point. Grant helps you team math in the best possible way such that you retain the concept in best possible way.
https://www.youtube.com/playlist?list=PLZHQObOWTQDMsr9K-rj53DwVRMYO3t5Yr
Answer: I found this
I myself used Tom Apostol's Calculus volume 1.(I am not really an expert )
[MIT Open courseware]
Answer: The web site www.academicearth.org has a wide variety of entire courses in mathematics, especially in calculus (Not to mention history, philosophy, psychology, etc.). It's one of my favorite sites!
Answer: I studies Single variable calculus from Thomas Finney and currently doing Multi-variable calculus from Kenneth Kuttler.
NOTE: In Video lecture for Multi-variable Calculus by Edward Frenkel of UC berkeley, in the first lecture he is referring to an equation (function y=f(x)) and he says that there are 2 "independent" variables and 1 equation, so number of independent variables minus number of equations gives us the dimension.
Answer: The video lectures at the "best" schools tend to be less systematic and orderly. All are useful, but if you are using videos to self-teach I would suggest the UMKC calculus 1 lectures by Delaware. There is no live audience, and thus no stammering, no showing up and teaching off the top of one's head. More progressive and orderly.
Answer: I highly recommend learning Calculus from the ground up with Professor Leonard. His video lectures are comprehensive, comprehensible, and help the math stick long after you've watched his videos. I completed his Calc 1 and Calc 2 courses. I am halfway through his Calc 3 videos. I suggest starting here: https://www.youtube.com/playlist?list=PLF797E961509B4EB5
The other recommendations such as the Strang Lectures and the 3Blue1Brown Essence of Calculus lectures make a great supplement, but I do not recommend them as the way to build your foundation.
The Apostol books can be considered the bible of Calculus. They are wonderful texts, but they are not for beginners.


Descending Minor7♭5 Introduction/Motif Questions

Question: Some jazz arrangements that I've heard use a motif(?) where a series of descending minor chords are played, starting on the #iv of the major scale.
For example, in the key of D, the progression is as follows:
A♭m7♭5 → Gm7 → G♭m7 → Fm7 → Em7 → A7 → Dmaj7
The video below shows an example of what I am trying to describe in an arrangement of "What a Friend We Have In Jesus" by Walter Rodrigues Jr.

Mr. Rodrigues begins the song playing an A♭m7♭5 followed by chromatic descending minor 7 chords until the ii (Em7) chord is reached. At this point the rest of the progression is a ii-V-I or Em7 → A7 → Dmaj7
Two questions:

Is there a name for this particular device/motif?
I've also heard this used in other sections of music in other songs, so if there was a request from someone to improvise a line or lines over this harmony, what would help one determine what lines to play?
Comment: That '-' is so confusing. Sometimes it means dash, others it means minor. More easily read as lower case or with 'm' instead. Yes, I know it's used a lot in jazz, but it's confusing, particularly in handwritten stuff, where it can even not be clearly seen. Never liked it in NNS either. Rant over!
Comment: @jazzBox, I really like this question and LOVE the example you gave. +1 I've made an edit and the biggest change is calling the starting chord a #iv rather than a bV. I believe #iv is the standard name for the chord. (The first paragraph [here](https://en.wikipedia.org/wiki/Half-diminished_seventh_chord#Function) has a good description.) Please check to make sure I haven't changed any of the content or overstepped in my editing!
Answer: I think this can be analyzed as a combination of two devices. The first is a ♯ivm7♭5 chord, and the second is iii → biii → ii movement.
♯ivm7♭5 chord
One function of the half-diminished chord (m7♭5 chord) is to serve as a chromatic passing chord, which leads to a diatonic chord. The diatonic chord would simply something like a IV chord, a iv chord, a iii chord, etc. For example, instead of writing Dm7 → E♭dim → Em7, we could write Dm7 → E♭m7♭5 → Em7.
Of all the possible ways to use a half-diminished chord as a passing chord, one of the most common is the ♯ivm7♭5 chord. In jazz, an iconic example of this is in Night and Day by Cole Porter:

In measure 9, we see F♯m7♭5, a ♯ivm7♭5 chord for the key of CMaj. After this, the progression continues almost exactly as your progression from Rodrigues Jr.'s. The only difference is the ♭iii chord. Using the key of C, we have this:
Your Progression: F♯m7(♭5) → Fm7 → Em7 →  E♭m7  → Dm7 → G7 → CMaj
Night and Day:    F♯m7(♭5) → Fm7 → Em7 → E♭dim7 → Dm7 → G7 → CMaj
The top progression (from Night and Day) is more common in jazz than the bottom progression. The top progression (or a variation of it) can be found in many other tunes, including All the Things You Are, as another good answer points out. But to understand your progression, we have to look at the ♭iii chord.
iiim7 → ♭iiim7 → iim7
As you've suggested yourself, the reason for the iiim7 → ♭iiim7 → iim7 is to preserve the parallel movement of the chromatic minor 7th chords. This sound is more common in funk, rock, and pop music. The first example that comes to mind is Alicia Keys's If I Ain't Got You. The key is GMaj, and repeatedly through the song we hear the progression Bmin → B♭min → Amin. The chorus uses a 16-measure form, and the progression is heard in measures 12-13. For example, the first chorus begins at 1:12, and so the first time we hear the chromatic descending min7 chords is at 1:28.
How to Solo
Descending minor licks sound good over this sort of progression. In fact, many people will simply take a single lick and move it down half steps over each chord. Doing that over every minor 7th chord can sound too mechanical for some, and so many people will limit that chromatic movement of the lick to the ♯ivm7♭5 chord and the ivm7 chord. Using descending Dorian scales sound good for that type of approach. Another way to add variety to descending chromatic licks is to simply change the feel when you reach the iim7 chord. An example I really like is to change from (a) descending chromatic Dorian licks to (b) a C blues sound or a C pentatonic sound. So for the entire ii-V-I progression, I might construct blues licks from a C-D-E♭-E-G-A scale or just use a C pentatonic scale.
Another nice option for soloing is to add the V7 chords and use descending ii-V licks. This is something you hear in bebop quite frequently, and it's a common technique for reharmonizing songs. (This might be planned or on-the-fly. I used to play with a sax player who loved to throw these in and expected the rhythm section to hear and follow him.) For example, in C, the progression would become:
|F♯m7(♭5) | Fm7  B♭7 | Em7  A7 | E♭m7  A♭7 | Dm7     | G7    | CMaj   |
There are many examples of chromatically descending ii-V progressions, but one that comes to mind is mm. 6-10 of Blues for Alice:

In a sense, this substitution makes soloing much easier because it's easier to find resolution in a ii-V progression than in descending ii chords. Whether we add the V chords or not, the implied ii-V progress is the reason that Dorian is the scale of choice on these types of descending iim7 chords.
Answer: I'd say it's a cliché, found in many jazz standards. It's a progression in descending chromatic seconds and then a progression in descending fifths. A shorter one can be found at the end of All the things you are: Dbmaj -Dbm7- Cm7 - Bdim- Bbm7 - Eb7 - AbMAJ. I couldnt say what I play over the chromatic progression when we play that tune but I try to have in mind where we are going and that's the II-V-I. I suppose that you could play dorian scales over the Xm7 chords and locrian#2 over the Xmb5 chord in the example you give.
Answer: Descending chromatic roots can be analysed as a 'cycle of 5ths' progression with alternate chords given their b5 substitution.  Hence D, G, C, F etc.   become D, Db, C, Cb...
Answer: It is descending chromatics, down to the expected ii>V>I. That Abm7b5 could almost be confused for a V9/V, with no root, so could pretend to herald a modulation into V, if it came in the middle, which doesn't happen. Thoughts initially were about tritone subs, but with all those minors, it can't be. Lovely sequence though.


How and why does Batch Normalization use moving averages to track the accuracy of the model as it trains?

Question: I was reading the batch normalization (BN) paper (1) and didn't understand the need to use moving averages to track the accuracy of the model and even if I accepted that it was the right thing to do, I don't understand what they are doing exactly.
To my understanding (which might be wrong), the paper mentions that it uses the population statistics rather than the mini-batch statistics once the model has finished training. After some discussion of unbiased estimates (that seems tangential to me and I don't understand why it talks about that) they go and say:

Using moving averages instead, we track the accuracy of the model as
it trains.

That is the part that is confusing to me. Why do they do moving averages to estimate the accuracy of the model and over what data set?
Usually what people do to estimate the generalization of their model, they just track the validation error of their model (and potentially early stop their gradient descent to regularize). However, it seems that batch normalization is doing something completely different. Can someone clarify what and why it's doing something different?

1: Ioffe S. and Szegedy C. (2015),
"Batch Normalization: Accelerating Deep Network Training by Reducing
Internal Covariate Shift",
Proceedings of the 32nd International Conference on Machine Learning, Lille, France, 2015.
Journal of Machine Learning Research: W&CP volume 37
Comment: Are you satisfied with the upvoted answer? It isn't an "answer" at all, if you ask me; if still relevant, I can provide a better answer.
Comment: @OverLordGoldDragon provide ur own answer :)
Answer: When using batch_normalization first thing we have to understand is that it works on two different ways when in Training and Testing.

In Training we need to calculate mini batch mean in order to normalize the batch

In the inference we just apply pre-calculated mini batch statistics

So in the 2nd thing how to calculate this mini batch statics
Here comes the moving average
<code>running_mean = momentum * running_mean + (1 - momentum) * sample_mean
running_var = momentum * running_var + (1 - momentum) * sample_var
</code>
Comment: This does not answer the question whatsoever; "why" and "how" was asked, and a superficial "what" was given. It shouldn't be upvoted.
Comment: @CharlieParker Training data, I would presume. The mini-batches are created during training and their mean/variance is also calculated during training, after all.
Comment: does the pre-calcualted stats come from data at training or test?
Answer: They are talking about batch normalization, which they have described for the training procedure but not for inference.
This is a process of normalizing the hidden units using sample means etc.
In this section they explain what to do for the inference stage, when you are just making predictions ( ie after training has completed).
However, in stopped validation you interleave prediction on validation set with training to estimate your validation error.
So during this process you don't have a population average (the averages are still changing as you train), so then you use a running average to calculate the batch norm parameters to calculate performance on validation set.
It is in this sense that

Using moving averages instead, we track the accuracy of the model as it trains.

nothing to do with literally using the running means as a metric for neural network performance.
Answer: In the paper you referenced, the suggested test time behavior is to compute sample mean and variance for each feature using a large number of training images rather than using a running average.
This block of code
<code> running_mean = momentum * running_mean + (1 - momentum) * sample_mean
 running_var = momentum * running_var + (1 - momentum) * sample_var
</code>
represents an alternative approach for test time that doesn't require the extra estimation step needed in the paper. For the alternative moving average we just update the mean and variance using exponential decay model based on the momentum parameter.


Is there a way to have 2 Factor Authentication on a specific application running on windows?

Question: I am trying to set up a 2FA system for a third party application. When a user clicks on this application's icon and it starts, it will ask for a PIN, which the user will have to input before being allowed to start the application. I've attached a workflow chart to illustrate.
I'm wondering if there's a way to to do this with any existing 2FA solutions (Authy/WinAuth etc.). If not, what is the best approach to creating an application like this?
Answer: Strictly speaking, it is not 2FA as it will only ask for one factor.
In general, if the app itself does not have it, then it will not be possible the way your workflow illustrates. What can be done is the following: you host the app on a different machine, and access to that machine is secured with 2FA (not only the PIN/OTP but also a username+password pair). Citrix XenApp or similar platform can do that.


How to find most popular genre of music?

Question: So I have two tables, table 1:Music Styles being with fields with StyleID and StyleName, with StyleName being a genre and table 2:entertainers with fields SyleID and EntertainerID.
I need help finding is:
1)  What's the most popular genre of music style in the database of entertainers?
This is what i have so far:
 SELECT StyleID, StyleName
   from EA_Music_Styles
  WHERE StyleID = (SELECT StyleID
                     from EA_Entertainer_Styles
                    WHERE StyleID = (SELECT MAX(StyleID)
                                       FROM EA_Entertainer_Styles));

But i got an error code of "Subquery returns more than 1 row"
I need help, don't know exactly what to do? First time beginner.
Here are the tables:
Table 1:
StyleID    StyleN
1         40's Ballroom Music
2         50's Music
3         60's Music
4         70's Music
5         80's Music
6         Country
7         Classical
8         Classic Rock & Roll
9         Rap
10        Contemporary
11        Country Rock
12        Elvis
13        Folk
14        Chamber Music
15        Jazz
16        Karaoke
17        Motown
18        Modern Rock
19        Rhythm and Blues
20        Show Tunes
21        Standards
22        Top 40 Hits
23        Variety
24        Salsa
25        90's Music
Table 2:
StyleID  EntertainerID
3        1003
3        1008
4        1010
6        1007
6        1008
7        1009
7        1011
7        1012
8        1003
10       1001
10       1013
11       1007
13       1004
13       1012
14       1009
14       1011
15       1005
15       1013
17       1002
19       1002
19       1005
20       1001
20       1011
21       1001
21       1009
21       1010
22       1006
22       1010
23       1002
23       1006
24       1005
24       1006
SO the result would output the two StyleID's, 7 & 21 and StyleName which would be Classical & Standards
Comment: also do remember that the MAX gives the maximum value not the most occurring value. To get the most used value you have to group by and count.
Answer: You just need to join your two tables and get the max count for entertainers
 SELECT ms.StyleName, count(*) most_popular
   from EA_Music_Styles ms
         INNER JOIN A_Entertainer_Styles es
         ON ms.StyleID = es.StyleID
  group by ms.StyleName
  order by 2 desc
  limit 1

This will give you the most popular (I take that it is the one that has more rows) StyleName. I count the ocurrences of StyleName and order it desc getting only the first result of this.
Answer: Here is how you can solve the problem.

In your entertainers table user group by StyleID while also selecting the count. This will give you the styleID count which you can sort by descending and limit 1 to find to most popular one
select StyleID, count(StyleID) c from EA_Entertainer_Styles
group by StyleID
order by c desc
limit 1;

Now use the styleID form the first step to get the StyleName from your table Music.
select StyleName from EA_Music_Styles
where StyleID = id_from_step1

You can use this two in a single query by joining them as in the answer shown by Jorge Campos
Answer: Max gives you the highest number in the database, not the most used. You should use count for that.
Next example should give correct result.
select StyleName from EA_Music_Styles
where StyleID = (
     select StyleID
     from EA_Entertainer_Styles
     group by StyleID
     order by count(StyleID) desc
     limit 1)

Comment: But this only shows 1 StyleName, there should be 2, if i change the limit it shows an error
Comment: you can't change the limit since you use "StyleID = (select...".
To keep this, you can only have one result in the second select statement.

To get all values that might be equal. You should fist get the most used StyleID's and then their names, one minute please
Comment: select StyleName from EA_Music_Styles
where StyleID in (
select b.StyleID
from EA_Entertainer_Styles b
group by b.StyleID
having count(b.StyleID) =(select count(a.StyleID)
                        from EA_Entertainer_Styles a
                        group by a.StyleID
                        order by a.StyleID
                        limit 1)
)


python regular expression to match anything not containing some word, in between 2 characters

Question: In Fortran, a data statement begins with the word "data", followed by the name of the array, then followed by the values of the array, sandwiched between two forward slashes "/".
pattern_data = r'''
( data [^/]+ / [^/]+ / )
'''

c = "data plevel = /4.56, 234., 1e-45/ data tlayer / -5.6, +290.098/"

In the above, c is like a sample Fortran code containing 2 data statements which I want to extract.  pattern_data is the regular expression that matches any sub-string that starts with "data", followed any character other than "/", followed by "/", followed by anything other than "/", followed by "/".
This seems to work, giving:
regex = re.compile(pattern_data, re.VERBOSE)

regex.findall(c)
['data plevel = /4.56, 234., 1e-45/', 'data tlayer / -5.6, +290.098/']

But what if I wanted to say instead: "data", followed by anything other than "/", followed by "/", followed by anything other than "data", followed by "/".  I think this would also match a data statement, but what is the regular expression for 'anything other than "data"'?
I have tried using a negative lookbehind like this:
data [^/]+ / (?<! data).* /

But this matches the entire string c.
Answer: Your attempt would prohibit data being immediately before the first slash, which is not what you want. This tests whether data is anywhere between the slashes:
( data [^/]+ /  (?! [^/]* data )  [^/]+ / )

Comment: Is it not possible to not have "[^/]" between the two "/"s?
Comment: The lookahead needs to be bounded as well. With `/ (?! .*? data) .*? /`, you would disqualify `/1, 2, 3/ data` (because lookahead will not stop where the match stops).


Rodapé do datatable não é exibido

Question: Seguindo a documentação do datatable: https://datatables.net/examples/advanced_init/footer_callback.html, mesmo assim não é exibido nada no rodapé da minha tabela, já chequei meu código umas 20 vezes e não consigo achar onde estou errando. Segue meu jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>

<!DOCTYPE html>

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">

<title>BI Lider</title>

<link href="<c:url value="/startbootstrap-sb-admin-2-1.0.5/bower_components/bootstrap/dist/css/bootstrap.min.css" />" rel="stylesheet">

<link href="<c:url value="/startbootstrap-sb-admin-2-1.0.5/bower_components/metisMenu/dist/metisMenu.min.css" />" rel="stylesheet">

<link href="<c:url value="/startbootstrap-sb-admin-2-1.0.5/bower_components/datatables-plugins/integration/bootstrap/3/dataTables.bootstrap.css" />" rel="stylesheet">

<link href="<c:url value="/startbootstrap-sb-admin-2-1.0.5/bower_components/datatables-responsive/css/dataTables.responsive.css" />" rel="stylesheet">

<link href="<c:url value="/startbootstrap-sb-admin-2-1.0.5/dist/css/sb-admin-2.css" />" rel="stylesheet">

<link href="<c:url value="/startbootstrap-sb-admin-2-1.0.5/bower_components/font-awesome/css/font-awesome.min.css" />" rel="stylesheet" type="text/css">

            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                Toggle navigation

            </button>
            BI Lider

 Meus Dados

 Configurações

 Sair

                            <input type="text" class="form-control" placeholder="Busca...">

                            <button class="btn btn-default" type="button">

                            </button>

                         Vendas

                                Por Supervisor

                                        tabelas

Acompanhamento por Supervisor

                        Aguinaldo

                                        Código
                                        Nome RCA
                                        Meta
                                        Venda
                                        Perc

                                    <c:set var="perc" value="${0}" />
                                    <c:forEach var="rca" items="${listaTeste }">

                                            ${rca.codusur }
                                            ${rca.nome }
                                            <fmt:formatNumber value="${rca.meta }" pattern="0.00" />
                                            <fmt:formatNumber value="${rca.venda}" pattern="0.00" />
                                            ${rca.perc1}

                                    </c:forEach>

Comment: Olhando na documentação a única diferença mesmo é na declaração da variavel api que esta diferente, mas não sei se realmente seja isso. No seu esta `var api = this.api();` e na documentação `var api = this.api(), data;` e isso supondo que esteja rodando o datatable e só o rodapé que não.
Comment: Oi Marcelo, então, incluindo ou não o data no código, não são mostradas as informações no rodapé.
Answer: Simplesmente inclua o footer no seu html:

                Total:

Comment: exemplo no link:
https://datatables.net/examples/advanced_init/footer_callback.html

Rodapé do datatable não é exibido


Poisson test - multiple replicates against null (in R)

Question: I feel like this should be a pretty basic question, but I can't find a clear answer.
I have multiple independent replicates of the same thing. Lets say I went and counted cars along a road between 8am and 9am, every Monday for a month. The assumption is those counts are all sampled from the same distribution. I counted 9, 10,  8, and  9 cars.
Let's further say the City Traffic Department publishes their modeled traffic rates. They think the road should have 10 cars per hour.
How do I test whether or not my counted observations match that prediction?
For any one count (e.g. a count of 9), it's trivial using R:
poisson.test(x = 9, T = 1, r = 10)
But how do I use the repeated counts?
I did think I could take the average of the four counts. As this is a Poisson distribution, it is fully described by the mean alone. In this case the mean is 9, so the result would be the same as above.
But it seems wrong that repeating counts and increasing my sample size has no impact at all on the conclusion. Let's say the true mean is 5 cars per hour - I could count every morning all year, reach a mean of 5, and still the simple poisson test would conclude there is not enough evidence to reject the null hypothesis that the mean is 10. Surely increasing my sample size increases power?
Answer: You would pass in the sum of your observations, and set the T parameter in poisson.test to the number of days you have taken samples:
#pretend these are your data points
x <- 8:16
poisson.test(sum(x),T=length(x),r=10)

# >         Exact Poisson test
# >
# > data:  sum(x) time base: length(x)
# > number of events = 108, time base = 9, p-value = 0.0647
# > alternative hypothesis: true event rate is not equal to 10
# > 95 percent confidence interval:
# >   9.843833 14.488079
# > sample estimates:
# > event rate
# >         12

Upping the T parameter reduces the variance of the overall estimate. See for example if we take the mean rate instead (and pass T=1):
poisson.test(mean(x),T=1,r=10)

# >         Exact Poisson test
# >
# > data:  mean(x) time base: 1
# > number of events = 12, time base = 1, p-value = 0.5234
# > alternative hypothesis: true event rate is not equal to 10
# > 95 percent confidence interval:
# >   6.200575 20.961585
# > sample estimates:
# > event rate
# >         12

So repeating the counts you gain precision in your estimate.

Since you can see that this only works with the overall sum of the observations, you will also likely want to check and see that the individual observations approximately look like a Poisson distribution as well (e.g. if everyday is exactly 10, then it is not Poisson).
I have a package I am working on, ptools, where you can see the Poisson fit to data using the check_pois function.


Jquery Ui slider min and max value range with if/elseif statement

Question: I'm attempting to make a simple payday loan calculator using jquery range slides. I have min: $500 and max: $5000 how can I display a statement when a user exceeds $2000 then I display "Only available on repeat customers"
So basically:
A. If loan amount <=2000, No warning message
B. If loan amount between >2000 and <=5000 and period is 3 or 5 months,then display warning message in RED as
i. This loan amount is available to repeat customers only
ii. This period(term) is available to repeat customers only.

$( document ).ready(function() {
function update() {
     $interest = 0.3 ;
     $perday = 15 ;
     $amount1 = $("#amount").val();
     $dayscount = $("#days").val();
     $amount2 = parseInt($amount1) + $interest * parseInt($amount1) + (parseInt($dayscount) * ($perday/100));
     $apr = (($amount2-$amount1 / $amount1 ) / ((parseInt($dayscount)/365) * 10000))  ;
     $("#amount2").val($amount2);
     $("#amount3").val(parseFloat($amount2-$amount1).toFixed(2));
     $("#amount4").val($apr);
}

debugger;

$("#slider1").slider({
    max:5000,
    min:500,
    step:10,
    slide: function(event, ui) {

        $("#amount").val(ui.value);
                update();

    },
        change: function (event, ui) {
            if (ui.value == 2) {
                $("#mindiv").show();
            } else {
                $("#mindiv").hide();
            }
        }
});

function addDaysToDate(days) {
  var mths = new Array("Jan", "Feb", "Mar",
    "Apr", "May", "Jun", "Jul", "Aug", "Sep",
    "Oct", "Nov", "Dec");

  var d = new Date();
  d.setHours(d.getHours() + (24 * days));

  var currD = d.getDate();
  var currM = d.getMonth();
  var currY = d.getFullYear();

  return mths[currM] + " " + currD + ", " + currY;
}

$("#slider2").slider({
    max:30,
    min:1,

    slide: function(event, ui) {

        $("#days").val(ui.value);
        $("#date").text(addDaysToDate(parseInt($("#days").val())));
                update();
    },
    create: function(event, ui) {
      $("#date").text(addDaysToDate(parseInt($("#days").val())));
    }
});

$("#days").val($("#slider2").slider("value"));

$("#days").change(function(event) {
  var data = $("#days").val();
  if (data.length > 0)
  {
     if (parseInt(data) >= 0 && parseInt(data) <= 31)
    {
        $("#slider2").slider("option", "value", data);
     }
     else
     {
        if (parseInt(data) < 1)
       {
           $("#days").val("1");
           $("#slider2").slider("option", "value", "1");
       }
       if (parseInt(data) > 31)
        {
            $("#days").val("31");
            $("#slider2").slider("option", "value", "31");
        }
     }
  }
  else
  {
    $("#slider2").slider("option", "value", "1");
  }
  $("#date").text(addDaysToDate(parseInt($("#days").val())));
});

update();
});
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Loan Calculator with  two jquery  slider inputs </title>

  <link rel='stylesheet prefetch' href='https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.0/themes/smoothness/jquery-ui.css'>
<link rel='stylesheet prefetch' href='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css'>

      <link rel="stylesheet" href="css/style.css">

  Loan Amount

Your Loan <input type="text" id="amount" value="500"/>

hhhh
asds

Loan Length

Days Loaned <input type="text" id="days" value="1"/>

Repayment Date

Your Loan
<input id="amount2" type="text" />
Interest
<input id="amount3" type="text" />

APR
<input id="amount4" type="text" />

Comment: Welcome to Stack Overflow. Just quickly, your `ui.value` will never equal `2`. Since the slider min is `500` and max of `5000`, the lowest value would only be 500 and that will always be greater than 2. The div would never be shown.
Answer: Consider the following example code.

$(function() {
  function update() {
    $interest = 0.3;
    $perday = 15;

    $amount1 = parseInt($("#amount").val());
    $dayscount = parseInt($("#days").val());
    $amount2 = $amount1 + $interest * $amount1 + ($dayscount * ($perday / 100));
    $apr = (($amount2 - $amount1 / $amount1) / (($dayscount / 365) * 10000));
    $("#amount2").val($amount2);
    $("#amount3").val(parseFloat($amount2 - $amount1).toFixed(2));
    $("#amount4").val($apr);
    return [$amount1, $dayscount, $amount2, parseFloat($amount2 - $amount1).toFixed(2), $apr];
  }

  function addDaysToDate(days) {
    var d = new Date();
    d.setHours(d.getHours() + (24 * days));

    var cStr = $.datepicker.formatDate("M d, yy", d);

    return cStr;
  }

  debugger;

  $("#slider1").slider({
    max: 5000,
    min: 500,
    step: 10,
    slide: function(event, ui) {
      $("#amount").val(ui.value);
      console.log(update());
    },
    change: function(event, ui) {
      if (ui.value >= 2000) {
        $("#mindiv").show();
      } else {
        $("#mindiv").hide();
      }
    }
  });

  $("#slider2").slider({
    max: 30,
    min: 1,
    slide: function(event, ui) {
      $("#days").val(ui.value);
      $("#date").text(addDaysToDate(parseInt($("#days").val())));
      update();
    },
    create: function(event, ui) {
      $("#date").text(addDaysToDate(parseInt($("#days").val())));
    }
  });

  $("#days").val($("#slider2").slider("value"));

  $("#days").change(function(event) {
    var data = $("#days").val();
    if (data.length > 0) {
      if (parseInt(data) >= 0 && parseInt(data) <= 31) {
        $("#slider2").slider("option", "value", data);
      } else {
        if (parseInt(data) < 1) {
          $("#days").val("1");
          $("#slider2").slider("option", "value", "1");
        }
        if (parseInt(data) > 31) {
          $("#days").val("31");
          $("#slider2").slider("option", "value", "31");
        }
      }
    } else {
      $("#slider2").slider("option", "value", "1");
    }
    $("#date").text(addDaysToDate(parseInt($("#days").val())));
  });

  update();
});
<link rel='stylesheet prefetch' href='https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.0/themes/smoothness/jquery-ui.css'>
<link rel='stylesheet prefetch' href='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css'> Loan Amount

Your Loan <input type="text" id="amount" value="500" />

 hhhh

asds

Loan Length

Days Loaned <input type="text" id="days" value="1" />

 Repayment Date

 Your Loan
<input id="amount2" type="text" /> Interest
<input id="amount3" type="text" />
 APR
<input id="amount4" type="text" />

Sometimes it's better to put your functions first. Also it appears you were comparing against a value that would never be reached in Slider 1. I adjusted it and now when the amount is over 2000, the warning is shown. It will be shown after the slider is released. If you want to it appear during the slide action, move the actions to the slide callback.


How to restrict ckeditor to display full html alone?

Question: I am using ck editor and want to hide the filtered html and plain text.
And user should use only the full html format. They should not get the option to select filtered html and plain text.
Anyone guide me how to do this in ck editor?
Answer: You can install the Better Formats module to achieve this.
Better formats is a module to add more flexibility to Drupal's core input format system.

Features
8.x & 7.x (needs more testing for a stable release)

Set allowed text formats per field.
Set default order of text formats per field.
Hide format tips per role.
Hide more format tips link per role.
Hide format selection per role per entity.
Currently only works on Field API fields on fieldable entities implementing core - style text processing. The good thing is that is
  most things in core and contrib.

This will let you limit what format is available per field implementing formatted text, like a body field.
Despite what the warning says, I have used this extensively on many sites to do exactly what you asked about.


Commerce: retrieve coupon code used in order

Question: Using the Commerce Coupon module, how can I retrieve any coupon codes used in a particular order, given the order id? It seems that the coupons used are not actually stored in the database (as far as I can see).
Answer: If you're using 1.x version, an entity reference field is attached to the commerce order field upon installation (see function commerce_coupon_order_configuration()). This creates the field table commerce_coupon_order_reference.
To check coupons attached to an order, simply access the commerce_coupon_order_reference field, like:
if (!empty($order->commerce_coupon_order_reference)) {
  // Traverse the coupons referenced by this order.
  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
  foreach ($order_wrapper->commerce_coupon_order_reference as $coupon_wrapper) {
    dpm($coupon_wrapper->value());
  }
}


SQLiteException no such table, am I missing something?

Question: I have researched other instances of this error all morning but nothing i've tried so far has worked. It could be something obvious as I am quite new to this.
I am trying to return the results of the GET_ALL_INGREDIENTS query. Which I will then put into a 2d array, but you don't need to worry about that. My TABLE_RECIPES table works fine.
SQLiteException: no such table: TABLE_INGREDIENTS (code 1): , while compiling: SELECT INGR...etc....
Which occurs on the last line of this bit of code:
public String[][] getRecipeIngredients(int id) {

String GET_ALL_INGREDIENTS = "SELECT INGREDIENT_NAME, INGREDIENT_QUANTITY, INGREDIENT_UNIT " +
            "FROM TABLE_INGREDIENTS " +
            "INNER JOIN TABLE_RECIPE_INGREDIENTS ON TABLE_RECIPE_INGREDIENTS.INGREDIENT_ID=TABLE_INGREDIENTS.INGREDIENT_ID " +
            "WHERE RECIPE_INGREDIENTS.RECIPE_ID=" + id;

    db = new MyDBHandler(mContext);
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor c = db.rawQuery(GET_ALL_INGREDIENTS, null);

Table Creation:
final String CREATE_TABLE_RECIPES = "CREATE TABLE IF NOT EXISTS " +
        TABLE_RECIPES + "(" +
        RECIPE_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
        RECIPE_NAME + " TEXT, " +
        RECIPE_INSTRUCTIONS + " TEXT " +
        ")";

final String CREATE_TABLE_INGREDIENTS = "CREATE TABLE IF NOT EXISTS " +
        TABLE_INGREDIENTS + "(" +
        INGREDIENT_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
        INGREDIENT_NAME + " TEXT NOT NULL UNIQUE " +
        ")";

final String CREATE_TABLE_RECIPE_INGREDIENTS = "CREATE TABLE IF NOT EXISTS " +
        TABLE_RECIPE_INGREDIENTS + "(" +
        RECIPE_ID + " INTEGER NOT NULL, " +
        INGREDIENT_ID + " INTEGER NOT NULL, " +
        INGREDIENT_QUANTITY + " REAL, " +
        INGREDIENT_UNIT + " TEXT, " +
        "PRIMARY KEY (" + RECIPE_ID + "," + INGREDIENT_ID + "), " +
        "FOREIGN KEY (" + RECIPE_ID + ") REFERENCES " + TABLE_RECIPES + "(" + RECIPE_ID + "), " +
        "FOREIGN KEY (" + INGREDIENT_ID + ") REFERENCES " + TABLE_INGREDIENTS + "(" + INGREDIENT_ID + ")" +
        ")";

public void onCreate(SQLiteDatabase db) {

    db.execSQL(CREATE_TABLE_RECIPES);
    db.execSQL(CREATE_TABLE_INGREDIENTS);
    db.execSQL(CREATE_TABLE_RECIPE_INGREDIENTS);
}

Thank you for reading and I really appreciate any help i can get with this.
Answer: TABLE_INGREDIENTS is a variable. It's value is likely not "TABLE_INGREDIENTS" that is a string literal. So you might want to change
"FROM TABLE_INGREDIENTS " +

to
"FROM " + TABLE_INGREDIENTS +

(You have a number of other similar issues in your SQL too.)
Comment: Didn't look everywhere but that `GET_ALL_INGREDIENTS` SQL has it all over.
Comment: Sorry, I realised. I thought you meant outside of that SQL statement. Thanks again :)


Problema com slick carrousel e modal do bootstrap

Question: Olá, estou realizando um projeto para um cliente onde estou utilizando um modal do bootstrap e dentro desse modal tem um carrousel utilzando o slick carrousel, entretanto eu não ao certo o porque mas não está iniciando ao abrir o modal, tem clicar em algo para ele iniciar, alguém poderia me orientar em relação a isso?
P.S: Como são coisas pré prontas não consigo colocar o codigo aqui por que não sei ao certo em que ponto está com problema, mas eu estou um pouco desesperado pois preciso entregar esse projeto e nao consigo arrumar esse bug.
site slick-carrousel:http://kenwheeler.github.io/slick/
Answer: Vou tentar te ajudar mesmo sem ver seu codigo.
Se você estiver usando o modal do bootstrap ou dialog do jquery, vc tem um problema ao instanciar o slick, pois quando ele é instanciado antes do modal abrir, as referencias são diferentes e quando abre o modal, está tudo aparentemente errado, então vamos fazer um truque.
Depois que você chamar o metodo para abrir o modal, tente instanciar o slick ou dar um resize nele.
Exemplo
<code>$('.modal').on('shown.bs.modal', function (e) {
    $('.my-slider').slick("setPosition", 0);
});
</code>
ou
<code>$('.modal').on('shown.bs.modal', function (e) {
      $('.my-slider').resize();
});
</code>
Segue um exemplo funcionando.
http://jsfiddle.net/vanduzled/nv446jgm/2/
Tente isso, se não der certo, envie o código e analisaremos juntos.


Executing bash script with PHP, and input commands

Question: I`m trying to execute a bash script using PHP, but the problem is that the script needs to have some commands and informations inputed during the execution process.
This is what I`m using
$old_path = getcwd();
chdir('/my/path/');
$output = shell_exec('./script.sh');
chdir($old_path);

The script execute OK, but I`m not able to input any option on the script.
Comment: Does the script accept arguments?
Comment: No, arguments are not accepted on the script, the script runs and ask for a input like, type the name, and for a lot of other inputs
Comment: Possible duplicate of [PHP, shell\_exec and an input](http://stackoverflow.com/questions/11737251/php-shell-exec-and-an-input)
Comment: It`s not the same, since the command is passed on the line, and in my problem the input can be diferent by the script requested, so the inputs cannot be passed before the execution, and during the execution.
Comment: Possible duplicate of [passing arguments to an interactive program non interactively](http://stackoverflow.com/questions/14392525/passing-arguments-to-an-interactive-program-non-interactively)
Answer: shell_exec() and exec() are not able to run interactive scripts. For that you need a real shell. Here is a project that gives you a real Bash Shell: https://github.com/merlinthemagic/MTS
//if the script requires root access, change the second argument to "true".
$shell    = \MTS\Factories::getDevices()->getLocalHost()->getShell('bash', false);

//What string do you expect to show in the terminal just before the first input? Lets say your script simply deletes a file (/tmp/aFile.txt) using "rm". In that case the example would look like this:

//this command will trigger your script and return once the shell displays "rm: remove regular file"

$shell->exeCmd("/my/path/script.sh", "rm: remove regular file");

//to delete we have to press "y", because the delete command returns to the shell prompt after pressing "y", there is no need for a delimiter.

$shell->exeCmd("y");

//done

I am sure the return of the script is far more complex, but the example above gives you a model for how to interact with the shell.
I would also mention that you might consider not using a bash script to perform a sequence of events, rather issue the commands one by one using the exeCmd() method. That way you can handle the return and keep all error logic in PHP rather than splitting it up between PHP and BASH.
Read the documentation, it will help you.
Answer: proc_open() makes this possible without any external libraries:
$process = proc_open(
    'bash foo.sh',
    array( STDIN, STDOUT, STDERR ),
    $pipes,
    '/absolute/path/to/script/folder/'
);

if ( is_resource( $process ) ) {
    fclose( $pipes[0] );
    fclose( $pipes[1] );
    fclose( $pipes[2] );
    proc_close( $process );
}


Python Pivot Table conditional count

Question: I am trying to generate a pivot table with following result
wondering how i calculate the # of win, lost, and draw....
essentially, I want to say count only if Result == 'Win'
I didn't want to use Result as a column because I don't want to have Speed breakdown by Win/Lost/Draw...is there a way to just count # of
Name    Result     Win   Loss   Draw   Speed
James    6         2      2      2       50
Bob      9         7      2      0       48
Mary     10        5      3      2       70

This is the code
report = pd.pivot_table(df,index=["Name"], values=["Result", "Speed"],  aggfunc= {"Result": len, "Speed": np.mean}, fill_value=0)

Thank you in advance
Comment: "Count the number of" what, exactly?
Comment: @jrd1 I am trying to count number of Win/Loss/Draw, in Result Column, it is a string of either Win/Loss/Draw....so when I do "len", i get number of Results....but I want to filter on number of Wins....so I guess len only if wins?
Comment: @jrd1 in other word, while Result: len gives me how many game each person plays, is there a way for me to count # of Wins....without have Result as a column
Comment: Is that table what your data looks like or is that the `report` variable?
Comment: @IanThompson report will be the output, and yes, the example table above is example output
Answer: Assuming your data looks something like this:
# sample data
df = pd.DataFrame({
    'Name' : ['James']*6 +\
             ['Bob']*9 +\
             ['Mary']*10,
    'Result' : ['Win']*2 + ['Loss']*2 + ['Draw']*2 +\
               ['Win']*7 + ['Loss']*2 +\
               ['Win']*5 + ['Loss']*3 + ['Draw']*2,
    'Speed' : [50]*6 +\
              [48]*9 +\
              [70]*10
})

Then just filter on 'Win' and pivot:
# Filter on 'Win'; make pivot table
df[df.Result == 'Win'].pivot_table(index = 'Name',
                                   values = ['Result', 'Speed'],
                                   aggfunc = {'Result' : 'count',
                                              'Speed' : 'mean'},
                                   fill_value = 0).rename(columns = {'Result' : 'Win'})

Or groupby and aggregate:
# groupby.agg()
df[df.Result == 'Win'].groupby('Name').agg({'Result' : 'count',
                                            'Speed' : 'mean'}).rename({'Result' : 'Win'})

Same results:

Python Pivot Table conditional count


Converting unit8list to video file with out creating it and its be on memory

Question: I have downloaded the bytes of a movie and stored them in a database.
I need a way to convert it back to a movie to give it to the video_player package to play.
How to convert it without creating a file?
I don't want my users to access the video files.
Comment: you could store it in a temporary directory, see https://docs.flutter.dev/cookbook/persistence/reading-writing-files for more info
Comment: my bro while its playing my user can com and copy it from folder and I dont want it ! the movie files are important !
Comment: I don't think that your user would be able to access that folder
Comment: Untill the user is not using a rooted device you can do it without any problem
Answer: Since there was no answer
I had found the way which is loading that bytes from db in to temp directory of mobile and then passing it to my player.
you could use this question.
answer


Evaluating the limit of a certain definite integral

Question:
Let $\displaystyle f(x)= \lim_{\epsilon \to 0} \frac{1}{\sqrt{\epsilon}}\int_0^x ze^{-(\epsilon)^{-1}\tan^2z}dz$ for $x\in[0,\infty)$.
Evaluate $f(x)$ in closed form for all $x\in[0,\infty)$ and sketch a graph of this function.

Hints, as well as solutions are welcome for this question :-)
Edit:  So far, I have, from substituting $\sqrt{\epsilon}u$ = z,
$\displaystyle f(x)= \lim_{\epsilon \to 0} \int_0^{\sqrt{\epsilon}u}  \sqrt{\epsilon}ue^{-(\epsilon)^{-1}\tan^2\sqrt{\epsilon}u}du$
But we can split the integral into two terms, with the first integral equal to zero, by dominated convergence theorem.  I think we only need to look at:
$\displaystyle f(x)= \lim_{\epsilon \to 0} \int_0^{a}  \sqrt{\epsilon}ue^{-(\epsilon)^{-1}\tan^2\sqrt{\epsilon}u}du$ +
$\displaystyle \lim_{\epsilon \to 0} \int_a^{\sqrt{\epsilon}u}  \sqrt{\epsilon}ue^{-(\epsilon)^{-1}\tan^2\sqrt{\epsilon}u}du$
= $$0+\displaystyle \lim_{\epsilon \to 0} \int_a^{\sqrt{\epsilon}u}  \sqrt{\epsilon}ue^{-(\epsilon)^{-1}\tan^2\sqrt{\epsilon}u}du$$
(I'm not sure if integrating away from the origin helps much, to be honest.)
Answer: Consider what happens on an interval $[n\pi-\frac\pi2,n\pi+\frac\pi2]$. Let $x=\tan(z)$ and $u=x/\sqrt{\epsilon}$, then
$$
\begin{align}
\lim_{\epsilon\to0}\frac1{\sqrt{\epsilon}}\int_{n\pi-\frac\pi2}^{n\pi+\frac\pi2}e^{-\tan^2(z)/\epsilon}\,\mathrm{d}z
&=\lim_{\epsilon\to0}\frac1{\sqrt{\epsilon}}\int_{-\infty}^\infty e^{-x^2/\epsilon}\frac{\mathrm{d}x}{1+x^2}\\
&=\lim_{\epsilon\to0}\int_{-\infty}^\infty e^{-u^2}\frac{\mathrm{d}u}{1+\epsilon u^2}\\
&=\int_{-\infty}^\infty e^{-u^2}\,\mathrm{d}u\\[6pt]
&=\sqrt\pi\tag{1}
\end{align}
$$
For all $\epsilon\gt0$, we have
$$
\frac1{\sqrt\epsilon}e^{-\tan^2(z)/\epsilon}\le\frac{|\cot(z)|}{\sqrt{2e}}\tag{2}
$$
Thus, for any $\lambda\gt0$, Dominated Convergence says
$$
\lim_{\epsilon\to0}\frac1{\sqrt{\epsilon}}\int_{n\pi-\frac\pi2}^{n\pi+\frac\pi2}\big[|z-n\pi|\ge\lambda\big]e^{-\tan^2(z)/\epsilon}\,\mathrm{d}z=0\tag{3}
$$
where $[\cdot]$ are Iverson Brackets. Combining $(1)$ and $(3)$ gives
$$
\lim_{\epsilon\to0}\frac1{\sqrt{\epsilon}}\int_{n\pi-\frac\pi2}^{n\pi+\frac\pi2}\big[|z-n\pi|\lt\lambda\big]e^{-\tan^2(z)/\epsilon}\,\mathrm{d}z=\sqrt\pi\tag{4}
$$
Limits $(3)$ and $(4)$ tell us that $\frac1{\sqrt\epsilon}e^{-\tan^2(z)/\epsilon}$ is an approximation of
$$
\sqrt\pi\sum_{n\in\mathbb{Z}}\delta(z-n\pi)\tag{5}
$$
where $\delta(z)$ is the Dirac delta function.
Thus,
$$
\bbox[5px,border:2px solid #C0A000]{\lim_{\epsilon\to0}\frac1{\sqrt{\epsilon}}\int_0^xz\,e^{-\tan^2(z)/\epsilon}\,\mathrm{d}z
=\left\{\begin{array}{}
\displaystyle\pi^{3/2}\,\frac{\lfloor x/\pi\rfloor^2+\lfloor x/\pi\rfloor}2&\text{if }x\not\in\pi\mathbb{Z}\\
\displaystyle\pi^{-1/2}\,\frac{x^2}2&\text{if }x\in\pi\mathbb{Z}
\end{array}\right.}\tag{6}
$$
The plot would look something like
Comment: @LebronJames: I am out getting dinner. I will address your questions as soon as I can.
Comment: @LebronJames: on $\big[-\frac\pi2,\frac\pi2\big]$, $\frac1{\sqrt\epsilon}e^{-\tan^2(x)/\epsilon}$ is a family of approximations to $\sqrt\pi$ times the Dirac delta function. Since $\tan^2(x)$ has a period of $\pi$, on $\mathbb{R}$, $\frac1{\sqrt\epsilon}e^{-\tan^2(x)/\epsilon}$ is an approximation to $\sqrt\pi$ times the sum of Dirac delta functions translated to $x=n\pi$. Thus, on an interval containing a neighborhood of $n\pi$, the integral of $\frac1{\sqrt\epsilon}f(x)e^{-\tan^2(x)/\epsilon}$ tends to $\sqrt\pi\,f(n\pi)$.
Comment: @LebronJames: on an interval ending at $n\pi$, the integral of $\frac1{\sqrt\epsilon}f(x)e^{-\tan^2(x)/\epsilon}$ tends to $\frac{\sqrt\pi}2\,f(n\pi)$. In the case at hand, $f(x)=x$.
Comment: @robjohn It doesn't change the thrust of your development, but the bound you want to establish dominated convergence is $$\frac{1}{\sqrt{\epsilon}}e^{-\tan^2x/\epsilon}\le \frac{1}{\sqrt{2e\tan^2x}}$$However, doesn't the DC theorem require the dominating function be integrable?  Neither $\cot^2x$ nor $|\cot x|$ are integrable on any interval containing a singularity.  So, does that not invalidate the reasoning here?
Comment: @Dr.MV: Oops... that is the bound, but that works as well. All we are trying to show with dominated convergence is $(3)$ and for that $|x|\ge\lambda$. Since $\frac1{\sqrt\epsilon}e^{-\tan^2(x)/\epsilon}\le\frac{\cot(\lambda)}{\sqrt{2e}}$, the integrands are bounded by $\frac{\cot(\lambda)}{\sqrt{2e}}$ on $|x|\ge\lambda$ and $|x|\lt\frac\pi2$ so the dominating function **is** integrable (bounded on a bounded set).
Comment: I don't want to nit pick, but you need an absolute value sign on the cotangent for the bound.
Comment: Indeed. Fixed in the answer.
Comment: @LebronJames: between each pair of consecutive integers, the limit is constant. At each integer, the limit is exactly half way between the values in the neighboring intervals. So the graph is horizontal lines between the integers and points half way between at the integers.
Comment: Mathematica concurs using `f[x_,e_]:=1/Sqrt[e]NIntegrate[z Exp[-Tan[z]^2/e],{z,0,x},WorkingPrecision->20]`
Comment: @Dr.MV: The proof above shows that on $[n\pi-\frac\pi2,n\pi+\frac\pi2]$, $$\lim_{\epsilon\to0}\frac1{\sqrt\epsilon} e^{-\tan^2(z)/\epsilon} =\sqrt\pi\delta(z-n\pi)$$ so that on the whole real line $$\lim_{\epsilon\to0}\frac1{\sqrt\epsilon} e^{-\tan^2(z)/\epsilon} =\sqrt\pi \sum_{n\in\mathbb{Z}}\delta(z-n\pi)$$ which is given in line $(5)$. Thus, integrating against $z$ we get the sum of $\sqrt\pi\,n\pi$ for each point $z=n\pi$ in the domain of integration. If the domain of integration ends at $n\pi$, then due to symmetry, we get half the value normally contributed at that point.
Comment: Hi @robjohn, I've been studying your solution all day today and finally have some meaningful questions to ask:  1)  we know the integrand goes to zero, if $tan^2$ is positive, since then the exponential factor of the integrand goes to zero exponentially fast - the 1/$\sqrt{\epsilon}$ does no harm.  But wherever $tan^2$ is equal to zero, then the integrand blows up - since there is only a z/$\epsilon$ term in the integrand.  But you showed that it is *at* the point of blow-ups of the integrand, namely when $sin^{2}$ is zero, which occurs at integer multiples of $\pi$,
Comment: that there is a nonzero contribution from the integration - $\sqrt{\pi}$
Comment: do I have the right idea?  so whichever x we are fixing as our upper limit, we are just counting the number of n$\pi$'s in our integration domain, and then multiplying $\sqrt{\pi}$ with consecutive integers (integration against z, as you called it), z = 1,2,3,...
Comment: and you showed that any z that is a positive distance away from n$\pi$ -- so, z not  of the form n$\pi$-- gives a zero integral, by dominated convergence theorem.
Comment: I don't understand the piecewise defined function -- is it just the consecutive integers formula?
Comment: So, I'm just trying to make sense of it all.  Thank you so much for posting this solution, @robjohn!! :-)
Comment: Ok, enjoy!! Very exciting solution.  I think I almost understand it all - you are indeed using the sum of consecutive integers formula, taking into account that x may not be an integer, so you're using the floor function to account for this case.  :-)
Comment: @robjohn How did you arrive at inequality $(2)$ for all positive $\epsilon$?  Take $\epsilon=4$ (yes, I know that we let $\epsilon \to 0$, but the bound states for all $\epsilon>0$), $z=\pi/3$ and we have $\frac{1}{\sqrt{\epsilon}}e^{-\tan^2z/\epsilon}=\frac12e^{-3/4}\approx. 0.236183$, while $\frac{1}{e\tan^z}=\frac{1}{3e}\approx. 0.122626$.  So, the inequality seems to fail.  Just curious ... how did you arrive at it?
Comment: Hi @robjohn, I just have one question remaining for this problem:  was the motivation to consider the interval you suggested coming from the fact that $tan^2$ is $\pi$ - periodic, so that perhaps ...if we knew the contribution of the integration over one period of the function, we pretty much know the integration over the whole real line?  (I think the exponential function, composed with $tan^2$, is still periodic with the same minimum period, $\pi$.)  Thanks,
Comment: @Dr.MV: Note that $\frac{\mathrm{d}}{\mathrm{d}\alpha}\alpha e^{-\alpha \tan^2(x)}=e^{-\alpha\tan^2(x)}(1-\alpha\tan^2(x))$. Thus, the maximum occurs when $\alpha=\frac1{\tan^2(x)}$; that is, when $\alpha e^{-\alpha\tan^2(x)}=\frac1{e\tan^2(x)}$.
Comment: But that isn't the right-hand side.  It is $\sqrt{\alpha}e^{-\alpha \tan^2(x)}$.  So, it appears that this is the source of error.
Comment: What would a sketch of the graph look like?  I have a set of dots that are monotone increasing.  In between these dots, I have a line going through the real axis (to show zero contribution away from n$\pi$...and then near n$\pi$ I connect the line on the real axis with the dot - to show a sharp spike upwards, and then sharply downwards back to the real axis (f(x) = 0).  Then repeat for the other (higher) dots (point masses).  So, this sketch would also be in line with what you described, @robjohn - I am just essentially sketching out a *family* of Dirac delta functions on $[0,\infty)$
Comment: Ok, got it.  Thanks so much @robjohn :-)
Answer: NOTE:
I wanted to give a special thanks to @robjon for his insightful comments.

We first observe that $\lim_{\epsilon\to 0}e^{-\tan z/\epsilon}=0$ unless $z=\ell \pi$, $\ell$ an integer.  Therefore, all of the "action" of the integration will take place over intervals around $\ell \pi$.  So, let's first see what is happening for $0<x<\pi/2$.

In the spirit of Laplace's Method, we have for $0<z<\pi/2$, $\tan^z =z^2+O(z^4)$ and thus for $0<x<\pi/2$
$$\begin{align}
\epsilon^{-1/2}\int_0^xze^{-\tan^2z/\epsilon}dz&\sim\epsilon^{-1/2}\int_0^xze^{-z^2/\epsilon}dz\\\\
&=\epsilon^{-1/2}\left.\left(-\epsilon^{-z^2/\epsilon}\right)\right|_{z=0}^{z=x}\\\\
&=\epsilon^{1/2}\left(1-e^{-x^2/\epsilon}\right)
\end{align}$$
which clearly goes to zero as $\epsilon\to 0$.

Next, we observe that the integration around singularities of the tangent function pose no challenge.  Thus, for a general $(L-1)\pi<x<L\pi$, and $\delta >0$ we can write
$$\begin{align}
\epsilon^{-1/2}\int_0^x ze^{-\tan^2z/\epsilon}dz&=\epsilon^{-1/2}\sum_{\ell=0}^{L-2}\left(\int_{\ell \pi+\delta}^{(\ell+1)\pi-\delta}ze^{-\tan^2z/\epsilon}dz+\int_{(\ell+1)\pi-\delta}^{(\ell+1)\pi+\delta}ze^{-\tan^2z/\epsilon}dz\right)\\\\
&+\epsilon^{-1/2}\int_{(L-1)\pi+\delta}^{x}ze^{-\tan^2z/\epsilon}dz \tag 1\\\\
\end{align}$$
We observe that in $(1)$ the only integrals that will contribute in the limit as $\epsilon \to 0$ are those around integer multiples of $\pi$.  Thus, we have for $(L-1)\pi<x<L\pi$ and $\delta>0$
$$\begin{align}
\lim_{\epsilon \to 0}\epsilon^{-1/2}\int_0^x ze^{-\tan^2z/\epsilon}dz&=\lim_{\epsilon \to 0} \epsilon^{-1/2}\sum_{\ell=0}^{L-2}\left(\int_{(\ell+1)\pi-\delta}^{(\ell+1)\pi+\delta}ze^{-\tan^2z/\epsilon}dz\right) \tag 2\\\\
\end{align}$$
We proceed to evaluate the integrals in $(2)$.  To that end we have
$$\begin{align}
\epsilon^{-1/2}\int_{(\ell+1)\pi-\delta}^{(\ell+1)\pi+\delta}ze^{-\tan^2z/\epsilon}dz &=\epsilon^{-1/2}\left(\int_{-\delta}^{\delta}ze^{-\tan^2z/\epsilon}dz+(\ell +1)\pi\int_{-\delta}^{\delta}e^{-\tan^2z/\epsilon}dz\right)\\\\
&=(\ell +1)\pi\epsilon^{-1/2}\int_{-\delta}^{\delta}e^{-\tan^2z/\epsilon}dz\\\\
&\sim (\ell +1)\pi\epsilon^{-1/2}\int_{-\delta}^{\delta}e^{-z^2/\epsilon}dz\\\\
&= (\ell +1)\pi\int_{-\delta/\epsilon^{1/2}}^{\delta/\epsilon^{1/2}}e^{-z^2}dz\\\\
&\to (\ell +1)\pi^{3/2}
\end{align}$$
Summing over $\ell$ we find for $(L-1)\pi<x<L\pi$
$$\lim_{\epsilon \to 0}\epsilon^{-1/2}\int_0^xze^{-\tan^2z/\epsilon}dz=\frac{L(L-1)\pi^{3/2}}{2}$$
One final note concerns the case in which $x=L\pi$.  For that case, we see that we need to add one more integral, namely
$$\begin{align}
\lim_{\epsilon\to 0}\epsilon^{-1/2}\int_{L\pi-\delta}^{L\pi}ze^{-\tan^z/\epsilon}&=L\pi\int_{-\infty}^0e^{-z^2}dz\\\\
&=\frac12 L\pi^{3/2}
\end{align}$$
Thus, for $x=L\pi$ we have
$$\lim_{\epsilon \to 0}\epsilon^{-1/2}\int_0^xze^{-\tan^2z/\epsilon}dz=\frac{L^2\pi^{3/2}}{2}$$
Putting it all together we have
$$\lim_{\epsilon \to 0}\epsilon^{-1/2}\int_0^xze^{-\tan^2z/\epsilon}dz=
\begin{cases}
\frac{L(L-1)\pi^{3/2}}{2},&(L-1)\pi<x<L\pi\\\\
\frac{L^2\pi^{3/2}}{2},&x=L\pi
\end{cases}
$$
Comment: This only works for $x\lt\pi$. The interesting part comes when $x\ge\pi$.
Comment: The part of your answer where you get $2z^2+O(z^6)$ is garbled. Are you claiming that $\tan^2(z)=2z^2+O(z^6)$? If so, that seems to be problematic as $\tan^2(z)=z^2+O(z^4)$.
Comment: You note that $\lim\limits_{\epsilon\to0} e^{-\tan^2(x)/\epsilon}=0$. However, what is needed is $\lim\limits_{\epsilon\to0} \frac1{\sqrt\epsilon}e^{-\tan^2(x)/\epsilon}=0$ for $x\ne0$, and that $\frac1{\sqrt\epsilon}e^{-\tan^2(x)/\epsilon}$ is uniformly bounded in $\epsilon$ for $x$ away from $0$ (the last is so that we can use Dominated Convergence).
Comment: @robjon I did note that and for purpose of gaining an understanding of where the "action" is in the integral.  I don't see that this note is inappropriate.
Comment: @LebronJames You're quite welcome.  And special thanks goes to Robjon for showing the way forward!
Comment: Really cool solution, @Dr.MV.  Can I ask a follow-up question?  How'd you get the -2z^2?
Comment: Such a cool solution, @Dr.Mv.  I was convinced that the answer couldn't possibly be zero, since that'd be trivial.  I'm going to sleep and re-do this problem in the morning.  Thanks so much!!  Have a great night :-)
Comment: Hi @Dr.MV, actually, do we have to worry about the blow-ups from the tan function? +infinity is fine, but if it's -infinity, we get $e^{\infty}$ .  Or is tan^2 always non-negative?
Comment: Yes, it's non-negative - the integrand doesn't blow up.  Sorry, I'm just in a state of shock that the answer is equal to zero, I guess.
Comment: Ok, got it - I will redo this problem along with the version with $\epsilon^{-1}$ to see what I integrate and come up with.  Thanks, @Dr.MV!  Good night!
Comment: In the final answer, you need to have $(L-1)\pi\le x\lt L\pi$; otherwise, there may be multiple choices for $L$ given a particular $x$.
Comment: @robjohn Yes, of course. I'll edit again.
Comment: Hi @Dr.MV, thanks so much for this!!  I think I finally understand this problem now :-)
Answer: For small $\epsilon$,
$\tan^2(\sqrt{\epsilon} u )
\approx \epsilon u^2$,
so the integral is of
approximately
$\sqrt{\epsilon}u e^{-u^2}$
which can be integrated.
Comment: Thanks for the cool observation, @martycohen! :-)


Passar Função javaScript por ajax

Question: Estou tentando retornar um alert do servidor, mas não estou conseguindo.
a ideia seria a seguinte
index.jsp

<title>Teste</title>
    <link rel="stylesheet" type="text/css" href="../estilos/estilo.css" />

  nome:<input type="text" maxlength="30" Id="nome" name="nome"></input>
  data:<input type="text" maxlength="10" Id="data" name="data"></input>
  <input type=button  tabindex="8" class="botao" onclick="manda('inclui',1);" value="Adicionar">

ajax.js
function openAjaxd2() {
  var ajax;
  try{
      ajax = new XMLHttpRequest(); // XMLHttpRequest para browsers decentes, como: Firefox, Safari, dentre outros.
  }catch(ee){
      try{
          ajax = new ActiveXObject("Msxml2.XMLHTTP"); // Para o IE da MS
      }catch(e){
          try{
              ajax = new ActiveXObject("Microsoft.XMLHTTP"); // Para o IE da MS
          }catch(E){
              ajax = false;
          }
      }
  }
  return ajax;
}

function manda(sinal,indice) {

  var resultado = document.getElementById('resultado');
  var ajax = openAjaxd2(); // Inicia o Ajax.

  var url = "teste2.jsp";
  var parametros = "sinal=" + sinal;
  ajax.open("POST", url, true);
  ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  if (sinal == "inclui")
  {
    parametros += "&nome=" + encodeURIComponent(document.getElementById('nome').value);
    parametros += "&data=" + encodeURIComponent(document.getElementById('data').value);
  } else if (sinal == "exclui")
  {
    parametros += "&indice=" + indice;
  }
  ajax.onreadystatechange = function () {
      if (ajax.readyState == 1){
          resultado.innerHTML = "Carregando...";
      }
      if (ajax.readyState == 4) {  // Quando estiver tudo pronto.
          if (ajax.status == 200) {
              var a = ajax.responseText;
              if (a.indexOf('Erro:') > 0) {
                  alert(a.substring(a.indexOf('Erro:') + 5, a.indexOf('Fim')));
                  a = a.substring(0, a.indexOf('Erro:')) + a.substring(a.indexOf('Fim') + 3, a.length);
              }
              resultado.innerHTML = a;
          } else{
              resultado.innerHTML = "Erro: " + ajax.statusText + " " + ajax.responseText;
          }
      }
  }
  ajax.send(parametros); // submete

}

teste2.jsp
<%@page import="Base.Utils"%>
<%@page import="java.util.List"%>
<%@page import="java.util.Date"%>
<%

 String sinal = request.getParameter("sinal");
 String linha;
 String str[];
 Date data;
 String nome;
 SimpleDateFormat sdf;
 {
 //***... trecho de código irrelevante... ***//
 }
 try{
    data =sdf.parse(request.getParameter("data"));
 }catch (Exception e){
   out.println("

");
 }
 {
 //***... mais um trecho de código irrelevante que inclui os nomes em uma List e monta uma
 com os valores... ***//
 }

%>

eu precisava que este script fosse executado, quando carrego direto a pagina teste2.jsp  ele da o alert, mas quando chamo por ajax não(ele aparece nos fontes html, junto da tabela que é gerada no teste2.jsp
Answer: Para resolver o problema tive que alterar os seguintes
teste2.jsp
<%@page import="Base.Utils"%>
<%@page import="java.util.List"%>
<%@page import="java.util.Date"%>
<%

 String sinal = request.getParameter("sinal");
 String linha;
 String str[];
 Date data;
 String nome;
 SimpleDateFormat sdf;
 {
     //***... trecho de código irrelevante... ***//
 }
 try{
        data =sdf.parse(request.getParameter("data"));
 }catch (Exception e){
   out.println("<input type=hidden id=\"erros\" name=\"erros\" value=\"data invalida\" />");
 }
 {
 //***... mais um trecho de código irrelevante que inclui os nomes em uma List e monta uma
 com os valores... ***//
 }

%>

ajax.js
function openAjaxd2() {
  var ajax;
  try{
      ajax = new XMLHttpRequest(); // XMLHttpRequest para browsers decentes, como: Firefox, Safari, dentre outros.
  }catch(ee){
      try{
          ajax = new ActiveXObject("Msxml2.XMLHTTP"); // Para o IE da MS
      }catch(e){
          try{
              ajax = new ActiveXObject("Microsoft.XMLHTTP"); // Para o IE da MS
          }catch(E){
              ajax = false;
          }
      }
  }
  return ajax;
}

function manda(sinal,indice) {

  var resultado = document.getElementById('resultado');
  var ajax = openAjaxd2(); // Inicia o Ajax.

  var url = "teste2.jsp";
  var parametros = "sinal=" + sinal;
  ajax.open("POST", url, true);
  ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  if (sinal == "inclui")
  {
    parametros += "&nome=" + encodeURIComponent(document.getElementById('nome').value);
    parametros += "&data=" + encodeURIComponent(document.getElementById('data').value);
  } else if (sinal == "exclui")
  {
    parametros += "&indice=" + indice;
  }
  ajax.onreadystatechange = function () {
      if (ajax.readyState == 1){
          resultado.innerHTML = "Carregando...";
      }
      if (ajax.readyState == 4) {  // Quando estiver tudo pronto.
          if (ajax.status == 200) {
              var a = ajax.responseText;
              resultado.innerHTML = a;
              var erros = document.getElementById('erros');
                if (erros===null) {
                    alert(erros.value);
                }
          } else{
              resultado.innerHTML = "Erro: " + ajax.statusText + " " + ajax.responseText;
          }
      }
  }
  ajax.send(parametros); // submete

}

Passar Função javaScript por ajax


R Stan: Rejecting initial value error only with real data, not with simulated data

Question: I am trying to fit a non-linear function to a dataset using Stan and R. I tested my model with a simulated dataset. It works nicely. However, as soon as I use real data that is formatted exactly the same as the simulated data, I get the error:

Rejecting initial value. Gradient evaluated at the initial value is not finite.

How can this be?
This is my stan file:
data {
  int<lower=0> N;
  real<lower=0, upper=1> p1[N];
  real<lower=0, upper=1> p2[N];
  real W1[N];
  real W2[N];
  real U[N];
}

parameters {
  real<lower=0, upper=1> r;
  real<lower=0> s;
  real<lower=0> tau;
}

transformed parameters {
  real pred[N];

  for (i in 1:N) {
    pred[i] = exp(-s*(-log(p1[i]))^r) * W1[i] + exp(-s*(-log(p2[i]))^r) * W2[i];
  }
}

model {
  // priors
  r ~ gamma(1, 1);
  s ~ gamma(1, 1);
  tau ~ gamma(1, 1);

  // model
  U ~ normal(pred, tau);
}

This is the relevant R code:
df = data.frame(p1 = as.vector(df$p1),
            p2 = as.vector(df$p2),
                W1 = rep(-5, nrow(df)),
                W2 = rep(-1, nrow(df)),
                U = as.vector(df$U))

#----RStan----
stan.data = c(as.list(df), N = nrow(df))

fit = stan("kortenkamp.stan",
           data=stan.data)

These are summaries of the simulated and the real dataset:
Simulated:
id            case           p1                p2               W1           W2           r                 s              error
 Min.   : 1.0   Min.   :1.0   Min.   :0.00329   Min.   :0.6037   Min.   :-1   Min.   :-5   Min.   :0.08291   Min.   :0.4841   Min.   :0.2602
 1st Qu.:13.0   1st Qu.:1.0   1st Qu.:0.06381   1st Qu.:0.6536   1st Qu.:-1   1st Qu.:-5   1st Qu.:0.08961   1st Qu.:0.6450   1st Qu.:0.4497
 Median :25.5   Median :1.5   Median :0.10819   Median :0.7011   Median :-1   Median :-5   Median :0.09930   Median :0.7253   Median :0.5179
 Mean   :25.5   Mean   :1.5   Mean   :0.10703   Mean   :0.6980   Mean   :-1   Mean   :-5   Mean   :0.10021   Mean   :0.7198   Mean   :0.5094
 3rd Qu.:38.0   3rd Qu.:2.0   3rd Qu.:0.15757   3rd Qu.:0.7460   3rd Qu.:-1   3rd Qu.:-5   3rd Qu.:0.10913   3rd Qu.:0.7849   3rd Qu.:0.5626
 Max.   :50.0   Max.   :2.0   Max.   :0.19998   Max.   :0.7998   Max.   :-1   Max.   :-5   Max.   :0.12677   Max.   :0.9536   Max.   :0.8519
         U
 Min.   :-4.757
 1st Qu.:-3.540
 Median :-3.126
 Mean   :-3.070
 3rd Qu.:-2.617
 Max.   :-1.223

Real:
       p1               p2               W1           W2           U
 Min.   :0.0000   Min.   :0.0000   Min.   :-5   Min.   :-1   Min.   :1.000
 1st Qu.:0.2150   1st Qu.:0.7300   1st Qu.:-5   1st Qu.:-1   1st Qu.:3.000
 Median :0.4000   Median :0.8550   Median :-5   Median :-1   Median :4.000
 Mean   :0.4222   Mean   :0.8133   Mean   :-5   Mean   :-1   Mean   :4.178
 3rd Qu.:0.6000   3rd Qu.:0.9500   3rd Qu.:-5   3rd Qu.:-1   3rd Qu.:6.000
 Max.   :1.0000   Max.   :1.0000   Max.   :-5   Max.   :-1   Max.   :9.000

The data is simulated like this:
pr = function(p, r, s){
  return(exp(-s*(-log(p))^r))
}

n = 100

df_sim = data.frame(id = rep(1:50, 2),
                case = c(rep(1, 50), rep(2, 50)),
                p1 = sample(seq(0, 0.2, 0.00001), n),
                p2 = sample(seq(0.6, 0.8, 0.00001), n),
                W1 = -1,
                W2 = -5,
                r = rep(rnorm(n/2, 0.1, 0.01), 2),
                s = rep(rnorm(n/2, 0.7, 0.1), 2),
                error = rnorm(n, 0.5, 0.1))

df_sim$U1 = df_sim$p1 * df_sim$W1
df_sim$U2 = df_sim$p2 * df_sim$W2

df_sim$Y = pr(df_sim$p1, df_sim$r, df_sim$s) * df_sim$W1 + pr(df_sim$p2, df_sim$r, df_sim$s) * df_sim$W2 + rnorm(n, 0, df_sim$error)

stan.data = list(
  N = nrow(df_sim),
  p1 = df_sim$p1,
  p2 = df_sim$p2,
  W1 = df_sim$W1,
  W2 = df_sim$W2,
  U = df_sim$Y)

A snippet of the real data:
p1   p2   W1  W2  U
0.4  0.9  -5  -1  2
0.2  0.95 -5  -1  2
0.4  0.8  -5  -1  2
0.9  0.41 -5  -1  3
0.6  0.84 -5  -1  7
0.2  0.75 -5  -1  6
0.5  1    -5  -1  4

I am completely new to Bayesian approaches, so any help is appreciated.
Comment: I would need the contents of `df` to actually help.  Can you post that?
Comment: I added the data simulation and some real data.
Comment: Can you please examine your minimal working example again?  it doesn't seem to run
Comment: My apologies, was missing a function definition.
Comment: I just noticed that to-be-predicted values in simulated data are negative, however in real data they are positive. Multiplying the column in real data with -1 (which would be theoretically meaningful) did not solve my issue though.
Answer: I can't reproduce this.  With cmdstanr...
library(cmdstanr)
code<-'data {
  int<lower=0> N;
  real<lower=0, upper=1> p1[N];
  real<lower=0, upper=1> p2[N];
  real W1[N];
  real W2[N];
  real U[N];
}

parameters {
  real<lower=0, upper=1> r;
  real<lower=0> s;
  real<lower=0> tau;
}

transformed parameters {
  real pred[N];

  for (i in 1:N) {
    pred[i] = exp(-s*(-log(p1[i]))^r) * W1[i] + exp(-s*(-log(p2[i]))^r) * W2[i];
  }
}

model {
  // priors
  r ~ gamma(1, 1);
  s ~ gamma(1, 1);
  tau ~ gamma(1, 1);

  // model
  U ~ normal(pred, tau);
}'

model = cmdstan_model(write_stan_file(code))

stan_data = list(
  p1 = c(4,2,4,9,6,2,5)/10,
  p2 = c(9, 9.5, 8, 4.1, 8.4, 7.5, 10)/10,
  W1 = -5*rep(1, 7),
  W2 = -1*rep(1, 7),
  U = c(2,2,2,3,7,6,4),
  N = 7
)

fit = model$sample(stan_data)

I do get a warning about metrpopolis proposals being rejected, but the warning appears once and not again making me think Stan is just being cautious (which is fine).
Here is the summary
fit
 variable   mean median   sd  mad     q5    q95 rhat ess_bulk ess_tail
  lp__    -22.73 -22.38 1.33 1.09 -25.37 -21.27 1.00     1695     1975
  r         0.29   0.23 0.23 0.22   0.02   0.76 1.00     3472     2268
  s         3.15   2.94 1.40 1.26   1.25   5.70 1.00     2760     1849
  tau       4.35   4.21 0.99 0.94   3.02   6.17 1.00     2784     2458
  pred[1]  -0.70  -0.52 0.64 0.47  -2.02  -0.06 1.00     2677     1921
  pred[2]  -0.64  -0.51 0.55 0.42  -1.74  -0.07 1.00     2543     1870
  pred[3]  -0.63  -0.44 0.63 0.43  -1.94  -0.05 1.00     2734     1837
  pred[4]  -1.34  -1.04 1.07 0.96  -3.52  -0.12 1.00     2834     1927
  pred[5]  -0.82  -0.60 0.76 0.57  -2.37  -0.07 1.00     2793     1883
  pred[6]  -0.50  -0.32 0.54 0.33  -1.61  -0.03 1.00     2744     1881

 # showing 10 of 11 rows (change via 'max_rows' argument)
```

Comment: Thanks very much for your work on this. This is really interesting. I will also give it a try using cmdstanr. And I will check row by row of the real data, if there is anything strange happening. What should I be looking out for with this kind of error? What are possible sources?


What were the reasons leading to development of Boolean algebra?

Question: What were the reasons leading to development of Boolean algebra?
Nowadays it's so fundamentally used that it almost seems like a triviality, but since it preceded the uses in electronics, then it's (more often) surprising as to why did Boole come to think of such system? Did he have some applications in mind? Or was he "suddenly" studying a simple algebra?
Is Boolean algebra just a reformulation or resyntaxing of earlier logic?
Comment: There is interesting material in Wikipedia: https://en.wikipedia.org/wiki/George_Boole
Comment: You can see also : [George Boole](https://plato.stanford.edu/entries/boole/) and [The Algebra of Logic Tradition](https://plato.stanford.edu/entries/algebra-logic-tradition/).
Comment: Maybe better suited for http://hsm.stackexchange.com.
Answer: George Boole's project must be understood in the context of the development of symbolic algebra in England (mainly Cambridge) during the early 1800s (taking into account also Leibniz's Influence on 19th Century Logic).
See G.Boole, The Mathematical Analysis of Logic: Being an Essay Towards a Calculus of Deductive Reasoning (1847) :

They who are acquainted with the present state of the theory of Symbolical Algebra, are aware, that the validity of the processes of analysis does not depend upon the interpretation of the symbols which are employed, but solely upon the laws of their combination. [...] But the full recognition of the consequences of this important
doctrine has been, in some measure, retarded by accidental circumstances. It has happened in every known form of analysis, that the elements to be determined have been
conceived as measurable by comparison with some fixed standard. The predominant idea has been that of magnitude, or more strictly, of numerical ratio.

Abstract algebra can "free itself" from the restricted domain of nubers and magnitudes and the process of "symbolizarion" can be applied to a wider domain.

That which renders Logic possible, is the existence in our minds of general notions,—our ability to conceive of a class, and to designate its individual members by a common name. The theory of Logic is thus intimately connected with that of Language. A successful attempt to express logical propositions by symbols, the laws of whose combinations should be founded upon the laws of the mental processes which they represent, would, so far, be a step toward a philosophical language. But this is a view which we need not here follow into detail.
Assuming the notion of a class, we are able, from any  conceivable collection of objects, to separate by a mental act, those which belong to the given class, and to contemplate them apart from the rest. [...] Now the several mental operations which in the above case we have supposed to be performed, are subject to peculiar laws.
Such are the elementary laws upon the existence of which, and upon their capability of exact symbolical expression, the method of the following Essay is founded.
The laws we have to examine are the laws of one of the most important of our mental faculties. The mathematics we have to construct are the mathematics of the human intellect.
Comment: @TorstenSchoeneberg - Not *sets* in the "modern" mathematical conception but *classes*, i.e. ["extensions of concepts" (or ideas)](https://en.wikipedia.org/wiki/Extension_(semantics)). Still B.Russell, into the [Principles (1903)](https://books.google.it/books?id=SNWLAgAAQBAJ&pg=PR6) speaks of *classes*.
Comment: The second quote sounds like preconceiving set theory too.


What is the win probabiity of an ice hockey team being down 1-0 at the end of the second period?

Question: I heard following hypothesis about ice-hockey statistics;
-20 min left (i.e. whole third period)
-situation is 0-1
I was told the team that is trailing, has bigger probability to win the game.
Has anyone seen such statistics to prove if this is the case?
Comment: Could you provide some information as to where you saw this? On the face of it, it sounds like complete rubbish, and extraordinary claims require extraordinary evidence.
Comment: I heard it from the radio.
Comment: Was it a general statement by the commentator, or specific to one of the teams involved? It's hard to believe it's true in general. But very possible if a team can't hold their lead, or surges back in the third
Comment: A site with per-period scores would make this easy to analyze.  I found one which shows it's not true for all teams trailing at the start of the third, but it doesn't break out "0-1" scores versus down by 4, so it's not that useful.
Comment: Question - are you counting a "win" as a regulation win only? or do OT / Shootout wins count as "wins", too?
Answer: Note: This is currently a preliminary answer - perhaps more to come depending on what the OP wants.

Going by the results from the 2020/2021 NHL season (until 7th May) there have been a total of 67 games where the game was 1-0 to either team at the end of the second period.
Of these, there were 6 games where that 1-0 deficit was overturned by the other team in regulation, giving an 8.96% overturn rate - or a roughly 1 in 11 chance.
So, statistically, the team trailing 1-0 at that point are significantly less likely to win1.
These games were:

Date
Game
End of P2 Score
Final

14th Feb 2021
Montreal Canadiens v Toronto Maple Leafs
0 : 1
2 : 1

19th Mar 2021
New York Rangers v Washington Capitals
1 : 0
1 : 2

24th Mar 2021
Calgary Flames v Ottawa Senators
1 : 0
1 : 3

4th Apr 2021
Minnesota Wild v Vegas Golden Knights
0 : 1
2 : 1

20th Apr 2021
Montreal Canadiens v Edmonton Oilers
1 : 0
1 : 4

1st May 2021
Los Angeles Kings v Anaheim Ducks
0 : 1
2 : 1

Obviously, as this data is coming from the middle of the 2020/21 season of the NHL, this is just a subset of all possible Ice Hockey games - so the real value is likely to be something different.

I must give credit to this site which listed out all of the games, plus their period by period scores, in which I scraped together the information into a spreadsheet...


i want to use the Url id as a filter of an array

Question: Im trying to put a variable in this case match.params.id into a map filter as a parameter. I want to be able to change my filter based on the URL ID return. I have put
a code example bellow with some comments to further explain.
<code>const allItems = [
{
title: item1,
itemColorBlack: 1,
itemColorWhite: 0
},
{
title: item2,
itemColorBlack: 0,
itemColorWhite: 1}
]
const itemlist = allItems.filter(
  function (item) {
    //So i want to be able with the change of the url display the itemColors.
    //In this example props.params.id returns "itemColorBlack" Url /itemColorBlack
    const itemsearch = props.match.params.id;

    //The output should only show the items where the output of itemColorBlack is 1
    //In this case the element with the title item1. and if i change the url to
    //itemColorWhite it should show the element with the title = item2
    return item.itemsearch == 1
   )}
.map((item) => {
  return <ItemContainer item=item />
 })
</code>
Hopefully this made sense if i need to elaborate further dont hesitate to send a message :)
Answer: I think you need to fetch that url first , then you extract the id passed in the url via req.query store it a state variable [color,setColor]; and put your code in useEffect hook that runs when color changes ;


Using a regex to check for special characters java

Question: I want to check and see if a word contains a special character and remove it. Lets say I have String word = "hello-there", I want to loop through and check to see if the word doesn't contain a letter, then remove that special character and concatenate the word. So I want to turn hello-there into hellothere using regex. I have tried this but I can't seem to figure out how to check individual characters of a string to a regex.
public static void main(String[] args){
String word = "hello-there";

for(int i = 0; i < word.length(); i++)
{
    if(word.charAt(i).matches("^[a-zA-Z]+"))

But the last if statement doesn't work. Anybody know how to take care of this?
Answer: You may use the following regex, that'll match any character, that is not a lower-case or upper-case letter.
[^a-zA-Z]+

see regex demo
Java ( demo )
class RegEx {
    public static void main(String[] args) {
        String s = "hello-there";
        String r = "[^a-zA-Z]+";
        String o = s.replaceAll(r, "");
        System.out.println(o); //-> hellothere
    }
}

Comment: Thank you! While I was waiting for an answer I found the replaceAll method and tried to work with it but couldn't figure out the regex that meant everything but a letter! Thank you!
Comment: Actually, that still doesn't remove most of the things I was looking for. Is there a way to check for anything that is not a lower or uppercase letter?
Comment: I tried it and it works! Although I think it is a-z on the first one not a-b. After changing it to a-z it worked!
Comment: @Programmer ya that's a typo :)
Comment: Thank you! It worked! Getting familiar with regex. Hard to understand but getting the hang of it. Thanks! XD


drf-yasg How to show sample response with with api?

Question: How can I add example responses -- (openapi doc) to my swagger doc using drf-yasg package?
Answer: Use drf_yasg.openapi.Response--(drf-yasg doc) with the help of @swagger_auto_schema(...)--(drf-yasg doc) decorator as
from drf_yasg.utils import swagger_auto_schema
from drf_yasg import openapi
from rest_framework.response import Response
from rest_framework.views import APIView

response_schema_dict = {
    "200": openapi.Response(
        description="custom 200 description",
        examples={
            "application/json": {
                "200_key1": "200_value_1",
                "200_key2": "200_value_2",
            }
        }
    ),
    "205": openapi.Response(
        description="custom 205 description",
        examples={
            "application/json": {
                "205_key1": "205_value_1",
                "205_key2": "205_value_2",
            }
        }
    ),
}

class MyTestAPIView(APIView):

    @swagger_auto_schema(responses=response_schema_dict)
    def post(self, request, *args, **kwargs):
        return Response({"foo": "bar"})
Schema rendered Result

Update

its keep loading and not showing anything

You may need to click on "Example Value" text if you are looking in Swagger doc
Comment: Yes, unless any of them are returning the same response.
Comment: I expected a *new question* with a reference link @DivyaKonda
Comment: So I have to write custom response for every api ? I have 22 apis . so for all of them ?
Comment: Sir , Can You tell how I can add post parameter in it as well ? I can't send post parameter
Comment: This is an *"another question"*, please do ask a new question regarding the new issue. BTW, please do accept and upvote the answer if you found this answer was helpful.
Comment: Then there must be some configuration issue in your case. This answer will work as-is @Fawad
Comment: In my case too, the examples is just loading and not showing anything.
Comment: Can you add a [minimal-reproducible-example](https://stackoverflow.com/help/minimal-reproducible-example) to reproduce the issue? @DivyaKonda
Comment: @ArakkalAbu I posted more details as an answer. the comments seem to have a character limit
Comment: someone actually answered on git - https://github.com/axnsan12/drf-yasg/issues/86
seems to be a css issue.
Comment: @FawadRana I hope the update might be useful for you!!!
Answer: In response to @JPG's response, there is a quick fix for that. Go to settings and add this.
SWAGGER_SETTINGS = {
    "DEFAULT_MODEL_RENDERING": "example"
}

This will render the example first.


Size of the set of palindromic functions

Question: Solve and prove for the size of the the set of functions from k bits to 2x bits where the output bitstrings are palindromic (the first x bits are the reverse bitstring of the last x bits).
Because they're bitstrings, I would assume it's something along the lines of $2^{{x2}^{(k/2)+1}}$, but I'm not sure. Any guidance?
Comment: The domain of our functions  is the set of $k$-bit words, of which there are $2^k$. It looks as if we want to count the functions from this set to the set of $2^x$ $x$-bit words, for once the first $x$ bits are given, the rest are determined. Then the number of functions has size $(2^x)^{2^k}$, or equivalently $2^{x2^k}$.
Answer: There are $n^m$ functions from a set of $m$ elements to a set of $n$ elements. Here $m=2^k$ ($k$-bit words) and $n=2^x$, because the first $x$ bits determine the palindrome. Hence, $n^m=2^{x2^k}$. (Exactly what  André Nicolas said in a comment.)


webdav and hardlinks Function not implemented error message

Question: I have webdav with nginx that I use to transfer files to a remote server. I mount it using davfs2 on a Debian box. The problem is that when I try to create a hardlink, I get the following error message:
ln: failed to create hard link 'cpool/test' => 'pc/test': Function not implemented

Is there a workaround?
Answer: Without special extensions, WebDAV does not support creation of hard links.  The closest standard thing in WebDAV is a 'redirect reference resource' (RFC 4437), which results in returning a 3xx status code, and therefore behaves like a symbolic link, not a hard link.  The upstream http_dav module in nginx does not support this extension (and in fact, doesn't support some of the standard commands (LOCK, UNLOCK, PROPFIND, and PROPPATCH aren't supported by it).  I'm not sure if the third-party module does, but it wouldn't surprise me if it didn't seeing as outside of power users and sysadmins, most people don't user symlinks much either.


how to install ssl on windows IIS server 2008

Question: I am trying to enable https on windows server 2008. I followed below link.
https://www.sslshopper.com/article-installing-an-ssl-certificate-in-windows-server-2008-iis-7.0.html
https://www.digicert.com/ssl-certificate-installation-microsoft-iis-7.htm
A ssl certificate get added but at the time of binding with https, it doesn't show any certificate added. please give me some reference link or tell me if i am doing any wrong config?
Answer: https://blog.lextudio.com/2015/06/the-whole-story-of-server-certificate-disappears-in-iis-77-588-510-0-after-installing-it-why/
Just make sure you create a PFX file as IIS wishes. Then you can import it easily.
Comment: Thanks for your reply. But i have the certificate from CA with .crt extension. Now i am trying to add this certificate to server and try to bind it with Default-website. And also there is no private key in the certificate. i have taken back up of private key in local.  Is there any need to convert it into .pfx file? Please reply.
Comment: @sanketThakare how did you generate the certificate request?
Comment: @ Lex Li  I followed this link:                                                                                https://docs.druva.com/KnowledgeBase/Articles/How_To/Using_Microsoft_IIS_to_generate_CSR_and_Private_Key                       and and i get certificate from below link.                http://manage.resellerclub.com/kb/answer/2409                                                                                Please tell me the format for IIS certificate. I have certificate with .crt extension.
Comment: @sanketThakare if you use IIS Manager to generate the certificate request, then you simply: 1) convert the .crt to a .cer file, https://support.comodo.com/index.php?/Default/Knowledgebase/Article/View/361/17/how-do-i-convert-crt-file-into-the-microsoft-cer-format 2) use the same IIS Manager on the same machine to complete the request with the .cer file. There is no need to use any other tools. 3) if you need to move this certificate to other machines, use IIS Manager to export it as a .pfx file.
Comment: @ Lex Li  ok, now as per your suggestion i follow  link:  https://support.comodo.com/index.php?/Default/Kncer-format                                                                                and got cer file of certificate. I successfully converted .crt to .cer file. certificate is added but at the time of binding, it disappears from drop down list. i dont understand why certificate doesn't show at the time of binding https? and when i return to my server certificate, added certificate disappears. please give any suggestion.
Comment: @sanketThakare did you use the .cer to finish the certificate request? And you must finish the request on the machine that you created the original request. Of course, to be safe you can now follow the blog post in the answer to merge the private key with the .cer file into a .pfx file.
Comment: Finally i got success with  install ssl  on windows server 2008. The issue was certificate created on different server and i was trying to install it on other server. I followed the bellow link and got success.    https://support.comodo.com/index.php?/Default/Knowledgebase/Article/View/678/0/exporting-and-restoring-a-pfx-file-to-iis. hope it will be helpful to someone.  Thanks Lex Li.


Metric Derivative Proof

Question: How do I go about proving
$\partial_{\mu} g^{\nu \rho}=-g^{\nu \sigma}g^{\rho \lambda}\partial_{\mu} g_{\sigma \lambda}$?
I've tried using the covariant derivative and the Christoffel symbols but it seems to be to no end in finding this specific relation.
Any ideas?
Comment: You need only to use $g^{\alpha \beta}g_{\beta \gamma} = \delta^\alpha_\gamma$. And it has nothing to do with Riemannian geometry.
Answer: (Just to make this question answered)
Observe that for any invertible matrix
$$ A^{-1} A = I $$
where $I$ is the identity matrix. Now, let $A(t)$ be a parametrised family of invertible matrices, you have by the product rule:
$$ (\partial_t A^{-1}) A + A^{-1} \partial_t A = 0 $$
since the identity matrix is independent of $t$. Therefore
$$ (\partial_t A^{-1}) A = - A^{-1} \partial_t A \implies \partial_t A^{-1} = - A^{-1} (\partial_t A ) A^{-1} $$
writing out the matrix multiplication in index notation you get exactly the expression you wanted.

Metric Derivative Proof


Combine all push notifications into one

Question: I'm using Parse Push Notifications to notify my app's users, but when I send 2 push notifications, I want them to be combined into one.
As you can see in this image, WhatsApp combines all notifications into one. How can I do such a thing?
So far I have found this code:
Notification noti = new Notification.Builder()
     .setContentTitle("5 New mails from " + sender.toString())
     .setContentText(subject)
     .setSmallIcon(R.drawable.new_mail)
     .setLargeIcon(aBitmap)
     .setStyle(new Notification.InboxStyle()
         .addLine(str1)
         .addLine(str2)
         .setContentTitle("")
         .setSummaryText("+3 more"))
     .build();

But I don't know where or how to use it.
Comment: did any of the answers help you?
Answer: I am not sure how it works in parse, but I have done the same for GCM. We have used a scheduler at the backed for pushing notifications after say every 5 minutes. There is a notification table which contains all the notifications with a status which is updated from the front end if the user receives a notification and performs some action, we update the table via a web service.
So suppose you have pushed 1st notification request(remember to define a unique key for this: collapse key) to the Google server and it did not reach the user, now when the scheduler re-checks for pending notifications it will re-pick the 1st one and there are few more new notifications to be pushed of similar kind. You can create a new request combining these and send request to the Google server.
{ "collapse_key": "score_update",
  "time_to_live": 108,
  "delay_while_idle": true,
  "data": {
     "score": "4 x 8",
     "time": "15:16.2342"
   },
  "registration_ids":["4", "8", "15", "16", "23", "42"]
}

You need to define a unique collapse key for your notifications, and if you create a new request with same collapse key all the previous pending requests will be discarded and only the latest one will be pushed to the users mobile which could be a list of couple of notifications.
Answer: The Android guide on notifications really explains all this very well. You can also look at the Android Notification design guide to get some additional ideas about how to best use notifications.
To use the notification you've built, add this code:
final NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
notificationManager.notify(mId, noti);

Later you can then update the notification to change its content, such as described there:

To set up a notification so it can be updated, issue it with a notification ID by calling NotificationManager.notify(). To update this notification once you've issued it, update or create a NotificationCompat.Builder object, build a Notification object from it, and issue the Notification with the same ID you used previously. If the previous notification is still visible, the system updates it from the contents of the Notification object. If the previous notification has been dismissed, a new notification is created instead.
Answer: Just use setGroup(Group-KEY) while setting notifications.
final static String GROUP_KEY_EMAILS = "group_key_emails";

// Build the notification, setting the group appropriately

Notification notif = new NotificationCompat.Builder(mContext)
         .setContentTitle("New mail from " + sender1)
         .setContentText(subject1)
         .setSmallIcon(R.drawable.new_mail)
         .setGroup(GROUP_KEY_EMAILS)
         .build();

Combine all push notifications into one


Munkres - Analysis on manifolds Lemma 16.2 proof

Question: I was reading through this proof but after it, it's remarked that a point x of the boundary of A intersects infinitely many of the cubes from the constructed collection.
I don't understand why is he saying that, if one of the conditions is precisely (2) that each of the rectangles is contained in an element of the collection of open sets, and therefore they cannot intersect the boundary of the union.
I'd like to know where I'm wrong.
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Answer: You wrote as follows:

a point $x$ of the boundary of $A$ intersects infinitely many of the cubes from the constructed collection.

But the author wrote:

Each neighborhood of a point $x$ of the boundary of $A$ intersects infinitely many of the cubes from the constructed collection.