Load a Partial View using jQuery .load() and no Razor

Question: I have a View which is the container for a PartialView. Let's say a Customer - Orders relation. The View should received a CustomerViewModel whereas the PartialView a collection of Orders, such as  IEnumerable<OrderViewModel>.
I basically have two ways of doing this (not to mention Angular), either Razor or jQuery. With Razor was pretty straightforward by utilizing  @Html.Partial("_CustomerOrdersPartial", Model.Orders). But let's assume I cannot use Razor syntax and here it is how I ended up posting this question. I have read many posts on this matter but, most of them (not to mention all), suggest to use  $("#container").load('@Url.Action("ActionName", new { parameterX = valueY })). Then here are my questions:

Why to mix Razor and jQuery?
Is this the only way?
Is there any way to call the View and pass the model?

The last question has to do with the fact that the above code requires an action on the server-side to be called, whereas the  @Html.Partial("_CustomerOrdersPartial", Model.Orders) mentioned above will just call the View (client-side) and send the given Model in.
Any idea on how to solve this would be really helpful.
Thanks in advance for your time and thoughts.
Comment: Because using `'@Url.Action()` will always ensure your url is correctly generated.
Comment: `@Html.Partial()` is server side code, not client side code. Not really sure what your asking here. `$.load()` is client side code. Why in the world would you send your model to the view then send it back again, unchanged, to the server to get a partial view based on it instead or just rendering it in the first place. You typically use `$.load()` (or any ajax method) in response to client side events
Comment: Because `Html.Partial()` is server side code. The method searches for a view with the matching name and adds it the the html being generated on the server side. It does not need a url because its already on the server. Using `.load()` however is client side code. The client has no knowledge of what is on the server unless it calls the server to return something, and to do that, you need to provide a url.
Comment: `@Url.Action` itself is a Razor syntax that generate URL based from controller and action method. Keep in mind that partial view created from a callback, without refreshing entire page.
Comment: Exactly what Stephen said. Your URLs are maintained by the MVC routing infrastructure. One of its main purposes is to ensure that there is only 1 place in the application to change if you want to change a URL later. Using `@Url.Action` ensures the URL is generated from routing rather than being hard coded in your view.
Comment: @stephen-muecke I agree `@Url.Action` will ensure the url is consistent, just as asp-controller tag helper does in ASP.NET Core but, still Url.Action will go server-side whereas `@Html.Partial` will stay client-side. Am I wrong?
Comment: Thanks for clarifying @stephen-muecke. Let me make myself clear about my question. What I'm trying to find out is, when using `@Html.Partial()`  why are the parameters to send in, the view_name and/or a model? meaning, there is no action method. Whereas, when using `$.load()` the parameter is the URL to an action. I mean, there is no way to inject a partial view through jQuery without the need of an action method.
Comment: thanks @StephenMuecke
Answer: my solution is:
function ReturnPanel(div, panel) {

    $.ajax({
        type: "POST",
        url: "@Url.Action("GetPanel", "ControllerName")",
        data: JSON.stringify({ 'idCurso': idCurso, 'panel': panel }),
        contentType: 'application/json; charset=utf-8',
        success: function (response) {
            $("#" + div).html(response);
        },
        error: function (xhr, status, errorThrown) {
            //Here the status code can be retrieved like;
            alert("Error: status = " + xhr.status + " Descripcion =" + xhr.responseText);
        }
    })
}

in cs.
 [HttpPost]
    public ActionResult GetPanel(int idCurso, string panel)
    {
        Contenido contenido = new Contenido();
        contenido.IdCurso = idCurso;
        return PartialView(panel, contenido);
    }

Answer: This code should do it.  The trick is to acquire the URL and then make sure you get the parameter list right. I used a little Razor to get the URL but you don't have to.  Also, If you fail to match the parameter list, your call will not even be acknowledged. You have been warned. I tried to name every thing in a way that helps.
    var url = '/controllerName/ActionName';
    $('#pnlFillMee').load(url, {NameOfParam: $('#elementID').val() },
    function () {CallMeAfterLoadComplete(); });

Here's a real world example I use at work. ReviewInfo is an action in the
controller associated with this page.  It returns a partialview result.
$(document).ready(function () {
var url = '/supervisor/reviewinfo';
$('#pnlReviewInfo').load(url, { FCUName: $('#FCU').children(':selected').text(), AccountsFromDate: $('#AccountsFrom').val()}, function () {
                    InitializeTabs(true);
                });
});

This goes somewhere on your form.

EDIT:
I would also look up the other jQuery functions like $.get, $.post and $.ajax which are more specialized versions of $.load. and see this link which might answer all your questions about passing models:
Pass Model To Controller using Jquery/Ajax
Hope this helps
Comment: well if you do this alert(url); in the code you will see that Url.Action is simply acquiring the controller name which is part of the routing system in MVC.  so URL turns out to be '/controllerName/actionName' Are you just trying to figure out the URL without using Razor. No matter how you slice it JQuery.Load needs the URL.
Comment: I have updated my answer. After a more in-depth reading of your question.
Comment: Thanks but, I still need to have an action method while when using `@Html.Partial()` I don't have to. I am looking for a way to inject a partial view into a view using jQuery without calling an action method.
Comment: Thanks @charles-mcinstosh
Answer: wrapping up this question and thanks to @stephen-muecke and @charles-mcintosh for their help:

Using @Html.Partial(partialViewName) the server returns a string resulting from the partial view passed in. Preferred method if you need to manipulate the partial before being displayed. Otherwise, using @Html.RenderPartial(partialViewName) will write into the stream output sent to the browser, the HTML code from the given partial.
As per jQuery API, $(elem).load(url[,data][,complete]) will place the returned HTML into the matching element. Thus, it requires an action method for the given url.
If for whatever reason Razor cannot be used on the UI, chances are you would likely end up either hard-coding the url like in the sample code provided above by @charles-mcintosh or using Angular.


How to compute $\int_0^{\frac{\pi}{2}} \frac{\ln(\sin(x))}{\cot(x)}\ \text{d}x$

