C# Execute SQL SP using multithreaded or parallel execution

Question: I have a SQL Server SP and would like to execute that for around 10 million user record sets to process the user info and update DB. Currently its taking few millisecond for 1 user to update in DB. Since, it has to process million records what are the best ways to do it?
I am thinking do it from the C# application using multithreaded or parallel foreach. Below is the basic code to run the SP, how can I use it to run it in multithreaded mode to do the processing job faster?
 string connString = "data source=.\SQLEXPRESS;initial catalog=Test;integrated security=True;";
            SqlConnection conn = new SqlConnection(connString);
            conn.Open();
            SqlCommand cmd = new SqlCommand("ETL_TEST", conn);
            cmd.CommandType = CommandType.StoredProcedure;

            cmd.Parameters.Add(new SqlParameter("@user_id", '12345'));
            cmd.ExecuteReader();
            conn.Close();

Comment: multithreading this will end up being a LOT slower. You would effectively have to change this to be row by row. Or is this process already doing this row by row?
Comment: there is one more SP written to do row by row operation and it takes lot of time.
Comment: @SeanLange: No it won't be a lot slower. Up to a point, multiple concurrent requests to SQL Server speed up overall throughput.
Comment: What user information i.e. columns,datatype are you trying to update? Also where is the update information coming from?
Answer:
how can I use it to run it in multithreaded mode to do the processing job faster?

Parallel.ForEach() is a very reasonable starting point to accomplish your goal.  Up to a point, sending concurrent requests to SQL Server can improve overall throughput.
Put your code into the action of Parallel.ForEach(). Use using statements to ensure that things are properly disposed (right now you will leave a connection open if an exception is thrown before it is closed).
Note that the .NET Framework will attempt to find an optimal number of threads (and different versions of the framework may end up selecting different numbers). It is possible that .NET will select a number of threads that is either

Too low (which you cannot influence, but you could solve by creating and managing tasks explicitly)
Too high, resulting in inefficient execution in SQL Server (due to IO or lock contention, high CPU, etc). In this case, you can use the MaxDegreeOfParallelism property to limit the number of threads. Don't forget to adjust the property if you move to a more or less powerful SQL Server.

Note that a multi-threaded solution, while probably more efficient than a single-threaded one, is still very chatty. It makes a request to the database for each user record. In this type of situation, I have achieved order-of-magnitude performance improvements by sending a batch of work over to SQL Server rather than a single work item. You'll likely see the greatest gains by redesigning the stored procedure to accept a number of users at once.
Comment: It is very important to stress that the TPL will generally be completely off from the optimal number of threads for IO work. The number of threads will (literally) trend to infinity over time. This is easy to reproduce with a `sleep(100)`. +1 because you said that but I wanted to stress that even more.
Comment: @usr: In my experience TPL does a reasonable but not perfect job of selecting the number of threads. In doing the work related to the linked question, I did have to specifically limit the degree of parallelism. Can you cite an example for when TPL will tend toward a very large number of threads? Would be curious to understand that situation.
Comment: https://github.com/dotnet/coreclr/issues/1754 Really bad. Unlimited thread creation in all realistic IO scenarios.
Comment: That link complains that core is too *slow* in creating new threads when the workload profile changes drastically. It doesn't mention that an arbitrary number of threads would ever be created.
Comment: Quoting: `The memory use is proportional to the number of threads (here: 731).`. Both problems are present. Slow increase but infinite increase. That picture is scary! Linear growth of thread count over time. Extrapolate that over night. This is the kind of problem that takes production systems down.
Comment: These threads are created on the thread pool, which imposes limits that have not been hit in the example http://stackoverflow.com/a/145323/141172. The number of threads that can be created in that scenario is further limited by the configured max requests https://msdn.microsoft.com/en-us/library/dd560842(v=vs.110).aspx. You can limit the maximum number of thread pool threads https://msdn.microsoft.com/en-us/library/system.threading.threadpool.setmaxthreads(v=vs.110).aspx, though I doubt many developers do that until they run into problems. Not saying it's not a problem but it can be managed.
Comment: It absolutely can be managed but it also means that a simple loop such as `Parallel.ForEach(fileNames, fn => WriteFile(fn))` will lead to infinite amounts of threads and also completely monopolize the thread-pool in the process.
Comment: @Eric Yes, Parallel.ForEach did do a great job on doing it faster from my C# app, but with adding MaxDegreeOfParallelism property though.
Answer: There are several ways you could speed this up:

Pass the data in a table-value parameter so you can process them in one call is likely the best way, but it does take a bit of setup and if this is a one-time thing, not really worth it, IMO.
Since you are dealing with a single parameter, turn it into a comma-separated value string and pass it in so you can process a couple thousand per call on the server.
The simplest thing you can do without changing much code is put this in a transaction and commit your records every couple thousand records, or all at once. Doing this will increase the speed by about 100-fold.
Answer:
Since, it has to process million records what are the best ways to do it?

If you are asking what is the best way to make the process parallel, then @Eric's answer looks promising. I would agree that generally speaking, "Up to a point, sending concurrent requests to SQL Server can improve overall throughput.", as long as we really stress the "Up to a point" part. But "that point" could easily be just a few running at a time (depending on the logic and schema), which isn't the type of gain you are looking for.
If you are asking what is the best way to accomplish the processing of 10 million "sets" of records as quickly / efficiently as possible, well, that is a much more involved question. It requires a bit more analysis. At bare minimum it would require reviewing both the logic in your ETL_TEST Stored Procedure and your Schema (Tables, Indexes, etc). So for the moment, there is not enough information presented here to provide any meaningful assistance along these lines.


Whats the difference between /deep/ ::ng-deep?

Question: Could you please tell me, the differences between the below two scss styles?
I didn't get the clear idea about this.
:host {
  display: inline-block;

  /deep/ {
    span {
      color: red;
    }
  }
}

:host {
  display: inline-block;

  ::ng-deep {
    span {
      color: red;
    }
  }
}

Comment: Is it create any impact If i could used the above two styles in ?
Answer: The main difference is, that ::ng-deep is supported by SASS, while support for /deep/ was removed. This is the reason why ::ng-deep was added to Angular in addition to /deep/
Besides that, both are deprecated in Angular, because when native shadow DOM support in all browsers becomes usable, they will probably remove ViewEncapsulation.Emulated


Views filter: how to compare two fields?

Question: I have two content types "type1" and "type2" and one taxonomy. I have assigned the taxonomy to both of the content types. In type1 its name is "field_type1_test" and in type its name is "field_type2_test".
Now I want to fetch the title and body from the "type1" Where values of "field_type1_test" = "field_type2_test".
Is this possible?
If yes then how will I do this in views? Help please.
Comment: Yessss, I want this too! =(
Answer: Not sure you are going to use it, but for those who may get here looking for the same:
Under the Filter Criteria, Search for "Globals: Fields Comparison".
For the record, the fields you want to compare should be among the fields you are loading in the current View.
So, if you want to compare to something you are not willing to show, you should add the fields to the View and check the Exclude from display.
Hope it helps!


BSOD 90% of the time during a TrueCrypt mount

Question: About 90% of the time when I mount a TrueCrypt share I get a blue screen of death. The error codes I see in the BSOD vary. The last two I saw mentioned eamon.sys and irql_less_than_or_equal.

Windows 7 Professional
TrueCrypt 7.0a
ESET NOD32 AV
I am not using the EXT2 driver

Googling didn't turn up much, but hinted at TueCrypt + NOD32 issues. I tried disabling NOD32 real time monitoring during mounts, but it didn't help. How can I determine the cause?
Comment: Have you tried disabling NOD32? Being that eamon is part of NOD32, I would try disabling it and see if it stops the BSOD. If so, maybe check to see if there is an update for NOD32 or open a ticket with them. A google search returns LOTS of BSOD issues in Win7 with NOD32.
Comment: I did, and it didn't help. At this point I'm about ready to move to Mac. Seriously.
Answer: UPDATE: The problem reoccurred; this didn't fix the issue.
Disabling NOD32 didn't help. The solution was to set the exe of TrueCrypt to Windows Vista SP2 compatibility.

Go to the installation folder for TrueCrypt

C:\Program Files (x86)\TrueCrypt

Right click TrueCrypt.exe
Go to the Compatibility tab
Check "Run this program in compatibility mode for:"
Set it to Windows Vista SP2
Comment: Good on you for coming back and posting your solution (correctly as well) after an extended period of time :)
Comment: @Mark - Thanks! But of course, after it not happening many times, I posted this answer and it BSOD'ed earlier today. Ugh.
Answer: This seems to be an on-going issue.  Please check the official support forums for further information.
A couple of posts indicate that by doing this, it may resolve your issues:

Disable boot sector scanning OR
Deactivating "Automatic startup file check" under schedule

wilders


Azure container can't access a mounted volume on startup why?

Question: I am having problems using a volume mount in my container on Azure container instances.
I can mount a volume mount to my container no problem. Here is the az cli command I am using and it works well. I followed this tutorial
az container create --resource-group mydemo --name paulwx --image containerregistry.azurecr.io/container:master --registry-username username --registry-password password --dns-name-label paulwx --ports 8080 --assign-identity --azure-file-volume-account-name accountname --azure-file-volume-account-key secretkey  --azure-file-volume-share-name myshare --azure-file-volume-mount-path /opt/application/config

This works great and I can attach to the container console and access the shared volume. I can touch files and read files.
The problem comes when I try to have the application read this folder on startup (to get its application configuration). Again the command is almost identical except the application is flagged to read the configs from the volume mount via an ENV variable called SPRING_CONFIG_LOCATION.
az container create --resource-group mydemo --name paulwx --image containerregistry.azurecr.io/container:master --registry-username username --registry-password password --dns-name-label paulwx --ports 8080 --assign-identity --azure-file-volume-account-name accountname --azure-file-volume-account-key secretkey  --azure-file-volume-share-name myshare --azure-file-volume-mount-path /opt/application/config --environment-variables SPRING_CONFIG_LOCATION=file:/opt/application/config/

The container now terminates with the following error.

Error: Failed to start container paulwx, Error response: to create
containerd task: failed to mount container storage: guest modify:
guest RPC failure: failed to mount container root filesystem using
overlayfs
/run/gcs/c/e51f86c414ae83c7c279a4252864a381399069d358f5d2303c97c630e17b049f/rootfs:
no such file or directory: unknown

So I can mount a volume as long as I don't access it on start up. Am I missing something very fundamental here? Surely having a volume mount means the mount point will be available when the container starts.
The volume mount type is samba and Standard_LRS.
Answer: So to cut a long story short the issue here was that the application on startup was configured to read the property file from a folder that was not where I expected it to be be.
The application failed to start due to not finding the application.properties where it expected to find them.The Azure error message was a red herring and not at all reflective of the problem. The application logger was not logging to standard out properly so I actually missed the application log which clearly stated application.properties not found.


For any two sets A and B, if $f: A \rightarrow B$ is injective, then if A is countable, B must be countable.

