text:
This is part 2 in a 3 part series about how I’ve decided to move teaching projectile motion from one of the earliest units I teach, until after my students have a thorough grounding in vectors, Newton’s laws and momentum. In part 1, I discussed the problem I see with teaching projectile motion as one of the earliest units in physics (before Newton’s Laws).

## Introducing projectile motion with Angry Birds

As I wrote previously, projectile motion really is a wonderful topic to study for students. The ideas motion of footballs, golf balls, and astronauts all, on a fundamental level, are controlled by the same single force, and their motion evolves in the same predictable way is very powerful. Matt Ridley recently wrote a beautiful article exploring how this motion, and or passion for games involving predicting where a projectile with a parabolic trajectory will land is deeply tied to our own evolution. This article served as a wonderful motivator for why my students should study projectile motion.

Inspired by Rhett Allain and his exploration of Angry Birds, I thought the best way to study projectile motion would be to begin by checking out the laws of physics on Angry Bird world.

a vector construction of change in velocity for a small part of the angry bird's trajectory;

This was enough for students to catch on and realize there must be a downward force (they wondered if it was the gravitational force) in the Angry Bird world, but since it was a pretty qualitative sketch, you couldn’t conclude for sure that there is no air resistance on AB world. You’d need to do something more quantitative to see that.

So how can we get more quantitative? My students instantly thought of Video Physics, which is a wonderful app, but I wanted to show them something even more powerful, Tracker Video Analysis. By far the most tedious part of any video analysis is having to click and mark the object of interest in individual frames. Doing this for much more than a few seconds turns into a true exercise in tedium. Enter Tracker, and it’s incredible autotracker. Here’s another wonderful chance to talk about computational thinking.

me: do you find it tedious to mark the location of the angry bird on 100 different frames?
s: yes!
me: Why?
s: because it’s dull, mindless and repetitive!
me: Dull, mindless and repetitive—that’s like the “beetlejuice, beetlejuice beetlejuice” of computers. A computer should be able to do this for you, and you need recognize these moments and call for computer reinforcements.
s: So, you can essentially say, hey computer find the angry bird in every frame and mark it?
me: yes. When would this fail?
s: When it’s hard to tell the angry bird from it’s surroundings?
me: when would that be?
s: when there isn’t enough contrast between the bird and the surroundings? Or when the bird changes shape?
me: bingo.

And so here’s the autotracker in action. IMO, this feature takes video analysis from the “fun and useful for people who know what they’re doing”, to “everybody should give this a whirl” category.

When I then showed them the projection of the the “trajectory of the angry brid, students were puzzled, but pretty quickly someone realized that the background is moving, and we need to account for that in order to properly track the bird’s motion.

because the background moves in the film, the trajectory of the bird recorded by tracker isn't the actual trajectory.

So we need something that stands still, and is visible for the whole time to serve as an origin. The pig will do nicely. Autotracker again, and we can plot the position of the bird relative to the pig.

My students really don’t jump for equations nearly as much as students I taught in previous years before I used the modeling curriculum. Instead, they think of models—whole collections of ideas (diagrams, graphs, equations and explanations) that can be used to to explain a phenomena. This really is a huge shift, and it gives my students much more power over thinking about physical situations and problem solving.

I decide to put this to the test by having them look at some data. I ask the students what to look at and they say the horizontal
position. Here we go:

The horizontal position of the Angry Bird, relative to the green pig.

What does this look like? What models accurately describe this motion? My students easily see this is a case of constant velocity (CVPM), and that the net force in the horizontal direction must be zero (BFPM). I then ask what this tells us about air resistance in the Angry Birds’ world, and my students see that it must mean the angry birds’s world has no drag forces. Nice!

We then switch over to looking at the vertical motion. Starting with the y position:

The y position of the bird as a function of time.

My students see automatically that since the slope is not constant, the y-velocity must be changing. So we look at the y-velocity:

The y-veloctiy of the bird plotted against time.

Here students can see that the velocity graph shows constant accleration (CAPM), and this must mean the net force on the birds are constant and not zero. Could this be the gravitational force? We look at the evidence:

• The force is only vertical. Check.
• The force is constant. Check.
• The force causes an acceleration of $9.8 \frac{\textrm{m}}{\textrm{s}^2}$. Hmm our acceleration isn’t this value, instead it is $-200$ and I pause to see what units students can come up with. Pretty soon they see that the acceleration is 200 pixels per second for every second. How can we equate this to something in the real world? Well we can start by following Rhett’s lead and scaling the world by the height of the slingshot. If we do this using the ruler tool, we find 200 px=1.6 slighshots.

Now if we make the assumption that the angry birds world is the same as ours, it must be that:

$\begin{array}{rcl} a_{angry\;birds}&=&g\\ so:\\ 1.6\; \frac{\textrm{slingshots}}{\textrm{s}^2}&=&9.8\frac{\textrm{m}}{\textrm{s}^2}\\ 1\; \textrm{slingshot} &=&6.1 \textrm{m} \end{array}$

Like Rhett, we found that the slingshot, and thus the angry birds are ridiculously huge. Which made my students ask, “What if the angry birds live on a really small planet, where they are normal sized, but the gravitational force is much less. Could this work?” Yes! I exclaim. (Note that they asked this without having studied the gravitational force in any detail, yet). We could study that too (marks idea journal: Angry Birds on Phobos).

In about 30 minutes of discussion, my students “discovered” the two big ideas of projectile motion: the horizontal component of motion is constant velocity, while the vertical component is constant acceleration. Both of these ideas are so well understood that my students were able to say they already thought they could solve most problems with these concepts. I told my students we’d take some time to practice, but essentially, in terms of understanding new ideas, they are ready to take a test on that unit now.

The key follow up that we didn’t have time to do just then would be to film and track the motion ball of a soccer ball thrown on a field or in our classroom and see if it matched the motion of the Angry Bird.

1. February 18, 2011 11:12 am

This is awesome…even though I remain a tad perplexed as to why angry birds is as popular as it is. While I can’t even remember the name, I think I personally prefer the old-school version (Tanks?) from 2 decades ago. Anyway, I digress. One question about your post. Now I’m no physics expert, but…

“My students easily see this is a case of constant velocity (CVPM), and that the net force in the horizontal direction must be zero (BFPM). I then ask what this tells us about air resistance in the Angry Birds’ world, and my students see that it must mean the angry birds’s world has drag forces.”

Wouldn’t a constant horizontal velocity imply NO drag force?

• February 18, 2011 11:19 am

Ooops, typo. It clearly means there are No drag forces, since any drag forces would be opposite the velocity, and since the velocity has a horizontal component, if there were a drag force, there would need to be a non zero horizontal acceleration. Since the horizontal acceleration is zero, the net horizontal force is zero, and since air is the only thing, presumably, that could be exerting a horizontal force, there are no drag forces. I fixed the post.

Be sure to check out the article I linked to by Matt Ridley from the WSJ, it really is a neat piece about how our fascination with predicting where parabolic trajectories will land is deeply connected with our evolution.

February 28, 2011 11:41 am

I think you are thinking of “Artillery”,and it was 30 years ago we were playing on our Commodore PETS. 🙂

2. February 18, 2011 1:53 pm

Wonderful post, can’t wait to share it.

I’m having my students do some tracking this semester for their advanced lab projects and it was fun to watch how they eventually decided to look into tracking software. They started by hand and got sick of it. Now they know more about the tracking software than I do!

• February 18, 2011 1:58 pm

I’ve decided that tracking anything for more than about 30 frames really is too much of a PITA to ask students to do it. They lose all sense of the value of the exercise. But autotracker makes this go away, and the angry birds world is built for autotracker.

• February 18, 2011 2:02 pm

I couldn’t agree more. What I like about my students is they find these cool solutions without asking me.

3. July 26, 2011 10:57 am

Wow Thanks for this physics look at AB. I’m currently working on an Algebra II perspective, noting the properties of parabolas. The program math teachers are using is called GeoGebra. It’s also free and there are wonderful tutorials on YouTube. Good luck to all educators using Angry Birds in their classroom. And let’s keep our fingers crossed it doesn’t go out of fad too soon.

• July 27, 2011 1:34 am

Geogebra is great, and I’ve used it to do a lot of work to analyze photos and show vector constructions. I do think Angry Birds is probably on the downward slope as a fad. Tiny Wings had basically taken over for my students by the end of the year, and there was also a Cut the Rope craze—and that’s great, because all of these games can be studied in a very similar way.

4. November 3, 2011 8:24 pm

This may be a stupid question, but how did you get the video of angry birds into Tracker? I can do it as a screen shot after the fact.

• November 3, 2011 8:27 pm

I simply did a screen recording of the game. On a mac, you can do this with quicktime.


text:
EC 101A MT1

Introduction

I’m taking these notes for the 101A midterm on Thursday. I did not go to lecture, so these may not reflect the content on the test. The notes are based on the 12th edition of Microeconomic Theory by Nicholson and Snyder. You may or may not find a copy of that textbook here.

Chapter 1

The ceteris paribus assumption restricts the forces at play. In economics, controlled experiments are usually impossible to conduct, so statistical methods are used to control for other factors.

Factors that are outside of a decisionmaker’s control, such as prices, are called exogenous variables. Factors within their control, such as quantity bought, are called endogenous variables. Often, we want to study the effect of changing an exogenous variable.

Economic actors are assumed to be optimizers. It helps to create solvable models and the assumption has some empirical validity.

Economists disagree over the positive-normative distinction. Some economists believe in pure positive analysis, where economics should only describe events. Others believe that economics is inevitably laden with views on ethics, morality, and fairness.

Originally, economists like Adam Smith struggled with the water-diamond paradox. Water, imminently useful, was cheap. Diamonds, which had little practical use, were expensive. The marginal revolution resolved this paradox. Prices reflect the marginal evaluations of demanders and producers. Water is cheap because it has little marginal value and a low cost of production. Diamonds are expensive because they have high marginal value and a high cost of production.

The production possibility frontier is models tradeoffs between two goods. Because of scarcity, producing good A imposes an opportunity cost in terms of good B.

Modern developments include mathematical foundations sophisticated models of markets, incorporation of uncertainty and information, and the study of behavioral economics. Computers now enable researchers to leverage large amounts of real world data to test models.

Chapter 2

To maximize a function $$f$$, we must have $$f'(x^*) = 0$$ and $$f''(x^*) < 0$$.

Elasticity between two goods $$x$$ and $$y$$ is defined as $$e_{y, x} = \frac{\frac{\delta y}{y}}{\frac{\delta x}{x}} = \frac{dy(x)}{dx} \frac{x}{y}$$.

Implicit functions reveal tradeoffs between variables. For example, suppose we have $$f(x_1, x_2) = 0$$. We can express $$x_2$$ in terms of $$x_1$$ so that $$x_2 = g(x_1)$$. Differentiating with respect to $$x_1$$ yields $$\frac{dg(x_1)}{dx_1} = -\frac{f_1}{f_2}$$.

Comparative statics denotes the effect of an exogenous variable $$a$$ on an endogenous variable $$x$$. In other words, $$\frac{dx(a)}{da} = - \frac{\frac{df}{da}}{\frac{df}{dx}}$$.

