Should CRUD actions be Java classes?

Question: I am working on a simple project developing a telephone directory application. As such, it requires the implementation of the CRUD actions. Right now I have them as individual classes (e.g. "AddEntry"), which are nested under an "Actions" directory. I was considering creating an "Entry" class and having each action as an instance method, but Entry objects are not actually stored as Entry objects; entries are stored in CSV format. Is it proper design to leave the actions as individual classes?
Answer: In layman's terms:

Classes should be modeled after entities, things, not verbs.
Methods should be modeled after verbs.

Then...
The class sould be PhoneDirectoryEntry (a thing) which has a method called save() (a verb).
Bottomline:
No, classes should not be modeled after actions/verbs (CRUD or otherwise).
Answer: Although classes usually represents entities there can be exceptions. For example if you are implementing a command pattern (https://en.wikipedia.org/wiki/Command_pattern) your classes represent actions. So there is no hard and fast rule saying that you cannot model your actions as classes but it depends on your requirement.
Answer: This might be clearer if you think of REST API calls.
Entry is the resource.
Add is modelled as a POST call on the entry resource.
Therefore the java jaxrs would be something like:
@Path("entry")
public class Entry {
  @POST
  public String addEntry(@FormParam("entry") String name) {
    // store csv
  }
  @GET
  public String retrieveEntryFromCSV(@Context UriInfo ui) {
    // get entry
  }
}

Comment: Since this class adds and retrieves entries, it should be called `EntryManager`. An `Entry` object should perform operations based on it's own state, like `save()` where it saves it's state to database, a file etc.
Answer: There's (at least) three directions we can approach the question to find reasons that all suggest a single class with multiple methods is more appropriate.
First, one reason is that each of the individual C,R,U,D operations need access to the same underlying storage.  If you change the underlying storage object/mechanism, that means likely changing all 4 C/R/U/D classes (and if it doesn't mean that then the underlying common storage object is already providing a CRUD abstraction to  hide its details!).  The common underlying storage requirement suggest a single class with methods over multiple classes sharing a common storage object (one class vs. 5 classes).
Second, another reason is we should think about how we might pass around and/or share the CRUD capabilities with other code that wants to use that.  As separate classes, we'd have to pass C, R, U, and D objects separately to various other users of the capabilities.  As a single class, we merely pass around the one entity.
Good programming is about providing abstractions that can be built upon by you and perhaps someone else.  You want to move away from low-level operations and provide useful and relevant abstractions.  These abstractions are necessarily groups of capabilities that are related to each other, packaged together.  Sometimes this means a single class, other times a class hierarchy, and other times a set of interfaces.  A third reason is that as you're not providing a real class hierarchy (but rather instead a flat set of classes), you choose a single class as the packaging for your abstraction.
When we do this right, we separate providers from consumers, which provide for a measure of independence.  This allows for layering where one layer simple doesn't have to worry about all the layers below it because it has just the right tools from the immediately lower layer to implement a useful abstraction for the next layer up.

Should CRUD actions be Java classes?


Why did Prophet Muhammad (PBUH) marry Zainab bint Jahsh?

Question: So this is something I wanted to know the answer about for a long time. Why did the Prophet Muhammad (saw) marry his first cousin but also daughter in law Zainab? This is a question I've also noticed some Muslims are hesitant to answer so if anyone could provide details that would be lovely. Thank you once again.
Comment: I am not sure I understand the question. Marrying a first cousin and former wife of an adopted son is permissible. The motivation behind it should be the same as why anyone else marries, because he liked her and to strengthen his ties with the family.
Answer: Praise to be Allah..
About this marriage, There are some verse in The Holy Quran
In one sentence Answer will be:   This was a ordered, What allah wanted
Firstly we need to read the Holy Quran Verses
From Surah Al-Ahzab (33) : 37-40
if anyone can read those verse carefully, will got the answer....

And [remember, O Muhammad], when you said to the one on whom Allah bestowed favor and you bestowed favor, "Keep your wife and fear Allah," while you concealed within yourself that which Allah is to disclose. And you feared the people, while Allah has more right that you fear Him. So when Zayd had no longer any need for her, We married her to you in order that there not be upon the believers any discomfort concerning the wives of their adopted sons when they no longer have need of them. And ever is the command of Allah accomplished. [37]

There is not to be upon the Prophet any discomfort concerning that which Allah has imposed upon him. [This is] the established way of Allah with those [prophets] who have passed on before. And ever is the command of Allah a destiny decreed. [38]

[Allah praises] those who convey the messages of Allah and fear Him and do not fear anyone but Allah. And sufficient is Allah as Accountant. [39]

Muhammad is not the father of [any] one of your men, but [he is] the Messenger of Allah and last of the prophets. And ever is Allah, of all things, Knowing. [40]

Al-Ahzab (33) : 37-40
There are many things allah give us as a message from those verses
From those verse many islamic rules are implemented in Islam
Some Below

anyone can marry adopted son's wife after divorce/talak
adopted son not actually son of his/her
ever is the command of Allah accomplished, So anyone will not disobey Allah's Order
people will criticism, do not discomfort to obey god's order. fear only allah
Answer: My understanding comes from surah Ahzab verse 37. There's a detailed commentary on this vere here: http://islamicstudies.info/reference.php?sura=33&verse=37-40
I suspect the reason you'll find people hesitant to answer is because schars differ in the details. Which is why I rather refer you to the verse to study and find your own answer.
May Allah bless us all with correct understanding.


Is Styrofoam or Balsawood better for gliders?

Question: I have a project that requires me to use either one of the materials. Which one of the materials is better to use?
Comment: in order for us to answer you, you'll have to define "better"
Comment: What kind of project are you doing? What size? What is your end goal? Balsawood is stronger but foam can resist crash landings during tests more easily
Comment: Better as in based on strength and whether it will affect flight performance (distance flown, etc.), this project's end goal is to make an unpowered glider with a minimum wing span of 30cm that can fly as far as possible in a straight line.
Comment: 30 cm? you shoul probably go to drones.se and post it there then. and include a good explanation of what is "better" for you. "based on strength" does not mean much.
Comment: How will it be launched?
Answer: Good old balsa is generally better.  It is stronger for its weight than Styrofoam, stiffer, and offers variety in building.
Styrofoam is cheap, easily molded and easier to repair.  "Foamies" can be mass produced and are adequate as models with reinforcement such as carbon fibre rods. Several types of foam are available.
Combinations of balsa and foam are possible, such as a foam core with wooden skin.
But building up a truss core structure (lots of triangles), spars, and ribs with balsa instead will save weight and will be far stronger. Skin can be 1/32 " balsa, Monokote, or even doped paper.
Construction will more closely resemble that of a full scale aircraft.


Indexing Calculated field in Sharepoint Online List

Question: In my list, there is a Calculated Field which is being Set based on some conditions and another Calculated Field
So, now it has more than 5000 items and it will keep on increasing.
So, I have read that calculated fields cannot be Indexed but still wanted to know if there is any way through which I can Index my Calculated field or solve my Threshold Error.
Comment: There is not a way to create an index on Calculated column -- but depending on how you want to view the list, there are multiple options for working around the List View Threshold.  Are you trying to fix one or more views in the UI, or trying to access list items through API?
Answer: Calculate columns is not supported for indexing: https://support.office.com/en-us/article/add-an-index-to-a-sharepoint-column-f3f00554-b7dc-44d1-a2ed-d477eac463b0

To solve the list Threshold Error, you could:

Use modern
Add index on other supported columns
Edit the list view

You could read this for more:
https://support.office.com/en-us/article/manage-large-lists-and-libraries-in-sharepoint-b8588dae-9387-48c2-9248-c24122f07c59
Answer: I know this old post but adding info for future search,
As calculated column is not allowed to index, for all the scenario you can use the workaround of creation of text column and adding the power automate to set the value of it as per calculated formula.
So whenever new item is added or edited, that column will be updated and just create index on that column to resolve it.


is there an oil-based sealant to discourage carpenter bees from eating cedar siding and trim

Question: I have read that only a paint or varnish layer will do the trick, but I'm wondering if there's any oil-based penetrating sealant for cedar that has some ingredient carpenter bees find noxious, so I can discourage them from chewing up my siding and trim.  Last summer was really bad, and today they're back.
Answer: They're are insecticides that will keep these flying drill bits from nesting in your eaves. The ones I know of need to be applied by a pro but seem to be good for multiple years.
Comment: Thanks. I have to look into whether the application is a coating, or a spray that could get carried on the air onto shrubs.
Answer: I too have had this problem... adding a lavender bush next to house with pine siding is asking for trouble.
But to answer your question, yes and no. Regarding noxious, the solvents (in the varnish) will repell the bees for a short while (the first year perhaps). But to be sure, it won't keep the bees out indefinitely. edit- I think that you would have to deep seal it with shellac, then perhaps epoxy over that, which should pretty much blow your budget. Borates are the most common wood treatment (before you varnish). You can also use carbaryl (sevin) for short term fix (every summer) after you varnish.
Comment: A side note- the toxicity of carbaryl toward bees is so high, manufacturers don't like to mention it, on account of issues with honey bees.
Comment: Thanks for the caveat. http://www.ct.gov/deep/lib/deep/pesticide_certification/Supervisor/protecting_honeybees.pdf
Comment: Carpenter bees have a similar level of sensitivity, and since honey bees don't really spend much time on houses, carbaryl is a good choice for dealing with carpenter bees. The only drawback is that carbaryl only lasts for about 2 weeks.


Habitability inside an enclosed solar system

Question: In D&D Spelljammer, there's a concept of "crystal spheres" that enclose a solar system, with its radius being double the radius between the sun and its furthest planet. For my solar system, I did all the calculations for its "habitable" zone, and I found out that I can (barely) fit two habitable planets within it. I was hoping for several unique planets within the solar system. My question is, if the entire solar system was enclosed, would the sun's heat be trapped, almost like an oven? I think it would radiate slowly through the crystal, but would the ambient heat be enough to theoretically extend the habitable zone?
Comment: Welcome to the site spacemagician3001, please take the [tour] and read up in our help centre about how we work: [ask] Absolutley it can, if you say so, you're the author. It's not as if the "crystal sphere" is of a real-world material with known properties. It's your world, you get to define it. It reflects in as much heat and light as you want, or lets it out, or changes over time - your choice. If you need a scientific answer, then you need to ask a different question with different tags. At the  moment your question is too opinion based, so I'm voting to put on hold 'till you [edit] it down
Comment: I agree with @Agrajag.  If the crystal material is a thermal insulator, it will hold the heat.  If it's not (or if it's 100% transparent to EM radiation) then it won't.  If it's reflective on the inside, that could actually be a bit cool.  No stars at night, just this really low light level.  However, keep in mind that it won't be like an oven.  There's no atmosphere in space (and would not be here).  The energy is trapped, which would heat the crystal, but nothing else - unless it completely reflected all EM radiation.  That's interesting.  Where do you want to go from here?
Answer: Yes, the habitable zone would be extended. And widened as well. This is because planets would gain some heat from infra-red radiation of the sphere and it would be uniform inside the sphere instead of centered on the sun. How big the difference is depends on the inner surface temperature of the sphere, which in turn depends on its ability to radiate heat outside. Note that this also evens out the seasons!
Reflectivity affects the spectrum the sphere radiates at. A more reflective sphere will contribute larger proportion of its energy in the visible spectrum. The night would not necessarily be dark.
And other effects are possible. A sphere that is reflective in the UV range would make seeing UV light much more practical. More likely it would be set to reflect in the near infra-red and night vision of many races would be boosted by that.
But you should ignore all that. Spelljammer has as its basic premise that pretty much all that we know about space does NOT apply. Specifically the spheres, the suns and the planets are created with and kept in order with divine magic. So the habitability of a planet is whatever who created it set it to be. Unless some other divine class power meddles with it or the powers that set it up lose their power or some similar stuff.
While you could mix science with it and stuff like there is more near infra-red because of the sphere and the sky looks very different to elves than it does to humans is a nice touch IMHO, that is probably as far as you should take it. Specifically that the celestial mechanics and planetary formation and habitability do not follow scientific principles is, as I said before, part of the main premise of Spelljammer. It is connected to the main point of doing Spelljammer at all. If you want your setting to be like Spelljammer, you should keep that unscientific IMHO.
This does actually apply to some extent even when the sphere is actually a precursor Dyson sphere. The precursors would have shaped the way the sphere radiates to affect the planets in the way wanted. If you are going to build a Dyson sphere and keep habitable planets inside it taking that extra step is absolutely trivial. Amusingly this would allow different planets in the same system to see different constellations or the constellations to actually change over time because the stars would actually be simple sources of light pointed at the planet covering the sphere. The administrative AI would have full real time control of what people see.
Comment: Where are you taking "planets would gain some heat from infra-red radiation of the sphere and it would be uniform inside the sphere instead of centered on the sun." from? OP never specified that.
Comment: @L.Dutch What exactly is the issue?
Comment: It's a magic crystal sphere, with unspecified properties. You are assuming it is opaque to IR, but the OP never stated or negated it. Actually, didn't specify at all what this sphere does.
Comment: @L.Dutch That is fine then, I'll probably rewrite that part eventually because it has an error (unrelated to your concern and not really important to the question) but as for this I am simply assuming it has a temperature that is not absolute zero. That is justified by this question being asked at all. Even if it is magic if it did not interact with EM at least to that extent this question about heat being trapped would make no sense. In fact the question specifically talks about heat and radiation being trapped.


Why do coherent states behave semi-classically, but harmonic oscillator states do not?

Question: A coherent state of the quantum harmonic oscillator is defined as an eigenvector $|\alpha\rangle$ of the annihilation operator $\hat a$ with eigenvalue $\alpha$ or as spatial translations of the ground state of the QHO:$$T_{x_0}|0\rangle = \exp(-\frac i \hbar\hat px_0)|0\rangle:=|\bar x_0\rangle$$the definitions are equivalent when $\alpha$ is real. Coherent states exhibit certain semi-classical properties, such as the following:$$\langle \bar x_0|\hat x_H(t)|\bar x_0\rangle= x_0\cos\omega t,$$where $\omega$ is the angular frequency of the harmonic oscillator, and the $H$ subscript represents a Heisenberg operator. We have also $$\langle \bar x_0|\hat p_H(t)|\bar x_0\rangle = -m\omega x_0 \sin \omega t.$$ So that both the expectation value of position and momentum oscillate with time, in contrast to the energy eigenstates of the harmonic oscillator, which have vanishing expectation values for these operators. So, my question is: why do the coherent states actually behave like oscillators, when the harmonic oscillator energy eigenstates do not? What is a physical intuition for why the expectation values vanish for the QHO energy eigenstates?
Comment: Energy eigenstates also behave like those of a classical oscillator, whose energy remains constant in time :)
Comment: @RogerVadim But they do not oscillate with time.
Comment: oscillator energy does not oscillate with time. In fact, if we start with the time-dependent Schrödinger equation, then there is factor $e^{-i\omega (n+1/2)t}$.
Comment: @RogerVadim I am referring to the expectation values of position and momentum. In which case, the factor you mentioned gets cancelled by its inverse.
Comment: @DanileWaters I see. I gave an answer - perhaps, it is not complete, but too long for the comments section.
Comment: These formulas that you write are valid in any state (if generalized by allowing some constant phase shift, as usual also in classical mechanics), due to the Heisenberg equations of motion. The energy eigenstates just happen to have the oscillation amplitude $x_0$ equal to 0.
Answer: The discovery and study of coherent states represents one aspect of one
of the biggest problems physicists have faced with the birth and the
subsequent development, supported by excellent experimental results, of the
quantum mechanics: the search for a correspondence between the new theory, conceived
for the analysis of microscopic systems, and classical physics, still fully valid
for the description of the macroscopic world.

The history of coherent states begins immediately after the advent of mechanics
quantum: their introduction on a conceptual level dates back to a
article published in 1926, in which Schrödinger reports the existence of a class of
states of the harmonic oscillator that show, in a certain sense, behavior
analogous to that of a classic oscillator: for these states it is verified that the energy
mean corresponds to the classical value and the position and momentum averages have
oscillatory forms in constant phase relation.
Returning to Schrödinger's article, the "almost classical" states from him
identified present, in addition to the characteristics already mentioned, an important aspect:
being represented by Gaussian wave packets that do not change shape in the
time, guarantee the minimization of the product among the uncertainties about
position and on the impulse, that is the condition closest to the possibility of measuring
simultaneously the aforesaid quantities with arbitrary precision, allowed
from classical physics.

So, starting from the following relations:
\begin{equation}
a^{\dagger}|n\rangle=\sqrt{n+1}|n+1\rangle \quad a|n\rangle=\sqrt{n}|n-1\rangle
\end{equation}
it is noted that, by virtue of the orthonormality of the states
stationary, the diagonal matrix elements of the position and momentum operators are
null in the representation of energy, which means that the expectation values of
position and momentum on any stationary state are zero instant by instant.

The stationary states just analyzed are characterized by distributions of
constant probabilities with respect to the position over time; the wait values of the position e
of the impulse are null at all times: this aspect is a fundamental one
difference with the states of the classic oscillator, for which, once the energy is defined
(as long as different from zero), the observables position and momentum evolve over time
according to sinusoidal functions and are always in phase quadrature with each other. Also, if yes
calculate the uncertainties on position and momentum for a steady state with n photons, yes
gets the uncertainty relation $\Delta x \Delta p=(n+1/2)\hbar$.
it is therefore possible to obtain the minimization of the product of the uncertainties on impulse and
position, which represents the maximum similarity with classical mechanics.

A state that is as similar as possible to the classical case must therefore
have the following characteristics:

1): The evolution over time of the position and momentum expectation values must
be of a simple periodic type, with a constant phase ratio between position and
impulse.

2): The wave functions must be as narrow as possible around the value
average of the position, so that the probability distribution with respect to the
position may tend, by varying appropriate parameters, to a delta function of
Dirac;

3): The product of the uncertainties on the position and on the impulse must be minimal.

So you can see this "classical" behavior, that admits these particular states, as an intrinsic property of QHO.
Furthermore I have say that: also the harmonic oscillator energy eigenstates actually behave like oscillators.

Maybe this answer is a bit too long but I hope it can help you.
Comment: I had a thought regarding the oscillatory behavior of the stationary states. Considering them as translated ground states, can we think about the oscillation  of $\langle \bar x_0|\hat x_H(t)|\bar x_0\rangle$ in time as if we had "pulled" the spring by a distance $x_0$, as in classical mechanics?
Comment: You can think as if you had "pulled" the spring but only if you think $\langle x \rangle_t$ as a statistical average of several measures of the same experiment prepared in the same state. And also if the distribution of values is narrow i.e. the state of the particle is localized in regions much more smaller compared to the typical length in the experiment. In this limit you can use average value as a good approximation. And so you can think as you said.  This is the "limit bridge" beteween CP and QM: consequence you can see starting from the Heisenberg rapresentaion.
Answer: The energy states of a harmonic oscillator can be thought of as averaged over the initial phase of the oscillations.
Indeed, it is instructive to look at how the correspondence principle works for a harmonic oscillator at high energies:

For a quantim oscillator the probability of finding the oscillator in the interval $(x,x+dx)$ is given by
$$p(x)dx=|\psi_n(x)|^2dx$$
For classical oscillator the same probability density can be calculated as
$$p(x)=\int_0^{2\pi}\frac{d\phi}{2\pi}\delta\left(x-A\cos(\omega t + \phi)\right),$$
where $A$ is the amplitude of the oscillations, and $\phi$ is the initial phase of the oscillator, averaged upon.
After a bit of mathematical manipulations we arrive at
$$
p(x)=\frac{1}{\pi}\frac{1}{\sqrt{A^2-x^2}}.$$

The quantum and classical cases then compare as in the figure linked here:
More detailed discussions are available from many sources and can be found by googling harmonic oscillator classical limit or harmonic oscillator correspondence principle.
Remark:
This could also be viewed as the expression of the phase-number uncertainty, as the coherent states have well-defined phase, $\phi$, whereas the eigenstates have well-defined number of quanta $n$.)
Comment: So I see that you were speaking of the semi-classical nature of QHO energy eigenstates. Thanks for clarifying that they do behave somewhat classically.
Comment: Indeed, one could call the HO eigenstates *incoherent states*, since they average over phase... in fact, all this might be tied to the phase-number uncertainty (*coherent states* have well-defined phase, while the eigenstates have well-defined $n$.)


Do Latin American speakers use vosotr@s when in Spain?

Question: I do understand that vosotr@s is not used in most, if not all of Latin American Spanish-speaking countries, but suppose a Mexican or a Peruvian goes to Spain to see his distant relatives (who use the peninsular variety of Spanish), will he start using vosotr@s to avoid sounding too formal?
Comment: I'm voting to close this question because it calls for an opinion.
Answer: Latin American speakers of Spanish may understand vosotros to be formal.  This is because virtually their only exposure to it is through reading of the Bible.  (This is similar to the way English speakers have attached a formal sense of meaning to words like thee, thou, and ye, despite those being the informal equivalent of words like tú and vosotros in the old English.)
When I first arrived in North America from Spain, speaking Castilian Spanish, I regularly used "vosotros."  I soon learned not to, because most often the Mexican, Cuban, Puerto Rican, etc. speakers with whom I was speaking would understand "nosotros" in its place.  It took me several weeks to adjust--maybe over a month.  But it is unlikely to be the same for Latin Americans going to Spain, because they habitually use ustedes, which would not be at all confusing (just more formal).
I would guess that some would never find the need to adapt, but that most would gradually begin using "vosotros" as they became accustomed to hearing it--depending on how quickly they adapted, and on how much they interacted with the Spaniards, anywhere from a few weeks to a few months.
Comment: This is a matter of opinion. My husband is from Spain and never changed his way of speaking. The Spanish speakers from elsewhere all understand him. So, this was your choice, it is not everybody's. Anyway, all this is just opinion and has no "scientific" validity at all. Also, Spanish speakers from other parts of the Spanish speaking world see a lot of TV produced in Spain. And I think they must understand it just fine.
Comment: You may choose to regard it as a matter of opinion if you wish. I simply shared my experience.  It is true that each one has a different experience. One of the other reasons I changed was because people informed me that using the Spanish informal pronouns was disrespectful when used toward those older than you. In Spain, students can use tú even with their teachers, and people use tú to address God in prayer, so, although I did not feel in agreement with them, I did try to speak according to their standard so as not to offend.  I would be interested in if your husband had a similar experience.


Milestone behavior in MS Project

Question: I am working in MS Project with a project someone else set up. This project contains 29 activities which are auto scheduled, has a minimum start date constraint on an activity, and two milestones. The behavior of the milestone is odd. It seems like the milestone itself is arranging the successor events so the resources have no overlapping activities. When I take out the milestones and adjust the dependencies I have overallocation warnings in the indicator column. In addition multiple activities with the same resource are scheduled on the same date In the Gantt chart. I tried switching the activities to be manually scheduled and the same thing happens. How do milestones effect the resource over allocation? How do they affect the assignment of the start dates of the successor activities.
Comment: Note that MS Project will not move dates based on the resources used unless you have it level the resource. This can be dangerous as it can expand the timeline significantly. If you have set up relationships between your tasks and milestones, then MSP will honor the work flow of predecessors and successors.
Answer: Milestones don't directly affect resource allocation. They are just another element in your schedule (tasks, summary tasks, and milestones). Milestones are scheduled the same way tasks are except they have no duration.
It is likely that the milestone you are referring to was being used as an anchor to prevent an overlap of resources. As an anchor, I mean someone put a constraint on it pushing it into the future to avoid a resource over-allocation. Without seeing an image of your Gantt, I can't confirm this, but that is my thought. This is not the way I would do this.
My preferred method would be to remove the milestone and simply add task relationships that take into account the sequence of work the resource will perform. This will provide for a realistic sequencing of tasks rather than allowing Microsoft Project to resolve the over-allocation. I don't ever want Microsoft Project to make resource leveling decisions for me in my schedules.
Comment: +1 for: "I don't ever want Microsoft Project to make resource leveling decisions for me in my schedules."

Milestone behavior in MS Project


Red Moon a Characteristic of all Total Lunar Eclipses?

Question: I understand that the redness of the moon during the total lunar eclipse last night/this morning (April 14-15 2014) is a reflection of the red light caused in earth's atmosphere due to Rayleigh scattering (basically, a reflection of all the sunsets and sunrises happening around the earth).  Because of this, it seems to me that the moon will appear red during every total lunar eclipse that happens.  Is this the case, or are there some lunar eclipses where the moon does not turn red?  If it is the case that all total lunar eclipses produce a red moon, why was the media so hyped up about last night's eclipse producing a red moon?  Was it especially red?
Answer: No, not all total lunar eclipses will turn the Moon deep red. Most of them do, but not all.
If you were standing on the Moon during the eclipse, you'd see the Earth passing in front of, and obscuring, the Sun. But the Earth will never become fully dark, even when the Sun is fully covered. A bright ring will always surround the Earth. Why?
That ring is sunlight refracted by the atmosphere. It's there because the Earth has an atmosphere. You could say it's all the sunrises and sunsets of the Earth, all seen at once. It's this light that continues to illumine the Moon during the eclipse.
But why is the Moon red, instead of some other color? This is because the blue end of the spectrum is scattered more easily in all directions (same mechanism that explains why the sky is blue on Earth), whereas the red part of the spectrum is scattered less easily and moves on a straighter path along the refraction lines. The bright ring around the Earth, as seen from the Moon, is probably red, because most of the blue in it has been scattered away.
Now, if the Earth's atmosphere is full of dust particles from huge volcanic eruptions, the bright ring is a lot weaker. That makes the Moon during the eclipse a much darker shade of red. Sometimes the Moon is a very dark, dull grey during the eclipse, no red hue at all - so dark in fact that it's hard to see in the sky while the eclipse is full. This has happened some decades ago after the Pinatubo eruption.
http://en.wikipedia.org/wiki/Lunar_eclipse#Appearance
http://eclipse.gsfc.nasa.gov/LEcat5/appearance.html
EDIT:
A measure of the brightness and color of a lunar eclipse is the Danjon scale. Eclipses are rated between 0 (almost invisible, black or very dark grey) and 4 (bright orange with bluish rim).
http://en.wikipedia.org/wiki/Danjon_scale
http://eclipse.gsfc.nasa.gov/OH/Danjon.html
My estimate is that the last eclipse was a 3.
I can't find a list of recent eclipses rated on a Danjon scale, but here's a list of 20th century eclipses, with a measure of the magnitude of the umbra.
http://eclipse.gsfc.nasa.gov/LEcat5/LE-1999--1900.html
As you can see, the magnitude varies quite a bit.
Bottom line: each eclipse is a bit different. A majority would have some kind of orange, copper or red tint. A minority are too dark to see any color. Unusual colors (outside of the red-yellow interval) are very rarely possible. Brightness and hue varies from one instance to another, since it depends on Earth's atmosphere, which is a system that changes greatly over time.
Comment: Just a point is reflection should not named. Light truly reflected from Earth can be sort of green , blue or white from water, and brown sort from desertic areas  most important reflected light cannot it the moon during eclipse.  The phenomenon is purely based on the light that goes throughout the atmosphere ( and so does twice, to reach our eyes).
Comment: His question showed that he understands the process, his question was about the degree and the corresponding media attention. Your link to the NASA site has a good reference on the scale of colour, that is a useful addition.
Comment: Indeed, I do understand the process.  Your information on how volcanic eruptions affect the appearance of the moon was enlightening.  Barring volcanic eruptions or some other source of an excess of ash/dust in the air, will the moon always appear red during a total eclipse?
Comment: I've added an edit to the reply, expounding a bit on the Danjon scale, umbra magnitude, and variability of lunar eclipses (TLDR: all are different, most are red, a few are too dark to have any color).
Answer: Pretty most all lunar eclipses will turn the moon red like that. The amount of redness does vary, and sometimes so little light gets to the sun it is almost completely dark. However the redness is so typical of a lunar eclipse that NASA describes it as a "characteristic orange-red color". That link has a neat table with a categorization of the colour ranges.
Probably what triggered the media's "do a story on that!" bells was lots of chatter they noticed online, mostly from the loony fringe making more of it than it deserves.
The reason for the extra attention was probably because this lunar eclipse (I can't bring myself to write 'blood moon' ick I've done it) is coincident with the Jewish Passover - not a surprising event, as Passover is always when the moon is full after the spring equinox. It happens that the Passover that was celebrated the evening before the day Jesus was executed was followed by a lunar eclipse, and the Bible makes mention of 'the moon being turned to blood.' Simple and straightforward, but then some people start going off on their own weird supposes and imagining that Jesus' second coming will occur on another lunar eclipse, as if a lunar eclipse after the spring equinox was the only time it is possible for him to visit. So you get lots of internet chatter, the media notices what is trending on twitter and does a half-baked story.
Lunar eclipse will occur in other months too, but without this association, people don't seem to care as much.
Comment: "All lunar eclipses will turn the moon red like that." - incorrect. I'll post a more detailed answer below.
Comment: Well, I can tweak it some also.
Answer: The redness of the moon is due to Earth's atmosphere refraction of Sun rays and pollution - dust particles etc. The intensity of the colouring will depend on the path the moon takes through the Earth's corona.
If it goes right through the middle  then we will see a darker moon, while if it travels close to the edges then the influence of refraction and pollution will be greater and thus a redder moon.
Answer: One other aspect: if you are seeing the lunar eclipse too close to sunrise or sunset, with the sky still relatively bright, you can lose the Moon's color. Atmospheric light scattering effectively cloaks the reflected light returning from the Moon (after the atmosphere had refracted the light onto the eclipsed Moon).
But atmospheric scattering is not all bad. In small amounts it can actually give an enhanced contrast. The N9vember 2022 total lunar eclipse came a few hours before sunrise in Chicago, and the view in that city (perhaps aduded by atmospheric scattering of the city lights) looked like this:


