Jquery TokenInput filtering search query with params[:q] not matching first char

Question: I am trying to create a token field using the TokenInput plugin to add members (only the friends of the user creating the group) to a group.
So, I have my friendships controller code here:
class FriendshipsController < ApplicationController

 def index

 @friend_list = @current_user.friends.map { |f| {:id => f.id, :name => f.first_name + ' ' + f.last_name}}

 respond_to do |format|
  format.html # index.html.erb
  format.json { render json: @friend_list }
 end
end

This returns an array, like below, at the url "/friendships.json":
[{"id":6,"name":"John Smith"},{"id":7,"name":"Jane Doe"}]

Then, I have my form, with the jquery for TokenInput below it:
 <%= form_for(@group) do |f| %>

<%= f.label :group_name, "Name" %>

<%= f.text_field :group_name %>

<%= f.label :member_tokens, "Members" %>

<%= f.text_field :member_tokens %>

<%= f.submit %>

<% end %>

My question is, how do I filter the array at /friendships.json? I have tried doing the following in my FriendshipsController:
friend_list = @current_user.friends.map { |f| {:id => f.id, :name => f.first_name + ' ' + f.last_name}}
@friend_list = friend_list.where("name LIKE ?", "%#{params[:q]}%")

... but this only returns an empty array at /friendships.json.
If anyone could let me know why this is returning an empty array I would greatly appreciate it.
UPDATE:
I tried doing this:
 @friend_list = @user_name.friends.where("name LIKE ?", "%#{params[:q]}%")
 @friend_list = @friend_list.map { |f| {:id => f.id, :first_name => f.first_name + ' ' + f.last_name}}

... but when I add the code ".where("name LIKE?", "%#{params[:q]}%")" to the end of @friend_list = current_user.friends, then I no longer get any autocomplete results in the TokenInput field (it returns "No Results").
When I manually enter the q param into the URL, for example "http://localhost:3000/friendships.json?q=k" ... I end up with an empty array. This is weird because a User with first_name Kevin is in my application.
Here is what is outputted on my ruby server:
Started GET "/friendships.json?q=ke" for 127.0.0.1 at 2012-09-16 19:27:53 -0400
Processing by FriendshipsController#index as JSON
Parameters: {"q"=>"ke"}
[...]
User Load (0.7ms)  SELECT "users".* FROM "users" INNER JOIN "friendships" ON "users"."id" = "friendships"."friend_id" WHERE "friendships"."user_id" = 2 AND (first_name LIKE '%ke%')
[...]

HOWEVER, I just tried typing in "evin" into the tokenInput text_field, and it found the user. For some reason the q parameter can't find the first letter of the user's first_name. Anyone have any thoughts on this?
Answer: Apparently postgresql considers a LIKE query case-sensitive, which is why the search query was not finding the capitalized first letter of the user's name. Instead, you have to use ilike with postgresql. See thread about this here: https://groups.google.com/forum/?fromgroups=#!topic/heroku/b6_dJyTXrCU
Here is the code that worked:
class FriendshipsController < ApplicationController

def index
@friend_list = @user_name.friends.where("name ilike ?", "%#{params[:q]}%")
@friend_list = @friend_list.map { |f| {:id => f.id, :name => f.name}}
[...]
end

Comment: Ah you got it working, nice work. It's always something simple like this in the end isn't it? ;)
Answer: From what you wrote I would expect a server error (500), not just an empty array. When you write this in your controller:
friend_list = current_user.friends.map { |f|
  {:id => f.id, :name => f.first_name + ' ' + f.last_name}
}
@friend_list = friend_list.where("name LIKE ?", "%#{params[:q]}%")

A problem will occur: First you are getting a collection of friends from the current_user and mapping it into an array. Then on the next line you call the ActiveRecord #where method on the array you created. But since the friend_list is not an ActiveRecord collection, you should get an error such as "undefined method 'where' for [...]:Array"
I think what you're trying to do is this:
@friend_list = current_user.friends.where("name LIKE ?", "%#{params[:q]}%")
@friend_list = @friend_list.map { |f|
  {:id => f.id, :name => f.first_name + ' ' + f.last_name}
}

Comment: Ok, yeah I tried that. But when I add the code ".where("name LIKE?", "%#{params[:q]}%")" to the end of @friend_list = current_user.friends, then I no longer get any autocomplete results in the TokenInput field (it returns "No Results"). I put an if params[:q] block around my controller code and this gave me "null" at the url /friendships.json. This makes me think that the params[:q] is not getting sent properly? On the plugin site here (http://loopj.com/jquery-tokeninput/) it says that "Your script must accept a GET parameter named q which will contain the term to search for."


WebBrowser não carrega css c#

Question: Eu tentei criar um Browser simples e quando acabei apercebi me que não carrega css o site fica horrível parece um site desatualizado. :\
Alguém me pode ajudar?
Fotos do site, se fizer jeito o código deste pequeno browser terei todo o gosto em o dar.

código que se segue é o código do browser.
public Form1()
{
    InitializeComponent();
    webBrowser1.AllowWebBrowserDrop = false;
    webBrowser1.ScriptErrorsSuppressed = true;
    webBrowser1.WebBrowserShortcutsEnabled = false;
    webBrowser1.IsWebBrowserContextMenuEnabled = false;
}

private void url_KeyPress(object sender, KeyPressEventArgs e)
{
    bool link = true;
    bool dom = true;
    if (e.KeyChar == (char)13)
    {
        for(int i =0;i<url.Text.Length;i++)
        {
            if(url.Text[i] == ' ' )
            {
                link = false;
            }

        }
        if(link == true)
        {
            for (int i = 0; i < url.Text.Length-1; i++)
            {
                if (url.Text[i] == '.')
                {
                    dom = false;
                }

            }
            if(dom == false)
            {
            }
            else
            {
                url.Text = "https://www.google.com/search?client=firefox-b-d&q=" + url.Text.Replace(" ", "+");
            }
        }
        else
        {
            url.Text = "https://www.google.com/search?client=firefox-b-d&q=" + url.Text.Replace(" ", "+");
        }
        webBrowser1.Navigate(url.Text);
    }
}

private void F5_Click(object sender, EventArgs e)
{
    webBrowser1.Refresh();
}

private void begin_Click(object sender, EventArgs e)
{
    webBrowser1.GoForward();
}

private void back_Click(object sender, EventArgs e)
{
    webBrowser1.GoBack();
}

private void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e)
{
    url.Text = Convert.ToString(webBrowser1.Url);
}

Comment: claro vou ja atualizar a pergunta
Comment: Olá Gonçalo, poderia mostrar um pouco do código?
Answer: O CSS esta funcionando sim, o que ocorre é que simplesmente o Google esta carregando uma versão mais "leve" e "antiga" de seu site, isto porque ou ele não reconhece o seu navegador como um navegador moderno, ou pensa que ele é o Internet Explorer.
O componente WebBrowser (https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.webbrowser?view=netframework-4.8) vai usar o recurso do sistema operacional do usuário, através de ActiveX, no caso depende da versão do IE que o cliente tiver instalado, será o suporte que terá o teu componente, então se for carregar um site projetado com suporte para navegadores antigos, vai funcionar perfeitamente, caso contrário é impossível.
Se deseja uma engine/motor melhor, como o mesmo usado no Google Chrome, chamado Chromium, você pode experimentar este projeto:

https://github.com/cefsharp/CefSharp

Se for usar com WinForms, instale via Nuget:

https://www.nuget.org/packages/CefSharp.WinForms/

Um exemplo do CefSharp (https://ourcodeworld.com/articles/read/173/how-to-use-cefsharp-chromium-embedded-framework-csharp-in-a-winforms-application):
public partial class Form1 : Form
{
    public ChromiumWebBrowser chromeBrowser;

    public Form1()
    {
        InitializeComponent();

        // deve ser chamado depois de InitializeComponent
        InitializeChromium();
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }

    public void InitializeChromium()
    {
        CefSettings settings = new CefSettings();

        // Inicia as configurações que você forneceu
        Cef.Initialize(settings);

        // Cria o componente
        chromeBrowser = new ChromiumWebBrowser("https://www.google.com.br");

        // Adiciona para o form (ajuste aqui)
        this.Controls.Add(chromeBrowser);
        chromeBrowser.Dock = DockStyle.Fill;
    }

    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        //Finaliza "quando fechar"
        Cef.Shutdown();
    }
}

Comment: Usar o [WebView do Microsoft Edge](https://docs.microsoft.com/en-us/windows/communitytoolkit/controls/wpf-winforms/webview) também é interessante.
Comment: Boa dica @CypherPotato, infelizmente fica limitado ao Windows10, então esse limite ao sistema operacional pode ser um pouco incomodo, tendo em vista que tem gente que usa até mesmo win7, em casa e em empresas, mas a dica ainda sim é otima ;)

WebBrowser não carrega css c#


What is the relation between Zeta Function and nth Integral?

Question: I was reading the article in Wikipedia about Apery Constant and I saw the triple integral
$$\int_{0}^{1}\int_{0}^{1}\int_{0}^{1}\frac{1}{1-xyz}dx~dy~dz$$
By curiosity I removed the z variable and the third integral leaving only the double integral
$$\int_{0}^{1}\int_{0}^{1}\frac{1}{1-xy}dx~dy$$
calculated it with Desmos and got the result of $$\frac{\pi^{2}}{6}$$
I then tried with one integral but unfortunately that was undefined
I throw even more curiosity and wanted to know what will happen with 4 integrals and I got the value $$\int_{0}^{1}\int_{0}^{1}\int_{0}^{1}\int_{0}^{1}\frac{1}{1-xyzw}dx~dy~dz~dw=\zeta(4) = \frac{\pi^{4}}{90}$$
So far I have reached till $\zeta(4)$ does this pattern continue and what is the thing that makes this true?
Comment: Yes, it continues. To see why expand $\frac{1}{1-x_1x_2\dots x_n}$ as a geometric series and interchange summation and integrations.
Comment: The non-convergence of the integral $\int\limits_0^1 \frac{1}{1-x} \, dx$ is consistent with the pole of $\zeta(s)$ at $s=1$.
Answer: Yes the pattern exists. Indeed,
\begin{align}
\int_{[0,1]^n} \frac1{1 - \prod_{\ell=1}^n x_\ell}\mathrm dx_1\ldots\mathrm dx_n
&= \sum_{k=0}^\infty \int_{[0,1]^{n}} \left(\prod_{\ell=1}^n x_\ell\right)^k\mathrm dx_1\ldots\mathrm dx_n\\
&= \sum_{k=0}^{\infty} \left(\int_0^1 x^k\mathrm d x\right)^n\\
&= \sum_{k=0}^{\infty} \frac1{(k+1)^n} = \zeta(n)
\end{align}


mlogit. Negative value for sd

Question: I fit a mixed logit using mlogit package, but I get negative values for standard deviation. Any idea why I am getting negative values and how this is interpreted?
library(mlogit)
#data
code=c( "obs4694", "obs4681", "obs1362", "obs3372", "obs1001", "obs747",  "obs4738", "obs3861", "obs3044", "obs2651",
         "obs2354", "obs1805", "obs3289", "obs2460", "obs1547", "obs2904", "obs534", "obs2818", "obs3681", "obs2516",
         "obs2527", "obs2283", "obs2173", "obs3765", "obs444",  "obs4513", "obs1005", "obs1934", "obs3229", "obs2561")
mcollege=c("no",  "no",  "no",  "yes", "yes", "no",  "yes", "no",  "no",  "no",
           "no",  "no",  "no",  "no",  "no",  "yes", "no",  "yes", "no",  "yes",
           "yes", "no",  "no",  "no",  "no",  "no",  "no",  "no",  "no", "no")
Dist=c(1,1,4,1,4,3,2,4,1,3,3,4,1,3,3,2,1,2,1,1,3,2,4,1,3,3,4,1,3,1)
Data <- data.frame(code, mcollege, Dist)

