How to know wether Intel SGX DCAP is installed

Question: How should I know if Intel SGX DCAP is installed or not? the server is running ubuntu 20.4.
Is there a way to check this?
Answer: SGX driver should be already installed on >5.11 Linux Kernel, while DCAP is supported by >8th generation Intel processors, as well as Flexible Launch Control. This is how you check:
╰─➤  ls -ltr /dev/sgx*
     crw------- 1 root root    10, 124 Oct  3 16:30 /dev/sgx_vepc
     crw-rw---- 1 root sgx_prv 10, 126 Oct  3 16:30 /dev/sgx_provision
     crw-rw---- 1 root sgx     10, 125 Oct  3 16:30 /dev/sgx_enclave

     /dev/sgx:
     total 0
     lrwxrwxrwx 1 root root 16 Oct  3 16:30 provision -> ../sgx_provision
     lrwxrwxrwx 1 root root 14 Oct  3 16:30 enclave -> ../sgx_enclave

Comment: which line indicates DCAP?
Answer: Do the following:
apt list --installed | grep dcap

You should see something like this:
sgx-dcap-pccs/unknown,now 188.8.131.52-focal1 amd64 [installed]


How to get websocket session on service?

Question: I have a service called UserMediator that has a method to retrieve all users on the database that the session user has access.
<code>@Service
@Scope(scopeName = "websocket", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class UserMediator {

    @Autowired
    private UserService userSerivce;

    pulibc Collection<User> getAllUsers() {
        Session session = someMethodToGetTheCurrentSessionFromThisService();
        return userService.getAllUsersThatYouAreAllowedToSee(session);
    }

}
</code>
I know that, using websocket scope, one instance of this service will be created for each websocket session, so, there must be a way to retrieve the session that created this bean, i think.

One way to do that is to redefine getAllUsers() to getAllUsers(StompHeaderAcessor ha) and get the session using this header acessor, but this not seems to be the proper solution for me.
Is there any way to get the current websocket session in a websocket scoped service without passing it explicity by arguments?
Comment: Check this if it helps - https://www.devglan.com/spring-boot/spring-session-stomp-websocket
Answer: Solved this issue by creating a SessionHolder service:
<code>@Service
@Scope(scopeName = "websocket", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class SessionHolder {

    private User user = null;

    @Autowired
    public SessionHolder(SimpMessagingTemplate template) {
        this.template = template;
    }

    @EventListener(SessionConnectedEvent.class)
    public void handleSessionConnected(SessionConnectedEvent event) {
        if (user == null && event.getUser() != null) {
            StompHeaderAccessor ha = StompHeaderAccessor.wrap(event.getMessage());
            user = SessionUtils.getUser(ha);
        }
    }

    public User getUser() {
        return user;
    }

}
</code>


How to define the weighted average of two functions?

Question: Let $A=\{a_1,a_2,a_3\}$ and $B=\{b_1,b_2,b_3\}$ be two sets, and let
\begin{gather}
\Delta(B)=\left\{\delta\in[0,1]^B\mid\sum_{b\in B}\delta(b)=1\right\}
\end{gather}
be the set of all lotteries over the set $B$. Further, let $f:A\to\Delta(B)$ and $g:A\to\Delta(B)$ be two functions satisfying $f\neq g$. Then, define the function $h:A\to\Delta(B)$ as follows:
\begin{gather}
h=(2/3)f+(1/3)g
\end{gather}
I have three questions regarding such a construction:

Is the function $h$ a legitimate construction?
If it is, does it really have domain $A$?
If it is, is the function $h$ as previously defined equivalent to defining it as
\begin{gather}
    (\forall a\in A)[h(a)=(2/3)f(a)+(1/3)g(a)]
\end{gather}
Answer: Short answer. Yes.
(3) is the way you define the sum of functions.
Your notation is correct but much more formal than necessary.
The straightforward way to describe this situation is to say that a convex combination of probability distributions is a probability distribution.
Comment: You are right. I was confused by your too elaborate formal definition of "lottery". You should just have called them probability distributions. I will edit my answer.
Comment: Thank you very much for your answer. While I understand your short answer, I don't really understand your full explanation. First, why will the codomain of $h$ be the set of functions on subsets of B? Second, why if a function has value other than $0$ or $1$ will not be a lottery? As I defined them, lotteries are just probability distributions. Could you please elaborate further?


Import error in django

Question: I have two files within the same folder (app) feed.
models.py
from django.db import models
from .managers import FeedManager

class Feed(models.Model):
    #fields for my model

managers.py
from django.db import models

from .models import Feed

class FeedManager(models.Manager):
    def get_queryset(self, *args, **kwargs):
        return super(FeedManager, self).get_queryset(*args, **kwargs)

I get the following error when I run the server:
      Unhandled exception in thread started by <function wrapper at 0x04064370>
Traceback (most recent call last):
  File "C:\Users\Sumit\Desktop\django\venv\lib\site-packages\django\utils\autoreload.py", line 229, in wrapper
    fn(*args, **kwargs)
  File "C:\Users\Sumit\Desktop\django\venv\lib\site-packages\django\core\management\commands\runserver.py", line 107, in inner_run
    autoreload.raise_last_exception()
  File "C:\Users\Sumit\Desktop\django\venv\lib\site-packages\django\utils\autoreload.py", line 252, in raise_last_exception
    six.reraise(*_exception)
  File "C:\Users\Sumit\Desktop\django\venv\lib\site-packages\django\utils\autoreload.py", line 229, in wrapper
    fn(*args, **kwargs)
  File "C:\Users\Sumit\Desktop\django\venv\lib\site-packages\django\__init__.py", line 18, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "C:\Users\Sumit\Desktop\django\venv\lib\site-packages\django\apps\registry.py", line 108, in populate
    app_config.import_models(all_models)
  File "C:\Users\Sumit\Desktop\django\venv\lib\site-packages\django\apps\config.py", line 198, in import_models
    self.models_module = import_module(models_module_name)
  File "C:\Python27\Lib\importlib\__init__.py", line 37, in import_module
    __import__(name)
  File "C:\Users\Sumit\Desktop\django\network\feed\models.py", line 7, in <module>
    from .managers import FeedManager
  File "C:\Users\Sumit\Desktop\django\network\feed\managers.py", line 3, in <module>
    from .models import Feed
ImportError: cannot import name Feed

Why am I getting this error and how do I fix this ?
Comment: You're facing circular import issue. Remove the `.models import Feed` from the top of your `managers.py` file, and you'll be good to go. Whenever you need the model, you can import it inside the manager function itself.
Answer: You've introduce introduced a circular import: models module depends on managers module which in turn depends on the models module.
Neither of the modules can be resolved since their dependency cannot be resolved. Try re-organizing your modules.

Import error in django


Nash equilibrium: comparing different definitions

Question: A Nash equilibrium seems to be defined in different ways in different books. Sometimes a Nash equilibrium refers to a single strategy (Definition $1$ below) and sometimes a Nash equilibrium is defined for a pair of strategies (Definition $2$ below).
Definition $1$: A strategy $\mathbf{p}$ is a Nash equilibrium if it is a best reply to itself (e.g., Hofbauer and Sigmund Evolutionary Games and Population Dynamics, p. 62.)
Definition $2$: The pair $(\mathbf{p}, \mathbf{q})$ is a Nash equilibrium if $\mathbf{p}$ is a best response to $\mathbf{q}$ and $\mathbf{q}$ is a best response to $\mathbf{p}$ (e.g., Broom and Rychtar Game theoretical models in biology).
My question is this. How are these definitions related? What is the definition of Nash equilibrium that is used by the Nash existence theorem$?$

Further comments:

I initially thought that the Definition 1 is a particular case of the Definition 2 for symmetric games, but I don't think this is true. For instance, consider a symmetric $2\times 2$ game with payoff matrix:

$$\begin{array}{ccc}
    & A & B\\
    A& a & b\\
    B& c & d
  \end{array}
$$
where $a<c$ and $b>d$. According to Definition 1, neither $A$ nor $B$ is a Nash equilibrium (because neither $A$ nor $B$ are a best reply to itself). But according to Definition 2, the pairs $(A,B)$ and $(B,A)$ are Nash equilibria.

Sometimes, Nash equilibrium is still defined in another way (as A. Sh. pointed out, this is a generalization of Definition 2 for n players):

Definition $3$: A Nash equilibrium is a strategy profile in which every player is playing a best response to the current strategy profile.
The above definition appears in Gintis Game Theory Evolving, p. 43. It is also the definition that appears in the Wikipedia article on Nash equilibrium: https://en.wikipedia.org/wiki/Nash_equilibrium#Formal_definition
Comment: I checked it out, but didn't get too much wiser. I did however realize that if they mean that $(p,p)$ is a Nash equilibrium, then $p$ is of course a best reply to itself. For an arbitrary NE though, falsum's example sure breaks that definition. I think the authors might be a bit sloppy in their notation in using definition 1? (Why else call a strategy an equilibrium, that doesn't type-check at all…)
Comment: How would a single strategy (as per definition 1) also be an equilibrium? I have only encountered the second definition (and its extensions to several players) so far. Maybe definition 1 applies in one-person games?
Comment: @A.Sh The cases that I've seen the Definition 1 being applied are for symmetric two-player games.
Comment: Ok, then I believe it is safe to assume that definition 1 is a simplification for that particular scenario, although I cannot see why it holds water at the moment. However, definition 2 is the standard, and is the one used in the existence theorem, and that should answer your question.
Comment: @A.Sh I thought that the Definition 1 could be derived from Definition 2 once we assume that we are dealing with symmetric games. But I think they give different answers for symmetric games. I added an example to my question to explain why I think so.
Comment: Be more precise about the context of the first definition. Is it really given as a Definition in the textbook (I do not have it unfortunately) or as a *sufficient* condition (but *not necessary*) for a strategy to be used in a Nash equilibrium of a symmetric game? Clearly the second definition is the correct one, but the first one has to be also correct in the context used by the author (because textbook - authors never make mistakes :))
Comment: @Stef This is a great point. Hofbauer and Sigmund say that a Nash equilibrium "is a strategy which is a best reply to itself." So I believe that this being the best reply to itself is at least a sufficient condition for being a Nash equilibrium. I added the page number in case someone wants to check it out.
Comment: Regarding that third definition, it reduces to definition 2 in the case of 2 players, it's just a definition that admits arbitrary numbers of players.
Comment: @A.Sh Hmmm It seems to be that the Definition 2 is considering the payoff for both players, whereas the Definition 3 is only considering the payoff of a single player. Am I missing something?
Comment: Never mind. The definition is for every player $i$. My bad.
Answer: Definition 3 is the correct definition of Nash equilibrium of a general $n$-player game.
Definition 2 is a special case of Def 3 in a general $2$-player game.
Definition 1 is the definition of a Symmetric Nash equilibrium in a $2$-player game. And note that Symmetric Nash equilibrium is a proper subset of Nash equilibrium, and so strictly speaking, Def 1 should not be taken as a definition of Nash equilibrium.
Answer: The first definition refers to a special case of a symmetric game. The second one is more general and is a standard one, as far as I know.


Prove that $\lim a_{n}=e$?

Question:
Given that $a_{1}=0$, $a_{2}=1$ and
  $$a_{n+2}=\frac{(n+2)a_{n+1}-a_{n}}{n+1}$$
  prove that $\lim\limits_{n\to\infty} a_n=e$

What I did:
It was hinted to prove that $a_{n+1}-a_{n}=\frac{1}{n!}$ which I did inductively.
But then using this information now I get:
$a_{n+1}=a_{1}+\frac{n}{n!}=\frac{1}{(n-1)!}$ so $a_{n}=\frac{n-1}{n!}$.
Now $a_{n}$ is bounded above by $\sum_{k=0}^{n}\frac{1}{k!}$ which converges to $e$. I can't find a lower bound that converges to $e$ as well. I'm starting to think I was supposed to go about this differently.
Thanks in advance.
Comment: You wrote $a_{n+1}=a_n+\frac{1}{n!}$, then just kept decreasing the index of $a_n$ while adding on $\frac{1}{n!}$s. But as the index decreases, the thing you add on needs to change too. For instance, $$a_4=a_3+\frac{1}{3!}=a_2+\frac{1}{2!}+\frac{1}{3!}=a_1+\frac{1}{1!}+ \frac{1}{2!} +\frac{1}{3!}. $$
Comment: Also, either it should state $a_0=0$ and $a_1=1$, or else the limit should be $e-1$.
Answer: Instead, you should have got:
$$a_{n+1} = a_n + \frac1{n!} = a_{n-1} + \frac1{(n-1)!} + \frac1{n!}= \cdots = a_1  + \frac1{1!} + \frac1{2!} + \cdots + \frac1{(n-1)!} + \frac1{n!}$$
i.e.
$$a_{n+1} = \sum_{k=1}^n \frac1{k!} = \sum_{k=0}^n \frac1{k!} - 1$$
Hence, the limit is actually $e - 1$.
If, instead, the sequence was defined as $a_0 = 0$ and $a_1 =1$, then the limit would have been $e$ (by the same reasoning as above).
Comment: Thank you! Just one question though: shouldn't it be $a_{n+1} = \sum_{k=1}^n \frac1{k!}$ instead?
Comment: @John11 you're welcome; no, but there was a typo and I fixed it
Comment: @John11 actually, no you are right and the current version does not answer the question as it is posed. But for the result to be correct anyway, it should've been $a_0 = 0$ and $a_1 = 1$.
Comment: Ok because otherwise it converges to $e-1$?
Comment: @John11 yes. I'll add that.
Answer: Now you can use induction to show that $\displaystyle a_n=1+\frac{1}{2!}+\frac{1}{3!}+\cdots+\frac{1}{(n-1)!}$,
so then $\displaystyle\lim_{n\to\infty}a_n=\sum_{k=1}^{\infty}\frac{1}{k!}=\color{red}{e-1}$

Prove that $\lim a_{n}=e$?


functional reason why stored procedures don't support INSERT/EXECUTE INTO?

Question: In SQL Server, there's no way to create a temp table on the fly from the results of a stored procedure, ala:
CREATE TABLE #temptable AS
EXEC spMyStoredProc

or
EXEC spMyStoredProc INTO #temptable

or something like that. Instead, you have to know the SP layout beforehand, and have to do something like this:
CREATE TABLE #temptable (col1 INT, col2 VARCHAR(255))

INSERT INTO #temptable
EXEC spMyStoredProc

Is there a functional reason why this is the case? Maybe a limitation of SQL Server? Or is it just something that hasn't been added to the SQL spec yet, and I can hold out hope that one day they'll support it?
Comment: Please use "sql-server" tag...
Answer: A stored procedure can return many result sets, or none, and it can vary entirely depending upon the execution of the stored procedure.
When it is compiled it's meta-information does not describe it as having any specific expectable result set output.
I expect given those constraints, they elected not to implement this because of the lack of strong typing of what a stored procedure may return.
Comment: I can see why they wouldn't implement this, but there are a number of ways to get the return schema of an SP in VB or C#, so I'd think the same thing would apply here. I suppose an unpredictable result table format is less than ideal, but it still seems like something you should be able to do, since there are many other, less-predictable, things you're allowed to do in T-SQL. Anyway, thanks for your insight!
Comment: Cool - no probs, you have to remember though the behaviour and initial implementation goes way back to 1995 and before when Microsoft bought the Sybase source code.

Back in the day what you are talking about was a little bit more labour when you are writing it in C rather than a higher level language like .NET or VB!

Hence minimalistic restrictions like this! :)
Answer: Not from a sproc, but you can use tabled values functions to do something similar.
Select * From fnMyFunction

You'd be able to insert into a # table if you desired.
Comment: Fair enough. I'll leave the answer tho incase it helps a future googler.
Comment: I've used table-based UDFs before, but they don't support a number of things that SPs do, like making decisions based on the date. And if an existing system is built with SPs, there's nothing I can do about that. I've just always wondered why SPs don't support the exact thing you're describing with UDFs.
Comment: I'm not sure what the general consensus is, but I'm almost never in favor of deleting an answer - even if it doesn't help me, it's bound to help somebody in the future. Thanks for your input, especially since it's more a head-scratcher for me than looking for an actual solution, since I don't think one exists.
Answer: Try this out
DECLARE @temptable TABLE (ID INT, NAME VARCHAR(255))

declare @query varchar(max)

set @query='Select whatever from whereever'

INSERT INTO @temptable

EXEC (@Query)

select *from @temptable

Answer: If I needed such functionality I would use an inline UDF, like this:
CREATE PROCEDURE MySample
AS
SELECT a,b,c FROM dbo.MyInlineUDF(1,2,3)
GO

SELECT * INTO #t
FROM dbo.MyInlineUDF(1,2,3) WHERE 1=0

INSERT INTO #t EXEC MySample


Content type with multiple different flavours

Question: I want to create content type (document) with title, comment and file attachment (PDF or doc). I don't want to create different content types (for each document type form, policy, abuse etc..) because if i need to add/remove/change field in it it's need to be repeated on all content types. I'm thinking about taxonomy but I'm not sure.
What's the best solution for one content type with multiple different "flavours"?
Answer: You can use taxonomy to categorize the content. If you want categorize the content like form, policy, abuse etc... create a taxonomy vocabulary name as Document Type then add form, policy, abuse etc... as terms in it. Then Add a term reference field(in D7) in manage field settings. And also you can use Conditional Fields for display fields according to the document type.
Answer: An alternate method of accomplishing this result would be to use Panels, and use taxonomy (or some other field) to display or hide parts of the panel, which may include fields or related views, as appropriate.


Two questions involving Bayes Theorem

Question:
You draw two balls from one of three possible large urns, labelled A,
  B, and C. Urn A has 1/2 blue balls, 1/3 green balls, and 1/6 red
  balls. Urn B has 1/6 blue balls, 1/2 green balls, and 1/3 red balls.
  Urn C has 1/3 blue balls, 1/6 green balls, and 1/2 red balls. With no
  prior information about which urn your are drawing from, you draw one
  red ball and one blue ball. What is the probability that you drew from
  urn C?

So I know Bayes Theorum is this:
On a high level, could I take the probability of drawing one red ball and one blue ball from Urn C and divide that by the total probabality of drawing one blue ball and one red ball from all the urns summed up?
The numerator would be $\frac{1}{2} * \frac{1}{3}$ right? The denominator would the the probabilities of drawing a blue and red from all the urns summed up right?

In the NFL, a professional American football league, there are 32
  teams, of which 12 make the playoffs. In a typical season, 20 teams
  (the ones that don't make the playoffs) play 16 games, 4 teams play 17
  games, 6 teams play 18 games, and 2 teams play 19 games. At the
  beginning of each game, a coin is flipped to determine who gets the
  football first. You are told that an unknown team won ten of its coin
  flips last season. Given this information, what is the posterior
  probability that the team did not make the playoffs (i.e. played 16
  games)?

I have no idea how to approach this one. Can someone shed some insight?
Comment: Please check http://stats.stackexchange.com/tags/self-study/info and edit your question accordingly to homework-like questions policy we have.
Comment: I added some more work. I'm genuinely stuck on the second.
Answer: I'll answer your second question.
First, lets let $H$ be the event that the team did not make the playoffs and $E$ be the event that the team won 10 coin flips in the season.  So we want to know $P(H|E)$ which is equal to $\frac{P(E|H)P(H)}{P(E|H)P(H) + P(E|\neg H)P(\neg H)}$.
We know that $P(H) = 20/32$ and $P(\neg H) = 12/32$.  Furthermore, $P(E|H) = \binom{16}{10}(0.5)^{16} $ since knowing $H$ means we know the team only played 16 games, and out of 16 flips there are 10 successes.
Next, we need to tackle $P(E|\neg H)$.  Let $A$ be the event that the team played 17 games, let $B$ be the event that the team played 18 games, and let $C$ be the event that the team played 19 games.  Then by the law of total conditional probability, we have $$P(E|\neg H) = P(E|A, \neg H)P(A|\neg H) + P(E|B, \neg H)P(B|\neg H) + P(E|C, \neg H)P(C|\neg H).$$  Since $\neg H$ is the event of making the playoffs, we know that $P(A|\neg H) = 4/12$, $P(B|\neg H) = 6/12$, and $P(C|\neg H) = 2/12$.  Also, $P(E|A, \neg H) = \binom{17}{10}(0.5)^{17}$, $P(E|B, \neg H) = \binom{18}{10}(0.5)^{18}$, and $P(E|C, \neg H) = \binom{19}{10}(0.5)^{19}$, using the same logic as for $P(E|H)$.
So, our final answer is
$$P(H|E) = \frac{\binom{16}{10}(0.5)^{16} \frac{20}{32}}{\binom{16}{10}(0.5)^{16} \frac{20}{32} + \left(\binom{17}{10}(0.5)^{17}(\frac{4}{12})  + \binom{18}{10}(0.5)^{18}(\frac{6}{12}) + \binom{19}{10}(0.5)^{19}(\frac{2}{12})\right) \frac{12}{32}}$$$$ \approx 0.556.$$
Comment: Welcome djr! Nicely structured and thorough answer, but somewhat incorrect. You assumed that the probabilities for A, B, C all are equal to 12/32 - how is this possible? You can repare this by using the probabilities given in the problem directly, and not considering ¬H, so P(A)=4/32, P(B)=6/32, P(C)=2/32. Only condition E on A, B, or C, not on ¬H.
Comment: Thank you Ute!  If I'm understanding the law of total expectation correctly though, I think my answer would be correct if I corrected $P(A|\neg H) = 4/12$, $P(B|\neg H) = 6/12$ and $P(C|\neg H) = 2/12$.  Do you agree?  I didn't assume that the probabilities for $A$, $B$, and $C$ are equal to 12/32, I just substituted in for $P(\neg H)$.
Comment: Yes, these are the conditional probabilities, and you would need to multiply with 12/32 afterwards. It is an extra conditioning step, that could be avoided, because H, A, B and C are mutually disjoint events, and their probabilities add to 1. But if you are more comfortable with conditional probabilities than with a Bayes formula with more than two events in the denominator, just stick to your old plan :-)
Comment: Great, thank you for the clarification!
Comment: Looks good now (+1) :-)
Answer: So I'll give two answers one for each question. Let's first discuss the first question and then in a separate answer I will attempt to answer the second question(this might take a while because I have some other things to do :)).
So first lets expand bayes theorem and then we will consider what this means.
So want $P(drew from C|red, blue)=\frac{P(red ,blue|drew from C)P(drew from C)}{P(red ,blue|drew from C)P(drew from C)+ P(red ,blue|drew from A)P(drew from A)+P(red ,blue|drew from B)P(drew from B)}$
Technically we do not know $P(drew from A),P(drew from B),P(drew from C)$! So technically we cannot calculate this chance. But we can make a reasonable assumption and that is that $P(drew from A)=P(drew from B)=P(drew from C)=\frac{1}{3}$. Now to determien all the other terms lets start with $P(red ,blue|drew from C)$ now we assume these are independent chances e.g. If I pick blue first the chance of blue stays the same for the second choice (which would in real life not be true) than the chance of $P(red ,blue|drew from C)=(\frac{1}{3} \frac{1}{2}+\frac{1}{2} \frac{1}{3})=\frac{1}{3}$ remember that not only red, blue counts but also blue ,red thus we should count both possibilities.  the other probabilities can be calculated in a similar way. so that $P(drew from C|red, blue)=\frac{\frac{1}{3}\frac{1}{3}}{\frac{1}{3}\frac{1}{3}+ 2\frac{1}{2}\frac{1}{6}\frac{1}{3}+2\frac{1}{3}\frac{1}{6}\frac{1}{3}}=0.428$ (approximately)
Answer: Below are two methods. The first uses Bayes' Theorem in full, and the second is a quicker approach (just for fun). Importantly, the two results agree! (They also do not agree with the earlier answer posted by zen...)
$X := \text{Picked Red and Blue}$, $A := \text{Picked Urn A}$, $B := \text{Picked Urn B}$, $C := \text{Picked Urn C}$.

