The Gedolim's Reaction to the Artscroll Talmud

Question: What were the Gedolim's (Torah greats') reaction to ArtScroll and later the Schottenstein Talmud? I'm wondering what accounts exist of the various Gedolim's reactions to the company/proposal.
Comment: What is the difference between the two? Aren't they the same?
Comment: @Menachem the Schottenstein Talmud was their revolutionary translation and commentary on the Talmud but they have translated and commentated on many other areas such as Tanach and Mishnayos
Answer: Most Gedolim who they asked agreed. (The initial idea that they write a gemora was the suggestion of Rav Yaakov Kamenetsky)
Some of the Gedolim who primarily dealt with the more learned crowd were opposed due to the fear that "when there is an easier  option the harder one becomes impossible" and the Artscroll Gemara would cause many people to lose their ability to understand Gemara without it. None of them said so in very public forums.
Rav Shach was opposed to it for the reason given above. He considered saying so publicly but decided not to after speaking to  Gedolim who supported Artscroll .
Rav Aharon Schechter in his long haskama heavily stresses his opinion that Artscroll should only refer to themselves as the Artscroll explanation rather than a translation.Because  while an  explanation is subject to debate,  translation implies that Artscroll is a definitive authority of what the Gemara really means. He felt they should make it clear that they aren't.
In general both the Gedolim on the supporting and opposing side agreed that there is some validity to what other side is saying. Almost none would say it is a good idea for a regular Yeshiva Bocher to learn from an Artscroll Gemara. The Yeshivas of those who wrote haskamas for the Artscroll Gemara for the most part do not have any Artscroll Gemaras themselves.
Answer: In the autobiography of Rav Gifter zt"l by Rabbi Yechiel Spiro, (Mesorah Publications -  2011), pp.166-167 it writes about a reception that was held following the publication of Megillas Koheles (the third book of tanach that Artscroll released) where Rav Gifter made a point of meeting the two editors Rav Zlotowitz and Rav Scherman - it writes:

Not only did he offer his encouragement, he even offered to read and comment on manuscripts in progress, which he did for several years. He was truly the father of the Artscroll series, foreseeing its potential when few others did, and providing indispensable support in its fledgling years. At every new initiative, his guidance and public involvement were essential elements of its success, especially regarding the Artscroll/Schottenstein Edition of the Talmud, the impact of which he foresaw from the start.
When Artscroll/Mesorah Publications first undertook the daunting task of translating the Gemara in the Schottenstein Edition of the Talmud, there were those who felt it could not be done properly. As such, there was a disagreement among the giants of Torah Jewry as to whether the project should continue. Rav Elazar Shach, rosh yeshivah of Ponevezh in Israel, was one of those who shared these concerns. But Rav Gifter, who valued Rav Shach's opinion as the authority of the Torah world, campaigned avidly for Rav Shach to allow the project to continue
He felt that he knew American Jewry and understood the importance of such an undertaking. He knew the benefits and understood the concerns. Nevertheless, he felt quite strongly that the project should proceed. Rav Shach acquiesced; he trusted Rav Gifter's insights and perspectives. He had no personal agenda, just the pursuit of kvod haTorah.
Comment: It is also worth noting that Rav Moshe was also a supporter - in his autobiography (by Rabbi Shimon Finkelman - Expanded 25th Yahrzeit Edition, (Mesorah Publications - 2001) p.325)  it features his haskomo to Megillas Esther which was the inaugural volume of the Artscroll series.
Answer: You can see various approbations from gedolim in the introduction. Especially Rav Mordechai Gifter z"l who spoke English fluently.
Comment: A few of them say very different things in English and Hebrew so pay close attention


What happened after the Ring was dropped into Mount Doom?

Question: In the Peter Jackson movie, once the One Ring is thrown into the volcano in Mount Doom, why does the mountain and tower collapse, and the ground disappears everywhere where the orcs are standing but not where the humans are? Where are all the orcs running to, what do they do next?
Comment: I gather you have seen the movie but not read the books?
Comment: @scholar - There are multiple (good) questions here; 1) Why does Mordor fall apart, 2) What happens next to Gandalf. In your absence, I've asked them both and asked/closed the gandalf one as a dupe.
Comment: Yes, exactly. Well, I've read the Hobbit...
Comment: Here is what happened to the main characters http://imgur.com/a/Hp6ew
Answer: The Tower collapses because its foundations was built by the power of the Ring.  When the Ring was destroyed, the foundations crumbled, and the tower fell.
The mountain collapsed for much the same reason.  Sauron had reshaped the volcano in the past, and those changes were being un-done.
The ground collapsing under the orcs and not the humans was a visual effect added by Peter Jackson and his crew.
The Orcs fled in fear and madness after the will of their Master was removed.
No, evil still exists in the world.  One of my favorite post-Ring chapters "The Scouring of the Shire", was completely removed from the movie.  It deals with the evil that men continue to do in the world.
As above, there is quite a lot of story, post-Ring, found in the novels that was removed when the movie was made.  But, even in the movie, Gandalf and Bilbo leave Middle-Earth for the undying lands.
Comment: A brief glimpse of the scouring can be seen when Frodo looks into Galadriel's magic bird-bath and sees the Shire burning & under attack. That's as close as we get to seeing it.
Comment: @Omegacron in fact, IIRC, the scene was included in the script at first (thus they filmed it, or parts of it), but was later dropped. I believe it's mentioned in the Additional Materials from FOTR.
Comment: The Orcs fled from the battle in fear after Sauron's will vanished when he was defeated. I edited your answer to reflect this.
Answer:
Sauron built the tower of Barad-Dur using the Ring, and when the Ring was destroyed, so were all the things Sauron had built with it.
In the books, the Orcs are not swallowed up by the earth, but many of them are killed.  The rest scatter and go back to their usual habits of waylaying people, robbery, and low level criminality.
Evil is not eradicated from the world, but the singular evil that became incarnate in Sauron will be replaced by many smaller, more difficult to conquer evils.
Gandalf is immortal. He goes to the Undying Lands with Frodo and Bilbo, as well as Galadriel, Elrond, and a number of other characters.
Comment: " the singular evil that became incarnate in Sauron will be replaced by many smaller, more difficult to conquer evils." which are not nearly as dangerous as that posed by Sauron.
Comment: @WhatRoughBeast we may have mosquitos, but at least we don't have giant magical stirges flying around trying to suck our blood.


Determining the concentration of ammonium nitrate by chemical means

Question: I have several litres of ammonium nitrate solution that I do not know the concentration of, but is approximately 0.6M. I don't have precise enough instruments to determine it via its density. I titrated it with NaOH, since the ammonium ion is a weak acid, but it is too weak and the endpoint is impossible to discern clearly. I then realised of course I could just evaporate the water and weigh the solute, but the question still stuck with me: how could I determine its concentration by chemical means? The only other way I can think of is to measure its conductance and compare this value to existing data.
Comment: Try adding a precise amount to excess standard NaOH, carefully distilling off the ammonia and titrating the remaining NaOH with HCl.
Comment: If you have a good balance and a 100 ml volumetric flask you can determine the density of the solution directly.
Comment: @MaxW, I tried that but the values I got are way off -- less dense than pure water. The balance is only to 2 d.p. so I suspect it is not good enough.
Answer: As long as the solution is pure, your idea of making standardized $\ce{NH4NO3}$ solutions and comparing conductance should work.
Caveat: This works as long as conductivity vs. concentration is a monotonic function. For some other substances is not, e.g., for $\ce{H2SO4}$, which, at STP, has a distinct peak in conductance at ~30%, and then drops off, so that there are two points on the curve at which conductivity is the same, but concentration quite different.
This is also the case for $\ce{NH4NO3}$ above 8.0 m/mol kg-1, but, in the region in which you are interested, it should not be an issue.
However, there is another, simpler, rather old alternative: use a hydrometer. The density of $\ce{NH4NO3}$ is a monotonic function. And others have already done the work for you, charting density against concentration.
Eureka!
Comment: Thank you @DrMoishe. I have learned something new about monotonic functions!


How do contact icons propagate among services and devices?

Question: I've been perplexed trying to understand the following issue. I have several devices and services: specifically, for example, a Macbook, an iPhone, and a Gmail e-mail account. Each provides its own Contacts interface, and there is some degree of syncing among the devices and services.
Somehow, "strange things happen" that I can't explain. For example, people for whom I've never set a contact icon somehow develop a contact icon spontaneously. This icon is sometimes the same in Gmail and on my phone, and sometimes not. (Presumably, the contact in question chose his/her icon, and it was automagically pushed to my device or account.)
Similarly, though I never set an icon for my Gmail account, somehow it just found the icon that used to be my user account icon on a former Macbook that I migrated to the current one, and without ever asking me, set that as my contact icon.
This is especially odd or disconcerting to me for the following reason. Sometimes I get e-mails on which are cc'd other Gmail users who have never emailed me before, yet I can immediately see their contact icons just by hovering over their e-mail addresses in the recipient list. This seems like an invasion of their privacy (and consequently of mine, as I presume the same happens to me). I can't find a setting in Gmail that controls this behavior. Notably, I've never set the "Select a picture that everyone will see when you e-mail them" option; this is unconfigured in my Gmail. The help page implies that if I did set it then I could control who could see it, yet I don't seem to be able to control that without setting it, and though I haven't set it, I still have an icon! How odd.
I'm not especially worried about this, just confused. I'd like to know what the propagation schema is for contact icons. In general, whose icons are being broadcast to whom, and via what services? E.g. do only iMessage recipients see the icon that I choose for a Contacts account in iCloud, and only Gmail recipients see the icon that I choose for a Gmail account? Does syncing contacts across these services push my contact icon between them? What about icons I select for others? What about the icons others have selected for themselves? Etc.
I find it odd that I know nothing about how this works even though I aggressively configure settings for all of my services and devices, and it seems to be a bit of a hole in the universe of privacy settings. Am I missing something obvious?
Answer: Even using iCloud only, I can't get a reliable contact sync for my own personal icon, let alone for other contacts. I think there are some easy to reqch edge cases or bugs in iOS and iCloud handling of this for sure vine before you take it to a hybrid cloud solution with google managing some portion of the contact syncing and database.


Data Structure for efficient nearest neighbor search using generalized distance?

