Why do we need Minkowski spacetime in special relativity?

Question: I'm learning general relativity recently and something confused me. if we return back to the original formulation of special relativity by Einstein, we need nothing but Lorentz transformation to complete the theory and it seems no motivation to study the geometrical structure of spacetime. no matter what metric tensor we define in a 4D Riemann space, the minkowski line element is invariant under Lorentz transformation. does the geometrization of spacetime in SR lead to some mathematical unnecessaries in the physical theory or not?
Comment: Studying SR with only space is like studying Newtonian mechanics with only the plane.
Answer: In terms of transforming a set of measurements in one inertial frame of reference to another, the Lorentz Transformations are what are needed. But Special Relativity is so much more than those transformation equations. (Similarly, Euclidean geometry is so much more than a rotation matrix. How well can you analyze a triangle with only formulas and a rotation matrix?)
Note: in general relativity, the tangent space at a point-event has the structure of a Minkowski vector space. (Similarly in Riemannian geometry, the tangent space at a point has the structure of a Euclidean vector space.)
So, one important value of the structure of Minkowski spacetime is that it can be used in more general situations than it was initially conceived for.
Answer: Special relativity is a theory of inertial reference frames.  The idea underlying it is that the laws of physics are the same in all inertial reference frames, and we can use the Lorentz transformations to transform observations in one reference frame to observations in another reference frame.  Importantly, at the level of special relativity, we have to ignore the effects of gravity.
Einstein's big idea in developing general relativity was the equivalence principle:  the idea that a freely falling reference frame in a gravitational field should be equivalent to an inertial reference frame in the absence of gravity.  This stems from the idea that "a freely falling observer does not feel their own weight".
The problem is that freely falling reference frames can only be equivalent locally to an inertial reference frame in deep space, since gravitational fields are generally non-uniform.  If I'm falling towards the Equator of the Earth, and another person is falling towards the North Pole, we are in different freely falling reference frames;  if we each try to extend our frames to include the other, we would each conclude that the other person has forces acting on them (causing them to accelerate) while we personally have no forces acting on us.
So if we buy the idea of the equivalence principle, then we have to give up on the idea that an inertial observer (redefined as a freely-falling observer) can construct a global inertial reference frame.  Rather, the best any observer can do is to construct a local inertial reference frame which is equivalent a neighborhood of Minkowski space.  And a space in which there's a neighborhood of every point which is equivalent to $\mathbb{R}^4$ is precisely the idea of a manifold, which leads naturally into the study of metrics, parallel transport, curvature, etc.
Answer: We don't need Minkowski spacetime, but it's a convenient mathematical abstraction. Poincaré's refinement of Lorentz's ether theory is experimentally indistinguishable from Special Relativity even though it does not employ Minkowski spacetime.
Answer: Einstein originally conceived SR in terms of Lorentz transformations. Minkowski later pointed out that the theory could thought of as the geometry of spacetime. Einstein originally wasn't fond of this idea. But later in the development of General Relativity, he realised that the geometry idea was much preferable.
Basically in General Relativity, Lorentz transformations no longer hold a special place. Technically, they don't hold a special place in SR either. Laws of physics can be written in any co-ordinate system: you just have to specify the metric. In SR, there exist nice co-ordinate systems where the metric is the diagonal one. Lorenrz transformations are the way to switch between these nice co-ordinate systems with the diagonal metric. In GR, there is curvature, so we must explicitly specify the metric. Lorentz transformations are no longer special.


What is the difference between Google Identity Toolkit, Google OAuth, Firebase Auth and Google+ sign in