Method 1.
Using Bayes' Theorem, we now compute as follows:
$$\frac{P(X|C)P(C)}{P(X|C)P(C) + [P(X|A)P(A) + P(X|B)P(B)]}$$
where the bracketed portion in the denominator corresponds to the cases in which red and blue were selected but did not come from Urn C.
Under the assumption that each of $P(C)$, $P(A)$, and $P(B)$ is $1/3$, we can cancel this factor from the numerator and denominator to get:
$$\frac{P(X|C)}{P(X|C) + [P(X|A) + P(X|B)]}$$
Next, we calculate each of these terms:
$P(X|C) = 2(3/6)(2/5) = 12/30$;
$P(X|B) = 2(2/6)(1/5) = 4/30$; and
$P(X|A) = 2(1/6)(3/5) = 6/30$.
And so the earlier expression becomes:
$$\frac{12/30}{12/30 + 4/30 + 6/30} = \frac{12}{12+4+6} = \frac{6}{6+2+3} = \frac{6}{11}$$

Method 2.
Without loss of generality, let us suppose each of the urns contains exactly six M&Ms. Then, the number of ways to choose a red and blue M&M from the urns can be computed as follows.
Urn A: BBBGGR; so, picking RB can be done in $1 \cdot 3 = 3$ ways.
Urn B: GGGRRB; so, picking RB can be done in $2 \cdot 1 = 2$ ways.
Urn C: RRRBBG; so, picking RB can be done in $3 \cdot 2 = 6$ ways.
So the probability of it being Urn C given that RB were selected is just:
$$\frac{6}{6+3+2} = \frac{6}{11}$$
as in Method 1.
Comment: It was not clear to me that the statement "having no prior information about  which urn you are drawing from".  I read it as the prior probabilities for P(A), P(B) and P(C) were unknown and not they were equal.  That would make the problem unsolvable.  If you take it to mean prior to drawing the ball the choice of urn is equally likely, in which case P(C|X) can be determined.
Comment: How do you get $P(X|c)=2(3/6)(2/5)$? shouldn't it be $P(X|c)=2(3/6)(2/6)$ ? It is not given that there are 6 balls in the urns right? why then say that the chance of getting a blue is now $(2/5)$ instead of $(2/6)$?
Comment: For example try to calculate the chance of picking (blue ,blue ,blue ,blue,blue,blue,blue)  from urn C by either of your methods. I think you implicilty assume there are 6 balls.
Answer: So for the second question I will just offer some help in the form of tips after which I hope you will understand it. tip 1: consider all teams equal so and calculate the chance that $P(played 16 games)=\frac{20}{32}$. 2. then see that the concitional probability your looking for is $P(played 16 games|coin wins =10)$
3. $P(coin wins =10 |played 16 games)$ is binomially distributed with (n=16,p=0.5) and X=10 ( or k=10 in wiki notation).

