text:
<title>Transcript Segmentation
   </title>
    <link href="../../../Mainpage/transcriptseg.css" rel="stylesheet" />

Khan 1

We've already explored a two-dimensional version of the divergence theorem.

If I have some region-- so this is my region right over here.

We'll call it R.

And let's call the boundary of my region, let's call that C.

And if I have some vector field in this region, so let me draw a vector field like this.

If I draw a vector field just like that, our two-dimensional divergence theorem, which we really derived from Green's theorem, told us that the flux across our boundary of this region-- so let me write that out.

The flux across the boundary, so the flux is essentially going to be the vector field.

It's going to be our vector field F dotted with the normal outward-facing vector.

So the normal vector at any point is this outward-facing vector, So our vector field, dotted with the normal-facing vector at our boundary times our little chunk of the boundary.

If we were to sum them all up over the entire boundary-- let me write that a little bit neater-- that's the same thing as summing up over the entire region.

So let's sum up over the entire region.

So summing up over this entire region, each little chunk of area, dA-- we could call that dx dy if we wanted to if we're dealing in the xy domain right over here, but each little chunk of area times the divergence of F, which is really saying, how much is that vector field pulling apart? So it's times the divergence of F.

And hopefully, it made intuitive sense.

The way that I drew this vector field right over here, you see everything's kind of coming out.

You could almost call this a source right here, where the vector field seems like it's popping out of there.

This has positive divergence right over here.

And so because of this, you actually see that the vector field at the boundary is actually going in the direction of the normal vector, pretty close to the direction of the normal vector, so it makes sense.

You have positive divergence, and this is going to be a positive value.

The vector field is going, for the most part, in the direction of the normal vector.

So the larger this is, the larger that is.

So hopefully, some intuitive sense.

If you had another vector field-- so let me draw another region-- that looked like this, so I could draw a couple situations.

So one where there's very limited divergence, maybe it's just a constant.

The vector field doesn't really change as you go in any given direction.

Over here you'll get positive fluxes.

I don't know what the plural of flux is.

You'll get positive fluxes, because the vector field seems to be going in roughly the same direction as our normal vector.

But here, you'll get a negative flux.

So stuff is coming in here.

If you imagine your vector field is essentially some type of mass density times volume, and we've thought about that before, this is showing how much stuff is coming in, and then stuff is coming out.

So your net flux will be close to zero.

Stuff is coming in, and stuff is coming out.

Here, you're just saying, hey, stuff is constantly coming out of this surface.

So hopefully, this gives you a sense that here you have very low divergence, and you would have a low flux, total aggregate flux, going through your boundary.

Here you have a high divergence, and you would have a high aggregate flux.

I could draw another situation.

So this is my region R.

And let's say that we have negative divergence, or we could even call it convergence.

Convergence isn't an actual technical term, but you could imagine if the vector field is converging within R, well, the divergence is going to be negative in this situation.

It's actually converging, which is the opposite of diverging.

So the divergence is negative in this situation.

And also the flux across the boundary is going to be negative.

Because as we see here, the way I drew it, across most of this boundary, the vector field is going in the opposite direction.

It's going in the opposite direction as our normal vector at any point.

So hopefully, this gives you a sense of why there's this connection between the divergence over the region and the flux across the boundary.

Well, now we're just going to extend this to three dimensions, and it's the exact same reasoning.

If we have a-- and I'll define it a little bit more precisely in future videos-- a simple, solid region.

So let me just draw it.

And I'm going to try to draw it in three dimensions.

So let's say it looks something like that.

And one way to think about it is this is going to be a region that doesn't bend back on itself.

And if you have a region that bends back on itself-- well, we'll think about it in multiple ways.

But out of all the volumes of three dimensions that you can imagine, these are the ones that don't bend back on themselves.

And there are some that you might not be able to imagine that would also not make the case.

But even if you had ones that bent back on themselves, you could separate them out into other ones that don't.

So here is just a simple solid region over here.

I'll make it look three dimensional.

So maybe if it was transparent, you would see it like that.

And then you see the front of it like that.

So it's this kind of elliptical, circular, blob-looking thing.

So that could be the back of it.

And then if you go to the front, it could look something like that.

So this is our simple solid region.

I'll call it-- well, I'll call it R still.

But we're dealing with a three dimensional.

We are now dealing with a three-dimensional region.

And now the boundary of this is no longer a line.

We're now in three dimensions.

The boundary is a surface.

So I'll call that S.

S is the boundary of R.

And now let's throw on a vector field here.

Now, this is a vector field in three dimensions.

And now let's imagine that we actually have positive divergence of our vector field within this region right over here.

So we have positive divergence.

So you can imagine that it's kind of-- the vector field within the region, it's a source of the vector field, or the vector field is diverging out.

That's just the case I drew right over here.

And the other thing we want to say about vector field S, it's oriented in a way that its normal vector is outward facing, so outward normal vector.

So the normal, it's oriented so that the surface-- the normal vector is like that.

The other option is that you have an inward-facing normal vector.

But we're assuming it's an outward-facing N.

Well, then we just extrapolate this to three dimensions.

We essentially say the flux across the surface.

So the flux across the surface, you would take your vector field, dot it with the normal vector at the surface, and then multiply that times a little chunk of surface, so multiply that times a little chunk of surface, and then sum it up along the whole surface, so sum it up.

So it's going to be a surface integral.

So this is flux across the surface.

It's going to be equal to-- if we were to sum up the divergence, if we were to sum up across the whole volume, so now if we're summing up things on every little chunk of volume over here in three dimensions, we're going to have to take integrals along each dimension.

So it's going to be a triple integral over the region of the divergence of F.

So we're going to say, how much is F? What is the divergence at F at each point? And then multiply it times the volume of that little chunk to sense of how much is it totally diverging in that volume.

And then you sum it up.

That should be equal to the flux.

It's completely analogous to what's here.

Here we had a flux across the line.

We had essentially a two-dimensional-- or I guess we could say it's a one-dimensional boundary, so flux across the curve.

And here we have the flux across a surface.

Here we were summing the divergence in the region.

Here we're summing it in the volume.

But it's the exact same logic.

If you had a vector field like this that was fairly constant going through the surface, on one side you would have a negative flux.

On the other side, you would have a positive flux, and they would roughly cancel out.

And that makes sense, because there would be no diverging going on.

If you had a converging vector field, where it's coming in, the flux would be negative, because it's going in the opposite direction of the normal vector.

And so the divergence would be negative as well, because essentially the vector field would be converging.

So hopefully this gives you an intuition of what the divergence theorem is actually saying something very, very, very, very-- almost common sense or intuitive.

And now in the next few videos, we can do some worked examples, just so you feel comfortable computing or manipulating these integrals.

And then we'll do a couple of proof videos, where we actually prove the divergence theorem.

Khan 2

Let's say we have a path in the xy plane.

That's my y-axis, that is my x-axis, in my path will look like this.

Let's say it looks like that; trying to draw a bit of an arbitrary path, and let's say we go in a counter clockwise direction like that along our path.

And we could call this path-- so we're going in a counter clockwise direction --we could call that path c.

And let's say we also have a vector field.

And our vector field is going to be a little unusual; I'll call it p.

p of xy.

It only has an i component, or all of its vectors are only multiples of the i-unit vector.

So it's capital P of xy times the unit vector i.

There is no j component, so if you have to visualize this vector field, all of the vectors, they're all multiples of the i-unit vector.

Or they could be negative multiples, so they could also go in that direction.

But they don't go diagonal or they don't go up.

They all go left to right or right to left.

That's what this vector field would look like.

Now what I'm interested in doing is figuring out the line integral over a closed loop-- the closed loop c, or the closed path c --of p dot dr, which is just our standard kind of way of solving for a line integral.

And we've seen what dr is in the past.

dr is equal to dx times i plus dy times the j-unit vector.

And you might say, isn't it dx, dt times dt? Let me write that can't dr be written as dx, dt times dti plus dy, dt times dtj? And it could, but if you imagine these differentials could cancel out, and you're just left with the dx and a dy, and we've seen that multiple times.

And I'm going to leave it in this form because hopefully, if we're careful, we won't have to deal with the third parameter, t.

So let's just look at it in this form right here with just the dx's and the dy's.

So this integral can be rewritten as the line integral, the curve c-- actually let me do it over down here.

The line integral over the path of the curve c of p dot dr.

So we take the product of each of the coefficients, let's say the coefficient of the i component, so we get p-- I'll do that in green, actually do that purple color --so we get p of xy times dx plus-- well there's no 0 times j times dy; 0 times dy id just going to be 0 --so this our line integral simplified to this right here.

This is equal to this original integral up here, so we're literally just taking the line integral around this path.

Now I said that we play our cards right, we're not going to have to deal with the third variable, t; that we might be able just solve this integral only in terms of x.

And so let's see if we can do that.

So let's look at our minimum and maximum x points.

That looks like our minimum x point.

Let's call that a.

Let's call that our maximum x point; let's call that b.

What we could do is we can break up this curve into two functions of x.

y is functions of x.