Question: For my understanding, Google Identity Toolkit provides a layer for login with different accounts, like Facebook, Yahoo etc. but how does that differ from the Google OAuth implementation? And regarding Google+ sign in, it is still using OAuth, but only enables login for Google accounts?
Comment: I agree that Google has not described this very well. And I would like a clear answer to. I think that Google Identity Toolkit is build with the single purpose to authenticate users and Google+ Sign In purpose is mostly to integrate the Google+ platform into your app, e.g. posts, likes, friends etc. So if your only need is to authenticate users, then go with Google Identity Toolkit. However I was also a bit confused about the Google+ Sign In since it allows users to create accounts and sign in with just username and password.
Answer: Update as of December 28, 2018:
Google is pushing a new service called Cloud Identity Platform.
Which is basically Firebase Authentication just for all GCP customers.
This service offers, like Firebase Authentication, an abstraction layer to any authentication platform (with easy 2-factor authentication starting at GA)
Google Sign-In and Smart Lock are both only the underlying "low level" technologies used by the Firebase Authentication and Cloud Identity Platform client SDKs.
Update as of June 15, 2016: It seems the guide mentioned in the original answer (below) is not kept up to date - the Google Identity Toolkit seems to be on its way out, apparently absorbed into the Firebase Authentication, which is not even mentioned in that guide.
Maybe a better starting point for checking the current Google authentication solutions might be the "Sign In + Identity" icon on the Products page.
Original answer:
I recently saw this Google Identity Platform guide for choosing between various Google identity solutions which may answer some/all of your questions:
https://developers.google.com/identity/choose-auth
Comment: Identity platform is very expensive, whereas Identity Toolkit was free. Are there any cheaper alternatives now that identity toolkit is gone?
Comment: @Price [Firebase Authentication](https://firebase.google.com/products/auth/) - in which the identity toolkit was absorbed, appears to be free...
Comment: @DanCornilescu Yes, but you have to sign up for the Firebase pay-as-you-go plan and even then some of the [email limits](https://firebase.google.com/docs/auth/limits) for things like email verification / password reset are quite low. The Identity Toolkit page doesn't say it's being deprecated - is sticking with it an option?
Comment: Sorry, just realized that while Id. Toolkit is [not currently planned to be deprecated](https://developers.google.com/identity/toolkit/migrate-firebase), it is not free - it has same pricing as Identity Platform according to the API console.
Comment: @DanCornilescu Can you please answer this? https://stackoverflow.com/questions/57391084/firebase-authentication-vs-google-identity-toolkit-pricing
Comment: @Ayyappa I can't really, I have yet to try out Firebase.


Will hanging a guitar in a cabinet have an effect on the instrument?

Question: Even if it has a door, which will limit the dust on the instrument?
Comment: You might find more info with regards to your question in answers to this similar question on Music Stack Exchange (http://music.stackexchange.com/q/29968/16897)
Answer: The wood of a guitar will swell and shrink in response to changes in humidity and temperature.  Unless the instrument is subject to extremes, very hot or very humid/dry, these changes do not affect the instrument other than putting it out of tune.
A cabinet, especially one that seals well, can help keep the instrument more stable in regards to the temperature and humidity, but unless your house has extreme variation it isn't really necessary.
The cabinet can also help protect the instrument from accidental damage, of things like small children visiting...


Solving system of linear equtions over binary field with error

Question: I have system of linear equations $f_1, \ldots, f_m$ over binary variables $x_1,\ldots,x_n$
where $m$ is much larger than $n$. We know if all equations are correct, we can find solution easily using Gaussian elimination. Among those $m$ equations, 90% equations are correct.
For the remaining 10%, constant terms are altered. So if the actual constant term is 0, it is given 1 etc.  Can we solve the system in polynomial time?  Instead of 90%, if it is 99%, can we solve in polynomial time?
Comment: I would note that solving for $n=256$, $p=0.9$ is tractable (by the simple expedient of selecting 256 random equations; with probability circa $2^{-39}$, all 256 equations are correct, and so Gaussian Elimination gives the right answer (which is easy to verify).
Comment: Thanks. But if n is getting larger say n=1024, we can not solve using this idea.
Comment: Not for $p=0.9$; it'd still be quite tractable with $p=0.99$
Comment: And a schemes based on this.. [Are there any signatures based on matrix](https://crypto.stackexchange.com/q/37562/18298)
Answer: The Learning Parity with Noise (LPN) problem is as follows

Let $\vec s\in\mathbb{F}_2^n$ be a fixed secret, and $\mathcal{O}_{\vec s}$ be an oracle that samples $\vec a_i\gets \mathcal{U}(\mathbb{F}_2^n)$, $e_i \gets \mathsf{Bern}(\tau)$, and returns $(\vec a_i, \langle \vec a_i, \vec s\rangle + e_i)$
The (search) LPN problem is, given query access to the oracle $\mathcal{O}_{\vec s}$, to recover the secret $\vec s$.

If you restrict some query bound of $m$ on how many times you call $\mathcal{O}_{\vec s}$, the problem is precisely the problem you're interested in.
When the noise rate $\tau$ is constant (as a function of $n$), iirc the best-known complexity for solving LPN is the Blum, Kalai, Wasserman (BKW) algorithm, which runs in time, memory, and sample complexity $2^{O(n/\log n)}$.
So we shouldn't (asymptotically) expect poly-time complexity.
Concretely though, for small enough $p$ the situation is tractable. For more reading on this, see LPN Decoded.
I have included an image of the running time of various LPN algorithms below.
Here, $\tau \in [0, 1/2]$ is the "noise rate", and can be written as $\tau = \min(p, 1-p)$ in your notation.

Note that for $p = 0.99$, we have that $\tau = 1 / 100$.
Then theorem 5 of the linked paper solves LPN with time/query complexity
$$\tilde{\Theta}\left(\left(\frac{1}{(1-\tau)^n}\right)^{\frac{1}{1+\log\left(\frac{1}{1-\tau}\right)}}\right).$$
This gives time/query complexity $\approx (100/99)^{\frac{n}{1+\log(100/99)}}$, which while not polynomial time, should be quite reasonable for moderately-sized $n$.
Comment: Yes it is. That will make your problem somewhat harder than the problem this paper solves. It's worth mentioning though that a similar problem (the "LWE problem") has what is called a "randomized self-reduction" --- given a number of (fixed) samples, you can make an *arbitrary* number of samples (although at higher noise rate). I don't know if LPN also has such a self-reduction, but I would expect that it does. In particular, if you "stack" your samples $\vec a_i$ into a matrix $A$, you can write them as $(A, As + e)$. You should then be able to make a new sample via $(xA, x(As + e))$ for ...
Comment: $x$ suitably distributed (probably uniformly random). I haven't formally analyzed this though, and in briefly searching "LPN randomized self-reduction" haven't found anything, so it is possible this sketch of a reduction isn't useful/is invalid for some reason.
Comment: I found a result, see [here](https://cseweb.ucsd.edu/~vlyubash/papers/parityproblem.pdf). Note that this particular result is too weak to "amplify samples" in your situation, but it is possible that follow-up work gets something strong enough.
Comment: What is "Samples" column? Is it m in my problem? In my case m is around 4n.
Comment: Thank you so much. I will look into those papers.


What is jquery stack?

Question:
Possible Duplicate:
How does the jQuery pushStack function work?

In the jQuery API I saw a function pushStack. The description sais: Add a collection of DOM elements onto the jQuery stack.
Does anyone know wat the jQuery stack is and for what can it be used? Does it has a relation with the DOM?
Answer: When you chain multiple jQuery methods together and each method returns a new jQuery object, jQuery keeps track of all the jQuery objects in a stack.  This allows you to return to a previously used jQuery object without having to save it in a local variable.  To make this work, when a jQuery method creates a new jQuery object as a result of a method call, it calls pushStack() to allow the new object to participate in the stack.
The jQuery method .end() is somewhat the reverse of .pushStack() in that it goes one item back in the stack to get the prior jQuery object and it can be called multiple times to continue going back in the stack.  See the .end() doc for more info.
For an example of using .pushStack(), let's say you wanted a method that would get all text nodes in a container, you could do so like this and return the new resulting jQuery object using .pushStack():
jQuery.fn.textNodes = function() {
    var nodes = [];
    this.each(function() {
        var node = this.firstChild;
        while (node) {
            if (node.nodeType == 3) {
                nodes.push(node);
            }
            node = node.nextSibling;
        }
    });
    return this.pushStack(nodes, "textNodes");
};

Comment: Fantastic example and spot-on explanation, thank you very much.
Answer: Most of jQuery's DOM traversal methods operate on a jQuery object instance and produce a new one, matching a different set of DOM elements. When this happens, it is as if the new set of elements is pushed onto a stack that is maintained inside the object. Each successive filtering method pushes a new element set onto the stack. You have different function to operate directly on this stack such as:

pushStack
end
andSelf
Answer: Looking at the jQuery source line 203 of core.js, the stack refers to the current set of elements in the jQuery object instance. Think of it like chaining.. when you filter you are adding to the stack. Calling end() will pop that set and return to the previous set in the stack. .pushStack() allows you to add a new set of elements to this stack.
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems, name, selector ) {

    // Build a new jQuery matched element set
    var ret = jQuery.merge( this.constructor(), elems );

    // Add the old object onto the stack (as a reference)
    ret.prevObject = this;

    ret.context = this.context;

    if ( name === "find" ) {
        ret.selector = this.selector + ( this.selector ? " " : "" ) + selector;
    } else if ( name ) {
        ret.selector = this.selector + "." + name + "(" + selector + ")";
    }

    // Return the newly-formed element set
    return ret;
},

Answer: You can use it with .end()
See:
jQuery pushStack
also:
http://www.bennadel.com/blog/1739-Using-PushStack-In-jQuery-Plugins-To-Create-New-Collections.htm

What is jquery stack?


Can I use the same power supply to double the voltage?

Question: I want to do a corded conversion as seen in this link
.  However, some Makita tools use dual batteries to have a 36V source.  That means the voltage from the 18V power supply will be combined to create a 36V source.  Will this present any problem
Answer: If you're talking about the power supplies like in the link given in the question then you shouldn't combine the two of them to have 36 VDC. Because they will probably not be fully isolated (i.e. they share the safety ground line). Even if they were, it's not practical.
So, instead of picking an extra power supply, you may pick an adjustable/programmable power supply. This will be practical as it can be adequate for both type of devices, but will not be cheap as you might think.
Comment: Those 36V tools use 2x 18V batteries.  Since I am doing a cordless to corded conversion, that means 2x batteries with 18V coming from the same power supply.  I am wondering if there is any danger in this.
Comment: @CaTx: You do realize that using a single power supply means that you'll be connecting the positive supply directly to the negative supply, right?
Comment: @CaTx With cordless-to-corded conversion, you'll always be charging up the battery as well during the the operation of the tool. If you supply 18V to a 36V-tool then the power supply cannot charge the batteries since two 18V batteries are connected in series. I don't see any potential danger in this but keeping the 18V power supply connected to 36V-tool is meaningless.
Comment: @IgnacioVazquez-Abrams, how can I do a corded conversion for the 36V tool?  Use a 36V power supply and have a dual-battery setup?


Is it necessary to have a tripod and remote to take pictures of a starry sky?

Question: Also, does the exposure time change if the camera is shaken and it has to focused again? I did have an ISO of 3200 and shutter speed of 1/125. All I obtained was a dark sky. Its the first time I went looking for dark skies to capture starry skies.
Comment: Hi and welcome to Photo.SE. Do any of the existing questions tagged with [astrophotography](https://photo.stackexchange.com/questions/tagged/astrophotography?tab=Votes) help? For example:
https://photo.stackexchange.com/questions/1061/how-do-i-get-started-in-astrophotography
or
https://photo.stackexchange.com/questions/23972/how-to-nail-focus-for-dslr-astrophotography
Comment: Also related: [What is the "Rule of 600" in astrophotography?](https://photo.stackexchange.com/q/30263/15871) and [How to set exposure for photographing the milky way?](https://photo.stackexchange.com/q/106684/15871) and  [What lens characteristics are important in star photography?](https://photo.stackexchange.com/q/43114/15871) and [What should I look for in a camera for Night Sky Photography?](https://photo.stackexchange.com/q/113114/15871)
Comment: you can use the self timer instead of a remote release, since you don't need to capture something quickly on-demand, like a volleyball spike. Some cameras let you set a timer for 2 seconds instead of 10, for just that very purpose.
Answer: Short answer: Tripod yes, remote no, but it is helpful.
Long answer: You will need a stable platform. A good tripod will work best. A remote is helpful, but not needed. You can also use the self timer. And you can configure some cams to switch the mirror into upward position some time ahead of the shutter to prevent shutter shock. All helping to take jitter-free shots.
As a starting setting, you will NEVER be at 1/125. Usually people start at 15-20 seconds. Be aware that at these times, stars will start to form star trails dues to the motion of earth.
To get ISO down, start at you widest aperture (the smallest number), 20 seconds, and ISO at around 6400. Then have a look what you will see. If too dark, go up with the ISO. If too bright, go down with ISO. If stars begin to trail, lower shutter speed to 15 sec, but you will then have to up the ISO.
Regarding focus: Set to manual focus and focus to the brightest star that you can see and let the focus there. Live View might be helpful there. If you point the cam elsewhere, you do not have to refocus.
There are whole websites giving tips for Astrophotography. This is the bare minimum. Please take some time and search for them to see what adventures await you there. For example there are star trackers that will move your cam according to the stars, so you can use longer exposures than 15-20 seconds. Have fun!


Relationship between the binomial and the geometric distribution

Question: I want to know the relationship between binomial and geometic distribution.
I know  the distribution both have two outcome and probability of success is the same for both distribution.
Answer: Binomial distribution describes the number of successes $k$ achieved in $n$ trials, where probability of success is $p$. Negative binomial distribution describes the number of successes $k$ until observing $r$ failures (so any number of trials greater then $r$ is possible), where probability of success is $p$. Geometric distribution is a special case of negative binomial distribution, where the experiment is stopped at first failure ($r=1$). So while it is not exactly related to binomial distribution, it is related to negative binomial distribution.
If you are looking to learn more about the probability distributions you can check the Statistics 110: Probability lectures by Joe Blitzstein from Harvard University that are freely available online.
Answer: The common definition of the Geometric distribution is the number of trials until the first success (and that's when the experiment stops). See the Wikipedia article https://en.wikipedia.org/wiki/Geometric_distribution . The following is an example for the difference between the Binomial and Geometric distributions: If a family decides to have 5 children, then the number of girls (successes) in the family has a binomial distribution. If the family decides to have children until they have the first girl and then stop, the the number of children in the family has a Geometric distribution (the number can be 1,2,...   and is in theory unbounded). A variation on the Geometric distribution is counting the number of failures until the first success, and then the number can be 0,1,2,.... In the example it would be counting the number of boys in the family before the first girl was born, and not the total number of children. The difference between the two variations is always 1.


What are Steven Weinberg's contribution to physics other than electroweak unification?

Question: What are Steven Weinberg's contributions to physics other than the Nobel-winning work on electroweak unification? Why is he so famous and respected among particle physicists compared to other Nobel laureates?
Comment: Luboš Motl wrote about it on [Weinberg's 75th birthday](https://motls.blogspot.com/2008/05/steven-weinberg-75th-birthday.html).
Answer: According to this page, Steven Weinberg also worked in plasma physics and other fields within particle physics. The same page mentions the following:

Though his Nobel Prize was for work in unification, Weinberg made significant contributions in a wide range of areas in particle physics and even in plasma physics. Among colleagues he was known more for versatility than for mathematical strength.

In an interview, he mentioned that he also wrote a book about cosmology and gravitation. Here is an excerpt of the interview:

It was just amusing to me that at a time when I was deeply involved in the late 1960s in exploring the implications of broken symmetries for elementary particle physics an example like this would crop up in plasma physics, it didn't affect what I did in elementary particle physics. I don't think the JASON work had much effect on my work in elementary particle physics, but it did have a big effect on my work, such as it is, in cosmology and in writing my book about gravitation and cosmology. Because, you know, for example, in an article I wrote in 1977 Ben Lee and I solved the Boltzmann equation in a situation where you have heavy neutrinos colliding and gradually disappearing. And I wouldn't have known what the Boltzmann equation was if it hadn't been for JASON.

I hope this helps.
Answer: You make it sound as though Stephen Weinberg's work on unifying the electromagnetic force with the weak force was a piece of cake and hardly worth winning the Nobel prize along with Abdus Salam and Sheldon Lee Glashow in 1979.
Is that not enough?
Abdus Salam was known for also pioneering supersymmetry and also for establishing the Trieste Centre of Physics to help develop the physics in the developing countries.
Along with James Bjorken, Sheldon Glashow predicted the existemce of a fourth quark, the charmed quark. Also along with Howard Georgi, he came up with first example of a grand unified theory.
Weinberg is known for pioneering renormalisation methods in physics and also the one example of a prediction based on the anthropic principle that worked, the anthropic bound on the cosmological constant.
Comment: I never said his work on EW unification is not worth the Nobel prize. I don't know where did you get that impression from. I too have high regards for Weinberg. I am asking that many people have won Nobel prizes and among them, I think, he is more famous than others. Perhaps he wrote three authoritative volumes of QFT which also earned him some of the respect. All I wanted to know what are other contributions of him to physics. Surely, electroweak unificication is the grandest of his contributions cannot be the only one.


When must a character save against a creature's inhaled poison?

Question: When a creature has the poison special ability, an inhaled poison is listed, and none of their attacks list poison as an effect, when must a creature save vs the poison?
Comment: Which creature is this?
Comment: @Rob from the Bestiary 3, and I don't have it in front of me at the moment.  Starts with an A, looks like a giant puffball fungus.
Answer: Well, it depends on the monster, the answer is probably somewhere in its stat block.
Take the fungal lizardman's inhaled poison - it's listed as an Aura on the fourth line of the statblock.  In this case, the standard inhaled poison rules apply, you have to save the second you enter the area (though you can attempt to hold your breath). As opposed to the Tatzlwyrm's inhaled poison, where it's listed as a special breath-type thing that requires an action, in which case you'd save when it breathes it on you.
EDIT: Based on your further comment you mean the Ascomoid.  That's pretty straight forward, it says straight out how its spore-poof works and you only have to save against the spores' poison if you fail the nausea save from the spores attack.  You'd save immediately and then of course each turn thereafter until you shake it off (2 saves or 6 rounds, whichever comes first).
Comment: I see @C.Ross doubt: beyond being explicitly stated in the Spores special attack, the Ascomoid's stat block refers to a Poison special attack. Being there, the immediate thought is that Poison is an active option for the ascomoid (not only a consequence of another special attack). You must read the entire description to find out that it is not.


HTML Link opening a page that Redirect to a Quicktime .MOV file displays garbage characters in IE when Target is _blank

Question: I have a .NET page that does a Response.Redirect to a Quicktime .mov file. When I create a link to this .NET page, if the link opens in the same window (i.e. no Target defined on the anchor tag), all is good and IE displays the Quicktime movie just fine. However if I set the Target of the link to "_blank" which opens a new window, IE displays garbage characters on the screen (as if you open a binary file). The URL in both cases (with or withotu target) is correct (i.e. http://localhost/movies/myMovie.mov). This is really puzzling...
Using Fiddler I can see that in both cases when the actual movie file is served after redirection, the content-type is video/quicktime which is correct.
Of course everything is good if I link directly to the .MOV files instead if a page that redirect to it but due to a business logic, I can't do that.
Answer: Off the top of my head, before you redirect, make sure you set Response.ContentType to "video/quicktime".


Is describing the scenery important in unfamiliar places?

Question: I'm writing a futuristic light novel, in which the world looks really different than the world we're used to and thus I feel like I have to describe every single detail. However I won't really have space for that since it's a light novel, so i'm wondering if and how impotant the scenery would be in my case.
Answer: It depends on the story. Is the scenery important to the events of the novel? Does it actually have an effect on things? Does it change the outcome? If so, then yes, you need to describe it.
However, usually the scenery is not necessary to the story. In fact, scenery by itself is never necessary to the story. If the scenery is just scenery, there is no need to describe it.
However, scenery (or setting as it is usually referred to) is commonly used to describe the vibe of a particular place (ie, raining during a depressing/sad scene), or to act as a base to show a character's emotions (ie, showing how he sees the setting: "rejoicing in the brilliant sunrise," etc.). Occasionally you can show the same scenery twice, far apart in the novel, and demonstrate how a character has changed by noting how differently he now sees the same scenery.
So to make a long story short: decide if your setting serves a purpose. If it does, then describe it. Don't go overboard though. The description only needs to be enough to accomplish the setting's goal. If your setting does not serve a purpose, there is no need to describe it. You can drop one-liners mentioning the setting on the side (details always add a small measure of credibility to a work), but never focus on it.
Answer: I wouldn't describe in details if it is a light novel and has to be read easily. But I think that if the whole novel is set there then you will have the opportunity to be quite thorough. Just don't do it at once. Start with some basic facts and tell only what is needed and then as the story goes you can tell more. I think action is very important to make the story light so I'd include a lot of action scenes which use the specifics of that place - I mean you could use the different physics there, the different architecture, the different demographics etc. to make the action scenes more intriguing and also introduce the world to the reader. And to repeat Thomas - make sure that every information you give serves a purpose for the story. To sum up - what I am trying to say - make up of alternative ways to show the environment like action scenes and dialogue instead of just describing.


Python - Instance Variable Access

Question: I am currently making a game. I have 2 classes and I want one to access the others instance variables. I'm not sure how to do this or if it is possible.
Both Classes at some point inherits to the class gameEngine
gameEngine <- Game
gameEngine <- SuperSprite <- Character <- Enemy
gameEngine <- SuperSprite <- Character <- Player
My Game class creates an instance variable of an object self.player = Player(self) and I want to be able to use that in my Enemy class so it can do self.player.x. So I can make AI in the enemy class so it's aware of my player. Any suggestions for how to do this, my logic might be wrong so any help would be grateful. If I need to post my code or anything please tell me.
That or I have been trying to pass an object to a function. So bob can get enemyAI in the game class. But I get an error 'Enemy' object is not callable. Yet it passes it and does the function prints out information then dies. BUT if I move  self.enemyAi(self.bob) into the clicked condition it works fine.
if self.enemyWeakBtn.clicked:
    print "spawning enemey"
    self.bob = Enemy(self)

    self.enemies.append(self.bob)
    self.enemyGroup = self.makeSpriteGroup(self.enemies)
    self.addGroup(self.enemyGroup)
    self.enemyActive = True

elif self.enemyActive:
    print self.bob
    self.enemyAi(self.bob)
    print " active"

Answer: If i understand you correctly, You want to have the Enermy instances get access to of the Player instance
There are 2 ways to accomplish it. I'm using the second method atm in my programs and plans to add the first method.
First way involves getting the class to have an instance, and calling a class method allows one to get that instance.
class Game:
    instance = False

    def __init__(self):
        if self.__class__.instance:
            raise RunTimeError("Game has already been initialized.") # RunTimeError might be a bad choice, but you get the point
        self.__class__.instance = self

    @classmethod
    def getInstance(cls):
        return cls.instance

##>>> g = Game()
##>>> g
##<__main__.Game instance at 0x02A429E0>
##>>> del g
##>>> Game.getInstance()
##<__main__.Game instance at 0x02A429E0>
##>>>
## Here you can have, in your enermy class, g = Game.getInstance(). And g.player will be able to access the player instance, and its properties

Second way to do it is what I've been working with. It involves having the Game class regulating EVERYTHING in the game. Meaning: Everything is a variable under game. Also, every single game variable (for example, a player) will have an attribute named game that reference back to the game instance.
Example:
class Player:
    def __init__(self, game):
        self.game = game
        print self.game.enermy

class Game:
    def __init__(self):
        self.enermy = "Pretend I have an enermy object here"
        self.player = Player(self)

##>>> g = Game()
##Pretend I have an enermy object here
##>>> g.player.game.enermy
##'Pretend I have an enermy object here'
##>>>
## Iin your enermy class, self.game.player will be able to access the player instance, and its properties

Some might object with having the second way, I, too, see the problem with an extra step. Maybe someone can shed some light on the comparison between the 2.
A combination method could be which is what I'm hoping to move to, however this raises some issue with which one you need to place first in the file, or else you might get Player not defined or Game not defined. Though I think it can be solved with separating the 2 classes into different files.
class Player:
    def __init__(self):
        self.game = Game.getInstance()

class Game:
    instance = False

    def __init__(self):
        if self.__class__.instance:
            raise RunTimeError("Game has already been initialized.") # RunTimeError might be a bad choice, but you get the point
        self.__class__.instance = self

    @classmethod
    def getInstance(cls):
        return cls.instance

Answer: The error is likely the lack of a constructor for the Enemy class.  By running:
self.bob = Enemy(self)

It looks for the function __init__(self, arg1) in the Enemy class.  If it is not provided, Python will be unable to treat Enemy as a "callable," meaning that it cannot be used like a function, or in this case, used to call a constructor with one argument.

Python - Instance Variable Access


Deploying a directory hierarchy alongside an exe

Question: I am deploying an application using ClickOnce. I can successfully include additional runtime dependencies (as long as they are files) by adding them to my exe assembly project with a Build Action of "Content". These files are placed alongside my exe when the application is installed via ClickOnce.
I need do the same thing for a folder hierarchy. How can I achieve this?
Answer: Have you application check and create it at startup.


What is the relationship between DDD and the "Onion Architecture"?

Question: What is the relationship between Domain-driven design (DDD) and "The Onion Architecture" of Jeffrey Palermo?
Answer: In my opinion - they complement each other - but from very different perspectives.
Onion Architecture is all about making the Domain/BusinessLogic independant on 'inferior' things like data-acccess, UI, services etc. The Onion Architecture doesn't really care how you made the domain you have - it's adamant about protecting it from outside dependencies.
Domain Driven Design is all about how you model your Domain and what you call your objects. Meaning that each Domain class should have a direct relation to what it represents in the business domain it is adressing (ie. the physical/real world). So a Customer object should be named a Customer in code - it should have the same rules as a Customer does in the real world (or as close as it is possible).
Answer: If you look at the image that describes the onion architecture in the link you provided, the Domain Model layer is what DDD focuses on.
Onion is an architectural pattern for a system, whereas DDD is a way to design a subset of the objects in the system. The two can exist without eachother, so neither is a subset of the other. If you were to use them together - then as a whole the part that is designed using DDD would be a subset of the entire system.
To use a (probably bad) analogy: Onion is a pattern to design a house, and DDD is a way to mill the wood that is a part of the house.
Comment: I think his reasoning would look somewhat better if we'd replace all "DDD" to "DM" (Domain Driven Design, the paradigm, which might drive e.g. the whole micro-services architecture - to Domain Model, a tactical toolset of DDD, which is only intended for the business logic of the more complex bounded contexts, or micro-services e.g.).
Answer: I think the two differs each other on the "how you design and what is your overall philosophy" on the system itself.
With the onion architecture all the world is around your Data store. This means that you do not care on how you "do the job" but you care more on "i want the job done". Obviously best practises are (small methods, good variable names, maybe some design patterns like Sigleton etc. etc) are still have a meaning in this scope of view but more for the code itself and not so more for the whole application overview.
On the other hand when we talk about DDD we talk about Business and when we take a decision about the architecture we always have the Business model we want to solve on our minds. And when I say decision I mean the total from decisions a system may have (from Variable/Class/Function names, to where we place a part of code and at the end of the day how we talk about this system itself). We could say that a DDD is a "programming abstraction" of the Business Model). But of course we can not make DDD with out have a business to solve e.x we can not make DDD on a program like Shazam but we can make DDD on a program like Facebook or Spotify.
My option is that you can not mix each other but instead it's the first decision.

What is the relationship between DDD and the “Onion Architecture”?


How to model a real diode 1N4148?

Question: In my university EE lab we were working with a 1N4148 diode to rectify half a sine wave and measure the RMS value of the current in a simple circuit. To the left is the circuit we had to make and to the right it's the modeled circuit for theoretical calculations.
However, from reading the datasheet (http://pdf.datasheetcatalog.com/datasheet/fairchild/1N4148.pdf) I find no reference not only to a model nor any mention of a resistance of 122 Ohm and the value of the DC voltage source of 0.48V. Is the model wrong, or am I just interpreting the datasheet wrong?
Comment: Every model is just as complicated as it needs to be for its specific purpose. Two different models typically mean that the same thing was considered under different questions. For example, you can model a human as a heating unit doing an average of 200W heat output, or you can model it as an 80 kg mass of flesh to be accelerated, or you can model it as tough-surface bag of wet rags – each of these models fits a different purpose (building AC design, car design, scalpel design). None of them is "righter" than the other.
Comment: Unrelated, are you aware that Rd is shorted and Vd is backwards in the second schematic?
Comment: the diode has a logarithmic change in voltage, as the  current is increased; about 0.058 volts per decade of current change. Yu might use 0.66 volt at 10 mA, 0.6 volts at 1 mA, 0.54 volts at 0.1 mA, and a Rseries of 10?? ohms.
Answer: The datasheets usually don't contain models for simple generic diodes. Some manufacturers may give out spice model for simulation purposes, but they are far more advanced than simply a resistor with a voltage source.
The model you happened to create is only a model, and it is specific to the environment it is in now (source voltage and impedance, load resistance, DC bias, AC signal). If that model is given to you or it is calculated from actual measurements then it should be correct.
Comment: Coming from a physics background that makes perfect sense, but my lack of experience in EE would you say that for this case with a sine wave with a peak value of 10V, the model would be a good aproximation to reality?
Comment: @Bidon No. But it might be good enough, I don't know what you're using it for. It's better to use a proper diode model if you can, with the exponential V-I curve.
Comment: In general, only worse models than this are ideal diode and ideal diode with voltage drop, so in general I would not call it a good approximation for a diode. The question is what is an acceptable quality for your case. Perhaps you can take a look at datasheet I-V curves to find out if the measured currents and voltages of the model somehow approximate with datasheet curves.
Answer: The AC resistance is the ΔV/ΔI small signal changes that we call incremental resistance or Ri in Ω. This value is inversely proportion a=to all diode power ratings. e.g worst-case Ri=1/Pd  1Ω/W , best case 0.25/Pd

1 MOhm at 10 uA DC bias
50 Ohms at 1 mA DC bias
5 Ohms at 10mA DC bias
1 Ohm  at 100mA DC bias
0.7 Ohms  800mA DC bias then flattens to 645 mOhms above this

Datasheets don't tell about the slope changes above saturation because the tolerances for VF at max current are too large and that is the load line slope above 100mA used as a switch.
But if you were modulating high current the change in voltage is actually less than the V/I load line slope.  This incremental AC resistance, Ri or Rs or as effective AC series resistance or as I like to call it, ESR, like in cap ESR.
The log V vs log I is a straight line until mobility saturation is complete and the electrode semi bulk resistance then dominates the slope to an almost constant value.
Here is a set of 3 ON SEMI IV curves

Here is my set of 1 curve with Ri shown below the load line for diode impedance vs current.

Based on these parameters

I should mention high power currents must be <1% duty cycle to achieve these voltages otherwise the NTC Vf coefficient shifts the load line to a lower voltage with rising temperature and the PN junction Ri reduces slightly and speed improves.
Comment: any questions?..
Answer: Typically datasheets concern themselves with worst-case values, and when you are doing modeling you at least want to start with nominal parameters. In the case of the Fairchild datasheet, no "typical" numbers are listed, so you're going to be looking at the graphs.
Figure 3 & 4 give you forward voltage vs. forward current, so the slope is dynamic resistance. The voltage at a given current can also be read from the graph, so subtract the voltage due to the bias current through the dynamic resistance at the operating point and you have the voltage source required.
Your voltage source + resistance model is inadequate to accurately describe the behavior with a large change in current however (it's okay as a small signal model linearized about an operating point). You can find a SPICE model for the 1N4148 and simulate the behavior or use the Shockley diode equation directly. The linked model shows a saturation current of 4.35nA and an ideality factor of 1.906.
Comment: Would you say that for this case with a sine wave with a peak value of 10V, the model would be a good aproximation to reality?
Comment: The error will be quite large in terms of diode voltage throughout the waveform but relatively small in terms of output voltage behaviour. Depends on what you are doing with the output voltage and what is varying.
Comment: It is a mere measurement to learn the basic concept of the RMS value, so maybe it would be a good approximation as the output voltage wouldn't be too affected. Thank you
Comment: It's slightly better than assuming an ideal diode with ~600mV drop.

How to model a real diode 1N4148?


Poly1305 variants with bigger output?

Question: This is a rather simple question, but answers are nowhere to be found. Are there any variants of Poly-n hashing algorithms which provide bigger outputs (like 32 instead of 16 bytes)? Or, is there any research which discusses the variability of the constant $2^{130}-5$, why this number is special or whether there are other good alternatives? I understand that it would be better if it was a prime number, but are all primes good (ignoring the cost of modular arithmetic)? Or, could I use the Poly1305 two times with two differenst pairs of $(r,s)$ and concatenate to produce a 32-byte hash?
Comment: You could do something like [Daence](https://eprint.iacr.org/2020/067).
Answer: $\newcommand{FP}{\mathbb F_p}$
The authenticator built on Poly1305 follows a generic construction to build MAC from a universal hash and a pseudo-random function. So, increasing the field size and hence output size (assumedly for security) is possible, in theory at least. Poly1305 precisely refers to the universal hash part of the construction. Which itself is a polynomial evaluation hash that can be generically defined over any field $\FP$. The actual details of Poly1305 are somewhat more complicated. But the point is that this construction yields an excellent Difference-Unpredictable Hash.
The "issue" comes from turning such a hash into a MAC, especially when $p$ is a prime. In the purest version of the MAC scheme, we would simply have a PRF generating values in $\FP$. However, the most practical and efficient PRFs, including AES that is commonly used with Poly1305, produce $n$-bit strings instead. Leaving us with two options for how big $p$ should be: 1) either slightly larger than $2^n$ or 2) slightly smaller. Poly1305 makes the first choice, which offers one big advantage: The message can be broken up and processed in $n$-bit blocks. With the second option, we would need to process inputs as field elements. Which is inconvenient if $p$ is prime. Again, the actual implementation details are likely to be more involved than this.
Finally, increasing the field size would require adjusting the PRF size accordingly. Otherwise, there might not be significant security gains. Which means that we would also need a performant PRF with bigger output space.
Answer: To add to Marc Ilunga's excellent answer, I would point out that that the efficiency of Poly1305 is platform dependent. It covers the very important software space where chip instructions can be relied on to include highly optimised integer/float multiplication and addition operations. I believe that the choices in Poly1305 are highly tuned to the capabilities of current chip sets.
In more constrained environment, it can be better to base the polynomial evaluation hash over a binary field $\mathbb F_{2^w}$. This is done in the GHASH function that is used in Galois Counter Mode and although usually described over $\mathbb F_{2^{128}}$, the 2004 GHASH paper describes GHASH for any even $w$. This also gives an exact match between blocks and field elements and hence provable universality.
There have been a few other polynomial evaluation hashes over prime fields tested for performance in the literature these include $p=2^{127}-1$ and $p=2^{64}-59$.
Answer: This SoK seems to provide variants of Poly1305 with bigger output and also discuss which other primes could be good alternatives.
Regarding concatenating two times Poly1305 with independent
keys, this is also another secure option as proven in section 7.5 of this other paper but according to the benchmarks in the SoK (cf. Appendix D), it is less efficient than simply choosing a bigger and good prime.

Poly1305 variants with bigger output?


What kind of audience can I expect for a scientific talk at University?

Question: I have been invited as a Guest speaker to a scientific workshop at a University. I know there will be faculty members but will there be students present as well? This is my first time as a Guest speaker, so any information of what happens in such events would be helpful.
Comment: Every workshop/seminar/conference is different. It is *always* a good idea to ask the guy that invited you about the expected audience.
Answer: The answer to this question will vary from school to school. Typically speaking, you could expect faculty, staff scientists, post-docs, and graduate students at a generic guest speaker's presentation. As such, you might aim your talk for an audience of educated scientists with familiarity to your field (but not experts of the field).
If you want more certainty, you could ask the organizer who invited you what audience you can expect.
If you are comfortable adapting to your audience on the spot, and you are comfortable being somewhat informal, you could ask for a show-of-hands at the beginning of your talk. E.g.: "Show of hands, how many post-docs are there in the audience? ... Graduate students? ... any undergraduates?"
Answer: This varies tremendously by venue, as it depends on exactly why the talk is being held, is influenced by who is funding the talk and why, etc.
As an example, one set of public talks may be held as part of a series for "public and community outreach". At these talks there will be a mix of a few scattered faculty members, students of various programs, and up to half will be members who live in the surrounding community, including retired people, professionals with only a vague general interest in the topic, business people who might have an interest in the field, etc.
Another set of talks might be purely directly at students. There may be only a few faculty members (1-2 wouldn't be unusual), mostly undergraduate students from the specific hosting program and a few from related/other programs (who may be required to be there, or receiving extra credit for a class), and a few grad students (who are there because they are really interested, and/or may be hoping for some fee snacks). Other talks are held specifically for grad students, and there will be very few undergrads (if any), and yet another set of talks might have mostly faculty, post-docs, staff, and a few scattered grad students.
Administrators (deans, department heads, etc) attend some types of talks, but tend not to be found at others.
However, it is always acceptable to ask your host about the predicted audience, and they usually have a pretty good idea of who can be expected to show up. You should certainly be prepared for this prediction to be less than perfectly accurate, and the general assumption is you'll have a range of intelligent, interested, people attending, though few will be anything resembling experts in your specific area.
If your workshop has limited attendance and sign-ups, you could even send out a survey to try to learn about your audience, but this a luxury that's not usually available if it's just an open talk.
Answer: This is really hard to answer since it depends on so many factors.
In our relatively small math department, the average guest talk had a small handful of faculty, and maybe 6 students or so, and it was usually those of us who spent a lot of time on campus because of the times of the talk (mid-afternoon).
If you want any metrics that could help determine, I'd ask the host:

what time the talk is (the further from noon, the less people you should expect)
if they know of any professors/instructors offering extra credit to students if they go to these talks (in a couple cases, a graph theory talk filled the classroom, another had to be moved to an auditorium).

Also it depends on the general attitude towards your topic in the school. For example, are you a Knot Theorist going to speak at a small liberal arts school? I wouldn't as expect many to come, compared to if you were speaking at a large polytechnic university.
In the end, unless you're worried about having enough handouts, or something like that, don't waste brain space thinking about how many people. You can give a talk to 1 person the same way you can give a talk to 1000.
Comment: Maybe some "fun facts" as well -- little tips and notes about some extra interesting  things you won't cover in your talk
Comment: Thank you so much! You have mentioned about handouts which I find would appeal more to the audience. Since, my presentation will include my scientific background and my research work, I was wondering what can I include in the handouts?
Comment: Probably relevant graphics and equations


Determining the preposition before 'which' to replace 'when/where'

Question: When using when/where in adjective clauses, we're allowed to substitute it with this form:
when = preposition + which
Or
where = preposition + which
First of all, I want to show an example:

Monday is the day when they will come then (on that day).

I'm sure it can be rewritten as follows:

Monday is the day on which they will come then.

That example above is what I took from my book and I'm able to understand because there's a hint in the bracket.
Another example I took from a novel: Harry Potter and The Deathly Hallows

He was still at the narrow fragment in  which, for a split second,
he had thought  he saw Dumbledore's eye.

I want to know where in comes from. At that moment, he's (Harry) holding a broken mirror on his hand, by the way, according to the story. And which conjunction is that? 'Where' or 'when'? My point question is just how to know which preposition we would use, for instance, when we want to subsitute where with preposotion + which.
Answer: You don't say what book you took the first example from, but then is incorrect in both cases.
We speak of seeing a reflection in a mirror, so the mirror is the place where we see it. It has nothing to do with time (when).


How to make Ruby or Python web sites to use multiple cores?

Question: Even though Python and Ruby have one kernel thread per interpreter thread, they have a global interpreter lock (GIL) that is used to protect potentially shared data structures, so this inhibits multi-processor execution. Even though the portions in those languajes that are written in C or C++ can be free-threaded, that's not possible with pure interpreted code unless you use multiple processes. What's the best way to achieve this? Using FastCGI? Creating a cluster or a farm of virtualized servers? Using their Java equivalents, JRuby and Jython?
Answer: I'm not totally sure which problem you want so solve, but if you deploy your python/django application via an apache prefork MPM using mod_python apache will start several worker processes for handling different requests.
If one request needs so much resources, that you want to use multiple cores have a look at pyprocessing. But I don't think that would be wise.
Answer: The 'standard' way to do this with rails is to run a "pack" of Mongrel instances (ie: 4 copies of the rails application) and then use apache or nginx or some other piece of software to sit in front of them and act as a load balancer.
This is probably how it's done with other ruby frameworks such as merb etc, but I haven't used those personally.
The OS will take care of running each mongrel on it's own CPU.
If you install mod_rails aka phusion passenger it will start and stop multiple copies of the rails process for you as well, so it will end up spreading the load across multiple CPUs/cores in a similar way.
Answer: Use an interface that runs each response in a separate interpreter, such as mod_wsgi for Python. This lets multi-threading be used without encountering the GIL.
EDIT: Apparently, mod_wsgi no longer supports multiple interpreters per process because idiots couldn't figure out how to properly implement extension modules. It still supports running requests in separate processes FastCGI-style, though, so that's apparently the current accepted solution.
Answer: In Python and Ruby it is only possible to use multiple cores, is to spawn new (heavyweight) processes.
The Java counterparts inherit the possibilities of the Java platform. You could imply use Java threads. That is for example a reason why sometimes (often) Java Application Server like Glassfish are used for Ruby on Rails applications.
Comment: yes, of course you can reuse a process for more than one request as you can use a threadpool to avoid spawning a thread per request. What I mean is that you have to spawn an own process per core that should be utilized.
Comment: There's no need to spawn new processes, simply re-use them between requests.
Answer: For Python, the PyProcessing project allows you to program with processes much like you would use threads. It is included in the standard library of the recently released 2.6 version as multiprocessing. The module has many features for establishing and controlling access to shared data structures (queues, pipes, etc.) and support for common idioms (i.e. managers and worker pools).


Nginx configuration works in production but not in docker

Question: I've been working towards dockerizing our production environment, which consists of a React frontend which makes API calls to an Nginx server. The Nginx server reverse-proxies all the requests to an ASP .NET Core application. I've managed to get the backend images (.NET and database) working and communicating correctly via docker-compose, but now I'm trying to tie in Nginx and it isn't working correctly. My configuration is as follows:
user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

events { worker_connections 1024; }

http {
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
    ssl_prefer_server_ciphers on;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    gzip on;

    # docker provides 'app' network address for api image
    upstream app_servers {
        server api:8080;
    }

    server {
        listen 80 default_server;
        listen [::]:80 default_server;
        server_name _;
        return 301 https://$host$request_uri;
    }

    server {

        # SSL configuration
        listen 443 ssl default_server;
        listen [::]:443 ssl default_server;

        ssl_certificate /etc/nginx/server.crt;
        ssl_certificate_key /etc/nginx/server.key;

        root /var/www/html;

        # Add index.php to the list if you are using PHP
        index index.html index.htm index.nginx-debian.html;

        server_name localhost;

        location /ver {
            proxy_pass   http://app_servers/api/version;
            proxy_set_header Host $host;
        }
        location / {
            if ($request_method = OPTIONS ) {
                add_header 'Access-Control-Allow-Origin' '*' always;
                add_header Access-Control-Allow-Methods "POST, OPTIONS";
                add_header Access-Control-Allow-Headers "Accept, Cache-Control, x-csrf-token, Authorization, Content-Type";
                add_header Content-Length 0;
                add_header Content-Type text/plain;
                return 200;
            }

            add_header 'Access-Control-Allow-Origin' '*' always;

            proxy_set_header   Host $host;
            proxy_set_header   X-Real-IP $remote_addr;
            proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header   X-Forwarded-Host $server_name;

            proxy_pass         http://app_servers/graphql;
            #
            #proxy_redirect     off;

            # First attempt to serve request as file, then
            # as directory, then fall back to displaying a 404.
            try_files $uri $uri/ =404;
        }
    }
}

The only difference between this configuration and the production server is that in production the proxy_pass is targeting 127.0.0.1 instead of app_servers, and the servername is an actual server name instead of localhost. The hostname api comes from the service definition in docker-compose.
What I'm experiencing is that I can successfully access the /ver endpoint, but any other request which should be routed to api:8080/graphql results in a 404. However, I can easily connect to the docker container exposing 8080 with GraphQL playground and make requests.
Any insight would be greatly appreciated, I'm not 100% confident this is specifically an Nginx issue but all evidence points that way.
Answer: It appears the solution was to remove the following lines:
try_files $uri $uri/ =404;
proxy_set_header   Host $host;


Expansion of space vs movement within space

Question: I understand that some very distant objects (galaxies) are moving away from us at speeds exceeding the speed of light and that such expansion induced speed is not limited by the theory of relativity. However these objects may also be moving within space at speeds limited by relativity. How do we distinguish between these 2 components of speed, following different laws?
Comment: Related, posibly a duplicate: [Expanding universe and the peculiar velocity](http://physics.stackexchange.com/q/96679/)
Comment: Possible duplicate of [Will acceleration rate of expansion of space become faster than speed of light?](http://physics.stackexchange.com/q/30037/)
Comment: See http://physics.stackexchange.com/questions/96679/expanding-universe-and-the-peculiar-velocity
Answer: The issue arises because you measure speeds relative to other objects. We have a convenient measuring stick in the form of the Cosmic Microwave Background (CMB), which we believe is "at rest" with the universe.
When we measure the wavelength of the CMB as seen from Earth, we see a slight blueshift in one direction and a slight redshift in the other, so we know we are going in "that" direction travelling at about 625 km/s.
Now consider some distant galaxy with a massive redshift. Well the CMB around it also has a massive redshift. Subtracting the two gives us the speed of the galaxy itself.
Answer: It might also help to recognize that the concept of "distance" in general relativity is much more subtle than the everyday version because it depends on the coordinate system.  GR gives you the instructions for how to get a distance once you have chosen a coordinate system, which means GR is a "metric" theory.  We are not used to this, we think you can use 2D latitude and longitude coordinates, or Cartesian coordinates in 3D, and still get that the distance between New York and London is a particular thing.  But on scales of the whole universe, you can get very different distances depending on your means of coordinatizing the events.  Because of the cosmological principle, however, there is one coordinate system that stands out, called "comoving frame coordinates" that move with the average of the local matter, because in those coordinates the universe seems to be the same everywhere at a given age.  It is that choice of coordinates that parses between "what space is doing" and "what matter is doing within the space."  Whether this is just a convenient language, or represents something deeper, requires the discovery of new laws to determine, but right now the cosmological principle is a kind of organizational principle of convenience.
Note however that the speed limit of special relativity is not subject to these problems, because that speed limit only applies to two objects passing each other at essentially the same place and time.   The global coordinates don't matter in such a local interaction, just like you don't need latitude and longitude coordinates to tell how fast you are passing someone on the highway.
Answer: In practice you cannot distinguish between 'peculiar velocity' and 'Hubble flow' per se.  There are numerous ways of accounting for both however.  The main factor to consider is that galaxy obey gravitational dynamics in exactly the same was as any other objects (like stars in galaxies, or planets in star systems).  In particular, their (peculiar) velocity depends on the local environment.  If you observe a cluster of galaxies that are associated with each-other, you can see variations in the velocities of the individual galaxies (peculiar velocity) and also an average velocity of the cluster as a whole (Hubble flow, velocity).  Galaxies in the field (i.e. not in clusters) tend to have much lower peculiar velocities.
Similarly, if you look at lots of galaxies---even ones completely unassociated with each-other---their peculiar velocities will tend to average out, because they're in random directions.
Answer: When you factor out the expansion of space you're left with the peculiar velocity of an object.


What is the difference between a cloud server a virtual server and a dedicated server?

Question: What exactly is the difference between a VPS (Virtual Private Server), a Cloud Server, and a Dedicated Server?  I'm having trouble finding a concise explanation that isn't littered with advertising.
Comment: +1 - I'm honestly surprised we haven't seen this question on here until now. I remember being similarly confounded by it when the term Cloud was first bandied about 2 years ago
Comment: The difference is mostly the region your marketing person is from.
Comment: @smartcaveman - do you mind mentioning what's incomplete about the currently provided answers that you've placed a bounty?
Comment: @Mark - this question from a couple weeks ago is quite similar (though omitting the dedicated server part): http://serverfault.com/questions/272987/whats-the-big-deal-with-cloud-vps/272991
Comment: @Mark, I've been on a hosting solution for the past 3 years.  I finally got fed up with them - and yea, the 'cloud' thing has been confusing
Comment: @smartcaveman - the good news about hosting solutions is that there are as many of those as there are definitions of "cloud"
Comment: @Jim B, any recommendation for Windows Server 2008?
Comment: It really depends on what features you need.  For windows, you want to look for a hoster that advertises SPLA compliance.  One of the oldest and most reputable that I am aware of is orcsweb.
Answer: VPS and Cloud are the same damn thing.
A dedicated server is a physical box sitting in a rack somewhere that is not shared with anyone else, that you can do whatever you want with.
Comment: Sometimes I wish we could implement a feature that denies any question with the word "cloud" in it, instructing the user to please use more explicit (and definable) terms.
Comment: @ErikA, my question is asking for a definition of the term...  So, that would be a little circular in this case.
Comment: @ErikA, Are you suggesting that "poking around the web" is the best way to find the definition of a word that is "devoid of meaning"?
Comment: @ErikA - I'm kinda assuming that the op has already done that, which is why they asked..?
Comment: @smartcaveman - while I understand your statement, it doesn't take too much poking around the web to realize that the word "cloud" has become so ubiquitous that it's nearly devoid of meaning.
Comment: @Mark - I always *hope* OPs have done their research before asking questions but well......
Comment: @John - I would classify that as a cloud *service* then, such as iCloud (I feel dirty even saying it) or Picasa Web
Comment: @Sirex - the two are not mutually exclusive. A VPS can certainly have load balancing and live migration (we offer our clients a service that we market as a VPS that has shared storage, high availability and live migration). As far as calling a product by a new name because of the way it's billed, that's just (good) marketing. Technically they're still the same.
Comment: @smartcaveman - no, I'm suggesting that, in poking around the web, it's not hard to come to the realization that the word is used in so many different contexts and is given so many definitions that for all intents and purposes, it has become undefinable.
Comment: Gotta disagree with you here Mark. A VPS may well be part of a cloud server but a cloud server isn't necessarily a VPS - it is more likely to be a collection of VPSs.
Comment: i always understood "cloud" to infer that there was some kind of load balancing or live migration ability (e.g multiple interconnected virtualiation hosts), and VPS to refer to a single instance of a VM host, which may or indeed may not be in a group/cloud setup. Also, a cloud bills per usage of resources, and a static VPS bills a flat rate even when idle. i.e: they are *not* the same thing. Is this not correct ?
Answer: A dedicated server is a full server to which you have exclusive, guaranteed access.
A VPS provides you with similar levels of administrative control as a dedicated server, but is powered by one of a number of technologies, either full virtualization (Xen, VMWare) or single-image segmentation (OpenVZ) to give you the illusion of exclusive access to what is really a shared resource (and almost always oversubscribed in many ways)
Traditionally, dedicated servers and VPSes are billed on a fixed cost for a time span. Dedicated servers in particular require investment on the part of the provider, and may be leased on a contract with a minimum duration.
A Cloud server is technically just a VPS, but it has some differences in billing and provisioning:

Cloud services are usually billed on a metered consumption basis. While a VPS may have a variable cost for data transfer over some threshold, an idle VPS would have a flat cost. A Cloud server would typically have a base cost per hour running -- and may also have charges for data transfer just like a VPS.
Cloud servers employ more automated ordering and deployment, including the ability to provision additional servers nearly identical your current ones quickly, possibly programatically using an API. This lets your application add capacity to itself -- this is not magic, and may require significant architectural changes to your environment.

Other services may be marketed as 'cloud': what was 'hosted email' before is now Cloud Email (Service-as-a-Service); some shared webhosting providers are relabeling their services similarly.
Good use cases for cloud servers are short-duration peak loads: services with hourly billing allow you more flexibility to create and destroy systems as needed. Constant load setups, which will always be running, may not be economical to run in a Cloud environment; applications that have constant sustained high load are unfriendly to a provider's over-subscription model, and may be better suited for a dedicated server.
Comment: I give you points for good explanation. However I disagree that constant high load will not benefit from cloud. The true cloud will allow additional resources to be provisioned immediately and and maybe automatically to serve the extra loads. That is not possible on dedicated servers or VPS where we can hit a hard limit. Also VPS cannot scale easily to multiple VPS and requires a lot of manual intervention, self setup etc which is not so on the cloud. In case of VPS or dedicated server you own the failure if not the hardware. On the cloud you can just move along without opening a ticket :)
Answer: A VPS is usually refering to a virtual machine that only your apps run on. A dedicated server is usually physical server dedicated to you.  a Cloud server is a way for the marketing idiots to get the world cloud out there as a VPS.  All of these are forms of IAAS - infrastructure as a service.  In doing a tiny bit a research and found one provider marketing PAAS as a cloud server (gogrid) PAAS is platform as a service.  Typical PAAS offerings are Microsoft Azure, Amazon beanstalk, and google appengine.
Comment: Haha, our company offers a SAAS running on a PAAS that's hosted by an IAAS. Do we win for the AAS acronym?
Comment: you can certainly have in house IAAS, as well as PAAS, and SAAS in house.  All of these models are management models.  IT as a service has been a standard business model since the 90's AFAIK
Comment: PAAS ans IAAS should be mutually exclusive- How did you manage that?
Comment: @JimB - the software we developed our SAAS in is called [uniPaaS](http://www.magicsoftware.com/en/products/?catID=70), because its runtime environment is marketed as PAAS.
Comment: @Mark You win a slighly used Marvel no-prize- it is in the mail. While certianly they market it as PAAS- it seems about as PAAS as Java or .net. Damn maketing weasels for absconding clearly defined terms
Comment: @joeqwerty, If you are offering software then that's SAAS.  PAAS means that you do not need to manage the things that make your application work (eg Azure or appengine). Defining sql ts and exchange as PAAS wouldn't fit (TS is, at best part of IAAS).  You could be providing IAAS - but that is NOT DNS and AD but providing other IT groups with server infrastructure for them to run those services.  I was going to ask a question defining these but then I found a million hits for it.  Take a look at http://www.silverlighthack.com/post/2011/02/27/IaaS-PaaS-and-SaaS-Terms-Explained-and-Defined.aspx
Comment: @Jim B: Yeah, after thinking about it I deleted my comment. In my simplified world view we're providing software, a platform, and the supporting infrastructure, but not in the strict sense that would apply to PAAS and IAAS. SAAS for sure though. Thanks for the link, that's the clearest explanation I've seen.
Comment: Yep, 'marketing idiot' gets a +1 from me too.
Answer: No Cloud and VPS are not exactly same thing, anyone who wants to downvote, please read below first...

VPS is just virtual server where we can adjust hardware resources that actually cost money
VPS is just a virtual replacement of dedicated server, but you are left to mange it by yourself, it only provides backup of Virtual Hard disk, but how you manage/store your hard disk is totally up to you.
VPS does not offer replication, and multi machine storage services

On other hand,

Cloud consists of Storage Service, Resource Service, Database Service that is all managed by Cloud Framework which includes automatic backup and provides API to manage infrastructure of hosting
Consider Amazon, Google and Azure for a minute, they dont offer VPS, they offer an API which will help you in building large scalable applications.
API consists of Storage Service, its not a Hard Disk, but its a virtual store, where you store your data as files, but you dont worry about how it is stored, fragmentation or where it is stored physically. Cloud gives you access to huge list of servers which is hidden behind the API to manage scalability. Both Amazon, Azure and Rackspace manage 3 copies of same files on multiple datacenters, of whatever you put in the store, so you do not need to worry about data because if one machine loose it, Cloud Provider will make it available through other machine.
API consists of CDN (Content Delivery Network) for high speed transfer based on location of IP, Cloud Provider automatically caches your files to different servers and give you a transparent URL which is switched to nearest server automatically.
API consists of Application Server, offering you easy to deploy and manage your application. Your application becomes independent of physical/network location and you can easily migrate and multiply physical resources needed without having to do any installation etc.
API consists of Replicated Database, Azure offers SQL Azure, which is automatically replicated to 3 different machines within their datacenter, so there is no way you will loose anything in your SQL database.
Comment: I just signed up with Rackspace Cloud - and I definitely see where you are coming from.  It seems like what you are saying is that the Cloud is a type of interfaces for a VPS may often be a critical aspect of its implementation.  However, are you certain that all your statements about a "Cloud" are universal to all Cloud implementations, or are they limited to the specific examples you provided.  Furthermore, are there any universal specifications for such cloud implementations?
Comment: No there is no universal specifications, but it will become more clear as we go forward. http://en.wikipedia.org/wiki/Cloud_computing
Answer: For the purposes of this discussion, a VPS and "Cloud Server" are the exact same thing - you don't get exclusive access to hardware but rather, the host hardware gets shared between two or more virtual servers.
A dedicated server is just that - your OS instance gets 100% exclusive access to the underlying hardware.
Comment: I hate the term "Cloud". Hate it hate it hate it. Especially how far Microsoft and Apple push the term. "Cloud" now has so many meanings it's just all grey and fuzzy and ultimately meaningless.
Comment: Agreed 100%. Hated it when it first came on the scene and my hatred has only grown since then.
Comment: In my opinion, cloud computing is not much more than an updated extension to time-share based computing back when mainframes were the defacto system... implemented by large entities and rented out in time slices to smaller entities. I know I'm over simplifying but that's the way I see it.
Comment: See also: http://serverfault.com/questions/272987/whats-the-big-deal-with-cloud-vps/272991#272991
Comment: thank the marketing monkeys for making anything off premise or virtual a cloud solution
Comment: Some clouds are 'grey and fuzzy' ;-)
Answer: VPS is generally a marketing term used by Internet hosting service providers. A VPS is a virtual machine that is exclusively used by an individual customer while a dynamic VPS (that is, it can be changed at runtime) is often referred as a cloud server.
Dedicated servers are most often housed in data centers and are entirely leased by the client. Client have full control over dedicated servers including choice of operating system, hardware etc.
Answer: I would summarize it like this:

Dedicated server is physical server that is 100% "yours".
VPS is a virtual server running on top of some hypervisor, usually several VPS share a single physical server;
Cloud is a framework for managing virtual servers (I would qualify VPS as one type of virtual servers). It provides provisioning of new servers, allocation of CPU resources, allocation of storage, and much more depending on who provides the service. It is usually combined with flexible automatic billing when you only pay for resources that you use. The term is evolving but this is what I make of it to date.
"Cloud" is also a new hype word that used by "marketing monkeys" to (a) full investors in an attempt to blow up value of the company, (b) cater to large businesses where buying decisions made by top level executives who has no clue what they are doing but read in Wall Street Journal that cloud is cool and everyone does it, (c) used by everyone else to full customers into buying their product.

BTW, the last hype word as far as I remember was "Organic", and there were plenty of idiots who used it indiscriminately for same foolish reasons. You may remember organic computers, organic monitors, organic water, organic gasoline... I wonder if it was FDA approved :-)
Answer: From my understanding, the difference is simple:
A dedicated server is a box sitting in a rackspace in a data center. So if it fails then your website or web application running in it fails, unless you have some kind of backup or distributed server handling facility available which is tedious and expensive to maintain.
On the other hand a Cloud is like a VPS (Virtual server) which is spread across multiple data centers spread across multiple physical locations like states, countries or even continents, so if one data center fails then it will be instantly switched to another data center, this also happens if the resources required to handle a sudden increase in traffic or the available storage in one data center are running out. All these tasks are handled automatically by the cloud, so you dont have to dedicate any resources for maintaining the infrastructure yourself which results in significant cost savings. So the end user can smoothly access your website or web application any time any day under any load if it is hosted in a cloud.
So to summarize a cloud offers virtualisation of OS, dynamic resource allocation, redundant backups, zero tolerance fail over switching to make a web application / Web site run continuously without fail under any circumstances.
Brilliant Idea isn't it. That's why it has been touted as the next big thing in the web application development world and also next computing gold rush.


How to configure how much RAM usage should to start swapping on Ubuntu

Question: I always notice that Ubuntu start using swap, as soon as the RAM usage is around 60-70%.
How to configure it so it should wait so RAM usage became 80-90%.
And is there a way to empty the swap, as soon as the there is space available on the RAM, other than swapoff manually?
Answer: The answer to your question how, is "no". Linux is extremely good at memory management. You could never hope to compete with it. And you wouldn't want to unswap just because you had free RAM. Because Linux knows what parts of the memory is most useful. In other words; you'd reduce performance drastically by manually moving unused memory from the harddisk and into RAM.
Comment: While I agree in principle, the absoluteness of `you could never compete with it` moves the kernel developers into a god-like position, which doesn't sound reasonable. :)
Comment: I was not talking about kernel developers. I was talking about the kernel. A human brain would never be able to analyze that kind of data as quickly as a computer can. Just remember that one byte is 256 combinations. Four bytes is 4.3 billion. Imagine a gigabyte.
Comment: You could rewrite the critical code in the kernel. It's open source.
Comment: Sure you could, but now we've come full circle; the point is that the kernel is already very good at this.
Comment: That's why I said I agree in principle.
Answer: See the section titled "What is swappiness and how do I change it?" on this page:
https://help.ubuntu.com/community/SwapFaq
But, I also agree with Jo-Erlend Schinstad. If there is no urgent need to change the default behavior, it is best to leave it alone. However, I see that the article itself recommends a value of 10, while the default is 60. So, changing to the recommended value of 10 should take you the way you want to go (less swapping).
Also, part of your original question is, how to empty swap. swap is emptied every time you reboot.
Comment: I can empty swap manually by using the "swapoff -a" command.
No need to reboot in this case.
Comment: `$ cat /proc/sys/vm/swappiness`
`$ 60`
`$ sudo sysctl vm.swappiness=10`
`$ sudo /etc/sysctl.conf`

**There is no trace for vm.swappiness in this file.**


Separate interface from implementation

Question: What is the meaning of separating interface from implementation in C++? And also what is implied by interface and implementation?
Comment: Look at [Ways to organize interface and implementation in C++](https://softwareengineering.stackexchange.com/questions/48857/ways-to-organize-interface-and-implementation-in-c?rq=1)
Comment: The interface specifies what the behavior should be, in C terminology that is the function/method's prototype. The implementation specifies how, that is the function/method's code body.
Answer: It means that you should use objects through interface classes (pure virtual) instead of concrete classes. This will allow you to change the concrete class while keeping the rest of the code intact (useful for refactoring, testing, etc)
For example if you have an interface
class INotify
{
public:
  virtual void Notify() = 0;
};

Then when your notifier uses it:
class Notifier
{
  // ...
  void Subscribe(INotify* subscriber)
  {
    m_subscribers.push_back(subscriber);
  }

  void NotifyAll()
  {
    for(auto it = m_subscribers.begin(); it != m_subscribers.end(); ++it)
    {
      (*it)->Notify();
    }
  }
  // ...
}

Notice how the Notifier is not coupled to any specific class implementation? Any class that implements INotify will work. This will allow you to use more than one class as your subscribers, it will allow you to refactor your subscribers without having to touch the Notifier and it will allow you to test the Notifier by mocking subscribers.
And for your second question, the interface is the public contract of a class (the operations that you can do with it) and implementation is the actual realization of that contract (e.g. a subscriber class inherits INotify and implements the contract by providing definition for Notify method).
In the example above, I showed only the interface of INotify but I didn't show any classes that implement that interface (inherit INotify and define an implementation for the pure virtual methods). I did this on purpose as I wanted to stress how the implementation is not relevant for the notifier, but only the interface (contract) is.
Comment: Nice answer.  However, I believe it is not complete.
Comment: @Christophe I agree. But imo, it only has the relevant part :p ... I don't consider c++'s header/cpp split as interface/implementation as the header at a minimum contains much more than just the "interface" (e.g. private and protected members). Even in the quote from Stroustrup, it says "*like* an interface"
Answer: The term "interface" is ambiguous in the C++ language, in the sense that it is not formally defined.
General definition
An interface is the specification of how a function, a class or an object interacts with the rest of the code.  This meaning is for example used in the C++ standard:

184.108.40.206/3: Interface convention requirements are stated as generally as possible. Instead of stating "class X has to define a
member function operator++()," the interface requires "for any object
x of class X, ++x is defined." That is, whether the operator is a
member is unspecified.

It is also used consistently by Bjarne Stroustrup in The design and evolution of C++, Addison-Wessley, 1994, for example when he explains core principles for the language design decisions he made for classes:

(5) function definitions are typically specified elesewhere
to make a class more like an interface specification than a lexical
mechanism for organizing source code.

In other words, this allows you to have a class declared in a header (interface that can be used across all the compilation units), and the implementation of its members defined in a compilation unit, which inernl's don't have to be known by the external world to use the interface.
Specific programming technique
The term "interface" gained popularity with Java, where it is a language feature used to complement the single inheritance. In C++ you can do the same by using an inheritance from abstract so-called interface class, as suggested in the C++standard:

10.4/1: An abstract class can also be used to define an interface for which derived classes provide a variety of
implementations.

For this just look at the very good example of Rado's answer
Comment: @Laiv yes. However, I used this formulation so to avoid  reanimating the usually heated discussion about whether or not MI is a good thing (I love it but don't want to offend anybody) ;-)

Separate interface from implementation


Scaling up a theoretical super Solar system arrangement into a Star system

Question: Recently an article came out about the maximum number of planets in an artificial Solar System. See below the image for the full article link . It suggests that if each planet is placed at a distance outside of each others sphere of influence then a large number of planets can be placed in the same orbit, then to cram as many planets as possible at different orbital distances, every other orbit is made to orbit in the opposite direction (in retrograde) so that passing planets gravitationally interact as little as possible.

https://www.livescience.com/maximum-number-of-planets-orbit-sun
Although this is theoretical and would need to be engineered is it possible to scale up the system to a system of stars orbiting a Supermassive Blackhole?
If the stars are placed at distances from each other further than their sphere of influence, could a sufficiently massive blackhole be at the centre of the system, if the stars are out at a distance to avoid eccentric orbits? Would the black hole have enough gravitational influence to keep stars in place at further out orbits and would the stars remain stable like the planets would theoretically be in the article?
Answer: What the article describes is essentially a series of concentric Klemperer rosettes. Such arrangements are known to be gravitationally unstable.


When switching off the engine, do the cam and crank shafts always come to rest in an initial state?

Question: Is it the case, when the engine comes to a halt, that the cylinder/piston/valve phases always finish up in the same starting or initial position relative to each other?
Comment: Are you asking if the engine always stops at the same place? (IE: cylinder 1 piston always stops at top dead center)
Comment: Yes, that's another way of asking the question.
Answer: No. An engine stops where it stops because it is random when you turn the ignition off, and therefore there is no set place for it to end up at.
Comment: They are all connected mechanically, so of course they stay in-sync, in-phase, or whatever you want to call it.  Unless something like a timing belt/chain/gear breaks, but that's pathological.
Comment: in fact the reason it is called a timing belt is that it keeps the timing in sync.
Comment: Right, okay. And presumably the phases remain sync'ed, across starting and stopping the engine. Is that right?
Comment: What do you mean by "phases"?
Comment: Ok, Mike65535 answered the question.


Do I need a Android phone for creating android applications?

Question: I started developing android applications. And am testing with the android emulator. Do I really need android phone before releasing it for public usage?
Answer: Short answer No. You can test and build a android application package with the SDK and an emulator. But I would say there are usually many things which it would be wise to test on a device.
Personally I have noticed that the emulator does not give a good indication of response times for UI controls. It is usually necessary to move functionality which has long processing times into background threads to maintain user interactivity without the 'force close' pop-up. Testing the effectiveness of your UI responsiveness must be done on a phone to be meaningful.
Network connectivity is another aspect which can be vastly different on a phone, 3G or wifi.
Device sizes and Android platform versions can be tested effectively on the emulator.
Some phone allow hot-swapping of the SD card (replacing the SDcard without turning off the phone). I am not sure how to replicate this on the emulator.
There may be many more things which may only become apparent when using your application on a real device. I would strongly suggest to always test under real conditions when feasible for any commercial project.
Comment: Yes, agree. Especially when you work with videos, it's much better to see it on a real device. Video playback on emulator isn't very stable.
Comment: Thanks to you all. I am going to get HTC Legend and test it, so that I can hope that my apps can be used by others :)
Answer: From a technical perspective there's no reason why you can't develop purely on the emulator.  You're not going to be able to test on every available device, so there's always going to be possibility of device specific bugs that you've missed.
However, I'd strongly recommend getting an actual phone to test your application on.
For me the biggest difference between an actual device and the emulator is the difference between using the interface with your fingers and using a mouse.  Interactions which make sense in the emulator sometimes don't work as well when you start using touch on the screen.  So if you develop purely on an emulator you'll won't lots of little improvements to your UI that would obvious when you used your app on a phone.
Answer: You can't feel a real app in your hands until you have a real phone. (I'm telling you as an Android developer)
So, developing w/o real phone is possible, but real phone gives you a lot more experience, fun & usefulness.
Answer: It depends on what type of application you're developing, for serious ones you need at least one device to test it on. For complex applications you would need a range of devices, for example with or without hardware keyboard, different navigational button etc. For basic, simple applications you'll probably do fine with just the emulator.
Answer: I would imagine with games you would definitely need to test on real devices.
Answer: Thanks to you all. I am going to get HTC Legend and test it, so that I can hope that my apps can be used by others :)
You guys suggest me HTC Desire or HTC Legend?


How can I change the RequestedTheme of an element from a control in a settings flyout?

Question: I'm trying to set an option in a settings flyout in my WinRT app for the user to change the theme of the app.
In the App.xaml file, I've set up different ResourceDictionaries for the light and dark themes. I can set the desired theme of my application from it's settings file with the following code (RootPage is the name of the grid the contains all of the elements):
if ((string)Windows.Storage.ApplicationData.Current.LocalSettings.Values["Theme"] == "0")
{
    RootPage.RequestedTheme = Windows.UI.Xaml.ElementTheme.Light;
}
if ((string)Windows.Storage.ApplicationData.Current.LocalSettings.Values["Theme"] == "1")
{
    RootPage.RequestedTheme = Windows.UI.Xaml.ElementTheme.Dark;
}

However, I would like to be able to change the theme dynamically. Basically, I want the theme to change immediately when the user selects the desired theme from the settings flyout, rather than having to wait for the application to be restarted.
I've tried using the following command:
App.Current.RequestedTheme = Windows.UI.Xaml.ApplicationTheme.Light;

But this crashes the app with a System.NotSupportedException.
I've also tried setting the theme only to the RootPage element with the following:
var MainPage = Windows.UI.Xaml.Window.Current.Content as MainPage;
MainPage.RootPage.RequestedTheme = Windows.UI.Xaml.ElementTheme.Light;

But I've done this wrong because it raises a System.NullReferenceException.
Could anyone help me work out how can I change the RequestedTheme of an element from a control in a settings flyout?
Answer: Windows 8 theme resources are provided using StaticResource and so can't be updated at runtime.
To somehow do what you want I'd recommend you to read this blog post.
Answer: Try setting the app requested theme within the App constructor in the App.xaml.cs.
Like this
public App()
{
     Current.RequestedTheme = ApplicationTheme.Light;
     this.InitializeComponent();
     ...
     ...
 }


Using PostGIS with Rails

Question: I'm new to postGIS, and am looking to use a spatial database with my Rails app (specifically, to retrieve points from the database that are within the bounding box of a Google Maps viewport). I posted a question on Stack Overflow with a few more details ( https://stackoverflow.com/questions/3555840/constucting-a-postgis-query-with-rails ), before coming across this site. I was following the tutorial at http://railsonpostgresql.com/2009/11/05/intro-to-postgis, but my implementation doesn't really seem to work - when zoomed in, the points don't appear as expected (but some appear when zoomed further out, although not those near the international date line). I'm using the spatial_adapter and GeoRuby gems at the moment - are there any good tutorials out there on how to begin integrating postGIS with Rails? From what I've read, it seems like using the geography type would be a good start for my project, but unfortunately I don't believe GeoRuby supports it. Any help/suggestions would be greatly appreciated!
Comment: I don't know whether you have seen it, but there is a really in depth 9 part series of blog posts by Daniel Azuma, author of the RGeo gem starting at http://www.daniel-azuma.com/blog/archives/60
Answer: The answer on Stackoverflow echos my thoughts: first, determine if the issue is in the google maps implementation or with the database results. I'd try installing QGIS, and point it at your PostGIS database -- if all the data shows up there fine, and zooming works as expected, the data is correct in the database.
From your example query, here's a quick map of the bounding box:

That is consistent with the parameters you're sending, so try another one that fails, check the logs and try the query directly against the database to see if its sending the results you want. Step backward from there till you've isolated the component that's failed. Hope that helps!
Comment: Thanks for your help - once I got my database on QGIS I spotted the problem immediately - I had the x/y and lng/lat correlation mixed up. Massive n00b error - it works perfectly now!!

Using PostGIS with Rails