qid
int64 1
74.7M
| question
stringlengths 0
58.3k
| date
stringlengths 10
10
| metadata
sequence | response_j
stringlengths 2
48.3k
| response_k
stringlengths 2
40.5k
|
---|---|---|---|---|---|
70,993 | We know through [General Relativity](http://en.wikipedia.org/wiki/General_relativity) (GR) that matter curves spacetime (ST) like a "ball curves a trampoline" but then how energy curves spacetime? Is it just like matter curvature of ST? | 2013/07/13 | [
"https://physics.stackexchange.com/questions/70993",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/25589/"
] | Theoretical viewpoint:
----------------------
Einstein field equations can be written in the form: $$\color{blue}{G\_{\mu\nu}}=\color{red}{\frac{8\pi G}{c^{4}}} \color{darkgreen}{T\_{\mu\nu}}$$
We can write in simple terms: $$\rm \color{blue}{Space-time \,\,geometry}=\color{red}{const.}\,\,\color{darkgreen}{Material \,\,objects}.$$
And the $T\_{\mu\nu}$ is a mathematical object (a tensor to be precise) which describes material bodies. In that mathematical object, there are some parameters such as the density, the momentum, mass-energy... etc. So it is those parameters that determine 'how much space-time curvature' is around a body. And one of the parameters is of course *energy*. Therefore, *energy* do bend space-time.
Experiments that confirm this point:
------------------------------------
First, do photons have mass? The answer is an emphatic **'no'**. The momentum of a photon is $p=\frac{hf}c$, and from special relativity: $$\begin{align}E=\sqrt{(mc^2)^2+(pc)^2}&\iff E^2=(mc^2)^2+(pc)^2\\&\iff E^2-(pc)^2=(mc^2)^2\\ \end{align}.$$
The energy of a photon is: $E=hf$ which is an experimental fact. It can also be expressed as $E=pc$ since $E=hf=\frac{hf}{c}\cdot c=pc.$ Therefore, $E^2=(pc)^2$ and so $E^2-(pc)^2=0$. Putting this in our previous derivation we get: $E^2-(pc)^2=(mc^2)^2=0$. Since $c^2$ is a constant, then $m=0$. Therefore, photons have no rest mass.
**Claim:** Photons are not subject to gravitational attraction since they have no rest mass.
**Experimental disproof:** [Gravitational lensing](http://en.wikipedia.org/wiki/Gravitational_lens):

You could see light being bent due to the presence of a strong gravitational field.
**Conclusion:** Even if light has no rest mass, it has energy and momentum. And it is being attracted due to gravity, so the natural conclusion is that energy do curve space-time. | The source of gravity in GR is not just mass, but the full energy-momentum tensor; this tensorial quantity is a measure of energy, momentum and stress, and applies to ALL forms of matter and all fields that are non-gravitational. Furthermore, there exists a quantity in differential geometry which is automatically conserved in a small neighbourhood on a differentiable manifold, called the Cartan moment of rotation - it turns out that this is mathematically just the dual of the Einstein tensor, and what GR does is relate these two tensorial quantities. This is what the field equations tell us - that the geometry of space-time is related to its energy-momentum content. |
70,993 | We know through [General Relativity](http://en.wikipedia.org/wiki/General_relativity) (GR) that matter curves spacetime (ST) like a "ball curves a trampoline" but then how energy curves spacetime? Is it just like matter curvature of ST? | 2013/07/13 | [
"https://physics.stackexchange.com/questions/70993",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/25589/"
] | According to Newtonian gravity if you made 100 million cannon balls (10kg each) and shipped them to deep space assembled them with some explosives and exploded it with enough force so none get hurt but they all went out spherically to a maximum of 2 miles (if you don't know what a mile is, just read it as a km and none of the physics will be different but the abbreviation is mi and I do use that later) from the center that only the mass of the cannon balls and the number of them matters, so it would be like a (very small) planet of mass 1000 million kg. Specifically, Newtonian gravity says you could instead send more explosives to shoot them so that they all travel spherically outwards for 10 miles and someone orbiting them would feel the same gravitational attraction as if you made a 2mi explosion of the balls, so it would be like a (very small) planet of mass 1000 million kg either way.
General Relativity disagrees. Which is good. Because that additional explosives to make it 10mi instead of 2mi had some mass and the gravitational attraction far away shouldn't change the instant you set them off. Not the exact same instant at least, since nothing should go faster than light by just setting off an explosive.
On the one hand your question looks like it has an easy answer, it is actually the energy associaited with the mass that makes curvature. The mass itself did nothing, only the energy associated with the mass did something. but that answer, while accurate, sidesteps the whole question about how curvature is caused.
The first thing to know about curvature is that it is natural. Einstein's equation $R\_{ab}-\frac{1}{2}g\_{ab}R=kT^\frac{8\pi G}{c^4}T\_{ab}$ has a version for vacuum that is $R\_{ab}-\frac{1}{2}g\_{ab}R=0$ and that equation does not say that curvature is zero. It says that certain combinations of rates of change of the metric have to balance against the existing current metric. So certain metrics have to change certain ways. The equation allows, for instance, gravitational waves to propagate through empty space with the rate of change of curvature in a region changing according to the way curvature varies nearby.
So curvature is natural, even in empty space, and curvature can cause itself, either causing curvature nearby or causing future curvature right there.
And certain kinds of curvature line up just fine in spacetime, and other do not. The kinds that do line up solve $R\_{ab}-\frac{1}{2}g\_{ab}R=0.$ The kinds that do not line up naturally, don't solve $R\_{ab}-\frac{1}{2}g\_{ab}R=0.$
The second thing to know about curvature is to note that $R\_{ab}-\frac{1}{2}g\_{ab}R$ always has the property that its (covariant) divergence vanishes. That means it is possible to have matter that equals $R\_{ab}-\frac{1}{2}g\_{ab}R$ because matter has its (covariant) divergence always vanishes. Some people go a bit extreme with this, they make spacetimes with warp bubbles and long lived wormholes and say, well you just need to put some really really really weird matter right in the right places.
But it does mean that matter can make things curve differently than it naturally would in a vacuum. Let's use that to see how matter can make spacetime curve.
Take two different natural curvatures. For the first, you can take the way the vacuum spacetime outside a planet in deep space is curved (the simplest one is called a Schwarzschild spacetime), since it is the region outside a planet where it is all vacuum, this is the kind of curvature that exists fine on its own, and even is curved just right so as to make the curvature in the future be just like the curvature now. For the second natural curvature, you can take a flat spacetime (called Minkowski spacetime). If you take a ball of radius 10 miles and take that region of flat Minkowski that can be your first region. Then you can take the Schwarzschild solution for a parameter of $M= 1000 million kg$ and cut out a spherical surface of surface area $4\pi (10mi)^2$ and glue the ball of Minkowski spacetime to the exterior of the Schwarzschild spacetime, so it is Schwarzschild on the outside and Minkowski on the inside
Anytime the surfaces line up, it is a possible spacetime. But the matter might have to be be really really weird. Do we need really really weird matter? No. Having the 100 million cannon balls of 10kg each that came to rest at 10mi from the center is exactly the right distribution of matter to sew those two solutions together.
And now as the canon balls come down we can see curvature get created. There is no curvature on the inside of the spherical shell of cannon balls. But as the canon balls fall down, the region right outside the outer shell doesn't have matter there anymore so it has to evolve in the natural (vacuum) way, but the curvature out there is the Schwarzschild curvature, which is one of the kinds of curvature that naturally evolves to itself, so the curvature right outside the shell of cannon balls will make more of itself inside if there is nothing to stop it.
And when I say more of itself, I strangely mean exactly that. A totally interesting (or mind blowing) feature is that when the cannon balls get to only being 9mi from the center the distance outside the shell of falling cannon balls is more than 1 mi away from where it started. When the cannon balls fall, the Schwarzschild solution outside creates more distance between itself and the region outside than it eats up from the inside down. It's like making a giant funnel that is deeper, to make the funnel go from a circle of circumference $2\pi(10cm)$ to a circle of circumference $2\pi(9cm)$ requires more than 1cm of distance between the two circles because the funnel surface is curved.
In out example it is like putting a flat disk of radius 10cm into your giant funnel and then taking it out and replacing it with a flat disk of radius 9cm, there will be more funnel visible because the smaller one covers up less of it. Normal geometry holds on the disk and curved geometry holds on the funnel. We are doing the same thing but in a higher dimension.
OK. So now we see how curvature gets created. Every galaxy was made in the past by matter infalling towards the center, as each shell of matter crosses over a spherical thin shelled region it ties together a region less curvature on the inside to a region of more curvature on the outside. Why? Because that is what ordinary everyday regular matter does. It's not really really weird matter, so it connects higher curvature on the outside to lower curvature (or none) on the inside. Thus leaving the outer galaxy curved so that the sun could one day orbit the galactic center. And similarly as the sun formed layer by layer, it connected a region of more curvature on the outside to a region of less curvature on the inside, leaving the solar system curved outside the sun so that we could one day orbit the sun. And similarly as the earth formed it left the region i\outside itself more curved, so that the moon could orbit the earth.
Now I said that GR gives a different curvature for the 2mi explosion and the 10mi explosion. Let's see what happens when the cannon balls get to 2mi away from the center. There are still 100 million cannon balls. And they still have a mass of 10kg each. But they have fallen 8 (or more?) mil and have been speeding up the whole way. They have more energy. And it is actually the energy, momentum, pressure, and stress of matter that allows different curvature regions to be sewn together. If you had the same number of cannon balls at 2mi radius from the center but all of them were at rest, they wouldn't have enough energy to connect up to such a highly curved spacetime. What that means is that when you brought the cannon balls and the smaller amount of explosives they didn't curve the spacetime around themselves as much when they were brought in the first time.
This makes sense, if you brought less explosives in when you made your cannon ball explosion the spacetime outside was curved less. If you brought in more explosives, then you curved space more. So when the explosives are used up (your explosives could have been matter and antimatter that exploded into pure energy, both regualr everyday matter and the antiparticles versus of regular everyday matter are have positive energy and positive mass, those really really really weird matter that you need for weird spacetimes are really really really weird). So when the explosives are used up the cannon balls take off with lots of energy but that region of spacetime outside is still curved the same way it was when you sent the explosives down to the center. This higher energy matter (more energy because moving faster) has to be enough to convert that higher curvature on the outside into (less) flat space that becomes the inside. We know the curvature on the inside has to be zero for symmetry reasons (everything is spherically symmetric and there is nothing inside the shell of matter and we assume the cannon balls are not really really really weird so they aren't lined with negative energy on one side and extra compensating positive energy on the other).
You can think of it as a certain amount of energy density leaves behind empty space of less distance than the curved surface distance it eats up as it expands. But that rate is determined by the energy and momentum and pressure and stress. And not by mass. Gravity and curvature are not created by mass, they are made by energy (and momentum and pressure and stress). Energy and momentum and pressure and stress together make $T\_{ab}$ and together they evolve in such as way as to have zero (covariant) divergence so only those can patch together a nonzero term on the left hand side of $R\_{ab}-\frac{1}{2}g\_{ab}R=kT^\frac{8\pi G}{c^4}T\_{ab}.$
Since it is energy, not mass, that evolves with zero covariant divergence it is energy, not mass, that can follow that seem of expanding and contracting space as the place where the vacuum solutions of natural curvature evolve. The sum of the rest masses of the parts does not change over time the way you need to patch up the two different natural curvatures to each other based on how the two natural (vacuum) curvatures evolve on their own.
So it is energy, not mass, that is the source of gravity, and by source, we mean something that can piece together different natural regions of curvature, energy changes as the surfaces move in such a way to allow it to continue patching them together (possibly making more space on one side than it eats up on the other, but that's really about keeping the differently flowing rates of time to line up, if time flows slower on the regions farther away from the outside of a surface, you need to make more space on the outside as you flow the surface in.
OK. I've answered your question, but there is one detail I want to be honest about. For brevity I sometimes talked about "more curvature on the outside" and "less curvature on the inside" and what I meant was like if you had two layers of thin shells then inside both it might be flat and in between the two shells it might look like a curvature similar to a star of "lower mass" and outside both of them it might look like a curvature outside a star of "higher mass". That's what I meant by higher curvature, and lower curvature. Around a star of fixed mass, the true real objective curvature gets smaller the farther out you are. So when the galaxy was forming, the curvature was small out here and as the contracting galaxy had lots of matter move in closer, it extended that curvature out here that was slight into a curvature closer in that was curved "the same" way, i.e. that natural vacuum kind of way. But that "same" way naturally has more actual curvature closer in, so there is more curvature closer in, and I didn't want to be misleading about that. But I was trying to make it clear that you have one type of natural curvature and another type of natural curvature, and they can be types that have higher or lower curvature (at the same distance from very very far away bodies). So my talk about more and less curvature was accurate when the matter was right there and the two regions where touching right there. It's just that later when the matter has moved on that natural region of curvature itself allows curvature to change from point to point. In our example, that means as the cannon balls fall in, the new additional region of more curved space created outside isn't just more space and isn't' just more curved because it is more of the type that was outside (which was more curved) it is even more curved than the stuff that used to be outside because the type of curvature that is outside is the kind that gets more curved the closer in you get (and that is also because it was made from normal not weird matter).
I hope that wasn't too confusing. But I wanted to have a real answer out here about what makes curvature and what i\t means to be a source of curvature. It means that you allow different natural curvatures to line up so you can make one transition in to the other, thus make more or less of one of them.
Potentially alowing one to build up more of a region to give it a chance to get stronger curvature in a direction if it is the kind of curvature that gets stronger in a direction. Leaving stronger curvature on the outside means the newly created region has the stronger curvature, so contracting matter (that isn't weird matter) creates more space and more curvature as it contracts. | The source of gravity in GR is not just mass, but the full energy-momentum tensor; this tensorial quantity is a measure of energy, momentum and stress, and applies to ALL forms of matter and all fields that are non-gravitational. Furthermore, there exists a quantity in differential geometry which is automatically conserved in a small neighbourhood on a differentiable manifold, called the Cartan moment of rotation - it turns out that this is mathematically just the dual of the Einstein tensor, and what GR does is relate these two tensorial quantities. This is what the field equations tell us - that the geometry of space-time is related to its energy-momentum content. |
70,993 | We know through [General Relativity](http://en.wikipedia.org/wiki/General_relativity) (GR) that matter curves spacetime (ST) like a "ball curves a trampoline" but then how energy curves spacetime? Is it just like matter curvature of ST? | 2013/07/13 | [
"https://physics.stackexchange.com/questions/70993",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/25589/"
] | Theoretical viewpoint:
----------------------
Einstein field equations can be written in the form: $$\color{blue}{G\_{\mu\nu}}=\color{red}{\frac{8\pi G}{c^{4}}} \color{darkgreen}{T\_{\mu\nu}}$$
We can write in simple terms: $$\rm \color{blue}{Space-time \,\,geometry}=\color{red}{const.}\,\,\color{darkgreen}{Material \,\,objects}.$$
And the $T\_{\mu\nu}$ is a mathematical object (a tensor to be precise) which describes material bodies. In that mathematical object, there are some parameters such as the density, the momentum, mass-energy... etc. So it is those parameters that determine 'how much space-time curvature' is around a body. And one of the parameters is of course *energy*. Therefore, *energy* do bend space-time.
Experiments that confirm this point:
------------------------------------
First, do photons have mass? The answer is an emphatic **'no'**. The momentum of a photon is $p=\frac{hf}c$, and from special relativity: $$\begin{align}E=\sqrt{(mc^2)^2+(pc)^2}&\iff E^2=(mc^2)^2+(pc)^2\\&\iff E^2-(pc)^2=(mc^2)^2\\ \end{align}.$$
The energy of a photon is: $E=hf$ which is an experimental fact. It can also be expressed as $E=pc$ since $E=hf=\frac{hf}{c}\cdot c=pc.$ Therefore, $E^2=(pc)^2$ and so $E^2-(pc)^2=0$. Putting this in our previous derivation we get: $E^2-(pc)^2=(mc^2)^2=0$. Since $c^2$ is a constant, then $m=0$. Therefore, photons have no rest mass.
**Claim:** Photons are not subject to gravitational attraction since they have no rest mass.
**Experimental disproof:** [Gravitational lensing](http://en.wikipedia.org/wiki/Gravitational_lens):

You could see light being bent due to the presence of a strong gravitational field.
**Conclusion:** Even if light has no rest mass, it has energy and momentum. And it is being attracted due to gravity, so the natural conclusion is that energy do curve space-time. | According to Newtonian gravity if you made 100 million cannon balls (10kg each) and shipped them to deep space assembled them with some explosives and exploded it with enough force so none get hurt but they all went out spherically to a maximum of 2 miles (if you don't know what a mile is, just read it as a km and none of the physics will be different but the abbreviation is mi and I do use that later) from the center that only the mass of the cannon balls and the number of them matters, so it would be like a (very small) planet of mass 1000 million kg. Specifically, Newtonian gravity says you could instead send more explosives to shoot them so that they all travel spherically outwards for 10 miles and someone orbiting them would feel the same gravitational attraction as if you made a 2mi explosion of the balls, so it would be like a (very small) planet of mass 1000 million kg either way.
General Relativity disagrees. Which is good. Because that additional explosives to make it 10mi instead of 2mi had some mass and the gravitational attraction far away shouldn't change the instant you set them off. Not the exact same instant at least, since nothing should go faster than light by just setting off an explosive.
On the one hand your question looks like it has an easy answer, it is actually the energy associaited with the mass that makes curvature. The mass itself did nothing, only the energy associated with the mass did something. but that answer, while accurate, sidesteps the whole question about how curvature is caused.
The first thing to know about curvature is that it is natural. Einstein's equation $R\_{ab}-\frac{1}{2}g\_{ab}R=kT^\frac{8\pi G}{c^4}T\_{ab}$ has a version for vacuum that is $R\_{ab}-\frac{1}{2}g\_{ab}R=0$ and that equation does not say that curvature is zero. It says that certain combinations of rates of change of the metric have to balance against the existing current metric. So certain metrics have to change certain ways. The equation allows, for instance, gravitational waves to propagate through empty space with the rate of change of curvature in a region changing according to the way curvature varies nearby.
So curvature is natural, even in empty space, and curvature can cause itself, either causing curvature nearby or causing future curvature right there.
And certain kinds of curvature line up just fine in spacetime, and other do not. The kinds that do line up solve $R\_{ab}-\frac{1}{2}g\_{ab}R=0.$ The kinds that do not line up naturally, don't solve $R\_{ab}-\frac{1}{2}g\_{ab}R=0.$
The second thing to know about curvature is to note that $R\_{ab}-\frac{1}{2}g\_{ab}R$ always has the property that its (covariant) divergence vanishes. That means it is possible to have matter that equals $R\_{ab}-\frac{1}{2}g\_{ab}R$ because matter has its (covariant) divergence always vanishes. Some people go a bit extreme with this, they make spacetimes with warp bubbles and long lived wormholes and say, well you just need to put some really really really weird matter right in the right places.
But it does mean that matter can make things curve differently than it naturally would in a vacuum. Let's use that to see how matter can make spacetime curve.
Take two different natural curvatures. For the first, you can take the way the vacuum spacetime outside a planet in deep space is curved (the simplest one is called a Schwarzschild spacetime), since it is the region outside a planet where it is all vacuum, this is the kind of curvature that exists fine on its own, and even is curved just right so as to make the curvature in the future be just like the curvature now. For the second natural curvature, you can take a flat spacetime (called Minkowski spacetime). If you take a ball of radius 10 miles and take that region of flat Minkowski that can be your first region. Then you can take the Schwarzschild solution for a parameter of $M= 1000 million kg$ and cut out a spherical surface of surface area $4\pi (10mi)^2$ and glue the ball of Minkowski spacetime to the exterior of the Schwarzschild spacetime, so it is Schwarzschild on the outside and Minkowski on the inside
Anytime the surfaces line up, it is a possible spacetime. But the matter might have to be be really really weird. Do we need really really weird matter? No. Having the 100 million cannon balls of 10kg each that came to rest at 10mi from the center is exactly the right distribution of matter to sew those two solutions together.
And now as the canon balls come down we can see curvature get created. There is no curvature on the inside of the spherical shell of cannon balls. But as the canon balls fall down, the region right outside the outer shell doesn't have matter there anymore so it has to evolve in the natural (vacuum) way, but the curvature out there is the Schwarzschild curvature, which is one of the kinds of curvature that naturally evolves to itself, so the curvature right outside the shell of cannon balls will make more of itself inside if there is nothing to stop it.
And when I say more of itself, I strangely mean exactly that. A totally interesting (or mind blowing) feature is that when the cannon balls get to only being 9mi from the center the distance outside the shell of falling cannon balls is more than 1 mi away from where it started. When the cannon balls fall, the Schwarzschild solution outside creates more distance between itself and the region outside than it eats up from the inside down. It's like making a giant funnel that is deeper, to make the funnel go from a circle of circumference $2\pi(10cm)$ to a circle of circumference $2\pi(9cm)$ requires more than 1cm of distance between the two circles because the funnel surface is curved.
In out example it is like putting a flat disk of radius 10cm into your giant funnel and then taking it out and replacing it with a flat disk of radius 9cm, there will be more funnel visible because the smaller one covers up less of it. Normal geometry holds on the disk and curved geometry holds on the funnel. We are doing the same thing but in a higher dimension.
OK. So now we see how curvature gets created. Every galaxy was made in the past by matter infalling towards the center, as each shell of matter crosses over a spherical thin shelled region it ties together a region less curvature on the inside to a region of more curvature on the outside. Why? Because that is what ordinary everyday regular matter does. It's not really really weird matter, so it connects higher curvature on the outside to lower curvature (or none) on the inside. Thus leaving the outer galaxy curved so that the sun could one day orbit the galactic center. And similarly as the sun formed layer by layer, it connected a region of more curvature on the outside to a region of less curvature on the inside, leaving the solar system curved outside the sun so that we could one day orbit the sun. And similarly as the earth formed it left the region i\outside itself more curved, so that the moon could orbit the earth.
Now I said that GR gives a different curvature for the 2mi explosion and the 10mi explosion. Let's see what happens when the cannon balls get to 2mi away from the center. There are still 100 million cannon balls. And they still have a mass of 10kg each. But they have fallen 8 (or more?) mil and have been speeding up the whole way. They have more energy. And it is actually the energy, momentum, pressure, and stress of matter that allows different curvature regions to be sewn together. If you had the same number of cannon balls at 2mi radius from the center but all of them were at rest, they wouldn't have enough energy to connect up to such a highly curved spacetime. What that means is that when you brought the cannon balls and the smaller amount of explosives they didn't curve the spacetime around themselves as much when they were brought in the first time.
This makes sense, if you brought less explosives in when you made your cannon ball explosion the spacetime outside was curved less. If you brought in more explosives, then you curved space more. So when the explosives are used up (your explosives could have been matter and antimatter that exploded into pure energy, both regualr everyday matter and the antiparticles versus of regular everyday matter are have positive energy and positive mass, those really really really weird matter that you need for weird spacetimes are really really really weird). So when the explosives are used up the cannon balls take off with lots of energy but that region of spacetime outside is still curved the same way it was when you sent the explosives down to the center. This higher energy matter (more energy because moving faster) has to be enough to convert that higher curvature on the outside into (less) flat space that becomes the inside. We know the curvature on the inside has to be zero for symmetry reasons (everything is spherically symmetric and there is nothing inside the shell of matter and we assume the cannon balls are not really really really weird so they aren't lined with negative energy on one side and extra compensating positive energy on the other).
You can think of it as a certain amount of energy density leaves behind empty space of less distance than the curved surface distance it eats up as it expands. But that rate is determined by the energy and momentum and pressure and stress. And not by mass. Gravity and curvature are not created by mass, they are made by energy (and momentum and pressure and stress). Energy and momentum and pressure and stress together make $T\_{ab}$ and together they evolve in such as way as to have zero (covariant) divergence so only those can patch together a nonzero term on the left hand side of $R\_{ab}-\frac{1}{2}g\_{ab}R=kT^\frac{8\pi G}{c^4}T\_{ab}.$
Since it is energy, not mass, that evolves with zero covariant divergence it is energy, not mass, that can follow that seem of expanding and contracting space as the place where the vacuum solutions of natural curvature evolve. The sum of the rest masses of the parts does not change over time the way you need to patch up the two different natural curvatures to each other based on how the two natural (vacuum) curvatures evolve on their own.
So it is energy, not mass, that is the source of gravity, and by source, we mean something that can piece together different natural regions of curvature, energy changes as the surfaces move in such a way to allow it to continue patching them together (possibly making more space on one side than it eats up on the other, but that's really about keeping the differently flowing rates of time to line up, if time flows slower on the regions farther away from the outside of a surface, you need to make more space on the outside as you flow the surface in.
OK. I've answered your question, but there is one detail I want to be honest about. For brevity I sometimes talked about "more curvature on the outside" and "less curvature on the inside" and what I meant was like if you had two layers of thin shells then inside both it might be flat and in between the two shells it might look like a curvature similar to a star of "lower mass" and outside both of them it might look like a curvature outside a star of "higher mass". That's what I meant by higher curvature, and lower curvature. Around a star of fixed mass, the true real objective curvature gets smaller the farther out you are. So when the galaxy was forming, the curvature was small out here and as the contracting galaxy had lots of matter move in closer, it extended that curvature out here that was slight into a curvature closer in that was curved "the same" way, i.e. that natural vacuum kind of way. But that "same" way naturally has more actual curvature closer in, so there is more curvature closer in, and I didn't want to be misleading about that. But I was trying to make it clear that you have one type of natural curvature and another type of natural curvature, and they can be types that have higher or lower curvature (at the same distance from very very far away bodies). So my talk about more and less curvature was accurate when the matter was right there and the two regions where touching right there. It's just that later when the matter has moved on that natural region of curvature itself allows curvature to change from point to point. In our example, that means as the cannon balls fall in, the new additional region of more curved space created outside isn't just more space and isn't' just more curved because it is more of the type that was outside (which was more curved) it is even more curved than the stuff that used to be outside because the type of curvature that is outside is the kind that gets more curved the closer in you get (and that is also because it was made from normal not weird matter).
I hope that wasn't too confusing. But I wanted to have a real answer out here about what makes curvature and what i\t means to be a source of curvature. It means that you allow different natural curvatures to line up so you can make one transition in to the other, thus make more or less of one of them.
Potentially alowing one to build up more of a region to give it a chance to get stronger curvature in a direction if it is the kind of curvature that gets stronger in a direction. Leaving stronger curvature on the outside means the newly created region has the stronger curvature, so contracting matter (that isn't weird matter) creates more space and more curvature as it contracts. |
63,514,476 | I am attempting to create a regular expression for validating edu emails which may or may not have a sub domain. Some schools have emails like "[email protected]" while other schools have emails like "[email protected]".
```
([0-9]|[a-z]|[A-Z])+@([0-9]|[a-z]|[A-Z])+([0-9]|[a-z]|[A-Z])\.edu$"
```
This is the current regular expression that I have but I am not well versed in these.
I am looking to create an expression that will validate emails with one domain and emails with a subdomain.
Any help would be appreciated. Thanks! | 2020/08/20 | [
"https://Stackoverflow.com/questions/63514476",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14140227/"
] | Didn't implement NLP for verb / noun separation, just added a list of good words.
They can be extracted and normalized with [spacy](https://spacy.io/) relatively easy.
Please note that `walk` occurs in 1,2,5 sentences and forms a triad.
```py
import re
import networkx as nx
import matplotlib.pyplot as plt
plt.style.use("ggplot")
sentences = [
"I went out for a walk or walking.",
"When I was walking, I saw a cat. ",
"The cat was injured. ",
"My mum's name is Marylin.",
"While I was walking, I met John. ",
"Nothing has happened.",
]
G = nx.Graph()
# set of possible good words
good_words = {"went", "walk", "cat", "walking"}
# remove punctuation and keep only good words inside sentences
words = list(
map(
lambda x: set(re.sub(r"[^\w\s]", "", x).lower().split()).intersection(
good_words
),
sentences,
)
)
# convert sentences to dict for furtehr labeling
sentences = {k: v for k, v in enumerate(sentences)}
# add nodes
for i, sentence in sentences.items():
G.add_node(i)
# add edges if two nodes have the same word inside
for i in range(len(words)):
for j in range(i + 1, len(words)):
for edge_label in words[i].intersection(words[j]):
G.add_edge(i, j, r=edge_label)
# compute layout coords
coord = nx.spring_layout(G)
plt.figure(figsize=(20, 14))
# set label coords a bit upper the nodes
node_label_coords = {}
for node, coords in coord.items():
node_label_coords[node] = (coords[0], coords[1] + 0.04)
# draw the network
nodes = nx.draw_networkx_nodes(G, pos=coord)
edges = nx.draw_networkx_edges(G, pos=coord)
edge_labels = nx.draw_networkx_edge_labels(G, pos=coord)
node_labels = nx.draw_networkx_labels(G, pos=node_label_coords, labels=sentences)
plt.title("Sentences network")
plt.axis("off")
```
[](https://i.stack.imgur.com/pLbLx.png)
**Update**
If you want to measure the similarity between different sentences, you may want to calculate the difference between sentence embedding.
This gives you an opportunity to find semantic similarity between sentences with different words like "A soccer game with multiple males playing" and "Some men are playing a sport". Almost SoTA approach using BERT can be found [here](https://keras.io/examples/nlp/semantic_similarity_with_bert/), more simple approaches are [here](https://stackoverflow.com/questions/45869881/finding-similarity-between-2-sentences-using-word2vec-of-sentence-with-python).
Since you have similarity measure, just replace add\_edge block to add new edge only if similarity measure is greater than some threshold. Resulting add edges code will look like this:
```
# add edges if two nodes have the same word inside
tresold = 0.90
for i in range(len(words)):
for j in range(i + 1, len(words)):
# suppose you have some similarity function using BERT or PCA
similarity = check_similarity(sentences[i], sentences[j])
if similarity > tresold:
G.add_edge(i, j, r=similarity)
``` | One way to handle this is to tokenize, remove the stop words and create the vocabulary. Then draw the graph based on this vocabulary. I am showing below and example on unigram based tokens but much better approach will be to identify phrases (ngrams) and use them as vocabulary instead of unigrams. Sentence similarly will be pictorially depicted by nodes (and the corresponding sentences) having more in and degree.
Sample:
```
from sklearn.feature_extraction.text import CountVectorizer
import networkx as nx
import matplotlib.pyplot as plt
corpus = [
"Trump says that it is useful to win the next presidential election",
"The Prime Minister suggests the name of the winner of the next presidential election",
"In yesterday conference, the Prime Minister said that it is very important to win the next presidential election",
"The Chinese Minister is in London to discuss about climate change",
"The president Donald Trump states that he wants to win the presidential election. This will require a strong media engagement",
"The president Donald Trump states that he wants to win the presidential election. The UK has proposed collaboration",
"The president Donald Trump states that he wants to win the presidential election. He has the support of his electors",
]
vectorizer = CountVectorizer(analyzer='word', ngram_range=(1, 1), stop_words="english")
vectorizer.fit_transform(corpus)
G = nx.DiGraph()
G.add_nodes_from(vectorizer.get_feature_names())
all_edges = []
for s in corpus:
edges = []
previous = None
for w in s.split():
w = w.lower()
if w in vectorizer.get_feature_names():
if previous:
edges.append((previous, w))
#print (previous, w)
previous = w
all_edges.append(edges)
plt.figure(figsize=(20,20))
pos = nx.shell_layout(G)
nx.draw_networkx_nodes(G, pos, node_size = 500)
nx.draw_networkx_labels(G, pos)
colors = ['r', 'g', 'b', 'y', 'm', 'c', 'k']
for i, edges in enumerate(all_edges):
nx.draw_networkx_edges(G, pos, edgelist=edges, edge_color=colors[i], arrows=True)
#nx.draw_networkx_edges(G, pos, edgelist=black_edges, arrows=False)
plt.show()
```
Output:
[](https://i.stack.imgur.com/yNVad.png) |
920 | It is well-known that we can learn a lot about the structure of the lower crust, mantle, and core by observing the ways in which they refract different kinds of seismic waves.
Do we have any *other* ways of imaging the deeper parts of the Earth, though? | 2014/05/13 | [
"https://earthscience.stackexchange.com/questions/920",
"https://earthscience.stackexchange.com",
"https://earthscience.stackexchange.com/users/67/"
] | Gravity can be used to investigate the lower crust and upper mantle (see for example [Fullea et al, 2014](http://dx.doi.org/10.1016%2Fj.jag.2014.02.003)). Satellite measurements of gravity could even be used to investigate deeper structures in the mantle, like subducting slabs ([Panet, 2014](http://dx.doi.org/10.1038%2Fngeo2063)). However, I couldn't find any use of gravity data to probe deeper, into the core for example.
The [magnetotelluric method](http://en.wikipedia.org/wiki/Magnetotellurics) is sometimes used for deep crustal structure. And features of the geomagnetic field, like [secular variation](http://en.wikipedia.org/wiki/Geomagnetic_secular_variation), can be inverted to investigate as far down as the outer core ([Gubbins, 1996](http://dx.doi.org/10.1016/S0031-9201(96)03187-1)).
However, the most common and well developed method to image the lower mantle and core is still through seismic waves. | One interesting and relatively new technique is by the detection of [geoneutrinos](http://en.wikipedia.org/wiki/Geoneutrino). These particles are produced by radioactive decay in the Earth's interior. They are uncommonly suitable for probing the deep Earth because -- unlike most particles and waves -- they can travel through thousands of kilometres of rock with very little absorption. Of course, this very same characteristic makes actually *detecting* them something of a challenge, and detectors tend to be [rather large](http://www.e15.ph.tum.de/research_and_projects/lena/) (in the thousands of cubic metres). [Araki et al. (2005)](http://www.nature.com/nature/journal/v436/n7050/abs/nature03980.html) gives some early results -- but as the Wikipedia article shows, there are more and bigger detectors on the drawing boards, so we should expect to see more geoneutrino results in the coming years and decades. [This abstract](http://scicolloq.gsfc.nasa.gov/McDonough.html) gives the best elevator pitch I've found so far for geoneutrino research:
>
> Radioactive decay of U and Th gives off ghost-like, neutrino particles that can be detected by 1000 ton detectors built a mile underground, where they are shielded from the cosmic rays that rain down on the Earth. Collaborations between physicists and geologists are detecting these "geo-neutrinos". Future underwater detectors, deployed at different points on the ocean floor, will create a neutrino tomographic image of mantle structures sited at the base of the mantle above the core.
>
>
> |
920 | It is well-known that we can learn a lot about the structure of the lower crust, mantle, and core by observing the ways in which they refract different kinds of seismic waves.
Do we have any *other* ways of imaging the deeper parts of the Earth, though? | 2014/05/13 | [
"https://earthscience.stackexchange.com/questions/920",
"https://earthscience.stackexchange.com",
"https://earthscience.stackexchange.com/users/67/"
] | Gravity can be used to investigate the lower crust and upper mantle (see for example [Fullea et al, 2014](http://dx.doi.org/10.1016%2Fj.jag.2014.02.003)). Satellite measurements of gravity could even be used to investigate deeper structures in the mantle, like subducting slabs ([Panet, 2014](http://dx.doi.org/10.1038%2Fngeo2063)). However, I couldn't find any use of gravity data to probe deeper, into the core for example.
The [magnetotelluric method](http://en.wikipedia.org/wiki/Magnetotellurics) is sometimes used for deep crustal structure. And features of the geomagnetic field, like [secular variation](http://en.wikipedia.org/wiki/Geomagnetic_secular_variation), can be inverted to investigate as far down as the outer core ([Gubbins, 1996](http://dx.doi.org/10.1016/S0031-9201(96)03187-1)).
However, the most common and well developed method to image the lower mantle and core is still through seismic waves. | Inverse problems are some of the most important mathematical problems in science and mathematics. Inverse problems arise in many branches of geophysics, medical imaging, remote sensing, ocean acoustic tomography, nondestructive testing, astronomy, physics and many other fields.
Geophysicists remotely measure the seismic (acoustic), gravity, and electromagnetic fields of the earth and then treat the inverse problem to constrain the properties of the earth's interior. |
920 | It is well-known that we can learn a lot about the structure of the lower crust, mantle, and core by observing the ways in which they refract different kinds of seismic waves.
Do we have any *other* ways of imaging the deeper parts of the Earth, though? | 2014/05/13 | [
"https://earthscience.stackexchange.com/questions/920",
"https://earthscience.stackexchange.com",
"https://earthscience.stackexchange.com/users/67/"
] | One interesting and relatively new technique is by the detection of [geoneutrinos](http://en.wikipedia.org/wiki/Geoneutrino). These particles are produced by radioactive decay in the Earth's interior. They are uncommonly suitable for probing the deep Earth because -- unlike most particles and waves -- they can travel through thousands of kilometres of rock with very little absorption. Of course, this very same characteristic makes actually *detecting* them something of a challenge, and detectors tend to be [rather large](http://www.e15.ph.tum.de/research_and_projects/lena/) (in the thousands of cubic metres). [Araki et al. (2005)](http://www.nature.com/nature/journal/v436/n7050/abs/nature03980.html) gives some early results -- but as the Wikipedia article shows, there are more and bigger detectors on the drawing boards, so we should expect to see more geoneutrino results in the coming years and decades. [This abstract](http://scicolloq.gsfc.nasa.gov/McDonough.html) gives the best elevator pitch I've found so far for geoneutrino research:
>
> Radioactive decay of U and Th gives off ghost-like, neutrino particles that can be detected by 1000 ton detectors built a mile underground, where they are shielded from the cosmic rays that rain down on the Earth. Collaborations between physicists and geologists are detecting these "geo-neutrinos". Future underwater detectors, deployed at different points on the ocean floor, will create a neutrino tomographic image of mantle structures sited at the base of the mantle above the core.
>
>
> | Inverse problems are some of the most important mathematical problems in science and mathematics. Inverse problems arise in many branches of geophysics, medical imaging, remote sensing, ocean acoustic tomography, nondestructive testing, astronomy, physics and many other fields.
Geophysicists remotely measure the seismic (acoustic), gravity, and electromagnetic fields of the earth and then treat the inverse problem to constrain the properties of the earth's interior. |
30,662,784 | I am trying to add validation check on this auto complete, however for some reason because its in an `each()` block it's causing me so many problems.
Full code:
```
<input type="text" class="productOptionSerialNumber" value="@opt.SerialNumber" data-part-num="@opt.PartNumber" />
```
```js
$(".productOptionSerialNumber").each(function () {
var partNum = $(this).attr("data-part-num");
$(this).autocomplete({
source: "@Url.Action("SerialPartNumStockSiteAutoComplete", "Ajax")?stocksitenum=LW&model=" + $("#Form_Prod_Num").val() + "&partnum=" + partNum + "&callnum=" + $("#Form_Call_Num").val(),
minlength: 2,
delay: 300,
})
});
```
For this .productOptionSerialNumber function i cannot do a validation.
i have a working example which has worked before (look below) but with this particular function it doesn't validate, i have tried to add it the same way i did before, but no luck.
Working:
```
$(document).ready(function () {
//$('input[name="Form.InstallType"]').on('change', function() {
var val = $('input[name="Form.InstallType"]:checked').val();
if (val == '1') {
var validOptions = "@Url.Action("SerialProdNumStockSiteAutoComplete", "Ajax")?stocksitenum=LW&model=" + $("#Form_Prod_Num").val();
previousValue = "";
$('#abc').autocomplete({
autoFocus: true,
source: validOptions,
}).change(function(){
var source = validOptions;
var found = $('.ui-autocomplete li').text().search(source);
console.debug('found:' + found);
var val = $('input[name="Form.InstallType"]:checked').val();
if (found < 0 && val === '1') {
$(this).val('');
alert("You must select a value from the auto complete list!");
}
});
}
});
```
So if I don't choose from auto complete I get an alert. I am trying to implement this to the first part of code but because its in a `.each` and `.attr` it's not liking it this way.
Any ideas | 2015/06/05 | [
"https://Stackoverflow.com/questions/30662784",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2519466/"
] | Without additional information I don't know what kind of problems you are experiencing with the each() loop, however what you are trying to accomplish is certainly do-able.
Here is an example, hopefully it will help you fill in anything you are missing on your end.
HTML
```
<label>productOption aaa:</label>
<input type="text" class="productOptionSerialNumber" value="" data-part-num="aaa" />
<br />
<br />
<label>productOption bbb:</label>
<input type="text" class="productOptionSerialNumber" value="" data-part-num="bbb" />
<br />
<br />
<label>productOption ccc:</label>
<input type="text" class="productOptionSerialNumber" value="" data-part-num="ccc" />
```
Jquery
```
var dataFromURL = {
'aaa':['What','Is','Up'],
'bbb':['Nothing','Much','Bro man'],
'ccc':['Clown','Question','Bro schmoe']
}
$(document).ready(function(){
$(".productOptionSerialNumber").each(function () {
var partNum = $(this).attr("data-part-num");
$(this).autocomplete({
source: dataFromURL[partNum],
minlength: 2,
delay: 300,
}).change(function(){
var data = $(this).autocomplete( "option" ).source;
var found = data.indexOf($(this).val());
if (found < 0) {
alert("You must select a value from the auto complete list!");
$(this).val('');
}
});
});
});
```
[Fiddle Example](http://jsfiddle.net/rkfs540q/) | If there isn't specifically a reason it needs to only execute after autocomplete (i.e. validation can occur whenever there is a change -- which, from my understanding is what occurs in the old, working code), you can still bind your validation to $(this).
Also,is there a reason you removed .change() from the new code?
If the reason is because you can't apply the validation to everything in the each statement, you need to check for a unique selector before binding the validation (typically an ID, but I see that there isn't one).
This code code does what I described. It uses ID as a unique selector. If adding an ID to the input tag is not an option, you'll need to find a different one.
```
$(".productOptionSerialNumber").each(function () {
$(this).autocomplete({
source: "@Url.Action("SerialPartNumStockSiteAutoComplete", "Ajax")?stocksitenum=LW&model=" + $("#Form_Prod_Num").val() + "&partnum=" + partNum + "&callnum=" + $("#Form_Call_Num").val(),
minlength: 2,
delay: 300,
});
if ($(this).attr('id') == "thisid")
{
$(this).bind('input propertychange',function(){
alert('this code executed because the input box changed');
});
}
});
``` |
19,574,593 | OK, so I have an Item class that has a many-to-many attribute to User through a 'Roles' class. I am trying to create a django-table for the Items such that out of any of the roles attached to the item, if the current User is attached to that role, the name of the role displays. I hope that makes some sort of sense. Here's what I have so far, which I didn't really expect to work because I don't see how the Table class can know about the request/user. I'm stuck.
models.py
```
class Item(models.Model):
name = models.CharField(max_length=255)
owner = models.ForeignKey(User, related_name='Owner')
roles = models.ManyToManyField(User, through='Role')
class Role(models.Model):
role_type = models.ForeignKey(RoleType)
user = models.ForeignKey(User)
item = models.ForeignKey(Item)
```
tables.py
```
class OwnedTable(tables.Table):
roles = tables.Column()
user = request.user
def render_roles(self):
for role in roles:
if role.User == user:
return role.role_type
else:
pass
class Meta:
model = Item
attrs = {"class": "paleblue"}
fields = ('id', 'name', 'owner', 'roles')
``` | 2013/10/24 | [
"https://Stackoverflow.com/questions/19574593",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1695507/"
] | You can get the `request` object from `self.context`. So if you only need `request.user`, that's one way to do it.
```
class OwnedTable(tables.Table):
roles = tables.Column(empty_values=())
def render_roles(self):
user = self.context["request"].user
...
```
Otherwise, @mariodev's solution works. | It seems like there's no way of using auth user without some overriding.
You can override `__init__` for our table class like this:
```
class OwnedTable(tables.Table):
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user', None)
super(OwnedTable, self).__init__(*args, **kwargs)
```
then, inside view, you call table with `user` argument, like so
```
table = OwnedTable(Person.objects.all(), user=request.user)
```
now you can use `self.user` inside `render_roles` method to refer to the currently logged in user. |
19,574,593 | OK, so I have an Item class that has a many-to-many attribute to User through a 'Roles' class. I am trying to create a django-table for the Items such that out of any of the roles attached to the item, if the current User is attached to that role, the name of the role displays. I hope that makes some sort of sense. Here's what I have so far, which I didn't really expect to work because I don't see how the Table class can know about the request/user. I'm stuck.
models.py
```
class Item(models.Model):
name = models.CharField(max_length=255)
owner = models.ForeignKey(User, related_name='Owner')
roles = models.ManyToManyField(User, through='Role')
class Role(models.Model):
role_type = models.ForeignKey(RoleType)
user = models.ForeignKey(User)
item = models.ForeignKey(Item)
```
tables.py
```
class OwnedTable(tables.Table):
roles = tables.Column()
user = request.user
def render_roles(self):
for role in roles:
if role.User == user:
return role.role_type
else:
pass
class Meta:
model = Item
attrs = {"class": "paleblue"}
fields = ('id', 'name', 'owner', 'roles')
``` | 2013/10/24 | [
"https://Stackoverflow.com/questions/19574593",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1695507/"
] | It seems like there's no way of using auth user without some overriding.
You can override `__init__` for our table class like this:
```
class OwnedTable(tables.Table):
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user', None)
super(OwnedTable, self).__init__(*args, **kwargs)
```
then, inside view, you call table with `user` argument, like so
```
table = OwnedTable(Person.objects.all(), user=request.user)
```
now you can use `self.user` inside `render_roles` method to refer to the currently logged in user. | Another solution is shown on <https://github.com/bradleyayers/django-tables2/issues/156>, which worked for me after some adjustments for my setup.
Given that a Person would have an M2M to Contacts, and you want to display all contacts for that Person in django-tables2, then the following would do:
```
class PersonTable(tables.Table):
person_contacts = tables.Column(accessor="contacts", verbose_name="Contacts")
def render_person_contacts(self, value, table):
clist = ""
cfirst = True
conts = list(value.all())
for c in conts:
if not cfirst:
clist += "<br />"
else:
cfirst = False
print c.id
uri = reverse('cont_detail', kwargs={'pk': c.id})
clist += '<a href="' + uri + '">' + c.name + '</a>' + ' (' + c.relation + ')'
return mark_safe(clist)
```
You basically add a column with a non-existent name, set the accessor to the M2M field name, then call `render_<newly_added_column>` where you obtain what you need from `value`. |
19,574,593 | OK, so I have an Item class that has a many-to-many attribute to User through a 'Roles' class. I am trying to create a django-table for the Items such that out of any of the roles attached to the item, if the current User is attached to that role, the name of the role displays. I hope that makes some sort of sense. Here's what I have so far, which I didn't really expect to work because I don't see how the Table class can know about the request/user. I'm stuck.
models.py
```
class Item(models.Model):
name = models.CharField(max_length=255)
owner = models.ForeignKey(User, related_name='Owner')
roles = models.ManyToManyField(User, through='Role')
class Role(models.Model):
role_type = models.ForeignKey(RoleType)
user = models.ForeignKey(User)
item = models.ForeignKey(Item)
```
tables.py
```
class OwnedTable(tables.Table):
roles = tables.Column()
user = request.user
def render_roles(self):
for role in roles:
if role.User == user:
return role.role_type
else:
pass
class Meta:
model = Item
attrs = {"class": "paleblue"}
fields = ('id', 'name', 'owner', 'roles')
``` | 2013/10/24 | [
"https://Stackoverflow.com/questions/19574593",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1695507/"
] | You can get the `request` object from `self.context`. So if you only need `request.user`, that's one way to do it.
```
class OwnedTable(tables.Table):
roles = tables.Column(empty_values=())
def render_roles(self):
user = self.context["request"].user
...
```
Otherwise, @mariodev's solution works. | Another solution is shown on <https://github.com/bradleyayers/django-tables2/issues/156>, which worked for me after some adjustments for my setup.
Given that a Person would have an M2M to Contacts, and you want to display all contacts for that Person in django-tables2, then the following would do:
```
class PersonTable(tables.Table):
person_contacts = tables.Column(accessor="contacts", verbose_name="Contacts")
def render_person_contacts(self, value, table):
clist = ""
cfirst = True
conts = list(value.all())
for c in conts:
if not cfirst:
clist += "<br />"
else:
cfirst = False
print c.id
uri = reverse('cont_detail', kwargs={'pk': c.id})
clist += '<a href="' + uri + '">' + c.name + '</a>' + ' (' + c.relation + ')'
return mark_safe(clist)
```
You basically add a column with a non-existent name, set the accessor to the M2M field name, then call `render_<newly_added_column>` where you obtain what you need from `value`. |
3,370,823 | I am trying to solve this task
>
> Consider the measure space $([0,1],\mathcal{B}([0,1]),\mu:=2\lambda\_1+3\delta\_{1})$ and the measurable function $f(\omega)=2-\omega$. Find $$\int\_{[0,1]}f\,d\mu$$
>
>
>
My Solution
$$\int\_{a}^{b} f(x) d x=\int\_{[a, b]} f d \lambda\_{1}$$
We know
Thus
$$\int\_{[0,1]} f d \mu=\int\_{[0,1]} 2- x\left(2d \lambda\_{1}+3 d \delta\_{1}\right)=\cdots=6$$ | 2019/09/26 | [
"https://math.stackexchange.com/questions/3370823",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/699012/"
] | I pressume that $\delta\_1$ is the Dirac measure and $\lambda\_1$ the Lebesgue measure.
If so,then you are correct.
Indeed:
So $$\int\_0^1f(x)d\mu(x)=2\int\_0^1(2-x)d\lambda\_1(x)+3\int\_0^1f(x)d\delta\_1(x)$$ $$=2\int\_0^1(2-x)dx+3 f(1)=2(2-\frac{1}{2})+3=6$$ | Marios answer is correct
Just wanted to note to the OP some general facts. It can be checked for simple functions, and then proven in general, that for $a,b$ non-negative and $\mu = a\lambda + b\delta$ where $\lambda,\delta$ finite on the measurable set $A$, we have
$$ \int\_{A} f d\mu = a\int\_{A} f d\lambda + b\int\_{A} f d\delta $$ |
30,123,332 | I'm trying to test my local storage so I've tried a few examples.
this example worked before but now its not. not sure what happened
<https://stackoverflow.com/questions/30116818/how-to-use-local-storage-form-with-html-and-javascript?noredirect=1#comment48344527_30116818/>
Now I am trying this code and nothing pops up on if else, it just says local storage is
```
function lsTest() {
var test = 'test';
try {
localStorage.setItem(test, test);
localStorage.removeItem(test);
return true;
} catch(e) {
return false;
}
}
var elem = document.getElementById('status');
if (lsTest() === true) {
elem.innerHTML += 'available.';
} else {
elem.innerHTML += 'unavailable.';
}
```
html
```
<div id="status">Local Storage is </div>
```
full code
<http://tny.cz/39896a73> | 2015/05/08 | [
"https://Stackoverflow.com/questions/30123332",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4796973/"
] | You should open your page using a webserver and not your local file system. The browser saves the localstorage data based on the host(domain). This prevents cross site local storage access. | There is no issue with your method, but I didn't see any call to this method.
To make it functional, you need to call it with some event. Like: button / anchor onlick, window load / ready as following:
**Javascript:**
```
window.onload = function(){lsTest();}
```
**jQuery:**
```
jQuery(document).ready(function(){
lsTest();
});
```
[**DEMO**](http://jsfiddle.net/6742rm6o/)
However, if you just want to check the browser compatibility of localStorage / sessionStorage then `if(typeof(Storage) !== undefined){}` is quite useful. |
30,123,332 | I'm trying to test my local storage so I've tried a few examples.
this example worked before but now its not. not sure what happened
<https://stackoverflow.com/questions/30116818/how-to-use-local-storage-form-with-html-and-javascript?noredirect=1#comment48344527_30116818/>
Now I am trying this code and nothing pops up on if else, it just says local storage is
```
function lsTest() {
var test = 'test';
try {
localStorage.setItem(test, test);
localStorage.removeItem(test);
return true;
} catch(e) {
return false;
}
}
var elem = document.getElementById('status');
if (lsTest() === true) {
elem.innerHTML += 'available.';
} else {
elem.innerHTML += 'unavailable.';
}
```
html
```
<div id="status">Local Storage is </div>
```
full code
<http://tny.cz/39896a73> | 2015/05/08 | [
"https://Stackoverflow.com/questions/30123332",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4796973/"
] | You should open your page using a webserver and not your local file system. The browser saves the localstorage data based on the host(domain). This prevents cross site local storage access. | Try this, using a webserver as Nimrodx said.
```js
window.onload = function(){
function lsTest(){
var test = 'test';
try {
localStorage.setItem(test, test);
localStorage.removeItem(test);
return true;
} catch(e) {
console.log(e);
return false;
}
}
var elem = document.getElementById('status');
if(lsTest() === true){
elem.innerHTML += 'available.';
}
else{
elem.innerHTML += 'unavailable.';
}
};
``` |
2,059,606 | I've got a list with list-style-none which needs to be able to add new items to itself via Ajax and have the background expand appropriately when it does. Adding via Ajax is easy, but every solution I try for the background fails me. I don't know if it's even possible; is it? I'm using a grid like this one:
<http://jqueryui.com/demos/sortable/#display-grid>
Both WebKit and Firebug are showing me skinny, empty bars when I hover over the enclosing divs and/or the enclosing ul tag. It appears that the minute you set a list loose with list-style-none and float:wherever, you give up control over its background. But that can't be right. | 2010/01/13 | [
"https://Stackoverflow.com/questions/2059606",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/250151/"
] | This is something I've run into a number of times. The problem is that floated elements aren't part of the normal box model, so they don't cause their parent elements to expand **unless** their parent elements are also floated. So if possible, float the ul or containing div.
Edit:
See [quirksmode](http://www.quirksmode.org/css/clearing.html) for another css-only workaround. | Could you provide a sample of your code? Also, why does the list have display:none set?
For instance, should be as simple as this:
HTML:
```
<ul id="dest"></ul>
```
JS:
```
// Simplified example, most likely wrapped in $.ajax
// This is the AJAX response function
function(data, response) {
var items = json.parse(data);
$.each(items, function() {
// Assumes item has a name property
$('#dest').append($('<li>' + this.name + '</li>'));
});
}
```
Should be just that simple. You shouldn't need the hide the list initially, as you can simply append list items and have the display update appropriately.
Hope that helps. |
2,059,606 | I've got a list with list-style-none which needs to be able to add new items to itself via Ajax and have the background expand appropriately when it does. Adding via Ajax is easy, but every solution I try for the background fails me. I don't know if it's even possible; is it? I'm using a grid like this one:
<http://jqueryui.com/demos/sortable/#display-grid>
Both WebKit and Firebug are showing me skinny, empty bars when I hover over the enclosing divs and/or the enclosing ul tag. It appears that the minute you set a list loose with list-style-none and float:wherever, you give up control over its background. But that can't be right. | 2010/01/13 | [
"https://Stackoverflow.com/questions/2059606",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/250151/"
] | Could you provide a sample of your code? Also, why does the list have display:none set?
For instance, should be as simple as this:
HTML:
```
<ul id="dest"></ul>
```
JS:
```
// Simplified example, most likely wrapped in $.ajax
// This is the AJAX response function
function(data, response) {
var items = json.parse(data);
$.each(items, function() {
// Assumes item has a name property
$('#dest').append($('<li>' + this.name + '</li>'));
});
}
```
Should be just that simple. You shouldn't need the hide the list initially, as you can simply append list items and have the display update appropriately.
Hope that helps. | For dealing with the float element, maybe you should know it's characteristic, gotcha, and how to deal with it.
See the links below, it also have demo, so you can understand the concept:
1. <http://www.smashingmagazine.com/2009/10/19/the-mystery-of-css-float-property/>
2. <http://www.smashingmagazine.com/2007/05/01/css-float-theory-things-you-should-know/>
3. <http://aloestudios.com/2009/12/goodbye-overflow-clearing-hack/>
and
<http://aloestudios.com/misc/overflow/> |
2,059,606 | I've got a list with list-style-none which needs to be able to add new items to itself via Ajax and have the background expand appropriately when it does. Adding via Ajax is easy, but every solution I try for the background fails me. I don't know if it's even possible; is it? I'm using a grid like this one:
<http://jqueryui.com/demos/sortable/#display-grid>
Both WebKit and Firebug are showing me skinny, empty bars when I hover over the enclosing divs and/or the enclosing ul tag. It appears that the minute you set a list loose with list-style-none and float:wherever, you give up control over its background. But that can't be right. | 2010/01/13 | [
"https://Stackoverflow.com/questions/2059606",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/250151/"
] | This is something I've run into a number of times. The problem is that floated elements aren't part of the normal box model, so they don't cause their parent elements to expand **unless** their parent elements are also floated. So if possible, float the ul or containing div.
Edit:
See [quirksmode](http://www.quirksmode.org/css/clearing.html) for another css-only workaround. | You need to explicitly set the width and height for the area.
Check out this link for Horizontal Scrolling: <http://valums.com/scroll-menu-jquery/>
Here is the script:
```
$(function(){
//Get our elements for faster access and set overlay width
var div = $('div.sc_menu'),
ul = $('ul.sc_menu'),
// unordered list's left margin
ulPadding = 15;
//Get menu width
var divWidth = div.width();
//Remove scrollbars
div.css({overflow: 'hidden'});
//Find last image container
var lastLi = ul.find('li:last-child');
//When user move mouse over menu
div.mousemove(function(e){
//As images are loaded ul width increases,
//so we recalculate it each time
var ulWidth = lastLi[0].offsetLeft + lastLi.outerWidth() + ulPadding;
var left = (e.pageX - div.offset().left) * (ulWidth-divWidth) / divWidth;
div.scrollLeft(left);
});
});
```
Basically, you need to update the `ulWidth` and `divWidth` when you add the new item.
Then just set the background image to repeat horizontally and you should be set.
```
ul.sc_menu {background:transparent url(image.png) repeat scroll 0 0;height:100px}
```
**Note: You will need to set the height; otherwise you will not see the background because the li are floated.** |
2,059,606 | I've got a list with list-style-none which needs to be able to add new items to itself via Ajax and have the background expand appropriately when it does. Adding via Ajax is easy, but every solution I try for the background fails me. I don't know if it's even possible; is it? I'm using a grid like this one:
<http://jqueryui.com/demos/sortable/#display-grid>
Both WebKit and Firebug are showing me skinny, empty bars when I hover over the enclosing divs and/or the enclosing ul tag. It appears that the minute you set a list loose with list-style-none and float:wherever, you give up control over its background. But that can't be right. | 2010/01/13 | [
"https://Stackoverflow.com/questions/2059606",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/250151/"
] | This is something I've run into a number of times. The problem is that floated elements aren't part of the normal box model, so they don't cause their parent elements to expand **unless** their parent elements are also floated. So if possible, float the ul or containing div.
Edit:
See [quirksmode](http://www.quirksmode.org/css/clearing.html) for another css-only workaround. | For dealing with the float element, maybe you should know it's characteristic, gotcha, and how to deal with it.
See the links below, it also have demo, so you can understand the concept:
1. <http://www.smashingmagazine.com/2009/10/19/the-mystery-of-css-float-property/>
2. <http://www.smashingmagazine.com/2007/05/01/css-float-theory-things-you-should-know/>
3. <http://aloestudios.com/2009/12/goodbye-overflow-clearing-hack/>
and
<http://aloestudios.com/misc/overflow/> |
2,059,606 | I've got a list with list-style-none which needs to be able to add new items to itself via Ajax and have the background expand appropriately when it does. Adding via Ajax is easy, but every solution I try for the background fails me. I don't know if it's even possible; is it? I'm using a grid like this one:
<http://jqueryui.com/demos/sortable/#display-grid>
Both WebKit and Firebug are showing me skinny, empty bars when I hover over the enclosing divs and/or the enclosing ul tag. It appears that the minute you set a list loose with list-style-none and float:wherever, you give up control over its background. But that can't be right. | 2010/01/13 | [
"https://Stackoverflow.com/questions/2059606",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/250151/"
] | You need to explicitly set the width and height for the area.
Check out this link for Horizontal Scrolling: <http://valums.com/scroll-menu-jquery/>
Here is the script:
```
$(function(){
//Get our elements for faster access and set overlay width
var div = $('div.sc_menu'),
ul = $('ul.sc_menu'),
// unordered list's left margin
ulPadding = 15;
//Get menu width
var divWidth = div.width();
//Remove scrollbars
div.css({overflow: 'hidden'});
//Find last image container
var lastLi = ul.find('li:last-child');
//When user move mouse over menu
div.mousemove(function(e){
//As images are loaded ul width increases,
//so we recalculate it each time
var ulWidth = lastLi[0].offsetLeft + lastLi.outerWidth() + ulPadding;
var left = (e.pageX - div.offset().left) * (ulWidth-divWidth) / divWidth;
div.scrollLeft(left);
});
});
```
Basically, you need to update the `ulWidth` and `divWidth` when you add the new item.
Then just set the background image to repeat horizontally and you should be set.
```
ul.sc_menu {background:transparent url(image.png) repeat scroll 0 0;height:100px}
```
**Note: You will need to set the height; otherwise you will not see the background because the li are floated.** | For dealing with the float element, maybe you should know it's characteristic, gotcha, and how to deal with it.
See the links below, it also have demo, so you can understand the concept:
1. <http://www.smashingmagazine.com/2009/10/19/the-mystery-of-css-float-property/>
2. <http://www.smashingmagazine.com/2007/05/01/css-float-theory-things-you-should-know/>
3. <http://aloestudios.com/2009/12/goodbye-overflow-clearing-hack/>
and
<http://aloestudios.com/misc/overflow/> |
17,011,831 | I am trying to googling for passing in acceptable parameters for setting up cronJobs based on a users timeZone. Im using a cronJob module which can be found here.
<https://github.com/ncb000gt/node-cron>
The problem is I need to pass different timeZones but I can't seem to find the acceptable parameters and format for the different timezones. Can anyone point me in the right direction? | 2013/06/09 | [
"https://Stackoverflow.com/questions/17011831",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1382927/"
] | malloc returns a void\*. You need to cast the returned value.
```
HugeInteger *ptr = (HugeInteger*)malloc(sizeof(HugeInteger) * INIT_MEMO_SIZE);
``` | Your comment says that this code "creates and initializes a Memo struct" however, I see no place where it either creates or initializes a `Memo` `struct`. In fact, the function doesn't even return such a struct (unless memory allocation failed). Perhaps you want something like this:
```
Memo *createMemo(void)
{
Memo *memo = malloc(sizeof(Memo));
if(memo == NULL)
return NULL;
memo->F = malloc(sizeof(struct HugeInteger) * INIT_MEMO_SIZE);
if(memo->F == NULL)
{ // Oops, memory allocation failed.
free(memo);
return NULL;
}
// other initialization here -- perhaps set memo->length
// to some sensible value
memo->length = INIT_MEMO_SIZE;
// and return the new memo
return memo;
} // End of *createMemo
```
Generally speaking, you should not need to typecast the result of a `malloc` operation in C. Indeed, doing so can often cause subtle issues that can be difficult to diagnose. So, frankly, if the **compiler** is complaining, this would suggest that you are compiling as C++.
*However*, you say that not casting results in `malloc` being underlined in red and having some kind of "error" associated with it. This suggests to me what what you are seeing is not a compiler error, but a warning from an overzealous **editor** (via Intellisense, perhaps in combination with the SDL checks that VS2012 implements) that's trying to preemptively warn you about what it perceives to be an issue before you even compile. |
50,861,823 | i have something like this:
```
DELETE FROM `history` WHERE `date_field` <= now() - INTERVAL 10 DAY
```
but if all records is older than 10 days - this query deletes all! i want to keep last 20 records, even if they too old !
Please help, what and how i need to upd my code, and what will be better use limit+offset of windowed function **OVER()** or need smth another ? | 2018/06/14 | [
"https://Stackoverflow.com/questions/50861823",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5809937/"
] | Join with a subquery that gets the most recent 20 days and excludes them.
```
DELETE h1
FROM history AS h1
LEFT JOIN (
SELECT id
FROM history
ORDER BY date_field DESC
LIMIT 20
) AS h2 ON h1.id = h2.id
WHERE date_field < now() - INTERVAL 10 DAY
AND h2.id IS NULL;
``` | How about not using `delete` at all? Write a query to save the records you want. Then truncate the table and insert them back in:
```
create temporary table tokeep as
select h.*
from history h
where `date_field` > now() - INTERVAL 10 DAY
union
select h.*
from history h
order by date_field desc
limit 20;
truncate table history;
insert into history -- the only situation where I don't list the columns
select *
from tokeep;
``` |
13,102 | I am in the process of building a dining table out of solid walnut. I don't have the skills or equipment to make the tabletop myself, so I got my wood supplier to do it for me. The tabletop is 6/4 walnut, 7' long by 40" wide, and is made up of 6 smaller boards glued together. The shop is reputable and seems to know what they are doing. I received it about a month ago, and since then, it's been standing behind my living room couch leaning against the wall (long side on the floor). It was leaning at maybe a 10 degree angle, with the underside of the piece facing away from the wall.
Anyways, now that I've completed the base, I'm paying attention to the tabletop, and I notice that there is some significant cupping. The concave side (the underside) goes in about 3/16" in the middle down from the edges.
Unfortunately, I didn't check for cupping when I initially received the piece, so I'm not sure if it came like this or if I caused it myself somehow. Regardless, the damage is done, so what are my options now?
I've seen some articles/videos where they dampen the concave side of a cupped board and let it sit overnight to straighten it out, but will that work on my 6/4 tabletop? I tried applying this technique yesterday evening, but this morning I don't measure any difference in the amount of cupping.
Any advice would be greatly appreciated.
Note: I don't have a table saw, thickness planer, or jointer. | 2021/09/18 | [
"https://woodworking.stackexchange.com/questions/13102",
"https://woodworking.stackexchange.com",
"https://woodworking.stackexchange.com/users/2909/"
] | >
> Any advice would be greatly appreciated.
>
>
>
3/16” over the length and width of the table isn’t much; if you put the top on the base and leave it unattached, it might flatten out on its own after a week or two. You could encourage it by putting something heavy, like a box of books (or two) in the middle. Whether that helps or not, you can probably also pull it flat with a screw or two through the middle of the base into the bottom of the tabletop. Depending on your design, that might mean that you have to add a piece to the base across the middle. | There are a couple reasons for cupping like this. The first is assembly if you don't pay attention to the glue up job or don't actually make your joints square, you can get this, sometimes with rather exaggerated bends. It doesn't really sound like that is the case here, and I would certainly hope that a professional shop with any reputation wouldn't screw up like that.
The next is some boards have a lot of 'spring' in them and will 'bend' when pressure is released, some times even after cutting and squaring it, I generally see this the length of the board, and I've had Hickory give me some major headaches (but that comes with milling your own logs...) but once again, a professional shop generally uses fairly high quality lumber and it's usually the wood with sap wood and/or flat sawn that does a lot of cupping.
So the other much more likely culprit. Moisture if you had it against the wall near an air vent or under an open window or where it got a lot of sun throughout the day, there is a good chance that one side dried out faster than the other, with 6/4 lumber it's pretty easy to have uneven moisture content to happen.
'Fixing' this might be as simple as Caleb stated, putting it on your base and waiting a little bit for the moisture to restablize, it might take near the same amount of time as it did to cup in the first place. Good luck. |
27,969 | In an "alternate universe" where NASA continued to receive a mandate, funding and public support at say peak Apollo levels, could another ten or twenty years have gotten boots on Mars, with astronauts in those boots?
Or would there be some clear technical challenge that really needed several more decades of development before this would have been possible?
**Ideally:** a bit of math or some supporting links should be presented and not just an opinion or a list.
This question is motivated in part by [this thoughtful answer](https://space.stackexchange.com/a/27968/12102). | 2018/06/20 | [
"https://space.stackexchange.com/questions/27969",
"https://space.stackexchange.com",
"https://space.stackexchange.com/users/12102/"
] | If you want to get really bummed out for 'what could have been', check out the Wikipedia page for [List of manned Mars mission plans](https://en.wikipedia.org/wiki/List_of_manned_Mars_mission_plans).
The earliest plan to get to Mars was [written by von Braun in 1948](http://www.wlym.com/archive/oakland/docs/MarsProject.pdf), with the idea that we would be landing in 1965. With our current knowledge of Mars, it reads like science fiction. Seven passenger ships and three cargo ships would be assembled in Earth orbit using reusable shuttles to launch the materials. They would fly to Mars in the same way we do currently, at the optimal transfer window. They would find a landing site from orbit. A manned glider would be used to make the first landing on Mars, using skis to land on the polar ice cap. The crew would then travel overland using rovers and then build a landing strip.
[](https://i.stack.imgur.com/H5qEQ.png)<http://www.astronautix.com/v/vonbraunmarpedition-1952.html>
Obviously we now know much of this would be impossible. Mars doesn't have the thickness of atmosphere needed to support landing with gliders, and the radiation of interstellar space was completely unknown at the time. Additionally, the technology and engineering which would be needed to develop reusable shuttles were almost 30 years away, and even then NASA was unable to keep reuse tempos anywhere near what would be necessary for an extended space construction project.
Quick budgetary baseline here: Apollo cost about $107 billion in today's dollars. Here are the yearly figures in that-year-dollars from [Wikipedia](https://en.wikipedia.org/wiki/Apollo_program#Costs):
[](https://i.stack.imgur.com/AfYtW.png)
The NASA estimates for the space shuttle (which was being costed and developed around the same time Von Braun and Boeing were putting together) was 43 billion in 2011 dollars. This was based on 50 launches per year, which was very unrealistic (lots more to be said here, effectively NASA planned for the Space Shuttle as being the sole launch vehicle for the entirety of the US including commercial and military launches). The actual final total for the space shuttle was 196 billion, so the estimates were way off.
Back to the plans. Von Braun updated his plan throughout the Apollo program, and at the very end of his career, proposed his [1969 plan](http://www.astronautix.com/v/vonbraunmarpedition-1969.html). This plan was huge, and would likely have required an amount of investment in excess of what Apollo ran (his estimate was a peak of $8 billion per year, which is more than double what Apollo cost at its peak). The first step of the plan was the space shuttle, albeit a far different shuttle than the one you and I know, mainly because it would use a nuclear rocket for propulsion. This would be followed by an earth space station, and finally the creation of the spacecraft which would take us to Mars. The main lifting vehicle from Earth for this would be a future-state Saturn V, the [Saturn V -25U](http://www.aerospaceprojectsreview.com/blog/?p=1359). This rocket would be a longer version of the Saturn V which took us to the moon, with four solid rocket boosters attached to the bottom, and the upper stages replaced by NERVA, a nuclear rocket engine. This rocket was entirely technically possible at the time, and would have required significant but not impossible engineering and integration work.
[](https://i.stack.imgur.com/9qeu8.png) <http://www.astronautix.com/v/vonbraunmarpedition-1969.html>
The two Mars ships would be assembled in Earth orbit, fly to Mars using a standard trajectory, astronauts would descend using a to-be-designed descent module, stay for 90 days, then swing by Venus on their way back to Earth, docking with the space station and then returning in the reusable shuttle.
The big driver for the 1969 plan, as well as for a competing plan from Boeing, was the NERVA rocket. Nuclear Engine for Rocket Vehicle Application (NERVA) was a nuclear-based rocket engine.
[](https://i.stack.imgur.com/KwDyo.jpg) <https://en.wikipedia.org/wiki/NERVA#/media/File:NERVA.jpg>
This rocket engine was (and may still eventually be) the key to interplanetary travel. In a nuclear rocket, you don't need a chemical fuel. Liquid hydrogen is used, and is heated to a very high temperature in a nuclear reactor. As in a conventional rocket engine, the gas then expands and is propelled out the back of the ship. NERVA would have provided basically twice the fuel efficiency of a chemical rocket. I keep saying 'would have', but NERVA was an extensively developed project. Research on nuclear thermal rockets began in 1952, and continued for two decades. Two engines were built and tested. The second, NERVA XE, was basically a complete flight system and tested in a near-vacuum environment. It ran for a total of 115 minutes and was started 28 separate times.
[](https://i.stack.imgur.com/I84aK.jpg)
In my opinion (and the opinion of 1960s engineers far far smarter than I), the answer to whether we could have done it technically is yes. The budget would have needed to exceed that of peak apollo, but that would have included far more than just the Mars mission, but also an earth-orbit space station, a reusable shuttle, and a nuclear rocket engine. Whether those estimates were reasonable, given the massive expansion of the space shuttle compared to initial estimates, is debatable. Whether it would have survived the political pressures not only to cut spending in the 70s and 80s, but also the environmental movement which was (and is) diametrically opposed to nuclear rockets is another. But if we'd been willing to double the investment we were making in Apollo, and public support had existed, I absolutely think we could have gotten not only there but to even more distant parts of our solar system. | I second what Edlothiad suggested, Mars Direct would have been perfectly feasible. Mars Direct was created and proposed mainly by Dr. Robert Zubrin. His approach to a human Mars mission was precisely to find a way to do it using the available technology and not using technologies that are still in development or experimental, such as Nuclear Thermal Rockets, advanced propulsion, on orbit assembly, which would all drive up the costs. His research was initiated due to the 90-day report\* and the very high costs associated with a more extensive and elaborate plan for going to Mars. He also suggested a mission that is as lean as possible, requiring the least amount of mass to be launched to make this possible with the class of launch vehicle technology available.
Some of the key points to his approach:
* Use available Saturn V/Shuttle class launch vehicle
* Launch, transfer, land and verify an unfueled return vehicle prior to crewed transfer
* Create propellant for return voyage on Mars with the Sabatier reaction using small amount of hydrogen and a small nuclear reactor brought from earth(ISRU).
* Transfer crew on direct orbit to Mars, no on orbit rendezvous, use a slower orbit that is safer due to it having a free return in case of emergency
* Land all crew on mars(no astronaut stays on orbit)
* Stay on mars for an extended time (due to conjunction orbit)
Zubrin has been pushing this approach for decades without any real movement from NASA. The main reason for this is that, due to multiple reasons, NASA is no longer driven to a singular goal, such as mars, and has many technology driven goals instead. To do humans to mars with the available budget even in this cost effective way would mean giving up on other programs such as ISS.
Some of the excuses given by opponents for why it would not work (or any other plan using available technology) are:
* We do not know how to deal with radiation, so more radiation research needed
* We want to go to Mars faster, so advanced propulsion needed
* ISRU has never been done so we cannot rely on it, so we need to bring fuel, so we need a huge ship and advanced propulsion
* The mass margins are too slim
Which can all be disproved, and have been, by Zubrin.
You can find multiple publications of this plan and the details such as:
<http://www.marspapers.org/paper/Zubrin_1991.pdf>
\*Report of the 90 Day Study on Human Exploration of the Moon and Mars, 1989 |
27,969 | In an "alternate universe" where NASA continued to receive a mandate, funding and public support at say peak Apollo levels, could another ten or twenty years have gotten boots on Mars, with astronauts in those boots?
Or would there be some clear technical challenge that really needed several more decades of development before this would have been possible?
**Ideally:** a bit of math or some supporting links should be presented and not just an opinion or a list.
This question is motivated in part by [this thoughtful answer](https://space.stackexchange.com/a/27968/12102). | 2018/06/20 | [
"https://space.stackexchange.com/questions/27969",
"https://space.stackexchange.com",
"https://space.stackexchange.com/users/12102/"
] | If you want to get really bummed out for 'what could have been', check out the Wikipedia page for [List of manned Mars mission plans](https://en.wikipedia.org/wiki/List_of_manned_Mars_mission_plans).
The earliest plan to get to Mars was [written by von Braun in 1948](http://www.wlym.com/archive/oakland/docs/MarsProject.pdf), with the idea that we would be landing in 1965. With our current knowledge of Mars, it reads like science fiction. Seven passenger ships and three cargo ships would be assembled in Earth orbit using reusable shuttles to launch the materials. They would fly to Mars in the same way we do currently, at the optimal transfer window. They would find a landing site from orbit. A manned glider would be used to make the first landing on Mars, using skis to land on the polar ice cap. The crew would then travel overland using rovers and then build a landing strip.
[](https://i.stack.imgur.com/H5qEQ.png)<http://www.astronautix.com/v/vonbraunmarpedition-1952.html>
Obviously we now know much of this would be impossible. Mars doesn't have the thickness of atmosphere needed to support landing with gliders, and the radiation of interstellar space was completely unknown at the time. Additionally, the technology and engineering which would be needed to develop reusable shuttles were almost 30 years away, and even then NASA was unable to keep reuse tempos anywhere near what would be necessary for an extended space construction project.
Quick budgetary baseline here: Apollo cost about $107 billion in today's dollars. Here are the yearly figures in that-year-dollars from [Wikipedia](https://en.wikipedia.org/wiki/Apollo_program#Costs):
[](https://i.stack.imgur.com/AfYtW.png)
The NASA estimates for the space shuttle (which was being costed and developed around the same time Von Braun and Boeing were putting together) was 43 billion in 2011 dollars. This was based on 50 launches per year, which was very unrealistic (lots more to be said here, effectively NASA planned for the Space Shuttle as being the sole launch vehicle for the entirety of the US including commercial and military launches). The actual final total for the space shuttle was 196 billion, so the estimates were way off.
Back to the plans. Von Braun updated his plan throughout the Apollo program, and at the very end of his career, proposed his [1969 plan](http://www.astronautix.com/v/vonbraunmarpedition-1969.html). This plan was huge, and would likely have required an amount of investment in excess of what Apollo ran (his estimate was a peak of $8 billion per year, which is more than double what Apollo cost at its peak). The first step of the plan was the space shuttle, albeit a far different shuttle than the one you and I know, mainly because it would use a nuclear rocket for propulsion. This would be followed by an earth space station, and finally the creation of the spacecraft which would take us to Mars. The main lifting vehicle from Earth for this would be a future-state Saturn V, the [Saturn V -25U](http://www.aerospaceprojectsreview.com/blog/?p=1359). This rocket would be a longer version of the Saturn V which took us to the moon, with four solid rocket boosters attached to the bottom, and the upper stages replaced by NERVA, a nuclear rocket engine. This rocket was entirely technically possible at the time, and would have required significant but not impossible engineering and integration work.
[](https://i.stack.imgur.com/9qeu8.png) <http://www.astronautix.com/v/vonbraunmarpedition-1969.html>
The two Mars ships would be assembled in Earth orbit, fly to Mars using a standard trajectory, astronauts would descend using a to-be-designed descent module, stay for 90 days, then swing by Venus on their way back to Earth, docking with the space station and then returning in the reusable shuttle.
The big driver for the 1969 plan, as well as for a competing plan from Boeing, was the NERVA rocket. Nuclear Engine for Rocket Vehicle Application (NERVA) was a nuclear-based rocket engine.
[](https://i.stack.imgur.com/KwDyo.jpg) <https://en.wikipedia.org/wiki/NERVA#/media/File:NERVA.jpg>
This rocket engine was (and may still eventually be) the key to interplanetary travel. In a nuclear rocket, you don't need a chemical fuel. Liquid hydrogen is used, and is heated to a very high temperature in a nuclear reactor. As in a conventional rocket engine, the gas then expands and is propelled out the back of the ship. NERVA would have provided basically twice the fuel efficiency of a chemical rocket. I keep saying 'would have', but NERVA was an extensively developed project. Research on nuclear thermal rockets began in 1952, and continued for two decades. Two engines were built and tested. The second, NERVA XE, was basically a complete flight system and tested in a near-vacuum environment. It ran for a total of 115 minutes and was started 28 separate times.
[](https://i.stack.imgur.com/I84aK.jpg)
In my opinion (and the opinion of 1960s engineers far far smarter than I), the answer to whether we could have done it technically is yes. The budget would have needed to exceed that of peak apollo, but that would have included far more than just the Mars mission, but also an earth-orbit space station, a reusable shuttle, and a nuclear rocket engine. Whether those estimates were reasonable, given the massive expansion of the space shuttle compared to initial estimates, is debatable. Whether it would have survived the political pressures not only to cut spending in the 70s and 80s, but also the environmental movement which was (and is) diametrically opposed to nuclear rockets is another. But if we'd been willing to double the investment we were making in Apollo, and public support had existed, I absolutely think we could have gotten not only there but to even more distant parts of our solar system. | **Probably yes**. To add to the other already excellent answers: There is the very relevant blog [Spaceflight History](https://spaceflighthistory.blogspot.com/) which focusses on "space exploration history told through missions & programs that didn't happen".
It has many [postings regarding Mars](https://spaceflighthistory.blogspot.com/search?q=mars).
Some examples:
* The [NERVA-Electric Piloted Mars Mission](https://spaceflighthistory.blogspot.com/2016/12/nerva-electric-mars-mission-1966.html) from 1966, which was the last great plan by Braun and would put humans on Mars in 23 September 1986. That might be what you are looking for: it's the most realistic plan from 1966, i.e. when Apollo was not yet doomed.
* [After EMPIRE: Using Apollo Technology to Explore Mars and Venus](https://spaceflighthistory.blogspot.com/2015/07/after-empire-using-apollo-technology-to.html) from 1965, which would lead to a manned flyby in 1978. Certainly possible.
* [A New Step in Spaceflight Evolution: To Mars by Flyby-Landing Excursion Mode](https://spaceflighthistory.blogspot.com/2017/09/a-new-step-in-spaceflight-evolution-to.html) from 1966, which describes a manned flyby with an orbiter in 1978. Also quite possible and didn't even need peek Apollo.
* [Humans on Mars in 1995](https://spaceflighthistory.blogspot.com/2015/10/the-martian-adventure-humans-on-mars-in.html) from 1980-1981, which uses the Shuttle and puts humans on Mars in 1995. This is a realistic plan from 1980 with European involvement.
* And if you really want to dream: [Dyna-Soar's Martian Cousin](https://spaceflighthistory.blogspot.com/2015/09/the-martian-adventure-dyna-soars.html) from 1960 which uses a version of X-20 Dyna-Soar to put humans on Mars in 1971. But that's more SF as you need a working X-20 in 1965. |
27,969 | In an "alternate universe" where NASA continued to receive a mandate, funding and public support at say peak Apollo levels, could another ten or twenty years have gotten boots on Mars, with astronauts in those boots?
Or would there be some clear technical challenge that really needed several more decades of development before this would have been possible?
**Ideally:** a bit of math or some supporting links should be presented and not just an opinion or a list.
This question is motivated in part by [this thoughtful answer](https://space.stackexchange.com/a/27968/12102). | 2018/06/20 | [
"https://space.stackexchange.com/questions/27969",
"https://space.stackexchange.com",
"https://space.stackexchange.com/users/12102/"
] | If you want to get really bummed out for 'what could have been', check out the Wikipedia page for [List of manned Mars mission plans](https://en.wikipedia.org/wiki/List_of_manned_Mars_mission_plans).
The earliest plan to get to Mars was [written by von Braun in 1948](http://www.wlym.com/archive/oakland/docs/MarsProject.pdf), with the idea that we would be landing in 1965. With our current knowledge of Mars, it reads like science fiction. Seven passenger ships and three cargo ships would be assembled in Earth orbit using reusable shuttles to launch the materials. They would fly to Mars in the same way we do currently, at the optimal transfer window. They would find a landing site from orbit. A manned glider would be used to make the first landing on Mars, using skis to land on the polar ice cap. The crew would then travel overland using rovers and then build a landing strip.
[](https://i.stack.imgur.com/H5qEQ.png)<http://www.astronautix.com/v/vonbraunmarpedition-1952.html>
Obviously we now know much of this would be impossible. Mars doesn't have the thickness of atmosphere needed to support landing with gliders, and the radiation of interstellar space was completely unknown at the time. Additionally, the technology and engineering which would be needed to develop reusable shuttles were almost 30 years away, and even then NASA was unable to keep reuse tempos anywhere near what would be necessary for an extended space construction project.
Quick budgetary baseline here: Apollo cost about $107 billion in today's dollars. Here are the yearly figures in that-year-dollars from [Wikipedia](https://en.wikipedia.org/wiki/Apollo_program#Costs):
[](https://i.stack.imgur.com/AfYtW.png)
The NASA estimates for the space shuttle (which was being costed and developed around the same time Von Braun and Boeing were putting together) was 43 billion in 2011 dollars. This was based on 50 launches per year, which was very unrealistic (lots more to be said here, effectively NASA planned for the Space Shuttle as being the sole launch vehicle for the entirety of the US including commercial and military launches). The actual final total for the space shuttle was 196 billion, so the estimates were way off.
Back to the plans. Von Braun updated his plan throughout the Apollo program, and at the very end of his career, proposed his [1969 plan](http://www.astronautix.com/v/vonbraunmarpedition-1969.html). This plan was huge, and would likely have required an amount of investment in excess of what Apollo ran (his estimate was a peak of $8 billion per year, which is more than double what Apollo cost at its peak). The first step of the plan was the space shuttle, albeit a far different shuttle than the one you and I know, mainly because it would use a nuclear rocket for propulsion. This would be followed by an earth space station, and finally the creation of the spacecraft which would take us to Mars. The main lifting vehicle from Earth for this would be a future-state Saturn V, the [Saturn V -25U](http://www.aerospaceprojectsreview.com/blog/?p=1359). This rocket would be a longer version of the Saturn V which took us to the moon, with four solid rocket boosters attached to the bottom, and the upper stages replaced by NERVA, a nuclear rocket engine. This rocket was entirely technically possible at the time, and would have required significant but not impossible engineering and integration work.
[](https://i.stack.imgur.com/9qeu8.png) <http://www.astronautix.com/v/vonbraunmarpedition-1969.html>
The two Mars ships would be assembled in Earth orbit, fly to Mars using a standard trajectory, astronauts would descend using a to-be-designed descent module, stay for 90 days, then swing by Venus on their way back to Earth, docking with the space station and then returning in the reusable shuttle.
The big driver for the 1969 plan, as well as for a competing plan from Boeing, was the NERVA rocket. Nuclear Engine for Rocket Vehicle Application (NERVA) was a nuclear-based rocket engine.
[](https://i.stack.imgur.com/KwDyo.jpg) <https://en.wikipedia.org/wiki/NERVA#/media/File:NERVA.jpg>
This rocket engine was (and may still eventually be) the key to interplanetary travel. In a nuclear rocket, you don't need a chemical fuel. Liquid hydrogen is used, and is heated to a very high temperature in a nuclear reactor. As in a conventional rocket engine, the gas then expands and is propelled out the back of the ship. NERVA would have provided basically twice the fuel efficiency of a chemical rocket. I keep saying 'would have', but NERVA was an extensively developed project. Research on nuclear thermal rockets began in 1952, and continued for two decades. Two engines were built and tested. The second, NERVA XE, was basically a complete flight system and tested in a near-vacuum environment. It ran for a total of 115 minutes and was started 28 separate times.
[](https://i.stack.imgur.com/I84aK.jpg)
In my opinion (and the opinion of 1960s engineers far far smarter than I), the answer to whether we could have done it technically is yes. The budget would have needed to exceed that of peak apollo, but that would have included far more than just the Mars mission, but also an earth-orbit space station, a reusable shuttle, and a nuclear rocket engine. Whether those estimates were reasonable, given the massive expansion of the space shuttle compared to initial estimates, is debatable. Whether it would have survived the political pressures not only to cut spending in the 70s and 80s, but also the environmental movement which was (and is) diametrically opposed to nuclear rockets is another. But if we'd been willing to double the investment we were making in Apollo, and public support had existed, I absolutely think we could have gotten not only there but to even more distant parts of our solar system. | There's always the thought that if you put enough money/resources behind a project, you can do anything, and while this is true in many cases, the amount of resources needed without key innovations can be astronomical and ultimately prohibitive. An example I often cite is the Pyramids- they were built without the wheel, but the resources needed to do them without the wheel was an immense human-powered task!
Much in the same way, if we funneled a virtually limitless volume of resources into NASA, we could have any number of major advances using the technology we have available, and the funding to fuel new, incremental breakthroughs. Would these breakthroughs ultimately lead to an easier path to Mars is impossible to speculate, but consider this- if money were no object, a nation could incrementally build an immense space-faring habitat that could, in time, make it's way to Mars. Whether peak Apollo-era funding would have been sufficient to achieve something of that scale is hard to say- but consider this:
One Saturn V Rocket could move 310,000 pounds into orbit at the cost of roughly 190 million dollars. The modern International Space Station weighs 500 tons, or just about 1,000,000 pounds. Supposing the habitat that would travel to mars weighed a conservative double of that, or 2,000,000 pounds (1000 tons), you are looking at no less than 7 successful Saturn V rocket launches, totaling $1.3 Billion in launches alone, not counting the craft, support, development, labor, assembly, and other costs- all in 1970's dollars. At those dollar amounts, you're beginning to look at taking a huge slice out of the United States total budget pie-chart at the time.
So, in summation, while I think will and determination can overcome pretty much any technical hurdle, the economic factors make the possibility of this very, very slim, even with peak Apollo-level funding. |
27,969 | In an "alternate universe" where NASA continued to receive a mandate, funding and public support at say peak Apollo levels, could another ten or twenty years have gotten boots on Mars, with astronauts in those boots?
Or would there be some clear technical challenge that really needed several more decades of development before this would have been possible?
**Ideally:** a bit of math or some supporting links should be presented and not just an opinion or a list.
This question is motivated in part by [this thoughtful answer](https://space.stackexchange.com/a/27968/12102). | 2018/06/20 | [
"https://space.stackexchange.com/questions/27969",
"https://space.stackexchange.com",
"https://space.stackexchange.com/users/12102/"
] | If you want to get really bummed out for 'what could have been', check out the Wikipedia page for [List of manned Mars mission plans](https://en.wikipedia.org/wiki/List_of_manned_Mars_mission_plans).
The earliest plan to get to Mars was [written by von Braun in 1948](http://www.wlym.com/archive/oakland/docs/MarsProject.pdf), with the idea that we would be landing in 1965. With our current knowledge of Mars, it reads like science fiction. Seven passenger ships and three cargo ships would be assembled in Earth orbit using reusable shuttles to launch the materials. They would fly to Mars in the same way we do currently, at the optimal transfer window. They would find a landing site from orbit. A manned glider would be used to make the first landing on Mars, using skis to land on the polar ice cap. The crew would then travel overland using rovers and then build a landing strip.
[](https://i.stack.imgur.com/H5qEQ.png)<http://www.astronautix.com/v/vonbraunmarpedition-1952.html>
Obviously we now know much of this would be impossible. Mars doesn't have the thickness of atmosphere needed to support landing with gliders, and the radiation of interstellar space was completely unknown at the time. Additionally, the technology and engineering which would be needed to develop reusable shuttles were almost 30 years away, and even then NASA was unable to keep reuse tempos anywhere near what would be necessary for an extended space construction project.
Quick budgetary baseline here: Apollo cost about $107 billion in today's dollars. Here are the yearly figures in that-year-dollars from [Wikipedia](https://en.wikipedia.org/wiki/Apollo_program#Costs):
[](https://i.stack.imgur.com/AfYtW.png)
The NASA estimates for the space shuttle (which was being costed and developed around the same time Von Braun and Boeing were putting together) was 43 billion in 2011 dollars. This was based on 50 launches per year, which was very unrealistic (lots more to be said here, effectively NASA planned for the Space Shuttle as being the sole launch vehicle for the entirety of the US including commercial and military launches). The actual final total for the space shuttle was 196 billion, so the estimates were way off.
Back to the plans. Von Braun updated his plan throughout the Apollo program, and at the very end of his career, proposed his [1969 plan](http://www.astronautix.com/v/vonbraunmarpedition-1969.html). This plan was huge, and would likely have required an amount of investment in excess of what Apollo ran (his estimate was a peak of $8 billion per year, which is more than double what Apollo cost at its peak). The first step of the plan was the space shuttle, albeit a far different shuttle than the one you and I know, mainly because it would use a nuclear rocket for propulsion. This would be followed by an earth space station, and finally the creation of the spacecraft which would take us to Mars. The main lifting vehicle from Earth for this would be a future-state Saturn V, the [Saturn V -25U](http://www.aerospaceprojectsreview.com/blog/?p=1359). This rocket would be a longer version of the Saturn V which took us to the moon, with four solid rocket boosters attached to the bottom, and the upper stages replaced by NERVA, a nuclear rocket engine. This rocket was entirely technically possible at the time, and would have required significant but not impossible engineering and integration work.
[](https://i.stack.imgur.com/9qeu8.png) <http://www.astronautix.com/v/vonbraunmarpedition-1969.html>
The two Mars ships would be assembled in Earth orbit, fly to Mars using a standard trajectory, astronauts would descend using a to-be-designed descent module, stay for 90 days, then swing by Venus on their way back to Earth, docking with the space station and then returning in the reusable shuttle.
The big driver for the 1969 plan, as well as for a competing plan from Boeing, was the NERVA rocket. Nuclear Engine for Rocket Vehicle Application (NERVA) was a nuclear-based rocket engine.
[](https://i.stack.imgur.com/KwDyo.jpg) <https://en.wikipedia.org/wiki/NERVA#/media/File:NERVA.jpg>
This rocket engine was (and may still eventually be) the key to interplanetary travel. In a nuclear rocket, you don't need a chemical fuel. Liquid hydrogen is used, and is heated to a very high temperature in a nuclear reactor. As in a conventional rocket engine, the gas then expands and is propelled out the back of the ship. NERVA would have provided basically twice the fuel efficiency of a chemical rocket. I keep saying 'would have', but NERVA was an extensively developed project. Research on nuclear thermal rockets began in 1952, and continued for two decades. Two engines were built and tested. The second, NERVA XE, was basically a complete flight system and tested in a near-vacuum environment. It ran for a total of 115 minutes and was started 28 separate times.
[](https://i.stack.imgur.com/I84aK.jpg)
In my opinion (and the opinion of 1960s engineers far far smarter than I), the answer to whether we could have done it technically is yes. The budget would have needed to exceed that of peak apollo, but that would have included far more than just the Mars mission, but also an earth-orbit space station, a reusable shuttle, and a nuclear rocket engine. Whether those estimates were reasonable, given the massive expansion of the space shuttle compared to initial estimates, is debatable. Whether it would have survived the political pressures not only to cut spending in the 70s and 80s, but also the environmental movement which was (and is) diametrically opposed to nuclear rockets is another. But if we'd been willing to double the investment we were making in Apollo, and public support had existed, I absolutely think we could have gotten not only there but to even more distant parts of our solar system. | It seems strange to me that no one has mentioned Project Orion (1958-1965), a theoretical study of using atomic bombs to launch rockets and propel them in interplanetary space.
That would have been many times more efficient than chemical rockets and the members of project Orion hoped that it would enable manned lunar and interplanetary missions in the the 1960s and 1970s.
In regard specifically to Mars, in 2003 the BBC aired a documentary about Project Orion titled *To Mars by A Bomb: The Secret History of Project Orion*.
It seems quite possible that if Project Orion had been supported there could have been manned missions to Mars and other planets in the 1970s. |
27,969 | In an "alternate universe" where NASA continued to receive a mandate, funding and public support at say peak Apollo levels, could another ten or twenty years have gotten boots on Mars, with astronauts in those boots?
Or would there be some clear technical challenge that really needed several more decades of development before this would have been possible?
**Ideally:** a bit of math or some supporting links should be presented and not just an opinion or a list.
This question is motivated in part by [this thoughtful answer](https://space.stackexchange.com/a/27968/12102). | 2018/06/20 | [
"https://space.stackexchange.com/questions/27969",
"https://space.stackexchange.com",
"https://space.stackexchange.com/users/12102/"
] | I second what Edlothiad suggested, Mars Direct would have been perfectly feasible. Mars Direct was created and proposed mainly by Dr. Robert Zubrin. His approach to a human Mars mission was precisely to find a way to do it using the available technology and not using technologies that are still in development or experimental, such as Nuclear Thermal Rockets, advanced propulsion, on orbit assembly, which would all drive up the costs. His research was initiated due to the 90-day report\* and the very high costs associated with a more extensive and elaborate plan for going to Mars. He also suggested a mission that is as lean as possible, requiring the least amount of mass to be launched to make this possible with the class of launch vehicle technology available.
Some of the key points to his approach:
* Use available Saturn V/Shuttle class launch vehicle
* Launch, transfer, land and verify an unfueled return vehicle prior to crewed transfer
* Create propellant for return voyage on Mars with the Sabatier reaction using small amount of hydrogen and a small nuclear reactor brought from earth(ISRU).
* Transfer crew on direct orbit to Mars, no on orbit rendezvous, use a slower orbit that is safer due to it having a free return in case of emergency
* Land all crew on mars(no astronaut stays on orbit)
* Stay on mars for an extended time (due to conjunction orbit)
Zubrin has been pushing this approach for decades without any real movement from NASA. The main reason for this is that, due to multiple reasons, NASA is no longer driven to a singular goal, such as mars, and has many technology driven goals instead. To do humans to mars with the available budget even in this cost effective way would mean giving up on other programs such as ISS.
Some of the excuses given by opponents for why it would not work (or any other plan using available technology) are:
* We do not know how to deal with radiation, so more radiation research needed
* We want to go to Mars faster, so advanced propulsion needed
* ISRU has never been done so we cannot rely on it, so we need to bring fuel, so we need a huge ship and advanced propulsion
* The mass margins are too slim
Which can all be disproved, and have been, by Zubrin.
You can find multiple publications of this plan and the details such as:
<http://www.marspapers.org/paper/Zubrin_1991.pdf>
\*Report of the 90 Day Study on Human Exploration of the Moon and Mars, 1989 | There's always the thought that if you put enough money/resources behind a project, you can do anything, and while this is true in many cases, the amount of resources needed without key innovations can be astronomical and ultimately prohibitive. An example I often cite is the Pyramids- they were built without the wheel, but the resources needed to do them without the wheel was an immense human-powered task!
Much in the same way, if we funneled a virtually limitless volume of resources into NASA, we could have any number of major advances using the technology we have available, and the funding to fuel new, incremental breakthroughs. Would these breakthroughs ultimately lead to an easier path to Mars is impossible to speculate, but consider this- if money were no object, a nation could incrementally build an immense space-faring habitat that could, in time, make it's way to Mars. Whether peak Apollo-era funding would have been sufficient to achieve something of that scale is hard to say- but consider this:
One Saturn V Rocket could move 310,000 pounds into orbit at the cost of roughly 190 million dollars. The modern International Space Station weighs 500 tons, or just about 1,000,000 pounds. Supposing the habitat that would travel to mars weighed a conservative double of that, or 2,000,000 pounds (1000 tons), you are looking at no less than 7 successful Saturn V rocket launches, totaling $1.3 Billion in launches alone, not counting the craft, support, development, labor, assembly, and other costs- all in 1970's dollars. At those dollar amounts, you're beginning to look at taking a huge slice out of the United States total budget pie-chart at the time.
So, in summation, while I think will and determination can overcome pretty much any technical hurdle, the economic factors make the possibility of this very, very slim, even with peak Apollo-level funding. |
27,969 | In an "alternate universe" where NASA continued to receive a mandate, funding and public support at say peak Apollo levels, could another ten or twenty years have gotten boots on Mars, with astronauts in those boots?
Or would there be some clear technical challenge that really needed several more decades of development before this would have been possible?
**Ideally:** a bit of math or some supporting links should be presented and not just an opinion or a list.
This question is motivated in part by [this thoughtful answer](https://space.stackexchange.com/a/27968/12102). | 2018/06/20 | [
"https://space.stackexchange.com/questions/27969",
"https://space.stackexchange.com",
"https://space.stackexchange.com/users/12102/"
] | I second what Edlothiad suggested, Mars Direct would have been perfectly feasible. Mars Direct was created and proposed mainly by Dr. Robert Zubrin. His approach to a human Mars mission was precisely to find a way to do it using the available technology and not using technologies that are still in development or experimental, such as Nuclear Thermal Rockets, advanced propulsion, on orbit assembly, which would all drive up the costs. His research was initiated due to the 90-day report\* and the very high costs associated with a more extensive and elaborate plan for going to Mars. He also suggested a mission that is as lean as possible, requiring the least amount of mass to be launched to make this possible with the class of launch vehicle technology available.
Some of the key points to his approach:
* Use available Saturn V/Shuttle class launch vehicle
* Launch, transfer, land and verify an unfueled return vehicle prior to crewed transfer
* Create propellant for return voyage on Mars with the Sabatier reaction using small amount of hydrogen and a small nuclear reactor brought from earth(ISRU).
* Transfer crew on direct orbit to Mars, no on orbit rendezvous, use a slower orbit that is safer due to it having a free return in case of emergency
* Land all crew on mars(no astronaut stays on orbit)
* Stay on mars for an extended time (due to conjunction orbit)
Zubrin has been pushing this approach for decades without any real movement from NASA. The main reason for this is that, due to multiple reasons, NASA is no longer driven to a singular goal, such as mars, and has many technology driven goals instead. To do humans to mars with the available budget even in this cost effective way would mean giving up on other programs such as ISS.
Some of the excuses given by opponents for why it would not work (or any other plan using available technology) are:
* We do not know how to deal with radiation, so more radiation research needed
* We want to go to Mars faster, so advanced propulsion needed
* ISRU has never been done so we cannot rely on it, so we need to bring fuel, so we need a huge ship and advanced propulsion
* The mass margins are too slim
Which can all be disproved, and have been, by Zubrin.
You can find multiple publications of this plan and the details such as:
<http://www.marspapers.org/paper/Zubrin_1991.pdf>
\*Report of the 90 Day Study on Human Exploration of the Moon and Mars, 1989 | It seems strange to me that no one has mentioned Project Orion (1958-1965), a theoretical study of using atomic bombs to launch rockets and propel them in interplanetary space.
That would have been many times more efficient than chemical rockets and the members of project Orion hoped that it would enable manned lunar and interplanetary missions in the the 1960s and 1970s.
In regard specifically to Mars, in 2003 the BBC aired a documentary about Project Orion titled *To Mars by A Bomb: The Secret History of Project Orion*.
It seems quite possible that if Project Orion had been supported there could have been manned missions to Mars and other planets in the 1970s. |
27,969 | In an "alternate universe" where NASA continued to receive a mandate, funding and public support at say peak Apollo levels, could another ten or twenty years have gotten boots on Mars, with astronauts in those boots?
Or would there be some clear technical challenge that really needed several more decades of development before this would have been possible?
**Ideally:** a bit of math or some supporting links should be presented and not just an opinion or a list.
This question is motivated in part by [this thoughtful answer](https://space.stackexchange.com/a/27968/12102). | 2018/06/20 | [
"https://space.stackexchange.com/questions/27969",
"https://space.stackexchange.com",
"https://space.stackexchange.com/users/12102/"
] | **Probably yes**. To add to the other already excellent answers: There is the very relevant blog [Spaceflight History](https://spaceflighthistory.blogspot.com/) which focusses on "space exploration history told through missions & programs that didn't happen".
It has many [postings regarding Mars](https://spaceflighthistory.blogspot.com/search?q=mars).
Some examples:
* The [NERVA-Electric Piloted Mars Mission](https://spaceflighthistory.blogspot.com/2016/12/nerva-electric-mars-mission-1966.html) from 1966, which was the last great plan by Braun and would put humans on Mars in 23 September 1986. That might be what you are looking for: it's the most realistic plan from 1966, i.e. when Apollo was not yet doomed.
* [After EMPIRE: Using Apollo Technology to Explore Mars and Venus](https://spaceflighthistory.blogspot.com/2015/07/after-empire-using-apollo-technology-to.html) from 1965, which would lead to a manned flyby in 1978. Certainly possible.
* [A New Step in Spaceflight Evolution: To Mars by Flyby-Landing Excursion Mode](https://spaceflighthistory.blogspot.com/2017/09/a-new-step-in-spaceflight-evolution-to.html) from 1966, which describes a manned flyby with an orbiter in 1978. Also quite possible and didn't even need peek Apollo.
* [Humans on Mars in 1995](https://spaceflighthistory.blogspot.com/2015/10/the-martian-adventure-humans-on-mars-in.html) from 1980-1981, which uses the Shuttle and puts humans on Mars in 1995. This is a realistic plan from 1980 with European involvement.
* And if you really want to dream: [Dyna-Soar's Martian Cousin](https://spaceflighthistory.blogspot.com/2015/09/the-martian-adventure-dyna-soars.html) from 1960 which uses a version of X-20 Dyna-Soar to put humans on Mars in 1971. But that's more SF as you need a working X-20 in 1965. | There's always the thought that if you put enough money/resources behind a project, you can do anything, and while this is true in many cases, the amount of resources needed without key innovations can be astronomical and ultimately prohibitive. An example I often cite is the Pyramids- they were built without the wheel, but the resources needed to do them without the wheel was an immense human-powered task!
Much in the same way, if we funneled a virtually limitless volume of resources into NASA, we could have any number of major advances using the technology we have available, and the funding to fuel new, incremental breakthroughs. Would these breakthroughs ultimately lead to an easier path to Mars is impossible to speculate, but consider this- if money were no object, a nation could incrementally build an immense space-faring habitat that could, in time, make it's way to Mars. Whether peak Apollo-era funding would have been sufficient to achieve something of that scale is hard to say- but consider this:
One Saturn V Rocket could move 310,000 pounds into orbit at the cost of roughly 190 million dollars. The modern International Space Station weighs 500 tons, or just about 1,000,000 pounds. Supposing the habitat that would travel to mars weighed a conservative double of that, or 2,000,000 pounds (1000 tons), you are looking at no less than 7 successful Saturn V rocket launches, totaling $1.3 Billion in launches alone, not counting the craft, support, development, labor, assembly, and other costs- all in 1970's dollars. At those dollar amounts, you're beginning to look at taking a huge slice out of the United States total budget pie-chart at the time.
So, in summation, while I think will and determination can overcome pretty much any technical hurdle, the economic factors make the possibility of this very, very slim, even with peak Apollo-level funding. |
27,969 | In an "alternate universe" where NASA continued to receive a mandate, funding and public support at say peak Apollo levels, could another ten or twenty years have gotten boots on Mars, with astronauts in those boots?
Or would there be some clear technical challenge that really needed several more decades of development before this would have been possible?
**Ideally:** a bit of math or some supporting links should be presented and not just an opinion or a list.
This question is motivated in part by [this thoughtful answer](https://space.stackexchange.com/a/27968/12102). | 2018/06/20 | [
"https://space.stackexchange.com/questions/27969",
"https://space.stackexchange.com",
"https://space.stackexchange.com/users/12102/"
] | **Probably yes**. To add to the other already excellent answers: There is the very relevant blog [Spaceflight History](https://spaceflighthistory.blogspot.com/) which focusses on "space exploration history told through missions & programs that didn't happen".
It has many [postings regarding Mars](https://spaceflighthistory.blogspot.com/search?q=mars).
Some examples:
* The [NERVA-Electric Piloted Mars Mission](https://spaceflighthistory.blogspot.com/2016/12/nerva-electric-mars-mission-1966.html) from 1966, which was the last great plan by Braun and would put humans on Mars in 23 September 1986. That might be what you are looking for: it's the most realistic plan from 1966, i.e. when Apollo was not yet doomed.
* [After EMPIRE: Using Apollo Technology to Explore Mars and Venus](https://spaceflighthistory.blogspot.com/2015/07/after-empire-using-apollo-technology-to.html) from 1965, which would lead to a manned flyby in 1978. Certainly possible.
* [A New Step in Spaceflight Evolution: To Mars by Flyby-Landing Excursion Mode](https://spaceflighthistory.blogspot.com/2017/09/a-new-step-in-spaceflight-evolution-to.html) from 1966, which describes a manned flyby with an orbiter in 1978. Also quite possible and didn't even need peek Apollo.
* [Humans on Mars in 1995](https://spaceflighthistory.blogspot.com/2015/10/the-martian-adventure-humans-on-mars-in.html) from 1980-1981, which uses the Shuttle and puts humans on Mars in 1995. This is a realistic plan from 1980 with European involvement.
* And if you really want to dream: [Dyna-Soar's Martian Cousin](https://spaceflighthistory.blogspot.com/2015/09/the-martian-adventure-dyna-soars.html) from 1960 which uses a version of X-20 Dyna-Soar to put humans on Mars in 1971. But that's more SF as you need a working X-20 in 1965. | It seems strange to me that no one has mentioned Project Orion (1958-1965), a theoretical study of using atomic bombs to launch rockets and propel them in interplanetary space.
That would have been many times more efficient than chemical rockets and the members of project Orion hoped that it would enable manned lunar and interplanetary missions in the the 1960s and 1970s.
In regard specifically to Mars, in 2003 the BBC aired a documentary about Project Orion titled *To Mars by A Bomb: The Secret History of Project Orion*.
It seems quite possible that if Project Orion had been supported there could have been manned missions to Mars and other planets in the 1970s. |
27,969 | In an "alternate universe" where NASA continued to receive a mandate, funding and public support at say peak Apollo levels, could another ten or twenty years have gotten boots on Mars, with astronauts in those boots?
Or would there be some clear technical challenge that really needed several more decades of development before this would have been possible?
**Ideally:** a bit of math or some supporting links should be presented and not just an opinion or a list.
This question is motivated in part by [this thoughtful answer](https://space.stackexchange.com/a/27968/12102). | 2018/06/20 | [
"https://space.stackexchange.com/questions/27969",
"https://space.stackexchange.com",
"https://space.stackexchange.com/users/12102/"
] | It seems strange to me that no one has mentioned Project Orion (1958-1965), a theoretical study of using atomic bombs to launch rockets and propel them in interplanetary space.
That would have been many times more efficient than chemical rockets and the members of project Orion hoped that it would enable manned lunar and interplanetary missions in the the 1960s and 1970s.
In regard specifically to Mars, in 2003 the BBC aired a documentary about Project Orion titled *To Mars by A Bomb: The Secret History of Project Orion*.
It seems quite possible that if Project Orion had been supported there could have been manned missions to Mars and other planets in the 1970s. | There's always the thought that if you put enough money/resources behind a project, you can do anything, and while this is true in many cases, the amount of resources needed without key innovations can be astronomical and ultimately prohibitive. An example I often cite is the Pyramids- they were built without the wheel, but the resources needed to do them without the wheel was an immense human-powered task!
Much in the same way, if we funneled a virtually limitless volume of resources into NASA, we could have any number of major advances using the technology we have available, and the funding to fuel new, incremental breakthroughs. Would these breakthroughs ultimately lead to an easier path to Mars is impossible to speculate, but consider this- if money were no object, a nation could incrementally build an immense space-faring habitat that could, in time, make it's way to Mars. Whether peak Apollo-era funding would have been sufficient to achieve something of that scale is hard to say- but consider this:
One Saturn V Rocket could move 310,000 pounds into orbit at the cost of roughly 190 million dollars. The modern International Space Station weighs 500 tons, or just about 1,000,000 pounds. Supposing the habitat that would travel to mars weighed a conservative double of that, or 2,000,000 pounds (1000 tons), you are looking at no less than 7 successful Saturn V rocket launches, totaling $1.3 Billion in launches alone, not counting the craft, support, development, labor, assembly, and other costs- all in 1970's dollars. At those dollar amounts, you're beginning to look at taking a huge slice out of the United States total budget pie-chart at the time.
So, in summation, while I think will and determination can overcome pretty much any technical hurdle, the economic factors make the possibility of this very, very slim, even with peak Apollo-level funding. |
20,873,246 | I've spent far too long messing with this before asking for help. I can't seem to get RSpec and Sorcery to play together nicely. I've read through the docs on [Integration testing with Sorcery](https://github.com/NoamB/sorcery/wiki/Integration-Testing-with-Rspec,-Capybara-and-Fabricator) and can post the login action properly, but my tests still doesn't think the user is logged in.
```
# spec/controllers/user_controller_spec
describe 'user access' do
let (:user) { create(:user) }
before :each do
login_user(user[:email], user[:password])
end
it "should log in the user" do
controller.should be_logged_in
end
end
```
And my login\_user method
```
# spec/support/sorcery_login
module Sorcery
module TestHelpers
module Rails
def login_user email, password
page.driver.post(sessions_path, { email: email , password: password, remember_me: false })
end
end
end
end
```
The sessions controller handles the pages properly when I use them on the generated pages just fine. I tried outputting the results of the login\_user method and it appears to properly post the data. How do I persist this logged in user through the tests? Does a before :each block not work for this? I'm just not sure where it could be running wrong and I'm pretty new to testing/RSpec so I may be missing something obvious. I'd appreciate any help.
Here's the output of the failed tests:
```
1) UsersController user access should log in the user
Failure/Error: controller.should be_logged_in
expected logged_in? to return true, got false
``` | 2014/01/01 | [
"https://Stackoverflow.com/questions/20873246",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1467579/"
] | I just went through this yesterday. Here's what I did, if it helps.
Sorcery provides a test helper `login_user` that relies on a `@controller` object being available. This works great in controller specs, but doesn't work in integration tests. So the workaround in integration tests is to write another method (like the one you have above) to simulate actually logging in via an HTTP request (essentially simulating submitting a form).
So my first thought is that you should try renaming your method to `login_user_post` or something else that doesn't collide with the built-in test helper.
Another potential gotcha is that it looks to me like the Sorcery helper assumes that your user's password is 'secret'.
Here's a link to the built-in helper so you can see what I'm talking about:
<https://github.com/NoamB/sorcery/blob/master/lib/sorcery/test_helpers/rails.rb>
Good luck - I really like this gem except for this part. It is really only fully explained by patching together SO posts. Here's the code I use:
**Integration Helper**
```
module Sorcery
module TestHelpers
module Rails
def login_user_post(user, password)
page.driver.post(sessions_url, { username: user, password: password})
end
def logout_user_get
page.driver.get(logout_url)
end
end
end
end
```
**Integration Spec** (where user needs to be logged in to do stuff)
```
before(:each) do
@user = create(:user)
login_user_post(@user.username, 'secret')
end
```
**Controller Spec** (where the regular `login_user` helper works fine)
```
before(:each) do
@user = create(:user)
login_user
end
```
Note that login\_user doesn't need any arguments if you have an `@user` object with the password 'secret'. | The way you pass a password is probably wrong. It may be encrypted at this point. In provided example I will try to do this at first:
```
describe 'user access' do
let (:user) { create(:user, password: 'secret') }
before :each do
login_user(user[:email], 'secret')
end
it "should log in the user" do
controller.should be_logged_in
end
end
``` |
20,873,246 | I've spent far too long messing with this before asking for help. I can't seem to get RSpec and Sorcery to play together nicely. I've read through the docs on [Integration testing with Sorcery](https://github.com/NoamB/sorcery/wiki/Integration-Testing-with-Rspec,-Capybara-and-Fabricator) and can post the login action properly, but my tests still doesn't think the user is logged in.
```
# spec/controllers/user_controller_spec
describe 'user access' do
let (:user) { create(:user) }
before :each do
login_user(user[:email], user[:password])
end
it "should log in the user" do
controller.should be_logged_in
end
end
```
And my login\_user method
```
# spec/support/sorcery_login
module Sorcery
module TestHelpers
module Rails
def login_user email, password
page.driver.post(sessions_path, { email: email , password: password, remember_me: false })
end
end
end
end
```
The sessions controller handles the pages properly when I use them on the generated pages just fine. I tried outputting the results of the login\_user method and it appears to properly post the data. How do I persist this logged in user through the tests? Does a before :each block not work for this? I'm just not sure where it could be running wrong and I'm pretty new to testing/RSpec so I may be missing something obvious. I'd appreciate any help.
Here's the output of the failed tests:
```
1) UsersController user access should log in the user
Failure/Error: controller.should be_logged_in
expected logged_in? to return true, got false
``` | 2014/01/01 | [
"https://Stackoverflow.com/questions/20873246",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1467579/"
] | I just went through this yesterday. Here's what I did, if it helps.
Sorcery provides a test helper `login_user` that relies on a `@controller` object being available. This works great in controller specs, but doesn't work in integration tests. So the workaround in integration tests is to write another method (like the one you have above) to simulate actually logging in via an HTTP request (essentially simulating submitting a form).
So my first thought is that you should try renaming your method to `login_user_post` or something else that doesn't collide with the built-in test helper.
Another potential gotcha is that it looks to me like the Sorcery helper assumes that your user's password is 'secret'.
Here's a link to the built-in helper so you can see what I'm talking about:
<https://github.com/NoamB/sorcery/blob/master/lib/sorcery/test_helpers/rails.rb>
Good luck - I really like this gem except for this part. It is really only fully explained by patching together SO posts. Here's the code I use:
**Integration Helper**
```
module Sorcery
module TestHelpers
module Rails
def login_user_post(user, password)
page.driver.post(sessions_url, { username: user, password: password})
end
def logout_user_get
page.driver.get(logout_url)
end
end
end
end
```
**Integration Spec** (where user needs to be logged in to do stuff)
```
before(:each) do
@user = create(:user)
login_user_post(@user.username, 'secret')
end
```
**Controller Spec** (where the regular `login_user` helper works fine)
```
before(:each) do
@user = create(:user)
login_user
end
```
Note that login\_user doesn't need any arguments if you have an `@user` object with the password 'secret'. | Did you try adding to spec/spec\_helpers.
```
RSpec.configure do |config|
# ...
config.include Sorcery::TestHelpers::Rails::Controller
end
```
Nota that you need to include `Sorcery::TestHelpers::Rails::Controller`, not just `Sorcery::TestHelpers::Rails`.
Then you will be able to `login_user` from any controller specs like:
```
describe CategoriesController do
before do
@user = FactoryGirl::create(:user)
end
describe "GET 'index'" do
it "returns http success" do
login_user
get 'index'
expect(response).to be_success
end
end
end
``` |
20,873,246 | I've spent far too long messing with this before asking for help. I can't seem to get RSpec and Sorcery to play together nicely. I've read through the docs on [Integration testing with Sorcery](https://github.com/NoamB/sorcery/wiki/Integration-Testing-with-Rspec,-Capybara-and-Fabricator) and can post the login action properly, but my tests still doesn't think the user is logged in.
```
# spec/controllers/user_controller_spec
describe 'user access' do
let (:user) { create(:user) }
before :each do
login_user(user[:email], user[:password])
end
it "should log in the user" do
controller.should be_logged_in
end
end
```
And my login\_user method
```
# spec/support/sorcery_login
module Sorcery
module TestHelpers
module Rails
def login_user email, password
page.driver.post(sessions_path, { email: email , password: password, remember_me: false })
end
end
end
end
```
The sessions controller handles the pages properly when I use them on the generated pages just fine. I tried outputting the results of the login\_user method and it appears to properly post the data. How do I persist this logged in user through the tests? Does a before :each block not work for this? I'm just not sure where it could be running wrong and I'm pretty new to testing/RSpec so I may be missing something obvious. I'd appreciate any help.
Here's the output of the failed tests:
```
1) UsersController user access should log in the user
Failure/Error: controller.should be_logged_in
expected logged_in? to return true, got false
``` | 2014/01/01 | [
"https://Stackoverflow.com/questions/20873246",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1467579/"
] | I just went through this yesterday. Here's what I did, if it helps.
Sorcery provides a test helper `login_user` that relies on a `@controller` object being available. This works great in controller specs, but doesn't work in integration tests. So the workaround in integration tests is to write another method (like the one you have above) to simulate actually logging in via an HTTP request (essentially simulating submitting a form).
So my first thought is that you should try renaming your method to `login_user_post` or something else that doesn't collide with the built-in test helper.
Another potential gotcha is that it looks to me like the Sorcery helper assumes that your user's password is 'secret'.
Here's a link to the built-in helper so you can see what I'm talking about:
<https://github.com/NoamB/sorcery/blob/master/lib/sorcery/test_helpers/rails.rb>
Good luck - I really like this gem except for this part. It is really only fully explained by patching together SO posts. Here's the code I use:
**Integration Helper**
```
module Sorcery
module TestHelpers
module Rails
def login_user_post(user, password)
page.driver.post(sessions_url, { username: user, password: password})
end
def logout_user_get
page.driver.get(logout_url)
end
end
end
end
```
**Integration Spec** (where user needs to be logged in to do stuff)
```
before(:each) do
@user = create(:user)
login_user_post(@user.username, 'secret')
end
```
**Controller Spec** (where the regular `login_user` helper works fine)
```
before(:each) do
@user = create(:user)
login_user
end
```
Note that login\_user doesn't need any arguments if you have an `@user` object with the password 'secret'. | This seems to be very poorly documented. The above solutions did not work for me. Here's how I got it to work:
Check your `sessions_url`. Make sure it is correct. Also, check what params are necessary to log in. It may be `email`, `username`, etc.
```
module Sorcery
module TestHelpers
module Rails
def login_user_post(email, password)
page.driver.post(sessions_url, { email:email, password: password })
end
end
end
end
```
RSpec config:
```
config.include Sorcery::TestHelpers::Rails
```
Spec helper:
```
def app
Capybara.app
end
```
spec/controllers/protected\_resource\_spec.rb:
```
describe UsersController do
before do
# Create user
# Login
response = login_user_post( user.email, :admin_password )
expect( response.headers[ 'location' ]).to eq 'http://test.host/'
# I test for login success here. Failure redirects to /sign_in.
@cookie = response.headers[ 'Set-Cookie' ]
end
specify 'Gets protected resource' do
get protected_resource, {}, { cookie:@cookie }
expect( last_response.status ).to eq 200
end
``` |
20,873,246 | I've spent far too long messing with this before asking for help. I can't seem to get RSpec and Sorcery to play together nicely. I've read through the docs on [Integration testing with Sorcery](https://github.com/NoamB/sorcery/wiki/Integration-Testing-with-Rspec,-Capybara-and-Fabricator) and can post the login action properly, but my tests still doesn't think the user is logged in.
```
# spec/controllers/user_controller_spec
describe 'user access' do
let (:user) { create(:user) }
before :each do
login_user(user[:email], user[:password])
end
it "should log in the user" do
controller.should be_logged_in
end
end
```
And my login\_user method
```
# spec/support/sorcery_login
module Sorcery
module TestHelpers
module Rails
def login_user email, password
page.driver.post(sessions_path, { email: email , password: password, remember_me: false })
end
end
end
end
```
The sessions controller handles the pages properly when I use them on the generated pages just fine. I tried outputting the results of the login\_user method and it appears to properly post the data. How do I persist this logged in user through the tests? Does a before :each block not work for this? I'm just not sure where it could be running wrong and I'm pretty new to testing/RSpec so I may be missing something obvious. I'd appreciate any help.
Here's the output of the failed tests:
```
1) UsersController user access should log in the user
Failure/Error: controller.should be_logged_in
expected logged_in? to return true, got false
``` | 2014/01/01 | [
"https://Stackoverflow.com/questions/20873246",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1467579/"
] | Did you try adding to spec/spec\_helpers.
```
RSpec.configure do |config|
# ...
config.include Sorcery::TestHelpers::Rails::Controller
end
```
Nota that you need to include `Sorcery::TestHelpers::Rails::Controller`, not just `Sorcery::TestHelpers::Rails`.
Then you will be able to `login_user` from any controller specs like:
```
describe CategoriesController do
before do
@user = FactoryGirl::create(:user)
end
describe "GET 'index'" do
it "returns http success" do
login_user
get 'index'
expect(response).to be_success
end
end
end
``` | The way you pass a password is probably wrong. It may be encrypted at this point. In provided example I will try to do this at first:
```
describe 'user access' do
let (:user) { create(:user, password: 'secret') }
before :each do
login_user(user[:email], 'secret')
end
it "should log in the user" do
controller.should be_logged_in
end
end
``` |
20,873,246 | I've spent far too long messing with this before asking for help. I can't seem to get RSpec and Sorcery to play together nicely. I've read through the docs on [Integration testing with Sorcery](https://github.com/NoamB/sorcery/wiki/Integration-Testing-with-Rspec,-Capybara-and-Fabricator) and can post the login action properly, but my tests still doesn't think the user is logged in.
```
# spec/controllers/user_controller_spec
describe 'user access' do
let (:user) { create(:user) }
before :each do
login_user(user[:email], user[:password])
end
it "should log in the user" do
controller.should be_logged_in
end
end
```
And my login\_user method
```
# spec/support/sorcery_login
module Sorcery
module TestHelpers
module Rails
def login_user email, password
page.driver.post(sessions_path, { email: email , password: password, remember_me: false })
end
end
end
end
```
The sessions controller handles the pages properly when I use them on the generated pages just fine. I tried outputting the results of the login\_user method and it appears to properly post the data. How do I persist this logged in user through the tests? Does a before :each block not work for this? I'm just not sure where it could be running wrong and I'm pretty new to testing/RSpec so I may be missing something obvious. I'd appreciate any help.
Here's the output of the failed tests:
```
1) UsersController user access should log in the user
Failure/Error: controller.should be_logged_in
expected logged_in? to return true, got false
``` | 2014/01/01 | [
"https://Stackoverflow.com/questions/20873246",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1467579/"
] | Did you try adding to spec/spec\_helpers.
```
RSpec.configure do |config|
# ...
config.include Sorcery::TestHelpers::Rails::Controller
end
```
Nota that you need to include `Sorcery::TestHelpers::Rails::Controller`, not just `Sorcery::TestHelpers::Rails`.
Then you will be able to `login_user` from any controller specs like:
```
describe CategoriesController do
before do
@user = FactoryGirl::create(:user)
end
describe "GET 'index'" do
it "returns http success" do
login_user
get 'index'
expect(response).to be_success
end
end
end
``` | This seems to be very poorly documented. The above solutions did not work for me. Here's how I got it to work:
Check your `sessions_url`. Make sure it is correct. Also, check what params are necessary to log in. It may be `email`, `username`, etc.
```
module Sorcery
module TestHelpers
module Rails
def login_user_post(email, password)
page.driver.post(sessions_url, { email:email, password: password })
end
end
end
end
```
RSpec config:
```
config.include Sorcery::TestHelpers::Rails
```
Spec helper:
```
def app
Capybara.app
end
```
spec/controllers/protected\_resource\_spec.rb:
```
describe UsersController do
before do
# Create user
# Login
response = login_user_post( user.email, :admin_password )
expect( response.headers[ 'location' ]).to eq 'http://test.host/'
# I test for login success here. Failure redirects to /sign_in.
@cookie = response.headers[ 'Set-Cookie' ]
end
specify 'Gets protected resource' do
get protected_resource, {}, { cookie:@cookie }
expect( last_response.status ).to eq 200
end
``` |
68,138,677 | I was wondering how I can count the number of unique words that I have in a list from a specific data frame.
For example, let's say I have a list = `['John','Bob,'Hannah']`
Next, I have a data frame with a column called sentences
```
df =
['sentences']
0 Bob went to the shop
1 John visited Hannah
2 Hannah ate a burger
```
I want the output to be:
```
John 1
Bob 1
Hannah 2
```
How can I count the unique names in any given sentence in any row in a dataset? | 2021/06/26 | [
"https://Stackoverflow.com/questions/68138677",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16319156/"
] | You can use `Series.str.contains` and call the `sum` to get the number of occurances of a word in the given column, just iterate over the list for all the substrings and do the same for each word, store the result as dictionary.
```py
list1 = ['John','Bob','Hannah']
output = {}
for word in list1:
output[word] = df['sentences'].str.contains(word).sum()
```
**OUTPUT:**
```py
{'John': 1, 'Bob': 1, 'Hannah': 2}
```
You can even use it in a dictionary comprehension:
```py
>>> {word: df['sentences'].str.contains(word).sum() for word in list1}
{'John': 1, 'Bob': 1, 'Hannah': 2}
```
**PS:** If a word/substring is present multiple time in the same row of the given column, the above method will count those multiple occurrences as 1, if you want to get multiple counts in that case, you can implement the same logic for each cell value | You also may use `str.split`, `explode`, and `value_counts`
```
l = ['John', 'Bob', 'Hannah']
df.sentences.str.split().explode().value_counts()[l]
Out[239]:
John 1
Bob 1
Hannah 2
Name: sentences, dtype: int64
```
However, I think `dict comprehension` is faster. |
68,138,677 | I was wondering how I can count the number of unique words that I have in a list from a specific data frame.
For example, let's say I have a list = `['John','Bob,'Hannah']`
Next, I have a data frame with a column called sentences
```
df =
['sentences']
0 Bob went to the shop
1 John visited Hannah
2 Hannah ate a burger
```
I want the output to be:
```
John 1
Bob 1
Hannah 2
```
How can I count the unique names in any given sentence in any row in a dataset? | 2021/06/26 | [
"https://Stackoverflow.com/questions/68138677",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16319156/"
] | You can use `Series.str.contains` and call the `sum` to get the number of occurances of a word in the given column, just iterate over the list for all the substrings and do the same for each word, store the result as dictionary.
```py
list1 = ['John','Bob','Hannah']
output = {}
for word in list1:
output[word] = df['sentences'].str.contains(word).sum()
```
**OUTPUT:**
```py
{'John': 1, 'Bob': 1, 'Hannah': 2}
```
You can even use it in a dictionary comprehension:
```py
>>> {word: df['sentences'].str.contains(word).sum() for word in list1}
{'John': 1, 'Bob': 1, 'Hannah': 2}
```
**PS:** If a word/substring is present multiple time in the same row of the given column, the above method will count those multiple occurrences as 1, if you want to get multiple counts in that case, you can implement the same logic for each cell value | In your case
```
list1 = ['John','Bob','Hannah']
df.Col1.str.findall('|'.join(list1)).explode().value_counts()
Hannah 2
Bob 1
John 1
Name: Col1, dtype: int64
``` |
7,737,028 | I need help in a Math logic issue.
Let say I have an object that can be manipulate (move) by user.
After the user moved the object I would like the object to continue moving and decelerate to a stop.
Example, when a user move an object from point A to B with a total distance of 100pixel in X axis, after user release a finger, I want to let the object continue moving and decelerate to a stop from point B to point C.
So how can I calculate the new distance of point C if I set the time for it to decelerate and stop in 2sec?
Thank you! | 2011/10/12 | [
"https://Stackoverflow.com/questions/7737028",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/986916/"
] | d = ½at² + vit + d0
d0 is the point at which the user "let go". Calculate vi from the motion before letting go. Set a to something negative; you'll have to fiddle with this to get it to feel right. Increment t from 0 through 2. d is where the object will end up. Remember that a and vi are **vectors** pointing in opposite directions, and that d0 and d are **points**. | If the acceleration, a, is constant you can use the formula:
d = ½at²
With t = 2s you get d = 2a.
The acceleration is enough to accelerate to v in 2s,
so a = v/2.
You get:
d = v
So if v= 100 pixels per second, the object should continue 100 pixels if it stops in 2 seconds under constant deceleration. |
7,737,028 | I need help in a Math logic issue.
Let say I have an object that can be manipulate (move) by user.
After the user moved the object I would like the object to continue moving and decelerate to a stop.
Example, when a user move an object from point A to B with a total distance of 100pixel in X axis, after user release a finger, I want to let the object continue moving and decelerate to a stop from point B to point C.
So how can I calculate the new distance of point C if I set the time for it to decelerate and stop in 2sec?
Thank you! | 2011/10/12 | [
"https://Stackoverflow.com/questions/7737028",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/986916/"
] | d = ½at² + vit + d0
d0 is the point at which the user "let go". Calculate vi from the motion before letting go. Set a to something negative; you'll have to fiddle with this to get it to feel right. Increment t from 0 through 2. d is where the object will end up. Remember that a and vi are **vectors** pointing in opposite directions, and that d0 and d are **points**. | If all you want is the *distance* from **B** to **C**, that's easy. If the object went a distance N pixels (say 100) from **A** to **B** in k seconds, then the distance from **B** to **C** will be N/k.
If you want the *location* of **C**, so that A, B and C are integers on the x-axis, C = B+(B-A)/k.
If you want to *animate* the motion, so that you can update the position x at every time step dt (say 0.1 seconds), then start (at **B**) with v=N/k, and at each step,
```
x += v * dt
v -= N * dt/(2 * k)
```
(Be sure to use floats, not integers, or the round-off error will ruin the effect.) |
198,714 | Consider \$3\$ binary strings of length \$n\$ chosen independently and uniformly at random. We are interested in computing the exact expected minimum [Hamming distance](https://en.wikipedia.org/wiki/Hamming_distance) between any pair. The Hamming distance between two strings of equal length is the number of positions at which the corresponding symbols are different.
Task
====
Given an input n between 2 and 10, inclusive, consider \$3\$ binary strings of length \$n\$ chosen independently and uniformly at random. Output the exact expected minimum Hamming distance between any pair.
Output should be given as a fraction.
Your code should run in [TIO](https://tio.run/#) without timing out. | 2020/01/31 | [
"https://codegolf.stackexchange.com/questions/198714",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/-1/"
] | [Pari/GP](http://pari.math.u-bordeaux.fr/), ~~92~~ 90 bytes
===========================================================
2 bytes saved thanks to @Nicolas!
```
n->sum(a=0,n,sum(b=0,n-a,sum(c=0,n-a-b,n!/a!/b!/c!/(n-a-b-c)!*min(a+b,min(a+c,b+c)))))/4^n
```
[Try it online!](https://tio.run/##JcpBCsMwDATAr8Q9KY2EEmiPzlMKksDBh6jGbd/vxokOu8OiIjXTVlqKzWn9/HaQOKNjl3aRnLbLpOiBJbAGtsBwTmRjuO/ZQSbFqw11srEfP17e0ruCxwWfM5aa/Qs@3AZaj0jgx1P7Aw "Pari/GP – Try It Online")
$$ f(n) = \frac{1}{4^n} \sum\_{\substack{a+b+c+d=n\\a,b,c,d\geq 0}} \binom{n}{a,b,c,d}\min(a+b,a+c,b+c)$$
A more direct brute force approach may be shorter in some languages, but I'm not sure if that's true for Pari. Anyway, it's a shame that Pari's `min` only accepts two arguments.
I can avoid the `min` and be about 6 times faster, but the compensating additional code makes it longer. Maybe in another language this is the shorter way. And maybe it is possible to simplify further and get rid of the innermost sum.
```
n->sum(a=0,n,sum(b=a,n-a,sum(c=b,n-a-b,n!/a!/b!/c!/(n-a-b-c)!*(a+b)*6/(1+(a==b)+(b==c))!)))/4^n
```
[Try it online!](https://tio.run/##HYxBCsMwDAS/EvUkxRZKoO1NeUpBNrjkUNW47ftdJ5dhWHa3Wtv5WXvR7rx9fi80XaLHw5JadLbTs6bDeRDEQBJIBsEz4kwwo4VE811wDeNCE4Wx10wERCTXh/fybui6xtsSa9v9iz5dJt4GCvoo9T8 "Pari/GP – Try It Online") | [Jelly](https://github.com/DennisMitchell/jelly), 31 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
====================================================================================================================
```
Ḷṗ4S⁼¥Ƈɓ!×Ṗṁ4SƝṂƲ}:!P$}ð€S,4*$}
```
A monadic Link accepting an integer which yields a pair of integers, `[numerator, denominator]` (not reduced to simplest form).
**[Try it online!](https://tio.run/##AUAAv/9qZWxsef//4bi24bmXNFPigbzCpcaHyZMhw5fhuZbhuYE0U8ad4bmCxrJ9OiFQJH3DsOKCrFMsNCokff///zEw "Jelly – Try It Online")** Or see [all of n=2 to 10](https://tio.run/##AV8AoP9qZWxsef//4bi24bmXNFPigbzCpcaHyZMhw5fhuZbhuYE0U8ad4bmCxrJ9OiFQJH3DsOKCrFMsNCokff8ycjEwwrUs4oCcIC0@IOKAnSzDhzpnLyTFkuG5mMaKKVn//w "Jelly – Try It Online") reduced to simplest form.
### How?
Uses the same approach as [Christian Sievers' Pari/GP answer](https://codegolf.stackexchange.com/a/198730/53748)
```
Ḷṗ4S⁼¥Ƈɓ!×Ṗṁ4SƝṂƲ}:!P$}ð€S,4*$} - Link: integer, n
Ḷ - lowered range -> [0..n-1]
ṗ4 - Cartesian power 4 (all length 4 tuples using alphabet [0..n-1]
Ƈ - filter keep those for which:
¥ - last two links as a dyad:
S - sum
⁼ - equals n?
ɓ ð€ - for each tuple do f(n, tuple):
! - factorial = n*(n-1)*...*1
} - use right argument:
Ʋ - last four links as a monad:
Ṗ - pop i.e. (a,b,c,d)->(a,b,c)
ṁ4 - mould like 4 -> (a,b,c,a)
Ɲ - for neighbours:
S - sum -> (a+b,b+c,c+a)
Ṃ - minimum
× - multiply
} - use right argument:
$ - last two links as a monad:
! - factorial -> (a!,b!,c!,d!)
P - product -> a!×b!×c!×d!
: - integer division
S - sum
} - use right argument:
$ - last two links as a monad:
4 - four
* - exponentiate -> 4^n
, - pair
``` |
198,714 | Consider \$3\$ binary strings of length \$n\$ chosen independently and uniformly at random. We are interested in computing the exact expected minimum [Hamming distance](https://en.wikipedia.org/wiki/Hamming_distance) between any pair. The Hamming distance between two strings of equal length is the number of positions at which the corresponding symbols are different.
Task
====
Given an input n between 2 and 10, inclusive, consider \$3\$ binary strings of length \$n\$ chosen independently and uniformly at random. Output the exact expected minimum Hamming distance between any pair.
Output should be given as a fraction.
Your code should run in [TIO](https://tio.run/#) without timing out. | 2020/01/31 | [
"https://codegolf.stackexchange.com/questions/198714",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/-1/"
] | [Pari/GP](http://pari.math.u-bordeaux.fr/), ~~92~~ 90 bytes
===========================================================
2 bytes saved thanks to @Nicolas!
```
n->sum(a=0,n,sum(b=0,n-a,sum(c=0,n-a-b,n!/a!/b!/c!/(n-a-b-c)!*min(a+b,min(a+c,b+c)))))/4^n
```
[Try it online!](https://tio.run/##JcpBCsMwDATAr8Q9KY2EEmiPzlMKksDBh6jGbd/vxokOu8OiIjXTVlqKzWn9/HaQOKNjl3aRnLbLpOiBJbAGtsBwTmRjuO/ZQSbFqw11srEfP17e0ruCxwWfM5aa/Qs@3AZaj0jgx1P7Aw "Pari/GP – Try It Online")
$$ f(n) = \frac{1}{4^n} \sum\_{\substack{a+b+c+d=n\\a,b,c,d\geq 0}} \binom{n}{a,b,c,d}\min(a+b,a+c,b+c)$$
A more direct brute force approach may be shorter in some languages, but I'm not sure if that's true for Pari. Anyway, it's a shame that Pari's `min` only accepts two arguments.
I can avoid the `min` and be about 6 times faster, but the compensating additional code makes it longer. Maybe in another language this is the shorter way. And maybe it is possible to simplify further and get rid of the innermost sum.
```
n->sum(a=0,n,sum(b=a,n-a,sum(c=b,n-a-b,n!/a!/b!/c!/(n-a-b-c)!*(a+b)*6/(1+(a==b)+(b==c))!)))/4^n
```
[Try it online!](https://tio.run/##HYxBCsMwDAS/EvUkxRZKoO1NeUpBNrjkUNW47ftdJ5dhWHa3Wtv5WXvR7rx9fi80XaLHw5JadLbTs6bDeRDEQBJIBsEz4kwwo4VE811wDeNCE4Wx10wERCTXh/fybui6xtsSa9v9iz5dJt4GCvoo9T8 "Pari/GP – Try It Online") | [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 26 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
============================================================================================================================
```
Ý4ãʒOQ}ε¨Ćü+ßI!*y!P÷}O4Im‚
```
Port of [*@JonathanAllan*'s Jelly answer](https://codegolf.stackexchange.com/a/198772/52210), which uses the same formula as [@ChristianSievers's Pari/GP answer](https://codegolf.stackexchange.com/a/198730/52210).
Just like his answer, the output is not reduced to its simplest form.
[Try it online](https://tio.run/##ATEAzv9vc2FiaWX//8OdNMOjypJPUX3OtcKoxIbDvCvDn0khKnkhUMO3fU80SW3igJr//zEw) or [verify all test cases](https://tio.run/##AUYAuf9vc2FiaWX/MlTFuHZ5PyIg4oaSICI/ecKp/8OdNMOjypJPwq5Rfc61wqjEhsO8K8Ofwq4hKnkhUMO3fU80wq5t4oCa/yz/).
**Explanation:**
```python
Ý # Push a list in the range [0, (implicit) input-integer]
# (NOTE: Jonathan's Jelly answer uses the range [0,input) instead of
# [0,input], but that doesn't pose an issue, since the mapped value will
# result in 0, not affecting the total sum)
4ã # Create all possible quartets by using the cartesian product with 4
ʒ # Filter these quartets by:
O # Take the sum
Q # And check if it's equal to the (implicit) input-integer
}ε # After the filter: map each remaining quartet [a,b,c,d] to:
¨ # Remove the last item d: [a,b,c]
Ć # Enclose the list, appending its own head: [a,b,c,a]
ü+ # Sum each consecutive pair: [a+b,b+c,c+a]
ß # Pop and push the minimum of this
I! # Push the input, and take its factorial
* # Multiply both by each other
y! # Take the factorial of each value in the quartet: [a!,b!,c!,d!]
P # Take the product of this: a!*b!*c!*d!
÷ # Integer-divide the two: (min(a+b,b+c,c+a)*n!) // (a!*b!*c!*d!)
}O # After the map: take the sum of all values in the list
I # Push the input-integer again
4 m # And take 4 to the power this
‚ # And finally pair both together
# (after which this pair is output implicitly as result)
``` |
19,663,048 | Hello I have a page where the code was working perfectly that would launch a video when an an element with ".onclick" is assigned. Howvever it only seems to work in Chrome. There was even an instance when one page's video would work (in all browsers) but now neither of them work.
This works perfectly fine in Chrome though. I'm figuring I've messed up somewhere in my code and since FF is the most strict of browser's is the reason it won't play (oddly in IE as well). Any help would be appreciated. Thanks. | 2013/10/29 | [
"https://Stackoverflow.com/questions/19663048",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2554449/"
] | Care to share your code because I cannot seem to get it to work in FF. Works great in other browsers though.
Here is the code I am using.
JS
```
var video = document.getElementById('video');
video.addEventListener('click',function(){
video.play();
},false);
```
HTML
```
<video src="your_video" width="250" height="50" poster="your_image" onclick="this.play();"/></video>
``` | Actually I found the issue. Firefox makes you put a "#" inside the A href tag for this situation.
Thanks for anyone who actually looked into it for me. |
40,749,024 | Please help me with the query
Below are the table and requirement details
[](https://i.stack.imgur.com/ux4O6.png) | 2016/11/22 | [
"https://Stackoverflow.com/questions/40749024",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6874511/"
] | Case statement constructs one variable.
For your example you can try this, with one statement of Case :
```
data example;
input x $;
datalines;
A
A
A
B
B
;
run;
proc sql;
create table make_two_from_one_2 as
select *
, case
when x = 'A' then 'Result1A,Result2A'
when x = 'B' then 'Result1B,Result2B'
else 'Error'
end as thing0
from example
;
quit;
data example1(drop=thing0);
set make_two_from_one_2;
thing1=scan(thing0,1,',');
thing2=scan(thing0,2,',');
run;
``` | In your case, maybe you could try this:
```
proc sql;
create table make_two_from_one as
select *
, case
when x = 'A' then 'Result1A'
when x = 'B' then 'Result1B'
else 'Error'
end as thing1,
translate(calculated thing1,'2','1') as thing2
from example
;
quit;
``` |
40,749,024 | Please help me with the query
Below are the table and requirement details
[](https://i.stack.imgur.com/ux4O6.png) | 2016/11/22 | [
"https://Stackoverflow.com/questions/40749024",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6874511/"
] | Case statement constructs one variable.
For your example you can try this, with one statement of Case :
```
data example;
input x $;
datalines;
A
A
A
B
B
;
run;
proc sql;
create table make_two_from_one_2 as
select *
, case
when x = 'A' then 'Result1A,Result2A'
when x = 'B' then 'Result1B,Result2B'
else 'Error'
end as thing0
from example
;
quit;
data example1(drop=thing0);
set make_two_from_one_2;
thing1=scan(thing0,1,',');
thing2=scan(thing0,2,',');
run;
``` | Personally I think this need, i.e., to overcome a cumbersome syntactic barrier with something that can be maintained in one place, is a good use case for SAS macro.
The macro version also avoids the perils of parsing, is nicely tabular, and makes no type assumptions.
```
%macro _case(when_A, when_B, error='Error');
case
when x = 'A' then &when_A
when x = 'B' then &when_B
else &error
end
%mend;
proc sql;
create table make_two_from_one_v2 as
select *
, %_case('Result1A', 'Result1B') as thing1
, %_case('Result2A', 'Result2B') as thing2
from example
;
quit;
``` |
40,749,024 | Please help me with the query
Below are the table and requirement details
[](https://i.stack.imgur.com/ux4O6.png) | 2016/11/22 | [
"https://Stackoverflow.com/questions/40749024",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6874511/"
] | Just for completeness, this is straightforward in a data step, using `select`, `when`, `do`, `otherwise`. Or you could just use `if`, `then`, `do`, `else`.
```
data want;
set example;
select (x);
when ('A') do;
thing1 = 'Result1A';
thing2 = 'Result2A';
end;
when ('B') do;
thing1 = 'Result1B';
thing2 = 'Result2B';
end;
otherwise do;
thing1 = 'Error';
thing2 = 'Error';
end;
end;
run;
``` | In your case, maybe you could try this:
```
proc sql;
create table make_two_from_one as
select *
, case
when x = 'A' then 'Result1A'
when x = 'B' then 'Result1B'
else 'Error'
end as thing1,
translate(calculated thing1,'2','1') as thing2
from example
;
quit;
``` |
40,749,024 | Please help me with the query
Below are the table and requirement details
[](https://i.stack.imgur.com/ux4O6.png) | 2016/11/22 | [
"https://Stackoverflow.com/questions/40749024",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6874511/"
] | Just for completeness, this is straightforward in a data step, using `select`, `when`, `do`, `otherwise`. Or you could just use `if`, `then`, `do`, `else`.
```
data want;
set example;
select (x);
when ('A') do;
thing1 = 'Result1A';
thing2 = 'Result2A';
end;
when ('B') do;
thing1 = 'Result1B';
thing2 = 'Result2B';
end;
otherwise do;
thing1 = 'Error';
thing2 = 'Error';
end;
end;
run;
``` | Personally I think this need, i.e., to overcome a cumbersome syntactic barrier with something that can be maintained in one place, is a good use case for SAS macro.
The macro version also avoids the perils of parsing, is nicely tabular, and makes no type assumptions.
```
%macro _case(when_A, when_B, error='Error');
case
when x = 'A' then &when_A
when x = 'B' then &when_B
else &error
end
%mend;
proc sql;
create table make_two_from_one_v2 as
select *
, %_case('Result1A', 'Result1B') as thing1
, %_case('Result2A', 'Result2B') as thing2
from example
;
quit;
``` |
16,006 | From <http://en.wikipedia.org/wiki/Mutant_%28fictional%29#DC_Comics>
>
> Mutants play a smaller, but still substantial role in DC Comics
>
>
>
However, that particular Wiki article only mentions very few mutants (Captain Comet, and a couple of Batman adversaries), neither of whom strike me as important enough to warrant "**substantial**" role.
Was that expression inaccurate? Or are there really mutants who play genuinely substantial role in DC universe? | 2012/05/03 | [
"https://scifi.stackexchange.com/questions/16006",
"https://scifi.stackexchange.com",
"https://scifi.stackexchange.com/users/976/"
] | The issue at hand is the DC Universe's definition of mutant. Finishing off your quote:
>
> DC Comics **does not make a semantic or an abstract distinction between humans (or superheroes/villains) born with mutations making them different from humans mutated by outside sources**.
>
>
>
This is to say by DC standards, Spider-man is a mutant, not a mutate. This opens up our definition and the number of applicable characters.
>
> Also characters who were transformed through radiation or a mutagenic gas are sometimes identified as mutants instead of Marvel's term, 'mutates'.
>
>
> All humans with powers are simply referred to, and treated as, one group collectively known as *metahumans*. The term mutant does still exist for humans born with actual powers instead of attaining them.
>
>
>
Here is a handy picture for DC supers:

And for Marvel:

So anyone who's been 'mutated' by an external force would be considered a mutant in their lexicon. For instance, *The Flash* might be considered a mutant, as the chemicals he was exposed to mutated him. Because of the huge overlap with metahumans though, and being the more general case, they're often just called meta humans. | DC steers away from the Marvel version of *mutant*, perhaps because it plays such a major role at the *House of Ideas* or simply because they feel no need. There are mutants within the DC Universe and have been for some time; the first I can recall is ***Captain Comet*** who, if memory serves, left the Earth *because* he was a mutant and different from other humans.
Others include **Jade** and **Obsidian**, the children of the Golden Age **Green Lantern** and **Nuklon** or **Atom Smasher** as he is now called - all of whom were founding members of **Infinity Inc.**, the legacy group of the **JSA**.
*Metahumans* seems to be the operative word of choice at DC and encompasses (pretty much) all heroes and villains with powers. |
20,131,226 | I am parsing XML in PHP with SimpleXML and have an XML like this:
```
<xml>
<element>
textpart1
<subelement>subcontent1</subelement>
textpart2
<subelement>subcontent2</subelement>
textpart3
</element>
</xml>
```
When I do `$xml->element` it naturally gives me the whole element, as in all three textparts.
So if I parse this into an array (with a `foreach` for the children) I get:
```
0 => textpart1textpart2textpart3, 1 => subcontent1, 2 => subcontent2
```
I need a way to parse the `<element>` node so that each textpart that stops at, or begins after a subelement is treated as its own element.
As a result I am looking for an ordered list that could be express in an array like this:
```
0 => textpart1, 1 => subcontent1, 2 => textpart2, 3 => subcontent2, 4 => textpart3
```
Is that possible without altering the XML file? Thanks in advance for any hints! | 2013/11/21 | [
"https://Stackoverflow.com/questions/20131226",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1648520/"
] | You are actually looking for all text-nodes that are descendants of the `element` element node. This can be expressed as the following xpath:
```
/*/element//text()
```
Even SimpleXML has an `xpath` method that does execute this query without any errors, the actual text-nodes are converted to their parents element nodes. This is because of how SimpleXML works and for what it has been designed for.
Compare with:
* [Which DOMNodes can be represented by SimpleXMLElement?](https://stackoverflow.com/a/17557961/367456)
* [SimpleXML access seperated text nodes](https://stackoverflow.com/a/17582811/367456)
* [Re: [PHP-DEV] SimpleXML->children() and text nodes](http://marc.info/?l=php-internals&m=107559525402120&w=2)
However, with some help of the sister-library DOMDocument which can represent text-nodes on their own, it is possible to get it to work:
```
<?php
/**
* SimpleXML get Element Content between Child Elements
* @link https://stackoverflow.com/q/20131226/367456
*/
$buffer = <<<BUFFER
<xml>
<element>
textpart1
<subelement>subcontent1</subelement>
textpart2
<subelement>subcontent2</subelement>
textpart3
</element>
</xml>
BUFFER;
$xml = simplexml_load_string($buffer);
$xpath = new SimpleXMLXpath($xml);
$result = $xpath->query('/*/element//text()');
print_r($result);
```
The result output then is:
```
Array
(
[0] =>
textpart1
[1] => subcontent1
[2] =>
textpart2
[3] => subcontent2
[4] =>
textpart3
)
```
This is possible because of the `SimpleXMLXpath` class that wraps `DOMXPath` internally and stringifies the result in case it's a textnode:
```
/**
* Class SimpleXMLXpath
*
* @author hakre <http://hakre.wordpress.com/>
*/
class SimpleXMLXpath
{
private $xml;
public function __construct(SimpleXMLElement $xml)
{
$this->xml = $xml;
}
public function query($expression)
{
$context = dom_import_simplexml($this->xml);
$xpath = new DOMXPath($context->ownerDocument);
$result = [];
foreach ($xpath->query($expression, $context) as $node) {
switch (TRUE) {
case $node instanceof DOMText:
$result[] = $node->nodeValue;
continue;
case $node instanceof DOMElement:
case $node instanceof DOMAttr:
isset($class) || $class = get_class($this->xml);
$result[] = simplexml_import_dom($node, $class);
continue;
}
}
return $result;
}
}
``` | The simple answer is no. SimpleXML does not implement any kind of support for text nodes.
In this case your best and preferred option is to use [DOMDocument](http://docs.php.net/manual/en/book.dom.php). |
20,131,226 | I am parsing XML in PHP with SimpleXML and have an XML like this:
```
<xml>
<element>
textpart1
<subelement>subcontent1</subelement>
textpart2
<subelement>subcontent2</subelement>
textpart3
</element>
</xml>
```
When I do `$xml->element` it naturally gives me the whole element, as in all three textparts.
So if I parse this into an array (with a `foreach` for the children) I get:
```
0 => textpart1textpart2textpart3, 1 => subcontent1, 2 => subcontent2
```
I need a way to parse the `<element>` node so that each textpart that stops at, or begins after a subelement is treated as its own element.
As a result I am looking for an ordered list that could be express in an array like this:
```
0 => textpart1, 1 => subcontent1, 2 => textpart2, 3 => subcontent2, 4 => textpart3
```
Is that possible without altering the XML file? Thanks in advance for any hints! | 2013/11/21 | [
"https://Stackoverflow.com/questions/20131226",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1648520/"
] | As others have said, SimpleXML doesn't have any support for accessing individual text nodes as separate entities, so you will need to supplement it with some DOM methods. Thankfully, you can switch between the two at will using [`dom_import_simplexml`](http://php.net/dom_import_simplexml) and [`simplexml_import_dom`](http://php.net/manual/en/function.simplexml-import-dom.php).
The key pieces of DOM functionality you need are:
* the DOMElement->childNodes member variable for accessing all nodes directly under a particular element as an iterable list
* the DOMNode->nodeType variable for determining if a particular child is a text node or an element
* the DOMNode->nodeValue variable to get the actual text
Given those, you can write a function which returns an array with a mixture of SimpleXML objects for child elements, and strings for child text nodes, something like this:
```
function get_child_elements_and_text_nodes($sx_element)
{
$return = array();
$dom_element = dom_import_simplexml($sx_element);
foreach ( $dom_element->childNodes as $dom_child )
{
switch ( $dom_child->nodeType )
{
case XML_TEXT_NODE:
$return[] = $dom_child->nodeValue;
break;
case XML_ELEMENT_NODE:
$return[] = simplexml_import_dom($dom_child);
break;
}
}
return $return;
}
```
In your case, you need to recurse down the tree, which makes it a little confusing if you mix DOM and SimpleXML as you go, so you could instead write the recursion entirely in DOM and convert the SimpleXML object before running it:
```
function recursively_find_text_nodes($dom_element)
{
$return = array();
foreach ( $dom_element->childNodes as $dom_child )
{
switch ( $dom_child->nodeType )
{
case XML_TEXT_NODE:
$return[] = $dom_child->nodeValue;
break;
case XML_ELEMENT_NODE:
$return = array_merge($return, recursively_find_text_nodes($dom_child));
break;
}
}
return $return;
}
$text_nodes = recursively_find_text_nodes(dom_import_simplexml($simplexml->element));
```
[Here's a live demo of that last function.](http://codepad.viper-7.com/BrIjY7) | The simple answer is no. SimpleXML does not implement any kind of support for text nodes.
In this case your best and preferred option is to use [DOMDocument](http://docs.php.net/manual/en/book.dom.php). |
20,131,226 | I am parsing XML in PHP with SimpleXML and have an XML like this:
```
<xml>
<element>
textpart1
<subelement>subcontent1</subelement>
textpart2
<subelement>subcontent2</subelement>
textpart3
</element>
</xml>
```
When I do `$xml->element` it naturally gives me the whole element, as in all three textparts.
So if I parse this into an array (with a `foreach` for the children) I get:
```
0 => textpart1textpart2textpart3, 1 => subcontent1, 2 => subcontent2
```
I need a way to parse the `<element>` node so that each textpart that stops at, or begins after a subelement is treated as its own element.
As a result I am looking for an ordered list that could be express in an array like this:
```
0 => textpart1, 1 => subcontent1, 2 => textpart2, 3 => subcontent2, 4 => textpart3
```
Is that possible without altering the XML file? Thanks in advance for any hints! | 2013/11/21 | [
"https://Stackoverflow.com/questions/20131226",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1648520/"
] | As others have said, SimpleXML doesn't have any support for accessing individual text nodes as separate entities, so you will need to supplement it with some DOM methods. Thankfully, you can switch between the two at will using [`dom_import_simplexml`](http://php.net/dom_import_simplexml) and [`simplexml_import_dom`](http://php.net/manual/en/function.simplexml-import-dom.php).
The key pieces of DOM functionality you need are:
* the DOMElement->childNodes member variable for accessing all nodes directly under a particular element as an iterable list
* the DOMNode->nodeType variable for determining if a particular child is a text node or an element
* the DOMNode->nodeValue variable to get the actual text
Given those, you can write a function which returns an array with a mixture of SimpleXML objects for child elements, and strings for child text nodes, something like this:
```
function get_child_elements_and_text_nodes($sx_element)
{
$return = array();
$dom_element = dom_import_simplexml($sx_element);
foreach ( $dom_element->childNodes as $dom_child )
{
switch ( $dom_child->nodeType )
{
case XML_TEXT_NODE:
$return[] = $dom_child->nodeValue;
break;
case XML_ELEMENT_NODE:
$return[] = simplexml_import_dom($dom_child);
break;
}
}
return $return;
}
```
In your case, you need to recurse down the tree, which makes it a little confusing if you mix DOM and SimpleXML as you go, so you could instead write the recursion entirely in DOM and convert the SimpleXML object before running it:
```
function recursively_find_text_nodes($dom_element)
{
$return = array();
foreach ( $dom_element->childNodes as $dom_child )
{
switch ( $dom_child->nodeType )
{
case XML_TEXT_NODE:
$return[] = $dom_child->nodeValue;
break;
case XML_ELEMENT_NODE:
$return = array_merge($return, recursively_find_text_nodes($dom_child));
break;
}
}
return $return;
}
$text_nodes = recursively_find_text_nodes(dom_import_simplexml($simplexml->element));
```
[Here's a live demo of that last function.](http://codepad.viper-7.com/BrIjY7) | You are actually looking for all text-nodes that are descendants of the `element` element node. This can be expressed as the following xpath:
```
/*/element//text()
```
Even SimpleXML has an `xpath` method that does execute this query without any errors, the actual text-nodes are converted to their parents element nodes. This is because of how SimpleXML works and for what it has been designed for.
Compare with:
* [Which DOMNodes can be represented by SimpleXMLElement?](https://stackoverflow.com/a/17557961/367456)
* [SimpleXML access seperated text nodes](https://stackoverflow.com/a/17582811/367456)
* [Re: [PHP-DEV] SimpleXML->children() and text nodes](http://marc.info/?l=php-internals&m=107559525402120&w=2)
However, with some help of the sister-library DOMDocument which can represent text-nodes on their own, it is possible to get it to work:
```
<?php
/**
* SimpleXML get Element Content between Child Elements
* @link https://stackoverflow.com/q/20131226/367456
*/
$buffer = <<<BUFFER
<xml>
<element>
textpart1
<subelement>subcontent1</subelement>
textpart2
<subelement>subcontent2</subelement>
textpart3
</element>
</xml>
BUFFER;
$xml = simplexml_load_string($buffer);
$xpath = new SimpleXMLXpath($xml);
$result = $xpath->query('/*/element//text()');
print_r($result);
```
The result output then is:
```
Array
(
[0] =>
textpart1
[1] => subcontent1
[2] =>
textpart2
[3] => subcontent2
[4] =>
textpart3
)
```
This is possible because of the `SimpleXMLXpath` class that wraps `DOMXPath` internally and stringifies the result in case it's a textnode:
```
/**
* Class SimpleXMLXpath
*
* @author hakre <http://hakre.wordpress.com/>
*/
class SimpleXMLXpath
{
private $xml;
public function __construct(SimpleXMLElement $xml)
{
$this->xml = $xml;
}
public function query($expression)
{
$context = dom_import_simplexml($this->xml);
$xpath = new DOMXPath($context->ownerDocument);
$result = [];
foreach ($xpath->query($expression, $context) as $node) {
switch (TRUE) {
case $node instanceof DOMText:
$result[] = $node->nodeValue;
continue;
case $node instanceof DOMElement:
case $node instanceof DOMAttr:
isset($class) || $class = get_class($this->xml);
$result[] = simplexml_import_dom($node, $class);
continue;
}
}
return $result;
}
}
``` |
12,013,956 | I've got a container div with a bunch of scrollable content (for the record I'm using iScroll - if that changes the solution). When I scroll to the top I want to load content above the current scroll position. If I simply prepend the div using jQuery "prepend();" the contents in my scrollable area shift down. Ideally we'd want to keep the current content in the frame and have the scrollable area grow upwards above the content.
Any thoughts?
Thanks! | 2012/08/17 | [
"https://Stackoverflow.com/questions/12013956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1118481/"
] | According to [the iScroll website](http://cubiq.org/iscroll), it has a method called `scrollToElement`:
>
> **`scrollToElement(el, runtime)`**: scrolls to any element inside the scrolling area. `el` must be a CSS3 selector. Eg: `scrollToElement("#elementID", '400ms')`
>
>
>
If you always prepend a fixed amount of `div`s (e.g. always a single `div`), I imagine you could use it to scroll to (e.g.) the second element right after you've prepended the new content:
```
// ... (prepend new content)
myScroll.scrollToElement('#scroller :nth-child(2)', '0ms');
```
I haven't tried this, so please let us know if this works for you. | After a quick look through iScroll's source, here's what I've found:
* The current `x` and `y` are always available through `myScroll.x` and `myScroll.y`.
* iScroll has an internal function `_offset(el)`, which returns the `left` and `top` offset of any given element.
This basically opens up two solutions:
1. Use `_offset(el)`. While possible, this is inadvisable. The underscore is a convention for marking a function "private", meaning, amongst other things, that it's not part of the official API.
*or*
2. Use the newly added element's height:
```
var x = myScroll.x;
var y = myScroll.y;
// ... (prepend new content)
y += $('#scroller :first-child').outerHeight();
myScroll.scrollTo(x, y, '0ms');
```
You may need to pass `true` to [`.outerHeight()`](http://api.jquery.com/outerHeight/), which makes it include margins.
Once again, I haven't tested this, so please let us know if it works. |
29,723,423 | Today I made a small typo in my program, and was wandering why I wasn't getting any output, although the program compiled fine. Basically it reduces to this:
```
#include <iostream>
int main()
{
std::cout < "test"; // no << but <
}
```
I have absolutely no idea what kind of implicit conversion is performed here so the program still compiles (both g++4.9.2 and even g++5). I just realized that clang++ rejects the code. Is there a conversion to `void*` being performed (cannot think of anything else)? I remember seeing something like this, but I thought it was addressed in g++5, but this doesn't seem to be the case.
**EDIT:** I was not compiling with `-std=c++11`, so the code was valid in pre-C++11 (due to conversion to `void*` of `ostream`). When compiling with `-std=c++11` g++5 rejects the code, g++4.9 still accepts it. | 2015/04/18 | [
"https://Stackoverflow.com/questions/29723423",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3093378/"
] | Yes, the compiler is converting `cout` to a `void*`. If you use the `-S` switch to get the code's disassembly, you'll see something like this:
```
mov edi, OFFSET FLAT:std::cout+8
call std::basic_ios<char, std::char_traits<char> >::operator void*() const
cmp rax, OFFSET FLAT:.LC0
setb al
test al, al
```
Which makes it clear that `operator void*` is the culprit.
Contrary to what Bill Lynch said, I'm able to reproduce it with `—std=c++11` on [Compiler Explorer](http://goo.gl/RgweWS). However, it does appear to be an implementation defect, since C++11 should have replaced `operator void*` with `operator bool` on `basic_ios`. | This is only valid before C++11.
You're basically doing: `((void *) std::cout) < ((char *) "test")` |
14,832,221 | I have a DF where I want to add a new variable called "B" into the 2nd position.
```
A C D
1 1 5 2
2 3 3 7
3 6 2 3
4 6 4 8
5 1 1 2
```
Anyone have an idea? | 2013/02/12 | [
"https://Stackoverflow.com/questions/14832221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2061634/"
] | The easiest way would be to add the columns you want and then reorder them:
```
dat$B <- 1:5
newdat <- dat[, c("A", "B", "C", "D")]
```
Another way:
```
newdat <- cbind(dat[1], B=1:5, dat[,2:3])
```
If you're concerned about overhead, perhaps a `data.table` solution? (With help from [this answer](https://stackoverflow.com/a/12232123/1465387)):
```
library(data.table)
dattable <- data.table(dat)
dattable[,B:=1:5]
setcolorder(dattable, c("A", "B", "C", "D"))
``` | ```
dat$B <- 1:5
ind <- c(1:which(names(data) == "A"),ncol(data),(which(names(data) == "A")+1):ncol(data)-1)
data <- data[,ind]
```
Create the variable at the end of the data.frame and then using an indicator vector signaling how to reorder the columns. ind is just a vector of numbers |
30,072 | So far in Dead Island I've noticed white, green, blue, and purple items. These seem to indicate different rarities, similar to the classification system used in Borderlands, but I don't know what these colors actually mean. Is green more rare than blue? What are the different rarity colors? | 2011/09/10 | [
"https://gaming.stackexchange.com/questions/30072",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/207/"
] | So far, here are all the colors I've found ordered in quality (based on overall stats when compared to one of lesser color and also how often I see weapons of that color):
white->green->blue->purple->orange
The in game text during loading says that some of the quest rewards gives you unique weapons, and (assuming Gabriel's Sledgehammer is a unique), it is still an orange colored weapon. So I'm going to assume that even unique weapons are orange. I've also found a Master Chef, which was also orange.
[This link](http://www.g4tv.com/thefeed/blog/post/716093/dead-island-weaponsmods-location-guide/) seems to back up my answer. | Orange are the super rare or legendary weapons. Purple are rare, blue and green are rare but tend to be less rare than others. |
30,072 | So far in Dead Island I've noticed white, green, blue, and purple items. These seem to indicate different rarities, similar to the classification system used in Borderlands, but I don't know what these colors actually mean. Is green more rare than blue? What are the different rarity colors? | 2011/09/10 | [
"https://gaming.stackexchange.com/questions/30072",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/207/"
] | So far, here are all the colors I've found ordered in quality (based on overall stats when compared to one of lesser color and also how often I see weapons of that color):
white->green->blue->purple->orange
The in game text during loading says that some of the quest rewards gives you unique weapons, and (assuming Gabriel's Sledgehammer is a unique), it is still an orange colored weapon. So I'm going to assume that even unique weapons are orange. I've also found a Master Chef, which was also orange.
[This link](http://www.g4tv.com/thefeed/blog/post/716093/dead-island-weaponsmods-location-guide/) seems to back up my answer. | As Ashley Nunn points out in an [answer to another question](https://gaming.stackexchange.com/a/46137/8366), the Dead Island wiki [explains each color in detail](http://deadisland.wikia.com/wiki/Item_Rarity):
>
> There are a total of FIVE different levels of rarity for an item in Dead Island. These are:
>
>
> * White (Common) - Absolutely everywhere, most items and weapons are this color.
> * Green (Uncommon) - Frequently found in chests and given as a reward from quests. Uncommon items are occasionaly [sic] dropped by zombies on death.
> * Blue (Rare) - Often given as a reward from quests but can be found on zombies after death and in chests although the chance is low.
> * Violet (Unique) - Occasionaly [sic] given as a reward from quests but can be found on zombies after death and in chests but the chance of this is very low.
> * Orange (Legendary) - Rarely given as a rewards from quests and is both rarely dropped by zombies on death and found in chests. Finding one of these is truely [sic] a gem, congratulations if you have one.
>
>
> |
2,436,502 | Is it possible, in the `expr` expression of the `with()` function, to access the `data` argument directly? Here's what I mean conceptually:
```
> print(df)
result qid f1 f2 f3
1 -1 1 0.0000 0.1253 0.0000
2 -1 1 0.0098 0.0000 0.0000
3 1 1 0.0000 0.0000 0.1941
4 -1 2 0.0000 0.2863 0.0948
5 1 2 0.0000 0.0000 0.0000
6 1 2 0.0000 0.7282 0.9087
> with(df, subset(.data, select=f1:f3)) # Doesn't work
```
Of course the above example is kind of silly, but it would be handy for things like this:
```
with(subset(df, f2>0), foo(qid, vars=subset(.data, select=f1:f3)))
```
I tried to poke around with `environment()` and `parent.frame()` etc., but didn't come up with anything that worked.
Maybe this is really a question about `eval()`, since that's how `with.default()` is implemented. | 2010/03/12 | [
"https://Stackoverflow.com/questions/2436502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/169947/"
] | Using `parent.frame()`:
```
# sample data:
set.seed(2436502)
dfrm <- data.frame(x1 = rnorm(100), x2 = rnorm(100), g1 = sample(letters, 100, TRUE))
# how to use it:
with(subset(dfrm, x1<0), {
str(parent.frame(2)$data)
"Hello!"
})
# 'data.frame': 47 obs. of 3 variables:
# $ x1: num -0.836 -0.343 -0.341 -1.044 -0.665 ...
# $ x2: num 0.362 0.727 0.62 -0.178 -1.538 ...
# $ g1: Factor w/ 26 levels "a","b","c","d",..: 11 4 15 19 8 13 22 15 15 23 ...
```
### How the magic works
Using `ls()` you can inspect `parent.frames`:
```
with(subset(dfrm, x1<0), {
print(ls())
print(ls(parent.frame(1)))
print(ls(parent.frame(2)))
print(ls(parent.frame(3)))
})
# [1] "g1" "x1" "x2"
# [1] "enclos" "envir" "expr"
# [1] "data" "expr"
# [1] "dfrm"
```
As you can see:
* `parent.frame(3)` is base environment (in this case),
* `parent.frame(2)` is environment of `subset` function
* `parent.frame(1)` is environment of `{` function (see `?Paren`) | I tend to invert it, i.e. put the `with()` outside and have `subset()` work on its data:
```
R> data(mtcars)
R> with(subset(mtcars, gear==4), lm(mpg ~ wt)) # no data arg
Call:
lm(formula = mpg ~ wt)
Coefficients:
(Intercept) wt
42.49 -6.86
```
This is also a silly example because `lm(mpg ~ wt, data=mtcars, subset=gear==4)`
obviously does the same but you get the drift. |
4,836,038 | I need to decode:
```
file://localhost/G:/test/%E6%B0%97%E3%81%BE%E3%81%90%E3%82%8C%E3%83%AD%E3%83%9E%E3%83%B3%E3%83%86%E3%82%A3%E3%83%83%E3%82%AF.mp3
```
into
```
file://localhost/G:/test/気まぐれロマンティック.mp3
```
How to do it in Delphi prior 2009 (I use Delphi 2006) ? | 2011/01/29 | [
"https://Stackoverflow.com/questions/4836038",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/193431/"
] | The Indy TIdURI class in IdURI unit contains UrlDecode / UrlEncode functions. You could try it with a recent version (10.5.8) of Indy, which has encoding parameters:
```
class function TIdURI.URLDecode(ASrc: string; AByteEncoding: TIdTextEncoding = nil
{$IFDEF STRING_IS_ANSI}; ADestEncoding: TIdTextEncoding = nil{$ENDIF}
): string;
``` | mjn may be correct, but I would strongly advise that if you are going to be handling any kind of Unicode within Delphi, try to persuade your bosses to upgrade to the latest version of Delphi (or just Delphi 2009). The Unicode support in Delphi 2009 is very good, and just works out of the box. If you really cant do this, the [TNT components](http://www.axolot.com/TNT/) worked for us but in the end we just waited for Delphi 2009 to come out because it was so much simpler to have it out of the box from Borland. |
4,836,038 | I need to decode:
```
file://localhost/G:/test/%E6%B0%97%E3%81%BE%E3%81%90%E3%82%8C%E3%83%AD%E3%83%9E%E3%83%B3%E3%83%86%E3%82%A3%E3%83%83%E3%82%AF.mp3
```
into
```
file://localhost/G:/test/気まぐれロマンティック.mp3
```
How to do it in Delphi prior 2009 (I use Delphi 2006) ? | 2011/01/29 | [
"https://Stackoverflow.com/questions/4836038",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/193431/"
] | I have no Delphi 2006, so I tested the code on Delphi 2007; you should:
convert the string with "%" characters to plain UTF8 string;
convert UTF8 string to Wide String (UTF8Decode);
convert Wide String to Ansi String with Japanese encoding (WideCharToMultiByte):
```
const
SrcStr = 'file://localhost/G:/test/%E6%B0%97%E3%81%BE%E3%81%90%E3%82%8C%E3%83%AD%E3%83%9E%E3%83%B3%E3%83%86%E3%82%A3%E3%83%83%E3%82%AF.mp3';
function Src2Utf8(const S: string): string;
var
I: Integer;
S1: string;
B: Byte;
begin
I:= 0;
Result:= '';
SetLength(S1, 3);
S1[1]:= '$';
while I < Length(S) do begin
Inc(I);
if S[I] <> Char('%') then Result:= Result + S[I]
else begin
Inc(I);
S1[2]:= S[I];
Inc(I);
S1[3]:= S[I];
B:= StrToInt(S1);
Result:= Result + Char(B);
end;
end;
end;
procedure TForm8.Button1Click(Sender: TObject);
var
S: WideString;
S1: string;
begin
S:= Utf8Decode(Src2Utf8(SrcStr));
SetLength(S1, 4 * Length(S)); // more than enough
FillChar(PChar(S1)^, Length(S1), 0);
WideCharToMultiByte(932 {shift-jis codepage}, 0, PWideChar(S), Length(S),
PChar(S1), Length(S1), nil, nil);
S1:= PChar(S1); // to remove ending zeroes
Label1.Caption:= S1;
end;
```
When I tested the above code with different fonts the Japanese symbols from the fonts with names starting from '@' appeared rotated 90 degrees counterclockwise compared with the Japanese string from the question. The "Arial Unicode MS" font with SHIFTJIS\_CHARSET gives exact (non-rotated) appearance. | mjn may be correct, but I would strongly advise that if you are going to be handling any kind of Unicode within Delphi, try to persuade your bosses to upgrade to the latest version of Delphi (or just Delphi 2009). The Unicode support in Delphi 2009 is very good, and just works out of the box. If you really cant do this, the [TNT components](http://www.axolot.com/TNT/) worked for us but in the end we just waited for Delphi 2009 to come out because it was so much simpler to have it out of the box from Borland. |
4,836,038 | I need to decode:
```
file://localhost/G:/test/%E6%B0%97%E3%81%BE%E3%81%90%E3%82%8C%E3%83%AD%E3%83%9E%E3%83%B3%E3%83%86%E3%82%A3%E3%83%83%E3%82%AF.mp3
```
into
```
file://localhost/G:/test/気まぐれロマンティック.mp3
```
How to do it in Delphi prior 2009 (I use Delphi 2006) ? | 2011/01/29 | [
"https://Stackoverflow.com/questions/4836038",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/193431/"
] | I've found the solution, I got a pointer here: [delphigroups.info/2/5/209620.html](http://www.delphigroups.info/2/5/209620.html) then experiment with HttpDecode in httpApp.pas, the solution is:
```
TntEdit2.Text := UTF8Decode(HTTPDecode('file://localhost/G:/test/%E6%B0%97%E3%81%BE%E3%81%90%E3%82%8C%E3%83%AD%E3%83%9E%E3%83%B3%E3%83%86%E3%82%A3%E3%83%83%E3%82%AF.mp3'));
``` | mjn may be correct, but I would strongly advise that if you are going to be handling any kind of Unicode within Delphi, try to persuade your bosses to upgrade to the latest version of Delphi (or just Delphi 2009). The Unicode support in Delphi 2009 is very good, and just works out of the box. If you really cant do this, the [TNT components](http://www.axolot.com/TNT/) worked for us but in the end we just waited for Delphi 2009 to come out because it was so much simpler to have it out of the box from Borland. |
38,353,992 | So I am currently reading through [Clean Code](https://rads.stackoverflow.com/amzn/click/com/0132350882) and I really like the idea of super small functions that each tell their own "story". I also really like the way he puts how code should be written to be read in terms of "TO paragraphs", which I've decided to kind of rename in my head to "in order to"
Anyway I have been refactoring alot of code to include more meaningful names and to make the flow in which it will be read a little better and I have stumbled into something that I am unsure on and maybe some gurus here could give me some solid advice!
I know that code-styles is a highly controversial and subjective topic, but hopefully I wont get reamed out by this post.
Thanks everyone!
PSA: I am a noob, fresh out of College creating a web app using the MEAN stack for an internal project in an internship at the moment.
Clean Code refactor
```
//Modal Controller stuff above. vm.task is an instance variable
vm.task = vm.data.task;
castTaskDataTypesForForm();
function castTaskDataTypesForForm() {
castPriorityToInt();
castReminderInHoursToInt();
castDueDateToDate();
getAssigneObjFromAssigneeString();
}
function castPriorityToInt() {
vm.task.priority = vm.task.priority === undefined ?
0 : parseInt(vm.task.priority);
}
function castReminderInHoursToInt() {
vm.task.reminderInHours = vm.task.reminderInHours === undefined ?
0 : parseInt(vm.task.reminderInHours);
}
function castDueDateToDate() {
vm.task.dueDate = new Date(vm.task.dueDate);
}
function getAssigneObjFromAssigneeString() {
vm.task.assignee = getUserFromId(vm.task.assignee);
}
```
Possibly better refactor? / My question ----------------------------
```
//Modal Controller stuff above. vm.task is an instance variable
vm.task = vm.data.task;
castTaskDataTypesForForm();
function castTaskDataTypesForForm() {
castPriorityToInt();
castReminderInHoursToInt();
castDueDateToDate();
getAssigneObjFromAssigneeString();
function castPriorityToInt() {
vm.task.priority = vm.task.priority === undefined ?
0 : parseInt(vm.task.priority);
}
function castReminderInHoursToInt() {
vm.task.reminderInHours = vm.task.reminderInHours === undefined ?
0 : parseInt(vm.task.reminderInHours);
}
function castDueDateToDate() {
vm.task.dueDate = new Date(vm.task.dueDate);
}
function getAssigneObjFromAssigneeString() {
vm.task.assignee = getUserFromId(vm.task.assignee);
}
}
``` | 2016/07/13 | [
"https://Stackoverflow.com/questions/38353992",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1370270/"
] | You should define default router for `''` like:
```
const routes: RouterConfig = [
{ path: '', component: Home },
{ path: 'page2', component: Page2 }
];
```
Or by using redirect:
```
const routes: RouterConfig = [
{ path: '', redirectTo: '/page2', pathMatch: 'full' },
{ path: 'page2', component: Page2 }
];
```
See also the example from angular2 documentation
* <https://angular.io/docs/ts/latest/guide/router.html#!#redirect> | to be my understanding , you want to use as app.ts page default page and loaded page2 by click **Page2**?
**Option1:** *quick solve issue*
By solving your current console error you can add to your *app.route.ts*
```
import { App} from './app';
const routes: RouterConfig = [
{ path: '', component: App, useAsDefault: true }
{ path: 'page2', component: Page2 }
];
```
And Result will be
[](https://i.stack.imgur.com/Z0X0O.png)
But you will see your app.ts html will load two time on load! which is not good way to solve!
**Option2:**
As I use in my project,I recommended you create new home page make as default page .Then call Page2 in app.ts
Here is Plnkr <http://plnkr.co/edit/vzl9lw>
Would it meet your requirement! |
38,353,992 | So I am currently reading through [Clean Code](https://rads.stackoverflow.com/amzn/click/com/0132350882) and I really like the idea of super small functions that each tell their own "story". I also really like the way he puts how code should be written to be read in terms of "TO paragraphs", which I've decided to kind of rename in my head to "in order to"
Anyway I have been refactoring alot of code to include more meaningful names and to make the flow in which it will be read a little better and I have stumbled into something that I am unsure on and maybe some gurus here could give me some solid advice!
I know that code-styles is a highly controversial and subjective topic, but hopefully I wont get reamed out by this post.
Thanks everyone!
PSA: I am a noob, fresh out of College creating a web app using the MEAN stack for an internal project in an internship at the moment.
Clean Code refactor
```
//Modal Controller stuff above. vm.task is an instance variable
vm.task = vm.data.task;
castTaskDataTypesForForm();
function castTaskDataTypesForForm() {
castPriorityToInt();
castReminderInHoursToInt();
castDueDateToDate();
getAssigneObjFromAssigneeString();
}
function castPriorityToInt() {
vm.task.priority = vm.task.priority === undefined ?
0 : parseInt(vm.task.priority);
}
function castReminderInHoursToInt() {
vm.task.reminderInHours = vm.task.reminderInHours === undefined ?
0 : parseInt(vm.task.reminderInHours);
}
function castDueDateToDate() {
vm.task.dueDate = new Date(vm.task.dueDate);
}
function getAssigneObjFromAssigneeString() {
vm.task.assignee = getUserFromId(vm.task.assignee);
}
```
Possibly better refactor? / My question ----------------------------
```
//Modal Controller stuff above. vm.task is an instance variable
vm.task = vm.data.task;
castTaskDataTypesForForm();
function castTaskDataTypesForForm() {
castPriorityToInt();
castReminderInHoursToInt();
castDueDateToDate();
getAssigneObjFromAssigneeString();
function castPriorityToInt() {
vm.task.priority = vm.task.priority === undefined ?
0 : parseInt(vm.task.priority);
}
function castReminderInHoursToInt() {
vm.task.reminderInHours = vm.task.reminderInHours === undefined ?
0 : parseInt(vm.task.reminderInHours);
}
function castDueDateToDate() {
vm.task.dueDate = new Date(vm.task.dueDate);
}
function getAssigneObjFromAssigneeString() {
vm.task.assignee = getUserFromId(vm.task.assignee);
}
}
``` | 2016/07/13 | [
"https://Stackoverflow.com/questions/38353992",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1370270/"
] | You need to specify a route for the case where the user is at the index page of your app, that route is the path '' and it should look like this: `{ path: '', component: MyComponent }`
If you want your default page to be page2 you must tell your index path to redirect to it like this:
```
{ path: 'page2', component: Page2 },
{ path: '', redirectTo: '/page2', pathMatch: 'full' }
```
The order here is important, the most specific route should come first. | to be my understanding , you want to use as app.ts page default page and loaded page2 by click **Page2**?
**Option1:** *quick solve issue*
By solving your current console error you can add to your *app.route.ts*
```
import { App} from './app';
const routes: RouterConfig = [
{ path: '', component: App, useAsDefault: true }
{ path: 'page2', component: Page2 }
];
```
And Result will be
[](https://i.stack.imgur.com/Z0X0O.png)
But you will see your app.ts html will load two time on load! which is not good way to solve!
**Option2:**
As I use in my project,I recommended you create new home page make as default page .Then call Page2 in app.ts
Here is Plnkr <http://plnkr.co/edit/vzl9lw>
Would it meet your requirement! |
855,289 | How to find the limit
$$\lim\_{x \rightarrow \infty} x^{2/3} -(x^2+1)^{1/3}$$
I've tried:
$$\lim x^{2/3} -(x^2+1)^{1/3} = \lim x^{2/3} \cdot \lim \left[1 - \left(1+\frac{1}{x^2}\right)^{1/3} \right] = \infty \cdot 0$$
Any help, please? | 2014/07/03 | [
"https://math.stackexchange.com/questions/855289",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/161448/"
] | Use AM > HM on $\frac{a+b+c}{a+b}, \frac{a+b+c}{b+c}$ and $\frac{a+b+c}{c+a}$. | Here is another nice proof.
We have to prove;
$$\frac{a}{b+c}+\frac{b}{a+c}+\frac{c}{a+b}\geq \frac{3}{2}\\\frac{a+b+c}{b+c}+\frac{a+b+c}{a+c}+\frac{a+b+c}{a+b}\geq \frac{3}{2}+3\\(a+b+c)\left(\frac{1}{b+c}+\frac{1}{a+c}+\frac{1}{a+b}\right)\geq \frac{9}{2}\\([b+c]+[a+c]+[a+b])\left(\frac{1}{b+c}+\frac{1}{a+c}+\frac{1}{a+b}\right)\geq 9\\$$Now we use this well known inequality for $x>0\to x+\frac{1}{x}\geq2$;
(quick proof: $\left (\sqrt x-\frac{1}{\sqrt x}\right )^2\geq0\to x+\frac1x\geq2$)
$$1+1+1+\left[\frac{a+b}{a+c}+\frac{a+c}{a+b}\right]+\left[\frac{a+b}{b+c}+\frac{b+c}{a+b}\right]+\left[\frac{a+c}{b+c}+\frac{b+c}{a+c}\right]\geq 9\\q.e.d.$$ |
855,289 | How to find the limit
$$\lim\_{x \rightarrow \infty} x^{2/3} -(x^2+1)^{1/3}$$
I've tried:
$$\lim x^{2/3} -(x^2+1)^{1/3} = \lim x^{2/3} \cdot \lim \left[1 - \left(1+\frac{1}{x^2}\right)^{1/3} \right] = \infty \cdot 0$$
Any help, please? | 2014/07/03 | [
"https://math.stackexchange.com/questions/855289",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/161448/"
] | By Cauchy-Schwarz $$\begin{align}\sum\_{cyc}\frac{a}{b+c}&=\sum\_{cyc}\left(\frac{a}{b+c}+1\right)-3\\
&=\sum\_{cyc}a\sum\_{cyc}\frac{1}{b+c}-3\\
&=\frac{1}{2}\sum\_{cyc}(b+c)\sum\_{cyc}\frac{1}{b+c}-3\\
&\geq\frac{1}{2}\cdot9-3=\frac{3}{2}.\end{align}$$
Done!
Another way.
By C-S $$\sum\limits\_{cyc}\frac{a}{b+c}=\sum\limits\_{cyc}\frac{a^2}{ab+ac}\geq\frac{(a+b+c)^2}{\sum\limits\_{cyc}(ab+ac)}=\frac{(a+b+c)^2}{2(ab+ac+bc)}\geq\frac{3}{2},$$
where the last inequality it's just $\sum\limits\_{cyc}(a-b)^2\geq0$.
Done!
Another way.
$$\sum\limits\_{cyc}\frac{a}{b+c}-\frac{3}{2}=\sum\limits\_{cyc}\left(\frac{a}{b+c}-\frac{1}{2}\right)=\sum\limits\_{cyc}\frac{2a-b-c}{2(b+c)}=\sum\limits\_{cyc}\frac{a-b-(c-a)}{2(b+c)}=$$
$$=\sum\limits\_{cyc}(a-b)\left(\frac{1}{2(b+c)}-\frac{1}{2(a+c)}\right)=\sum\limits\_{cyc}\frac{(a-b)^2}{2(a+c)(b+c)}\geq0.$$
Done! | We can also use rearrangement inequality to prove it.
$\displaystyle\frac a{b+c}+\frac b{a+c}+\frac c{a+b}$
$\displaystyle=\frac12\left(\left(\frac a{b+c}+\frac b{a+c}+\frac c{a+b}\right)+\left(\frac a{b+c}+\frac b{a+c}+\frac c{a+b}\right)\right)$
$\displaystyle\geq\frac12\left(\left(\frac a{a+c}+\frac b{a+b}+\frac c{b+c}\right)+\left(\frac a{a+b}+\frac b{b+c}+\frac c{a+c}\right)\right)$
$=\dfrac32$ |
855,289 | How to find the limit
$$\lim\_{x \rightarrow \infty} x^{2/3} -(x^2+1)^{1/3}$$
I've tried:
$$\lim x^{2/3} -(x^2+1)^{1/3} = \lim x^{2/3} \cdot \lim \left[1 - \left(1+\frac{1}{x^2}\right)^{1/3} \right] = \infty \cdot 0$$
Any help, please? | 2014/07/03 | [
"https://math.stackexchange.com/questions/855289",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/161448/"
] | By Cauchy-Schwarz $$\begin{align}\sum\_{cyc}\frac{a}{b+c}&=\sum\_{cyc}\left(\frac{a}{b+c}+1\right)-3\\
&=\sum\_{cyc}a\sum\_{cyc}\frac{1}{b+c}-3\\
&=\frac{1}{2}\sum\_{cyc}(b+c)\sum\_{cyc}\frac{1}{b+c}-3\\
&\geq\frac{1}{2}\cdot9-3=\frac{3}{2}.\end{align}$$
Done!
Another way.
By C-S $$\sum\limits\_{cyc}\frac{a}{b+c}=\sum\limits\_{cyc}\frac{a^2}{ab+ac}\geq\frac{(a+b+c)^2}{\sum\limits\_{cyc}(ab+ac)}=\frac{(a+b+c)^2}{2(ab+ac+bc)}\geq\frac{3}{2},$$
where the last inequality it's just $\sum\limits\_{cyc}(a-b)^2\geq0$.
Done!
Another way.
$$\sum\limits\_{cyc}\frac{a}{b+c}-\frac{3}{2}=\sum\limits\_{cyc}\left(\frac{a}{b+c}-\frac{1}{2}\right)=\sum\limits\_{cyc}\frac{2a-b-c}{2(b+c)}=\sum\limits\_{cyc}\frac{a-b-(c-a)}{2(b+c)}=$$
$$=\sum\limits\_{cyc}(a-b)\left(\frac{1}{2(b+c)}-\frac{1}{2(a+c)}\right)=\sum\limits\_{cyc}\frac{(a-b)^2}{2(a+c)(b+c)}\geq0.$$
Done! | Here is another nice proof.
We have to prove;
$$\frac{a}{b+c}+\frac{b}{a+c}+\frac{c}{a+b}\geq \frac{3}{2}\\\frac{a+b+c}{b+c}+\frac{a+b+c}{a+c}+\frac{a+b+c}{a+b}\geq \frac{3}{2}+3\\(a+b+c)\left(\frac{1}{b+c}+\frac{1}{a+c}+\frac{1}{a+b}\right)\geq \frac{9}{2}\\([b+c]+[a+c]+[a+b])\left(\frac{1}{b+c}+\frac{1}{a+c}+\frac{1}{a+b}\right)\geq 9\\$$Now we use this well known inequality for $x>0\to x+\frac{1}{x}\geq2$;
(quick proof: $\left (\sqrt x-\frac{1}{\sqrt x}\right )^2\geq0\to x+\frac1x\geq2$)
$$1+1+1+\left[\frac{a+b}{a+c}+\frac{a+c}{a+b}\right]+\left[\frac{a+b}{b+c}+\frac{b+c}{a+b}\right]+\left[\frac{a+c}{b+c}+\frac{b+c}{a+c}\right]\geq 9\\q.e.d.$$ |
855,289 | How to find the limit
$$\lim\_{x \rightarrow \infty} x^{2/3} -(x^2+1)^{1/3}$$
I've tried:
$$\lim x^{2/3} -(x^2+1)^{1/3} = \lim x^{2/3} \cdot \lim \left[1 - \left(1+\frac{1}{x^2}\right)^{1/3} \right] = \infty \cdot 0$$
Any help, please? | 2014/07/03 | [
"https://math.stackexchange.com/questions/855289",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/161448/"
] | By Cauchy-Schwarz $$\begin{align}\sum\_{cyc}\frac{a}{b+c}&=\sum\_{cyc}\left(\frac{a}{b+c}+1\right)-3\\
&=\sum\_{cyc}a\sum\_{cyc}\frac{1}{b+c}-3\\
&=\frac{1}{2}\sum\_{cyc}(b+c)\sum\_{cyc}\frac{1}{b+c}-3\\
&\geq\frac{1}{2}\cdot9-3=\frac{3}{2}.\end{align}$$
Done!
Another way.
By C-S $$\sum\limits\_{cyc}\frac{a}{b+c}=\sum\limits\_{cyc}\frac{a^2}{ab+ac}\geq\frac{(a+b+c)^2}{\sum\limits\_{cyc}(ab+ac)}=\frac{(a+b+c)^2}{2(ab+ac+bc)}\geq\frac{3}{2},$$
where the last inequality it's just $\sum\limits\_{cyc}(a-b)^2\geq0$.
Done!
Another way.
$$\sum\limits\_{cyc}\frac{a}{b+c}-\frac{3}{2}=\sum\limits\_{cyc}\left(\frac{a}{b+c}-\frac{1}{2}\right)=\sum\limits\_{cyc}\frac{2a-b-c}{2(b+c)}=\sum\limits\_{cyc}\frac{a-b-(c-a)}{2(b+c)}=$$
$$=\sum\limits\_{cyc}(a-b)\left(\frac{1}{2(b+c)}-\frac{1}{2(a+c)}\right)=\sum\limits\_{cyc}\frac{(a-b)^2}{2(a+c)(b+c)}\geq0.$$
Done! | \begin{eqnarray\*}
% \nonumber to remove numbering (before each equation)
&& \frac{x}{y+z}+\frac{y}{z+x}+\frac{z}{x+y}-\frac{3}{2}\\
&=& \frac{2(x^3+y^3+z^3)-(x^2y+xy^2+y^2z+yz^2+z^2x+zx^2)}{2 (x + y) (x + z) (y + z)}\\
&=& \frac{(x+y)(x-y)^2+(y+z)(y-z)^2+(z+x)(z-x)^2}{2 (x + y) (x + z) (y + z)}\geq0
\end{eqnarray\*}
with equality holds if and only if $x=y=z$. |
855,289 | How to find the limit
$$\lim\_{x \rightarrow \infty} x^{2/3} -(x^2+1)^{1/3}$$
I've tried:
$$\lim x^{2/3} -(x^2+1)^{1/3} = \lim x^{2/3} \cdot \lim \left[1 - \left(1+\frac{1}{x^2}\right)^{1/3} \right] = \infty \cdot 0$$
Any help, please? | 2014/07/03 | [
"https://math.stackexchange.com/questions/855289",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/161448/"
] | Use AM > HM on $\frac{a+b+c}{a+b}, \frac{a+b+c}{b+c}$ and $\frac{a+b+c}{c+a}$. | We can also use rearrangement inequality to prove it.
$\displaystyle\frac a{b+c}+\frac b{a+c}+\frac c{a+b}$
$\displaystyle=\frac12\left(\left(\frac a{b+c}+\frac b{a+c}+\frac c{a+b}\right)+\left(\frac a{b+c}+\frac b{a+c}+\frac c{a+b}\right)\right)$
$\displaystyle\geq\frac12\left(\left(\frac a{a+c}+\frac b{a+b}+\frac c{b+c}\right)+\left(\frac a{a+b}+\frac b{b+c}+\frac c{a+c}\right)\right)$
$=\dfrac32$ |
855,289 | How to find the limit
$$\lim\_{x \rightarrow \infty} x^{2/3} -(x^2+1)^{1/3}$$
I've tried:
$$\lim x^{2/3} -(x^2+1)^{1/3} = \lim x^{2/3} \cdot \lim \left[1 - \left(1+\frac{1}{x^2}\right)^{1/3} \right] = \infty \cdot 0$$
Any help, please? | 2014/07/03 | [
"https://math.stackexchange.com/questions/855289",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/161448/"
] | If we denote $s:=a+b+c$, we have to minimize
$$\frac{a}{s-a}+\frac{b}{s-b}+\frac{c}{s-c}$$
for $a,b,c>0$.
Using new variables $x:=a/s$, $y:=b/s$, $z:=c/s$ we can see, that this is equivalent to minimizing
$$\frac{x}{1-x}+\frac{y}{1-y}+\frac{z}{1-z}$$
for $x+y+z=1$.
If we notice that [the function](http://www.wolframalpha.com/input/?i=x%2F%281-x%29)
$$f(x)=\frac{x}{1-x}=-1+\frac1{1-x}=-1-\frac1{x-1}$$
is convex on the interval $(0,1)$, we have
$$\frac{f(x)+f(y)+f(z)}3 \ge f\left(\frac{x+y+z}3\right),$$
i.e.
$$f(x)+f(y)+f(z) \ge 3f(1/3).$$
By computing $f(1/3)=1/2$ we see, that the last inequality is precisely
$$\frac{x}{1-x}+\frac{y}{1-y}+\frac{z}{1-z} \ge \frac32.$$ | Here is another nice proof.
We have to prove;
$$\frac{a}{b+c}+\frac{b}{a+c}+\frac{c}{a+b}\geq \frac{3}{2}\\\frac{a+b+c}{b+c}+\frac{a+b+c}{a+c}+\frac{a+b+c}{a+b}\geq \frac{3}{2}+3\\(a+b+c)\left(\frac{1}{b+c}+\frac{1}{a+c}+\frac{1}{a+b}\right)\geq \frac{9}{2}\\([b+c]+[a+c]+[a+b])\left(\frac{1}{b+c}+\frac{1}{a+c}+\frac{1}{a+b}\right)\geq 9\\$$Now we use this well known inequality for $x>0\to x+\frac{1}{x}\geq2$;
(quick proof: $\left (\sqrt x-\frac{1}{\sqrt x}\right )^2\geq0\to x+\frac1x\geq2$)
$$1+1+1+\left[\frac{a+b}{a+c}+\frac{a+c}{a+b}\right]+\left[\frac{a+b}{b+c}+\frac{b+c}{a+b}\right]+\left[\frac{a+c}{b+c}+\frac{b+c}{a+c}\right]\geq 9\\q.e.d.$$ |
855,289 | How to find the limit
$$\lim\_{x \rightarrow \infty} x^{2/3} -(x^2+1)^{1/3}$$
I've tried:
$$\lim x^{2/3} -(x^2+1)^{1/3} = \lim x^{2/3} \cdot \lim \left[1 - \left(1+\frac{1}{x^2}\right)^{1/3} \right] = \infty \cdot 0$$
Any help, please? | 2014/07/03 | [
"https://math.stackexchange.com/questions/855289",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/161448/"
] | Use AM > HM on $\frac{a+b+c}{a+b}, \frac{a+b+c}{b+c}$ and $\frac{a+b+c}{c+a}$. | By Cauchy-Schwarz $$\begin{align}\sum\_{cyc}\frac{a}{b+c}&=\sum\_{cyc}\left(\frac{a}{b+c}+1\right)-3\\
&=\sum\_{cyc}a\sum\_{cyc}\frac{1}{b+c}-3\\
&=\frac{1}{2}\sum\_{cyc}(b+c)\sum\_{cyc}\frac{1}{b+c}-3\\
&\geq\frac{1}{2}\cdot9-3=\frac{3}{2}.\end{align}$$
Done!
Another way.
By C-S $$\sum\limits\_{cyc}\frac{a}{b+c}=\sum\limits\_{cyc}\frac{a^2}{ab+ac}\geq\frac{(a+b+c)^2}{\sum\limits\_{cyc}(ab+ac)}=\frac{(a+b+c)^2}{2(ab+ac+bc)}\geq\frac{3}{2},$$
where the last inequality it's just $\sum\limits\_{cyc}(a-b)^2\geq0$.
Done!
Another way.
$$\sum\limits\_{cyc}\frac{a}{b+c}-\frac{3}{2}=\sum\limits\_{cyc}\left(\frac{a}{b+c}-\frac{1}{2}\right)=\sum\limits\_{cyc}\frac{2a-b-c}{2(b+c)}=\sum\limits\_{cyc}\frac{a-b-(c-a)}{2(b+c)}=$$
$$=\sum\limits\_{cyc}(a-b)\left(\frac{1}{2(b+c)}-\frac{1}{2(a+c)}\right)=\sum\limits\_{cyc}\frac{(a-b)^2}{2(a+c)(b+c)}\geq0.$$
Done! |
855,289 | How to find the limit
$$\lim\_{x \rightarrow \infty} x^{2/3} -(x^2+1)^{1/3}$$
I've tried:
$$\lim x^{2/3} -(x^2+1)^{1/3} = \lim x^{2/3} \cdot \lim \left[1 - \left(1+\frac{1}{x^2}\right)^{1/3} \right] = \infty \cdot 0$$
Any help, please? | 2014/07/03 | [
"https://math.stackexchange.com/questions/855289",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/161448/"
] | Use AM > HM on $\frac{a+b+c}{a+b}, \frac{a+b+c}{b+c}$ and $\frac{a+b+c}{c+a}$. | \begin{eqnarray\*}
% \nonumber to remove numbering (before each equation)
&& \frac{x}{y+z}+\frac{y}{z+x}+\frac{z}{x+y}-\frac{3}{2}\\
&=& \frac{2(x^3+y^3+z^3)-(x^2y+xy^2+y^2z+yz^2+z^2x+zx^2)}{2 (x + y) (x + z) (y + z)}\\
&=& \frac{(x+y)(x-y)^2+(y+z)(y-z)^2+(z+x)(z-x)^2}{2 (x + y) (x + z) (y + z)}\geq0
\end{eqnarray\*}
with equality holds if and only if $x=y=z$. |
855,289 | How to find the limit
$$\lim\_{x \rightarrow \infty} x^{2/3} -(x^2+1)^{1/3}$$
I've tried:
$$\lim x^{2/3} -(x^2+1)^{1/3} = \lim x^{2/3} \cdot \lim \left[1 - \left(1+\frac{1}{x^2}\right)^{1/3} \right] = \infty \cdot 0$$
Any help, please? | 2014/07/03 | [
"https://math.stackexchange.com/questions/855289",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/161448/"
] | If we denote $s:=a+b+c$, we have to minimize
$$\frac{a}{s-a}+\frac{b}{s-b}+\frac{c}{s-c}$$
for $a,b,c>0$.
Using new variables $x:=a/s$, $y:=b/s$, $z:=c/s$ we can see, that this is equivalent to minimizing
$$\frac{x}{1-x}+\frac{y}{1-y}+\frac{z}{1-z}$$
for $x+y+z=1$.
If we notice that [the function](http://www.wolframalpha.com/input/?i=x%2F%281-x%29)
$$f(x)=\frac{x}{1-x}=-1+\frac1{1-x}=-1-\frac1{x-1}$$
is convex on the interval $(0,1)$, we have
$$\frac{f(x)+f(y)+f(z)}3 \ge f\left(\frac{x+y+z}3\right),$$
i.e.
$$f(x)+f(y)+f(z) \ge 3f(1/3).$$
By computing $f(1/3)=1/2$ we see, that the last inequality is precisely
$$\frac{x}{1-x}+\frac{y}{1-y}+\frac{z}{1-z} \ge \frac32.$$ | \begin{eqnarray\*}
% \nonumber to remove numbering (before each equation)
&& \frac{x}{y+z}+\frac{y}{z+x}+\frac{z}{x+y}-\frac{3}{2}\\
&=& \frac{2(x^3+y^3+z^3)-(x^2y+xy^2+y^2z+yz^2+z^2x+zx^2)}{2 (x + y) (x + z) (y + z)}\\
&=& \frac{(x+y)(x-y)^2+(y+z)(y-z)^2+(z+x)(z-x)^2}{2 (x + y) (x + z) (y + z)}\geq0
\end{eqnarray\*}
with equality holds if and only if $x=y=z$. |
855,289 | How to find the limit
$$\lim\_{x \rightarrow \infty} x^{2/3} -(x^2+1)^{1/3}$$
I've tried:
$$\lim x^{2/3} -(x^2+1)^{1/3} = \lim x^{2/3} \cdot \lim \left[1 - \left(1+\frac{1}{x^2}\right)^{1/3} \right] = \infty \cdot 0$$
Any help, please? | 2014/07/03 | [
"https://math.stackexchange.com/questions/855289",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/161448/"
] | If we denote $s:=a+b+c$, we have to minimize
$$\frac{a}{s-a}+\frac{b}{s-b}+\frac{c}{s-c}$$
for $a,b,c>0$.
Using new variables $x:=a/s$, $y:=b/s$, $z:=c/s$ we can see, that this is equivalent to minimizing
$$\frac{x}{1-x}+\frac{y}{1-y}+\frac{z}{1-z}$$
for $x+y+z=1$.
If we notice that [the function](http://www.wolframalpha.com/input/?i=x%2F%281-x%29)
$$f(x)=\frac{x}{1-x}=-1+\frac1{1-x}=-1-\frac1{x-1}$$
is convex on the interval $(0,1)$, we have
$$\frac{f(x)+f(y)+f(z)}3 \ge f\left(\frac{x+y+z}3\right),$$
i.e.
$$f(x)+f(y)+f(z) \ge 3f(1/3).$$
By computing $f(1/3)=1/2$ we see, that the last inequality is precisely
$$\frac{x}{1-x}+\frac{y}{1-y}+\frac{z}{1-z} \ge \frac32.$$ | We can also use rearrangement inequality to prove it.
$\displaystyle\frac a{b+c}+\frac b{a+c}+\frac c{a+b}$
$\displaystyle=\frac12\left(\left(\frac a{b+c}+\frac b{a+c}+\frac c{a+b}\right)+\left(\frac a{b+c}+\frac b{a+c}+\frac c{a+b}\right)\right)$
$\displaystyle\geq\frac12\left(\left(\frac a{a+c}+\frac b{a+b}+\frac c{b+c}\right)+\left(\frac a{a+b}+\frac b{b+c}+\frac c{a+c}\right)\right)$
$=\dfrac32$ |
2,720,618 | I know it's very basic question and hope not so important, but i want to know the answer, please don't suggest only refer links.
we all daily face `<input>` type tag and their attributes (`type, class, id, value, name, size, maxlength, tabindex etc..`), I just want to know
* is there any specific order required for attributes in `<input>` tag or can we use any order?
* if there an order then what is it? | 2010/04/27 | [
"https://Stackoverflow.com/questions/2720618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/155861/"
] | You can use any sequence | The order of attributes in HTML elements doesn't matter at all. You can write the attributes in any order you like. |
2,720,618 | I know it's very basic question and hope not so important, but i want to know the answer, please don't suggest only refer links.
we all daily face `<input>` type tag and their attributes (`type, class, id, value, name, size, maxlength, tabindex etc..`), I just want to know
* is there any specific order required for attributes in `<input>` tag or can we use any order?
* if there an order then what is it? | 2010/04/27 | [
"https://Stackoverflow.com/questions/2720618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/155861/"
] | You can use any sequence | my preference is: id, name, type, class, attributes (like selected, checked), value |
2,720,618 | I know it's very basic question and hope not so important, but i want to know the answer, please don't suggest only refer links.
we all daily face `<input>` type tag and their attributes (`type, class, id, value, name, size, maxlength, tabindex etc..`), I just want to know
* is there any specific order required for attributes in `<input>` tag or can we use any order?
* if there an order then what is it? | 2010/04/27 | [
"https://Stackoverflow.com/questions/2720618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/155861/"
] | Already been answered, but my full and expanded answer is:
* There is no predefined order for the attributes in terms of passing w3c validation... it's completely up to you.
However, you should introduce your own standard and stick to it.
If there are multiple coders working on the application they should all stick to the same standard.
If you are a team leader, web-dev business owner, manager, etc, it is your responsibility to encourage (and enforce) a culture that uses this standard.
When doing code reviews the attribute order should be checked, and anything that fails you should make the coder responsible fix it up... they'll only muck it up once or twice if they know they'll have to rewrite their code!!!
And why all this fuss and bother over attribute order?
* This will increase code development and debugging speed.
* It makes code more readable
* It encourages the coders (or you) to pay attention to the little details
* It helps to fosters an environment of "accountability for your own code"
My personal preference is:
1. type (so you can instantly see what it is)
2. id
3. class (I like to keep 2 and 3 together as they are the most common js/jQuery selectors)
4. name
5. value (I like to keep 4 and 5 next to each other so you can quickly reference what input it is and it's value).
6. All others (like checked, max-size, etc)
7. style
8. tabindex (I like 7 and 8 to be at the end as it's "non-relevant", in terms of the actual functionality, they are more styling/usability stuff, keep 'em out of the way! | You can use any sequence |
2,720,618 | I know it's very basic question and hope not so important, but i want to know the answer, please don't suggest only refer links.
we all daily face `<input>` type tag and their attributes (`type, class, id, value, name, size, maxlength, tabindex etc..`), I just want to know
* is there any specific order required for attributes in `<input>` tag or can we use any order?
* if there an order then what is it? | 2010/04/27 | [
"https://Stackoverflow.com/questions/2720618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/155861/"
] | You can use any sequence | Here's code guide from [Mark Otto](https://twitter.com/mdo)
[General attribute order guide](http://codeguide.co/#html-attribute-order)
He gives a general guideline to HTML CSS and JS although nothing specific about input tags alone. I think it's a good read. |
2,720,618 | I know it's very basic question and hope not so important, but i want to know the answer, please don't suggest only refer links.
we all daily face `<input>` type tag and their attributes (`type, class, id, value, name, size, maxlength, tabindex etc..`), I just want to know
* is there any specific order required for attributes in `<input>` tag or can we use any order?
* if there an order then what is it? | 2010/04/27 | [
"https://Stackoverflow.com/questions/2720618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/155861/"
] | The order of attributes in HTML elements doesn't matter at all. You can write the attributes in any order you like. | my preference is: id, name, type, class, attributes (like selected, checked), value |
2,720,618 | I know it's very basic question and hope not so important, but i want to know the answer, please don't suggest only refer links.
we all daily face `<input>` type tag and their attributes (`type, class, id, value, name, size, maxlength, tabindex etc..`), I just want to know
* is there any specific order required for attributes in `<input>` tag or can we use any order?
* if there an order then what is it? | 2010/04/27 | [
"https://Stackoverflow.com/questions/2720618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/155861/"
] | Already been answered, but my full and expanded answer is:
* There is no predefined order for the attributes in terms of passing w3c validation... it's completely up to you.
However, you should introduce your own standard and stick to it.
If there are multiple coders working on the application they should all stick to the same standard.
If you are a team leader, web-dev business owner, manager, etc, it is your responsibility to encourage (and enforce) a culture that uses this standard.
When doing code reviews the attribute order should be checked, and anything that fails you should make the coder responsible fix it up... they'll only muck it up once or twice if they know they'll have to rewrite their code!!!
And why all this fuss and bother over attribute order?
* This will increase code development and debugging speed.
* It makes code more readable
* It encourages the coders (or you) to pay attention to the little details
* It helps to fosters an environment of "accountability for your own code"
My personal preference is:
1. type (so you can instantly see what it is)
2. id
3. class (I like to keep 2 and 3 together as they are the most common js/jQuery selectors)
4. name
5. value (I like to keep 4 and 5 next to each other so you can quickly reference what input it is and it's value).
6. All others (like checked, max-size, etc)
7. style
8. tabindex (I like 7 and 8 to be at the end as it's "non-relevant", in terms of the actual functionality, they are more styling/usability stuff, keep 'em out of the way! | The order of attributes in HTML elements doesn't matter at all. You can write the attributes in any order you like. |
2,720,618 | I know it's very basic question and hope not so important, but i want to know the answer, please don't suggest only refer links.
we all daily face `<input>` type tag and their attributes (`type, class, id, value, name, size, maxlength, tabindex etc..`), I just want to know
* is there any specific order required for attributes in `<input>` tag or can we use any order?
* if there an order then what is it? | 2010/04/27 | [
"https://Stackoverflow.com/questions/2720618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/155861/"
] | Already been answered, but my full and expanded answer is:
* There is no predefined order for the attributes in terms of passing w3c validation... it's completely up to you.
However, you should introduce your own standard and stick to it.
If there are multiple coders working on the application they should all stick to the same standard.
If you are a team leader, web-dev business owner, manager, etc, it is your responsibility to encourage (and enforce) a culture that uses this standard.
When doing code reviews the attribute order should be checked, and anything that fails you should make the coder responsible fix it up... they'll only muck it up once or twice if they know they'll have to rewrite their code!!!
And why all this fuss and bother over attribute order?
* This will increase code development and debugging speed.
* It makes code more readable
* It encourages the coders (or you) to pay attention to the little details
* It helps to fosters an environment of "accountability for your own code"
My personal preference is:
1. type (so you can instantly see what it is)
2. id
3. class (I like to keep 2 and 3 together as they are the most common js/jQuery selectors)
4. name
5. value (I like to keep 4 and 5 next to each other so you can quickly reference what input it is and it's value).
6. All others (like checked, max-size, etc)
7. style
8. tabindex (I like 7 and 8 to be at the end as it's "non-relevant", in terms of the actual functionality, they are more styling/usability stuff, keep 'em out of the way! | my preference is: id, name, type, class, attributes (like selected, checked), value |
2,720,618 | I know it's very basic question and hope not so important, but i want to know the answer, please don't suggest only refer links.
we all daily face `<input>` type tag and their attributes (`type, class, id, value, name, size, maxlength, tabindex etc..`), I just want to know
* is there any specific order required for attributes in `<input>` tag or can we use any order?
* if there an order then what is it? | 2010/04/27 | [
"https://Stackoverflow.com/questions/2720618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/155861/"
] | Here's code guide from [Mark Otto](https://twitter.com/mdo)
[General attribute order guide](http://codeguide.co/#html-attribute-order)
He gives a general guideline to HTML CSS and JS although nothing specific about input tags alone. I think it's a good read. | my preference is: id, name, type, class, attributes (like selected, checked), value |
2,720,618 | I know it's very basic question and hope not so important, but i want to know the answer, please don't suggest only refer links.
we all daily face `<input>` type tag and their attributes (`type, class, id, value, name, size, maxlength, tabindex etc..`), I just want to know
* is there any specific order required for attributes in `<input>` tag or can we use any order?
* if there an order then what is it? | 2010/04/27 | [
"https://Stackoverflow.com/questions/2720618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/155861/"
] | Already been answered, but my full and expanded answer is:
* There is no predefined order for the attributes in terms of passing w3c validation... it's completely up to you.
However, you should introduce your own standard and stick to it.
If there are multiple coders working on the application they should all stick to the same standard.
If you are a team leader, web-dev business owner, manager, etc, it is your responsibility to encourage (and enforce) a culture that uses this standard.
When doing code reviews the attribute order should be checked, and anything that fails you should make the coder responsible fix it up... they'll only muck it up once or twice if they know they'll have to rewrite their code!!!
And why all this fuss and bother over attribute order?
* This will increase code development and debugging speed.
* It makes code more readable
* It encourages the coders (or you) to pay attention to the little details
* It helps to fosters an environment of "accountability for your own code"
My personal preference is:
1. type (so you can instantly see what it is)
2. id
3. class (I like to keep 2 and 3 together as they are the most common js/jQuery selectors)
4. name
5. value (I like to keep 4 and 5 next to each other so you can quickly reference what input it is and it's value).
6. All others (like checked, max-size, etc)
7. style
8. tabindex (I like 7 and 8 to be at the end as it's "non-relevant", in terms of the actual functionality, they are more styling/usability stuff, keep 'em out of the way! | Here's code guide from [Mark Otto](https://twitter.com/mdo)
[General attribute order guide](http://codeguide.co/#html-attribute-order)
He gives a general guideline to HTML CSS and JS although nothing specific about input tags alone. I think it's a good read. |
27,736,680 | How can I transform the string "Test(5)" into "Test\(5\)" dynamically? (JQuery or Javascript)
I have tried this but with no success
```
var string = "Test(5)";
string = string.replace("(","\(");
string = string.replace(")","\)");
console.log(string);
```
<http://jsfiddle.net/mvehkkfe/> | 2015/01/02 | [
"https://Stackoverflow.com/questions/27736680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3115251/"
] | I assume you meant
>
> replace the string "Test(5)" into "Test\(5\)"
>
>
>
In which case:
```
var string = "Test(5)";
string = string.replace("(","\\(");
string = string.replace(")","\\)");
console.log(string);
```
Escape the backslash | If you want to replace the string "Test(5)" into "Test\(5\)", you can use below code
```
var string = "Test(5)";
string = string.replace("(","\\(");
string = string.replace(")","\\)");
console.log(string);
``` |
58,701,672 | The `create_mileage(exclude=None)` function creates a new two-dimensional dictionary with data from the three-dimensional `VEHICLES` dictionary and the default `"unknown"` value.
The `exclude` parameter can contain a dictionary with key-value pairs to be excluded from the new dictionary. Unfortunately this does not work like this.
Code:
```
VEHICLES = {"car": {
"VW Polo": {"power": 75,
"color": "blue"},
"BMW 5 series": {"power": 400,
"color": "black"}},
"truck": {
"MAN TGL": {"power": 200,
"color": "red"},
"Mercedes-Benz Actros": {"power": 500,
"color": "white"}},
"bus": {
"Mercedes-Benz Citaro": {"power": 300,
"color": "yellow"},
"Solaris Vacanza 13": {"power": 400,
"color": "green"}}
}
def create_mileage(exclude=None):
result = dict()
for vehicle_type, vehicle_model in VEHICLES.items():
if {vehicle_type: vehicle_model} not in exclude.items(): # Doesn't work
result[vehicle_type] = dict.fromkeys(vehicle_model, "unknown")
return result
print(create_mileage({"car": "VW Polo", "truck": "Mercedes-Benz Actros"}))
```
The output should be as follows...
```
{'car': {'BMW 5 series': 'unknown'}, 'truck': {'MAN TGL': 'unknown'}, 'bus': {'Mercedes-Benz Citaro': 'unknown', 'Solaris Vacanza 13': 'unknown'}}
```
...but it is as follows.
```
{'car': {'VW Polo': 'unknown', 'BMW 5 series': 'unknown'}, 'truck': {'MAN TGL': 'unknown', 'Mercedes-Benz Actros': 'unknown'}, 'bus': {'Mercedes-Benz Citaro': 'unknown', 'Solaris Vacanza 13': 'unknown'}}
```
What needs to be changed to make the code work as intended? | 2019/11/04 | [
"https://Stackoverflow.com/questions/58701672",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7481773/"
] | `items()` returns a `tuple`, not a `dict`:
```
def create_mileage(exclude=None):
result = dict()
eItems = exclude.items()
for vehicle_type, vehicle_model in VEHICLES.items():
if (vehicle_type, vehicle_model) not in eItems:
result[vehicle_type] = dict.fromkeys(vehicle_model, "unknown")
return result
print(create_mileage({"car": "VW Polo", "truck": "Mercedes-Benz Actros"}))
```
Result:
>
> {'car': {'VW Polo': 'unknown', 'BMW 5 series': 'unknown'}, 'truck': {'MAN TGL': 'unknown', 'Mercedes-Benz Actros': 'unknown'}, 'bus': {'Mercedes-Benz Citaro': 'unknown', 'Solaris Vacanza 13': 'unknown'}}
>
>
> | `dict.items()` returns the key:value pairs as tuples, not dictionaries.
```
print({'a':1} in {'a':1,'b':2}.items())
False
print(('a',1) in {'a':1,'b':2}.items())
True
```
You're checking for `{vehicle_type: vehicle_model}`, try checking for `(vehicle_type, vehicle_model)` instead |
2,602,791 | I'm trying to figure out the best way to use agents to consume items from a Message Queue (Amazon SQS). Right now I have a function (process-queue-item) that grabs an items from the queue, and processes it.
I want to process these items concurrently, but I can't wrap my head around how to control the agents. Basically I want to keep all of the agents busy as much as possible without pulling to many items from the Queue and developing a backlog (I'll have this running on a couple of machines, so items need to be left in the queue until they are really needed).
Can anyone give me some pointers on improving my implementation?
```
(def active-agents (ref 0))
(defn process-queue-item [_]
(dosync (alter active-agents inc))
;retrieve item from Message Queue (Amazon SQS) and process
(dosync (alter active-agents dec)))
(defn -main []
(def agents (for [x (range 20)] (agent x)))
(loop [loop-count 0]
(if (< @active-agents 20)
(doseq [agent agents]
(if (agent-errors agent)
(clear-agent-errors agent))
;should skip this agent until later if it is still busy processing (not sure how)
(send-off agent process-queue-item)))
;(apply await-for (* 10 1000) agents)
(Thread/sleep 10000)
(logging/info (str "ACTIVE AGENTS " @active-agents))
(if (> 10 loop-count)
(do (logging/info (str "done, let's cleanup " count))
(doseq [agent agents]
(if (agent-errors agent)
(clear-agent-errors agent)))
(apply await agents)
(shutdown-agents))
(recur (inc count)))))
``` | 2010/04/08 | [
"https://Stackoverflow.com/questions/2602791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/126617/"
] | What you are asking for is a way to keep handing out tasks but with some upper limit. One simple approach to this is to use a semaphore to coordinate the limit. Here is how I would approach it:
```
(let [limit (.availableProcessors (Runtime/getRuntime))
; note: you might choose limit 20 based upon your problem description
sem (java.util.concurrent.Semaphore. limit)]
(defn submit-future-call
"Takes a function of no args and yields a future object that will
invoke the function in another thread, and will cache the result and
return it on all subsequent calls to deref/@. If the computation has
not yet finished, calls to deref/@ will block.
If n futures have already been submitted, then submit-future blocks
until the completion of another future, where n is the number of
available processors."
[#^Callable task]
; take a slot (or block until a slot is free)
(.acquire sem)
(try
; create a future that will free a slot on completion
(future (try (task) (finally (.release sem))))
(catch java.util.concurrent.RejectedExecutionException e
; no task was actually submitted
(.release sem)
(throw e)))))
(defmacro submit-future
"Takes a body of expressions and yields a future object that will
invoke the body in another thread, and will cache the result and
return it on all subsequent calls to deref/@. If the computation has
not yet finished, calls to deref/@ will block.
If n futures have already been submitted, then submit-future blocks
until the completion of another future, where n is the number of
available processors."
[& body] `(submit-future-call (fn [] ~@body)))
#_(example
user=> (submit-future (reduce + (range 100000000)))
#<core$future_call$reify__5782@6c69d02b: :pending>
user=> (submit-future (reduce + (range 100000000)))
#<core$future_call$reify__5782@38827968: :pending>
user=> (submit-future (reduce + (range 100000000)))
;; blocks at this point for a 2 processor PC until the previous
;; two futures complete
#<core$future_call$reify__5782@214c4ac9: :pending>
;; then submits the job
```
With that in place now you just need to coordinate how the tasks themselves are taken. It sounds like you already have the mechanisms in place to do that. Loop (submit-future (process-queue-item)) | Perhaps you could use the `seque` function? Quoting `(doc seque)`:
```
clojure.core/seque
([s] [n-or-q s])
Creates a queued seq on another (presumably lazy) seq s. The queued
seq will produce a concrete seq in the background, and can get up to
n items ahead of the consumer. n-or-q can be an integer n buffer
size, or an instance of java.util.concurrent BlockingQueue. Note
that reading from a seque can block if the reader gets ahead of the
producer.
```
What I have in mind is a lazy sequence getting queue items over the network; you'd wrap this in `seque`, put that in a Ref and have worker Agents consume items off of this `seque`. `seque` returns something which looks just like a regular seq from the point of view of your code, with the queue magic happening in a transparent way. Note that if the sequence you put inside is chunked, then it'll still be forced a chunk at a time. Also note that the initial call to `seque` itself seems to block until an initial item or two is obtained (or a chunk, as the case may be; I think that's more to do with the way lazy sequences work than `seque` itself, though).
A sketch of the code (a *really* sketchy one, not tested at all):
```
(defn get-queue-items-seq []
(lazy-seq
(cons (get-queue-item)
(get-queue-items-seq))))
(def task-source (ref (seque (get-queue-items-seq))))
(defn do-stuff []
(let [worker (agent nil)]
(if-let [result
(dosync
(when-let [task (first @task-source)]
(send worker (fn [_] (do-stuff-with task)))))]
(do (await worker)
;; maybe do something with worker's state
(do-stuff))))) ;; continue working
(defn do-lots-of-stuff []
(let [fs (doall (repeatedly 20 #(future (do-stuff))))]
fs)))
```
Actually you'd probably want a more complex producer of the queue item seq so that you can ask it to stop producing new items (a necessity if the whole thing is to be able to be shut down gracefully; the futures will die when the task source runs dry, use `future-done?` to see if they've done so already). And that's just something I can see at first glance... I'm sure there's more things to polish here. I think that the general approach would work, though. |
2,602,791 | I'm trying to figure out the best way to use agents to consume items from a Message Queue (Amazon SQS). Right now I have a function (process-queue-item) that grabs an items from the queue, and processes it.
I want to process these items concurrently, but I can't wrap my head around how to control the agents. Basically I want to keep all of the agents busy as much as possible without pulling to many items from the Queue and developing a backlog (I'll have this running on a couple of machines, so items need to be left in the queue until they are really needed).
Can anyone give me some pointers on improving my implementation?
```
(def active-agents (ref 0))
(defn process-queue-item [_]
(dosync (alter active-agents inc))
;retrieve item from Message Queue (Amazon SQS) and process
(dosync (alter active-agents dec)))
(defn -main []
(def agents (for [x (range 20)] (agent x)))
(loop [loop-count 0]
(if (< @active-agents 20)
(doseq [agent agents]
(if (agent-errors agent)
(clear-agent-errors agent))
;should skip this agent until later if it is still busy processing (not sure how)
(send-off agent process-queue-item)))
;(apply await-for (* 10 1000) agents)
(Thread/sleep 10000)
(logging/info (str "ACTIVE AGENTS " @active-agents))
(if (> 10 loop-count)
(do (logging/info (str "done, let's cleanup " count))
(doseq [agent agents]
(if (agent-errors agent)
(clear-agent-errors agent)))
(apply await agents)
(shutdown-agents))
(recur (inc count)))))
``` | 2010/04/08 | [
"https://Stackoverflow.com/questions/2602791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/126617/"
] | ```
(let [switch (atom true) ; a switch to stop workers
workers (doall
(repeatedly 20 ; 20 workers pulling and processing items from SQS
#(future (while @switch
(retrieve item from Amazon SQS and process)))))]
(Thread/sleep 100000) ; arbitrary rule to decide when to stop ;-)
(reset! switch false) ; stop !
(doseq [worker workers] @worker)) ; waiting for all workers to be done
``` | What you are asking for is a way to keep handing out tasks but with some upper limit. One simple approach to this is to use a semaphore to coordinate the limit. Here is how I would approach it:
```
(let [limit (.availableProcessors (Runtime/getRuntime))
; note: you might choose limit 20 based upon your problem description
sem (java.util.concurrent.Semaphore. limit)]
(defn submit-future-call
"Takes a function of no args and yields a future object that will
invoke the function in another thread, and will cache the result and
return it on all subsequent calls to deref/@. If the computation has
not yet finished, calls to deref/@ will block.
If n futures have already been submitted, then submit-future blocks
until the completion of another future, where n is the number of
available processors."
[#^Callable task]
; take a slot (or block until a slot is free)
(.acquire sem)
(try
; create a future that will free a slot on completion
(future (try (task) (finally (.release sem))))
(catch java.util.concurrent.RejectedExecutionException e
; no task was actually submitted
(.release sem)
(throw e)))))
(defmacro submit-future
"Takes a body of expressions and yields a future object that will
invoke the body in another thread, and will cache the result and
return it on all subsequent calls to deref/@. If the computation has
not yet finished, calls to deref/@ will block.
If n futures have already been submitted, then submit-future blocks
until the completion of another future, where n is the number of
available processors."
[& body] `(submit-future-call (fn [] ~@body)))
#_(example
user=> (submit-future (reduce + (range 100000000)))
#<core$future_call$reify__5782@6c69d02b: :pending>
user=> (submit-future (reduce + (range 100000000)))
#<core$future_call$reify__5782@38827968: :pending>
user=> (submit-future (reduce + (range 100000000)))
;; blocks at this point for a 2 processor PC until the previous
;; two futures complete
#<core$future_call$reify__5782@214c4ac9: :pending>
;; then submits the job
```
With that in place now you just need to coordinate how the tasks themselves are taken. It sounds like you already have the mechanisms in place to do that. Loop (submit-future (process-queue-item)) |
2,602,791 | I'm trying to figure out the best way to use agents to consume items from a Message Queue (Amazon SQS). Right now I have a function (process-queue-item) that grabs an items from the queue, and processes it.
I want to process these items concurrently, but I can't wrap my head around how to control the agents. Basically I want to keep all of the agents busy as much as possible without pulling to many items from the Queue and developing a backlog (I'll have this running on a couple of machines, so items need to be left in the queue until they are really needed).
Can anyone give me some pointers on improving my implementation?
```
(def active-agents (ref 0))
(defn process-queue-item [_]
(dosync (alter active-agents inc))
;retrieve item from Message Queue (Amazon SQS) and process
(dosync (alter active-agents dec)))
(defn -main []
(def agents (for [x (range 20)] (agent x)))
(loop [loop-count 0]
(if (< @active-agents 20)
(doseq [agent agents]
(if (agent-errors agent)
(clear-agent-errors agent))
;should skip this agent until later if it is still busy processing (not sure how)
(send-off agent process-queue-item)))
;(apply await-for (* 10 1000) agents)
(Thread/sleep 10000)
(logging/info (str "ACTIVE AGENTS " @active-agents))
(if (> 10 loop-count)
(do (logging/info (str "done, let's cleanup " count))
(doseq [agent agents]
(if (agent-errors agent)
(clear-agent-errors agent)))
(apply await agents)
(shutdown-agents))
(recur (inc count)))))
``` | 2010/04/08 | [
"https://Stackoverflow.com/questions/2602791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/126617/"
] | What you are asking for is a way to keep handing out tasks but with some upper limit. One simple approach to this is to use a semaphore to coordinate the limit. Here is how I would approach it:
```
(let [limit (.availableProcessors (Runtime/getRuntime))
; note: you might choose limit 20 based upon your problem description
sem (java.util.concurrent.Semaphore. limit)]
(defn submit-future-call
"Takes a function of no args and yields a future object that will
invoke the function in another thread, and will cache the result and
return it on all subsequent calls to deref/@. If the computation has
not yet finished, calls to deref/@ will block.
If n futures have already been submitted, then submit-future blocks
until the completion of another future, where n is the number of
available processors."
[#^Callable task]
; take a slot (or block until a slot is free)
(.acquire sem)
(try
; create a future that will free a slot on completion
(future (try (task) (finally (.release sem))))
(catch java.util.concurrent.RejectedExecutionException e
; no task was actually submitted
(.release sem)
(throw e)))))
(defmacro submit-future
"Takes a body of expressions and yields a future object that will
invoke the body in another thread, and will cache the result and
return it on all subsequent calls to deref/@. If the computation has
not yet finished, calls to deref/@ will block.
If n futures have already been submitted, then submit-future blocks
until the completion of another future, where n is the number of
available processors."
[& body] `(submit-future-call (fn [] ~@body)))
#_(example
user=> (submit-future (reduce + (range 100000000)))
#<core$future_call$reify__5782@6c69d02b: :pending>
user=> (submit-future (reduce + (range 100000000)))
#<core$future_call$reify__5782@38827968: :pending>
user=> (submit-future (reduce + (range 100000000)))
;; blocks at this point for a 2 processor PC until the previous
;; two futures complete
#<core$future_call$reify__5782@214c4ac9: :pending>
;; then submits the job
```
With that in place now you just need to coordinate how the tasks themselves are taken. It sounds like you already have the mechanisms in place to do that. Loop (submit-future (process-queue-item)) | Not sure how idiomatic this is, as I'm still a newbie with the language, but the following solution works for me:
```
(let [number-of-messages-per-time 2
await-timeout 1000]
(doseq [p-messages (partition number-of-messages-per-time messages)]
(let [agents (map agent p-messages)]
(doseq [a agents] (send-off a process))
(apply await-for await-timeout agents)
(map deref agents))))
``` |
2,602,791 | I'm trying to figure out the best way to use agents to consume items from a Message Queue (Amazon SQS). Right now I have a function (process-queue-item) that grabs an items from the queue, and processes it.
I want to process these items concurrently, but I can't wrap my head around how to control the agents. Basically I want to keep all of the agents busy as much as possible without pulling to many items from the Queue and developing a backlog (I'll have this running on a couple of machines, so items need to be left in the queue until they are really needed).
Can anyone give me some pointers on improving my implementation?
```
(def active-agents (ref 0))
(defn process-queue-item [_]
(dosync (alter active-agents inc))
;retrieve item from Message Queue (Amazon SQS) and process
(dosync (alter active-agents dec)))
(defn -main []
(def agents (for [x (range 20)] (agent x)))
(loop [loop-count 0]
(if (< @active-agents 20)
(doseq [agent agents]
(if (agent-errors agent)
(clear-agent-errors agent))
;should skip this agent until later if it is still busy processing (not sure how)
(send-off agent process-queue-item)))
;(apply await-for (* 10 1000) agents)
(Thread/sleep 10000)
(logging/info (str "ACTIVE AGENTS " @active-agents))
(if (> 10 loop-count)
(do (logging/info (str "done, let's cleanup " count))
(doseq [agent agents]
(if (agent-errors agent)
(clear-agent-errors agent)))
(apply await agents)
(shutdown-agents))
(recur (inc count)))))
``` | 2010/04/08 | [
"https://Stackoverflow.com/questions/2602791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/126617/"
] | ```
(let [switch (atom true) ; a switch to stop workers
workers (doall
(repeatedly 20 ; 20 workers pulling and processing items from SQS
#(future (while @switch
(retrieve item from Amazon SQS and process)))))]
(Thread/sleep 100000) ; arbitrary rule to decide when to stop ;-)
(reset! switch false) ; stop !
(doseq [worker workers] @worker)) ; waiting for all workers to be done
``` | Perhaps you could use the `seque` function? Quoting `(doc seque)`:
```
clojure.core/seque
([s] [n-or-q s])
Creates a queued seq on another (presumably lazy) seq s. The queued
seq will produce a concrete seq in the background, and can get up to
n items ahead of the consumer. n-or-q can be an integer n buffer
size, or an instance of java.util.concurrent BlockingQueue. Note
that reading from a seque can block if the reader gets ahead of the
producer.
```
What I have in mind is a lazy sequence getting queue items over the network; you'd wrap this in `seque`, put that in a Ref and have worker Agents consume items off of this `seque`. `seque` returns something which looks just like a regular seq from the point of view of your code, with the queue magic happening in a transparent way. Note that if the sequence you put inside is chunked, then it'll still be forced a chunk at a time. Also note that the initial call to `seque` itself seems to block until an initial item or two is obtained (or a chunk, as the case may be; I think that's more to do with the way lazy sequences work than `seque` itself, though).
A sketch of the code (a *really* sketchy one, not tested at all):
```
(defn get-queue-items-seq []
(lazy-seq
(cons (get-queue-item)
(get-queue-items-seq))))
(def task-source (ref (seque (get-queue-items-seq))))
(defn do-stuff []
(let [worker (agent nil)]
(if-let [result
(dosync
(when-let [task (first @task-source)]
(send worker (fn [_] (do-stuff-with task)))))]
(do (await worker)
;; maybe do something with worker's state
(do-stuff))))) ;; continue working
(defn do-lots-of-stuff []
(let [fs (doall (repeatedly 20 #(future (do-stuff))))]
fs)))
```
Actually you'd probably want a more complex producer of the queue item seq so that you can ask it to stop producing new items (a necessity if the whole thing is to be able to be shut down gracefully; the futures will die when the task source runs dry, use `future-done?` to see if they've done so already). And that's just something I can see at first glance... I'm sure there's more things to polish here. I think that the general approach would work, though. |
2,602,791 | I'm trying to figure out the best way to use agents to consume items from a Message Queue (Amazon SQS). Right now I have a function (process-queue-item) that grabs an items from the queue, and processes it.
I want to process these items concurrently, but I can't wrap my head around how to control the agents. Basically I want to keep all of the agents busy as much as possible without pulling to many items from the Queue and developing a backlog (I'll have this running on a couple of machines, so items need to be left in the queue until they are really needed).
Can anyone give me some pointers on improving my implementation?
```
(def active-agents (ref 0))
(defn process-queue-item [_]
(dosync (alter active-agents inc))
;retrieve item from Message Queue (Amazon SQS) and process
(dosync (alter active-agents dec)))
(defn -main []
(def agents (for [x (range 20)] (agent x)))
(loop [loop-count 0]
(if (< @active-agents 20)
(doseq [agent agents]
(if (agent-errors agent)
(clear-agent-errors agent))
;should skip this agent until later if it is still busy processing (not sure how)
(send-off agent process-queue-item)))
;(apply await-for (* 10 1000) agents)
(Thread/sleep 10000)
(logging/info (str "ACTIVE AGENTS " @active-agents))
(if (> 10 loop-count)
(do (logging/info (str "done, let's cleanup " count))
(doseq [agent agents]
(if (agent-errors agent)
(clear-agent-errors agent)))
(apply await agents)
(shutdown-agents))
(recur (inc count)))))
``` | 2010/04/08 | [
"https://Stackoverflow.com/questions/2602791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/126617/"
] | Perhaps you could use the `seque` function? Quoting `(doc seque)`:
```
clojure.core/seque
([s] [n-or-q s])
Creates a queued seq on another (presumably lazy) seq s. The queued
seq will produce a concrete seq in the background, and can get up to
n items ahead of the consumer. n-or-q can be an integer n buffer
size, or an instance of java.util.concurrent BlockingQueue. Note
that reading from a seque can block if the reader gets ahead of the
producer.
```
What I have in mind is a lazy sequence getting queue items over the network; you'd wrap this in `seque`, put that in a Ref and have worker Agents consume items off of this `seque`. `seque` returns something which looks just like a regular seq from the point of view of your code, with the queue magic happening in a transparent way. Note that if the sequence you put inside is chunked, then it'll still be forced a chunk at a time. Also note that the initial call to `seque` itself seems to block until an initial item or two is obtained (or a chunk, as the case may be; I think that's more to do with the way lazy sequences work than `seque` itself, though).
A sketch of the code (a *really* sketchy one, not tested at all):
```
(defn get-queue-items-seq []
(lazy-seq
(cons (get-queue-item)
(get-queue-items-seq))))
(def task-source (ref (seque (get-queue-items-seq))))
(defn do-stuff []
(let [worker (agent nil)]
(if-let [result
(dosync
(when-let [task (first @task-source)]
(send worker (fn [_] (do-stuff-with task)))))]
(do (await worker)
;; maybe do something with worker's state
(do-stuff))))) ;; continue working
(defn do-lots-of-stuff []
(let [fs (doall (repeatedly 20 #(future (do-stuff))))]
fs)))
```
Actually you'd probably want a more complex producer of the queue item seq so that you can ask it to stop producing new items (a necessity if the whole thing is to be able to be shut down gracefully; the futures will die when the task source runs dry, use `future-done?` to see if they've done so already). And that's just something I can see at first glance... I'm sure there's more things to polish here. I think that the general approach would work, though. | Not sure how idiomatic this is, as I'm still a newbie with the language, but the following solution works for me:
```
(let [number-of-messages-per-time 2
await-timeout 1000]
(doseq [p-messages (partition number-of-messages-per-time messages)]
(let [agents (map agent p-messages)]
(doseq [a agents] (send-off a process))
(apply await-for await-timeout agents)
(map deref agents))))
``` |
2,602,791 | I'm trying to figure out the best way to use agents to consume items from a Message Queue (Amazon SQS). Right now I have a function (process-queue-item) that grabs an items from the queue, and processes it.
I want to process these items concurrently, but I can't wrap my head around how to control the agents. Basically I want to keep all of the agents busy as much as possible without pulling to many items from the Queue and developing a backlog (I'll have this running on a couple of machines, so items need to be left in the queue until they are really needed).
Can anyone give me some pointers on improving my implementation?
```
(def active-agents (ref 0))
(defn process-queue-item [_]
(dosync (alter active-agents inc))
;retrieve item from Message Queue (Amazon SQS) and process
(dosync (alter active-agents dec)))
(defn -main []
(def agents (for [x (range 20)] (agent x)))
(loop [loop-count 0]
(if (< @active-agents 20)
(doseq [agent agents]
(if (agent-errors agent)
(clear-agent-errors agent))
;should skip this agent until later if it is still busy processing (not sure how)
(send-off agent process-queue-item)))
;(apply await-for (* 10 1000) agents)
(Thread/sleep 10000)
(logging/info (str "ACTIVE AGENTS " @active-agents))
(if (> 10 loop-count)
(do (logging/info (str "done, let's cleanup " count))
(doseq [agent agents]
(if (agent-errors agent)
(clear-agent-errors agent)))
(apply await agents)
(shutdown-agents))
(recur (inc count)))))
``` | 2010/04/08 | [
"https://Stackoverflow.com/questions/2602791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/126617/"
] | ```
(let [switch (atom true) ; a switch to stop workers
workers (doall
(repeatedly 20 ; 20 workers pulling and processing items from SQS
#(future (while @switch
(retrieve item from Amazon SQS and process)))))]
(Thread/sleep 100000) ; arbitrary rule to decide when to stop ;-)
(reset! switch false) ; stop !
(doseq [worker workers] @worker)) ; waiting for all workers to be done
``` | Not sure how idiomatic this is, as I'm still a newbie with the language, but the following solution works for me:
```
(let [number-of-messages-per-time 2
await-timeout 1000]
(doseq [p-messages (partition number-of-messages-per-time messages)]
(let [agents (map agent p-messages)]
(doseq [a agents] (send-off a process))
(apply await-for await-timeout agents)
(map deref agents))))
``` |
26,487,801 | **What's been done so far:**
* I was on Django 1.5 and upgraded to 1.6 (cannot go higher as we are on Python 2.6) and this did not solve the problem.
* I have researched this issue to death and cannot seem to find a definite answer. Looking through the Django Project Bug Tracker, I have seen similar issues but none seem to fit my particular case
* I have resolved the problem in the past using a raw SQL call to replace for example `affpart.damage_types.all()` with a custom function but this is starting to happen more frequently now and is becoming a real pain.
**Description:**
I have two Django apps under one project. One of the apps makes use of models in another app using a many-to-many relationship.
This has been working smoothly for months, and in fact it works fine on my production machine but fails on my development machine. The scenario lately has been that I am asked to add a new feature and when I start to work on it I get a `FieldError` in related code which I haven't even touched.
The offending line of code for this latest issue is:
`for dt in affpart.damage_types.all()`
The error is:
```
Cannot resolve keyword u'affectedpart' into field. Choices are: cgs_damage_code, description, id, reg_exp, sti
```
The error occurs in the bowels of Django in the `query.py` module.
From a high-level, this error occurs when I am trying to use a Many-to-many between models in different Django apps. For example, an affected part can have more than one type of damage and a damage type can be found on different affected parts.
The two apps are: `trending` and `sitar`
`sitar` was built first and has the models that I want to use from trending.
In `trending`, my `models.py` file has an `AffectedPart` model something like this:
```
from sitar.models import (Part, DamageType, Aircraft)
# this model is in trendin.models
class AffectedPart(models.Model):
res = models.ForeignKey(Res, null=True)
arising = models.ForeignKey(Arising, null=True)
aircraft = models.ForeignKey(Aircraft)
# filled out automatically only if part to Damage/Repair type matching done
maintenance_phase = models.CharField(max_length=10,
choices=MAINTENANCE_PHASE_CHOICES)
occurrence_date = models.DateField()
partnumber = models.ForeignKey(Part)
damage_types = models.ManyToManyField(DamageType, null=True, blank=True)
repair_types = models.ManyToManyField(RepairType, null=True, blank=True)
def __unicode__(self, ):
if self.res:
parent = self.res.number
else:
parent = str(self.arising)
return '{0} - {1}'.format(self.partnumber.number, parent)
# The following models are in sitar.models
class Part(models.Model):
''' This model is used to create pick-lists so the user can associate
one or more applicable parts from a pre-defined list to
a tracked item.
It will also allow for regular CRUD functionality which is
implemented by taking advantage of the Django admin interface. '''
# Added to associate a zone with a part
zones = models.ManyToManyField("Zone", null=True, blank=True)
number = models.CharField(max_length=50, unique=True)
description = models.CharField(max_length=100, blank=True)
comments = models.TextField(blank=True)
material = models.CharField(max_length=100, blank=True)
class Meta:
''' Order by part number field (ascending) when presenting data '''
ordering = ['number']
def __unicode__(self):
''' Return unicode description of a part instance '''
if self.description:
return '%s -- %s' % (self.number, self.description)
else:
return self.number
def get_encoded_part_number(self):
'''
This method will remove any '/' in part numbers and replace them
with '~' so that they can be used in URLs.
'''
return self.number.replace('/','~')
class DamageType(models.Model):
description = models.CharField(max_length=50, unique=True)
# a regular expression to account for possible spelling mistakes when
# querying the database
reg_exp = models.CharField(max_length=50, blank=True)
# Added to provide damage code for TRENDING
cgs_damage_code = models.CharField(max_length=10, blank=True,
verbose_name="CGS Damage Code")
def __unicode__(self):
''' Return unicode representation of a DamageType instance. '''
return self.description
class Meta:
''' Order by description field (ascending) when presenting data '''
ordering = ['description']
def save(self):
''' Override the save method of the DamageType model in order to assign
a regexp if one does not exist.'''
# if the tracked item does not have a reg_exp just use
# the description
if not self.reg_exp:
self.reg_exp = self.description
super(DamageType,self).save()
```
Stack Trace
```
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/trending/trend/
Django Version: 1.6
Python Version: 2.6.7
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'sitar')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
Traceback:
File "C:\virtual_env\sitar_env2\lib\site-packages\django\core\handlers\base.py" in get_response
114. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\virtual_env\sitar_env2\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
22. return view_func(request, *args, **kwargs)
File "C:\virtual_env\sitar_env2\cissimp\trending\views.py" in trend
418. list_result = utils.convert_queryset_to_lists(q_results, form)
File "C:\virtual_env\sitar_env2\cissimp\trending\utils.py" in convert_queryset_to_lists
918. for dt in affpart.damage_types.all()]),
File "C:\virtual_env\sitar_env2\lib\site-packages\django\db\models\manager.py" in all
133. return self.get_queryset()
File "C:\virtual_env\sitar_env2\lib\site-packages\django\db\models\fields\related.py" in get_queryset
539. return super(ManyRelatedManager, self).get_queryset().using(db)._next_is_sticky().filter(**self.core_filters)
File "C:\virtual_env\sitar_env2\lib\site-packages\django\db\models\query.py" in filter
590. return self._filter_or_exclude(False, *args, **kwargs)
File "C:\virtual_env\sitar_env2\lib\site-packages\django\db\models\query.py" in _filter_or_exclude
608. clone.query.add_q(Q(*args, **kwargs))
File "C:\virtual_env\sitar_env2\lib\site-packages\django\db\models\sql\query.py" in add_q
1198. clause = self._add_q(where_part, used_aliases)
File "C:\virtual_env\sitar_env2\lib\site-packages\django\db\models\sql\query.py" in _add_q
1232. current_negated=current_negated)
File "C:\virtual_env\sitar_env2\lib\site-packages\django\db\models\sql\query.py" in build_filter
1100. allow_explicit_fk=True)
File "C:\virtual_env\sitar_env2\lib\site-packages\django\db\models\sql\query.py" in setup_joins
1351. names, opts, allow_many, allow_explicit_fk)
File "C:\virtual_env\sitar_env2\lib\site-packages\django\db\models\sql\query.py" in names_to_path
1274. "Choices are: %s" % (name, ", ".join(available)))
Exception Type: FieldError at /trending/trend/
Exception Value: Cannot resolve keyword u'affectedpart' into field. Choices are: cgs_damage_code, description, id, reg_exp, sti
```
If anyone has a solution to this or knows of best practices for models in one application having many-to-many relationships with models in another application I would love to hear it.
Thanks | 2014/10/21 | [
"https://Stackoverflow.com/questions/26487801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/898635/"
] | Use [NSSound](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/ApplicationKit/Classes/NSSound_Class/) instead:
Get list of audio devices with `CoreAudio` functions. Then get the devices' unique identifiers:
```
//...
address.mSelector = kAudioDevicePropertyDeviceUID;
CFStringRef uid = NULL;
UInt32 size = sizeof(uid);
AudioObjectGetPropertyData(deviceId, &address, 0, NULL, &size, &uid);
//...
```
Initialize sound item, set `playbackDeviceIdentifier` property value. | Opened a DTS case with Apple and they said it was not possible (as i need to support 10.8). If you only need to support 10.9 and above AVPlayerAudioDeviceSupport should work. |
53,783,166 | I'm getting an error on iOS only:
```
TypeError: undefined is not an object (evaluating 'this._callListeners.bind')
This error is located at:
in DrawerLayout (at DrawerView.js:161)
...
```
Project dependencies:
```
"dependencies": {
"@babel/runtime": "7.2.0",
"@babel/plugin-proposal-async-generator-functions": "7.2.0",
"@babel/plugin-proposal-class-properties": "7.2.1",
"@babel/plugin-proposal-object-rest-spread": "7.2.0",
"babel-preset-expo": "5.0.0",
"expo": "31.0.2",
"expo-cli": "2.5.0",
"native-base": "2.8.1",
"react": "16.6.3",
"react-native": "0.57.8",
"react-redux": "6.0.0",
"react-navigation": "3.0.8",
"react-native-vector-icons": "6.1.0",
"redux": "4.0.1"
}
```
This started when I began using react-navigation; but works fine on Android.
Here's the code where we're using react-navigation, this is the main app the imports include the Home and Settings screens:
```
//imports...
const routes = {
Home: Home,
Settings: Settings
};
const AppNavigator = createDrawerNavigator(routes);
const AppContainer = createAppContainer(AppNavigator);
export default class App extends React.Component {
state = {}
render() {
if (this.state.isReady) {
return (
<AppContainer/>
);
}
else {
return (<Container><Spinner/></Container>);
}
}
componentWillMount() {
this._loadAssets();
}
async _loadAssets() {
await Expo.Font.loadAsync({
Roboto: require("native-base/Fonts/Roboto.ttf"),
Roboto_medium: require("native-base/Fonts/Roboto_medium.ttf")
});
this.setState({ isReady: true });
}
}
``` | 2018/12/14 | [
"https://Stackoverflow.com/questions/53783166",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1366972/"
] | The [`calloc`](https://en.cppreference.com/w/c/memory/calloc) sets all bytes of the allocated memory to zero.
As it happens, that's also the valid [IEEE754](https://en.wikipedia.org/wiki/IEEE_754) (which is the most common format for floating point values on computers) representation for `0.0`.
IIRC there's no part of the C specification that requires an implementation to use IEEE754, so to be picky it's not portable. In reality though, it is (and if you're ever going to work on a non-IEEE754 system then you should have gathered enough experience to already know this and how to solve such problems).
Also note that this also is valid for pointers. On all systems you're likely to come in contact with, a null pointer should be equal to `0`. But there might be systems where it isn't, but if you work on such systems you should already know about it (and if you use `NULL` then it should not be a problem). | All bytes zero for a `float` does not mean `0.0`. From [here](https://en.cppreference.com/w/c/memory/calloc)
>
> Initialization to all bits zero does not guarantee that a floating-point or a pointer would be initialized to 0.0 and the null pointer value, respectively (although that is true on all common platforms)
>
>
> |
53,783,166 | I'm getting an error on iOS only:
```
TypeError: undefined is not an object (evaluating 'this._callListeners.bind')
This error is located at:
in DrawerLayout (at DrawerView.js:161)
...
```
Project dependencies:
```
"dependencies": {
"@babel/runtime": "7.2.0",
"@babel/plugin-proposal-async-generator-functions": "7.2.0",
"@babel/plugin-proposal-class-properties": "7.2.1",
"@babel/plugin-proposal-object-rest-spread": "7.2.0",
"babel-preset-expo": "5.0.0",
"expo": "31.0.2",
"expo-cli": "2.5.0",
"native-base": "2.8.1",
"react": "16.6.3",
"react-native": "0.57.8",
"react-redux": "6.0.0",
"react-navigation": "3.0.8",
"react-native-vector-icons": "6.1.0",
"redux": "4.0.1"
}
```
This started when I began using react-navigation; but works fine on Android.
Here's the code where we're using react-navigation, this is the main app the imports include the Home and Settings screens:
```
//imports...
const routes = {
Home: Home,
Settings: Settings
};
const AppNavigator = createDrawerNavigator(routes);
const AppContainer = createAppContainer(AppNavigator);
export default class App extends React.Component {
state = {}
render() {
if (this.state.isReady) {
return (
<AppContainer/>
);
}
else {
return (<Container><Spinner/></Container>);
}
}
componentWillMount() {
this._loadAssets();
}
async _loadAssets() {
await Expo.Font.loadAsync({
Roboto: require("native-base/Fonts/Roboto.ttf"),
Roboto_medium: require("native-base/Fonts/Roboto_medium.ttf")
});
this.setState({ isReady: true });
}
}
``` | 2018/12/14 | [
"https://Stackoverflow.com/questions/53783166",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1366972/"
] | The [`calloc`](https://en.cppreference.com/w/c/memory/calloc) sets all bytes of the allocated memory to zero.
As it happens, that's also the valid [IEEE754](https://en.wikipedia.org/wiki/IEEE_754) (which is the most common format for floating point values on computers) representation for `0.0`.
IIRC there's no part of the C specification that requires an implementation to use IEEE754, so to be picky it's not portable. In reality though, it is (and if you're ever going to work on a non-IEEE754 system then you should have gathered enough experience to already know this and how to solve such problems).
Also note that this also is valid for pointers. On all systems you're likely to come in contact with, a null pointer should be equal to `0`. But there might be systems where it isn't, but if you work on such systems you should already know about it (and if you use `NULL` then it should not be a problem). | C11 documentation has this explicit notice for `calloc`
>
> Footnotes
>
>
> 296. Note that this need not be the same as the representation of
> floating-point zero or a null pointer constant.
>
>
>
In practice, all zero bits is a (or the) representation for 0.0 on all major platforms as they use IEEE 754 representation. Yes, this will hold on Intel, ARM, Linux, Windows, Mac, Raspberry PI, the smartphones. |
53,783,166 | I'm getting an error on iOS only:
```
TypeError: undefined is not an object (evaluating 'this._callListeners.bind')
This error is located at:
in DrawerLayout (at DrawerView.js:161)
...
```
Project dependencies:
```
"dependencies": {
"@babel/runtime": "7.2.0",
"@babel/plugin-proposal-async-generator-functions": "7.2.0",
"@babel/plugin-proposal-class-properties": "7.2.1",
"@babel/plugin-proposal-object-rest-spread": "7.2.0",
"babel-preset-expo": "5.0.0",
"expo": "31.0.2",
"expo-cli": "2.5.0",
"native-base": "2.8.1",
"react": "16.6.3",
"react-native": "0.57.8",
"react-redux": "6.0.0",
"react-navigation": "3.0.8",
"react-native-vector-icons": "6.1.0",
"redux": "4.0.1"
}
```
This started when I began using react-navigation; but works fine on Android.
Here's the code where we're using react-navigation, this is the main app the imports include the Home and Settings screens:
```
//imports...
const routes = {
Home: Home,
Settings: Settings
};
const AppNavigator = createDrawerNavigator(routes);
const AppContainer = createAppContainer(AppNavigator);
export default class App extends React.Component {
state = {}
render() {
if (this.state.isReady) {
return (
<AppContainer/>
);
}
else {
return (<Container><Spinner/></Container>);
}
}
componentWillMount() {
this._loadAssets();
}
async _loadAssets() {
await Expo.Font.loadAsync({
Roboto: require("native-base/Fonts/Roboto.ttf"),
Roboto_medium: require("native-base/Fonts/Roboto_medium.ttf")
});
this.setState({ isReady: true });
}
}
``` | 2018/12/14 | [
"https://Stackoverflow.com/questions/53783166",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1366972/"
] | The [`calloc`](https://en.cppreference.com/w/c/memory/calloc) sets all bytes of the allocated memory to zero.
As it happens, that's also the valid [IEEE754](https://en.wikipedia.org/wiki/IEEE_754) (which is the most common format for floating point values on computers) representation for `0.0`.
IIRC there's no part of the C specification that requires an implementation to use IEEE754, so to be picky it's not portable. In reality though, it is (and if you're ever going to work on a non-IEEE754 system then you should have gathered enough experience to already know this and how to solve such problems).
Also note that this also is valid for pointers. On all systems you're likely to come in contact with, a null pointer should be equal to `0`. But there might be systems where it isn't, but if you work on such systems you should already know about it (and if you use `NULL` then it should not be a problem). | [C standard](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf) deliberately avoids specifying the way that `float` and `double` are represented:
>
> 6.2.6.1 General
>
>
> 1. The representations of all types are unspecified except as stated in this subclause.
>
>
>
Therefore, you have no guarantee that `calloc` would produce 0.0 values.
Representation of unsigned integers, on the other hand, is specified as follows:
>
> If there are N value bits, each bit shall represent a different
> power of 2 between 1 and 2N−1, so that objects of that type shall be capable of representing values from 0 to 2N − 1 using a pure binary representation.
>
>
>
Therefore, the value of `calloc`-ed `unsugned int` is guaranteed to be zero. |
53,783,166 | I'm getting an error on iOS only:
```
TypeError: undefined is not an object (evaluating 'this._callListeners.bind')
This error is located at:
in DrawerLayout (at DrawerView.js:161)
...
```
Project dependencies:
```
"dependencies": {
"@babel/runtime": "7.2.0",
"@babel/plugin-proposal-async-generator-functions": "7.2.0",
"@babel/plugin-proposal-class-properties": "7.2.1",
"@babel/plugin-proposal-object-rest-spread": "7.2.0",
"babel-preset-expo": "5.0.0",
"expo": "31.0.2",
"expo-cli": "2.5.0",
"native-base": "2.8.1",
"react": "16.6.3",
"react-native": "0.57.8",
"react-redux": "6.0.0",
"react-navigation": "3.0.8",
"react-native-vector-icons": "6.1.0",
"redux": "4.0.1"
}
```
This started when I began using react-navigation; but works fine on Android.
Here's the code where we're using react-navigation, this is the main app the imports include the Home and Settings screens:
```
//imports...
const routes = {
Home: Home,
Settings: Settings
};
const AppNavigator = createDrawerNavigator(routes);
const AppContainer = createAppContainer(AppNavigator);
export default class App extends React.Component {
state = {}
render() {
if (this.state.isReady) {
return (
<AppContainer/>
);
}
else {
return (<Container><Spinner/></Container>);
}
}
componentWillMount() {
this._loadAssets();
}
async _loadAssets() {
await Expo.Font.loadAsync({
Roboto: require("native-base/Fonts/Roboto.ttf"),
Roboto_medium: require("native-base/Fonts/Roboto_medium.ttf")
});
this.setState({ isReady: true });
}
}
``` | 2018/12/14 | [
"https://Stackoverflow.com/questions/53783166",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1366972/"
] | C11 documentation has this explicit notice for `calloc`
>
> Footnotes
>
>
> 296. Note that this need not be the same as the representation of
> floating-point zero or a null pointer constant.
>
>
>
In practice, all zero bits is a (or the) representation for 0.0 on all major platforms as they use IEEE 754 representation. Yes, this will hold on Intel, ARM, Linux, Windows, Mac, Raspberry PI, the smartphones. | All bytes zero for a `float` does not mean `0.0`. From [here](https://en.cppreference.com/w/c/memory/calloc)
>
> Initialization to all bits zero does not guarantee that a floating-point or a pointer would be initialized to 0.0 and the null pointer value, respectively (although that is true on all common platforms)
>
>
> |
53,783,166 | I'm getting an error on iOS only:
```
TypeError: undefined is not an object (evaluating 'this._callListeners.bind')
This error is located at:
in DrawerLayout (at DrawerView.js:161)
...
```
Project dependencies:
```
"dependencies": {
"@babel/runtime": "7.2.0",
"@babel/plugin-proposal-async-generator-functions": "7.2.0",
"@babel/plugin-proposal-class-properties": "7.2.1",
"@babel/plugin-proposal-object-rest-spread": "7.2.0",
"babel-preset-expo": "5.0.0",
"expo": "31.0.2",
"expo-cli": "2.5.0",
"native-base": "2.8.1",
"react": "16.6.3",
"react-native": "0.57.8",
"react-redux": "6.0.0",
"react-navigation": "3.0.8",
"react-native-vector-icons": "6.1.0",
"redux": "4.0.1"
}
```
This started when I began using react-navigation; but works fine on Android.
Here's the code where we're using react-navigation, this is the main app the imports include the Home and Settings screens:
```
//imports...
const routes = {
Home: Home,
Settings: Settings
};
const AppNavigator = createDrawerNavigator(routes);
const AppContainer = createAppContainer(AppNavigator);
export default class App extends React.Component {
state = {}
render() {
if (this.state.isReady) {
return (
<AppContainer/>
);
}
else {
return (<Container><Spinner/></Container>);
}
}
componentWillMount() {
this._loadAssets();
}
async _loadAssets() {
await Expo.Font.loadAsync({
Roboto: require("native-base/Fonts/Roboto.ttf"),
Roboto_medium: require("native-base/Fonts/Roboto_medium.ttf")
});
this.setState({ isReady: true });
}
}
``` | 2018/12/14 | [
"https://Stackoverflow.com/questions/53783166",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1366972/"
] | [C standard](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf) deliberately avoids specifying the way that `float` and `double` are represented:
>
> 6.2.6.1 General
>
>
> 1. The representations of all types are unspecified except as stated in this subclause.
>
>
>
Therefore, you have no guarantee that `calloc` would produce 0.0 values.
Representation of unsigned integers, on the other hand, is specified as follows:
>
> If there are N value bits, each bit shall represent a different
> power of 2 between 1 and 2N−1, so that objects of that type shall be capable of representing values from 0 to 2N − 1 using a pure binary representation.
>
>
>
Therefore, the value of `calloc`-ed `unsugned int` is guaranteed to be zero. | All bytes zero for a `float` does not mean `0.0`. From [here](https://en.cppreference.com/w/c/memory/calloc)
>
> Initialization to all bits zero does not guarantee that a floating-point or a pointer would be initialized to 0.0 and the null pointer value, respectively (although that is true on all common platforms)
>
>
> |
53,783,166 | I'm getting an error on iOS only:
```
TypeError: undefined is not an object (evaluating 'this._callListeners.bind')
This error is located at:
in DrawerLayout (at DrawerView.js:161)
...
```
Project dependencies:
```
"dependencies": {
"@babel/runtime": "7.2.0",
"@babel/plugin-proposal-async-generator-functions": "7.2.0",
"@babel/plugin-proposal-class-properties": "7.2.1",
"@babel/plugin-proposal-object-rest-spread": "7.2.0",
"babel-preset-expo": "5.0.0",
"expo": "31.0.2",
"expo-cli": "2.5.0",
"native-base": "2.8.1",
"react": "16.6.3",
"react-native": "0.57.8",
"react-redux": "6.0.0",
"react-navigation": "3.0.8",
"react-native-vector-icons": "6.1.0",
"redux": "4.0.1"
}
```
This started when I began using react-navigation; but works fine on Android.
Here's the code where we're using react-navigation, this is the main app the imports include the Home and Settings screens:
```
//imports...
const routes = {
Home: Home,
Settings: Settings
};
const AppNavigator = createDrawerNavigator(routes);
const AppContainer = createAppContainer(AppNavigator);
export default class App extends React.Component {
state = {}
render() {
if (this.state.isReady) {
return (
<AppContainer/>
);
}
else {
return (<Container><Spinner/></Container>);
}
}
componentWillMount() {
this._loadAssets();
}
async _loadAssets() {
await Expo.Font.loadAsync({
Roboto: require("native-base/Fonts/Roboto.ttf"),
Roboto_medium: require("native-base/Fonts/Roboto_medium.ttf")
});
this.setState({ isReady: true });
}
}
``` | 2018/12/14 | [
"https://Stackoverflow.com/questions/53783166",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1366972/"
] | C11 documentation has this explicit notice for `calloc`
>
> Footnotes
>
>
> 296. Note that this need not be the same as the representation of
> floating-point zero or a null pointer constant.
>
>
>
In practice, all zero bits is a (or the) representation for 0.0 on all major platforms as they use IEEE 754 representation. Yes, this will hold on Intel, ARM, Linux, Windows, Mac, Raspberry PI, the smartphones. | [C standard](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf) deliberately avoids specifying the way that `float` and `double` are represented:
>
> 6.2.6.1 General
>
>
> 1. The representations of all types are unspecified except as stated in this subclause.
>
>
>
Therefore, you have no guarantee that `calloc` would produce 0.0 values.
Representation of unsigned integers, on the other hand, is specified as follows:
>
> If there are N value bits, each bit shall represent a different
> power of 2 between 1 and 2N−1, so that objects of that type shall be capable of representing values from 0 to 2N − 1 using a pure binary representation.
>
>
>
Therefore, the value of `calloc`-ed `unsugned int` is guaranteed to be zero. |
72,523,117 | Say I have a dataframe that ***looks*** like this (wasn't sure how to actually rep. this data, given its size):
```
minutes <- seq(0,585, by = 15)
salinity <- as.numeric(sample(x = 29:55, size = 40, replace = TRUE))
site <- c(1, 2, 3, ...etc.)
year <- c(2020, 2019, ...etc.)
season <- c("Dry", "Wet")
df <- cbind.data.frame(year, season, site, minutes, salinity)
> head(df)
year season site minutes salinity
1 2020 DRY 1 0 54
2 2020 DRY 1 15 39
3 2020 DRY 1 30 44
4 2020 DRY 1 45 54
5 2020 DRY 1 60 43
6 2020 DRY 1 75 40
```
and in reality it has +800k rows of continuously measured data in 15 min. increments for the past couple of years at "n" sites.
I'm attempting to make a matrix/table like this in R (that was originally created in Excel). Color is not important, I only hope to re-create the table itself. The values in this plot are the maximum/highest number of minutes where a range of values were consistently measured (ex. For each site, season, and year, create a table that shows the longest lasting run of continuous minutes where the values stayed between 40-50).
[](https://i.stack.imgur.com/nXHga.png) | 2022/06/06 | [
"https://Stackoverflow.com/questions/72523117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16401542/"
] | This error comes from Vue Language Features (Volar).
[issue page](https://github.com/johnsoncodehk/volar/issues/1405)
Rolling back the volar plug-in to version 0.36.1 can solve this problem. | Just change the volar version **0.37.2 to 0.36.0** and everyting will be fine.
Note: I spent coulple of hours and didn't find the exact solution and then simply tried this; then everything worked fine.
This link helped to get some idea regarading this issue:
<https://github.com/microsoft/TypeScript/issues/28631#issuecomment-472606019> |
72,523,117 | Say I have a dataframe that ***looks*** like this (wasn't sure how to actually rep. this data, given its size):
```
minutes <- seq(0,585, by = 15)
salinity <- as.numeric(sample(x = 29:55, size = 40, replace = TRUE))
site <- c(1, 2, 3, ...etc.)
year <- c(2020, 2019, ...etc.)
season <- c("Dry", "Wet")
df <- cbind.data.frame(year, season, site, minutes, salinity)
> head(df)
year season site minutes salinity
1 2020 DRY 1 0 54
2 2020 DRY 1 15 39
3 2020 DRY 1 30 44
4 2020 DRY 1 45 54
5 2020 DRY 1 60 43
6 2020 DRY 1 75 40
```
and in reality it has +800k rows of continuously measured data in 15 min. increments for the past couple of years at "n" sites.
I'm attempting to make a matrix/table like this in R (that was originally created in Excel). Color is not important, I only hope to re-create the table itself. The values in this plot are the maximum/highest number of minutes where a range of values were consistently measured (ex. For each site, season, and year, create a table that shows the longest lasting run of continuous minutes where the values stayed between 40-50).
[](https://i.stack.imgur.com/nXHga.png) | 2022/06/06 | [
"https://Stackoverflow.com/questions/72523117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16401542/"
] | This error comes from Vue Language Features (Volar).
[issue page](https://github.com/johnsoncodehk/volar/issues/1405)
Rolling back the volar plug-in to version 0.36.1 can solve this problem. | According to the [issue page](https://github.com/johnsoncodehk/volar/issues/1405), add this config to your tsconfig.json file:
```json
// tsconfig.json
{
"vueCompilerOptions": {
"experimentalSuppressInvalidJsxElementTypeErrors": true
}
}
```
update:
the volar have updated to version v0.37.3 to resolve this issue.so,just reinstall the volar.
that works fine for me. |
72,523,117 | Say I have a dataframe that ***looks*** like this (wasn't sure how to actually rep. this data, given its size):
```
minutes <- seq(0,585, by = 15)
salinity <- as.numeric(sample(x = 29:55, size = 40, replace = TRUE))
site <- c(1, 2, 3, ...etc.)
year <- c(2020, 2019, ...etc.)
season <- c("Dry", "Wet")
df <- cbind.data.frame(year, season, site, minutes, salinity)
> head(df)
year season site minutes salinity
1 2020 DRY 1 0 54
2 2020 DRY 1 15 39
3 2020 DRY 1 30 44
4 2020 DRY 1 45 54
5 2020 DRY 1 60 43
6 2020 DRY 1 75 40
```
and in reality it has +800k rows of continuously measured data in 15 min. increments for the past couple of years at "n" sites.
I'm attempting to make a matrix/table like this in R (that was originally created in Excel). Color is not important, I only hope to re-create the table itself. The values in this plot are the maximum/highest number of minutes where a range of values were consistently measured (ex. For each site, season, and year, create a table that shows the longest lasting run of continuous minutes where the values stayed between 40-50).
[](https://i.stack.imgur.com/nXHga.png) | 2022/06/06 | [
"https://Stackoverflow.com/questions/72523117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16401542/"
] | This error comes from Vue Language Features (Volar).
[issue page](https://github.com/johnsoncodehk/volar/issues/1405)
Rolling back the volar plug-in to version 0.36.1 can solve this problem. | Fixed on `0.37.3`, so you don't have to alter your config or anything - <https://github.com/johnsoncodehk/volar/issues/1405#issuecomment-1149618450> |
72,523,117 | Say I have a dataframe that ***looks*** like this (wasn't sure how to actually rep. this data, given its size):
```
minutes <- seq(0,585, by = 15)
salinity <- as.numeric(sample(x = 29:55, size = 40, replace = TRUE))
site <- c(1, 2, 3, ...etc.)
year <- c(2020, 2019, ...etc.)
season <- c("Dry", "Wet")
df <- cbind.data.frame(year, season, site, minutes, salinity)
> head(df)
year season site minutes salinity
1 2020 DRY 1 0 54
2 2020 DRY 1 15 39
3 2020 DRY 1 30 44
4 2020 DRY 1 45 54
5 2020 DRY 1 60 43
6 2020 DRY 1 75 40
```
and in reality it has +800k rows of continuously measured data in 15 min. increments for the past couple of years at "n" sites.
I'm attempting to make a matrix/table like this in R (that was originally created in Excel). Color is not important, I only hope to re-create the table itself. The values in this plot are the maximum/highest number of minutes where a range of values were consistently measured (ex. For each site, season, and year, create a table that shows the longest lasting run of continuous minutes where the values stayed between 40-50).
[](https://i.stack.imgur.com/nXHga.png) | 2022/06/06 | [
"https://Stackoverflow.com/questions/72523117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16401542/"
] | Just change the volar version **0.37.2 to 0.36.0** and everyting will be fine.
Note: I spent coulple of hours and didn't find the exact solution and then simply tried this; then everything worked fine.
This link helped to get some idea regarading this issue:
<https://github.com/microsoft/TypeScript/issues/28631#issuecomment-472606019> | According to the [issue page](https://github.com/johnsoncodehk/volar/issues/1405), add this config to your tsconfig.json file:
```json
// tsconfig.json
{
"vueCompilerOptions": {
"experimentalSuppressInvalidJsxElementTypeErrors": true
}
}
```
update:
the volar have updated to version v0.37.3 to resolve this issue.so,just reinstall the volar.
that works fine for me. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.