I have two orthonormal vectors and a fixed vector b. I need to show orthogonality of the "error vector"

Question: I have two orthonormal vectors $q_1$ and $q_2$ and a fixed vector b. The first part of the question was to find the optimal linear combination $\alpha$$q_1$+$\beta$$q_2$ that is closest to b in the 2-norm sense. I believe that $x=Q^T$$b$. For the second part of the question I have the "error vector" $r=b-\alpha$$q_1$$-\beta$$q_2$ and I have to show this is orthogonal to $q_1$ and $q_2$. Can I do this by showing that the projection of b into the range of Q is in the range of Q? Am I even on the right track? Thanks
Answer: let the error vector $\epsilon$ be defined by $$b = (q_1^\top b) q_1 + (q_2^\top b) q_2 + \epsilon \tag1$$ $(1)$ implies that $\epsilon$ is orthogonal to $q_1, q_2$ and in fact is orthogonal to any linear combination of $q_1, q_2.$
we will use the phythagors theorem to show that $(q_1^\top b) q_1 + (q_2^\top b) q_2$ is the closest vector in the span of $\{q_1, q_2\}.$  consider $$b - \alpha q_1 -\alpha q_2 = (q_1^\top b - \alpha) q_1 + (q_2^\top b -\beta) q_2 + \epsilon \tag 2$$ since $(q_1^\top b - \alpha) q_1 + (q_2^\top b -\beta) q_2$ and $\epsilon$ are orthogonal,
$$\begin{align}| b - \alpha q_1 -\alpha q_2|^2 &= |(q_1^\top b - \alpha) q_1 + (q_2^\top b -\beta) q_2|^2 +|\epsilon|^2\\
&\ge |\epsilon|^2 = |b -(q_1^\top b) q_1 + (q_2^\top b) q_2|^2\end{align}$$
Answer: Since $x=Q^{T}b=\left(q_1^{T}b\right)q_1+\left(q_2^{T}b\right)q_2$,
$\;\;\;r=b-\left(q_1^{T}b\right)q_1-\left(q_2^{T}b\right)q_2$;
so you just need to show that $q_1^{T}r=0$ and $q_2^{T}r=0\;\;$  (using that $q_1$ and $q_2$ are orthonormal).


Where is the iPhone app EULA displayed for the user?

Question: I am planning to submit an iPhone app for certain special purpose calculations. I want to add a legal disclaimer about the calculations somewhere so that the user can see it atleast once before starting to use the app. Should this go into the EULA that may be submitted as part of app submission process? Or should that be a one time screen shown when the app is started first time? What is the right way?
Thanks for responses.
Answer: The EULA would be submitted as part of your delivery to the App Store, so as to be displayed alongside the app's entry in the Store (so the user can read prior to purchase).
But you'd also be well-advised to display the very same language the first time the app is launched, prompting the user to "Accept".  (Ideally, if it's more than one page, you can make it so the Accept button is disabled until the user scrolls to the bottom of the text.)
If you want to be even more thorough, you could prompt the user to accept the EULA the first TWO times the app is run, just to be safe.
Hope this helps!
Comment: Why did someone downvote this? It is correct. The EULA is submitted as part of the submission process through iTunes Connect. The user can view it on the App Store via iTunes or the App Store app on the iPhone. It is completely up to the developer of the app whether or not they think the EULA should be shown when the App starts or not, but the EULA should be made available in the app in some way, at least, whether its via a link to a website containing it or it being embedded in the app.
Comment: Upvoted! ;) Followup question: What is a good practice to follow when you have your own EULA, for DIFFERENT COUNTRIES, and you are required (by the client) to show it in-app? Show 'em all in one long list? Assume an auto-selection based on l10n? (ehhhh.) Make them choose? (Ugh.) Suggestions/BPs welcome!
Comment: Thank you, Jasarien!  You're correct, this wasn't supposed to be legal advice -- it was an unstated assumption that legal matters should be referred to qualified professionals, and this wasn't intended to be a substitute for that.  My answer was a practical one of implementation, and which touched on specifics of the attendant user-interface design.  So, thanks for your vote of confidence.  I hope others find these ideas helpful as well.
Answer: Show it first time the app is shown, or if it isn't crucial, add a mention in the app description.


Probability that both people flip their first tails on the same round?

Question: Sarah and Paula are flipping coins. During each round, each one flips a fair coin and then they compare their results. What is the probability that both girls flip their first tails during the same round?
Comment: And what have you done so far on this?
Comment: This is equivalent to asking, on a given series of flips, what is the probability of getting an even number of heads followed by two tails.  I'm not sure if this is an easier situation to analyze, but it does have the benefit of only dealing with one series of coin flips instead of two.
Answer: Since they flip the coins independently the event is in fact which each of them draws $\{T,HT,HHT,HHHT,...\}$ with probability so the general probability is $$P=Pr\{(T,T),(HT,HT),(HHT,HHT),(HHHT,HHHT),...\}=\dfrac{1}{4}+\dfrac{1}{16}+\dfrac{1}{64}+...=\dfrac{1}{3}$$
Answer: The rounds that give two heads can be neglected.
Looking at the first round that gives at least one tail let $T$ denotes the number of tails is that round.
Then you are asked to find: $$P(T=2\mid T\geq1)=\frac{P(T=2)}{P(T\geq1)}=\frac{1/4}{3/4}=\frac13$$


How is rainfall measured when the news speaks of "two inches of rain"