Question: I have a list of objects that have a defined measure of distance between them and I'm trying to store them in a data structure such that I can easily and quickly query which of the objects is closest to a key which is not necessarily in the list (like nearest-neighbor). The problem is that these objects aren't points and, as far as I'm aware, can't be converted to points, so something like a k-d tree won't work. All I have to compare them is this distance metric (which does obey the triangle inequality), though it is possible to compute the distance between any two of the objects. Is there any data structure that supports efficient nearest neighbor search but works only off of distance? One idea I had would be to try and convert each object to a point such that the distance between them maps to the euclidean distance of the points, but that seems computationally expensive and I think would require as many dimensions as points in the worst case.
Comment: 1. Will the key always be one of the objects in the list?  Could the key be an object that is not in the list?    2. Do you have distances for all pairs of objects in the list?  If not, what is the definition of which object is closest to X, if I don't know the distance between X and every other object?  Please [edit] the question to clarify the problem statement.
Answer: You can use a CoverTree. It indexes objects purely by distance. One implementation is available here.
I have my own implementation here (Java) which is based on a more recent publication "Faster Cover Trees" by Mike Izbicki and Christian R. Shelton.
You may have to modify my implementation because it expects points as input.
Answer: Have a good day!You can find the correlation coefficient between what you want and every node of a binary search tree , then choose the value with the highest correleation coefficient.
Comment: The only issue with this is O(n) search time. Otherwise, this would be my strategy


Python: PyQt4 Py2exe

Question: Greetings!
So I've made a Python application that uses the ever so great PyQt as it's interface. Now if I was to specify the --bundle 0 option for Py2Exe the resulting compiled executable file works fine! But with all the needed files, the folder gets cluttered up. So I tried passing 1 and 2 for the --bundle option. One packs everything into file file whilst the other packs everything except the Python dll. However both of those options results in the executable file exiting upon execution. No errors are chucked back.
Another question on stackoverflow said to supply the "--includes sip" parameter for py2exe however that does not solve this issue. The sip module was already being included in all builds of the application so I can't think it has anything to do with sip.
I've used procmon to monitor what the file did upon execution. Can anyone make light of this? http://www.sendspace.com/file/z67dox
Thanks bye!
Comment: You can always use PyInstaller!
Comment: I get a 'list index out of range' error with Pyinstaller.
Answer: I know that even using raw win32ui with py2exe can cause problems. Seems like they could be related, but I don't know enough about the architecture of PyQt.
Py2exeAndWin32ui
Though I realise this wouldn't give you a neat solution even if it did help.

Python: PyQt4 Py2exe


Textural reference(s) for Bhadda Kapilani, a practitioner who for many lifetimes made the aspiration to be reborn as a woman?

Question: I just read '. . . Bhadda Kapilani, a practitioner who for many lifetimes made the aspiration to be reborn as a woman.' What are the textural references for this?
Answer: An overview regarding Bhadda Kapilani Theri can be found in Palikanon. Nothing here talks about her wanting to be reborn a woman. She seems to have always been reborn a woman according to this page.
Here are some other references:
There is one entry in Thig 4.1.
There's another very long entry on Bhadda Kapilani on Thi Ap 27.

"The foremost of my nun disciples who recollect past lives is Bhaddā daughter of Kapila."
AN 1.5.10

The long story from the AN commentary can be found here: AA 1.5.10.
The same story can be found in Ven. Sujato's blog entry: Kassapa and Bhadda Kapilani.
There is a story of Bhadda Kapilani in Chapter 2: Bhadda Kapilani of Hellmuth Hecker's essay entitled Maha Kassapa: Father of the Sangha.
There are many more references on Bhadda Kapilani, many of them in the Vinaya. You can search for "Bhadda Kapilani" on Sutta Central to find these.


Does a 97 Mazda Demio Have a Cabin Filter, if so Where is it?

Question: I have a 97 Mazda Demio 121. Imported from Japan. Do these use a cabin filter, and if so where is it located? I have looked behind the glove box, and around the driver's side, but can't see anything in the obvious spots
Comment: Welcome to Motor Vehicle Maintenance & Repair!
Answer: Raise the hood and look for the cabin air filter box on the passenger side below the windshield. It's behind the rear rubber seal that touches the hood when the hood is closed. You'll find it directly below the air slots that are under the wipers. Unsnap the two clips that hold the box closed and flip the door open to replace the filter.


"Has" vs. "have"

Question: Can anyone tell me where we have to use "has" and where we have to use "have"?
I am confused.
Can anyone explain me in a simple way?
Answer: As you may know, have and has are both present forms of the verb to have and are employed with the verb have alone (for a present simple), with have/has (used as an auxiliary verb) and the past participle of another verb (for a present perfect) or with have/has (used as an auxiliary verb), the past participle of be and the past participle of another verb (for a present perfect continuous).

Has is used with a third singular person ("he", "she", "it", or a noun) i.e. when the subject is singular but it's neither the person who's writing/speaking ("I") or the person who's reading/listening ("you"):

• He has just asked a question.

Have is used in any other case:

• Can anyone tell me when we have to use "have", etc.
• I have just copied a sentence from your question.
• Have you noticed it?

Here you will find the complete conjugation of the verb.
Comment: It is not broadly used, but third party singular agreement applies to *to-infinitive* and *gerund (or gerund-participle)* when they are used as a subject.
Answer: The words 'has' and 'have' are used as a main verb and auxiliary verb in the present tense.
In either case, has is used for the third person singular:  he, she, it.
As for have, it's used for the third person plural and the first and second persons, singular and plural.
Examples as a main verb:

He/she has a big house.
Mr Smith has no car.
It has five rooms
They/I/We/You have a big house.

Examples as an auxiliary to make sentences in the present perfect:

He has completed his homework.
She has had her breakfast.
I have completed my homework.
They have eaten their food.

"Has" vs. "have"


Do US Taxi cabs come inside the cemetery like this?

Question: I watching US Marshals (1998) movie, Man with green hat hired a taxi and it
dropped him at chapel which is inside the cemetery.
Comment: Why wouldn't they? Sufficiently large cemeteries have roads so you can drive around inside of them. Why would the taxi driver throw their passenger out at the gate instead of taking them where they want to go?
Comment: @ZachLipton it is unusual (although not unheard off) for vehicles to enter cemeteries in most of Europe. Hence the question (I imagine).
Comment: I too find it weird to see a vehicle inside a cemetery. Probably a cultural difference... My hometown has an 84-acre cemetery, one of the largest in France, and if you want to visit, you'll have to walk.
Comment: @KevinAnthonyOppegaardRose Good point. What a cemetery means varies a lot depending on cultural expectations. Most US cemeteries I've seen, excepting old or small ones, have at least some roads, certainly roads to any chapel inside, and it's not uncommon to hire towncars to carry family members if there is going to be a funeral procession. I can see how that would seem quite strange if you're not used to seeing that at home.
Comment: North-Americans have everything as drive-throughs.  That includes cemeteries.  I lived next to a drive-through cemetery when in Toronto.
Answer: Sure, it's not uncommon in a large city like New York City, USA, where many people do not own a car and would not have an easy way to get to the cemetary otherwise.
It's also pretty common to go to historic cemeteries like the Arlington National Cemetery in Arlington, Virginia, USA.  There was an article in the newspaper the Washington Post, a story of a Taxi Cab driver who was repeatedly fined for waiting to pick up passengers near the cemetery without a public transportation permit. The story notes that a county permit was needed to pick up passengers anywhere in the county, even within Arlington National Cemetery, which is technically federal property.  The Taxi driver did not have that permit, which is the reason why he got fined, not that he could not drive into the cemetery.


What is the difference in packet structure for tag VLAN and port VLAN

Question: I am new to networking. I just want to know the difference in ethrenet packet structure for tag based VLAN and port based VLAN. For tag VLAN, a VLAN tag is added to the ethernet packet frame so that any packet having that tag is considered belonging to the respective VLAN. How do the same is happening for port VLAN? How do a packet is being identified if it belongs to particular port VLAN? Any help is highly appreciated.
Comment: Wikipedia has a [nice diagram](https://en.wikipedia.org/wiki/IEEE_802.1Q#Frame_format) of the tag that's added on tagged links. Note that it is part of the *frame* (the layer-2 unit of data), not the *packet* (the layer-3 unit, which corresponds to the "Payload" in the wiki diagram).
Comment: Did any answer help you? If so, you should accept the answer so that the question doesn't keep popping up forever, looking for an answer. Alternatively, you can post and accept your own answer.
Answer: Inside a switch, the VLAN is just associated with a frame. How the frame is stored while it is being processed varies and doesn't matter for us.
A port-based VLAN has switch ports assigned to it directly. In reverse, each port is assigned a VLAN and only ports in the same VLAN communicate with each other. A frame is associated with its port VLAN when entering the switch, and forwarding is restricted accordingly. Frames are generally untagged.
Port-based VLANs work fine with a single switch but when using multiple switches you'd want to keep a VLAN association across your network, without requiring a dedicated link for each VLAN.
VLAN tags allow a switch to pass a frame's VLAN association to another switch. That way, you can use a single link between switches for all used VLANs - this is called a (VLAN) trunk.
VLAN trunks are also used with servers, so they can attach to multiple VLANs using a single NIC or LAG group.


Simple WCF Webservice Call from Silverlight (Need Help Please!)

Question: I'm new to Silverlight programming and networking in general and I've been trying to find an answer to this all day.  I'm trying to build a very simple Silverlight4 web application in VS2010 that calls a webservice on the ASP.NET website (exact same Solution as the Silverlight client app so there shouldn't be any cross-domain issues???).  I wrote a Webservice using VS' "Silverlight-Enabled WCF Service" that simply returns a string.
I then wrote the code to consume the service in Silverlight:
public MainPage()
        {
            InitializeComponent();
<code>        TestServiceClient proxy = new TestServiceClient();
        EndpointAddress address = new EndpointAddress("http://localhost:" + HtmlPage.Document.DocumentUri.Port +
            "/SilverlightApplication1.web/TestService.svc");

        proxy.Endpoint.Address = address;
        proxy.GetStringCompleted += new EventHandler<GetStringCompletedEventArgs>(proxy_GetStringCompleted);
        proxy.GetStringAsync();

    }

    void proxy_GetStringCompleted(object sender, GetStringCompletedEventArgs e)
    {
        MessageBox.Show(e.Result.ToString());
    }
</code>
This works great when I run it from VS2010.  However, when I publish it to my personal webserver (IIS7) on the same computer, I get an error:
Webpage error details
User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; OfficeLiveConnector.1.4; OfficeLivePatch.1.3; .NET4.0C; .NET4.0E)
Timestamp: Mon, 17 May 2010 08:29:51 UTC
Message: Unhandled Error in Silverlight Application An exception occurred during the operation, making the result invalid.  Check InnerException for exception details.   at System.ComponentModel.AsyncCompletedEventArgs.RaiseExceptionIfNecessary()
   at SilverlightApplication1.TestServiceReference1.GetStringCompletedEventArgs.get_Result()
   at SilverlightApplication1.MainPage.proxy_GetStringCompleted(Object sender, GetStringCompletedEventArgs e)
   at SilverlightApplication1.TestServiceReference1.TestServiceClient.OnGetStringCompleted(Object state)