So this bottom one right here we could call as y1 of x.

This is just a standard curve; you know when we were just dealing with standard calculus, this is just you can imagine this is f of x and it's a function of x.

And this is y2 of x.

Just like that.

So you can imagine two paths; one path defined by y1 of x-- let me do that in a different color; magenta --one path defined by y1 of x as we go from x is equal to a to x is equal to b, and then another path defined by y2 of x as we go from x is equal to b to x is equal to a.

That is our curve.

So what we could do is, we could rewrite this integral-- which is the same thing as that integral --as this is equal to the integral-- we'll first do this first path --of x going from a to b of p of x.

And I could to say p of x and y, but we know along this path y is a function of x.

So we say x and y1 of x.

Wherever we see a y we substitute it with a y1 of x, dx.

So that covers that first path; I'll do it in the same color.

We could imagine this is c1.

This is kind of the first half of our curve-- well it's not exactly the half --but that takes us right from that point to that point.

And then we want to complete the circle.

Maybe I'll do that, and I'll do that in yellow.

That's going to be equal to-- sorry we're going to have to add these two --plus the integral from x is equal to b to x is equal to a of-- do it in that same color --of p of x.

And now y is going to be y2 of x.

Wherever you see a y, you can substitute with y2 of x along this curve.

y2 of x, dx.

This is already getting interesting and you might already see where I'm going with this.

So this is the curve c2.

too I think you appreciate if you take the union of c1 and c2, we've got our whole curve.

So let's see if we can simplify this integral a little bit.

Well one thing we want to do, we might want to make their end points the same.

So if you swap a and b here, it just turns the integral negative.

So you make this into a b, that into an a, and then make that plus sign into a minus sign.

And now we can rewrite this whole thing as being equal to the integral from a to b of this thing, of p of x and y1 of x minus this thing, minus p of x and y2 of x, and then all of that times dx.

I'll write it in a third color.

Now, I'm going to do something a little bit arbitrary, but I think you'll appreciate why I did this by the end of this video, and it's just a very simple operation.

What I'm going to do is I'm going to swap these two.

So I'm essentially going to multiply this whole thing by negative 1, or essentially multiply and divide by negative 1.

So I can multiply this by negative 1 and then multiply the outside by negative 1, and I will not have changed the integral; I'm multiplying by negative 1 twice.

So if I swap these two things, if I multiply the inside times negative 1, so this is going to be equal to-- do the outside of the integral, a to b.

If I multiply the inside-- I'll do a dx out here --if I multiply the inside of the integral by negative 1, these two guys switch.

So it becomes p of x of y2 of x.

And then you're going to have minus p of x and y1 of x.

My handwriting's getting a little messy.

But I can't just multiply just the inside by minus 1.

I don't want to change the integral, so I multiplied the inside by minus 1, let me multiply the outside by minus 1.

And since I multiplied by minus 1 twice, these two things are equivalent.

Or you could say this is the negative of that.

Either way, I think you appreciate that I haven't changed the integral at all, numerically.

I multiplied the inside and the outside by minus 1.

And now the next step I'm going to do, it might look a little bit foreign to you, but I think you'll appreciate it.

It might be obvious to you if you've recently done some double integrals.

So this thing can be rewritten as minus the integral from a to b of-- and let me do a new color --of the function p of x, y evaluated at y2 of x minus-- and let me make it very clear; this is y is equal to y2 of x --minus this function evaluated at y is equal to y1 of x.

And of course all of that times dx.

This statement and what we saw right here-- this statement right here --are completely identical.

And then if we assume that a partial derivative of capital P with respect to y exists, hopefully you'll realize-- and I'll focus on this a little bit because I don't want to confuse you on this step.

Let me write the outside of this integral.

So this is going to be equal to-- and this is kind of a neat outcome, and we're starting to build up to a very neat outcome, which will probably have to take the next video to do --so we do the outside dx.

If we assume that capital P has a partial derivative, this right here is the exact same thing.

This right here is the exact same thing as the partial derivative of P with respect to y, dy, the antiderivative of that from y1 of x to y2 of x.

I want to make you feel comfortable that these two things are equivalent.

And to realize they're equivalent, you'll probably just have to start here and then go to that.

We're used to seeing this; we're used to seeing a double integral like this, and then the very first step we say, OK to solve this double integral we start on the inside integral right there, and we say, OK let's take the antiderivative of this with respect to y.

So if you take the antiderivative of the partial of p with respect to y, you're going to end up with p.

And since this is a definite integral, the boundaries are going to be in terms of x, you're going to evaluate that from y is equal to y2 of x, and you're going to subtract from that y is equal to y1 of x.

Normally we start with something like this, and we go to something like this.

This is kind of unusual that we started, we kind of solved, we started with the solution of the definite integral, and then we slowly built back to the definite integral.

So hopefully you realize that this is true, that this is just we're kind of going in a reverse direction than we normally do.

And if you do realize that, then we've just established a pretty neat outcome.

Because what is this right here? Let me go back, let me see if I can fit everything.

I have some function-- and I'm assuming that the partial of P with respect to y exists --but I have some function defined over the xy plane.

You know, you could imagine we're dealing in three dimensions now.

We'll draw a little bit neater.

So that's y, that's x, that's z, so this, you could imagine, is some surface; it just happens to be the partial of P with respect to x.

So it's some surface on the xy plane like that.

And what are we doing? We're taking the double integral under that surface, around this region.

The region's boundaries in terms of y are defined by y2 and y1 of x.

So you literally have that curve.

That's y2 on top, y1 on the bottom.

And so we're essentially taking the volume above.

So if you imagine with the base is-- the whole floor of this is going to be the area inside of this curve, and then the height is going to be the function partial of P with respect to y.

It's going to be a little hard for me to draw, but this is essentially some type of a volume, if you want to visualize it that way.

But the really neat outcome here is if you call this region r, we've just simplified this line integral.

And this was a special one.

It only had an x-component, the vector field, but we've just simplified this line integral to being equivalent to-- maybe I should write this line integral because that's what's the really neat outcome.

We've just established that this thing right here, which is the same as our original one, so let me write that.

The closed line integral around the curve c of p of xy, dx, we've just established that that's the same thing as the double integral over the region r-- this is the region r --of the partial of P with respect to y.

And we could write dy, dx, or we could write da, whatever you want to write, but this is the double integral over that region.

The neat thing here is using a vector field that only had an x-component, we were able to connect its line integral to the double integral over region-- oh, and I forgot something very important.

We had a negative sign out here.

So this was a minus sign out here.

Or we could even put the minus in here, but I think you get the general idea.

In the next video, I'm going to do the same exact thing with the vector field that only has vectors in the y-direction.

And then we'll connect the two and we'll end up with Green's theorem.

Khan 3

Let's take the derivative with respect to x of x to the n plus 1-th power over n plus 1 plus some constant c.

And we're going to assume here, because we want this expression to be defined, we're going to assume that n does not equal negative 1.

If it equaled negative 1, we'd be dividing by 0, and we haven't defined what that means.

So let's take the derivative here.

So this is going to be equal to-- well, the derivative of x to the n plus 1 over n plus 1, we can just use the power rule over here.

So our exponent is n plus 1.

We can bring it out front.

So it's going to be n plus 1 times x to the-- I want to use that same color.

Colors are the hard part-- times x to the-- instead of n plus 1, we subtract 1 from the exponent.

This is just the power rule.

So n plus 1 minus 1 is going to be n.

And then we can't forget that we were dividing by this n plus 1.

So we have divided by n plus 1.

And then we have plus c.

The derivative of a constant with respect to x-- a constant does not change as x changes, so it is just going to be 0, so plus 0.

And since n is not equal to negative 1, we know that this is going to be defined.

This is just going to be something divided by itself, which is just going to be 1.

And this whole thing simplifies to x to the n.

So the derivative of this thing-- and this is a very general terms-- is equal to x to the n.

So given that, what is the antiderivative-- let me switch colors here.

What is the antiderivative of x to the n? And remember, this is just the kind of strange-looking notation we use.

It'll make more sense when we start doing definite integrals.

But what is the antiderivative of x to the n? And we could say the antiderivative with respect to x, if we want to.

And another way of calling this is the indefinite integral.

Well, we know this is saying x to the n is the derivative of what? Well, we just figured it out.

It's the derivative of this thing, and we've written it in very general terms.

We're actually encapsulating multiple constants here.

We could have x to the n plus 1 over n plus 1 plus 0, plus 1, plus 2, plus pi, plus a billion.

So this is going to be equal to x to the n plus 1 over n plus 1 plus c.

So this is pretty powerful.

You can kind of view this as the reverse power rule.

And it applies for any n, as long as n does not equal negative 1.

Let me make that very clear.

n does not equal negative 1.

Once again, this thing would be undefined if n were equal to negative 1.

So let's do a couple of examples just to apply this-- you could call it the reverse power rule if you want, or the anti-power rule.

So let's take the antiderivative of x to the fifth power.

What is the antiderivative of x to the fifth? Well, all we have to say is, well, look, the 5 is equal to the n.