# model
MNLData <- mlogit.data(Data, id='code', shape='wide', choice='Dist')
Output <- mlogit(Dist~1|mcollege|1, MNLData,rpar=c('2:(intercept)'='n', '3:(intercept)'='n', '4:(intercept)'='n', '2:mcollegeyes'='n', '3:mcollegeyes'='n', '4:mcollegeyes'='n'), R=100, halton=NA, print.level=1)
summary(Output)

When I check the coefficient results in summary the estimated sd for four of the variables are negative:
Coefficients :
                   Estimate Std. Error t-value Pr(>|t|)
2:(intercept)       -2.6593    56.1853 -0.0473   0.9622
3:(intercept)      -14.4052   389.3052 -0.0370   0.9705
4:(intercept)      -12.3455   323.4815 -0.0382   0.9696
2:mcollegeyes      -21.7190  1322.7599 -0.0164   0.9869
3:mcollegeyes      -32.4405   894.8809 -0.0363   0.9711
4:mcollegeyes      -68.2683  7951.4086 -0.0086   0.9931
sd.2:(intercept)    -1.1784    73.3574 -0.0161   0.9872   #negative
sd.3:(intercept)    52.0240  1373.2141  0.0379   0.9698
sd.4:(intercept)    27.0898   698.0700  0.0388   0.9690
sd.2:mcollegeyes  -275.3367 14154.1320 -0.0195   0.9845   #negative
sd.3:mcollegeyes   -41.2779  1680.3746 -0.0246   0.9804   #negative
sd.4:mcollegeyes   -96.8595  7558.5953 -0.0128   0.9898   #negative

Comment: Where do you see the standard deviation?
Comment: @Pascal: I updated the post
Comment: At least, `stdev(Output)` are positive.
Comment: Interesting. does it mean that I can rely on `stdev(Output)` and assume that estimated SDs are all positive?
Comment: Thanks for your suggestion. I posted similar question on Cross Validated.
Answer: Interpret the values as positive. The negative values are a side-effect of how the MSLE algorithm works (specifically how the normal variates are generated; since the normal distribution symmetric, it doesn't matter if you generate a $N(\mu,\sigma)$-distributed random variable with $\mu + \sigma Z$ or $\mu - \sigma Z$ where $Z$ is a standard normal; furthermore, allowing $\sigma$ to be negative means that the optimization is unconstrained rather than constrained, making it a much easier problem to solve).
For publication/distribution to others, I just manually change the negative values to positive values in the table of estimates. If you do manipulation/graphing of the estimates themselves you'll want to make sure you use abs() or stdev() so you don't get unexpected results. If you look in the source code of stdev.rpar() you'll see that it simply applies abs() to the sigma component of the rpar object.

mlogit. Negative value for sd


Why McNemar is usually significant even in case of zero events on both sides?

Question: After propensity score matching, we can assess balance between matched cohorts using McNemar test.
I wonder why it is usually significant even in case of zero events  on both sides.
I saw prior question but this didn't answer my query. Code obtained from here
x<-matrix(c(1,1,85,85),2,2); mcnemar.test(x)

McNemar's Chi-squared test with
continuity correction
data:  x
McNemar's chi-squared = 84.012, df =
1, p-value < 2.2e-16

x<-matrix(c(0,0,86,86),2,2); mcnemar.test(x)

McNemar's Chi-squared test with continuity correction
data:  x
McNemar's chi-squared = 80.105, df = 1, p-value < 2.2e-16

This is the data that I am trying to do McNemar test for it. I have many outcomes and Null hypothesis would be "No difference between both groups" while the alternative hypothesis would be that difference exists

Am I doing something wrong?
Any advice will be greatly appreciated.
Comment: Always try to post the data, not just a code which creates the data. I.e., in your example, show the frequncy tables themselves.
Comment: dunno. if i knew I would have posted a full answer. the point anyway is what is the actual hypothesis you want to test
Comment: Read about what this test tests. Carlo above has actually answered you.
Comment: mcnamar test is just a binomial test over the two diagonal cells of the matrix (upper right and lower left). the other ones are ignored.
Comment: @carlo So, its use here is correct and I can use it in such low events number?
Comment: @ttnphns Thx for your advices. I added the outcomes table and stated the null hypothesis. Upvoted your comment.
Answer: So you have 86 matched pairs of values judging by your opening remarks. In that case the table you need is one which shows the diagonal as being those pairs which were both positive and those which were both negative. The off-diagonal cells are those where one pair member is positive and one negative. As it stands you are saying that there are 172 pairs, which seems to contradict the table you show and there are 96 pairs which agreed and 86 which differed, all in the same direction.
I think you have misunderstood what it going on here.


ssl-cert-check is not getting the correct expiry dates for Lets Encrypt certificates

Question: I'm using ssl-cert-check to track a list of my domains certificates.
In my crontab I set it to run quietly and email me expiring domains, but the command that I'm using to debug is:
ssl-cert-check -f ssldomains.txt -x 21 -i

It is correctly reading the file and retrieving the certificates for the entire list, but it does not appear to be getting the correct expiry date for certificates issued by LetsEncrypt.org
Other certificate providers do not seem to be affected by this problem.
For example a certificate that is expiring on 24 March 2017 when I inspect it in my browser is reported to be expiring on 15 Jan 2017.
I'm serving with nginx.
Why would the CLI tool be retrieving the wrong expiry date and how can I correct this?
Comment: Oh, the tool I linked to seems to be a different one than the one shipped with ubuntu. Still, I'd assume an SNI problem.
Comment: what distribution are you using? As far as I can see the version of the script that is shipped with Ubuntu 14.04 and 16.04 is bugged.
Comment: How old is your ssl-cert-check? Older versions didn't have support for SNI, resulting in the wrong certificate to be fetched if you have multiple domains on the same IP. This should be fixed with versions [later than 2014-08-20](https://raimue.blog/tag/ssl-cert-check/)
Comment: Its 14.04 and it looks like a bug because now it's retrieving them all with the date 5th April 2017 (nothing has changed in system setup).
Comment: If you make your comment an answer I'll accept it.  It hadn't occurred to me to RTFS and when I replaced the script with the current version linked in the source it works properly.  Thanks for the help!
Answer: This seems to be an SNI problem. If you provide multiple SSL certificates on the same IP the client sends the host name along with the initial request, so the server can provide the correct certificate. Older versions of ssl-cert-check don't do that, the feature was introduced with version 3.27.
Both Ubuntu versions 14.04 and 16.04 ship version 3.27, but it seems like the feature is bugged in this version. There are basically two lines of code that are relevant:
TLSSERVERNAME="FALSE"

and:
if [ "${TLSSERVERNAME}" = "TRUE" ]
then
     TLSFLAG="${TLSFLAG} -servername $1"
fi

As you can see, the variable is set to FALSE and later it is checked for TRUE, but it is never changed.
The current version on GitHub (3.30) has an additional code block:
if ${OPENSSL} s_client -h 2>&1 | grep '-servername' > /dev/null
then
    TLSSERVERNAME="TRUE"
else
    TLSSERVERNAME="FALSE"
fi

This checks the installed openssl version for the servername support. When I add this block into the script on my local Ubuntu installation the result is fine, without the block I get the wrong certificate, just like you.
So, this is a bug, which has been fixed by the author, but hasn't found it's way yet into the Ubuntu repository. You can fix it yourself and hope after the next update the repo contains a fixed version, or you use the script from github instead.


Standard Deviation of a mean whose variables have their own uncertainty

Question: So let's say I have some collection of variables $x_i$ each with their own uncertainty $\sigma_i$. (I'm trying to generalize this but if it helps, the $x_i$ themselves are a mean of other variables and $\sigma_i$ are the standard deviations of those means.)
Now I want to take the mean of these $x_i$ and compute the standard deviation on this mean. But I don't know how I should go about including the existing uncertainty in this calculation. My instinct says to just compute the propagated uncertainty of the mean and the standard deviation of the mean separately and then add those in quadrature, but I'm not sure if that's right.
Answer: So you want the standard deviation of $\frac{1}{n}\sum_i x_i ?$
I'll presume you intend that the $x_i$ are independent (though  it's still doable if they aren't). One can show that for independent (or more generally uncorrelated) $x_i$ that $\operatorname{Var}(\sum_i x_i) = \sum_i \operatorname{Var}(x_i).$ So you have $$ \operatorname{Var}\left(\frac{1}{n}\sum_i x_i\right) = \frac{1}{n^2} \operatorname{Var}\left(\sum_i x_i\right) = \frac{1}{n^2}\sum_i\sigma^2_i$$
So the standard deviation is just the square root of this, which I believe matches your verbal description.
Comment: The problem with this is that if all $\sigma_i=0$ then the standard deviation is $0$ and thus doesn't incorporate the spread of the $x_i$.
Comment: @A-P I thought $\sigma_i$ *was* the spread of the $x_i.$ In fact you say exactly that these are the standard deviations of the $x_i$ and that they are the uncertainties in the $x_i.$ Please clarify.
Comment: @A-P you might want to write down an explicit model of what's going on. Random variables already have uncertainty, so what is this "existing uncertainty." Do you mean that each $x_i$ is a measurement of the same (random) quantity where each measurement has an independent error. So $x_i = x+ \epsilon_i$ where $x$ and the $\epsilon_i$ are independent random variables and the means of the epsilon are zero and the standard deviations are $\sigma_i$?
Comment: Hopefully this clarifies it, (i'm splitting this up into multiple comments because I exceeded the character limit)
 I am starting with a collection of $\{y_{i,j}\}_{i\in[1,N],j\in[1,M]}$ Each $x_i=\frac{1}{M}\sum_{j=1}^M y_{i,j}$ (i.e. the mean of the $y$'s). And each $\sigma_i=\sqrt{\frac{1}{M}\sum_{j=1}^M (y_{i,j}-x_i)^2}$. (i.e. the standard deviation on the mean)
Comment: So now I want to find the mean of all $x_i$ with $\bar{x}=\frac{1}{N}\sum_{i=1}^N x_i$. Finally I want to compute the standard deviation, call it $\sigma'$, on this mean. But as far as I know there seem to be two ways of doing this. I could say $\sigma'=\sqrt{\frac{1}{N}\sum_{i=1}^N (x_i-\bar{x})^2}$. This would give the standard deviation of the spread, ignoring the uncertainties associated with $x_i$. Alternatively I could do what you suggested above which is just the result of propogating uncertainties through the function "mean."
Comment: I'm thinking I should be doing both, setting $\sigma^*=\sqrt{\sum_{i=1}^N \left(\frac{\sigma_i}{N}\right)^2}$, and then taking my final standard deviation to be $\sigma=\sqrt{\sigma'^2+\sigma^{*2}}$
(Done)
Comment: @A-P So $\sigma_i$ is a *measured* quantity? And you're estimating, not computing? Also what do you want your final answer to represent? Is there any reason  you aren't just doing $$\frac{1}{NM-1}\sum_{i=1}^{N}\sum_{j=1}^M (y_{ij}-\bar x)^2 ?$$
Comment: @A-P Like are the $x_i$ a different thing for each $i$, not just a different measurement of the same thing? Like $x_1$ is the mean of the heights of $10$ men, $\sigma_1$ the std deviation, and $x_2$ is of $10$ women. And (for some reason) you want to report the average height of everyone in the sample with a standard error? (And you have forgotten somehow the original data and only have the summary statistics so you can't do as I said above). If this is on the wrong track sorry, I'm trying to understand what quantity you're going for here.
Comment: @A-P I think what you have probably makes sense since we can write (being sloppy with the $N-1$'s etc) $$ \frac{1}{NM} \sum_i\sum_j (y_{ij}-\bar x)^2 = \frac{1}{NM} \sum_i\sum_j ((y_{ij}-x_i) - (x_i-\bar x))^2\\ =\frac{1}{NM}\sum_i\sum_j (y_{ij}-x_i)^2 - 2(y_{ij}-x_i)(x_i-\bar x) + (x_i-\bar x)^2 \\= \frac{1}{N}\sum_i \sigma_i^2 + \frac{1}{N}\sum_i (x_i-\bar x)^2 $$
Comment: Yeah that's about it, each $i$ varies across one dimension while each $j$ varies across another. And I think your second comment makes a lot of sense. Thanks.


How to find a basis for the intersection of two vector spaces in $\mathbb{R}^n$?

Question: What is the general way of finding the basis for intersection of two vector spaces in $\mathbb{R}^n$?
Suppose I'm given the bases of two vector spaces U and W:
$$ \mathrm{Base}(U)= \left\{ \left(1,1,0,-1\right), \left(0,1,3,1\right) \right\} $$
$$ \mathrm{Base}(W) =\left\{ \left(0,-1,-2,1\right), \left(1,2,2,-2\right) \right\} $$
I already calculated $U+W$, and the dimension is $3$ meaning the dimension of $ U \cap W $ is $1$.
The answer is supposedly obvious, one vector is the basis of $ U \cap W $ but how do I calculate it?
Comment: A = (Base(U) | Base(W)) as columns. The answer is the nullspace of A?
Comment: The procedure can be described as: (i) put down a list of the basis vectors of $U$ and $W$ (ii) Perform base changes on both list until a common vector appears. Keep that one. Repeat for the other vectors, until no common vectors can be found anymore.
Comment: @Annan I think what it ends up meaning is that the basis for the intersection will be basis vectors for example from U which are linear combinations of basis vectors from W, or the other way around.  Another way of thinking about it is that you're looking for vectors which are in the column space / span of both sets which I think can only happen when some basis vector of one set is in the column space of the other set.
Answer: Assume $\textbf{v} \in U \cap W$. Then $\textbf{v} = a(1,1,0,-1)+b(0,1,3,1)$ and $\textbf{v} = x(0,-1,-2,1)+y(1,2,2,-2)$.
Since $\textbf{v}-\textbf{v}=0$, then $a(1,1,0,-1)+b(0,1,3,1)-x(0,-1,-2,1)-y(1,2,2,-2)=0$. If we solve for $a, b, x$ and $y$, we obtain the solution as $x=1$, $y=1$, $a=1$, $b=0$.
so $\textbf{v}=(1,1,0,-1)$
You can validate the result by simply adding $(0,-1,-2,1)$ and $(1,2,2,-2)$
Comment: What would you do if U had dimension 3? So you would have 3+2=5 variables and 4 equations.
Comment: @MartinThoma 10 years later, I too, am curious
Comment: Now I feel old
Answer: The comment of Annan with slight correction is one possibility of finding basis for the intersection space $ U \cap W $, the steps are as follow:
1) Construct the matrix $ A=\begin{pmatrix}\mathrm{Base}(U) & | & -\mathrm{Base}(W)\end{pmatrix} $ and find the basis vectors $ \textbf{s}_i=\begin{pmatrix}\textbf{u}_i \\ \textbf{v}_i\end{pmatrix} $ of its nullspace.
2) For each basis vector $ \textbf{s}_i $ construct the vector $ \textbf{w}_i=\mathrm{Base}(U)\textbf{u}_i=\mathrm{Base}(W)\textbf{v}_i $.
3) The set $ \{ \textbf{w}_1,\ \textbf{w}_2,...,\ \textbf{w}_r \} $ constitute the basis for the intersection space $ span(\textbf{w}_1,\ \textbf{w}_2,...,\ \textbf{w}_r) $.
Comment: @Urgent You are on the right way. Just be careful, it should be null([U,-W]) (not null([U,W]))!
Comment: could you please be more specific about $s_i$? suppose my $U$ is $4\times 2$ and $W$ is also $4\times 2$ so $A=[U,W]$ is $4\times 4$ in Matlab I give command $null(A)$ and I get a matrix of order $4\times 1$ now what is my $u_i$ and $v_i$?U=\begin{pmatrix}1& 0\\0 &2\\-1& -1\\0& 1\end{pmatrix} W=\begin{pmatrix}1& 0\\0 &1\\1& -1\\0 &2\end{pmatrix}, null([U,W])=\begin{pmatrix} 0.70711
  \\ 0.00000\\
  -0.70711\\
   \\0.00000\end{pmatrix}$