Line: 1
Char: 1
Code: 0
URI: http://thunder.webhop.org:8001/home.html
When I catch the exception in App.xaml.cs, I get the following message:
System.InvalidOperationException: Eval failed.
at System.Windows.Browser.HtmlWindow.Eval (String code)
at
SilverlightApplication1.App.ReportErrorToDOM(ApplicationUnhandledExceptionEventArgs e)
I should mention that the webserver otherwise seems to work fine.  I can host Silverlight apps on it without any problems through port 8001.  I just can't for the life of me figure out how to make a successful webservice call!  Any help with this would be GREATLY appreciated.  I've wasted an entire afternoon and evening on this.  My mind's flipping in circles right now...  :-(
Many, many thanks in advance!
Luck
P.S. Apologies for cross-posting at Silverlight forums but had some problems there while posting.
Answer: I guess this doesn't actually have to do with the web service call as the exception caught in App.cs says something about "Eval failed."
I think it might be the code in your proxy_GetStringCompleted handler. MessageBox.Show is nothing else than a JavaScript alert behind the scenes. Maybe you're using a browser that has a JavaScript blocker activated or the like? Anyway; what you could try is to simply use something else than MessageBox.Show(), e.g.
<code>(new ChildWindow { Content = new TextBlock { Text = e.Result.ToString() } }).Show();
</code>
.
Cheers, Alex


What changes occur while an atom approches the speed of light?

Question: My knowledge of atomic dynamics is a little superficial. But to my understanding an electron travels an orbital path around a nucleus of an atom. "correct?" So let's say that if a hydrogen atom were to travel "extremely close to" the speed of light (relative to some laboratory system). With the electron circling the proton approximately already traveling "extremely close to" the speed of light, how is it that the electron can circle the proton without exceeding light speed? (or does it continue to orbit at all?)
Answer: In the rest frame of the atom there are of course no changes, so I assume you're asking what the atom will look like to the stationary observer watching the moving atom.
First note that electrons don't orbit the atom like planets orbiting a star. The electrons in atoms exist as a delocalised probability distribution. This distribution can have a non-zero angular momentum, but that can't be simply interpreted as the electrons circling the nucleus.
Can I answer what I think is the spirit of your question and consider a solar system moving at nearly the speed of light relative to us. That is a lot clearer because (viewed in the plane of the ecliptic) the planets are unambiguously moving towards and away from us as they orbit. The answer is that at relativistic speeds velocities don't just add. So if the solar system is moving at $0.999c$ and the orbital velocity of the planet is $0.002c$ the planet is not moving away from us at $1.001c$. The relativistic formula for adding velocities $u$ and $v$ is:
$$ V = \frac{u + v}{1 + uv/c^2} $$
In limit of $u$ and $v$ much less than $c$ this simplifies to the usual $V \approx u + v$, but if you do the sums for very high velocities you'll find the combined velocity can never exceed $c$.
Comment: To emphasize John's first point: [What the difference between "orbital" and "orbit"?](http://physics.stackexchange.com/q/35545/520).
Answer: The situation you described gives evidence that, if we really believe nothing can travel faster than the speed of light, the usual view of an electron actually orbiting the nucleus (like a planet orbits a star) can't be correct.
The model of the atom you described, with electrons moving around the nucleus, also has other problems. Physicists noticed these problems and responded by creating new theories to address them. They did this in stages.
First came non-relativistic quantum mechanics (usually just called quantum mechanics). In this model, the electron doesn't orbit the atom in a definite path like the planets do. The electrons's location can only be predicted probabilistically. One common view is a cloud; where the cloud is thickest, the electron is more likely to be found.
Next came, quantum electrodynamics, which is more applicable than just plain quantum mechanics because it takes special relativity into account. This is what physicists use today when dealing with electrical interactions on the particle scale. It's similar to Q.M. in that electrons have a probabilistic location. Beyond that I won't go into detail, mainly because I don't know it well. But I think it's safe to say that the "shape" of the probability cloud changes when the atom moves faster.
While I didn't answer your question directly, the biggest thing to take away is that the view of the electron orbiting a nucleus leads to problems like the one you thought of, so that view is no longer thought to be an accurate description of an atom. Instead, physicists invented a new model that doesn't have the problem you described.
Comment: There's nothing logically inconsistent about a universe with Bohr-style atoms obeying relativity. The OP's conceptual problem lies in Galilean vs. Lorentzian shifting of reference frames.


dragging ccb file to the layer not working cocosbuilder

Question: this should be a quick question, I was reading cocosbuilder tutorial here. I created a CCNode class and add some image animation to it, then I create a CCLayer class and wanted to add the node to the CCLayer class. Here's what it said on the tutorial "From the project view, drag the Dragon.ccb file to the canvas." But when I did, it's not showing up anything, it just creates a new CCNode class. Anyone knows what I did wrong? Thank you in advanced for your answers.
Answer: Never mind, I figure it out. I just didn't save the class.
 It's weird this way but if you want to save the class you created. You have to double click it first and save it manually. Just click the save option WILL NOT SAVE EVERY CLASS you created. So you have to go to each class and save each of them manually, I feel kinda lame this way...


Newest references from Mendeley are not imported to Latex