Question: I am trying to compute this integral.
$$\int_0^{\frac{\pi}{2}} \frac{\ln(\sin(x))}{\cot(x)}\ \text{d}x$$
Any thoughts will help. Thanks.
Comment: Firstly one has to find out whether it converges. In 0, the function is bounded since it is infinitesimal. What about $\frac\pi2$? It is asymptotic to $\frac{\sin x-1}{\cos x}$ there. By L'Hôpital's rule this goes to $\lim_{x\to\frac\pi2}\frac{\cos x}{-\sin x}=0$, so OK, the integral converges.
Comment: Let $u=\sin x$, and you get the integral $$\int_0^1\frac{\ln u}{2(1-u)}-\frac{\ln u}{2(1+u)}\,du.$$ Just turn the corresponding geometric series around and integrate. You will get a rational constant times $\pi^2$.
Comment: @mickep nice, that was also my first thaught
Answer: Note that
$$\int_{0}^{\frac{\pi}{2}}{\frac{\ln(\sin{x})}{\cot{x}}}\,dx = \int_{0}^{\frac{\pi}{2}}{\ln(\sin{x})\tan{x}}\,dx = \int_{0}^{\frac{\pi}{2}}\frac{\ln(\sin{x})\sin{x}}{\cos{x}}\,dx $$
$$= \int_{0}^{\frac{\pi}{2}}\frac{\ln\left(\sqrt{1-\cos^2{x}}\right)\sin{x}}{\cos{x}}\,dx$$
Now, set $u=\cos{x}\implies du=-\sin{x}\,dx$. Also, note that $\ln\left(\sqrt{1-u^2}\right)=\frac{1}{2}\ln\left(1-u^2\right)$ Also, don't forget to change the limits. Now, we have
$$\int_{0}^{\frac{\pi}{2}}\frac{\ln\left(\sqrt{1-\cos^2{x}}\right)\sin{x}}{\cos{x}}\,dx=\frac{1}{2}\int_{0}^{1}\frac{\ln\left(1-u^2\right)}{u}\,du$$
There are two paths you can take from here. One I have shown below, and the other is shown by Dr. MV in the comments below.
Now, we need to find what $\ln\left(1-u^2\right)$ is. Recall the Maclaurin Series for a natural logarithm. Therefore,
$$\ln\left(1-u^2\right)=-\sum_{n=1}^{\infty}\frac{u^{2n}}{n}$$
$$\therefore \frac{1}{2}\int_{0}^{1}\frac{\ln\left(1-u^2\right)}{u}\,du=-\frac{1}{2}\int_{0}^{1}\sum_{n=1}^{\infty}\frac{u^{2n}}{nu}\,du=-\frac{1}{2}\sum_{n=1}^{\infty}\int_{0}^{1}\frac{u^{2n-1}}{n}\,du$$
$$=-\frac{1}{4}\sum_{n=1}^{\infty}\left.\frac{u^{2n}}{n^2}\right|_{u=0}^{u=1}=-\frac{1}{4}\sum_{n=1}^{\infty}\frac{1}{n^2}$$
Since $\sum_{n=1}^{\infty}\frac{1}{n^2}=\frac{\pi^2}{6}$,
$$\int_{0}^{\frac{\pi}{2}}{\frac{\ln(\sin{x})}{\cot{x}}}\,dx=-\frac{\pi^2}{24}$$
Comment: @MickG Monotone Convergence Theorem : all the terms of the series are non-negative because $0\leq u\leq1$.
Comment: $$-\int_0^1 \frac{\log(1-u^2)}{u}\,du=\text{Li}_2(1)+\text{Li}_2(-1)=\frac12 \text{Li}_2(1)=\frac{\pi^2}{12}$$
Comment: @mickep I don't see a compelling reason to compute the anti-derivative in this case.  I was pointing out that there is no need to proceed with the series representation after the substitution when the integral is already in the form that leads to a very straightforward result.
Comment: One thing: how do you justify swapping integral and series?
Comment: @Dr.MV If you want to go the polylogarithmic way, it seems that $$-(\ln \sin x)(\ln(1+\sin x))/2+\text{Li}_2(1-\sin x)/2-\text{Li}_2(-\sin x)/2$$ is a primitive to the original integrand.
Comment: @MickG What Nicolas said is the justification, but this may be of help too http://math.stackexchange.com/questions/83721/when-can-a-sum-and-integral-be-interchanged
Answer: Note that
\begin{eqnarray}
&&\int_0^{\frac{\pi}{2}} \frac{\ln(\sin(x))}{\cot(x)}\ \text{d}x\\
&=&\int_0^{\frac{\pi}{2}}(\cos x)^{-1}\sin x\ln(\sin x)\ \text{d}x=\lim_{a\to0,b\to2}\frac{d}{db}\int_0^{\frac{\pi}{2}}(\cos x)^{a-1}(\sin x)^{b-1}\ \text{d}x\\
&=&\lim_{a\to0,b\to2}\frac{d}{db}\frac{1}{2}B\left(\frac{a}{2},\frac{b}{2}\right)\\
&=&\lim_{a\to0,b\to2}\frac{1}{4}B\left(\frac{a}{2},\frac{b}{2}\right)\left(\psi\left(\frac{b}{2}\right)-\psi\left(\frac{a+b}{2}\right)\right)\\
&=&\lim_{a\to0}\frac{1}{4}B\left(\frac{a}{2},1\right)\left(\psi\left(\frac{b}{2}\right)-\psi\left(\frac{a+2}{2}\right)\right)\\
&=&\lim_{a\to0}\frac{1}{4}B\left(\frac{a}{2},1\right)\left(\psi(1)-\psi\left(\frac{a}{2}+1\right)\right)\\
&=&-\lim_{a\to0}\frac{1}{4}B\left(\frac{a}{2},1\right)\left(\gamma+\psi\left(\frac{a}{2}+1\right)\right)\\
&=&-\lim_{a\to0}\frac{1}{4}\frac{\Gamma(\frac{a}{2})\Gamma(1)}{\Gamma(\frac{a+2}{2})}\left(\gamma+\psi\left(\frac{a}{2}+1\right)\right)\\
&=&-\lim_{a\to0}\frac{1}{4}\left(\frac{2}{a}+O(a^2)\right)\left(\frac{\pi^2}{12}a+O(a^2)\right)\\
&=&-\frac{\pi^2}{24}.
\end{eqnarray}
Here we use the following fact
$$ \Gamma(a)\approx\frac{1}{a}, \gamma+\psi(\frac{a}{2}+1)\approx\frac{\pi^2}{12}a.$$
Comment: [This](http://homepage.tudelft.nl/11r49/documents/wi4006/gammabeta.pdf) is very relevant for someone who tries to follow your solution without knowing anything about those functions. Too bad it does not contain the derivatives of $B$…
Comment: What are $B$, $\psi$ and $\gamma$? Is $\gamma$ the [Euler-Mascheroni constant](https://en.wikipedia.org/wiki/Euler%E2%80%93Mascheroni_constant), which [Wolfram](http://www.wolframalpha.com/input/?i=gamma&a=*C.gamma-_*NamedConstant-&a=*DPClash.CharacterE.gamma-_*%7F611.dflt-) states is $-\int_0^\infty\frac{\log t}{e^t}dt$? And is $\psi$ the [Digamma function](https://en.wikipedia.org/wiki/Digamma_function)? And I'm betting $\Gamma$ is the [Euler gamma function](https://en.wikipedia.org/wiki/Gamma_function#18th_century:_Euler_and_Stirling), right?
Comment: @MickG, yes, your right. 4b
Comment: Is [this](http://mathworld.wolfram.com/BetaFunction.html) your $B$?
Answer: A partial answer: Let $I$ be the given integral. You can integrate by parts, letting
$$\begin{matrix}u=\dfrac{\ln(\sin x)}{\cot x}&&&\mathrm{d}v=\mathrm{d}x\\[1ex]
\mathrm{d}u=\left(1+\sec^2x\ln(\sin x)\right)\,\mathrm{d}x&&&v=x\end{matrix}$$
which yields
$$\begin{align*}
I&=\frac{x\ln(\sin x)}{\cot x}\Bigg|_{x=0}^{x=\pi/2}-\int_0^{\pi/2} x\left(1+\sec^2x\ln(\sin x)\right)\,\mathrm{d}x\\[1ex]
&=0-\left(\int_0^{\pi/2}x\,\mathrm{d}x+\int_0^{\pi/2} x\sec^2x\ln(\sin x)\,\mathrm{d}x\right)\\[1ex]
&=-\frac{\pi^2}{8}-\int_0^{\pi/2} x\sec^2x\ln(\sin x)\,\mathrm{d}x
\end{align*}$$
It turns out that the remaining integral is twice $I$, which means $3I=-\dfrac{\pi^2}{8}$, or $I=-\dfrac{\pi^2}{24}$. I'm still seeing what can be done to establish this last part, though.
Comment: could u show the last step? i don't get it :(
Comment: @tired I don't know what can be done (if anything can be done) to establish that the last integral is equal to $2I$, I'm afraid.
Answer: Hint: $\cot(x) = (\ln(\sin(x)))'$
Comment: Maybe I'm missing something, but would that not help if we had the reciprocal of that ratio, concluding the antiderivative was $\log(\log(\sin x))$? Besides, seeing [Wolfram's antiderivative](http://www.wolframalpha.com/input/?i=integrate+ln%28sin%28x%29%29%2Fcot%28x%29+dx) and its bunch of $Li_2$s, I find it hard to believe that such a simple hint would solve the problem…
Comment: I saw that too, but I don't know how it helps. Can you add some more details to your hint
Comment: It would be $\frac{f'(x)}{f(x)}$ where $f(x)=\cot x$ which is helpful


Vue.js watch DOM element property outside components / app

Question: I have a vue component nested in a regular website.
I would like to watch from the component if a DOM element is clicked outside of this component. this is just a regular HTML element NOT in a vue component
I can't use v-on. I also tried a regular event listener but that does not work either because it cannot access the component's property...
Is there a way to do this ?
Answer: Simply add an event listener in mounted() of your component. Here's a fiddle I put together: https://jsfiddle.net/2kwjvtun/


Intuitive meaning of Neumann boundary condition

Question: I was revising some notes and found myself not understanding the Neumann boundary condition. I understand it analytically - it's $\frac{∂u}{∂x}|_{x=0}=f(t)$ (let's consider the 1-D example of a metal rod with coordinates $x\in[0,1]$ and time $t\in[0,\infty]$), but I can't understand what it really means. Wikipedia says it is "heat flux" - so I try to imagine heat flux as a heater on the left side of the rod. But if the rod is really hot then the heater accounts for negative heat flux, so the heat flux is the function of the rod's temperature $u|_{x=0}$, which is not in the definition. Another question is the meaning of the derivative $\frac{du}{dx}$. It denotes the steepness of the temperature function at $x=0$. But what if the rod is perfectly insulated inside itself and no thermal conduction is possible? That would only be possible if $\frac{∂u}{∂t}=0$ - a degenerate version of the heat equation. In other words, I don't understand how the $\frac{∂u}{∂x}|_{x=0}=f(t)$ boundary condition does not depend on the properties of the rod (the heat equation itself).
How do you understand this condition to yourself?
Comment: FYI -- "Neumann", not "Neymann", after Carl Neumann
Comment: @MPW sorry! edited!
Comment: @MPW Wow! I always thought it was John von.
Comment: How exactly is $u$ defined here. What are the parameters it depends on?
Comment: @Allawonder time and the coordinate x. It's the temperature of a 1-D rod
Comment: @Allawonder : I guess that would be "von Neumann boundary condition"
Answer: The condition says that the rate at which the temperature changes at the end of the rod where $x=0$ is a function of time. The special case $f(t)=k,$ for some constant $k,$ says the temperature at that point is fixed for all time.
Answer: I will answer the second part first. You can heuristically derive the heat equation by noting that

since heat transfer is basically diffusion, the heat flux $\vec q$  is essentially given by the gradient of  the temperature $u$ (this is Fourier's law), $$\vec q= - k \vec \nabla u\,,$$
and the change of temperature at any given point depends of the net flux of heat, $$\frac{\partial u}{\partial t}= A \vec \nabla\cdot\vec q\,.$$

Here, $k$ is the thermal conductivity and $A$ is essentially the specific heat times density. Combining these equations, we get the heat equation, with a combined coefficient $\alpha$.
Now, you ask what happens if the rod is perfectly insulated inside itself. This would mean $k=0$ and thus $\alpha=0$, so indeed there would be nothing interesting happening. Of course, this is also physically obvious.
For the first part: From the general PDE perspective, one can always consider Dirichlet or Neumann BCs. The first, in this case, are physically intuitive -- the temperature at the boundary is kept fixed. The second choice, by Forier's law, means that the heat flux out of the boundary is fixed. If $u_x=0$, this is again simple to interpret -- the sample is insulated, and no heat enters of leaves. For a nonhomogeneous choice, $u_x=f(t)$, it is physically less obvious how to realise such a setting, but it still means that a given amount of heat is entering or leaving the sample. And since the heat equation is linear, it suffices to consider these cases to build general solutions.
However, there is a different choice of BCs (mixed or Robin BCs) that is easier to interpret: You can impose $u + \kappa u_x=f(t)$, with a constant $\kappa$. This says that the heat flux is proportional to the temperature -- just what you expect when the material is ion contact with some other substance, and the heat transfer depends on the relative temperature. Again, by linearity, this type of BCs is already covered if you have dealt with Neumann and Dirichlet BCs.
Comment: Just a side question: please do you know the practical meaning of the compatibility condition $\int_Df =0$? I know sometimes $f$ represents the source term and $\nabla u\nu=g, ~~ (g=0)$ stands for the heat flux at the boundary. But I am barely looking for a reference that gives the meaning (in practice or physical ) of the compatibility condition $\int_Df+\int_{\partial D} g   =0$ or the meaning (in practice or physical) of the quantity $\int_Df+\int_{\partial D} g $.
Comment: Maybe you help: I have asked my question here: https://mathoverflow.net/questions/385745/seeking-for-references-on-some-pdes


Double com precisão de no máximo 40 dígitos

Question: Estou a precisar que meu programa retorne um valor alto de dígitos, na casa de no máximo 40 dígitos.
Vi que o tipo DOUBLE tem uma abrangência que vai de 1.7 X 10^-308 até 1.7X10^308, por isso devo pensar que ele atende, até demais, minhas necessidades.
Mas quando esse simples programa é iniciado:
int main()
{
  double p = 1234567890123456789012345678901234567890.0;

  printf("%.0lf", p);

  return 0;
}

Ver também no Ideone
O retorno obtido será: 1234567890123456780000000000000000
Como contornar o problema em questão?
Comment: Você já fez esta pergunta e ela já foi respondida: http://pt.stackoverflow.com/questions/38138/divis%C3%A3o-matem%C3%A1tica-precisa Ou não?
Answer: Não é possível obter esta precisão com double.
Números em notação de ponto fluante como o double são excelentes para representar números muito pequenos ou números muito grandes, mas não uma mistura dos dois. Para números muito grandes, os valores de ordem de magnitude menores influenciam muito pouco no resultado das operações, sendo descartados sem grandes perdas.
Se quiser saber mais, veja sobre o padrão IEEE 754, que é o padrão que os processadores x86 implementam (acredito que ARM utiliza o mesmo padrão).
Para precisões arbitrárias é necessário utilizar uma biblioteca como a GMP (GNU Multi-Precision Library). Ela é capaz de manipular números tão grandes quanto sua memória, sejam estes números inteiros, fracionários ou de ponto flutuante.
O site da lib:
The GNU Multiple Precision Arithmetic Library
Ela suporta as principais plataformas (Windows, Mac, Linux, FreeBSD).
Comment: Estás respondendo pela segunda vez a mesma pergunta para o mesmo AP :-)
Comment: @pcccj Tenho até medo de perguntar, mas por que você precisa fazer isso? O que essa "função hash" faz? (i.e. para que ela serve?) Em geral, quando queremos trabalhar com dados de tamanho arbitrário, não convertemos esse dado em número primeiro e fazemos operações numéricas nele, esse seu requisito me parece um tanto inusitado... Poderia por favor contextualizar melhor?
Comment: tenho a seguinte função: code("casa") = c*26^3 + a*26^2 + s*26^1 + a*26^0 = 35620.
Comment: para strings grandes, dá erro. preciso desses numeros para no fim utilizar numa funcao hash: x mod tam
Comment: @Caffé para você ver como não lembro nem o que almocei!
Comment: Estou implementando uma Hash Table. A funcao code() irá codificar as strings. Desculpe-me a confusão.


Show relationship summary using Entity Reference

Question: First question, hope I can get some answers. I have this information schema:
Books: Title and Author (Entity Reference field to Books content type)
Author: Name and Books (Entity Reference field to Author content type)
I created a view to show the authors with their ID's. I want to also show in the Books field the ID's for the books that reference them. I already created the relationship and turned aggregation on and asigned it to the books field. The view looks like it's working and aggregation also seems to be working, however, no results are showing in the books field. Any ideas?
I'll appreciate any answer. Thanks!
Answer: First off, you only need an entity reference field on the content type Books that points to Author in your example. It would be a pain in the long run to manually maintain the two relationships and all data needed to describe your relationship is given in the Book->Author field.
Now let's create a View that lists books.

(I've removed the second column in the screenshot from Views as no settings were done there)
Add the entity reference relationship under Relationships.
Add Content: title and use your relationship.
Under Format and Settings, set group by to the Content: Title field you created in the step before.
Now all books are listed and grouped by their author.
In my example I also sort by the authors name. If you rather show the Nid of the content, just switch from Content: Title to Content: Nid.


Issue with rails mailer and rake task

Question: If an agent hasn't been verified, I want one email to be generated and sent to me with all of their names. Not sure where I went wrong.
agent_card_mailer.rb
class AgentCardMailer < ActionMailer::Base
  default from: "Help <firstname.lastname@example.com>"

  def not_verified_message(agent_card)
    @agent_card = agent_card

    mail(:to => "email@example.com", :subject => "Agent License Issues")
  end
end

not_verified_message.html.erb
Hi there,

These agents have not been verified.

<% @agent_cards.each do |agent_card| %>
  <%= agent_card.agent.name %>

<% end %>

issue_with_license.rake
namespace :agent_cards do
  desc 'Send out weekly email for agents with issues'
  task remind_license_issues: :environment do
    AgentCard.all.each do |agent_card|
      if agent_card.verified == false
        AgentCardMailer.not_verified_message(agent_card).deliver_now
      end
    end
  end
end

error:
ActionView::Template::Error: undefined method `each' for nil:NilClass

Answer: Your mailer is setting the attribute @agent_card but the template is looking for the plural @agent_cards
Comment: If you call Something by another name, the app can't find it. You set `@agent_card` in the controller then you have to use the same in the view. (It's only when dealing with models that you sometimes you pluralize like `@user=User.first` `@email@example.com` post is pluralized here because you expect many)
Comment: Actually your `each do` will probably fail unless `agent_card` you pass in the `not_verified_message` method is a collection, not a single record. Give us all your models in order to help you. If, let's say, there is an Agent which is parent of Agent_card like `Agent has_many agent_cards` then pass the agent in the method and then you can retrieve all agent cards in the view...

Issue with rails mailer and rake task


How to add a groupby to a view query

Question: I have a view and I need to add a groupby at the end of the SQL query but, for some bugged module the interface do not save the 'Grouping field Nr.' option and I don't know how to achieve this view -.-

SELECT DISTINCT taxonomy_term_data.tid AS tid,
  field_testata_taxonomy_term_data.product_id AS field_testata_taxonomy_term_data_product_id,
  field_magazine_commerce_product.nid AS field_magazine_commerce_product_nid,
  field_magazine_commerce_product.LANGUAGE AS field_magazine_commerce_product_language,
  taxonomy_term_data.NAME AS taxonomy_term_data_name,
  taxonomy_term_data.vid AS taxonomy_term_data_vid,
  taxonomy_vocabulary.machine_name AS taxonomy_vocabulary_machine_name,
  'taxonomy_term' AS field_data_field_mondi_azzurra_taxonomy_term_entity_type,
  'taxonomy_term' AS field_data_field_avatar_taxonomy_term_entity_type,
  'taxonomy_term' AS field_data_field_logo_slider_taxonomy_term_entity_type,
  'taxonomy_term' AS field_data_field_image_taxonomy_term_entity_type,
  'commerce_product' AS field_data_field_image_commerce_product_entity_type,
  'taxonomy_term' AS field_data_field_call_to_action_taxonomy_term_entity_type
FROM {taxonomy_term_data} taxonomy_term_data
  LEFT JOIN {field_data_field_testata} field_data_field_testata ON taxonomy_term_data.tid = field_data_field_testata.field_testata_tid AND (field_data_field_testata.entity_type = 'commerce_product' AND field_data_field_testata.deleted = '0')
  LEFT JOIN {commerce_product} field_testata_taxonomy_term_data ON ield_data_field_testata.entity_id = field_testata_taxonomy_term_data.product_id
  LEFT JOIN {field_data_field_magazine} field_testata_taxonomy_term_data__field_data_field_magazine ON field_testata_taxonomy_term_data.product_id = field_testata_taxonomy_term_data__field_data_field_magazine.field_magazine_product_id
  LEFT JOIN {node} field_magazine_commerce_product ON field_testata_taxonomy_term_data__field_data_field_magazine.entity_id = field_magazine_commerce_product.nid
  LEFT JOIN {taxonomy_vocabulary} taxonomy_vocabulary ON taxonomy_term_data.vid = taxonomy_vocabulary.vid
WHERE (((taxonomy_vocabulary.machine_name IN ('testate'))))

I have to pick the last node connected to the taxonomy term [connected to another taxonomy term filtered by context] and now for each term and I have all the taxonomy-node coupple.
How can I achieve this?
There is a way to add 'Groupby tid' at the end of the query? Or I have to build the query diffrently?
UPDATE:
If I active 'Use aggregation' I have this query
SELECT DISTINCT field_data_field_avatar. AS field_data_field_avatar_,
field_data_field_logo_slider. AS field_data_field_logo_slider_, field_data_field_image. AS field_data_field_image_, field_magazine_commerce_product.nid AS field_magazine_commerce_product_nid, field_magazine_commerce_product.language AS field_magazine_commerce_product_language, field_data_field_call_to_action.field_call_to_action_value AS field_data_field_call_to_action_field_call_to_action_value, taxonomy_term_data.name AS taxonomy_term_data_name, taxonomy_term_data.vid AS taxonomy_term_data_vid, taxonomy_term_data.tid AS tid_1, taxonomy_vocabulary.machine_name AS taxonomy_vocabulary_machine_name, COUNT(DISTINCT field_data_field_mondi_azzurra.field_mondi_azzurra_tid) AS field_data_field_mondi_azzurra_field_mondi_azzurra_tid, COUNT(DISTINCT field_data_field_mondi_azzurra.delta) AS field_data_field_mondi_azzurra_delta, COUNT(DISTINCT field_data_field_mondi_azzurra.language) AS field_data_field_mondi_azzurra_language, COUNT(DISTINCT field_data_field_mondi_azzurra.bundle) AS field_data_field_mondi_azzurra_bundle, MIN(taxonomy_term_data.tid) AS tid, 'taxonomy_term' AS field_data_field_avatar_taxonomy_term_entity_type, 'taxonomy_term' AS field_data_field_logo_slider_taxonomy_term_entity_type, 'taxonomy_term' AS field_data_field_image_taxonomy_term_entity_type, MIN(field_testata_taxonomy_term_data.product_id) AS field_testata_taxonomy_term_data_product_id, 'commerce_product' AS field_data_field_image_commerce_product_entity_type, MAX(field_testata_taxonomy_term_data__field_data_field_image.bundle) AS field_testata_taxonomy_term_data__field_data_field_image_bun, 'taxonomy_term' AS field_data_field_call_to_action_taxonomy_term_entity_type
FROM
{taxonomy_term_data} taxonomy_term_data
LEFT JOIN {field_data_field_testata} field_data_field_testata ON taxonomy_term_data.tid = field_data_field_testata.field_testata_tid AND (field_data_field_testata.entity_type = 'commerce_product' AND field_data_field_testata.deleted = '0')
LEFT JOIN {commerce_product} field_testata_taxonomy_term_data ON field_data_field_testata.entity_id = field_testata_taxonomy_term_data.product_id
LEFT JOIN {field_data_field_magazine} field_testata_taxonomy_term_data__field_data_field_magazine ON field_testata_taxonomy_term_data.product_id = field_testata_taxonomy_term_data__field_data_field_magazine.field_magazine_product_id
LEFT JOIN {node} field_magazine_commerce_product ON field_testata_taxonomy_term_data__field_data_field_magazine.entity_id = field_magazine_commerce_product.nid
LEFT JOIN {taxonomy_vocabulary} taxonomy_vocabulary ON taxonomy_term_data.vid = taxonomy_vocabulary.vid
LEFT JOIN {field_data_field_mondi_azzurra} field_data_field_mondi_azzurra ON taxonomy_term_data.tid = field_data_field_mondi_azzurra.entity_id AND (field_data_field_mondi_azzurra.entity_type = 'taxonomy_term' AND field_data_field_mondi_azzurra.deleted = '0')
LEFT JOIN {field_data_field_avatar} field_data_field_avatar ON taxonomy_term_data.tid = field_data_field_avatar.entity_id AND (field_data_field_avatar.entity_type = 'taxonomy_term' AND field_data_field_avatar.deleted = '0')
LEFT JOIN {field_data_field_logo_slider} field_data_field_logo_slider ON taxonomy_term_data.tid = field_data_field_logo_slider.entity_id AND (field_data_field_logo_slider.entity_type = 'taxonomy_term' AND field_data_field_logo_slider.deleted = '0')
LEFT JOIN {field_data_field_image} field_data_field_image ON taxonomy_term_data.tid = field_data_field_image.entity_id AND (field_data_field_image.entity_type = 'taxonomy_term' AND field_data_field_image.deleted = '0')
LEFT JOIN {field_data_field_image} field_testata_taxonomy_term_data__field_data_field_image ON field_testata_taxonomy_term_data.product_id = field_testata_taxonomy_term_data__field_data_field_image.entity_id AND (field_testata_taxonomy_term_data__field_data_field_image.entity_type = 'commerce_product' AND field_testata_taxonomy_term_data__field_data_field_image.deleted = '0')
LEFT JOIN {field_data_field_call_to_action} field_data_field_call_to_action ON taxonomy_term_data.tid = field_data_field_call_to_action.entity_id AND (field_data_field_call_to_action.entity_type = 'taxonomy_term' AND field_data_field_call_to_action.deleted = '0')
WHERE (( (taxonomy_vocabulary.machine_name IN  ('testate')) ))
GROUP BY field_data_field_avatar_taxonomy_term_entity_type, field_data_field_logo_slider_taxonomy_term_entity_type, field_data_field_image_taxonomy_term_entity_type, field_data_field_image_commerce_product_entity_type, field_data_field_call_to_action_taxonomy_term_entity_type

and this SQL error
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'AS field_data_field_avatar_, field_data_field_logo_slider. AS field_data_field_l' at line 1

As you can see this query is not correctly written by drupal: there are some dots after the fields name in the frist part of the query..
Do you think I can fix this Views's core error?
Comment: If you suspect the module is buggy, you should file a bug report, which sort of makes the question off-topic. In the mean time though, you could hook_views_alter the query.
Comment: I tryed to build an hook_views_alter() but it do not seem to work. I use add_groupby($clause) but the result just work before the groupby add..
Answer: You need to enable aggregation under Advanced > Use aggregation. You can then select how you want your data grouped using the settings under Fields, Sort criteria and Filter criteria.
Comment: If I try to use aggregation the query return me an SQL error: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'AS field_data_field_avatar_, field_data_field_logo_slider. AS field_data_field_l' at line 1. I tryed that.
Comment: Try turning on the SQL view and debugging it using SQL directly for comparision. You should be able to detect the cause of the error. Possibly a missing field or a grouping in the wrong place. Visit Views settings http://example.com/admin/structure/views/settings and check the `Show the SQL query` checkbox under `Live Preview settings`
Comment: I have SQL debbugging already active but i didn't read the query with the aggregation mode on.. question updated
Comment: I think you need to try getting the query working how you want it in SQL first then try any track down what you have done incorrectly in Views that causes a bad query. I've noticed a couple of times that unless you have specified a Sort criteria the query will always fail. Try sorting on term ID or something. If that stops the query from failing then you can continue to debug.

How to add a groupby to a view query


How to change axios request config?

Question: For each request to the backend, I send an access token. If the token has not passed verification, then I save the config of the original request and make a request to update the tokens. If everything is fine, then I re-send the original request. The problem is that the original request is sent with the old token. Tell me how I can update the value in headers.Authorization?
<code>import axios from 'axios'

import { setAccessToken } from '../store/authSlice'

export const axiosConfig = (accessToken: any, dispatch: any) => {
    const API_URL = 'http://localhost:3001/api'

    const $api = axios.create({
        withCredentials: false,
        baseURL: API_URL
    })

    $api.interceptors.request.use((config) => {
        config.headers!.Authorization = `Bearer ${accessToken}`
        return config
    })

    $api.interceptors.response.use(
        (config) => {
            return config
        },
        async (error) => {
            const originalRequest = error.config

            if (error.response.status === 403 && error.config && !error.config._isRetry) {
                originalRequest._isRetry = true

                try {
                    const response = await axios.get(`${API_URL}/auth/refresh-tokens`, {
                        withCredentials: false,
                        headers: {
                            Authorization: `Bearer ${localStorage.refreshToken}`
                        }
                    })

                    localStorage.setItem('refreshToken', response.data.refreshToken)
                    dispatch(setAccessToken(response.data.accessToken)) // new token

                    return $api.request(originalRequest) // <=== original request with old token
                } catch (e) {
                    console.log('error')
                }
            }
            throw error
        }
    )
    return $api
}
</code>
Answer: You are using $api.interceptors.response.use() which is on the response not the request. You will not be able to change the Authorization header on a request that has already been sent.
I would use some type of error handler or axios response intercepter to direct user to the login page if they are expired/not logged in. Then I would have an error handler function that can try to attempt a re-authorization then have the error handler function resend the original request that would then have the updated Authorization token. But remember you still cant change the request that has already been sent.
<code>    myAxoisInstance.interceptors.request.use(
      function (config) {
        // This is run on each request so if you have or then update
 the token for local storage your next request will get that updated token

           const token = localStorage.getItem("token");
            if (token) {
              //Assign the token to the config
              //If you need to send a request here to see if token is valid I don't recommend that. If you are using a JWT token you can check if it is expired here and do something else like a redirect to login.
              config.headers!.Authorization = `Bearer ${token}`;
            } else {
              //Can retrieve and assign token here I typically like to do a redirect here as they are likely not logged or sesson expired. in or something like that. Then allow the sign-in process to add the token to the local storage.
            }
            return config;
          },
          function (error) {
            return Promise.reject(error);
          }
        );
</code>
Comment: I don't want to change a request that has already been sent. I need to send a new request with the parameters of the old request.

In this case, I get an access token from createAsyncThunk and pass it to $api.interceptors.request. And I don't change it anymore.

I just needed to add an additional variable so that the token in the header was valid.

let currentAccessToken = accessToken
...
config.headers!.Authorization = `Bearer ${currentAccessToken}`
...
currentAccessToken = response.data.accessToken

How to change axios request config?


How to mark calendar days between two dates?

Question: I added two cck for start date and end date. I want to mark the dates on calendar.
If I select the start date and end date in single field by enabling requires to date option it works fine.
But I have a different date field for end date.How to do it?
Comment: Why not just removed the extra field and use the "to date" option instead?
Comment: I did the same now.
Comment: Is there any reason why you could not just use a single date field and use that option? You know there is that possibility, but you don't say why you don't use it.
Comment: @kiamlaluno yes.. because I the event have start date and end date. Between these days the time of event should be same. So that I keep different time field.
Comment: In that case, using a single date field should not be the solution, should it be?
Comment: Date field is single but time field is different.
Comment: In the question you say that you could use a single date field and select an option, which means you know that is a possibility, but you have two date fields. In the answer you say you used a single date field. In other words, you know that _option A_ is possible, but you ask the question; then you answer the question saying that you used _option A_. What is the purpose of the question? Why did you ask the question if you already know the answer?
Answer: I did this with the same date field and enabled the to date option.


Jquery load function getting stuck after first load

Question: Hi I have this sample code to load random quotes.
PHP Code:
<?php
  //Selecting Random quotes from database --randomquotes.php
  require('dbconnection.php');
  // $temp=10;
  $sql = "SELECT * FROM db.q order by rand() LIMIT 1";
  $res = mysql_query($sql,$con);
  while ($res1=mysql_fetch_assoc($res))
  {
    print "".$res1['quote']."";
  }
?>

HTML CODE:

<?php
  require('randomquotes.php');
?>

Jquery Code:

This code is working well for the first time , but is getting stuck on second quote and is not changing the quote.
Also everytime i see the second quote to be the same always.
What is the problem . Please help?
Answer: I believe the output is being cached by jQuery. You can try with caching disabled.
setInterval(function() {
    $j.ajax({
        url: 'randomquotes.php',
        cache: false,
        success: function(data) {
            $j(".class_box_shadow_quote").html(data);
        }
    });
}, 7000);

Answer: Try adding a random seed at the end of your URL to avoid browser caching, like so:
    $(".class_box_shadow_quote").load('randomquotes.php?s=' + (Math.Random() * 1000000))

Comment: Actually `cache: false` does the same. It adds a randomizer to the url.
Comment: Wow this is new to me...but the previous solution was easy to avoid caching .
Comment: Sometimes, manipulating the cache headers don't work. I've run into that problem several times. It's getting better though. :)


Existence and Uniqueness of solutions

Question: I'm pretty confused about this topic in Differential Equations.
It's a simple topic, but I just can't get the gist of it.
Here are two examples that I would like for you to explain to me

$\dfrac{dy}{dx} = y^\frac{1}{3},\quad  y(0) = 1$
$\dfrac{dy}{dx} = y^\frac{1}{3},\quad  y(0) = 0$

for number 1 a unique solution exist near $x = 0$,
but for 2 uniqueness is not guaranteed. Please explain, boggles my mind.
Answer: We know that Picard gives sufficient conditions for the existence of a unique solution:

Theorem: Let $R$ be a rectangular region in the $xy$-plane defined by $$a\leq x\leq b, ~~c\leq y\leq d$$ that contains the point $(x_0,y_0)$ in its interior. If $f(x,y)$ and $\partial f/\partial y$ are continuous on $R$ , then there exists an interval $I$ centered at $x_0$ and a unique function $y(x)$ defined on $I$ satisfying the initial-value problem $$y'=f(x,y),~~y(x_0)=y_0$$

Here you have the OE, $y'=\sqrt[3]{y}$. So $f(x,y)=\sqrt[3]{y}$ and then $\partial f/\partial y=\frac{1}{3y^{2/3}}$. Now, I think you will find the answer by your own and by using the Theorem. Just look at the origin and the point $(0,1)$ in the following graph:
Comment: Nice graph, nice answer! +1
Comment: @amWhy: Thanks amWhy. ;-)
Answer: Observe, for number 2 for example, that applying the Mean Value Theorem we have
$$\frac{| \sqrt[3]{y} - \sqrt[3]{x} |}{|x-y|}= \frac{1}{3\sqrt[3]{c^2}}=f^{\prime}(c), $$
for a certain $c \in (x,y) \subset B(0,\varepsilon)$, $\varepsilon >0$, so as $x \to y$, this tends to $f^{\prime}(0) = \infty$. Hence, there exists some $M>0$, as big as you want, such that
$$| \sqrt[3]{y} - \sqrt[3]{x} | > M |y - x |,$$
for $x$, $y$ in a neighbourhood of zero. Hence, $\sqrt[3]{y}$ is not a Lipschitz function near zero and thus uniqueness cannot be granted. Note that this does not happen in case 1 because if you take values around one instead of zero the derivative is not going to be infinity. This is due to Picard's Theorem. The existance is granted in both cases because of the weaker version, the Peano's Theorem, which states that if the function is continuous around the initial condition, then the solution does exist. However, you need Lipschitz-ness for the uniqueness.

Existence and Uniqueness of solutions


Getting names/values of multiple properties

Question: Lets say I have one method, which extracts property name and value:
public TModel Get (Expression<Func<object>> param)
{
        using (OracleConnection connection = new OracleConnection(GetConnectionString()))
        {
            connection.Open();

            var propertyName= ((MemberExpression)param.Body).Member.Name;

            var value = param.Compile()();

            // GetTableName() returns table name of TModel
            var query = $"SELECT * FROM {GetTableName()} WHERE {propertyName}='{value}'";

            var output = connection.Query<TModel>(query);
            connection.Dispose();
            return output.FirstOrDefault();

        }
}

and using it as:
var model = Get(() => foo.FirstProperty);

However, if I want to get name and value from the unknown number of properties, I do this:
public TModel Get(params Expression<Func<object>>[] param)
        using (OracleConnection connection = new OracleConnection(GetConnectionString()))
        {
            connection.Open();

            var query = new StringBuilder();

            query.Append($"SELECT * FROM {GetTableName()} WHERE ");
            for (int i = 0; i < param.Length; i++)
            {
                var propertyName = ((MemberExpression)param[i].Body).Member.Name;

                var value = param[i].Compile()();

                query.Append($"{propertyName} = '{value}'");
                if (i + 1 < param.Length) query.Append(" AND ");
            }

            var output = connection.Query<TModel>(query.ToString());
            connection.Dispose();
            return output.FirstOrDefault();
        }
    }

But, implementation looks a bit 'ugly' and verbose:
var model = Get(() => foo.FirstProperty, () => foo.SecondProperty); // and so on

I could send manualy name of the property + value, however, I would like to keep the implementation as simple as possible and less verbose.
Is there any way to simplify this?
Comment: If this is code you've written, and it works, and you'd like a review of all aspects of your code, this *might* be better off on [codereview.se], but I'd check their help center first before asking.
Comment: Are you doing it this way for speed reasons?  Reflection already has this functionality.
Comment: @RobertHarvey I do this because I'm using Oracle database and Dapper. However, Dapper.contrib is not very friendly with oracle and I do not want to write every single query manually. Therefore I came up with an idea to have one method which will build that query based on given properties. My code snippet works, however, as I mentioned, It looks a bit 'verbose', especially for 3+ parameters which will force to write ' () => ' every time I pass a property
Comment: I think we'd have to see more of your code to come up with a solution.
Comment: @RobertHarvey I've edited my post.
Comment: Is this a different API than Dapper.Contrib?  Because Dapper.Contrib is just `connection.Get(id)`.  Can the consumer still use the original API?
Comment: It is Dapper.Contrib. If I use connection.Get(dynamic id), I'm getting ''ORA-00936: missing expression'. Similar with others Contrib methods. I believe, that underlying sql query is slightly different in oracle. I.e. if I want to get/insert DateTime from/in database, it throws bunch of exceptions. And this is a reason why I manually build a query and passing it.
Answer: we can shorten the expressions by making Get generic, giving Get the foo instance, and changing the expressions to T, object so that they can accept foo.
using System;
using System.Linq.Expressions;

namespace SO60378405
{
    static class Program
    {
        static void Main(string[] args)
        {
            var foo = new SomeContainer("hello", 123);
            Get(foo, s => s.SomeString, s => s.SomeInt);
        }
        static void Get<T>(T foo, params Expression<Func<T, object>>[] expressions)
        {
            foreach (var expression in expressions)
            {
                var memberExpression = GetMemberExpression(expression);
                var propertyName = memberExpression.Member.Name;
                var propertyGetter = expression.Compile();
                var propertyValue = propertyGetter(foo);
                Console.WriteLine($"{propertyName} = '{propertyValue}'");
            }
        }
        static MemberExpression GetMemberExpression<T>(Expression<Func<T, object>> expression)
        {
            switch (expression.Body)
            {
                case MemberExpression memberExpression:
                    return memberExpression; //string
                case UnaryExpression unaryExpression when unaryExpression.Operand is MemberExpression operandMemberExpression:
                    return operandMemberExpression; //int, decimal
                default:
                    throw new InvalidOperationException();
            }
        }
    }
    public class SomeContainer
    {
        public string SomeString { get; set; }
        public int SomeInt { get; set; }
        public SomeContainer(string someString, int someInt)
        {
            SomeString = someString;
            SomeInt = someInt;
        }
    }
}


compress and write a file in another container with azure blob storage trigger in nodejs

Question: i have to make an api call passing a compressed file as input. i have a working example on premise but I would like to move the solution in cloud. i was thinking to use azure blob storage and the azure function trigger. i have the below code that works for file but I don't know how to do the same with azure blob storage and azure function in nodejs
const zlib = require('zlib');
const fs = require('fs');

const def = zlib.createDeflate();

input = fs.createReadStream('claudio.json')
output = fs.createWriteStream('claudio-def.json')

input.pipe(def).pipe(output)

this code read a file as stream , compress the file and write another file as stream.
what I would like to do is reading the file any time I upload it in a container of azure blob storage, then I want to compress it and save in a different container with different name, then make an API call passing as input the compressed file saved in the other container
I tried this code for compressing the incoming file
const fs = require("fs");
const zlib = require('zlib');
const {Readable, Writable} = require('stream');
module.exports = async function (context, myBlob) {
    context.log("JavaScript blob trigger function processed blob \n Blob:", context.bindingData.blobTrigger, "\n Blob Size:", myBlob.length, "Bytes");
   // const fin = fs.createReadStream(context.bindingData.blobTrigger);
   const def = zlib.createDeflate();
   const s = Readable.from(myBlob.toString())
  context.log(myBlob);
  context.bindings.outputBlob = s.pipe(def)
};

the problem with this approach is that in the last line of the code
  context.bindings.outputBlob = s.pipe(def)

i don't have the compressed file, while if i use this
s.pipe(def).pipe(process.stdout)

i can read the compressed file
as you can see above i also tried to use the fs.createReadStream(context.bindingData.blobTrigger) that contains the name of the uploaded file with the container name, but it doesn't work
any idea?
thank you
Answer: this is the solution
var input = context.bindings.myBlob;

var inputBuffer = Buffer.from(input);
var deflatedOutput = zlib.deflateSync(inputBuffer);

context.bindings.myOutputBlob = deflatedOutput;

https://learn.microsoft.com/en-us/answers/questions/500368/compress-and-write-a-file-in-another-container-wit.html


Exponential map on $SO(3)$

Question: (1) As I read some article in here ( I cannot found ), so we know that $$ {\rm exp} \ (T_eSO(3)) \neq SO(3) $$
( ${\rm diag}(-1,-1,1)$ cannot be covered by ${\rm exp}$ )
But there exists some open ball $B$ in $T_eSO(3)$ so that ${\rm exp}\ B$ is open.
Then can we choose $\{ g_1, ... , g_n \}\subset SO(3)$ such that $\{ g_i B\}$ is open cover ? If so, can we find smallest $n$ ?
(2) My second question is : What is ${\rm exp}\ (T_eSO(3))$ ?
$$\{  {\rm exp}\ tE_{12} | t\in {\bf R} \}=SO(2)$$ where $E_{12}$ is a matrix having only nonzero $(1,2),\ (2,1)$-entries which are $1$ and $-1$. That is $\{  {\rm exp}\ tE_{12} | t\in {\bf R} \}$ is a closed geosic in $SO(3)$. But what is ${\rm exp}\ (T_eSO(3))$ ?
Answer: Rethink your assumptions - $\rm diag(-1,-1,1)$ is the exponential of $$\left(\begin{matrix} 0& \pi& 0\\ -\pi& 0& 0\\ 0& 0& 0\end{matrix}\right).$$ In fact the exponential map is surjective - this is true for any compact connected Lie group.

Exponential map on $SO(3)$


Why some features are overriden after installation

Question: This is my hook_install:
function moocollar_web_install() {

  // enable features
  $global_features = array ('display_modes_feature' , 'field_bases_feature' , 'image_styles_feature' , 'roles_permissions_feature' , 'sitewide_feature'  , 'wysiwyg_feature' , 'menus_feature');
  $functionality_features = array ('blog_feature');

  $enable_dependencies = TRUE;
  module_enable($global_features, $enable_dependencies);
  module_enable($functionality_features, $enable_dependencies);

  // create editor user
  $role = user_role_load_by_name ('editor');
  $new_user = new stdClass();
  $new_user->name = 'editor';
  $new_user->pass = user_password(8); // random password.
  $new_user->mail = 'firstname.lastname@example.com';
  if ($role) {
    $new_user->roles = array ($role->rid => $role->name);
  }
  $new_user->status = 1;
  $new_user->is_new = TRUE;
  user_save($new_user);

  variable_set('features_default_export_path', 'profiles/moocollar_web/modules/features');
}

After install the blog_feature is overriden:
drush features-diff blog_feature
Legend:
Code:       drush features-revert will remove the overrides.
Overrides:  drush features-update will update the exported feature with the displayed overrides

Component type: info
  features[field_instance][] = node-blog_post-body
  features[field_instance][] = node-blog_post-field_image
< features[menu_links][] = menu-editor-menu_aadir-post:node/add/blog-post
  features[node][] = blog_post
  features[user_permission][] = create blog_post content

Component type: menu_links
< array(
<   'menu-editor-menu_aadir-post:node/add/blog-post' => array(
<     'customized' => 1,
<     'link_path' => 'node/add/blog-post',
<     'link_title' => 'Añadir post',
<     'menu_name' => 'menu-editor-menu',
<     'module' => 'menu',
<     'options' => array(
<       'identifier' => 'menu-editor-menu_aadir-post:node/add/blog-post',
<     ),
<     'router_path' => 'node/add/blog-post',
<   ),
< )
---
> array()

But if I execute revert features via drush, the features is on default state:
drush features-revert blog_feature
Do you really want to revert blog_feature.menu_links? (y/n): y
Reverted blog_feature.menu_links.                                                                       [ok]
vagrant@precise32 (linkinicio *) httpdocs$ drush fd blog_feature
Feature is in its default state. No diff needed.

On the blog_feature.info I've the dependency and the item:
...
dependencies[] = menu
dependencies[] = menus_feature
....
features[menu_links][] = menu-editor-menu_aadir-post:node/add/blog-post
....

Thanks you all for your time.
Answer: Normally Features automatically detects ctools exportables and add the modules containing those exportables to the dependency list, unless a module requirement for an exportable was not detected, or dependent modules were installed since feature was enabled.
Based on your menu link machine name (menu-editor-...), it seems it relies on Menu Editor module and you've missing dependency to that module, therefore Features module didn't detect that component as a requirement, so it become overridden and unrevertable.
The solution is to add the missing module into dependencies list. Then either disable the feature module and reenable it, or manually enable any dependencies not enabled (see Feature Diff to expose them).
See: Troubleshooting: Reasons Features may be stuck as Overridden at Drupal.org


vsftp work in terminal but not on filezilla and browser

Question: I work under in a docker image, under a VPS!
i have install vsftp in my ubuntu 20.04! at the beginning I tested ftp 127.0.0.1 in the command line and everything goes well I created a user and I tested the file transfer.
after adding the ssl certificate and I wanted to connect by filezilla or by browser it does not work and the server does not have the ip address 127.0.0.1!
how can I fix this please!
here is the output of filezilla :
Response: 220 (vsFTPd 3.0.3)
Command: AUTH TLS
Answer: 530 Please login with USER and PASS.
Command: AUTH SSL
Answer: 530 Please login with USER and PASS.
Status: Unsecured server, it does not support FTP over TLS.
Command: USER rayen
Answer: 530 Permission denied.
there is nothings in the file log => it's empty  /var/log/vsftpd.log
/etc/vsftpd.conf : listen=NO
listen_ipv6=YES
anonymous_enable=NO
local_enable=YES
write_enable=YES
dirmessage_enable=YES
use_localtime=YES
xferlog_enable=YES
connect_from_port_20=YES
chroot_local_user=YES
secure_chroot_dir=/var/run/vsftpd/empty
pam_service_name=vsftpd
rsa_cert_file=/etc/ssl/private/vsftpd.pem
rsa_private_key_file=/etc/ssl/private/vsftpd.pem
ssl_enable=YES
user_sub_token=$USER
local_root=/home/$USER/ftp
pasv_min_port=30000
pasv_max_port=31000
userlist_enable=YES
userlist_file=/etc/vsftpd.user_list
userlist_deny=NO
i followed this tuto :
https://www.howtoforge.com/tutorial/ubuntu-vsftpd/
Comment: Show us a log from the terminal.  + Did you check the server-side log?
Comment: this is vsftp.log
Comment: Fri Apr  9 05:37:48 2021 [pid 1647] CONNECT: Client "::ffff:188.8.131.52"
Fri Apr  9 05:45:37 2021 [pid 1649] CONNECT: Client "::ffff:188.8.131.52"
Comment: Please do not post any information in comments. Edit everything into your question. + Try increase vsftpd logging level. + Post console log.
Comment: aaa ok sorry it's the first time that i posted here !
Answer:
Status: Unsecured server, it does not support FTP over TLS.

You need to issue a certificate (I suggest using Let's Encrypt for this)
After issuing a certificate, set these variables on /etc/vsftpd.conf file
<code>listen=NO
listen_ipv6=NO
anonymous_enable=NO
local_enable=YES
write_enable=YES
local_umask=022
dirmessage_enable=YES
use_localtime=YES
xferlog_enable=YES
connect_from_port_20=YES
chroot_local_user=YES
pam_service_name=vsftpd
rsa_cert_file=/etc/ssl/certs/server.pem
rsa_private_key_file=/etc/ssl/private/server.key
ssl_enable=YES
</code>
To connect using Filezilla, remember to select the option Use explicit FTP over TLS if available.
Comment: listen=NO
listen_ipv6=NO
anonymous_enable=NO
local_enable=YES
write_enable=YES
local_umask=022
dirmessage_enable=YES
use_localtime=YES
xferlog_enable=YES
connect_from_port_20=YES
chroot_local_user=YES
pam_service_name=vsftpd user_sub_token=$USER
local_root=/home/$USER/ftp
pasv_min_port=35000
pasv_max_port=40000
userlist_enable=YES
userlist_file=/etc/vsftpd.userlist
userlist_deny=NO
rsa_cert_file=/etc/ssl/private/vsftpd.pem
rsa_private_key_file=/etc/ssl/private/vsftpd.pem
ssl_enable=YES  !!!! and always the  same problem !! i think that firezilla don't  see my server !!!!
Comment: @RayenBenSaid The error message says your "server doesn't support FTP over TLS", so you're supposed to not be using a valid certificate
Comment: I have this setup working fine and connection via FileZilla with FTP over TLS
Comment: it's normal that ftp:\\x.x.x.x don't work ??? i enter my user name and passwrd and nothings happen – Rayen Ben Said


Will the silhouette not approach 1 when increasing k to n?

Question: My understanding of silhouette in the context of k-means clustering is that its equal to:
$$\frac{\mbox{Av. distance to subjects in hearest neighboring cluster} - \mbox{Av. distance to subjects in my cluster}}{\mbox{max. of the two above}}$$
So, assume really good clustering, Av. distance to subjects in neighbouring cluster is really big and average distance to subjects in my cluster is really small (numerator becomes approx. the first term), divide by the max, so the silhouette becomes 1 --> Good clustering.
But if I have as many clusters as I have items, then will not the average distance to subjects in neighbouring cluster always be greater than the distance to the current cluster (since the item is sitting on it)? Then I should always get silhouette = 1, no?
Comment: By convention, the silhouette index for any singleton object is set to 0. Alternatively, you may set it to missing (no value). We can never say how well a singleton is clusrtered because there are no other points in its cluster, to compare the distance to them with that to the neighbouring cluster.
Comment: @ttnphns intuitively that convention doesn't make much sense to me. The distance to every point in a singleton cluster seems like it should be zero, because the distance between any point and itself is zero.
Comment: @ssdecontrol, In clustering indices such as silhouette, comparing within and between cluster densities, the distances and their averages serve as indicators of density. Singleton object is formally a cluster, yet it has _undefined_ (and not zero or 1) density within. It is difficult to say if a singleton object alone is clustered "well" or "bad". Therefore Silhouette index is set to 0 (neither any good nor completely bad), or is set to missing. It makes clear sense.
Answer: A problem with silhouette is that it is not well defined for 1 element clusters. Because the average distance to other cluster members then is an average over 0 values and thus undefined.
In the original Silhouette work, IIRC the author suggested to use 0 for such "clusters".
So by (complete) definition, a data set (with no duplicates) where every object is its own cluster will have a Silhouette of 0.
Because of this anomaly, Silhouettes can be a bit unreliable sometimes. They really punish outliers and noise, so in the presence of such data, avoid Silhouette.
There is another unresolved corner case in Silhouette: Assuming we have points 0, 0, 0, and 0 and cluster them as 0,0 and 0,0. Then the average distance within is 0, the average distance across is 0, and we compute 0/0.
Comment: +1, Btw thanks to pointing to the last problem (4 identical point belonging to 2 clusters). Would you suggest to assign silhouette value 0 in such a case?
Comment: I think so, but I don't have a 'proof' or anything. I would argue that if the distance to the own cluster is the same as to the other cluster, then the value should be 0. For practical purposes, the simplified Silhouette may often be the better choice (also because of performance). Which uses the distance to the centroid rather than the average distance. But it suffers from the same problem.


How to get specified columns with result as array of table class objects?

Question: I have simple problem. In my table have columns ID, NAME, CONTENT, TIMESTAMP. If i use session.query(table).all() result is array of table class objects. So i have no problem with modify one or more objects and update, or use this objects in associations. But i need only columns ID and NAME. If use session.query(table.id, table.name) i get as result tuple with id and name. Using this tuple in update it's - maybe - easy, but code it's.. ugly. As same in associations. And there's is unnecessary database load if i want only ID to make association.
Until now i use simple code to get array of table class objects querying only specified columns:
for row in session.query(table.id, table.name).all():
    data.append(table(id=row.id, name=row.name))
It's make updates easy, but using in associations is complex. For example, i get 10 rows in array of table objects from my code. I want association 1 row to table2.
If i use:
session.add(table2(name = 'test', association = data[1])) and commit,
sqlalchemy want to create new table2 row, new association table row and new table row (this first, associated to table2).
It's there any way to get result as array of table objects, not tuples, with specified columns, wheres returning objects is same if make query(table)?
Sorry for my English anyway, i never used it to describe complex problem, until now.
Answer: If you want to reduce the number of columns loaded from db with .query(Table), thus reducing the overhead, you might want to try defering the unneeded columns when defining the relationship. Say id and name are essential for your updates and info is not, you can tell the mapper to defer info:
mapper(Class, table, properties={
  "info":column_property(table.c.info, deferred=True),
  ... other properties ....
})

So, when you do session.query(Class), info won't get picked on select. It will be called only if somewhere in the code you have obj.info, that is, when you explicitly call for this attribute.


the sides of my activity change

Question: Every time I work with the emulator the app is fine, but when I send it to its sides it always turns upside down and everything on the right goes to the left and everything on the left goes to the right. can you please try to help me figure out what do I need to do in order to make this stop, so the app in my phone will be like the emulator?
example:
the activity in my phone
Example:
the activity in the emulator
here is the xml code
<code><LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>

<LinearLayout
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="settings"
        android:textColor="#0000FF"
        android:textSize="50dp"
        android:textAlignment="center"
        android:textStyle="italic"
        />
</LinearLayout>
<LinearLayout
    android:orientation="horizontal"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="choose your level"
        android:textColor="#3300FF"
        android:textSize="30dp"
        android:textStyle="bold"
        android:layout_weight="1"
        />

</LinearLayout>

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"

        >

        <RadioButton
            android:id="@+id/begginer"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="begginer"
            android:textSize="30dp"

            />

        <RadioButton
            android:id="@+id/pro"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="professional"
            android:textSize="30dp" />

        <RadioButton
            android:id="@+id/WorldClass"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="WorldClass"
            android:textSize="30dp" />

        <RadioButton
            android:id="@+id/Legendery"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Legendery"
            android:textSize="30dp" />
    </RadioGroup>

</LinearLayout>
<LinearLayout
    android:orientation="vertical"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="enter your name"
        android:textColor="#3300FF"
        android:textSize="27dp"
        android:textStyle="bold"
        android:layout_weight="1"
        />
<EditText
    android:textSize="30dp"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:id="@+id/nameid"
    android:textColor="#FFFFFF"
    />
</LinearLayout>

<LinearLayout
    android:orientation="vertical"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
    <ImageView
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:scaleType="centerCrop"
        android:src="@drawable/tetrisstartgamebutton"
        android:onClick="start"
        />
</LinearLayout>
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="0dip"
    android:layout_weight="1"
    android:gravity="right|bottom"
    android:orientation="vertical" >

    <ImageView
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:onClick="menu"
        android:layout_marginBottom="20dp"
        android:layout_marginRight="40dp"
        android:scaleType="centerCrop"
        android:src="@drawable/aaaaaa"
        android:id="@+id/BackToTheMenu"/>
</LinearLayout>
</code>
Answer: One reason could be because Force RTL layout direction is enabled
So check in device if you have it as enabled (Settings > Developer Options > Force RTL layout direction) and disable it.

The cause could be related to RTL o something like that, greetings

the sides of my activity change


Calulate norms of orthogonals vectors

Question: I need to calculate
$(||2u+3v||^2 - ||2u-3v||^2)$
knowing that u and v are orthogonal.
I don't understand how i can calculate without any information on those vectors and why the fact that these vectors are orthogonal help to that.
Answer: Hint
For any vectors $x,y$, you have
$$\Vert x \Vert^2 - \Vert y\Vert^2 =\langle x-y , x+y \rangle$$
Comment: The inner product is bilinear...
Comment: Also use the fact that the $u$ and $v$ vectors are perpendicular. That would simplify the scalar product
Comment: so x and y are vectors ? and the result is the scalar product of x-y and x+y ?
Comment: Just plug in $x=2u+3v$
Comment: And $y=2u-3v$ to get the conclusion
Comment: @WitzigAdrien Yes. This is an identity satisfied by the inner product.
Comment: but how can i do the dot product of vectors i don't know anything ?
Comment: Have you tried to do the plug in that we suggested?
Comment: yes but i came to <6v.4u> how can i get further ?
Comment: i think i understand, so (||2u+3v||^2 − ||2u−3v||^2)  = 0 ?
Comment: That is right!!

Calulate norms of orthogonals vectors


How should a Backbone model or collection handle views?

Question: I have a collection of models, each of which is attached a view. The collection also globally has a view. Is it best for the model views to take care of deleting the corresponding model, or should the collection (or collection view) do that?
Answer: Collections have a .add and .remove method, when you use one of them, they fire an add or remove event on the collection. This is how you can bind without using a view at all.
var ships = new Backbone.Collection();
ships.bind('add', function(ship) {
  alert('Ahoy ' + ship.get('name') + '!');
});
ships.add([
  {name: 'Flying Dutchman'},
  {name: 'Black Pearl'}
]);

So attach the collection to the view, inside of the constructor. This simply makes the collection available via this.collection
var ShipView = Backbone.View.extend({
  collection: ships
});

This is how you can bind using the view.
// Create collection instance.
var ships = new Backbone.Collection();

// Create view class.
var ShipView = Backbone.View.extend({
  collection: ships,
  initialize: function() {
    // This is binding add, to the view function.
    this.collection.bind('add', this.add);
  },
  add: function(ship) {
    alert('Added ' + ship.get('name') + '!');
  }
  /*Optional for DOM.
  events: {
    'click .addMyShip': 'addShip'
  },
  addShip: function(eventObject) {
    this.collection.add([models]);
  }*/
});

// Create view instance.
var shipView = new ShipView();

// Add two ships.
ships.add([
  {name: 'Flying Dutchman'},
  {name: 'Black Pearl'}
]);

When the view initializes, it binds the collection's add event to run this.add which is a function of the view. Optionally, you can use the delegateEvents API to handle mapping DOM elements event selector to function that runs the function in the view. That function can call this.collection.add, of which will create the domino effect.
The way the view interacts with the collection, or model, is by binding to events, you can define those events and handle them inside the view. There are several special options that, if passed, will be available to the view: model, collection, el, id, className, and tagName.
Comment: so to go further on that, clicking the remove button, you could raise a remove event, picked up by the collection, the collection removes the given model (ship in this example), which triggers the remove event, the view can listen to that, and unbind it's events and remove the view from the dom.  am i missing anything?


i want to return false when instantiating an object

Question: well, this is not an easy question, but in the fiddle you will see a simplified version of  what it is i am trying to do:
I want to instantiate an object, do all the operation i need to initialize it, but i want the statement:
var obj = new class;

to return 'false' to obj given some conditions.
here's the code anyhow:
var cl = function(id){
   this.init(id);
   if(this.id > 5){
       return false;
   }
};

cl.prototype = {
    init: function(id){
        this.id = id;

    }
}

var arr = [];

for(i = 0; i < 10; i++){
    var obj = new cl(i);
    if(obj){
         arr.push(obj);
    }
}

console.log(arr);

I know the end result can be achieved by creating a control property to the object, but i am curious to if there is any pattern to do this cleaner.
Comment: you can't return anything but the object created when `new` is used. so I would do `throw new Error("Invalid id")` and abort the operation.
Comment: you can also return an other object (null is a value, although typeof null is object), everything else returned is ignored.
Answer: maybe not exactly what you've asked, but a solution could be to use the factory pattern. Ofcourse you'd have to call the factory method instead of the constructor. checkout this fidlle
Comment: btw; this is not the use the factory pattern is intended for... but it does work, and does create either an object or a boolean for you. And if it works, what the hell ;)
Comment: thanks, it is also not what i was looking for, but cudos for presenting me with a valid alternative


execute python script with argparse inside python script

Question: I got two different python script, the first one is using argparse to get some additional argument (I will call it arg.py) and the second one is my main script (main.py).
I want to call arg.py inside main.py but I don't know how to do so. I take a look at the command execfile but I didn't manage to make it work.
I try to put
execfile('arg.py -h')
In main.py but python try to find the file 'arg.py -h' which doesn't exist. Does anyone know how to do that ?
Thanks in advance
Comment: What happens when you enter the complete path to `arg.py` as argument in `execfile`?
Answer: You can run it as a separate process using subprocess.call or subprocess.Popen.  If you don't want to run it as a child process, then it starts to get more complicated (depending on the structure of your arg.py script.
execfile takes the file you pass to it and includes it in the current script -- Much like a #include pre-processor directive in c/c++ (although this is done dynamically).  One really ugly option using execfile would be:
#completely untested.
import sys
def run_script(script_name,*args):
    _argv = sys.argv[:]
    sys.argv = list(args)
    execfile(script_name)
    sys.argv = _argv


Selenium JavascriptExecutor document.evaluate 'XPathResult': The result type is not a number

Question: I'm tring to take first node of an div from html using JavascriptExecutor document.evaluate
String txt = ((JavascriptExecutor)driver)
           .executeScript("return document.evaluate(\"//div[@id = 'SIvCob']/node()[1]\",
                           document, null, XPathResult.ANY_TYPE, null)").toString();

System.out.print(txt);

But I get an error at executeScript
org.openqa.selenium.JavascriptException:
    javascript error:
        Failed to read the 'numberValue' property from 'XPathResult':
            The result type is not a number.

The node I want is a simple text(without html tags or other things)
I'm using ChromeDriver.
Comment: @C.Peck Are you sure? It looks like if the backslashes were removed, then the Java would not even compile.

KunLun, are you saying that you want the Text value of the found element? If so, why not just do "return document.getElementByXPath(\"my xpath expression\").Text; ?
Comment: Well for one thing you don't need the backslashes to escape the quotes surrounding the xpath. Not sure if that will fix it fully but that is definitely an invalid xpath.
Comment: Yes, you are right, I missed that it was inside the jsexecutor's quotes.
Comment: Can you upload the HTML of the page you are looking at or provide the URL?  That is the easiest/maybe the only way I think you will get a good answer.
Comment: @C.Peck I figured it. I added `stringValue` at `return document.evaluate(...).stringValue` P.S: `document.getElementByXPath` don't exists in javascript.
Comment: Can you please provide the solution in an answer if you've solved it?
Answer: The solution for my problem was to call stringValue at the result of document.evaluate(...).
Like this: document.evaluate(...).stringValue


SQL Text Searching, AND Ordering

Question: I have a query:
SELECT *
FROM Items
WHERE column LIKE '%foo%'
   OR column LIKE '%bar%'

How do I order the results?
Let's say I have rows that match 'foo' and rows that match 'bar' but I also have a row with 'foobar'.
How do I order the returned rows so that the first results are the ones that matched more LIKEs?
Answer: Case or the kind of conditional construct your RDBMS supports is a way to do it
select *, case when col like '%foo%' and col like '%bar%' then 2 end
else 1 end as ordcol
from items
where col like '%foo%' or col like '%bar%' order by ordcol

Comment: Obviously, you don't need the 2nd when in that CASE statement (since the WHERE clause already takes care of it for you). So "case when col like '%foo%' and col like '%bar%' then 2 else 1 end" will do.
Comment: Also, this query won't return rows that contain only 'foo' or rows that contain only 'bar' so, based on the result set, the CASE doesn't do anything useful. Just "select * from Items where column LIKE '%foo%' AND column LIKE '%bar%'" would return the same results.
Comment: @Matt like '%foo%' does match 'foo', and the case does do something useful, which is to return the desired ordering
Comment: The where clause should be "where col like %foo% OR col like %bar".
Comment: @Vinko - the CASE isn't useful.  Since your WHERE clause is "like '%foo%' AND col like '%bar%'" which is exactly the same as your CASE WHEN condition, every row will have a value of 2 for the ordcol column, which won't sort anything.  Like Mark said, it should be OR.
Comment: @Matt yes, the original question had an or, which is what I meant of course.
Comment: @Vinko, sorry to be so pedantic.  I figured it was just a mistake, but I couldn't edit/correct it so I felt compelled to comment.  Maybe I should lighten up... ;)
Answer: SELECT * FROM Items WHERE column LIKE '%foo%' OR column LIKE '%bar%'
ORDER BY
(IF(column LIKE '%foo%',1,0) + IF(column LIKE '%bar%',1,0))
DESC

The syntax for if is
IF ( condition, true_value, false_value )
Answer: SELECT * FROM Items
WHERE col LIKE '%foo%'
    OR col LIKE '%bar%'
ORDER BY CASE WHEN col LIKE '%foo%' THEN 1
                WHEN col LIKE '%bar%' THEN 2
            END

Answer: You could use a UNION:
SELECT * FROM Items WHERE column LIKE '%foo%' AND column LIKE '%bar%'
UNION
SELECT * FROM Items WHERE column LIKE '%foo%' AND NOT (column LIKE '%bar%')
UNION
SELECT * FROM Items WHERE column LIKE '%bar%' AND NOT (column LIKE '%foo%');

But this may be bad performance-wise. Worse, I'm guessing that you want to use this to construct a search engine that gives the most meaningful results first, and then the number of words does not remain limited to 2.
In that case, you could create a score column which contains the number of matches. Something like this:
SELECT
    *,
    (IF(column LIKE '%bar%', 1, 0) + IF(column LIKE '%foo%', 1, 0)) AS score
FROM Items
WHERE column LIKE '%foo%' OR column LIKE '%bar%'
ORDER BY score DESC;

My SQL is a bit rusty, but something like this should be possible in at least MySQL 5.0. See also the manual for the IF function:
http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html
Answer: Which DBMS?
It can be done via CTE or Union for example, but if you are using, for example, MySQL, then you can forget about it.
Answer: Try this code:
SELECT * FROM Items WHERE column LIKE '%foo%' OR column LIKE '%bar%'
order by (select count(*) from items i where i.column= item.column) DESC

You could also group by column and count(*) then ORDER, if you don't care about the details.
Comment: I can't figure out how using count(*) provides a meaningful sort order.  What if "column" doesn't contain unique values?  Or, conversely, say that it does; wouldn't the value of count(*) always be 1, then?
Answer: You might want to give this a go:
SELECT *
FROM Items
WHERE column LIKE '%foo%' OR column LIKE '%bar%'
ORDER BY CASE WHEN column LIKE '%foo%' AND column LIKE '%bar%' THEN 1 ELSE 0 END DESC

Note: this is drycoded and probably not very portable.
Answer: 2 Queries:
SELECT * FROM Items WHERE column LIKE '%foo%' AND column LIKE '%bar%';
SELECT * FROM Items WHERE (column LIKE '%foo%' AND column NOT LIKE '%bar%') OR (column NOT LIKE '%foo%' AND LIKE '%bar%')
(No XOR in SQL)
Answer: Not all RDBMS support IF (or DECODE in Oracle) statements. If not you could use a subquery to define table "a" and search for all employee's named JO SMITH or a combination.
SELECT
 a.employee_id,
 a.surname,
 sum(a.counter)
FROM

 (SELECT
   employee_id,
   surname,
   1 as counter
  FROM
   MyTable
  WHERE
   surname like '%SMITH%'

  UNION ALL

  SELECT
   employee_id,
   surname,
   1 as counter
  FROM
   MyTable
  WHERE
   surname like '%JO%'
   ) a

GROUP BY
 a.employee_id,
 a.surname
ORDER BY 3,1,2

Make sure you use UNION ALL otherwise it will not work. Also you may way to use UPPER() to make your search non-case sensitive.
Answer: As your query is currently written, the WHERE clause will not give you any information that can be used to sort your results.  I like Brian's idea; add a constant column and UNION the queries and you could even get everything in one result set.  For example:
SELECT 1 as rank, * FROM Items WHERE column LIKE '%foo%' AND column LIKE '%bar%'
UNION
SELECT 2 as rank, * FROM Items WHERE column LIKE '%foo%' AND column NOT LIKE '%bar%'
UNION
SELECT 2 as rank, * FROM Items WHERE column LIKE '%bar%' AND column NOT LIKE '%foo%'
ORDER BY rank

However, this would only give you something like this:

The unordered set of all rows that match foo and match bar
followed by (the unordered set of) all rows that match foo or bar, but not both (although you could break this up into two separate groups using a different constant in the last SELECT statement).

Which might be just what you're looking for, but it wouldn't tell you which rows matched foo three times, or sort them ahead of rows that only contained one instance of foo.  Also all those LIKEs can get expensive.  If what you're really looking to do is sort results based on relevance (however you define that) you might be better off using a full text index.  If you're using MS SQL Server, it has a built-in service that will do this, and there are also third-party products that will do the same.
EDIT: After looking at all the other answers (there were only two when I started mine - I'm obviously going to have to learn to think faster ;-) ) it's obvious that there are several ways to go about this, depending on exactly what you're trying to accomplish.  I would advise you to test and compare solutions based on how they perform on your system.  I'm not a performance/tuning expert, but functions tend to slow things down, especially if you're sorting on the result of a function.  The LIKE operator isn't necessarily spry, either.  As a developer, it seems natural to use familiar constructs like "IF" and "CASE", but queries that use more of a set-based approach usually have better performance in a RDMS.  Again, YMMV, so it's best to test if you're at all concerned about performance.

SQL Text Searching, AND Ordering


Questions on setting up proper mappings when applying first isomorphism theorem for rings

Question: The first isomorphism theorem is usually stated in the following form:

Let $f:R\rightarrow S$ be a surjective homomorphism of rings with kernel $K$.  Then the quotient ring $R/K$ is isomorphic to $S$, and $K = kernel f$.

In the proof of the theorem, there usually appears a function such as $\phi(a + K)=f(a)$.  I am trying to apply the first isomorphism theorem to solve the following problem by imitating the strategy from its proofs.  I have to show that $Z_{20}/(5)\cong Z_{5}$.  So I let $f:Z_{20}\rightarrow Z_{5}$ be defined by $f(a+Z_{20})=a+Z_{5}$ and since $Im(f)=a+Z_{5}$ and $kernel f =\{[0]_5, [5]_5, [10]_5, [15]_5\}$.  At this point, do I just define the function $\phi(a+ ker f)=Im(f)=a+ Z_{5}$. Is this the proper way going about the solution?  The reason I am asking is because in many (not all) instances where i see the application of first isomorphism theorem is use.  I see an explicit function $f$ being written out mapping from $R$ to $S$ or to $Im(f)$ being set up, then the kernel is found of $f$ is described and then by the isomorphism theorem, it is solved.  The solutions usually skips the step of writing out explicitly the the function $\phi(R/K) = Im(f)$   Also, I am just wondering why that is. Thank you in advance
Comment: Your notation is not good: "$a+Z_{20}$ doesn't make sense: $Z_{20}$ is the whole ring you are working in! What are your definitions of $Z_n$? Is it $\mathbb{Z}/n\mathbb{Z}$? In that case, you wnt $a+20\mathbb{Z}$ and $a+5\mathbb{Z}$.
Comment: Note: the "right" way to use the First Isomorphism Theorem to show that $R/I$ is isomorphic to $S$ is *not* to try to define the map from $R/I$ to $S$ following the argument of the proof, but instead to define a surjective map $R\to S$ and then prove its kernel is $I$.The whole point of the Isomorphism Theorem is that once you prove it, you do **not** need to write out the explicit function $R/I\to S$: you can just invoke the theorem to know it exists.
Answer: The "gold standard" way to apply the First Isomorphism Theorem to prove that a quotient $R/I$ is isomorphic to $S$ is to first define a surjective morphism $f\colon R\to S$, and then prove that $\mathrm{ker}(f)=I$. Then the First Isomorphism Theorem does all the work for you. The reason you never see the map $\Phi$ in the applications is that you don't want to go through the every step of the proof each time you want to apply the theorem. That's the whole point of proving the theorem in the first place!
Your notation leaves something to be desired. The elements of $\mathbb{Z}_{20}$ do not look like $a+\mathbb{Z}_{20}$: that doesn't even make sense, as you never write an element of a ring $R$ as $a+R$. I'm going to guess that you define $\mathbb{Z}_n$ as the quotient $\mathbb{Z}/n\mathbb{Z}$, so that elements of $\mathbb{Z}_{20}$ are of the form $a+20\mathbb{Z}$ with $a\in\mathbb{Z}$, and the elements of $\mathbb{Z}_5$ are of the form $b+5\mathbb{Z}$, with $b\in\mathbb{Z}$.
So, to prove that $\mathbb{Z}_{20}/\langle 5+20\mathbb{Z}\rangle$ is isomorphic to $\mathbb{Z}_5$, we want to define a morphism $\mathbb{Z}_{20}\to\mathbb{Z}_5$ whose kernel will be exactly $\langle 5+20\mathbb{Z}\rangle$.
Your definition works. But you need to show that it is a ring homomorphism in order to use the Theorem. Once you prove it is a ring homomorphism, the fact that the kernel is precisely $$\{0+20\mathbb{Z}$, 5+20\mathbb{Z}, 10+20\mathbb{Z},15+20\mathbb{Z}\} = \langle 5+20\mathbb{Z}\rangle$$
gives you the desired isomorphism, via the Isomorphism Theorem. The isomorphism is going to be annoying to write, since the elements of the quotient group are cosets of cosets... It would look something like
$$\Phi\Bigl((a+20\mathbb{Z})+\langle 5+20\mathbb{Z}\rangle\Bigr) = a+5\mathbb{Z}.$$
Comment: Thank you for your explanations.  This is what I understand from your answer.  To show isomorphism involving quotient rings and its image. I need to just create a surjective homomorphism map and also find the kernel and show that it is an ideal.  Then the first isomorphism theorem will do rest of the work for me.  In the case of my question,  The surjective homomorphic map would be: $f([a]_{20})=[a]_5$ and the kernel is: $<5+[a]_{20}>$.  Then I don't need to write out an explicit map from the quotient ring from $Z_{20}/(5)$ to $Z_5$ like...
Comment: the map:  $$\Phi\Bigl((a+20\mathbb{Z})+\langle 5+20\mathbb{Z}\rangle\Bigr) = a+5\mathbb{Z}.$$ which you wrote in the end.
Also, are the notation $n\mathbb{Z}$ and $(n)$ both denote the concept of ideals for the case of $mod n$, or is it respectively $$ or $$.  Notations for denoting $mod n$ as rings are equally confusing, I sometimes see $Z_n$ or $\mathbb{Z}/n\mathbb{Z}$.
Comment: @SethMai: Kernels of ring homomorphisms are *always* ideals. You don't "need to show [the kernel] is an ideal" if you show the function is a ring homomorphism. Given your notation, your description of the kernel of $f$ is still incorrect. The correct kernel is $\langle [5]_{20}\rangle$, not "$5+[a]_{20}$", which is not an element of $\mathbb{Z}_{20}$. Likewise, it would not be "$Z_{20}/(5)$", but $Z_{20}/([5]_{20})$. Notation needs to be defined. That's why I asked you what *your* definition is. There are multiple ways of describing the ring of integers modulo $n$.
Comment: thank you so much for your detailed explanations.


KoaJS middleware and database access

Question: If I had this to show an index for a users model:
app.use(route.get('/user', list));

function *list() {
  var res = yield users.find({});
  this.body = res;
};

Is it possible to put the database access part into its own middleware and then call next?
How could you pass the resulting list of users down to the next middleware?  And somehow pass next through the route?
So the first middleware is any DB access needed, and the second middleware is presentation?
Answer: Essentially you attach the information to the request context or the this keyword within the middleware.
I created a screencast on writing middleware that might be helpful:
http://knowthen.com/episode-4-writing-middleware-in-koajs/
Here is an example of how you would pass information to downstream middleware.
let koa   = require('koa'),
    users = require('./users'),
    app   = koa();

function *firstMiddleWare (next) {
  this.session = {
    user: yield users.find({});
  }
  yield next;
}

function *secondMiddleware (next) {
  // this.session.user is available here
  yield next;
}

app.use(firstMiddleWare);
app.use(secondMiddleware);

app.use(function *(){
  // this.session.user is available here as well
  this.body = this.session.user;
});

app.listen(3000);

Comment: Thanks! Great tutorial :)

KoaJS middleware and database access


important features in RandomForest - Sklearn

Question: 1) How to find important features in RandomForest classifier (in sklearn) with high statistical significant?
2) The input data I have is unbalanced which I simply repeat data to compensate that. When I do shuffling, some of these repeated data go to training and some goes to test which definitely increase the prediction accuracy. I know in reality it is not correct but what about if I only want to find important feature?
3) What is the meaning of a feature value (for example, 0.05) in randomforest? in Feature importance it is said that this value means 5% of data is classified correctly by this feature? To find the most important features can I sum up their values till become 0.9 and then I say 90% of data is classified correctly by this features?
Answer: The answer to this question describes how feature importances are computed in sklearn.  Maybe it will help you with your questions #1 and #3.
Regarding question #1:  It does not seem that this definition of importance is explicitly related to statistical significance.
Regarding question #2:  You could still report the feature importances reported by sklearn, but they would be defined relative to your augmented data set and therefore seem more difficult to interpret.  Using this augmented data set would at least change the "proportion of samples reaching that node" portion of the importance score equation (when compared with the original data set).  By the way, I've had good results using SMOTE over-sampling of the minority class, combined with under-sampling of the majority class, when dealing with imbalanced data sets.
Regarding question #3:  I'm not sure, but I don't think this definition of importance means that you could make the statement you make about 90% of the data being classified correctly by these features.


inverse action of cross product

Question: Suppose we have two vectorsfield A(x,y,z) and B(x,y,z).If we know B = (0,2,1) can we compute A if:

?
EDIT:
After some searching online I found that there are infinitely many vectors fields A(x,y,z) in order for : to be true.However do all these A vectors have something in common with each other?
Comment: $\nabla\times \vec A$ is notation usually used for vector _fields_, not just vectors. Are you saying $\vec B$ is a constant vector field?
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Comment: @Arthur I have edited.
Comment: @Arthur yes B is a costant vector field.
Comment: [Adding a gradient to $\vec A$](https://en.wikipedia.org/wiki/Curl_(mathematics)#Inverse) will give the same result.
Answer: The curl operator $\nabla \times$ is not injective so you have indeed infinitely many solutions. However, if one particular solution $A_0$ is given such that :
$$ \nabla \times A_0 = B $$
then any other solution $A$ has to satisfy :
$$ \nabla \times (A - A_0) = 0 $$
by linearity of the curl operator. Considering $A - A_0$ instead of $A$, you just look for solutions of :
$$ \nabla \times A = 0 $$
In $\mathbb{R}^3$, it is equivalent to the existence of a scalar function $\varphi$ such that $A = \nabla \varphi$ (it may be different if you change the base space). This means that your set of solutions is of the form :
$$ \{ A_0 + \nabla \varphi, \varphi : \mathbb{R}^3 \to \mathbb{R}, \mathcal{C}^1 \} $$
Note that the existence of $A_0$ depends on $B$ : namely, $B$ should satisfy $\nabla \cdot B = 0$. See for instance the Biot-Savart law (here).

inverse action of cross product


Existe limite máximo de tamanho para uma página HTML?

Question:
Obs.: Esta pergunta não é sobre otimização de código.

É sabido que os navegadores possuem um limite de tamanho para uma URI. Existe algum tipo de limite para requisição/renderização de um arquivo HTML?
Dando um exemplo simples, digamos que uma página HTML gerada no servidor, por algum bug ou erro de consulta, retorne uma tabela com milhões de linhas e várias colunas. Tal página (com centenas ou milhares de Megabytes) teria sua renderização bloqueada pelo navegador, ou ela é unicamente dependente do número de recursos do hardware em que o navegador está rodando?
Comment: um dos dois lados travará.. ou o server ou o cliente.. Um server um pouco mais carregado, com certeza vai dar algum problema. Mas normalmente o cliente vai dar crash tb. Os browsers normalmente travam depois de uns 60 ou 80mb, mas normalmente o cliente já trava bem antes disso.
Answer: Não existe limite no padrão HTML para o tamanho máximo que ele pode ter. Não faria sentido limitar o que um navegador pode aguentar até porque, se o navegador conseguisse passar desse limite, pode ter certeza não seria um padrão que o faria se recusar a aceitar a página.
Basta olhar o quanto os navegadores são compreensivos com HTMLs que possuem erros. Se um navegador se recusar a abrir a página que possui um erro e outro navegador aceitá-la (mesmo que não seja uma exibição perfeita), ele perde um usuário. O mesmo valeria aqui.
Em geral, padrões se limitam a exigir um mínimo de funcionalidade e não a ditar um máximo.
Answer: Limites impostos por padrão não, porém limites existem, sejam eles do lado do servidor ou do cliente.
Você pode usar um laço de repetição pra gerar algo muito grande e complexo para o navegador renderizar, além de sobrecarregar o seu servidor, que também poderá travar, irá chegar até um ponto no qual o navegador não vai conseguir renderizar de forma satisfatória e irá travar, seja por processamento ou uso de memória, lembre-se que computadores não tem memória infinita, por mais que possuam memória de sobra hoje em dia.
É como uma página de scroll infinito. Irá perceber que a cada scroll fica mais pesado, pode demorar um pouco de acordo com sua máquina, e se quiser ver resultados nítidos carregue uma imagem a cada scroll.

Por algum bug ou erro de consulta, retorne uma tabela com milhões de
  linhas e várias colunas.

A maioria dos programadores trata esse erro para que isso não aconteça, na maior parte das vezes se trata de erro de lógica, que pode ser corrigido ou detectado simplesmente fazendo testes.
Enquanto a consulta retorna resultados infinitamente, eles não serão exibidos, somente apenas terminar a execução e imprimir o resultado (ou se você fizer algo dinâmico pra exibir enquanto faz as queries). Em PHP por exemplo, você pode limitar o tempo de execução de um script, caso entre em loop infinito, isso iria parar a execução.

Limitar o tempo de execução de um script PHP

Na maior parte, quando um loop infinito ocorre e você não tem nenhum tratamento pra evitar isso, o cliente recebe um erro 500.
Enquanto do lado do cliente, quando o servidor (numa situação muito improvável) consegue executar e retornar algo absurdo, costumam travar em média de 90 MB, alguns ainda conseguem exibir, porém demoram bastante no processamento.


WebMvcTest not giving any code coverage in IntelliJ

Question: I have integration test class for a controller as below
<code>@WebMvcTest(DepartmentController.class)
public class DepartmentControllerTest {

    @MockBean
    private DepartmentService departmentService;

    @MockBean
    private RestTemplateBuilder restTemplateBuilder;

    @Autowired
    private MockMvc mockMvc;

    @Autowired
    private ModelMapper modelMapper;

    @Autowired
    ObjectMapper objectMapper;

    @Test
    void Get_Department_Returns_200_Ok_When_Department_Present() throws Exception {
        Optional<Department> deptOptional = Optional.of(new Department(1, "Tech"));
        when(departmentService.getDepartment(1)).thenReturn(deptOptional);
        assertThat(departmentService.getDepartment(1)).isEqualTo(deptOptional);
        mockMvc.perform(get("/department/{id}", 1)
        .contentType("application/json")
        ).andExpect(status().isOk());
    }

    //other tests
}
</code>
All the tests pass but it is not including the controller in the coverage results in IntelliJ
Answer: How I got this problem
I have encountered the same problem with code coverage in Intellij when using @WebMvcTest.  When I ran a single class (i.e., Run 'DepartmentControllerTest' with Coverage), there was No coverage result.

Possible Solution
I have fixed it by running coverage on a directory level.
Run 'Tests in 'controller' with Coverage
Image example of this action: