What's the deal with Guinan's hat?

Question: Guinan dons two hats, if I recall correctly (pictured below).  My question is: are these hats something special to El Aurians, something special to 24th century bartenders, or something else?  I don't recall ever seeing anyone else wearing either type of hat in TNG (and I've seen it all now!). I've noticed that both hats completely conceal the top of her head, but I don't know if that's significant.
Comment: Look at the top picture. It is clearly a homage to the saucer section.
Comment: Guinan has always liked hats. Remember [Time's Arrow](http://en.memory-alpha.org/wiki/Time%27s_Arrow_%28episode%29)?
Comment: I think several of these answers are valid, I also suspect that aside from practical issues with the hats, the costume designer drew on South African Zulu head dresses called Isicholo.
Comment: https://i.stack.imgur.com/DBGbL.jpg Looks like a variation on the tignon the Spanish government made African women wear in the New Orleans colony back in the late 18th century.
Comment: @ReinstateMonica-GoodbyeSE:   Well, yeah, Guinan's job is to be a saucer.   She gets people sauced.
Answer: Whoopi Goldberg had/has dreadlocks (quite some quantity) so the hat was to cover them up.  Presumably El-Aurian women don't have dreadlocks.
Durinda Rice Wood, Senior TNG Costume Designer has given a convincing "out of universe" reason for Guinan's choice of hats...

*As for Whoopi Goldberg's character Guinan, Rice Wood also explained that she wanted her to look different without her typical dreadlock look and that's the reason Guinan is wearing large hats.
Comment: Sounds like they wanted Guinan to look different from _Whoopi_, not that El-Aurians can't/don't have dreadlocks
Comment: I'm just passing on the reason given by the costume designer. See my comment above.
Comment: Considering her dreadlocks are clearly visible at the back of her neck in all appearances as Guinan (save for the _Time's Arrow_ two-parter), I doubt that's the reasoning.
Comment: Here is a link to Memory Alpha, where this is given as a reason by the Costume designer http://en.memory-alpha.org/wiki/Durinda_Rice_Wood
Comment: I should have mentioned that this is given as a reason in one of the special features on the TNG DVD's (or it could be one of the movies).
Comment: That reason is sort of thrown out in *Generations* though, as she is seen without her hat in her quarters, with her deadlocks on full display.
Comment: Good out of universe answer, @Jaydee.
Answer: We have seen a few other El-Aurians, most prominently Soran:

Also, we have seen another male El-Aurian: Martus Mazur.

Also from Generations, when we meet the lovely Mr. Soran, we also see a lot of Guinan's people in one of their space stations. Female El-Aurians sometimes wear hats:

And sometimes do not:

And the hat of the first one is quite different from Guinan's. Since Guinan seems to wear civilian clothing (not a starfleet uniform), it stands to reason the hats are just her personal taste.
Comment: The unnamed El-Aurians were actually seen on Enterprise B, not a space station.
Comment: They were actually two El-Aurian refugee ships.
Comment: With regard to the OP's "something special to 24th century bartenders," a picture of Quark on DS9 (and Nog in the alternate universe DS9) would be good.
Comment: @Xantec: They were seen on the Enterprise B, yes. But they came from the space station that was hit by the Nexus IIRC.
Comment: ["Female El-Aurians sometimes wear hats and sometimes do not so it stands to reason the hats are just her personal taste."] -1
Answer: Guinan's hats durign the TV series are most likely her own style, since as you pointed out we never see anyone else wearing ones like them.
However, when we first see Guinan in the movie Generations she is wearing a hat very similar to the ones donned by most of the other hat-wearing El-Aurians seen on the Enterprise B (as shown in bitmask's answer).

Why she, or any of the other El-Aurians, wore hats was likely just as a stylish means to keep her hair out of the way, especially while working in Ten Forward. You probably wouldn't be too pleased if your bartender's hair fell in your synthehol or ice cream sundae.
Comment: Hair would probably make that body synthetic alcohol taste better!
Answer: If you ignore the colors and texture of Guinan's costume it becomes obvious that what she is wearing is a slightly updated nun's cornette and habit.

Given her ever-placid demeanor and role as confidante to several characters her costume is a visual cue to the audience that cannot be accidental.
Comment: Ehm, you mean a subliminal clue that the audience should go watch Sister Act?
Comment: @BrianMinton I think the wimple is the unstarched piece underneath that covers the hair.  The stiff piece on top of that is the cornette.
Comment: "That cannot be accidental"?  That's a little strong for what is at best a theory.
Comment: The only thing that's obvious is that this is complete conjecture.
Comment: :) Curiously enough, the Sister Act films were well after Guinan first appeared on TNG.  Otherwise, I doubt Goldberg would have donned the habit again as Guinan.
Comment: I always thought that kind of hat was called a wimple...
Answer: Not sure if Star Trek Online is considered canon on the Stack Exchange, but Nelan on Earth Spacedock is another El-Aurian bartender and he wears practically the same costume, hat and all. He's also a male, meaning that the outfit is most likely unisex. Maybe it's some kind of "bartender uniform" in El-Aurian culture?

What's the deal with Guinan's hat?


How to use SqlBulkCopy to prevent duplicates insert?

Question: I am going to use SqlBulkCopy, but I need to prevent duplicates insert. What is the best way to do it? Have I do check existence for each item before make execute WriteToServer command?
Comment: What Magnus gave is good enough if you want to remove duplicates from the rows available in db. But are you asking for some general practices in finding the duplicates in the data set you are inserting.
Answer: The best way to do this would be to add a unique index onto the table you are inserting the data into. This will prevent any duplicate entries from being added to the table.
This also prevents you from having to potentially load too much data into memory and creating other problems for yourself.
Answer: you do not really specify what is your source. If it is a flat file you could SqlBulkCopy into a staging table and afterwards use a insert into sql statement that filters out the duplicates.


Pneumatic Vs Mechanical Rotary Hammer

Question: I was told by some people from the store that there exists 2 types of percussion types regarding the rotary hammer drill: the pneumatic percussion and the mechanical percussion. I need a confirmation if this is true or not ?
The second question is: What is the difference between a rotary hammer that has a pneumatic percussion system and a rotary hammer that uses a mechanical percussion system ?
The 3rd question is: how can I identify (if the manual does not specify) which is pneumatic and which is mechanical ?
Comment: If they both drill the hole and are the same mass & cost, what does it matter?
Comment: The life of the nerves in one's hands...
Comment: There is a patent on (EP) electro pneumatic hammer devices, which is what all the rotary hammer drills and demo hammers I am familiar with employ...or at least something very similar. The feature is high impact with high frequency impact isolation for the operator's hands.  Other vibration isolation mechanisms are normally also used to further isolate operator's hands.
Answer: I think the first step is to clear up the terms you are using.  There are "rotary hammers" and there are "hammer drills".  You are combining the two, causing some confusion.
In general, if a product is called a hammer drill, it will have (to simplify) a pair of ridged disks inside it that rub together and cause the bit to move in and out a little when the drill rotates.   This hammer drill will have a high "beats per minute" and has a characteristic sound almost like slowly rubbing a coarse file with a nail.
A rotary hammer is normally larger and the in and out motion of the bit is performed by a pneumatic piston.  They are more powerful and also absorb shock more for the user so can be used for longer periods.  They also will typically have the ability to use the hammer without the bit rotating (which is not possible on a hammer drill).
So to answer your last question, if it is called a hammer drill, it uses mechanical percussion, and if it's called a rotary hammer it uses a piston.  I guess a manufacturer could use the wrong term and at that point you would need to look at the manual or a parts diagram. This article from Popular Mechanics actually mentions a drill that is marketed as a hammer drill but is designed like a rotary hammer (the Rockwell).
Comment: Good explanation and I'll add that there is no comparison between the performance of these two.  A pneumatic rotary hammer is a far superior tool and, if you have much drilling to do, is worth the extra cost.  It will save you hours of drilling time.
Comment: It is noteworthy that the hammer drill and rotary hammer terminology have gone through changes over several decades.  Similar to sabre saws, reciprocating saws, and jig saws.  So old literature may refer to a hammer drill, which is really a rotary hammer by today's usage, and of course a rotary hammer which is really a hammer drill by today's usage.

Pneumatic Vs Mechanical Rotary Hammer


How to Apply Gaussian Filter to Raw Audio Files in Python?

Question: I am recording raw files in python to later break them into phonemes, but the noise in the surrounding environment is hampering the result. So, there is a need to apply a filter to the recorded raw audio files. How can this be done ??
Comment: Why do you think a Gaussian filter is going to help with noise in the surrounding environment?
Answer: Do it using the following steps:

Look for the optimal frequency for the Low Pass Filter. Usually close as possible to the bandwidth of your desired signal.
Design an LPF filter according to the frequency above. If you're after Gaussian based filter you need to optimize the STD ($ \sigma $) parameter.
Apply the filter either using convolution, Using Numpy's convolve() function (Only in case of FIR Filter) or Scipy's lfilter() function (Which, in case of FIR Filter does convolution as well yet can also handle IIR Filters).

Remark
Gaussian based filters aren't optimal for the task you are after (Their passband isn't flat).
I'd would design a filter using Remez Method (See Scipy's remez()) which is Equiripple Method or using Chebyshev Filter Type II (cheby2()) and Butterworth Filter (butter()) which has flat passband (Namely they won't do any harm to the audio content).


do we have to register our trademark to be valid.... can we take a legal action if someone is using similar trademark but our is not registered?

Question: My question is about do we have to register our trademark to be valid.
1. can we take a legal action if someone is using similar trademark but our is not registered?
Answer: In the US, trademarks do not need to be registered. The owner of the mark can sue in state court for infringement of the trademark without ever registering. However, there is increased protection and specific benefits to registration.
The US Patent and Trademark office (USPTP) PDF publication Basic facts About Trademarks says (on pages 10-11):

In the United States, parties are not required to register their marks to obtain protectable  rights. You can establish "common law" rights in a mark based solely on use of the mark in Principal Register provides a number of significant advantages over common law rights alone,
  including:
• A legal presumption of your ownership of the mark and your exclusive right to use the mark
  nationwide on or in connection with the goods/services listed in the registration (whereas a
  state registration only provides rights within the borders of that one state, and common law
  rights exist only for the specific area where the mark is used);
• Public notice of your claim of ownership of the mark;
• Listing in the USPTO's online databases;
• The ability to record the U.S. registration with U.S. Customs and Border Protection to prevent importation of infringing foreign goods;
• The right to use the federal registration symbol "®";
• The ability to bring an action concerning the mark in federal court; and
*The use of the U.S. registration as a basis to obtain registration in foreign countries.

The USPTO is supported in part by fees from trademark applications, and obviously wants to promote registration.
Registration involves fees, and time and expense in preparing the application. It often involves the services of a trademark lawyer. Many businesses find nit worthwhile. Whether it is a good idea for a particular business is an individual, fact-based, business decision, and I cannot advise on it.
Answer: In the USA, I know that when someone applies for a trademark, you can complain about it and possibly prevent them from getting the trademark. This will most likely be successful if you have been using say a logo identifying your company in trade, and another company tries to get a trademark for your logo slightly modified, without ever having used it.
Comment: One can do more than object to another's conflicting mark, see my answer. It is true that an unregistered mark is stronger if one can show use in trade..


If one of your research partners stops working halfway but doesn't withdraw what should you do?

Question: I am about to start a research project with two other people. I was wondering if there are any countermeasures if someone stops working halfway through but doesn't officially withdraw. Do I still have to give them credit? Or what would happen?
Comment: 1. If people participate in building half a house, you need to give them credit for participating in building the house. 2. Don't be miserly about giving credit.
Comment: This question doesn't meet site quality standards in my opinion because [you are asking an open-ended, hypothetical question: "What if ______ happened?"](https://academia.stackexchange.com/help/dont-ask). Do you have a "practical, answerable questions based on an actual problem that you face"?
Comment: If you're spending time wondering about what to do if your collaborators back out before you even begin work, perhaps you don't have the right collaborators.
Comment: How, exactly, do you know that they have "stopped working"?  Did they say so?
Answer: While this is a frustrating part of collaboration (aka grown up group projects) it isn't something you can prevent. If someone contributes early on and then drops off the grid you still have to acknowledge their contribution - they must be given credit for their work. That may mean they still retain some middle authorship or it may mean only a thank you in the acknowledgements. This would depend on the specific circumstances.
The best way to mitigate the chances of this happening are to set expectations for contribution early and assign achievable, discrete goals for every member of the team.
Past that it's just luck of the draw, at least until you can really control who you work with.
Answer: This is quite discipline specific; here's a mathematician's perspective.
The social contract and the rule of thumb that I've often heard cited and that I abide by is that if a person contributed 10% of the work on the paper, they deserve authorship. For a two-author paper, this means one person might end up doing 90% of the work, and I personally find it helpful to make peace with this possibility before entering a collaboration (your mileage may vary, of course). I've not been in a project that's nearly as skewed as 90:10, but I've been in situations where it was 70:30 or 30:70 (in my subjective judgement). In the end, it tends to even out over a sufficiently long period of time.
It's unfortunate when one author stops contributing halfway through, but assuming that they made significant contributions until this point they should be given credit (as a naïve approximation, half the contribution for half of the time is one quarter of the total work, which is fair for coauthorship). This situation may or may not be their fault, and it's best to give people the benefit of the doubt whenever possible. In either case, maintaining good relationships in the community tends to be more important than upgrading co-authorship to solo authorship on a specific paper (the same point applies even more strongly to papers with more than two coauthors).
The best countermeasure is to avoid collaboration with colleagues that you've had negative experiences with. It's also helpful to talk about expectations ahead of time, especially when there is significant uncertainty involved and if the publication is particularly important for one of the participants. (For instance, if me and a colleague come up with an idea for a paper and we're fairly sure it will work out, he's uncertain whether he'll have the time to work on it in near future and I need to get the paper on arXiv before April to include it in my CV when applying for a job, we might tentatively agree to work on it together with the contingency that if he doesn't make significant contribution by February I'll do the remainder of the work and publish it alone.) Finally, you don't have to rely just on your own experience, you can also ask others about their history of working with a specific person. Coauthors who ended up doing more than their fair share of work tend to be at least mildly annoyed and happy to talk. Just make sure these conversations don't turn hostile!
Answer: While you need not over worry about it, nonetheless, what a splendid research approach; carrying out a risk analysis and ensuring risk mitigation. The threat factor, you've identified, is valid and 'common'.
Having the 'right' collaborators in the first instance is golden. Ensure your circles are of the right type.
Ordinarily, being part of a research project ought to attract co-authorship, however, this is not (shouldn't be) cast in stone. There're other expectations of writing up and especially reading (or signing off) the final manuscript.
Beyond these, as you rightly identified, co-authors might not pull their weight and put the research projects at risk.
[Remediation/Contingency]

engage and have clear expectations from the onset; including authorship, communication strategy, conflict management...
address delays, incommunicado, below par contributions collegiately yet firmly and outcome oriented
do not shy away from quick phone calls, quick chat/SMS, friendly reminder/nudging
ditto: initiate/call for project risk/crisis meeting
where and when need be, set clear specific deadlines
...
do what is academically necessary to get the research project going/completed

Couples of previous questions to pay attention to and factor into your risk analysis and treatment

What can I do if my coauthor takes a long-time/unreliable to finalize/submit a paper?
Former advisor/coauthor not answering emails
How to politely and diplomatically ask one "half-senior" coauthor to contribute more?
How to handle a coauthor who is very late in finalizing a research paper?
Coauthor always postpones working on article
How should I confront an under-performing coauthor?
How to treat an under-performing coauthor?
Coauthor wrote a small part of the paper then ghosted us
Unresponsive coauthor
Non-responsive co-author
What can I do if one coauthor tries to prevent a journal paper from being published?
How to submit errata when a coauthor disagrees

Not losing sight of
How to politely ask a co-author to remove his/her name from my manuscript?
and
Coauthor used large part from common paper almost verbatim in another paper
All the best and may you have like-minded positive collaborators.
Answer: Academics is a repeated game.
Having a non-performing co-author, if there are already three authors, comes at almost no cost to anyone.
Just put their name as co-author and never work with them again.
Prior to submission, all co-authors should approve the manuscript to be submitted.
If an author is being unresponsive, is fine to send an email a week or so before submission saying, "Please review this manuscript and make sure you agree with all statements made. Please alert me to any typos or other errors. If you do not respond by dd.mm.yyyy, we will assume you are no longer interested in co-authorship and you will be thanked in the Acknowledgements." Send a follow-up message three days later.
(By the way, our Departmental musical group is called "The Non-Contributing Co-Authors". More than once I have knocked people off of short lists or declined writing them an evaluation letter because they were non-contributing co-authors. Justice is often served in the long game, and not in individual papers.)
Answer: What do you mean by "countermeasure"? I know you don't mean to threaten any potentially lazy coauthors :) Truth is you can't make someone do the work you want them to do, but if they provided even an iota of intellectual propriety they should be considered according to the journal's authorship criteria - which are very detailed.
Since the submission process goes between named authors and the journal, I'm sure lots of collaborators "fall off" either due to malice or otherwise - but that gets hairy if the offended non-author discovers the paper and takes issue with the editor. A bad reputation is just the beginning in that case.
I do stats. I've had several uncomfortable discussions about not gaining authorship upon doing a final analysis because the prior statistician did several times more work than I, although it was all for nought because the team had no well defined hypothesis or understanding of the data. But Lancet is Lancet, JSON is JSON, etc. etc. There are many papers where one author contributes heavily at the front end and very little to the final manuscript. In another example, I stressed the importance of predetermining the entire content of the paper, and I wrote my section, performed all analyses and provided very little additional work even when it was requested. I did this to enforce a bit of data integrity toward the design. Many content experts naturally posit more and more hypotheses as they see more and more results, but we know it turns into a fishing expedition and the result is confusing and not meaningful. My strategy was good in this case, the paper was exceptionally focused. The team however despised my approach and felt probably similar to your concerned scenario. By giving less, I was confident I gave them more.
So at a minimum you can a. Share the authorship guidelines from the target journal and b. solicit some acknowledgement of the work expectations for authorship, but it's far easier and more political to give credit where it's not due than it is to withdraw credit from where it might be due.
Answer: A good collaboration should result in a whole that is worth more than the sum of its parts, such as when experiment and computation combine into a coherent description of a phenomenon.
Such a collaboration creates a powerful disincentive for your collaborator to "defect", in that if they leave the collaboration, they lose a very nice piece of work that would otherwise help their career. Additionally, most people simply enjoy the feeling of having helped someone else. You should know these are powerful motivators -- after all, I'm sure those are the reasons you want to collaborate with them!
So the most efficient thing to do is to let these motivators have their way, and to smoothen the collaboration with clear, consistent communication. Be sure that you both know what to do, and that you both know that you both know. (An indisputable paper trail happens to be very important for claiming priority should a collaboration go wrong.)
Of course, some collaborations will nonetheless fail because of unfortunate circumstances (pandemics and the like), but there's nothing either you or your collaborators can do about those besides being resilient and planning well.


Origin of "the beatings will continue until morale improves"

Question: What is the origin of the phrase the beatings will continue until morale improves?
There is a Metafilter and a Quora out on it, but they are inconclusive, and the phrase does not appear in the dictionary.
Comment: Interestingly ngrams has nothing before 1976 for "continue until morale improves".  I chose this form because there's a 5-word limit and "floggings" is sometime seen instead of "beatings".  Some of the earliest hits in that ngrams search were for "firings".  The question is actually interesting, but the OP could have done a lot of the initial searching .
Comment: Although often attributed to Captain Bligh, I cannot find any real citation.
Comment: In what context? Where did you see/hear/read this? More information is needed for clarity.
Comment: @Chris H - you could add to the question your initial research and make it on topic.
Comment: @Josh I was thinking about it but didn't have time to do anything I would call proper before shutting down my PC. I .e. the ngrams bit isn't sufficient IMO, and most of the rest of my conclusions were from Google's search-page summaries. Comments are one thing on a mobile, citable edits another.
Comment: I certainly heard this going back to 1970 or so.
Comment: This is not an expression; it is writing. So there is no "origin to the  phrase". Piffle.
Comment: I originally saw this on [my friend's calendar](https://pbs.twimg.com/media/CjeZlIzW0AE-iFX.jpg:large) and recognized the reference but didn't know where it was from. I did google it before I posted this, thanks @Josh for posting about the inconclusive google results.
Comment: I first heard this while working in the computer engineering business ca 1972.  There was a satiric columnist/author in the computer sector who may have originated it, but I can't remember his name.
Comment: The guy I'm thinking of is Fred Brooks.  His seminal work was "The Mythical Man Month", but that does not contain the saying.  However, he was a columnist of sorts and may have said it in one of those columns.
Comment: Related: [Are "who first said"-questions on-topic?](https://english.meta.stackexchange.com/questions/2846).
Answer: Morale is probably the key word of the expression which has a few variants;
"The firings/floggings/beatings will continue until morale improves"

Morale meaning "confidence" (especially in a military context) first recorded 1831, from confusion with French moral (Modern French distinguishes le moral "temperament" and la morale "morality"). (etymonline)

and the military contexts are the probably where the expressions come from as suggested by the site barrypopik.com

The saying might have originated in the navy. The Dictionary of Military and Naval Quotations (1966) by Robert Debs Heinl includes, "There will be no liberty on board this ship until morale improves.—Excerpt from Plan of the Day, USS * * *." "No leave until morale improves" has been cited in print since at least 1967.

The same site provides  a few related sentences from the 60s:
From Dictionary of Military and Naval Quotations
By Robert Debs Heinl
Annapolis, MD: U.S. Naval Inst.
1966

Pg. 197:
There will be no liberty on board this ship until morale improves.
Excerpt from Plan of the Day, USS

From House of Commons Debates, Official Report
Canada. Parliament. House of Commons
Issue 1, Volume 14
1966

Pg. 14,511:
Part of the daily orders reads as follows: There will be no leave until morale Improves. The words "no leave until morale improves" have been underlined by the person who sent this excerpt to the Darmouth Free Press.

The is no real evidence to support the more commonly cited origins, that is Captain Bligh and the Mutiny on the Bounty, and the commander of the Submarine Force of the Japanese Imperial Navy during World War II.
Comment: If the phrase dated back to Bligh it would antedate the citation you have above for *morale*, so another word would probably be needed. I couldn't think of an appropriate synonym when I played with ngrams earlier.
Answer: The sentiment is surely as timeless a grumble as any. Pour encourager les autres, borrowed from Voltaire, is used often enough to find its way into dictionaries (e.g. MW, OLD). Taken literally, it would map more closely to the meaning of make an example of someone to use a modern idiom. Candide (1759), however, is a work of satire, and the phrase is used ironically.
For the phrasing as X until morale improves, however, there doesn't seem to be any clear origin, nor for variations floating around like floggings will continue until morale improves (which I have seen on T-shirts as FWCUMI) or all leave has been canceled until morale shall have improved, among others.
Morale in the sense of one's confidence and good emotional state is attested only from the early 19th century, according to the OED. Prior to that, the predominant meaning would have been morality. As such, I think the attribution to Captain Bligh of the Bounty is probably apocryphal, especially as there appears to be no such direct quotation from him or from the mutineers, even in their Hollywood adaptations.
A military origin is possible. There is an entry in Robert Heinl's 1966 Dictionary of Military and Naval Quotations, published by the U.S. Naval Institute:

There will be no liberty on board this ship until morale improves. — Excerpt from Plan of the Day, USS * * *

A cartoon captioned … and all liberty is canceled until morale improves appears even further back in All Hands, a magazine published by the U.S. Bureau of Naval Personnel, from November 1961.
There are unattested attributions on the web to some or other never-named World War II Japanese naval commander. That too, seems likely to be apocryphal. But such a tale could have been spun by one sailor and then popularized through the ranks, eventually making its way into print and vernacular usage.
Comment: [Here](http://www.navy.mil/ah_online/archpdf/ah196111.pdf#page=57) is the full PDF of that *All Hands* issue.
Comment: That link is dead now, here's the archive (see page 55) - https://web.archive.org/web/20170531204929/http://www.navy.mil/ah_online/archpdf/ah196111.pdf
Answer: The earliest closely relevant match I've been able to find for this expression is from a cartoon by Lt. B.E. Lodge, U.S. Navy, submitted for the All-Navy Cartoon Contest and published in All Hands: The Bureau of Naval Personnel Information Bulletin (November 1961) with the following caption:

"... and all liberty is canceled until morale improves."

The same cartoon appears almost five years later, in All Hands: The Bureau of Naval Personnel Career Publication (July 1966), with the same wording (but different punctuation):

"And all liberty is canceled until morale improves."

A very similar expression appears in Terrence Sutherland, "Applications of Recent Sociological Surveys to Personnel Management Aboard Ship," in Naval War College Review (April 1967):

The story of an assistant manager of an industrial department which had a poor production record illustrates the above point further: "This interest-in-people approach is all right, but it's a luxury. I've got to keep pressure on for production, and when I get production up, then i can afford to take time to show an interest in my employees and their problems!" This sounds much like a frequently repeated phrase heard in jest in the Navy today: "Now all liberty is cancelled until morale improves."

Well of course the phrase was frequently repeated in jest in the Navy at that time—it kept showing up every five years or so in All Hands.
The expression also appears in the "Training" chapter of U.S. Bureau of Naval Personnel, Steelworker 1 & C (1966 edition):

How can you tell that training is needed? A need for training is indicated whenever the following conditions exist:
...

Morale is low and men are disloyal. Low morale can be a serious problem and it cannot be raised by saying "liberty is cancelled until morale improves."

Steelworker 1 & C was published in three major editions—in 1950, 1960, and 1966—as well as with minor updates in other years. I have not found a copy of the 1960 edition, but an intermediate edition from 1954 does not include any mention of the expression, despite referring to "morale" on four separate occasions.
The next-earliest match for an expression of the form [punishment] until morale improves" appears in a Canadian House of Commons debate referring to a newspaper item published in the Dartmouth [Nova Scotia] Free Press on March 17, 1967 [combined snippets], where "liberty" is repolaced by "leave":

[Mr. McCleave (Halifax-East Hants).] If there is any question among hon. members opposite that morale is not a problem in the Royal Canadian Navy, I should like to refer to the daily orders of H.M.C.S. Saguenay, a destroyer-escort, for Monday, February 27, 1967. I have before me a photo- stat copy as reproduced in the Dartmouth Free Press for March 17. Part of the daily orders reads as follows:

There will be no leave until morale improves.

The words "no leave until morale improves" have been underlined by the person who sent this excerpt to the Dar[t]mouth Free Press. So any attempt to gloss over the suggestion that morale in the services is not the same as it used to be before these strange processes got under way is defeated, and the minister can find no comfort in the state of the morale in the Royal Canadian Navy today, which he can observe just as easily as we can.
...
Mr. Cadieux (Terrebonne): May I ask the hon. gentleman a question? The hon. member referred to an order which had been posted on the Saguenay on February 27, I think he said, indicating that no leave would be granted. I should like to underline the fact that on Monday, February 27 the Saguenay was at sea, so certainly some of the naval personnel at Halifax have not lost their sense of humour.
Mr. McCleave: It is possible they have not lost their sense of humour, and that is one way to look at the situation. But I presume that application must be made for leave and this is a matter which is dealt with during the course of a voyage and as the ship approaches port. So if this was an attempt at humour it was an ill-conceived attempt. It meant enough to some people at least that they raised a fearful row, or attempted to, by sending this extract to one of the newspapers in my area.

Another shift in wording appears in James McKenney, "Motivation and Marines," in The Marine Corps Gazette (July 1975):

Ever heard, "No mail until morale improves." We know this is said in jest, but the implication is that more mail will increase motivation/morale.

The earliest non-military instance of the expression I found involves firing rather than beating or flogging. From "IBEW Members Fight Back in West Virginia: VEPCO Workers Fired After Filing Safety Complaint," in Mountain Life and Work (May 1979) [snippet view]:

A desk sign currently on the market to brighten your day reads, "Firings will continue until morale improves." The philosophy seems to work. One hundred forty-eight workers at Vepco's Mt. Storm, West Virginia plant are still on the job despite the selective firing of forty of their brothers.

Next to arrive (in the databases I consulted) is "floggings," which appears in the title of an article by Ed Rasco in the January 1987 issue of Management World, cited in Human Resources Management (1990):

"The Floggings Will Continue Until Morale Improves"

Confirmed instances of "beatings" begin to appear a couple of years later. From Thomas Hinton, The Spirit of Service: How to Re-invent a Customer-Focused Service Strategy for the New Decade and Beyond (1991) [snippet View]:

Contrarily, in the fast food restaurant that has an unusually high churn factor and suffers from low morale and low pay, this is where you find posters hanging on the office walls saying, "Beatings will continue until morale improves!" But more on service cultures later.

Likewise in 1991, Bad Bob Smith published an 88-page book titled Mox Nix: Memoirs of an American GI, Or, The Beatings Will Continue Until Morale Improves.

Conclusions
It seems very likely that humorous/sardonic expressions of the form "[a punishment" will continue until morale improves" originated in the U.S. Navy in the form "all liberty is canceled until morale improves." The first recorded instance that various book and periodical database searches turn up is from a cartoon caption in 1961, although the cartoonist may simply have been repeating a witticism already in circulation.
Subsequent permutations of the expression involve "no leave" (from the Canadian Royal Navy in 1967), "no mail" (U.S. Marine Corps in 1975), "firings" (a labor union magazine in 1979), "floggings" (a human resources magazine in 1987), and "beatings" (U.S. business and U.S. Army sources in 1991).
Answer: ALSO USED by an Agentinian Commander played by Richard Boone in
"Way of a Gaucho" (set in Argentina, circa 1875), starring Rory Calhoun as Martin Penalosa, ALIAS Valverde, and Gene Tierney as Teresa Chavez - 1952
Comment: 1952 is way earlier than the any other source described here (1961 All Hands). So please upvote this answer. Does anyone know what was the specific line in the movie? I am sad that callous downvoting seems yet again to have driven away a helpful newcomer...
Comment: Thank you. I actually happened to see the movie on TV last night for the second time.
Comment: Others are saying the phrase does not appear in the movie and I didn't find it in a search of the transcript.  Please provide the exact phrase you're referring to, and its position in the movie.  Here is one YouTube link (don't know how long it will survive) https://www.youtube.com/watch?v=ASVCAvg1yvI
Comment: The question was, "What's the origin", not "Who else copied it".
Comment: I just checked all of the scenes in which Richard Boone appears in Kilo's YouTube link (which includes the entire movie) and didn't find anything in them similar to the quoted phrase. My apologies if I missed it somewhere in skipping through the scenes.
Answer: Capt. Horatio Stark 1811. Per a T-shirt seen at Fort Madison IA in reference to a commander of the Fort during the war of 1812.
Comment: Welcome to EL&U. Are you actually citing a t-shirt as a source?
Comment: I can't find an earlier source alas
Answer: Herb Caen column, November 1964, sign at an "industrial plant," "Layoffs will continue until morale improves."  (Probably not from management, but from a disgruntled employee who picked up the saying elsewhere.)
Comment: Can you please include a link or cite your source more completely, i.e. the name of the newspaper in which Herb Caen was a journalist, I have tried searching myself in order to check the date but came up empty handed.
Comment: The question was, "What's the origin", not "Who else copied it".


Can you call it an error if there is something wrong in a pupil's homework?

Question: Let's say a pupil has written a story (subject is English). There is a word written incorrectly.
I know it's called mistake.
But could you also call this an error?
Comment: Have you looked at the words "mistake" and "error" in a good dictionary? If so what did it say? And is there anything you still don't understand?
Comment: @WS2 I forgot to say that both words have the same translation in German. Both are translated as "Fehler".
Answer: Whether "error" is correct depends on the situation, and why the student wrote that word incorrectly.
ESL teachers are commonly taught there's a difference between the words "mistake" and "error" as part of our certification training.
An error is doing something incorrect in English due to a lack of knowledge. Most of the things beginners get wrong are errors.
A mistake is doing something incorrect in English despite knowing the correct way. A learner can self-correct a mistake.
The distinction is made to help ESL teachers respond appropriately to incorrect language use. A "mistake" should be corrected with a simple reminder, or even just a nudge, and not a full explanation of that aspect of English. An "error" requires teaching that aspect of English from scratch, not merely naming it or pointing out that it's incorrect.
THAT SAID, most ESL teachers I know either can't remember which is which, or forget they ever learned this. Only the most pedantic teachers correct "incorrect" use of these terms.
In everyday life, outside the world of English teachers, the words "error" and "mistake" are mostly used interchangeably, with the word "error" feeling more serious and formal, and "mistake" more casual and informal.
So, if it's an ESL teacher talking, and the student wrote that word incorrectly even though they'd already learned the right way, then "error" is technically incorrect, but excusable. Otherwise, "error" is correct.


making a server chat

Question: I am not very familiar with server stuff I just know C# so I am not very familiar with the code below. I am trying to make a server chat the kind that will allow people on a server to chat with each other. I am talking about the kind of server you have at schools or workplaces. I am not sure though how to do this or how to use the below code IF it accomplishes this.
Overal what I am trying to accomplish is a chat among a group of people on the same server but am having great difficulty because I don't know a lot of server things.
<code>using System;
using System.Drawing;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;

public class MulticastChat : Form
{
   TextBox newText;
   ListBox results;
   Socket sock;
   Thread receiver;
   IPEndPoint multiep = new IPEndPoint(IPAddress.Parse("188.8.131.52"), 9050);

   public MulticastChat()
   {
      Text = "Multicast Chat Program";
      Size = new Size(400, 380);

      Label label1 = new Label();
      label1.Parent = this;
      label1.Text = "Enter text string:";
      label1.AutoSize = true;
      label1.Location = new Point(10, 30);

      newText = new TextBox();
      newText.Parent = this;
      newText.Size = new Size(200, 2 * Font.Height);
      newText.Location = new Point(10, 55);

      results = new ListBox();
      results.Parent = this;
      results.Location = new Point(10, 85);
      results.Size = new Size(360, 18 * Font.Height);

      Button sendit = new Button();
      sendit.Parent = this;
      sendit.Text = "Send";
      sendit.Location = new Point(220,52);
      sendit.Size = new Size(5 * Font.Height, 2 * Font.Height);
      sendit.Click += new EventHandler(ButtonSendOnClick);

      Button closeit = new Button();
      closeit.Parent = this;
      closeit.Text = "Close";
      closeit.Location = new Point(290, 52);
      closeit.Size = new Size(5 * Font.Height, 2 * Font.Height);
      closeit.Click += new EventHandler(ButtonCloseOnClick);

      sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
      IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9050);
      sock.Bind(iep);
      sock.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(IPAddress.Parse("22.214.171.124")));
      receiver = new Thread(new ThreadStart(packetReceive));
      receiver.IsBackground = true;
      receiver.Start();
   }

   void ButtonSendOnClick(object obj, EventArgs ea)
   {
      byte[] message = Encoding.ASCII.GetBytes(newText.Text);
      newText.Clear();
      sock.SendTo(message, SocketFlags.None, multiep);
   }

   void ButtonCloseOnClick(object obj, EventArgs ea)
   {
      receiver.Abort();
      sock.Close();
      Close();
   }

   void packetReceive()
   {
      EndPoint ep = (EndPoint)multiep;
      byte[] data = new byte[1024];
      string stringData;
      int recv;
      while (true)
      {
         recv = sock.ReceiveFrom(data, ref ep);
         stringData = Encoding.ASCII.GetString(data, 0, recv);
         results.Items.Add("from " + ep.ToString() + ":  " + stringData);
      }
   }

   public static void Main()
   {
      Application.Run(new MulticastChat());
   }
}
</code>
Comment: wpf, winforms, asp.net ?
Comment: have you tested it?  What exactly is your question / problem?
Comment: When I run it I get the error ln 85 "Cross-thread operation not valid: Control '' accessed from a thread other than the thread it was created on."
Comment: my question is how can I accomplish a simple server chat not too code heavy?
Answer: Although it does look like the code above at least achieved something similar to what you're asking I believe you'll be better off trying to clarify exactly what you need.
For instance why not just use a simple form which submits the chat text to the server, and displays to all users?  You would store each 'chat' into a database and show them all on a page ordered by time.  This could be set up to automatically poll the server at short intervals (or even long poll) and it would appear to users that they are chatting to each other.
Although not the most elaborate solution, I would say it appears to certainly be in reach for you.

making a server chat


Delete mistaken post

Question: Can somebody please delete this question as it is useless as it stands, and I am apparently not allowed to do it myself.
Comment: Can you join @0scar in [chat] as he seems to have an answer. I can delete it if you *really* want but it might be better to discuss/explain first to avoid confusion and people taking time to post answers which are then deleted. If you could explain why you think it is useless then it might help others to understand.
Answer: It is perfectly fine to post a duplicate question. You cannot be aware of all questions, and searching sometimes does not bring up a similar question! Hence, other people mark it as duplicate. Having duplicates is very good because some problems can be described differently, this increases the chance a question is found using the search functionality!
Therefore, there is no need to delete it. Also, in your question there where a bunch of side questions, which could be answered while the main problem is described in the duplicate question. Sorry to see you want it to be deleted, there is no need for that.
Please explain why it is useless in your opinion (IMHO I think it is not useless, it is helpful!).

Delete mistaken post


Order of multiple adverbs

Question: 1) Нe went upstairs quietly last night.
2) Нe quietly went upstairs last night.
What version is right? I can't find information about this issue.
Comment: You left out: *3. Quietly, he went upstairs last night. 4. He went quietly upstairs last night. 5. He went upstairs last night, quietly.* The point is, there is no "right" place to put the adverb.
Comment: @Robusto thanks. I'm just using materials and it says that "He went quietly upstairs last night" isn't right. I don't trust 100% in this material. Just want to know what is "right" for native speaker, you can speak every variant, but for me like Russian speaker second variant is more pleasant.
Answer: The answer is that adverbs like quietly have considerable flexibility.
From http://www.edufind.com/english-grammar/adverbs-manner/
He asked me quietly to leave the house. the request is quiet
He asked me to leave the house quietly. the leaving is quiet
Sometimes an adverb of manner is placed before a verb + object to add emphasis.
EXAMPLES
He gently woke the sleeping woman.
She angrily slammed the door.
Some writers put an adverb of manner at the beginning of the sentence to catch our attention and make us curious.
EXAMPLES
Slowly she picked up the knife.
Roughly he grabbed her arm.
Answer: I don't think there is any theory that accounts successfully for adverb placement in English.  McCawley gives a pretty straightforward theory in The Syntactic Phenomena of English.  It goes like this.  Adverbs are modifiers, and the natural places for modifiers are prefixed to what they modify or suffixed to what they modify. "Quietly", like other manner adverbs, modifies V' (or, what are also called VP).
The basic constituent structure of your example is

[S he [V' went upstairs ] ]

and "last night", being a time adverbial, is either a V' modifier or an S modifier, so if it's a V' modifier, we have:

[S he [V' [V' went upstairs ] last night ] ]

and so we'd predict 4 possible positions for "quietly", before and after the two V's in this structure, which I'll number:

[S he (1) [V' (2) [V' went upstairs ] (3) last night ] (4) ]

For this particular example, the theory works pretty well, except that there are a couple of other places the "quietly" could go.

Order of multiple adverbs


How to force a component's re-rendering in Angular 2?

Question: How to force a component's re-rendering in Angular 2?
For debug purposes working with Redux i'd like to force a component to re-render it's view, is that possible?
Comment: Possible duplicate of [Triggering Angular2 change detection manually](http://stackoverflow.com/questions/34827334/triggering-angular2-change-detection-manually)
Comment: What do you mean by "re-rendering". Update the bindings?
Comment: Just a quick question why you need to force re-rendering?
Answer: Rendering happens after change detection.  To force change detection, so that component property values that have changed get propagated to the DOM (and then the browser will render those changes in the view), here are some options:

ApplicationRef.tick() - similar to Angular 1's $rootScope.$digest() -- i.e., check the full component tree
NgZone.run(callback) - similar to $rootScope.$apply(callback) -- i.e., evaluate the callback function inside the Angular 2 zone. I think, but I'm not sure, that this ends up checking the full component tree after executing the callback function.
ChangeDetectorRef.detectChanges() - similar to $scope.$digest() -- i.e., check only this component and its children

You will need to import and then inject ApplicationRef, NgZone, or ChangeDetectorRef into your component.
For your particular scenario, I would recommend the last option if only a single component has changed.
Comment: Any working code on ChangeDetectorRef for final version of angular2? I am now facing a situation where view is not updated after a http's post request to create a new user and then on success pushing the new object to the existing old userlist (used to iterate in view). Quite strange that `this is the first time I am facing an update not working in ng2`. The change detection strategy is default so i know i have not messed up with the change detection strategy.
Comment: @Gary, you should post a new question and include your component and your service code (ideally, include a minimal plunker demonstrating the issue).  A common problem I've seen is not using the proper `this` context in the POST callback.
Comment: @ncohen, I'm not aware of any way to manually trigger a pipe update.  You could use a pure pipe and change the object reference whenever you want to trigger an update.  This is discussed under the "Pure Pipes" section of the [Pipes doc](https://angular.io/docs/ts/latest/guide/pipes.html).  Depending on your use case, you might want to use a component property instead of a pipe.  This technique is briefly discussed at the end of the Pipes doc.
Comment: @N-ate, all of the links are fixed.
Comment: ChangeDetectorRef.detectChanges() does not work for me. I think, it's because there are no changes. I just want to tigger redrawing / computing. Update pipe values. I want to trigger it every x seconds by setInterval. I thinks re-assigning the variable is currently a easy way to do this. But maybe not the best.
Comment: Do you know if I can manually trigger the pipes whenever I perform a change? I've tried to trigger the change detection but the pipe doesn't update... I've also tried with `pure:false` in the pipe. It works but it is way too expensive (inefficient) for my use case.
Answer: tx, found the workaround I needed:
  constructor(private zone:NgZone) {
    // enable to for time travel
    this.appStore.subscribe((state) => {
        this.zone.run(() => {
            console.log('enabled time travel');
        });
    });

running zone.run will force the component to re-render
Comment: what is appStore in this context - which kind of variable and its type ? seems to be observable ... but my observable is inside the component which I want to refresh on a click of a button ... and I do not know how to access a child component method/variable from parent/current location
Answer: ChangeDetectorRef approach
import { Component, OnInit, ChangeDetectorRef } from '@angular/core';

export class MyComponent {

    constructor(private cdr: ChangeDetectorRef) { }

    selected(item: any) {
        if (item == 'Department')
            this.isDepartment = true;
        else
            this.isDepartment = false;
        this.cdr.detectChanges();
    }

}

Answer: I force reload my component using *ngIf.
All the components inside my container goes back to the full lifecycle hooks  .
In the template :
<ng-container *ngIf="_reload">
    components here
</ng-container>

Then in the ts file :
public _reload = true;

private reload() {
    setTimeout(() => this._reload = false);
    setTimeout(() => this._reload = true);
}

Comment: This is the best solution for me. This solved my translation issue using my custom translator pipe.
Comment: Thanks for this, @loonis!  I felt like this should work, and I had everything except for the `setTimeout()`.  Now mine is working with a simple and lightweight solution!
Comment: 1 thing to note - the container disappearing and appearing again can can cause size changes and the page could flicker
Comment: Thanks, a little bit hacky, but that is the only solution that works for my case (slider of videos)
Comment: Except that if you are using @ViewChild() on this component, to get it, then it will be undefined.
Answer: Other answers here provide solutions for triggering change detection cycles that will update component's view (which is not same as full re-render).
Full re-render, which would destroy and reinitialize component (calling all lifecycle hooks and rebuilding view) can be done by using ng-template, ng-container and ViewContainerRef in following way:

  <ng-container #outlet >
  </ng-container>

<ng-template #content>
  <child></child>
</ng-template>

Then in component having reference to both #outlet and #content we can clear outlets' content and insert another instance of child component:
@ViewChild("outlet", {read: ViewContainerRef}) outletRef: ViewContainerRef;
@ViewChild("content", {read: TemplateRef}) contentRef: TemplateRef<any>;

private rerender() {
    this.outletRef.clear();
    this.outletRef.createEmbeddedView(this.contentRef);
}

Additionally initial content should be inserted on AfterContentInit hook:
ngAfterContentInit() {
    this.outletRef.createEmbeddedView(this.contentRef);
}

Full working solution can be found here https://stackblitz.com/edit/angular-component-rerender .
Comment: I guess that in previous versions of angular this hook may be correct (not sure). But with newer one (v13 for me) it does not work and anybody interested in this solution should use `ngAfterViewInit`.
BTW, it interestingly is the only solution that worked for me when input's held the previous values despite form model was correct. This occurred when I was switching between routes differentiated by the `:id` route.
In the end I had to call the `rerender` function every time that navigation ended.
Answer: ChangeDetectorRef.detectChanges() is usually the most focused way of doing this. ApplicationRef.tick() is usually too much of a sledgehammer approach.
To use ChangeDetectorRef.detectChanges(), you'll need this at the top of your component:
import {  ChangeDetectorRef } from '@angular/core';

... then, usually you alias that when you inject it in your constructor like this:
constructor( private cdr: ChangeDetectorRef ) { ... }
Then, in the appropriate place, you call it like this:
this.cdr.detectChanges();

Where you call ChangeDetectorRef.detectChanges() can be highly significant. You need to completely understand the life cycle and exactly how your application is functioning and rendering its components. There's no substitute here for completely doing your homework and making sure you understand the Angular lifecycle inside out. Then, once you understand that, you can use ChangeDetectorRef.detectChanges() appropriately (sometimes it's very easy to understand where you should use it, other times it can be very complex).


Lombok for Salesforce Apex

Question: I'm looking for some solution, which helps me to write less code in Apex.
Is there any tool like Lombok for Java.
Comment: If you use the right IDE (such as Illuminated Cloud in IntelliJ IDEA) you'll find support for many live templates that allow for code generation in the editor even for Apex. I don't know if this is available in VSCode since I don't use it.
Comment: Addendum: I watched the Lombok video and unfortunately there can't be any annotations like the ones used in Lombak in Apex because the code is compiled on Salesforce's servers. The only productivity options are typeahead, snippets, and templates, but within those, you have a lot of options for saving time.
Comment: In case you're using VSCode you can take a look at the [Apex extension](https://marketplace.visualstudio.com/items?itemName=salesforce.salesforcedx-vscode-apex), which has code-completion suggestions.
Comment: GitHub Copilot will also work with Apex: https://copilot.github.com/
Answer: Illuminated Cloud (paid plugin for IntelliJ) has live templates for Apex and Lightning Web Components to help save time. Likewise, you can create your own live templates for IntelliJ if desired.
There's a video of the Apex Live Templates in action, but an example of a live template is that you can type sqblt + prompts for the object type to output the following where your cursor ends up in the query to define fields
for (List<SObjectType> results : [SELECT fields cursor FROM SObjectType]) {
    for (SObjectType result : results) {

    }
}

It also has Template-based source file creation - so you can quickly create apex unit test classes, a default apex class, etc with expected values and format. You can configure and/or extend them as you wish.

Otherwise, in VS Code you can achieve similar functionality to the above. The Salesforce Extension Pack comes with several code snippets to save yourself time.
You can see them defined here. Ex.
"Map from list of records": {
     "prefix": "mapfromrecordlist",
     "body": [
         "Map<Id, ${1:SObject}> ${2:variable} = new Map<Id, ${1}>(${3:recordList});"
     ],
     "description": "Map from List of records"
 },

While writing apex, you can select Insert Snippet from the Command Palette (Ctrl+Shift+P) to see available snippets for you. Once you know the prefix, you can then just use that.

You can also define your own User Snippets (notice log in above screenshot).
File --> Preference --> User Snippets --> Select "Apex"
In the apex.json file that opens, you can define a snippet.
Each snippet is defined under a snippet name and has a prefix, body and description.

The prefix is what is used to trigger the snippet
body will be expanded and inserted.
Possible variables are:

$1, $2 for tab stops,
$0 for the final cursor position
${1:label}, ${2:another} for placeholders. Placeholders with the
same ids are connected.

The example given in the file is below:
"Print to console": {
    "prefix": "log",
    "body": [
    "console.log('$1');",
        "$2"
     ],
     "description": "Log output to console"
}

Where typing log + tab will output console.log('cursor'); with your cursor focus in the message
If you don't feel like creating your own - you can search for extensions that provide it. A quick search (have not used these) shows several you can try:

Salesforce LWC Short Keys
Salesforce Lightning Component Snippets
Salesforce Snippets
Zambra's Snippets

And, in terms of class/file template creation, you can modify Custom Code Templates. The ones provided are listed here, but you can modify it if you expect certain things to exist when creating an Apex Unit Test, DefaultApexClass, etc.
Comment: Live Templates are `da bomb` - i couldn't live without them
Answer: I am using JetForcer plugin for IntelliJ: https://plugins.jetbrains.com/plugin/9238-jetforcer--the-smartest-force-com-ide
I am quite happy with it!
I think you can use the IntelliJ snippets there and this should save you some time.
Then combine this with the SF APEX recipes and I think you would be satisfied:
https://trailhead.salesforce.com/en/content/learn/projects/quick-start-explore-the-apex-recipes-sample-app

Lombok for Salesforce Apex


Custom csv export - customers

Question: how can I add custom csv customer export and export only email and customer group? I need put this code to the own module.
Answer: In default Magento 2 there is an option to export columns from grid view. You can enable only 2 columns - e-mail and customer group and hit export.

Custom csv export - customers


Generalized eigenvalue solver online

Question: For demonstrative purposes, I am trying to find an online solver where alumni can input data of two matrices A and B, then the system outputs the first eigenvalues and eigenvectors in the generalized eigenvalue problem. Do you know any?
Comment: Have you tried: http://www.bluebit.gr/matrix-calculator/ ?
Comment: how can i input my two matrices there?
Answer: I'd suggest an online interpreter for Python, like: https://www.pythonanywhere.com/try-ipython/
Python (with the packages NumPy and SciPy) is a popular open-source alternative to Matlab. So, using an online interpreter like the one above can give your students a realistic impression on how to solve eigenvalue problems in practice.
Example
First import the Python packages that include matrices and eigensolvers:
In [1]: import numpy as np
In [2]: import scipy.linalg

Create two random 3x3 matrices:
In [3]: A = np.random.randn(3, 3)
In [4]: B = np.random.randn(3, 3)

Solve the generalized eigenvalue problem:
In [5]: E, U = scipy.linalg.eig(A, B)

Print eigenvalues:
In [6]: E
Out[6]: array([-28.36682105+0.j, 0.10868568+0.j, -0.85885290+0.j])

Print eigenvectors:
In [7]: U
Out[7]:
array([[ 1.,          1. ,        -1. ],
       [ 0.104041 ,  -0.10251811, -0.35878059],
       [-0.73142778, -0.08405626,  0.44436849]])

Documentation
There are several different eigensolvers, optimized for different conditions (e.g. symmetric or sparse matrices). See the documentation of NumPy and Scipy for details.
If you already are familiar with Matlab, this comparison may be useful to you:

NumPy for MATLAB users
Answer: Go to compileonline.com's Matlab/octave page, enter the following, and click on "Execute Script":
A = rand(3);
B = rand(3);
[V,D] = eig(A,B)

Unfortunately their Python page doesn't seem to support numpy, but they also support R if you like that. Another option for octave specifically is Octave online, but it only supports line-by-line interpretation of input. Both support plotting.

Generalized eigenvalue solver online


Test scheduled class

Question: I am scheduling a class which performs some computations I want to know how to track the execution of class apart from viewing scheduled jobs as I have scheduled the class to execute at system time but I cannot see it changing next scheduled run or publishing any logs after the time.
Comment: how you want to track this??
Answer: The easiest way to save logging information about code in production is to create a separate custom object to store it, and saving new instances of that custom object when the code runs (or when it errors out, which is the more common use case).  In your case, you can specialize this to have fields matching the actual steps of the calculation you want to track, or simply have a large text field to store a log trace.
You can use debug logs to track scheduled classes, but you have to go to the Apex Logs section and explicitly track the logs for the user who owns the scheduled job.  This has a time limit though, so you have to actively be looking to track the logs, whereas the solution above can be done passively by the class and will be available if you have a sudden need to check the last log.

Test scheduled class


Algorithm for the locally nameless representation used by Lean

Question: I have heard that Lean uses the locally nameless representation for handling binders, yet if I input an expression that has a bound variable in it, the bound variable is not displayed using its de Bruijn index (example [click at the end of the #check line]). Is there a detailed description of the algorithm that Lean uses for this? How is the input parsed and represented internally and how does the internal representation get translated for display? What happens if the original names can no longer be used for display, for example, if using them would produce an expression no longer alpha equivalent to the internal one? How are new names chosen in that case?
Comment: **Displaying** is a completely different matter. You can, for example, store an optional *suggested name* alongside de Bruijn indices so that it displays that name for readability.
Comment: I completely rewrote my answer if you want to take another look.
Comment: @Trebor This is what I am after. I updated the question.
Comment: @Trebor A small nitpick: It appears the names are stored with the binder not the variable (which uses de bruijn indices) and don't appear to be optional (at least in Lean 3, it might be different in Lean 4).
Comment: ...Actually, maybe I should be a bit more careful in what I say.  There might be some macro magic which lets you associate optional names to things that I don't know about.  Also, in `∀ p : Prop, p → p` the inner variable (which is unused) is automatically assigned a name of `ᾰ` while one can instead write the `→` explicitly as a binder such as `∀ p : Prop, ∀ h : p, p`.  So maybe that is what you mean by optional.
Comment: @JasonRute Yeah I meant to say binder. It is definitely more reasonable.
Answer: I implemented the spartan type theory as an educational tool for people who are interested in implementing their own formal systems. If you look at how the type of expressions expr is defined,
type expr =
  | Bound of index (** de Bruijn index *)
  | Atom of atom (** primitive symbol *)
  | Type (** the type of types *)
  | Prod of (Name.ident * ty) * ty (** dependent product *)
  | Lambda of (Name.ident * ty) * expr (** lambda abstraction *)
  | Apply of expr * expr (** application *)

you will see that Prod and Lambda take a Name.ident, i.e., they remember what the name of the bound variable was, even though de Bruijn indices are used (that's the Bound constructor). When expressions are printed out (see print_expr) an auxiliary function print_binders figures out what strings it should use to print out de Bruijn indices. It tries to use the string that is stored in Lambda and Prod, if possible, otherwise it finds another name (see Name.refresh which find such a name).
In addition, here are my blog posts on "How to implement type theory" (part 1, part 2, part 3). Note however that the source code for these tutorials is somewhat messed up. The tutorials themselves still explain some basic ideas.
I know you want to implement first-order logic, but that is irrelevant. Many things that are explained in the above material will be useful in your endavors.
Answer: I'm not sure what you mean by algorithm, but it sounds like you want to know how an expression is stored internally in Lean.  Let's take your example:
∀ (x : ℕ), x ≥ 0

Even if you turn off all the notation, Lean will display it with variables since the input and output of Lean is variable based.  But you are correct that internally it also uses de Bruijn indices.  To see this, you can do the somewhat complicated looking:
#eval ```(∀ (x : ℕ), x ≥ 0).to_raw_fmt.to_string
</code>
The triple-quotes around your code turn it into a lean expression, so it has type <code>expr</code> instead of type <code>Prop</code>.  The <code>.to_raw_fmt.to_string</code> just prints the expression to a string representing the underlying constructors for the expression.
<code>(pi x default [macro annotation (const nat [])] (app (app [macro annotation (const ge [])] (var 0)) [macro prenum]))
</code>
Unfortunately, this still shows a lot of macros (which are sort of promises to elaborate that part of the expression later).  This can be fixed by putting in a more elaborated formula to begin with:
<code>#eval ```(∀ x : nat, nat.ge x nat.zero).to_raw_fmt.to_string
-- (pi x default (local_const nat nat (const 4._.98 [])) (app (app (local_const nat.ge nat.ge (const 4._.99 [])) (var 0)) (local_const nat.zero nat.zero (const 4._.100 []))))

The var 0 is how the variable x in x ≥ 0 is represented.  It has a de Bruijn index of 0 pointing it to the binder pi x.  (Notice the variable name x is also there, but is stored with the binder instead of the variable).
If you would like to understand this more, you can look at the code for the inductive expr datatype in Lean 3, which has good comments.  (Here is the Lean 4 version which is cleaner.)
This is also documented in the paper A Metaprogramming Framework for Formal Verification which covers the expression datatype in more detail.
The general way one accesses such low level details (including some of the tricks I used like the triple back quotes) is through meta-programming.  For Lean 3, see Tutorial: tactic writing in Lean.  For Lean 4, see (work in progress) Lean 4 metaprogramming book.


Managing Unsubscribes,hard bounces

Question: I have access only to email studio and i want to suppress hard bounces and unsubscribes. So is there any automated way to do it or do I have to export them manually and then import them into suppression list?
Answer: Hard bounces and unsubscribes are automatically suppressed as per these documents describing the processes:
Bounces - this one has a really good diagram explaining the process of marking a subscriber as Undeliverable, refraining from more emails being sent to that email address:

Also, unsubscribes is handled automatically, and should a subscriber use e.g. list-unsubscribe header method of opting out, the status on all subscribers list for that subscriber changes to Unsubscribed
If you indeed by writing suppress unsubscribes and hard bounces, mean ignoring them, you will need access to Automation Studio and process the data based on your data views - updating All Subscribers with this automation.
Comment: thanks, Lukas! But before making it undeliverable I think I send it for two more times and then make the status as undeliverable. I want to supress them after the first time only. I have to do that manually only as i don't have access to automation studio
Comment: OK, in that case - you can't do it in Email Studio alone, since you will need to maintain a suppression list in Automation Studio.
Answer: You won't be able to do it automatically with access to Email Studio only.
To be able to automate it, you would need access to Automation Studio: https://help.salesforce.com/articleView?id=mc_as_automation_studio.htm&type=5
You could then write an SQL query to regularly query the Bounce (https://help.salesforce.com/articleView?id=mc_as_data_view_bounce.htm&type=5) and Unsubscribe (https://help.salesforce.com/articleView?id=mc_as_data_view_unsubscribe.htm&type=5) Data Views and populate subscribers who are present in those tables to your Suppression list.
Comment: Yes, codeRage I know that my only concern was to make it automated using email studio. and I think I have to do it manually only

Managing Unsubscribes,hard bounces


Example of non extensible functions ( $f(x) \notin EXT $) for reduction

Question: This is the definition of $EXT = \{x\ | \varphi_x\ can\ be\ extended\ to\ a\ total\ computable\ function \}$. I'm trying to proof that $\overline{K} \le_{rec} EXP$ and I can't think of an example of a function that can't be extended
Answer: Every total uncomputable function cannot be extended to a total computable function. More generally, let $g$ be an uncomputable function, and let $h$ be a total computable one-to-one function, for example $h(x) = 2x$. Define a partial function $f$ by $f(h(x)) = g(x)$ (so $f$ is defined only on the range of $h$). The function $f$ cannot be extended to a total computable function.
Comment: With "uncomputable" you mean that the function diverges on every input?
Comment: @GerardoZinno "uncomputable" simply means "not computable". Above it is also taken to be total, so it never diverges.
Answer: A classic example is
$$
f(n) = \begin{cases}
 k & \mbox{if $\phi_n(n)\downarrow$ in exactly $k$ steps} \\
 \uparrow  & \mbox{if $\phi_n(n)\uparrow$ } \\
\end{cases}
$$
Above, "in $k$ steps" can be formalized more precisely using TMs (or another equivalent computational model), or Kleene's T,U normal form.
Here $f$ is trivially computable: we can try to simulate the evaluation of $\phi_n(n)$ using a universal program / TM / whatever, and count the number of required computation steps.
Further, $f$ is partial since its domain is $K$.
However, $f$ can not be extended to a total recursive function $g$, since otherwise we could exploit $g$ to decide $K$. Indeed, $n\in K$ is equivalent to "$\phi_n(n)$ converges in $g(n)$ steps", and the latter is decidable if $g$ is total recursive.


editing auto invoice

Question: How do I edit the organization's contact information on an invoice automatically generated when a person signs up for a CiviEvent and chooses to Pay Later (also for event registration confirmation)?  The invoice was created by a developer the organization no longer uses, and the organization's address and phone have changed.  We currently have Joomla 3.3.1 and CiviCRM 4.4.5
Answer: If the organization's information in its Civi contact record is correct, then the next place I would look would be in the message templates (Administer > Communications > Message Templates, the templates for receipts are under System Workflow Messages).  You should be able to locate the information in those with a find - if you are not familiar with Smarty, however, be careful not to modify the code around the information as you might inadvertently break the template.  (It's probably a good idea to save the version currently in use before you start modifying, just in case you need to step back.)
Hope this helps,
Lesley
Comment: Message templates did the trick!  Thanks so much!
Answer: In addition to what Lesley said, you may want to consider updating CiviCRM to Version 4.6.x as it has a nice built-in invoice feature.
As it is a customization (and prpobably no one knows how it works in detail?), if you cannot find the template under workflow messages it may be a good idea to upgrade instead of trying to fix the custom function.

editing auto invoice


Check if www.listentoyoutube.com provides exact audio copy

Question: If this question do not belong to this site, please tell me where it belongs if you are kind.
I need to download the exact sound clip of youtube videos, and I've been using this online site: www.listentoyoutube.com. When entering a youtube video url, after following trivial steps one downloads a mp3 file with supposedly the audio part of the video, in mp3 format. I want to know if this audio part matches exactly that of the youtube video.
I'm aware that the video and audio of youtube are separated, so my question makes sense.
My concern is that the website extracts the audio and probably converts it so that it looses quality.
Answer: What you can do

Download your video from this website with (lossless) settings and desired quality:
cconverter
make a checksum of both audio files
The one downloaded by listentoyoutube and the one by cconverter.
After converting them to a lossless audio file format (using ffmpeg for example) compare them with the checksum command line on your terminal.
The following post might help you:
related post

Cheers,
Comment: Two questions. First, by downloading a video with lossless settings, I have only to do these steps: paste the link in the text box, and then press "download" (wich says no conversion in the hidden caption) , and then press continue? And then start, wait for the conversion... then download. That's what you are telling me to do? I think I understand. But this involves downloading probably much more data in some cases.
Comment: yes you've understood well. Only thing is that I'm telling you to dl this time the video in order to compare if your website does the job you're waiting for. If everything sounds good then no need to go through cconverter anymore.


Is there a way to sync audio messages in iMessage between iPhone and Mac?

Question: My text messages are automatically synced between my iPhone and Mac. Is there a way to get my audio messages to sync too? Sometimes when I look back in a message thread it's hard to follow because either I or the other has sent an audio message instead of texting.
Answer: I managed to solve it! I needed to check this box in order to make it work:

Go to Messages in your Mac. Go to Preferences in the Messages menu. Click the iMessage tab. Click "Enable Messages in iCloud". Voila!


How do I compile a .c file on my Mac?

Question: How do I compile a .c file on my Mac?
Comment: Probably because all the answers are quite out of date. Any .c file can be added to an Xcode project and added to a target. Then it will compiled along with all the .m (Objective-C) files or Swift files.
Answer: You'll need to get a compiler. The easiest way is probably to install XCode development environment from the CDs/DVDs you got with your Mac, which will give you gcc.
Then you should be able compile it like
gcc -o mybinaryfile mysourcefile.c

Comment: what would those DVD's say on them. i have two. one is a start up disk i think and the other says aplications on it.
Comment: @David: I'm not a mac user, but since you're trying to install some applications, you might try the one that says applications. (And if I'm wrong, well, try the other one)
Comment: I'd bet it's on the Applications CD. I only have the snow Leopard upgrade DVD (and that's just a single DVD), and XCode is in "Optional Installs/Xcode.mpkg"
Answer: You will need to install the Apple Developer Tools. Once you have done that, the easiest thing is to either use the Xcode IDE or use gcc, or  nowadays better cc (the clang LLVM compiler), from the command line.
According to Apple's site, the latest version of Xcode (3.2.1) only runs on Snow Leopard (10.6) so if you have an earlier version of OS X you will need to use an older version of Xcode. Your Mac should have come with a Developer Tools DVD which will contain a version that should run on your system. Also, the Apple Developer Tools site still has older versions available for download. Xcode 3.1.4 should run on Leopard (10.5).
Comment: Just for anyone googling here, this QA is some **ten years old** (!!!)  This answer is (utterly) out of date, the modern answers down the bottom explain how to do it easily these days.
Comment: Hi Adam, is the gcc from Apple Developer Tools a symbolic link to clang c compiler or it's a real gcc c compiler?
Answer: In 2017, this will do it:
cc myfile.c

Comment: Perhaps the question could be more specific. My interpretation is that it asks how to install a compiler on macOS
Comment: It's 2023, that's what worked for me (after installing Xcode dev tools)
Answer: Just for the record in modern times,
for 2017 !
1 - Just have updated Xcode on your machine as you normally do
2 - Open terminal and
$ xcode-select --install

it will perform a short install of a minute or two.
3 - Launch Xcode.  "New" "Project" ... you have to choose "Command line tool"
Note - confusingly this is under the "macOS" tab.

Select "C" language on the next screen...

4- You'll be asked to save the project somewhere on your desktop. The name you give the project here is just the name of the folder that will hold the project. It does not have any importance in the actual software.
5 - You're golden! You can now enjoy c with Mac and Xcode.
Answer: You can use gcc, in Terminal, by doing gcc -c tat.c -o tst
however, it doesn't come installed by default. You have to install the XCode package from tour install disc or download from http://developer.apple.com
Here is where to download past developer tools from, which includes XCode 3.1, 3.0, 2.5 ...
http://connect.apple.com/cgi-bin/WebObjects/MemberSite.woa/wo/22.214.171.124.126.96.36.199.0.1.1.0.126.96.36.199.1
Comment: I went on apples site and they only had Xcode for snow lepord. which i don't have. Where can i find an ealeir version of Xcode on their site? or will the version they have up work for me?
Comment: You should be able to find an older version there as well, not just the Snow Leopard one. If not, it might be on your install DVD in the "Extras" folder which corresponds to your OS. I believe XCode 3.0 was compatible with Leopard, and possibly 3.1 as well.
Comment: Added URL to the Apple Connect site where archived XCodes are available.
Answer: Ondrasej is the "most right" here, IMO.
There are also gui-er ways to do it, without resorting to Xcode.  I like TryC.

Mac OS X includes Developer Tools, a developing environment for making
  Macintosh applications. However, if someone wants to study programming
  using C, Xcode is too big and too complicated for beginners, to write
  a small sample program. TryC is very suitable for beginners.

You don't need to launch a huge Xcode application, or type unfamiliar
  commands in Terminal. Using TryC, you can write, compile and run a C,
  C++ and Ruby program just like TextEdit. It's only available to
  compile one source code file but it's enough for trying sample
  programs.
Comment: TryC crashes at the frequency of rainy season downpour.
Answer: Use the gcc compiler.  This assumes that you have the developer tools installed.
Answer: STEP 1
Just check wheater your MacBook has the compiler or not using this command  clang --version in your command line interface.  If the tool exists then you will be able to see the version like this
STEP 2
Next, go to the directory where your source code exists using CMD Interface, then run the command make "filename" without the .c extension.
STEP 3
The final command to run your source code after compiling it is ./filename without the .c extension.
This is how you can compile and run your program on the Macintosh system.

How do I compile a .c file on my Mac?


Are there any great replacement lenses for the Nexus 5?

Question: I really like my Nexus 5 (Android Phone), and I use it to take a lot of pictures. Recently, it seems that there are couple of dust spots on the sensor, which leads to some black dots in live view and in the pictures. This is pretty annoying. I am thinking about replacing the original lens with a better one; does anyone know which lens could be compatible with Nexus 5, preferably a large aperture one?
Answer: You can't really do this. Smartphones are designed as a whole, and the camera isn't meant to have its lens replaced. In this case, the camera lens is part of the rear housing:

and as you can see, it's not really designed for multiple options. You might be able to hack something up, but the market for such a thing is so tiny that I'm sure it'd be a one-off DIY exercise, not a product you could find somewhere. (You can buy drop-in replacements for just the cracked rear lens, but they're meant to replicate the original, not provide alternatives.)
If you just want to do a simple swap, this part is called the "midframe" on iFixit, by the way, and it goes for $7, although it's currently (and possibly permanently) out of stock — look on eBay instead.
It's possible, though, that you could solve your problem just by taking this panel out and carefully — use a brush designed for the purpose, plus rocket-style blower rather than compressed air! — cleaning it. You should be able to figure out if the dust is inside this lens, or under it, or on the front of the camera module, or inside the camera. The iFixit site has a step-by-step guide for replacing the camera module, which you could use if it comes to the worst case, or, of course, use partway to get to what you need to clean in better cases.
Answer: I'm not aware of any smartphones which have a replaceable lens (and certainly not a replaceable sensor), so I think you're out of luck here. What you're perhaps being confused by are the accessory lenses which can be clipped onto the outside of a phone to give (normally) telephoto capabilities, but they still use the original sensor and lens.


Is there even a slight transient current when a piece of wire is connected to a single terminal of a cell?

Question: Suppose I have a cell/battery , both the terminals are at non-zero potentials.If I connect a piece of wire to say the negative terminal will there be some sort of electron redistribution in the wire.
The wire was initially at zero potential , when it's attached to the terminal which is at nonzero potential , shouldn't electrons redistribute themselves to make the wire equipotential ?
what will be the potential of the wire if there is such a thing , I guess its the same as that of the terminal be for the wire was connected , because the way I'm seeing things , the wire appears to be just an extension of the terminal.
Comment: See https://physics.stackexchange.com/questions/421473/capacitor-connected-to-battery-at-one-end. You can model the end of the piece of wire as creating a capacitor with a very very small capacitance between the end of the wire and the other terminal of the battery. In this model a small amount of charge does transiently flow to charge the capacitor and to equilize the potential along the wire with the terminal of the cell. There is also an accompanying redistribution of electric field lines around the battery and wire.
Comment: I think the model of "capacitance with the other terminal of the battery" is not actually complete, because you are not including what I think the questioner is truly asking about, which is:

https://en.wikipedia.org/wiki/Capacitance#Self_capacitance

You can tell the difference because the further you position the wire from the other terminal of the battery, the lower their mutual capacitance will be, but the self-capacitance of the wire will remain roughly constant no matter how far away it is from the battery.
Comment: I think the answer is complete. It allows you to calculate how the wire charges up in time using the mutual capacitance between the end of the wire and the other terminal of the battery. I think the relationship to self capacitance that you bring up has to do with the fact that if the battery is made very big (or the wire is made very small) so that the other terminal of the battery can be considered to be "at infinity" then the value of the mutual capacitance between the end of the wire and the other terminal will approach the value of the self capacitance of the wire itself.
Answer: Unless the metal of the wire is the same as the metal of the battery terminal,
there will be redistribution of charge, because of diffusion of charge carriers.
The side with the higher concentration of electrons will lose some, the side
with the lower concentration will gain some, in the vicinity of the connecting
surfaces.   This diffusion makes a small internal voltage gradient.
Because this phenomenon is temperature-dependent, it is useful in measurement
(thermocouples).  As for a battery, its 'negative' or 'positive' terminals
aren't absolute-voltage references, those values only come into play through
infinitesimal stray capacitance, stray conductance, and other minor effects,
unless more connections than just one battery terminal and the wire are made.
A complete circuit can be sketched with stray capacitances, but one usually
ignores the static electric effects (until there's enough energy to give you
a jolt after shuffling shoes on carpet).   Capacitance is a useful concept for
a one-terminal device, if high voltages are present.


What is basic difference between photoelectric effect and Compton effect?

Question: What is basic difference between photoelectric effect and Compton effect? In both case a photon hits a loosely bound electron So whats the difference? We get current in photoelectric effect but not in Compton. Please help whats happening there.
Answer:
Photo electric effect occur in bound electron, while compton effect occur in free electron.
In photo electron effect, the photo and hence energy of the photon is absorbed by the electron. While in compton effect photon is scattered.
Comment: In photoelectric effect the electron comes out from the metal surface.Does the electron similarly come out from the foil or remain at the  foil being only scattered ?
Answer: A better way to analyze this is to realize that in the photoelectric effect, the electromagnetic wave couples two electron states (bound and excited) via the frequency difference which those states share with the electromagnetic wave. In the Compton effect, there is also an electromagnetic wave and two electron states (in a center-of-mass system we can consider them incoming and outgoing) but in this system it is the wavelength, not the frequency difference, which couples the electromagnetic wave to the electron states.
This is most apparent in the case of a head-on "collision" where the superposition of the incoming and outgoing electron states creates an effective diffraction grating of parallel sheets of charge, which is of course totally impervious to an incoming electromagnetic wave.
I explain this in more detail in my blogpost, "The Day I Almost Won the Nobel Prize".
Answer: The only differnce between photoelectric effect and compton effect is that in Photoelectric effect,gamma rays
(photons) give ful of its energy to  eject electron and itself disappear while in compton effect gamma rays give some of its energy to electron and the the rest of energy carry itself and not disppear.


Save application autostart login token on computer

Question: I need to login desktop application while autostart on server (like skype does). What is the best practice to save authentication token (password)? Should I use something like RSA encryption (which typically used for .config connectionstrings encryption in ASP.NET applications)?
Answer: The most secure generally available storage option that you're going to have on Windows is is the Windows Data Protection API (widely known by the acronym DPAPI.)   This is one of the options for managing the encrypted web.config file sections that you mentioned as an example.
DPAPI gives you user and machine specific encrypted storage for sensitive data, so even if the encrypted data is stolen, it can't be decrypted on another computer, and even if the attacker has access to the computer housing the encrypted data, it can't be decrypted without the correct user logging into Windows with the correct password.  It isn't foolproof, but it's a fairly strong mechanism and would be what I would probably choose in this situation.
Answer: Are you developing this software?
I would just generate a unique token stored in database such as:

TokenId
UserId (Or some entity which this token relates to.)
TokenKey (Which will be used as an identify to the public.)
IsExpired
Ip (Which is hashed such as SHA512 so doesn't expose the users IP if compromised.)
CreatedOn
UsedOn

Now, we need reduce the risk of token stealing.
So, let's start with IP. If the IP doesn't match the token owners then you'll want to either disallow the token thief as it doesn't match the IP of the owner. Or a more aggressive approach would be to expire the token as the computer must have been compromised to gain access to that token. You could send other information, such as a key based on hardware serials and so on, but of course this is easy to spoof.
If the token is expired, they will have to re-authenticate and get a new token.
Edit for local storing passwords:
Oops, I must of misunderstood your post. When I read your post on password tokens I thought that's what you was looking for. Encryption for a password is always a no-no. Only use encryption when you HAVE to decrypt the sensitive data. For passwords you'll want to use hashes such as SHA512. There is a lot of trade-off (size, speed etc) on hashes but there are posts out there explaining all differences.
Methods of stealing the hash:

Person with physical or remote access to folder could gain access to your password.
A network sniffer like Cain could gain passwords going through the network.

So, saving a password locally is really lowering the security of your software at the expense of user convenience.
Comment: Yes, I agree.But I need to know best practise with storing passwords locally on computer (client).Here is one example - http://stackoverflow.com/questions/12657792/how-to-securely-save-username-password-local .May be other practise exist.


Hydrogen: Whether it's a metal or non-metal

Question: I know hydrogen is a non metal, but when I just study about some introductory elementary band theory I find the band structure of hydrogen has a half filled valence band just like alkali metals, and this should make it conductive. Is there some thing more complex about it or is my understanding is wrong? How can the non metallic nature of hydrogen be explained using band theory?
Answer: Solid hydrogen is not made up from hydrogen atoms. It contains hydrogen molecules held together by relatively weak Van der Waals forces. In the hydrogen molecule the two $1s$ levels of the atoms form a bonding $\sigma$ molecular orbital that is full and an antibonding $\sigma^*$ orbital that is empty:

In the solid the $\sigma$ level broadens to form a full valence band and the $\sigma^*$ level broadens to form an empty conduction band, with a gap of around 15eV between the two bands. That is why solid hydrogen is an insulator.
Comment: Metallic hydrogen ostensibly does exist at extremely high pressures.
Comment: Does the bands overlap when hydrogen becomes metallic...
Comment: @GracemarsMars yes. If you compress solid hydrogen you reduce the band gap. I don't think we have ever compressed it enough to make it metallic, though as I recall we have measured a decrease of the band gap to less than 1eV so we've managed to make solid hydrogen semiconducting. Everyone expects the band gap to fall to zero at higher pressure but those pressures are higher than we can currently achieve in the lab.
Comment: @GracemarsMars The [Wikipedia page on metallic hydrogen](https://en.wikipedia.org/wiki/Metallic_hydrogen) has a good listing of all the ways that people have tried to get to the pressures at which hydrogen might become metallic ─ as well as the reasons why each of them have been disputed.
Comment: They have compressed it (in the form of $H_2 S$) enough to turn it into a BCS superconductor https://arxiv.org/abs/1506.08190
Answer: In solid hydrogen the electrons are localised in H2 bonds. There are various crystal structures. The band structure of course depends on this. Upon very strong  compression the crystal structure should change to a  high coordination characteristic of a metal. The H2 bonds then disappear. So the behaviour is more complex than just a shift of bands. It is a structural and electronic phase transition. Search for metal-insulator transition.


Distribution for Paired Elo Matches Drawn from Normal Distribution

Question: Is there a nice way (closed form) to represent the distribution of $Z$  that results from taking two independent normal draws $X_1, X_2 \sim N(0,1)$ and determining the outcome using $Y \sim U(0,1)$ as follows:
$$Z = \begin{cases} X_1\ \  \mbox{if } Y\le\frac{1}{1 + e^{X_2 - X_1}} \\
X_2 \ \ \mbox{otherwise} \end{cases}$$ That is, we select two players from a normal distribution of skill and take the winner of a match played between them by using an Elo model. It would be nice if we could iterate the solution to determine the players left after conducting $n$ rounds of elimination matches. It would be fine to use sigmoid-type functions other than the logistic to determine win probability and skill distributions other than the normal if this would make this problem more tractable.
Answer: Looking at the MGF of $Z$
\begin{align*}
\mathbb E[e^{tZ}] &= \mathbb E[\mathbb E[e^{tZ}|X_1,X_2]]\\
&= \mathbb E\left[e^{tX_1} \frac{e^{X_1}}{e^{X_1}+e^{X_2}} +
e^{tX_2} \frac{e^{X_2}}{e^{X_2}+e^{X_1}}\right]\\
&= \mathbb E\left[e^{tX_1} \frac{e^{X_1}}{e^{X_1}+e^{X_2}}\right] +
\mathbb E\left[e^{tX_2} \frac{e^{X_2}}{e^{X_2}+e^{X_1}}\right]\\
&=2 \mathbb E\left[e^{tX_1} \frac{e^{X_1}}{e^{X_1}+e^{X_2}}\right]
\end{align*}
which is not a Normal MGF.
Answer: A proof will have to wait, but some simulations indicate that the distribution of the Elo score of the winner is normal:

Here is the R code:
<code>N <- 1e7
set.seed(7*11*13)
X1 <- rnorm(N); X2 <- rnorm(N)
Y <- runif(N)
Z <- ifelse(Y<= 1/(1+exp(X2-X1)), X1, X2)

 (mu <-mean(Z))
[1] 0.363302
 (sigma <- sd(Z))
[1] 0.9316078
</code>