I had a sex dream and didn't ejaculate

Question: I had a sex dream last night (there was no penetration but there was other sexual activities). There was no orgasm during the dream and when I woke up, I didn't find anything on my clothes, so basically I didn't ejaculate.
My question is, do I have to take a shower(ghusl) even though I didn't ejaculate? Just because I had a dream about something sexual? If I don't take a shower, will that break my fast?
Answer: Firstly, a wet dream does not have any effect on fasting at all. It only effects your ritual purity for purposes like prayer, and ritual purity is not a condition for observing a fast.
Secondly, if you saw a dream but did not find any traces of fluid, then you do not need to perform ghusl.

عن الرجل يرى أنه قد احتلم، ولا يرى بللًا، فقال: لا غسل عليه
He was asked about a person who remembered that he had a sexual dream but did not find moisture. He replied: Ghusl is not necessary for him.
— Sunan Abi Dawud

I had a sex dream and didn't ejaculate


Entries of the Inverse Laplacian

Question: Let $L$ be a graph Laplacian. What is the meaning of the entries of its (pseudo)inverse $L^{-1}$? In other words, are there any interpretations which might help with understanding the entries of $L^{-1}$?
Comment: There is no graph - your link is missing.
Comment: I fixed it, thank you.
Answer: I originally wanted to pose the question, but then I started investigating and found a few very helpful interpretation that haven't been collected anywhere (to my knowledge). Hence, I will write my results here for future reference:
Interpretation of the entries of $L^{-1}$:

The i'th row (or column, it's symmetric) of $L^{-1}$ represents the voltage at vertices required such that the unique electrical flow sends a total of 1 unit of flow from the i'th vertex in a way that each vertex receives $1/|V|$ units of flow.

Let the energy of a flow $f \in \mathbb{R}^E$ be $\sum_{e \in E} f_i^2$. Let the effective resistance between two vertices $u, v$ be the minimum energy requred to send a unit of flow from $u$ to $v$. The effective resistance between $u, v \in V$ is $(1_u - 1_v)^T L^{-1} (1_u - 1_v)$ where $1_i$ is the i'th canonical basis vector.

(Assume the graph is connected, degree regular, and not bipartite.) Let $s, t \in V$. Start with +1 units of "supply" in $s$ and -1 of "supply" in $t$. Do a random walk (each vertex chooses a random incident edge and pushes all of its supply to the other node). The expected amount of supply at node j (summed up over all steps) is exactly $M_{sj} - M_{tj}$ where $M := L^{-1}$ (I had to introduce M due to some MathJax+SE formatting issue).

Entries of the Inverse Laplacian


Air spark temp equation

Question: Is there an equation that can be used to determine the air temperature around a given spark discharge? Let's say I produce a 50K volt spark between two wires using a standard HV generator. I'm sure the air in close proximity to the discharge must also rise in temperature, but how to get a practical idea of its temperature and more importantly, the temp gradients around this air? An equation would produce more useful data. Thanks!
Comment: Near the spark, radiation temperature is going to dominate material heat transport as the source of local temperature. You can approximate radiation temperature by assuming air is transparent, drawing a symmetric surface around your arc, and treating the symmetric surface as a blackbody with a radiant flux of $IV$. Note that arcs are non-ohmic resistor so you can't just use the breakdown voltage, you'll need to actually measure, or find an experimentally curve-fit formula to estimate from.
Answer: Determining temperature is never easy because of the heat equation which is a differential equation. Temperature is determined by rate of energy input vs rate of dissipation into the surrounding environment, and the rate is controlled by the difference between the two, but the difference changes if they have not reached equilibrium.
But in your case, you might be in luck because if the spark is large and fast enough, the flow out could be neglected since the rate of energy in is significant compared to the rate of energy out. Then you can use adiabetic heat transfer where all the energy transferred in, stays in.
So you would then just need voltage across and current in the spark gap to calculate input energy. Then use that to calculate how much a volume air would heat up after accounting for the energy required to ionize (similar to phase change energy when something evaporates) which won't contribute to temperature rise. Air volume seems tricky to determine though.
No gradients though. That is the first principles heat equation and simulation territory with differential equations.

Air spark temp equation


Protect page from guest users

Question: I am using drupal for one of my portals. Logged in users can see the "documentation link" button in the application which is pointed to an html page. My concern is that, that link is accessible even if someone bookmark the link and open it without logging in to drupal portal. Is there some option/module in drupal available so that if someone access our documentation link directly, it should redirect to login page and load the html page if he is already logged in.
Comment: You could set something like that up but it would be awkward and goes against good practice (and not something someone's likely to write a tutorial for here). You'd have to change the HTML page to something dynamic whichever way you look at it, so you may as well do it the proper way and move your HTML page(s) into Drupal's routing, protecting with permissions as normal
Answer: Assuming that documentation link is a landing page either resulting from a content type or View Page, you can easily restrict the access to that page via permissions. The concept can be found using Node View Permissions. Although the module is overkill, it will provide ways on how to use it. The recommendations would be to do this through standard permissions first and then use modules or write your own custom module to do this for you.
Additionally you could write a hook that checks to see if user is an anonymous user, if so then let them through otherwise redirect them to a login page. In D7, you can write a hook to check the user_is_logged_in variable. In D8 this answer to check for logged in users.
Other module:

Content Access

Also when you add questions, please indicate if it's for D7 or D8.

Protect page from guest users


Apply button is greyed out in subdivision modifier how to fixe this?

Question: The subdivision modifier apply button is grayed out, therefore I am unable to apply. Below is the screenshot for clarification.
Comment: Most likely this donut is linked duplicate (alt+D) of another one. So that they share the same geometry and you can't modify this geometry applying the modifier. Use "object/relations/make single user/object and data" so that it is no more linked.
Comment: Why is that. Does Blender does not support modifier on linked object?
Comment: It supports modifiers on linked objects, but applying them will modify the geometry and as this geometry is shared by other objects, this is not allowed.
Comment: But if you link the modifier it is ok. Select both objects (the one with the modifier as active) then ctrl+L and "modifiers". Now you can apply on all objects.
Comment: From what I understand. We can indeed apply modifier on the link object, but it is not good practice. It is better to apply the modifiers then make the linked duplicate copy. But not before.
Answer: I managed to solve the issue by selecting the object on which I have to apply sub div modifier, then I "make the single user object and data".

The problem was that I had created a Duplicated Linked object Alt + D instead of a Duplicate Object Shift + D.
For those who does not know the difference between Duplicated Linked Object Alt + D and Duplicate Object Shift D below is the explanation:

The  duplicate linked  Alt +D works as an instance. Meaning it creates the instance copy of the original model, and if I make changes on one model it will affect both.

The duplicate object Shift + D makes a complete separate copy of the object. Meaning that any changes to it will not affect the original model, as it is a completely as separate object.


How can I cache untracked (binary) files associated to a branch?

Question: Assume I am one of many developers working with git on a huge code project, which has an incredibly long compilation time.
Now, my personal day-to-day changes are usually limited, and the codebase is decently modular, which means that as far as my personal work is concerned, compiling from scratch is a price that only has to be paid once. Afterwards, I can recompile only the modules I modified.
On the other hand, I frequently have to fix bugs in (at least two) branches which reflect states of the codebase completely distinct from the branch I work on. Those two branches are indeed the result of work from the entire development team, and often have entire modules rewritten or added. Having compiled everything before pushing a bugfix is mandatory.
My first approach was to switch from my development branch every time a bugfix is needed, then clean, bugfix, recompile from scratch, push, switch back to the original branch, clean again, recompile - the delay for doing this is intolerable.
I then moved to keeping three separate checkouts of the codebase on my machine. This solves the "costly recompilation" problem (my changes in every branch are incremental again), but it makes the question "what am I developing on right now ?" more complex to answer (since it depends on the current directory), and it makes synchronization of these three copies complex (it multiplies all the routine push/remote update/pull commands I have to do by three).
A simpler solution would be to have the ability to save the state of a directory (untracked, where I generate compiled files) every time my checkout "leaves"a branch, and to recall the state of that directory, if it exists, every time I "enter" (checkout) a branch.

Are there git commands that would help me achieve this behavior ?
If not, is there a tool that would allow me to do that ?
If not, does git provide checkout hooks that could help me script this behavior ?
Comment: A not so elegant solution is to append, for example, the branch name,  to the compilation output folder, and rename it back when you are working on that branch.
Comment: @nhahtdh: I think that's the most elegant solution as long as all those folders are inside a common folder so you don't clutter the root source folder with those folders.
Answer: I would suggest to use stashes, they are pretty close to what you need.
In recent versions of git, you can stash untracked files with the --include-untracked option. You can also give messages to your stashes and recall them, so you can check in which stash must be applied after checking out a branch.
#before leaving branch
git stash save --include-untracked "compiled stuff for my_branch"
git checkout another_branch
#what stash contains compiled stuff for another_branch?
git stash list
git stash pop stash@{n}

You can script a bit to make things more practical...
Comment: Thanks a lot ! very good suggestion ! I think you have to put the `--include-untracked` *after* the `save` command though.
Answer: I'm afraid I do not have exact answers as I did not have to deal with a case like yours, but anyway I'd like to provide possible hint: Git is able to use several distinct work trees "connected" to a single repository (read more in this answer for instance), so instead of maintaining multiple checkouts, you can just use multiple work trees with a single repository.
I should add that I like @CharlesB's solution better (conceptually) but on the other hand I would measure: supposedly git stash would effectively copy your files when turning them into blobs to store in the stash which would a) temporarily double the space occupied by those huge files on the filesystem; b) have unknown long-standing effect on the size of the Git's object database size.
Answer: My 2 cents : keep track of the compilation directory as a submodule - but as I haven't used this git feature yet, I can only point you to the doc page...


Should I use a voltage regulator?

Question: I'm powering an attiny45 from a single lithium ion battery; that when fully charged should have a maximum voltage of ~4volts and will be cutoff at 3volts. I was thinking I should be safe to just directly connect the attiny to the li-ion battery, am I right? Or am I missing something?
Answer: The safe voltage range for the ATtiny45 is between 2.7V and 5.5V, so you should be able to connect the battery directly to the MCU provided you don't need a different specific voltage for external components.
A switching power supply could allow you to get longer life out of the battery if you run it at about 3V or so the whole time, both because the MCU will use less current at the lower voltage and because the reduction of output voltage with a switching regulator translates to a reduction of input current (after taking the regulator efficiency into account).
Comment: @Passerby: Does that cover it?
Comment: Eh I see what you mean now,  but the gain probably isn't worth it.

Should I use a voltage regulator?


Should a privileged port (<1024) be used to deploy Postgresql in production?

Question: I've never found a recommendation to run Postgresql on a privileged port in production. What type of port should be used in production regarding security and best practices?
Comment: In production, PostgreSQL will typically be on its own box alone without user accounts or on a box where user accounts are considered to be safe, that is not knowingly attacking things by trying to start processes that bind on important ports. Also PostgreSQL should be configured to start on boot before many other things, which reduce the window opportunity to grab its TCP/IP port.
Comment: Linux. Sorry for leaving that out.
Comment: Why would you want to run Postgresql on a privileged port? Why run on any port other then the default? Changing ports is merely security through obscurity anyway.
Comment: What operating system?
Comment: @Colin'tHart If  I use a non-privilege port, won't any executable be able to take over the port and listen in on the traffic?  Granted, this is general advice I have read and not specific to PG deployments.
Comment: @Colin'tHart Correction on my part: I was worried about `server spoofing`. Not about external attacks. Turns out the PG manual already discusses how to prevent server spoofing: https://www.postgresql.org/docs/current/static/preventing-server-spoofing.html
Comment: If postgres starts first no other application can claim port 5432 or listen to the traffic.
Answer: Using a privileged port for Postgres would require the postgres daemon to run with root privileges, which in itself is a security vulnerability. So, no, you should not use a privileged port for Postgres.
Comment: "to run with root privileges" or be just given the appropriate capability to bind to low numbered ports. No need for full root rights to do that on any modern Unix system. See this example: https://stackoverflow.com/a/414258/6368697
Answer: Running PostgreSQL under 1024 requires some hacking. It's almost impossible outside of win32. From the backend/main/main.c,

"root" execution of the PostgreSQL server is not permitted. The server must be started under an unprivileged user ID to prevent possible system security compromise.  See the documentation for more information on how to properly start the server.

After which the backend calls exit(1). It also doesn't run as a setuid script. From the source,

Also make sure that real and effective uids are the same. Executing as a setuid program from a root shell is a security hole, since on many platforms a nefarious subroutine could setuid back to root if real uid is root.  (Since nobody actually uses postgres as a setuid program, trying to actively fix this situation seems more trouble than it's worth; we'll just expend the effort to check for it.)

The only way to even set this up on Linux that I know of is

IPTABLES
Reverse Proxy
Recompile the kernel
setcap with cap_net_bind_service capability (never tried it)

However, if you are worried about server spoofing (another server taking over the non-privilege connection before the PG executable) you can still be secure if you take some pre-cautions, as explained in Preventing Server Spoofing:

Local connection: use a Unix domain socket directory (unix_socket_directories) that has write permission only for a trusted local user.
Local connection: use requirepeer to specify the required owner of the server process connected to the socket.
TCP connection: the best solution is to use SSL certificates and make sure that clients check the server's certificate.
Comment: What about using setcap with CAP_NET_BIND_SERVICE on the executable? Or would that lead to just another security hole?
Comment: erg, turn off connections from Unix domain socket. Not UDP, typo.
Comment: SSH port-forwarding is the simple and secure way to bind any service to any desired port not already used.
Comment: @da99 I actually think that may work I'll update my post.
Comment: @EvanCarroll Thanks again for all your help.
Comment: @da99 yea, if your goal is simply to prevent server spoofing **use ssl** and just turn off UDP.
Comment: @EvanCarroll Is UDP used just for PG statistics? Should I ask a separate question about this? I seem to be having trouble finding it in the PG manual.
Comment: @EvanCarroll Should  Kondybas's comment (ie use SSH port-forwarding) be included too?
Comment: @da99 I'm cool with that, it's just a reverse proxy though =) Yes. SSH can do it, and it's a pretty reasonable method of doing it. You would have to run SSH as root though, or use `capabilities` or something.


