Sprite can jump up through platform onto platform, once while it's on platform, but falls through second time

Question: Sorry, I'm kind of new to this whole thing and trying to learn both Unity and its use of C#. I have overlapping box colliders set up and a trigger on the lower one to allow me to jump through the lower platform. That works fine, and once on the platform, I can jump through it and land on the top, and I can make a singular jump while I am on the platform, but as soon as I jump a second time, I fall right through. Does anyone have any suggestions as to how to go about fixing this? I originally thought it was that the overlap on the two colliders was too much, or that the radius of my ground points were too large, but fixing both of those didn't do me any good. Thanks for the help!
Comment: you are developing for 2D or 3D?
Comment: Experimented with the collision detection of the player (Switched from discrete to continuous), and found that to fix the problem too!
Comment: This is the first step friend :)
Answer: If you are developing in 2D environment then try to implement Platform Effector. In you Platform Sprite, attach a BoxCollider2D and mark check on Used By Effector and attach Platform Effector 2D like this, you are all done.
Comment: Thanks! That seems like it's helping a lot, but I'm still sort of falling through the platform occasionally. I have two box-colliders set up like this; I assumed that the effector would be used with the collision box instead of the trigger box (Though I did try with the trigger box and it made the platform intangible to the sprite). So far this is my setup: (Sorry, gotta figure out how to incorporate this! One sec)
Comment: Yea, it must not be Trigger
Comment: If I uncheck trigger it doesn't let me walk in front of (through) the platform. Is  there a way to fix that? Or do I have to pick which one I'd rather have?
Comment: Your one collider is normal `Trigger`, change, uncheck `Trigger` and mark check on`User By Effector`
Comment: (Here's my setup, I don't know if that'll be helpful at all; the bigger lower box is the one I have triggered to allow me to walk through it, the upper one is the one that causes collision) http://imgur.com/a/fpr4I
Comment: Still can't seem to walk through the platform but I'd much rather be able to jump on the platform without falling through! Thanks!
Comment: @RainbowElephant why you have two colliders instead of two sprites? If you don't have flat platform then I'd suggest to have different sprites as different platforms
Comment: I was following the youtube tutorials by inScope Studios and they suggested using the two colliders with a triggers script where touching the lower collider box would turn off the collision for the top box. I'll keep that in mind for next time, though. Thanks!


Is there a way to make dynamic paint affect the reaction diffusion from tissue?

Question: I've been experimenting with the tissues reaction-diffusion, but I can't find a way to render the animation so I'm trying to control it with the dynamic paint, using some spheres to paint, but the reaction-diffusion doesn't seem to recognize it. Is there a way to make this work or is it not the best way to render an animation with reaction-diffusion?
Comment: What is it you would like to do with dynamic paint? Or are you simply trying to find some way to visualize what reaction diffusion is doing?
Comment: Yes, I just dont find a way to control the reaction diffusion, so a thought i could do it with a brush so that I can repeat the animation for a render
Comment: If only visualizing is the main goal, I can think of a couple ways. Thing is that reaction diffusion (as far as I understand) is *creating* vertex group data, so we can only use this information in dynamic paint or other modifiers to visualize what the data being generated is doing.
Comment: It seems that the animation option is not working with new versions of blender
Answer: Here is a way to visualize reaction diffusion, it takes a few steps but it seems to work I guess. Unfortunately, it does not seem that dynamic paint will directly work to control reaction diffusion, but we can use other ways to visualize it.
Starting with a densely subdivided quad-sphere, I have set up reaction diffusion and painted some random pattern on vertex group B with animation running. One thing I am also doing here is adding a few keyframes in the scale parameter throughout the timeline to add a bit of variation in the animation.
Here are my settings:

Bake the reaction diffusion before moving on.

In object mode, make a copy of the object, and do not move it.
Shift + D then Enter.
The copy and original must be in the same place for the next step to work properly.

In Weight Paint again, first select the original object, then select the copy and go to Weights>transfer weights to copy the weights from the original to copy. This will copy the reaction diffusion from the original mesh to the copy, also allowing the animated weights to be used in modifiers in object mode.
Now you will be able to use the vertex groups with any combination of modifiers, such as displace, mask, etc.
For example, here is the quadsphere with just a displace modifier using the B vertex group.

Here is the .blend if you would like to inspect it
Comment: @vklidu I use the dev version of tissue from [here](https://github.com/alessandro-zomparelli/tissue)
Comment: I haven't find any version with Cache ... may I ask what blender version contains such feature?


How good is 1. e4 c5 move for black? Why does Stockfish play it?

Question: I've been running some engine vs engine games out of boredom and noticed Stockfish, when playing as black, 90% of the time played c7-c5 on white's e4. I've never actually seen a human play this, in the few years of my playing. Is it a move that mostly professionals play? Is there a concrete reason for that move?
Comment: According to the Lichess database 1  ... c5, The Sicilian defence, is the most common response to 1 e4, being over twice as common as the next response ( 1 ... e5 ). To help give an answer can you explain, by editing the question *not* a comment, why "Looking from the humans' perspective, I don't think any human would play that"
Comment: It's very strange that you've never encountered the Sicilian in your human games. Are you playing 1.e4 only against a very restricted set of humans? As a random piece of data, here are 50 books written about the Sicilian in the last 20 years: https://www.chessbooks.online/sicilian-defense/
Comment: "The Sicilian is the most popular and best-scoring response to White's first move 1.e4." -- https://en.wikipedia.org/wiki/Sicilian_Defence . I can't think of a reply that would add to the Wikipedia page for the opening.
Comment: @IanBush Edited
Comment: Related, possibly duplicate: https://chess.stackexchange.com/questions/25100/conceptually-what-makes-the-sicilian-opening-sensible-for-black
Comment: Is stockfish using the opening book or is it just pure engine?
Answer: 1...c5 initiates the Sicilian Defense. It is absolutely a respectable opening, and I am surprised you've never seen it before. I'll just quote Wikipedia:

The Sicilian is the most popular and best-scoring response to White's first move 1.e4. Opening 1.d4 is a statistically more successful opening for White because of the high success rate of the Sicilian defence against 1.e4. New In Chess stated in its 2000 Yearbook that of the games in its database, White scored 56.1% in 296,200 games beginning 1.d4, but 54.1% in 349,855 games beginning 1.e4, mainly because the Sicilian held White to a 52.3% score in 145,996 games.

Because the Sicilian is so good, it shouldn't be surprising that Stockfish plays the opening.
Answer: Any answer to the question will be as dangerously biased as the database behind it, and moreover Stockfish will have other opening "reasons" than a human (I play 100% c5, and that even without knowing theory...), but here are some values from the database behind the Lichess analysis board, as number of games and white win-white loss:

c5 - Sicilian - 480000 - 6%
e5 - Open - 230000 - 10%
e6 - French - 130000 - 11%
c6 - Caro-Kann - 79000 - 8%
d6 - Modern - 40000 - 12%
g6 - probably KID - 30000 - 7%
d5 - Scandinavian - 22000 - 14%
Nf6 - Aljechin - 20000 - 11%

Observe how good g6 scores, I guess because it mostly ends as Kings Indian and a no holds barred fight will ensue.
Comment: Actually I don't think an answer need be very biased, I'm just not sure if the question is "Why does stockfish play 1 ... c5 so often" or "Why is 1 ... c5 a good move in response to 1 e4". The answer to the former is that that is how Stockfish uses its opening book. The answer to the later should be given by a Sicilian player, i.e. not me
Answer: 1...c5 is a great move that fights for the center even better perhaps than 1...e5. By playing ...c5, White will only be able to play d4 either by trading one of his central pawns for a side pawn or by preparing it with c3 (a move the b1 knight won't be happy about).
On the other hand, 1...c5 is not a developping move (and does not help development at all), so White can try to profit from an early lead in piece activity. The most ambitious plays to try to exploit that often lead to chaotic games with wild attacks.
Overall, the Sicilian Defense (1.e4 c5) is the most common response to 1.e4 in tournament play. Even if opening popularity is a matter of fashion, the Sicilian has stayed on top for a long time.


Disable internet access in XP VM but keep local network

Question: I'm using Windows XP in Virtualbox for some legacy development and my IT department freaks out (rightly so) about XP being on the network. While I can simply disconnect the network access and be done with it, I'm planning on building this VM so that I can distribute it to other members of my team who may need access to legacy tools. I'd rather have the VM boot up with internet access already disabled (independent of Virtualbox and/or VMWare installations - this setup will be running in both).
However, the nature of my work (embedded systems) often requires me to create local networks with the hardware I'm developing/fixing (high-voltage power supplies for X-ray and CT machines) So usually what we do is we have multiple network cards: one for internet access and another for development purposes. We'll change the IP address settings of the development card to a standard, manual static address (192.168.1.4) and leave the internet card properties alone. This enables us to talk to the web (for Google and other miscellaneous uses, we don't need to connect the power supplies to the internet directly) and develop for our devices.
Now the issue is that some of our development software is legacy (Metroworks Codewarrior, VB6) and they run best in XP. I'd still like to be able to develop in XP and talk to our boards from the XP VM. However, I do not want the VM to access the internet (however, the host machine should still be able to access the internet).
I saw some other answers on here relating to this, such as this one, but I'm wondering if there's other ways given that I'm running in a VM on a host machine.
Answer: If you are connecting to a central VM server
The easiest thing to do would be block all traffic going out of the network or coming from the internet that is directed to or from that IP address of the server. If you do this anyone on LAN can still access the computer but no internet access as long as the IP stays the same.
If you are connecting to just your computer and only you need access to the VM and the VM does not need access to anything
If you want only the one host machine to have access to the vm then you can setup a "host only network" or even fully disable the VM's NIC card from the VM management software. Any popular VM software (virutalbox / vm workstation) will have this ability.
If you need XP VM to have access to the specific static NIC noted above
Give the VM only access to the physical adapter card for connecting to those devices then for the static info of the VM to match so it can only communicate with those devices


How to get the weights for a beta neutral portfolio?

Question: Given a ranking of 100 long stocks and 100 short stocks. Looking at these 200 betas: How can I find the optimal weights to get a beta = 0 long/short portfolio?
Comment: Optimal in what sense?
Comment: There are many ways. An EW (or MW) portfolio of all the long stocks has a certain Beta, a similar portfolio of all the shorts has another Beta. Knowing these two betas you can combine the two portfolios such that they have overall beta of zero (you leverage one of the portfolios and deleverage the other). This is just the simplest way to do it.
Comment: @BobJansen agree that's an underlying problem. How to optimize this?
In the best case scenario I could leverage my ranking in each leg and keep as many stocks as possible. Any idea?
Comment: Thanks @noob2 sounds really easy that way! You say there is many ways. Any thoughts on what other technics I could use?
Comment: If you are using optimization then you can just add one linear constraint to make the portfolio beta = 0. (see answer below).
Answer: The author did not define what optimal means, therefore I assume here that we want to find portfolio that has $\beta=0$ and has minimum variance $\sigma^2_{\pi}$ for the expected return $\mu_{\pi}$. This is an extension to Markowitz portfolio and we can find efficient frontier i.e. the set of portfolios that has the lowest risk for a given level of expected return. The algorithm below is not constrained to finding 100 long stocks and 100 shorts stocks, rather it finds optimal weights that minimize the variance no matter how many long and shorts positions it produces. By reading comments I assume that this would be sufficient.
We are in an economy with $n$ different assets. Each asset $i$ is characterized by its expected return $\mu_i$ and variance $\sigma^2_i$. Assets $i$ and $j$ are correlated with correlation $\rho_{i,j}$. The proportion invested in asset $i$ is $w_i$.
Asset's $i$ return is given by:
$$\mu_i=\alpha_i+\beta_i r_m+\epsilon_i$$
where $\alpha$ is asset's alpha and $\beta$ is assets beta and $r_m$ is market return.
The vector of asset expected return
$$\mu=[\mu_1,...,\mu_n]'$$
The weight vector
$$w=[w_1,...,w_n]'$$
The Betas vector:
$$\beta=[\beta_1,...,\beta_n]'$$
Covariance matrix $\Sigma$ is given as:
$$
    \begin{bmatrix}
    \sigma_1^2 & \rho_{1,2}\sigma_1 \sigma_2 & \cdots & \rho_{1,n}\sigma_1 \sigma_n\\
    \vdots & \vdots & \ddots & \cdots \\
    \rho_{1,n}\sigma_1 \sigma_n & \cdots & \cdots &  \sigma_n^2\\
    \end{bmatrix}
$$
Therefore the portfolio return is given by:
$$\mu_{\pi}=\mu'w$$
Portfolio variance:
$$\sigma^2_{\pi}=w'\Sigma w$$
The portfolio selection problem is defined as a minimization of risk
subject to a return constraint. Our objective function is the portfolio variance and we will minimize it with respect to the portfolio weights.
Therefore we want to minimize:
$$min_w \frac{1}{2} \sigma^2_{\pi}=\frac{1}{2} w'\Sigma w$$
with 3 constraints:
$$\mu'w=m$$
i.e. the portfolio return must be equal to a prespecified level $m$.
$$\mathbf 1'w=1$$
i.e. the portfolio weights have to sum to 1.
$$\beta' w=0$$
i.e. the portfolio beta has to be 0.
This problem is an optimization with equality constraints. We can solve it
using the method of Lagrange.
We form the Lagrange function with three Lagrange multipliers $\lambda$, $\gamma$, $\theta$:
$$L(w,\lambda, \gamma, \theta)=\frac{1}{2} w'\Sigma w + \lambda (m-w'\mu) + \gamma (1-w'\mathbf 1) + \theta (-w'\beta)$$
Next, we solve for the first order condition by taking the derivative with respect
to the vector w:
$$\frac{\partial L}{\partial w} = \Sigma w - \lambda \mu - \gamma \mathbf 1 - \theta \beta = 0$$
Checking the second order condition, the Hessian of the objective function is
equal to the covariance matrix $\Sigma$, which is positive definite. Therefore, we have reached the optimal weight vector $w^*$:
$$w^*=\Sigma^{-1} (\lambda \mu + \gamma \mathbf 1 + \theta \beta)$$
To solve for $\lambda$, $\gamma$, $\theta$ we have to substitute $w^*$ to three constraints equations:
$$\mu' \Sigma^{-1} (\lambda \mu + \gamma \mathbf 1 + \theta \beta)=m$$
$$1' \Sigma^{-1} (\lambda \mu + \gamma \mathbf 1 + \theta \beta)=1$$
$$\beta' \Sigma^{-1} (\lambda \mu + \gamma \mathbf 1 + \theta \beta)=0$$
This yields:
$$\lambda \mu' \Sigma^{-1} \mu + \gamma \mu' \Sigma^{-1} \mathbf 1 + \theta \mu' \Sigma^{-1} \beta=m$$
$$\lambda \mathbf 1' \Sigma^{-1} \mu + \gamma \mathbf 1' \Sigma^{-1} \mathbf 1 + \theta \mathbf 1' \Sigma^{-1} \beta=1$$
$$\lambda \beta' \Sigma^{-1} \mu + \gamma \beta' \Sigma^{-1} \mathbf 1 + \theta \beta' \Sigma^{-1} \beta=0$$
For our convenience let's define the following scalars:
$$A=1' \Sigma^{-1} 1$$
$$B=\mu' \Sigma^{-1} 1=1'\Sigma^{-1} \mu$$
$$C=\mu' \Sigma^{-1} \mu$$
$$D=\beta' \Sigma^{-1} 1 = 1' \Sigma^{-1} \beta$$
$$E=\beta' \Sigma^{-1} \beta$$
$$F=\beta' \Sigma^{-1} \mu = \mu' \Sigma^{-1} \beta$$
Therefore rewriting our system of equations in terms of A, B, C... we get:
$$\lambda C + \gamma B + \theta F = m$$
$$\lambda B + \gamma A + \theta D = 1$$
$$\lambda F + \gamma D + \theta E = 1$$
Putting it in the matrix form we get:
$$
    \begin{bmatrix}
    C & B & F\\
    B & A & D \\
    F & D & E\\
    \end{bmatrix}
*
    \begin{bmatrix}
    \lambda \\
    \gamma \\
    \theta \\
    \end{bmatrix}
=
    \begin{bmatrix}
    m \\
    1 \\
    0 \\
    \end{bmatrix}
$$
Therefore the solution is:
$$
    \begin{bmatrix}
    \lambda \\
    \gamma \\
    \theta \\
    \end{bmatrix}
=
\begin{bmatrix}
    C & C & F\\
    B & A & D \\
    F & D & E\\
    \end{bmatrix}^{-1}
*
    \begin{bmatrix}
    m \\
    1 \\
    0 \\
    \end{bmatrix}
$$
Putting $\lambda$, $\gamma$, $\theta$ into our equation of vector $w^*$ we get the weights:
$$w^*=\Sigma^{-1} (\lambda \mu + \gamma \mathbf 1 + \theta \beta)$$
How to produce efficient frontier curve?
Calculate portfolio expected returns and standard deviation for different levels $m$ and plot the result. I have implemented it to check if that works and I got standard efficient frontier curve:


Questions about absolutely continuous function

Question: It could be a silly question but the definition of absolutely continuous function says that
"A real valued function $f:[a,b]\rightarrow\mathbb{R}$ is absolutely continuous on $[a,b]$ if for all $\epsilon>0$, there is a $\delta>0$ such that for every finite disjoint collection $\{(a_k,b_k)\}_{k=1}^n$ of $(a,b)$, $\sum_{k=1}^n[b_k-a_k]<\delta$ implies $\sum_{k=1}^n|f(b_k)-f(a_k)|<\epsilon$."
As I know every absolutely continuous function on $[a,b]$ is continuous on $[a,b]$. But with this definition it seems not hold if we take strange values at $x=a,b$ because the definition only depends on open intervals in $(a,b)$. Is it right that this statement does not hold with above definition?
Comment: Are you sure the definition says $(a,b)$ (and not $[a,b]$)? If you look, for example, at http://en.wikipedia.org/wiki/Absolute_continuity, you'll see that the interval $I$ in the definition is the same as the interval from which the $a_k$ are chosen.
Comment: Yes. I'm sure. I read the definition in Royden's real analysis and many other books.
Comment: I just looked it up in Royden. Actually in his definition he does not make it precise from where the $x_i$ (as he denotes them) are taken, but in particular he does not request to take them from the open interval, so what you said is not correct. I, to the contrary, am absolutely sure that if you define absolute continuity on an interval $I$ (regardless whether open or close) you have to allow the $x_i$ to be taken from all of $I$.
Answer: You're overthinking this. Let $\varepsilon>0$, and choose the corresponding $\delta$. Then for any $\eta<\delta$ such that $a+\eta\leqslant b$, we have
$$|f(a+\eta)-f(a)|<\varepsilon, $$
and hence $f$ is continuous at $a$. $f$ is continuous at $b$ by a similar argument.
Answer: There is no 'continuity' in a closed interval, mainly because of the +/-(δ>0) criteria at the upper/lower bounds.
Comment: Sorry, but this is simply not correct.
Comment: There are left and right continuous terminologies that are used for continuous functions in closed terminals, but not sure how it can be generalized.  Even if we take f(x) = |x| can we say it is left-continuous at [0,1] o right-continuous at [-1,0] ?
Comment: $f: I\rightarrow \mathbb{R}$ is continuous in $x\in I$ if for every $\varepsilon >0$ you can find $\delta >0 $ such that $|f(x)-f(y)| < \varepsilon$ for every $y\in I$ such that $|y-x|< \delta$. By requesting $y\in I$ it does not matter whether $x$ is a boundary point of $I$. The reason to define right continuity is more that there are functions which have a discontinuity in the interior of an interval but behave still nicely on side of that point.
Comment: I will relook at my Goldberg book.  Thanks for the note.


Problems proxy requests to multiple backends with http2, "connection coalescing", connection reuse in google chrome

Question: We are looking for a way to use http2, one proxy with SSL termination and multiple different backends for different subdomains.
I found this explanation of the problem and I am looking for solutions that would work for haproxy. Which would probably work for other proxies as well.
The problem you ran into is caused by "Connection coalescing".
For example, if a browser (Chrome/Firefox) connects to an http2 server "a.example.org" which resolves to 192.168.2.1 and later connects to "b.example.org", it checks 2 things:

1. Do DNS entries match? This will always be the case since our proxy only has one IP.
2. Has a.example.org provided a certificate that also matches b.example.org. (e.g. wildcard or multidomain cert).

If both are the case it will not initiate a second connection but instead reuse the existing connection to host a.example.org.
This is fine in theory but due to the use of sniproxy a.example.org is unable to handle b.example.org because they are in reality, two different hosts.
One way the solve this should be the use of different certs that only cover a single domain (e.g. no wildcard).
I have not tested it but I think it might work.

Is there a way to force our proxy 'haproxy' to check existing connections and confirm that domain, subdomain are correct for the backend that the connection is actually being sent to.
We have tried changing timeout values, using force
option http-server-close
option forceclose

Nothing works the way we would like. Connection to subA.domain.com and then connecting to subB.domain.com fails as they are set up on two different backends. The browser resues the same connection and for two different backends.
Answer: Not the answer, just a workaround. Has to disable HTTP2 on web server. Then everything works again. Sometime new standard just breaks old things.


Can we apply 'Minoxidil' on scalp or face to get proper scalp or beard hair?

Question: Minoxidil contains alcohol (synthetic), also we r not consuming, just applying. So, is it allowed? Some people say that because it is synthetic alcohol which is made by chemical, not natural alcohol, so it is OK. Also, we are not consuming, we are just applying on body, so it is fine. Other people say that even though it is synthetic and we are just applying, still it is haraam, and also by trying to modify your looks by doing this, you are Nauzubillah challenging Allah that I do not like the way you have made me and I am changing it. So it is not allowed. Can you please let us know whether this is allowed or no?
Comment: Alcohol is najis.
Comment: So that means if we apply, then we have to do ghusl necessarily before performing any Namaz? Also, even if we assume that the alcohol in it is not synthetic, it is the actual toxic alcohol that is used to consume, then also it will be the same thing as above?
Answer: It depends. The following points should be kept in mind:

Alcohol is distinct from Ethanol which is distinct from Wine. Alcohol a genus in Chemistry for all chemicals which have the -OH group. Ethanol is a specific type of alcohol which causes intoxication, which can be produced by fermentation of sugars or synthetically. Wine is a beverage produced by fermentation of fruit, which contains ethanol as its essence.
According to some madhabs (Hanafis) it is Wine (produced from grapes or dates) that is unclean and forbidden for use, not ethanol - they would allow for use of ethanol obtained from other than Wine as long as it does not cause intoxication.  Mioxidil does not contain wine, and its topical use does not lead to intoxication.
Further, other alcohols like Isopropanol or Methanol or Propylene glycol , do not have the same ruling as Ethanol as they are a different substance with different properties. Minoxidil preparations may contain any one or more of them.

Using Wine or another haram substance as medicine remains forbidden. See Can necessary medication be permissible even if it contains haram ingredients?

There might be other alternates available to Minoxidil, such as hormonal treatment or the use of Finasteride or Dutasteride. It might also be possible to obtain minoxidil that is free from ethanol. You can ask your doctor to suggest any alternates.
Answer: if the alcohol is ethanol alcohol made through brewing then no, but if its isopropyl or rubbing alcohol then its ok
Comment: Would it be possible to [edit] in some reliable references please?
Answer: Yes, you can apply 'Minoxidil' on your sculp or face to grow hairs, if you have been affected by hairfall or beard fall. Hairfall and bearfall are sickness'. According to Muhammad's (Peace Be Upon Him) lifestyle and hadith, using medicine is halal and 'Minoxidil' plays the role of medicine of hairfall and beard-fall. And when using urine to make medicine is allowed, why wouldn't it be allowed to make medicine with alcohol?

Anas (R) said, "Some people of 'Ukl or 'Uraina tribe came to Medina and its climate did not suit them. So the Prophet (pbuh) ordered them to go to the herd of (Milch) camels and to drink their milk and urine (as a medicine). [Al-bukhari, 233]

So, it is halal, according to my knowledge.
Every answer can be wrong in this forum, so Please consider asking this question to a mufti. Don't rely on this answer.
Answer: Alcohol was once used to sanitise and cleanse an area of the arm before using a hypodermic needle there.
It's less often used that way. This is no way is against Islam as the patient is not being asked to drink it. It's merely being used for the purposes for hygiene.
Similarly for the situation you have outlined.


Are there any experiments in progress designed to explore the interiors of gas giants like Jupiter or Saturn?

Question: I know that the high atmospheric pressure on these planets make a unique challenge to learn about the planets interiors.  Are there any active projects designed to learn more about the interior of the gas giants?
Comment: There is a rather similar question with a slightly different scope: http://space.stackexchange.com/questions/835/do-we-have-instruments-that-can-measure-the-depth-of-storms-like-the-great-red-s
Answer: The Juno probe will be doing some of this for Jupiter's atmosphere.  Due to the extreme densities involved it will be doing so from orbit; not by entering into it.
From Wikipedia

Scientific objectives Image of Jupiter aurora in UV by the Hubble
  Space Telescope. Bright streaks and dots are caused by magnetic flux
  tubes connecting Jupiter to its largest moons (Io: bright streak on
  the far left; Ganymede: bright dot below center; Europa: dot on the
  right).
The Juno spacecraft's suite of science instruments will:

Determine the ratio of oxygen to hydrogen, effectively measuring the abundance of water in Jupiter, which will help distinguish among prevailing theories linking the gas giant's formation to the Solar System.
Obtain a better estimate of Jupiter's core mass, which will also help distinguish among prevailing theories linking the gas giant's formation to the Solar System.
Precisely map Jupiter's gravity to assess the distribution of mass in Jupiter's interior, including properties of the planet's structure and dynamics.
Precisely map Jupiter's magnetic field to assess the origin and structure of the field and how deep in Jupiter the magnetic field is created. This experiment also will help scientists understand the fundamental physics of dynamo theory.
Map the variation in atmospheric composition, temperature, structure, cloud opacity and dynamics to pressures far greater than 100 bars (10 MPa; 1450 pound/sq inch) at all latitudes.
Characterize and explore the three-dimensional structure of Jupiter's polar magnetosphere and its auroras.[17]

A recent analysis of data from the Voyager 2 flyby's of Uranus and Neptune found their weather layers were at most 1000km thick.  I don't know if a followup to repeat the analysis for Jupiter and Saturn is planned or not.
Answer: A good example is the Fourier imaging asteroseismology technique used by SYMPA:

SYMPA, a dedicated instrument for Jovian seismology I. Principle and performance
SYMPA, a dedicated instrument for Jovian seismology
II. Real performance and first results
Detection of Jovian seismic waves: a new probe of its interior structure

JOVIAL is next-gen implementation, also from Earth:

JOVIAL;Jovian Oscillations through radial Velocimetry ImAgingobservations at several Longitudes.
Jupiter's interior: from gravimetry to seismology


Can a novel be open source, although it does not have a source?

Question: If I want something I have written release as open source, for instance a novel, is that possible? A novel does not have a source, the work itself is all that is needed to recreate the work. In cases of software I need the source code to create a changed version of the software, but in case of a novel all I need is the novel itself? So does the written text works as it's own source? Or are written text impossible to open source?
Answer: Novels and other written works do have source code: it's the "preferred form for modification", so basically the files you need if you want to edit the "work", whatever it is. If you write your novel in LibreOffice, it's the .odt file, plus any external files you may need (images, diagrams etc.). If you write it in LaTeX, it's the .tex file, plus any external files required. Don't forget any files you may use to prepare the final output (the cover, etc.). For images, ideally you'd keep the .xcf files for example if you're using the Gimp, as well as the PNGs or JPEGs you use in the document.
If you work directly on paper (handwriting or using a typewriter or whatever), then the preferred form for modification is the manuscript because that's all there is. You can still use a free / open source license on the text though; it's just that the effort required is greater... (This is pretty much the same reasoning as allowing JPEGs of photos as the preferred form for modification, rather than everything that was photographed!)
So yes, you can open source written text.
Comment: If you write on a typewriter it's ...
Comment: Good point, I think that's still coverable by open licenses (albeit in a much less practical fashion).
Comment: This is true, but for anyone wanting to make substantial changes to a novel not having the original 'source' is unlikely to be a significant barrier - it's generally relatively easy to recreate that from the published ebook. It's not even very hard to recreate from a paper book by either copy-typing or OCR.

Copyright law and conventions around not copying without permission are likely to be much more relevant.
Comment: @bdsl the question here is about releasing a novel as open source, so licensing and copyright aren't going to be an issue. And yes, recreating some form of source from a written text isn't exceedingly difficult; that's effectively a variation on my second paragraph. Recreating a source form which produces exactly the same output as the original is another matter, but it's typically not required...
Answer: Novels, unlike software, don't have the large transformation between source code and binary that is usually the case with software. You can study and "tinker" with novels, but you cannot do the same (without great difficulty) with software without source code. Source code is important for software since it is a prerequisite for modification and sharing derivations. Therefore terms like "source code" are mostly irrelevant for novels, or things like visual art and documentation.
It is for this reason that, although you can apply software licenses to them, there are much better options. This is a big reason why the Creative Commons licenses were created; they, unlike software licenses, contain no mention of "source code" and are designed for creative works in general. GFDL may also be a suitable free license for such works.
When referring to such licenses, it may be less appropriate to refer to them as "free software" or "open source". Instead, people usually refer to these as "free culture". Even though there is no source code, the goals and ethoses have large overlaps, and focus on user freedoms such as the freedom to use for any purpose, the freedom to redistribute, and the freedom to share your modifications. If you compare this to FSF's definition of free software, this is almost the same with the exception of freedom 1 which is inapplicable. Those licenses that do not grant these freedoms are "not free culture licenses", or just "non-free" for short. For example, CC-BY-NC is "not approved for free cultural works" because it restricts commercial use.
Comment: Isn't "free culture" the movement? I'd say [free/libre content](https://en.wikipedia.org/wiki/Free_content) is the more common term.
Answer: You can, and indeed it has been done. You can write the novel in Markdown or LaTeX and upload it to GitHub. Why not? You will have to choose a Creative Commons license, which are not included by default when you create a GitHub repo, but that's all.
Comment: @Zizouz212 Some CC licenses are absolutely open source.
Comment: Two things: CC licenses aren't actually open source (though they have nearly equivalent goals), and you don't have to choose a CC license when you upload on a GitHub repo - you can even choose something like MIT for all you want. It's been done - images have been placed under the Apache license too.


How do I save a complete webpage displayed in Android's WebView?

Question: I am developing an Android application in which I have a WebView. I want to save the entire webpage loaded in this webview (Html + all resources + images + icons etc) into a folder and zip it and upload it to a server.
If you use WebView's saveWebArchive, then it is saved in archive format. How do I get the Html and images back from this archive? Is there any documentation for the format of this archive?
If I use addJavaScriptInterface to get the html as described here, I still have to copy the images and other resources from the webview cache dir (/data/data/your app package/cache/webviewCache/). However I did not find webview cache dir (/data/data/your app package/cache/webviewCache/) in Icecream Sandwich.
Is there a way to save the entire webpage displayed in webview along with resources in Android?
Thanks
Comment: Good question, I need to know this as well.
Answer: If anyone is still interested, there is an open source project here that can read WebView's archive format (saved with saveWebArchive) and display it back in a WebView.
https://github.com/gregko/WebArchiveReader
I couldn't find details of the actual format yet.
Answer: You can use HTML 5 to store pages in the cache and load from the cache itself.
Caching is easy using HTML5, all you have to do is to make and refer a manifest file that holds information on what all elements need to be cached. Here is a tutorial.
And here is a good way to implement the cache feature in your web view.


Db_select Condition Collate

Question: In drupal 7 db_query, when i use (LIKE), i add (COLLATE utf8_turkish_ci) after field. Because i want to search by Turkish characters. It works fine.
But i dont know how i use this in db_select. For example;
I use that condition
<code>$query->condition('title', '%' . db_like($some_text) . '%', 'LIKE');
</code>
And i use orderby like that
<code>$query->orderBy('title', 'ASC')
</code>
How can i add COLLATE utf8_turkish_ci for condition and order?
Answer: I have a solution now.
For LIKE;
<code>$query->where('n.title COLLATE utf8_turkish_ci LIKE :title', array(':title' => '%'.db_like($some_text).'%'));
</code>
For ORDER BY;
<code>$query->orderBy('n.title COLLATE utf8_turkish_ci', 'ASC');
</code>

Db_select Condition Collate


What is the physical significance of an imaginary field?

Question: How should we understand a complex field? What is the physical significance of its imaginary part? For example, a complex scalar field is written as:
\begin{equation}
\phi = \phi_{1} + i \phi_{2}
\end{equation}
What is the physical significance of $\phi_{2}$? If it is the same as the significance of $\phi_{1}$, why is $\phi_{2}$ put in the imaginary part? What does imaginary mean? Does it mean unreal or virtual? If not, then what?
Comment: The significance of $\phi_2$ is probably the same as the significance of $\phi_1$.
Comment: Related: http://physics.stackexchange.com/q/11396/2451
Answer: Complex fields appear in real-valued (Hermitian) Lagrangians. For example, your $\phi$ may appear in a kinetic term $\partial_\mu\phi^\ast \partial^\mu\phi=\partial_\mu\phi_1 \partial^\mu\phi_1 +\partial_\mu\phi_2 \partial^\mu\phi_2$. In theory, you could forget about $\phi$ altogether, thinking instead in terms of uncoupled real fields $\phi_1,\,\phi_2$; indeed, they remain uncoupled if the potential term is proportional to  $\phi^\ast\phi=\phi_1^2+\phi_2^2$. But there is an advantage to writing everything instead in terms of one complex field, which is that the $U\left( 1\right)$ symmetry is obvious, whereas the biggest symmetry you might otherwise notice is $\mathbb{Z}_2^2$.
If $\phi$ denotes the Higgs field, the potential term also contains a contribution proportional to $\left( \phi^\ast\phi\right)^2=\phi_1^4+2\phi_1^2\phi_2^2+\phi_2^4$ which manifestly couples $\phi_1$ to $\phi_2$. However, it is only when we think in terms of the complex $\phi$ that the spontaneous symmetry breaking induced by a choice of a vacuum is evident.
Asking about the physical significance of $\phi_1,\,\phi_2$ separately is a bit like asking about the separate significance of Cartesian coordinates in a plane. If you've studied orbital mechanics for a 2-body solar system, you'll know that polar coordinates have a more obvious physical relevance and interpretation. And in the case of a Mexican hat potential, again a polar representation is more relevant. Let's consider the vacuum case. Writing $\phi=\rho e^{i\theta}$, $\rho$ is the vacuum amplitude while $\theta$ is an arbitrary phase that breaks the symmetry. This cleaving of a computable physical parameter from an arbitrary one implies a greater physical significance than either $\phi_1$ or $\phi_2$ has.


Can one take an Italian rental car into Slovenia and Croatia?

Question: We will begin our trip to Croatia by flying into Venice.  We are now thinking about renting a car and driving first to Ljubljana and then throughout Croatia.  Is this easy to do, or will we have to rent separate cars for each country?
Answer: You can rent a car but you must check what the agency's policy is regarding international crossing. Sometimes it's minimal and they ask for an additional fee or sometimes a substantially higher insurance rate. The most steep fee though happens if you do not return the car in the same country of origin.
Eurocar charged me 300 EUR last time for that. For a simply border crossing, in my case Croatio to Montenegreo and back it was only 5 EUR. Sixt has a detailed policy in their agency about which fees applies which crossing. Also, in their case, you have to mention this when you rent the car because some of their cars are not allowed in certain countries, possibly for legal reasons.
Now, unless you plan to stop a lot between those places, I highly recommend trains for the northern part of the trip. The cost is much cheaper than what you would pay for gaz over the same distance! From Split though we used high-speed catamarans to reach the south and then renter a car after leaving Dubrovnik which is pedestrian only and having a car quite problematic. Slovenia is easy to drive around though. You can rent local cars or use buses for out-of-the-way places and day-trips which will save you considerable money.
Comment: The cost comparison needs to know how many people are traveling.
Comment: For a larger group, it's possible the car would be cheaper, but even a family of 4, it was cheaper than car rental plus gas. Trains are surprisingly cheap in Europe! Definitely not the prices we get here in NA.
Comment: Yes, I've found it cheaper in the past to hire a car in country one (even driving it across the border if desired), then drop it off at a train station, training across the border, then hiring another car, than to pay the one-way-different-country fee.
Answer: Yes, under EU insurance rules a car insurance policy issued in one member state is valid for travel in all others. It's not possible to issue a vehicular insurance policy which is valid for Italy but not Slovenia or Croatia.
If you plan to leave to EU (for example by going to Serbia or Montenegro) you may need to pay more for additional cover.
See: http://ec.europa.eu/finance/insurance/consumer/motor/index_en.htm#maincontentSec1


have refugee status in UK and going to marry a German citizen and live in Germany

Question: I am non-EU nationality and have 5 years UK refugee resident permit, and now want to marry a German citizen in Germany and apply for German resident permit to live there. In this case can I hold both residency? and extend my UK resident permit to permanent resident at the end of duration of this 5 years?
Comment: I suppose the UK will consider that you have abandoned your residence in the UK and refuse to grant indefinite leave to remain.  But I haven't yet found anything explicit in the immigration rules that leads to this conclusion.
Comment: my 5 years resident permit is valid until 2020, so what will happen that if I get German resident permit?
Comment: my assumption is that the amount of time you spend in the UK is more important than whether you have a residence permit elsewhere, but I do not know and I cannot find anything explicit in the sources online. Your best course of action is probably to consult a UK immigration lawyer who has experience with refugees, or a refugee organization in the UK.
Answer: The first problem is that you can't apply for "indefinite leave to remain" (which is what I think you mean by "permanent resident") until you have lived in the UK for 10 years (not 5) ... so you can't apply for ILR yet.
The second problem is that if you go and live in Germany, you will stop being resident in the UK, so you will at the very least stop the clock on the 10 years.
The third problem is that I believe that if you go and live in Germany then your refugee residence permit will be considered abandoned and will cease to be valid.  However I can't find any evidence for that.
I think you are going to have to pick one of UK and Germany.
Comment: The first paragraph is incorrect.  See [Settlement: refugee or humanitarian protection: Eligibility](https://www.gov.uk/settlement-refugee-or-humanitarian-protection/eligibility)
Comment: I have moved from the UK to Germany, so guess which one I would choose!
Comment: @phoog - Great catch!  I didn't find that.  I will edit the answer properly later and ping you when I have .


How to make Grape Must

Question: I just bought some grape must - it's a must on spinach salad! I am thinking of turning some of my own homemade concord grape juice into the same. Any advice, other than to reduce by slow boiling? Can I can the results in a hot water bath? Will the acid level change by reducing the liquid?
Comment: I think if you're starting with juice, you've already gone past the must stage.  It looks like must is just freshly crushed grapes and includes the stems, seeds, and skins.  [link](http://en.wikipedia.org/wiki/Must)
Comment: Looks like it's time to use science! Try it and report back?
Comment: Thanks - yes, it looks like you have to start with the grapes. However I wonder what would happen if I did reduce the liquid from my grape juice, would it be similar to must? The concord grape flavor is so intense in the juice, I wonder if it could intensify even more.
Comment: the reduced liquid is similar to a treacle, not to a must. I will include such non-cane treacles in one of my future preserve blog posts from this series: http://cooking.blogoverflow.com/2012/07/cherry-berry-nut-14/.
Answer: Based on the wikipedia article, it sounds like you want the pulp and skin as well.  It sounds like you won't get the same texture, consistency or sweetness by only reducing grape juice.
However, I found this cool how-to page on how to make grape must jelly.  I think the hand-crushing grapes part will be the most relevant to you.
You could use some kind of pressing machine, such as an OJ squeezer, to get the same effect without red hands.  I'd stay away from blenders and puree machines, as cutting foods doesn't have the same effect as crushing them.
I don't think I've had grape must, so you'll have to be the judge on how much or how little of the pulp goes into your final product.
Answer: When grapes are pressed for wine, the results of the first gentle pressing go into the wine. "Grape must" is the second, more violent pressing, which may include adding a little water to get the "virtues" out. The must has a range of uses. The French convert the best must into a  brandy-like distilled drink called "marc", which is rarely exported.
A lot of the Italian grape must goes into a condiment described as "aceto balsamico di Modena IGP" - it is not the true "balsamic vinegar that chefs love, and in my local "German supermarket" three varieties are sold, red, white and brown. Tell me that the brown color owes more to caramel than to balsam, and I will believe you. Whatever, the stuff is no substitute for "real" balsamic vinegar, but if you want to make a salad dressing it works well when involved with mustard and olive oil. I think that's what you've discovered.
More of the Italian grape must goes into fizzy wine-like stuff called Lambrusco. If Lambrusco gets above 9.5% alcohol, it has been made from grape juice. Below that, it usually is mostly fermented must that has been mucked about with to give a product of acceptable taste, and is usually about 5.5% alcohol.
I'm not saying what the Germans do with it beyond asking if you've ever tried Asbach brandy? That's the good stuff, it gets worse.
That's about as much as I must know.
A postscript - the point I was making is that the must is the second pressing juice. What I didn't mention clearly is that the concentrated must is formed in the same way that fruit juices are concentrated for transport, in large industrial plants fitted with pumps etc. to exclude the air.
If you try to reduce your grape juice by gentle boiling, I'm afraid that the flavour components will surely be oxidized.
Comment: Authentic balsamic vinegar doesn't contain the plant called "balsam". But I agree that these cheap little bottles aren't made by the traditional process.
Comment: The Italians also make _grappa_ in the same way the French make _marc_; grappa is easy to find in the U.S. at least. As far as _aceto balsamico_, you may be thinking of _mosto cotto_, which is both the first step of making real balsamic vinegar (which carries the "_tradizionale_" designation) and sold on its own as a condiment (at various ages). The low-grade stuff is not generally made from boiled must.
Comment: @JoshCaswell - the stuff I'm referring to clearly states on the label that it is a mix of wine vinegar and concentrated grape must, although it is marked balsamic vinegar / aceto balsamico there's no balsam listed in the ingredients. It is cheap (€1.25/£1 for a bottle), and useful for salads. My main intent was to point out to the asker that the stuff is available for his main purpose of salad dressing. I don't think it fits into the scheme of making real balsamic vinegar, it is a "volume product" of itself - why it always says "balsamic" is a mystery.
Comment: You would not add a plant, anyway - balsam is a gummy extract from a plant, usually a tree. One might argue that there **is** a trace of balsam in authentic balsamic vinegar because at one stage of the process it is kept in a barrel made from acacia wood, and gum acacia (a balsam) would transfer from the wood to the vinegar. That really is splitting hairs, isn't it?

How to make Grape Must


Visualizing directed preorders

Question: I am trying to understand directed preorders, a.k.a. directed sets. Are they analogous to connected DAGs?
Comment: One may visualize any preorder as follow. A preorder is a certain type of category. If the category is small, we may take it's nerve. One might also might be able to visualize this as a graph of some sort.
Answer: Not quite. A DAG cannot have edges $x\to y$ and $y\to x$, while a directed preorder can have $x\leq y$ and $y\leq x$.
In general, you can visualize a preorder as the reachability relation on the vertices of a directed graph. Then a directed preorder corresponds to a graph where any two vertices are reachable from some third vertex.
Comment: So it is necessary that the directed graph be at least weakly connected.

Visualizing directed preorders


Fluid Simulation does not follow collision object morphing with skape keys

Question: I have an ice cube in my scene that is melting. I want a slow melt so didn't want to use fluid to geometry. So I have my ice cube with a flow object ontop of it acting as the water dripping from the cube. The cube melts by using shape keys. I have used sculping to replicate the ice shrinking. Animating the shape key number value, making the ice cube shrink as the water runs down it.
However the water flow effector only follows the first shape, even though the mesh is being "compressed".
How do I replicate this, do I apply scale to the animation in each time the shape changes? Is there something I need to change?
I have attached images of my work flow below.
Comment: Yes I did, I figured out the solution I'm going to post the answer now
Comment: Did you bake the fluid simulation before you animated the cube shrinking?
Answer: So to correct this issue, I applied a scale keyframe at each start frame and end frame of the shape key. i.e. from 0-1.0 of the shape key key frame. Once all my shape keys and scale key frames were in place I baked the fluid simulation.


Does one have to be good at competition math to become a great mathematician in academia?

Question: So I'm seventeen and currently a junior in high school. I love mathematics very much, it's developed into a strong passion over the past few years, after witnessing the president of the math club at my school give Euclid's proof on the infinitude of primes I've obsessed over finding beautiful arguments and proofs. The dilemma I've been having recently is regarding my relatively lackluster performance at mathematics competitions. I've worked my way through quite a few math books. (currently reading spivak's calculus on manifolds, have read his calculus, Shilov's linear algebra, apostol's calculus volumes and apostol's mathematical analysis.) I usually don't have insurmountable trouble doing the exercises here, but show me a problem on the AMC12 and I'll take an ungodly amount of time trying to make sense of it. My interests don't particularly lie in the discrete sort of mathematics that those sorts of competitions test though, but shouldn't the bit of mathematical maturity I seem to have be able to help me reason through these tests? Do these sorts of problem solving skills help me become a better mathematician? One last thing to note is I'm not a very competitive person so I feel that probably strongly affects the way I approach these competitions.
Comment: Many outstanding mathematicians have been very good at contests. Many have not.
Comment: If you love simple, ingenious, elegant proofs, I'd like to recommend [this book](http://books.google.com/books?id=9W6GQ42BRR0C&printsec=frontcover) to you.
Comment: See the prior question [Advantages of IMO students in Mathematical Research](http://math.stackexchange.com/q/4846/242).
Comment: Thanks Lucian the book looks quite fun :). Does anyone think it would behoove me to better acquaint myself with the sort of problem solving necessitated by competitions?
Answer: I hear you @Eric. I personally am not a fan of mathematical competitions either. Actually I am not fond of any sort of strangled time restriction on problem solving. Yes, you need to learn to meet deadlines if you intend to work in industry, but the highest echelon in mathematics to me is research and that takes time, hard work and it comes with perpetual, repetitive failures.
I always thought I lacked the computational skills my fellow students had when I was in high school. Actually, I still doubt my capabilities in that regard. But I've been told and have learnt, that does not decide whether you will be of any importance when it comes to mathematics.
Yes, mathematical competitions are very useful. They provide great incentive to budding mathematicians and lure bright young minds into the field. But performing substandard in these time-restricted tests does not mean you are less capable than your fellows.
The crucial point is that you love mathematics. The subject in its purest form. You seem like you have a serious curiosity to learn math and have a taste for the beauty that lies in its precision, truth and  subtlety. That is your strength. Pursue what you like, what whets your curiosity and keep doing what you enjoy, the results and the recognition will follow.
I am a critic of short mathematics tests. I am in college and our papers are only 2 hours long and sometimes include MCQ questions which I despise. I came across a Graph Theory paper online once which required students to solve 4 rather difficult and long problems but were given 6 hours to do so. I would kill to be sitting for papers of that form because like you I am not a fan of rushing a solution to a problem. I mean, you miss all the fun. The joy lies in wrecking your brain to come up with a "solution". Not to come up with an answer following a known, taught algorithm.
So where were we? Right. You'll be just fine. Don't be discouraged. You have a long way to go. And keep reading. You've got your hands on some good literature. Might also want to read some number theory books. Search for reference request questions on Elementary Number Theory, there are plenty on this site.
Good Luck!!
Comment: Thanks a lot! I won't be discouraged so easily. I'll read through a book on elementary number theory when I have a bit of time on my hands.
Comment: @Ishfaaq The USAMO is exactly the sort of competition that you might like, then!
Comment: Hmm I think having 6 hours for 4 difficult problems would be a psychological nightmare for me; just knowing that the problems are difficult also let's you know that if you just don't see that trick(s) that's required to solve them there's a real chance you could end up with a score of 0 after 6 hours, which is terryfing.


What prevents an all-out war against ISIS and its allies?

Question: Why may not nations (even if they aren't friendly with each other) declare an all-out war against ISIS and its allies?
Answer: You may not remember an all-out-war.  There hasn't been any involving superpowers for 70 years.
All-out war means lots and lots of people dying.  And these aren't theoretical people. They are actual real-life, flesh and blood people, being killed painfully and gruesomely: bleeding out, with shrapnel wounds, with body parts missing. They are not all "bad people" they are people like you.
All-out war doesn't mean a few smart bombs, it means people like you being drafted and sent overseas to do or die.
And at the end of it you are left with the seeds of the next war.  Get rid of ISIS, but there are other groups. There are other people who will take advantage of some regional instability.
The twentieth century saw two all-out wars.  Let us hope the twenty-first will have two fewer.
Comment: @divibisan The Vietnam conflict officially wasn't a war. The US lost about 58000 soldiers in the Vietnam conflict, which was more than the 53000 lost US lives in World War I (but considerably less in terms of population), and a whole lot less than the 405000 US lives lost in World War II. Vietnam, north and south, lost considerably more than 58000 lives in the Vietnam conflict, but not nearly as many as Europe lost in either World War I or World War II. Moreover, Vietnam definitely was not all-out war. By the mid 1960s, an all-out war would have inevitably involved nuclear weapons.
Comment: Wouldn't you consider Vietnam an all-out-war? It certainly wasn't a _total_ war, at least on the US side, but it definitely wasn't a minor conflict either. This doesn't affect your excellent point.
Comment: For context, 618,000 died in the US Civil War. Some put that estimate at the low end.  US population is 1860 was about 31,000,000...so at least 2% of the population was killed by war alone.
Answer: After the devastation of World Wars I and II, and the beginning of the nuclear arms race, governments came to the conclusion that full-scale war was simply too economically damaging to justify its goals. The only victories in modern war are pyrrhic victories. So through the Cold War and beyond, major industrialized nations have restricted themselves to bush wars (small-scale proxy wars between puppet states), peace-keeping missions (efforts to stop internecine violence within under-developed nations), and incursions (limited-goal strikes against specific targets, now mainly accomplished by drones). Small wars can mean big business in arms sales and supplies; big wars would destroy too much to be viable.
Answer: This question seems fundamentally flawed in its premise.
There has been pretty much an all-out war on ISIS, within the limitations imposed by its structure.

Western countries have had a large coalition bombing and attacking their infrastructure and camps.  Numerous countries have participated: USA, France, Canada, among others.

Iraq and Kurdish areas have fought hard on the ground to expel them from their territories.

Arab countries fought them.  One of their atrocities was burning a captured Jordanian pilot.

Russia has attacked ISIS in Syria, though some of that is also muddled by their support of Hassad: a number of rebel groups have a radical Islamic ideology, so would be targeted regardless of ISIS affiliation or not.

Iran (Shia) fights them as they are Sunni.

Even the Taliban don't get along with them in Afghanistan.

Now, regarding the all-out war aspect:
ISIS, even in its caliphate-territory phase, was an amorphous organization with ill-defined borders and irregular troops.  It has embedded itself in civilian areas.
During some of the final battles for their strongholds, in places like Raqqa or Mosul, it was an overriding concern to limit civilian casualties as much as possible.  This isn't just about being nice - civilian deaths fuel insurgencies.  On the flip side, ISIS aimed to get as many people killed as possible and wanted to keep their human shield.
So you may not have seen "carpet bombing" or the like and retaking ISIS-held cities seemed to take forever.  But the fighting was nevertheless intensive by all metrics (and a large number of civilians died).
In short, pretty much everyone did what they could to get rid of them.
No nation state has, to my knowledge, allied with them.  The fallout if a nation was caught backing them would be too problematic and they would be near-uncontrollable and totally untrustworthy allies in any case.
Does that mean it's easy to get rid of them?  No.
Answer: While ISIS has declared itself as a state, the view of the rest of the world is somewhat muddied (emphasis mine):

Since ISIS declared itself a caliphate on June 19, 201410, the group has received extensive attention in the media, and several attempts have been made to define the goals of ISIS and its role in the world. However, ISIS' claims to statehood are illegitimate and misguided. While organizations such as the U.S. Bureau of Counterterrorism consider ISIS a terrorist organization11, some have ventured to claim that ISIS is not a terrorist group.

This makes prosecuting a traditional was somewhat difficult. If they aren't a state, then how, or, more specifically, where would you fight them? They have no official territory of their own. At least theoretically, any territory they have would technically be another state's land. That complicates things considerably. Any action taken against them would need the permission of the legitimate state, or else you would risk souring relations with that state as well. That certainly doesn't make it impossible, but it certainly complicates things.

Of course, as others here have correctly pointed out, there's also the fact that most countries have a poor opinion of all out war after what happened in World War 2. Thus, they try to exercise self-restraint and avoid war (at least at that level) at all costs.


Invertibility of an ideal differentiator

Question: Is the system $y(t)= dx(t)/dt$  invertible or not?
If yes, please determine the inverse system for it.
Answer: It is not. It suffices to find a counter example. Let me tell you that "I am flat". Could you derive my actual value?
So, any constant function $f(t) =c$ is differentiable, and have the same derivative, $f'(t)=0$. Only from knowing that  $f'(t)=0$, you cannot recover the original (constant) function. Hence the system is not invertible.
Answer: The system is not invertible because you can always add an arbitrary constant $c$ to any function $x(t)$ and the system will map it to same differentiated function $y(t)$. So, the mapping is not unique or one-to-one and hence not invertible.
Answer: Delta coding (with no quantization) is quite close to what you are asking. Let:
x=randi([0 10], 8,1);
delta = diff([0; x]);
x_hat = cumsum(delta);
assert(all(x-x_hat)==0);
But then you have a «silent agreement» to preprepend a zero such that you have a known starting point. And differentiation/integration is replaced by its discrete equivalents.
Knut


How to embed a Mathematica demonstration in Google sites?

Question: I want to have students submit articles that include Mathematica demonstration projects in a document that is on Google sites. I am having problems with embedding the JS code. Could you provide step-by-step instructions.
Comment: There aren't really any "steps": You're just supposed to copy the CDF Web Deployment Wizard to wherever you want the CDF to be shown. Remember to change the URL of the CDF and the image that is shown if the user does not have the CDF plugin installed.
Answer: There is no need to use Javascript to include CDF in a web page. (but better to use Java script, please see end of post)
Upload the CDF file (source.cdf) and the HTML page (index.htm) into a folder on the server. Keep both files in same folder for simplicity.
Edit the index.htm file using a text editor and type this line in the HTML anywhere you want the CDF to show up and play in the web page:
   <embed src="source.cdf" width="800" height="700">

Change the width and height to the correct values as needed so the the content area reserved on the web page matches well with the size of the display you want.
If this still does not work for you, please follow up with error messages. Make sure to use CDF export from Mathematica, using Standalone option.

From comment below, may be there is some confusion, so I thought I make the steps more clear.
Here are the steps:
1 Student needs Mathematica to make CDF
2 Student starts Mathematica, opens new notebook, makes HW assignment and Manipulate in the notebook.
3 Student exports the notebook to CDF file as standalone. Now there are 2 files in student folder on their PC (university computer or student own computer). one file is called hw.nb and one called hw.cdf
4 Student makes an index.htm file using a text editor, here is a template for one to use:

<!DOCTYPE html>

<title>my HW</title>

 <embed src="hw.cdf" width="800" height="700">

5 Now there are 3 files in student folder  hw.nb, hw.cdf and index.htm
6 Student uploads the files hw.cdf and index.htm to server, on a folder there. Keeping both files in same folder on server.
update:
From comment below:

It is best practice to use the JavaScript file. What it does is
  checking if the user has the CDF player installed and if not it
  displays an image that acts as a link to a website where it can be
  downloaded
Comment: So I need to have Mathematica license itself and open the CDF file in it and then export it as a standalone?
Comment: @Maesumi  You need Mathematica to create CDF file from notebook file. i.e Mathematica is need for the step nb->cdf. Then CDF is used on the web page, not the .nb file. You do not need Mathematica to use CDF file. Only to create one.
Comment: It is best practice to use the JavaScript file. What it does is checking if the user has the CDF player installed and if not it displays an image that acts as a link to a website where it can be downloaded. So "no need" is a bit exaggerated, I think you should mention this downside at the top of your answer.
Comment: Thanks for this very helpful answer, but I encountered some silly, noob issues while implementing this on Google Sites. I have referenced this answer, and posted the same as a question on Webapps Stack, at [this link](https://webapps.stackexchange.com/questions/124046/can-we-use-google-drive-to-embed-mathematica-cdf-demonstrations-in-the-new-googl). If you have something to say regarding this issue (either here, or on Webapps SE), I will be very grateful. Thanks.
Comment: @Nasser: I have MMA 11.03 version and I cannot see the option to make a CDF standalone. How can I make a nb as a CDF standalone?


Overview of basic results on cardinal arithmetic

Question: Are there some good overviews of basic formulas about addition, multiplication and exponentiation of cardinals (preferably available online)?
Comment: [Pete Clark](http://math.stackexchange.com/users/299/pete-l-clark) has some stuff written up in his [website](http://math.uga.edu/~pete/expositions2012.html) under "Set Theory". Chapter 2 gives the basics.
Comment: I have a sequence of blog posts on this topic. It starts here: http://caicedoteaching.wordpress.com/2009/02/05/580-ii-cardinal-arithmetic/
Comment: And perhaps the most efficient way of looking at all the relevant posts is to go to http://caicedoteaching.wordpress.com/ and then select category 580 (and scroll down).
Answer: $\newcommand{\alnul}{\aleph_0}\newcommand{\mfr}[1]{\mathfrak{#1}}\newcommand{\Ra}{\Rightarrow}\newcommand{\card}[1]{\left|#1\right|}\newcommand{\powerset}[1]{\mathcal P(#1)}\newcommand{\Lra}{\Leftrightarrow}\newcommand{\Zobr}[3]{#1\colon#2\to#3}$I have no doubt that you there are many useful online resources for these, but many such identities are available here at MSE, together with their proofs.
I'll give a list of some basic results on cardinal arithmetics and I'll add links to results, which have proofs here at MSE. I am making this CW, so feel free to add more identities and pointers to further useful questions and answers.
In the identities below, $a$, $b$, $c$ denote arbitrary cardinals, $X$ is an arbitrary set, $\alnul$ is the cardinality of $\mathbb N$ and $\mfr c=2^{\alnul}$. Cardinality of a set $X$ is denoted by $\card X$ and $\powerset X$ is the notation of the power set of $X$.
Equality of cardinal numbers is defined as follows:
$$|A|=|B| \Lra \text{ there exists a bijection }\Zobr fAB.$$
Inequality of cardinal numbers is defined as follows:
$$|A|\le|B| \Lra \text{ there exists an injective function }\Zobr fAB.$$
The definitions of the operations on cardinal numbers (addition, multiplication, exponentiation) can be found e.g. in this answer.
Validity of Axiom of Choice is assumed. If you want to learn about cardinals without AC, you can have a look e.g. at this question: Defining cardinality in the absence of choice

$a\le b$ $\land$ $b\le c$ $\Ra$ $a\le c$

This follows from the fact that composition of two injective maps is injective

$a\le b \land b\le a \Ra a=b$

This result is known as Schröder–Bernstein theorem. (Also called Cantor–Bernstein theorem or Cantor–Schröder–Bernstein theorem.)

If $A$ and $B$ are sets such that $|A|\le |B|$ and $|B|\le|A|$, then $|A|=|B|$.

The following results says that for any two sets the cardinalities are comparable.

For any two sets $A$, $B$ we have $|A|\le|B|$ $\lor$ $|B|\le|A|$. I.e. any two sets/any two cardinal numbers are comparable.

Note: Proof of this result uses the Axiom of Choice, but it is not required. For the role of AC in this result see here: Is the class of cardinals totally ordered? and For any two sets $A,B$ , $|A|\leq|B|$ or $|B|\leq|A|$ and Proving $(A\le B)\vee (B\le A)$ for sets $A$ and $B$.

$|A|\le|B| \Lra (\text{there exists a surjective function }\Zobr fBA \text{ or $A$ is empty}).$

There exists an injection from $X$ to $Y$ if and only if there exists a surjection from $Y$ to $X$.
Note: Proof of this result uses the Axiom of Choice.

$\card{\powerset X}=2^{\card X}$

See e.g. How to show equinumerosity of  the powerset of $A$ and the set of functions from $A$ to $\{0,1\}$ without cardinal arithmetic? or Finding a correspondence between $\{0,1\}^A$ and $\mathcal P(A)$ or this answer. The question
What is the set of all functions from $\{0, 1\}$ to $\mathbb{N}$ equinumerous to? deals with a special case, but it can be easily generalized.

$a+b=b+a$

This follows simply from commutativity of union: $A\cup B=B\cup A$.

$a+(b+c)=(a+b)+c$

This follows from associativity of union: $A\cup(B\cup C)=(A\cup B)\cup C$.

$b\le c \Ra a+b\le a+c$

This is (after adding some details) basically the same thing as the implication $B\subseteq C$ $\Ra$ $A\cup B\subseteq A\cup C$. See Does $a \le b$ imply $a+c\le b+c$ for cardinal numbers?

$ab=ba$

A bijection $A\times B\to B\times A$ can be given by $(x,y)\mapsto (y,x)$.

$a(bc)=(ab)c$

A bijection between $A\times(B\times C)$ and $(A\times B)\times C$ can be given by $(x,(y,z))\mapsto ((x,y),z)$. See here: A bijection between $X \times (Y \times Z)$ and $ (X \times Y) \times Z$

$a(b+c)=ab+ac$

This follows from the fact that $A\times(B\cup C)=A\times B\cup A\times C$.

$b\le c \Ra  ab\le ac$

See e.g. Proof of cardinality inequality: $m_1\le m_2$, $k_1\le k_2$ implies $k_1m_1\le k_2m_2$ or Will $\kappa_1, \kappa_2, m$ cardinals. Given $\kappa_1 \leq \kappa_2$. prove: $\kappa_1 \cdot m \leq \kappa_2 \cdot m$

$a^2=a\cdot a$

See e.g. this answer

$a\le b \Ra a^c\le b^c$

See e.g. this answer.

$a\le b \land c\ne 0 \Ra c^a\le c^b$

See e.g. this question.
Note that this is not true for $c=0$, since $0^0=1$. (The set $\emptyset^\emptyset=\{\emptyset\}$ has one element.) The set $\emptyset^\emptyset$ and its cardinality is also discussed here.

$a^{b+c}=a^b\cdot a^c$

See e.g. Let $A,B,C$ be sets, and $B \cap C=\emptyset$. Show $|A^{B \cup C}|=|A^B \times A^C|$ and Notation on proving injectivity of a function $f:A^{B\;\cup\; C}\to A^B\times A^C$.

$(a^b)^c=a^{bc}$

See e.g. How to show $(a^b)^c=a^{bc}$ for arbitrary cardinal numbers?

$(ab)^c=a^c\cdot b^c$

See e.g. Equinumerousity of operations on cardinal numbers and How to prove $|{^A}{(K \times L)}| =_c |{^A}{K} \times {^A}{L}|$?

$a^b\le 2^{ab}$

See e.g. this answer

$a<2^a$

This is Cantor's theorem. The question Is the class of subsets of integers countably infinite? deals with the special case $a=\alnul$, but there are answers which discuss the more general result or can be easily generalized. See also Understanding the proof for $ 2^{\aleph_0} > \aleph_0$. This question asks about the general result: Cardinality of a set A is strictly less than the cardinality of the power set of A

$\alnul+\alnul=\alnul$

See e.g. Let $X$ and $Y$ be countable sets. Then $X\cup Y$ is countable

$a\ge\alnul \Ra \alnul+a=a$

$\alnul\cdot\alnul=\alnul$

See e.g. Bijecting a countably infinite set $S$ and its cartesian product $S \times S$, How does one get the formula for this bijection from $\mathbb{N}\times\mathbb{N}$ onto $\mathbb{N}$?,
The cartesian product $\mathbb{N} \times \mathbb{N}$ is countable and Proving the Cantor Pairing Function Bijective
The following result is, to some extent, related to the following:

Union of countably many countable sets is countable.

It is worth mentioning that proof of this uses Axiom of Choice. See Prove that the union of countably many countable sets is countable.

$\alnul^{\alnul}=2^{\alnul}=\mfr c$

See e.g. Is $\aleph_0^{\aleph_0}$ smaller than or equal to $2^{\aleph_0}$? or What is $\aleph_0$ powered to $\aleph_0$? or What's the cardinality of all sequences with coefficients in an infinite set? (One of the answers to this question also discusses powers of the form $\aleph_\alpha^{\aleph_\beta}$ in general.

If $a$ is infinite cardinal, then $a^2=a$.

See e.g. About a paper of Zermelo
Note: Proof of this result uses the Axiom of Choice. See also: For every infinite $S$, $|S|=|S\times S|$ implies the Axiom of choice

If $b$, $c$ are infinite cardinals, then $b+c=bc=\max\{b,c\}$.

See e.g. How to prove that from "Every infinite cardinal satisfies $a^2=a$" we can prove that $b+c=bc$ for any two infinite cardinals $b,c$?
Note: This is a consequence of the preceding result, so it relies on the Axiom of Choice too.
Comment: You have set the bar high for future "Overview" questions!
Comment: I've posted a question at meta about the format of answer I've chosen here. http://meta.math.stackexchange.com/questions/3967/would-organizer-posts-be-useful-wellcome-here
Comment: Do you think that you should mention the use of the axiom of choice, or at least which results holds without it?
Comment: @Asaf: I've added a note mentioning AC. (The last two are the only identities from the list that use AC, right?) To be honest, I am not completely sure about the usual definition of
_cardinal_ and _cardinality_ when we do not assume AC. I should probably read one of your answers on this topic. ;-)
Comment: BTW I was a little surprised that I did not find the proof of $a^2=a$ here. (Maybe we don't have it here, maybe it is somewhere but I did not find it.)
Comment: I wrote that proof: [$a^2=a$](http://math.stackexchange.com/questions/54892/about-a-paper-of-zermelo/54904#54904). Cardinals without choice: [Defining cardinality](http://math.stackexchange.com/questions/53770/defining-cardinality-in-the-absence-of-choice/53771#53771).
Comment: Comparability of cardinals (which, like $a^2=a$, is equivalent to choice) should be here, assuming there's something on math.se to link to.
Comment: Good catch @Chris; thanks. I've added some more stuff about inequality of cardinal numbers and if I find corresponding questions, I'll add links to them, too. I made the question CW, so feel free to improve it.
Comment: Martin, there was a question whether the cardinals are totally ordered. It should be enough to answer Chris' request. I recall that we both answered and yours was accepted.
Comment: @Asaf You mean [this question](http://math.stackexchange.com/questions/69774/is-the-class-of-cardinals-totally-ordered/). The question is more about whether AC is needed for this result, so I've added it to the part about AC.
Comment: Yes. I think that the post can use a reorganization somehow. One day I will sit and do that.
Comment: @Martin: Do you think it might be time for a good revision and addition to this page? I've seen a lot of questions being re-asked (and in some the answers are superior to previous answers).
Comment: @Asaf Feel free to make any improvements you find useful.
Comment: Hi, I'm just here to say this answer is really good, obvious +1.
Comment: If $a_i\lt b_i$ for $i\in I$ then $\sum_{i\in I}a_i\lt\prod_{i\in I}b_i$.


Random row from Linq to Sql

Question: What is the best (and fastest) way to retrieve a random row using Linq to SQL when I have a condition, e.g. some field must be true?
Comment: As with lots of answers on this site - second-rated is much better than the accepted one.
Comment: You have two options for the order you check the true conditions. If the true condition happens on most items then just grab a random item then test and repeat while false. If rare let the database limit the options to the true condition and then grab one at random.
Answer: You can do this at the database, by using a fake UDF; in a partial class, add a method to the data context:
partial class MyDataContext {
     [Function(Name="NEWID", IsComposable=true)]
     public Guid Random()
     { // to prove not used by our C# code...
         throw new NotImplementedException();
     }
}

Then just order by ctx.Random(); this will do a random ordering at the SQL-Server courtesy of NEWID(). i.e.
var cust = (from row in ctx.Customers
           where row.IsActive // your filter
           orderby ctx.Random()
           select row).FirstOrDefault();

Note that this is only suitable for small-to-mid-size tables; for huge tables, it will have a performance impact at the server, and it will be more efficient to find the number of rows (Count), then pick one at random (Skip/First).

for count approach:
var qry = from row in ctx.Customers
          where row.IsActive
          select row;

int count = qry.Count(); // 1st round-trip
int index = new Random().Next(count);

Customer cust = qry.Skip(index).FirstOrDefault(); // 2nd round-trip

Comment: I know this is old, but if you are selecting many random rows from a large table, see this: http://msdn.microsoft.com/en-us/library/cc441928.aspx    I don't know if there's a LINQ equivalent.
Comment: If is it 30k *after* the filter, I'd say no: don't use this approach. Do 2 round-trips; 1 to get the Count(), and 1 to get a random row...
Comment: @Neal S.: the order by ctx.Random() could be mixed with Take(5); but if you are using the Count() approach, I expect 6 round trips is the simplest option.
Comment: What if you want five (or "x") random rows?  Is it best just to make six round-trips or is there a convenient way to implement it in a stored procedure?
Comment: don't forget to add a reference to System.Data.Linq or the System.Data.Linq.Mapping.Function attribute wont work.
Comment: My table has approximately 30.000 rows, would you say it's small-to-mid size?
Comment: +1 This is a much better approach than what I had said.  I nominated mine for deletion.
Comment: Thank you. Based on your comment, il use the 2 round-trip version.
Comment: [sighs happily] Marc Gravell does it again!  What would we do without him?  THANK YOU! :)
Comment: @Shaul probably have better up-time on stackoverflow :p
Comment: @MarcGravell i am trying the 2nd option cause the table has many records, but some records are missing when returned, eg: when `
**first request** count 4
index 1

shows 3 product in view

**second request** count 4
index 2

shows 2 product in view

**third request** count 4
index 3

shows 1 product in view` may i know what i am missing ?
Answer: Another sample for Entity Framework:
var customers = db.Customers
                  .Where(c => c.IsActive)
                  .OrderBy(c => Guid.NewGuid())
                  .FirstOrDefault();

This does not work with LINQ to SQL. The OrderBy is simply being dropped.
Comment: This doesn't workin LINQ to SQL... maybe it works in Entity Framework 4 (not confirming it). You can only use .OrderBy with Guid if you are sorting a List... with DB it won't work.
Comment: Have you profiled this and confirmed that it works? In my tests using LINQPad, the order by clause is being dropped.
Comment: Just to finally confirm that this works in EF4 - it's great option in that case.
Comment: Could you edit your answer and explain why the orderBy with a new Guid  do the trick? Nice answer by the way :)
Comment: This is the best solution to this problem
Answer: EDIT: I've only just noticed this is LINQ to SQL, not LINQ to Objects. Use Marc's code to get the database to do this for you. I've left this answer here as a potential point of interest for LINQ to Objects.
Strangely enough, you don't actually need to get the count. You do, however, need to fetch every element unless you get the count.
What you can do is keep the idea of a "current" value and the current count. When you fetch the next value, take a random number and replace the "current" with "new" with a probability of 1/n where n is the count.
So when you read the first value, you always make that the "current" value. When you read the second value, you might make that the current value (probability 1/2). When you read the third value, you might make that the current value (probability 1/3) etc. When you've run out of data, the current value is a random one out of all the ones you read, with uniform probability.
To apply that with a condition, just ignore anything which doesn't meet the condition. The easiest way to do that is to only consider the "matching" sequence to start with, by applying a Where clause first.
Here's a quick implementation. I think it's okay...
public static T RandomElement<T>(this IEnumerable<T> source,
                                 Random rng)
{
    T current = default(T);
    int count = 0;
    foreach (T element in source)
    {
        count++;
        if (rng.Next(count) == 0)
        {
            current = element;
        }
    }
    if (count == 0)
    {
        throw new InvalidOperationException("Sequence was empty");
    }
    return current;
}

Comment: FYI - I ran a quick check and this function does have a uniform probability distribution (the incrementing count is essentially the same mechanism as the Fisher-Yates shuffle so it seems reasonable that it should be).
Comment: @Greg: Cool, thanks. It looked okay to me with a quick check, but it's so easy to get off-by-one errors in code like this. Virtually irrelevant to LINQ to SQL of course, but useful nonetheless.
Comment: @JonSkeet, hi, can you check [this](http://stackoverflow.com/q/30752514/2218697) and let me know what i am missing
Comment: @TylerLaing: No, there's not meant to be a break. On the first iteration, `current` will *always* be set to the first element. On the second iteration, there's a 50% change that it will be set to the second element. On the third iteration, there's a 33% chance it will be set to the third element. Adding a break statement would mean you'd always exit after reading the first element, making it not random at all.
Comment: @JonSkeet Doh! I misread your use of count (e.g. was thinking this was Fisher-Yates style with a random range like n-i).  But to select the first element in Fisher-Yates is to fairly choose any of the elements.  However, that requires knowing the total number of elements.  I see now that your solution is neat for an IEnumerable in that the total count is not known, and there is no need to iterate over the whole source just to get the count, to then iterate again to some randomly chosen index. Rather this solves in one pass, as you stated: "need to fetch every element unless you get the count".
Comment: Shorthand: `public static T RandomElement(this IEnumerable source, Random rng) => source.Where((x, i) => rng.Next(i + 1) == 0).Last();`
Answer: One way to achieve efficiently is to add a column to your data Shuffle that is populated with a random int (as each record is created).
The partial query to access the table in random order is ...
Random random = new Random();
int seed = random.Next();
result = result.OrderBy(s => (~(s.Shuffle & seed)) & (s.Shuffle | seed)); // ^ seed);

This does an XOR operation in the database and orders by the results of that XOR.
Advantages:-

Efficient: SQL handles the
ordering, no need to fetch the whole
table
Repeatable: (good for
testing) - can use the same random
seed to generate the same random
order

This is the approach used by my home automation system to randomize playlists.  It picks a new seed each day giving a consistent order during the day (allowing easy pause / resume capabilities) but a fresh look at each playlist each new day.
Comment: what would the effect on randomness be if instead of adding a random int field you just used an existing auto-incrementing identity field (the seed would obviously remain random)?  also - is a seed value with a a maximum equal to the number of records in the table adequate or should it be higher?
Comment: Agreed, this is a great answer which IMO should have more upvotes. I used this in an Entity Framework query, and the bitwise-XOR operator ^ seems to work directly thus making the condition a bit cleaner: `result = result.OrderBy(s => s.Shuffle ^ seed);` (ie. no need to implement the XOR via the ~, & and | operators).
Answer: if you want to get e.g. var count = 16 random rows from table, you can write
var rows = Table.OrderBy(t => Guid.NewGuid())
                        .Take(count);

here I used E.F, and the Table is a Dbset
Answer: If the purpose of getting random rows is sampling, I have talked very briefly here about a nice approach from Larson et al., Microsoft Research team where they have developed a sampling framework for Sql Server using materialized views. There is a link to the actual paper also.
Answer: I have random function query against DataTables:
var result = (from result in dt.AsEnumerable()
              order by Guid.NewGuid()
              select result).Take(3);

Answer: Came here wondering how to get a few random pages from a small number of them, so each user gets some different random 3 pages.
This is my final solution, working querying with LINQ against a list of pages in Sharepoint 2010. It's in Visual Basic, sorry :p
Dim Aleatorio As New Random()

Dim Paginas = From a As SPListItem In Sitio.RootWeb.Lists("Páginas") Order By Aleatorio.Next Take 3

Probably should get some profiling before querying a great number of results, but it's perfect for my purpose
Answer: Using LINQ to SQL in LINQPad as C# statements look like
IEnumerable<Customer> customers = this.ExecuteQuery<Customer>(@"SELECT top 10 * from [Customers] order by newid()");
customers.Dump();

The generated SQL is
SELECT top 10 * from [Customers] order by newid()

Answer: The example below will call the source to retrieve a count and then apply a skip expression on the source with a number between 0 and n. The second method will apply order by using the random object (which will order everything in memory) and select the number passed into the method call.
public static class IEnumerable
{
    static Random rng = new Random((int)DateTime.Now.Ticks);

    public static T RandomElement<T>(this IEnumerable<T> source)
    {
        T current = default(T);
        int c = source.Count();
        int r = rng.Next(c);
        current = source.Skip(r).First();
        return current;
    }

    public static IEnumerable<T> RandomElements<T>(this IEnumerable<T> source, int number)
    {
        return source.OrderBy(r => rng.Next()).Take(number);
    }
}

Comment: Some explanation would be nice
Comment: This code is not threadsafe and can only be used in single threaded code (so **not** ASP.NET)
Answer: i use this method for take random news and its work fine ;)
    public string LoadRandomNews(int maxNews)
    {
        string temp = "";

        using (var db = new DataClassesDataContext())
        {
            var newsCount = (from p in db.Tbl_DynamicContents
                             where p.TimeFoPublish.Value.Date <= DateTime.Now
                             select p).Count();
            int i;
            if (newsCount < maxNews)
                i = newsCount;
            else i = maxNews;
            var r = new Random();
            var lastNumber = new List<int>();
            for (; i > 0; i--)
            {
                int currentNumber = r.Next(0, newsCount);
                if (!lastNumber.Contains(currentNumber))
                { lastNumber.Add(currentNumber); }
                else
                {
                    while (true)
                    {
                        currentNumber = r.Next(0, newsCount);
                        if (!lastNumber.Contains(currentNumber))
                        {
                            lastNumber.Add(currentNumber);
                            break;
                        }
                    }
                }
                if (currentNumber == newsCount)
                    currentNumber--;
                var news = (from p in db.Tbl_DynamicContents
                            orderby p.ID descending
                            where p.TimeFoPublish.Value.Date <= DateTime.Now
                            select p).Skip(currentNumber).Take(1).Single();
                temp +=
                    string.Format("
" +
                                  "{1}
",
                                  news.ID, news.Title);
            }
        }
        return temp;
    }

Answer: If you use LINQPad, switch to C# program mode and do this way:
void Main()
{
    YourTable.OrderBy(v => Random()).FirstOrDefault.Dump();
}

[Function(Name = "NEWID", IsComposable = true)]
public Guid Random()
{
    throw new NotImplementedException();
}

Answer: var cust = (from c in ctx.CUSTOMERs.ToList() select c).OrderBy(x => x.Guid.NewGuid()).Taket(2);

Select random 2 row
Answer: To add to Marc Gravell's solution. If you are not working with the datacontext class itself (because you proxy it somehow e.g. to fake the datacontext for testing purposes), you cannot use the defined UDF directly: it will not be compiled to SQL because you're not using it in a subclass or partial class of your real data context class.
A workaround for this problem is to create a Randomize function in your proxy, feeding it with the query you want to be randomized:
public class DataContextProxy : IDataContext
{
    private readonly DataContext _context;

    public DataContextProxy(DataContext context)
    {
        _context = context;
    }

    // Snipped irrelevant code

    public IOrderedQueryable<T> Randomize<T>(IQueryable<T> query)
    {
        return query.OrderBy(x => _context.Random());
    }
}

Here is how you'd use it in your code:
var query = _dc.Repository<SomeEntity>();
query = _dc.Randomize(query);

To be complete, this is how to implement this in the FAKE datacontext (which uses in memory entities):
public IOrderedQueryable<T> Randomize<T>(IQueryable<T> query)
{
    return query.OrderBy(x => Guid.NewGuid());
}

Random row from Linq to Sql


Protein interaction prediction- how to input this data structure

Question:
I know the basics of machine learning and have quite an experience with time series data or data fed in a tabular format. But in the picture, the data is arranged as a graph. Is there a way to input the graph into a ML tool such as Artificial Neural Network or any other? I don't know if there is a theory for handling such data structure. The task is to recreate the graph from the output of the ML algorithm after training. So, whatever input I get, the output should be the same as the input -- quite similar to an auto-associative memory. Can somebody please help?
Comment: See this paper: https://arxiv.org/abs/1812.00085.
Answer: https://en.wikipedia.org/wiki/Adjacency_matrix

For such problems, you can tabulate these connections as adjacency matrix and create a network to predict weights for the matrix given some properties of nodes (Say for a social graph; given properties of User1 and User2 [for example Zipcode, school ...] output 1, or 0),
Some examples are :
https://www.biorxiv.org/content/biorxiv/early/2018/01/14/247577.full.pdf
http://kawahara.ca/convolutional-neural-networks-for-adjacency-matrices/
Edit : Illustration of Train_X and Train_Y

Columns A through H form Train_X and Column I is Train_Y.
Comment: Thank you for your answer and the links to the papers. But one thing is unclear could you please clarify? In the papers, the authors use CNN and the input is an image of the adjacency matrix. But how to include the properties of nodes as inputs along with adjacency matrix to CNN as you have mentioned in your answer? Should the properties of the nodes be included in the adjacency matrix? Can you please elaborate on the social network example, on what basis you gave labels.
Comment: Lastly, is this method applicable when the graph models traffic
flow as signals on vertices of a graph? The graphs for protein is static in nature....I believe no signal in transmission but for brains, there are signals transmitted.
Comment: Input to the model will be a set of rows. Each row will have all properties of two nodes and a binary output [Output 1 if nodes are connected, otherwise not]. With this train_x and train_y, I would experiment with CNN as well as a all dense layers.


Importing album art from ripped music

Question: I have over 130+ artists with 1000s of tracks all sorted and with valid metadata externally to the Music / iTune app on my Mac (Catalina).  The folder layout is Artist / Album / CD in Album (ranges 1-12 currently) / Tracks (e.g. 01 - Composer - Track Name.p4a)
When I import the artist / track, Music does not apply the artwork even though its in the track metadata and stored as Folder.jpg in the source folder.  The latter works on a couple of music players and Volumio on the Raspberry under the TV :-)
I'm happy to delete the whole Mac music library and start again if needed.
Though I can, if needed, hack around in Python, I'm not an Apple script creator.
I could go through the whole lot and manually link the jpg to the album but does anyone know of an easier way?
Answer: Turns out if you leave it about 20 minutes and exit out of Music and go back in it sorts itself.

Importing album art from ripped music


How to access port number of a TCP connection (for coding) from a kernel source code?

Question: I am trying to write a congestion control algorithm (like TCP cubic, reno) in net/ipv4/ folder. For that, I want to use the established TCP connection port number in the code. How to get a port number from any linux kernel files for the code.
Answer: Use htons((unsigned short int)inet_sk(sk)->inet_sport) and htons((unsigned short int)inet_sk(sk)->inet_dport) to get ports as per Wireshark port.