Two questions involving Bayes Theorem


Is there any way to making transition without storyboard?

Question: I tried making transition animation for changing between two viewController. Is there any way to make that without using storyboard?
This code for calling new viewController (which I didn't use storyboard):
 @objc func handleAccount() {
    let navController = UINavigationController(rootViewController: userButtonLauncher())
    navController.transitioningDelegate = self
    navController.modalPresentationStyle = .custom
    self.present(navController, animated: true, completion: nil)
}

And this codes for transition:
    func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
    transition.transitionMode = .present
    transition.startingPoint = CGPoint(x: 0, y: 0)
    return transition
}

func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
    transition.transitionMode = .pop
    transition.startingPoint = CGPoint(x: 0, y: 0)
    return transition
}

Comment: try searching `push viewController programmatically`
Comment: Hi Lu, I already tried push viewController but I think transition page cover viewController. When I wrote                                                                                'let navController = UINavigationController(rootViewController: userButtonLauncher())
        navController.transitioningDelegate = self
        navController.modalPresentationStyle = .custom
        self.present(navController, animated: true, completion: nil)' . UserButtonLauncher under the transition page. I see only blank page.
Answer: I solve my problem. I just add that code for calling animation transition in my homecontroller:
extension HomeController: UIViewControllerTransitioningDelegate {
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
    return faceanim()

}
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
    return faceanim()

}

}
And to button action is:
    @objc func handleAccount() {

    let userConVC = UINavigationController(rootViewController: userButtonLauncher())
    userConVC.transitioningDelegate = self
    navigationController?.isNavigationBarHidden = false
    self.present(userConVC, animated: true, completion: nil)

}

Comment: Please, mark this as resolved so others can quickly find the solution. Thanks!
Answer: Of course you can! It depends on what you would like to do, so if you need to use the defaults animation on code without using storyboard you can just:
instantiate your ViewController, set the animation you want and open the ViewController
let vc = self.storyboard?.instantiateViewController(withIdentifier: "vc_id")
vc.modalTransitionStyle = .flipHorizontal
self.present(vc, animated: true, completion: nil)
Otherwise you can create your custom transition, see this easy guide:
https://www.raywenderlich.com/322-custom-uiviewcontroller-transitions-getting-started
Comment: Thanks for answer Marcoc. I'm new in swift I tried a lot of thing to do that but I can't find any way. If I ask more clearly I write CircularTransition.swift but I didn't use segue so I call second viewController with navigationController code but transitionDelegate and modalTransitionStyle codes cover my second controller I think. I don't know did I explain properly ?
Comment: No problem! I suggest you to update your question with some code of your project, so it's easier to help you. Anyway try to comment the transitionDelegate line and see if it still covered or not please
Comment: I tried to edit my question. I hope I will explain my question more clearly. Thank you for your help!
Comment: thank you! from where do you call handleAccount ?  from the transition class?
Comment: Actually I can't call handleAccount in my transition class because I created circle as UIView(). I can't find way to call that function in transition class. Is there any way to call?
Comment: Did you try to comment the transitioningDelegate line?


Panels Custom Context

Question: I have created a Panels Everywhere variant that uses a single View with a contextual filter (Content Type). The Panel variant is set to page paths. These paths are related to content types. For example:
Path:
drivers (list of 'driver' Content Type)
lawyers (list of 'lawyer' Content Type)

So if I go to /drivers the Context of Content Type 'driver' should be passed to the View, etc. I know this is possible as %user context is a variable object; therefore, I should be able to create another variable object and pass this to the View. The problem is that I don't know where to start :( Any ideas?
Answer: Large parts of the question doesn't actually make sense to me, but...
If you want to pass an arbitrary part of the URL as a string to a View, just assign that variable part to a string in the argument settings, and then set that argument, %url_from_string, as the argument to the View.
The better solution though, would be to create a new context type called 'content type', because I don't think a context like that is available out of the box, and then assign the argument to that instead. That allows you to do validation of the incoming context and gracefully handle an argument that's not valid.
A third solution, though mostly a workaround, is to tell the View to pull it's arguments directly from the URL. This setting is available for all content pane displays under their argument settings.
Comment: The difficulty here is that I don't want to pass the content type as an argument because it's redundant: The path already explains what content I am trying to access. If I go to '/drivers' it would make no sense to have a query of '/drivers/driver' or '/drivers?type=driver'. Is there to a way to pass the only path element of the page URL without the arguments as context?
Comment: If your pages are at the root, /, then you can't have variable arguments, but you can still manually attach the relevant context to each page. Also having the View pulling it's argument from the URL will also still work, though I still wouldn't recommend it.

Panels Custom Context


binding value in hiddenfield using Eval

Question: I am using this code in my website, where it gives me the parser error, "The server tag is not well formed."
<asp:HiddenField runat="server" ID="hfFirstName" Value='<%# String.IsNullOrEmpty(Eval("Title").ToString()) ? Eval("FirstName") : (Eval("Title").ToString().Split(' ')[0]) %>' />
please help me in this.
Answer: Instead of using .Split(' ') try using .Split(" ".ToCharArray()).
That should get rid of the parser error you're seeing.

binding value in hiddenfield using Eval


Manipulação de horas com Joda Time