Dogs peeing inside my house

Question: I have 4 adult male dogs and a very large kitchen with a doggy flap. My dogs can hold their pee which has been proved when we go away and sleep in the caravan but when I go to work, go to bed or even just nip out I come back to puddles of pee.
They can get to the garden all day and night but they still insist on peeing inside and destroying my kitchen. It is becoming exhausting and making me resent my beloved pooches.
What can I do or use to stop this happening? I refuse to crate them as I have the doggy flap.
I would appreciate any help what so ever
Comment: What are the breeds and ages of your dogs?
Answer: Two possibilities: either they get anxious when they are left in the kitchen for some reason, and react by peeing, or they just don't understand that peeing in the kitchen is something they are not supposed to do. If you have four of them all loose together, it's going to make it hard because if just one gets confused and starts marking, then it will encourage the other three to do the same.
Personally, I would use  (large, comfortable, well padded) individual crates for each dog short term while you are re-training this behaviour.  That way you can at least work out which dog is doing it, and where you need to focus your attention on retraining. You can then eliminate the crates as you establish which dog(s) need more help, so you don't have to have your kitchen stuffed with huge boxes forever. It may well be that one or two of them are not part of the problem at all, so if you can borrow crates even for just a couple of weeks, that might be long enough to give you a clearer idea of where the problem lies.
Scrub the whole area with a cleaning agent designed to eliminate dog odours.  Simple Solution is widely recommended, although there are a number of products that will do the job.  You will need to check that no urine has seeped into the floor or under kitchen units: their noses are very sensitive and if they can still smell it, then they will be stimulated to urinate in that area again.
I would also suggest that you video their behaviour while you are not there, so you can see if any individual is just peeing in an absent minded kind of way, or if they are pacing, howling, barking or appear otherwise stressed. Sometimes, you'll find that dogs can hear sounds, pick up scents, see animals passing or pick up vibrations in one room that they can't detect elsewhere, and that makes them more anxious in that location and more likely to urinate inappropriately.

Dogs peeing inside my house


Finding reachable vertices for every vertex in a directed graph

Question: I know that brute force approach to do this is perform DFS on all the vertices of the graph.So for this algorithm the complexity would be O(V|V+E|). But is there more efficient way to do this?
Answer: I really suspect that there isn't a known better algorithm for general graphs. All the papers I found on the subject [1] [2] describe algorithms that run in O(|V| * |E|) time. That isn't better than your naïve attempt in the worst case.
Even the wikipedia page [3] says the fastest algorithms reduce the problem to matrix multiplication, which the fastest algorithms are only marginally better than your baseline.
[1] http://ion.uwinnipeg.ca/~ychen2/conferencePapers/tranRelationCopy.pdf
[2] http://www.vldb.org/conf/1988/P382.PDF
[3] http://en.wikipedia.org/wiki/Transitive_closure#Algorithms
Comment: Could you please explain how to apply fast multiplication to this problem
Comment: @teja Don't know if there are faster algorithms, but you can use the adjacency matrix M, and perform M^|V|. Using the fastest matrix multiplication algorithms (and exponentiation by squaring) this is O(|V|^2.37 log |V|)
Answer: I get the impression from papers like http://research.microsoft.com/pubs/144985/todsfinal.pdf that there is no algorithm that does better than O(VE) or O(V^3) in the general case. For sparse graphs and other special graphs there are faster algorithms. It seems, however, that you can still make improvements by separating "index construction" from "query", if you have some idea of the number of queries that will be made on the data. If there are going to be a lot of queries, O(1) is possible for queries if all the data is pre-computed (DFS or Floyd-Warshall, etc.) and stored in O(n^2) space. On the other hand, if there are going to be relatively few queries, space and/or index construction time can be reduced at the expense of query time.
Answer: [EDIT: As pointed out by kraskevich, the final query step can be worse than I had originally claimed: up to O(|V|^2) even for an output of size O(|V|), which is no better than ordinary DFS without any preprocessing.].
In the worst case, O(|V|^2) space would be needed to store all this information explicitly -- i.e., to store the complete list of reachable vertices for each vertex (think of a graph in which every vertex has an edge to every other vertex).  But it's possible to represent it in such a way that only O(|V|) space is needed, and this representation can be built in O(|V|+|E|) time, and a query on it will only take time proportional to the size of the answer (number of reachable vertices).
The basic idea is: Every vertex in a strongly connected component (SCC) can reach every other vertex in the same SCC (this is the definition of SCC), and can reach all vertices in SCCs that it can reach, and no other vertices.

Find all SCCs; this can be done in O(|V|+|E|) time.  Build a table SCC, so that SCC(u) = i if the SCC of u is i (both vertices in G and SCCs can be represented as integers).  Afterwards make another pass through this table to build a dual table, Verts, so that Verts(i) contains a list of all vertices in the ith SCC.
Build a new graph G' whose vertices are the SCCs of G.  G' will necessarily be acyclic.

So, given a vertex u in G, look up its SCC, SCC(u).  Call this i.  Perform a DFS through G' starting at vertex i: For each vertex (of G') j encountered during this DFS, output every vertex (of G) in Verts(j).
Comment: Actually, it looks like the time in the worst case is not proportional to the size of the answer. Imagine a graph which has three layers. There are all possible edges from the third to the second layer and from the second to the first layer. It is a DAG, so finding SCC does not change it. However, running a DFS from any vertex of the third layer involves examining all edges(`O(n^2)`), but there are at most `O(n)` reachable vertices. So running a DFS from all vertices of the third layer results in `O(n^3)` time, which is not better than a naive solution.
Comment: @kraskevich: I realise now that such an efficient query would imply that DFS can be done in time less than O(|V|+|E|)!
Comment: @kraskevich: You're absolutely right.  I can't see a way around this...  Can you?  Is there perhaps some way to efficiently query for the next child of a vertex that avoids already-seen vertices?