Comment: How do you know that $\vec{w}$ produced this way are linearly independent so that we have a basis?
Comment: @helios321 This is so because the basis vectors $\textbf{u}_i$ are linearly independent as those are part of basis themselves. You can check this one directly form the definition, just do $c_i \textbf{w}_i=\textbf{0}$ and show it is only possible when all $c_i$'s are zero.
Answer: Let $\mathcal U$ and $\mathcal V$ be two finite-dimensional vector spaces. We want to find a basis for the intersection $\mathcal U\cap\mathcal V$.
Let $U$ and $V$ be matrices whose columns are the basis vectors of $\mathcal U$ and $\mathcal V$, respectively. The problem is then equivalent to that of characterising $\operatorname{Range}(U)\cap \operatorname{Range}(V)$.
In other words, we are looking for non-zero $x,y$ such that
$$Ux=Vy.\tag A$$
In fact, $z\in\operatorname{Range}(U)\cap \operatorname{Range}(V)$ iff there are $x,y$ such that $z=Ux=Vy$.
Solving (A) amounts to finding the nullspace of $A\equiv(U|-V)$, the matrix placing $U$ and $-V$ one next to the other. This is because $AX=0$ with $X\equiv\begin{pmatrix}x\\y\end{pmatrix}$ implies $Ux=Vy$.
Once we have a basis for the nullspace of $A$, in the form of a set of vectors $\{X_i\}$ (with each $X_i$ corresponding to a pair $x_i,y_i$), we obtain the corresponding set of vectors in the intersection computing $w_i\equiv Ux_i=Vy_i$ for each $i$.
To prove that $\{w_i\}_i$ is linearly independent. Suppose $\sum_i c_i w_i=0$. Then $U(\sum_i c_i x_i)=0$ and $V(\sum_i c_i y_i)=0$. But because $\operatorname{Ker}(U)=\operatorname{Ker}(V)=\{0\}$, this means that $\sum_i c_i x_i=\sum_i c_i y_i=0$.
But this is, in turn, equivalent to $\sum_i c_i X_i=0$, and because $\{X_i\}$ is a linearly independent set, this implies $c_i=0$.
We conclude that $\{w_i\}$, where $w_i\equiv U x_i=V y_i$ and $\{(x_i, y_i)\}_i$ is a basis for $\operatorname{Ker}[(U|-V)]$, is a basis for $\mathcal U \cap\mathcal V$.
Comment: ${X_i}$ doesn't necessarily need to be orthonormal, am I right?
Answer: Parameterize both vector spaces (using different variables!) and set them equal to each other.  Then you will get a system of 4 equations and 4 unknowns, which you can solve.  Your solutions will be in both vector spaces.
Answer: It is a one dimensional vector space, so find any non-zero vector which is in both spaces and it will be a basis.
Comment: any *nonzero* vector that is in both...
Answer: Let me try to describe another interpretation of common techniques to compute intersections of two vector subspaces.
Fix a base field $k$.
First, there is a well known method to compute the kernel and the cokernel of a linear map. To be more precise, let $E,F$ be two vector spaces and let $T\colon E\to F$ be a linear map. The recipe is to consider the matrix $\begin{pmatrix}T\\I\end{pmatrix}$ and perform elementary column operations to a matrix like $\begin{pmatrix}J&0&0\\J'&K&0\end{pmatrix}$ where $J$ has the same number of rows as $T$ and $J,K$ are of full column rank. Then the column vectors of $K$ freely generate $\ker T$ and the column vectors of $J$ freely generate $\operatorname{Im}T$.
Now return to the question of computing the intersection. Let $V=k^n$ be a vector space and $E,F\subseteq V$ be two vector subspaces. Consider the map $T\colon E\oplus F\to V, x\oplus y\mapsto x+y$. Note that $\ker T\cong E\cap F$ (realized by the linear map $E\cap F\to\ker T,x\mapsto x\oplus(-x)$) and $\operatorname{Im}T=E+F$. Then we can apply the preceding recipe to compute $E\cap F$ and $E+F$ in the same time.
Explicitly, we start with taking bases $B_E$ and $B_F$ of $E$ and $F$ respectively. Let $B=\begin{pmatrix}B_E&B_F\end{pmatrix}$, and we form the matrix $\begin{pmatrix}B\\I\end{pmatrix}$. As before, we perform elementary column operations to get a matrix like $\begin{pmatrix}J&0&0\\J'&K&0\end{pmatrix}$ where $J,K$ are of full column rank. Then the columns of $J$ freely generate $E+F$ in $V$ and the columns of $K$ freely generate the image of the injective linear map $E\cap F\to E\oplus F,x\mapsto x\oplus(-x)$. To recover a base of $E\cap F$, it suffices to take the preimages, that is, take the first $\dim E$ coordinates and perform a linear combination with the chosen base $B_E$ of $E$. This is more-or-less same as other answers but interpreted in a slightly different way.
Answer: You can use Zassenhaus Sum-Intersection algorithm. See here:
https://en.wikipedia.org/wiki/Zassenhaus_algorithm
or here:
https://kito.wordpress.ncsu.edu/files/2021/03/ma405-l.pdf


is submitting a form

Question: I have this code:
haha

inside a form, for some misterious reason the form submits upon link clicking.
why is that so and how to prevent that?
p.s. this is a wordpress post
Comment: That code, alone, will not cause the effect you describe.
Comment: Can you put the code of your form?
Comment: It is not submitting a form, the link is refreshing the page
Answer: change it to
haha
Comment: thanks a lot, this did the trick!
for some mistrious reason, a href are taken as submit unless implicitly changed...
Answer: You can achieve this by using jquery
$(document).ready(function(){

    $("a").click(function(e){
        e.preventDefault();//this will prevent the link trying to navigate to another page
        $("#questionnaire").show()
    });
});

is submitting a form


How to create a list of paragraphs not linked to a node

Question: Is there a way to create/edit several paragraphs (from within a UI) and use them grammatically by after.
Here is my use case:
I have a paragraph type made of 3 fields:

Unit Source : taxonomy term reference (Kg, g, piece, box of
tomatoes,...)
Unit target : idem
Conversion factor: floating number

And I would like to encode some data like

Unit source = box of tomatoes
Unit target = kg
Conversion factor = 3

(A box of tomatoes is equal to 3kg of tomatoes)
I would like to be able
1- to encode through a UI a list of those conversion data
2- to be able to call them in some other function by after.
Answer: No, this is not possible. By concept paragraphs are always tied to a parent entity, just like normal fields. If it can exist on it's own, better use a node instead.


How do you formally denote a family as a function?