Question: <code> String tempo1 = "01:30:30";
 String tempo2 = "24:25:10";

    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
    try {
        Date date1 = (Date)sdf.parse(tempo1);
        Date date2 = (Date)sdf.parse(tempo2);

        DateTime dateTime1 = new DateTime(date1);
        DateTime dateTime2 = new DateTime(date2);
</code>
Pessoal, como faço pra somar essas duas Strings que fique da seguinte forma: "25:55:40"?
Tá sempre retornando 01:55:40.
Comment: Não creio que seja duplicata @DiegoF pois a pergunta se refere à soma de tempos utilizando JodaTime e não Java puro.
Answer: Utilizando JodaTime creio eu que a seguinte função resolveria seu problema:
<code>private DateTime somarTempos(DateTime t1, DateTime t2) {
    return t1.plusHours(t2.getHourOfDay())
            .plusMinutes(t2.getMinuteOfHour())
            .plusSeconds(t2.getSecondOfMinute());
}
</code>

Manipulação de horas com Joda Time


Asymptotics of two functions

Question: Is $$O(1-cf(n))=O(1-f(n))$$ for any constant $c$ and any function $f$? I am afraid not. Could you tell me how to get from $$1-cf(n)$$ to $$1-f(n)?$$
Anything I can think of is $$1-cf(n)=c(1-f(n))+1-c=O(1-f(n))+1-c$$ but this does not help.
Answer: If $f(x)=o(1)$, then $$O(1-cf(x))=O(1)=O(1-f(x)).$$ Otherwise, $$O(1-cf(x))=O(cf(x))=O(f(x))=O(1-f(x)).$$
UPDATE:
There is a special case: when $f(x)=O(1)$, we can have $O(1-cf(x))=o(1)$ (if the limit of $f$ is $\frac1c$). But then $1-f(x)=O(1)$.
Comment: When the limit of $f$ is $1$ (the limit is $cf=c$), you have $1-cf(x)=O(1)$ while $1-f(x)=o(1)$.
Comment: So for every possible constant $c$ and every $f$ this holds?

I have that $0n$.
Comment: I am sorry, I have some typos. I tried to fix them, but it seems to be too late. We define

$$f(n):=Pr[Bin(n,p) \geq x]$$ where $x$ is a constant. So this function does not have a finite Domain, does it?

So my Problem is that I have $1-c f(n)$ and I want to prove that it is in $O(Pr[Bin(n,p)< x])$. Does this work?

Asymptotics of two functions


Linux - A more fine grained -mtime for find?

Question: find is a great tool for finding files. It has the option to find files that were modified in the last X days with -mtime. However I'd like something more fine grained than that. I want to be able to find files that were modified in the last 2 hours. Is there some way to make find (or some other similar tool) do this?
Answer: man find
-mmin
File's data was last modified n minutes ago.
Comment: also see Tometzsk'y answer to http://serverfault.com/questions/88222/find-files-modified-in-an-interval-on-unix
Comment: to be more verbose, find . -mmin -120 will find all files with an mtime within the past 2 hours
Answer: An alternative to Paul Brewer's (best) answer: -newer.  It essentially finds anything newer than a file.  So you can use touch to create a timestamp for a file in the past, then see what's newer than that.
touch -t 201002160900 timestamp
find . -newer timestamp
Comment: This trick is great when you need to find stuff modified by running a command (`touch timestamp && (some command) && find ...`)


Constantly trigger mousemove event

Question: I have a script that triggers when the cursor is being moved:
<code>window.addEventListener('mousemove', function(e){
        mouse.x = e.x;
        mouse.y = e.y;

        // This script changes the position of an object in relation to the mouse-position.
});
</code>
The Problem:
The following thing might happen: The cursor is not being moved, but the object that moves in relation to the cursor changes its size, in order for the object to stay in the right position, the script has to be run constantly. (…while the object changes size.)
I want the function inside of the EventListener to constantly be called, even when the cursor is not being moved, how can I do this?

I know that this works, because on mobile the object moves in relation to the device-orientation and everything behaves exactly like I want it to, because the gyroscope-sensor inside of a mobile device, normally, constantly spits out new values, even when the device is, basically, completely still. – Then the values only change very slightly, but it works. – This constant refreshment of values is what also I need on desktop, even when the cursor doesn't move.
Comment: What about the event object and the x and y coordinates?
Comment: You could store the mouse object as a global variable and use `setInterval` to read from it regularly.
Comment: @ControlAltDel I'm not sure, if I understand you question, but: When the cursor moves, `mouse.x` and `mouse.y` are updated to the cursor position and I need this to happen constantly, even when the cursor doesn't move. – I will turn this on and off.
Comment: two choices: 1. set an event on on said element with [resizeObserver](https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver) and call your function within that handler. 2. `setInterval` - blah
Comment: @AndyRay @RandyCasburn, thank you for your answers! I did not know about `resizeObserver`, or `setInterval ` I'm looking into it now. :)
Comment: To deal with the non-mouse movement issue, create a synthetic movement by using the `getBoundingClentRec()` of the resizing element. Use those coordinates a "mouse movement" coordinates.
Answer: If you use requestAnimationFrame the brower will know that you want to perform an animation (move the cursor's object related) and will execute the callback function (parameter of requestAnimationFrame) before the next repaint.
Don't forget to call requestAnimationFrame in your callback function.

Constantly trigger mousemove event


Drupal 7 Click tracking / traffic per node

Question: I'd like to track the number of times a node shows up in search results, the number of times it's clicked on in a search result, and the number of times it is displayed. I'd like all of this information to be readily available - perhaps stored in the content type? I could use some help determining the best practice here.
Alternatively. Could I use google analytics to track all of this somehow such that I could access the results from a custom designed module (which, can anyone point me in a direction on?)
Ultimately I want uses to look at a node and be able to see how much traffic came from in-site linking, off-site linking, and how many times users followed a link from the node to an external website.
Can I export google analytic data for each node somehow to drupal?
Answer: The google_analytics_reports module is a starting point for you to look at. I don't think it will cover all your requirements.
Comment: Well the GA api get's me started.. I was looking at http://code.google.com/apis/analytics/docs/gdata/gdataExplorer.html and http://www.lullabot.com/articles/analyze-using-google-analytics-api
Comment: Any idea how I can track the number of times a link is clicked using that gdata explorer?
Answer: you can do all this by:

using google analytics module (it covers basic tracking, tracking clicks in external links, file downloads, you can also use it to pass tokens into custom variables)
you should add javascript to your node type of choice to add events when clicking in internal links

actually, at the moment, best approach would be to go with Google Tag Manager, where you can enable click tracking in all elements and pick in GTM, which one should be tracked.
take a look at following modules:
https://www.drupal.org/project/google_tag
https://www.drupal.org/project/datalayer
First one installs GTM on your page, second one enables passing many variables and taxonomies to be passed to dataLayer. It also has an alter function, if you'd like to add some extra data (since the module is written in a general way and i.e. extracting taxonomies from json arrays on the GTM side can be complicated).
WARNING! keep in mind, that GA has a limit of events sent during one session, and for one user per day. First one is 500, second one AFAIK is around 200k. It might look that it's more than enough, but if you plan to track no of displays for many elements, you'd use up all your "event credits" right a way - another caveat is, that after the page load, you have a credit of 10-12 events, and each second it adds 2 tokens - it's an DDoS mechanism implemented on server side in GA.
So... what you're describing is more of a adserver mechanism where you want to measure click through rate (CTR) of your "promotional banners" - even if it's a node teaser, if you want to measure CTR, you should think about it as a banner.
Another way to measure it (clicks only) is to add a suffix to node link, which would later on allow on identifying where click came from, but you can also do this with standard reports on a page level, where you can check navigation summary for each page - it won't be as precise to tell you that specific teaser was clicked, but you'll know previous page.


Como imprimir 0.10 ao invés de 0.1 em Java?

Question: O código abaixo conta quantas letras tem numa palavra e multiplica por 0.01. O problema é que quero que, quando uma palavra de 10 letras, por exemplo, for digitada, tenha uma saída de 0.10 e não 0.1.
import java.util.Scanner;
import java.text.DecimalFormat;

public class MedidaDeTempo{

    public static void main(String[] args){
        Scanner ler = new Scanner(System.in);
        String teste;
        int C, tamanho, i = 0;
        double T;

        C = ler.nextInt();

        do{
            i++;
            teste = ler.nextLine();
            tamanho = teste.length();
            T = tamanho * 0.01;

            if(T > 0.00){
                DecimalFormat df = new DecimalFormat("0.##");
                String decimal = df.format(T);
                System.out.printf(decimal + "\n");
            }
        } while(i <= C);
    }
}

Answer: Assim?
System.out.format("%.2f%n", decimal);

Coloquei no GitHub para referência futura.
Você precisa indicar o número de casas decimais e não como deve ser formatado. Espero que não precise de exatidão, esta solução não garante isto.
Comment: Obrigada! Descobri o que eu estava fazendo de errado! Eu estava colocando "%.00f" ao invés de "%.2f", como você colocou.


"The intervals considered dissonant have changed since the 'Middle Ages'"; How so?

Question: In reading my new book 'Complete Classical Music Guide', I understand the following:

If two notes are separated by a consonant the sound is pleasing to the ears. If they are of a dissonant interval they clash with each other. Therefore they have to be resolved by a suitable consonance.

However, I do not understand (as it does not explain):

Intervals considered dissonant have changed since the Middle Ages

Is this because:

we have later accepted that these "sounds" are not correct, as they were originally listed because ...

or

it is wholly opinion at the forefront of why intervals were once considered dissonant?

I would be most grateful if someone could explain why dissonant intervals have changed as so?
Changed in what way?

EDIT 30/12
This subject has particularly fascinated me. I have done some further reading.
I read the following in a PDF article, available here (A History of 'Consonance' and 'Dissonance' by James Tenney)

Musically speaking, there are not really dissonant intervals, but only dissonant notes, Which  note  is dissonant in an interval physically (acoustically) dissonant. This depends on the clang to which that interval has to be referred By thus distinguishing dissonant.. .notes in place of the old system of intervals and chords, a much clearer view of  chords is obtained.

Whilst an 'Interval' is the difference between two pitches not necessarily a harmony per-se, when these notes are played together they dramatically tell the story of the piece, so I find the above quotation remarkably odd; "there are not really dissonant intervals".
This is more interesting from The Harvard Dictionary of Music by Don Randel, available here:

During the Middle Ages, theorists generally believed that polyphonic textures were primarily consonant in nature and those imperfect consonances played a subordinate role to perfect consonances. They recognised that phrases begin and end on perfect consonance and that the final perfect consonance is approached by step in contrary motion from the nearest imperfect consonance.

Are we suggesting then here that this is all perceived by many many factors like temperament, genre, range, and the actual interval itself? Almost to a point (as my original post suggests) that opinion is of the highest principle here?
This is what is confusing: An augmented second and a minor third are identical. But in traditional understanding, the first one is considered a dissonance, and the other consonance.
The big question then is can it be argued then that an octave could be dissonant?
Comment: As far as I know, major and minor thirds were not considered consonant in Europe until the 1500s. In fact, this was partially the reason for the development of meantone temperament and its variants - to preserve the quality of the thirds while ensuring the perfect fourth and fifth were not altered by too many cents.
Comment: @Dekkadeci are you sure it wasn't the other way around?
Comment: @leftaroundabout, I might be mixing it up with the times I've read that perfect fourths were considered dissonant in counterpoint (such as https://www.ars-nova.com/Theory%20Q&A/Q85.html and https://en.wikibooks.org/wiki/Counterpoint/First_Species). Hold on, https://en.wikipedia.org/wiki/Perfect_fourth indicates this, according to *The New Grove Dictionary of Music and Musicians*, second edition: "In the 15th century the fourth came to be regarded as dissonant on its own, and was first classed as a dissonance by Johannes Tinctoris in his Terminorum musicae diffinitorium (1473)."
Comment: I've read that the perfect fourth was considered dissonant in the Middle Ages but consonant today.
Comment: @syntonicC you don't need any temperament for choral music, it's perfectly possible and natural to sing 5-limit (or even 7- or higher) just intonation. This seemingly just _didn't occur to middle-age composers_.
Comment: Certain intervals *were* more dissonant (and more or less so depending on what fret you were holding down). @syntonicC suggests this motivated the creation of modern temperaments; I think he may well be right.
Answer: OK, so first a clarification of the contexts:
The quoted materials are mostly concerned with Western European music. The music of the Middle Ages almost certainly refers to the liturgical music of that time and place, so we're mostly talking about Gregorian Chant, organum, motets, etc. When talking about changes in the later eras, I suspect they're mostly talking about changes that had entirely solidified by the time of Classical composers like Mozart and Beethoven. If we push further into the twentieth and twenty-first century music of that lineage we see further changes in interval usage, as we would if we push into other genres such as jazz, rock, pop and hip-hop.
Next, an executive summary:
I suspect that the first book is mostly referring to a shift from the perfect fourth being mostly treated as a consonance in the Middle Ages to being treated as a dissonance in some contexts in the Classical era. Concomitant with this shift is a shift from a tendency to treat what we now call imperfect consonances (major and minor thirds and sixths) as dissonances in the Middle Ages to the consonances they generally are in the Classical era. We could also speak of a much later shift from Classical to Jazz: in the former the seventh is virtually always a dissonance while it's often a consonance in the latter.
To go into more detail, I think it's extremely useful to shore up the sometimes loose definitions of "consonant" and "dissonant." In particular, I think it would be helpful to use the terms "concordant" and "discordant" to refer to objective measures of how simply the frequencies of two notes relate to each other. This is shown somewhat in the picture you posted that includes an illustration of the highly concordant interval of the octave—wherein the periods of the two waveforms are highly correlated—and the fairly discordant interval of a second. The waveforms of the second take far longer before they get back to their starting relationship (not shown in the image, since the image would have to be too long for the page width) than the octave, which shows the waveforms getting back to their starting relationship twice in just a brief span. Although there might be some ambiguities and debate about a highly-specific ranking of every possible interval, it's fair to say generally that perfect unisons and octaves are extremely concordant; perfect fourths and fifths and quite concordant; major and minor thirds and sixths are moderately concordant; minor sevenths and major seconds are fairly discordant; major sevenths and minor seconds are highly discordant. This is purely based on how the pitches interact with each other in terms of their periodic waveforms.
If we let those terms stand for a more "scientific" understanding of intervallic relationships, we can then use "consonant" and "dissonant" to refer to the way that composers (in the broadest sense of that term) actually use the intervals within the context of their piece and genre. A dissonant interval is one that tends to be treated as unstable: an interval that needs to resolve to a more consonant interval. A consonant interval is one that is treated as stable; it's an interval that can be resolved to. Because this is entirely about style and context, this is the aspect of interval definitions that has shifted the most over the years. Unfortunately, there's one more complication that has to be discussed before talking about that.
For the most part, introductory texts treat pitch and tuning as far clearer than they actually are. They tend to assume equal temperament, which is fine for beginners, but the question of historical shifts in interval usage cannot be separated from the issue of temperament. There are lots of questions on this site that will give you the details, but suffice to say that the earliest tunings used during the Middle Ages for fixed-pitch instruments (instruments like fretted strings or keyboards where you have to set the exact tuning of the pitches in advance and can't easily modify the tuning during performance) was Pythagorean. This is a system where all the notes are tuned according to perfect fifths. If you do this—essentially tune your piano by going around the circle of fifths and getting every fifth truly perfect—then your major thirds will be quite discordant compared to our modern equally-tempered major thirds and will be very discordant compared to a pure major third. Again, the specifics of these differences are complicated, but you can find out more by looking up "just intonation", "temperament" and "equal temperament" among other topics. The upshot as far as this question is concerned is that it isn't surprising that composers of liturgical music in the Middle Ages treated the major third as a dissonance that needed to resolve to purer intervals such as the fourth and fifth. In part this is because it is less common to treat an interval as discordant as the Pythagorean major third as a point of resolution.
It's vastly oversimplified, but very generally speaking, different attitudes start to emerge (over the course of centuries) during the Renaissance. The sweetness of pure thirds (which were easy to explore in a capella singing for example) became more popular, and people started tuning fixed-pitch instruments so that they had pure (or purer) thirds as well. Composers started using thirds (and sixths) as primary consonances and so needed to adjust the tuning of fixed-pitch instruments to make those thirds more concordant as well. As the third became a primary consonance, an ambiguous status for the perfect fourth emerges. Although the perfect fourth was just as concordant as it was before (more concordant than a major third!) it was only a half step away from being a third. This led to a natural "gravity" as—in the context of the music that was being written—the top note of those fourths tended to "want" to resolve down a half step and become a consonant third. The objective concordance of the perfect fourth didn't change, but its contextual meaning did. When the bottom note of the fourth is the lowest note of an entire harmony, the fourth became a clear and strong dissonance.
The fourth didn't become more discordant, it just became more dissonant.
And, just to reiterate, this is only in certain contexts even within music of the Classical era. When the fourth is between two upper notes within a larger harmony, it's perfectly consonant. The fourth is only treated like a dissonance when the bottom note of the fourth is also the lowest note of the entire harmony. (Look up the cadential 6/4 chord for the quintessential example of this, although also see the conversation in the comments to this answer between me and @leftaroundabout, which adds some interesting subtleties to this issue). The distinction between concordance/discordance on the one hand and consonance/dissonance on the other also helps to clarify your question about the augmented second versus the minor third. First off, in many non-equal tempered scenarios, those two intervals are not the same. The augmented second will be wider and far more discordant than the pure minor third. The books you're quoting, however, are talking about equally-tempered instruments like the modern piano, and on those it is true that the augmented second and minor third interval are the same objective relationship. As a result, it would be entirely correct to say that they are equally concordant (or discordant), but because "consonance" and "dissonance" are contextually defined, it isn't ridiculous to say that an augmented second is dissonant while a minor third is consonant. That tends to be their usage in music of the Classical era: a composer would almost never spell out the interval as an augmented second unless they intended it to be performed as an instability that needs to resolve. The spelling of notes in the score is not simply an instruction about what buttons to push, it can also indicate the rhetorical intent of the composer.
So, to sum up, the fourth was initially treated as a consonance equal to the perfect fifth in the Middle Ages of Europe and thirds tended to be dissonances that resolve to them. As the status of thirds began to change, the fourth became ambiguous and is often a dissonance that needs to resolve to a third. Historically, there was some shift in the concordance of thirds due to changing standards of tuning, but the primary shift is a purely contextual one toward consonance. More recently, we hear something similar happen to the treatment of the seventh in jazz music, where it's often a perfectly consonant interval despite its relative discordance.
EDIT TO ADD:
I just saw where you asked for sources. One problem is that this kind of question falls into an unfortunate hole in the literature. On the one hand, it's too basic for discussion in academic journals; on the other hand, the historical evolution of something so specific is seen as too tangential for an introductory text. I think most textbooks of both music theory and music history at least mention it, sort of like the book that prompted your question. I know that both the Clendinning/Marvin and Kostka/Payne music theory texts at least devote a paragraph to the topic. I don't have my copy on hand, but I think there are a few paragraphs in the Burkholder/Grout/Palisca textbook on this as well—however I recall that is just discussed across the course of the text as it moves from early music into the Baroque, not in one clear place.
Perhaps the best place to look for authoritative sources is in Grove Music (now called Oxford Music). The article on the Fourth in there is pretty brief, but includes this paragraph:

The 4th has a unique position in Western music because it has been regarded as a Perfect interval (like the unison, 5th and octave) and a dissonance at the same time. In ancient Greek music the basis of melody was the Tetrachord, a set of four pitches encompassed by a 4th. The earliest forms of medieval parallel Organum favoured it as the interval between the vox organalis and vox principalis. With the further development of polyphonic music in the 12th and 13th centuries, the 5th replaced the 4th as the most important Consonance after the octave and the unison. By the 15th century the 4th appeared as a consonance only between the upper parts of a vertical sonority, for example in 6-3 chords of the fauxbourdon style and at 8-5-1 cadences (e.g. D–A–D); composers of the later 15th century, including Du Fay, sometimes deliberately avoided the 4th in three-part writing (see Non-quartal harmony), and Tinctoris deemed it a dissonance in his Terminorum musicae diffinitorium (c1473).

You'll notice that the concord-discord/consonance-dissonance distinction I talk about is far from universal, and the terms are used differently in most texts on the topic. Ultimately, this is the kind of information I learned during a semester-long graduate course on The History of Theory. As is common in such courses, there was no textbook, we engaged with primary historical sources. We began with ancient theorists like Aristoxenus and, later, Gaudentius, then moved to later writers like Boethius et al. For the most part, these writers don't talk much about the shift in thinking, instead, one has to intuit and observe the shift between them. Anyway, I hope this at least helps situate your understanding a bit.
Comment: Excellent discussion. I'd remark that a ₄⁶ chord is in fact more discordant than a root-position major chord, _if a wide voicing is used_ (perhaps with the bass note octave-doubled, as common in orchestral settings): 3:8:10 vs 2:5:6. In a close voicing, as typical on guitar, it is not more discordant, and fifth-in-bass chords are indeed commonly used by guitarists, not usually perceived as dissonant.
Comment: @leftaroundabout This is an interesting frame that I haven't considered before. It does seem like a wider spacing certainly emphasizes the instability more, although I'm not sure why 6:8:10 would be *that* much closer in stability to 2:5:6 than 3:8:10. Definitely true that this issue is more-or-less irrelevant to proper guitar style, but I've always taken the shift away from 6/4 as dissonant to be more of a genre issue than an instrumental one. When baroque and classical composers write for lute/guitar do they still use 6/4 chords primarily for unstable functions like passing and cadential?
Comment: Well, you don't hear 6:8:10 but 3:4:5 in a close-voiced ₄⁶ chord, and I daresay that is quite concordant indeed. — Sure, when classical composers use ₄⁶ it's usually e.g. predominant rather than tonic because _genre convention_. Then again, in classical guitar, the voicings tend to be wider than in folk/rock styles, and classical training emphasises the need to make the bass note stand out clearly below the rest.
Comment: @Esther: It's helpful because while dissonance is certainly culturally-determined to *some* extent, it's also not by any means *entirely* arbitrary — there seem to be at least some objective physical attributes that underlie the culturally-determined qualities.  Most different cultures' systems of harmony are connected in some way or another back to the physical frequency relationships of pitches, though they build on those relationships in many very different ways.
Comment: "I think it would be helpful to use the terms "concordant" and "discordant" to refer to objective measures of how simply the frequencies of two notes relate to each other." -- helpful *for what purpose*? As soon as you acknowledge that music is more usefully discussed in terms of culturally-defined consonances and dissonances, what use does this arbitrary scientific classification have left?
Answer: My view (perhaps not quite mainstream-agreed) is that nothing has changed in what intervals were dissonant, between the middle ages and today. Rather they simply didn't use some of the intervals that we use as consonances today, vice versa.
Middle-age harmony was strictly Pythagorean in nature, meaning all intervals were constructed by multiplying or dividing frequencies with the numbers 3 and 2. For instance, you get a perfect fifth when starting out with some frequency (e.g. A3: 220 Hz), multiplying by 3 (660 Hz) and dividing by 2 (330 Hz), which as you'll notice is almost exactly the frequency of an E4 on a modern piano (329.6 Hz). An octave simply has the double frequency, and so on.
From this construction, you get as the most natural intervals: octave, fifth, fourth, major ninth, major second...
OTOH, to construct, say, something like a C♯ from that A3, you'd need to first go to B3 (twice up a fifth, i.e. multiply with 3×3 = 9 and divide by 2×2 = 4, then down another octave; compound factor: ⁹⁄₈) and then up another full step, which makes the total frequency ratio ⁸¹⁄₆₄. It's pretty far-fetched to call that a consonant interval, and indeed if you search the internet for "Pythagorean major third" you'll find it sounds pretty jarring. This interval is not really used in post-1700 music at all, not so much because it sounds dissonant as because the instruments can't play it.
Because in the Renaissance, musicians (re-) discovered another note quite close to that "C♯" of 278.4 Hz, one that can't be constructed from Pythagorean tuning. Namely, if you just multiply by ⁵⁄₄, you end up at 275 Hz, which gives a very sweet, harmonious-sounding interval. Ever since, instruments were built with that consonant major third in mind, and that interval is a mainstay of Western music. But it's not the interval that folks in the middle ages, rightly, considered dissonant, though the frequencies are quite similar.
Comment: While it's true that medieval treatises on tuning favored Pythagorean interavals, it's an open question how musicians tuned in practice.  I seriously doubt that medieval singers aimed for Pythagorean thirds in the many pieces, especially in English and Alpine music, that were primarily based on thirds.  But I guess there's no way of knowing for sure.
Answer: Why have dissonant intervals changed over time, and how? Briefly, the concepts of consonance and dissonance are a combination of objective, acoustic phenomena—what we might call "acoustic consonance/dissonance" or "concordance/discordance"—and subjective, cultural phenomena that may or may not correlate with acoustics (but often do). Cultures change; acoustic principles don't. Tenney (1988) offers the broadest look at the changing concept of consonance/dissonance across Western musical eras, but this work need not be taken as the final word; there are fine details within each period that underlie these larger shifts.
Now, on to some examples. The perfect fourth is the archetypal example of an interval that has experienced a change in consonance/dissonance category. This interval, bearing a 4:3 ratio of fundamental frequencies, is acoustically consonant—it has high harmonicity (likeliness to a single harmonic complex tone) and promotes perceptual fusion (hearing two sounds as one). But it also doesn't fit well within the concept of harmonic root: the P4 is an interval "standing on [its] head" (Thomson 1993, 127), in that a modern (chord-oriented) listener is prone to hear the P4 as an inversion of a P5, pointing toward the upper tone as the "root" (as in a six-four chord). So with the gradual change in Renaissance-era musical practice from tenor (middle) to bass (lowest) as structural voice, the P4 changes from stable (consonance) to less stable (dissonance). Basically, the change is with the system of consonance/dissonance, not with the P4: the P4 just happens to be standing on the fault line.
Regarding the distinction between augmented second and minor third—intervals that are enharmonically equivalent in equal temperament, which is implicit in your question—the "dissonance" ascribed to the A2 is one of melodic practice and musical expectation. Most works in the Western art-music tradition ("the canon") simply do not make use of the A2 as a melodic interval, though we may find one or two hidden instances, like the forbidden parallel fifths that we occasionally find in Romantic-era piano works. The essential instance of this interval is found in the so-called harmonic minor scale between the lowered sixth (le) and raised seventh (ti) scale degrees. Western music (and its listeners) have learned to treat and hear each of these scale degree as "gravitating" toward the more structural degrees that lie a semitone away—le above sol, ti below do. A jump from le down to ti, a diminished seventh, is culturally okay, because it honors the "gravitational pull" of le downward. (Check out Bach's Two-part Invention no. 4 in D Minor, BWV 775, for an example of this diminished-seventh interval in both directions.) But le up to ti, an augmented second, violates this gravitational pull; it "leaps a gap" that is often obscured when we practice writing the harmonic minor scale as starting on do and going up the octave. And while talk of "gravity" in music smacks of some of the more lofty "will of the tones" concepts found in musical treatises, Larson (2004) offers a reasonable, cognition-oriented description and analysis of gravity as a "melodic force."
Lastly, can an octave be dissonant? I'd offer a qualified "yes." Because the octave has high harmonicity with its 2:1 ratio, it will always be prone to harmonic fusion, and will "sound good" in a chord or a melodic leap. But it's possible to create a context in which octaves are considered syntactically unfit. The "free atonal" style of composition, most often associated with Schoenberg and like minds in their pre-serial works, rigorously avoids the octave in its chords. (Yes, we may find octave doubling in a piano melody, but this is just that—doubling a melody for purposes of dynamics and texture, not two independent voices.) Cramer (2003) theorizes that Schoenberg and Webern used the major seventh and minor ninth—the "altered octave"—as a replacement for the stable octave, and that these intervals may be heard as both acoustically (through their roughness) and practically (through their frequency of use) structural. Would an octave in this style of music therefore sound dissonant? The test would be in the ability to hear an octave as a non-harmonic ("non-chord") tone—such that the listener would expect it to resolve to a consonance. I'd suggest a suspension that resolves from octave to major seventh; I can't think of such an example in the literature, but perhaps we might find one, or compose one for that matter.
Similarly (but not directly on-topic), can we hear the "altered octave"—major seventh or minor ninth—as a consonance? I'll suggest a musical example, heard in "Angst und Hoffen," no. 7 from Schoenberg's Book of the Hanging Gardens (Op. 15, 1908–09). Listen to the first two three-tone chords in the piano—the first an augmented triad (Gb-Bb-D), the second a "Viennese trichord" of stacked augmented and perfect fourths (set class 016), spelled upwards Fb-Bb-Eb. Try to hear them as dominant to tonic within an Eb tonic. (Minor? Major? Let's just call it "E-flat.") Hear the melody in the voice rising from ti ("Angst") to do ("Hof-"), doubling the upper tones of each chord. Now listen to the final melodic passage of the work, at the Sehr langsam tempo marking, as Schoenberg begins an embellished scalar descent in the voice from sol (Bb) to a final re–do (F to Eb); the piece ends with the same "dominant to tonic" pair of chords as are heard in the beginning. Is the final chord consonant? Can you learn to hear it as consonant? Could other listeners do this as well? I think so, but perhaps I ask too much of listeners.
Sources
Cramer, Alfred. 2003. "The Harmonic Function of the Altered Octave in Early Atonal Music of Schoenberg and Webern: Demonstrations Using Auditory Streaming." Music Theory Online 9 (2), http://www.mtosmt.org/issues/mto.03.9.2/mto.03.9.2.cramer.html
Larson, Steve. 2004. "Musical Forces and Melodic Expectations: Comparing Computer Models and Experimental Results." Music Perception 21 (4), 457–498.
Tenney, James. 1988. A History of Consonance and Dissonance. New York: Excelsior.
Thomson, William. "The Harmonic Root: A Fragile Marriage of Concept and Percept." Music Perception 10 (4), 385–415.
Answer: Here is an excerpt from a review of Beethoven's Op. 111 Sonata, written in 1823, soon after it was published:

Beethoven ... is suffering under a privation that to a musician is intolerable - he is almost totally bereft of the sense of hearing ... The Sonata, op. 111 consists of two movements ... In [the first movement] are visible some of those dissonances the harshness of which may have escaped the observation of the composer.

Here's a performance of the Op. 111. Perhaps you will decide whether or not you agree with the critic.

The point, then, is that dissonance is a purely subjective concept, at least as far as we currently know.
This is borne out by the fact that the concept of what is and isn't dissonant has been under constant revision over the past few hundred years. It's interesting to realize that in the 1400s the tritone (B to F, for example) was referred to as diabolus in musica, and its use was strictly forbidden in sacred music. Presumably because its "obvious" dissonance was something that couldn't come from God. Over time, we have found our way to the idea that since dissonance is a subjective concept, we can define musical structure any way we like, without regard to whether music written using that structure "sounds dissonant" or not.
However, I got into a very interesting discussion on the subject some years ago, talking about the idea of resonance. If the human body resonates to sound -- and the laws of physics suggest that it does, as does any other physical object -- then it follows that certain frequencies could create resonances that are objectively beneficial to health and certain other frequencies could create resonances that are objectively less so. For example, it would seem likely that there are frequencies that could set up vibrations in tumors that would cause them to break apart, and others that could damage internal organs.
If it came about that some intervals had more beneficial effects on the health of the body than others, then that might be considered an objective standard of consonance vs. dissonance.
So, perhaps 200 years from now, we will look back on the discussions of
"subjective dissonance" from our times with that avuncular fondness that we currently observe for discredited ideas such as bodily humors and bloodletting.
Answer: All the above answers are good. I'd like to add a different point of view. The terms "consonance and dissonance" as used (if not always explicitly described) in music are not equivalent (nor necessarily related) to harsh and sweet sounds or the terms concord and discord. Dissonance (as I understand it from some texts and looking at lots of music) normally means a sound that indicates musical movement; dissonance needs to be resolved. Consonance means that no movement is implied. These are "local" features. In a large musical structure (sonata movement, fugue, etc.) there are tonal regions that seem to call for something to follow. The opening of a sonata (in a major key, the tonic section followed by  dominant or other key area) seems incomplete though no local dissonance need occur. Similarly for a fugue after only a couple of statements of the theme.
There are two points I'd like to make here. First that consonance and dissonance are most subjective terms and musical physics doesn't really explain everything. (Temperament choices may be of interest in this field though.) Second, consonance and dissonance are not fixed terms but their meaning depends strongly on musical style. Note that the fourth above a bass was (is?) considered dissonant in two part counterpoint and that this may be because it implies a 6-4 chords which in turn is considered a decoration of dominant chord. Non-cadential 6-4 chords don't sound dissonant. Over the centuries, styles have changed but this change is (I don't think) rooted in the dissonant or consonant character of the music.
Answer: Thirds were never considered dissonances in European music, but until the 11th century, they were left out of the list of consonant intervals for discant but included consonances for organum and plainchant. The scientists of music theory made an attempt to update ancient Greek theory, via Boethius, to match some aspects of current practice insofar as composition was concerned (but not about the mathematics of intervals, which led to centuries of confusion - which lasts to today). After around 1100, all the treatises list thirds as consonances, usually designated "imperfect" or some similar term because their use in the starting and ending notes of a work was considered beyond the bounds of typical musical grammar. In some areas it (using thirds at the starting or ending note of a polyphonic work) was accepted both in theory and in practice, however. In vertical consonance (for plainchant) it was designated as normal to end on a major third above the tonic in major modes.
Harmony in practice and in theory, was never truly Pythagorean, and neither was intonation nor temperament.
You'll find plenty of medieval music, both plainchant and polyphony, using major thirds as vertical and horizontal consonances: just about anything written in one of the major modes, from the St Martial School to Perotin to Philippe de Vitry to Machaut to Matteo of Perugia.
When we see distorted thinking today about medieval aversion to thirds, at least we can know it's not a new distortion: even a 14th century theorist complained about the use of thirds in the realm of musical practice of his day, and complained about rhythmic innovations too.
Answer: Consonance/dissonance are not a binary thing that intervals naturally fall into. It's a gradient. What we can do is mathematically determine the ordering of the intervals along this gradient to show which intervals are more or less consonant/dissonant than other intervals. This is fairly objective.
But where you want to draw the line and classify everything on one side as consonant and on the other dissonant, is up to you. Whether it's wise to classify intervals in such a binary fashion in the first place is also up to you.
Answer: If 'Intervals considered dissonant have changed since the Middle Ages' worries you (and it's only a statement by one author, not an established fact) perhaps you'd rather think of the subject this way. The spectrum of dissonance is unchanged - we still recognise that an octave is perfectly consonant, a 5th nearly as much, a 4th as somewhat unstable etc. etc. - we've just developed a taste for intervals further away from pure consonance.   We haven't changed our opinion of what's consonant and what's dissonant, just our opinion of how much dissonance is acceptable.


ASA 5505 stops local internet when connected to VPN

Question: I have a Cisco ASA router running firmware 8.2(5) which hosts an internal LAN on 192.168.30.0/24.
I have used the VPN Wizard to setup L2TP access and I can connect in fine from a Windows box and can ping hosts behind the VPN router.
However, when connected to the VPN I can no longer ping out to my internet or browse web pages. I would like to be able to access the VPN, and also browse the internet at the same time - I understand this is called split tunneling (have ticked the setting in the wizard but to no effect) and if so how do I do this?
Alternatively, if split tunneling is a pain to setup, then making the connected VPN client have internet access from the ASA WAN IP would be OK.
names
!
interface Ethernet0/0
 switchport access vlan 2
!
interface Ethernet0/1
!
interface Vlan1
 nameif inside
 security-level 100
 ip address 192.168.30.1 255.255.255.0
!
interface Vlan2
 nameif outside
 security-level 0
 ip address 220.127.116.11 255.255.255.252
!
ftp mode passive
access-list inside_nat0_outbound extended permit ip any 10.10.10.0 255.255.255.128
access-list inside_nat0_outbound extended permit ip 192.168.30.0 255.255.255.0 192.168.30.192 255.255.255.192
access-list DefaultRAGroup_splitTunnelAcl standard permit 192.168.30.0 255.255.255.0
access-list DefaultRAGroup_splitTunnelAcl_1 standard permit 192.168.30.0 255.255.255.0
pager lines 24
logging asdm informational
mtu inside 1500
mtu outside 1500
ip local pool LANVPNPOOL 192.168.30.220-192.168.30.249 mask 255.255.255.0
icmp unreachable rate-limit 1 burst-size 1
no asdm history enable
arp timeout 14400
global (outside) 1 interface
nat (inside) 0 access-list inside_nat0_outbound
nat (inside) 1 192.168.30.0 255.255.255.0
route outside 0.0.0.0 0.0.0.0 220.127.116.11 1
timeout xlate 3:00:00
timeout conn 1:00:00 half-closed 0:10:00 udp 0:02:00 icmp 0:00:02
timeout sunrpc 0:10:00 h323 0:05:00 h225 1:00:00 mgcp 0:05:00 mgcp-pat 0:05:00
timeout sip 0:30:00 sip_media 0:02:00 sip-invite 0:03:00 sip-disconnect 0:02:00
timeout sip-provisional-media 0:02:00 uauth 0:05:00 absolute
timeout tcp-proxy-reassembly 0:01:00
timeout floating-conn 0:00:00
dynamic-access-policy-record DfltAccessPolicy
http server enable
http 192.168.30.0 255.255.255.0 inside
snmp-server enable traps snmp authentication linkup linkdown coldstart
crypto ipsec transform-set ESP-AES-256-MD5 esp-aes-256 esp-md5-hmac
crypto ipsec transform-set ESP-DES-SHA esp-des esp-sha-hmac
crypto ipsec transform-set ESP-3DES-SHA esp-3des esp-sha-hmac
crypto ipsec transform-set ESP-DES-MD5 esp-des esp-md5-hmac
crypto ipsec transform-set ESP-AES-192-MD5 esp-aes-192 esp-md5-hmac
crypto ipsec transform-set ESP-3DES-MD5 esp-3des esp-md5-hmac
crypto ipsec transform-set ESP-AES-256-SHA esp-aes-256 esp-sha-hmac
crypto ipsec transform-set ESP-AES-128-SHA esp-aes esp-sha-hmac
crypto ipsec transform-set ESP-AES-192-SHA esp-aes-192 esp-sha-hmac
crypto ipsec transform-set ESP-AES-128-MD5 esp-aes esp-md5-hmac
crypto ipsec transform-set TRANS_ESP_3DES_SHA esp-3des esp-sha-hmac
crypto ipsec transform-set TRANS_ESP_3DES_SHA mode transport
crypto ipsec security-association lifetime seconds 28800
crypto ipsec security-association lifetime kilobytes 4608000
crypto dynamic-map SYSTEM_DEFAULT_CRYPTO_MAP 65535 set transform-set ESP-AES-128-SHA ESP-AES-128-MD5 ESP-AES-192-SHA ESP-AES-192-MD5 ESP-AES-256-SHA ESP-AES-256-MD5 ESP-3DES-SHA ESP-3DES-MD5 ESP-DES-SHA ESP-DES-MD5 TRANS_ESP_3DES_SHA
crypto map outside_map 65535 ipsec-isakmp dynamic SYSTEM_DEFAULT_CRYPTO_MAP
crypto map outside_map interface outside
crypto isakmp enable outside
crypto isakmp policy 10
 authentication pre-share
 encryption 3des
 hash sha
 group 2
 lifetime 86400
telnet timeout 5
ssh timeout 5
console timeout 0
dhcpd auto_config outside
!

threat-detection basic-threat
threat-detection statistics access-list
no threat-detection statistics tcp-intercept
webvpn
group-policy DefaultRAGroup internal
group-policy DefaultRAGroup attributes
 dns-server value 192.168.30.3
 vpn-tunnel-protocol l2tp-ipsec
 split-tunnel-policy tunnelspecified
 split-tunnel-network-list value DefaultRAGroup_splitTunnelAcl_1
username user password Cj7W5X7wERleAewO8ENYtg== nt-encrypted privilege 0
tunnel-group DefaultRAGroup general-attributes
 address-pool LANVPNPOOL
 default-group-policy DefaultRAGroup
tunnel-group DefaultRAGroup ipsec-attributes
 pre-shared-key *****
tunnel-group DefaultRAGroup ppp-attributes
 no authentication chap
 authentication ms-chap-v2
!
class-map inspection_default
 match default-inspection-traffic
!
!
policy-map type inspect dns preset_dns_map
 parameters
  message-length maximum client auto
  message-length maximum 512
policy-map global_policy
 class inspection_default
  inspect dns preset_dns_map
  inspect ftp
  inspect h323 h225
  inspect h323 ras
  inspect rsh
  inspect rtsp
  inspect esmtp
  inspect sqlnet
  inspect skinny
  inspect sunrpc
  inspect xdmcp
  inspect sip
  inspect netbios
  inspect tftp
  inspect ip-options
!
service-policy global_policy global
prompt hostname context
: end

Answer: Which client software are you using to connect?  Split tunneling is set up, but I believe you'll need to be connecting with the Cisco client software for it to function.
Anyway, to get the VPN client's internet traffic to make it out to the internet, looks like all you need is:
same-security-traffic permit intra-interface
nat (outside) 1 192.168.30.0 255.255.255.0


deploying docker container to heroku

Question: I built a web app using docker composer , locally. Docker composers have multiple services which inturn have their individual dockerfiles as below:
version: '2'
services:

  # The Application
  app:
    build:
      context: ./
      dockerfile: app.dockerfile
    working_dir: /var/www
    volumes:
      - ./:/var/www
    environment:
      - "DB_PORT=3306"
      - "DB_HOST=database"

  # The Web Server
  web:
    build:
      context: ./
      dockerfile: web.dockerfile
    working_dir: /var/www
    volumes_from:
      - app
    ports:
      - 9002:80

  # The Database
  database:
    image: mysql:5.6
    volumes:
      - dbdata:/var/lib/mysql
    environment:
      - "MYSQL_ROOT_PASSWORD=****"
      - "MYSQL_DATABASE=****"
      - "MYSQL_USER=***"
    ports:
        - "33061:3306"

  #Cache
  memcached:
    image: memcached
    ports:
        - "11211:11211"
    mem_limit: 1g
    command: memcached -m 1024m

volumes:
  dbdata:

How do I deploy my app to heroku ? Can it be done using docker compose file ? Or I need to build an image .
I am new to heroku . Please help.
Update: Below is the output of my docker images command:
REPOSITORY           TAG                 IMAGE ID            CREATED             SIZE
<none>               <none>              dbdc39e8d1ae        36 hours ago        415MB
<none>               <none>              6e6ebf3dc133        36 hours ago        559MB
simplesms_app        latest              d43e46560ed8        46 hours ago        761MB
simplesms_web        latest              d1923872bf33        2 days ago          182MB
<none>               <none>              715ac76296bf        2 days ago          756MB
php                  7-apache            a47f065418d5        3 weeks ago         391MB
php                  7.0-apache          a47f065418d5        3 weeks ago         391MB
runwaytest_web       latest              a47f065418d5        3 weeks ago         391MB
php                  7.0-fpm             62e3017b4758        3 weeks ago         380MB
nginx                latest              b8efb18f159b        4 weeks ago         107MB
mysql                5.6                 cdfa8cc50c33        4 weeks ago         298MB
mysql                5.7                 c73c7527c03a        4 weeks ago         412MB
mysql                latest              c73c7527c03a        4 weeks ago         412MB
memcached            latest              0b0366c7c206        4 weeks ago         58.6MB
hello-world          latest              1815c82652c0        2 months ago        1.84kB
nginx                1.10                0346349a1a64        5 months ago        182MB
startx/sv-memcache   latest              706858567fa8        10 months ago       253MB
php                  7.0.5-fpm           e6673411c12c        16 months ago       501MB
php                  7.0.4-fpm           81d7a2fdc6dc        17 months ago       494MB

Comment: Yes, I did read that article and followed the steps mentioned . However on executing `heroku container:push web` , it says `No images to push`. I am clueless here. How to proceed now?
Comment: Add output of `docker images` to your question
Comment: Did you read this article ? https://devcenter.heroku.com/articles/local-development-with-docker-compose
Comment: Updated it now @TarunLalwani
Comment: As you can see there is no web image. This is because you build using `docker-compose`. Try `heroku container:push simplesms_web`
Comment: it doesn't work...gives the same message as above.
Answer: Your web docker file should be named something like dockerfile.web
Then you can run heroku container:push --recursive --app [YOUR_APP]
Or more specifically heroku container:push web --recursive --app [YOUR_APP]
More info on the subject

deploying docker container to heroku


Yoneda Lemma on Generalized Elements

Question: I am reading about additive categories from https://ncatlab.org/nlab/show/additive+category and trying to prove that in any Ab-enriched category, if the coproduct and product of A,B exist, then there is an isomorphism between them.  This is proposition 2.1 in the linked page.
In particular, I am trying to understand equation (**) in 2.1.  We are showing that $(id\times 0)\pi_1 + (0\times id)\pi_2 = id_{X_1\times X_2}$ by composing both sides of this equation with every possible morphism from $R\rightarrow X_1\times X_2$ and checking that they both give the same result.   Why is this enough to check that these morphisms are the same?  The linked page says that this is the "Yoneda Lemma on Generalized Elements," but I cannot find any information on what that means.
My understanding of category theory & the Yoneda lemma is very limited, so any details that can be spelled out here are very much appreciated.
Answer: Generalizing, consider two arrows of a category $\mathcal{C}$, $g, h : A \to B$.  We have the hom-functors $\mathcal{C}(-,A)$ and $\mathcal{C}(-,B) : \mathcal{C}^{op}\to\mathbf{Set}$.  The Yoneda embedding turns each arrow into a natural transformation $g\circ - : \mathcal{C}(-,A) \to \mathcal{C}(-,B)$ similarly for $h$.  As a simple corollary of the Yoneda lemma, the mapping $g \mapsto g \circ -$ is a natural bijection.
$\sigma = \tau$ holds for $\sigma, \tau : \mathcal{C}(-,A)\to\mathcal{C}(-,B)$ if and only if for all $R \in \text{Ob}(\mathcal{C})$ and for all $f \in \mathcal{C}(R,A)$, $\sigma_R(f) = \tau_R(f)$.  For the natural transformations above, this is $g\circ f = h\circ f$ for all $f \in \mathcal{C}(R,A)$ for all $R \in \text{Ob}(\mathcal{C})$.  The (natural) bijection given by the Yoneda lemma then implies that this means $g = h$.  Of course, this is obvious because we can choose $R = A$ and $f = id$ which is nothing more than half of the proof of the Yoneda lemma.
The story is basically the same in the $\mathbf{Ab}$-enriched case.
Answer: Invoking the Yoneda lemma for this is more of a habit than a necessity. Given two arrows $f,g : X \to Y$, the following are equivalent:

$f = g$
$f \circ 1_X = g \circ 1_X$
$f \circ h = g \circ h$ for all $h$ with codomain $X$
$f_*, g_* : \hom(-, X) \to \hom(-, Y)$ are the same natural transformation

For the example at hand, it suffices to use the second bullet; i.e. take $R = X_1 \times X_2$, and the generalized element named by the identity map, written as $(\alpha, \beta)$ where $\alpha$ and $\beta$ are the two projections $R \to X_1$ and $R \to X_2$.
Of course, such a proof looks basically the same as a proof of the third bullet or of the fourth bullet, so with experience one tends to conflate these ideas rather than carefully distinguishing between them, which is why the Yoneda lemma is invoked as the rationale.

Yoneda Lemma on Generalized Elements


Drupal 7 video player for stream

Question: I'm using JW Player for playing video files and it's working great.
Is it possible to play video streams with this player?
I already have a rights to stream and link for a TV station. It's in this format: http://XX.XXX.XXX.XXX:9090/stream.flv
How can I set this link for stream?
If you know some alternative player with possibility of live streaming, please let me know.
Answer: JWPlayer does streaming.
http://www.longtailvideo.com/jw-player/hls-rtmp-live-streaming
I wasn't able to find a module that did this, but you can add this to your page, using the Full HTML text input:

Loading the player

Comment: I've tried your code. I've changed the path src="http://www.mywebsite.com/sites/all/libraries/jwplayer/jwplayer.js" changed into HTML, but it's not appearing the player. When I've copied your code and changed the format into Full HTML and revert back into plain text, automatically deletes the code and only Loading the player stayed there.
Comment: I t has to be FUll HTML. I tried this on my site and it works exactly right.
Comment: Scott, so you have Installed JW Player 7.x-1.0-alpha1 on your website and then you're adding your code, and after saving everything is working, right? Please add some details, 'cos I've tried with your code in FULL HTML and nothing appeared.
Comment: I have not installed any modules, I just added the player to my theme folder and went from there. If you try the module it wont let you use stream URL's.
Comment: Usually every code when I add into my wysiwyg editor first I enable plain text and then I switch into FULL HTML, but in this case when I'm switching your code into full html automatically deletes the code and only left this text "Loading the player". The editor does this when the script code is not right.
Comment: Thank you for clearing that. I'll try now to download the new JW Player from the official website and put into my theme folder, but first I'll disable the module.
Comment: OK, finally it works.I see some annoying bufferings while streaming, but on other website that uses Flow player it works better. I'll try with other version of JW Player, I hope will work better. Scott, thank you very much.
Comment: Glad you got it to work!
Comment: Hi, Scott. As I wrote before I've managed to play the stream with the newest version JW Player, but now when I've tried with version 5, it's not working. Is there any difference with the code for version 5? By the way what version do you use?
Comment: Here's a working demo of the stream, but from longtailvideo website http://bit.ly/1a1abIr. I didn't find a way to copy and edit the code from their website. Can you help me how to play this stream with JW Player version 5?
Comment: OK, now everything is ok. The problem comes from the paths. In the version 5, the two files are working when I've moved into the root folder.

Drupal 7 video player for stream


pandas dataframe use clip on a subset of columns

Question: I am still super confused on how pandas dataframes handle functions applied to a slice of the overall dataframe. Here is what I want to do..
I have a dataframe (normally would be much larger and with more columns!)
>> df
            one  two  three
0           NaN  0.0  1000
1           NaN  0.0  2000
2  1.262950e+36  NaN  3000
3           NaN  NaN  4000

I want to clip the value 1.262950e+36  to some other value, say 1000, so that no value in the dataframe (except for column 3) will have values larger than 1000.
My try 1
I tried the following:
df.loc[:, df.columns.tolist()[:-1]].clip(upper=1000, inplace=True)

but it doesn't seem to work as we get
>> df
               one  two  three
7317           NaN  0.0      1
7318           NaN  0.0      2
7319  1.262950e+36  NaN      3
7320           NaN  NaN      4

My try 2
So I tried with copy
df.loc[:, df.columns.tolist()[:-1]] copy.deepcopy(df.loc[:, df.columns.tolist()[:-1]].clip(upper=1000))

which works but it is obviously too long and unreadable!
Is there a better, faster, more concise and more pythonic way?
Edit: Dtypes
The dtypes of the columns are
>> df.dtypes()
one      float64
two      float64
three      int64
dtype: object

Comment: I did replicate something very close with your first try and it worked, what are the `dtypes` of your columns? (`df.dtypes`)
Comment: I've just updated my question!
Comment: try this:  df.loc[:, ['one', 'two']] = df[['one', 'two']].clip(None, 1000)
Comment: @joaoavf I just tried and it works!
Comment: I think it is worth trying this: `df[df.columns[:-1]].clip(upper=1000)`
Comment: thanks! did you try: `df.clip(upper=1000)`? (I know it will mess with column 'three', but just to get an idea of where the problem might be coming from)
Comment: @hkyi one problem with that is that in my original dataframe I have a lot of columns (24) and I need to use `clip()` on all of them, apart from the first 2 columns (so [2:]). But yes, I noticed that it works that way, however I was hoping for something that would work more in general
Comment: @joaoavf but as you said, it messes up with column 'three'
Comment: You wanna to look df.columns, exclude some column names not to clip with, and then replace it with ['one', 'two'] at the above expression.
Answer: If you have numpy, using np.maximum is faster than using df.clip in most cases.
import numpy as np

cols = ['one', 'two']:
df[cols] = np.maximum(df[cols], 0)


Nginx second domain rewrite rule

Question: What im trying to do:
I have nginx running with wordpress
Now i want DOMAIN-2 to redirect to a path of DOMAIN-1
http://DOMAIN-1/Content-for-Domain-2

but not just a simple redirect, it should change to
http://DOMAIN-2/Content-for-Domain-2

So that users can go to DOMAIN-2 directly if they want to see that content or enter normaly with DOMAIN-1
Any suggestions? I think this should be do-able with rewrite rules?
Comment: I believe the following would do the trick

Source:
http://stackoverflow.com/questions/19703772/htaccess-redirect-to-new-domain-with-path-intact-for-both-www-and-non-www-as-we
Comment: No, i want the new domain to go to the path of the old domain but with  the new domain infront of it.
Comment: For this you need a CNAME DNS record and setup application to use multiple hosts. See my answer for more detailed info.
Answer: To do this first you have to set CNAME DNS records of DOMAIN-2 and point it to DOMAIN-1.
After that, adjust you nginx configuration for your virtual host. You will have your server_name directive defined like this:
server_name DOMAIN-1;

You have to update it to this so nginx also accepts requests for DOMAIN-2:
server_name DOMAIN-1 DOMAIN-2;

E.g.
server_name example.com example.net;

Comment: And how do i end up to only a special path with this setup? I want to be pointed to Domain2.com/path-i-want. This setup you posted will just  allow me to go to the homepage of domain 1, isnt it like this?

Nginx second domain rewrite rule


Issues with Regex Dictionary and Definitions

Question: Apologies for probably a dumb question, but very green at Python here.
I am trying to parse a txt file by using regex and instructions found here: https://www.vipinajayakumar.com/parsing-text-with-python/
I'm having two issues:
1) Regex dictionary only ever matches one value: all three of my definitions "match" when the ones above are commented out, but only one matches when passed the line of the file.  I also verified that different lines are being passed to the _parse_line function each time.
2) \d and \d+ don't seem to be working - the only time I get a match is if I use .* - I've read through the way regex works several times and it seems straight forward, but I simply can't get this to work.
Many thanks for any and all input.
rx_dict = {
    'serial': re.compile(r'SERIAL\s(?P<serial>\d+)\n'),
    'operation': re.compile(r'MODE\s(?P<operation>.*)\n'),
    'ch': re.compile(r'CHANNEL\s(?P<ch>.*)\n')
}

#line parser

def _parse_line(echo):

    for value, rx in rx_dict.items():
        match = rx.search(echo)
        print (match)
        if match:
                return value, match
        return None, None

Comment: Have you solved the issue? If not please share a sample line you test against and provide expected results. Note you *must* post full relevant code snippet to repro the issue, the code above is *NOT* enough to understand where what fails.
Answer: It appears you have an indentation problem. If the first regex in the dictionary does not match, you never get to try the others. Don't you mean:
def _parse_line(echo):

    for value, rx in rx_dict.items():
        match = rx.search(echo)
        print (match)
        if match:
                return value, match
    return None, None # outdent

If \d* matches, but \d+, does not, then you do not have a number following SERIAL.
Comment: Thanks...definitely a noob mistake on the indentation.

\d* does not return either.  The match.group() outputs look like this:
                            1

I can easily shed the whitespace, but why isn't it ignoring that when I specify it's there with /s?
Comment: @RyanWogh You need to show exactly what the complete *input* is and then what you expect the output match to be, i.e a MInimal Reproducible Example. This is a basic prerequisite to getting a good answer.