We just have to increment the exponent by 1.

So this is going to be equal to x to the 5 plus 1 power.

And then we divide by that same value.

Whatever the exponent was when you increment it by 1, we divide by that same value, divided by 5 plus 1.

And of course, we want to encapsulate all of the possible antiderivatives, so you put the c right over there.

So this is going to be equal to x to the sixth over 6 plus c.

And you can verify.

Take the derivative of this using the power rule, you indeed get x to the fifth.

Let's try another one.

Let's try-- now we'll do it in blue.

Let's try the antiderivative of-- let's make it interesting.

Let's make it 5 times x to the negative 2 power dx.

So how would we evaluate this? Well, one simplification you can do-- and I haven't rigorously proven it to you just yet-- but we know that scalars can go in and out of the derivative operator when you're multiplying by a scalar.

So this is, indeed, equal to 5 times the antiderivative of x to the negative 2 power, dx.

And now we can just use, I guess we could call it this anti-power rule, so this is going to be equal to 5 times x to the negative 2 power plus 1 over the negative 2 power plus 1 plus some constant right over here.

And then we can rewrite this as 5 times negative 2 power plus 1 is x to the negative 1 over negative 2 plus 1 is negative 1, plus some constant.

And this is equal to 5 times negative x to the negative 1 plus some constant.

And then if we want, we can distribute the 5.

So this is equal to negative 5x to the negative 1.

Now, we could write plus 5 times some constant, but this is just an arbitrary constant.

So this is still just an arbitrary constant.

So maybe we could [INAUDIBLE] this.

If you want it to show that it's a different constant, you could say this is c1, c1, c1.

You multiply 5 times c1, you get another constant.

We could just call that c, which is equal to 5 times c1.

But there you have it.

Negative 5x to the negative 1 plus c.

And once again, all of these, try to evaluate the derivative, and you will see that you get this business, right over there.

Khan 4

We want to find the derivative with respect to x of all of this business right over here.

And you might guess-- and this is definitely a function of x.

x is one of the boundaries of integration for this definite integral.

And you might say, well, it looks like the fundamental theorem of calculus might apply, but I'm used to seeing the x, or the function x, as the upper bound, not as the lower bound.

How do I deal with this? And the key realization is to realize what happens when you switch bounds for a definite integral.

And I'll do a little bit of an aside to review that.

So if I'm taking the definite integral from a to b of f of t, dt, we know that this is capital F, the antiderivative of f, evaluated at b minus the antiderivative of F evaluated at a.

This is corollary to the fundamental theorem, or it's the fundamental theorem part two, or the second fundamental theorem of calculus.

This is how we evaluate definite integrals.

Now, let's think about what the negative of this is.

So the negative of that-- of a to b of f of t, dt, is just going to be equal to the negative of this, which is equal to-- so it's the negative of f of b minus f of a, which is equal to capital F of a minus capital F of b.

All I did is distribute the negative sign and then switch the two terms.

But this right over here is equal to the definite integral from, instead of a to b, but from b to a of f of t, dt.

So notice, when you put a negative, that's just like switching the signs or switching the boundaries.

Or if you switch the boundaries, they are the negatives of each other.

So we can go back to our original problem.

We can rewrite this as being equal to the derivative with respect to x of-- instead of this, it'll be the negative of the same definite integral but with the boundaries switched-- the negative of x with the upper boundary is x, the lower bound is 3 of the square root of the absolute value of cosine t, dt, which is equal to-- we can take the negative out front-- negative times the derivative with respect to x of all of this business.

I should just copy and paste that, so I'll just copy and paste.

Let me-- and paste it.

So times the derivative with respect to x of all that, and now the fundamental theorem of calculus directly applies.

This is going to be equal to-- we deserve a drum roll now.

This is going to be equal to the negative-- can't forget the negative.

And the fundamental theorem of calculus tells us that that's just going to be this function as a function of x.

So it's going to be negative square root of the absolute value of cosine of not t anymore, but x.

And we are done.

Khan 5

Let's say I have some function f that is continuous on an interval between a and b.

And I have these brackets here, so it also includes a and b in the interval.

So let me graph this just so we get a sense of what I'm talking about.

So that's my vertical axis.

This is my horizontal axis.

I'm going to label my horizontal axis t so we can save x for later.

I can still make this y right over there.

And let me graph.

This right over here is the graph of y is equal to f of t.

Now our lower endpoint is a, so that's a right over there.

Our upper boundary is b.

Let me make that clear.

And actually just to show that we're including that endpoint, let me make them bold lines, filled in lines.

So lower boundary, a, upper boundary, b.

We're just saying and I've drawn it this way that f is continuous on that.

Now let's define some new function.

Let's define some new function that's the area under the curve between a and some point that's in our interval.

Let me pick this right over here, x.

So let's define some new function to capture the area under the curve between a and x.

Well, how do we denote the area under the curve between two endpoints? Well, we just use our definite integral.

That's our Riemann integral.

It's really that right now before we come up with the conclusion of this video, it really just represents the area under the curve between two endpoints.

So this right over here, we can say is the definite integral from a to x of f of t dt.

Now this right over here is going to be a function of x-- and let me make it clear-- where x is in the interval between a and b.

This thing right over here is going to be another function of x.

This value is going to depend on what x we actually choose.

So let's define this as a function of x.

So I'm going to say that this is equal to uppercase F of x.

So all fair and good.

Uppercase F of x is a function.

If you give me an x value that's between a and b, it'll tell you the area under lowercase f of t between a and x.

Now the cool part, the fundamental theorem of calculus.

The fundamental theorem of calculus tells us-- let me write this down because this is a big deal.

Fundamental theorem-- that's not an abbreviation-- theorem of calculus tells us that if we were to take the derivative of our capital F, so the derivative-- let me make sure I have enough space here.

So if I were to take the derivative of capital F with respect to x, which is the same thing as taking the derivative of this with respect to x, which is equal to the derivative of all of this business-- let me copy this.

So copy and then paste, which is the same thing.

I've defined capital F as this stuff.

So if I'm taking the derivative of the left hand side, it's the same thing as taking the derivative of the right hand side.

The fundamental theorem of calculus tells us that this is going to be equal to lowercase f of x.

Now why is this a big deal? Why does it get such an important title as the fundamental theorem of calculus? Well, it tells us that for any continuous function f, if I define a function, that is, the area under the curve between a and x right over here, that the derivative of that function is going to be f.

So let me make it clear.

Every continuous function, every continuous f, has an antiderivative capital F of x.

That by itself is a cool thing.

But the other really cool thing-- or I guess these are somewhat related.

Remember, coming into this, all we did, we just viewed the definite integral as symbolizing as the area under the curve between two points.

That's where that Riemann definition of integration comes from.

But now we see a connection between that and derivatives.

When you're taking the definite integral, one way of thinking, especially if you're taking a definite integral between a lower boundary and an x, one way to think about it is you're essentially taking an antiderivative.

So we now see a connection-- and this is why it is the fundamental theorem of calculus.

It connects differential calculus and integral calculus-- connection between derivatives, or maybe I should say antiderivatives, derivatives and integration.

Which before this video, we just viewed integration as area under curve.

Now we see it has a connection to derivatives.

Well, how would you actually use the fundamental theorem of calculus? Well, maybe in the context of a calculus class.

And we'll do the intuition for why this happens or why this is true and maybe a proof in later videos.

But how would you actually apply this right over here? Well, let's say someone told you that they want to find the derivative.

Let me do this in a new color just to show this is an example.

Let's say someone wanted to find the derivative with respect to x of the integral from-- I don't know.

I'll pick some random number here.

So pi 2x-- I'll put something crazy here-- cosine squared of t over the natural log of t minus the square root of t dt.

So they want you take the derivative with respect to x of this crazy thing.

Remember, this thing in the parentheses is a function of x.

Its value, it's going to have a value that is dependent on x.

If you give it a different x, it's going to have a different value.

So what's the derivative of this with respect to x? Well, the fundamental theorem of calculus tells us it can be very simple.

We essentially-- and you can even pattern match up here.

And we'll get more intuition of why this is true in future videos.

But essentially, everywhere where you see this right over here is an f of t.

Everywhere you see a t, replace it with an x and it becomes an f of x.

So this is going to be equal to cosine squared of x over the natural log of x minus the square root of x.

You take the derivative of the indefinite integral where the upper boundary is x right over here.

It just becomes whatever you were taking the integral of, that as a function instaed of t, that is now a function x.

So it can really simplify sometimes taking a derivative.

And sometimes you'll see on exams these trick problems where you had this really hairy thing that you need to take a definite integral of and then take the derivative, and you just have to remember the fundamental theorem of calculus, the thing that ties it all together, connects derivatives and integration, that you can just simplify it by realizing that this is just going to be instead of a function lowercase f of t, it's going to be lowercase f of x.

Let me make it clear.

In this example right over here, this right over here was lowercase f of t.

And now it became lowercase f of x.

This right over here was our a.

And notice, it doesn't matter what the lower boundary of a actually is.

You don't have anything on the right hand side that is in some way dependent on a.