Question: Is there any way to speak of a family by denoting it as a function? In that case, what denotation could we use? And after denoting the said family in the form of a traditional function, say ƒ for now, would I be right if I said that {xᵢ} = ranƒ?
Comment: The statement "let $\{A_i\}_{i\in I}$ be a family of sets in $X$" formally means "let $A$ be a function from $I$ to $X$, and write $A_i$ for $A(i)$". The range of the family can be written as $\{A_i:i\in I\}$. As far as I understand, the symbols $\{A_i\}_{i\in I}$ and $\{A_i\}$ are both used to refer to the family itself, i.e. the function $A$. Does that help?
Comment: That should work. Keep in mind, however, that $A$ would be a function from $I$ to the *power set* of $X$, not to $X$.
Comment: Most of my query has been cleared, thank you! Of the remaining, will it ever seem conventional to speak of the range and domain of A the same way you would speak of that of a regular function? E.g: let {Ai}(i∈I) be a family of sets in X. Formally, this assigns A as a function that maps indices from a set I to a set X. Can I refer to the range of this family as ranA? If I could, would ranA = {Ai}(i∈I)? Thanks in advance.
Comment: @Camelot823: It would be strange to refer to the range of $A$ as $\operatorname{ran}A$, even though it would technically make sense. This is because, in practice, mathematicians don't think of families as functions – rather, they think of them as sets where the elements are ordered in some way (and repeats are allowed). The formal definition of a family as a function is just the way that we "encode" it in set theory, just as how we encode the ordered pair $(a,b)$ as the set $\{\{a\},\{a,b\}\}$.
Answer: The word "family" has multiple interpretations. Anyway, a family is some "collection of objects". I think you understand it as an   indexed family of objects. These objects are elements of some set $X$. An indexed family is formally defined as a function $f : I \to X$. Here $I$ is the index set. With $x_i = f(i)$ one often writes $\{x_i\}$ or $\{x_i\}_{i \in I}$ for indexed families. Personally I do not like this notation because it uses the set braces $\{ \quad \}$ which suggests that an indexed family is itself a set. But this is not true, it contains more information than the image of the index function $f$. If we only know $f(I) = \{ x_i \mid i \in I\}$, we can neither reconstruct the index set $I$ nor the index function $f$. In particular $f$ can have the same value for more than one index, i.e. in an indexed family we can have repetitions.
So yes, you can consider the range $\operatorname{ran}(f)$ of $f$ which is nothing else than $f(I)$ and get $\operatorname{ran}(f) = \{ x_i \} = \{ x_i \mid i \in I\}$.
Note that each set $M$ can be regarded as an indexed family by "self-indexing". Simply take $I = M$ and $f = id : M \to M$.
Using indexed families is unnecessary in many cases, one could work simply with sets of objects. This means that often the range set $\{ x_i \} $ is completely sufficient for a given purpose.
Comment: @Camelot823 Yes, this is correct.
Comment: much thanks! One query has accomodated my read through your question, though. When a set "self-indexes" itself, the indices are simply the elements of the set, correct?


Higher order partial derivatives of implicit function?

Question: Given the surface $z = f(x,y)$, with parameterization $x = u + v^2$, $y = u^2 - v^3$, $z = 2uv$ near the point $(3,3,4)$ which corresponds to the point $(2,1)$ in the $uv$-plane, find $\frac{\partial^2 f}{\partial x \partial y}(3,3)$.
I'm familiar with using Jacobians to find first partial derivatives, but not how to find higher order partial derivatives of multivariate implicit functions.
Answer: By the Inverse Function Theorem, the equations $x=u+v^2$ and $y=u^2-v^3$ locally define $u$ and $v$ as $C^1$ functions of $x$ and $y$ near the point in question, since $x(u,v)=u+v^2$ and $y(u,v)=u^2-v^3$ are functions of class $C^1$ and the Jacobian determinant
$$
\begin{vmatrix}
x_u & x_v
\\
y_u & y_v
\end{vmatrix}
=
\begin{vmatrix}
1 & 2v
\\
2u & -3v^2
\end{vmatrix}
=
- (3v^2 + 4uv)
$$
is nonzero at the point $(u,v)=(2,1)$.
The partial derivatives of the inverse functions
$u(x,y)$ and $v(x,y)$
are given by
$$
\begin{pmatrix}
u_x & u_y
\\
v_x & v_y
\end{pmatrix}
=
\begin{pmatrix}
x_u & x_v
\\
y_u & y_v
\end{pmatrix}^{-1}
=
\begin{pmatrix}
1 & 2v
\\
2u & -3v^2
\end{pmatrix}^{-1}
=
\frac{1}{3v^2 + 4uv}
\begin{pmatrix}
3v^2 & 2v
\\
2u & -1
\end{pmatrix}
,
$$
from which we read off
$$
u_x = \frac{3v^2}{3v^2 + 4uv}
,
$$
and so on.
The formulas $z=f(x,y)$ and $z=2uv$ say that $f$ is simply
$$
f(x,y) = 2 \,u(x,y) \, v(x,y)
,
$$
so
$$
f_{xy} = 2 (u_{xy} v + u_x v_y + u_y v_x + u v_{xy})
.
$$
In this expression, we already know everything except $u_{xy}$ and $v_{xy}$. From the chain rule, we get
$$
u_{xy} = (u_x)_{y} = (u_x)_u \, u_y + (u_x)_v \, v_y
= \frac{\partial}{\partial u} \left( \frac{3v^2}{3v^2 + 4uv} \right) \, u_y
+ \frac{\partial}{\partial v} \left( \frac{3v^2}{3v^2 + 4uv} \right) \, v_y
= \cdots
$$
and similarly for $v_{xy}$. I'll leave it to you to complete the computation, and to insert $(u,v)=(2,1)$ to get $f_{xy}(3,3)$.
Comment: @RaxAdaam: Thanks for spotting the mistake and fixing it!


Chamar função de outro arquivo, NODE

Question:  Boa Tarde, gostaria de saber como puxar a função de um mini-programa para um programa em JS, exite o verificaNota.js que contem a função verificaNota, gostaria de saber como puxar essa função no arquivo calculaNota.js
Quando ultilizo o import ele gera o seguinte erro
SyntaxError: Unexpected token {

Comment: O arquivo `verificaNota.js` está expondo a função `verificaNota` através do [`export`](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Statements/export)?
Comment: Não, como faço para expor ?
Comment: Veja o link do comentário anterior.
Comment: @AndersonCarlosWoss segui os passos mas agora está gerando o erro anexado na imagem
Comment: Parece que no Node você utilizará o [`require`](https://nodejs.org/api/modules.html).
Comment: @AndersonCarlosWoss utilizei o require e deu certo obg amigo, abs
Answer: Consegui resolver, transformei a função em uma variável e a nomeei assim exports.verificaNota, depois abri no segundo programa e inseri o seguinte comando var nota = require('./verificaNota') , agora para chamar  a função utilizo nota.verificaNota(8,1)

Chamar função de outro arquivo, NODE


How to implement XEP-0333 in iOS Application?

Question: I am developing one chat app in that i need to show message status like WhatsApp app for that i have tried XEP-0333(Chat Marker) but facing issue Like.
1) After getting Received Marker from other end XMPPMessage Archive not updated message with Received Marker (In Core data, message chat marker status not updated).
2) How to implement Displayed Marker logic? (means for each message we need to send displayed marker or for only one dialog at once.)
XEP Link : XEP-0333
Code:
<code>         //(Sender Part)
            let completeMessage = DDXMLElement.element(withName: "message") as! DDXMLElement //(In that i have set id,body,to and type as chat)
            let msgObj = XMPPMessage(from: completeMessage)
            msgObj?.addMarkableChatMarker()
            xmppStream?.send(msgObj)

        //(Receiver Part)
    didReceivedMessage - Method

    //*Check One condition*
    if message.isChatMessageWithBody() && message.isErrorMessage() == false {
       if (message.hasChatMarker() == true){
                 printLog("Message ID\(message.elementID())")
                 let msgElement = XMPPMessageMng.getChatMessageElement(recipient: message.from().bare(), thread: "")
                    let threadElement = DDXMLElement.element(withName: "thread") as! DDXMLElement
                    threadElement.stringValue = "Thread"
                    msgElement.addChild(threadElement)
                    let msgReceived = XMPPMessage(from: msgElement)
                    msgReceived?.addReceivedChatMarker(withID: message.elementID())
                    xmppStream.send(msgReceived)
                }
    }

    else{
          if (message.hasMarkableChatMarker() == true){
               printLog("Chat Marker ID\(message.chatMarkerID())")
             }else if (message.hasReceivedChatMarker() == true){
                  printLog("Chat Marker ID\(message.chatMarkerID())")
             }
    }
</code>
//For Display Marker I have done below things.
- When you load message from message archive with JID.
loadArchivedMessagesFromJID - Method
<code>//message as XMPPMessageArchiving_Message_CoreDataObject
let msgReceived = XMPPMessage(from: msgElement)
                            msgReceived?.addDisplayedChatMarker(withID: message.message.elementID())
xmppStream.send(msgReceived)
</code>
Let me know in which right way we can implement Chat marker protocol.
Dev Tools : Xcode 8.3(Swift 3.0) ,
Server : ejabberd
Comment: Hi, @Jay Mehta, Have you resolved this? Please help me to implement the same functionality.
Answer: ejabberd still doesn't support xep-0333
here's the link for supported XEP:
Protocols Supported by ejabberd
Comment: So achieve above functionality which XEP i need to implement?


Make a WHERE clause affect a single column in a query

Question: As the questions stated I am looking to make a WHERE clause affect a single column and am having issues. My query is as follows
Select exp, COUNT(grade), COUNT(exp)
FROM table
WHERE grade = 100
GROUP BY exp;

essentailly I want a output that groups by exp and gives a full count of everyone with that exp but in the second column shows only how many of those people got perfect scores. The problem is the current WHERE affects the COUNT(exp). Beginner to SQL so sorry if this is simple and thanks for any help.
Answer: You want conditional aggregation, which in Postgres uses filter:
SELECT exp, COUNT(*),
       COUNT(*) filter (where grade = 100)
FROM table
GROUP BY exp;


seeking advice to plot a nice 4 quadrant bubble plot on R

Question: I am currently trying to plot a nice bubble plot on R. I have tried with ggplot and succeeded but the colors are too pale, and the size too small, and I am convinced it is possible to do a way better plot on R .
I thus tried using library(plotly), without success this time . I am not sure plotly is the best option too, as it gives interactive plots whereas ultimately I will want to export on PDF this plot (so I need the labels to appear on it without having to activate anything, as in an interactive plot). Does anyone have any ideas to plot this ?
Here is my code :
library(ggplot2)
library(dplyr)

 p <- ggplot(plot_3D, aes(x = actes_evolution_2020_2021, y = tx_0_nuit_2021)) +
   geom_point(aes(color = regroupement, size = actes_2021), alpha = 0.5) +
   scale_color_manual(values = c("#00AFBB", "#E7B800", "#FC4E07",
                                "#FFB5C5", "#BF87B3", "#7F5AA2")) +
  scale_size(range = c(5, 12)) +
  geom_hline(yintercept=0) +
  geom_vline(xintercept=0) +
  scale_y_continuous(labels = ~ paste0(.x, '%'), limits = c(-100, 100)) +
  scale_x_continuous(labels = ~ paste0(.x, '%'), limits = c(-100, 100)) +
  xlab("évolution du nombre d'actes entre 2020 et 2021") +
  ylab("taux de 0 nuits en 2021")
p

# And when trying with plotly

library(plotly)

colors <- c('#4AC6B7', '#1972A4', '#965F8A', '#FF7070', '#C61951')

