Simple experimental evidence that Earth revolves around Sun

Question: What are the simplest experiments or calculations that give evidence that the earth revolves around the sun? Can you please explain them and reference the history? Many simple explanations such as this cite observations such as that relative position of two stars are observed from earth vary every night - which would not be true if the stars orbited the earth. But isn't the observation also consistent with a model where the stars orbit the earth but do so at different speeds, while the earth still orbits the sun? Simple explanations would be helpful.
Comment: Actually, as @MarkOlson notes, the geocentric view is actually quite correct for the Sun/Moon/stars, since we can view all motion as relative. The problem is with the planets: they clearly don't orbit the Earth in simple circles or even ellipses. You can compensate by using epicycles, but having the planets revolve around the Sun requires fewer artificial constructs. From there, it's a small leap to treating our solar system as heliocentric, instead of having the Sun and Moon orbit the Earth and the other planets orbit the Sun.
Comment: It doesn't  If the Earth tried to move that fast, the stack of turtles holding it up would fall apart.
Comment: @barrycarter That's basically Occam's Razor, which is useful as a guiding principle, but not really a proof.
Comment: The sun and the stars *do* orbit the earth--but the math is very complicated. The choice of reference frame (the earth is stationary, the sun is stationary, the mass-center of the solar system is stationary) is chosen for convenience, and "earth is stationary" makes the math really hard.
Comment: Does "simple" include accepting the modern theory of gravity?  Because if you start accepting the relative masses of the sun and planets, "Everything orbits the earth" can't work.
Comment: @Barmar: Occam's razor works both ways. Indeed, eliminating observations which are unachievable by unaided eyesight alone, and applying Occam's razor, we would be forced to adopt a flat earth as the center of the known universe. After all, believing that all seven (classical) planets are of the same nature (with regards to their motion and composition) requires the smallest set of assumptions compared to believing that the sun is a star which does not revolve around the earth, that the moon is a satellite revolving around the latter, and the rest are (modern) planets, revolving around the sun.
Comment: Of course, the most accepted models don't exactly have the Earth orbiting the Sun so much as the two orbiting a common center which happens to exist very much near the a point we could describe as the Sun's center of mass
Comment: @Lucian Quite true. The ancient Greeks probably thought that assuming all rotational motion was based on circles was simplest, so epicycles seemed reasonable.
Comment: Distant stars would not "orbit", they just bob back and forth every 6 months. And they do that with a different amplitude, depending on their distance, but all together, in perfect unison (save their proper motion). And proper motion of the stars can also be observed. But neither that not the parallax could be instrumentally observed in Galileo's time.
Answer: The answer is ironic: Without good instruments, there is no evidence. The people who thought that the Sun went around the Earth were perfectly correct as far as the actual evidence went until the early 1700s and mid-1800s when two lines of evidence opened up that showed that the Earth moved.
Aberration of Starlight
Wikipedia has a correct but over-complicated explanation. The easiest way to think about it is to imagine yourself at a stop sign in a car in the rain, and the rain is falling straight down. When you start moving, the rain's apparent direction of fall changes so that it appears to be falling from ahead of you and slanting down towards you. That's aberration.
In the early 1700s, the stars were discovered to be shifting position, and in 1727, James Bradley correctly identified it as abberation of starlight due to the motion of the Earth around the Sun. (For any star in the ecliptic, the Earth is moving towards it at some time of the year and away from it six months later.)
Parallax
Wikipedia's article on parallax is better, and I refer you to it for details. Basically, if you hold your finger up before you and look at it with your left eye closed, and then with your right eye closed, it appears to jump with respect to the background -- the wall beyond or the trees outside or whatever. Switch back and forth between your eyes quickly to see it clearly.
As the Earth circles around the Sun, nearby stars also appear to shift their position relative to the more distant stars.  A key point here is that there were good scientific reasons to suppose that the stars were much smaller than the Sun. Seen through a telescope, stars showed disks and if they were like the Sun, their distance could be deduced from those disks. And they were close enough that if the Earth really went around the Sun, parallax should have been observed. But it wasn't and the lack of any noticeable parallax was a strong empirical argument against Heliocentric theories.
In reality of course parallax exists, but the parallax of all stars is small, because they are much further away than was estimated from their disks. (The visible disks were actually diffraction disks and not true disks at all -- but it was not until nearly a century later that diffraction began to be understood.)  Friedrich Bessel first measure the real parallax of a star in 1838.
Comment: The change in solar zenith was known from prehistoric times and convinced no one of a heliocentric world, so, no, it doesn't strongly suggest anything until you make other assumptions (e.g., that the Sun is massive w/respect to the Earth or that something like gravitation creates the motions of the heavenly bodies) that are incompatible with geocentrism.  It's not direct evidence of heliocentrism.  (It's worth remembering that the lack of a visible parallax was already in ancient times one of the arguments used *against* heliocentrism.)
Comment: [Part 9](http://tofspot.blogspot.com/2013/10/9-great-ptolemaic-smackdown-from.html) of TheOFloinn's ["The Great Ptlemaic Smackdown"](http://tofspot.blogspot.com/2013/10/the-great-ptolemaic-smackdown-table-of.html) details the historical accretion of the evidence you mention as well as Guglielmi's 1791 measurement of lateral Coriolis force showing *rotation*.  The prior eight parts are also a fun read of the detailed replacement of geocentric with heliocentric models and probable evidence tampering against Galileo (by a justifiably angry large political institution).
Comment: Good answer. We tend to think of early cosmologists as flat-earther,denying an obvious truth. In fact they had good technical arguments for believing in things like 'a fixed dome of stars'. Without a good understanding of optics, how point sources can appear much larger than they actually are, they thought distant stars would have to be vastly bigger than our Sun in order to show no parallax.
Comment: It is also worth noting the observation of phases of Venus (https://en.wikipedia.org/wiki/Phases_of_Venus) in 1610 which ruled out the possibility that planets orbit Earth, although it is consistent with both Earth orbiting the Sun and Sun orbiting Earth while other planets orbit the Sun.
Comment: @littleO: Not a stab in the dark, exactly, but it seems to have been a combination of him thinking the heliocentric hypotheses was more elegant -- which it was -- and his own cantankerous nature. (Even without the near sainthood later myth-makers gave him, he was a *very* good scientist for his age. But he was also one of the more unpleasant people around and enjoyed driving off his friends and benefactors. He probably liked it because it would annoy people.) Read Owen Gingerich's book on him -- or read the "The Great Ptlemaic Smackdown" recommended a dozen comments above.
Comment: I'm not completely convinced -- doesn't the change in solar zenith over the seasons strongly suggest Earth is orbiting, since a geocentric Sun would have to have some pretty large perturbations in its orbit.
Comment: @Micha Wiedenmann: Not really. I believe that he's correct, but that he is not answering the question asked. The question asked for "simple experimental evidence" why the Earth goes around the Sun, while his answer gives an interesting theoretical discussion of why it's difficult to make absolute statements about pretty much anything. Nonetheless, in Galileo's apocryphal words, "Still, it goes around the Sun". (Well, the barycenter, anyway.)
Comment: As you wish. It still doesn't answer the question.
Comment: @user7496 To your second point, no, the Heliocentric theory was *not* supported experimentally before parallax and aberration were observed. Venus' phases showed that Venus went around the Sun and not the Earth, but the Tychonic system also predicted that.  Heliocentrism was more elegant for many, but -- especially in the Copernican version which insisted on circular orbits -- had nothing experimental to recommend it in preference to some of the other theories of the time.  The Great Ptolemaic Smackdown website referred to around here somewhere has a great narrative of the whole thing.
Comment: @Eric Towers: Wonderful and very useful to this question. (I'd lost track of Flynn, but in the past had attended many of his excellent talks at Boskone and Worldcon.)  Many thanks!
Comment: Does your answer contradict David Hammen's answer?
Comment: @MarkOlson I am not convinced since most certainly there is a frame of reference in which the earth is at rest and the sun moves around the earth.
Comment: Are you sure none of this is predicted by general relativity when you use a reference frame with a stationary Earth? Because if it is (which seems likely given that relativity is based on the notion of all reference frames being equally valid), then this would be wrong.
Comment: "No evidence" So how did Galileo know the heliocentric picture was correct? Surely he wasn't just taking a stab in the dark.
Comment: @littleO: please read the series of 9 blog posts by TheOFlonn mentioned above in comments. "He just knew" is the answer. He was so sure hist theory is correct that he defended it to the point of almost dishonesty or self-deception. This is not to belittle Galileo the scientist, no question he was a genius, just to understand who was Galileo the man. By the way, Einstein also famously noted that he is not interested in experimental confirmation of his GR, as an experiment contradicting it would certainly be invalid. This human side of science is fascinating!
Comment: @jpmc26:there is no such thing as a "reference frame with stationary earth" in GR. There are no stationary objects in the 4D spacetime (except certain surfaces around singular solution points, but that's a technicality). The GR does away with the inertial/non-inertial frame distinction by design. The main Einstein impetus was to unite inertia and gravity. The fact that the $m$ in $F=m a$ (inertial mass) and in $F=G\frac{M m}{r^2}$ (gravitational mass) is so freaking same measured to umpteen decimals cried for an explanation. GR is based on the postulate that they are one and the same.
Comment: @kkm Obviously, when I say stationary Earth, I'm talking about the Earth's overall position in the spatial dimensions, not the time dimension. Surely, it's not impossible to define a coordinate system where the center of the Earth stays at (0,0,0) and it's not rotating. Or if it is for some reason, then this answer needs to address that.
Comment: @jpmc26: Stays for *which observer*? Remember, we are talking about a 4D space with a non-Euclidean metric, and you can project it on an arbitrary 3D hyperplane in an infinite number of ways (even with the simplified metric, e. g.. in a local SR approximation). You seem to be forgetting that GR is a purely geometric theory. Every object, both observers and observed, is described by a straight line, "there and forever". Nothing *moves*, everything *is*. And this space is equipped with a complicated metric. You cannot separate time and space until you simplify it to the Newtonian dynamics.
Comment: @jpmc26 "this answer needs to address that" -- I respectfully disagree. An answer does not *need* to address every imaginable misconception. The answer did not even mention the GR, your comment did. I am only trying to clarify things for you because of this comment, not commenting about the answer in general. Now, this is a meta-meta-comment. :)
Comment: @kkm It's annoying to me that you're nitpicking at my comments but that you don't ask Mark to specify what observer is observing the aberration or parallax. It's not "addressing every imaginable misconception." The answer needs to explain why these phenomenon are impossible in a geocentric reference frame that accounts for GR. In particular, GR is commonly taught and understood to be largely based on the notion of that there is no preferred reference frame, and this answer blatantly contradicts that concept. That needs to be discussed if that conception is wrong.
Comment: @jpmc26: I think I understand your point that a theory you call GR cannot account for the aberration. Unfortunately, the GR I had a privilege to be taught was the now-classic Ensteinian one, and apparently differs from that which you are talking about. I admit I never heard of it (or any other GR), despite its being commonly taught and easily accessible, as you have noted. I sincerely wish you good luck with your research on reconciling the "blatant contradictions" with observations that it apparently suffers. I am afraid I cannot help you with that, but hope you would meet someone who can.
Comment: @MarkOlson: could you expand on the parallax argument? if other stars don't have noticeable parallax why would that be evidence of geocentric vs. heliocentric models?
Comment: @user7496: I added some material. Does that work?
Comment: @MarkOlson Im sorry I don't follow this "correctly identified it as abberation of starlight due to the motion of the Earth around the Sun. (For any star in the ecliptic, the Earth is moving towards it and some time of the year and away from it six months later.)" - how was aberration correctly identified with motion of the earth? On your second parallax argument, this makes it seem like there was no evidence until parallax was measured precisely by Bessel - but wasn't the heliocentric model thought be supported experimentally long before?
Comment: @user7496 It's hard to explain in a comment. (You might try to wade through the Wikipedia artcile I cited, but I found it confusing.)  Basically, think of standing still in a car in a rainstorm with drops are falling straight down.  Start moving and the angle of the drops change so that they appear to come from in front of you, and more so the faster you go. Light behaves the same way, and it manifests to us as an annual change in the apparent position of the stars. The effect is large, but hard to observe, because all stars in a given portion of the sky are shifted by the same amount.
Answer: You cannot prove that the Earth orbits the Sun rather than vice versa because this goes very much against the grain of all frames of reference being equally valid (but some make a lot more sense than others). For example, it makes much more sense to use an Earth-centered, Earth-fixed point of view rather than a non-rotating geocentric, heliocentric, barycentric, or galactocentric point of view when modeling the weather or the tides. One could, for example, use a heliocentric  or even galactocentric point of view to model the Earth's weather, but doing so would be beyond stupid.
On the other hand, when modeling the behavior solar system it makes much more sense to use a heliocentric, or even better, a solar system barycentric point of view. One could however use an Earth-centered, Earth-fixed point of view because all frames of reference are equally valid (in theory). Doing so would of course make the equations of motion quite ugly, and uglier yet on trying to make those equations of motion relativistically correct. A geocentric point of view nonetheless remains theoretically valid -- even for modeling the behavior of the Milky Way.
The problem with a geocentric point of view isn't that it's invalid (which it isn't). The problem is that advocates of geocentricism argued (and sadly, continue to argue) that this is the one and only valid point of view. This argument is invalid, because once again, all frames of reference are equally valid.
Note well: Just because inertial frames are special in some sense does not mean that non-inertial frames are invalid.
Comment: @BenCrowell while equations of motion in inertial frames are generally nicer, this doesn't make non-inertial frames invalid – just introduces fictitious forces.
Comment: As an aside, one of my favorite tests of the orbital dynamics framework I developed for NASA's Johnson Space Center was to place an object in orbit about the Earth's moon, but to model the time evolution of that object from the perspective a Neptune-centered inertial point of view. It worked, at least for a short period of time. While all frames of reference are equally valid in theory, some choices are rather dimwitted compared to others due to numerical accuracy concerns. My choice of Neptune-centered inertial was intentionally dimwitted.
Comment: Nah, you just needed more numerical precision! :-)
Comment: *all frames of reference are equally valid* Not true. Both Newtonian mechanics and general relativity distinguish between inertial and noninertial frames of reference. (In GR, an inertial frame is a free-falling frame.)
Comment: Also, the basic postulates of general relativity apply in exactly the same way in all reference frames, inertial or otherwise.  Newton's postulates do not.
Comment: @BenCrowell, perhaps you meant the special relativity, not the GR. In the GR framework, everything is "free-falling" along their geodesics, pretty much by postulate from which the theory is developed.
Comment: How would the Sun orbiting the Earth explain trigonometric parallax?
Comment: The stars would also be going in circles, consistent with the coordinate system.  It's simply a different coordinate system, and the key lesson of relativity is don't reify your coordinates, coordinates are just the language you have chosen.
Comment: @KenG Why should all the stars be executing little circles? Orbiting their own planets I guess? But why all with a period of 1 year? This motion tells us that it is more correct to say that the Earth goes around the Sun and argues strongly against a geocentric point of view.
Comment: You are making an essentially sociological point.  But we are talking about coordinates-- and there is no problem applying the postulates of general relativity to coordinates in which all the stars are moving in either little circles to make the Earth stationary in its orbit, or even in very large circles to make the Earth not spin either.  That's all just the mathematical language.  Einstein made the physics work in all these languages, that was the crux of his great achievement.  Philosophically, he used that this must be possible as a guiding principle of his theory.
Answer: If you start with the idea that the planets, the sun, the moon and the earth are all bodies that all move through space, exclude the apparently fixed stars, and then see what evidence there is as to how they move relative to each other, then in that context there is some evidence to be found in naked-eye astronomy aided by navigational instruments available even to the ancients.
The patterns of observed movement of the planets is evidence of heliocentric orbit.  The visible planets follow certain patterns.  First, Mercury and Venus:

They are always seen in the vicinity of the sun.
The observed angular separations of both Mercury and Venus from the sun have a regular pattern.
Mercury has a much closer maximum separation than Venus, and its angular separation changes at a much faster rate.
Both planets stay close to the ecliptic, and never oscillate normal to it.
Both planets' orbits around the sun can be documented and predicted with relative ease.  This can be done imprecisely even without a telescope, though it is much harder for Mercury, being so close to the sun.

Beginning with the premise of bodies moving through the heavens, I believe the evidence is there for Mercury and Venus having a heliocentric orbit.  Kepler described it precisely, but the ancient Greeks were able to model their motion very well without telescopes in the Antikythera Mechanism in geocentric terms.
If an ancient Greek astronomer had wanted to precisely model the motion of the inner planets in heliocentric terms, he could have.  The way to do it is to assume the fixed stars are rigidly fixed, and measure the angular distances between them all, and then plot the motions of the moving planets among them.  Sextants and other devices were used by ancient mariners who were highly skilled even with primitive ones.  So this could have been done to realize the "simple experiement or calculation" you are asking for.  Whether it ever was done, with that question in mind, is a bit different issue.
Now for the earth itself.  Even in the ancient world the relationship between the sidereal day and the solar day has been well understood.  The precession of the sun around the ecliptic plane is evidence of a heliocentric orbit.  One just has to model it to make this clear.  Ancient calculations relating to sidereal time and the Metonic cycle reveal that the earth's heliocentric motion could have been mathematically modeled, if conceived of and desired.
As for the outer planets, to my mind this is the least intuitive, but there is evidence for a heliocentric orbit for them too, but only by building on the idea that earth and the inner planets orbit the sun.  This comes from observing their retrograde motion.  These planets will move retrograde against the "fixed background stars" at certain times, and those times can be correlated to their angular separation from the sun.  Also the different planets move through the zodiac at different speeds, which also correlate with the amplitude of retrograde motion.
If you simulate all this with a heliocentric orrery, it is very plainly evident that we on an inner, faster planet observe an outer, slower planet in its orbit.  The ancient Greeks had enough skill to model the motions of Mars, Jupiter and Saturn in their Antikythera Mechanism in geocentric terms.  So it follows that a precise, mathematical model of heliocentric motion for the outer planets was within their reach, if they ever reached for it.
There is also some evidence that at least some ancient thinkers were able to decode all this into a heliocentric model.  The ancient Greek Aristarchus of Samos had a heliocentric model.  However, Plato and others seemed to disfavor it, and this reconstruction of the Antikythera Mechanism which is believed to come well after Aristarchus' day features a geocentric orrery which models planetary retrograde motion.  And heliocentric thinking stayed within the minority in the west until the modern age.  Perhaps the obvious geocentric orbit of the moon, or the question of the stars (whether they should be included in any correct model or not), or the lack of a universal theory of gravity, sufficiently obscured for them what to us is clear.
Comment: I think you're disregarding the fact that the heliocentric model doesn't do a much better job of actually modeling the system until you give up on circles. The first attempts at heliocentric models (even at the time of Galileo) had the issue of having even more exceptions than the geocentric ones due to using circles which don't actually work well. http://tofspot.blogspot.com/2013/10/the-great-ptolemaic-smackdown-table-of.html does seem to do a great job of explaining this.
Comment: The Antikythera Mechanism amazingly had an eccentric *gear* in its lunar module, accounting for the moon's elliptical orbit, which I imagine is close enough to us for a half-decent sextant to measure eccentricity.  But for the others it looks like all circles in Antikythera, with the caveat that not all of the device was recovered.  Nor have I seen any reference online to the Greeks discussing such issues with the visible planets.
Comment: @DRF You can probably tell I approached this from the point of view of, did the Greeks have enough *information* and *theory*, if not the insight, to prove heliocentricity at their level of mathematics, physics and technology?  Following that same line, I don't know, but I wonder if you have to have good quality lenses in order to disprove circular orbits.  Galileo had pretty good lenses, so maybe the Greeks were not capable of his level of precision.  I'm not sure.
Comment: Although your blog author you linked to makes a pretty good case that the Greeks could have proved even elliptical orbits at their level, if they had followed all the thought processes of the later European astronomers, without lenses.
Answer: The best experimental evidence is probably retrograde motion. The data is not easily acquired: it takes a long time to collect, not to mention an astronomer would have to stay up every night keeping painstaking measurements of the positions of each object. But it can be done (ancient Greeks were aware of it) and in the modern world you can simply use a simulator like Stellarium.
Download Stellarium, start it up, and navigate to your local position. Then set the simulation running and speed it up many times. You should see the sun and stars rotate around you. Then turn the ground off (so you can see through the Earth), turn the atmosphere off (so you can see stars during the day), switch to the equatorial mount (Ctrl + M; this is the mount where most of the sky is stationary), and zoom out until the Sun, the Moon, and all the planets appear to move in a circle.
Now look carefully at the motions of all the planets. You should see that the Moon (and the Sun) goes in circles without ever slowing down. This is what you'd expect if they went around the Earth. However Mercury does not follow this motion - it visibly disappears around the Sun. Mars behaves differently as well: it goes round and round, then stops, goes backwards, and then goes round and round again. This last behavior is called retrograde motion and its explanation occupied a lot of ancient astronomy. Ancient Greeks came up with a complicated theory of epicycles to explain it, given that the planets orbited the Earth and moved in perfect circles (neither of these are true in modern knowledge).
However retrograde motion can be easily explained if Mars didn't go around the Earth, but went around the Sun instead. This would simply mean that Mars goes retrograde when we overtake it on its orbit. In addition, this also explains how each time Mars goes retrograde, it is at its brightest, plus it is on the opposite side of the sky relative to the Sun. It also explains why Mercury does its loops around the Sun.
This doesn't mean that the geocentric model is not able to account for the same observations, but it's drastically simpler. In the heliocentric model, every planet goes round the Sun on a simple path, an ellipse. In the geocentric model, every planet goes round the Earth, but on epicycle after epicycle. That's when we apply Occam's Razor and conclude that the simpler explanation is correct.
Answer: Well... the seasonal cycle is evidence enough that the Earth and Sun are orbiting each other. Whether A orbits B or B orbits A is an argument about relative mass. If you find that the movement of all the other planets are consistent with them orbiting the Sun but not the Earth, you can conclude that the Sun's mass is enormous and therefore barely affected by the pull of the Earth.
Answer: Detailed observations of any star in the sky reveal that the Earth moves in an elliptical orbit with a speed of approximately 30 km/s.
When the line of sight velocities of stars are measured using the Doppler effect, they have to be corrected for the motion of the Earth. If they are not, then one would see an unexplained modulation of the velocities, with a period of 1 year and an amplitude of up to 30 km/s that would differ depending on the direction of the star with respect to the Earth-Sun orbital plane.
Likewise, a geocentric model fails to explain why an observer on the Earth sees the positions of stars on the sky execute periodic ellipses on the sky with amplitudes (a.k.a. the trigonometric parallax) that appear to be inversely correlated with how far away they are, but all with a period of one year.
Perhaps these are not the"simple" experiments that you were thinking of, but the universe cannot always be understood with what is visible to the naked eye and common sense.
Answer: This might oversimplify things but here's my go:

Create a flat surface (the larger the better as long as it stays flat), e.g. by placing a board on a still surface of water.
Put up a long pole (the longer the better) vertically on that surface at noon.
Measure its shadow (direction and length), which needs to be completely on the flat surface.
Have someone do the same (esp. same length of pole) at the same time far to the north of you (the further the better).
Have a third of the exact same measurements far to the south of you.

Evaluating the measurements should establish:

Earth's surface is roughly spherical (actually earth is an oblate ellipsoid but you need more than 3 measurements to confirm that)
Earth diameter is within reported values (+/- expected deviation for measurement error and the fact that you only measured a very rough estimation)
Rough estimation of earth-sun distance by triangulating

Using a pinhole camera you can now achieve a rough estimation of sun's actual diameter by its apparent diameter and the distance estimation from above. Even accumulating all the measurement errors, the difference in size between sun and earth should be some orders of magnitude.
Attach two balls to the opposite ends of a rod (the lighter the rod compared to the balls the better). The balls need to be rough approximations of the above established measurements (e.g. you could guess the sun is pure hydrogen and the earth is pure iron to achieve an estimation of mass). Attach a string to the rod and find the point of balance. Most likely it will be way to the ball representing the sun (you need to accommodate for weight of the rod).
You can now make the two balls circle each other while hanging from the string.
Which one revolves around the other?
Comment: Feel free to extend/correct this answer. I thought about how to have the described experiment/model as simple as possible. The only hope for  this to achieve anything is that the difference in diameter and mass between earth and sun is so staggering large that the numbers work out although they are likely to be 50% (or more) off from the actual values.
Answer: With relatively simple equipment it is possible to observe the behaviour of the satellites of Jupiter. Assuming the hypothesis that Jupiter and all the planets rotate around the Earth, it should be expected that the occlusion of the satellites by Jupiter would happen on a highly regular basis. But what we see is the event happening at different times relative to Earth-bound clocks, even not very accurate ones, which proves that the orbit of Jupiter is not a simple epicycle around the Earth. Also the observation of any satellite not directly orbiting the Earth casts doubt on the Earth-centric view.
Answer: Very simply: because of relative motion, no proof exists.  Any situation that you come up with can be explained by a tweaked geocentric module. Albert Einstein came to the same conclusion when he said   "I have come to believe that the motion of the Earth cannot be detected by any optical experiment."  and "...to the question whether or not the motion of the Earth in space can be made perceptible in terrestrial experiments. We have already remarked... that all attempts of this nature led to a negative result. Before the theory of relativity was put forward, it was difficult to become reconciled to this negative result."
Comment: It really makes sense to elaborate on this particular quote. You are being downvoted, because this well-known quotation is often seen torn out of its contest to show as if E. supported the geocentric model. I am surprised, however, that no one except you has so far mentioned the GR in this context. This looks like an introduction to a very good and educational answer, if only abruptly ended.


Entropy without thermodynamic limit

Question: I am reading K. Huang Statistical Mechanics (2Ed , Wiley, 1987) Chapter 14 Ising Model. The paragraph of title Absence of Spontaneous Magnetization in One Dimension bothers me.
Problem discussed is as follows. One dimensional chain of classical spins each denoted by $s_i$. Each spin can only take values 1 and -1. Energy of configuration is given by
$$
E(s) = -\epsilon\sum_{i=1}^{N-1} s_i s_{i+1}
$$
where $\epsilon$ is a positive constant and $N$ is number of spins in the system.
The argument presented in the book considers the following transition:

initially all spins are aligned in the same direction $\uparrow\uparrow\uparrow\uparrow\uparrow\uparrow\uparrow\uparrow$

the energy is at the absolute minimum, but the entropy is zero.

final state have a wall $\uparrow\uparrow\uparrow\uparrow\downarrow\downarrow\downarrow\downarrow$

the energy increases by $2\epsilon$, but the entropy increases by $k \log (N-1)$, since we have $N-1$ choices to place the wall.

Clearly, the author uses the microcanonical ensemble, where $S = k \log \Gamma$ with $\Gamma$ denoting the number of configurations which are characterized by the same value of energy ($-(N-1)\epsilon$ for the initial state and $-(N-3)\epsilon$ for the final state).
The thing that bothers me is why the author does not take the thermodynamic limit in the expression for entropy, a procedure which was introduced and justified in the earlier chapters.
In the introductory chapters the entropy was defined as a function which value can be obtained by the following procedure
$$
s = k\lim_{N \rightarrow \infty} \frac{1}{N} \log(N-1),
$$
where $s$ denotes the entropy concentration $s=\frac{S}{N}$ and its equal to zero in the considered case.
Can you please explain to how to obtain the author's value of entropy and preserve the thermodynamic limit?
Answer: The thermodynamic limit in this case is sort of trivial.  Kerson is assuming that the reader notices that as $N\rightarrow\infty$, the entropy of a single domain wall grows unboudedly, while the the energy of the domain wall remains a (small) constant.  Therefore, the free energy $A=E-TS$ is going to be dominated by the $-TS$ entropic term at thermodynamically large $N$, unless $T=0$.  Since the free energy change associated with creating a domain wall is negative, the domain wall will form spontaneously; the lowest-energy state (with all the spins aligned) is not the equilibrium state.

Entropy without thermodynamic limit


If I list a book in Bibliography, do I need to take permission?

Question: If I list a book in my book's bibliography, do I need to take permission from the publisher of that book that I am listing? I will list title, author and publisher and year, but not the page numbers as i am looking here and there, small bits of info, to confirm. I am looking at various general, well established information on the subject matter (nothing specific to that book, but things that can also be found in many other sources). My book will be in certain subjects of engineering but lower than academic level. It will be introductory - intermediate level, displaying only general info on the subject.
Comment: What? No, why would you need a permission to cite something?
Comment: *(thinking out loud)* If such permissions were needed for a bibliographic listing, then publishers would probably need a relatively large support staff devoted entirely to fielding the enormous number of permission requests made of their publications.
Answer: No, for a bibliography you don't need permission. The information is public knowledge.
If you quote or paraphrase specific information from within the book  you also need to cite that at the place where you use it. But that goes in the text itself, not the bibliography.
Generally, though, if the book you use is at the level of, say, an undergraduate text, then you can write about ideas from the book without citation as they are common knowledge in almost all cases. Using specific phrases, with proper quotation, however, requires citation.
So, if you only use the book for your own learning, and write those ideas in your own words, then no citation is needed, though it might be helpful to put such books in a bibliography for the benefit of readers who want to go beyond what you write.
And, don't give the impression that the ideas in the book are yours originally.
There are some exceptions for the need to quote and cite. Some things are known to be expressible in only one way. This is why, say, the definition of the derivative of a function is essentially identical in every beginning Calculus book, without quoting. This will be true for some things in engineering.


Generating survival times with covariates

Question: I would like to generate the survival time from an exponential distribution via inverse transformed method. The thing is, how can we generate a survival time having the covariates (eg. age) affected on it?
Answer: The probability density function (pdf) of exponential distribution is $f(x) = \lambda e^{-\lambda x}$. So it has just one parameter $\lambda$. You want to generate the random values following exponential distribution with different $\lambda$ according to some covariates.
At first, you can generate a dataset with all of covariates according to your plan. For example you want 1000 people, half of them are men, and the ages follow normal with mean 45 and standard deviation 15,.... Next, generate a new variable lambda derived from covariates for each person. Last thing is generating the random number following the exponential distribution with given lambda.
Comment: Thank u very much @user158565 for your explanation, I understand what you're trying to say. But, I have another question regarding your answer. In order to generate a new variable lambda derived from covariates for each person, do we need to derived it directly from the covariate PDF (eg. _N(45,15^2)_ for ages)? If yes, which parameter of the Normal dist will become the lambda? Or, do we need to perform the linear combination of all covariates (if we have more than 1 covariate).
Comment: First, select a person with specified covariate values as reference, for example, male, age = 40, ..., and think about his mean survival time, the inverse of it is the lambda for this person. Then following your idea to adjust the lambda according to covariate values. for example. for female, the survival time will be longer, then minus a value from reference lambda. ...
Comment: So, what you're trying to say is, for each person, the value of the new lambda may be different from another person, depending on their covariates, isn't it?
Comment: Yes. Just like fit a model, each person has his hazard according to his values on covariates.
Comment: Got it. Tqvm...


Visual stuidio publish query

Question: Q1. How can I (if I can) publish a website project with source code? Whenever I publish my website, it converts .cs files to DLLs in bin folder. But I want it to pe published with cs files and all refered external DLLs
Q2. When I publish a web application project, it gives publish/package settings options which is not available for website projects. This setting tab does give options to copy with source code but it creates many other unwanted files like config.debug, config.release etc. How can I make it publish application with files already in the project and nothing new.
Answer: Use "Copy site" instead of "Publish site" (right click on the web project or click "Web site" menu).

Visual stuidio publish query


Authentication / Authorization in Hot Towel Template

Question: How can I provide authentication / authorization for an asp.net mvc 4 web application that is built on Hot Towel template. All the views are considered as html pages. In this case how can I redirect my user to login view when s/he requests a view that needs specific credentials?
Answer: You can do that in your viewmodel js files and adding attributes to web api controllers. In the viewmodel's activate function when you go to the webserver to pull data, you can secure your API call by adding attributes which will ensure that the API call is executed only when the user is authenticated. In case the user is not authenticated you can return appropriate Response message or 401 or 403 message type. ViewModel can interpret this response type and redirect the user to login view.
Answer: In a project of mine I used CodeFirst Membership Provider  along with AccountController from the BreezeJS sample project. As for redirecting, try building a global library that checks if a user is logged in on every module activate call, and if the authentication fails, redirect them to login page.
Answer: Take a look at the ASP.NET SPA template, which uses the standard MVC authentication.
You can take the authentication code from there and put it into the Hot towel project.


How to compress a range of wavelengths into a single wavelength?

Question: Given the light spectrum from 400 to 500 nano-meters,
How can I convert all wavelengths in the range to one wavelength of say 450nm?
Comment: Use it to charge up a solar cell, then use that to power a laser.
Comment: Question is: why?
Comment: Split it by a prism and reflect of a mirrored cone rotating at about 20% of the speed of light. The redshift (or blueshift) can compensate for the wavelength difference. Alternatively split the light by a prism and run it near a neutron star for the gravitational redshift to work the same way.
Answer: If you want to convert your wavelengths to a single, mathematical, real-number, point-like wavelength at exactly $\lambda=450\:\mathrm{nm}$, it isn't possible, unless you're willing to wait for a literal eternity (details).
If you just want to compress light in some bandwidth $\Delta\lambda=50\: \mathrm{nm}$ down to a very thin sliver of spectrum at, say, $\delta\lambda=1\:\mathrm{pm}$, centered at $\lambda=450\:\mathrm{nm}$, then you're still looking at some very major difficulties, and frankly your best bet is to simply filter the light you don't want, or find a better light source.
The reason for this is that linear processes are completely incapable of altering the frequency of the radiation they operate on, so as far as linear optics is concerned, $400\:\mathrm{nm}$ light is going to stay at $400\:\mathrm{nm}$ no matter what.
That immediately tells you that do do your compression scheme you're going to need a nonlinear process, and those can be fiddly beasts. In principle, it is possible to use third-order nonlinearities to, say, take a pair of photons* at $440\:\mathrm{nm}$ and $460\:\mathrm{nm}$ and convert them into two degenerate photons at $450\:\mathrm{nm}$, and if you did this carefully enough, and your initial spectrum was coherent enough (and completely symmetric about your target wavelength), then you could hope for this to be doable. As an example, the reverse process, called supercontinuum generation, is perfectly possible (link, link), and it is an integral part of many technological breakthroughs of the past 20 years.
However, to arrange those processes in a way that narrows the bandwidth instead of widening it would require some very special preconditions, and it would require a lot of care in how you did this. More importantly, I don't see this working over a range as broad as $100\:\mathrm{nm}$ without some very special conditions in place.
Bottom line: get a new light source.

* I'm oversimplifying the math - it's the sum of frequencies that gets conserved, not the sum of wavelengths.
Answer: As Emilio Pisanty said it's not possible to reduce the input spectral width to a single wavelength, and I agree that the best path to reducing the bandwidth is likely to be either spectral filtering or abandoning your current light source for a more appropriate one. However, if your broadband signal has a relatively high-intensity time domain distribution (order of kW) then a lot of spectral compression can be achieved with a neat trick that doesn't require too much practical effort or appropriately balanced phase matching constraints and doesn't result in the heavy losses associated with spectral filtering.
Spectral compression can be achieved nonlinearly by inducing self-phase modulation on a negatively chirped pulse. Self-phase modulation changes the instantaneous frequency of an optical signal as a function of its intensity gradient and propagation distance, which for a Gaussian-shaped pulse looks like this:
$\omega(t,L)=\omega_{0}+\frac{4\pi Ln_{2}I_{0}}{\lambda_{0}\tau^{2}}t\times\text{exp}\left( \frac{-t^{2}}{\tau^{2}} \right)$
$\omega_{0}$ is the central angular frequency, $L$ is the propagation distance, $n_{2}$ the nonlinear refractive index of the propagation medium, $I_{0}$ the peak intensity, $\lambda_{0}$ the central wavelength, and $\tau$ the pulse duration. If we take the difference between the maximum and minimum values of $\omega(t,L)$ to be the signal bandwidth, we see that self-phase modulation causes the bandwidth to change with $L$. Using the example of a Gaussian pulse, the minimum and maximum instantaneous frequencies are given by:
$\omega_{\text{min, max}}(t,L)=\omega\left( t=\pm \tau/\sqrt{2}, L\right)$
and the bandwidth by:
$\Delta \omega(t,L) = \omega\left( \tau/\sqrt{2}, L \right) - \omega\left(-\tau/\sqrt{2}, L \right)$
We also see that self-phase modulation gives the instantaneous frequency a positive and largely linear variation, or chirp, about $t=0$ with a gradient given by $(4\pi Ln_{2}I_{0})/(\lambda_{0}\tau^{2})$. If we introduce a negative linear chirp at the input, we can force $\Delta\omega(t,L)$ to pass through a minimum at some propagation distance, compressing the optical spectrum from a broadband input to a narrowband output. If the propagation medium is truncated at this length, the broadband input signal will be spectrally compressed to a narrowband output.
Example:
Input: Gaussian pulse with a duration of 1 ps and a chirp parameter of -20 (meaning that the input optical bandwidth of the 1 ps pulse could support 50 fs), and a central wavelength of 1040 nm (288.3 THz). The pulse energy was 1 nJ giving an input peak power of ~0.94 kW. The nonlinear propagation medium was standard single-mode silica fibre.

The figure above shows the spectral evolution as a function of fibre length (linear scale, colourmap normalized to peak power spectral density). The compression is smooth and roughly linear with propagation distance away from the minimum. Overlaying the input and output pulse profiles shows the extent of the nonlinear spectral compression quite nicely:

The input and output time domain profiles are shown on the left, and the spectra on the right in wavelength. The FWHM of the output spectrum is smaller than the input by a factor of 7.2. By optimizing the fibre length, intensity, and chirp, higher compression factors will be possible. Other than the small propagation loss from the fibre (~0.001 dB here) the input average power is transferred directly to the output, meaning a much higher spectral power density for the compressed spectrum than for the input. This isn't possible with spectral filtering.
I've chosen different wavelengths to the question for my own convenience, mainly, but this choice is kind of arbitrary. Given an appropriate propagation medium this will work in the 400 -- 500 nm range too.
Regarding the "why" question which has appeared in the comments: There are a lot of reasons why you might want to induce spectral compression. The exact method described above is used in many so-called 'breathing-pulse' and soliton modelocked oscillators as a form of bandwidth control without having to introduce excessive cavity loss with a spectral filter. Similarly, if you want to seed a narrow-band amplifier adequately it can be a good idea to squeeze as much of the spectrum into the gain bandwidth as possible, and this method works well for doing that.
Answer: Some lasers are tunable.  E.g., diode lasers can be tuned via the current and temperature.  If you can find a diode that can be tuned around the wavelength you're interested in, then the linewidth can be dramatically reduced by locking the laser to a stable cavity.  A commonly used technique (which was crucial in the experimental achievement of BEC) is Pound-Drever-Hall:
https://en.wikipedia.org/wiki/Pound%E2%80%93Drever%E2%80%93Hall_technique


Google Meet: Allow microphone but not camera?

Question: Is there any way to enable Google Chrome/Meet to use a microphone but not a camera?  I'm not a Chrome user, but have to use it for some online training where I need to hear/speak but not use the camera
Comment: Questions about Google platforms are off-topic unless you are asking about the use of your computer hardware. In that case, there is no way for us to know how to help you when we know nothing about your computer/webcam. Please use the [edit] feature to add details. If you are not worried about high-tech solution, see my answer below.
Comment: If the permissions to use a Microphone and Camera are the same permission, then both have to be granted, it sounds like that is indeed the case if there isn't an option to only one or the other.
Comment: @CharlieRB This site isn't restricted to questions about computer hardware.  "Super User is for computer enthusiasts and power users. If you have a question about …

    computer hardware,
    computer software, or
    personal and home computer networking"
Comment: I know that. If you look a little closer, you will see where online applications, like Google (Drive, Sheets, YouTube, etc), are off topic. I am not familiar with Meet, so I did not down vote or vote to close. It appears Meet may be software that resides on the computer, therefore making it on-topic.
Answer: Get yourself a roll of electircal tape.

Cut a small piece and put it over your camera.
Comment: Actually, I already did that.  But it seems to me that it should be possible to do it via Meet settings.
Comment: Some kind of painters tape would be better. Good electrical tape is not incredibly easy to remove cleanly. Or just a thick piece of paper folded over. Or you can get purpose built after market webcam privacy shields online.
Answer: This is a generic solution that will apply to even non Google apps:
Remove all mic/camera permission in Chrome for that site, then do a call that requires only microphone and grant that access alone. After that make a video call and when it asks for video permission, deny that.
If you did a video call initially, it grouped microphone and camera in a single permission item... which you can't break apart later.
However, that seems to have stopped working well this morning for me as Google Meet now continually harasses you to allow camera as well.
Comment: But the suggestion about the tape is still my preferred solution! There are some nice magnetic sliding covers that work well for laptops and phones that you can stick on as well...
Answer: You have to go to the meet website and click the lock in the search box the permissions should come up and just block the camera
Answer: These procedures are for the chrome browser but I guess there have to be similar methods for other browsers.

go to google meet and create a new meeting.
on top bar accept the access of camera and microphone.
Go to the chrome setting and then privacy and security tab.
click on the camera option and delete google meet access to your camera.

This leads to just microphone access.


How do I know the credentials by which I SSH into my Linode VPS?

Question: I have been handed a user/pass to login into the web-based front end on linode.com but this user/pass doesn't work for SSH.
Answer: I think you should create your own users and passwords in the web interface and login with those.
Answer: Log into your linode control panel. Click on the Linode you wish to access. Shut down the server using button on right side. Then click "Settings & Utilities" and fill in the new root password details bottom left. Start up server again and then try root@newpassword!


Detect continuity in AC line during load shedding and take action via DC circuit?

Question: I'm a noob. I have asked another question in this forum, but in component level. As the answer of that question says to use 12v and 5v relay. I reached out to local electroni6c market. But for covid-19 everything is shutdown in Bangladesh, local online electronic suppliers also stopped their services. So I need another solution. Any help would be great.
I have a 4g modem with WiFi hotspot. As my main home router doesn't support sim card, so I have to use this in some situations, but not all the time. But now I also need this to work during the load shedding. So I tried to modify it. But for not having the skills required to do all this, I couldn't.
Here is my existing setup:

Numbers in blue are the parts number:

A 12V 1A power supply.(I'll replace this with a 12V 3A power supply in few days)
A IR RGB LED controller with maximum output of 3A. But I have connected only 0.2 meter LED strip instead of 1 meter.
A 12V to 5V 2A buck converter. This circuit bord is actually from my car phone charger.
A desktop fan to keep everything cool, specially the router. Cuz it gets so hot that after working for 30 to 40 minutes without fan, it stops working.
The router.

So to make it work during the load shedding, I added a 5V 1A power powerbank circuit. Which doesn't support pass through charging. So I had to add that like this:

But it creates more problem then it solves. Because, I found out that, connecting the both input and output line in parallel of the powerbank circuit will fry the chip in the powerbank circuit. Also I was about to add the 12V fan line to the powerbank. But, I couldn't. So during the load shedding even if I separately run the router from the powerbank, it's gets hot due to no cooling fan. (I can add another fan parallel to the router, but it will spin all the time instead of only when the power bank is powering)
Even if I connect desktop fan parallel to the router, this will blow the chip in powerbank, 12V buck converter and the router as this will bypass the 12V to 5V buck converter.
As the purple colour 1 marked red line shows this in the below photo:
This is only my DC circuit problem. I also want to add a feature exactly like intelligent LED lights. Where if I cut the AC line via switch, everything should turn off, like the router, fan, LED driver. But if the switch is on but no AC power due to load shedding. The fan and router should be on and consume power from the powerbank.
Finally the question is over as I thik I have explained everything. But if you have any questions please let me know. Also any suggestion regarding improvement of the question would be appreciated.
Note: I could have just used the intelligent LED light circuit I had bought, but It is a very low quality circuit with a 4V lead acid battery. It didn't had any battery protection ic. So I searched for better LED light with li-on battery and minimum protection circuit. But in my area all electronics shops only keep this as they are cheap.
Answer: You can try adding Schottky diodes on both input and output +V lines of your PB (6).

simulate this circuit – Schematic created using CircuitLab
D1, D2 should be Schottky. Not the best solution, but it might work as a "poor mans" backup power solution. Better solutions involve more complex schematics so I'm not sure if you can find parts for them in the current situation.
Or if your PB (6) supports both charging & powering output at the same time you can disconnect your router (5) from DC-DC (3) and connect it only to the PB (6) output. That way it will work as a simple UPS. Some power banks can support this mode.
Comment: Thanks for the answer, bought a mi power bank with pass through charging. So this problem is solved. But I'm looking forward for any relay alternative.
Comment: @ShohidulAlam I've updated my answer with a schematics on what I've meant on another solution.


How can I calculate the relative permeability of iron?

Question: I'm a high school physics student, and part of our project requires us to make an electromagnet. We have an iron core, and it will go inside a solenoid. The problem is, we don't know what the relative permeability constant of iron is so we can calculate the magnetic field with the iron.  How can we get this constant?
Answer: As you don't know the purity of the iron, I don't think you can calculate the permeability. Therefore, if you are not going to buy another core with known properties, you should measure the properties of the existing one, for example, by using the core in the electromagnet:-) If the properties of the test electromagnet are not satisfactory, you can redesign the coil based on the test results.
Answer: This Wikipedia page has the permeability value for iron, and other materials.  Obtain the relative permeability by dividing by the fundamental constant $\mu_0$ (defined elsewhere on that page).
Comment: I've already been on that page, and I am looking for another way because I don't know the purity of the iron.
Answer: We could make use of some of the inductance properties for resonating potentials.
$$ f = \frac{1}{2pi\sqrt{LC}} $$
The inductance of rectangular coil of sizes $L$ x $W$ x $H$ with N turns of wire (spire) is :
$$ L = \mu_0 \mu_r \frac{N^2 A}{l} $$
Here is our test circuit:

We could make use of alternative current from a transformer (in Europe the frequency $f$ would be $60$Hz but you can use the frequency from your own region).
$$ f = \frac{1}{2pi \sqrt{\mu_0 \mu_r \frac{N^2 A}{l} C}} $$
How ? Well, the circuit will resonate with the AC source only when the LC circuit has the same frequency with it. If the frequency of the LC is higher or lower than of the AC then the ampermeter will show irregular current.
We will add/subtract more turns(spires; will increase/decrease $N$) to the core and/or a smaller/bigger capacitor until our circuit resonates (we could really use an oscilloscope or a low frequency AC such as 2Hz, but I leave this for you to solve).
Since we know all the other parameters we can extract our coil magnetic permeability $\mu_r$ :
$$ \mu_r = \frac{1}{4pi^2 f^2 \mu_0 \frac{N^2 A}{l} C} $$
$L$ - coil inductance
$C$ - capacitance in Farads
$N$ - number of turns (spire) of wire
$A$ - core's surface (aria = height * width)
$l$ - core's length
$f$ - resonance frequency [Hertz]
$\mu_0$ - vacuum magnetic permeability (= $4 \pi 10^{-7})$
$\mu_r$ - core's magnetic permeability


Mount remote directory using SSH

Question: How to mount a remote directory using SSH to be available  same as if it is  a local directory?
Answer: First install the module:
sudo apt-get install sshfs

Load it to kernel:
sudo modprobe fuse

Setting permissions (Ubuntu versions < 16.04):
sudo adduser $USER fuse
sudo chown root:fuse /dev/fuse
sudo chmod +x /dev/fusermount

Now we'll create a directory to mount the remote folder in.
I chose to create it in my home directory and call it remoteDir.
mkdir ~/remoteDir

Now I ran the command to mount it (mount on home):
sshfs email@example.com:/home/maythuxServ/Mounted ~/remoteDir

Now it should be mounted:
cd ~/remoteDir
ls -l

Comment: No fuse group needed (Ubuntu 16.04, Nov 2017): https://stackoverflow.com/questions/35635631/ubuntu-15-10-no-fuse-group
Comment: Half of this answer either does not work or is outdated. Please consider updating.
Comment: I skipped some of these steps under 14.04 when I used the following guide: https://help.ubuntu.com/community/SSHFS
Comment: On 18.04, I skipped the full 2nd block - setting permissions and it works fine.
Comment: I'm a little confused... in the `sshfs` command, I think that the mountpoint local directory is named `remoteDir`, and when I'm on the ssh serever, there is a dir `/home/maythuxServ/Mounted` that is not mounted locally, and I can not tell, or care, whether it's mounted elsewhere?
Comment: Are these commands running on the client or the server?
Answer: Configure ssh key-based authentication
Generate key pair on the local host.
$ ssh-keygen -t rsa

Accept all sugestions with enter key.
Copy public key to the remote host:
$ ssh-copy-id -i .ssh/id_rsa.pub user@host

Install sshfs
$ sudo apt install sshfs

Mount remote directory
$ sshfs user@host:/remote_directory /local_directory

Don't try to add remote fs to /etc/fstab
Or don't try to mount shares via /etc/rc.local .
In both cases it won't work as the network is not available when init reads /etc/fstab.
Install AutoFS
$ sudo apt install autofs

Edit /etc/auto.master
Comment out the following lines
#+/etc/auto.master.d
#+/etc/auto.master

Add a new line
/- /etc/auto.sshfs --timeout=30

Save and quit
Edit /etc/auto.sshfs
Add a new line
/local_directory -fstype=fuse,allow_other,IdentityFile=/local_private_key :sshfs\#user@remote_host\:/remote_directory

Remote user name is obligatory.
Save and quit
Start autofs in debug mode
$ sudo service autofs stop
$ sudo automount -vf

Observe logs of the remote ssh server
$ ssh user@remote_server
$ sudo tailf /var/log/secure

Check content of the local directory
You should see contents of the remote directory
Start autofs in normal mode
Stop AutoFS running in debug mode with CTRL-C .
Start AutoFS in normal mode
$ sudo service autofs start

Enjoy
(Tested on Ubuntu 14.04)
Comment: Still good on Ubuntu 18.04. Used it to mount a directory from a Raspberry Pi 2 on a PC.
When issuing `sudo automount -vf`, if you get `1 remaining in /-` it is likely because you have already manually mounted the directory at step `Mount remote directory`. Rebooting should fix the issue.
Comment: the part about not adding stuff to /etc/fstab is wrong the option _netdev is made for this case.
Answer: Based on my experiments, explicitly creating the fuse group and adding your user to it is NOT required to mount ssh file system.
To summarize, here are the steps copied from this page:

Install sshfs

$ sudo apt-get install sshfs
2.Create local mount point
$ mkdir /home/johndoe/sshfs-path/
3.Mount remote folder /remote/path to /home/johndoe/sshfs-path/
$ sshfs  email@example.com:/remote/path /home/johndoe/sshfs-path/

And finally, to umount ...

$ fusermount -u /home/johndoe/sshfs-path/
Comment: Works on Ubuntu 20.10
Answer: Install sshfs
sudo apt-get install sshfs
Add to fstab:
<USER>@<SERVER_NAME>:<server_path> <local_path> fuse.sshfs delay_connect,_netdev,user,idmap=user,transform_symlinks,identityfile=/home/<YOUR_USER_NAME>/.ssh/id_rsa,allow_other,default_permissions,rw,nosuid,nodev,uid=1000,gid=1000,nonempty 0 0

Comment: Worked for me on Debian 11 but without `noempty`
Answer: Although it is not answering your question exactly but I just wanted to mention that you can achieve the same goal using "sftp" as well. Just inside your file manager address bar type this command:
sftp://firstname.lastname@example.com/remote/path

Comment: you can but it's very slow compared to sshfs :)
Answer: An easy way to run sshfs mounts at startup is also by adding it to the root (or another user's) crontab, like this:
@reboot sshfs firstname.lastname@example.com:/remote/path /home/johndoe/sshfs-path/

And if you need to add a delay, you can use:
@reboot sleep 60 && sshfs email@example.com:/remote/path /home/johndoe/sshfs-path/

Answer: I would like to warn that, it seems that by default only the user which set up the mount can access the remote directory.
I set up a remote directory, and create a crontab with sudo crontab -e. Later I found out the backup file didn't write the remote directory at all. Then I found out that I could not cd into the remote disk as root ! So eventually I create the same task with crontab -e and everything works as I expected.

Mount remote directory using SSH


How range of the signal increases when modulation is done?

Question: I am very confused because we know by increasing frequency we decrease the wavelength hence the distance covered will be very less but when we modulate a signal we are basically increasing the signal frequency which increases the range of the signal  , so how is that possible??
Comment: Hi! This is basically an **electromagnetics** question, not a DSP. Btw the answer is that antenna efficiency is tremendously dependent on the correct frequency of radiation that's why modulation is performed. Furthermore the frequecy dependent penetration (path) loss, skin depth etc, is mostly insignificant through surface athmosphere **air** at the practical RF range in use, and the gain from the frequency mathced antennas overwhelms.
Comment: what you're saying doesn't make any sense. Maybe you're mixing up different meanings of the word "modulate".
Answer: I think that you are interpreting the Friis equation to mean that RF signals carry for less distance than lower frequency RF signals. The "path loss" term "predicts this".
The first point which is still confused of why we modulate should be fairly obvious, because we don't want a 5000 meter antenna. One also uses modulation with amplification.  One also needs to be aware that frequency spectrum is regulated. In the US the FCC is not tolerant of unlicensed transmission so no signal regardless of carrier frequency will carry if you are in jail.
The Friis equation covers lossless spherical spreading just like the homogeneous wave equation.
https://en.m.wikipedia.org/wiki/Wave_equation
The wave equation predicts that the signal amplitude from an ideal point source drops off as $1/r$ and if that ideal point source has managed to radiate a signal there is no frequency dependence on the electromagnetic field.
The Friis equation doesn't predict electromagnetic field behavior. It predicts the voltage at the output of an antenna. Path loss refers to the path loss with respect  to an antenna with a fixed aperture where voltage does drop off with the carrier frequency.
For someone like myself who started out as a SONAR engineer, the term "path loss" is an unfortunate choice.
Terrestrial RF propagation almost never conforms to the physical assumptions which the Friis equation is based on. It does have `relevance because it is actually useful as a first order heuristic.  Higher frequencies are more susceptible to scattering and shading than low frequencies.
Low frequencies penetrate buildings deeper. High frequencies tend be favored in line-of-sight applications.
There are other reasons why we want to use a modulated carrier. There isn't a deep theoretical contradiction in play.
Essentially your conception of Electromagnetic attenuation is a bit too simple. Waveguides for instance have a characteristic known as the cut off frequency. A field has to have a frequency above the cut off frequency to propagate. Photons are electromagnetic waves and they travel billions of miles. The wavelength is not in itself the cause of attenuation, it is the interactions with matter which have the various effects
Comment: In a few paragraphs no. Can you explain why wavelength in of it self attenuates a propagating Signal in a homogeneous isotopic free space?  Your original proposition is false.
Comment: Can u just explain how modulation increases the range of the signal?


Ant command not recognized as an internal or external command on Windows

Question: I'm just trying to run ant from a Windows terminal. I put my /bin directory under C:\Program Files\apache-ant\apache-ant-1.10.14. I added that as my ANT_HOME system variable and added %ANT_HOME%\bin to my PATH. I thought maybe it wasn't resolving ANT_HOME but I can cd to ANT_HOME.
Comment: It would certainly help to show the output of `Dir "%ANT_HOME%\bin" /A-D` and the actual command you are running which is outputting the message shown in your title. In fact, as you are clearly running the command from a batch file, you should submit, at the very least, a [mcve] of that file's content.
Comment: @Compo updated to include more info. Just trying to run `ant`.
Comment: That is only some of the information I asked for, we need the batch file content, in order to isolate the issue. I could make a couple of guessses, **1.** You have in that script defined a variable named `path`, and in doing so, overwritten the important system variable. **2.** You have a corrupted or modified `pathext` variable, the value of which should always begin with `.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH`, and in that order. What is the output from `Set Path`?
Answer: Try adding adding it manually, that may work. If that doesn't work, try putting it in a folder on your desktop and all the files for the program there. then try 'cd'ing to  that folder then trying again. Then troubleshoot from then on.
Comment: Adding it to the path manually does work, but I want to know why it's not working using ANT_HOME.


Example of a Riemannian metric in $(1+1)$D by oscillating geodesics

Question: Newtonian gravitational potential for one mass gives oscillating motions to test particles.
Can a somewhat similar movement be produced by ($2$-dimensional $+-$) curvature? I mean an explicit metric and its geodesics.
Comment: Wouldn't any of the Schwarzschild metrics that are singularity free in 1+1 dimension do the job here?
Answer: Take the Schwarzschild equivalent in $1+1$ dimensions, that would be
$$ds^2 = -f(r) dt^2 + \frac{1}{f(r)} dr^2$$
We'll also require that $f(r)$ be asymptotically flat (just for being a "realistic" potential) and that it is non-singular (so that the particle can't crash in the singularity). The gravity should also be attractive here, so we should require the geometric equivalent of the strong energy condition, $R_{ab} X^a X^b \geq 0$ (I say the geometric equivalent because in 2D as usual gravity isn't dynamic with the matter content).
The inverse metric, as it is diagonal, is fairly simply $g^{rr} = f$, $g^{tt} = f^{-1}$
The connection is
\begin{eqnarray}
{\Gamma^t_{tt}} &=& {\Gamma^t}_{rr} = {\Gamma^r}_{tr} = {\Gamma^r}_{rt} = {\Gamma^t}_{rt} = {\Gamma^t}_{tr} = 0\\
{\Gamma^r_{rr}} &=& - \frac{1}{2}  \frac{f'}{f} \\
{\Gamma^r_{tt}} &=& -\frac{1}{2} f f'\\
\end{eqnarray}
Fortunately, in $1+1$ dimensions, the Riemann tensor only has one independant component. That component would be, up to interchange
\begin{eqnarray}
{R^r}_{trt} &=& {\Gamma^r}_{tt,r} - {\Gamma^r}_{tr,t} + {\Gamma^a}_{tt} {\Gamma^r}_{ar} - {\Gamma^a}_{tr} {\Gamma^r}_{at} \\
&=& -(\frac{1}{2}  ff'' + \frac{1}{4} (f')^2)
\end{eqnarray}
The Ricci tensor is $R_{ab} = {R^c}_{acb}$, so that
\begin{eqnarray}
R_{tt} &=& {R^r}_{trt} = -(\frac{1}{2}  ff'' + \frac{1}{4} (f')^2) \\
R_{rr} &=& {R^t}_{rtr} = -(\frac{1}{2}  ff'' + \frac{1}{4} (f')^2) \\
R_{tr} &=& R_{rt} = 0
\end{eqnarray}
A good function to simulate some gravity would simply be a function around $r = 0$ decreasing with distance. Let's pick for instance
$$f(r) = 1 + \frac{1}{r^2 + 1}$$
As it is $$f(r) \underset{r \to \infty}{\to} 1$$
and it is bounded. We have
\begin{eqnarray}
f'(r) &=& -\frac{2r}{(r^2 + 1)^2} \\
f''(r) &=& -2 \frac{r^4 + 1}{(r^2 + 1)^3}
\end{eqnarray}
Then the geodesic equation :
\begin{eqnarray}
\ddot{r} -\frac{1}{2} (\frac{f'}{f}\dot{r}^2 + ff' \dot{t}\dot{t}) &=& 0\\
\ddot{t} &=& 0
\end{eqnarray}
We have fairly easily $t = K \tau + \tau_0$, which we'll fix as simply $t = \tau$. The equation to solve is then
\begin{eqnarray}
\ddot{r}[(r^4 + 3r^2 + 2) (1 + r^2)^2 + 2] + \dot{r}^2 r (r^2 + 1)^2 + r(r^4 + 3r^2 + 2) + r^3 + 2r &=& 0
\end{eqnarray}
or something of that form. I'll admit, I don't know what the analytical solution may be. Here's an attempt from Wolfram Alpha to solve it numerically :

which seems periodic to me. It might be interesting to try some Fourier methods here, though as it is nonlinear I'm not sure it will be quite nice.
you can find other similar periodic numerical solutions to the geodesic equation by using other localized functions such as $e^{-r^2}$ or $\operatorname{sech}(r)$, although none of them seem particularly solvable due to their very nonlinear nature.


Referring to a diagram

Question: In a math book, should I write "diagram 3" or explicitly "diagram at the figure 3", when referring to a diagram in a displayed figure? (The title of the figure (as autogenerated by LaTeX) is "Figure 3." not "Diagram 3".)
Comment: What are the diagrams of and why are there more than one per figure?
Comment: @TriskalJM Why have you decided that there more than one diagram per figure? Usually there is at most one diagram per figure. In my case a diagram is a part of a figure. A figure may consist of a caption, a diagram, and a description (so called "legend") of what the diagram means
Comment: I thought multiple diagrams would be weird, but I thought it'd be best to ask. When referring to it in the text, the Figure is counted as a unit.
Answer: You should refer to it as Figure 3. For the purposes of the text, the diagram is the part that counts. The caption and anything else are information that augments the diagram.

Referring to a diagram


Validation of machine learning algorithms implementation

Question: What are some techniques by which we can verify that a current implementation of a machine learning algorithm is correct?  Is using the results of a benchmark dataset is enough?
Comment: Unit testing is the way to go. Make toy data sets for which you know what to expect and verify that you get that results.
Comment: @Magellanea it's feasible and natural if you're writing good code
Comment: Thanks a lot for the reply, sometimes that's not a feasible solution, for example if I wanted to validate an LDA topic modeling algorithm?
Answer: This question has several right answers. Here are three:

Unit test your code. Rather than testing the entire algorithm, test each step separately to make sure it gives the right result. The test cases only need to be as complicated as the individual step. This will enforce good coding habits anyway.
Use toy data. If you are fitting a SVM, you should be able to find the correct support vector on a linearly separable data set.
Replicate an existing result. Many, if not most, stats and ML method papers include a demonstration or experiments section. Replicate their demo and make sure your results match.

And of course don't forget the obvious: if the results don't make any sense, re-check your code before you re-check your model.


formal Chinese for Chinese relatives

Question: If my nephew(姪兒) and I dine with a relative, she is my mother's younger brother's daughter, what should my nephew call her in formal Chinese?
Answer: "If my nephew(姪兒) and I dine with a relative, she is my mother's younger brother's daughter, what should my nephew call her in formal Chinese?"
Your mother's brother's (舅舅的) daughter is your cousin - 表姐/妹. Now, if you are a sibling of your nephew's father, then he shall call her 表姑 (as for his father's cousin). Otherwise, 表姨, if you are a sister of his mother; or brother of his mother. But in the latter case, as noted by @monalisa, your nephew is your 外甥 instead of 侄子.
表姑 表姨
Comment: @r13 "a father-side relative and call her 表姨." Isn't 姨 mother side and 姑 father side?
Comment: If he calls you 舅舅, then he's not 姪兒, but 外甥. But OP clearly says this is 姪兒, which means his father is your brother. Paragraph 3 in your answer is not correct.
Comment: @monalisa Thanks for the reminder.
Comment: @joehua You are correct.
Answer: Let's call this nephew Peter, to simplify the explanation somewhat. Now Peter is your 姪兒, which means he is your brother's son. That will make your mother his paternal grandmother.
This female relative is his grandmother's niece (brother's daughter), which is also his father's cousin.
So your question is basically this:
What do you call your father's female cousin?
Your father's sisters are your 姑媽 (older) or 姑姐 (younger).
With cousins you add the word 表. If this female relative is older than Peter's father, she is 表姑媽; if younger, 表姑姐.
If you draw a little tree, it will become very clear. The relationship between Peter and this female relative does not need to go through you, and it is not as distant as it sounds.
Chinese kinship terms are not so complicated after all, I hope.
Edit: I feel compelled to add this to my answer even though it does not pertain to your question. I said add the word 表 to your sibling terms to turn them into cousins. Well, that's not entirely true all of the time. If, for example, this female relative were Peter's paternal grandfather's brother's daughter, then she would be a 堂姑媽 or 堂姑姐.
The difference between 堂 relative and 表 relative is that with 堂, the relationship is through an "all-male" cast. In our hypothetical case, this is Peter's father's father's brother's daughter. Not counting the two people whose relationship you're trying to figure out, every person that is involved is a male. Then this relative is a 堂 relative. As soon as there is at least one female involved, it becomes 表.
This begs the question, why the distinction. Well, the 堂 relatives have the same family name, and in a patriarchal society, it deserves a special term, I believe. Once a (married) woman is involved, the family name isn't the same anymore, assuming everybody takes their father's family name.
Comment: https://www.facebook.com/CantoneseMuseum/photos/a.405413536135531/3011425298867662/
Answer:
"1->3": 1 calls 3, "3->1": 3 calls 1.
1->3 兒子
3->1 母親
2->3 外甥
3->2 舅舅
3->5 表姐/表妹
5->3 表哥/表弟
5->1 姑姑
1->5 侄女
6->3 叔叔/伯伯
6->5 表姑
5->6 表侄
6->1 祖母
6->2 舅公
2->6 外甥孫

formal Chinese for Chinese relatives


Making custom template & variables in module

Question: I am working with D8, and don't usually do themeing, so I am stuck on a problem.
I have a custom route in a custom module that calls a method checkinConfirmation() on a controller.
Inside that controller, I have this:
public function checkinConfirmation() {
  $output['items'] = [
    '#type' => 'fieldset',
    '#title' => t('Checked in items'),
  ];
  $output['items']['name'] = [
    '#prefix' => '
',
    '#suffix' => '
',
    '#markup' => t('Name'),
  ];
  $output['#theme'] = 'circulation_confirmation';
  $output['#output'] = $output;

  return $output;
}

and inside of my theme, I have this inside of hook_theme()
public function mytheme_theme() {
  $theme['circulation_confirmation'] = [
    'template' => 'page/circulation--confirmation',
    'variables' => [
      'output' => [],
    ],
  ];
}

In my template, I have a {{ output }} variable to print the rendered output provided from $output. The problem is though, I do not get the items in the template, and I cannot figure out why. The template is getting pulled in, as the wrapper in the template file is being applied on the page, and the main container is the width it should be.
In using this instead (in the controller):
return [
  '#theme' => 'circulation_confirmation',
  '#output' => $output,
];

I at least get the data, but it doesn't appear to be using the template I provided as the wrapper is now gone and the main container is full width instead of the width it should be.
I don't usually do themeing or templating, and when I do it's usually forms so I can just pass it 'render element' => 'form', to get it to pass the form items to the theme. I am not sure what I am doing wrong.
Please help?
Comment: You have a single underscore in the return['#theme'], but a double hyphen in the template name.
Comment: You shoudn't do this: $output['#output'] = $output; But try adding a '#type' => 'markup' to your #markup - items
Comment: That made no change. Additionally the fieldset isn't being pulled in either.
Answer: You can try this:
In your custom_module.module:
function custom_module_theme() {
    return [
        'circulation_confirmation' => [
            'render element' => 'output',
            'variables' => [
                'output' => [],
            ],
        ],
    ];

And in your controller:
public function checkinConfirmation() {
    $rtn = [
        '#theme' => 'circulation_confirmation',
        '#output' => [],
    ];

    $rtn['#output']['items'] = [
        '#type' => 'fieldset',
        '#title' => t('Checked in items'),
    ];

    $rtn['#output']['items']['name'] = [
        '#prefix' => '
',
        '#suffix' => '
',
        '#markup' => t('Name'),
    ];

    return $rtn;
}


Mapinfo: Color label by attribute-expression

Question: It can be done in QGIS, but how to do that in Mapinfo?. I need to classify the labels color by  attributes from a column.
Answer: Hmmm not easily! and not without MapBasic or a lot of work to the best of my knowledge.
How many attribute types do you have? If there are only a few you could query each attribute, add the result to the map, and style the labels accordingly.
Aside from that the only other way that I thought of would be to effectively do the same thing, but use MapBasic and loop through each of the attributes, add it to the map, style it and move to the next one.
Comment: 300 different colours!!?? That might be hard to distinguish on the screen or ?
Comment: Hi Morgan. Approximately 300. I had the same ideas as the ones you are mentioning. Not an easy solution for that no.
Comment: Yeah sorry, limitation of MI Pro me thinks.


Installation 16.04 question related to lvmetad

Question: I erased windows 10 from my new machine and installed ubuntu 16.04, the installation was said to be complete. However, I did not see the guide says to check install third party software, so that is the only difference I had with the installation guide. I have tried Shift right key but nothing shows up. So I cannot boot now. The following shows and it won't proceed. How do I deal with this? Can I reinstall again?
lvmetad is not active yet; using direct activation during sysinit.
Answer: I am guessing that GRUB did not install correctly. To fix that please follow these steps carefully:

Insert Ubuntu installation disk (USB or DVD).
Boot and select "Try without installing" option
Open a terminal when the desktop has loaded
Run the following commands:
sudo -s
add-apt-repository ppa:yannubuntu/boot-repair
apt update
apt install boot-repair
boot-repair
Chose recommended option.
After a while it will ask you to copy and paste commands into the terminal. Copy and paste all commands given, open a new terminal window, and paste them. You will need to do this at least twice.
Once finished, shut down, remove installation medium, and reboot your computer.

This procedure will install GRUB on your computer, the utility that loads the Ubuntu operating system.
Comment: Thanks for the suggestion! Also, I selected using LVM when installing the machine. That may be where the lvmetad comes from.. However, if I just insert the USB drive with ubuntu on it, there is no option to let me select "try without installing". Should I press anything before that shows up?
Comment: Reinstalled Ubuntu 16.04 without lvm selected and also check the third party software box. Now the lvmetad message does not appear. It freezes after.. /dev/sda2: clean, 185441/121544704 files, 8571149/486174976 blocks. Starting /etc/rc.local Compatibility... Starting Automatically refresh installed snaps...


Exiting/entering the US - minor's US passport expired

Question: I'm a US citizen as is my son. Due to COVID-19, I was unable to renew my son's passport. We have tickets and are supposed to travel to Spain within the next two weeks. He also has a current Spanish passport (holds dual citizenship). Will I have trouble boarding the plane or leaving/entering the US? I can provide a birth certificate, street address and school ID if needed. Will I need other documents, or can I get a letter from your agency to assist me with this endeavor?
Comment: I'm not sure what you mean by "your agency".  This site is not an agency and is not official in any way.  It is just a community Q&A site.
Comment: Please see the question I linked. The short answer is that it is a legal requirement for your son to bear a valid US passport when he leaves the US, but there is no enforcement of this law, nor any penalty for violating it.
Comment: FYI [Why would airlines not let a US citizen with an expired passport board a plane back to the US?](https://travel.stackexchange.com/q/156755/1810).
Comment: If you are not an EU-Citizen, make sure that you can prove that you are a **legal guardian of a minor EU-Citizen**, since the exact conditions for entering the Schengen Area from the 1st of July are not yet known.
Answer: Short answer:

He will have no problems leaving the country.
Your son cannot be denied entry into the US. He may get questioned or yelled at by CBP but he will get in, if he manages to get to the border in the first place
However, no airline will let him board a US bound flight with an expired US passport
As a dual citizen you are required to use your US citizenship in all dealings with US government including entry and exit of the US.

In other words, he can easily get to Spain, but it's very difficult to come back to the US. There are potential work around but they are complicated not legally on the "murky" side of things, so I'd recommend against them.


Troubleshooting P0507 code on 05 KIA Spectra?

Question: I bought an 05 Kia Spectra EX for my daughter. The engine is throwing a P0507 code which is Idle Air RPM greater than expected. I did some research and apparently this is a pretty generic code that can be caused by a variety of issues. Is there a best order to step through the various things that could be causing? I fear it is a vacuum leak which I'm not keen on chasing because I am not that experienced (but I am willing to learn) and it sounds like it can get really tricky trying to diagnose that particular cause. I do have the Haynes manual and I am comfortable underneath the hood even if I am not that experienced. As far as the engine behavior goes it definitely seems to be erratic, sometimes it idles high (even when having been operated for a while) and sometimes it idles at what seems to be a more appropriate RPM.
Answer: I would definitely start with cleaning things before attempting to replace them. A simple solution may be to just clean your throttle body and idle air control valve (iac). Look at the air filter for large blockages just as an extra precaution. Take an overall glance at each intake piece to make sure nothing is disconnected, cracked, or broken and go from there. Hopefully you can find something simple before replacing anything.
Comment: Dalton said it exactly right. Go over each and every vacuum hose on the engine.  Gently squeeze, and check for cracks, burn marks, etc... Other possibilities include brake vacuum booster, Exhaust Gas Recirc stuff, Idle Air control... but check hoses first!.  Also consider purchasing a Service manual from Haynes or Chilton ($30 well spent.)  That will show you exactly how to check each of the things that could be causing troubles.
Answer: The fact that its intermittent does not rule out a vacuum leak but makes it less likely.
A common cause is failure of the idle air control valve (IAC). It can be tested by applying 12 volts to the center terminal #2 and then applying a ground to the outer terminals. It should open when #1 is grounded and close when #3 is grounded.


Are there more efficient ways to search for help/documentation than Google/SO/...?

Question: Google sometimes come up with irrelevant links, not everything is available on SO, there are cases where the local documentation is also annoying to look through... Are there other efficient ways you use to search?
Answer: Practise your Google-fu. Google is pretty awesome, but it's not magic. Sometimes you'll need to use search operators to get better answers, especially on some code phrases that can be difficult to search. Check out the Google Guide, for example.
If I know where the answer is, I might use the site: operator, or if I need something citable I often use inurl:edu. Google Code is handy for finding examples, and I use it to search for APIs sometimes.
Answer: One of the most useful pieces of advice I can give is to start using Google Bookmarks. These results will appear when you are searching Google. I really like how (unlike other bookmarking services) this is set and forget. The bookmark sharing could be improved however.
Answer: I honestly just use google with enough keywords to get the directly to the documentation without having to pull up giant RAM eating pages like the entire Java 6 class list.
Comment: **ZOMG! FRAMES!!**
Comment: Your link points to the Java **6** class list.
Answer: For programming issues I tend to look at bookmark websites using tags for example - http://www.delicious.com/tag/programming
Another resource to check out are books, sometimes a good book about a topic can give you just what you are looking for. So Google Book Search is a good way to identify the books that might be of help.


Lisp: circular structure printing through user-defined print methods: what are the requirements?

Question: In a Lisp dialect, I've implemented ANSI-CL-like support for printing objects such that their circular and shared structure is encoded. This is enabled by the special variable *print-circle*. Similarly to ANSI-CL, I have it working when it traverses objects that have custom print methods. But there are tricky corner cases.
For reference, let's make this diagram. Object X is the thing being printed, and the pyramid underneath it represents the dependent tree of constituent objects: nested lists, and whatever. Object O is a constituent which is an OOP object with a custom print method. When this is invoked, it can print various objects such as objects R and NR.  R is reachable through one or more of the slots of object O.  Object NR is not reachable that way: the print method pulls it from a global variable or whatever:
                     X
                     |
                    / \
                   /   \
                  /     \
                 /       \
                /         \
               <_________O_>
                         |
                        / print
                     ,-'   `---.
                     |         |
                     R         NR
                     |         |
                    / \       / \
                   <___>     <___>

Now I developed an algorithm which works in two passes. When the printer is called out of the blue to print X (not a recursive call) and circle printing is enabled, it creates a new circle printing context which contains a hash table for cycle detection. Before doing anything else, the function walks the entire graph rooted at X, which reaches O and recurses into R. It then knows all the duplicate objects and cycles, and can proceed to walk the structure and generate the circular notation. It has no knowledge of NR. However, when object O's print method is called, and recurses into the printer to print the object NR, the printer will supplement the hash table by walking the object NR at that point. Everything is cool if NR is self-contained: it can have internal cycles and shared substructure. What we ensure is that the label numbering for the objects occurring in NR doesn't conflict. If X and R use labels 1 through 21, then any labels under NR start at 22.
The troublesome case is this one:
                     X
                     |
                    / \
                   /   Y < ----------.
                  /     \            |
                 /       \           |
                /         \          |
               <_________O_>         |
                         |           |
                        / print      |
                     ,-'   `---.     |
                     |         |     |
                     R         NR    |
                     |         |     |
                    / \       / \    |
                   <___>     <   >--'

Suppose NR contains a backpointer into the previously traversed structure, either X or R, to some object Y. The algorithm will break down; if that referenced object Y does not appear two or more times in the originally traversed structure, then it was not noted by the algorithm as requiring the special label def/ref notation. It cannot be correctly rendered as a #<n># reference.  (If Y did appear two or more times prior to processing NR, then the occurrence of it encountered via NR is just another occurrence that will be rendered correctly. For instance if Y is represented as label 17, it will turn into #17#.)  If Y appeared once, though, we can no longer go back and patch the #17= label definition in front of it in the output that we already printed; by the time we call the print method which recurses into NR, prior structure has already been printed.
Good sub-case of bad case:
                     X
                     |
                    / \  rendered as #17=Y
                   /   Y < ----------.
                  /     \            |
                 /       \           |
                /         \          |
               <_________O_>         |
                         |           |
                        / print      |
                     ,-'   `---.     |
                     |         |     |
                     R         NR    |
                     |         |     |
                    / \       / \    |
                   <_Y_>     <__Y>---'
     Rendered as #17#         Also rendered as #17#: lucky!

If the second occurrence of Y under R is missing, then the top Y is just rendered as itself without the #17= label. When printing NR, we therefore cannot render Y as #17#; that would be a dangling label ref. We might render Y as a new object, say number 256: #256=(...) which might recurse into NR again, where the second printing of Y becomes #256#. Or we could recognize the situation and throw an exception: a print method pitched us a curve ball unsupported by *print-circle*.
The question is: is it a requirement in ANSI Common Lisp to handle that case? Can print methods procure absolutely any existing object from the image, pass it to the printer recursively, and must it be handled properly, no matter that it is unrelated to the object O and not reachable through that object's slots?
Comment: Is your Lisp dialect implementation available as free software? What URL?
Comment: @BasileStarynkevitch http://www.nongnu.org/txr
Answer: The answer is: yes, but the printer is not required to sweep the whole image, only the objects provided to printing functions.
Nothing forbids the Lisp printer from performing multiple passes or any other technique it can afford.
With multiple passes, the printer could populate per-stream hash tables with the duplicates in the first pass starting with a null stream (e.g. a broadcast-stream with no component streams), stopping recursion on the found duplicates with #n#, then actually print to the destination stream including the #n= markers before the first instance of each duplicate object.
Without multiple passes, the printer could create a special purpose stream which records the position of every printed object to insert #n= markers internally.  One thing that can get simpler with this approach is the per-stream circularity bookkeeping.  However, column counting would not be accurate.
Pretty printers (more advanced than plain printing) usually use a mix of techniques: multiple passes, where the stream used on each pass is a special purpose one with adjustable size, column, circularity table and all other state it needs, plus either performing a last pass or writing intermediate results into the destination tream.
This has only scratched the surface regarding the Lisp printer, especially a pretty printer.  I suggest you search the web for more information, there are a bunch of papers about the subject.  Start with CLtL2 §27. Pretty Printing and XP - A Common Lisp Pretty Printing System.
As long as you use write, prin1, princ or format with ~a, ~s or ~w on the same stream inside print-object, the printer will consider any given object for circularity.  It doesn't matter if a given object is part of some other object's structure or not.  Also, the printer doesn't have to take into account every object in memory, only those that are actually printed.
Essentially, it seems you've duplicated the Lisp printer's behavior regarding duplicates.  By not relying on the printer's effort, you cannot actually guarantee that your own #n=/#n# are unique regarding the top-most write operation that initializes the printer's own circularity context.
Comment: (To clarify, I do not have a printer to rely on; I'm working on a Lisp dialect. I.e I have implemented ANSI-CL-Like circular notation *in a non-ANSI-CL Lisp dialect*. I am not confined by ANSI CL requirements: but that's a separate consideration from knowing what exactly they *are*! I should know where my own requirements stand in respect to ANSI CL ones.