Anyway, hope you enjoyed that.

And in the next few videos, we'll think about the intuition and do more examples making use of the fundamental theorem of calculus.

Khan 6

So let's see if we can take the derivative of this expression right over here, if we can find capital F prime of x.

And once again, it looks like you might be able to use the fundamental theorem of calculus.

A big giveaway is that you're taking the derivative of a definite integral that gives you a function of x.

But here I have x on both the upper and the lower boundary, and the fundamental theorem of calculus, is at least from what we've seen, is when we have x's only on the upper boundary.

And then, of course, it's an x squared, but we've seen examples of that already when we used the chain rule to do it.

But how can we break this up and put this in a form that's a little bit closer to what we're familiar with when we apply the fundamental theorem of calculus? And to realize that, we really just have to attempt to graph what this is representing.

So let's say that this is our lowercase f of x, or I should say f of t.

So let's call this lowercase f of t.

And let's graph it over the interval between x and x squared.

So let's say this is my y-axis.

This is my t-axis.

And let's say that this right over here is y is equal to f of t.

I'm drawing it generally.

I don't know what this exactly looks like.

And we're going to talk about the interval between x and x squared.

So if we're going to talk about the interval between x, which is right over here, it's the lower bound, so x and x squared.

It's the lower bound, at least for this definite integral.

We don't know for sure.

It depends on what x you choose on which one is actually smaller.

But let's just say that for the sake of visualizing, we'll draw x right over here, and we will draw x squared right over here.

So this whole expression, this entire definite integral, is essentially asking for, is essentially representing this entire area, the entire area under the curve.

But what we could do is introduce a constant that's someplace in between x and x squared.

Let's say that constant is c, and break this area into two different areas with c as the divider.

So that same exact whole area we can now write it as two separate integrals.

So one integral that represents this area right over here, and then another integral that represents this area right over there, and where we just say c is some constant between x and x squared.

Well, how can we denote this area in purple? Well, that's going to be-- So this thing is going to be equal to the sum of these two areas.

The purple area we can show is the definite integral from x to c of our function of t, cosine t over t dt.

And then to that we're going to add the green area.

And then we'll get the original area.

So for the green area, our lower bound of integration is now our constant c, and our upper bound of integration is x squared, and it's going to be of cosine t over t dt.

And this is a form where, if we know how to apply the chain rule, we can apply the fundamental theorem of calculus.

And this is almost in a form.

We're used to seeing it where the x is the upper bound.

And, well, we already know what happens.

We can swap these two bounds, but it'll just be the negative of that integral.

So this is going to be equal to-- let me rewrite it-- the negative of the definite integral from c to x of cosine t over t dt.

And then we have plus the definite integral that goes from c to x squared of cosine t over t dt.

So all we've done is we've rewritten this thing in a way that we're used to applying the fundamental theorem of calculus.

So if we want to find F prime of x, well, applying the derivative operator over here, we're going to have a negative out front.

It's going to be equal to negative cosine x over x.

Once again, just the fundamental theorem of calculus.

And then plus-- we're first going to take the derivative of this thing with respect to x squared, and that's going to give you cosine of x squared over x squared.

Wherever you saw t, you replace it with an x squared.

And then you're going to multiply that times the derivative of x squared with respect to x.

So that's just going to be-- derivative of x squared with respect to x is just 2x.

And we're done.

We just need to simplify this thing.

So all of this is going to be equal to negative cosine x over x plus-- well, this is going to cancel out with just one of those-- plus 2 cosine x squared over x.

And I guess we could simplify it even more as being equal to-- and we can swap these-- everything over x 2 cosine of x squared minus cosine of x.

And we are done.

Khan 7

I thought I would do a few more examples of taking antiderivatives, just so we feel comfortable taking antiderivatives of all of the basic functions that we know how to take the derivatives of.

And on top of that, I just want to make it clear that it doesn't always have to be functions of x.

Here we have a function of t, and we're taking the antiderivative with respect to t.

And so you would not write a dx here.

That is not the notation.

You'll see why when we focus on definite integrals.

So what's the antiderivative of this business right over here? Well, it's going to be the same thing as the antiderivative of sine of t, or the indefinite integral of sine of t, plus the indefinite integral, or the antiderivative, of cosine of t.

So let's think about what these antiderivatives are.

And we already know a little bit about taking the derivatives of trig functions.

We know that the derivative with respect to t of cosine of t is equal to negative sine of t.

So if we want a sine of t here, we would just have to take the derivative of negative cosine t.

If we take the derivative of negative cosine t, then we get positive sine of t.

The derivative with respect to t of cosine t is negative sine of t.

We have the negative out front.

It becomes positive sine of t.

So the antiderivative of sine of t is negative cosine of t.

So this is going to be equal to negative cosine of t.

And then what's the antiderivative of cosine of t? Well, we already know that the derivative with respect to t of sine of t is equal to cosine of t.

So cosine of t's antiderivative is just sine of t-- so plus sine of t.

And we're done.

We've found the antiderivative.

Now let's tackle this.

Now we don't have a t.

We're taking the indefinite integral with respect to-- actually, this is a mistake.

This should be with respect to a.

Let me clean this up.

This should be a da.

If we were taking this with respect to t, then we would treat all of these things as just constants.

But I don't want to confuse you right now.

Let me make it clear.

This is going to be da.

That's what we are integrating or taking the antiderivative with respect to.

So what is this going to be equal to? Well once again, we can rewrite it as the sum of integrals.

This is the indefinite integral of e to the a da, so this one right over here-- a d I'll do it in green-- plus the indefinite integral, or the antiderivative, of 1/a da.

Now, what is the antiderivative of e to the a? Well, we already know a little bit about exponentials.

The derivative with respect to x of e to the x is equal to e to the x.

That's one of the reasons why e in the exponential function in general is so amazing.

And if we just replaced a with x or x with a, you get the derivative with respect to a of e to the a is equal to e to the a.

So the antiderivative here, the derivative of e to the a, the antiderivative is going to be e to the a.

And maybe you can shift it by some type of a constant.

Oh, and let me not forget, I have to put my constant right over here.

I could have a constant factor.

So let me-- always important.

Remember the constant.

So you have a constant factor right over here.

Never forget that.

I almost did.

So once again, over here, what's the antiderivative of e to the a? It is e to the a.

What's the antiderivative of 1/a? Well, we've seen that in the last video.

It is going to be the natural log of the absolute value of a.

And then we want to have the most general antiderivative, so there could be a constant factor out here as well.

And we are done.

We found the antiderivative of both of these expressions.

Khan 8

Let's say that we have capital F of x as being equal to the definite integral from pi to x of cotangent squared of t dt.

And what we're curious about finding is the derivative of this business.

We want to figure out what F prime of x is equal to.

Well this is a direct application of the fundamental theorem of calculus.

This is just going to be the derivative with respect to x of all of this craziness.

So let me just copy and paste that.

So it's just going to be the derivative with respect to that.

And the fundamental theorem of calculus tells us that this is going to be equal to just this function, but it's not going to be a function of t anymore.

It's going to be a function of x.

So it's going to be equal to cotangent squared of x.

And you'll often see problems like this if you go to calculus competitions or things like that and, or maybe certain exams.

And It's like, oh my god, I have to take the antiderivative of all of this business, evaluate it at the different boundaries, and then I got to take the derivative.

No.

You just apply the fundamental theorem of calculus, and it's actually a very straightforward and a very fast thing to do.

Now let's mix it up a little bit.

Let's say that you had the expression the definite integral from pi-- instead of from pi to x, let's say it's from pi to x squared-- and let me write that x squared in a different color just to make it clear what I'm doing-- from pi to x squared of cotangent squared of t dt.

And you wanted to take the derivative of this business.

So you want to take the derivative with respect to x of this business.

How would you do it? Well the recognition here is that this is capital-- capital F of x was defined as this.

Now instead of an x, you have an x squared.

So this is the exact same thing as taking the derivative with respect to x of capital F of-- not x.

That would be this.

Instead, we have capital F of x squared.

Where we had an x here before, we now have an x squared.

You can verify.

If you had capital F of x squared, every place where you saw the x here would be an x squared.

So it would look exactly like this.

And so we just have to apply the chain rule.

So this is going to be equal to the derivative of F with respect to x squared.

And this is just straight out of the chain rule.

It's going to be F prime of x squared times the derivative with respect to x of x squared.

This is the derivative of F with respect to x squared and then times the derivative of x squared with respect to x.

This is just the chain rule right over here.

So what's F prime of x squared-- the derivative of F with respect to x squared? Well, if you evaluate F prime at x squared, instead of just being cotangent squared of x, it's going to be cotangent squared of x squared.

So this part right over here, this business right over here, is going to be cotangent squared of x squared.

So this is the derivative of all of this business with respect to x squared, and then you have to multiply that times the derivative of x squared with respect to x, which is just 2x.

So there you have it.

The derivative of this, all this craziness, is equal to 2x cotangent squared of x squared.

Khan 9

So, our goal in this video is to take the antiderivative of this fairly crazy looking expression.