fig <- plot_ly(plot_3D, x = ~actes_evolution_2020_2021, y = ~tx_0_nuit_2021,
               color = ~regroupement, size = ~actes_2021, colors = colors,
               type = "scatter", mode = "markers", sizes = c(min(plot_3D$actes_2021),
max(plot_3D$actes_2021)),
               marker = list(symbol = "circle", sizemode = "diameter",
                          line = list(width = 2, color = '#FFFFFF')),
           text = ~paste("Spécialité:", regroupement_elsan, "
nombre d'actes en 2021
:", actes_2021,
                         "
taux de 0 nuit en 2021", tx_0_nuit_2021))

fig <- fig %>%
  layout(title = "Lien entre le nombre d'actes et le taux de séjours de moins de 24h",
     xaxis = list(title = "évolution du nombre d'actes entre 2021 et 2020",
                  gridcolor = 'rgb(255, 255, 255)',
                  range = c(2.003297660701705, 5.191505530708712),
                  type = 'log',
                  zerolinewidth = 1,
                  ticklen = 5,
                  gridwidth = 2),
      yaxis = list(title = "taux de 0 nuit en 2021",
                  gridcolor = 'rgb(255, 255, 255)',
                  range = c(36.12621671352166, 91.72921793264332),
                  zerolinewidth = 1,
                  ticklen = 5,
                  gridwith = 2),
      paper_bgcolor = 'rgb(243, 243, 243)',
      plot_bgcolor = 'rgb(243, 243, 243)')

fig

Here is the head of my dataset plot_3D, for reproducibility :
structure(list(code_1 = c("M01b", "C01", "C02", "C04", "M01",
"Total"), regroupement = c("Endoscopies digestives", "Ortho (+ rhumato et
rachis)",
"Chirurgie digestive", "Uro-néphro", "Gastro", "autres"), actes_2019 = c(36079,
29520, 14618, 6515, 9179, 33707), actes_2020 = c(30192, 25451,
12845, 7376, 7933, 24154), actes_2021 = c(42333, 24055, 13735,
8196, 6504, 26115), tx_0_nuit_2019 = c(96.0955377574371, 63.5718186783179,
41.4435389988359, 36.2817362817363, 3.92397302268547, 783.752765264434
), tx_0_nuit_2020 = c(96.0936155567028, 67.3069146785281, 40.5855855855856,
34.344262295082, 3.29588014981273, 895.206473285694), tx_0_nuit_2021 =
c(96.7053774299419,
73.2892690513219, 51.0503369005153, 41.9021364576154, 3.6068530207394,
849.200890941822), actes_evolution_2019_2020 = c(-16.3169710912165,
-13.7838753387534, -12.1288822000274, 13.2156561780507, -13.5744634491775,
-28.3412940932151), actes_evolution_2020_2021 = c(40.2126391096979,
-5.48504970335154, 6.92876605683145, 11.117136659436, -18.0133619059624,
8.11873809720957)), row.names = c(NA, 6L), class = "data.frame")

Answer: You should change a bit your layout for both axis. You can use ticksuffix for the "%" and create a range from -100% to 100%. Also you can do the same for size as in ggplot like this:
library(plotly)

colors <- c('#4AC6B7', '#1972A4', '#965F8A', '#FF7070', '#C61951')

fig <- plot_ly(plot_3D, x = ~actes_evolution_2020_2021, y = ~tx_0_nuit_2021,
               text = ~paste("Spécialité:", regroupement, "
nombre d'actes en 2021:", actes_2021,
                              "
taux de 0 nuit en 2021", tx_0_nuit_2021),
               type = 'scatter', mode = 'markers', size = ~actes_2021, color = ~regroupement, colors = colors,
               marker = list(symbol = "circle", sizemode = "diameter",
                             line = list(width = 2, color = '#FFFFFF')))

fig <- fig %>% layout(title = "Lien entre le nombre d'actes et le taux de séjours de moins de 24h",
                      xaxis = list(title = "évolution du nombre d'actes entre 2021 et 2020",
                                   ticksuffix = "%",
                                   range = c(-100, 100)),
                      yaxis = list(title = "taux de 0 nuit en 2021",
                                   ticksuffix = "%",
                                   range = c(-100, 100)))

fig

Created on 2022-08-11 by the reprex package (v2.0.1)
This is the hover of one bubble:
Comment: thanks ! do you know how I could make the hover appear permanently on the plot ?


Conectando Banco de Dados MYSQL com PHP e Phonegap

Question: Estou criando um app em HTML, CSS e JS com Cordova. E gostaria de saber como eu faço a conexão dele com um Banco de Dados de um server... No caso eu quero pegar as informações dele e passar pro app.
Comment: Tem que trabalhar com API, criar uma api em PHP ou outra linguagem e fazer chamadas via Ajax para a mesma
Answer: Eu tenho um app que trabalha desta forma. O que vc precisa fazer é conectar o php ao mysql e todas as operações de update, select, insert fazer no php.
Toda vez que precisar fazer alguma operação, vc pode usar um ajax e apontar para as urls onde estão seu arquivos php.
Comment: E como faço isso? Tem algum tutorial?


Several selected options in UIPickerView with one section

Question: Is possible have several selected options in a UIPickerView?
For example, a var array = [1,2,3,4,5] In the UIPickerView  select [1,3,5] at the same time with only one section in UIPickerView.
Thanks in advance.
Answer: Here is good control that is doing exactly same .
Also there is work around using just UITapGestureRecognizer .
Objective C
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
    UITableViewCell *cell = (UITableViewCell *)view;

    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
        [cell setBackgroundColor:[UIColor clearColor]];
        [cell setBounds: CGRectMake(0, 0, cell.frame.size.width -20 , 44)];
        UITapGestureRecognizer *singleTapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleSelection:)];
        singleTapGestureRecognizer.numberOfTapsRequired = 1;
        [cell addGestureRecognizer:singleTapGestureRecognizer];
    }

    if ([selectedItems indexOfObject:[NSNumber numberWithInt:row]] != NSNotFound) {
        [cell setAccessoryType:UITableViewCellAccessoryCheckmark];
    } else {
        [cell setAccessoryType:UITableViewCellAccessoryNone];
    }
    cell.textLabel.text = [datasource objectAtIndex:row];
    cell.tag = row;

    return cell;
}

- (void)toggleSelection:(UITapGestureRecognizer *)recognizer {
    NSNumber *row = [NSNumber numberWithInt:recognizer.view.tag];
    NSUInteger index = [selectedItems indexOfObject:row];
    if (index != NSNotFound) {
        [selectedItems removeObjectAtIndex:index];
        [(UITableViewCell *)(recognizer.view) setAccessoryType:UITableViewCellAccessoryNone];
    } else {
        [selectedItems addObject:row];
        [(UITableViewCell *)(recognizer.view) setAccessoryType:UITableViewCellAccessoryCheckmark];
    }
}

Swift
func pickerView(pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusingView view: UIView) -> UIView {
    var cell: UITableViewCell = view
    if cell == nil {
        cell = UITableViewCell(style: UITableViewCellStyleDefault, reuseIdentifier: nil)
        cell.setBackgroundColor(UIColor.clearColor())
        cell.setBounds(CGRectMake(0, 0, cell.frame.size.width - 20, 44))
        var singleTapGestureRecognizer: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "toggleSelection:")
        singleTapGestureRecognizer.numberOfTapsRequired = 1
        cell.addGestureRecognizer(singleTapGestureRecognizer)
    }
    if selectedItems.indexOfObject(NSNumber.numberWithInt(row)) != NSNotFound {
        cell.setAccessoryType(UITableViewCellAccessoryCheckmark)
    }
    else {
        cell.setAccessoryType(UITableViewCellAccessoryNone)
    }
    cell.textLabel.text = datasource.objectAtIndex(row)
    cell.tag = row
    return cell
}

func toggleSelection(recognizer: UITapGestureRecognizer) {
    var row: Int = NSNumber.numberWithInt(recognizer.view.tag)
    var index: UInt = selectedItems.indexOfObject(row)
    if index != NSNotFound {
        selectedItems.removeObjectAtIndex(index)
        (recognizer.view).setAccessoryType(UITableViewCellAccessoryNone)
    }
    else {
        selectedItems.addObject(row)
        (recognizer.view).setAccessoryType(UITableViewCellAccessoryCheckmark)
    }
}

Comment: In swift, How I can call `[(UITableViewCell *)(recognizer.view) setAccessoryType:UITableViewCellAccessoryNone];` ?
Comment: I have a warning **Value of type UIView? has no member setAccessoryType**


Average value of area of circles