Question: So i was given two questions you either prove or disprove them.
A) For any two sets A and B, if $f: A \rightarrow B$ is injective, then if A is countable, B must be countable.
B) For any two sets A and B, if $f: A \to B$ is surjective, then if A is countable, B must be countable.
I know Every subset of a countable set is countable and I know i have to use injectivity of f to create a bijection for A but i don't know how. Also for B im quite clueless does it follow A?
Comment: @ChristopherW: I would suggest changing the letters so you either use parts 1,2 , or change the letters you use for the sets to avoid using the letters $A,B$ for both. It seems kind of confusing.
Comment: Were you told to *prove* or were you told to "prove or disprove" these two statements?
Comment: @Asaf Karagila You could do either depending on whether you think it is true or false.
Comment: @AsafKaragila: Both: this is a new, inconsistent theory.
Comment: I think that A) is false and B) is true. For example, the mapping $\mathbb{Z} \to \mathbb{R}$ which identifies $a \in \mathbb{Z}$ is injective. It is easy to see that $\mathbb{Z}$ is countable and $\mathbb{R}$ is uncountable.
Answer: For (A) consider a function that takes an integer in $\mathbb Z$ to itself , with $\mathbb Z$ living in $\mathbb R$.
For (B), we have hat $B=f(A)$, so that $|B|=|f(A)|$, and since every element in $A$ maps into a single element in $B$, we have $|B|\leq |f(A)|$. Can you use your idea that every subset of a countable set is countable to show how $f(a)$ can be made into a "subset" of $A$? , i.e., find an injection between $A$ and $f(A)$?
Comment: Wait so A would not be true because $\Bbb R$ is uncountable
Comment: @ChristopherW: Are you referring to $(A)$? Then , what element in $\mathbb Z$ corresponds to, say $1/2$?
Answer: I like to think of the existence of an injection from $A$ to $B$ as saying "$A$ has at least as many elements as $B$" and the existence of a surjection from $A$ to $B$ as saying "$B$ has at least as many elements as $A$". This is easy to see when $A$ and $B$ have a finite number of elements; the idea can be heuristically extended to infinities.

The injection shows that $B$ can potentially have 'more' elements than $A$. Indeed, the identity map from $\mathbb N$ to $\mathbb R$ suffices for a counterexample.
The surjection shows $B$ has 'less' elements than $A$, implying $B$ is also countable. Rigorously, enumerate $A$ by $\{a_1,a_2,\ldots\}$. If $B$ is finite, then we are done. If not, for any $b \in B$, there exists $n \in \mathbb{N}$ such that $f(a_n) = b$. Then $B$ is in a one-to-one correspondence with the subset of $\mathbb N$ generated by the $b$'s. Every infinite subset of $\mathbb N$ is countable, so $B$ is countable.


Expand $f(z) = \frac{z}{(z+1)(z-2)}$ in a Laurent series

Question: $f(z) =\frac{z}{(z+1)(z-2)}$
given $1 < |z+1| <3$
So I have to write it as the power of $(z+1)$, but using partial fractions I get
$-\frac{z}{3(z+1)} + \frac{z}{3(z-2)}$ and I don't know how to deal with this $z$ on the nominator. How can I write it as power of $(z+1)$?
(it is probably something very simple, but I have no ideia)
Answer: One may write, for $1<|z+1|<3$,
$$
\begin{align}
\frac{z}{z-2}&=\frac{(z-2)+2}{z-2}
\\&=1+\frac{2}{z-2}
\\&=1-\frac23\cdot\frac{1}{1-\dfrac{z+1}3}
\\&=1-\frac23\cdot \sum_{n=1}^\infty \left(\dfrac{z+1}3\right)^n
\end{align}
$$ finally,
$$
\frac{z}{(z+1)(z-2)}=\frac{1}{3(z+1)}-\frac{2}{9}-\frac23\cdot \sum_{n=1}^\infty \left(\dfrac{z+1}3\right)^n.
$$
Comment: Oh, now I get it! Thank you very much!
Comment: @Mark You are welcome.


Upper bounding randomized k-SAT solver

Question: Problem:
Consider a k-SAT solver that assigns values independently uniformly at random to all the variables. Given the formula has $m$ clauses provide an upper bound for the probability of a random assignment to be unsatisfiable.

The issue is that I have no clue from where to start. Both Markov, Chernoff, Chebyshev and McDiarmid's inequalities seem to be not applicable in this situation as the probability of a particular clause to be unsatisfiable depends on the probability of other clauses with overlapping variables to be unsatisfiable.
For every clause the probability of it to be unsatisfiable is
$${1 \over {2^k}}$$
There are $m$ clauses in total, so if there are all independent, the answer would be
$$P(assignment~is~unsatisfiable) = (2^{-k})^m$$
If somebody would help me a bit with at least some kind of hint I would be extremely grateful.
Comment: Cross-posted: http://math.stackexchange.com/q/2043787/14578, http://cs.stackexchange.com/q/66936/755.  Please [do not post the same question on multiple sites](http://meta.stackexchange.com/q/64068). Each community should have an honest shot at answering without anybody's time being wasted.
Answer: It always helps in these sorts of problems to determine your distribution and the event that you are working with. By definition of the algorithm, you are taking probabilities over the uniform distribution over all possible assignments. You are trying to find the probability of the event that at least one of the $m$ clauses (call these $C_1, \dots, C_m)$ in the given formula is not satisfied. i.e.
$$
\Pr\left(\bigvee_{i = 1}^m \text{$C_i$ is not satisfied}\right).
$$
Now you are on the right track. In probability theory, we have ways of giving upper bounds on the disjunction of events, even if they are not independent. (HINT. Treat them like they are independent) (FURTHER HINT. union bound).
Comment: Thank you a lot! Every time I do this kind of tasks I forget about union bound.

Upper bounding randomized k-SAT solver


What is the multivariate distribution of $(X_1, \ldots, X_n | X_1+ \dotsm + X_n = y)$?

Question: What is the multivariate distribution of $(X_1, \ldots, X_n | X_1+ \dotsm + X_n = y)$, given $y$ and that $X_i$ is (otherwise; without being given $y$) unconditionally independently normally distributed with mean $\mu $ and standard deviation $\sigma$?
And, to the task at hand: How do I simulate random drawings of $X$ given $y,~ \mu,$ and $\sigma$?
Comment: Please just apply any of the formulas for conditional Normal distributions: https://stats.stackexchange.com/search?q=normal+conditional+variance.  The application is direct and simple, because $(X_1,\ldots, X_n, X_1+\cdots+X_n)$ has an $(n+1)$-variate Normal distribution whose parameters are particularly easy to compute from the independence of the $X_i.$
Answer: As pointed out by @whuber, we can simply use the known formulas for conditional distributions in the multinormal, as given for instance at Deriving the conditional distributions of a multivariate normal distribution (we will use notation from there).  At first I doubted, since the full covariance matrix $\Sigma$ in this case is singular, but a close reading of the proof by user macro shows that we only need that $\Sigma_{22}$ is non-singular. That $\Sigma$ itself is singular does not matter.
For this case, we can easily compute (details not given) that
$$
\Sigma =\begin{pmatrix} \Sigma_{11} & \Sigma_{12} \\
                        \Sigma_{21} & \Sigma_{22}
         \end{pmatrix}
       =\sigma^2 \begin{pmatrix}I_n & 1_n \\
                                  1_n^T & n  \end{pmatrix}
$$
where $I_n$ is the $n \times n$ identity matrix, and $1_n$ is the column vector with $n$ $1$'s. Then using the formulas we find that the conditional distribution of $X$ given that $Y=y$, where $Y=\sum_1^n X_i$, is the n-dimensional multinormal distribution with mean
$$ \mu_{x|y} = 1_n \frac{y}n $$ that is, all the components have the same conditional expectation $y/n$, and covariance matrix
$$ \Sigma_{x|y} = \sigma^2 \begin{pmatrix} I_n - 1_n 1_n^T / n
    \end{pmatrix} $$