Or another way of saying it is to find the indefinite integral of this crazy looking expression.

And the key realization right over here is that you, this expression is made up of a bunch of terms.

And the indefinite integral of the entire expression is going to be equal to the indefinite integral of each of the terms.

So this is going to be equal to, we could look at this term right over here and just take the indefinite, take the indefinite integral of that.

x to the 3rd dx.

And then from that we can subtract the indefinite integral of this thing.

So we can say this is, and then minus.

The indefinite integral of 5 times the square root of x d x.

And then we can look at this one right over here.

So then we can say plus the indefinite integral of 18 square root of x.

Square roots of x over x to the third, dx and then finally, and I'm running out of colors here.

Finally, I need more colors in my thing.

We can take the anti derivative of this.

So plus the anti derivative of x to the negative 40th power dx.

So, I've just rewritten this and color coded things.

So, let's take the anti derivative of each of these and you'll see that'll we'll be able to do it.

Using our whatever we wanna call the inverse of the power rule or the anti power rule.

Whatever you might wanna call it.

So lets look at the first one.

So we have, we have, what I'm gonna do is I'm just gonna find the anti derivative without the constant and just add the constant at the end for the sake of this.

So we just make sure we get the most general anti derivative.

So here the exponent is a 3.

So we can increase it by 1.

So it's going to be x to the 4th.

It's gonna be that same purple color.

Or that pink color.

It's going to be x to the 4th.

And we're gonna divide x to the 4th.

So it's x to the 4th over 4 is the antiderivative of x to the 3rd, and you just had this scaling quantity.

The 7 out front.

So we can still just have 7 out front.

So we get 7x to the 4th over 4.

Fair enough.

From that, we're going to subtract the antiderivative of this.

Now, at first, this might not be obvious that this, you could use our inverse power rule or anti-power rule here.

But then you just need to realize that 5 times the principal root of x is the same thing as.

So, this is the same thing as 5 x X to the 1 half power.

And, so, once again, the exponent here is one half, we can increment it by 1.

This is going to be X to the 3 halves.

And then, divide by the incremented exponent.

So, divide by.

Three halves and of course we had this five out front so we still want to have the five out front.

Now this next expression looks even wackier but once again we can simplify a little bit.

This is the same thing.

Let me do it right over here.

This is the same thing as 18 times x to the one half times x to the negative three power.

X to the third in the denominator is the same thing as x to the negative three.

We have the same base, we can just add the exponent so this is going to be equal to 18 times x to the 2 and a half power, and a half power or another way of thinking about it, this is the same thing as 18 times x, 18 times x to the 5 halves power.

Two the 5 halves power.

Did I do that right? Yeah, negative 3, oh sorry, this is negative 2 and a half let me make this very clear and this is going to be the negative 5 half power.

X to the negative 3 is the same thing as x to the negative 6 halves, negative six halves plus 1 half is negative 5 halves.

So once again we just have to increment this exponent.

So negative 5 halves, plus 1 is going to be negative 3 halves.

So you're going to have x, x to the negative 3 halves, and then you divide by what your exponent is when you increment, so divide it by negative, divide it by negative 3 halves.

And then you have the 18 out front.

And we obviously are going to have to simplify this.

And then finally, our exponent in this term, let me not use that purple any more, the exponent, in this term right over here is negative 40, if we increment we get x to the negative 39 power, all of that over negative 39.

And now we can add our constant.

Now we can add our constant C, and all we need to do is simplify all of this craziness.

So the first one is fairly simplified.

We can write it as seven fourths.

X to the 4th.

Now this term right over here is essentially 5 divided by 3 halves, so 5 over three halves is equal 5 times two thirds, which is equal to 10 over 3.

So this thing right over here simplifies to negative 10 over 3X to the three halves.

And then we have all of this craziness.

Now 18 divided by negative three halves.

divided by negative 3 halves is equal to 18 times.

Negative two thirds, which is equal to, well, we can, we can simplify this a little bit.

This is the same thing as 6.

This is the same thing as 6 times negative 2 which is equal to negative 12.

So, this expression right over here, is negative 12 x to the negative 3 halves.

And then finally this one right over here, we can just rewrite it as.

If we want, we could, well, we could just write negative one thirty-ninths x to the negative 39.

Plus, plus C, and we're done.

We found the indefinite integral of all of this craziness.

And I encourage you to take the derivative of this, and you can do it using really just the power rule, to take the derivative of this and verify that it does indeed equal this expression that we took, that we took the anti-derivative of.


text:
namespace {

const FX_CHAR* const g_sHighlightingMode[] = {
    // Must match order of HighlightingMode enum.
    "N", "I", "O", "P", "T"};

}  // namespace

CPDF_FormControl::CPDF_FormControl(CPDF_FormField* pField,
                                   CPDF_Dictionary* pWidgetDict)
    : m_pField(pField),
      m_pWidgetDict(pWidgetDict),
      m_pForm(m_pField->m_pForm) {}

CFX_ByteString CPDF_FormControl::GetOnStateName() const {
  ASSERT(GetType() == CPDF_FormField::CheckBox ||
         GetType() == CPDF_FormField::RadioButton);
  CFX_ByteString csOn;
  CPDF_Dictionary* pAP = m_pWidgetDict->GetDictFor("AP");
  if (!pAP)
    return csOn;

  CPDF_Dictionary* pN = pAP->GetDictFor("N");
  if (!pN)
    return csOn;

  for (const auto& it : *pN) {
    if (it.first != "Off")
      return it.first;
  }
  return CFX_ByteString();
}

void CPDF_FormControl::SetOnStateName(const CFX_ByteString& csOn) {
  ASSERT(GetType() == CPDF_FormField::CheckBox ||
         GetType() == CPDF_FormField::RadioButton);
  CFX_ByteString csValue = csOn;
  if (csValue.IsEmpty())
    csValue = "Yes";
  else if (csValue == "Off")
    csValue = "Yes";

  CFX_ByteString csAS = m_pWidgetDict->GetStringFor("AS", "Off");
  if (csAS != "Off")
    m_pWidgetDict->SetNewFor<CPDF_Name>("AS", csValue);

  CPDF_Dictionary* pAP = m_pWidgetDict->GetDictFor("AP");
  if (!pAP)
    return;

  for (const auto& it : *pAP) {
    CPDF_Object* pObj1 = it.second.get();
    if (!pObj1)
      continue;

    CPDF_Object* pObjDirect1 = pObj1->GetDirect();
    CPDF_Dictionary* pSubDict = pObjDirect1->AsDictionary();
    if (!pSubDict)
      continue;

    auto subdict_it = pSubDict->begin();
    while (subdict_it != pSubDict->end()) {
      const CFX_ByteString& csKey2 = subdict_it->first;
      CPDF_Object* pObj2 = subdict_it->second.get();
      ++subdict_it;
      if (!pObj2)
        continue;
      if (csKey2 != "Off") {
        pSubDict->ReplaceKey(csKey2, csValue);
        break;
      }
    }
  }
}

CFX_ByteString CPDF_FormControl::GetCheckedAPState() {
  ASSERT(GetType() == CPDF_FormField::CheckBox ||
         GetType() == CPDF_FormField::RadioButton);
  CFX_ByteString csOn = GetOnStateName();
  if (GetType() == CPDF_FormField::RadioButton ||
      GetType() == CPDF_FormField::CheckBox) {
    if (ToArray(FPDF_GetFieldAttr(m_pField->m_pDict, "Opt"))) {
      int iIndex = m_pField->GetControlIndex(this);
      csOn.Format("%d", iIndex);
    }
  }
  if (csOn.IsEmpty())
    csOn = "Yes";
  return csOn;
}

CFX_WideString CPDF_FormControl::GetExportValue() const {
  ASSERT(GetType() == CPDF_FormField::CheckBox ||
         GetType() == CPDF_FormField::RadioButton);
  CFX_ByteString csOn = GetOnStateName();
  if (GetType() == CPDF_FormField::RadioButton ||
      GetType() == CPDF_FormField::CheckBox) {
    if (CPDF_Array* pArray =
            ToArray(FPDF_GetFieldAttr(m_pField->m_pDict, "Opt"))) {
      int iIndex = m_pField->GetControlIndex(this);
      csOn = pArray->GetStringAt(iIndex);
    }
  }
  if (csOn.IsEmpty())
    csOn = "Yes";
  return PDF_DecodeText(csOn);
}

bool CPDF_FormControl::IsChecked() const {
  ASSERT(GetType() == CPDF_FormField::CheckBox ||
         GetType() == CPDF_FormField::RadioButton);
  CFX_ByteString csOn = GetOnStateName();
  CFX_ByteString csAS = m_pWidgetDict->GetStringFor("AS");
  return csAS == csOn;
}

bool CPDF_FormControl::IsDefaultChecked() const {
  ASSERT(GetType() == CPDF_FormField::CheckBox ||
         GetType() == CPDF_FormField::RadioButton);
  CPDF_Object* pDV = FPDF_GetFieldAttr(m_pField->m_pDict, "DV");
  if (!pDV)
    return false;

  CFX_ByteString csDV = pDV->GetString();
  CFX_ByteString csOn = GetOnStateName();
  return (csDV == csOn);
}