Question: I am supposed to find the average value of the area of circles whose radii vary from $0$ to $R$.
I know that the formula for the arithmetic mean of a function $f$ on an interval $[a,b]$ is
$$\frac{1}{b-a} \int_a^b f(x)\,dx.$$
So for these circles it seems like it would now be this:
$$\begin{align}
\mu &= \frac{1}{R} \int_0^R \pi r^2\,dr \\
&=\frac{\pi}{R} \left(\frac {R^3}{3}\right) \\
&=\frac{R^3 \pi}{3}
\end{align}$$
So I try and verify this using three circles that are easy to calculate, of radius $1$, $2$ and $3$.
Using $$\frac{ \pi + 4 \pi + 9 \pi}{3}$$
gives me $\frac{14\pi}{3}$
Using my formula gives me $9 \pi$.
This makes me reevaluate what I am doing; it seems like my previously discovered formula accounts for a circle of radius $0$. I compensate for that Using $$\frac{ \pi + 4 \pi + 9 \pi}{4} = \frac{7\pi}{2}$$
Still wrong, what did I do incorrectly?
Comment: You are misunderstanding a fundamental difference between discrete and continuous averages. When you check your work with three distinct radii, you are not considering the continuum between them.
Comment: Your formula accounts for all the $R\in\mathbb{R^+}$ while you assumed $R\in\mathbb{N}$ in your verification.
Comment: You forgot to cancel one $R$ from your integral. It should read $\pi R^2/3$. Remember the following "reality check". You measure $R$ in feet or meters, whichever is standard from where you are. Therefore $R^3$ has units that are cubic feet or cubic meters. Now how on earth could the average **area** be some number of cubic ft or meters?
Comment: ... and what other have said about discrete vs. continuous variables. There is a branch of numerical analysis that deals with questions such as how to select a finite set of sample points in such a way that the weighted average calculated at those points equals the continuous average. None of your suggestions fit.
Comment: @JyrkiLahtonen Do you have any references on that? I am interested.
Comment: @Orangutango: What I had in mind are formulas that are designed to be accurate up to certain degree of polynomial factor in the integrand. See [this Wikipedia page](http://en.wikipedia.org/wiki/Gaussian_quadrature) for starters. If the domain is the surface of an $n$-sphere, then [spherical designs](http://en.wikipedia.org/wiki/Spherical_design) do the same thing. IANA, so there's probably a lot more. Those are the bits that have crossed my path.
Comment: Note that $\frac{7\pi}{2}$ is a fairly good approximation to the (corrected) continuous average of $3\pi$.
Comment: @JyrkiLahtonen The extra R came from when I evaluated it as a definite integral.
Comment: I can evaluate the definite integral, thank you. But you were supposed to multiply the definite integral by $1/R$. See my first comment for a way of quickly seeing that something went wrong. That is one of the things I teach my calculus students to check when critically appraising the answer they got.
Comment: I don't know if that really helps, cubic feet makes as much sense as feet^5
Answer: As expalined in the comments, you have an extra $R$, so that the formula should read:
$$R^2\pi \over 3$$
I'd like to relate this to the discrete calculation you did. For $n$ circles of radius $1,2..n$, the average area is:
$${\pi \over n} \sum_{i=1}^n i^2 = {\pi\over6} (n+1) (2 n+1)= {\pi n^2\over 3} + O(n)$$
Thus, you see that as  the number of concentric circles becomes larger, approximating the integral by discrete concentric circles becomes closer to your integral formula.
Comment: The extra R came from when I evaluated it like a definite integral.

Average value of area of circles


Can I just change Drupal's default timezone to test to see if some scheduled rules will fire?

Question: I need to test to see if some scheduled rules will fire as expected. I cannot change the server time, as I do not have access to do this. However, if I change Drupal's default timezone can I expedite the process? If not is there another way to do this.
Note: I cannot just shorten the schedules rules as they are hardcoded in a contrib module.
Answer: I am 95% certain that drupal is using the server's system time so changing the timezone will have no effect as far as rules are concerned.
Alternatively, you could (temporarily) hack the contrib module to test whatever you need to test and when you're sure things are working, restore the original module when done.


Xcode: Universal framework: Conditionally link other .framework dependency for specific platform only

Question: While working with universal framework that targets all apple platforms I wish to conditionally link to another .framework dependency for OSX only.
I can add this dependency to Linked Framework and Libraries and mark it as Optional. However I don't know what custom field should I add or modify in Build Settings to only actually link this .framework for specific platform only. (without anything since the dependency is optional - build will always fail with ld: framework not found)
Any suggestion guys?
As a workaround I can split this over two targets: one for OSX and one for anything else, but that will already derail the concept of universal framework.
Answer: This can be achieved without resorting to Linked Framework and Libraries.
While we have a universal target with full range of supported platforms: macosx iphoneos iphonesimulator appletvos appletvsimulator watchos watchsimulator, consider the case that we want to link a framework for OSX only.
For linking our framework we need two things:

Add the path to desired .framework to Framework Search Path
Add -framework YourFrameworkName to Other Linker Flags

And Build settings allows us to specify fields conditional for specific platform. When expanding the individual field and hovering the mouse over Debug/Release, you will be able see the plus sign appearing, pressing on the plus sign will bring you the picker where you will be able to select the desired platform.
The hypothetical added build settings for linking Realm and RealmSwift for OSX will look the following way:

(both Intel 64-bit arch and Any macOS SDK will represent building for OSX)


I love with Ableton Live as a composition tool (session views). But I can only use Logic Pro X for studio mixes. What can I do?

Question: Is there anything else for creative composing along the lines of Ableton Live?  The session views make a lot of sense.  It's a nice program.  And ultimately I believe professional music can be make on any software, especially Live/Logic/Reason/etc.
I ask because I'm locked into Logic due to my hardware constraints and my actual physical studio–I record a lot of serious audio (32 audio tracks at a time sometimes) and need Logic's very mature audio editing engine.
However, on a personal level, I'm composing a lot of electronic music, DnB (old Aphex Twin stuff :), so let's just say "EDM".  And Live makes that a lot easier.
The thing is, Ableton's pricing structure is totally out of whack.
The entire Logic Pro X package–the FULL package–sells for $200.  That's with far more instruments and effects, a huge sample library, and a much mature editing system, so on and so forth.  Ableton just has this jazzy tab button thing going for it.  I guess I could get over it, but still.
Ableton sells a dumbed down version with barely anything for $99, and then their "standard" version is $450, and the real standard version (which they call "suite") is $750!  Suite mainly just comes with Max for Live, which is a free license (for personal use) piece of software anyway, so Ableton seems to be taking advantage of something... probably EDM's peak in commercialization right now.  Oh well, karma...  It won't last long.
Anyway, if anyone has any suggestions on sequencers or other apps with interfaces that are great for putting together beats/sections/grooves and even arrangements in a more intuitive way than the standard sequencer arrange view (kinda like Live's Session view, but not so expensive), please let me know...  Even something with a more modern interface like Live would help (Logic is a bit long in the tooth, not that I'd go with anything else for recording a serious session besides Pro Tools, and its plugin architecture is outdated among other things).
Comment: I haven't tested it yet, but Bitwig Studio was inspired in Live, and has a similar session/arrange view dynamic (in general it is very similar to Live). It is around $300 USD. http://www.bitwig.com/en/bitwig-studio/overview.html
Comment: +1 For Bitwig. I am still an Ableton guy but I tried Bitwig out for a while and it does everything Ableton can do and more. Worth checking out.
Answer: You can use ReWire to essentially turn the basic version of Ableton Live into a plug-in that runs inside Logic. This is a very common way to use Live inside Logic or Pro Tools. Typically it is done for exactly the reason you describe: to add the Session View to an existing studio.
If you have Logic, you don't need Live Suite, because you already have "Logic Suite." You can use the instruments and effects and sounds that you already have in Logic with the basic version of Live and you won't miss the additional instruments and effects and sounds from Live Suite.
I would never recommend Live Suite to a new Ableton user anyway, because there is great upgrade pricing. So it is best to start with the smallest version and only move up if and when you find that you have a real need for the larger version. If you are not doing live DJ shows or generating videos, there is no need to pay for the features that are applicable to those use cases.
Comment: Excellent answer.  And the correct one.  I did eventually end up using ReWire to connect Live to Logic.  Works perfectly fine.
Answer: Ableton offers a trial version for around $49, It has some limitations but you can do a good bit of composing in it before running out of trackspace.  This entry level edition comes free with a lot of inexpensive controllers as well, such as launchpad mini.
Akai has a similar product that comes bundled with some of their controllers, its called ignite.  It has a similar composition style as ableton and the learning curve is fairly quick.
Happy Dawing@!
Answer: Logic sucks. Avoid it like the plague. Unless they jave fixed the multitimbral bug, you will run an instance of ko takt for every midi track you use. Almost 500mb per instance!!! Tracks will not route to channels independently and every sample loaded will receive the other tracks automation. MADDENING!
If you are serious spend the 750 and keep using a DAW that you are comfortable with. Also, producing the genre you want to produce...Live is the way to go. Plugs are WAY superior, sidechains and ducking etc way more user friendly.
Rewire is great until you decide to change meter or tempo. Then you are effed.
Cubase is the best balance of audio and MIDI that I have used.
Answer: Have you looked at bitwig studio?  It's basically Ableton's first contender.  The only bad thing at the moment is that it doesn't support AU plugins.


Structure of $E(\mathbb{F}_{q})$ for $E/\mathbb{F}_{q}$ an elliptic curve

Question: I'd like to verify an answer I have for the following question:
Given that for an elliptic curve over a finite field $E/\mathbb{F}_{q}$ we have an isomorphism
$$ E(\mathbb{F}_{q}) \cong \mathbb{Z}/m\mathbb{Z} \oplus \mathbb{Z}/mn\mathbb{Z} $$ where gcd$(q, m) = 1$, show that $q \equiv 1 \ \text{mod} \ m$.
My solution is as follows:
Let $S \in E(\mathbb{F}_{q})$ be a point contained in the first invariant factor of the decomposition above, so that $S \in E[m]$, and let $T \in E[m]$. We note that since $E[m] \cong \mathbb{Z}/m\mathbb{Z} \oplus \mathbb{Z}/m\mathbb{Z}$, that $E[m] \subset E(\mathbb{F}_{q})$. This implies (see Silverman AEC Chapter 3, Corollary 8.1.1) that the the image $\mu_{m}$ of the Weil $e_{m}$-pairing is contained in $\mathbb{F}_{q}^{*}$. In particular we have
\begin{align} e_{m}([q]S, T) &= e_{m}(S, T)^{q} \\ &= e_{m}(S, T) \end{align} so that by the non-degeneracy of the Weil pairing we have
$$ [q]S = S $$ for any $S \in \mathbb{Z}/m\mathbb{Z}$, so multiplcation by $q$ acts as the identity mod $m$ so $q \equiv 1 \ \text{mod} \ m$.
Any corrections or ways I could streamline this proof would be appreciated!
Answer: As you say, $\mu_m\subseteq\Bbb F_q^*$. By Lagrange's theorem, $m\mid q-1$.


How to show translated taxonomy terms in term listing in content listing style

Question: I have question about translation of taxonomy terms in Drupal 8. Let's assume this configuration:
New created vocabulary, vocabulary language - not specified, terms language - not specified, show language selector, enable translation.
With this config, I should be able to translate new created taxonomy terms, if I select specific language while creating one. So I create taxonomy term in English language. Then I go and translate that term by clicking the "translate" tab in this term. I fill all values and save the form. Term is now translated to another language.
And now comes the difference - when I do the same approach with content, in content overview I see all nodes - original, and also translated. When I do this with taxonomy terms, in vocabulary listing I see only taxonomy term which was created first (so in my example the English one) - see the image.

How can I achieve the same behaviour as in content listing? I am expecting, that all terms will be listed here (as in content overview), or at least, when in specified language, terms with this language set should be shown (e.g. in English only links in english translations, if they exists). Taxonomy terms and nodes are all entities, so I would expect the same behaviour while translating them... Or is this a bug?
Thanks
Answer: Yes, it kind of is a bug.
The page is I think one of the the only two lists (the other is comments) that is hardcoded and not a view.
Views have configurable behavior to show show the entity in the best translation, or show the default translation.
You can replace this list with a view yourself, just create a view that lists terms on that path. Views doesn't support a few features of that UI however, specifically, that is the drag and drop hierarchy and weight handling. if you don't need that, fine. If you do, you might need to look for contrib modules that offer such features, I'm not sure if there are some for Drupal 8.
Comment: is there some patch for this bug (is this bug addressed on Drupal.org issue queue), if I do not want to use custom view? Or we have to solve it ourselves?
Comment: Well, thank you for response. I am just surprised, that when lot of things changes in Drupal 8, some of the old "bad practices" still remains... Or nobody really care for full functional transliteration?
Comment: do you have some update about this issue? I quickly checked Drupal 9 and it seems like nobody fixed this problem (existing more that 5 years). Do you have knowledge about issue on drupal.org, where this is discussed or any module, which will replace this buggy page? It seems like this is the only one page in Drupal 9 without view.... That is very sad.


Best way to format this data for exploratory factor analysis, using R?

Question: I originally asked this on StackOverflow, but it's more of a stats question than a coding question.
My question is about data formatting.  I have this dataset (well, this is just the first two of several hundred rows):
df <- structure(list(X.Case.ID. = 310:311, GENDER = c(1L, 1L), AGE = c(32L,
45L), EMPLOYMENT = c(1L, 1L), EDUCATION = c(6L, 6L), FUNCTION = c(6L,
6L), A = c(1L, 1L), SECTOR = 1:2, EMPLOYEES = c(567L, 500L),
    STATE = c(35L, 10L), REGION = 3:2, REVENUE = 9:8, Q1 = c(2L,
    2L), Q2 = 2:1, Q3 = 1:2, Q4 = c(1L, 3L), Q5 = 3:2, Q6_C1 = c(0L,
    0L), Q6_C2 = 0:1, Q6_C3 = c(0L, 0L), Q6_C4 = 1:0, Q6_C5 = 0:1,
    Q6_C6 = c(0L, 0L), Q6_C7 = c(0L, 0L), Q6_C8 = c(0L, 0L),
    Q6_C9 = c(0L, 0L), O_Q6_C9 = c(NA, NA), Q7_C1 = 0:1, Q7_C2 = c(0L,
    0L), Q7_C3 = c(0L, 0L), Q7_C4 = c(0L, 0L), Q7_C5 = 1:0, Q7_C6 = 0:1,
    Q7_C7 = c(0L, 0L), Q7_C8 = c(0L, 0L), Q7_C9 = c(0L, 0L),
    Q7_C10 = c(0L, 0L), O_Q7_C9 = c(NA, NA), Q8 = 4:3, Q9_C1 = c(0L,
    0L), Q9_C2 = 0:1, Q9_C3 = c(0L, 0L), Q9_C4 = c(0L, 0L), Q9_C5 = c(1L,
    1L), Q9_C6 = 0:1, Q9_C7 = c(0L, 0L), Q9_C8 = c(0L, 0L), Q9_C9 = c(0L,
    0L), Q10 = c(3L, 1L), Q11_C1 = c(0L, 0L), Q11_C2 = 1:0, Q11_C3 = 0:1,
    Q11_C4 = 0:1, Q11_C5 = 1:0, Q11_C6 = c(0L, 0L), Q11_C7 = c(0L,
    0L), Q12 = c(34L, 15L), Q13 = c("99,994", "700"), Q14 = 1:2,
    Q15 = 1:2, Q16_C1 = c(0L, 0L), Q16_C2 = c(0L, 0L), Q16_C3 = c(0L,
    0L), Q16_C4 = c(0L, 0L), Q16_C5 = c(0L, 0L), Q16_C6 = c(0L,
    0L), Q16_C7 = c(0L, 0L), Q16_C8 = c(0L, 0L), Q16_C9 = c(0L,
    0L), Q16_C10 = c(0L, 0L), Q16_C11 = c(0L, 0L), O_Q16_C11 = c(NA,
    NA), Q17_C1 = c(0L, 0L), Q17_C2 = c(0L, 0L), Q17_C3 = c(0L,
    0L), Q17_C4 = c(0L, 0L), Q17_C5 = 1:0, Q17_C6 = 0:1, Q17_C7 = c(0L,
    0L), Q17_C8 = 0:1, Q17_C9 = 0:1, Q17_C10 = 1:0, Q17_C11 = c(0L,
    0L), Q17_C12 = c(0L, 0L), O_Q17_C11 = c(NA, NA), Q18 = c(5L,
    3L), Q19_C1 = 0:1, Q19_C2 = 1:0, Q19_C3 = c(0L, 0L), Q19_C4 = 0:1,
    Q19_C5 = c(0L, 0L), Q19_C6 = c(0L, 0L), Q19_C7 = c(0L, 0L
    ), Q19_C8 = c(0L, 0L), O_Q19_C7 = c(NA, NA), Q20_M1 = c(7L,
    1L), Q20_M2 = 2:3, Q20_M3 = 3:4, Q20_M4 = 6:5, Q20_M5 = c(5L,
    2L), Q20_M6 = c(4L, 7L), Q20_M7 = c(1L, 6L), YEARSATCOMPANY = c(7L,
    10L), YEARSINBUS = c(12L, 10L), OFFICES = 3:2, SEGMENTS = c("Enterprise",
    "Commercial"), DEDICATED_STAFF = c(">=20", "<20"), HOURS = c(">=10000",
    "<1000"), VULNERABLE = c("Vulnerable", "Not Vulnerable"),
    Hours.Adjusted = c("10000", "700"), Commerical.or.Enterprise = c("Enterprise",
    "Commercial"), Q13.num = c(99994, 700), Segments = c(2, 1
    ), Dedicated.Staff = c(2, 1), Vulnerable = c(2, 1), Hours = c(4,
    1)), row.names = 1:2, class = "data.frame")

I realize the column names and the values aren't clear but we have some questions, like the demographics, that each person has a single response to.
There are questions like Q1:

And then there are the questions like Q6, which has 9 parts to it (O_Q6_C9 and others like it are empty).  Here are the first 3 parts, for brevity.

Considering questions like Q6 are "long" questions in wide format, we essentially have one-to-one and one-to-many structure but formatted so it's all one-to-one. What's the best way to format this data for an exploratory factor analysis?  Leave it wide format or put it in long format which will result in the one-to-one variables to be duplicated?
I was wondering that for questions like Q6, all of the parts to it are around a common concept - would that pose problems?
I will be encoding all the data numerically and will not be using all of the questions.  However, I will be using a mix of the one-to-one and one-to-many questions.  Other than that mix of structure, there isn't anything complex like repeated measures or complex sampling.
Answer: I believe most of the R packages for EFA use wide format, and I would use wide format for your data. The questions like Q6 might be best handled by a non-standard EFA, where you account for correlations between the pieces of Q6 separately from the other factors in the EFA. The psychometrics people would call Q6 a "testlet", and there are specific models for testlets. One thing to clarify is whether you want to treat the responses as continuous or as categorical/ordinal. Testlets more often involve categorical variables, but similar ideas can apply to continuous variables.
Comment: It's mostly categorical and not ordinal though a couple are ordinal, like Q1.  Thank you for introducing me to the concept of "testlets".  I will go do some reading up on it!  Thanks for your input!
Answer: I will answer assuming that because you are using R, you will be using the fa function from the psych package to run the EFA. With this in mind, it is better to have your data in wide format for this purpose. The reason being is that the fa function will kick back the data with an error stating that the labels in the long data are not numeric. You could remove them, but then you have basically long column of variables in one, so the EFA will treat the data like it is just one variable.
The best way to do this is to simply run the data with just numeric items with column names, or as a correlation or covariance matrix instead (the latter is automatically converted to the former before the EFA is conducted).
Below are some examples using the mtcars data in R, where I run the EFA using a data frame, a tibble, a correlation matrix, and a covariance matrix:
#### Glimpse Data ####
library(tidyverse)
glimpse(mtcars)

#### Convert Data into Tibble, Cov/Cor Matrix, and Long Data ####
mt.tib <- mtcars %>% as_tibble()
mt.cov <- cov(mtcars)
mt.cor <- cor(mtcars)
mt.pivo <- mtcars %>%
  pivot_longer(cols = everything(),
               names_to = "Measure",
               values_to = "Value")

#### DF, Tibble, and Cov ####
fa(mtcars,
   nfactors = 2,
   rotate = "oblimin") # data frame version

fa(mt.tib,
   nfactors = 2,
   rotate = "oblimin") # tibble version

fa(mt.cov,
   n.obs = nrow(mtcars), # have to supply n here
   nfactors = 2,
   rotate = "oblimin") # covariance matrix

fa(mt.cor,
   n.obs = nrow(mtcars), # have to supply n here
   nfactors = 2,
   rotate = "oblimin") # covariance matrix

All four of these have the same results:
Factor Analysis using method =  minres
Call: fa(r = mt.cor, nfactors = 2, n.obs = nrow(mtcars), rotate = "oblimin")
Standardized loadings (pattern matrix) based upon correlation matrix
       MR1   MR2   h2    u2 com
mpg  -0.61  0.54 0.85 0.147 2.0
cyl   0.71 -0.48 0.94 0.064 1.7
disp  0.58 -0.60 0.90 0.102 2.0
hp    0.89 -0.12 0.88 0.124 1.0
drat -0.17  0.78 0.71 0.292 1.1
wt    0.42 -0.70 0.82 0.179 1.6
qsec -0.92 -0.35 0.78 0.216 1.3
vs   -0.80  0.12 0.71 0.292 1.0
am    0.13  0.93 0.82 0.183 1.0
gear  0.22  0.93 0.80 0.200 1.1
carb  0.85  0.24 0.66 0.342 1.2

                       MR1  MR2
SS loadings           4.71 4.15
Proportion Var        0.43 0.38
Cumulative Var        0.43 0.81
Proportion Explained  0.53 0.47
Cumulative Proportion 0.53 1.00

 With factor correlations of
      MR1   MR2
MR1  1.00 -0.28
MR2 -0.28  1.00

Mean item complexity =  1.4
Test of the hypothesis that 2 factors are sufficient.

df null model =  55  with the objective function =  15.4 with Chi Square =  408.01
df of  the model are 34  and the objective function was  2.76

The root mean square of the residuals (RMSR) is  0.04
The df corrected root mean square of the residuals is  0.06

The harmonic n.obs is  32 with the empirical chi square  6.87  with prob <  1
The total n.obs was  32  with Likelihood Chi Square =  69.56  with prob <  0.00031

Tucker Lewis Index of factoring reliability =  0.827
RMSEA index =  0.178  and the 90 % confidence intervals are  0.121 0.245
BIC =  -48.28
Fit based upon off diagonal values = 0.99
Measures of factor score adequacy
                                                   MR1  MR2
Correlation of (regression) scores with factors   0.98 0.98
Multiple R square of scores with factors          0.97 0.96
Minimum correlation of possible factor scores     0.94 0.92

Running the EFA in long format reliably doesn't work because of the label vector created by the pivoted data:
#### Long Format ####
fa(mt.pivo,
   nfactors = 2,
   rotate = "oblimin")

Which gives us this (translation is that "x must be a numeric variable"):
Error in cor(r, use = use) : 'x'必需为数值

Simply removing it in this case doesn't work because it gives us nonsense output (due to it also being just one column of pivoted values:
fa(mt.pivo %>% select(-1),
   rotate = "oblimin")

As shown here:
Factor Analysis using method =  minres
Call: fa(r = mt.pivo %>% select(-1), rotate = "oblimin")
Standardized loadings (pattern matrix) based upon correlation matrix
      MR1    h2 u2 com
Value   0 1e-30  1   1

               MR1
SS loadings      0
Proportion Var   0

Mean item complexity =  1
Test of the hypothesis that 1 factor is sufficient.

df null model =  0  with the objective function =  0 with Chi Square =  0
df of  the model are -1  and the objective function was  0

The root mean square of the residuals (RMSR) is  NaN
The df corrected root mean square of the residuals is  NA

The harmonic n.obs is  352 with the empirical chi square  0  with prob <  NA
The total n.obs was  352  with Likelihood Chi Square =  0  with prob <  NA

Tucker Lewis Index of factoring reliability =  NaN
Fit based upon off diagonal values = NaN
Measures of factor score adequacy
                                                  MR1
Correlation of (regression) scores with factors     0
Multiple R square of scores with factors            0
Minimum correlation of possible factor scores      -1

Comment: Thanks so much for this!  This is good to know and I will take your advice, as well!
Comment: Great! If you feel either answer has provided a solution to your problem, feel free to hit the checkmark next to one of the answers here.
Comment: @ShawnHemelstrand ; this somewhat brushes over the issue that many of he data in the op are ordinal or dichotomous, where as you calculate pearson correlation
Comment: The key question here was regarding the data format, but yes OP would need to apply the proper arguments in R for that, I believe here using polychoric correlations using the `cor="poly"` argument.
Comment: Agreed. Which, and how, a specific analysis is carried out, using R in this case, can depend on the data format e.g. does the data need to be recorded as factors, integers, numeric etc. So data format is linked to analysis choice.


Rails Using Edit action in a Show View

Question: I'm trying to update an object in it's show view. I've been following railscasts HABTM checkboxes.
Getting the following error:

No route matches [PUT] "/accounts/4/edit"

Here is my form:
<%= form_for @account, :url => { :action => "edit"} do |form| %>
    <%= hidden_field_tag "account[checklist_ids][]", nil%>
    <% Checklist.all.each do |checklist| %>
        <%= check_box_tag "account[checklist_ids][]", checklist.id, @account.checklist_ids.include?(checklist.id) %>
        <%= checklist.task %>

    <% end %>

<%= form.submit "Update Checklist", class: 'btn' %>
<% end %>

/app/controllers/accounts_controller.rb
class AccountsController < ApplicationController
  before_filter :authenticate_user!
  respond_to :html, :json

  def show
    @account = Account.find(params[:id])
    @notes = @account.notes.all
    @contacts = @account.contacts.all
  end

  def edit
    @account = Account.find(params[:id])
  end

  def update
    @account = Account.find(params[:id])
    @account.update_attributes(params[:account])
    respond_with @account
  end
end

/app/models/account.rb
class Account < ActiveRecord::Base
  attr_accessible :address, :city, :name, :phone, :state, :website, :zip, :contactname
  attr_accessible :conferences_attributes, :checklists_attributes
  has_many :notes, :dependent => :destroy
  has_many :accountchecklists
  has_many :checklists, :through => :accountchecklists, :dependent => :destroy
  has_many :contacts, :dependent => :destroy
  has_and_belongs_to_many :conferences
  accepts_nested_attributes_for :conferences
  accepts_nested_attributes_for :checklists
end

Answer: <%= form_for @account, :url => { :action => "edit"} do |form| %>
change to
<%= form_for(@account) do |form| %>
Answer: I changed
<%= form_for @account, :url => { :action => "edit"} do |form| %>

change to
<%= form_for @account, :url => { :action => "update"} do |form| %>

and then I made the checklist_ids accessible since I was getting a can't mass assign checklist_ids
class Account < ActiveRecord::Base
   attr_accessible  :checklist_ids
end

Rails Using Edit action in a Show View


How to get the string value from the function CountryManager::getStandardList()?

Question: Input :
<code> $li = array();
    $list = \Drupal\Core\Locale\CountryManager::getStandardList();
    foreach($list as $key => $value){
        $li[$key] = $value;
    }
    // print_r($li);
</code>
Output :
<code>[AF] => Drupal\Core\StringTranslation\TranslatableMarkup Object
        (
            [string:protected] => Afghanistan
            [translatedMarkup:protected] => Afghanistan
            [options:protected] => Array
                (
                )
</code>
How can I fetch String value from the above structure?
Answer: To fetch the string value from the translatable markup object use type casting:
<code>$li[$key] = (string) $value;
</code>
Comment: Gr8 Answer and very much  helpful for me!!
Answer: While you can explicitly cast it to a string as suggested in 4k4's answer, in 99% of the cases, you don't have to.
print_r(), var_dump() and similar will show the object, but when you actually print it out, it will be implicitly cast to a string.
There are only very few cases where you must cast yourself, for example when you want to use the string as an array key.
You can pass such an object along in a render array, #options for a select or almost anything else and it will just work.


How to reduce vocal strain when singing long duration high notes?

Question: Usually when I hit songs that have long notes and are somewhat in my mid/high position in range my voice kind of tires out. I can sing the whole song again, but at these long note parts I just can't last very long.
My voice still kind of "tires out" till the end. I feel as if my muscles can't sustain that pitch anymore, and it just drops. I am using head voice when singing high notes. Now I can sing these songs but after or almost till the end I feel so strained. Sometimes I can't finish them.
Comment: Sorry if this seems cruel, but I am glad that someone else has this problem too!
Comment: It seems it was a breathing problem, too much breath, and not breathing properly through the diaphragm can wear off the voice, never thought could be a bigger problem. Ahh well. :)
Comment: Use some vibrato.
Answer: The answer was given about 'not breathing properly through the diaphragm' This is a profound statement, as most proponents of body singing tell us that we must sing 'with' the diaphragm..or at the very least...'use the diaphragm' to sing properly. Perhaps we could just simply sing 'through' and 'with' our souls? We could use our energy...wouldn't that be wonderful!!! Take care of all these sundry problems with the body singing business, no? It's a bit like watching people playing computer games, or people driving with a GPS....as my son Damon (who owns a computer business) says to ALL of them "don't get too attached to the MAP!!!!" Or, perhaps it may be like the people who demand that the Taoists say 'we must walk the centred path - looking neither to the left or right....' Perhaps the word was scented??? Maybe we could just wake up, and smell the Roses? This is but my humble opinion, based on 66 years of experiencing life and research in all it's wonderous forms. We need to but learn the 3 'R's - Relax - Relax - RELAX !!!! It's as simple as A.B.C. Awareness - Balance - Control. Dear friend Ivan, it is not your voice that tires out - it is your breath..the body will breathe better and more fully if we would but allow it...by simply letting go of our mind's attachment to it.
Answer: I have the same problem sometimes, too, so don't worry. I can suggest two things, though. Try singing scales and working your way up to the specific note(s) that you wish to sing. You can also try projecting your voice. But, don't get so loud that you are straining to be louder. I love to sing and I tried to sing really high notes when I first started and my choir director suggested these two things. They worked for me, so I hope this helps! Enjoy singing and don't forget to practice!
Answer: try gradually warming up into your high range throughout the day.  I know when I wake up on saturdays all ultra stoked and start singing full steam my high range gets worn out


Cocoapod path reference error

Question: I have newly added cocoapods into my application, now getting "parser error" while compiling the code in client machine, But the same source code working fine in my system (without any changes).
Please find below error along with screen shot.
../../../FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKAccessToken.h

And also i have added this tag ($(inherited) - > non-recursive) into below paths in Target -> Build settings.
Header Search Path,
Framework Search path,
Library Search Path.
i hope this is cocoapods path reference issue, Please any one help me out of this issue.
Note: Have sent file to client as a .zip.
Comment: don't looks like pods issue
Comment: @Misha actually, i need to know why this issue occurring in only client end. Can u tell me why this issue happening.
Comment: the error is says you are missing parenthesis , I could help more if you could post more detail screenshot
Comment: @Misha thanks for your response, Have solved this issue by, sent source file to another machine(Client Place) as a .tar.gz file format instead of .zip file.
Answer: Finally i came up with answer, I have sent source file to client end(other systems) as a .tar.gz format instead of .zip file.
This is solved my issue.Hope it will help for some one in the future.....

Cocoapod path reference error


How Can I Isolate Individual Drums From An Overhead Track?

Question: Me and my band were demoing some stuff at rehearsal the other day. For my style of mixing, I'd much prefer every drum close miked and as isolated as possible from everything, but this wasn't possible with the space and limitations we have. So we recorded the drums using just 2 mics (one just above the kick and one above the drummer's shoulder). Coming down to mix it, I want to try and replace the snare, kick and toms with samples, but obviously I can't just replace them from the track because it's picking up everything.
So how would you guys go about isolating each individual drum from the 2 tracks? I imagine I'll have to use an EQ and try and find a frequency specific to each drum, boost the hell out of it and use it as a trigger for some samples, but are there any better ways of doing this?
Thanks all!
Answer: Another idea to add (for future readers who want to put live humanized drums into their recordings but retain the ability to mix them optimally with their DAW), is to use drum triggers which make your acoustic kit record like an electronic one.
Obviously for the recording you have already made, Todd Wilcox suggestions are probably your best option (even if somewhat time intensive).  But for future sessions, if you add electronic triggers to your drummer's snare, kick and tom, you will be able to manipulate those and convert them to samples in your workstation with far less work.  You can also still use mics and create a custom blend of sampled hits and acoustic mic'd sounds to get a really unique and realistic sound in your finished demo.
I understand the technology in these type triggers is continually advancing and improving.  Adding triggers to an acoustic set can not only be more economical than buying a decent electronic kit, but many drummers don't like the feel and responsiveness and the dynamics of the electronic kits.
But for recording drums, electronic kits or acoustic drum triggers can certainly make life easier for whomever is engineering and editing the tracks.
Just sayin .......
Comment: Good point. The thought passed through my head while I was writing my answer but did stick. If you have extra input channels, you can record just the click from the triggers and use that for replacement (good to label your tracks well in this case!). If input channel count is a limiting factor, then there are some affordable trigger to MIDI boxes, and MIDI is just one input and virtually no hard drive space.
Comment: @ToddWilcox  I believe if you run your triggers into a electronic drum control module you can connect with one input channel also.
Comment: Yes if that module is a drum machine that is playing back sampled or synthesized drum sounds based on the trigger inputs. Good point.
Comment: If I had the means at the time, this would have been the best option because I have more than enough inputs on my own interface for a close miked kit as well as triggers on most drums, so it would be my choice but given the limitations at the time, I have to make do unfortunately!
Comment: @JamieBrace - I do recognize that.  That's why my answer started off with "for future readers ...  "  Sometimes folks come across these questions and answers when searching for a solution to whatever problem they are trying to solve at the time.  I took that into consideration and took the opportunity to add some valuable content for future readers who might otherwise not think about using triggers for adding drums to their home recordings.  I'm sorry that I had nothing further to add specific to your current situation.  I wish you the best of luck though.
Comment: @RockinCowboy sorry, I didn't mean to offend, I appreciate what you've added here and it's definitely the option I would choose if I had the means!
Comment: @JamieBrace No offense taken.  Rock on brother!
Answer: Probably your best bet will be a gate with a sidechain or a gate plug-in with frequency/band settings. You definitely want to find a way to gate separately for each drum since you want no signal at times when you don't want the trigger to go off. You can set trigger sensitivity to eliminate quiet sounds, but you might want some of the dynamics going into the trigger and you'll get the easiest replacement by having a fully isolated track before you go into the trigger/replacement.
In case it's not obvious, you'll want to make a separate copy of your two channel drum tracks for each piece you want to isolate. Then start processing each copy separately until you can unmute them all and hear the kit pieces separated out.

Kick might be the easiest because a low pass filter somewhere between 50 and 150 Hz before a gate should be good enough to mostly isolate it. You may get some floor tom coming through with a low pass and gate. If so, you'll probably have to manually mute/delete those regions that have floor tom. You're going to be doing some editing on these tracks so might as well warm up with an easy one.
Snare will both be difficult and probably the most important one. The problem is that the body of the snare overlaps the toms and the snare rattle overlaps the cymbals. First thing I would do is go through and mute/delete all tom fills. Hopefully you mainly have toms played on fills and not as an integral part to many beats. In the latter case it's going to be a long night. Put a bypassed highpass filter and bypassed lowpass filter on the "snare" track, and then a gate. Start with the gate. Take the threshhold to the point where the gate is always closed and you have no sound. Dial back the threshold until the snare starts poking through. Usually the snare is really loud so this should be doable for the loudest hits. As you bring in the quieter snare hits you'll start to get kick hits and maybe some of the louder high hat and crash hits. At this point I would play with the time controls on the gate so I'm getting clean gate open and close on the loudest hits of the whole kit. Then I would bring the threshold down to where I'm getting 95%+ of the snare hits I want. Then start bringing the high pass up to eliminate kick hits coming through, and then bring low pass down to eliminate cymbals. You will probably reach a point where you are have eliminated most of the none snare hits but not all of them. You might have to manually mute or delete some section where there is just too much bleed. It's a pain but it's worth it for a clean, dymanic snare trigger track.
For the toms, I would just edit around the tom fills unless there is a lot of tom work. If there is a lot of integral tom work, again, you're in for a long night. I would proceed like the snare work above, and look to find the note/tonal center of each tom. You might have more success with boosting a bandpass filter before the gate rather than playing with high and low pass filters. If the snare has a real "ping" to it, a narrow bandpass might isolate that better than high and low pass also.

It'll be a lot of work. But that's the story of good drum tracks, no matter how you get them. It's a lot of work but it's always worth it in the end.
Comment: Haha I feared this might be the answer! In all honestly, this is exactly what I had in mind but I just wanted to see other people's ideas on the matter. I've had to do this where toms were part of the actual beat, not just fills, and it was a real pain. Luckily, this one is a little more simple so hopefully it won't be too long a night!
Comment: Ah, well sorry I didn't have any magic ideas. Have fun!
Answer: Do you have to replace the drums with samples? Can you get a decent mix from the drums as they are? The mic positioning you used is a common method for recording a well balanced kit with only two mics.
I realize that samples are common place, but as a drummer I wouldn't want the character and dynamics of my playing completely removed by replacing everything with samples. I do practice at home with an electronic Roland V-Drum kit and while it is great for low-volume practice, I feel the same way about the sound and feel of playing it vs a real kit. There just is no comparison! I would much rather hear even a mediocre recording of a real kit as it was actually played than pristine samples that sound fake.
I would give mixing the real drums a try before replacing them completely. Another option would be to mix samples underneath the real drums if you need to fatten or increase the volume of particular drums where normal EQ/compression isn't quite cutting it. Mix the samples in just enough to get what you need without overriding the original performance.
Comment: Honestly, it sounds very garage rock/metal to me and IMO pristine drum samples would not suite the mix or feel. The drums sound well balanced as a whole so I think those are salvageable. They are a bit buried by the guitars. If the snare and kick are balanced between the two mics you could try panning them R/L a bit to get some width on the drums. You can get a lot of clarity through heavy parallel-processing. Here is a video demonstrating the technique, this is a close miced snare so when blending be sure to listen that the cymbals don't turn harsh. https://www.youtube.com/watch?v=N7MqRrztfmQ
Comment: I don't have to, but the recording is pretty bad, there's hardly any quality to it and it's pretty hard to mix how I want. If it was a garage rock song, I would be more than happy to use the 2 mics and mix it that way, but for the style of the song, I want a clearer drum sound. Obviously using samples will never sound as good as a properly recorded kit, but for this purpose I want to be able to individually balance the drums with the rest of the instruments and it'll by far easier to do this after I've sample replaced most of the kit. Don't get me wrong, I understand where you're coming from.
Comment: Can you post a short audio clip of the song? You might be right about the drums being unsalvageable, but it can't hurt to get a second opinion on it. Also, if you do replace the drums with samples, you'd have much more control to simply zoom in on the timeline and place the samples by hand where you want them...this maybe faster too. Trying to isolate via EQ/gate might take more time than it's worth and not produce the results you want (missing snare grace notes for example) I've done quite a bit of editing/comping for drums/percussion and editing by hand doesn't take as long as you'd think.
Comment: https://soundcloud.com/jamiebrace/metaeqquickmaster-mp3/s-ez0ga - that was before I tried to mix it (it was uploaded just to send to the other band members really). They're not horribly bad but I would just prefer to have more detail and a bit more clarity really. I'm quite happy to spend the time doing it, besides my samples are from Superior Drummer and Addictive Drums so I'll be using Drumagog to trigger the samples :P
Comment: be warned of the lyrics though - explicit doesn't cover it haha
Comment: @JamieBrace  if the guitars are on a dedicated track, you could bring out the drums by pulling down the guitars and playing with the EQ on them.  They are quite overpowering in the clip you posted.  The vox might sit better as well if you pull down the guitars.
Answer: You could try nmfdemix, which is a simple commandline program that splits a signal into multiple frequency bands (free). I have successfully did exactly what you mentioned using this tool. If you search youtube for "nmfdemix" my tutorial is there for setup a demo (individual drum hit extraction is towards the end of it). It is all dependent on the quality of the source tracks, but it is the best I've found so far. Hope it helps.