Question: I left a wheelbarrow outside overnight and it rained heavily. This morning, the water in the wheelbarrow is five (5) inches deep. It's not sitting under an eave where water might have been channeled to it, but out in the back yard fully exposed to the sky. And it's sitting quite level; I'm not measuring "at the deep end". The weather news is saying we had two (2) inches of rain. Are there local pockets of heavier rain that would explain the discrepancy, or is the wheelbarrow not an appropriate way to measure rainfall? Is there some sort of averaging involved?
Comment: Does this answer your question? [What does a mm of rain mean?](https://earthscience.stackexchange.com/questions/14587/what-does-a-mm-of-rain-mean)
Comment: See also: [what does a mm of rain mean](https://earthscience.stackexchange.com/questions/14587/what-does-a-mm-of-rain-mean/14589) ?
Comment: Hi. Requesting three clarifications: (1) Does your wheelbarrow have a perfectly constant horizontal section, like a cylinder or rectangular cuboid?; (2) How large an area did this weather news cover? Rain can be very localised, so saying "it rained an average of 2 inches over the whole city" is not the same thing as saying "it rained 2 inches in my garden"; (3) You left the wheelbarrow overnight: did the weather news use the word "overnight" or "over the last xx hours" or something different?
Comment: @Stef On the road, sorry for the delay in responding.  The wheelbarrow does have a curved "lip" in the front that would increase the catchment surface area by a little, say 10%; not enough to explain the rather egregious difference between the reported 2 inches and my 5. I think the phrase was "in the past 24 hours", but that only increases the discrepancy, since I left the wheelbarrow exposed for only about 12 of those hours.  I've been told by a neighbor that the news I heard may rely on the gauges at the international airport which is about 5 miles away.
Comment: I've known rain to follow a road, in that one side was dry while the other side was overflowing the gutters. Weather can absolutely be very localized, and in fact often is. https://scifi.stackexchange.com/a/270191/47955
Comment: Well, if it's more than 2 inches in an hour you can measure it by the number of cars floating down your street! ;-)
Comment: Speaking of floating cars, when I was 15 I managed to barely stay above the [Rapid City Flood](https://www.visitrapidcity.com/blog/post/1972-black-hills-flood-remembering-disaster-and-rebuilding-rapid-city/). And that was "just" 10 inches over 12 hours.
Comment: @OrangeDog  I will have to find out if that is how it is being done and reported here locally, or if there is some sort of translation/restatement involved.
Answer: A wheelbarrow is usually considerably wider at the top than at the bottom, so the accumulated water at the bottom will likely be deeper than what actually fell.
However, rainfall can also have considerable variation in space.  I often see reported rainfall totals being for the local airport or similar.  For example, if this rainfall were reported for the airport (northeast of the highway intersection in the little black outline), people a short ways southwest would have gotten half again more rain.

Averaging will depend on what's being reported.  As mentioned, it's often at the airport or similar, but you can also see area-wide averages.  Any given reporting method could still vary significantly from the precipitation at a given point unless it's measured right there.
Answer: Weather stations measure the depth of rain that falls over a small, set area by setting an open topped cylinder of precise diameter in the open at a standard height above the ground and measuring how high the water rises within it over (usually) a 24 hour period. A standard 8"/203mm diameter is widely used for weather station rain gauges but is not required to give accurate measurements.
At its simplest the height of the water within the cylinder - which must be flat bottomed as well as the same diameter top to bottom is measured. Buckets, wheelbarrows that are wider at the open top than the bottom - or jars that are smaller at the top - are not suitable.
In practice, to make it easier and for greater accuracy a separate calibrated measuring cylinder of smaller diameter is used to measure what has collected. Each mm or inch marked on the measuring cylinder is equivalent to one mm or inch in the collecting cylinder.
(The use of a separate measuring cylinder - or automated measuring equipment - means the collecting container shape or size becomes irrelevant. Measurement is calibrated to the size of the opening - the top rim of brass in the example shown. Automated rain gauges are becoming more common.)
Comment: Interesting.  I'd expect the funnel to be deeper the tube to prevent rain splashing out.
Comment: @chux-ReinstateMonica - I've done the duty myself a few times; the gauge I handled looked well optimised, including a sharpish inside edge to the precise brass rim, that would slice raindrops. The funnel starts a bit down from the rim. Seemed well designed for avoiding splash back out.
Answer: In addition to what others have mentioned, sometimes measurements are simply wrong, in particular where measurements are automated.
Some weeks ago, two weather stations in Germany reported over 60 mm of rain, when all the others nearby reported zero, radar reported zero, model reported zero, and satellite imagery was not consistent with precipitation.  What was going on?  You would think that automatic rainfall measurements shouldn't be too hard?  Those were automated weather stations with automated rain gauges.  During those erroneous measurements, there was a snowpack that was melting.  Most likely, rather than measuring rainfall, those gauges had been measuring snowmelt and reporting it as rain.  Since there's nobody present at weather stations in Germany any more, this will remain a hypothesis and it's up to the data users to filter out measurements that are clearly wrong.
There are many other things that can go wrong with automated weather stations, but they satisfy politicians who want to reduce public spending, so...
Comment: As a scientist, and having supervised student projects, sooner or later something will always go wrong.  An additional data source makes a big difference.  Here it could be a camera covering the weather station; I've used a combination of weather data and an insistence on logging against wall-clock time to find glitches caused by sunlight getting past the blind onto the experiment in the lab.
Comment: There was a story back when I was a student where some unexpected rain occurred.  Turned out a drunk guy ended up using it for a restroom(!?!) :-p  You are right that previous ice can wind up measured as rain (though that's why the highest standard typically are heated).  The data that goes public (at least from the main instruments in the US) also gets automatically quality controlled to look for odd anomalies like that.  I like weather, but honestly would think there's a lot of better things to spend money/time on. Though I think we may still have weather observers at certain large airports
Comment: @JeopardyTempest True, there is quality control, and snowmelt is not supposed to end up being measured as rain when asking the manufacturer, and weather stations are supposed to be fenced to avoid such drunks as you mention, but there certainly wasn't 60 mm of rainfall at those stations some weeks ago.  Maybe the explanation is a different one, but in any case quality has gone down since widespread automation (I think airports are also here the only ones that still have humans, but they're working on automating those too; the barrier for doing so is much higher, though).
Comment: @chrish I'll be honest, don't know why don't work to add them at asos sensors, as you're absolutely right.  Wonder if the power/data profiles would be quite significantly challenged???
Comment: @JeopardyTempest I suspect cost.  And someone would have to ensure that every installation was acceptable for privacy (i.e. only looking at the kit, but OTOH you do want to include some background for maximum usefulness). You don't need live video for troubleshooting, or massive resolution, after all
Answer: Properly designed rain gauges can give accurate results for a given location or point in space, but the problem is that it's hard to have enough of them packed densely enough in an area to give the level of detail that you might see in maps on news stations or weather websites. Models and extrapolation can fill in the gaps to a degree, but there could be a lot of error with it.
On the other hand, Doppler radar (a remote sensing tool) can measure the type and intensity of precipitation at various altitudes across an area with a radius of 100+ miles. By "scanning" periodically (it might miss very short bursts of precipitation!), this data can give a pretty good idea of what the accumulation was to a pretty fine level of spatial detail. It's the data used to create those animated maps showing the progress of a storm you might see on news channels or weather websites. Ground stations/rain gauges are then used to calibrate/verify the Doppler data; you don't need many of them for this purpose.
As others mentioned, a wheelbarrow will likely overestimate how much rain accumulates. But also, the models that use the Doppler data to create precipitation accumulation estimates won't be 100% perfect; averaged across a large area (or time), they're probably really good, but as you start to zoom in towards a small enough area or point, you could very well see some deviation (variance) from the true amount.
Here are a few links related to the topic of weather radar and precipitation accumulation (I'm not an expert by any means):

(Wikipedia) Weather Radar: Accumulations
(Wikipedia) Rain: Measurement
National Weather Service (United States): About our WSR 88-D Radar
Comment: Note that radar measurements also have error, in particular since they cannot measure close to the ground, where precipitation happens.  The farther from the radar, the larger the blind zone near the surface.  Some rain evaporates on the way down, or rain  accumulates in a vertical column.
Comment: As maybe hinted at, radar also has another issue: the relationship between Z (radar reflectivity) and R (rainfall rate) are not one-to-one; a certain reflectivity can in reality be a range of droplet size\shape distributions.  Higher reflectivity of course means higher rate... but it's not as cut and dry to figure out the rainfall values (and different Z-r ratios are used for different weather).  The implementation of polarmetric radar helps some, allowing a better idea of shapes and separate contributions of different frozen shapes and such.  But it's still a complex science.
Comment: In fact, each radar has its own unique patterns too, in part because of slight differences in equipment and environment.  So altogether, thus, ground truth is important in calibrating continually.  [See also](https://all-geo.org/highlyallochthonous/2020/03/measuring-precipitation-radar-and-satellite-based-measurements/)
Answer: It's the depth of water in a container of any arbitrary size (more specifically, arbitrary area of ground it covers¹, the height has to be enough to measure the volume of rain that fell) with a perfectly flat bottom and perfectly vertical sides, collected over the course of the entire period of rainfall.
This is a proxy for the volume of water that fell, but is particularly useful because it's invariant of the total area that the water fell over¹ and can thus be easily used to calculate the volume for any given area of interest (because you can just multiply it by the area, instead of having to know the size of the measurement container and rely on ratios like you would if you just used the volume). This ability to use quick math to figure out the volume for a given area of ground is really useful because it lets you more quickly calculate:

How much the level of a lake is likely to rise as a result of runoff from the rainfall.
How much the flow rate of a river or stream is likely to change given the rainfall (this is super important for ships navigating the river).
How much water needs to be let through a dam to maintain a constant reservoir depth given the rainfall.
How much water needs to be used when irrigating a field to ensure the crops are not over or under watered.
How likely it is that ponding (buildup of standing water in areas with poor drainage) will occur in a given area.

But, for such measurements to be accurate, the container used for measuring must be designed to actually make the measurements. This means that the bottom must be flat and level, and that the sides must be perfectly vertical and perfectly parallel to each other. A wheelbarrow almost never meets those requirements.
Additionally, these measurements are almost always taken at some central location for the region being covered. Quite often it's based on the nearest airport, seaport, or military installation as they typically have very accurate weather stations. Otherwise, it may be some government operated weather station in the region, or possibly a station operated by whatever entity is providing the reporting. If you're more than a few kilometers from the measurement site, you're actually reasonably likely to see different numbers².

1: I mentioned above that the measurement container can cover any area, and that the depth is invariant of the total area covered. This may seem unintuitive, but it's actually a logical side-effect of the random nature of precipitation when observing at the scale of individual raindrops or snowflakes. If you have a infinitesimally small point, the probability that it gets hit by a raindrop in a rainstorm follows a (roughly) uniform distribution dependent on the rate of rainfall (unless there are objects nearby that might obstruct the flow, in which case their positions together with the wind direction and speed also influence the probability). Because of the law of large numbers, this means that any two arbitrary points near each other will see roughly the same number of raindrops hit them in a rainstorm, provided enough total raindrops fall proportionate to the area the storm covers (which almost always happens). This same effect is why the ground eventually ends up uniformly wet during a rainstorm no matter the rate of rainfall.
2: In contrast to the point above about small-scale uniformity of precipitation, when measuring at large scales there's quite a bit of variance (otherwise meteorology would be a much simpler science with far more accurate predictions), and the possible variance increases proportionate to the distance between the measurement sites. What this means is that the further away you are from the site the data you're seeing is being measured at, the more likely it is that you will see different measurements locally.
Comment: For some reason, your answer reminds me of [Is it better to walk or run in the rain?](https://www.youtube.com/watch?v=3MqYE2UuN24)


Yahoo Pipes - Return items in a feed by range?

Question: There exists an RSS feed with over 1000 items.  I want to create a Yahoo Pipes RSS feed that returns a subset of the feed's items, specified by the index of the first and last item.  For example, I could pass in first=500 and last=600, and the Pipe will return an RSS feed with only the 500th through 600th itemd in the source feed.  Is this possible with Yahoo Pipes, and if so can someone point me in the right direction?
Answer: Figured it out... use the truncate filter followed by the tail filter with inputs a and b respectively.  This results in [a-b:a] items.
Answer: As you figured out so rapidly, the best way to work with Yahoo pipes is to think much like you would when making up a Unix pipeline -- here, the obvious Unix pipeline would be to take the tail of the head, and the Yahoo pipes approach is perfectly analogous (except that by calling 'head' by the name of 'truncate' they're putting a little obstacle in your way;-).


.NET Generic Parameters for Generic Lists

Question: Running .NET 2.0, I have a generic method with the following signature:
static listType FillCollection<listType, objType>(IDataReader dr) where listType : ICollection<objType>, new()

it's purposes is to translate a datareader into a collection of objects both of my choosing.  My problem, which isn't exactly a problem, is that when I call it, the call ends up looking something like this:
List<MyObject> data = FillCollection<List<MyObject>, MyObject>(dr);

I'm curious if there's a way to cut out the redundancy of having to specify MyObject twice in the call.  Ideally, I'd be able to only specify it once, along with the collection type and maintain the strong typed nature of the method.  Adding another wrapper method to abstract the ICollection type sorta does the trick:
List<MyObject> data = FillList<MyObject>(dr);

static List<objType> FillList<objType>(dr)
{
    return FillCollection<List<objType>, objType>(dr);
}

But I'd rather not have a wrapper method for every collection i want to use.
Maybe I have no choice in the matter, but if so, I don't have to like it! ;)
Thanks!
Answer: This might be something worth trying:
static listType FillCollection<objType>(IDataReader dr, ICollection<objType> list)

This would let you call it without specifying the type twice, but you'd be forced to create the collection outside of FillCollection.
var list = new List<MyObject>();
var data = FillCollection<MyObject>(dr, list);

Probably not what you were hoping for since you still refer to MyObject twice (once in the creation of the List and another in the FillCollection), but I don't think you're going to be able to get away from that without losing strong typing.
Answer: If you use Visual Studio 2008, you can still target .NET 2.0, but use C# 3.0 syntax. This means you can use the "var" keyword:
var data = FillCollection<List<MyObject>, MyObject>(dr);

When you're using Visual Studio 2005, you're out luck I'm afraid.
Comment: I think he wanted to avoid specifying MyObject twice in the method call, like you're still doing. I could be wrong though.
Comment: Hmmm... I didn't read it like that. But there's only one person who can help us out. Wes? What did you mean?
Comment: Lasse's correct, that was what I was trying to avoid.

But I'm still on VS2005, so no var.
Answer: Could you use var?
Answer: Personally, I'm not really sure why you need your method to be able to create multiple different implementations of ICollection. My inclination would be to have a method signature as follows, and just create a List inside the method and return it.
static ICollection<T> FillCollection<T>(IDataReader dr) where T : class, new()

If that's not acceptable, then I'd go with Joseph's answer.
Comment: Marked this one as correct as it's a better way to do what I was doing.  But the goal of my question was to see if there was a more implicit way to handle generic types between generic methods and the generic types being assigned to.  There really isn't.
Answer: Sort of going off of what Joseph mentioned, I've used "out" parameters in the past with good results, but never with one generic type relying on another one without taking or returning a value of that type. Anyway, you could do something like this, though you'd have to have a list of objTypes and a single object of objType declared outside of the call to FillCollection, and FillCollection would become void. Here's what it would look like, but whether or not it's a good idea to increase readability is up to you.
public static void FillCollection<listType, objType>(IDataReader dr, out listType collection, out objType obj)
    where listType : ICollection<objType>, new()
    where objType : new()
{
    collection = new listType();
    obj = new objType();

    // Do whatever you do to fill the collection
}

public static void TestFillCollection()
{
    IDataReader dr;
    List<MyObject> myObjects;
    MyObject myObject;

    FillCollection(dr, out myObjects, out myObject);
}


What properties are most important for a fluid in the generation of steam power?

Question: I was curious if water is the most efficient fluid for use in generating steam power. I thought it might be, since it has the highest latent heat of evaporation of any fluid. I wasn't sure if other properties were more important, though, like he density of the fluid or its boiling point.
Comment: What is **your** definition of "efficiency"?
Comment: @SolarMike Producing more net energy/power? That's how I figured efficiency is measured, production. I was curious if something was technically better than water for steam engines.
Comment: Efficiency can be many things, like quickest time or lowest power use. If you are not clear then are ee expected to guess?
Comment: @SolarMike Title has power in it. That's what I mentioned in the comment. Power is in the tags, and in the question description. So I'm not sure how much clearer I can be, or why you need to guess.
Comment: @SolarMike I found this, which defines power efficiency more exactly: https://www.rapidtables.com/electric/efficiency.html Sorry for not being more exact about what I meant before, I took it for granted that this is how power efficiency is defined.
Answer: Is it the most efficient?  Maybe or maybe not, but it is an outstanding medium to turn into vapor for use in a turbine.  It is extremely plentiful, the heat of vaporization is high, and it is easy to work with.  It isn't toxic or corrosive and is easy to dispose of.  Pumps to work with water are ubiquitous, and cheap to make because you can use the medium to cool the packing - it's generally okay to have a water pump that leaks a bit.  The technology to maintain water boiler chemistry is well known and hasn't changed significantly in at least 50 years.
There are other liquids that can be used to transfer heat (brine, glycol, even liquid sodium) but they all have negative qualities and none are used for turning to vapor in a relatively open system, which is what a steam cycle is.  Refrigerants are chosen for their properties of evaporation at varying pressures, no one tries to run a turbine with them.
Comment: These are good points, thank you. I would like to know about the efficiency, though. If there were a liquid with a higher LHoE, would it be more efficient, for example?


Modifying Live Call through REST API, how to pass parameters to Twiml URL

Question: I want to pass some parameters through to twiml script that will be executed as a result of a call update https://www.twilio.com/docs/api/rest/change-call-state. The parameters of a get are not being passed through.
Answer: Twilio employee here. An HTTP GET request will not work, you need to make a HTTP POST instead.
Look at the XML and JSON examples on the doc page that you linked.


Problem cloning root and home before doing an upgrade from Trusty to Utopic

Question: I'm trying to copy root and home to other partitions on my notebook
internal drive and then boot from them (root2 and home2).
Once it works, it can be an (almost) live backup or I could upgrade from
Kubuntu Trusty to Utopic on the new partitions and smooth out any
wrinkles while still having Trusty working in the other partitions so I
can continue to get things done.
I copied home too because I don't want to have to deal with things like
config file changes in Utopic which might screw up Trusty when I boot
back into it.
(I had some fun with that on my other notebook when I upgraded from
Oneiric to Precise using a separate partition for root, but just one
home. Some things went a bit bonkers.)
It didn't quite work, so I must have missed something.
Here's what I did:
Used gparted to reformat /dev/sda5 and /dev/sda7 as ext4 (which should
have cleared out what was on them) and labeled them as root2 and home2
again.
Stopped user tasks that modify files like bittorrent. (But I didn't boot
from a live CD, etc.. I made the copies on the running system.)
Used rsync to copy everything with permissions, etc. preserved from root
(/dev/sda3) to root2 (/dev/sda5)
and from home (/dev/sda6) to home2 (/dev/sda7). (sda3 and sda5 are both
the same size as are sda6 and sda7.)
I don't think it makes a difference, but sda3 is labeled "root", sda5 is
labeled "root2", sda6 is labeled "home" and sda7 is labeled "home2".
Mounted /dev/sda5 on /media/bigbird/root2
Edited /media/bigbird/root2/etc/fstab and changed the uuids for root and
home to the ones for /dev/sda5 and /dev/sda7.
(Got them by running ls -l /dev/disk/by-uuid and copy and pasting them.)
Ran grub-customizer which updated the boot menu to show the new OS on
/dev/sda5.
Thought I was done and rebooted, selecting the OS on /dev/sda5 on the
grub2 menu.
Boot looked fine, but when I ran df, it showed root as /dev/sda3 and
home as /dev/sda6 - like nothing had changed.
Mounted /dev/sda5  again and verified that my changes to fstab were
still there. They were.
Noticed that /etc/fstab~ was left over from the editing and deleted it.
Tried to get online, but couldn't. My wifi said it was connected, but
there was a second instance of the connection available that should not
have been there. Tried to connect to that, which appeared to work, but I
still couldn't get online.
Rebooted into my original partition (/dev/sda3) - which still works fine
and has no problem coming online.
Apparently, I've missed some steps needed to make this work.
Also, I seem to have made my router unhappy because it wouldn't let me
connect to the Internet when I booted the new way. I didn't try to just
login to the router.
It did seem a little too simple just to copy everything, change fstab,
grub, and reboot.
What do I need to do to get this to work?
EDIT:
I have included my fstabs and some other stuff showing what the UUIDs are below.
What looks like the immediate problem is that grub.cfg is messed up on both partitions.
In the first code block below is a snip of it which shows the schizophrenic entry for sda5 with the root partition set correctly, but with the boot image set to use the one on sda3. (Other entries have the same problem.) It may have other errors. I'm not familiar with it enough to know. (FYI: the kernel versions on sda5 are a little old because I have done updates on sda3 since copying it and haven't run the rsyncs again yet.)
I just looked at the grub entry again and I can't see how it worked at all! It looks like it's looking for kernel 46 on sda3 - which doesn't exist. That older kernel is only on sda5 because I haven't run the rsyncs again yet.
This could be something caused by grub-customizer. I don't know. It probably needs to be fixed before looking for other problems.
Since this file is generated, I need to fix it indirectly, but I don't know how to do it.
/boot/grub/grub.cfg snipped:
### BEGIN /etc/grub.d/30_os-prober_proxy ###
menuentry "Kubuntu 14.04.2 LTS (14.04) (on /dev/sda5) Testing/backup" --class gnu-linux --class gnu --class os $menuentry_id_option '$
        insmod part_msdos
        insmod ext2
        set root='hd0,msdos5'
        if [ x$feature_platform_search_hint = xy ]; then
          search --no-floppy --fs-uuid --set=root --hint-bios=hd0,msdos5 --hint-efi=hd0,msdos5 --hint-baremetal=ahci0,msdos5  2540779$
        else
          search --no-floppy --fs-uuid --set=root 2540779b-43d7-4e38-a227-68057afceb47
        fi
        linux /boot/vmlinuz-3.13.0-46-generic root=UUID=9aae2d22-4393-436a-a505-130db27e0e55 ro quiet splash $vt_handoff
        initrd /boot/initrd.img-3.13.0-46-generic
}

fstabs and UUID info:
sda3 (current working root partition)

bigbird@ramdass:/etc$ cat fstab
# /etc/fstab: static file system information.
#
# Use 'blkid' to print the universally unique identifier for a
# device; this may be used with UUID= as a more robust way to name devices
# that works even if disks are added and removed. See fstab(5).
#
# <file system> <mount point>   <type>  <options>       <dump>  <pass>
proc            /proc           proc    nodev,noexec,nosuid 0       0
# / was on /dev/sda3 during installation
UUID=9aae2d22-4393-436a-a505-130db27e0e55 /               ext4    errors=remount-ro 0       1
# /home was on /dev/sda6 during installation
UUID=1be3e600-6582-4fe6-a8bc-b5479f1444b1 /home           ext4    defaults        0       2
# swap was on /dev/sda8 during installation
UUID=3d9fe1af-25fe-4d28-82c9-5c2b4d895b79 none            swap    sw              0       0
bigbird@ramdass:/etc$

sda5 (copy of sda3 to be used as a fall back if the upgrade goes south, etc.)

bigbird@ramdass:/media$ sudo mount /dev/sda5 /media/work
bigbird@ramdass:/media$ cd work
bigbird@ramdass:/media/work$ ls
bin   C:\nppdf32Log\debuglog.txt  dev  initrd.img      lib    libnss3.so  opt   run   srv  var      vmlinuz.old
boot  Desktop                     etc  initrd.img.old  lib64  lost+found  root  sbin  usr  vmlinuz
bigbird@ramdass:/media/work$ cd etc
bigbird@ramdass:/media/work/etc$ cat fstab
# /etc/fstab: static file system information.
##JJP Modified for root2 and home2
#
# Use 'blkid' to print the universally unique identifier for a
# device; this may be used with UUID= as a more robust way to name devices
# that works even if disks are added and removed. See fstab(5).
#
# <file system> <mount point>   <type>  <options>       <dump>  <pass>
proc            /proc           proc    nodev,noexec,nosuid 0       0
# / is on /dev/sda5 (root2)
UUID=2540779b-43d7-4e38-a227-68057afceb47 /               ext4    errors=remount-ro 0       1
# /home is on /dev/sda7 (home2)
UUID=8e3aca35-c376-4a71-b6be-5c3c063a184b /home           ext4    defaults        0       2
# swap was on /dev/sda8 during installation
UUID=3d9fe1af-25fe-4d28-82c9-5c2b4d895b79 none            swap    sw              0       0
bigbird@ramdass:/media/work/etc$

bigbird@ramdass:/media/work/etc$ ls -l /dev/disk/by-uuid
total 0
lrwxrwxrwx 1 root root 10 Apr  9 03:53 0A1258CF1258C0FD -> ../../sda2
lrwxrwxrwx 1 root root 10 Apr  9 03:53 180E32C60E329CA6 -> ../../sda1
lrwxrwxrwx 1 root root 10 Apr  9 03:53 1be3e600-6582-4fe6-a8bc-b5479f1444b1 -> ../../sda6
lrwxrwxrwx 1 root root 10 Apr  9 03:53 2540779b-43d7-4e38-a227-68057afceb47 -> ../../sda5
lrwxrwxrwx 1 root root 10 Apr  9 03:53 3d9fe1af-25fe-4d28-82c9-5c2b4d895b79 -> ../../sda8
lrwxrwxrwx 1 root root 10 Apr  9 03:53 8e3aca35-c376-4a71-b6be-5c3c063a184b -> ../../sda7
lrwxrwxrwx 1 root root 10 Apr  9 03:53 9aae2d22-4393-436a-a505-130db27e0e55 -> ../../sda3
lrwxrwxrwx 1 root root 11 Apr  9 03:53 accbe348-0237-436f-b1b8-c642b95ec49c -> ../../sda10
lrwxrwxrwx 1 root root 10 Apr  9 03:53 b8f4a41f-5056-4b06-a190-14f9f1ea0244 -> ../../sda9
bigbird@ramdass:/media/work/etc$

Comment: When grub boots it needs to load stuff from a filesystem on a partition - so unless you have a separate /boot partition you will have two copies. And running update-grub from a running OS will only update the one copy in the current /boot dir. I'm also not sure if /sda[5..] can be set as bootable - it is in an extended partition (sda[1..4] are primary, bootable partitions). It may help (or may not) to know that you can run update-grub on the other OS by way of chroot + mount -t bind commands.
Answer: Try to boot into a DVD of Ubuntu, then mount /dev/sda5 via:
mkdir /tmp/sda5
mount /dev/sda5 /tmp/sda5

Then, after this, edit fstab
nano /tmp/sda5/etc/fstab

And you should look for a line that begins with '/'. This should be /dev/sda5 not /dev/sda3. If it is not, then adjust appropriately. Also make sure that your /home and other settings are correct in the file and pointing to the right partitions.
check them using fdisk:
sudo fdisk -l

or using gparted
sudo apt-get install -y gparted
gksudo gparted

Once fstab is fixed reboot and you should now have root as /dev/sda5
Comment: That's what I thought, but I've double checked fstab on both partitions and they look good to me. I use gparted whenever I do stuff like this - even just  to look at what's there. It's a great tool. Since sda5 isn't mounted when I boot normally from sda3, I can just mount sda5 from there without a live CD. I'll see if I can edit my question to include both fstabs.


How can I set a timer?

Question: I would like to set a stopwatch timer that will determine how long an input is in a certain state before changing. I want to set it so that, depending on the output my code executes one of 2 switch cases. But my trouble comes in on setting a timer. Is there a function I could use? Or a method that somebody knows? The time that the input will be for each case is not fixed so I cannot use a delay.
Comment: As I suggested in the comments to your other question, you can also use `millis()` here to measure time differences (use `micros()` if the time to measure is smaller than a few milliseconds).
Answer: Even though you are not running an actual (complex) Operating System, you should adhere to common practices.  For an Arduino, you should, in many cases, avoid directly controlling the hardware so as to be compatible with as many existing libraries for your particular Arduino platform as possible.
Setting the timer directly (if you are using an official Arduino Uno which contains an Atmel328P processor the processor's timers are covered in section 14 of the Atmel328P Specifications) may cause unexpected results should you use a library which expects the timer to run without being altered.
Instead, consider using the millis() function built into the Arduino IDE.  The function returns the current number of milliseconds since the Arduino was powered up.  Record this value in your code.  Then, if you want to know if One Second has elapsed, get the new value of millis and subtract this saved value from it and see if it is greater than 1000.  When that is true, One Second has elapsed.
Comment: Re "_consider added the code to detect this roll over_": better to just [write rollover-safe code](https://arduino.stackexchange.com/questions/12587/how-can-i-handle-the-millis-rollover), like `if (millis() - start_time >= duration)`. "check to see if millis() returns a number which exceeds this value" is _not_ rollover-safe.
Comment: True Edgar.  @Damon Swart is brand new to the site and I like trying, testing & vetting 1 idea at a time (using millis()) - then, after the 1st idea is working, adding to it (roll-over).  Also, I rather not include code.  It takes longer to post answers w/code and the code may not be correct or complete.  Besides, describing the solution makes the Original Poster think through the problem.
Comment: @Damon Swart, if you try the answer and it works for you, accept the answer as correct so that others can also find and use the answer.  If it doesn't work for you, post a comment here and we can try to change the answer so that it does work for you.
Comment: This answer should be edited to do things the safe way.  There's no reason anyone should have to check for rollover if you write code correctly.  Always see how long it has been.  Never try to predict a future time.
Comment: Please see my proposed edit.
Answer:
Use micros() (reference page) to obtain a microsecond timestamp, and millis() (reference page) to obtain a millisecond timestamp.
Full Disclosure: I link to a library I maintain in my answer below, and I mention a few products (no links) I created with various techniques presented here in order to act as representative examples of when one approach might be preferred over another.
Example 1: simple linear (synchronous) software timing measurement, including low-resolution (micros()) and high-resolution (timer2.get_count())
In the simplest sense, let's measure how long it takes to set an output pin HIGH and then LOW again:
void setup()
{
    Serial.begin(115200);
    // I'll just leave pin 9 as an input; but uncomment the line below to make it an output
    // pinMode(9, OUTPUT);
}

void loop()
{
    // Measure and print how many microseconds it takes just to set an output pin HIGH and then
    // LOW again.
    uint32_t time_start_us = micros();    // <=== START TIMESTAMP
    digitalWrite(9, HIGH);
    digitalWrite(9, LOW);
    uint32_t time_end_us = micros();      // <=== END TIMESTAMP
    uint32_t time_elapsed_us = time_end_us - time_start_us;
    Serial.print("time_elapsed_us = ");
    Serial.println(time_elapsed_us);
    delay(100);
}

The really cool ShowInfo Arduino speed profiling sketch shows that Arduino's digitalWrite() function takes about 5us each, so expect the code above to print ~10us. Let's see if that's correct. I ran this on an Arduino Nano and got this output:
time_elapsed_us = 8
time_elapsed_us = 12
time_elapsed_us = 12
time_elapsed_us = 12
time_elapsed_us = 12
time_elapsed_us = 12
time_elapsed_us = 12
time_elapsed_us = 8
time_elapsed_us = 12
time_elapsed_us = 12
time_elapsed_us = 8
time_elapsed_us = 12
time_elapsed_us = 8
time_elapsed_us = 12
time_elapsed_us = 12
time_elapsed_us = 12
time_elapsed_us = 12
time_elapsed_us = 8

That's weird. Why only 8 or 12 us? Why not 10? Or 9? Or something else? Well, it turns out the Arduino micros() function only has a resolution of 4us, so it will actually print out either 8 or 12 us since those are multiples of 4 us. To get better resolution you'd have to modify the hardware timer registers, as I've done in my eRCaGuy_Timer2_Counter library, which has 0.5us-resolution. Full Disclosure: I wrote and maintain this library. It is free and open source, but I have it on my personal website, which has ads, and I solicit donations for downloads. A fully-functional snippet is also available in code at the bottom of that web-page without downloading anything.
Here is how to do the above code with my library:
#include <eRCaGuy_Timer2_Counter.h>

// Convert timer2 clock counts, which are 0.5us each, to us.
float counts_to_us(uint32_t time_counts)
{
    float time_us = (float)time_counts/2.0;
    return time_us;
}

void setup()
{
    Serial.begin(115200);
    // I'll just leave pin 9 as an input; but uncomment the line below to make it an output
    // pinMode(9, OUTPUT);

    // Configure Timer2. This MUST be done before the other Timer2_Counter functions work.
    // Note: since this messes up PWM outputs on pins 3 & 11, as well as interferes with the tone()
    // library (http: arduino.cc/en/reference/tone), you can always revert Timer2 back to normal by
    // calling `timer2.unsetup()`
    timer2.setup();
}

void loop()
{
    // Measure and print how many microseconds it takes just to set an output pin HIGH and then
    // LOW again.
    uint32_t time_start_counts = timer2.get_count();    // <=== START TIMESTAMP
    digitalWrite(9, HIGH);
    digitalWrite(9, LOW);
    uint32_t time_end_counts = timer2.get_count();      // <=== END TIMESTAMP
    uint32_t time_elapsed_counts = time_end_counts - time_start_counts;
    float time_elapsed_us = counts_to_us(time_elapsed_counts);
    Serial.print("time_elapsed_us = ");
    Serial.println(time_elapsed_us);
    delay(100);
}

Now look at the output. Here's the more accurate and precise results with my eRCaGuy_Timer2_Counter library. Much better! But why those spurious 14.50us values I have marked with <===? Why are they off by 4us? I will explain below.
time_elapsed_us = 10.00
time_elapsed_us = 10.50
time_elapsed_us = 10.00
time_elapsed_us = 10.00
time_elapsed_us = 14.50  <===
time_elapsed_us = 10.50
time_elapsed_us = 10.50
time_elapsed_us = 10.50
time_elapsed_us = 10.00
time_elapsed_us = 10.00
time_elapsed_us = 14.50  <===
time_elapsed_us = 10.00
time_elapsed_us = 10.00
time_elapsed_us = 10.50
time_elapsed_us = 10.50
time_elapsed_us = 10.50
time_elapsed_us = 10.50
time_elapsed_us = 10.00

The tradeoff of doing what Im doing is that you will get a 4us jitter introduced more often. Every time the 8-bit timer2 counter overflows, an ISR (Interrupt Service Routine) is called. This counts overflows to keep track of the 32-bit software timer from an 8-bit hardware counter. Entering this ISR takes about 4us, which means that if you try to grab a timestamp but then the ISR is called, you have to wait 4+us to get that timestamp, so it is off by that much. One of the several Arduino experts I really look up to, Nick Gammon, mentions this here in his Interrupts article where he says, "There is a tweaking figure of 4 µS...". So, this 8-bit counter counts at 1 tick per 0.5us, which means it rolls over every 256 ticks * 0.5us/tick = 128us. So, every 128us you will have at least a 4us delay error introduced if you try to call the timer2.get_count() exactly when the ISR is called. If you get really unlucky you may even get this effect twice and be off by as much as 8us. When using the standard micros() function, since it rolls over only every 256 ticks * 4us/tick = 1024us, you get this 4us error effect 8x less frequently. That's the tradeoff of getting better resolution: you also get more-frequent 4+us jitter.
And just for kicks, here's a really bad one. Notice the 20.50us value--off by 10.50us!
time_elapsed_us = 15.00 <===
time_elapsed_us = 10.50
time_elapsed_us = 10.00
time_elapsed_us = 10.00
time_elapsed_us = 10.00
time_elapsed_us = 10.00
time_elapsed_us = 15.00 <===
time_elapsed_us = 10.50
time_elapsed_us = 10.00
time_elapsed_us = 20.50 <======
time_elapsed_us = 10.00
time_elapsed_us = 10.00
time_elapsed_us = 10.00
time_elapsed_us = 10.50
time_elapsed_us = 10.00
time_elapsed_us = 10.50
time_elapsed_us = 10.50
time_elapsed_us = 10.00
time_elapsed_us = 10.00
time_elapsed_us = 10.00

Using mode filters, median filters, or other filters, these spurious results can be removed, at, of course, the cost of reduced frequency response to the thing being measured (all this means really is it takes multiple measurements to know the true value, just as we need to see with our eyes multiple measurements above to deduce 10.0us seems to be the right answer).
Example 2: non-blocking (asynchronous) timing measurement of external event
More-complicated Example: measure how long INPUT pin 9 is HIGH, and print out the HIGH time out each time it goes LOW again.
In general, use this approach for any and all input events you need to measure at the 100us to ~200us resolution or larger level. You can use this on every single pin at once and get good results with resolutions around that level, depending really just on how long your main loop takes to run each iteration.
constexpr uint8_t PIN = 9;

void setup()
{
    Serial.begin(115200);
    pinMode(PIN, INPUT);
}

void loop()
{
    // This will measure how long `SOME_PIN` is HIGH, in microseconds.

    static uint32_t time_start_us = micros();
    bool time_just_acquired = false; // true if a new time value was just measured
    uint32_t time_elapsed_us = 0;

    bool pin_state = digitalRead(PIN);
    static bool pin_state_old = LOW;

    if (pin_state == HIGH && pin_state_old == LOW)
    {
        // The pin just barely went HIGH, so "start the timer" by obtaining a timestamp of the
        // start time
        time_start_us = micros();
        pin_state_old = pin_state; // update
    }
    else if (pin_state == LOW && pin_state_old == HIGH)
    {
        // The pin just barely went LOW, so "stop the timer" by obtaining a timestamp of the
        // end time
        uint32_t time_end_us = micros();
        pin_state_old = pin_state; // update
        time_elapsed_us = time_end_us - time_start_us;
        time_just_acquired = true;
    }

    // In some other place later down the code where you need this value,
    // you can use it like this. Here I just print the value.
    if (time_just_acquired)
    {
        time_just_acquired = false; // reset
        Serial.print("time_elapsed_us = ");
        Serial.println(time_elapsed_us);
    }
}

IMPORTANT: notice in all my examples above I use ONLY UNSIGNED INTEGER variables for timestamps. This is ESSENTIAL. Using signed integers for timestamps in the same way I've written them here would be a violation of the C standard because it will produce undefined behavior when you do subtraction which results in underflow, or when the integer has overflow. Using unsigned integers, however, is perfectly valid. Ex: (uint8_t)0 - (uint8_t)1 = 255, because it is an unsigned 8-bit integer which safely underflows from its lowest value back around to its highest value. Similarly, (uint8_t)255 + (uint8_t)1 = 0 because it is an unsigned 8-bit integer which safely overflows from its highest value back around to its lowest value. This is how time_elapsed_us = time_end_us - time_start_us works in both of my examples as well. As the 32-bit microsecond counter overflows, which it will every 70 minutes or so, it wraps around back to 0. This means that sometimes time_end_us will be SMALLER than time_start_us, and you could end up with a measurement like this: time_elapsed_us = 124 - 4294967295, which equals 125.
Example 3: use external interrupts to detect changes on pins to measure external events
Use this approach when you need to measure external events at the 4~10us or larger resolution level on 2 pins maximum at a time.
This is a really good approach for measuring external events, but you get only 2 pins per Arduino Uno or Nano or similar that can do it. They are pins 2 or 3. See the table here: https://www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/.
For a demo, see Edgar Bonet's answer here.
Example 4: use pin change interrupts to measure external events
Use this approach when you need to measure external events at the 4~10us or larger resolution level on > 2 pins maximum at a time.
These are like external interrupts except you have to manage up to 8 pins in a single interrupt service routine (ISR), instead of only 1 pin per ISR, so they aren't quite as good as "external interrupts". Every single digital-capable pin on an Arduino Uno or Nano can do this. I use this approach when reading many PWM signals from a radio control receiver, for instance, but it requires some sophistication and a ring buffer to do it right, as the time in the ISR must be minimized or else you get tons of jitter all over the place! That means you just grab the timestamp in the ISR, store it in a ring buffer, and exit. You do NOTHING ELSE! No subtraction, no math, no determining which pin fired, nothing! You then process the ring buffer of timestamps and pin states in your main loop to determine which pin changed and do the math to obtain a new time reading on that pin. I used this for passing signals through a fire-shooting battlebots hexacopter that flew on ABC TV. It worked well. It made me happy to see the ISR do its job.
Example 5: use input capture (on pin 8 only) to measure an external event
This is the "golden", or "best" approach. But, you get 1 pin per Arduino Uno or Nano that can do it. Use this approach when you need to measure external events at the 62.5 nanosecond or larger resolution level jitter-free. There will be NO ISR TIMESTAMP DELAY WHATSOEVER with this approach, which is really cool.
Input Capture is only available on 16-bit timers on the 8-bit AVR microcontrollers such as the ATmega328. Since an Uno or Nano only has 1 16-bit timer, this means they get 1 single input capture pin. It is pin 8. Don't waste this pin for anything else if you need perfect time measurements of external events using input capture. Input capture is the "perfect" way to measure external events since it stores the time count in a hardware register at the moment the event happens, without CPU interaction through an ISR, which, as we know, would cause a delay and 4+us jitter.
I first did this on a commercial product I made which needed to read a single Radio Control receiver PWM pin. It made me happy to see it work right, as it has zero jitter. I'll come back and add a demo (code only, no more mention of the product) if I get a chance. This technique is also perfect for reading PPM (Pulse Position Modulation) signals, which are just a bunch of multiplexed Radio Control PWM signals.
Comment: Your last link points the user to a website that is full of advertisements and solicits either a monetary donation or your email address to continue. This question has been locked.
Comment: That isn't supposed to happen. Can you screenshot it? I updated my ads recently to Google auto-ads. I need to adjust it and reduce them. I'll take care of it as soon as I can, but I don't know what email address or donation would possibly be requested to continue.
Comment: Also, I've never heard of locking an entire question over one link. That seems really weird.
Comment: I'm voting to close this answer because the last link points the user to a website that is full of advertisements and solicits either a monetary donation or your email address to continue.
Answer: Your title is about "setting a timer", but your actual question is about
measuring the length of a pulse. There are two functions provided by the
Arduino IDE for this purpose, pulseIn() and pulseInLong():

pulseIn() is based on a carefully timed delay loop. It
has a resolution of the order of one microsecond, but will not count
the time spent servicing interrupt requests. It works best for very
short pulses timed with interrupts turned off.
pulseInLong() is based on micros(). It has a
resolution of 4 µs and will not work properly if interrupts are
turned off. It works best for longer pulses where its limited
resolution and interrupt latency are tolerable.

Both of these are blocking functions: they completely block your
sketch while they perform the measurement. If you don't want your sketch
to be unresponsive during this time, you can write a non-blocking
version of pulseInLong() using a finite-state machine like
this:
// Measure the length of a pulse in a non-blocking manner.
// Returns 0 if no measurement is available at the time of the call.
void get_pulse_length() {
    static enum {
        INITIAL_WAIT,    // wait for the first (partial) pulse to end
        BETWEEN_PULSES,  // wait for the pulse to start
        WITHIN_PULSE     // wait for the pulse to end
    } pulse_state = INITIAL_WAIT;
    static uint32_t pulse_start;  // when the current pulse started

    uint8_t pin_state = digitalRead(pulse_pin);
    uint32_t now = micros();
    switch (pulse_state) {
        case INITIAL_WAIT:
            if (pin_state == LOW)
                pulse_state = BETWEEN_PULSES;
            break;
        case BETWEEN_PULSES:
            if (pin_state == HIGH) {
                pulse_start = now;
                pulse_state = WITHIN_PULSE;
            }
            break;
        case WITHIN_PULSE:
            if (pin_state == LOW) {
                pulse_state = BETWEEN_PULSES;
                return now - pulse_start;
            }
            break;
    }
    return 0;
}

Note that this measures high pulses. You will have to swap HIGH and
LOW if you want to measure low pulses. You would use it like this:
void loop() {
    uint32_t pulse_length = get_pulse_length();
    if (pulse_length) {
        // handle the pulse
    }
}

The resolution of the measurement is the execution time of loop(), so
you have to make sure there is nothing blocking there, and specially no
calls to delay(). If you need a better resolution from a non-blocking
method, you can use interrupts to trigger the measuring process:
volatile uint32_t pulse_start, pulse_length;
volatile bool pulse_valid;

void on_rise() {
    pulse_start = micros();
    attachInterrupt(digitalPinToInterrupt(pin), on_fall, FALLING);
}

void on_fall() {
    pulse_length = micros() - pulse_start;
    pulse_valid = true;
    attachInterrupt(digitalPinToInterrupt(pin), on_rise, RISING);
}

uint32_t get_pulse_length()
{
    if (!pulse_valid) return 0;
    noInterrupts();
    uint32_t pulse_length_copy = pulse_length;
    pulse_valid = false;
    interrupts();
    return pulse_length_copy;
}

void setup() {
    attachInterrupt(digitalPinToInterrupt(pin), on_rise, RISING);
}

This should give you the resolution of micros(), i.e. 4 µs, but
occasionally you may get results that are slightly off if interrupts
happen to be disabled when the input transitions. If this is
unacceptable, the only other options I see is to use a hardware timer
with input capture capability. You will have to look at the datasheet
of your microcontroller to see how it works, and maybe do a Web search
for "Arduino input capture".

How can I set a timer?


What is the purpose of StreamReader when Stream.Read() exists?

Question: This has been bugging me. I know Stream is an abstract class and therefore can't be instantiated but it has classes that are derived from it. Why is there a StreamReader class and a Stream.Read() method (and vice verse for StreamWriter and Stream.Write())? You can write to a text file using 3 million different methods and it's rather frustrating trying to get my head around all of these different types and methods in the System.IO namespace. I found questions and answers regarding the differences between the writer and reader objects or the derived stream objects themselves but nothing regarding this particular case.
Comment: Since `StreamReader` is abstract, you need an object of a concrete class, such as `TextReader`, to call the `Stream.Read()` method on.  The class and the method are not redundant.
Answer: TextReader (which StreamReader is derived from) works with strings. Stream works with bytes. The conversion between text and bytes is performed by an Encoding.
Choose the right class based on whether the contents of your file text or binary.
It is important to understand the difference between text and bytes.
Comment: Sorry ignore my last comment, I misread. If a Stream works with bytes why in the heck did Microsoft call it a StreamReader if it works with text? The FCL can be so conflated sometimes.
Comment: They should have called it `StreamTextReader` or `StreamBasedTextReader`. Think of that name as being abbreviated... I understand your confusion because I had the same things to say when I learned this. It totally makes sense when you have some experience with this concept, though.
Comment: `StreamReader` works with text. It is derived from `TextReader`. A `StreamReader` *wraps* a `Stream` because `Stream` does not support text-based operations. How would you write a string to a file when all you have is a `Stream`?!
Comment: Maybe your confusion is more with the design of the BCL and less with the separation of text and bytes.
Comment: BCL? Do you mean FCL? I do indeed understand bytes and that text is just encoded bytes.
Answer: A StreamReader is a TextReader which means it is a Stream wrapper. A TextReader will convert (or encode) Text data (string or char) to byte[] and write them down to the underlying Stream.
Looking at the difference between the two implementations, you can see that StreamReader derives from TextReader, which, as declared, deals with text instead of bytes. It seems to me as an abstraction for users who want to work with textual representation. Of course, the underlying implementation will need a Stream to consume such data, but will provide a level of abstraction for end users.
Answer: These two cases are used in different scenario
When you are using the stream class you can access the file for read and write. But when you use streamreader class you can use it to read only. This prevent the usage of file to be written. Sometimes This class is used for security purpose. e.g. for system files which are readonly.


The effect of static properties in a web context

Question: I need to change a static property on an object in our web application.  The property has a default value that is hard-coded into the object.  If I change the static property in my Application_Start does that change stick:
A) Forever (well, until the app is recycled)
B) Until the object is GC'd then re-inialised by the next accessor
C) Depends
Note that the property I'd be setting is just a String
Answer: The scope of a static variable is its AppDomain. So no, it won't get garbage collected - but if the AppDomain is recycled (which can happen a fair amount in ASP.NET) then you'll end up with a "new" static variable, effectively.
Answer: In my experience with our web apps here, the answer is A. As far as I know, a static class will never be GCed, it lives on for the life of the process (in this case, the ASP.NET worker process)
Comment: Life of the AppDomain, not process.
Answer: Go for A)
App Instance Variable
For context storage, refer to httpContext.


Is interacting with registers the only way software and hardware interact?

Question: I'm aware that memory mapped addresses that point to registers are sometimes used to control hardware devices. Is that the only way they're controlled? I started asking about how software talks to hardware and most people told me about using registers and memory addresses to talk to devices. Is that the only way software and hardware interact? Thanks!
Comment: @jsotola Sorry, I didn't intend to put 3 questions in, I just thought it was the best way to phrase it at the time.
Answer:
most people told me about using registers and memory addresses to talk to devices

Shortly, that is the correct answer - if you are interested how software will (ultimately) talk to hardware. How hardware can have an impact on software, things get a lot more complicated.
If you want to understand deeply how things happen, you should study how micro-controllers are implemented. Studying the famous 8051 is a very good start, and there are countless books and articles about it. You will have the chance to understand timers, interrupts, ports, buses...
Comment: Ok, I'll go pickup some 8 bit MCUs and see how they work. Should I just work up in complexity from there until I reach modern 64-bit CPUs?
Answer: No. You are talking about memory-mapped I/O. It means that the CPU see the hardware as if it would be some like a memory module.
All the robots have these three components:

a controlling mechanism. It means a collection of chips.
sensors (to know the world around them).
and motors (or, more generally, end-effectors. For example, a robot capable to heat its arms has a non-mechanical end-effector).

(1) gets the data from the sensors (2), and using the collected data, says to (3) what to do.
All the chips have a set of pins. They can send voltage to them, or they can read the voltage on them send by others. The sensors and the end-effectors use electronical (or physical, chemical, anything) means to convert between the voltage on the pins and the external world. This might be quite complex, for example until the $\mu A$, 5V current becomes a regulated 3-phase, 50Hz, 380V current on a large industry robot, the steps are not trivial.
But this all is not important. The only important thing is that the CPU has to communicate somehow with the other chips/devices of the robot, and the only question is, how do we call the pins and what type of pins are on which the communication is going on.
A simple way, with some disadvantages, if the CPU see the hardware, as if it would be a memory block. If you write a data to a specific memory address, you send data to a device.
Another possibility is to have dedicated pins for I/O, it is the port-mapped I/O.
Mainly large mainframes had also specific I/O coprocessors, i.e. mediating chips only for I/O tasks.


Electrician Terminology "FAU"

Question: I've noticed these letters several times written on the circuit breaker panel door. Does someone know what F.A.U. stands for in this context?
Answer: FAU is likely a "forced air unit" (e.g. a heater or air conditioner).
If it's two breaker switches tied together, that's a 240V volt circuit (if there's no tie between the two switches, that's an immediate hazard and must be fixed).
Comment: Thanks. It is written twice, so as to label a double breaker slot. Would that imply the unit is powered for 220 volts?
Comment: If the breaker handles are tied together so they both operate simultaneously, then yes, it would be a 220/240V circuit.
Comment: Thanks. So if my furnace uses natural gas as a fuel to heat would that mean that the 220 line voltage is for the blower motor?
Answer: Yes, FAU is "forced air unit", but this term is not used everywhere. Around here you'll many times see AH, or A/H for "air handler", which is what we would call the inside blower unit of a split air conditioning system.
Comment: Thanks. I would think they would want to be more specific so as to identify what the breaker is protecting. (Air Con. or Attic Furnace, etc.). FAU is to general.

Electrician Terminology "FAU"


What is the "では" in "それでは"?

Question: My teacher told me the "で" in "それでは" was not the particle "で", would that mean it is the same "では" as in "ではない" (aka the て-form of です)? If, so what is the literal meaning of "それでは"?
Comment: I am baffled by your teacher's comment.  で has many meanings and uses, but で is で is で.  The only case I can think of where it's not the particle / copula is when it's the _rendaku_ version of conjunctive verb suffix て. ???
Comment: Right, I think he was probably trying not to confuse the other students who are complete beginners (since this is our first year of Japanese), by distinguishing the particle で and the copula だ (made of で + ある), but I agree, he probably shouldn't have said that "it isn't the particle で".
Comment: @EiríkrÚtlendi - I assumed they meant それでは in the sense of "then" as in それでは終わりましょう.
Answer: I do not agree with your teacher, and can assure you that syntactically, the で of では is 100% the てform of だ, and this では is the same では as in ではない。
Now, both では and ではない are already common expressions, and are usually taught as "one single thing." But let's break them down and see why are they the way they are, shall we?
First, let's take a verb "to run" 走る. This is its terminal form, which is the same as its dictionary form, which should only appear at end of sentences or relative clauses. Ex. He runs 彼は走る The dog that runs 走る犬.
Now, what if I want to make this action of running the subject of my sentence? Well, two options. One is to nominalize the verb using こと, so (the action of) running is not ok would be 走ることはいけない. The second option is to use its てform, which kind of "nominalizes" the verb, and we can use it as the subject now. Running is not ok 走ってはいけない.
This is one of many uses of てform, but is the one we are focusing on to explain では. The terminal form of "(something) is a dog" is 犬だ. What if I want to use this "(something) being a dog" as the subject? Same answer - the てform, which is 犬で. Then, we can say things like

(something) being a dog is not ok 犬ではいけない (Not necessarily the listener being a dog is not ok. Maybe you're choosing your favourite animal, and I tell you 犬ではいけない, then your choice being a dog is not ok.)
(something) being a dog is scary 犬では恐ろしい (Again, the something here can be a lot of things based on context, could be me being a dog is scary, could be my friend's new pet being a dog is scary, etc.)
And classically, not a dog. 犬ではない. Here, it literally means "(the idea of) something being a dog does not exist". Conversely, you might have also heard 犬で(は)ある. It means "it's a dog", but more literally "(the idea of) something being a dog exists"

Sometimes ではない is でない, and である can also be ではある. Same meaning, just sometimes people drop the は particle.
Now, I hope you see that the で of では is exactly the てform of だ, and では in ではない is not anything special. For your example, それでは, or sometimes just では at beginning of sentences, it translates as "that said" or "therefore", but literally it's just "regarding (it) being that", or それ{that} で{being}  は{regarding}
それでは、会議を終わらせましょう。
So, let's end the meeting.
Regarding it being like that, let's end the meeting.
Japanese is a very structural language, and I often times feel its grammar is taught in an unnecessarily complex way. If we can break down set phrases to trace the grammatical elements behind them then the students can surely get a better understanding of the language, and once the literal meaning is known, some of the nuances and quirks of certain phrases (like what tone does this carry) would come as a natural realization.
Comment: As an additional note, do you see now why we say 全部食べてもいいよ, instead of 全部食べるもいいよ ? Even 全部食べていいよ is grammatical, but 全部食べるいいよ is not. This is just one of the functions of てform.
Comment: Really grateful for the time you took to write this, it is exactly the kind of answer I wish appeared in textbooks! I just have a question concerning the nominalization function of the て-form (which is the first time I hear about this and can't find much info about); I get how "走ることは" means the "thing of running", but how would you literally translate "走っては", or at least the て-form of verbs in general? I used to think "走って..." meant "to run AND ..." (let me know if this should be a whole other question altogether).
Comment: Hi, you're more than welcome! As for the てform, I mentioned it's "is just one of the functions of てform", because there are mainly two. The first one is to combine 用言, i.e. 彼は走って出かけた。これは綺麗で貴重だね。 By extension, there are also some combination that are common and taught as separate grammar, like していく、している、してください, etc.  In essence, these are just てform of verbs + 行く、いる、or 下さる。Aside from the combining feature, てform can also "idea-lize" a 用言, then we can use as subject. てform is special coz there's no 1-to-1 counterpart in English, so how you translate each one is based on usage and context.
Answer: I think you should take it just as a single word それでは. Since it can be では, I don't think it is particularly helpful for understanding because で in では cannot be (perceived as) a particle or a copula.

That said, hopefully the following gives some idea.
で can be a particle or a copula, depending on the usage.
それでは means (The interjection usage omitted):

[接]
1 前に示された事柄を受けて、それに対する判断・意見などを導く。そういうことなら。それなら。では。それじゃ。「―いずれ手にはいるね」「―こうしたらどうか」
2 物事をその時点で始めたり終えたりすることを示す。では。それじゃ。「―私から発言しよう」「―これで打ち切りとします」
[連語]そういうことでは。そういう状態では。それじゃ。「―まるで解決にならない」「―私の顔が立たない」

So simply, it means (1) then as a conjunction ([接]) and (2) with that as a combination ([連語]) of で and は.
In the sense (1), で is a copula. それでは is equivalent to something like if (things) are so and で works as a copula connecting the omitted subject and それ.
In the sense (2), で is a particle for with,by. Basically, it is the same usage as 箸で食べる=to eat with chopsticks. それでは解決にならない means, at the bottom, It is not resolved by that.

What is the "では" in "それでは"?


Private vs Permissioned blockchains

Question: I have seen these two words - private and permissioned, a lot. Sometimes, they're used interchangeably. I don't believe these words have the same meaning. Can anyone give a detailed description differentiating these two types of blockchains?
Answer: Private Blockchain
Is a blockchain, where we allow only known nodes to participate in the network. Ideally, it is internal for an organisation, a bank per se.
Permissioned Blockchain

The first primary difference between a properly conceived permissioned blockchain network and an unpermissioned blockchain network is whether the participants in the network have an ability to restrict who can participate in the consensus mechanism of the blockchain's network.

Is a blockchain where we can allow certain actions to be performed only by certain addresses (wallets)
Source

docs.erisindustries.com
bitcoinmagazine.com
lightrains.com
Comment: There doesn't seem much difference between your two definitions. In both cases, it seems control over participation is the key characteristic. Can you expand further on the differences?
Comment: @DuncanJones yes, participation and data privacy differentiate these two.
Comment: same here, my question is probably really how are access control implemented, is it centralized auth?  if so, how is it really more secure than a centralized arch (instead of blockchain) in the first place?
Comment: i mean there are a lot of archs, like CDN / multi-region cloud, that looks discentralized but are really centralized because their auth is centralized. so if the auth is centralized here, then how could it be called discentralized at all?   if the auth is discentralized, can you point to some reference for that?
Answer: They are definitely not used interchangeably since they have a very different meaning/purpose:
Private blockchains are private because of the genesis block they are using. Their blocks do not match with any other blockchains (you cannot link blocks from the main net to blocks of a private net with a different genesis blocks as the block header hashes won't match).
Note that any node can connect to a private blockchain if it knows a bootstrap node address to sync, the network id, and the genesis file. This node can perform any action on the private net; mine, make transactions, deploy contracts, etc.
Permissioned blockchains on the other hand offer an access control mechanism so that peers are allowed or rejected based on a control value (an address, a certificate, etc.).

Private vs Permissioned blockchains


Does the Dow Jones Industrial Average (DJIA) always have 30 constituent companies?

Question: I know that the Dow Jones Industrial Average (DJIA) started with 12 industrial companies in 1896, but that's not what I'm asking about here. I'm asking about its contemporary version. The S&P 500 and Russell 3000 do not always contain 500 and 3000 companies respectively. If there is a merger, acquisition, or delisting, they may contain less constituent companies. I'm wondering if this is also the case for the DJIA. Does the DJIA always have 30 constituent companies, or can it vary?
Comment: Was able to find [https://en.wikipedia.org/wiki/Historical_components_of_the_Dow_Jones_Industrial_Average](https://en.wikipedia.org/wiki/Historical_components_of_the_Dow_Jones_Industrial_Average) as the conditions you mentioned can't be surprises the index owner can swap out companies to maintain 30 components.
Answer: With only 30 companies in the index it is easy to keep it at that number. While these companies do split in two, they do merge with other companies, and they do split their stock price, these tend to not be surprises.
If you look at the changes to the Dow you will see additions and subtractions whenever a split of a component company takes place. They use the time between the potential split, and the actual split to plan their actions. They do the same for mergers.
It would have to take an epic rapid collapse of a company to end up with fewer companies in the Dow. Something like on Friday everybody thinks company X is doing great. But on Monday morning they announce they are liquidating everything.
Also remember indexes like the Russell index are part of a family of indexes. They rank a bunch of companies and then decide where the dividing line should be. They periodically re-sort and then decide if they want to fudge/blur the location of the dividing line a bit to reduce the amount of stocks changing indexes. That leaves them with the Russell 3000 having approximately 3000 companies.
Comment: Is the answer "yes" (except when difficult)?


Change ubuntu 16.04 text in login

Question: I am currently compiling an Ubuntu 16.04 however I want to change the text 'Ubuntu 16.04' to 'FT Linux v1.0' as I'm trying to get rid of all ubuntu traces for my distro. As of now I'm compiling the distro but I hope to get a answer on how to mod the text in the login screen saying 'Ubuntu 16.04 LTS' Thanks.
Answer: You can change this message by editing the /etc/issue and /etc/issue.net.

Customizing your Logon with /etc/issue
Comment: Your answer while helpful will become useless if/when the link is no longer active and for that reason it would be better to include essential parts of the answer here and use the link as a reference. Please refer to: http://askubuntu.com/help/how-to-answer  Thank you for helping improve the site!
Comment: @ElderGeek "Edit `/etc/issue`" is a sufficient and complete answer to **that question**.  Questioner will reach the goal by simply editing a few letters of the `/etc/ issue`.  I think that there is no need for all of the answer is in reference to cover specification. However, if you write a different answer, I will learn from your answer.
Comment: Assuming of course that the OP  knows how to edit those files (which based on a number of questions I've seen here may not be true.) I try to create answers that even a completely inexperienced user can follow as this has a tendency to reduce the number of messages I get in my inbox asking how to do basic tasks. Perhaps your results will differ.
Comment: Link only answers are not acceptable here, please read http://askubuntu.com/help/how-to-answer, if you don't improve this answer, it will be removed.

Change ubuntu 16.04 text in login


Solving 2-CNF TQBF with #SAT solver?

Question: We clearly know that 2-QCNF is in $\mathsf{P}$. Since that, if I understand it right, it is possible to solve it with #SAT solver (because $\mathsf{P} \subseteq \mathsf{\#P}$). But how can we only knowing amount of positive assignments for some non-quantified formulae solve 2-QCNF? And why this doesn't hold (at least, assumed so) for general case of TQBF?
Answer: First of all, it is a bit misleading to say that $\mathsf{P} \subseteq \mathsf{\#P}$, since $\mathsf{P}$ is a class of decision problems, while $\mathsf{\#P}$ is a class of counting problems. However, we can think of a decision problem as a counting problem in which the answer is 0 (no) or 1 (yes), and in that sense it is certainly true that $\mathsf{P} \subseteq \mathsf{\#P}$.
The problem $\mathsf{\#SAT}$ is $\mathsf{\#P}$-complete. This means that for any problem $A \in \mathsf{\#P}$ there exists a polynomial time reduction $f$ such that for any instance $x$ of $A$, we have
$$ A(x) = \mathsf{\#SAT}(f(x)), $$
where $A(x)$ is the value of the counting problem $A$ on instance $x$.
Since $\mathsf{2QCNF} \in \mathsf{P}$, there is a trivial reduction from $\mathsf{2QCNF}$ to $\mathsf{\#SAT}$: if the $\mathsf{2QSAT}$ is satisfiable, we output the formula $x$, and otherwise we output the formula $x \land \lnot x$. This reduction runs in polynomial time since $\mathsf{2QCNF} \in \mathsf{P}$.
Comment: But here we solve 2QSAT to convert it to #SAT? Why we even reduce it, if we already know the answer? I thought that's not how reduction works.
Comment: We can do whatever we want as long as we follow the rules. The reduction I describe satisfies all the requisite properties, so it's a valid reduction.
Comment: As to *why* we reduce it, if we already know the answer - it's because *you* asked for such a reduction.
Comment: But if we had $\mathsf{NL}^{\mathsf{\#P}}$ machine, that machine should be capable to solve 2QCNF (or not?) but such reduction is restricted. All I know that such machine can solve 2QCNF with zero-error probability, as well as $\mathsf{P}^{\mathsf{\#P}}$ machine can solve TQBF with zero-error probability.

Solving 2-CNF TQBF with #SAT solver?


Two paths under the same package in bintray

Question: I have successfully uploaded a library to bintray, which shows the version and the dependency correctly. But when I requested to link it to jcenter, I got this response:

Hi,
We can see that there are two paths under the same package, one used for the .aar/.jar/.apk and jar-sources.jar and *-javadoc.jar files on under:
  /com/androiddev/android-dev-core/1.0.0
and one for the .pom file:
  /com/androiddev/core/1.0.0
We can only approve one path for a single package.
  Please consolidate the two paths and let us know which path prefix you would like to include.
Thanks,
  JFrog Support

I can see the two paths under file section in bintray. Any idea how to solve this?
Answer: To avoid this problem make sure your library name is similar to the one you have created on bintray. If they differ, it will create two separate paths when you upload your library to bintray from android studio terminal using bintrayUpload command.
My bintray configuration in build.gradle is given below.
<code>ext {
bintrayRepo = 'dev' //the maven repo name (created on bintray)
bintrayName = 'android-dev-core' //the name you want to give at your project on bintray
orgName = 'thisisjatinrana' //your user name

publishedGroupId = 'com.jatin' //aaaa : the librairy group
artifact = 'android-dev-core' //BBBB : the library name
libraryVersion = "1.0.0" //the librairy version

//the library will be : aaaa:BBBB:version

libraryName = 'android-dev-core'
libraryDescription = 'Android essential building blocks to speed up development process'

siteUrl = 'https://github.com/thisisjatinrana/AndroidDevCore'
gitUrl = 'https://github.com/thisisjatinrana/AndroidDevCore.git'

developerId = 'jatinrana'
developerName = 'Jatin Rana'
developerEmail = 'email@example.com'

licenseName = 'The Apache Software License, Version 2.0'
licenseUrl = 'http://www.apache.org/licenses/LICENSE-2.0.txt'
allLicenses = ["Apache-2.0"]
</code>
}
Here artifact and bintray project name should be same as your library name in android studio.
Answer: If your lib and artifact have different name,  you will see there will be two folders in bintray's file section. Pom files and jar files will be in different folder. To avoid this, you should rename your artifact and your lib(module) as same.
I think that bintray project name can be different. It is optional. Artifact and module name equality will be enough. You will see your pom files and jar files in same folder after build your project.


What is the meaning of the expression "Being into the blue"?

Question: Can that be used to describe somebody running out of money other than feeling down/depressed?
Comment: http://www.thefreedictionary.com/into+the+blue
Answer: Please supply some context.
A physicist talking about the Doppler effect may describe light waves as "being shifted into the blue".
Sometimes we talk about someone who has left without saying where he is going as having "disappeared into the blue". I'd guess this comes from the fact that the sky is blue, and we imagine him flying off into the sky and disappearing. But I'm just guessing about that.
In a specific context it could mean all sorts of things. Like, "When job applicants arrive, put forms from people with experience in the green box and those with no experience into the blue." "She wasn't sure whether she should wear her green dress or her blue dress, but after some hesitation she slipped into the blue." "Picasso's paintings tended more and more into the blue during this period." Etc.
Answer: The phrase "being into the blue" is not a set expression in English, and by itself does not make much sense to me.
feeling blue is the phrase you are thinking of for feeling down/depressed.
in the red is the phrase you're looking for for being in debt/making a loss. The opposite of it is in the black.
There are various other set expressions using blue, but none I can think of that involve losing money/being in debt.  Into the blue itself, if pressed, I would associate with the sea/sailing - as "the blue" is sometimes used to mean the sea.


Permutations with duplicates

Question: I have a data set $2\; 3\; 3\; 4\; 4\; 4\; 4$
I want to find the number of unique numbers of $3$ digit numbers that can be formed using this.
I was thinking of doing $\large{\frac{^7P_3}{4!\times 2!}}$, but this doesn't seem right.
Comment: Does this answer your question? [How to find the number of $k$-permutations of $n$ objects with $x$ types, and $r_1, r_2, r_3, \cdots , r_x$ = the number of each type of object?](https://math.stackexchange.com/questions/2372/how-to-find-the-number-of-k-permutations-of-n-objects-with-x-types-and-r)
Answer: I answered a similar question here.
Your data set is a multiset that can be written as
$$
S=(\underbrace{2,\cdots,2 }_{1},\underbrace{3,\cdots,3 }_{2},\underbrace{4,\cdots,4 }_{4})
$$
where the number under the brace is the multiplicity of the element above, wich is the number of instances of the element in the multiset. Lets call the number of digit you need $l$ (in this case $l=3$). Lets call the number of distinct elements of the multiset $n$ (in this case $n=3$) and lets call the multiplicity of the $k_{th}$ element $m_k$ (in this case $m_1=1$, $m_2=2$ and $m_3=4$), what you need are all the combinations of $(x_1,x_2,\dots,x_n)$ where $0 \leq x_k \leq m_k$ so that
$$
\sum_{k=1}^n x_k = l
$$
Lets list all the values that any $x_k$ can have:
$$
x_1=(0,1)
$$
$$
x_2=(0,1,2)
$$
$$
x_3=(0,1,2,3,4)
$$
and, with those values, lets list all their possible combinations, remembering that their sum must be equal to $l$:
$$
C_1=(0,0,3)
$$
$$
C_2=(0,1,2)
$$
$$
C_3=(0,2,1)
$$
$$
C_4=(1,0,2)
$$
$$
C_5=(1,1,1)
$$
$$
C_6=(1,2,0)
$$
Since the sum of the elements of each combination is equal to $l$, you can see each combination as a multiset in wich $l$ is equal to the sum of the multiplicity of each element, so the number of permutations for each combination is
$$
\frac{l!}{x_1!x_2! \dots x_k!}
$$
What remains to do is to sum all the numbers of permutations of each combination to get the final answer, so
$$
\frac{3!}{0!0!3!}+\frac{3!}{0!1!2!}+\frac{3!}{0!2!1!}+\frac{3!}{1!0!2!}+\frac{3!}{1!1!1!}+\frac{3!}{1!2!0!}=1+3++3+3+6+3=19
$$
If you need a deeper explanation of why this works you can check the link above. I came up with this method while working on a project and I'm not a matematician myself, so it could be a bit messy. Sorry in advance.
Answer: If you have 2 as the first digit, you can have 3 and 4 as the second and third digits, so this gives 233 234 243 244, four numbers.
If you have 3 as the first digit, you can have 2 and 3 and 4 as second and third digits (but 2 only once), giving 323 332 324 342 334 343 344, seven numbers.
If you have 4 as the first digit, you can have 2, 3 and 4 as second and third digits, giving 424 442 423 432 433 434 443 444, eight numbers.
4 + 7 + 8 = 19 unique 3 digit numbers.
Rather brute force, but it works pretty easily for this problem.
Answer: Alternatively, start from all 3-digit permutations of {2,3,4}, with repeats. That's $3^3=27$. Then remove numbers that have too many 2's or 3's.
Take out numbers with exactly 2 2's: 2 choices for the remaining digit and 3 ways to permute the 3 digits is 6.
Take out numbers with exactly 3 2's, of which there's only 1.
Take out numbers with 3 3's, of which there's only 1.
Then what's left is 27-6-1-1 = 19
Answer: If you start off with the 7P3 ways of choosing three distinct ordered elements from the multiset {2,3,3,4,4,4,4} then you will need to compensate for the multiply-counted 3-digit numbers in different ways depending on the structure of the number itself.  Consequently, you're likely to be stuck using an almost brute-force attack on the problem.
For example, you could generate all the unordered 3-digit numbers:
233, 234, 244, 334, 344, 444

Then consider one-by-one how many ordered 3-digit numbers have those particular digits.
3!/2! + 3! + 3!/2! + 3!/2! + 3!/2! + 3!/3!

Once you're done, you could check your result using GAP by:
Arrangements([2,3,3,4,4,4,4],3);

Answer: It seems to me that a general formula for this simple but irregular question would be an overkill. Perhaps it is more efficient to simply count the possibilities:

for each of the possible 3 locations of 2 there are 4 such numbers, for a total of 12;
there are a total of 8 different 3-digit numbers which have digits 3 or 4; however exactly one of them, namely 333, is not permissible; thus there are 7 different allowable 3-digit numbers, which have 3 and 4 as their only digits;

We see that all together there are 12+7 = 19 different solutions (3-digit numbers, which satisfy the stated assumptions).

Permutations with duplicates


Old English Etymology

Question: Recently in my research I came across an O.E. word, 'ingebringan' out of a dictionary wherein the scholar translated it as "to bring in". It seems to me that in a verbatim translation, he left out the suffix 'an' which on both nouns and adjectives means 'of or belonging to' or it may also mean 'one'. The word ge in O.E. can mean to, into or together. Can a scholar out there clarify this for me. Thank you
Comment: Do you have a citation showing the use of _ingebringan_? What is the name of the dictionary?
Comment: Source: A Concise Anglo-Saxon Dictionary by John Clark Hall, 1916, page 176. On the internet
Comment: Thank you. I'm afraid I can't really add anything. It isn't in any of the couple of Old English books that I have, and probably isn't that common.
Answer: -an is the Old English verbal suffix indicating the infinitive, e.g. singan, "to sing", drincan, "to drink", niman, "to take". (Compare singen, trinken, nehmen in Modern German.) The scholar's analysis seems correct to me.
Edit: I overlooked the other part of the question. ġe- could be a simple intensifier, but further context is in order if we want to be certain, as it can mean a number of things.
Comment: Are you familiar with German? Ge- usually signifies a participle form . Also OP's concern about the ending 'an' is also misguided... if one were to be familiar with German infinitive endings - OE being heavy Germanic.
Comment: @d'alar'cop yes I am, and yes it does, and yes that is one of the things it does in Old English, too (as you will see by following my link). In fact we have a [dedicated question](http://english.stackexchange.com/a/22710/300) on that. However, the prefix alone does not usually a participle make. Note how it's *gelost* and not *gelosian*, or back to German again *gebracht* and not *gebringen*.
Comment: But not all OE past participles were formed with _ge-_.
Comment: Yes, and then there's that.
Comment: I found this reference and I thought to add it here: "an, suffix. I. Derivative. 1. repr. L. anus, ana,-anum, of or belonging to. Orig. in M.E. -ain, or (after i ) -en, after OFr., but later refash. -an. Esp. added to proper names; 'belonging to a place', as Oxonian, etc.; 'following a founder', or 'a system', as Lutheran, Anglican..." Source: Shorter Oxford English Dict., Vol. 1, A-M, 1933, Oxford University Press. In understanding Modern English the word 'bring' is regarded now as a verb. But was it always thus?

Old English Etymology


Capital losses treatment

Question: I incurred capital losses as a resident alien in the USA. Now, having left the USA, I am a non-resident alien and I am given to understand that I do not have to show capital gains or losses on the tax return form. Does this mean I cannot deduct any of the said losses from future capital gains from now on?
Answer: Capital Gains arising from not effectively connected income (Schedule NEC) of 1040-NR, i.e. Stock, Bond, Savings Account, are exempt from US Capital Gains Tax. So if you had Capital Loss carryover, there is nothing to offset with.
"Capital gains of aliens present in the United States 183 days or more if such gains and losses were effectively connected with the conduct of a trade or business within the United States"
For Effectively Connected Income (ECI) and if you are present but not deemed as resident, according to 26 U.S. Code §871. (a)(2),

such gains and losses shall be determined without regard to section
  1202 and such losses shall be determined without the benefits of the
capital loss carryover provided in section 1212.

Either way, NEC or ECI, your past Capital Loss is useless.
Comment: Thank you. What if I become a resident alien again in the future?

Capital losses treatment


Is it always true that if $\gcd(a,b)=1$ then $\gcd(ab, c) = \gcd(a, c)\gcd(b, c)$?

Question: We had a discussion in lecture recently about the greatest common denominator, and the topic came up about, given $\gcd(a, b) = 1$ and any nonzero integer $c$, whether or not $$\gcd(ab, c) = \gcd(a, c)\gcd(b, c).$$ Is this always true? We also talked about the general case $\gcd(ab, c) = \gcd(a, c)\gcd(b, c)$, and how that is not always true, but this other problem has interested me. Can anyone offer some insight?
Comment: @tetori, there are no $x$s and $y$s in the question...
Comment: If $x$ and $y$ are relatively prime, this equality holds.
Comment: I edited the title.  It was too easy to misunderstand the question the way it stood.
Comment: @Mariano Suárez-Alvarez♦ Oh, it is my mistake :(
Answer: $\: (a,c)(b,c) = (a(b,c),c(b,c)) = (ab,ac,bc,cc) = (ab,(a,b,c)c),  $ which $= (ab,c)$ if $\:(a,b,c) = 1$. Thus it is certainly true in your case $\:(a,b)=1,\:$ but not generally, e.g. it fails for  $\:a = b = c > 1$.
Remark $\ $  We can go further to obtain a precise condition for equality:
Theorem $\quad (a,c)(b,c) = (ab,c) \iff (a,b,c,ab/(ab,c)) = 1$
Proof $\quad $ Continuing from the above calculation  we have
$\begin{eqnarray}\quad  (a,c)(b,c)
&=&\qquad (c\ (a,b,c),ab)\ &&\ \ \text{by above} \\
&=&\, ((ab,c)\,(a,b,c),ab) &&\ \ \text {by a known gcd law [1] }\\
&=&\ \ (ab,c)((a,b,c),ab/(ab,c)) && \ \ \text{by factoring out}\ (ab,c)
\end{eqnarray}$
and the above $ =\, (ab,c)$ iff the 2nd factor $= 1.\ $ QED $ $ $ $  Here's said link [1]
Comment: As you well know, there is no obligation for downvoters to explain anything.
Comment: @MarianoSuárez-Alvarez But there's etiquette in FAQ:
Be honest. `Above all, be honest. If you see misinformation, vote it down. Add comments indicating what, specifically, is wrong. Provide better answers of your own. Best of all — edit and improve the existing questions and answers!`
Comment: This has been debated in meta. While itt is *nice* if people explain downvotes, they are certainly not *required* to, so any claims that «downvoters should» do anything are simply wrong. A downvote is a downvote: just ignore it like you'd profitably do with upvotes...
Comment: The downvoter should explain, as the above is correct.
Answer: The answer is yes.
Let
$$\gcd(ab,c)= p_1^{\alpha_1}  \cdots p_n^{\alpha_n}$$
Then for each $i$ we have
$$p_i^{\alpha_i}\mid c \,;\, p_i^{\alpha_i}\mid ab$$
Since $a,b$ are relatively prime, we get $ p_i^{\alpha_i}\mid a$ or $ p_i^{\alpha_i}\mid b$. Thus $p_i^{\alpha_i\mid \gcd(a,c)}$ or $p_i^{\alpha_i}\mid\gcd(b,c)$.
This proves that
$$\gcd(ab,c) \mid \gcd(a,c) \gcd(b,c)$$
For the other implication, the key is to observe that
$$\gcd( \gcd(a,c), \gcd(b,c)) \mid \gcd(a,b)=1$$
Since $\gcd(a,c)\mid\gcd(ab,c)$, $ \gcd(b,c)\mid\gcd(ab,c)$ and the two numbers are relatively prime, their product divides $\gcd(ab,c)$.
Answer: Consider $$a = 2 \\ b = 2 \\ c = 2 $$
Comment: The question is asking about the case when $\gcd(a,b)=1$, though it is somewhat unclear (I made the same mistake).
Comment: Ah I shall adjust.
Answer: Let $d_1=gcd(ab,c)$, $d_2=gcd(a,c)$ and $d_3=gcd(b,c)$. For any prime $p$, let $ord_p m$ denote the highest power of $p$ that divides $m$. Want to show that for any prime $p$, $ord_p d_1 = ord_p (d_2 d_3)$. It is trivial to see that $ord_p (mn)=ord_p m + ord_p n$. This means WTS $ord_p d_1 = ord_p d_2 +ord_p d_3$.
Suppose there exists $p$ prime s.t.$ord_p d_1 > ord_p d_2 +ord_p d_3$ . Then if $ord_p d_1=k$ then $p^k|ab$ and $p^k|c$. Since $gcd(a,b)=1$, the first tells us that either $p^k|a$ or $p^k|b$. In the former case $p^k$ is a common divisor for $a$ and $c$ and in the latter for $b$ and $c$. This means in the former case $p^k|d_2$ implying $ord_p d_2\geq k$ clearly a contradiction, since $ord_p$ is a non-negative function and LHS>RHS. It also means, in the latter case $p^k|d_3$ implying $ord_p d_3\geq k$ a contradiction for the same reason. Suppose there exists $p$ prime s.t.$ord_p d_1 > ord_p d_2 +ord_p d_3$ . It is easy to argue that if $ord_p d_2 \neq 0$ then $ord_p d_3=0$, and the other way around. If not, you would have that for some prime $p$, $p$ divides both $d_1$ and $d_2$ and therefore, both $a$ and $b$ a contradiction. WLOG suppose $ord_p d_2=k\neq 0$. We have that $p^k|d_2$ implying $p^k|a$ and $p^k|c$. This means $p^k|ab$ and therefore $p^k|d_1$. This implies $ord_p d_1\geq k = ord_p d_2+ord_p d_3$. This is a contradiction with the fact that $ord_p d_1 > ord_p d_2 +ord_p d_3$. It follows therefore that for all primes $p$ $ord_p d_1 = ord_p (d_2 d_3)$. Therefore the equality is true.