void CPDF_FormControl::CheckControl(bool bChecked) {
  ASSERT(GetType() == CPDF_FormField::CheckBox ||
         GetType() == CPDF_FormField::RadioButton);
  CFX_ByteString csOn = GetOnStateName();
  CFX_ByteString csOldAS = m_pWidgetDict->GetStringFor("AS", "Off");
  CFX_ByteString csAS = "Off";
  if (bChecked)
    csAS = csOn;
  if (csOldAS == csAS)
    return;
  m_pWidgetDict->SetNewFor<CPDF_Name>("AS", csAS);
}

void CPDF_FormControl::DrawControl(CFX_RenderDevice* pDevice,
                                   CFX_Matrix* pMatrix,
                                   CPDF_Page* pPage,
                                   CPDF_Annot::AppearanceMode mode,
                                   const CPDF_RenderOptions* pOptions) {
  if (m_pWidgetDict->GetIntegerFor("F") & ANNOTFLAG_HIDDEN)
    return;

  CPDF_Stream* pStream = FPDFDOC_GetAnnotAP(m_pWidgetDict, mode);
  if (!pStream)
    return;

  CFX_FloatRect form_bbox = pStream->GetDict()->GetRectFor("BBox");
  CFX_Matrix form_matrix = pStream->GetDict()->GetMatrixFor("Matrix");
  form_matrix.TransformRect(form_bbox);
  CFX_FloatRect arect = m_pWidgetDict->GetRectFor("Rect");
  CFX_Matrix matrix;
  matrix.MatchRect(arect, form_bbox);
  matrix.Concat(*pMatrix);
  CPDF_Form form(m_pField->m_pForm->m_pDocument,
                 m_pField->m_pForm->m_pFormDict->GetDictFor("DR"), pStream);
  form.ParseContent(nullptr, nullptr, nullptr);
  CPDF_RenderContext context(pPage);
  context.AppendLayer(&form, &matrix);
  context.Render(pDevice, pOptions, nullptr);
}

CPDF_FormControl::HighlightingMode CPDF_FormControl::GetHighlightingMode() {
  if (!m_pWidgetDict)
    return Invert;

  CFX_ByteString csH = m_pWidgetDict->GetStringFor("H", "I");
  for (size_t i = 0; i < FX_ArraySize(g_sHighlightingMode); ++i) {
    if (csH == g_sHighlightingMode[i])
      return static_cast<HighlightingMode>(i);
  }
  return Invert;
}

CPDF_ApSettings CPDF_FormControl::GetMK() const {
  return CPDF_ApSettings(m_pWidgetDict ? m_pWidgetDict->GetDictFor("MK")
                                       : nullptr);
}

bool CPDF_FormControl::HasMKEntry(const CFX_ByteString& csEntry) const {
  return GetMK().HasMKEntry(csEntry);
}

int CPDF_FormControl::GetRotation() {
  return GetMK().GetRotation();
}

FX_ARGB CPDF_FormControl::GetColor(int& iColorType,
                                   const CFX_ByteString& csEntry) {
  return GetMK().GetColor(iColorType, csEntry);
}

FX_FLOAT CPDF_FormControl::GetOriginalColor(int index,
                                            const CFX_ByteString& csEntry) {
  return GetMK().GetOriginalColor(index, csEntry);
}

void CPDF_FormControl::GetOriginalColor(int& iColorType,
                                        FX_FLOAT fc[4],
                                        const CFX_ByteString& csEntry) {
  GetMK().GetOriginalColor(iColorType, fc, csEntry);
}

CFX_WideString CPDF_FormControl::GetCaption(const CFX_ByteString& csEntry) {
  return GetMK().GetCaption(csEntry);
}

CPDF_Stream* CPDF_FormControl::GetIcon(const CFX_ByteString& csEntry) {
  return GetMK().GetIcon(csEntry);
}

CPDF_IconFit CPDF_FormControl::GetIconFit() {
  return GetMK().GetIconFit();
}

int CPDF_FormControl::GetTextPosition() {
  return GetMK().GetTextPosition();
}

CPDF_Action CPDF_FormControl::GetAction() {
  if (!m_pWidgetDict)
    return CPDF_Action();

  if (m_pWidgetDict->KeyExist("A"))
    return CPDF_Action(m_pWidgetDict->GetDictFor("A"));

  CPDF_Object* pObj = FPDF_GetFieldAttr(m_pField->m_pDict, "A");
  if (!pObj)
    return CPDF_Action();

  return CPDF_Action(pObj->GetDict());
}

CPDF_AAction CPDF_FormControl::GetAdditionalAction() {
  if (!m_pWidgetDict)
    return CPDF_AAction();

  if (m_pWidgetDict->KeyExist("AA"))
    return CPDF_AAction(m_pWidgetDict->GetDictFor("AA"));
  return m_pField->GetAdditionalAction();
}

CPDF_DefaultAppearance CPDF_FormControl::GetDefaultAppearance() {
  if (!m_pWidgetDict)
    return CPDF_DefaultAppearance();

  if (m_pWidgetDict->KeyExist("DA"))
    return CPDF_DefaultAppearance(m_pWidgetDict->GetStringFor("DA"));

  CPDF_Object* pObj = FPDF_GetFieldAttr(m_pField->m_pDict, "DA");
  if (pObj)
    return CPDF_DefaultAppearance(pObj->GetString());
  return m_pField->m_pForm->GetDefaultAppearance();
}

CPDF_Font* CPDF_FormControl::GetDefaultControlFont() {
  CPDF_DefaultAppearance cDA = GetDefaultAppearance();
  CFX_ByteString csFontNameTag;
  FX_FLOAT fFontSize;
  cDA.GetFont(csFontNameTag, fFontSize);
  if (csFontNameTag.IsEmpty())
    return nullptr;

  CPDF_Object* pObj = FPDF_GetFieldAttr(m_pWidgetDict, "DR");
  if (CPDF_Dictionary* pDict = ToDictionary(pObj)) {
    CPDF_Dictionary* pFonts = pDict->GetDictFor("Font");
    if (pFonts) {
      CPDF_Dictionary* pElement = pFonts->GetDictFor(csFontNameTag);
      if (pElement) {
        CPDF_Font* pFont = m_pField->m_pForm->m_pDocument->LoadFont(pElement);
        if (pFont)
          return pFont;
      }
    }
  }
  if (CPDF_Font* pFormFont = m_pField->m_pForm->GetFormFont(csFontNameTag))
    return pFormFont;

  CPDF_Dictionary* pPageDict = m_pWidgetDict->GetDictFor("P");
  pObj = FPDF_GetFieldAttr(pPageDict, "Resources");
  if (CPDF_Dictionary* pDict = ToDictionary(pObj)) {
    CPDF_Dictionary* pFonts = pDict->GetDictFor("Font");
    if (pFonts) {
      CPDF_Dictionary* pElement = pFonts->GetDictFor(csFontNameTag);
      if (pElement) {
        CPDF_Font* pFont = m_pField->m_pForm->m_pDocument->LoadFont(pElement);
        if (pFont)
          return pFont;
      }
    }
  }
  return nullptr;
}

int CPDF_FormControl::GetControlAlignment() {
  if (!m_pWidgetDict)
    return 0;
  if (m_pWidgetDict->KeyExist("Q"))
    return m_pWidgetDict->GetIntegerFor("Q", 0);

  CPDF_Object* pObj = FPDF_GetFieldAttr(m_pField->m_pDict, "Q");
  if (pObj)
    return pObj->GetInteger();
  return m_pField->m_pForm->GetFormAlignment();
}

redpajama_set_name: RedPajamaGithub


text:
export ARDUINO_ESP32_PATH="$ARDUINO_USR_PATH/hardware/espressif/esp32"
if [ ! -d "$ARDUINO_ESP32_PATH" ]; then
	echo "Installing ESP32 Arduino Core ..."
	script_init_path="$PWD"
	mkdir -p "$ARDUINO_USR_PATH/hardware/espressif"
	cd "$ARDUINO_USR_PATH/hardware/espressif"

	echo "Installing Python Serial ..."
	pip install pyserial > /dev/null

	if [ "$OS_IS_WINDOWS" == "1" ]; then
		echo "Installing Python Requests ..."
		pip install requests > /dev/null
	fi

	if [ "$GITHUB_REPOSITORY" == "espressif/arduino-esp32" ];  then
		echo "Linking Core..."
		ln -s $GITHUB_WORKSPACE esp32
	else
		echo "Cloning Core Repository..."
		git clone https://github.com/espressif/arduino-esp32.git esp32 > /dev/null 2>&1
	fi

	echo "Updating Submodules ..."
	cd esp32
	git submodule update --init --recursive > /dev/null 2>&1

	echo "Installing Platform Tools ..."
	cd tools && python get.py
	cd $script_init_path

	echo "ESP32 Arduino has been installed in '$ARDUINO_ESP32_PATH'"
	echo ""