Note that $1_n 1_n^T$ is an $n \times n$-matrix with all components 1.
Comment: I don't follow that, because the present question is *explicitly* about vectors!  Moreover, the method of this answer and the formula it relies on apply *without any modification whatsoever* to your new question.
Comment: This works like a charm. Thanks!
Comment: It's unclear what you might mean by "one more dimension," because all it means is -- the vectors are of a different dimension.  But since this answer applies to *all* dimensions, it applies to any situation you might contemplate.
Comment: I don't know if the extension to vectors is straightforward, so here's that question: https://stats.stackexchange.com/q/609277/370545
Comment: @whuber Scalars, vectors, matrices... What I meant was one more dimension. And I did not have too much trouble implementing the above answer, but I am having a terrible time implementing it for the higher-dimensional case. :(
Comment: @whuber This question (above) asks about $X_i$s that are scalars (and $X$ thus being a vector). The other question asks about $X_i$s that are vectors. So, in that question the $X$s are either matrices or vectors of vectors. I'm sure that the above answer provides the necessary clues on how to handle this, but I haven't figured it out yet.
Comment: This question asks about an $X$ that is explicitly a *vector.*  Any bunch of vectors is, according to the axioms, *also a vector.*  Your $y$ here is also a (dimension 1) *vector.*  Proceed from there.
Comment: @whuber OK, that is good to know (about the axioms). Thanks! But whereas the unconditional distributions of the $X_i$s are independent, they are not in the other question. To (hopefully) clarify: in the above question, the unconditional $X$  represents one time series (of length $n$). In the other question the unconditional $X$ represents a bunch of time series that have a covariance (matrix, I dare to say).
Comment: Right: and you just plug in the entries of that covariance matrix where needed and the remaining ones are given by the independence assumption.
Comment: @whuber I'm giving it a shot (in the other question).


Posicionar conteudo dentro do Navbar Bootstrap

Question: Estou utilizando e remodelando um navbar cujo template é feito pelo próprio site do Bootstrap porem após fazer inserções das classes que julgava capaz de posicionar os objetos notei que eles não estavam funcionando (apesar de muitos estarem), então aqui esta um print da pagina:

o meu intuito era centralizar o formulario search (inclui os radio button) e colocar no mesmo nivel os botões login e create account
Codigo com Bootstrap:

                <button class="navbar-toggle" type="button" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>
                Meu Site

                <form class="navbar-form" role="search">

                        <input type="radio" name="optradio">Option 1
                        <input type="radio" name="optradio" checked="">Option 1
                        <input type="radio" name="optradio">Option 1
                        <input class="form-control" type="text" placeholder="Search" />

                    <button class="btn btn-default" type="submit">Search</button>
                </form>

<button class="btn btn-default">Login

<button class="btn btn-default">Create Account

Answer: Acho que isso irá te ajudar:
<form class="navbar-form navbar-form navbar-left" role="search">

Substitua o código antigo pelo código acima.
Comment: @RicardoHenrique Nos botões Login e Create Account use a classe navbar-btn. Estou vendo o problema do campo de texto da pesquisa e já te dou outra resposta.
Comment: @RicardoHenrique Adicione este código nos botões: Login Create Account


Is "not independent" the same as "dependent" in English?

Question: When I learned about conditional probability, I found this statement:

if A is not independent of B then also B is not independent of A. Formally, if P(A) ≠ P(A|B) then P(B) ≠ P(B|A).

I think "not independent" is the same as "dependent", right?
So does that mean this statement is also correct: "if A is dependent on B then B is also dependent on A"? I'm a little bit confused because in my mother language, the translation of "dependent" is directed word that's not symmetrical.
Comment: By the way, in non-technical English it's "A is not independent of B" and "A is dependent on B" (or "A depends on B"). Different preposition. Also by the way, in statistics I'd never write it this way. I'd write either "A and B are independent" or "A and B are not independent". It's a symmetric relation. But I guess that's what you're being asked to prove.
Answer: In statistics, "dependent" and "not independent" have the same meaning. There is no inherent notion of causation.
In regular English, I would say that "dependent" implies causation. Dinner temperature depends on oven temperature, not the other way around.
Comment: "dependent" and "depends on" are different terms. This answer conflates them a bit, which may be misleading. In stats, it's correct usage to say "A and B are dependent", but it's incorrect usage to say "A is dependent on B" or "A depends on B" (unless you have a specific causal model maybe). Whereas in regular English, you wouldn't say "A and B are dependent" but you would use the other forms.
Comment: @usul I think I misunderstood the point of your comment at first. The *main* issue is as Dave said, and the answer is quite correct as-is. But I agree with what I think you're saying - it would be helpful to add a *note* that in addition to the meaning being fundamentally different, the way you construct sentences using the statistics definition of "dependent" and the regular definition also differs slightly.
Answer: Independence is more properly termed mutual independence which eliminates the use of "$A$ is independent of $B$" and replaces it by "$A$ and $B$ are mutually independent". Thus, there is no such thing as $A$ being independent of $B$ and wonderment if that implies that $B$ is dependent of $A$: independence is mutual. Be aware that "$A$ is independent of $B$ if $P(A\mid B) = P(A)$" is an incomplete statement as a definition: $A$ and $B$ can be independent even if $P(A\mid B)$ is undefined e.g. as when $B$ is an event of probability $0$.
The generally accepted definition  of independent events is that

$A$ and $B$ are said to be (mutually) independent events if $P(A\cap B) = P(A)P(B)$,

and as in all definitions, the "if" is understood to be "iff" or "if and only if".
Note the complete absence of "independent of" and the symmetry in the roles of $A$ and $B$. Except for those who do not believe in the commutativity of multiplication of real numbers or the commutativity of set intersection, the definition works equally well if we interchange $A$ and $B$ throughout in the definition.
Finally, turning to the question of whether "not independent" means "dependent", the answer is Yes.
Answer: In probability calculus there is no expression for causal dependency. No one can express with its semantics the popular example that manipulation on barometer do not change the weather, but changes of the weather change barometer measurements. Either two events 'tend to occurs together' (correlate) or not.
The very definition of independence is (probably) derived from the idea, that knowledge if $B$ occurred, do not change probability of occurring event $A$. This is formally written as $P(A) = P(A|B)$.
The contradiction to situation state is lack of independency: the probability of occurring event $B$ increases or decreases probability of occurring event $A$. This is true for barometer and the weather and expressed as $P(A) \neq P(A|B)$.
Mathematicians often know, that their not independency is not always the 'true' dependency and restrain themselves from using causally marked expression. Especially, that in econometrics or causal inference such definition is exist. Therefore at some probability calculus courses you would hear, that no one discussed $dependency$, the discussed ideas were not independency and correlation.
The mathematical tool which analyses dependency in the more natural meaning is do-calculus (by Judea Pearl). This tool extends standard probability calculus with the do operator, which describes intervention in the system. For the barometer and the weather all four statements will be true:
$$P(A) \neq P(A|B)$$
$$P(B) \neq P(B|A)$$
$$P(B) \neq P(B|do(A))$$
$$P(A) = P(A|do(B))$$
In this context I would strongly discourage using word dependent in context of standard probability calculus and statistics. Not independent is good enough, and in fact more precise in context of this 'more advanced' mathematics.
Comment: Good points. Another way of looking at it is that writers who use "not independent" are not just being needlessly verbose. There are *reasons* to prefer it to the shorter word "dependent". In addition to what you mention, most pairs of events are dependent, it is seldom necessary to mention it -- except when you want to contrast it with independence. Thus "not independent" is often a way of emphasizing what you want to emphasize.
Answer:
"if A is dependent of B then also B is dependent of A"

Grammatically, that is not correct; the correct preposition is "on", not "of".
Mathematically, the term "dependent" is often used in a nonsymmetric sense: if y is being treated as a being a function of x, then y is dependent on x. In experimental setup, the variable we directly control is called the "independent" variable, and the one that results from the independent variable is called the "dependent" variable.
If you wanted to emphasize the symmetrical nature, you could say "x and y are dependent on each other".
Answer: "Not independent" and "dependent" are grammatically same, not only in English but also in other languages as well, including the language of mathematical logic. However, when discussing statistics, one has to use more accurate language. The key observation is that two events can be independent in a unique way, but there are many ways in which they can be dependent (such having a causal relationship, etc.). There is no point in saying that events or random variables are dependent without describing the structure of the dependency. Stating that two events are just "dependent" is meaningless.


Determine whether the list in k^4 is linearly independent.

Question: Determine whether the list
$v_1 = (1, 1, −1, 2), v_2 = (2, 2, −3, 1), v_3 = (−1, −1, 0, −5)$
in $k^4$ is linearly independent.
Work:
I put it into $Ax=0$ form:
\begin{bmatrix}
    1 & 2 &  -1  & | & 0 \\
    1 & 2 &  -1  & | & 0 \\
    -1 & -3 &  0  & | & 0 \\
    2 & 1 &  -5  & | & 0
\end{bmatrix} and reduced it down to:
\begin{bmatrix}
    1 & 0 &  -3  & | & 0 \\
    0 & 0 &  0  & | & 0 \\
    0 & 1 &  1  & | & 0 \\
    0 & 0 &  0  & | & 0
\end{bmatrix}
and so $Rank (A)=2 \neq 4$.
I'm not sure what to do from here - does this mean the list is linearly dependent?
Comment: $(2,2,-3,1)=3(1,1,-1,2)+1(-1,-1,0,-5)$
Answer: They are linearly dependent as you see, we have here three equations in four variables so we can always find solutions where all four are not zero. Hence the system is linearly dependent.


R glmer.nb output. How to get $\hat{\theta}$?

Question: I would like to obtain estimated $\theta$ from glmer.nb function in lme4 package. In my understanding this function fits the model:
$$
Y_{ij}|\boldsymbol{B}_{i}=\boldsymbol{b}_i \overset{ind.}{\sim} NB\Big(mean=\mu,var=\mu + \frac{\mu^2}{\theta}\Big)
$$
where $NB$ refers to the negative binomial distribution and:
$$
\mu = \exp(\boldsymbol{X}_{ij}^T \boldsymbol{\beta} + \boldsymbol{Z}_{ij}^T \boldsymbol{b}_i)
$$
and
$$
\boldsymbol{B}_i \overset{i.i.d.}{\sim} MVN(mean=\boldsymbol{0},var=\Sigma).
$$
So glmer.nb must be estimating unknown parameters $\boldsymbol{\beta}$, $\Sigma$ and $\theta$ via maximizing its likelihood. The help file of glmer.nb little explains its functionality, and it says "glmer() for Negative Binomial". However, the negative binomial is NOT an exponential family when the parameter $\theta$ is unknown. So $\theta$ must be estimated in some other ways that generalized linear mixed effect models (GLMM) do not take, and the estimated $\theta$ must be obtained in some special ways that GLMM do not take. How can I access to the estimate of $\theta$ which should be one of glmer.nb output?
Answer: Looking at the source code, this isn't something that is trivially exposed. Essentially, glmer.nb is (from github sources):
glmer.nb <- function(..., interval = log(th)+c(-3,3), verbose=FALSE)
{
  g0 <- glmer(..., family=poisson)
  th <- est_theta(g0)
  if(verbose) cat("th := est_theta(glmer(..)) =", format(th),"\n")
  g1 <- update(g0, family = negative.binomial(theta=th))
  ## if (is.null(interval)) interval <- log(th)+c(-3,3)
  optTheta(g1, interval=interval, verbose=verbose)
}

Which essentially is:

fit a standard Poisson GLMM
estimate $\theta$ using maximum likelihood estimation given this standard Poisson fit. This uses MASS::theta.ml()
refit the model using this value of $\theta$ and the negative.binomial() family function which needs a fixed $\theta$,
last line does an optimization to find $\theta$ given the updated fit, and that function throws an error if the original estimate from 2. and the optimised one from 4. don't match.
the last line performs 1-d optimisation on the interval log(theta) + c(-3, 3) via optimize() to find the value of $\theta$ that minimises the deviance of the negative binomial GLMM.

That said, you might try:
lme4:::getNBdisp(fit)

where fit is the model returned by glmer.nb. This is just a guess based on reading the code but it is used by the authors in tests etc.
Comment: Thank you very much for reading the source code. I understand that this algorithm is iteratively maximizing ($\Sigma$,$\beta$), and then $\theta$, twice to find MLE. It is interesting and surprising for me that two iterations are enough to find the maximum likelihood estimates.
Comment: It isn't doing just two iterations. The first estimate in 2 is derived using maximum likelihood via the `theta.ml` function from the [MASS](https://stat.ethz.ch/R-manual/R-devel/library/MASS/html/theta.md.html) package, given information from the Poisson fit in 1. It then refits a negative binomial model with this theta fixed. In 4 I was mistaken: what is done is a 1d optimization for theta by minimizing the deviance of the fitted NB GLMM.
Comment: I see now what is being done; the first couple of lines get you close to the MLE of $\theta$ and a NB GLMM is fitted using this, then 4 homes in on best theta by trying all values of theta around  +/- the initial estimate to find one that gives minimum deviance.


Cannot scroll DIV for Primefaces' Tiered Menu

Question: How to do auto scroll for Primefaces Tiered Menu?
I would like to set div width 200px. At that time, I cannot see the primefaces sub-menu.
I would like bring to front sub-menu of tieredMenu.
Code
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:c="http://java.sun.com/jsp/jstl/core"
    xmlns:p="http://primefaces.org/ui"
    xmlns:fu="http://java.sun.com/jsf/fileUpload"
    template="/common/commonLayout.xhtml">
    <ui:define name="content">
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

        <h:form enctype="multipart/form-data">

        </h:form>
    </ui:define>
</ui:composition>

Need your suggestions.
Update  I update the picture and code for more clear.
I would like to see
 the top of DIV.
Comment: For setting up the width, something like this maybe http://stackoverflow.com/questions/16979300/how-to-auto-adjust-the-length-of-submenu-of-primefaces
Comment: @Andy, It is notwork for me. thz for your help
Comment: Do you want to bring sub-menu out of the scrollable DIV? right??
Comment: @KishorP Yes, I would like to do like that.
Answer: Here use the following JQuery script, right after you closing the div tag:
[PUT the script after DIV tag]

After Huge effort I finally came up with this script:

Comment: thanks for your answer, But, it is still cannot see the sub-menu. DIV cover the sub-menu like my picture.
Comment: I update as u suggest. `Position Fixed` is problem. Sub-menu display top of the browser. How can I click sub-menu. Plz, check my new uploaded image. Thanks for your supporting.
Comment: I'll fix it and let you know!!
Comment: see the edited answer. Please select it as correct answer(If it works for you)
Comment: @KishorP This is really nice.


Does $g$ always normalize $H \cap H^g$?

Question: Let $G$ be any group, $H$ a subgroup, $g$ an element of $G$ and $H^g:=g^{-1}Hg$ the conjugate of $H$ by $g$. Is it true that $$g\in N_G(H\cap H^g)?$$
Answer: No.
As a counterexample take $G$ to be the split extension of an elementary abelian group of order $16$ by a cyclic group of order $4$ with this action
$$
G=\left\langle x_1,x_2,x_3,x_4, g\mid x_i^2=1, x_i x_j=x_j x_i,   g^4=1, x_i^g=x_{i+1 \mod 4}\right\rangle
$$
and let $H=\langle x_1,x_2\rangle$.
Then $H\cap H^g=\langle x_2\rangle$ is not normalised by $g$.
Comment: The same idea would work with an elementary group of order $8$ with an acting element of order $3$.
Comment: Indeed @DerekHolt, I suppose I just wanted to give myself a bit of elbow room! And I suppose I show the answer is "not even in a $p$-group".

Does $g$ always normalize $H \cap H^g$?


Tamanho de fonte de texto dentro de um botão

Question: Como consigo mudar o tamanho da fonte do texto que esta dentro de um botão? Estou usando Materialize.
featured_play_listVer Lista de Compras
updateAlterar Produto
add_circleCadastrar Produto
deleteExcluir Produto

Valeu.
Comment: E o que você sabe de CSS?
Comment: pouco na vdd... hsuahsauhsauhsaushaush
Answer: Cria uma class em CSS.
.minhaclass{
    font-size: 18px;
}

Aplica ela depois das classes que já estão sendo chamadas, assim irá sobrepor.
featured_play_listVer Lista de Compras

Comment: muito obrigado, cara...


Can I use a C# dll with unsafe code in VB.NET?

Question: There is an FastBitmap class for C#, that lets you acces and modify pixel information of am bitmap. I have already used it in some C# project, but I need it now in VB.NET.
The problem is that that class uses unsafe code, that is not supported in VB.NET.
The question is. Can I compile the FastBitmap class in a dll and use it in VB.NET?
[EDIT]
Or is there  some library that can be used to modfy pixel data in VB.NET?
Answer: Yes, you can do that.
If the class doesn't expose any unsafe features in its public interface (e.g. method taking a pointer) then you shouldn't have any problems using it from VB.NET. The common language runtime (CLR) supports unsafe code, so C# doesn't do any magic when you write unsafe programs.
If you wanted, you could also reimplement the FastBitmap class in VB.NET using the Marshal class, which gives you fast access to memory using a standard .NET interface accessible from VB.NET as well. But the ability to mix multiple languages in a single project is a great advantage of .NET.
Answer: Fast answer, yes. By the way, did you try it?
Comment: No, I didn't try it. I was busy at the moment that I came with the idea and didn't have time to experiment.


MySQL Simple Forum

Question: So I'm trying to build a simple forum. It'll be a list of topics in descending order by the date of either the topic (if no replies) or latest reply. Here's the DB structure:
forum_topic

id, name, email, body, date

forum_reply

id, email, body, date, topic_id

The forum itself will consist of an HTML table with the following headers:

Topic, Last Modified, # Replies

What would the query or queries look like to produce such a structure? I was thinking it would involve a cross join, but not sure... Thanks in advance.
Comment: Just a word of advice - this will be painful to extend if you later want to add a proper user-login system, and/or a threaded reply structure.
Answer: Somewhat like this:
select * from forum_topic
inner join forum_reply on forum_topic.id=topc_id

However, don't use select *
That's bad practice :)
And I don't like the way you avoid normalization! Meaning I would rather have:
Users

UserID
Name
Email

Threads

ThreadID
Subject
Answered
AskedByUserID
Date

Replies

ReplyID
ThreadID
UserID
Answer
Date

Then selecting a Thread like this:
select ThreadID, Subject, Answered, AksedByUserID, Date from Threads

And selecting all replies like this
select Answer, Date, Name, Email from Threads
inner join Replies on Threads,ThreaID=Replies.ThreadID
inner join Users on AskedByUserID=UserID
where Threads.ThreadID=xxx

Now this was just written from the top of my head, but you might need to add some group by as well.
Comment: There seems to be some harsh downvoting going on indeed. I would guess in your case it's because your query doesn't actually return the data required
Comment: No idea why you got downvoted. FYI, the columns were named as such for simplicity in explanation :-)
Comment: What i provide is just an example of how a "better" forum would be presented and an example of how to use the joins, downvoting is just evul when trying to provide some solid nice examples.
Comment: I figured you wanted to select the forum thread and not a list of all threads, im sorry for the missunderstanding. For that you would use COUNT and have to use a GROUP BY clause.
Comment: Also my respons is more of a generic one to show a simplified structure which follow normalization rules.
Answer: Yes, you should be able to get it with a query like this:
SELECT
  forum_topic.id,
  forum_topic.name AS Topic,
  MAX(forum_reply.date) AS Last_Modified,
  count(*) AS  Replies