Question: In the beginning, the import of references from Mendeley worked well. However, now it does not import the newest references from Mendeley into Latex (overleaf).
When I click on the refresh button in latex it states:
Imported from Mendeley at 6:39 pm Thu, 31st Jan 19
So somehow it does not refresh to the actual date (22.02).
I installed Mendeley around 2 months ago and did not do any updates in Mendeley or Overleaf since then. I did not use any unusual references that I haven't used in the beginning, when it was still working
I would be really glad if somebody has an idea what the problem could be.
Best, Susi
Comment: Welcome to TeX.SE! Currently, your question lacks a bit of detail necessary to answer it. You can edit by pressing the small _edit_ link below the question text. Most importantly: which program do you use to write your documents? TeXStudio? Overleaf? LyX? TeXnicCenter? Something else? Also: did you do any updates recently for Mendeley or for your editor? Did you add any unusual references in the past few weeks?
Comment: Thanks for your update, it is more clear now. I've changed the tags a bit, maybe that will help to attract attention from the right people. Meanwhile, you can also try to contact Overleaf support, they might be able to help you or to tell you how to get a log file or other debugging information for the Mendeley API calls.
Answer: For future readers with this issue using Overleaf, you may try clicking the New File icon in the upper left-hand corner of your project, then click "From Mendeley." If it says that it's unable to refresh from the account, follow the link in the prompt and scroll down in order to unlink and re-link your Mendeley account. Then try refreshing your bibTex file.
I had to do this after changing my Mendeley password, and my existing references were not affected.
Even if you don't see the refresh error when adding a new file, re-linking your Mendeley may resolve this problem.
Comment: This problem still exists with the same solution
Comment: So others are aware, I believe this is now a premium feature as of accounts made [after Sep 2018](https://www.overleaf.com/blog/348-new-manage-shared-references-with-mendeley-groups)
Answer: Desktop or Web?
Are you using Mendeley Desktop? If so, possibly you did not sync your Mendeley Desktop library with your Mendeley Web library. Overleaf links to your Mendeley Web account, so refreshing in Overleaf will only sync with the Mendeley Web library.

in Mendeley  Desktop go to File → Synchronize Library, or just press cmd+r or ctrl+r
Now refresh the .bib file in your Overleaf project that is linked to Mendeley.
Recompile your LaTex document.

Entire library or only group?
Are you possibly importing only a specific Mendeley group? If so, then you need to make sure that the newly added references are not only added to the Mendeley library, but also to your specific group.

Add your new references to the desired Mendeley group.
If on Mendeley Desktop: Sync your Mendeley library (see above).
Now refresh the .bib file in your Overleaf project that is linked to Mendeley.
Recompile your LaTex document.


Ethernet via Thunderbolt display with MacBook Pro 2017 (A1707)?

Question: I've connected my new MacBook Pro to my Apple Thunderbolt display using the Apple Thunderbolt 3 (USB-C) to Thunderbolt 2 Adapter. The display and USB are working as expected but I'm not getting any ethernet. Ethernet is working fine with my old Thunderbolt 2 MacBook Pro. Has anyone been able to get this working?
Answer: It looks like this other post provided the hint that I needed to get this working! MacBook Sierra display ethernet needs constant re-starting
Unplugging the display and then plugging it back in fixed the problem! What a pain!
Comment: That doesn't work for me. I get the external display and USB devices plugged into the monitor are recognized, but no ethernet at all. Was there anything else you had to do to make things work?
Answer: According to this the trick is:

To get the ethernet on the display working, I had to disconnect the
  USB-C adapter, delete (AFAIR) the Thunderbolt Bridge from the network
  preferences, and then reconnect the adapter.

This worked for me too, I now have Display Ethernet in the network interfaces list.
Comment: Thanks for this great tip, which also solved my issues!
Actually I deleted more 'unused' connections from the Network-Preferences. Note that a restart was needed in order to have the desired effect!


Model Performance on external validation Set really low?

Question: I am using the LGBM model for binary classification. My train and test accuracies are 87% & 82% respectively with cross-validation of 89%. ROC-AUC score of 81%. But when evaluating model performance on an external validation test that has not been seen before, the model gives a roc-auc of 41%. Can somebody suggest what should be done?
Comment: First thing I would do is go back to basics and see how the training/test/validation sets are alike or different. Use frequencies, summaries, across the different levels. there are so many things that could go wrong.
Answer: First, an AUC less than 50% is terrible: it means that you get better performance by switching the positive and negative labels! So the model is doing worse than nothing on this data.
In general there seems to be some problem with the design of the task and/or its evaluation: either the original test set and/or the validation set is/are  not a representative sample for the target problem.
In case the validation set is supposed to be representative, it means that the test set is not valid, possibly due to data leakage (it contains information from the training set). In this case the test set evaluation is meaningless, and the fact the validation performance is much lower means that there is overfitting: the model is capturing details which happen by chance in the training set, because it's too complex and/or the training set is not representative enough.
Comment: Hello Erwan! I checked my data again too. I actually have data of chemical molecules, and when I cross-checked my validation set has many molecules that are almost 85-90% similar to molecules in the train and test set. Can you highlight what could go wrong in the design of the task? As i said im also evaluating ROC-AUC, confusion matrix, accuracy, etc. All of which perform poorly. while training the model metric is also AUC, it is a binary classification and has applied regularization too. I can provide more details if needed.
Comment: How can I detect data leakage? I did not perform any data processing in the beginning so what can be methods of detecting data leakage if any?
Comment: @As13 it's difficult to say what can go wrong. data leakage is not easily detectable in general, because it depends completely on the data and how it was collected. My first idea would be to try to measure the similarity of the validation and test set vs the training set. One way to do this would be to use clustering on all the instances together and then observe whether the ones from the validation set always end up separated from the training set, this would mean that they don't follow the same distribution.
Comment: I don't know the data at all but it's clear that the instances in this validation set were not taken randomly, so the main design question is whether it makes sense to have this different sample separate: would it make sense to redo a random selection of the data among all the instances? this way the model would be trained also on some instances that it currently doesn't know. This would probably work better, but it's important to make this decision only for good 'expert reasons', and I can't really help with this.
Comment: Thanks Erwan for the detailed possibilities!! I will try to implement it. Thanks @Erwan


Pali Scriptures & Folklore

Question: What is she difference between the Pali Suttas and folklore or the Indian folklore at the time? Is it possible some suttas include folklore as well as authentic words of the Buddha?
Answer: Pali scriptures were brought down by the Sangha who actively practice the teachings of the Buddha. The oral tradition and later the scriptures were verified by many Buddhist councils which were headed by enlightened monks. These councils were held specifically to eliminate alien elements.
Folklore is just stories told by ordinary householders who might not even be Buddhist. ex: Hindus believe that Buddha is an avatar of one of their Gods
Answer: Buddha said when told a sutta, do not reject or accept it right away but remember the details so later to compare to other sutta and vinaya if it doesnt fit well with other sources then it is time to reject it.  One sample i can think of is about holy water.  in at least 12+ sutta, Buddha rejected and prohibited monks to make holy water but in a sutta where vesali was afflicted by a famine, Buddha gave Ven. Ananda his alms bowl to make holy water to sprinkle around the city to get rid of the illness.   IMO, I reject this sutta.  There are many sutta especially from Lanna/shan tipitaka that don't really fit well.

Pali Scriptures & Folklore


How to apply the CA-CFAR methods in practice?

Question: Applying constant false alarm rate is a critical step for estimation of performance of all detectors. Has anybody experience on practical implementation of this estimator for energy detector? Can anybody explain and introduce a code to me?
Answer: Constant false alarm rate detection is more of a general technique that underlies a class of approaches; you can't really say that there's "an" implementation of CFAR processing. CFAR techniques are useful when you need to detect the presence of a signal where there is some uncertainty as to what the magnitude of the signal will be, especially relative to any background noise or interference. The general principle of constant false alarm rate detection is that the detector makes some effort to estimate the background level and set a detection threshold adaptively relative to the observed ambient environment. This approach makes the performance of the detector (typically measured quantitatively using the probability of detection $P_d$ and probability of false alarm $P_{fa}$) insensitive to the bulk magnitude of the signal under observation; only relative changes in the statistics of the signal over time (such as a transition from noise only to signal-of-interest plus noise) are important.
Comment: Thanks and I should add that it has several types. CA-CFAR is one of the types. Now could you please let me know how in practice people simulate this? Indeed in practice means that without using statistical distribution how based on concept of false alarm we can simulate CFAR detection.
Comment: I'm not sure what you're asking. If you're familiar with how radar systems work, then implementing cell-averaging CFAR detection is very straightforward. If you're going to simulate it, then you need to have some kind of statistical model for the environment and radar measurements. Otherwise, how do you generate the data for the simulation?


According to Scripture, where is Hell?

Question: Do scriptures say where Hell is? I read another answer on this site, and they said that the Bible says the other planets in our solar system were referred to as "heavens". So if these other planets are "heavens", is it wrong to assume that, maybe the Sun is Hell? Is there any evidence to backup this theory?
Comment: I'm not sure that [tag:catholicism] and [tag:biblical-basis] are necessarily contradictory. That would mean he'd want a Catholic perspective on the biblical passages dealing with 'hell.'
Comment: If you're interested in insights from the historical and linguistic aspects on 'hell', check out my answers to these questions on BH.SE: [Is the Valley of Hinnom adequately translated as hell?](http://hermeneutics.stackexchange.com/a/4758/423) and [Why is Hadēs translated as "hell"?](http://hermeneutics.stackexchange.com/a/8212/423) and [Is Peter's use of Tartarus adoptive of Hellenistic language or ideas?](http://hermeneutics.stackexchange.com/a/4225/423)
Comment: [tag:catholocism] and [tag:biblical-basis] generally should not be used together. biblical basis is asking us to interpret scripture for you, Catholicism is asking what bishops have written on the subject. Very different things. I've removed Catholicism because you asked about the scriptures. Please keep this in mind going forward.
Comment: The Latin word *infernum* carried the idea of divine punishment and gradually came to be confused with the distinct concepts of γέεννα (Gehenna), ταρταρόω (Tartaroo/us), and ᾅδης (Hades). The King James Version of the Bible then followed suit, having long forgotten the distinction between the terms, and translated all of them as 'hell.' This distinction must be kept in mind when discussing this.
Answer: The answer is quite simple: Scripture does not specify where Hell is.
There is a lot of speculation, however, about "where" Hell is, and I suspect the most common beliefs are that:

Hell is not a physical place, but rather a spiritual "place" outside of the known universe.
Hell may be a physical place, but is likely outside of the known universe (i.e. you couldn't get there in a space ship)
Hell is a state of mind, and exists all around us wherever anyone suffers, and in the after life, it may be the same "physical" place as Heaven.

But this is all speculation based on analogies, which is really the only evidence we have in scripture.  So the real answer to your question is: Scripture doesn't say.
This is discussed, from a Catholic perspective, at the Catholic Encyclopedia. Although it doesn't make any dogmatic assertions as to where Catholics believe hell is, it does reference a few scripture verses, and other opinions, which, if taken literally, may indicate a location for hell, but suggests the verses are likely only metaphore. One example:

The Bible seems to indicate that hell is within the earth, for it describes hell as an abyss to which the wicked descend. We even read of the earth opening and of the wicked sinking down into hell (Numbers 16:31 sqq.; Psalm 54:16; Isaiah 5:14; Ezekiel 26:20; Philippians 2:10, etc.). Is this merely a metaphor to illustrate the state of separation from God?

And further:

The Church has decided nothing on this subject; hence we may say hell is a definite place; but where it is, we do not know.
Answer: In order to understand where hell is, we need to understand what hell is first.
Those who wrote the Scriptures were Hebrew, and when they use the term "hell" which comes from the terms "sheol" or "gehenna", we find that the word literally means "a hole in the ground, or a pit".
With this understanding that "hell" is merely a pit or hole in the ground, there's much more clarity to Kind David's quote in Psalm 16:10 where he writes

For thou wilt not leave my soul in hell; neither wilt thou suffer
  thine Holy One to see corruption.

David, a Hebrew, clearly understood that hell was simply the grave, and alludes to the future resurrection of Jesus Christ when Jesus will resurrect all the dead from their graves.
So in a sense, all who die go to hell.  As dismal as that sounds, we have hope!

Psalm 49:15
  But God will redeem my soul from the power of the grave:
  for he shall receive me. Selah.
Comment: Welcome to the site!  This doesn't really have much to do with your answer, but I find that sharing the following tends to help new visitors avoid mistaking the purpose of this site. I do hope to see more from you!  When you get a chance, please see [How we are different than other sites?](http://meta.christianity.stackexchange.com/questions/1808/how-we-are-different-than-other-sites) and [What makes a good supported answer?](http://meta.christianity.stackexchange.com/questions/692/what-makes-a-good-supported-answer)
Answer: "Heavens" refer to everything that's "out there" (from the perspective of humans dwelling on the surface of the earth), and this is distinct from the use of "Heaven" (the abode of God; Ge 21:17, Ge 24:7). No particular place is signified as "Heaven," so it would be overstating the case to claim that Heaven existed on some other planet. Though such a thing might be conceivable, the Scriptures do not make this assertion. Similarly, the "location" of Hell (if there is one in the physical universe) is never specified.
You could suggest that it's the sun, and nobody could prove you wrong. You'd be hard pressed to prove that you're right, though.
It seems more likely (to me) that Heaven and Hell are "places" in the spiritual realm, not loci in the physical universe.

According to Scripture, where is Hell?


How to get all products of a Shopify shop?

Question: In my theme development, I don't find the way to get all the products of my shop.
Although, I can retrieve all the collections with the variable collections (exemple: {% for c in collections %}).
Answer: Check this url: https://help.shopify.com/en/themes/customization/collections/change-catalog-page
Like magic... all your products...
Comment: You can pull 250 with the API at once, and with pagination set to 1000 for example, front-end code can pull 1000. There is no limit of 50 unless you set that for yourself or do nothing.
Comment: While true, it is limited to you having to paginate by 50 or less, and you can't pull more than 50 anywhere else on the site either.
Comment: "Don't paginate a collection by more than 50, that's the maximum amount of products you should query per page." according to their own documentation seen here: http://docs.shopify.com/themes/liquid-variables/paginate
Comment: Key word "should"
Answer: Get all products at once or to run a query(API Request) for all products in shopify store :
using this app is more managed -> https://github.com/phpish/shopify_private_app-skeleton so, my solution below is based on this app or you can relate the solution with your solution as well
<?php

session_start();

require __DIR__.'/vendor/autoload.php';
use phpish\shopify;
require __DIR__.'/conf.php';

$shopify = shopify\client(SHOPIFY_SHOP, SHOPIFY_APP_API_KEY, SHOPIFY_APP_PASSWORD, true);

try
{
    $products = $shopify('GET /admin/products/count.json', array('published_status'=>'published'));

    $totalproducts = $shopify('GET /admin/products/count.json', array('published_status'=>'published'));
    $limit = 50;
    $totalpage = ceil($totalproducts/$limit);
    for($i=1; $i<=$totalpage; $i++){
        $products = $shopify('GET /admin/products.json?'.$limit.'=50&page='.$i, array('published_status'=>'published'));
        foreach($products as $product){
          //do anything at once for all the products in store
        }
     }
  }
  catch (shopify\ApiException $e)
  {
    //
  }

Summary : The idea is to retrieve with page=x as parameter. after calculating the number of pages we will have with specified limit i.e 50 at one time fetch.


Why are stop order called "stop" when it is in fact a "start" condition?

Question: A GTC, stop 65 RMB, limit 100 RMB buy order means start buying the security when it rises above 65 RMB, and stop buying when it reaches 100. So why is it called stop and not start?
Answer: Historically they were conceived as a way to cut losses when the market turned against you. You would tell your broker something like "buy me 100 shares of Anaconda and stop me if it goes below $110"
You can read references to this in old books like Reminiscences of a Stock Operator, the ABC of Options pricing, or the Day Trader's Bible.
Answer: I had this exact question and wasn't entirely happy with the answers given, so here's what I ended up finding out:
A Stop Order: such as a Buy Stop or Sell Stop, is indeed an order to /start/ (that is to "open") a trade.
So why is it called a Buy/Sell Stop?
Because you use it to hedge a loss on an order to buy or sell.
Example if selling: I want to Sell X if X's price goes above $50 for I predict at $50 X is being overbought and the price action will quickly correct itself to a lower price and I want to capitalise on that by selling at its peak, so I put in an order to sell, but, in case I am wrong, I want to STOP selling and start BUYing if X's price reaches $55, because at $55 I predict X has already begun an upward trend instead, so on my order to sell I put in a BUY STOP - stopping my order to sell at $55 and starting my order to buy at $55, because I don't want to lose out on being able to sell them at a higher price.
Hence why BUY STOP (or sell stop in an inverse trade scenario) doesn't sound right at first glance but makes sense in the end!
Another Stop Order is a Stop Loss Order, which shouldn't give confusion behind its name because it would simply stop (exit) your order at $55, without any further action.
Hope this helps anyone.
Answer: A stop order can be used to both enter or exit a position. A stop loss is used to set the price you want to get out if the price reaches that level. Whilst a stop buy or entry order is used to get into a position if the price reaches your desired level for entry.
The stop order just means that you want to place your order at that level, you then need to specify if you are buying to open, selling to open, buying to close or selling to close your position at the stop level.
Comment: What George means by position is simply a trade, where you can buy to enter a long trade or sell to open a short trade, or you sell to exit a long trade or buy to exit a short trade. I am not sure what you mean by your last sentence as it doesn't make any sence, but a stop is simply an order type which can be used as a trigger point to either enter or exit a trade pretty much as George described.
Comment: I have a no idea what you mean by enter or exist a position. This is not about a position. Stop order is an validity instruction. Therefore it is used to telling when to fill in an order. The stop initiate the order, where as limit is where to you the order to stop.


What word is this?

Question: In the film Gangs of New York, what is this word spoken?
http://www.youtube.com/watch?v=ADmX9eMEV9U&t=1m38s
It sounds like benay. What does it mean? The subtitles don't have anything for this word.
Answer: If you log into IMSDB (The Intenet Movie Script Database) you'll find the script: http://www.imsdb.com/scripts/Gangs-of-New-York.html. Look for masterscene header 7, and in that scene Vallon says bene, which is Italian for good, or probably it this context, it expresses well.
Answer: He's saying "Bene" which is Latin for "good".
He's addressing what looks like some kind of Catholic priest or mock-priest, which may have prompted the Latin.
Answer: Bene
From Middle English bene, from Old English bēn ("prayer, request, petition, favour, compulsory service"),
http://en.wiktionary.org/wiki/bene
http://www.etymonline.com/index.php?term=bene-
Answer: "Bene" is Italian rather than Latin, commonly heard in cities where there were Italian immigrants. In The Godfather, Luca Brasi is offered a job with a rival family to the Corleones. He asks how much he'll be paid, and when they tell him, he says, "Bene", meaning "Fine".
Answer: The answers here have the right interpretation of the word bene (good), but in my opinion, they have missed the mark on the origin. Here's the possible origins, in reverse order of likelihood (in my opinion.)
Italian
The word was used by an Irish-Catholic priest and his son, so it is unlikely to be an Italian usage. One might make the argument that the word was part of general NYC slang at the time, but I find that unsatisfying because the majority of Italian immigration to the States happened after Italian unification in 1871, while the movie is set in 1846/1862.
Latin
The word could also be used in the Latin sense, because an Irish-Catholic priest gang leader may indeed have knowledge of Latin, but I also find that unlikely in the context the word is used directly in that way.
Thieves' Cant
I think it's ultimately lower-class slang. Although there aren't many other instances of very obscure slang that I recall in the script, I think that the usage of bene is very idiosyncratic, and clearly understood by the other underworld characters. This is the Gangs of New York, after all, and the word is used by the leader of an early 19th century criminal gang.
Here is the entry for bene in an 1899 publication of A New Dictionary of the Terms Ancient and Modern of the Canting Crew.
And via Project Gutenberg, Slang Dictionary Etymological Historical and Anecdotal (1913):

Bene, good. Benar, better.

So while I can't be certain that the word was chosen for this reason by the writers of the script, I presume they made some research into underworld slang of the time. I think they chose some link to this culture which would still be reasonably easy to interpret by a modern movie viewer.

What word is this?


Which one is better to create a web application? web2py or cherrypy

Question: I am using Raspberry Pi to function as a mini web server. At first, i came across web2py and started to learn it. It was tough for a beginner like me. Later, a friend in a forum introduced CherryPy to me and i started to work on the web application skeleton that he gave me. Soon, I abandoned web2py and proceeded with cherrypy as it is fairly straightforward.
Somehow, I think web2py could be a good choice too. Web application for both are written in python, with html, css and javascripts. So whatever i've done using cherrypy may be possible to transfer over to web2py. (is it true?)
I would like to find out what are the main differences between those 2 and their respective pros and cons. I hope to find out more about fellow users' experiences in using web2py and cherrypy. In such way, future visitors can make a comparison before they proceed in choosing which one to use. Thank you!
Answer: web2py is using MVC model and each of the scripts are nicely separated. It can be deployed at pythoneverywhere.com. not too sure about cherrypy.
Answer: I found a good source of information to compare between web2py and others. Here's the link: http://www.web2py.com/examples/static/web2py_vs_others.pdf


Using whatsapp on two devices

Question: One device has my Sim card, the other one only the internet connection. Both devices have already been verified by my number. Will I get incoming messagges in both devices?
Answer: You're not allowed to do this, From whatsapp FAQ:

Using one WhatsApp account on multiple phones, or with multiple phone numbers
  Your WhatsApp account can only be verified with one number on one device. If you have a dual SIM phone, please note that you still must choose one number to verify with WhatsApp. There is no option to have a WhatsApp account with two phone numbers.
If you attempt to frequently switch your WhatsApp account between different devices, at a certain point, you may be blocked from re-verifying your account. Please don't repeatedly switch between different devices and numbers.
Comment: What about theb phone without sim working on wifi? I read there whatsapp works and it would be a second device
Answer: You cannot use the same WhatsApp account on more than one device at a time. As soon as you sign-in to a new device, the old one becomes invalidated.
WhatsApp does not support a 2nd device.
Comment: What if I dont need to sign up? I mean, it happened that when I changed the smartphone, I transferred all the back ups, the files... In the new device I didn't need to sign up to use whatsapp so I had whatsapp working both in the old and new device.. How is it possible?

Using whatsapp on two devices


How quickly can fortifications be built in D&D 4e, magically and otherwise

Question: My bad guys have holed themselves up for a couple months.  Given little preexisting fortification, what resources are there for for building mechanical and magical defenses?  Is there something equivalent to 3e's Mage's Magnificent Mansion?  How about Wall of Stone?  I don't even know where to begin with magical defenses, but presumably those exist as well.
Answer: The fastest way is to ritually create a stronghold with a level 20 ritual. Assuming you don't have the levels for that,
The article notes:

If buying or seizing a stronghold doesn't fit with
your plans, you can build one from scratch. Doing
so doesn't cost any more than buying one. It does
take time, though. Considering that a community
might spend decades building a cathedral or a
castle, don't expect to move in right away. Even in a
perfect scenario, you need to rely on the availability of local materials and labor. This situation gets
worse if you make an artful decision and place the
stronghold in a ridiculous spot, such as clinging to
the side of a mountain or on a remote and barren
island. Depending on what you want, it could take
1d10 + 5 months to build an impressive wooden
structure such as the longhouse illustrated in this
article, to 1d10 + 5 years to build a stone castle or
cathedral from scratch. Extra time can be tacked on
for extremely difficult projects.

The article provides the following ritual:

Bigby's Construction Crew
Level: 15 Component Cost: 5,000 gp
Category: Creation Market Price: 20,000 gp
Time: 24 hours Key Skill: Arcana (no check)
Duration: Permanent
A veritable army of magical hands appears in the
air around you, each armed with tools appropriate
to the task to which you set them, from carpentry to
masonry. When you perform the ritual, you describe
the desired construction in great detail. ... You can use this ritual to build a stronghold whose
constructed space does not exceed 300 squares.
That space can be divided and arranged any way you
please but must be contiguous.

Lower levels have a much more difficult time of it, as the idea of manipulating terrain is something best handled in a skill-challenge rather than mechanically.
My recommendation, if the players don't want a stronghold, is to turn it into an extended skill challenge, with each success in arcana, dun geoneering, history, nature, thievery, etc.. providing some interesting feature which they can blow up/use later in the expected epic defense battle. Every failure wastes time or resources.
Answer: Aside from magical powers of any kind there is a historical model of fortification involving simple manual labor that may useful to you.
Roman Legions could construct a "castra", a fortified camp in as little as a few hours even while under attack.  These came in many different variations depending on how they were used and how long they would be used. Wikipedia roman legion castra
If your bad guys have any knowledge or experience with fighting and defending, (if not they should) then in a couple months with just manual labor they could build a very respectable fortification with out any magic used at all.  Plenty of stakes in the ground, pit falls, walls, gates, and even a few towers if that would be appropriate.  They could even have stock piled munitions and fighting supplies at key points in the defenses.  All these would be tailored to how they intend to fight and defend.  Bad news for an attacking party especially if the bad guys know how the party fights.  They would prepare for that.
Since it sounds like you are the DM, don't worry too much about "magic building techniques" and just build the fortification.  The party isn't going to be analyzing how it was built, but more on can they survive breaching it.
Comment: That's impressive.  I kinda figured they'd probably have time to set up a palisade wall, but not a castle.  This indicates that with just manual labor they can get a lot closer to castle than I would have expected.
Comment: Yes, and not just a crappy one but something well thought out and defensible.  A lot of things have been done historically that we marvel at today.  Don't over look manual labor.  It is cheap (free if the bad guys use slaves) and plentiful.  Watch the movie Bridge Over the River Kwai for a good example of conscript labor and why it is more effective than most people think.
Comment: Also if you add in magic excavation to enhance the lifting and moving of things the bad guys could very well have a full-blown Castle waiting for the party.
Answer: This is a resource for DnD 3.x, but you may find good spells to turn into rituals for use in 4e.  I ran a campaign with it, and it did large-scale battles really well.  Eden Odyssey's Fields of Blood: The book of war The Q&A site for it is here.
It has rules for building fortifications, cities, and the like.  One of the spells used was a spell that made a 5ft bump of earth, with a 5ft ditch behind it.  It was a low-level spell, and the Druid used it a lot.  He could also move a ton (many tons, actually) with a stone-shape spell and all but put the construction industry out of business!  Each casting of that 3rd level spell could produce 100 squares of 2x5x5ft stone. (20cuft at level 10)  See this posting for an answer on translation stone-shape to 4e.
My actual suggestion for the badguys using 4E as-is:

Use a ruined fort.
Make a ton of passages using the ritual excavation.
Conceal those passages.
Use Kobold tactics.
...
Profit!

And besides, you're the GM.  Do whatever makes the PC's squeal. :D
Comment: @valadil, even kobolds know how to build good, sneaky defenses.  :D
Comment: 1. Check!  2. Excavation is exactly the kind of thing I was looking for.  I'd assumed the defenses would be above ground, but I like your idea a whole lot better.  Given what excavation does, I see no reason why the bad guys would make themselves vulnerable to flying PCs.
Comment: @valadil, tunnel fighting is exceptionally dangerous, especially if the badguys rig fall-ins or, better yet, trigger the traps themselves so there's nothing for the thief to disarm.  The PCs will be sore-pressed to stop them.  :D  Never give a badguy *several months* to dig in.
Comment: Good to know.  Thankfully I hadn't yet established how long they'd been there except that it's between 1 and 6 months.  Also the enemy isn't terribly well organized, so some amount of bad planning on their part is justifiable.


Variable entered in logistic regression model is part of another variable entered in the same model

Question: I´m trying to find variables predicting a disease by using first logistic regression for each variable on the disease and then entering the significant variables into a multiple logistic regression model. However, one of the variables in the multivariate model is a clinical score, which contains some of the variables adjusted for (among others bmi<18).
My question is: does it make sense to have both in the multivariate model? And if yes, what is the interpretation of an insignificant clinical score in the multivariate model? Is it insignificant because I controlled for some of its variables?
Answer: Two comments:
First, I would explore other methods of variable selection. Looking at a set of unadjusted regressions and choosing the "significant" variables to then include in a final model is not an ideal approach. Your options are plentiful - search around here for topics on model selection to get you started. There are experts on this topic floating around, so perhaps some of them will add more here.
Second, think about the interpretation of the regression coefficient in a multiple regression. An increase in your clinical score is associated with X change in Y, holding covariates constant. Theoretically, if your clinical score increases, and you hold some component of that score constant, than the estimated association must be due to the other aspects of the clinical scale.
What to do really depends on what your goals are. Are you more interested in predicting things, or making any causal inferences? Can you discard the clinical scale entirely and focus on its components,or are you stuck using it?
Comment: Then I definitely wouldn't include components of the score as covariates, for the reason stated above. This older but very useful paper might help further expand your horizons a bit (Harrell's 1996 Stats Med paper on multivariable prognostic models - http://www.unt.edu/rss/class/Jon/MiscDocs/Harrell_1996.pdf)
Comment: Thank you both for very useful comments! I read the paper. However, now I am thinking to leave out the log reg completely and focus only the ROC analysis. Would that be enough? Or is it better to do af univariable log reg of all possible variables and then choose the significant ones to assess further in a ROC statistic?
Comment: The score has been developed some yers ago and has been validated when using it to monitor patients. Now we would like to see if it has other areas it can e used in, fx in screening a group of patients for this disease. I am also looking at other, by previous research suggested, variables to see what of the current knowledge works best. Apart from the log reg I also use ROC stat of the significant variables. So to answer the last question; I am stuck with the score.
Comment: To add to D L's good responses:  You never want to have a situation in which, because of multivariate control, you end up controlling part of a relationship right out of itself.  Statistical cannibalism, you might call it.  What meaning would there be to say the relationship between X1 and Y was ... when part of X1 (embodied in X2 and X3) was being controlled?  It would be nonsensical.


What are the best burger buns available in the UK?

Question: In recipes online I see recommendations for buns such as Martin's Potato Rolls. However it doesn't seem like it's possible to get this kind of bun in the UK, or indeed anything other than the basic no frills sesame seed burger bun. What is the best burger bun available? And where should one shop for it?
Comment: "Best" is quite subjective. Can you qualify what you look for in a burger bun? I've had sourdough, pretzel, kaiser buns before and each have its own pros and cons.
Comment: Go to your local favorite artisan bakery and ask for some burger buns.
Comment: Make them yourself. Here in Germany, all bought buns are crap whereas self made buns turn junk food into a truly luxury dish. Sample recipe: https://www.ploetzblog.de/2013/02/09/leserwunsch-hamburgerbroetchen-hotdogbroetchen-nach-peter-reinhart/
Answer: After living in the UK for more than a decade I share your pain in finding good burger buns. You can often find burger buns in the store but they are usually pretty bland and artificial. Better quality buns in the right shape or size are usually heavy and chewy.
You could take a cue from the artisan "posh" burger places that are popping up all over London and use brioche buns. These are widely available, and they have many of the right qualities as they are soft but still have structure and flavor. They do have a sweetness which I don't think goes with a burger but that's really minor. Other than that it depends on what supermarket chains are around (Waitrose and coop are the best sources I've found) and what bakeries you have around you. Shop around and pinch some buns till you find what you want.
You could go down the route of making them yourself, the Hawksmoor slider bun recipe is available on-line here, it's pretty simple and reliable.


All iPhone 4s pics not showing on Windows 7 PC

Question: I have an Iphone 4s and a Windows 7 PC.
When I plug in my phone it is recognized, but when I open the pictures folder (DCIM) there are only 2 folders showing.
One shows about 30 pictures, 1 video, the other shows about 70 pictures, 3videos. I have just over 1500 pictures on my actual phone, I'm looking to back them up onto the PC but why are they not all showing?
I've tried unlocking the phone first.
Please help!
Thank you.
Comment: Is this new problem? have you been able to see them before.
Comment: DCIM says your windows sees the iphone as a SSD card, not as iPhone. Did you try iTunes on Widows, or do you have those photos on iCloud. This might help https://support.apple.com/en-us/HT201302
Comment: I've never actually tried before. I have synced with iTunes, but the same issue with all the same photos. I do have all my photos on the iCloud I think, I have it set to automatically back up to the iCloud, I was kind of looking for another trustworthy back up.
Comment: Do you have iCloud photo library enabled?
Answer: Have you enabled iCloud Photo Library? If you have, go to Settings > Apple ID > iCloud > Photos to see whether you tick on "Optimise iPhone Storage". If you've ticked on this item, then that will explain your situation. If you enable this feature, it's normal for you to see just a few photos showing on the picture folder, because the rest of your photos is optimised to thumbnail and won't be shown on computer.
In this case, you should check your iCloud. All photos in your iPhone 4s will be stored there.
Answer: If you want to sync data from your iPhone with Windows always use iTunes.
You can download it here: https://www.apple.com/itunes/download/
iTunes is the official software from Apple to sync data from your iPhone with an other device and crucial for your iPhone when communicating with Windows.
Comment: I've done that, Where do the pictures go once synced with iTunes though?


xConnect Certificate Expiration

Question: Im getting an error as my xConnect certificate appears to have expired today! Im a little suspicious by those dates as it would appear to be valid from Feb 2018 to today. Does this sound possible and would I use SIF to create a new one?
Answer: Assuming it's expired you can easily create a new certificate using Windows Powershell by running the following command(so no need of SIF just for that part):
New-SelfSignedCertificate -CertStoreLocation Cert:\LocalMachine\My -DnsName "ClientStaging" -FriendlyName "Client Staging Self Signed" -NotAfter $([datetime]::now.AddYears(10))

Don't worry about the DnsName — you can assign the cert to any host name.
This is for self-signed certificates. After you run that you will get the thumbprint of it, so just make sure you update the connection string and the AppSettings.config file, under the xconnect folder which is normally something like myxconnectroot\App_Config\AppSettings.config
Comment: You will also need to make sure to add this new cert to a trusted root store. I followed this guide successfully: https://www.aubrett.com/article/information-technology/web-development/iis/powershell-new-selfsignedcertificate
Answer: You also need to add the xConnect App Pool user to the new certificate via Manage Computer Certificates MMC. Right-click on the new cert then > All Tasks > Manage Private Keys. Add the xConnect App Pool user there.
Answer: Ran into the same this week on Sitecore 10.1.2. I had difficulty getting indexing operations in CM to accept the new self-signed cert from the accepted answer to take even though https requests to xConnect showed secure; I kept getting different flavors of Invalid Certificate error through CM, including the dreaded "The request was aborted: Could not create SSL/TLS secure channel" error.
It also happened that my local identityserver and site certificates expired same day, so we needed to do this three times, and as you know it involved several configs to update.
Ran across this forum post:

We have a LOT of test environments. As the certs have been expiring, i was complaining about the manual process I was using to change/update these. My clever co-worker Karl bowled up a powershell script that has been such a help!
This will generate a new CA cert for you to base all your self-signed certs on, or it will use one you already have. Put the pfx file in the same directory as the script. It displays all the sites in IIS and you pick the one to update - say a Sitecore 9 xconnect site, changes out the cert in the bindings, updates the thumbnails where needed in config. So easy once you've used it a couple of times. Enjoy. NB uploading as a txt which will need to be renamed to a ps1

This was a super helpful script that took care of xConnect, identityserver, and local Sitecore site in just a few moments.
NB: If you're going to go this route, make sure you do not delete your expired certs or unbind them in IIS. The script will use those certs and bindings to reverse-engineer CN, O, OU, etc., for the new ones.

# 2022-03-31: Script to issue/renew local SSL certificates and update configuration for Sitecore sites.
# Note: requires administrative permissions to run successfully. USE AT OWN RISK.
# Author: FuseIT

[CmdletBinding(PositionalBinding=$false)]
param (
    # Root CA password.
    [string] $p,
    # Number of years to issue for.
    [int] $y,
    # Optional settings for new CA certificate.
    [string] $cn,
    [string] $o,
    [string] $ou,
    [string] $fn,
    # Root CA file, or "new" to generate a self-signed CA certificate.
    [Parameter(ValueFromRemainingArguments)]
    [string] $rootfile
)

Import-Module -Name WebAdministration

function GetInputWithDefault ([string]$prompt, [string]$default) {
    $input = ""
    if ($default -eq "") {
        # Input is required.
        while ($input -eq "") {
            $input = Read-Host -Prompt "$($prompt)"
        }
    } else {
        # Allow default value.
        $input = Read-Host -Prompt "$($prompt) [$($default)]"
    }
    if ($default -ne "" -And $input -eq "") {
        $input = $default
    }
    return $input
}

function CreateCACert ([string]$rootfile, [string]$p, [string]$cn, [string]$o, [string]$ou, [string]$fn, [DateTime]$notafter) {

    # Get values for new self-signed CA cert.
    $cn = GetInputWithDefault "Common Name (CN)"  "LocalDevCA"
    $o = GetInputWithDefault "Organization (O)" "Local"
    $ou = GetInputWithDefault "Organizational Unit (OU)" "localdev.ca"
    $fn = GetInputWithDefault "Friendly name" "Local dev root CA"

    # Generate a new self-signed root CA certificate, in the local Personal store.
    $cacert = New-SelfSignedCertificate `
     -Subject "CN=$($cn),O=$($o),OU=$($ou)" `
     -CertStoreLocation cert:\LocalMachine\My `
     -KeyExportPolicy Exportable `
     -KeyUsage CertSign,CRLSign,DigitalSignature `
     -KeyLength 2048 `
     -KeyUsageProperty All `
     -KeyAlgorithm 'RSA' `
     -HashAlgorithm 'SHA256' `
     -Provider "Microsoft Enhanced RSA and AES Cryptographic Provider" `
     -NotAfter $notafter `
     -FriendlyName "$($fn)"

    Write-Host ""

    # Verify.
    if ($cacert -eq $null) {
        Write-Host "Failed to create self-signed CA certificate."
        return $null
    }
    Write-Host "Created self-signed CA certificate:"
    Write-Host $cacert
    Write-Host "----------------------------------------"
    Write-Host ""

    # Perform the export and verify.
    $certfile = Export-PfxCertificate -Cert $cacert -FilePath $rootfile -Password (ConvertTo-SecureString -String $p -AsPlainText -Force)
    if ($certfile -eq $null) {
        Write-Host "Failed to export self-signed CA cert to PFX file."
        return $null
    }
    Write-Host "Self-signed CA certificate exported to $($rootfile)."
    Write-Host ""

    return $cacert
}

function GetCACertFromFile ([string]$rootfile, [string]$p) {
    # Read the existing CA cert file to get the thumbprint (and verify that it is a valid cert).
    $cacert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
    $cacert.Import((Resolve-Path $rootfile), (ConvertTo-SecureString -String $p -AsPlainText -Force), [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::DefaultKeySet)

    # Get-PfxCertificate did not have the -Password parameter prior to Powershell version 6.
    # $cacert = Get-PfxCertificate -FilePath $rootfile -Password (ConvertTo-SecureString -String $p -AsPlainText -Force)

    if ($cacert -eq $null -Or $cacert.Thumbprint -eq "") {
        Write-Host "Failed to load CA certificate from file $($rootfile)."
        return $null
    }

    return $cacert
}

function FindOrImportRootCACert ([string]$thumbprint, [string]$rootfile, [string]$p) {
    # Attempt to locate the CA certificate in the root store.
    $rootcert = Get-ChildItem Cert:\LocalMachine\Root | Where-Object {$_.Thumbprint -eq $thumbprint}

    if ($rootcert -eq $null) {
        # Offer to install the certificate from file.
        if ((Read-Host -Prompt "CA certificate not in Root store. Install? [y/N]") -ne "Y") {
            return $null
        }
        $rootcert = Import-PfxCertificate -FilePath $rootfile -Password (ConvertTo-SecureString -String $p -AsPlainText -Force) -CertStoreLocation Cert:\LocalMachine\Root

        if ($rootcert -eq $null) {
            Write-Host "Certificate import to Root store failed."
        }
    }

    return $rootcert
}

function FindOrImportPersonalCACert ($rootcert) {
    # Attempt to locate existing.
    $signingcert = Get-ChildItem Cert:\LocalMachine\My | Where-Object {$_.Thumbprint -eq $rootcert.Thumbprint}

    if ($signingcert -eq $null) {
        # Add to Personal store.
        $mystore = Get-Item cert:\LocalMachine\My
        $mystore.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite)
        $mystore.Add($rootcert)
        $mystore.Close()
        $signingcert = Get-ChildItem Cert:\LocalMachine\My | Where-Object {$_.Thumbprint -eq $rootcert.Thumbprint}

        if ($signingcert -eq $null) {
            Write-Host "Certificate import to Personal store failed."
        }
    }

    return $signingcert
}

function GetIISBindingCertificates ([int]$idx) {
    $bindinglist =@()

    # Iterate IIS SSL bindings.
    Get-ChildItem -Path IIS:SSLBindings | ForEach-Object -Process `
    {
        if ($_.Sites) {
            # Locate certificate matching thumbprint in Personal store.
            $certificate = Get-ChildItem -Path CERT:LocalMachine/My |
                Where-Object -Property Thumbprint -EQ -Value $_.Thumbprint

            $bindinglist += [PsCustomObject]@{
                Select = $idx
                Site = $_.Sites.Value
                DnsName = $certificate.DnsNameList
                Expiry = $certificate.NotAfter
                Thumbprint = $certificate.Thumbprint
                Subject = $certificate.Subject
                FriendlyName = $certificate.FriendlyName
                Port = $_.Port
                HostName = $_.Host
                IPAddress = $_.IPAddress
            }

            $idx++
        }
    }

    return $bindinglist
}

function CreateSelfSignedCertificate ([String[]]$dnsnamearr, [DateTime]$notafter, $signingcert, [string]$subject, [string]$fname) {
    # Generate new self-signed certificate, valid for configured period, into the Personal store.
    $newcert = New-SelfSignedCertificate `
        -CertStoreLocation cert:\LocalMachine\My `
        -DnsName $dnsnamearr `
        -NotAfter $notafter `
        -Signer $signingcert `
        -KeyLength 2048 `
        -KeyUsageProperty All `
        -KeyAlgorithm 'RSA' `
        -HashAlgorithm 'SHA256' `
        -Subject $subject `
        -FriendlyName $fname

    return $newcert
}

function GetCertificateAcl ($cert) {
    # Get permissions from old certificate.
    $certkeys = [System.Security.Cryptography.X509Certificates.RSACertificateExtensions]::GetRSAPrivateKey($cert)
    # The existing cert keys may be in one of a couple of subdirectories, just find match by name.
    $aclpath = Get-ChildItem -Path "$env:ALLUSERSPROFILE\Microsoft\Crypto\" -Name "$($certkeys.key.UniqueName)" -Recurse
    $aclpath = "$env:ALLUSERSPROFILE\Microsoft\Crypto\$aclpath"
    if ($aclpath -eq $null) {
        return $null
    } else {
        return Get-Acl -Path $aclpath
    }
}

function SetCertificateAcl ($cert, $acl) {
    # Apply ACL to certificate.
    $certkeys = [System.Security.Cryptography.X509Certificates.RSACertificateExtensions]::GetRSAPrivateKey($cert)
    $aclpath = Get-ChildItem -Path "$env:ALLUSERSPROFILE\Microsoft\Crypto\" -Name "$($certkeys.key.UniqueName)" -Recurse
    $aclpath = "$env:ALLUSERSPROFILE\Microsoft\Crypto\$aclpath"
    if ($aclpath -ne $null) {
        Set-Acl -Path $aclpath -AclObject $acl
    }

    return $aclpath
}

function AddAclRule ($acl, $identity) {
    $arglist = $identity, "FullControl", "Allow"
    $newrule = New-Object System.Security.AccessControl.FileSystemAccessRule -ArgumentList $arglist
    $acl.SetAccessRule($newrule)
}

function CopyCertificateAcl ($oldcert, $newcert) {
    # Get permissions from old certificate.
    $acl = GetCertificateAcl $oldcert
    if ($acl -ne $null) {
        # Apply to new.
        $aclpath = SetCertificateAcl $newcert $acl
    } else {
        $aclpath = $null
        Write-Host "Unable to locate private keys to match permissions from old certificate, please set permissions on the new certificate manually."
    }

    return $aclpath
}

function UpdateIISBinding ($site, $selectedbinding, $newcert) {
    # Update the IIS binding (make sure to get the matching one where multiple exist for the same site).
    # Note strange things happen if we don't explicitly remove the old one and add a new one. Also assume SNI.
    if ($selectedbinding.IPAddress) {
        Remove-WebBinding -Name $site.Name -Protocol "https" -Port $selectedbinding.Port -IPAddress $selectedbinding.IPAddress
        New-WebBinding -Name $site.Name -Protocol "https" -Port $selectedbinding.Port -IPAddress $selectedbinding.IPAddress -SslFlags 1
        $binding = Get-WebBinding -Name $site.Name -Protocol "https" -Port $selectedbinding.Port -IPAddress $selectedbinding.IPAddress
    } else {
        Remove-WebBinding -Name $site.Name -Protocol "https" -Port $selectedbinding.Port -HostHeader $selectedbinding.HostName
        New-WebBinding -Name $site.Name -Protocol "https" -Port $selectedbinding.Port -HostHeader $selectedbinding.HostName -SslFlags 1
        $binding = Get-WebBinding -Name $site.Name -Protocol "https" -Port $selectedbinding.Port -HostHeader $selectedbinding.HostName
    }
    $binding.AddSslCertificate($newcert.GetCertHashString(), "my")
    Write-Host ""
    Write-Host "Updated IIS Binding to use new certificate"
}

# ==============================
# Main script start.
# ==============================

if ($rootfile -eq "" -Or $p -eq "") {
    # Root CA file and password parameters are required.
    echo "Usage: RenewSSLCert.ps1 |new -p ROOT_CA_PWD [-y YEARS_VALIDITY=10]"
    echo ""
    exit
}
if ($rootfile.ToLower() -ne "new" -And (Test-Path($rootfile)) -ne $true) {
    # Root CA must be either "new" or a valid filename.
    echo "Root CA file '$($rootfile)' not found."
    echo ""
    exit
}

if ($y -eq 0) {
    # Default to 10 years validity period.
    $y = 10
}
# Validity period for new certificates.
$notafter = (Get-Date).AddYears($y)

echo ""

if ($rootfile.ToLower() -eq "new") {
    # Export the certificate to a file in the current directory.
    $dirpath = Split-Path $MyInvocation.MyCommand.Path
    $rootfile = "$dirpath\RootCA.pfx"

    # Confirm creating the self-signed CA cert.
    if ((Read-Host -Prompt "A self-signed CA certificate will be generated and installed with password '$($p)'. OK? [y/N]") -ne "Y") {
        exit
    }

    # Create.
    $cacert = CreateCACert $rootfile $p $cn $o $ou $fn $notafter
}
else {
    $cacert = GetCACertFromFile $rootfile $p
}
if ($cacert -eq $null) {
    exit
}

# Ensure the CA certificate is installed in the Root store.
$rootcert = FindOrImportRootCACert $cacert.Thumbprint $rootfile $p
if ($rootcert -eq $null) {
    exit
}

# The CA certificate must be present in the Personal store to be used for signing.
$signingcert = FindOrImportPersonalCACert $rootcert
if ($signingcert -eq $null) {
    exit
}
echo "CA signing certificate ready for use."
echo ""

# ==============================
# CA certificate setup complete.
# ==============================

echo "Certificate renewal options:"
$bindinglist = GetIISBindingCertificates 2

if ($bindinglist.count -eq 0) {
    echo "No existing IIS SSL bindings found."
}

# A couple of special options.
echo "[0] Cancel"
echo "[1] Generate a new certificate for a binding not shown"

# Display the certificate list and ask the user for a selection.
foreach ($b in $bindinglist) {
    echo "[$($b.Select)] $($b.Site) - $($b.DnsName)"
}
echo ""
[uint16]$bindingidx = Read-Host -Prompt "Please select a certificate to renew or 0 to exit"
echo ""

# Make sure we got a sensible response.
if ($bindingidx -eq 0) {
    exit
}
if ($bindingidx -lt 1 -Or $bindingidx -gt ($bindinglist.count + 1)) {
    echo "Invalid selection"
    exit
}

if ($bindingidx -eq 1) {
    $site = $null
    $sitepath = ""
    $selectedbinding = $null
    $oldcert = $null
    $aclpath = $null

    # Issue a new certificate for a binding that doesn't appear.
    $dnsnames = GetInputWithDefault "Domain Name(s), comma-separated" ""
    $fname = GetInputWithDefault "Friendly name" ""
    $dnsnamearr = $dnsnames.Split(",")

    $newcert = CreateSelfSignedCertificate $dnsnamearr $notafter $signingcert $dnsnames $fname
}
else {

    $bindingidx = $bindingidx - 2
    $selectedbinding = $bindinglist[$bindingidx]
    $oldcert = Get-ChildItem Cert:\LocalMachine\My | Where-Object {$_.Thumbprint -eq $selectedbinding.Thumbprint}

    # Make sure we can load the full IIS site info.
    $site = Get-IISSite $selectedbinding.Site
    if ($site -eq $null) {
        echo "Failed to load IIS site information."
        exit
    }
    $sitepath = $site.Applications["/"].VirtualDirectories["/"].PhysicalPath

    # Display the full certificate details and warning.
    echo ""
    echo "================================"
    echo $oldcert
    echo ""
    echo "This will generate a new certificate using the CA certificate '$($signingcert.FriendlyName)', which is locally trusted but NOT FOR PRODUCTION USE!"

    # Big warning because this is a self-signed certificate.
    if ((Read-Host -Prompt "ARE YOU SURE? [y/N]") -ne "Y") {
        exit
    }

    # Need to convert to a string array for DnsName property.
    [String[]]$dnsnamearr = @()
    foreach ($d in $selectedbinding.DnsName) {
        $dnsnamearr += "$d"
    }
    # Check Subject and FriendlyName values.
    $subject = "$($selectedbinding.Subject)"
    if ($subject.Length -eq 0) {
        $subject = $dnsnamearr[0]
    }
    $fname = "$($selectedbinding.FriendlyName)"
    if ($fname.Length -eq 0) {
        $fname = $dnsnamearr[0]
    }

    # Create a new certificate using details from the old certificate.
    $newcert = CreateSelfSignedCertificate $dnsnamearr $notafter $signingcert $subject $fname
}

# Display to user.
echo ""
echo "New certificate created:"
$newcert
echo ""

if ($oldcert -ne $null) {
    # Copy the permissions from the old to the new.
    $aclpath = CopyCertificateAcl $oldcert $newcert
}

if ($aclpath -eq $null) {
    # Either a new certificate or failed to copy ACL for replacement. Attempt to set manually.
    $acl = GetCertificateAcl $newcert
    if ($acl -eq $null) {
        echo "Unable to load ACL for certificate, permissions will need to be set manually."
    } else {
        $identities = GetInputWithDefault "Assign certificate key permissions to (comma-separated)" "IIS_IUSRS,LOCAL SERVICE"

        # Iterate the provided identities and attempt to add one by one.
        foreach ($identity in $identities.Split(",")) {
            AddAclRule $acl $identity
        }

        # Apply the ACL.
        SetCertificateAcl $newcert $acl
    }
    echo "Further permission changes can be made via the Certificates Manager if required."
}
echo ""

# ==============================
# New certificate setup complete.
# ==============================

if ($selectedbinding -eq $null) {
    # This is as far as we can go for new certificates.
    echo "The IIS binding will need to be configured to use the new certificate manually."
    echo ""
    if ((Read-Host -Prompt "If this is for a Sitecore site further manual configuration is required. Show details? [y/N]") -eq "Y") {
        echo ""
        echo "Your new certificate thumbprint is: $($newcert.Thumbprint)"
        echo ""
        echo "For an XConnect site, set this thumbprint in:"
        echo "  * \App_Config\AppSettings.config"
        echo "  * \App_Data\jobs\continuous\AutomationEngine\App_Config\ConnectionStrings.config"
        echo "  * \App_Data\jobs\continuous\ProcessingEngine\App_Config\ConnectionStrings.config"
        echo "  * Primary Sitecore site \App_Config\ConnectionStrings.config for the XConnect connection."
        echo ""
        echo "For an Identity server site, set this thumbprint in:"
        echo "  * \Config\production\Sitecore.Identity.Server.Host.xml"
    }
    exit
}

# Update the IIS binding to use the new certificate.
UpdateIISBinding $site $selectedbinding $newcert

# ==============================
# IIS binding setup complete.
# ==============================

# Sitecore configuration update support (optional).

# We need to distinguish between three different types: main sitecore, xconnect, identityserver.
# Each has different configuration requirements.
echo ""
echo "Additional automatic changes can be made to update the certificate thumbprint for Sitecore."
echo "Please select the Sitecore site type:"
do {
    write-host "Sitecore [X]Connect"
    write-host "Sitecore [I]dentity server"
    write-host ""
    write-host "[0] Do not attempt changes"
    write-host ""
    write-host -nonewline "Enter type: "
    $sitetype = read-host
    write-host ""
    $ok = @("X","I","0") -contains $sitetype
    if ( -not $ok) { write-host "Invalid selection" }
}
until ( $ok )

# Locate the sitecore web root and appropriate config files, and validate whether everything looks good.
switch ($sitetype) {
    "X" {
        # We need the following config files:
        $files = $("\App_Config\AppSettings.config",
            "\App_Data\jobs\continuous\AutomationEngine\App_Config\ConnectionStrings.config",
            "\App_Data\jobs\continuous\ProcessingEngine\App_Config\ConnectionStrings.config")
        foreach ($f in $files) {
            $fp = "$sitepath$f"
            if ((Test-Path -Path $fp) -ne $true) {
                echo "Expecting file at $fp but none found - you will need to manually change the thumbprint to the new one."
            } else {
                # Replace all instances of the old thumbprint with the new one.
                (Get-Content $fp) -replace $oldcert.Thumbprint, $newcert.Thumbprint | Set-Content $fp
                echo "Replaced $($oldcert.Thumbprint) with $($newcert.Thumbprint) in $fp"
            }
        }

        # The primary site also needs updating with the new XConnect cert thumbprint.
        $idx = 1
        $sitelist =@()
        echo ""
        echo "Select primary Sitecore site for XConnect thumbprint update:"
        # Iterate IIS sites.
        Get-IISSite | ForEach-Object -Process {
            if ($_.Name -ne $selectedbinding.Site) {
                $sitelist += [PsCustomObject]@{
                    Select = $idx
                    Site = $_.Name
                }

                $idx++
            }
        }

        if ($sitelist.count -gt 0) {
            # Display the certificate list and ask the user for a selection.
            foreach ($b in $sitelist) {
                echo "[$($b.Select)] $($b.Site)"
            }
            [uint16]$scidx = Read-Host -Prompt "Please select a site or 0 to skip"
            echo ""

            # Make sure we got a sensible response.
            if ($scidx -gt $sitelist.count) {
                echo "Invalid selection, skipping. The primary Sitecore site will need its \App_Config\ConnectionStrings.config file updated with the new XConnect certificate thumbprint manually."
            }
            elseif ($scidx -gt 0) {
                $scsite = Get-IISSite $sitelist[$scidx - 1].Site
                if ($scsite -eq $null) {
                    echo "Failed to load IIS site information."
                } else {
                    $scsitepath = $scsite.Applications["/"].VirtualDirectories["/"].PhysicalPath
                    $fp = "$scsitepath\App_Config\ConnectionStrings.config"
                    if ((Test-Path -Path $fp) -ne $true) {
                        echo "Expecting file at $fp but none found - you will need to manually change the thumbprint to the new one."
                    } else {
                        # Replace all instances of the old thumbprint with the new one.
                        (Get-Content $fp) -replace $oldcert.Thumbprint, $newcert.Thumbprint | Set-Content $fp
                        echo "Replaced $($oldcert.Thumbprint) with $($newcert.Thumbprint) in $fp"
                    }
                }
            }
        } else {
            echo "No other Sites found, the primary Sitecore site will need its \App_Config\ConnectionStrings.config file updated with the new XConnect certificate thumbprint manually."
        }
    }

    "I" {
        $fp = "$sitepath\Config\production\Sitecore.IdentityServer.Host.xml"
        if ((Test-Path -Path $fp) -ne $true) {
            echo "Expecting file at $fp but none found - you will need to manually change the thumbprint to the new one."
        } else {
            # Replace all instances of the old thumbprint with the new one.
            (Get-Content $fp) -replace $oldcert.Thumbprint, $newcert.Thumbprint | Set-Content $fp
            echo "Replaced $($oldcert.Thumbprint) with $($newcert.Thumbprint) in $fp"
        }
    }
}

echo ""
# Offer to delete the old certificate.
if ((Read-Host -Prompt "Delete the old certificate? [y/N]") -eq "Y") {
    $oldcert | Remove-Item
}

xConnect Certificate Expiration