fi


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
     Copyright (C) 2021 The Android Open Source Project

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="top"
    android:layout_marginTop="?attr/actionBarSize"
    tools:context=".ScannerFragment">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/scan_recyclerview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>


text:
module QA
  module Page
    module Admin
      module Settings
        class General < Page::Base
          include QA::Page::Settings::Common

          view 'app/views/admin/application_settings/general.html.haml' do
            element :account_and_limit_settings
          end

          def expand_account_and_limit(&block)
            expand_section(:account_and_limit_settings) do
              Component::AccountAndLimit.perform(&block)
            end
          end
        end
      end
    end
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    style="@style/TopNavigationEntry">

</TextView>


text:
declare interface JQBlockUIOptions {
    useTimeout?: boolean;
}


text:
void GraphicsGroup::draw(DisplayBuffer & buffer)
{
	if (!_visibility) return;
	buffer.setOffset(_x, _y);
	for (const auto& g : _graphics) {
		g.second->draw(buffer);
	}
	buffer.setOffset(0,0);
}
void GraphicsGroup::update()
{
	for (const auto& g : _graphics) {
		g.second->update();
	}
}
void GraphicsGroup::add(std::shared_ptr<Graphic>& graphic, int x, int y, int layer, std::string tag)
{
	graphic->setX(x);
	graphic->setY(y);
	graphic->setTag(tag);
	_graphics.insert({ layer,std::move(graphic) });
}

void GraphicsGroup::add(std::shared_ptr<Graphic>&& graphic, int x, int y, int layer, std::string tag)
{
	graphic->setX(x);
	graphic->setY(y);
	graphic->setTag(tag);
	_graphics.insert({ layer,std::move(graphic) });
}

void GraphicsGroup::bind(Scene* s) {
	_parentScene = s;

	for (const auto& g : _graphics) {
		g.second->bind(s);
	}
}

std::shared_ptr<Graphic> GraphicsGroup::getGraphicByTag(const std::string& tag)
{
	for (const auto& g : _graphics) {
		if (g.second->getTag() == tag) return g.second;
	}
	return nullptr;
}


text:
function pid_out = mofi_log_pid
%
% pid = mofi_log_pid
%
% This function writes MATLAB's PID (Process ID) to the STD ERR file stream.
%
%
% 2013-09-16, MOFI, Init version.
%

% Get the process ID
pid   = feature('getpid');

% Print the PID
stderr = 2;
fprintf(stderr, 'PID: %i\n', pid);

% set the output
if nargout > 0
    pid_out = pid;
end


text:
#import "../AmazonServiceRequestConfig.h"

/**
 * Delete Volume Request
 *
 * \ingroup EC2
 */

@interface EC2DeleteVolumeRequest:AmazonServiceRequestConfig

{
    NSString *volumeId;
}

/**
 * The ID of the EBS volume to delete.
 */
@property (nonatomic, retain) NSString *volumeId;

/**
 * Default constructor for a new DeleteVolumeRequest object.  Callers should use the
 * property methods to initialize this object after creating it.
 */
-(id)init;

/**
 * Constructs a new DeleteVolumeRequest object.
 * Callers should use properties to initialize any additional object members.
 *
 * @param theVolumeId The ID of the EBS volume to delete.
 */
-(id)initWithVolumeId:(NSString *)theVolumeId;

/**
 * Returns a string representation of this object; useful for testing and
 * debugging.
 *
 * @return A string representation of this object.
 */
-(NSString *)description;

@end


text:
Geolocation = (function() {

  var get = function(element) {
    var missing = function() {element.innerHTML = "MISSING.";};
    var error   = function() {element.innerHTML = "ERROR!";   };

    if (!("geolocation" in navigator)) {
      return missing();
    }

    navigator.geolocation.getCurrentPosition(function(pos) {
      element.innerHTML = "
" +
        pos.coords.latitude.toString()  + "
" +
        pos.coords.longitude.toString() + "
";

      var img = new Image();
      img.src = "https://maps.googleapis.com/maps/api/staticmap?center=" +
        pos.coords.latitude  + "," +
        pos.coords.longitude + "&zoom=13&size=300x300&sensor=false";

      element.appendChild(img);
    }, error);
  };

  // Public interface:
  return {get: get};
})();


text:
char *build_get_query(char* path, char* protocol,char* host){
	// template used to build the query
	char *tpl= "GET %s %s\r\nHost: %s\r\n\r\n";
	// length of the query string
	int query_len;
	// the query string itself
	char* query;
	// -6 to account for %s in template
	query_len= strlen(tpl)-6+strlen(host)+strlen(path)+strlen(protocol);
	// allocate memory and clean it
	query = (char *)malloc(query_len);
	memset(query, 0, query_len);

	// build query from template and return it
	sprintf(query, tpl, path, protocol, host);
	return query;
}

int send_query(int sockfd, char* query, char* response) {
	int sent=0, write_res, size=strlen(query), res;

	while (sent<strlen(query)){
		// FIXME:
		// commenting the import of unistd makes this write call accept any number
		// of args, and still compiles fine. Understand why....
		res = write(sockfd, query+sent, size-sent);
		if (res == -1) {
			printf("Can't write\n");
			return -1;
		}
		sent+=res;
	}
	return sent;
}

int print_response(int sockfd){
	int bufsize=1024, read, total_read=0;
	char buf[bufsize];
	memset(buf, 0, bufsize);

	while ( read =recv(sockfd, buf, bufsize, 0)> 0){
		printf("%s",buf);
		memset(buf, 0, read);
		total_read+=read;
	}
}

int main(void){
	// rv: getaddrinfo result code
	int sockfd, portno, rv;
	struct sockaddr_in server;
	struct hostent *host;

	// hints: indicate which type of resolution we want
	// servinfo: info received from getaddrinfo call
	// p : used in loop
	struct addrinfo hints, *servinfo, *p;

	// GET query and response
	char* query, *response;
	int res;

	// clean memory
	memset(&hints, 0, sizeof hints);

	// fill in hints
	hints.ai_family = AF_UNSPEC; // AF_INET6 forces IPv6
	hints.ai_socktype = SOCK_STREAM;

	// host resolution
	if ((rv = getaddrinfo("www.multipath-tcp.org", "80", &hints, &servinfo)) != 0) {
		fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
		exit(1);
	}

	for(p = servinfo; p != NULL; p = p->ai_next) {
		// create socket
		if ((sockfd = socket(p->ai_family, p->ai_socktype,
						p->ai_protocol)) == -1) {
			perror("socket");
			continue;
		}

		// connect
		if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
			close(sockfd);
			perror("connect");
			continue;
		}

		break; // if we get here, we must have connected successfully
	}

	freeaddrinfo(servinfo);

	if (p == NULL) {
		// looped off the end of the list with no connection
		fprintf(stderr, "failed to connect\n");
		exit(2);
	}

	// FIXME: specify inexisting protocol to test
	query = build_get_query("/","HTTP/1.0","www.multipath-tcp.org");
	fprintf(stderr, "\nQuery: \n%s\n", query);
	res = send_query(sockfd, query, response);

	if ( res == strlen(query) ) {
		// query sent in full, read response
		fprintf(stderr,"Sent %d bytes\n", res);
		print_response(sockfd);
	}

	int val, len;
	getsockopt(sockfd, IPPROTO_TCP, 26, &val, &len);
	fprintf(stderr,"MPTCP_ENABLED = %d\n", val);
	getsockopt(sockfd, IPPROTO_TCP, TCP_USER_TIMEOUT, &val, &len);
	fprintf(stderr,"TCP_USER_TIMEOUT = %d\n", val);
	getsockopt(sockfd, IPPROTO_TCP, TCP_MAXSEG, &val, &len);
	fprintf(stderr,"TCP_MAXSEG = %d\n", val);
	getsockopt(sockfd, IPPROTO_TCP, TCP_TIMESTAMP, &val, &len);
	fprintf(stderr,"TCP_TIMESTAMP = %d\n", val);

	free(query);
	close(sockfd);

	return 0;

}


text:
package com.xpeppers.phonebook.model;

import java.io.Serializable;

public class Contact implements Serializable {

	/**
	 *
	 */
	private static final long serialVersionUID = -4902062694160973038L;

	// private variables
	int _id;
	String _name;
	String _surname;
	String _phone_number;

	// Empty constructor
	public Contact() {

	}

	// constructor
	public Contact(int id, String name, String surname, String _phone_number) {
		this._id = id;
		this._name = name;
		this._surname = surname;
		this._phone_number = _phone_number;
	}

	// constructor
	public Contact(String name, String surname, String _phone_number) {
		this._name = name;
		this._surname = surname;
		this._phone_number = _phone_number;
	}

	// getting ID
	public int getID() {
		return this._id;
	}

	// setting id
	public void setID(int id) {
		this._id = id;
	}

	// getting name
	public String getName() {
		return this._name;
	}

	// setting name
	public void setName(String name) {
		this._name = name;
	}

	// getting surname
	public String getSurname() {
		return this._surname;
	}