To maximize a function of multiple variables, the partials with respect to each variable must equal 0 and the second partials must be negative.

To assess the impact of an exogenous variable $$a$$ on $$y(x)$$, we could solve for $$x^*$$ in terms of $$a$$ and compute $$y(x^*)$$. However, we could also apply the Envelope Theorem and immediately conclude that $$\frac{dy^*}{da} = x^*(a)$$. The theorem also holds for the many variable case, so that $$\frac{dy^*}{da} = \frac{df}{da}\|_{x_i = x_i^*(a)}$$.

Langrange multipliers are used for constrained optimization. To maximize $$y=f(x_1, x_2,..., x_n)$$ subject to constraint $$g(x_1, x_2, ..., x_n) = 0$$, set up the Langrangian $$\mathcal{L} = f + \lambda g$$. The conditions are $$\frac{\delta \mathcal{L}}{\delta x_i} = f_i + \lambda g_i = 0$$ for each good $x_i$ and $$g = 0$$.

The multiplier can be interpreted as the benefit-cost ratio, i.e. $$\lambda = \frac{mb}{mc}$$ for all $$x_i$$. It means that if the constraint were slightly relaxed, it wouldn’t matter which $$x_i$$ were increased.

The envelope theorem means $$\frac{dy^*}{da} = \frac{d \mathcal{L}}{da} (x_1^*,...,x_n^*; a)$$.

Often, we wish to deploy inequality constraints such a $$g(x_1, x_2) \geq 0$$ or $$x_1 \geq 0$$. We can use slack variables, such as $$g(x_1, x_2) - a^2 = 0$$ and $$x_1 - b^2 = 0$$. Substituting, we introduce the additional first-order conditions $$\frac{d\mathcal{L}}{da} = -2a\lambda_1$$ and $$\frac{d\mathcal{L}}{d\lambda_1} =g(x_1, x_2) - a^2 = 0$$.

Chapter 3

Preference relations have three properties. First, completeness. For two options A and B, it must be the case that either A is preferred to B, B is preferred to A, or that they are equally attractive. Second is transitivity. If A is preferred to B and B is preferred to C, then A is preferred to C. Third is continuity. If A is preferred to B, then options “close enough” to A are also preferred to B.

Utility is only defined as a monotonic transformation. We can’t ask “how much more is A preferred to B?” because there isn’t a unique answer. One consequence is that utility can’t be compared across individuals. Ceteris paribus is in effect: when utility is specified as a function of goods, then it is assumed that all other factors are held constant. A utility function of goods takes the form:

$U(x_1, x_2, ..., x_n)$

Indifference curves represent all of the combinations of goods with a given utility $$U_1$$. The slope of the indifference curves indicates the trade someone is willing to make between goods. Indifference curves never intersect. Otherwise, the axioms of transitivity suggest produce a contradiction.

Goods face diminishing marginal utility, since people do not want too much of any one good. A diminishing MRS produces a convex indifferent curve.

There are several key utility functions. One common function is Cobb-Douglas, where $$U(x, y) = x^\alpha y^\beta$$, often normalized to $$U(x, y) = x^\alpha y^{1-\alpha}$$.

Linear indifference curves are generated by $$U(x, y) = \alpha x + \beta y$$. These denote perfect substitutes, since MRS is constant. An example would be indifference towards where to buy gasoline.

Perfect complements denote pairs of goods that “go together,” like coffee and cream. In the extreme case, $$U(x, y) = \min (\alpha x, \beta y)$$. The ratio of goods consumed is given by $$\frac{y}{x} = \frac{\alpha}{\beta}$$.

The Constant Elasticity of Substitution (CES) function takes the form of $$U(x, y) = [x^\alpha + y^\alpha]^{\frac{1}{\alpha}}$$, and it incorporates each of the previous utility functions. As $$\alpha \to 0$$, it approaches Cobb-Douglas. As $$\alpha \to -\infty$$, it approach perfect complements.

When the utility function takes in many goods, the MRS between two goods is

$MRS = -\frac{dx_2}{dx_1}|_{U(x_1 x_2, ..., x_n) = k} = \frac{U_{x_1}(x_1, x_2,..., x_n)}{U_{x_2}(x_1, x_2, ..., x_n)}$

Chapter 4

If someone faces a budget constraint $$p_xx+p_yy \leq I$$, then their possible combinations of goods is bounded by a triangle with slope $$-\frac{p_x}{p_y}$$. The first order conditions is that the slope of the indifference curves equals the slope of the indifference curve, i.e. that:

$\frac{-p_x}{p_y} = \frac{dy}{dx}|_{U = constant}$

Tangency is only a sufficient condition when the MRS is diminishing, which guarantees that the utility function is quasi-concave. Often, there can be a corner solution, e.g. $$x = x^*$$ and $$y = 0$$, which we must check separately.

In the $$n$$ good case, we have $$\mathcal{L} = U(x_1, x_2,..., x_n) + \lambda(I - p_1x_1 - p_2x_2 - ... -p_nx_n)$$. The first order conditions dictate that $$MRS(x_i for x_j) = \frac{dU/dx_i}{dU/dx_j} \frac{p_i}{p_j}$$. Here, $$\lambda$$ represents the marginal utility per extra dollar of income, which is constant across goods.

To account for corner solutions, we consider the case where $$\frac{d\mathcal{L}}{dx_i} = \frac{dU}{dx_i} - \lambda p_i \leq 0$$, where if the the marginal utility is less than the basket-wide marginal utility per income, then none of that good is consumed, i.e. $$x_i = 0$$.

Since demand functions dictate the consumption of goods such that $$x^* = x(p_1, p_2, ..., p_n, I)$$, utility can be rewritten as a function of exogenous variables such that $$U = V(p_1, p_2, ..., p_n, I)$$. Indirect utility allows us to assess the effect of a tax on one good. The lump sum principle states that for the same amount of revenue, an income tax will depress utility less than a tax imposed on one good.

Expenditures minimization involves an expenditure function $$E = p_1x_1 + p_2x_2 +...+p_nx_n$$ with constraint $$\bar{U} = U(x_1, x_2, ..., x_n)$$. Utility maximization with a budget constraint and expenditure minimization with a target utility constraint are equivalent problems. Notice that this is the inverse of the utility function. In practice, the expenditure function is more useful because the envelope theorem helps reveal key elements of demand.

Expenditure functions share several properties. First, homogeneity. A doubling of all prices will double the required expenditure. Second, expenditure functions are nondecreasing in prices. That is to say, $$\frac{dE}{dp_i} \geq 0$$ for all goods. Third, expenditure functions are concave in prices. If the price of a good decreases, expenditure decreases even faster because it can efficient reallocate goods.

Chapter 5

A demand function for a good $$x_i$$ takes the form $$x_i ^* = x(p_{x_1}, p_{x_2}, ..., I)$$. One property is homogeneity: $$x_i^* = x_i(tp_1, tp_2, ..., tp_n, tI)$$. Changing all prices and incomes with the same proportion will not change quantity of goods demanded.

Consumption of normal goods increases and income increases. For inferior goods, quantity purchased decreases as income rises. If there are only two goods, if one good is inferior then the other must be normal.

When a good’s price changes, there are two forces at play that affect consumption of that good. First, there is the substitution effect, as the MRS changes to reflect the new ratio of prices. Second, there is the income effect, as a decrease in price increases real income.

For normal goods, these effects reinforce each other. For inferior goods, the substitution effect still increases consumption, but the increase in income works in the opposite direction. When the income effect is strong enough, an increase in the price of an inferior good can paradoxically increase consumption.

Utility varies along an uncompensated demand curve $$x = x(p_x, p_y, I)$$, since income and other prices are constant. A decline in $$p_x$$ therefore increases purchasing power. We could also hold real income constant, forming a Hicksian or compensated demand curve $$x^c = x^c(p_x, p_y, U)$$. Notice that the Hicksian of a good $$x$$ can be obtained by differentiating the expenditure function with respect to $$p_x$$. The compensated demand curve must have a negative slope: an increase in price will always decrease the amount consumed. Because the income effect doesn’t play a role for compensated demand curves, the uncompensated curve is more price-sensitive.

Now, notice that $$x^c(p_x, p_y, U) = x[p_x, p_y, E(p_x, p_y, U)]$$. By differentiating with respect to $$x$$, we obtain

$\frac{dx^c}{dp_x} = \frac{dx}{dp_x} + \frac{dx}{dE} * \frac{dE}{dp_x}$

and rearrange to yield

$\frac{dx}{dp_x} = \frac{dx^c}{dp_x} - \frac{dx}{dE}*x^c$

We can interpret this to mean that the change in quantity consumed to price is equal to the compensated change in consumption (the substitution effect) minus the sensitivity of consumption to expenditure multiplied by the sensitivity of expenditure to a change in a good’s price (the income effect). The consequence is that we can decompose a good’s price sensitive into the income effect and substitution effect.

Built with Jekyll on the Swiss theme.

format: plain


text:
# George Leibman

George Joseph Leibman earned his Ph.D. under my supervision in June, 2004 at the CUNY Graduate Center. He was my first Ph.D. student. Being very interested both in forcing and in modal logic, it was natural for him to throw himself into the emerging developments at the common boundary of these topics.  He worked specifically on the natural extensions of the maximality principle where when one considers a fixed definable class $\Gamma$ of forcing notions.  This research engaged with fundamental questions about the connection between the forcing-theoretic properties of the forcing class $\Gamma$ and the modal logic of its forcing validities, and was a precursor of later work, including joint work, on the modal logic of forcing.

George Leibman

George Leibman, “Consistency Strengths of Modified Maximality Principles,” Ph.D. thesis, CUNY Graduate Center, 2004.  ar$\chi$iv

Abstract. The Maximality Principle MP is a scheme which states that if a sentence of the language of ZFC is true in some forcing extension $V^{\mathbb{P}}$, and remains true in any further forcing extension of $V^{\mathbb{P}}$, then it is true in all forcing extensions of $V$.  A modified maximality principle $\text{MP}_\Gamma$ arises when considering forcing with a particular class $\Gamma$ of forcing notions. A parametrized form of such a principle, $\text{MP}_\Gamma(X)$, considers formulas taking parameters; to avoid inconsistency such parameters must be restricted to a specific set $X$ which depends on the forcing class $\Gamma$ being considered. A stronger necessary form of such a principle, $\square\text{MP}_\Gamma(X)$, occurs when it continues to be true in all $\Gamma$ forcing extensions.

This study uses iterated forcing, modal logic, and other techniques to establish consistency strengths for various modified maximality principles restricted to various forcing classes, including ccc, COHEN, COLL (the forcing notions that collapse ordinals to $\omega$), ${\lt}\kappa$ directed closed forcing notions, etc., both with and without parameter sets. Necessary forms of these principles are also considered.

# The necessary maximality principle for c.c.c. forcing is equiconsistent with a weakly compact cardinal