FROM forum_topic
INNER JOIN forum_reply ON (forum_topic.id=forum_reply.topic_id)
GROUP BY forum_topic.id

The "group by" is the magic that gives us one row per topic, with the MAX() and COUNT() functions giving us the aggregated data you need.
(EDIT: I missed that the body of the first post was in the topic table, so posts with no replies would get missed by the above query. Filip has the right idea suggesting you normalize your data. Once normalized, a query similar the above would get you the data you need).
Comment: That's close, but with that query, the topic won't appear if it has no replies.
Comment: Damn, yes missed that. Assumed first post was a reply, but as there's a body in the topic....
Answer: First off, it seems to me noboody is actually answering your question, which was:

What would the query or queries look like to produce such a structure?

with a requested structure of
Topic, LastModified, # Replies.
The SQL to produce a result table with that structure, given the table structures you provided, would be:
SELECT t.Id, t.Name AS Topic,
       MAX(r.Date) AS LastModified,
       COUNT(*) AS NumReplies
FROM Forum_Topic t
LEFT OUTER JOIN Forum_Reply r ON t.id = r.topic_id
GROUP BY t.Id, t.Name

(sorry, this is tested only on SQL Server, as I don't have access to MySql at the moment)
Also, your structure IS already normalized. Suggestions to the contrary are making assumptions about what you want to do, e.g., assuming that you are interested in tracking user names in addition to email addresses. This is quite reasonable, but is nevertheless an assumption. There is nothing wrong, from a normalization perspective, with using email address as a unique user identifier.
Now, if you are looking for general suggestions on how to set up a database, we can give you LOTS of those. Before normalization, I would start with not using potential keywords as object names (e.g., don't give columns names like 'Name' and 'Date').
Regarding the comment from Matt about the value being NULL when there are no replies: using the COALESCE() function will fix that. COALESCE() returns the first non-NULL argument (or NULL if all arguments are NULL). So replace the MAX(r.Date) with MAX(COALESCE(r.Date, t.Date)).
Comment: That's 99% there. All topics now appear. The only problem now is that LastModified = NULL  when the topic has no replies. Any ideas?
Comment: It acutally doesnt follow normalization if you have a PK & Email and both are repeated. Then you will have redundance. But that's argumentative so let's just keep it out, just wanted to point out some important points and help to achieve the goal :)
Comment: Rob, you're the man. Works perfectly. Thanks everyone for the help!
Answer: By "normalized", you mean that the body column of "forum_topic" should be removed, and the actual topic body should be the first reply?
Comment: You can read more about that here: http://www.devshed.com/c/a/MySQL/An-Introduction-to-Database-Normalization/
Comment: Normalization bascily means to not repeate yourself when you dont need to. You have for instance "Email" in more than one place, i would rather use a User-table to store that.
Comment: Right, it's really a trade-off. Disk space vs. processor time. Joins can be expensive -- normalization isn't always the be-all end-all. In this case, I need for the topic itself to contain a description field. What would it take to modify your (or Paul's) query to show topics, even w/out replies?
Comment: Not very much. You simply do:
; select * from Threads
inner join Users on Threads. AskedByUserID=UserID
;
which will join the Usertable, giving you information about the users and the topic. However with replies you need to join that one too. Twice i'd say if you want the asking user info aswell.

MySQL Simple Forum


Launch function at the end of another swift

Question: I need to launch the funcion "caricaImmagine" after the function "caricaLavori". In the code is clear that caricaImmagine need that caricaLavori finish to append item to an array.
I've tried this but I don't know how to implement it.
Here's the "newMethod" (called in viewWillAppear):
<code> func newMethod(){
    print("login: \(login)")

    let userFetch = NSFetchRequest<NSFetchRequestResult>(entityName: "UserEntity")

    do {
        fetchUsers = try moc.fetch(userFetch) as! [User]
    } catch {
        fatalError("Failed to fetch person: \(error)")
    }

    do{
        let users = try moc.fetch(userFetch)
        if(users.count > 0){
            print("utente connesso")
            tableview.delegate = self
            tableview.dataSource = self
            let d_email = fetchUsers.first!.email

            caricaLavori(datore_email: d_email!)
            for i in 0...lavori.count{
                caricaImmagine(id_lavoro: lavori[i].id)
            }

        }else{
            DispatchQueue.main.async {
                self.performSegue(withIdentifier: "area_utente_segue", sender: self)
            }
        }
    }catch {}
}
</code>
If you want the other 2 functions I'll edit this post (both of them loads data from php script, both do an http request)
thank you guys
Answer: You say "both of them loads data from php script, both do an http request". That is a key piece of information.
On iOS you want to do network access asynchronously. That means that a function that submits a network requests submits that request and then returns immediately, before the request has even been sent to the remote server.
The solution is to write your methods to take a completion handler. The method invokes the completion handler once the task is complete.
Take a look at my answer in the thread below for code that includes a working example of using completion handlers:
Storing values in completionHandlers - Swift
Note that that post (And the sample app it links to) was written in Swift 2, and will need to be updated for Swift 3.


Where is the email New release(s) available coming from

Question: With Drupal 7, we are getting some emails that say "New release(s) available for name of site" , but they are going to someone who doesn't work here any more, and they are bouncing back to me.
Where are these emails coming from, they seem to be from drupal but I can't find where this is configured.
Thanks!!
Answer: It's configured on the "Available updates" settings page at /admin/reports/updates/settings:
Answer: Remove email address present at admin/reports/updates/settings.


How to count specific values from table

Question: I have below query that give my the next results (below).
I would like to know how can I count the "MIR_ID" that appears more than once only from query results (if it possible).
Thanks!
My query:
with Source as (
select
request_id
,description
,substring(VwDurationIndicator.RequestDetails, 5, 6) as Mir_ID
, request_type

from vortex_hvc.dbo.VwDurationIndicator
 left join
 vw_public_request_material_location_mir
 on substring(VwDurationIndicator.RequestDetails, 5, 6) like vw_public_request_material_location_mir.material_request_id
where DateDiff(hour, CreatedTime, getdate()) < 9 and
 request_type = 'MIR' and SITE = 'HVC'

        )
 select Source.*

 ,count(Mir_ID) as total
 from Source

 group by Mir_ID,request_id,description,request_type

 order by request_id

Query return:
request_id  description Mir_ID  request_type    total
152788  VPO: Y7363040RS, Step: PPV-M, Bin: BIN 01   335403  MIR 2
152788  VPO: Y7242580, Step: PPV-S FUSE, Bin: BIN 01    335403  MIR 1
152788  VPO: Y7243570, Step: PPV-S, Bin: BIN 01 335403  MIR 1
152788  VPO: Y7243580, Step: PPV-S, Bin: BIN 01 335403  MIR 1
152788  VPO: Y7322650, Step: PPV, Bin: BIN 01   335403  MIR 5
152788  VPO: Y7363020, Step: PPV-M, Bin: BIN 01 335403  MIR 2
152791  VPO: Y7324440, Step: OLB, Bin: BIN 2571 335412  MIR 1
152791  VPO: Y7324550, Step: OLB, Bin: BIN 2571 335412  MIR 1
152791  VPO: Y7324480, Step: OLB, Bin: BIN 2571 335412  MIR 2
152791  VPO: Y7324590, Step: OLB, Bin: BIN 2571 335412  MIR 1
152791  VPO: Y7324540, Step: OLB, Bin: BIN 2571 335412  MIR 1
152791  VPO: Y7324580, Step: OLB, Bin: BIN 2571 335412  MIR 3
152791  VPO: Y7324430, Step: OLB, Bin: BIN 2571 335412  MIR 1
152791  VPO: Y7324660, Step: OLB, Bin: BIN 2571 335412  MIR 1
152791  VPO: Y7324470, Step: OLB, Bin: BIN 2571 335412  MIR 1
152792  VPO: Y7342740, Step: PRODUCTION BURN-IN, Bin: BIN 01    335419  MIR 1
152792  VPO: Y7342730, Step: PRODUCTION BURN-IN, Bin: BIN 01    335419  MIR 1
152794  VPO: Y7324480, Step: OLB, Bin: BIN 2571 335420  MIR 1
152794  VPO: Y7324540, Step: OLB, Bin: BIN 2571 335420  MIR 1
152794  VPO: Y7324420, Step: OLB, Bin: BIN 2571 335420  MIR 2

Comment: By using COUNT????
Comment: if you have others ideas you're more than welcome :)
Comment: What would really help is some ddl, sample data and the desired output for that sample data. From the gibberish posted above it is impossible to tell what is in what column. Here is a great place to start. http://spaghettidba.com/2015/04/24/how-to-post-a-t-sql-question-on-a-public-forum/
Answer: This should do the job:
SELECT MIR_ID, COUNT(*) AS COUNT_MIR_ID
FROM YOUR_RESULT
GROUP BY MIR_ID
HAVING COUNT(*) > 1;

Assuming YOUR_RESULT contains the result you provided in the post. You can either store your result in a table OR use this query outside your original query.
Comment: hi,
I have checked it but query retunes no values after executing.
Comment: What are possible values of `MIR_ID`? I am not able to figure out from your post.
Comment: my mistake it return values but not counting according to MIR_ID.
Comment: Are you storing the results in a table before running the `COUNT(*)`? If so, try verifying the table contains the results as expected.
Comment: only numbers... for example after query executing I want to see that MIR_ID "335403" appears 5 times and like this for all others MIR_ID numbers.
Comment: What is the count you are getting for `MIR_ID` 335403?
Comment: Its appears at 3 different rows, one of them has 2, 2nd has 5 and the last have 2 ( in my original results this Mir_id appears 6 times so this is the number I want to get)

How to count specific values from table


The Frattini subgroup contains a power of a certain subgroup

Question: This is from an article by Hall from 1961; it's probably one of the most trivial observations in that article, but I can't get the reasoning.
Let G be some group and let A be a normal abelian p-subgroup of G for some prime p. We want to show that $A^p$, the subgroup of p-th powers of elements of A, is contained in the Frattini subgroup of G.
So let M be a maximal subgroup in G which doesn't contain A and denote $N=M\cap A$. I have managed to show that N is normal in G and that A/N is a minimal normal subgroup of G/N. So
A/N can't have any nontrivial proper characteristic subgroups. Therefore $A^pN=N$, in which case we are done, or $A^pN=A$. I don't know where to go from here. I suppose the fact that A is a p-group should come into play somewhere, since all of the above works for any exponent n instead of p.
Comment: Can you point to the location in the paper where you find this claim (you probably should also give a citation for the paper, but I'll do that for you): Hall, P. Frattini Subgroups of Finitely Generated Groups, PLMS (3) 11, 1961, 327--352.
Comment: Are you talking about Lemma 10? He gives a proof. Regarding your write-up above, $A/N$ is an elementary abelian p-group, so has exponent p; that is, $A^pN/N$ is trivial.
Comment: Yes, it's Lemma 10 in that paper. The thing is, I don't see why $A/N$ should be elementary abelian.
Comment: $A/N$ is an abelian p-group with no non-trivial characteristic subgroups.  So what does the subgroup of elements of order p look like?
Comment: Right. The subgroup of elements of order p ($\Omega_1(A/N)$ I guess) is characteristic in $A/N$. If it were trivial, then $A/N$ would be trivial, otherwise it is the whole of $A/N$, which therefore is of exponent p. Great, thank you. Maybe you should post something as an answer.

As a side note, am I right in thinking that we could have a trivial subgroup of elements of order n (n not a power of p) in $A/N$, and not have the whole quotient group trivial?
Comment: @Miha: OK, I'll add an answer.  Yes you are right about general $n$; take $A=C_{p^2}\times C_p\times C_q$, with $n=p^2q$, but $A/N = C_p\times C_p \times C_q$ has no elements of order $n$.
Answer: Let $G$ be a group with a normal abelian p-subgroup $A$.  Let $M$ be any maximal subgroup of $G$ not containing $A$, then $N=M\cap A$ is normal in both $M$ and $A$ so is normal in $G=MA$.  If there is a normal subgroup $B$ of $G$ with $N < B\le A$, then $B=B(A\cap M)=BM\cap A = A$. So $A/N$ is a minimal normal subgroup of $G/N$. Thus $A/N$ is an abelian p-group which has no non-trivial characteristic subgroups.  Since $A/N$ certainly contains an element of order p, the subgroup of all elements of order p is $A/N$, and thus $(A/N)^p=A^pN/N$ is trivial, and so $A^p\le N\le M$.
Answer: The Frattini subgroup of $G$ is also the intersection of the maximal (proper) normal subgroups of $G$.
Let $M$ be such a subgroup.
If $M \cap A = A$, no problem.
So assume $M$ does not contain $A$.
Let $\{g_1,\ldots,g_k\}$ be a maximal subset of $A$ such that $M' = \langle M , g_1, \ldots, g_k \rangle$ does not contain $A$.
Then $M'$ is normalized by $A$ (the assumption that $A$ is abelian is used here), so for any $g \in A \setminus \left( M' \cap A\right)$, $\langle M',g \rangle = \left\{m'g^k\ |\ m' \in M',\ k \in \mathbb{Z} \right\}$.
By maximality of our subset of $A$, for any $a \in A$, $a = m'g^k$ for some $m' \in M'$ and some $k \in \mathbb{Z}$.
$m'=ag^{-k} \in A$, so we get that $M' \cap A$ is a maximal subgroup of $A$, so contains $A^p$ (the Frattini subgroup of a $p$-group $A$ is equal to $A^p[A,A]$, which is equal to $A^p$ in this case).
Since $M'$ does not contain $A$, $M'$ is a proper subgroup of $G$, containing $A^p$ and $M$.
Since $M = \cap_{g \in G} gM'g^{-1}$ by maximality, and $gA^pg^{-1}=A^p$ for any $g \in G$, $A^p \subset M$, and we win.
There must be an easier proof of this.
Comment: Could you explain (or point to a reference) why $Frat(A)=A^p[A,A]$ for an arbitrary $p$-group $A$? I'm aware of this fact only in the case $A$ is finite, where the proof hinges on the fact that maximal subgroups have index $p$ in $A$.
Comment: Oops, shame on me, I thought the term "$p$-group" implied "finite"... and I didn't think to look up the article before posting.


Strict Inequality in Homogenous LMI

Question: I'm studying Stephen Boyd's notes for EE 363, here.
In particular, I'm working through lecture 15, slide 9 on strict linear matrix inequalities.
An LMI is an expression of the form $G(x) = G_0 + x_1G_1 + \cdots + x_nG_n \geq 0$, where $G_i$ are symmetric $m \times m$ matrices and $x \in \mathbf{R}^n$.  The inequality is understood relative to the positive semidefinite cone.  If $G_0 = 0$, then $G(x)$ is homogeneous.  That is, $G(\alpha x) = \alpha G(x)$ for $\alpha > 0$.
Consider the set of all $x$ defined by the matrix inequalities $F(x) \geq 0$ and $F_\text{strict}(x) > 0$, where $F$ and $F_\text{strict}$ are homogeneous in $x$.  In the slide, he states that these inequalities can be replaced with $F(x) \geq 0$ and $F_\text{strict}(x) \geq I$.  My question is how to show this.
I have been unable to prove that this set is equivalent to the one defined by the inequalities $F(x) \geq 0$ and $F_\text{strict}(x) \geq I$.  I've unsuccessfully tried using the fact that if $A > 0$, then $A \geq \epsilon I$ for some $\epsilon > 0$ combined with the homogeneity of $F$ and $F_\text{strict}$.
Here's a related question which is essentially the same.
Thanks in advance!
Comment: I did posted an answer to [your linked question](https://math.stackexchange.com/questions/595365). But I am not sure if the same reasoning can be applied here because of the constant term $G_0$.
Comment: I read through your answer and I see your reasoning.  Here we have that  any $x$ which satisfies $F(x) \geq 0$ and $F_\text{strict}(x) \geq I$ must also satisfy $F(x) \geq 0$ and $F_\text{strict}(x) > 0$.  However, I'm still uncertain about how to show the converse.
Comment: You're also right that the definition of LMI that I gave above is not homogenous.  I've edited the post to fix this.
Comment: Does this answer your question? [Are $A^TP+PA<0$, $P>0$ and $A^TP+PA\leq-I$, $P\geq I$ equivalent?](https://math.stackexchange.com/questions/595365/are-atppa0-p0-and-atppa-leq-i-p-geq-i-equivalent)
Answer: You can. You have $F_{strict}(z)>0$  implies that $\exists \epsilon >0$ arbitrary small enough such that $F_{strict}(z)\geq \epsilon I$ and since $F_{strict}(z)$ is homonogeous in z then you get $F_{strict}(\frac{1}{\epsilon}z)\geq I$.
On the other hand, you have $F(z)\geq0$ and $F(z)$ is also homologous in z which implies $F(\frac{1}{\epsilon}z)\geq 0$. Using the exchange of variable $x=\frac{1}{\epsilon}$ you obtain $F(x)\geq 0$ and $F_{strict}(x)\geq I$.
Hence you have proved that $F(x)\geq 0$ and $F_{strict}(x)>0$ implies that $F(x)\geq 0$ and $F_{strict}(x)\geq I$. The implication in the other direction is evident.
Answer: As I said in my comment, any $x$ which satisfies $F(x) \geq 0$ and $F_\text{strict}(x) \geq I$ must satisfy $F(x) \geq 0$ and $F_\text{strict}(x) > 0$ because $I > 0$. I don't think that the converse of this statement holds in general.
However, suppose that we have any $x$ such that $F(x) \geq 0$ and $F_\text{strict}(x) > 0$.  For some $\epsilon > 0$, we must have that $F_\text{strict}(x) \geq \epsilon I$, and because $F$ and $F_\text{strict}$ are homogeneous, this implies that $\frac{1}{\epsilon}F_\text{strict}(x) = F_\text{strict}(\frac{1}{\epsilon}x) \geq I$.  We also have that $F(\frac{1}{\epsilon}x) \geq 0$.  Let $y = \frac{1}{\epsilon} x$, so $F(y) \geq 0$ and $F_\text{strict}(y) \geq I$.
So, in this context, solving the non-strict version (i.e., finding any $x$ satisfying  $F(x) \geq 0$ and $F_\text{strict}(x) \geq I$) gives a solution satisfying the strict version (i.e., $F(x) \geq 0$ and $F_\text{strict}(x) > 0$).  For any strict version solution there must exist a non-strict solution, $y$, which will itself satisfy the strict version.
We conclude that $F(x) \geq 0$ and $F_\text{strict}(x) > 0$ has a solution if and only if $F(x) \geq 0$ and $F_\text{strict}(x) \geq I$ has one.

Strict Inequality in Homogenous LMI


Collect inputs from two separate SharePoint lists and save results in a third list

Question: I'm building an app that has two screens, and these two screens are connected to two separate SharePoint lists.
Screen 1 is connected to the list 'Employees'. In this screen, I have an edit form with various fields related to individual employees, some are text freeform like Name and some are combo boxes (determined by the Sharepoint column's choices). When a user saves the form, it creates a new item in that list. This is what it looks like.
In Screen 2, I have a Container that is connected to the list 'Checklist'. This list is different because it's already filled - each item is a question and these questions have corresponding columns that give more detail about the question. For each question there is also a Yes/No choice column.
The Container is split into a Gallery on the left, and a view form and edit form on the right (so that the Yes/No choice can be selected). It also has a dropdown list that selects the Names from my first Employees list. After a user completes the checklist and answers Yes or No next to each question, they then click Save. This is what it looks like.
What I want to achieve is: the Save button taking everything from Screen 2 and saving it in a third SharePoint list called 'EmployeeChecklistScores'. I want it to take the employee name selected in the dropdown in Screen 2, but then calculate the Yes/No answers. If Yes then 1, if No then 0.
If the user answered 10 questions with Yes, then after clicking Save I want to have the EmployeeChecklistScores list showing two columns: Name (John Smith in this case) and Total score (10 in this case).
Basically, the purpose of this is to have is a checklist that can be filled out for each employee and then a total score calculated based on that.
Appreciate any advice here.
Edit (re comment below): New save button.
Answer: After the users submit their data on Screen1, you can refer to the data with Form1.LastSubmit.
PowerApps supports some data type coercing, so you can actually add up booleans:
true + true + false = 2

In your case, I believe Yes/No radio buttons would be better in Screen2 instead of the dropdown. This way, the user has to click anyway. In the OnChange of the radio element you can track their choices as booleans in a collection. You can then use a formula like Sum(MyCollection.BooleanColumn) to calculate the final score.
Also, if you are not planning on storing multiple results per employee, you could consider storing results simply in the first SharePoint list. Best of luck with your project.
Comment: Thanks for the reply and suggestion. I've simplified things and used a gallery for the questions and a radio button for the answers. Here is what I've used for the save button - https://i.stack.imgur.com/FOt5c.png - however it doesn't calculate the responses separately. If you pick yes in one and yes in the other it will still show 1 in total, whereas I want it to add up the responses (if two yes answers then a total of 2, if one yes and one no then a total of 1).
Comment: I checked your picture, and I don't think your formula is correct. You are using Sum() to evaluate Gallery.AllItems but you're not referencing any of its fields. Also, albeit not highlighted as an error, I guess referencing a control in the context of Gallery.AllItems would also not work. I still suggest you take the above recommended approach to ensure the calculation is dynamic.


sequence of functions for which the derivative is bounded converges uniformly?

Question: I'd like to prove that for a sequence of differentiables functions $(f_n)$ on $[0;1]$ which converges to $0$, actually converges uniformly.
We only know that $\vert f'_n(x)\vert \leq 2015 + \cos(x) $ for all $x$ and $n$.
I know that it means that the derivatives of all functions from the sequence is bounded by 2016 and thus they are lipschitz, but I don't know if it helps to prove that the convergence is uniform.
Any help would be welcome.
Answer: You have indeed identified the key element of the proof. The other is the compactness of $[0, 1]$.
If you don't want to work it out yourself :
Let $\varepsilon > 0$.
Since $[0, 1]$ is compact, there exists an integer $N$ and $x_1, \ldots, x_N \in [0, 1]$ such that
$$[0, 1] \subset \bigcup_{0 \leq i \leq N} B(x_i, \frac{\varepsilon}{2016}).$$
(no need for big guns here, you can just take $N = \mathrm{floor}(2016/\varepsilon)$ and $x_i = i/N $.
Since $f_n(x_i) \underset{n \to \infty}{\longrightarrow} 0$ for every $0\leq i \leq N$, there exists $n_0 \geqslant 0$ such that
$$\forall n \geq n_0, \forall 0 \leq i \leq N, |f_n(x_i)| \leq \varepsilon. $$
If $y \in [0, 1]$, there exists an index $i_0$ such that $x \in B(x_{i_0}, \frac{\varepsilon}{2016})$. Thus, applying the triangle inequality,
$$ \forall n \geq n_0, \quad |f_n(y)| \leq |f_n(y) - f_n(x_{i_0})| + |f_n(x_{i_0})| \leq 2016\cdot |y - x_{i_0}| + |f_n(x_{i_0})| \leq 2 \varepsilon. $$
Hence, $$\forall n \geq n_0, \|f_n\|_{\infty} \leq 2\varepsilon.$$ The convergence is uniform.


What implications do the formal rules of inversions have for suspended chords?

Question: I understand about the relationship between run-of-the-mill suspended chords and inverting them. For example, I know a Gsus2 (GAD) is an inversion of Dsus4 (DGA). Whatever ADG ought to be called, other than Gsus2 in 1st inversion or Dsus4 in 2nd inversion, I'm not sure.
Now Wikipedia insists that a chord in 1st inversion must have a third as the lowest note and the root a sixth above it, which has implications for my assumptions. If there's an unusual chord like this...

...would it be correct to say it's in 1st inversion or not? Granted there is no third—E—so, by the Wikipedia definition, it falls short. Intuitively, though, it is. At least to me.
So if the answer is no, that's not 1st inversion, would I have to name that chord Fsus2add♭9,♯11,13? Or F13♭9,♯11sus2omit7? Or Fsus2,♯4add♭9,13?
Or what if the D were lowered one octave? Would it now be Cmaj9♯11sus4 in 4th inversion? Or would that also require E to be present?
(I know, I know... context. Please remember this question is purely about formal theory and the example chord is just an example.)
Comment: There is no mystery in how you would name an inversion of a suspended chord. If the 4th is in the base, it is in first inversion. Whether you should call such a collection of notes a sus chord or something else is another question. Classical harmony considers four triads (maj, min, aug, dim), so inversions of sus triads don't make sense in this context. Jazz harmony treats sus chords differently, and sus triads are commonly referred to, at least in practice. Context.
Comment: @DavidBowling Can you suggest a source that discusses how to name inversions of suspended chords, then?
Comment: "I know, I know... context." -- Well, context is important when naming chords. Also, I doubt that Wikipedia is the best source for learning music theory.
Comment: I don't see a discussion of sus triads in either Piston (referenced in the Wikipedia article) or in Nettles & Graf (*The Chord Scale Theory & Jazz Harmony*), but [this Wikipedia article about sus chords _does_ mention sus chord inversions](https://en.wikipedia.org/wiki/Suspended_chord).
Answer: In close harmony, 1st inversion of a triad will have the third at the bottom, thus fifth next, and root a sixth above the lowest note. But after that, there is nothing to say which of 5 or root has to go where. Even with a four note chord - C7 for example, the 1st inversion will have 3rd under everything else.
Calling any chord xxxsus2/4 assumes the 2 or 4 will be replacing the 3. Otherwise it's an 'add 9 or add 11'.
Trying to name inversions of such chords may be a nice technical exercise, but in real terms not a great deal of use or help. Easier to show the dots...
Edit - in response to comment - let's take a fairly straightforward Cmaj9. C E G B D. In 1st inversion it'll have E at the bottom. Now let's take Cmaj7sus4. C F G B. Now, in 1st inv. there's an F at the bottom. If it was Cmaj7 add11, then it reads C E G B F, and the F is underneath. It's an interesting question, in theory!
Comment: But a technical exercise is exactly what I'm trying to do here. Can you help with that?
Answer: I think it depends on the musical context. It's first worth noting that Wikipedia also states:

Each suspended chord has two inversions.
...
Suspended fourth and second chords can be represented, in integer notation, as {0, 5, 7} and {0, 2, 7} respectively. The second inversion (quartal chord) is {0, 5, 10}.

So which is it? Rather than suggest that Wikipedia is contradicting itself, I simply think the page you cited is working within a limited musical context. Sure, genres might exist which restrict the notion of an inversion to triadic chords (by which I mean chords that contain the root, third, and fifth). But in many other musical contexts, a broader conception of inverting non-triadic chords is used, as the above citation shows.
So I think the answer depends on, e.g., whether you're in a classical theory course or a jazz theory course. I doubt you'll find a jazz musician who thinks that inversion, as a concept, can only be applied to triadic chords (pure triads or 7th chords). Then again, a chord as funky as Cmaj9(#11sus4) probably only exists in genres that permit the inversion of non-triads.
Answer: I don't think there's a formal ruling on this (who would make one, anyway?)  But it seems logical to name the inversion the same as if the 3rd WASN'T suspended.
As you say, many chords may be analysed in more than one way.  Sometimes it's useful to work out which would be more appropriate.  Other times it isn't.
Suspensions apart, my feeling is that when you have to name a chord in a way that requires 'omit 3rd', you're probably getting it wrong.


How to create a complex form control in reactive form angular

Question: I have a form which contain a list of checkboxes and if one of them was checked an input form display.
This is my component.ts :
  coveragestypes : Array<ItemPolicyModel>=  [{id:'1', name :'type 1'},{id : '2',name :'type 2'},{id : '3',name :'type 3'},{id:'4',name:'type 4'}]
 policyForm = new FormGroup({
  coverages :new FormArray([]),
  coveragesValue:new FormArray([]),
 })
ngOnInit() {
  this.names = this.coveragestypes.map(x => x.name)
  this.addCheckboxes();
}

addCheckboxes() {

this.names.forEach(() => this.coverageFormArray.push(new FormControl()));
this.names.forEach(() => this.coveragesValueFormArray.push(new FormControl('', Validators.pattern(/^-?(0|[1-9]\d*)?$/))));
 }
get coverageFormArray() {
return this.policyForm.controls.coverages as FormArray;
 }
get coveragesValueFormArray() {
  return this.policyForm.controls.coveragesValue as FormArray;
}

And this is my html :

              <input type="checkbox" kendoCheckBox [formControlName]="i" />
                {{names[i]}}
              <ng-container *ngIf="coverage.value">
                    <input type="text" [formControl]="policyForm.get('coveragesValue.'+i)">
              </ng-container>

It is saved like that when I console the policyForm value : coverages: (4) [true, true, false, false] coveragesValue: (4) ["123", "555", "", ""] or I want it to be saved in one form array like that :
coverages : [{id : '1', name : 'type1', value : '123'},{id : '2', name : 'type2', value : '555'}]
Can anyone help me please !
Comment: https://stackoverflow.com/questions/63797930/get-multiple-checkbox-value-as-an-array-in-angular/63799360#63799360
Answer: One way to achieve the formArray.value giving the correct object array representation
coverageExample: Record<String,any> = {id : '1', name : 'type1', value : '123'};
coverageTypes: Record<String,any>[] = [coverageExample];

would be to represent these objects with a formArray of formGroups.
Some formControls will only be used to store the object values.
// ...
addCheckboxes() {

    let formGroups: FormGroup[] = this.coveragestypes.map((coverage) => {
            return new FormGroup({
                    id: new FormControl(coverage.id),
                    name: new FormControl(coverage.name),
                    value: new FormControl('', Validators.pattern(/^-?(0|[1-9]\d*)?$/))
                    checked: new FormControl(false)});
        });
    this.coverageFormArray = new FormArray(formGroups);
}
// ...

with this structure coverages.value should return the object you want.
And the markup would need to be updated as follows

            <input type="checkbox" kendoCheckBox [formControl]="coverage.controls.checked" />
    {{coverage.controls.name.value}}
            <ng-container *ngIf="coverage.controls.checked.value">*
                Value:
                <input type="text" [formControl]="coverage.controls.value">
          </ng-container>

// ...

Edit:  fixed some markup and added the stackblitz
https://stackblitz.com/edit/how-to-create-a-complex-form-control?file=src/app/app.component.ts
Comment: I need this formArray in a formGroup 'PolicyForm' so I added this to your code `policyForm = new FormGroup({
   coverageFormArray : new FormArray(null)})` Then in the addcheckboxes method `this.policyForm.controls.coverageFormArray = new FormArray(formGroups)` But it gives me error `TypeError: Cannot read property 'forEach' of null`
Comment: There's no use of the forEach method in the stackblitz linked above, maybe the issue is somewhere else in your code ? You could update the linked stackblitz with your problem constraints to help us better understand the issue
Comment: Also please note that i used the addCheckboxes() method in the constructor, this prevents null formArray at init. if you receive the data later in async, you could init the array empty in constructor to avoid nulls.
Comment: https://stackblitz.com/edit/how-to-create-a-complex-form-control-ermubs?embed=1&file=src/app/app.component.ts
Comment: Ah yes you need to initialise with an empty array at line 28
   coverageFormArray: new FormArray([])
Comment: Yes I tried it but it gives me this error `ERROR
Error: Cannot read property 'controls' of undefined`
Comment: https://stackblitz.com/edit/how-to-create-a-complex-form-control-policyedit?file=src/app/app.component.ts
please take a look at these edits i made on the stackblitz above
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/228166/discussion-between-hiba-nebli-and-simplicitys-strength).


Drools integration vs. traditional way

Question: I'm new to Drools. I read a lot of examples for using Drools in Java enterprise applications or Spring applications.I found that Drools supports integration with Spring and CDI by using annotations or application context in spring to create Kie objects like KBase, KSession, and KContainer. I can't get the advantage of using this integration methods. Other examples develop Spring applications but create these objects using the traditional way. like this example
What is the benefit of using Drools integration rather than the traditional way? Which way should I use? Does the injection of KSession implement any session management or pooling ?
Answer: There will be no striking Performance Improvement in Spring Drools Integration vs Traditional way.
But as with any Spring Framework Module Spring Drools Integration will provide a Layer of Abstraction and Flexibility for your configurations of Drools.
Furthermore it enable to keep everything Simple by creating the necessary Drools objects easily with minimum configuration and lets you focus on the Core Rule Implementation.
Comment: Just to make sure, so this integration doesn't provide session management it's just for object creation

Drools integration vs. traditional way


C# NHibernate root aggregate filtering child collection with subquery

Question: I'm trying to retrieve a list of root elements and its child collection, applying a subquery filter in child collection. This subquery needs to bring the last occurrence of root's child elements.
The expected result is a list of root elements, where each of them have only the last occurence of its child on child collection attribute.
The class representation of these elements:
public class Root {
   public virtual long id { get; set; }
   public virtual ISet<Child> childList { get; set; }
}

public class Child {
   public virtual long id { get; set; }
   public virtual DateTime occurrence { get; set; }
   public virtual Root parent { get; set; }
}

I've tried to create a query using NHibernate's QueryOver, unfortunately it didn't work as expected.
This is the code I've tried:
Root rootAlias = null;
Child childAlias = null;

var query = QueryOver.Of(() => rootAlias)
   .Left.JoinAlias(
      () => rootAlias.childList,
      () => childAlias,
      Restrictions.Where<Child>(
         cd => cd.occurrence == QueryOver.Of<Child>()
            .Where(cx => cx.parent.id == rootAlias.id)
            .Select(cx => cx.occurrence)
            .OrderBy(cx => cx.occurrence).Desc
            .Take(1)
            .As<DateTime>()
   )
);

I'd be glad if you guys can help me with this issue, or even point me another way to reach the result described above.
Answer: After searching and reading hundreds of similar posts, I've found a solution for my issue.
As I said in the question: "The expected result is a list of root elements, where each of them have only the last occurence of its child on child collection attribute."
And this is the solution considering my classes structure:
// Aliases
Root rootAlias = null;
Child x_temp = null;
Child childAlias = null;

// Result list.
IList<Root> roots = null;

// Subquery which retrieves a list of child's id by max occurrence and grouping by
// root id.
var subquery = CurrentSession.QueryOver<Child>(() => x_temp)
    .SelectList(list => list
        .Select(() => x_temp.id)
        .SelectMax(() => x_temp.occurrence)
        .SelectGroup(() => x_temp.root.id)
    )
    .List<object[]>()
        .Select(p => p[0]).ToArray();

// Query root elements, joining with child collection, applying
// a restriction on child's id attribute through
// JoinAlias' "With clause" parameter.
var query = QueryOver.Of(() => rootAlias).Left.JoinAlias(
    () => rootAlias.childList,
    () => childAlias,
    Restrictions.On(() => childAlias.id).IsIn(subquery)
);

// retrieves the final result list through the query.
roots = query.GetExecutableQueryOver(CurrentSession).List();

That's it!
I hope it can be usefull for someone else with similar issue.


Easy steps for adding the imported content on one single page for display

Question: I have imported the data using the Feeds module from an Excel file.
But as I am new it has created multiple article nodes. I want all these articles to be shown under one article list page. Please explain step by step how can I move forward.
Comment: There are either too many possible answers, or good answers would be too long for this format. Please add details to narrow the answer set or to isolate an issue that can be answered in a few paragraphs.
Answer: You can use Views module to do it. Follow these steps, to set a page listing all articles--

Download views & keep it in sites/all/modules folder.
Enable Views & Views UI from your module list.
Under Structure click View & Add a new View.
Select Content under show & Article of type.
Give a name to it & check Create a page.
Save & continue.
Give a path to the created view page.
Now you can access your path like $basth_url/(your given path).

Thats it.
Comment: Thanx alot Rajeevk


How can I run a javascript code using a python web server?

Question: I have used BaseHTTPRequestHandler to create the server. I can run a normal html file without any problem but when I try to call a js program using

in my html file it doesn't work.
My file prueba.js is just a line containing console.log('hello');. When I execute my server starts running but it prints anything instead of 'Hello' in the browser console.
I have already tried to change the MIME type from text/html to text/javascript and application/javascript and nothing changed.
Comment: Look in the browser's developer tools' network tab. Does it download the correct file with the correct contents?
Comment: And where's the file located? As in, what's the directory structure?
Answer: The markup is incorrectly formatted. When browsers encounter incorrect syntax, they have various strategies to recover. In the case of Chrome (which I'm using), eliminating the comma between attributes allowed a test script to load. But you should also replace the semicolon with a space.

The correct type attribute is text/javascript if you're using HTML4.

The attribute is optional if you're using HTML5.

And you can omit the charset attribute if its value matches the encoding of your HTML document.

Comment: While true, not *sure* it would cause this problem. Depends on how the parser treats garbage between attributes.
Comment: Fair. I just ran a quick test w/ Chrome. I'll add an explanation.


peewee: filter select query results from many to many relationship

Question: I have the following code
#!/usr/bin/env python

"""doc"""

import peewee

db = peewee.SqliteDatabase(":memory:")

class BaseModel(peewee.Model):  # pylint: disable=W0232
    """base model"""

    class Meta:  # pylint: disable=C0111,W0232,R0903
        database = db

class Student(BaseModel):
    """doc"""
    name = peewee.CharField()

class Course(BaseModel):
    """doc"""
    name = peewee.CharField()

class StudentCourse(BaseModel):
    """doc"""
    student = peewee.ForeignKeyField(Student)
    course = peewee.ForeignKeyField(Course)

Student.create_table()
Course.create_table()
StudentCourse.create_table()

s1 = Student(name="Student1")
s1.save()
s2 = Student(name="Student2")
s2.save()
s3 = Student(name="Student3")
s3.save()
s4 = Student(name="Student4")
s4.save()
c1 = Course(name="course1")
c1.save()
c2 = Course(name="course2")
c2.save()
c3 = Course(name="course3")
c3.save()
sc21 = StudentCourse(student=s2, course=c1)
sc21.save()
sc22 = StudentCourse(student=s2, course=c2)
sc22.save()
sc23 = StudentCourse(student=s2, course=c3)
sc23.save()
sc31 = StudentCourse(student=s3, course=c1)
sc31.save()
sc32 = StudentCourse(student=s3, course=c2)
sc32.save()
sc41 = StudentCourse(student=s4, course=c1)
sc41.save()

query = (
    StudentCourse
    .select(StudentCourse, Student, Course)
    .join(Course)
    .switch(StudentCourse)
    .join(Student)
    .order_by(Student.name))

last = None
for student_course in query:
    student = student_course.student
    if student != last:
        last = student
        print "Student: %s" % student.name
    print "    - %s" % student_course.course.name

that produces this output:
Student: Student2
    - course1
    - course2
    - course3
Student: Student3
    - course1
    - course2
Student: Student4
    - course1

This is basically the example from peewee docs
I need to filter the results and pick only those students who have all the courses from a given subset:
courses = ["course1", "course2"]

I have tried to use the IN operator and modified the select query like this:
    query = (
    StudentCourse
    .select(StudentCourse, Student, Course)
    .join(Course)
    .switch(StudentCourse)
    .join(Student)
    .where(Course.name << courses)
    .order_by(Student.name))

But it produces a wrong result, which means I'm doing it wrong:
Student: Student2
    - course1
    - course2
Student: Student3
    - course1
    - course2
Student: Student4
    - course1

There are two wrong things here:

course3 for Student2 is not printed, I need it. I assume this is because course3 isn't in courses list.
Student4 gets selected, but it shouldn't, because Student4 doesn't have both course1 and course2, yet course1 is IN the courses list.

Is it possible to achieve what I want in just one query or I have to iterate over students, make a SELECT query for each of them and match the list of their courses against my courses filter?
My goal is to get this output:
Student: Student2
    - course1
    - course2
    - course3
Student: Student3
    - course1
    - course2

Answer: This should get you pointed in the right direction: https://www.simple-talk.com/sql/t-sql-programming/divided-we-stand-the-sql-of-relational-division/


Como funcionam os métodos usados dentro de classes?

Question: É muito comum no Ruby usarmos métodos dentro de classes, como o attr_accessor, ou até mesmo de bibliotecas, como o validates_presence_of, do Ruby on Rails.
Gostaria de criar:
class Person
  add_name_getter "Luiz"
end

Que adicionasse um campo name à classe, com o valor passado, como "Luiz", no exemplo acima.
p = Person.new
p.name == "Luiz" # true

Sei que é um algo inútil, mas é só para fins de exemplo.
Tentei criar um método como esse:
def add_name_getter *args
  puts args.to_s
end

Porém, eu não recebi como parâmetro nenhuma instância ou referência da classe.

Diante disso, ficam as questões:

Como se chamam essas construções?
O que são exatamente essas construções que são usadas nas classes (referi a elas como "métodos", apesar de que não saber se são exatamente métodos);
Como posso criar uma construção dessas?
Answer: Esse tipo de "construção" é um método, mas em alguns casos também são referidos como macros. Então, quando fazemos:
class MyClass
  some_method()
end

O método some_method está sendo executado no momento em que MyClass é avaliada. Para entender isso, é preciso saber que, diferentemente de linguagens como Java ou C++, class não é somente uma definição, mas uma expressão que é avaliada — e é nesse momento que some_method é invocado. Adaptado de outra resposta do StackOverflow.
Vale ressaltar, ainda, que elas são chamadas implicitamente com self, então, na verdade, o que está ocorrendo é o seguinte:
class MyClass
  self.some_method()
end

Isso significa que some_method deve ser um método da classe, e não um método da instância. Desse modo, há várias formas de se implementar esse some_method, tais como:
Na própria classe:
class MyClass
  def self.some_method
    puts "Hello, world!"
  end

  some_method
end

Em uma classe pai, que será herdada:
class Parent
  def self.some_method
    puts "Hello, world!"
  end
end

class MyClass < Parent
  some_method
end

Com isso, para implementarmos o referido add_name_getter, podemos fazer assim:
class UtilsClass
  def self.add_name_getter value
    # Criamos um método `:name` e retornamos `value` do método criado.
    define_method("name") do
      value
    end
  end
end

class MyClass < UtilsClass
  add_name_getter "Luiz"
end

ins = MyClass.new
p ins.name # => "Luiz"

Utilizei o método define_method para adicionar um método às instâncias de MyClass de forma dinâmica.


Restore and preserve UIViewController pushed from UINavigationController, no storyboard

Question: I try to restore a simple UIViewController that I pushed from my initial view controller. The first one is preserved, but the second one just disappear when relaunched. I don't use storyboard. I implement the  protocol in every view controller and add the restorationIdentifier and restorationClass to each one of them.
The second viewController inherit from a third viewController and is initialized from a xib file. I'm not sure if I need to implement the UIViewControllerRestoration to this third since I don't use it directly.
My code looks like typically like this:
<code>- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.restorationIdentifier = @"EditNotificationViewController";
        self.restorationClass = [self class];
    }
    return self;
}

-(void)encodeRestorableStateWithCoder:(NSCoder *)coder
{

}
-(void)decodeRestorableStateWithCoder:(NSCoder *)coder
{

}

+(UIViewController *)viewControllerWithRestorationIdentifierPath:(NSArray *)identifierComponents coder:(NSCoder *)coder
{
    EditNotificationViewController* envc = [[EditNotificationViewController alloc] initWithNibName:@"SearchFormViewController" bundle:nil];
    return envc;
}
</code>
Should perhaps the navigationController be subclassed so it too can inherit from UIViewControllerRestoration?
UPDATE:
Ok, it seems like pushing from UIViewController to UIViewController works. But pushing from UIViewController to UITableViewController and vice versa, don't work. The app crashes if the tableview implements the UIViewControllerRestoration protocol. If I don't implement the protocol, UIViewControllers pushed  from the tableView is not preserved.
How should one treat UITableViewControllers to preserve them without a crash?
UPDATE:
No crashing no more.. It was due to a memory bug specific for my app. But the tableView is still not preserved, neither the pushed viewController.
UPDATE:
The reason my tableview did not restore properly was because I deleted my datasource in the background.. But I still have a problem with modal viewController not showing up when I try to push it on another navigationController than self.navigationController. I set the restoration identifier to this modal navigationController, but the view does not show up.
Comment: have you given a restorationIdentifier to navigation controller, check this following [stare-restoration-without-storyboard](http://petr-pavlik.squarespace.com/blog/2013/6/16/stare-restoration-without-storyboard), [UINavigationController State Restoration (without Storyboards)](http://stackoverflow.com/questions/14376786/uinavigationcontroller-state-restoration-without-storyboards/17363529#17363529)
Comment: Yes, I have. I tried the navigationController from storyboard but no luck. Only tableviewControllers implementation of UIViewControllerRestoration that is somehow wrong..
Answer: The modal transition needs to be backed by a UINavigationController which has a restorationIdentifier and either a restoration class or a corresponding implementation in the app delegates method viewControllerWithRestorationIdentifierPath. That solved the last piece of the problem.


Prove $ 2\sqrt{2} \le \vert a+b+c \vert + \vert b+c-a \vert + \vert c+a-b \vert + \vert a+b-c \vert \le 4 $

Question:
Prove that for all $a,b,c \in \mathbb{R} $ and $a^2 + b^2 + c^2 = 1 $ the following inequalities are true:
$$  2\sqrt{2} \le \vert a+b+c \vert + \vert b+c-a \vert + \vert c+a-b \vert + \vert a+b-c \vert \le 4 $$

I proved the right one just squaring both sides of the inequality, but I don't know how to do the left inequality.
Right side proof, first i square both sides:
$ \vert a+b+c \vert  = A; \vert b+c-a \vert =B; \vert c+a-b \vert = C;
\vert a+b-c \vert =D $
Then we get:
$ A^2+B^2+C^2+D^2+2AB+2BC+2CD+2DA+2BD+2CA \leq 16 $
Then using $2xy \leq x^2 +y^2 $, for all 6 AB type terms;
$ A^2+B^2+C^2+D^2+2AB+2BC+2CD+2DA+2BD+2CA \leq 4(A^2+B^2+C^2+D^2) = 4(4(a^2+b^2+c^2)) = 16 $
Comment: This is a problem from an ongoing contest: problem 9 of the first stage of Polish Mathematical Olympiad. https://om.sem.edu.pl/static/app_main/problems/om75_1.pdf The deadline is 30 Nov.
Comment: Check the so called Khinchin inequality.
Answer: Initial guess for LHS, $a=b=\frac{\sqrt 2}{2},c=0$
Lemma:
Absolute value inequality, i.e.
$||a|-|b||≤|a±b|≤|a|+|b|$, Proof-LHS
Proof:
Given that $|a|+|b|\ge|a+b|$ (from Lemma),
$$   \vert a+b+c \vert + \vert b+c-a \vert \ge 2 |b+c|$$
Given that $|a|+|b|\ge|a+b|$ (from Lemma),
$$  \vert c+a-b \vert + \vert a+b-c \vert \ge 2|a| $$
$$  \vert a+b+c \vert + \vert b+c-a \vert + \vert c+a-b \vert + \vert a+b-c \vert \ge 2 |b+c| + 2 |a| $$
Given that $|a|+|b|\ge|a+b|$ (from Lemma),
$$\vert a+b+c \vert + \vert b+c-a \vert + \vert c+a-b \vert + \vert a+b-c \vert\ge 2|a+b+c|  $$
As $c = \sqrt{1-a^2-b^2}$
$$LHS \ge 2|a+b+c| \ge 2|a+b+\sqrt{1-a^2-b^2}| $$
Given that $||a|-|b||≤|a±b|$ (from Lemma),
$$LHS \ge 2||a+b|-|\sqrt{1-a^2-b^2}|| $$
To find the maximum of the right equation above for any a,b, i.e. $2||a+b|-|\sqrt{1-a^2-b^2}||$,
That is to Max $2|a+b|$ and Min $2|\sqrt{1-a^2-b^2}|$
To Min $2|\sqrt{1-a^2-b^2}|$, hence,  $\sqrt{1-a^2-b^2} = 0$, $1=a^2+b^2$,
To Max $2|a+b|$,
$$(\frac{a+b}{2})^2 \le \frac{a^2+b^2}{2}$$
Proof for the above inequation
Plug in $1=a^2+b^2$ and get,
$$2|a+b| \le 2 \sqrt{2(a^2+b^2)}=2\sqrt{2}$$
Hence Max $2|a+b| = 2\sqrt{2}$.
$$LHS \ge |2|a+b|-2|\sqrt{1-a^2-b^2}|| = | 2\sqrt{2} - 0| = 2\sqrt{2} $$
Comment: This is a problem from an ongoing contest: problem 9 of the first stage of Polish Mathematical Olympiad. https://om.sem.edu.pl/static/app_main/problems/om75_1.pdf The deadline is 30 Nov. Please delete your answer.