	// setting surname
	public void setSurname(String surname) {
		this._surname = surname;
	}

	// getting phone number
	public String getPhoneNumber() {
		return this._phone_number;
	}

	// setting phone number
	public void setPhoneNumber(String phone_number) {
		this._phone_number = phone_number;
	}
}


text:
//
//  KMContributionCollectionViewCell.m
//  TheMovieDB
//
//  Created by Kevin Mindeguia on 04/02/2014.
//  Copyright (c) 2014 iKode Ltd. All rights reserved.
//

#import "KMSimilarMoviesCollectionViewCell.h"

@implementation KMSimilarMoviesCollectionViewCell

#pragma mark -
#pragma mark Cell Init Methods

+ (KMSimilarMoviesCollectionViewCell*) similarMoviesCollectionViewCell
{
    KMSimilarMoviesCollectionViewCell * cell = [[[NSBundle mainBundle] loadNibNamed:@"KMSimilarMoviesCollectionViewCell" owner:self options:nil] objectAtIndex:0];

    return cell;
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

#pragma mark -
#pragma mark View Lifecycle

- (void)awakeFromNib
{
    self.cellImageView.layer.cornerRadius = self.cellImageView.frame.size.width/2;
    self.cellImageView.layer.masksToBounds = YES;

    self.cellBackgroundView.layer.cornerRadius = self.cellBackgroundView.frame.size.width/2;
    self.cellBackgroundView.layer.masksToBounds = YES;
    self.cellBackgroundView.layer.borderColor =  [UIColor colorWithRed:0/255.0 green:161/225.0 blue:0/255.0 alpha:1.0].CGColor;
    self.cellBackgroundView.layer.borderWidth = 1.0f;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

@end


text:
<?php

declare(strict_types=1);

/**
 * This file is part of Narrowspark Framework.
 *
 * (c) Daniel Bannert <d.bannert@anolilab.de>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Viserio\Contract\Translation;

use InvalidArgumentException;

interface Translator
{
    public const MESSAGE_DEFINED = 0;
    public const MESSAGE_MISSING = 1;
    public const MESSAGE_EQUALS_FALLBACK = 2;

    /**
     * Gets the string dictating the default language to translate into. (e.g. 'en').
     *
     * @return string
     */
    public function getLocale(): string;

    /**
     * Sets the string dictating the default language to translate into. (e.g. 'en').
     *
     * @param string $locale A string representing the default language to translate into. (e.g. 'en').
     *
     * @throws InvalidArgumentException If the locale contains invalid characters
     *
     * @return self
     */
    public function setLocale(string $locale): self;

    /**
     * Get the message selector instance.
     *
     * @return \Viserio\Contract\Translation\MessageFormatter
     */
    public function getFormatter(): MessageFormatter;

    /**
     * Get the message catalogue.
     *
     * @return \Viserio\Contract\Translation\MessageCatalogue
     */
    public function getCatalogue(): MessageCatalogue;

    /**
     * Translates the given message.
     *
     * @param string $id         The message id
     * @param array  $parameters An array of parameters for the message
     * @param string $domain     The domain for the message or null to use the default
     *
     * @throws InvalidArgumentException If the locale contains invalid characters
     *
     * @return string The translated string
     */
    public function trans(string $id, array $parameters = [], string $domain = 'messages'): string;

    /**
     * Add helper.
     *
     * @param string   $name
     * @param callable $helper
     *
     * @return self
     */
    public function addHelper(string $name, callable $helper): self;

    /**
     * Add filter.
     *
     * @param callable $filter
     *
     * @return self
     */
    public function addFilter(callable $filter): self;
}


text:
'use strict';

/**
 * @ngdoc service
 * @name webClientSideApp.user
 * @description
 * # user
 * Service in the webClientSideApp.
 */
angular.module('webClientSideApp')
  .factory('user', function ($http, $q, $rootScope, $notification, $location, $cookies, config) {
    // AngularJS will instantiate a singleton by calling "new" on this function
    var decision = false;

    return {
      create: (function (user, redirect) {
        return $http.post(config.apiURL + config.users, user)
          .success(function (response) {
            $notification.success("Succès", "L'utilisateur " + user.username + " a bien été créé.");
            $location.path(redirect);
          })
          .error(function (response) {
            $notification.error(
              "Erreur",
              "L'utilisateur " + user.username + " n'a pas été créé (" + response.message + ")."
            );
          });

      }),
      login: function (user, redirect) {
        return $http.post(config.apiURL + config.users + config.users_auth, user)
          .success(function (response) {
            $notification.success("Success", "You are now connected.");
            $cookies.putObject('user', {
              id: response._id,
              username: response.username,
              email: response.email
            });
            $rootScope.isLogged = true;
            $location.path(redirect);
          })
          .error(function (response) {
            $notification.error(
              "Error",
              "Cannot authenticate user " + user.username + " (" + response.message + ")."
            );
          });
      },
      updateUser : function(user){
        return $http.put(config.apiURL + config.users +user.id, user)

      }
      //checkUser : (function(user,myPedals){
      //
      //  var deferred = $q.defer();
      //
      //    $http.post("http://localhost:3000/api/users/auth", user)
      //        .success(function(data) {
      //          $notification.success("login", "connected successfuly");
      //          $rootScope.logged = true;
      //
      //          user._id = data._id;
      //          user.pedals = data.pedals;
      //          for (var i=0 ; i < data.pedals.length; i++){
      //              $http.get("http://localhost:3000/api/pedals/"+data.pedals[i])
      //                .then(function(response){
      //                  myPedals.push(response.data);
      //
      //                });
      //          }
      //        //  myPedals.push(data.login.pedals);
      //          deferred.resolve(data);
      //
      //
      //
      //        })
      //        .error(function() {
      //          decision = false;
      //          $notification.error("login", "refused");
      //          deferred.reject(false);
      //
      //        });
      //
      //
      //
      //  return deferred.promise;
      //}),
      //turnLogged : (function(){
      //  var deferred = $q.defer();
      //  return decision;
      //})

    };
  });


text:
const bodyParser = require('body-parser');
const cors = require('cors');
const express = require('express');
const jwt = require('jsonwebtoken');
const expressJwt = require('express-jwt');
const passport = require('passport');

const beginware = require('./middlewares/beginware');
const errorHandler = require('./middlewares/errorHandler');
const initRouters = require('./utils/initRouters');
const setDevDependencies = require('./utils/setDevDependencies');
const mainStrategy = require('./strategies/main');

module.exports = class App {
  constructor(port, db, config, jsonConfig) {
    this.port = port;
    this.db = db;
    this.config = config;
    this.jsonConfig = jsonConfig;
    this.server = null;
  }

  init() {
    const app = express();

    // set dev dependencies if the environment is develop
    if (this.config.APP_ENV !== 'prod') {
      setDevDependencies(app);
    }

    /**
     * JWT used for the authentication
     */
    app.set('jwt', jwt);
    app.set('jwtKey', this.config.JWT_KEY);
    app.set('jwtKeyRefresh', this.config.JWT_REFRESH);
    app.set('jwtExpire', this.config.JWT_EXPIRE);
    app.use(expressJwt({ secret: this.config.JWT_KEY }).unless(this.jsonConfig.jwtPath));
    app.use(passport.initialize());

    // enable cors for all requests
    app.use(cors());

    // set bodyParser for JSON
    // prettier-ignore
    app.use(bodyParser.urlencoded({
      extended: true,
    }));
    app.use(bodyParser.json());

    // set routes
    app.use(beginware(this.db));
    initRouters(app);

    // set error handler
    app.use(errorHandler);

    // set the passport local strategy
    passport.use(mainStrategy.local(app, passport, this.db));

    this.server = app.listen(this.port, () => {
      console.log(`\x1b[32mExpress application is listening on port ${this.port} ...\x1b[0m`);
    });
  }
};


text:
#!/usr/bin/env node

'use strict'

const
  allowedOptions = ['--config', '--native-runner', '--errors-only', '--omit-traces', '--error-reports-only', '--omit-report-traces', '--help']

let
  utils = require('./../utils'),
  args = utils.serverArgs(allowedOptions, help),
  srvUtils = require('./utils')

function help() {
  utils.serverHelp()
}

utils.handleHelp(args, help)

let
  bodyParser = require('body-parser'),
  express = require('express'),
  cbtr = express(),
  Log = require('./../../lib/core/log').Log,
  log = new Log('Server')

const
  settings = require('./settings')(args.config)

log.debug('args', args)

cbtr.use(bodyParser.json({limit: settings.limit}))
cbtr.use(bodyParser.urlencoded({limit: settings.limit, extended: true }))

if(!args['native-runner']) {
  /* eslint-disable global-require */
  cbtr.use('/runs', require('./runs'))
  /* eslint-enable global-require */
}
else {
  /* eslint-disable global-require */
  cbtr.use('/', require('./runners/native'))
  /* eslint-enable global-require */
}

srvUtils.defaults(cbtr)

log.debug('listening on %s:%s', settings.server.host, settings.server.port)

cbtr.listen(settings.server.port, settings.server.host)