• W. Hamkins Joel D.~and Woodin, “The necessary maximality principle for c.c.c.\ forcing is equiconsistent with a weakly compact cardinal,” MLQ Math.~Log.~Q., vol. 51, iss. 5, pp. 493-498, 2005.
@ARTICLE{HamkinsWoodin2005:NMPccc,
AUTHOR = {Hamkins, Joel D.~and Woodin, W.~Hugh},
TITLE = {The necessary maximality principle for c.c.c.\ forcing is equiconsistent with a weakly compact cardinal},
JOURNAL = {MLQ Math.~Log.~Q.},
FJOURNAL = {MLQ.~Mathematical Logic Quarterly},
VOLUME = {51},
YEAR = {2005},
NUMBER = {5},
PAGES = {493--498},
ISSN = {0942-5616},
MRCLASS = {03E65 (03E55)},
MRNUMBER = {2163760 (2006f:03082)},
MRREVIEWER = {Tetsuya Ishiu},
DOI = {10.1002/malq.200410045},
URL = {http://dx.doi.org/10.1002/malq.200410045},
eprint = {math/0403165},
archivePrefix = {arXiv},
primaryClass = {math.LO},
file = F,
}

The Necessary Maximality Principle for c.c.c. forcing asserts that any statement about a real in a c.c.c. extension that could become true in a further c.c.c. extension and remain true in all subsequent c.c.c. extensions, is already true in the minimal extension containing the real. We show that this principle is equiconsistent with the existence of a weakly compact cardinal.

See related article on the Maximality Principle

# A simple maximality principle

• J. D. Hamkins, “A simple maximality principle,” J.~Symbolic Logic, vol. 68, iss. 2, pp. 527-550, 2003.
@article{Hamkins2003:MaximalityPrinciple,
AUTHOR = {Hamkins, Joel David},
TITLE = {A simple maximality principle},
JOURNAL = {J.~Symbolic Logic},
FJOURNAL = {The Journal of Symbolic Logic},
VOLUME = {68},
YEAR = {2003},
NUMBER = {2},
PAGES = {527--550},
ISSN = {0022-4812},
CODEN = {JSYLA6},
MRCLASS = {03E35 (03E40)},
MRNUMBER = {1976589 (2005a:03094)},
MRREVIEWER = {Ralf-Dieter Schindler},
DOI = {10.2178/jsl/1052669062},
URL = {http://projecteuclid.org/getRecord?id=euclid.jsl/1052669062},
month = {June},
eprint = {math/0009240},
archivePrefix = {arXiv},
primaryClass = {math.LO},
}

In this paper, following an idea of Christophe Chalons, I propose a new kind of forcing axiom, the Maximality Principle, which asserts that any sentence$\varphi$ holding in some forcing extension $V^{\mathbb{P}}$ and all subsequent extensions $V^{\mathbb{P}*\mathbb{Q}}$ holds already in $V$. It follows, in fact, that such sentences must also hold in all forcing extensions of $V$. In modal terms, therefore, the Maximality Principle is expressed by the scheme $(\Diamond\Box\varphi)\to\Box\varphi$, and is equivalent to the modal theory S5. In this article, I prove that the Maximality Principle is relatively consistent with ZFC. A boldface version of the Maximality Principle, obtained by allowing real parameters to appear in $\varphi$, is equiconsistent with the scheme asserting that $V_\delta$ is an elementary substructure of $V$ for an inaccessible cardinal $\delta$, which in turn is equiconsistent with the scheme asserting that ORD is Mahlo. The strongest principle along these lines is the Necessary Maximality Principle, which asserts that the boldface MP holds in V and all forcing extensions. From this, it follows that $0^\sharp$ exists, that $x^\sharp$ exists for every set $x$, that projective truth is invariant by forcing, that Woodin cardinals are consistent and much more. Many open questions remain.


text:
# Picking a time to bet

You play a game with a friend: he deals cards face up one a time from a uniformly shuffled deck of 26 black cards and 26 red cards. At some point before all the cards have been dealt, you must call "bet". When you do, your friend flips the next card, and you win if it's black and lose if it's red.

What's the highest win probability you can achieve with any strategy?

• What happens when I don't say "bet" before the deck is empty? – Philipp Jan 15 '15 at 14:46
• @Philipp I would think that you lose. If not, you can play without losing by waiting until the last card (the color of which you will know) and either betting or passing. – KSmarts Jan 15 '15 at 15:31
• @Philipp: If you are required to yell "bet" before all cards are dealt, then if you haven't yelled "bet" by the time the 51st card was dealt you would be required to yell it then, even if such action was a guaranteed loss. – supercat Jan 15 '15 at 18:11
• @KSmarts: I would interpret the rules as saying that failure to bet on the 51st card simply isn't an option; failure to bet before the 50th is dealt would constitute an automatic bet on the 51st. – supercat Jan 15 '15 at 18:12
• @Philipp Yes, you are required to bet on the last card if you haven't already. – xnor Jan 15 '15 at 20:04

It is

$50-50$, i.e a fair game. In fact, any strategy will give you 50%

To show that

there are no strategy that maximizes gain, look at the game once we call stop. Suppose there are $k$ cards left. The probability that the next card is black is the same as the probability that the last card is black. But to bet on the next card is the same as betting on the last one whatever strategy I use, I have 50% chance of winning.

• I'm not convinced that's correct. If I call stop with 4 cards remaining and I've counted 25 red cards that means there's only one red card left. So isn't my change of winning 3/4? – Ash Burlaczenko Jan 15 '15 at 8:23
• @Ash, let me restate the second spoiler. Suppose there's 4 cards left and you're ready to stop. Your friend fans the last four cards out and says "Eh, take any one you want." Remember, the deck is randomly shuffled. So from your perspective, there is no difference between any of the four cards. So it doesn't matter which one you take. So you might as well take the bottom card. Do you agree? – Lopsy Jan 15 '15 at 9:17
• A great answer! Clear and simple. – Gamow Jan 15 '15 at 9:56
• @Lopsy, if I counted that of 4 remaining cards only one is red, my win chance is 75% regardless of which card I pick. A proper proof of the answer needs to show that advantageous and disadvantageous situations even out, regardless of strategy. – Cephalopod Jan 15 '15 at 20:43
• @Cephalopod That's right! The probability is 75% regardless of which one you pick, so you might as well take the bottom card. Of course, the exact numbers don't matter. If there are 19 cards left, 12 black, and you're ready to stop, the same argument applies. You might as well take the bottom card, because it's the same probability either way. In this game, at some point, you'll declare that you're ready to stop. Then, I'll fan out the cards, and you might as well take the bottom one. Hey, I'll set the bottom card over on that table; no matter what, you might as well pick it in the end. – Lopsy Jan 15 '15 at 21:18

We show that for $r$ red cards and $b$ black cards your chance of winning is $\frac{b}{r + b}$ and that this is true for all possible strategies. We do this by induction on $T = r + b$, the total number of cards left. This means we need to show that the chance to win is $\frac{b}{T}$.

For $T = 1$ you must, according to the rules of the game, call "bet". If $b = 1$, only a black card remains and your chance of winning is $1$. If $b = 0$, only a red card remains and your chance of winning is $0$. Your chance to win is $\frac{b}{T}$ in both cases.

Now for the induction step, we assume that your chance to win with $b$ black cards remaining in $T - 1$ cards is $\frac{b}{T - 1}$ (for any $b \leq T - 1$). We calculate the chance to win with $b$ black cards remaining in $T$ cards (for any $b \leq T$).

If you choose to call "bet" now, your chance of winning is clearly $\frac{b}{T}$. If you wait for the next card instead then your chance of winning = (chance of red on next card $\times$ chance of winning with 1 less red) $+$ (chance of black on next card $\times$ chance of winning with 1 less black). The chances to win after removing a card are given by our induction hypothesis. $$\frac{r}{T} \times \frac{b}{T - 1} + \frac{b}{T} \times \frac{b - 1}{T - 1}\\ = \frac{rb + b(b - 1)}{T(T - 1)}\\ = \frac{b(r + b - 1)}{T(T - 1)}\\ = \frac{b(T - 1)}{T(T - 1)}\\ = \frac{b}{T}$$ Regardless of whether you bet now or wait, your chance of winning is $\frac{b}{T}$.

This completes the induction, and so your chance of winning is always $\frac{b}{T} = \frac{b}{r + b}$. For the values given in the problem ($r = 26$, $b = 26$), this chance is $0.5$.

50%

But the way I thought of it was:

There are two types of strategies: one, wait after $x$ number of cards or wait after $x$ number of red cards (symmetry for black).

First strategy:

If I wait for one card and it's red, I now have a 25/51 chance of getting black on the next shot. If the card is black, I have a 26/51 chance of getting black. You gain or lose 1/102 chance with a 50% chance, which doesn't help. You can apply this for any $x$ number of cards.

Second strategy:

If I wait for the first red card, it's still the same thing as above only the position I stop at isn't decided ahead of time but through chance. If I wait for 10 reds, the chances that I find this before the 20th card and after the 20th card are the same, which correspond to a higher or lower chance of winning.

Other than these two strategies, there are no other (that I can think of) distinctive possible strategies other than cheesy ones like "go through all 51 in hopes the dealer messes up and shows you the next card".

• There are other strategies. Like "Wait until the number of black cards left in the deck is at least 20% more than the number of red cards left. (If this never happens, take the last card.)" – Lopsy Jan 15 '15 at 9:26
• I guess depending on what percentage you use, it changes the math. If you wait until the number of black cards are 5% more, you are more likely to hit that condition raising your chances, and if you happen to hit the last card, it is that much less likely to be a black card. I'm not sure how to prove this and I don't think the other answers specifically counter this either. Theosza's answer is basically my strategy one with variables, Jean's is basically "it's common sense" and disregards feedback strategies. – Quark Jan 15 '15 at 17:20
• The other answers don't specifically counter this. Because they don't need to: they work no matter what the strategy is. If you're not sure why another answer works, leave a comment on it, we're happy to explain better. – Lopsy Jan 15 '15 at 17:25
• So you're implying theoza's answer covers that theory but my strategy one doesn't? Can you specify where this distinction arises from? – Quark Jan 15 '15 at 17:32
• The first sentence of theoza's post says that their solution works "for all possible strategies." Your post considers two possible strategies. – Lopsy Jan 15 '15 at 19:06

Wait for him to drop almost all cards. Now there a three different possibilities:

• all 26 red cards are already on the table: you would have 100% chance to win since there are only (at least 2) black cards left.

• you can see that already 25 of your black cards are on the table at some earlier time: you have to wait for the end anyway because there is one black card among reds with a lower chance to hit. Not sure about the exact chance to win here.

• if there were one red and one black card left you would have to bet on the last card but one; giving you a 50% chance anyway - nothing to lose (Y).


text:
# Derivation of the formula for the vertex of a Parabola

I'm taking a course on Basic Conic Sections, and one of the ones we are discussing is of a parabola of the form

$y = a x^2 + b x + c$

My teacher gave me the formula:

$x = -\frac{b}{2a}$

as the $x$ coordinate of the vertex.

I asked her why, and she told me not to tell her how to do her job.

My smart friend mumbled something about it involving calculus, but I've always found him a rather odd fellow and I doubt I'd be able to understand a solution involving calculus, because I have no background in it. If you use something you know from calculus, explain it to someone who has no background in it. Because I sure don't.

Is there a purely algebraic or geometrical yet elegant derivation for the $x$ coordinate of a parabola of the above form?

-
Which definition of parabola are you using? The conic section one or the locus one? If you use the second, you can derive the equation of the parabola and the coordinates of the vertex directly from it. –  zar Aug 5 '10 at 8:30
Suggestion: tag it also "plane-curves" –  Américo Tavares Aug 29 '10 at 22:51
Off-topic: your teacher is terrible, and it's great that you're asking these kinds of questions. Don't give up. –  Paul VanKoughnett Oct 15 '10 at 3:40

Already so many answers, but I haven't seen my favorite one posted, so here's another.

The vertex occurs on the vertical line of symmetry, which is not affected by shifting up or down. So subtract $c$ to obtain the parabola $y=ax^2+bx$ having the same axis of symmetry. Factoring $y=x(ax+b)$, we see that the $x$-intercepts of this parabola occur at $x=0$ and $x=-\frac{b}{a}$, and hence the axis of symmetry lies halfway between, at $x=-\frac{b}{2a}$.

-
I see now that the idea of translating vertically is also used in Isaac's answer, but it is different from my answer. math.stackexchange.com/questions/709/… –  Jonas Meyer Oct 15 '10 at 2:52
Simply subtracting $c$ is something I would have never thought about, and reveals the zeroes as plain as day. The biggest jump in intuition was knowing what to do with the zeroes...and realizing that the axis of symmetry is exactly in between them. –  Justin L. Oct 16 '10 at 4:45
Very nice -- shifting up and down is a worthy trick here, mathematically and pedagogically –  David Lewis Feb 25 '12 at 1:43
There's no need for shifting. We need two points with the same second coordinate, so if we plug in $x=0$ and $x=-b/2a$, the zeroes of $ax^2+bx$, we get the same second coordinate, namely $c$. –  Michael Hoppe Aug 20 at 10:49

By the vertex I assume you mean the minimum/maximum point of the parabola. Indeed, this result can be discovered easily through a bit of calculus, but there is also a simple purely algebraic way, which I will present here.

Let's consider a generic quadratic expression:

$y = ax^2 + bx + c$

We now complete the square on this formula.

$y = a[x^2 + bx/a + c/a]$

$y = a[(x + b/2a)^2 - (b/2a)^2 + c/a]$

The expression $- (b/2a)^2 + c/a$ is a constant (it does not depend on x), so we can replace it with k for the matter of discussion.

$y = a[(x + b/2a)^2 + k]$

Now, depending on whether a is positive or negative, the parabola given by y will either have a maximum or minimum. Since a and k are fixed, this must occur when $(x + b/2a)^2$ is zero (we know it cannot be less than zero, and it can extend to infinity).

Hence, we know that for $(x + b/2a)^2$ to be zero, $x = -b/2a$. This in turn implies that the function y is at a minimum or a maximum when this is true. Q.E.D.

-

Parabolas of the form you described (y = ...) are symmetric over a vertical line through their vertex. Let's call that line x = k. This means that if the graph crosses the x-axis (meaning that $ax^2+bx+c=0$ has real solution(s)), they must be equidistant from x = k, so (k,0) must be the midpoint of the segment with endpoints at the zeros of the quadratic or k is the average of the zeros. From the quadratic formula, the two zeros of the quadratic are $\frac{-b\pm\sqrt{b^2-4ac}}{2a}$, so their sum is $-\frac{b}{a}$ and their average is $k=-\frac{b}{2a}$. So, the x-coordinate of the vertex must be $-\frac{b}{2a}$.

If the parabola does not cross the x-axis (no real solutions), there is another parabola with equation $y=ax^2+bx+c'$ for some $c'$ for which the graph is a vertical translation of the graph of the original quadratic, but crosses the x-axis. Its axis of symmetry is $x=-\frac{b}{2a}$ and because it is a vertical translation of the original, the axis of symmetry of the original is also $x=-\frac{b}{2a}$, so the vertices of both have x-coordinate $-\frac{b}{2a}$.

-

An alternative approach, which isn't necessarily the best in and of itself, but stick with me ...

Instead of using the fact that the vertex is the point where a vertical line cuts the parabola exactly in half, we'll use the fact that it's also the point where a horizontal line just brushes the curve, meeting it in a single point.

Consider how the horizontal line $y=d$ crosses the parabola as you adjust $d$. If $d$ places the line above or below the vertex, there are either 2 or 0 points of intersection (which is which depends upon whether the parabola points up or down); when $d$ places the line at the same height as the vertex, the parabola seems to sit comfortably on the line. (The line is tangent to the parabola the point they have in common, in the same way that lines can be tangent to circles.)

We can find the point of tangency (the vertex), then, by using algebra to determine when the intersection of our parabola and line equations have a single solution.

We begin with the standard find-the-intersection strategy, setting our formulas for $y$ equal:

$d = a x^2 + b x + c$

When does this equation have a single solution for $x$? Let's see. Rearranging and invoking the Quadratic Formula, we have:

$a x^2 + b x + c - d = 0$

$x = \frac{1}{2a}\left( - b \pm \sqrt{ b^2 - 4 a (c-d) } \right)$

Now, when the stuff under the radical matters, then we have either 2 or 0 values of $x$: two values if the stuff is positive (the square root gives a quantity to add and subtract from $-b$); no roots if the stuff is negative (the square root gives an imaginary number we can't use here). We'll have our sought-after single value of $x$ when $d$ is whatever-it-has-to-be (its exact value doesn't matter) to make the stuff under the radical becomes zero, making the radical term vanish; when that happens, our value of $x$ falls out as

$x = -\frac{b}{2a}$

Just like with the other approaches.

With this approach, however, we can consider a more sophisticated situation. It may be somewhat advanced for your class, but --if you can make sense of my rambling-- you can use it to blow your teacher's mind. :)

(Before we begin: I wouldn't necessarily recommend this exploration for every student just beginning to learn about parabola equations. However, I think having it "in the archive", as it were, can be worthwhile for people who come across the question to see that the answer can lead to some interesting places.)

What if we tilt the line?

That is: What can we say about the $x$-coordinate of the point of tangency where the parabola is touched by a line with slope $m$?

Let the slanted line's equation be $y = m x + d$, where $d$ is adjustable. We can make the same observations as in the horizontal case: if $d$ places the line above or below the point of tangency, the line will meet the parabola in either 2 or 0 places; for a special value of $d$, however, the line meets the parabola at the single point, the point of tangency.

As before, we set our formulas for $y$ equal to each other ...

$m x + d = a x^2 + b x + c$

... then rearrange and invoke the Quadratic Formula ...

$a x^2 + ( b - m ) x + ( c - d ) = 0$

$x = \frac{1}{2a}\left( -(b-m) \pm \sqrt{stuff} \right) = \frac{1}{2a}\left(m-b\pm \sqrt{stuff}\right)$

And as before, we don't really care about the complicated mess that "$stuff$" might be, since we're only interested in the situation where it goes away anyhow.[*] Once the radical term vanishes and the dust settles, we have this:

For the parabola described by the equation $y = a x^2 + b x + c$, the $x$-coordinate of the point where a line of slope $m$ lies tangent to the curve is given by

$x = \frac{1}{2a}\left( m - b \right)$

Here's the kicker that your smart friend[**] can appreciate: That statement really is a fact that most people don't see until Calculus. Except there, the issue tends to be phrased a little differently: It's not about finding the $x$-coordinate of the point-of-tangency based on a given slope, but about finding the slope of the line based on the $x$-coordinate for the point-of-tangency. So, we re-phrase the above equation to yield $m$:

For the parabola described by the equation $y = a x^2 + b x + c$, the slope $m$ of the line tangent to the curve at a point with $x$-coordinate $x$ is given by

$m = 2 a x + b$

You'll be way ahead of the game if you can see a neat way to get directly from the parabola equation to the slope formula. I'll give you a hint by showing how the formula fits in with a couple of facts you already know about the slopes of lines, and show you one step further, with a few unnecessary zeros thrown in:

$y = a$   slope = $0$.
$y = a x + b$   slope = $a + 0$.
$y = a x^2 + b x + c$   slope = $2 a x + b + 0$
$y = a x^3 + b x^2 + c x + d$   slope = $3 a x^2 + 2 b x + c + 0$
$y = a x^4 + b x^3 + c x^2 + d x + e$   slope = you tell me

Detect a pattern?

[*] Actually, you should care enough to convince yourself that you can find a value of $d$ that makes "$stuff$" go away, but for now you can trust me that such a $d$ exists.

[**] Keep in mind that "smart" doesn't always mean "having the right answers"; just as often, it means "asking the right questions". The fact that you chose not to accept a formula blindly and asked your teacher "why" --and then steadfastly continued your quest for an answer when she wouldn't provide one-- suggests to me that your smart friend has a smart friend, too.

-
Your solution may not have exploited the special structure of the problem, but you do get an upvote for generality. –  Guess who it is. Aug 9 '10 at 1:21
+1 for the "visual" solution. I didn't realize you were talking about the derivative until you derived it. –  stackErr Jun 17 '14 at 10:29

Here is the simplest way I know, using a bit of algebra. Starting with Isaac's observation that the vertex lies on the axis of symmetry, the line x = k. Question is, what's k? That's your answer.

if f(x) = ax2 + bx + c

Then the symmetry around x = k means that, for any h

f(k+h) = f(k-h)

From that, just multiply it all out and some simple additive cancellation gives

-2akh - bh = 2akh + bh

h cancels out, and a bit more algebra gives

k = -$\frac{b}{2a}$

To really complete this, however, we should show that x = k = -$\frac{b}{2a}$ is a maximum or minimum point. Again, with more algebra:

f(k+h) - f(k) boils down to ah2

So when a > 0, then f(k+h) > f(k) for any h != 0, establishing that x = k is a minimum point

And likewise when a < 0, x = k is a maximum. This also shows the symmetry around x = k, and how the coefficient a determines whether the curve is concave upward or downward.

-

I like Americo's answer using translation of y = ax^2. But to finish it, we should at least note that ax^2 has a maximum or minimum at <0,0>, which is quite obvious, and that translation preserves order and therefore maxima and minima, which is pretty easy.

-

The vertex of a parabola is the point on the axis of symmetry that intersects it (Wikipedia).

The point $(x,y)=\left( 0,0\right)$ is the vertex of the parabola given by $y=ax^{2}$. By making the change of coordinates

$X=x+\dfrac{b}{2a},Y=y+\dfrac{b^{2}-4ac}{4a}$,

equation $y=ax^{2}+bx+c$ is transformed into $Y=aX^{2}$, the vertex of which is the point $(X,Y)=(0,0)$, i.e. $(x,y)=\left(-\dfrac{b}{2a},-\dfrac{b^{2}-4ac}{4a}\right)$.

(This change of coordinates is a translation of both axes $x$, $y$, respectively, by $-\dfrac{b}{2a},-\dfrac{b^{2}-4ac}{4a}$.)

Hence, the $x$-coordinate of the vertex of the parabola is $-\dfrac{b}{2a}$.

Edit. Example. Plot of $y=2x^2-x+4$; blue axes: $X=x-1/4,Y=y-31/8$

-

Echoing Americo's and Isaac's answers, but without appealing to the quadratic equation:

First treat the special case f(x)=ax²+d (i.e. no "x" term); by remembering that the line that divides the parabola symmetrically passes through the vertex, and is in fact the y-axis (x=0), we see that 0 is the abscissa of the vertex.

To treat the more general f(x)=ax²+bx+c, we try a substitution of the form x=x'-h (geometrically, this corresponds to translating your coordinate system horizontally by h units). Expanding this, you will get something like a(x')²+(2ah+b)x'+(constant term). To go back to the special case we first treated, we find the value of h such that the coefficient of x' is 0. Thus you obtain the expression for the vertex's x-coordinate.

-

There are nice answers already but I would like to add another way to look at this:

The quadratic equation $a(x-r_1)(x-r_2) = ax^2 - a(r_1 + r_2)x + r_1 r_2 = 0$ defines a parabola, $r_1, r_2$ are the roots (intersections with the x-axis).

The middle point is between the two roots, $\frac{r_1 + r_2}{2} = -\frac{- a(r_1 + r_2)}{2a}$.

This leads to an interesting question about what happens when the parabola does not have real roots.

-

$y = ax^2 + bx + c$

for parabola written in Vertex Form vertex is (h,k).

$y = m(x-h)^2 + k = \underline{m}x^2 + \underline{(-2mh)}x+ \underline{mh^2 +k}$

$\rightarrow$

$a = m$

$b = -2mh = -2ah \rightarrow h = -b/2a$

$c = mh^2 + k = ah^2 + k \rightarrow k = c - b^2/4a$

source

-

Lots of interesting answers here. Might as well make it an even dozen. :-)

Actually, this can be derived directly from the definition of a parabola. Using the definition and the distance formula, you can derive the Standard Format for the equation of a parabola:

$$4p\left(y-k\right) = \left(x-h\right)^2$$

where $V=(h,k)$ is the vertex of the parabola and $p$ is the distance from the vertex to the focus (and also from the vertex to the directrix). If $p > 0$, the parabola opens upward; if $p < 0$, the parabola opens downward. I assume you've run across this standard form already and are familiar with it (there are plenty of online pages you can reference if not).

Now just expand the right-hand-side and solve for y. You end up with:

$$y = \left.\frac1{4p}\right.x^2 - \left.\frac{h}{2p}\right.x + \frac{h^2}{4p} + k$$

which is an equation of the form $y = ax^2 + bx + c$ with

$$a = \frac1{4p},\qquad b = -\frac{h}{2p},\qquad c = \frac{h^2}{4p} + k$$

Now just go right down the line and solve for $p$, $h$, and $k$.

\begin{align} a & = \frac1{4p} \\ p & = \frac1{4a} \\ \end{align}

[Here's the one you're interested in...] \begin{align} b & = -\frac{h}{2p} \\ b & = -\frac{h}{\frac1{2a}}\qquad \text{substituting}\; p = \frac1{4a}\; \text{above} \\ -\frac{b}{2a} & = h \\ \end{align}

and lastly,

\begin{align} c & = \frac{h^2}{4p} + k \\ c & = \frac{\left(-\frac{b}{2a}\right)^2}{\frac1a} + k\qquad \text{substituting for}\; p\;\text{&}\;h\;\text{above} \\ c & = \frac{\frac{b^2}{4a^2}}{\frac1a} + k \\ c & = \frac{b^2}{4a} + k \\ c - \frac{b^2}{4a} & = k \\ \end{align}

Now you can easily convert back & forth between Standard Format and the other.

-
Please see here for how to typeset common math expressions with LaTeX –  Zev Chonoles Jun 4 '13 at 4:23
I'll take a look. Thanks. –  Bullwinkle Jun 4 '13 at 15:02

It could be argued that the parabola is symetric respect to the vertical line passing through the vertex point. So, the vertex is located in the midpoint between the two roots of $y=0$.

As pointed out before, by completing the square, the parabola equation can be written as $$y = a(x - x_+)(x - x_-)\,,$$

where $x_+$ and $x_-$ are the roots mentioned above, given by $$x_\pm = \dfrac{ -b \pm \sqrt{ b^2 - 4 a c} }{2a} \,.$$

Then, the midpoint between $x_+$ and $x_-$ is $$x_0 = \dfrac12 (x_+ + x_- ) = -\frac{b}{2a} \,.$$

Note that this demonstration is also valid even when there is no real roots for $y=0$ (which is the case when $b^2 < 4a c$), since the complex terms in the last equation are mutually canceled.

Sketch of the parabola:

-


text:
# User:Integer

Jump to navigation Jump to search

There is currently no text in this page. You can search for this page title

in other pages,

search the related logs, or edit this page .


text:
# Composite divisors 2

Number Theory Level 5

Find the least positive integer $$n$$ such that $$n$$ $$\mid$$ $$2^{n}-2$$ but $$n$$ $$\nmid$$ $$3^{n}-3$$.

Try Part-1 also.

×


text:
# Is it practical to become an airline pilot in order to travel internationally?

I am a person with very diverse interests and a lot of life goals I want to achieve. One of them is becoming an airline pilot (just working as one for a year or two) and the other is traveling the world.

I would like to combine two goals in one, that is becoming an airline pilot after I finish college and travelling the world at the same time, i.e. flying intercontinental flights.

So, my question is basically this: Is it possible to learn to fly and become an airline pilot within about 3 years (let's say age 20-23), then immediately get employed as an airline pilot and fly intercontinental routes (even as a co-pilot)?

• All the long haul commercial pilots I know spent upwards of 6 years flying small craft, instructing, taking low paid jobs at small flying clubs and working their way up through local and regional airlines, to eventually reaching flight crew on long haul international carriers. The answer is going to be a big No unless you have some incredible source of funds to make this happen! Mar 5 '16 at 11:10
• becoming an airline pilot (just working as one for a year or two) - you're going to spend a large amount of money and spend many years training and progressing to do something for a year or two? To answer your question, no. It takes around 10 years to even get into the right hand seat of international flights. Mar 5 '16 at 11:16
• +1, since after all this is a valid question, that deserves a good answer for future searches and reference.
– mins
Mar 5 '16 at 11:36
• Now it could be interesting to understand what is the life of long haul crew members, and whether they have time to visit the country they land in during their legal rest time.
– mins
Mar 5 '16 at 13:01
• If you only want to be a pilot for one or two years, it is probably best to remove it of your bucket list and use the money you save by not investing in pilot training to travel the world. Mar 5 '16 at 14:41

No, this is not a good idea, and No, it is not possible finish your education at 23, and then get employed as an intercontinental airline pilot.

It seems you have a distorted idea of what an airline pilot actually does. An intercontinental airline pilot usually spends just 24 hours at the layover destination. Much of that time is spent sleeping to recover from the fatigue of the long haul flight and sleeping to prepare for the next long haul flight. Not much time for sight-seeing.

The first requirement for becoming an airline pilot is a love of aviation and aircraft. Most airline pilots today have been passionate about aviation since an early age.

You will never be successful unless you are passionate about aviation due to all the roadblocks and hardships you will have to overcome in order to reach your goal.

To say that you only want to do it for 1-2 years is proof enough that you don't have what it takes.

• Lets also mention that for the first 1-2 years of your career, you're probably running a short shuttle route in the midwest. No big jets, no international destintions. Mar 5 '16 at 15:16
• @abelenky Not every aviation career is in the USA, you know. Mar 5 '16 at 20:52
• @DavidRicherby or a given nation's equivalent of the boring midwest
– cat
Mar 5 '16 at 21:17
• @tac Well, most nations aren't big enough to have an equivalent of the boring Midwest. For example, in Europe, surely most commercial passenger pilots have to be on international flights. The countries aren't big enough to have a lot of internal flights and your one-hour Chicago to Omaha flight turns into a one-hour London to Frankfurt flight. Mar 5 '16 at 21:54
• @DavidRicherby has a point. The percentage of domestic flights in the U.S. is quite unique to the U.S. That said, intra-Europe flights are mostly analogous to U.S. domestic flights, except that they do technically cross international borders (even if they might remain within the Schengen zone and not require immigration.) That said, there are some airlines that fly almost exclusively long-haul international, but these are mostly in Asia (e.g. Korean Air, Asiana, Cathay Pacific.) If you want a fast-track to long-haul intercontinental, you'd probably need to move there. Mar 6 '16 at 3:54

Even once you get a job as a commercial pilot, you're not going to be starting intercontinental routes immediately.

For starters (in the US at least), you're probably only going to be able to start at a regional airline, flying short regional jet flights back and forth.

The airline industry is very much dependent on seniority, so you'll have to put in substantial time at that regional carrier before you have a chance at even getting hired by one of the big mainline airlines. Even once you do, the routes you fly on are bid based on seniority, so you're not going to get intercontinental routes for quite a while.

Also, don't forget that intercontinental flights are flown on different equipment than medium range mainline flights, which are different equipment from regional jets. you're going to have to get trained and certified for several different aircraft along the way.

So yes, if you become a pilot you may eventually be able to fly intercontinental routes and see the world, but it will likely take decades of work before you're in that position.

• In the U.S., this is very true. You'll rarely see a young pilot flying intercontinental routes for U.S. carriers. That said, it's not true for the whole world. If you get a job at Cathay Pacific, for example, you'll be flying wide-bodies almost immediately. Mar 6 '16 at 3:58
• Also, judging from a few aspiring airline pilots I've known, your first years may not be with airlines at all, but with freight companies doing runs between small towns to pick up & deliver for FexEx & UPS. (In piston twins, or even singles.) Apr 7 '16 at 19:28

If your intention is to travel the world, then don't be a pilot. Instead, be a flight attendant.

In addition to the possibility of being on international flights relatively early in your career, you will likely be surrounded by a majority of female coworkers who will be very glad to let you walk the aisles, lift the luggage, calm the rowdy passengers, and deal with the occasional butt-pincher.

• Another tip is to work as a freight pilot. Airline pilots fly a small number of routes. The trips freight pilots make are much more diverse. Mar 6 '16 at 23:49
• Hmm... At least for the case of the U.S., my understanding was that FAs had similar seniority situations to pilots, where it is mostly quite senior FAs on long-haul routes with junior FAs mostly stuck on regional routes. FAs also don't have the "move to Southeast Asia" fast-track option like pilots, unless perhaps they also happen to be young, attractive, and female. Mar 7 '16 at 2:19
• @reirab Had a friend get picked up as a flight attendant by Hawaiian Airlines a few years back and he was telling stories of adventures in Southeast Asia early on. No college, no experience either. Mar 8 '16 at 23:43
• @digitgopher Ah, yeah, I suppose Hawaiian would be an exception, since they have a much higher percentage of long-haul routes than other U.S. airlines (because nearly everything is long-haul from Hawaii, except the other Hawaiian islands.) Mar 9 '16 at 0:03

"...a year or two"? Seriously don't even think about it. But ignoring your lack of commitment, here are some ideas.

Instead of traveling the world, try living and working in a foreign country. This can be an incredible adventure and broaden your horizons. You'll have an understanding and appreciation for international concerns that can't be matched by merely being a tourist. You might still want to travel so you can use that place as a base to visit various destinations on your time off.

Southeast Asia has experienced tremendous growth in the last few years. Some of the biggest airplane orders are coming from there. Indonesia and Malaysia are looking for good pilots. Don't know if they provide training or not. Check out AirAsia and other regional airlines. Regional in this case means the Southeast Asia region and may be international.

Or the middle-east. Here's Etihad training program

This suggests Etihad accepts non-residents for training.

• The comments suggest that Etihad no longer accepts foreigners Mar 5 '16 at 20:55
• Judging from the pilots I've had when flying with them (and what I've heard from others,) Cathay Pacific heavily recruits Western pilots. Every pilot I've had with them was American, British, or Australian, even though the airline is based in Hong Kong. Mar 6 '16 at 4:00

Is it possible to learn to fly and become an airline pilot within about 3 years (let's say age 20-23), then immediately get employed as an airline pilot and fly intercontinental routes (even as a co-pilot)?

Yes, but not in the US. You'll have to look overseas at airlines like Emirates/Qatar etc. for that.

Airline routes are offered by seniority; and pilots that have been with the airline a significant amount of years (I am talking 5+ at minimum) are given the longer routes.

In the US, where I have the most exposure to the flight training side - once you get your ATP (Airline Transport Pilot) and have acquired all the relevant type certifications - your entire purpose in life is to build up your hours as PIC (Pilot In Command) / PF (Pilot Flying).

You will be doing this on regional airlines, which may be contracted out to larger airlines. You may be flying an aircraft that's painted in United colors, but its actually a regional airline used on "feeder" routes to the larger hub airports. This is typically the case in the US (and Europe).

Or, you may be employed by an airline that has no international routes.

Outside of these areas - if you come to the Middle East, you may be flying international routes at the start of your career; simply because that's the only option - and you may be flying the long haul jets if that's all the airline has to offer.

For example, Emirates (the largest operator of 777 and the A380) flies international exclusively; and the majority of their routes are medium to long haul (greater than 3 hours flight time). You may have a chance to fly internationally, but on shorter routes like Dubai - Muscat, Dubai - Bahrain, Dubai - Kuwait (this is the shortest A380 flight by Emirates, and is used for crew training/familiarization).

Qatar Airways is similar - they use their short routes for crew familiarization and training on their newer aircraft. They flew their 777-200/300LR on the Doha - Kuwait - Doha circuit when they first got the aircraft (a route normally served by the A320); and the 787 on the Doha - Dubai - Doha circuit (again, normally served by the A320).

However, you may not have the opportunity to fly the longer routes until well into your career with the airline; and you will be starting off (training) in smaller aircraft and a lot of simulator time.

Typical training period for commercial pilots is between 3 and 4 years (if you are directly trained by an airline, such as Emirate's flight training program) and then you are qualified as an airline pilot.

• Actually, Southwest flies to Mexico, Jamaica, the Dominican Republic and Costa Rica, Belize, the Bahamas and Aruba. See their map. Mar 6 '16 at 18:43
• I did not know that @DavidRicherby - thanks. Mar 6 '16 at 19:45
• @BurhanKhalid Yeah, international routes are a somewhat recent addition for Southwest. Many of them were added after they acquired AirTran Airlines, which already flew several routes to the Caribbean. Southwest doesn't have any long-haul, flights, though, as they only operate 737s. Mar 7 '16 at 2:23
• How feasible is it to work on Middle Eastern routes with Emerates for people who don't speak Arabic? Nov 20 '20 at 22:15

Seems like the hard way to see the world.

Assuming you have a private license with complex and retractable endorsements. Then the next step is to get your instrument rating, multi engine, turbine and commercial ATR rating and at least 800 to a thousand hours as PIC (Pilot in Command). By now you have spend over \$50,000 and might be employable as first officer for a small low budget commuter line at a couple of G's a month.

Is it worth it? That's up to you. I have over 4,000 hours in single and multi engine prop and jet aircraft. I own and fly a Beech Baron which is considered to be one of the more challenging light twin engine planes. I do not consider myself qualified to be an airline pilot.


text:
• We performed a 4.5-month multi-instrument campaign (from radio to VHE gamma rays) on Mrk421 between January 2009 and June 2009, which included VLBA, F-GAMMA, GASP-WEBT, Swift, RXTE, Fermi-LAT, MAGIC, and Whipple, among other instruments and collaborations. Mrk421 was found in its typical (non-flaring) activity state, with a VHE flux of about half that of the Crab Nebula, yet the light curves show significant variability at all wavelengths, the highest variability being in the X-rays. We determined the power spectral densities (PSD) at most wavelengths and found that all PSDs can be described by power-laws without a break, and with indices consistent with pink/red-noise behavior. We observed a harder-when-brighter behavior in the X-ray spectra and measured a positive correlation between VHE and X-ray fluxes with zero time lag. Such characteristics have been reported many times during flaring activity, but here they are reported for the first time in the non-flaring state. We also observed an overall anti-correlation between optical/UV and X-rays extending over the duration of the campaign. The harder-when-brighter behavior in the X-ray spectra and the measured positive X-ray/VHE correlation during the 2009 multi-wavelength campaign suggests that the physical processes dominating the emission during non-flaring states have similarities with those occurring during flaring activity. In particular, this observation supports leptonic scenarios as being responsible for the emission of Mrk421 during non-flaring activity. Such a temporally extended X-ray/VHE correlation is not driven by any single flaring event, and hence is difficult to explain within the standard hadronic scenarios. The highest variability is observed in the X-ray band, which, within the one-zone synchrotron self-Compton scenario, indicates that the electron energy distribution is most variable at the highest energies.
• Mrk 501 is one of the brightest blazars at TeV energies and has been extensively studied since its first VHE detection in 1996. Our goal is to characterize in detail the source gamma-ray emission, together with the radio-to-X-ray emission, during the non-flaring (low) activity, which is less often studied than the occasional flaring (high) activity. We organized a multiwavelength (MW) campaign on Mrk 501 between March and May 2008. This multi-instrument effort included the most sensitive VHE gamma-ray instruments in the northern hemisphere, namely the imaging atmospheric Cherenkov telescopes MAGIC and VERITAS, as well as Swift, RXTE, the F-GAMMA, GASP-WEBT, and other collaborations and instruments. Mrk 501 was found to be in a low state of activity during the campaign, with a VHE flux in the range of 10%-20% of the Crab nebula flux. Nevertheless, significant flux variations were detected with various instruments, with a trend of increasing variability with energy. The broadband spectral energy distribution during the two different emission states of the campaign can be adequately described within the homogeneous one-zone synchrotron self-Compton model, with the (slightly) higher state described by an increase in the electron number density. This agrees with previous studies of the broadband emission of this source during flaring and non-flaring states. We report for the first time a tentative X-ray-to-VHE correlation during a low VHE activity. Although marginally significant, this positive correlation between X-ray and VHE, which has been reported many times during flaring activity, suggests that the mechanisms that dominate the X-ray/VHE emission during non-flaring-activity are not substantially different from those that are responsible for the emission during flaring activity.
• We aim to characterize the broadband emission from 2FGL J2001.1+4352, which has been associated with the unknown-redshift blazar MG4 J200112+4352. Based on its gamma-ray spectral properties, it was identified as a potential very high energy (VHE; E > 100 GeV) gamma-ray emitter. The source was observed with MAGIC first in 2009 and later in 2010 within a multi-instrument observation campaign. The MAGIC observations yielded 14.8 hours of good quality stereoscopic data. The object was monitored at radio, optical and gamma-ray energies during the years 2010 and 2011. The source, named MAGIC J2001+439, is detected for the first time at VHE with MAGIC at a statistical significance of 6.3 {\sigma} (E > 70 GeV) during a 1.3-hour long observation on 2010 July 16. The multi-instrument observations show variability in all energy bands with the highest amplitude of variability in the X-ray and VHE bands. We also organized deep imaging optical observations with the Nordic Optical Telescope in 2013 to determine the source redshift. We determine for the first time the redshift of this BL Lac object through the measurement of its host galaxy during low blazar activity. Using the observational evidence that the luminosities of BL Lac host galaxies are confined to a relatively narrow range, we obtain z = 0.18 +/- 0.04. Additionally, we use the Fermi-LAT and MAGIC gamma-ray spectra to provide an independent redshift estimation, z = 0.17 +/- 0.10. Using the former (more accurate) redshift value, we adequately describe the broadband emission with a one-zone SSC model for different activity states and interpret the few-day timescale variability as produced by changes in the high-energy component of the electron energy distribution.
• We study the multifrequency emission and spectral properties of the quasar 3C 279. We observed 3C 279 in very high energy (VHE, E>100GeV) gamma rays, with the MAGIC telescopes during 2011, for the first time in stereoscopic mode. We combine these measurements with observations at other energy bands: in high energy (HE, E>100MeV) gamma rays from Fermi-LAT, in X-rays from RXTE, in the optical from the KVA telescope and in the radio at 43GHz, 37GHz and 15GHz from the VLBA, Mets\"ahovi and OVRO radio telescopes and optical polarisation measurements from the KVA and Liverpool telescopes. During the MAGIC observations (February to April 2011) 3C 279 was in a low state in optical, X-ray and gamma rays. The MAGIC observations did not yield a significant detection. These upper limits are in agreement with the extrapolation of the HE gamma-ray spectrum, corrected for extragalactic background light absorption, from Fermi-LAT. The second part of the MAGIC observations in 2011 was triggered by a high activity state in the optical and gamma-ray bands. During the optical outburst the optical electric vector position angle rotatated of about 180 degrees. There was no simultaneous rotation of the 43GHz radio polarisation angle. No VHE gamma rays were detected by MAGIC, and the derived upper limits suggest the presence of a spectral break or curvature between the Fermi-LAT and MAGIC bands. The combined upper limits are the strongest derived to date for the source at VHE and below the level of the previously detected flux by a factor 2. Radiation models that include synchrotron and inverse Compton emissions match the optical to gamma-ray data, assuming an emission component inside the broad line region (BLR) responsible for the high-energy emission and one outside the BLR and the infrared torus causing optical and low-energy emission. We interpreted the optical polarisation with a bent trajectory model.
• We present a study of the very high energy (VHE; E > 100 GeV) gamma-ray emission of the blazar PKS 1424+240 observed with the MAGIC telescopes. The primary aim of this paper is the multiwavelength spectral characterization and modeling of this blazar, which is made particularly interesting by the recent discovery of a lower limit of its redshift of z > 0.6 and makes it a promising candidate to be the most distant VHE source. The source has been observed with the MAGIC telescopes in VHE gamma rays for a total observation time of ~33.6 h from 2009 to 2011. The source was marginally detected in VHE gamma rays during 2009 and 2010, and later, the detection was confirmed during an optical outburst in 2011. The combined significance of the stacked sample is ~7.2 sigma. The differential spectra measured during the different campaigns can be described by steep power laws with the indices ranging from 3.5 +/- 1.2 to 5.0 +/- 1.7. The MAGIC spectra corrected for the absorption due to the extragalactic background light connect smoothly, within systematic errors, with the mean spectrum in 2009-2011 observed at lower energies by the Fermi-LAT. The absorption-corrected MAGIC spectrum is flat with no apparent turn down up to 400 GeV. The multiwavelength light curve shows increasing flux in radio and optical bands that could point to a common origin from the same region of the jet. The large separation between the two peaks of the constructed non-simultaneous spectral energy distribution also requires an extremely high Doppler factor if an one zone synchrotron self-Compton model is applied. We find that a two-component synchrotron self-Compton model describes the spectral energy distribution of the source well, if the source is located at z~0.6.
• The radio galaxy NGC 1275, recently identified as a very high energy (VHE, >100 GeV) gamma-ray emitter by MAGIC, is one of the few non-blazar AGN detected in the VHE regime. In order to better understand the origin of the gamma-ray emission and locate it within the galaxy, we studied contemporaneous multi-frequency observations of NGC 1275 and modeled the overall spectral energy distribution (SED). We analyzed unpublished MAGIC observations carried out between Oct. 2009 and Feb. 2010, and the previously published ones taken between Aug. 2010 and Feb. 2011. We studied the multi-band variability and correlations by analyzing data of Fermi-LAT (0.1-100 GeV), as well as Chandra (X-ray), KVA (optical) and MOJAVE (radio) data taken during the same period. Using customized Monte Carlo simulations corresponding to early MAGIC stereo data, we detect NGC 1275 also in the earlier campaign. The flux level and energy spectra are similar to the results of the second campaign. The monthly light curve >100 GeV shows a hint of variability at the 3.6 sigma level. In the Fermi-LAT band, both flux and spectral shape variabilities are reported. The optical light curve is variable and shows a clear correlation with the gamma-ray flux >100 MeV. In radio, 3 compact components are resolved in the innermost part of the jet. One of them shows a similar trend as the LAT and KVA light curves. The 0.1-650 GeV spectra measured simultaneously with MAGIC and Fermi-LAT can be well fitted either by a log-parabola or by a power-law with a sub-exponential cutoff for both campaigns. A single-zone synchrotron-self-Compton model, with an electron spectrum following a power-law with an exponential cutoff, can explain the broadband SED and the multi-band behavior of the source. However, this model suggests an untypical low bulk-Lorentz factor or a velocity alignment closer to the line of sight than the pc-scale radio jet.
• We present the results of stereoscopic observations of the satellite galaxy Segue 1 with the MAGIC Telescopes, carried out between 2011 and 2013. With almost 160 hours of good-quality data, this is the deepest observational campaign on any dwarf galaxy performed so far in the very high energy range of the electromagnetic spectrum. We search this large data sample for signals of dark matter particles in the mass range between 100 GeV and 20 TeV. For this we use the full likelihood analysis method, which provides optimal sensitivity to characteristic gamma-ray spectral features, like those expected from dark matter annihilation or decay. In particular, we focus our search on gamma-rays produced from different final state Standard Model particles, annihilation with internal bremsstrahlung, monochromatic lines and box-shaped signals. Our results represent the most stringent constraints to the annihilation cross-section or decay lifetime obtained from observations of satellite galaxies, for masses above few hundred GeV. In particular, our strongest limit (95% confidence level) corresponds to a ~500 GeV dark matter particle annihilating into tau+tau-, and is of order <sigma v> ~ 1.2x10^{-24} cm^3 s^{-1} - a factor ~40 above the <sigma v> thermal value.
• The bright gamma-ray quasar 4C +55.17 is a distant source ($z = 0.896$) with a hard spectrum at GeV energies as observed by the Large Area Telescope (LAT) on board the {{\it Fermi}} satellite. This source is identified as a good source candidate for very-high-energy (VHE; $> 30$ GeV) gamma rays. In general VHE gamma rays from distant sources provide an unique opportunity to study the extragalactic background light (EBL) and underlying astrophysics. The flux intensity of this source in the VHE range is investigated. Then, constraints on the EBL are derived from the attenuation of gamma-ray photons coming from the distant blazar. We searched for a gamma-ray signal from this object using the 35-hour observations taken by the MAGIC telescopes between November 2010 and January 2011. No significant VHE gamma-ray signal was detected. We computed the upper limits of the integrated gamma-ray flux at $95\%$ confidence level of $9.4 \times 10^{-12}$ cm$^{-2}$ s$^{-1}$ and $2.5 \times 10^{-12}$ cm$^{-2}$ s$^{-1}$ above $100$ GeV and $200$ GeV, respectively. The differential upper limits in four energy bins in the range from $80$ GeV to $500$ GeV are also derived. The upper limits are consistent with the attenuation predicted by low-flux EBL models on the assumption of a simple power-law spectrum extrapolated from LAT data.
• Indications of a GeV component in the emission from GRBs are known since the EGRET observations during the 1990's and they have been confirmed by the data of the Fermi satellite. These results have, however, shown that our understanding of GRB physics is still unsatisfactory. The new generation of Cherenkov observatories and in particular the MAGIC telescope, allow for the first time the possibility to extend the measurement of GRBs from several tens up to hundreds of GeV energy range. Both leptonic and hadronic processes have been suggested to explain the possible GeV/TeV counterpart of GRBs. Observations with ground-based telescopes of very high energy photons (E>30 GeV) from these sources are going to play a key role in discriminating among the different proposed emission mechanisms, which are barely distinguishable at lower energies. MAGIC telescope observations of the GRB 090102 (z=1.547) field and Fermi Large Area Telescope (LAT) data in the same time interval are analysed to derive upper limits of the GeV/TeV emission. We compare these results to the expected emissions evaluated for different processes in the framework of a relativistic blast wave model for the afterglow. Simultaneous upper limits with Fermi and a Cherenkov telescope have been derived for this GRB observation. The results we obtained are compatible with the expected emission although the difficulties in predicting the HE and VHE emission for the afterglow of this event makes it difficult to draw firmer conclusions. Nonetheless, MAGIC sensitivity in the energy range of overlap with space-based instruments (above about 40 GeV) is about one order of magnitude better with respect to Fermi. This makes evident the constraining power of ground-based observations and shows that the MAGIC telescope has reached the required performance to make possible GRB multiwavelength studies in the very high energy range.


text:
## Intermediate Algebra (6th Edition)

$7.613\times10^{-3}$
We are given the number $.007613$. Step 1: To write this number in scientific notation, we move the decimal point to the right until the original number is 7.613. Step 2: Since the original number was less than 1, we moved the decimal by 3 negative places. In other words, we will raise 10 to a power of -3. Now, we write the product of the two numbers found in Step 1 and Step 2. $7.613\times10^{-3}$


text:
# AES-encrypted key store

I am writing a program that needs to retain specific data but that should not be easily readable. I am in no way very skilled in crypto but I wrote this class that takes all of the data in and then returns the AES encrypted strings.

Is this an appropriate way to encrypt the data for storage in XML?

public class Crypto {

private String home;

public Crypto(String choice) throws Exception
{
home = System.getProperty("user.home") + "\\dataStore.keystore";
}

//Method to access the keystore, generate, and store the key.
public void storeSecretKey() throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException
{
//create the actual Keystore file
KeyStore keyStore = createKeyStore(home, "cryptoTesting");

//Generate our secret key
SecretKey key = KeyGenerator.getInstance("AES").generateKey();
KeyStore.SecretKeyEntry keyStoreEntry = new KeyStore.SecretKeyEntry(key);

//Store our secret key
keyStore.setEntry("dataVariables", keyStoreEntry, pwP);
keyStore.store(new FileOutputStream(home), "cryptoTesting".toCharArray());

}

//retrieve our AES key from the store
public SecretKey retrieveKey() throws Exception
{
KeyStore store = createKeyStore(System.getProperty(home), "cryptoTesting");

//Retrieve the entry from the keystore
KeyStore.Entry entry = store.getEntry("dataVariables", pwP);

//Assign the entry as our secret key for later retrieval.
SecretKey key = ((KeyStore.SecretKeyEntry) entry).getSecretKey();

return key;
}

//Actually create the keystore file.
private KeyStore createKeyStore(String path, String password) throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException
{
File file = new File(home);

final KeyStore keyStoreCreate = KeyStore.getInstance("JCEKS");

if(file.exists())
{
//if the file exists load the keystore.
}
else
{
//create keyStore.
}
return keyStoreCreate;
}

//Encrypt the data passed to the method
public String encryptData(String data) throws Exception
{
String encryptedString = "";

//Actual encryption process
Cipher cipher = Cipher.getInstance("AES");
byte[] dataToEncrypt = data.getBytes();
cipher.init(Cipher.ENCRYPT_MODE, retrieveKey());
byte[] encryptedBytes = cipher.doFinal(dataToEncrypt);
Base64.Encoder encoder = Base64.getEncoder();
encryptedString = encoder.encodeToString(encryptedBytes);

return encryptedString;
}

public String decryptData(String data) throws Exception
{
String decryptedText = "";
Cipher cipher = Cipher.getInstance("AES");
Base64.Decoder decoder = Base64.getDecoder();
byte[] encryptedBytes = decoder.decode(data);
cipher.init(Cipher.DECRYPT_MODE, retrieveKey());
byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
decryptedText = new String(decryptedBytes);
return decryptedText;
}
}

Here is the XML class to create that portion:

public class DataStorage {

{
this.account = account;
}

public void CreateXML() throws Exception
{
try
{
DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = documentFactory.newDocumentBuilder();

Document document = builder.newDocument();
Element rootElement = document.createElement("AccountInformation");
document.appendChild(rootElement);

//Identification number
Element userId = document.createElement("Developer");
rootElement.appendChild(userId);

//ID attributes
Attr attr = document.createAttribute("id");
attr.setValue("######-#######-#######-#######");
userId.setAttributeNode(attr);

//account name
Element accountName = document.createElement("Account");
accountName.appendChild(document.createTextNode(account));
userId.appendChild(accountName);

//user id
userId.appendChild(userId);

//write to XML
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT,"yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
DOMSource source = new DOMSource(document);

//String storage path
String path = System.getProperty("user.home") + "\\dataFile.XML";
StreamResult result = new StreamResult(new File(path));

transformer.transform(source, result);

}
catch(ParserConfigurationException | DOMException | IllegalArgumentException | TransformerException exc)
{
exc.printStackTrace();
}
}
}

Is this an appropriate way to encrypt the data for storage in XML?

Maybe. Note that encryption always works with bytes. So it doesn't care if your file is an image, a plaintext, an XML, or even something worse.

## Crypto

private String home;

Why is the latter static? Shouldn't both be just final?

public Crypto(String choice) throws Exception
{

• But you have no choice. Unused constructor argument makes hardly even sense.
• The brace belongs on the previous line.
• Declaring throws Exception forces you to catch Exception later. This is nearly always wrong. Wouldn't GeneralSecurityException do?

pwP is a terrible name. A password stored in the code gives you zero security against anyone in possession of the code. But there may not be a way out.

home = System.getProperty("user.home") + "\\dataStore.keystore";

Using \ as a separator is a terrible idea. For very lazy people or use-once code, / can be used as it (nearly always) works on Windows, too. The right way is to use File.separator.(*)

//Method to access the keystore, generate, and store the key.
public void storeSecretKey() throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException

• It's obviously a method, so never use the word "method".
• The method is called storeSecretKey, either it's exacly what it does, or it should be renamed.
• It actually generates and stores a key, so I'd call it generateAndStoreSecretKey.
• Comments with // or /* ... */ are for explaining code details or hacks. For method, Javadoc should be used.

//create the actual Keystore file KeyStore keyStore = createKeyStore(home, "cryptoTesting"); KeyStore.SecretKeyEntry keyStoreEntry = new KeyStore.SecretKeyEntry(key);

Not much information in the comment, but OK. Saying what a small code lock does makes sometimes sense. But note that writing Javadoc for non-trivial methods is way more important.

Use constants. Especially for repeated things like here.

private static final KEYSTORE_NAME = "cryptoTesting";

Twenty lines later, I see that I was wrong. It's not the KEYSTORE_NAME, but a PASSWORD. Using a properly named constant makes it clear.

//Store our secret key
keyStore.setEntry("dataVariables", keyStoreEntry, pwP);
keyStore.store(new FileOutputStream(home), "cryptoTesting".toCharArray());

For non-trivial file sizes you should use

new BufferedOutputStream(new FileOutputStream(home))

final KeyStore keyStoreCreate = KeyStore.getInstance("JCEKS");

Calling a variable ...Create is ugly. Variable names should be nouns, method names should be verbs. Just keyStore or better result.

The reason why crypto uses char[] instead of String is security. Strings are immutable and will hang around until they gets GC'ed, while an array can be cleared after use. But with the password being part of the program, you can safely ignore such things.

//Encrypt the data passed to the method
public String encryptData(String data) throws Exception
{

Again a negative-value comment. The method is clear without it. You could make it clearer with something like

public String encrypt(String plaintext) throws GeneralSecurityException {

    String encryptedString = "";

You really really don't need it here. Always minimize the scope of all variables. Actually, you don't need it at all, just

return encoder.encodeToString(encryptedBytes);

a few lines later.

Note that there's usually no need for the String result. For storing in a file, a byte[] is simpler. Actually, for everything a byte[] is better. You don't show any use of encryptData.

//Decrypt the data retrieved from the XML File
public String decryptData(String data) throws Exception

The comment is just confusing. If you later decide to switch from XML to something better, it'll stay there and confuse the reader even more. There's no XML in this method.

## DataStorage

private String account, username, password;

The variables should be final. By convention, there should be just one variable per line.

public void CreateXML() throws Exception

catch(ParserConfigurationException | DOMException | IllegalArgumentException | TransformerException exc)
{
exc.printStackTrace();
}

Wouldn't be a throws clause better? Printing the stack trace doesn't look like it solved the problem, does it?

(*) Many thanks Sun for this ugliness. Other languages (e.g. perl) simply guarantee that / works everywhere.

• Well, I do thank you for your input on everything. As I said this is merely a personal code project to attempt to learn things that I have not previously been exposed to. You make several extremely valid points and I will take them and go back to try and make the code better and more functional. As for the comments those were merely my personal reminders. I know the method should be self explanatory but on my personal things I like to just jot something down for personal remembrance. Thank you for you tips and I will go back and make it not ugly and moronic. – basic Jun 25 '15 at 20:07
• @xXspynXx You're welcome. And thank you for the kind words. It wasn't "ugly and moronic", it's just that there's always a lot to say. Have fun! – maaartinus Jun 25 '15 at 20:15
• haha quite welcome like always I came here for some advice and guidance and you followed through :) so thank you for that! – basic Jun 25 '15 at 20:18

In createKeyStore you don't actually use the first parameter path. Instead you default to home always.

The home field is a File path and everywhere you use it (except in one of the calls createKeyStore where it doesn't have any effect) you use it as such; so you may as well store it as a File and make it clear.

This lets you avoid the \\ vs / and use the constructor that always works:

home = new File(System.getProperty("user.home"), "dataStore.keystore");


text:
# Learning Tutorial

In this tutorial we set up a simple linear chain CRF, such as the one used for part-of-speech tagging, named-entity recognition, or noun phrase chunking. It will be our running example in this tutorial, but most of the things we’ll discuss generalize all across Factorie.

package cc.factorie.tutorial
object Tutorial60Learning extends App {
import cc.factorie._
import variable._
import cc.factorie.app.nlp._
import cc.factorie.app.chain._
import cc.factorie.optimize.{ SynchronizedOptimizerOnlineTrainer, Trainer, SampleRankTrainer }
import cc.factorie.infer.{ GibbsSampler, InferByBPChain }

implicit val random = new scala.util.Random(0)

First we create domains representing the labels and features.

  object LabelDomain extends CategoricalDomain[String]
class Label(val token: Token, s: String) extends LabeledCategoricalVariable(s) {
def domain = LabelDomain
}
object FeaturesDomain extends CategoricalVectorDomain[String]
class Features(val token: Token) extends BinaryFeatureVectorVariable[String] {
def domain = FeaturesDomain
}

The ChainModel class implements a default model for linear chains. It by default implements all the factor templates one expects from a linear chain model, with the exception that the (label, label, features) template is optional.

As we saw in the Model tutorial, a model in Factorie is an object that can take some variables and return some factors, which know how to score assignments of those variables. So models store weightsSet, and things like that.

To construct a chain model you need to give it a few things. First, the domains of the labels and the token features. Then, functions that can take a label to its feature vector, a label to its token, and a token to its label. These functions are used by the ChainModel class to generate factors.

  object model extends ChainModel[Label, Features, Token](
LabelDomain,
FeaturesDomain,
l => l.token.attr[Features],
l => l.token,
t => t.attr[Label])

// The Document class implements documents as sequences of sentences and tokens.
val document = new Document("The quick brown fox jumped over the lazy dog.")
val tokenizer = new app.nlp.segment.DeterministicTokenizer
tokenizer.process(document)
val segmenter = new app.nlp.segment.DeterministicSentenceSegmenter
segmenter.process(document)
assertStringEquals(document.tokenCount, "10")
assertStringEquals(document.sentenceCount, "1")

// Let's assign all tokens the same label for the sake of simplicity
document.tokens.foreach(t => t.attr += new Label(t, "A"))
// Let's also have another possible Label value to make things interesting
LabelDomain.index("B")
// Let's also initialize features for all tokens
document.tokens.foreach(t => {
val features = t.attr += new Features(t)
// One feature for the token's string value
features += "W=" + t.string.toLowerCase
// And one feature for its capitalization
features += "IsCapitalized=" + t.string(0).isUpper.toString
})

Now that we have one sentence and a model we can start to do inference in it.

Inference in Factorie is abstracted in objects that implement the Infer trait, which has one method, infer, that takes a sequence of variables, a model, and an optional Summary, and returns a Summary object with the result of inference.

A Summary object has two essential pieces of information in it: it allows you to compute the normalization constant of the model (useful for learning), and it can return marginal distributions over subsets of variables in your model. It also knows how to turn these marginals into expected sufficient statistics for learning.

The most commonly used Infer objects are those in the BP package.

  val summary = InferByBPChain.infer(document.tokens.toSeq.map(_.attr[Label]), model)
assertStringEquals(summary.logZ, "6.931471805599453")
"Proportions(0.49999999999999994,0.49999999999999994)")

Aside from InferByBPChainSum, which knows how to run forward-backward on chain models Factorie has MaximizeByBPChain, which runs viterbi, InferByBPTreeSum, which runs BP on trees, and InferByBPLoopy which runs loopy belief propagation.

For more inference tools see the Inference tutorial.

One of the main uses of inference is in learning.

The learning infrastructure in Factorie is made of three components which can be mixed and matched at will.

An Example abstracts over a piece of data and knows how to compute objectives and gradients.

GradientOptimizers know how to update a model’s weightsSet given gradients and values.

In the middle between Examples and GradientOptimizers we have Trainers, which control when the gradients are evaluated, where they are stored, the degree of parallelism, etc.

The most common example one uses is the LikelihoodExample, which computes the value and the gradient for maximum likelihood training. Here’s how to construct one for this sentence using Factorie’s BP inferencer.

  val example = new optimize.LikelihoodExample(document.tokens.toSeq.map(_.attr[Label]), model, InferByBPChain)

In this tutorial let’s use the AdaGrad optimizer, which is efficient and has per-coordinate learning rates but is not regularized

  val optimizer0 = new optimize.AdaGrad()

To learn a model the simplest way is to call Trainer.onlineTrain. This will optimize the parameters with AdaGrad and parameter averaging using SGD.

  Trainer.onlineTrain(model.parameters, Seq(example), optimizer = optimizer0)

// Factorie also supports batch learning. Note that regularization is built into the optimizer
val optimizer1 = new optimize.LBFGS with optimize.L2Regularization
optimizer1.variance = 10000.0
Trainer.batchTrain(model.parameters, Seq(example), optimizer = optimizer1)

Factorie also supports other batch trainers. The ParallelBatchTrainer keeps a per-thread gradient vector and aggregates all gradients before sending them to the optimizer, while the SynchronizedBatchTrainer keeps a single gradient vector and locks it.

Also note that all online optimizers can be used with the batch trainers, but not the other way around.

One can also not call Trainer.onlineTrain or Trainer.batchTrain and create a Trainer explicitly. A Trainer is a policy object which is responsible for deciding which gradients are evaluated, when, and in which threads, and when these gradients are given to the optimizers.

All trainers inherit from Trainer. To create a trainer, simply instantiate it.

  val trainer = new SynchronizedOptimizerOnlineTrainer(model.parameters, optimizer0)

To use the trainer we can either call .trainFromExamples or call things in a loop:

  trainer.trainFromExamples(Seq(example))
// or
while (!trainer.isConverged) {
trainer.processExamples(Seq(example))
}

Some trainers might require some tear down after training for optimal usage. See the implementation of Trainer.train for an example of how to do so.

Factorie also has many other optimizers. Usually AdaGrad with ParameterAveraging is a good bet, but often one wants something more specific.

There are two main regularized online optimizers in Factorie: AdaGradRDA, which uses regularized dual averaging and supports l1 and l2 regularization, and L2RegularizedConstantRate, which supports only l2 regularization. Neither of these optimizers support parameter averaging.

  // Now we can run inference and see that we have learned
val summary2 = InferByBPChain(document.tokens.map(_.attr[Label]).toIndexedSeq, model)
assertStringEquals(summary2.logZ, "48.63607808729122")
"Proportions(0.9999308678897892,6.913211020966629E-5)")

Factorie also has support for more efficient learning algorithms than traditional inference-based batch and online methods.

The main such method is SampleRank, which runs a sampler and updates the weightsSet while the sampler explores the posterior to make the model’s predictions match an arbitrary loss function.

  val sampler = new GibbsSampler(model, HammingObjective)
val sampleRankExamples = document.tokens.toSeq.map(t => new optimize.SampleRankExample(t.attr[Label], sampler))
Trainer.onlineTrain(model.parameters, sampleRankExamples, optimizer = optimizer0)
// SampleRank comes with its own trainer, however, for ease of use
val trainer2 = new SampleRankTrainer(model.parameters, sampler, optimizer0)
trainer2.processContexts(document.tokens.toSeq.map(_.attr[Label]))
}

Finally, there are many other useful examples in Factorie. The LinearMulticlassExample implements generalized linear models for many classification loss functions, for example, and the DominationLossExample knows how to do learning to rank.