How to modify Author Pane date fields?

Question: I have Author Pane installed along with D7 Advanced forum. I am wondering how to shorten the display format of 'Join' and how to remove 'Last seen:' from the pane?
I could not see any guidelines in the module's docs or issues about this.
Answer: Author Pane module contains appropriate templates files which control output.
author-pane.tpl.php is something that will help.
Just copy it in your theme directory, flush cache and do whatever you like with this file to customize Auth Pane block.
To remove 'Last seen:' from the pane comment or remove from the file
<?php /* Last active */ ?>
<?php if (!empty($last_active)): ?>

       <?php print t('Last seen'); ?>: <?php print t('!time ago', array('!time' => $last_active)); ?>

<?php endif; ?>

To shorten the display format of 'Join' find appropriate admin page (/admin/config/regional/date-time) and change Short date format to the format you prefer.
 * - $joined: Date the post author joined the site. (Uses shortdate format)

Comment: I copied author-pane.tpl.php into my theme's template page. Remove the 'Last active' part and flushed the cash. No effect.I even deleted the 'Last active' from the module's author-pane.tpl.php. No effect either. Really got confused. Any clues?
Comment: For example you use theme called MY THEME (theme's machine name my_theme). So the proper directory to copy .tpl files will be /sites/all/themes/my_theme/ for most cases. Path to tpl file will be either /sites/all/themes/my_theme/author-pane.tpl.php or /sites/all/themes/my_theme/templates/author-pane.tpl.php. Clear cache after you copy file. Let me know if you have any troubles or don't see changes.
Comment: I did that. no effect :(
Answer: Indeed, following this guide solved my problem. That is,
I copied
function THEMENAME_preprocess_author_pane(&$variables) {
  $variables['show_template_location'] = TRUE;
}

To THEMENAME/template.php and it showed the respective template path which in my case was in all/modules/advanced_forum/styles/naked/advanced-forum.naked.author-pane.tpl.php
Then I just edited the template and flushed cache.

How to modify Author Pane date fields?


Why does my honey always crystallized?

Question: My honey always crystallizes no matter where I store it. I have some that hasn't been opened yet and it has crystallized. I have stored it in dark and warm places I tried cool places the outcome is the same. I know I can still use it but sometimes I haven't thought ahead and I didn't prepare the honey from being crystallized. Is there anything I can do to stop it from being crystallized?
Comment: Is it a bad thing? I only eat crystallized honey, as it has a more enjoyable texture to eat and liquid honey is messy.
Comment: If I get a jar of honey that is over prone to crystallizing, I'll add a few ml of water to it. That helps. You don't want to add a lot though, or you'll get into a water activity range where molds can grow.
Comment: The only change in recipes in using crystalized honey is that it's more prone to get more of it on spoon.
Answer: That's normal for honey. When you buy good quality honey, it will always crystalize, no matter what you do. The speed and crystalization and the appearance of the crystals depends on the plant from which the honey was made.
If you want honey that doesn't crystalize, you can go to the supermarket and look at the cheaper honeys. If they are liquid in the supermarket already, there is a good chance that they have been treated in ways which prevent crystalization. Alternatively, you can buy products which are a mixture of bee honey and other sugars, which can also be formulated to not crystalize.
Comment: I bought this one at Costco and it crystallized even without being opened.
Comment: @GJ.Baker nothing unusual about that. Honey crystalizes on its own, no matter what you do.
Comment: Additionally, other than a bit of inconvenience, there's nothing wrong about crystallized honey, it's just as good as fresh for any purposes where the 'liquid state' isn't essential.
Answer: found this on the back of my honey...
All pure honey will crystallise over time. This change is a sign of quality. It can be restored to its liquid state by loosening the lid and standing in hot water or removing the metal lid and heating gently in a microwave oven on the lowest power. However, don't allow the honey temperature to exceed 40°C (104°F) as some of the goodness will be lost!

Why does my honey always crystallized?


how to Add my node_module, modules into package.json

Question: I have some module in my node_module folder but because I am amateur in nodejs, when I wanted to install theme, I forgot to use --save with npm install.now I have lots of module but my package.json is empty so is there any way to add theme into package.json.
Sorry if my question is silly one I am beginner in nodejs
Answer: Simply change into the directory containing node_modules, backup any existing package.json in there, then use npm init to re-create the package.json.
The generated package.json will include any modules that already exist within node_modules.
Sample run:
$ cd /my/project
$ mv package.json package.json.bak # Backup package.json
$ npm init                         # Recreate package.json with dependencies populated

Comment: "It only covers the most common items, and tries to guess sensible defaults." Hence, not all existing libraries in node_modules are added.
Answer: Already asked and well answered!
Here're different ways suggested to create / maintain package.json file
Is there a way to automatically build the package.json file for Node.js projects
Answer: Its simple. Edit the package.json file and add the following for development dependencies:
"devDependencies": {
    "broccoli-asset-rev": "^2.0.2",
    "broccoli-merge-trees": "^0.2.1",
    "broccoli-svg-sprite": "^1.0.3",
     ......
}

To get a list of package names and version numbers, you may look at node_modules/module folder/package.json for each of the modules to pick up the official package name and version. It will be of the form:
    {
  "name": "<<name of the package>>",
  "version": "2.1.0",
  "description": "broccoli asset revisions (fingerprint)",
....
}

just copy the name and version information from above into devDependencies into your project's package.json and you should be good to go.
Also have a look here Is there a way to automatically build the package.json file for Node.js projects
and here: https://docs.npmjs.com/files/package.json
Comment: Is the only way to add theme one by one I said I have lots module if I want to add theme one by it will take hours
Answer: You can install the same package again using npm install --save <package> and it should just replace the current package files with freshly installed ones. It will also add the packages you already added with the default version notation.
Comment: I have already known this approach but I looking for way without installing my modules again


What would happen if multiple GMs played on both sides of a chess match?

Question: Imagine a situation where a team of top Grandmasters would face another team of top Grandmasters over a single chess board and play a series of games. Would the games always end in a draw? Would having a team instead of an individual player eliminate errors or would (other) errors inevitably arise?
Comment: It's not an answer, but [Kasparov vs The World](https://en.wikipedia.org/wiki/Kasparov_vs_the_world) might give you some ideas as to what can happen.
Comment: What I can say for sure is that the game will end in a draw unless one of the two sides wins.
Comment: Deep Blue was suppossedly being changed while facing off against Kasparov. Thats 1 GM vs at least two. Kasparov ended up losing the second match.
Answer: I think that the draw rate does not have to be higher than games between individual Grandmasters. In a team versus team game, a small mistake will be severely punished. Most probably, grabbing the initiative will become more or less decisive. The opening battle will be very interesting and shape the rest of the game in a decisive manner. The type of positions that will arise in the games will depend to the team composition (the playing style of the players in each team). A team with players that prefer sharp and complex middlegames will probably have good chances to win the match. Adding a time control to the mix will make sure that a draw will not be a simple task for either team.
The probability of making a mistake will become lower. At the same time, the probability of noticing a mistake made by the opponent team will become higher. The ability to keep an initiative will increase. The ability to win endgames with a small advantage will increase. At the same time, having a time control will have an important effect. Also the exact rules will have an important effect, concerning the use of helping materials (books and engines). If using books and engines will be forbidden, the risk of making mistakes or becoming surprised in the opening will increase. It would be very exciting to see such a game with the normal time controls (90 min / 40 moves, 30 min / the rest of the game with a 30 second increment / move). The teams would have to show an excellent ability to communicate efficiently and make solid decisions at short time intervals. Probably they would not be allowed to have a demo board and would have to discuss the position in their heads. This should also increase the risk of making mistakes. All in all, longer time controls => less mistakes and higher quality of play.
Answer: These kind of games are called "consultation matches" and, although rare today, used to be much more common. The teams usually consisted of just two players each for the obvious reasons. Getting agreement between more and more players becomes more and more difficult.
Between 1958 and 1964 the BBC had a weekly chess programme on the radio which featured several of these matches. The tapes of the programmes have long been overwritten with other programmes but some of the programmes were written up in a book by Terence Tiller called "Chess Treasury of the Air".
Here are some of the results -
Alexander & Golombek 0 - 1 Clarke & Penrose
Bisguier & Penrose 0 - 1 Golombek & Gligoric
Fischer & Barden 0.5 - 0.5 Penrose & Clarke (adjudicated by Euwe as they ran out of time - 8 hours!)
Gligoric & Penrose 0 - 1 Tal & Golombek
So, not many draws there, although the main aim was probably entertainment for the listening audience.
Answer: It mostly depends on time limit. If you give them opportunity to take a lot of time for thinking, it would be a draw. If you give both sides standard time control (2 hours for each side), the result would be unpredictable, because discussions between GMs may take a lot of time.
Comment: What makes you sure that a draw would be guaranteed, if the teams have a lot of time ?


Staking / Unstaking EOS

Question: I am getting a "Failed to fetch" transaction failure when I try to both stake/delegate and unstake/undelegate my EOS on eostoolkit. Account is correctly attached via Scatter. Any pointers?
Comment: Try bloks.io! Welcome to EOS!!
Answer: are you aware of the new powerup model that has been deployed to main net?
https://eos.io/news/eos-powerup-model-explained/
eospowerup.io
Free daily powerups
Automated powerup service based on utilization
1% fee
arm.chintai.io
Automated powerups based on utilization
100% fee if paid with EOS
0% fee if paid with CHEX
github.com/eosauthority/authority_charge_client
Pay as you Go model - Pay per transaction
There are no powerups required
Fees range from 0.0005 to 0.0010 based on network

Staking / Unstaking EOS


grep a certain format, is this possible?

Question: I'm trying to find a certain unknown 11 character sequence in a huge packet capture file. The one thing I do know is that the string I'm looking has format x.x-xxxxxxx. I've been looking for a while and cannot find the right grep statement to accomplish this, can anyone help?
Comment: What do the `x`s stand for - any character at all?
Comment: yeah any character letters or numbers
Comment: OK, so alpha numeric - only `a` through `z`, `A` through `Z` and `0` through `9` ?
Comment: yes sir! the string cannot contain anything other than alpha numeric characters
Comment: You have regex as a tag, why not give it a go?
Answer: The format for grep is what we call a "POSIX regular expression" (look it up) and it support some simple matching primitives. If you know you want just alpha-numeric characters, you can use a character class like this: [a-zA-Z0-9]. grep even has a shortcut for this specific class (because it is so useful) like this: [[:alnum:]]. man grep has a lot more information about that.
You can also use repetition counting to specify how many of these characters you want to match. In your case you want to match: 1 alpha-numeric character, then a period, then one more character, then a dash followed by 7 characters. In POSIX regular expression this looks like so:
[[:alnum:]]\.[[:alnum:]]-[[:alnum:]]{7}

Notes:

I had to escape the period with a backslash, otherwise it will be resolved as the "catch all characters" regular expression.
In order for the repetition clause (the curly braces) to work you'd need to enable "extended regular expression mode" using -e or by running egrep instead of the standard grep.

So the full command may look like this:
egrep '[[:alnum:]]\.[[:alnum:]]-[[:alnum:]]{7}' /some/file

The output will be the lines where that expression matched, possibly highlighted in color (depending on your terminal). If your packet file is not line delimited (maybe it is binary) expect a lot of mess on the screen.
Comment: this was it. I was having trouble finding the correct regex expression for it. Thanks so much!


Alternate method for android sdk installation

Question:
   Is there an offline installation package for android? I installed the basic ADT and every time I try to access the site and download the APIs and other tools using sdk manager, there is an access problem(I dont even have the adb.exe). I found that downloading using sdk manager is out of option for me due to company policies. Is there some simple exe installation that would help me start my work? Thanks in advance for your help.
Answer: Instructions for offline download here -
http://qdevarena.blogspot.com/2010/05/download-android-sdk-standalone-for.html


Earliest Source for God is the Greatest Good

Question: The Ramchal says in Derech HaShem that the greatest good imaginable is HaShem himself. Does anyone know an earlier source for this statement?
Comment: Ramchal cites טוב ה׳ לכל ורחמיו על כל מעשיו as the source for that assertion IIRC
Comment: Where in Derech HaShem does he say that?
Comment: Isn't Bereshis the first source?
Comment: @DonielF I didn't find that in Derech Hashem, but a similar idea is found in his work called תקט"ו תפילות (end of 151): בזמן שאתה מתגלה נראים כל מעשיך שאין אתה פועל כי אם טוב שנאמר בך טוב ה' לכל
Comment: Tehillim (34:9) 'טעמו וראו כי טוב ה.
Comment: G-d is good by definition, once we're created as bad. Good makes no sense in a static system, only when there's a flow of something from the source to the recipient, there could be good. As we're created lacking in many areas and G-d is one to provide us with all our needs, He is defined as good. In other words, He doesn't choose to be good.
Answer: There might be a misunderstanding about what the Ramchal is saying. I don't believe he writes the greatest good is Hashem. He writes that Hashem wants to bestow the true good on man which means allowing man to attach (dveikut) himself to God through commandments (mitzvot).
Ramchal writes (Derech Hashem 1:2:1) (translation R Abba Zvi Naiman here)

Therefore since Hashem's will is to bestow good upon others it will
  not suffice Him to bestow only a small amount of goodness. Rather when
  He is bestowing the ultimate good possible for created beings to
  receive. And since Hashem alone is the true good, His desire will be
  satisfied only when He is benefitting others of that very selfsame
  goodness that is intrinsically a part of Himself, i.e., goodness that
  is perfect and true.

Ramchal further explains in the beginning of Mesilas Yesharim (ch. 1, translation artscroll)

When you look further into the matter, you will see that true
  perfection (artscroll: which is the ultimate good) lies only in clinging to G-d. This is what King David said
  "But as for me, closeness to G-d is my good" (Psalms 73:28) [...]
  For only this is the good, while anything besides this that people consider good is really emptiness and mistaken worthlessness. For a person to attain this good, it is proper that he first exert himself strenuously to acquire it, namely, to exert himself to cling to the blessed G-d through the power of deeds whose consequence is this end. These deeds are the commandments.

See also this related answer: what is good and what does it mean that God is good?
Comment: I don't understand how you are getting that he doesn't write that "the greatest good is Hashem," only that he bestows good, when he says in your quote itself (and many other places) "since Hashem alone is the true good." None of these quotes support saying that God isn't essentially good. The linked answer does, but even if you accepted that (and I don't think it fits the Ramchal's words), the Ramchal does say that God is good, and the question is for a source for that statement, however you explain it
Comment: I understand Ramchal as saying the greatest good is to attach oneself to Hashem. It is not same as Hashem being the greatest good.


Google Drive Migration sharing issues

Question: We want to migrate all google drive docs from one domain to other domain. While i got some links on how to transfer ownership of files but the sharing of new transferred files is being nullified . Is there any way to preserve sharing properties also while we transfer?
Answer: I think it's currently NOT possible.
As noted in Set file sharing permissions, files inherit sharing policy if transferred within same organization of the file owner. As mentioned:

Files always inherit sharing policy from the organizational unit of the file owner. A file may therefore inherit a new sharing policy if the owner moves to a new organizational unit or if file ownership is transferred to someone in a different organizational unit.

With this, new file owner might need to share files and folders.
Hope that helps!

Google Drive Migration sharing issues


How to open 2 windows of File/Projects explorer in netbeans?

Question: Is there a way to have 2 windows of files/projects open in netbeans? I want to have one of these windows pointed at one folder, and the other window pointed at another folder. When you have a lot of files and have to constantly switch between the two folders, it gets annoying to have to scroll that much each time.
Comment: +1 If you ever find the solution to this, please do share the with the rest of us. Thanks.
Comment: @Joraid Just open one 'Project' and one 'Files' window, like the answer below describes.
Comment: @Joraid Check my answer it works
Answer: Haven't found a way to have 2 project windows open but I have stacked a project and a file window in the same pane. Just open both windows and drag one down to half size. Also you can undock (float) the windows and put them where ever you want.
Comment: That's what I'm doing, works but sucks. They should add a way to open as many windows as needed, that's the whole point of OOP.
Answer: No exist solutions. But you can "hack" like this: https://pandazen.wordpress.com/2009/12/23/open-netbeans-with-two-instances-windows-simultaneously/
Answer: The instructions provided in opening-multiple-netbeans-ide-instances actually works.
I have tested it and working as expected. You need to create shortcut for tow different directories with providing project directory.
Answer: Two open two instances of Netbeans, I double click on two program files in quick succession before Netbeans can fire itself up.
Answer: Allow me to explicitly add in here the "hack" mentioned by @Do_Nhu_Vy  (since I don't trust third party websites, and I don't have enough reputation to reply to his comment). All credit goes to the original WordPress user (Pandazen) in said link.
Now then,
the hack/solution consists of changing the "userdir" of NetBeans at launch time: when NetBeans detects a different "userdir" (than the already opened Netbeans' window) it will then proceed to open a new window.
The process of changing NetBeans' userdir at launch is simple:

Create an empty user directory, for example: C:\tmp
Duplicate your already existing NetBeans shortcut (create a new one). You'll most likely find the shortcut in the "Start Menu" Windows directory C:\ProgramData\Microsoft\Windows\Start Menu\Programs\NetBeans"
Right click the newly created Netbeans shortcut and choose "Properties",
Modify the "Target" field by adding the --userdir DIRECTORY suffix with the chosen path, replacing DIRECTORY with your newly created empty directory. For example: "C:\Program Files\NetBeans 8.2\bin\netbeans64.exe"" --userdir C:\tmp

Now, every shortcut will launch a NetBeans instance in a different window. This works with NetBeans 8.2, but I haven't tested it with NetBeans 9 or 10.


Link-only answers targetting SO documentation?

Question: Another user asked for an error #1009, and got pointed to the documentation example. And the answer got flagged as being link-only. Does the policy for link-only answers apply if the link goes to SO documentation?
Answer: I don't think the destination of a link should affect our stance that good answers require a bit more effort than just providing a link.
While documentation does help to assure that link rot will be less of a problem, and that the overall experience someone is likely to have going to another resource will be good - self-contained answers are really one of our hallmarks.
In essence, while links to docs are probably 'safer' than others, we should treat it as a supplementary resource and still take a moment to write an extra sentence or two that points out what the reader should be looking to take away from the resource.
But as always please exercise common sense. There are some cases where the question is valid, and the best answer to it is "use the foo() function, here's some information on how it works." If anything else after that simply feels like useless fluff in order to satisfy some rule, well - there can be the occasional exception.
Comment: In the case of _anything else would feel like useless fluff_, it'd be useful to just be able to close the question with an option "covered in documentation". Because these questions are usually then also lack of research and not really worth retaining.
Comment: @bwoebi Not sure that applies everywhere. I've seen pretty great Python questions that describe some interesting constraints to be satisfied and show what the OP has tried, and the best answer happens to be "Oh, there's this module that ships with Python and does all of that for you that you've overlooked", Again, discretion is pretty paramount.
Comment: Oh, I agree. I mean in case the question is anyway of low-quality and not very likely to have people land on it from google (_usually_). In the rare instances this isn't the case, it should be the occasional exception as you said.
Comment: Hmm. While I was writing a response to one of the comments, it came to me that even here on SO documentation the linked example *can* be deleted, so the question becomes answered with a yes.
Comment: Most of the point of no external links is because the target can break without SO's control.  This is not the case here.  The reason you shouldn't just link to another SO answer with "the answer is here" is that we already have a mechanism (close as duplicate) for that.  I'm not sure what remaining arguments there are against link-only answers and what makes a link to a stable and comprehensive solution worse than copying it onto SO, other than your (unjustified above) assertion that this is so.  Maybe we need "closed: covered by documentation example", which would justify the position above.


Shaking a copper vessel

Question: I took some water in a copper vessel and gave it a vigorous shake for approximately 10 mins when I realised that the temperature of the vessel is being raised a bit. But how is this possible, I mean if  I shake it, I'm not providing any heat, although the water( in bulk) has some velocity( imparted by me ) but in a microscopic level each molecule will have the same initial K.E. ( I guess so ! ) so why will the temperature increase?If the K.E. increases then can I conclude that when we push a block( on a smooth floor) with some force through some distance it's temperature increases just because it's K.E. increases?
Comment: Yes, kinetic energy will raise the temperature (very) slightly. More importantly however, your hands would warm up the vessel as you're holding it
Comment: Yeah, but if I shake the vessel by insulating it from the outside ( thermally) by some means then change in temperature will be very slight,ryt?
Comment: Yes, if you insulate it, the rise in temp will be minimal - unless you shake it extremely vigorously.
Answer: FYI:
a standard high school experiment involves rotating a one metre long cardboard tube containing lead shot.  After 100 completely rotations, the rise in temperature in the shot from falling 200 m can be readily measured, and used to find the specific heat of lead...
Here's simple on-line simulation  http://www.gigaphysics.com/mech_equiv_lab.html
Answer: It is said that Joule during his honeymoon measured the temperature of the water at the top and bottom of a waterfall and found that the temperature at the bottom was slightly more than the temperature at the top.
In falling the water lost gravitational potential energy and gained kinetic energy.
On hitting rocks at the bottom of the waterfall the kinetic energy due to the falling water became the kinetic energy of water molecules moving in random directions.
So the water molecules at the bottom of the waterfall had a greater random motion kinetic energy than those at the top, i.e. the water at the bottom of the waterfall was greater than at the top.
If all the molecules had the same increase in velocity there would be no increase in temperature.
It is the randomisation of the molecular motion which means that the temperature has risen.
Answer: How about thinking the whole system as the copper vessel only? Water inside gives the pressure on the vessel, but no change in the volume. So, no work is done by water. However, friction loss in kinetic energy can be transported as heat. That is, work done by shaking is transported as heat to the vessel.
Answer: When you shake vessel it receives kinetic energy, right. But it does not accumulate it - it moves with the same speed after 10 minutes. Where does this energy goes? It is dissipated by friction between vessel and water(maybe friction between vessel and your hand as well if your grip is slightly loose). Friction turn movement to heat - see  how fire  is started by rubbing two pieces of wood.
If you applied about 10-20 Watt to shaking this vessel(this is equivalent to raising 1-2 kg to height of one meter per second) with 100 g of water and it didn't lose any heat, then water would heat up 15-30 degrees(10 Watt * 600 seconds = 6 kJ = 0.1 kg of water * 4 kJ per degree per kg of water * 15 degrees).
Actually it would not heat up so much because heat goes to the air and your hand. That is why you feel vessel heating up.
Comment: The fact that vessel is made of copper does not matter much. You would get basically same result with glass bottle. Maybe you would not feel heat if you used wood vessel - it does not transfer heat well, so heat would be mostly accumulated in water - it would heat up much more than water in copper vessel.
Answer: It is important to realize that adding heat to a system and doing mechanical work on a system are indistinguishable processes from one another at the microscopic level.  Essentially when you do work on the system you will raise its internal energy and hence the average kinetic energy of its constituency (you raise its temperature).

Shaking a copper vessel


Does this union break strict aliasing? What about floating point registers

Question: union
{
    Uint32 Integer;
    Float32 Real;
} Field;

I have to use that union for a little IEEE trick, does that break strict aliasing? GCC is not throwing any warning(tried with GCC 4.5 and 4.6 even with pedantic strict aliasing, but As Far As I Know, GCC is not very good catching strict aliasing rules infringiments (lots of false positives/negatives).
Field A;
A.Integer = (Value1 & B) || Value2;
return A.Real;

That's the snippet I'm currently using, it seems working correctly without any warning, but maybe there can be side effects or undefined behaviours with certain compilers optimizations. So If that piece of code can be unsafe under certain conditions I will use some effort to remove that.
Also I assume that this piece of code will require moving data from standard registers to floating pointing registers on most modern CPUs (just curious about that), involving some extra cycles respect to older CPUs, correct?
The code above don't intend to be an optimization, so just don't derogate me for abusing optimizing, the code above was the simplest way for me to obtain a certain result (and luckily the simplest way seems also to be the fastest in my case!), if the result can't be safe, then I'll use a slower way.
Thanks in advance
Answer: Aliasing via a union is defined in C but has undefined behaviour in C++; the undefined behaviour is equivalent to that which occurs when reading from an uninitialized variable (a lvalue-to-rvalue conversion).
Accordingly, the most likely way this would break is in the optimiser deciding to eliminate the read from the union, as it does not have a defined value.  However, most C-and-C++ compilers are likely to give you the C behaviour as they need to support that anyway.
The safe way to alias the values is via bytewise copy e.g. std::memcpy or std::copy(reinterpret_cast<char *>(...), ...).  Alternatively, if you can compile your project in both C and C++ you could move the union aliasing code to a C source file and compile just that code as C.
Comment: Are you sure that the bitwise copy is standards-compilant? Technically you'd be first reading `float` as `char[4]` (which is OK), then writing a `char[4]` in the memory location of the RHS, then aliasing `char[4]` as `int` which isn't allowed by the strict aliasing rule.
Comment: @Kos bytewise copying to/from an array of `char` is described in 3.9p2, and direct bytewise copy in 3.9p3, so that doesn't violate aliasing.  There is the caveat that the standard only covers source and destination having the same type.
Answer: It is UB (but doesn't require strict aliasing). Also, uniond data is always stored in memory by implementations, AFAIK, else would require knowing which register the source data came from, which means knowing the source type.


asp mvc design question: single view for multiple data types

Question: In my database, there are maybe a dozen tables that represent lookup types (All have ID and Name columns - No, they must remain as seperate tables, won't be normalized into one table).  I'm building an administration application, where I want an administrator to be able to add/edit/delete/list all of these lookups.  I know I can re-use the model, but is there a more efficient way for me to write this in an asp mvc 2 application, other than writing 3 views, 1 controller for each lookup type resulting in 48 views and 12 controllers?
Answer: I wouldn't recommend removing the coupling between your models, the controllers, and views. The idea behind this pattern is that you get to separate the business logic from the presentation from the workflow. If you start mixing multiple models into the same views/controllers, it gets messy.
Maybe try doing what you're attempting using a master page and having your models inherit from a common base class or something like that instead? This way you can reuse code without smashing it into the same files.
Answer: What about a more advanced ORM mapping that combines all of them in to a single entity?
Answer: I would do this with one controller and an action/view for each CRUD operation (1x4). When and if the schema changes on one or more lookup tables, I would deal with it then. Otherwise, think of the work entailed if you add a column to each of the tables: you would have to update 48x12 or whatever files.
The specifics of how you do it depend on your model, but it could be done simply using ADO.NET and returning a DataTable or similar populated with a dynamic SQL statement where the table name is supplied by the view. You would need to guard against SQL injection, of course, if you were using string concatenation.
The Create view would similarily use the table name coming from the posted form to know which table to update with the posted data.
Answer: Look into using T4 templates (decent example) to build everything out.  You should be able to code gen the controllers and views based each model.
Sorry, my answer is to go with the 48 views and 12 controllers ... have the code gen set up so that if you add more lookup types, all you need to do is re-run the code, and boom, controllers and views are set up.


When delete a row from database, why not "IsIdentity" decrement the row id?

Question: I have 3 records in my Products Table, with ProducID 1,2,3 respectively.
When I delete the record number 3 and after that insert a new record, the ProdcutID will 4.
My question is why not the index 3 given to that row?
Answer: Because an artifcial (aka "surrogate") primary key value - and that's what an autoincrement column is - has no meaning whatsoever.
So it does not matter whether the PK value for a new row is 4, 40, 400, 40000 or 365623563
If your code relies on incrementing, gapless values in the primary key you have to rethink your code.
Edit:
There is also a technical reason why this happens: in order for an autoincrement (or a sequence in most databases) to be fast and correct in an environment with concurrent transaction there have to be certain limitations to what sequences/autoincremnts can do. One of them is that they never decrement (or to be more precise: never change direction as there can be decrementing sequences) and they are not part of the transaction control. So once a value has been acquired it's "gone" from the underlying generator.
Comment: @shani: as I said: because it does **not** matter. The nature of an autoincrement is, well, that it increments. It never "stays" or decrements (mainly for performance and concurrency reasons). Stop worrying about that.
Comment: there is no way to store the data on the deleted index?
Comment: @shani: I don't understand that question. Which "deleted index"?
Comment: look i have only one record in table and its ID is 1, i delete this row of ID 1. after that i add new record and autoincrement goes to ID 2. my question is why not strore the data on ID 1?
Answer: Because identity number is stored in table or database (I'm not sure now) and is not "reverted", but only incremented for every insert operation.
Answer: Because 3 was allocated to a record. It will evermore hold this allocation, even in death. Think of it like being the Twilight Saga, only with IDs.
Seriously though, a lot of enterprise applications no longer hard delete rows anyway, preferring a soft delete for historical purposes.
If you haven't got a fully constrained database (bad practice) then you could end up with this rolled back ID inadvertantly inheriting the old #3's children etc. Also it would make things like auditing and transaction history confusing.
What would happen if one transaction deleted a row, while another inserted? In an auto increment world, there's no locking implied, in the id reuse world, things get messy quickly.
Answer: When the IDENTITY property is used with CREATE TABLE, Microsoft® SQL Server™ uses the NOT FOR REPLICATION option of CREATE TABLE to override the automatic incrementing of an identity column. Usually, SQL Server assigns each new row inserted in a table a value that is some increment greater than the previous highest value. However, if the new rows are replicated from another data source, the identity values must remain exactly as they were at the data source.
Here is a reference http://msdn.microsoft.com/en-us/library/aa933196(v=sql.80).aspx