Azure CLI running .sh script on windows

Question: Is it posible to run .sh files from Azure-CLI in windows command line.
Following is the cosmosDB collection creation script that I'm trying to run on local Azure-CLI
#!/bin/bash

# Set variables for the new account, database, and collection
resourceGroupName='testgropu'
location='testlocation'
accountName='testaccount'
databaseName='testDB'
prefix='prefix.'
tenantName='testTenant'

collectionTest='.test'

originalThroughput=400
newThroughput=500

az cosmosdb collection create \
    --resource-group $resourceGroupName \
    --collection-name "$prefix$tenantName$collectionTest" \
    --name $accountName \
    --db-name $databaseName \
    --partition-key-path "/'\$v'/testId/'\$v'"

Is it posible to run these commands as a script from Azure-CLI like in linux . test.sh?
Answer: Actually, you cannot run the bash script like in Linux . test.sh. But you can run the bash script in the command prompt if you install the WSL in your windows like this:
bash test.sh

Additional, if you do not install the WSL in your windows, then the bash is not recognized as an internal or external command. And you also cannot use the bash command in the PowerShell.
Note: you should take care of when you create the bash script in your windows, there are different about the chars between Windows and Linux. You can use the tools that support multiple languages, for example, the notepad++.

Azure CLI running .sh script on windows


How to remove similarity string between two strings in php

Question: I have two strings like this:
<code>$str_1 = 'catalog/view/javascript/bootstrap/css/bootstrap.min.css';
$str_2 = 'catalog/view/javascript/font-awesome/css/font-awesome.min.css';
</code>
How can I remove 'catalog/view/javascript/' from $str_2.
Thank you!
Comment: you can use `explode("/",$str);`  then you use `unset `or any remove method
Comment: I did do it. But I want to know some shorter code like XOR operator to get the similarity string or I remove all string is same in two variable.
Answer: Try this
<code>$str_2 = 'catalog/view/javascript/font-awesome/css/font-awesome.min.css';
echo str_replace( "catalog/view/javascript/", "", $str_2 );
</code>
Comment: I think he wants to determine what should be removed from `$str_1`.
Comment: Possible but that is not what he has written in the question.  He has asked how to remove part of the string.  If the OP wants a comparison then I am sure something else can be written.
Answer: demo here
<code><?php
$str_1 = 'catalog/view/javascript/bootstrap/css/bootstrap.min.css';
$str_2 = 'catalog/view/javascript/font-awesome/css/font-awesome.min.css';
$length = strlen($str_1);
$index = 0;
while($index < $length)
{
    if(strpos($str_2, substr($str_1, 0, $index + 1)) === false)
        break;
    $index++;
}
$str_2 =  substr($str_2, $index);
echo $str_2;
</code>
Comment: It seems interesting but I need some shorter code. Thankyou!
Comment: @Diego I thought you were remove the same part with str_1 from str_2. It seems you don't want that, $str_1 misleads me?????.     $str_2 = 'catalog/view/javascript/font-awesome/css/font-awesome.min.css';
echo $str_2 = substr($str_2, strlen('catalog/view/javascript/')); works for you.
Comment: Oh, I'm so sorry if I make you sad. I mean, your code is working, but I want to some shorter code like XOR operator, maybe!

Ex: while($str_1[$i] ^ $str_2[$i]) { $i++} ....


Admin menu sometimes doesn't show up

Question: I'm having some strange issues with the Drupal admin menu system. I can't reproduce it reliably, but these are the steps that usually cause the problem:

Go to /user and log in. This works as expected and redirects me to the user page, where I see the admin menu.
Navigate to the front page, either by clicking a link on the page or by manually entering the / address.
Observe that there is no admin menu.
Refresh the home page (possibly a couple of times), and the admin menu may eventually appear.

I've tried both Firefox and Chrome in private browsing sessions, as well as clearing the Drupal admin menu cache. I'm completely thrown by this, as checking in Firebug/Chrome developer tools reveals the SESSxxxx cookie properly set and not changing between when the menu is shown and when it isn't.
Related questions refer to CSS/JS aggregation issues as well as permissions errors. It seems unlikely that at least the latter problem would be so unreliable.
I have Drupal 7 running on PHP 5.4.39/Apache 2.2.22 under Debian wheezy.
Answer: The few times i have had a similar issue i have resolved it by turning off 'Cache menu in client-side browser' on this page admin/config/administration/admin_menu
Comment: I'm still seeing the issue after unticking that box and clearing caches and cookies and so on.
Answer: I have had this in the past with differing causes:

if you have jQuery Update installed - I found this occasionally caused an issue where the admin menu would not show - the trick was finding a version that still produced what I wanted while maintaining the admin menu visibility - this can be confirmed if you have jQuery update installed, by temporarily disabling it
when developing custom modules, adding functions to template.php or otherwise making changes to tpl files I have found on rare occasions that an error in one of those files will cause the admin menu to stop showing - this can be confirmed by disabling any custom modules and changing the theme to Bartik temporarily

Admin menu sometimes doesn't show up


Grafico com barra de erros em R

Question: Ola,
Estou tentando fazer um gráfico em linhas e barras de erros, mas os erros estão sendo plotados por cima da primeira linha, e não na segunda.... e minha legenda não esta sendo impressa. Vocẽ poderia ver o que esta errado?
Segue o código:
V_drone = c(.5, 1.0, 1.5, 2.0, 2.5, 3.0)
Tempo_Incremental_Antigo = c(2589.9, 1905.6, 1567, 1324.5, 1218.6,1119)
Tempo_Incremental_Novo = c(2455.5, 1678.5,1370.8,1147.6, 996.59,911);
Tempo_error_A = c(52.35233201, 87.73976673,88.0883395,49.61566573,192.8685591,50.74248713)
Tempo_error_N = c(46.04164781,56.39592184,75.66563876,64.87500803,161.2008043,75.55329245)

plot(V_drone,Tempo_Incremental_Antigo, ylab=expression("Overall Time(s)"),xlab=expression("Drone speed(m/s)"),col="blue", pch=15, ylim=c(0,3500), cex=1.3, type="b")
arrows(V_drone,Tempo_Incremental_Antigo, V_drone, Tempo + Tempo_error_A, length=0.1,angle = 90,col="blue")
arrows(V_drone,Tempo_Incremental_Antigo, V_drone, Tempo - Tempo_error_A, length=0.1,angle = 90,col="blue")

points(V_drone,Tempo_Incremental_Novo, ylab=expression("Overall Time(s)"), pch=15, ylim=c(0,3500), cex=1.3, type="b", col="red")
arrows(V_drone,Tempo_Incremental_Novo, V_drone, Tempo + Tempo_error_N, length=0.1,angle = 90, col="red")
arrows(V_drone,Tempo_Incremental_Novo, V_drone, Tempo - Tempo_error_N, length=0.1,angle = 90, col="red")

legend(20,30,legend=c("Fotossínte", "Condutância estomática"),pch=c(15,16),bty="n")
text(5,30,"Gráfico A")

Answer: O problema da linha de erro pelo que entendi foi pelo nome da variável do valor central, consertando ela as linhas são desenhadas.
A legenda o problema foram os valores de x e y fornecidos, você estava criando ela fora do valor do eixo x do gráfico. A mesma coisa para o texto.
E recomendo quando for postar algo com gráfico já postar ele junto que costuma facilitar as sugestões :)

V_drone = c(.5, 1.0, 1.5, 2.0, 2.5, 3.0)
Tempo_Incremental_Antigo = c(2589.9, 1905.6, 1567, 1324.5, 1218.6,1119)
Tempo_Incremental_Novo = c(2455.5, 1678.5,1370.8,1147.6, 996.59,911);
Tempo_error_A = c(52.35233201, 87.73976673,88.0883395,49.61566573,192.8685591,50.74248713)
Tempo_error_N = c(46.04164781,56.39592184,75.66563876,64.87500803,161.2008043,75.55329245)

plot(V_drone,Tempo_Incremental_Antigo, ylab=expression("Overall Time(s)"),xlab=expression("Drone speed(m/s)"),col="blue", pch=15, ylim=c(0,3500), cex=1.3, type="b")
arrows(V_drone,Tempo_Incremental_Antigo, V_drone, Tempo_Incremental_Antigo + Tempo_error_A, length=0.1,angle = 90,col="blue")
arrows(V_drone,Tempo_Incremental_Antigo, V_drone, Tempo_Incremental_Antigo - Tempo_error_A, length=0.1,angle = 90,col="blue")

points(V_drone,Tempo_Incremental_Novo, ylab=expression("Overall Time(s)"), pch=15, ylim=c(0,3500), cex=1.3, type="b", col="red")
arrows(V_drone,Tempo_Incremental_Novo, V_drone, Tempo_Incremental_Novo + Tempo_error_N, length=0.1,angle = 90, col="red")
arrows(V_drone,Tempo_Incremental_Novo, V_drone, Tempo_Incremental_Novo - Tempo_error_N, length=0.1,angle = 90, col="red")

legend(2,3000,legend=c("Fotossínte", "Condutância estomática"), pch=c(15,16), col = c("blue", "red"), bty="n")
text(1.75, 3400,"Gráfico A")

Created on 2020-05-12 by the reprex package (v0.3.0)

Grafico com barra de erros em R


The prime ideals of $\mathbb{Z} [x] \otimes_{\mathbb{Z}} \mathbb{F}_p$

Question: I'm trying to do exercise 9 of section 15.5 in the book Abstract Algebra written by Dummit and Foote, whose aim is to establish a homeomorphic map between the elements in the fiber over $(p)$ of the Zariski continuous map from $\mathrm{Spec}(\mathbb{Z} [x])$ to $\mathrm{Spec}(\mathbb{Z})$ and the elements in $\mathrm{Spec}(\mathbb{Z} [x] \otimes_{\mathbb{Z}} \mathbb{F}_p)$. But I don't know what does the prime ideals of $\mathbb{Z} [x] \otimes_{\mathbb{Z}} \mathbb{F}_p$ looks like since it's the first time for me to study the primes in a tensor product.
Or generally speaking, given two rings $A$ and $B$, since a ring can be considered as a $\mathbb{Z}$-algebra, so the tensor product $A \otimes_{\mathbb{Z}} B$ of $\mathbb{Z}$-algebras $A$ and $B$ is also a ring. And what is the elements of $\mathrm{Spec}(A \otimes_{\mathbb{Z}} B)$ look like?
Answer: The ring in question can be simplified using the standard isomorphism rules for tensor products: $\mathbb{Z}[x] \otimes_{\mathbb{Z}} \mathbb{F}_5 \cong \mathbb{Z}[x] \otimes_{\mathbb{Z}} \mathbb{Z} / 5 \mathbb{Z} \cong \mathbb{Z} [x] / 5 \mathbb{Z} [x] \cong  \mathbb{F}_5 [x]$.

The prime ideals in a PID are the maximal ideals and $0$, and in this case that means the nonzero prime ideals of $\mathbb{Z}[x] \otimes_{\mathbb{Z}} \mathbb{F}_5$ are in correspondence with irreducible polynomials $p(x) \in \mathbb{F}_5 [x]$.
Comment: Is the general form of this isomorphism is $A[x] \otimes_A A / I \cong A[x] / I[x]$?
Comment: More general: $A/I \otimes_{A} M \cong M / IM$.
Answer: For variety, here's a geometric argument.
The contravariant $\operatorname{Spec}$ functor sends colimits of rings to limits of schemes. In the category of rings, $\otimes_R$ is the pushout over $R$; in particular, there is a pushout square
$$ \begin{matrix} \mathbb{Z}  &\to& \mathbb{Z}[x]
\\ \downarrow & & \downarrow
\\ \mathbb{F}_p &\to& \mathbb{Z}[x] \otimes_{\mathbb{Z}} \mathbb{F}_p \end{matrix} $$
Since $\mathbb{Z}$ is the initial ring, this is equivalent to saying that $\otimes_{\mathbb{Z}}$ is the coproduct, so that $\mathbb{Z}[x] \otimes_{\mathbb{Z}} \mathbb{F}_p$ is the coproduct of the rings $\mathbb{F}_p$ and $\mathbb{Z}[x]$.
So, in terms of schemes, this means
$$\begin{align} \operatorname{Spec}(\mathbb{Z}[x] \otimes_{\mathbb{Z}} \mathbb{F}_p)
&\cong \operatorname{Spec}(\mathbb{Z}[x]) \times_{\operatorname{Spec}(\mathbb{Z})} \operatorname{Spec}(\mathbb{F}_p)
\\&\cong \operatorname{Spec}(\mathbb{Z}[x]) \times\operatorname{Spec}(\mathbb{F}_p)
\end{align}$$
Since $\operatorname{Spec}(\mathbb{F}_p)$ is a subscheme of $\operatorname{Spec}(\mathbb{Z})$, this means the fiber product is just the subscheme of $\operatorname{Spec}(\mathbb{Z}[x])$ that lies over $\operatorname{Spec}(\mathbb{F}_p)$.
It may not be clear that this description actually translates to the expected description on points. But by the definition of pullback, it follows that the following are equivalent:

The $k$-points of $\operatorname{Spec}(\mathbb{Z}[x] \otimes_{\mathbb{Z}} \mathbb{F}_p)$
A pair of a $k$-point of $\operatorname{Spec}(\mathbb{Z}[x])$ and a $k$-point of $\operatorname{Spec}(\mathbb{F}_p)$ that have the same image in $\operatorname{Spec}(\mathbb{Z})$

Thus, the points of $\operatorname{Spec}(\mathbb{Z}[x] \otimes_{\mathbb{Z}} \mathbb{F}_p)$ really are the points of $\operatorname{Spec}(\mathbb{Z}[x])$ whose image in $\operatorname{Spec}(\mathbb{Z})$ is the image of $\operatorname{Spec}(\mathbb{F}_p)$.


Created a module that has a form: How do I display on a page?

Question: I just created a module called member_survey that just contains a simple information gathering form.
What I'd like to do is create a page with the url www.example.com/member-survey that contains the survey that i just created.
I can't for the life of me figure out how to do this. Can anyone point me in the right direction?
Answer: You should use hook_menu().
function member_survey_menu() {
  $items['member-survey'] = array(
    'title' => 'Your title',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('your_form_function'),
    'access arguments' => array('access content'),
  );
  return $items;
}

Replace your_form_function with the function that generates the form.
Replace array('access content') with your desired permissions.
You can also use the webform module instead of writing a module.
Comment: Okay, but where can I view the form?
Comment: it's showing up under member_survey but not member-survey
Comment: It will be shown on _member-survey_ page.Perhaps you have a typo in `$items['member-survey']`
Comment: no there was no type, but I did have to clear the cache to make it appear. :P


How to rigorously show that if $x$ is of Order $m$ then $x^k$ is of order $\frac{\text{lcm}(m,k)}{k}$?

Question: I need to show the seemingly obvious fact that if $x$ is of Order $m$ then $x^k$ is of order $\frac{\text{lcm}(m,k)}{k}$. I'm struggling with rigorously showing this fact, as I don't know of a closed way to write the lcm. Also, the group to be considered is not necessarily abelian or finite.
Is there a more elegant, indirect way to show this fact without a way to write the lcm?
Answer: If we write $o(x)$ for the order of $x$, I most frequently see this claim as
$$o(x^k) = \frac{o(x)}{\text{gcd}(o(x),k)}$$
This (equivalent) statement might give a better idea of how to prove the claim.

Let $d = \text{gcd}(o(x),k)$.
Then $o(x) = dn$ and $k = dm$ with $n$ and $m$ coprime.
We want to show $o(x^k) = n$
First, we see $o(x^k)$ divides $n$:
$$(x^k)^n = (x^{dm})^n = (x^{dn})^m = (x^{o(x)})^m = e^m = e$$
Can you use Bezout's Lemma to show that $o(x^k)$ actually equals $n$?
A full solution can be found here if you get stuck.

I hope this helps ^_^


Dúvida em JavaScript - Centralizar imagem

Question: Tenho uma function que coloca imagens no background de uma div circular.
Gostaria de centralizar a imagem no centro da div circular como no exemplo a seguir:

Pensei em colocar um background-position:center; no JavaScript, será que dará certo?

 function clickImagem(src)
 {
   $(conteudo).empty()
   document.getElementById('conteudo').style.background="url('"+src+"') no-repeat";
 }
 .conteudo-externo{
  width:500px;
  height:500px;
  z-index:3;
  background:#f1f;
  float:left;
 }
 .conteudo{
  width:350px;
  height:350px;
  border-radius:50%;
  border:3px solid #000;
  z-index:5;
  background:#f4f;
  margin: 50px auto;
  }
  .img{
   z-index:1;
   width:130px;
                        height:130px
                        background-position:center;
   opacity:0.5;
  }
<!doctype html>

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no">
<title>Teste</title>

Comment: Parece ser exatamente a mesma dúvida que esta (https://pt.stackoverflow.com/q/239062/5878). Pode explicar qual é a real diferença entre as duas?
Comment: Aquela pergunta era para centralizar uma div circular dentro de uma div.
Esta pergunta é para centralizar uma imagem dentro da div circular @Anderson
Answer: faltou a propriedade center

function clickImagem(src)
 {
  $('#conteudo').css('background',"url('"+src+"') no-repeat center");
 }
.conteudo-externo{
  width:500px;
  height:500px;
  z-index:3;
  background:#f1f;
  float:left;
 }
 .conteudo{
  width:350px;
  height:350px;
  border-radius:50%;
  border:3px solid #000;
  z-index:5;
  background:#f4f;
  margin: 50px auto;
    background-position:center;
  }
  .img{
   z-index:1;
   width:130px;
      height:130px;
   opacity:0.5;
  }
<!doctype html>

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no">
<title>Teste</title>

Comment: Entendi !! Obrigado @Felipe
Comment: Perfeito !! Obrigado Felipe, não conheço muito de Java Script então não sabia como colocar este center na function
Comment: Denada kk, só repare que eu substitui a ação de background de javascript para jquery(biblioteca que auxilia no desenvolvimento javascript), recomendo que toda vez que for mexer no DOM ou manipular eventos, use a mesma.
Comment: Entendi, qualquer outra coisa que eu quiser alterar no css posso usar esta function mesmo certo?? Width e Height da imagem por exemplo
Comment: Isso mesmo, muito mais fácil e legível, editei a resposta simplificando ainda mais


Using type array for "batch"-calling of the same generic method with different generic parameters

Question: I'm looking for some sleeker solution concerning the following: In a message bus implementation of mine I have several components which are subscribed to the event when new messages are published to the bus. The message bus transports BusMessage-objects (whose value is of object). Each component additionally implements a function to handle specific bus messages (derived components can override existing handle functions for certain message types) as follows e.g. for incoming string-typed bus messages:
protected virtual void HandleMessage(BusMessage<string> msg) { ... }

In order to distribute the incoming messages to the specific handle functions I have implemented an
static bool TryClassify<T>(BusMessage msg, Action<BusMessage<T>> handleFunction)

method which takes a T and checks for a given BusMessage whether it is actually a BusMessage<T> meaning that its value is of type T. The event handler is always as follows:
void HandleMessage(BusMessage msg)
{
  if (BusMessage.TryClassify<string>(msg, HandleMessage)) return;
}

With every specific BusMessage-type I want to handle in a component I must repeat that one line with TryClassify over an over again - the only difference is the type I specify, because the specific HandleMessage to be used is determined by the compiler. I end up with a method body consisting of
if (BusMessage.TryClassify<string>(msg, HandleMessage)) return;
if (BusMessage.TryClassify<bool>(msg, HandleMessage)) return;
if (BusMessage.TryClassify<long>(msg, HandleMessage)) return;
if (BusMessage.TryClassify<int>(msg, HandleMessage)) return;
if (BusMessage.TryClassify<DateTime>(msg, HandleMessage)) return;
...

Is there a more elegant, sleeker way with less boilerplate code to accomplish what I need? Something into the direction of using an array of types { typeof(string), typeof(bool), typeof(long), typeof(int), typeof(DateTime) } maybe?
Comment: I assume you want to avoid using dynamic typing? How many places do you currently have this duplication? If it's just in a single method, I'd probably keep it as it is.
Comment: After understanding and reviewing Illidans4's solution to the problem, I agree with you and keep my code as it is - it will be easier to maintain in the future even though there are at least two dozens of places being cluttered up with the almost identical stack of lines of code.
Answer: You can build this code using expressions:
class BusMessage
{
    private static readonly Func<BusMessage,Delegate,bool> TryClass;

    static BusMessage()
    {
        Type[] classTypes = new Type[]{typeof(int), typeof(string)};

        MethodInfo mi = typeof(BusMessage).GetMethod("TryClassifyInternal", BindingFlags.NonPublic | BindingFlags.Static);

        var p1 = Expression.Parameter(typeof(BusMessage));
        var p2 = Expression.Parameter(typeof(Delegate));
        Expression exp = null;
        foreach(Type t in classTypes)
        {
            MethodInfo mig = mi.MakeGenericMethod(t);
            Expression e = Expression.Call(mig, p1, Expression.Convert(p2, typeof(Action<>).MakeGenericType(typeof(BusMessage<>).MakeGenericType(t))));
            if(exp == null)
            {
                exp = e;
            }else{
                exp = Expression.OrElse(exp, e);
            }
        }

        TryClass = Expression.Lambda<Func<BusMessage,Delegate,bool>>(exp, p1, p2).Compile();
    }

    private static bool TryClassifyInternal<T>(BusMessage msg, Action<BusMessage<T>> handleFunction)
    {
        //former TryClassify code
        return false;
    }

    public static bool TryClassify(BusMessage msg, Delegate handleFunction)
    {
        return TryClass(msg, handleFunction);
    }
}

But, in this case, I would prefer your original code for clearness (and it's probably the shortest possible if you don't want to change code of other methods).
Comment: An interesting approach to the problem, especially for me because I never had something to do with Expressions before. However I'm now convinced to stick with my original way - due to readability and better understandability.


Chain Rule - $z''(t) = z'(t) \frac{dz'(t)}{dz}$

Question: all. This question may be a trivial answer, but I'm having trouble figuring this out. I'm taking a course in classical mechanics and I don't exactly see how the following equation is a result of the chain rule. My professor keeps saying "obviously" when calling on it, but I do not understand how it follows.
For a function $z=z(t)$, my professor claims the following:
$$ z''(t) = z'(t) \frac{dz'(t)}{dz} $$
How does this follow from the chain rule definition?
Thank you.
Comment: Write $z' = \mathrm d z/\mathrm d t$.
Answer: The chain rule says that
$$\frac{\mathrm{d}u}{\mathrm{d}x}=\frac{\mathrm{d}u}{\mathrm{d}v}\frac{\mathrm{d}v}{\mathrm{d}x}$$
So in your case:
$$\frac{\mathrm{d}z'}{\mathrm{d}t}=\frac{\mathrm{d}z'}{\mathrm{d}z}\frac{\mathrm{d}z}{\mathrm{d}t}$$
Answer: $$z''(t) = z'(t) \frac{dz'(t)}{dz}=z'(t) \frac{dz'(t)}{dt}\frac{dt}{dz(t)}=\frac{z'(t)z''(t)}{z'(t)}$$


Hiding "days", "minutes","hours", "seconds" and the

Question: I have several Flipclock counters. I am looking for a way to hide "days", "minutes","hours", "seconds" and the divider between them. I know I can hide digits using different "faces".
For example, with hourly counter I can hide "days", with minute counter I can hide "days" and "hours" and with Daily Counter I can hide "seconds". But if I need, for example, to leave only "minutes" and "hours" and hide "seconds" and "days" or leave only "hours"/"minutes", how can I do it?
Answer: Using the Daily Counter as a base, here's a CSS solution that was the quickest to draw up rather than having to get a PhD in building clock faces. You can wrap this up in a custom plugin extension and build your set of parameters (hideSeconds, hideMinutes, etc) to then apply the appropriate CSS.
Link
<code>.flip-clock-divider.days,
.flip-clock-divider.hours,
.clock ul:nth-child(1),
.clock ul:nth-child(2),
.clock ul:nth-child(3)
{
    display: none;
}
</code>
Comment: If you the version you use is 0.7.x, use `.flip-clock-wrapper` instead of `.clock`. In case 0.8.x - `.flipclock-wrapper`.
Answer: To hide labels:
<code>.flip-clock-label{ display: none !important; }
</code>
Comment: Not sure if this helped the OP, but it helped me! This was the first post that came up when I was trying to find a way to hide the labels. (I also didn't need the "!important" addon, FWIW.)


Gravar com MVC e jQuery porém os dados estão vindo nulos

Question: Fiz uma jQuery para pegar os dados vindo do formulário. E fiz um método em  minha controller para gravar no Banco de Dados. Acontece que os dados do formulário estão vindos nulos. O que pode ser? Abaixo a minha jQuery e meu método de persistir no BD.
jQuery
$(function () {

    var result = {
        //Id: $("").val(),
        Nome: $("input[name='txtNome']").val(),
        CPF: $("input[name='txtCep']").val(),
        Email: $("input[name='txtEmail']").val(),
        DataNascimento: $("input[name='txtAno']").val() + "-" + $("input[name='txtMes']").val() + "-" + $("input[name='txtDia']").val(),
        Telefone: $("input[name='txtTelefone']").val(),
        Celular: $("input[name='txtCelular']").val(),
        Endereco: $("input[name='txtLogradouro']").val(),
        Numero: $("input[name='txtNumero']").val(),
        CEP: $("input[name='txtCep']").val(),
        Complmento: $("input[name='txtComplemento']").val()
    };

    $("#btnGravarPassageiros").click(function () {
        $.ajax({
            url: '/Passo/addCliente',
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            type: "POST",
            data: JSON.stringify({ _tb_clientes: result }),
            success: function (data) {
                alert();
            },
            error: function (error) {

            }
        });
    });
});

Meu método em minha controller.
public JsonResult addCliente(TB_CLIENTES _tb_clientes)
{

    AgaxturCmsEntities db = new AgaxturCmsEntities();

    db.TB_CLIENTES.Add(_tb_clientes);
    db.SaveChanges();

    var Result = _tb_clientes.Id;

    return Json(new { Result }, JsonRequestBehavior.AllowGet);
}

View:
@{
    Layout = null;
}

<!DOCTYPE html>

    <title>Agaxtur - 60 anos de Turismo</title>
    <meta charset="UTF-8" />
    <meta name="description" content="" />
    <meta name="keywords" content="" />

    <link rel="stylesheet" href="@Url.Content("~/Content/reset.css")" />
    <link rel="stylesheet" href="@Url.Content("~/Content/960_24_col.css")" />
    <link rel="stylesheet" href="@Url.Content("~/Content/jquery.bxslider.css")" />
    <link rel="stylesheet" href="@Url.Content("~/Content/table.css")" />
    <link rel="stylesheet" href="@Url.Content("~/Content/styles.css")" />

Lojas

Contato

Minhas Viagens

Minha Conta

Login

Portal do Agente

                    (11) 3067.0900

Você está em: Seleção de Pacotes

Seleção de pacotes

Lisboa Express

                        Ida: 12/12/2013
                         Volta: 12/01/2014

4 adultos

<button value="novaPesquisa">Nova pesquisa</button>

Resumo da Viagem

Pacote 2:

Voo 1 ida:

Voo 2 volta:

Total:

R$ 300,00

R$ 300,00

R$ 300,00

R$ 900,00

Pacotes

                    Passo 1

Aereo

                    Passo 2

Hotéis

                    Passo 3

Serviços
Adicionais

                    Passo 4

Resumo

                    Passo 5

Pagamento

                    Passo 6

Insira os dados do passageiro e pagamento.

Confirmação dos dados

                            Nome

                            <input id="txtNome" type="text" name="txtNome" class="grid_14 required" placeholder="Nome completo" required />

                            Email

                            <input id="txtEmail" type="email" name="txtEmail" class="grid_6  required" placeholder="Email válido" required />

                            CPF

                            <input id="txtCpf" type="text" name="txtCpf" class="grid_5  required" placeholder="99999999999" required />
                            @*@Html.ValidationMessageFor(model => model.)*@

                            Data Nascimnento

                            <select id="txtDia" name="txtDia" class="grid_2" required>
                                <option>Dia</option>
                            </select>
                            <select id="txtMes" name="txtMes" class="grid_2" required>
                                <option>Mês</option>
                            </select>
                            <select id="txtAno" name="txtAno" class="grid_2" required>
                                <option>Ano</option>
                            </select>

                            @*retirar após testes*@

                                    Qde de Passageiros

                                    <input type="text" name="txtTesteQdePass" class="grid_4  required" placeholder="Entre com a qde de passageiros" />

                    @*Botão preenche endereço*@

                        <button value="novaPesquisa" class="btn-pular-passo pull-right" id="btnEndereco">Continuar</button>

                    @*A partir daqui, colocar em uma div para esconder e aparecer*@

                                CEP

                                <input id="txtCep" type="text" name="txtCep" class="grid_3  required" placeholder="00000-000" required />

                                Endereço

                                <input id="txtLogradouro" type="text" name="txtLogradouro" class="grid_14 required" placeholder="Endereço completo" required />

                                Número

                                <input id="txtNumero" type="text" name="txtNumero" class="grid_3  required" required />

                                Complemento

                                <input id="txtComplemento" type="text" name="txtComplemento" class="grid_8  required" required />

                                Telefone

                                <input id="txtTelefone" type="text" name="txtTelefone" class="grid_6  required" required />

                                Celular

                                <input id="txtCelular" type="text" name="txtCelular" class="grid_6  required" required />

                    @*

                            <button value="novaPesquisa" class="btn-pular-passo pull-right">Continuar</button>

*@

            @{
                string
                    nm, dia, mes, ano, sexo, numpassaporte,
                    diavalidade, mesvalidade,
                    anovalidade, paisemissao, dados = "";

                for (int i = 1; i < 3; i++)
                {
                    nm = "txtNomePassageiro" + i;
                    dia = "txtDiaPassageiro" + i;
                    mes = "txtMesPassageiro" + i;
                    ano = "txtAnoPassageiro" + i;
                    sexo = "txtSexo" + i;
                    numpassaporte = "txtPassaporte" + i;
                    diavalidade = "txtDiaVal" + i;
                    mesvalidade = "txtMesVal" + i;
                    anovalidade = "txtAnoVal" + i;
                    paisemissao = "txtPaisEmissao" + i;

                    dados = "0" + i;

                            @{
                    if (i < 10)
                    {

Dados do Passageiro @dados

                    }
                    else
                    {

Dados do Passageiro @i

                    }
                            }

                            <form class="">

                                        Nome do passageiro

                                        <input id="@nm" type="text" name=@nm class="grid_14 required" placeholder="Nome completo" required />

                                        Data Nascimento

                                        <select name=@dia class="grid_2" required="required">
                                            <option>Dia</option>
                                        </select>
                                        <select name=@mes class="grid_2" required>
                                            <option>Mês</option>
                                        </select>
                                        <select name=@ano class="grid_2" required>
                                            <option>Ano</option>
                                        </select>

                                        Sexo

                                        <select name=@sexo class="grid_3" required>
                                            <option>Sexo</option>
                                            <option>Masculino</option>
                                            <option>Feminino</option>
                                        </select>

                                        Número do passaporte

                                        <input type="number" name=@numpassaporte class="grid_4  required" required />

                                        Validade

                                        <select name=@diavalidade class="grid_2" required>
                                            <option>Dia</option>
                                        </select>
                                        <select name=@mesvalidade class="grid_2" required>
                                            <option>Mês</option>
                                        </select>
                                        <select name=@anovalidade class="grid_2" required>
                                            <option>Ano</option>
                                        </select>

                                        País de emissão

                                        <select name=@paisemissao class="grid_3" required>
                                            <option>País</option>
                                        </select>

                                @*

                                        <button value="novaPesquisa" class="btn-pular-passo pull-right">Ir para o pagamento</button>

*@
                            </form>

                }

            }

                    <button id="btnGravarPassageiros" onclick="window.location.href='/Home/Index'" value="novaPesquisa" class="btn-pular-passo pull-right">Ir para o pagamento</button>

Institucional

Comment: já experimentas te dar `alert` de uma input para ver se tem os dados? Alguma vez a aplicação chega à função no controller?
Comment: @pnet você poderia postar a view também? Pois pelo que eu estava vendo, pode ser que exista uma forma muito mais limpa e curta
Comment: Estou postando coisas no desespero, devido ao atraso do projeto. Resolvi. As variáveis, no jquery, estavam declaradas fora. Deveriam ter sido declaradas dentro da função do click do botão. Resolvido.
Answer: Este método addCliente está bem fora do padrão do Web API. Eu faria uma coisa assim:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Description;
using MeuProjeto.Models;

namespace MeuProjeto.Controllers
{
    public class ClientesController : ApiController
    {

        // POST api/Clientes
        [ResponseType(typeof(TB_CLIENTES))]
        public async Task<JsonResult> PostCliente(TB_CLIENTES _tb_clientes)
        {
            AgaxturCmsEntities db = new AgaxturCmsEntities();

            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            db.TB_CLIENTES.Add(_tb_clientes);

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateException)
            {
                if (ClienteExists(_tb_clientes.Id))
                {
                    return Conflict();
                }
                else
                {
                    throw;
                }
            }

            return Json(new { _tb_clientes.Id }, JsonRequestBehavior.AllowGet);
        }
    }
}

Desta forma, eu confiro pelo contexto se o cliente já existe, levanto os conflitos se isto ocorrer e devolvo o status correto em tela.
Comment: Fui usar da forma postada pelo cigano e da erro de referência. O que devo adicionar? Não reconheceu: ResponseType, DbUpdateException, BadRequest, Conflict, Task e etc... Uso VS 2013
Comment: @pnet Editei a resposta. Veja agora.
Comment: Resolvi com alguns using, mas não todos.
Comment: Esses dois using eu não consigo add em meu projeo a dll deles. using System.Web.Http;
using System.Web.Http.Description;
Comment: Essas `dll`s são do Framework 4.5.


If $p$ and $q$ are positive prime numbers such that $p$ is divisible by $q$, show that $p = q$.

Question: To solve this problem, this is my approach. Assume $p\mid q$, there exists an $n∈N$ and assume $q\mid p$, there exists an $m∈N$. This would mean that $p=qn$ and $q=pm$. Then using substitution, $p=pmn$ where either $p=0$ or $mn=1$. If $mn=1$, then  $n=m=1$ and if $p=0$, then $q$ is also $0$ which means that $p=q$. However, the question states that $p$ and $q$ are primes, so does my approach work or is there something else? Help appreciated please.
Comment: Which definition of "prime" are you using?
Comment: Aside the fact that this is merely checking the definition, your proof uses $p\mid q$ which wasn't in the hypothesis. In fact you never used "primality", therefore your "result" holds for any number, but there exists at least 2 different integer numbers therefore something wrong:):)
Answer: Assume $q\mid p$. Since $p$ is prime, then there are only two divisors of $p$, namely $1$ and $p$. So, $q=1$ or $q=p$. Since $q$ is prime, $q>1$, so $q\neq1$. Thus, $q=p$.
Answer: Hint: Every prime number $p$ has only two positive divisors, $1$ and $p$. If $q|p$ then how many divisors would at least $p$ have if $p \neq q$? Now conclude.
Answer: I think you were on the right track up until the point you decided to use substitution. So back up to just before that point.
If $p = qn$ and $p$ is prime, then $n = 1$ or $n = -1$. The former means $p = q$, as desired, the latter means $p = -q$. But I have a feeling your textbook is concerned with positive primes only.


Yearly Archive with month in drupal7

Question: I  want to add news in my website . i want left sidebar and header as in image.
I dont know which module should i use for this.
Months are showing in tabs . I am using Bootstrap3 theme here
Answer: There is an archive view that comes bundled with Views (Check out admin/build/views page, views name Default Node view: archive (default)), just clone and modify it as per your need and it should work.
Also check this links containing discussion about the same requirement:

How to create monthly archive block
How to create a monthly archive block for a Drupal blog with Views
Views Archive Drill Down (Year//Month/Day) Block
Comment: @HituBansal That may be done through CSS as you can make the position of month block as absolute and accordingly modifying it as per the need. However for creating the block you refer the above solution.
Comment: i want years on left and all months on header.

Yearly Archive with month in drupal7


Sass "@at-root" not working

Question: Currently I have sass 3.3 installed but I am using compass to compile. The question at hand is , I have the following two mixins to do bem syntax:
<code>//elements get appended with "__" and the $name
=e($name)
    @at-root &__#{$name}
        @content

//modifiers get appended with "--" and the $name
=m($name)
    @at-root &--#{$name}
        @content
</code>
In use:
<code>.blocker
    +e(item)
        color: red
</code>
Output:
<code>.blocker {
  @at-root &__item {
    color: blue;
}

}
</code>
Why is it not working?
Comment: What version of Compass are you using?
Answer: I tried your mixin out an it seems to work fine, however, using the updated sass syntax, you don't need a mixin or @at-root to achieve this
<code>.blocker
    &__item
        color: red
    &--mod
        color: blue
</code>
will compile to
<code>.blocker__item {
    color: blue;
}
.blocker--mod {
    color: red;
}
</code>
If you want to try out the sass code itself, independently of your environment, take a look at SassMeister.
Comment: I tried your suggestion and wonder why it's not working.  Here is the gist - http://sassmeister.com/gist/2ec20689a0b33427dee7
Comment: @SatheeshKumar on sassmeister you need to change the settings of your gist from SCSS to Sass. Then the spacing needs to be consistent, either indenting with 2 spaces or 4. After this it compiled for me

Sass "@at-root" not working


Mathematical background in differential equations

Question: I am a philosophy postgraduate working on mathematical models in cognitive science. I would like some advice for what mathematical background I should acquire to understand the maths behind this paper of Turing's: The Chemical Basis of Morphogenesis.
Thank you so much,
Comment: Where did all the philosophers that *had* to know basic mathematics (say, at least undergraduate level) go? I can't remember right now where (somewhere in Germany or Russia...?), but someone once told me, or I read it somewhere, that there is (are) some university(ies) that *require* philosophy undergraduates to know basic mathematics thoroughly to access to graduate school...and as the answer below remarks: to read that paper by turing you must at least know some basic differential equations and some complex analysis.
Comment: Thanks for your comment. I also wonder why it's no longer (?) a requirement. Because anyway you wake up one day asking what some piece of maths is doing for your argument... I suppose most of us have to be self-taught.
Answer: Page 39 of the publication (page 4 of the pdf) is titled "Mathematical Background Required."  By reading that and glancing at the rest of the paper, it appears that you will need differential equations, at least through solving 2nd order linear equations.
To learn DE's, you typically need two semesters of Calculus (Calc I and II).


Intuitive way to look at Matrix addition

Question: There's a model for multiplication, but is there any visual meaning for adding two matrices together, while thinking of them as vectors or functions?
Comment: matrices are just  short hand notation, write them out and it is all obvious.
Answer: Let $A, B \in \mathbb{R}^{n \times m}$ be matrices. If you want to interpret them as functions $\mathbb{R}^n \rightarrow \mathbb{R}^m$ that takes $x$ to $Ax$ and $Bx$, respectively, then you can interpret $A + B$ as another function $\mathbb{R}^n \rightarrow \mathbb{R}^m$ which takes $x$ to $Ax + Bx$.


Django and Aggregate: Sum of distinct values?

Question: I am trying to do a django aggregate function, but am unable to produce the desired result.
What I've got:
income_posts.values_list('category__name','amount')
[(u'Donation', Decimal("2000.00")), (u'Paycheck', Decimal("1200.00")), (u'Donation', Decimal("1000.00"))]

Desired result:
[(u'Donation', Decimal("3000.00")), (u'Paycheck', Decimal("1200.00))]

I need to Sum the 'amount' fields that have the same category__name.
Answer: From this answer for a related question:
from django.db.models import Sum
income_posts.values('category__name').order_by('category__name').annotate(total=Sum('amount'))

Comment: The reason why this works is because [`.annotate()` works slightly differently after a `.values()`](https://docs.djangoproject.com/en/dev/topics/db/aggregation/#values): "However, when a values() clause is used to constrain the columns that are returned in the result set, the method for evaluating annotations is slightly different. Instead of returning an annotated result for each result in the original QuerySet, the original results are grouped according to the unique combinations of the fields specified in the values() clause."
Comment: this way you do not get `DISTINCT` and distinction is achieved by another column in `GROUP BY`.
Comment: Relevant documentation: http://docs.djangoproject.com/en/dev/topics/db/aggregation/
Answer: Just to add to arjun27's answer. Since that package seems to have been abandoned you might want to just copy past the 3 lines you need from it:
from django.db.models import Sum
class DistinctSum(Sum):
    function = "SUM"
    template = "%(function)s(DISTINCT %(expressions)s)"

Which can be used the same as above:
income_posts.annotate(total=DistinctSum('amount')

Comment: fine, except the case where the same amount comes from different sources
Answer: Django 3.0 introduced "distinct=True" on Sum and Avg:
https://docs.djangoproject.com/en/3.0/ref/models/querysets/#sum
Answer: I think this issue also related to Combining multiple aggregations.
Here is the ticket for this bug.
We can use Subquery(Django Docs) to achieve this issue:
from django.db.models import Subquery, OuterRef, IntegerField, Sum, Value, Count

MyModel.objects.annotate(
    count_model_a=Count('ModelA', distinct=True),
    sum_model_b=Coalesce(
        Subquery(
            ModelB.objects.filter(
                MyModel=OuterRef('pk')
            ).values('MyModel_id').annotate(
                my_sum=Sum('MyModel_Field')
            ).values('my_sum')[:1],
            output_field=IntegerField()
        ),
        Value(0)
    )
).values("count_model_a", "sum_model_b")

I also used Coalesce(Django Docs) function to prevent returning None.
The above code will run one query to DB.
Comment: Brialliant answer. This is the most underrated answer for the question. I wonder why this doesn't get enough upvotes
Answer: If you are on Postgres, you can use the django-pg-utils package for sum of distinct values.
from pg_utils import DistinctSum
income_posts.annotate(total=DistinctSum('amount')

Comment: The Github for django-pg-utils is not available anymore and the latest update was in 2017. It still works but beware with this module.
Answer: For those who are using django 2.2 LTE, this behavior can be achieved just reproducing django 3.0 commit that implements distinct for Sum:
https://github.com/django/django/commit/5f24e7158e1d5a7e40fa0ae270639f6a171bb18e
this way:
from django.db.models Sum

class SumDistinctHACK(Sum):
    allow_distinct = True

and now you can use the django 3.0 syntax:
queryset.annotate(
    sum_result=SumDistinctHACK(
        'relatedmodel__values_to_sum',
        distinct=True,
    )
)

remember to replace SumDistinctHACK to Sum if you upgrade to django >= 3.0
Answer: For older version of Django use Func
queryset.annotate(
   sum_result=Sum(
        Func(F('amount'), function='DISTINCT')
   )
)

Comment: This works as long as you have different values(amount). Once you have the same values, it won't work anymore.
Answer: You can do this:
income_posts.values("category__name").distinct().annotate(total=Sum("amount"))


Does the conductor sometimes play with the soloist (Or on his own)?

Question: I watched the following two videos and it gave me the distinct idea that the conductor played something of his own choosing. Does this happen or am I getting my wires crossed?
Malaguena:

Pasacaglia:
Comment: Just leave the link raw and the site will do the rest.
Comment: Can anyone maybe tell me how to get those youtube videos embedded?
Answer: Sure, there are times when the conductor will go ahead and be the soloist. It's not that uncommon especially when the orchestra is relatively small.


kendo grid number column formatting

Question: How can i use the jquery masking plugin with Kendo MVC Grid ?
I want to mask kendo grid column bound "phone number" column.
I am working on ASP.NET MVC4 application.

Or is there any other way to mask kendo mvc grid phone number column?
Comment: Mask it how? display or input for inline/popup edits/creates?
Answer: what do you mean by masking? like hidding the column ??
if this is what you are looking for, you can set the hidden attribute of the column to true, it will hide the column.
If you have the column menu available and do not want to see the column in that menu, set the menu attribute of the column to false.

kendo grid number column formatting


How should I keep count in a Recursive function. Without tail recursion, or extra parameters

Question: I have an ML programming assignment and in several of the functions, it would be useful to keep count. For example in one function I need to return a lists of indexes where an element appears.  I don't know how to track these things in recursion, as ever function call kills my count.  In the real world I would tack on a count variable, but that is not an option in school. Any tips?
Comment: You need to pass to a function the information that the function needs to do its job. Why can't you create helper functions which have extra parameters? Such things are often done in ML. The definition of the helper function can be purely local to the function (using `let fun ... in...end)` so in that sense the overall function isn't cluttered by any extra parameters.
Comment: Why is tail recursion not an option?
Comment: @Yawar, teachers orders.
Comment: @JohnColeman  I can use helper functions.  Should I just pass a count variable to the helper function.   For example my homer work says I must use the exact params for the original function, i.e. fun string2Int("1,2,3,4");  But I could pass "1,2,3,4" and a count variable to a helper function.

I'll try it again with helper functions, and see how it goes. Thanks John
Comment: @JohnColeman So I just wrote a function using helpers, and it works great. Thanks buddy!
Answer: If you can use a helper function, you can basically use tail recursion. Your teacher would not give you a recursion problem that forces you to use techniques other than pure recursion
The pattern with these functions is usually:
<code>fun outer list =
  let
    fun inner param inner_list =
      (* use tail recursion here *)
  in
    inner initial_param list
  end
</code>
Comment: I will use let, in, end, on at least one problem to get a feel for it.

By the way I'm jealous you got to hold the cup!  Thanks for your help.
Comment: Cheers  Sorry, just fixed up the syntax. I was probably thinking in OCaml when I wrote that initially.


Shrinkage of the eigenvalues

Question: Assume we have $n$ samples $X_1,..., X_n$ which are independent and identically distributed with mean = 0 and unknown non-singular covariance matrix $M$. Each sample $X_i$ is a vector of size $p\times 1$.
I want to apply the "Stein-Haff estimator" [Stein, C. 1975] which estimates $M$ by  shrinking its eigenvalues. So assume $M$ has the eigenvalues $\alpha_1, \alpha_2, ..., \alpha_p$. Its estimation $M'$ has the corrected eigenvalues $\alpha'_1, \alpha'_2, ..., \alpha'_p$.
Stein-Haff estimator is of the form Stein, C (1977b), Lecture 4 page 1391:
$~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~$$\alpha'_j = \alpha_j / L_j(\alpha)$
Where $L_j(\alpha) = n + p - 2j + 1 + 2 \sum_{i>j} (\alpha_i/ (\alpha_j - \alpha_i)) - 2\sum_{i<j} (\alpha_j / (\alpha_i - \alpha_j))$.
Unfortunately, this estimator is not very well since some corrected eigenvalues can be zero or even negative. That is why, they proceed to apply an "isotonic regression" to the above equation. There are a lot of references that explain how the isotonic version of this estimator is done:

Unfortunately, I am not able to get the PDF of the first two references. But can someone explain to me how Stein modified his estimator using the isotonic regression. So what is the final form of the equation above?
Kindly any help from your expriences will be very appreciated!
Answer: First of all, I don't know anything about Stein-Haff estimator other than what I saw from a few seconds of Googling in https://stat.duke.edu/~berger/papers/yang.pdf , which contains the quote "This estimator has two problems. First, the intuitively compatible ordering $\phi_1 \geq \phi_2 \geq \dots \geq \phi_p$ is frequently violated. Second, and more serious, some of the $\phi_i$ may even be negative. Stein suggests an isotonizing algorithm to avoid these problems. ... The details of this isotonizing algorithm can be found in Lin and Perlman (1985)".
That reference is: LIN, S. P. and PERLMAN,M. D. (1985). A Monte Carlo comparison of four estimators for a covariance matrix. In Multivariate Analysis 6 (P. R. Krishnaiah, ed.) 411-429. North-Holland, Amsterdam.
However, I do know about optimization. Isotonizing constraints can be placed on a least squares problem, making it into a (linearly constrained) convex Quadratic Programming (QP) problem, which is easy to formulate and numerically solve using off the shelf software.  If an L^1 norm is used for the regression, or even an L^1 penalty being added to an L^2 objective, that is still a convex QP.  In the case in which the objective is solely L^1, it would actually be a Linear Programming (LP) problem, which is a special case of a convex QP.
As for the negative eigenvalues, presuming those are still possible after adding the isotonizing constraints, that can be dealt with by imposing a semidefinite constraint on the covariance matrix.  I.e., imposing the constraint that the minimum eigenvalue $\geq 0$.  You could actually set a minimum eigenvalue value other than 0 if you so desire, and you would need to do this if you want to ensure the covariance matrix is nonsingular as you seem to suggest is desired or required.  Addition of this semidefinite constraint turns the whole optimization problem into a convex semidefinite program (SDP), or technically, something convertible thereinto.
Formulating and numerically solving such a convex SDP, i.e., objective in your choice of norm (L^p for any $p \geq 1$), plus any objective penalty in your choice of norm $(p \geq 1)$ which need not be the same as the other norm, plus isotonizing (linear) constraints, plus semi-definite constraint, is VERY easy and straightforward using a tool such as CVX http://cvxr.com/cvx/ .  This should be very fast executing unless dimension of the covariance matrix (what you called p, not what I called p) is in the thousands or greater. YALMIP http://users.isy.liu.se/johanl/yalmip/ could be used instead of CVX (which only allows formulation and solution of convex optimization problems, except for the optional specification of integer constraints).  YALMIP allows for a greater choice of optimization solvers and a greater range of problems (non-convex) which can be formulated and solved than CVX, but has a steeper learning curve.
Comment: Thank you for your time and answering me :). So in the case where we have more unknown regression coefficients than the dimension of the dependent variable, the least squares may be inefficient and thus some Eigenvalues can be negative or zero (undetermined system of equations). So in this case we can apply the isotonic constraint to the least squares instead of adding an L1  or penalties???
Comment: I don't know what the objective function in Stein-Haff  is "supposed to" be. Adding isotonnizing and semidefinite constraints is easy. You can change the objective function to whatever you want and call it the Christina-Stone-Stein-Haff estimator :) You don't have to add any penalty to the objective function - I was just saying you can without making the optimization problem solution more difficult. If using CVX or YALMIP, the preferrred approach for a Least Squares objective is to minimize a norm or sum of norms, not sum of squares. Too many coefficients sounds like a recipe for overfitting.
Comment: As i said, I don't know the what or why of Stein-Haff estimator, but if it has all these deficiencies, it could be that imposing isotonizing and semidefinite constraints is just a band-aid. In 1975, eigenvalue optimization was almost unheard of. Now it's fairly mature. I don't think Stein ever imposed or maybe knew about eigenvalue (semidefinite) constraints. Eigenvalue optimization for covariance matrices is easy because they're symmetric. I've done a lot of eigenvalue optimization, not just for covariance matrices, but for non-symmetric matrices, which is much harder due to non-convexity.

Shrinkage of the eigenvalues


Can PyPI serve packages directly from GitHub?

Question: Is there any way to link a PyPI repo directly to a GitHub repo so that it makes the latest version of the files available for download instead of uploading the files every time?
Answer: No, PyPI only serves packages uploaded to it.  pip can install from other sources than PyPI though:
pip install https://github.com/sopython/sopython-site/tarball/master

pip install git+ssh://firstname.lastname@example.com/sopython/sopython-site@master#egg=sopython-site


Controlling blocks displayed in domain access for each sub-domain

Question: I'm a noob in Drupal and have been exploring the Domain Access module ( http://drupal.org/project/domain ) in my local environment and till now has been doing pretty well. But when it comes to configuring block content i'm a bit baffled.
Problem goes like this:
domain is localhost.com
Sub domains are:

one.localhost.com
two.localhost.com
three.localhost.com

When i enable a block in one of the sub-domains two.localhost, say enabling Search in Right Sidebar and saving the changes they are applied not only to two.localhost but to all the others too.
Note that I'm working in drupal 6.22 with Garland theme in all the sub domains.
Is there anything I'm missing from the functionalities provided by the module like Domain Theme? or does it have to be coded by me to make blocks also in domain specific manner...any suggestions/helps would be much appreciated.
Thanks and cheers!
Answer: You've a module that gonna help you. Domain Blocks. And here you've many other that add some features to Domain Access module.
Comment: just to proceed on this does using domain prefix module with blocks related table serve as an alternative to this?
Comment: Yes, but the created blocks will not shared between all domains. And you've to prefix `blocks` and `boxes` and all related block tables (for example, cache and etc..)


Unir arrays diferentes em forma de árvore?

Question: tenho uma situação em que não estou conseguindo arranjar uma solução.
Suponha que tenhamos dois arrays da seguinte maneira:
array('br', 'com', 'example1' )

e outro array assim:
array('br','com','example2')

o que eu gostaria é de transformar estes dois arrays em apenas um de forma que pareça uma árvore de dados assim
br
!_com
    !_example1
    |_example2

ou se também é possível organizá-los de um formato que possa ler em jSon
br:{
   com:{ "example1", "example2" }
}

Alguém poderia propor um algorítmo ou existe alguma função em PHP que faça isto?
Comment: Pode dar mais exemplos ? Esse exemplo parece me talvez um pouco forçado ? Cada entrada do array é um nivel da arvore ? Podem ter entradas diferentes ? A ordem pode ser diferente ? A divisão fica sempre no fim ou pode ficar no meio ?
Comment: a ideia é que os valores repetidos na mesma posição dos arrays se tornem nós da arvore. no exemplo os dois arrays tem valores repetidos na primeira posição, então isto se tornaria um nó do array.
Answer: finalmente consegui elaborar uma solução para este algoritmo.
Suponha tenhamos o seguinte array:
$itens = array( array('br','com','exemplo1'), array('br,'com','exemplo2'));
$result = array(array());

No meu caso eu criei uma função que recebe o array final por referência da seguinte maneira:
function treeNodesArray( &$result, $itens)
{
    foreach( $itens as $array ){

       $node = &$result;

       foreach( $array as $value )
       {
        if( $node != null && array_key_exists( $value, $node ))
        {
            $node = &$node[$value];

        }else{
            $node[$value] = array();
            $node = &$node[$value];

        }
      }
    }
}

print_r( $result );

Obrigado!


nsclient - debugging connection issues

Question: I have numerous windows clients that I want to monitor via nagios/nsclient. I've installed the latest nsclient on two win7 x64 and one win2012 r2. Of these one win7 works while the other two machines return could not complete SSL handshake when a connection is attempted from the nagios machine (libexec/check_nrpe -H hostname -c check_cpu).
What I've tried:

check passwords - all these systems have identical nsclient.ini files.
check ports - nmap -P0 client_name returns the same for all (ports 5666 is open)
run nscp test - non-working systems return sslv3 alert: unexpected message(win7) or failed to establish secure connection: no shared cipher (win2012)

I'm stuck trying to figure out what's different between the working and non working windows 7 systems and trying to apply this to a windows 2012 system.
Comment: What version of check_nrpe?
Comment: Looks like 2.15. But that part is consistent between the working and nonworking systems.
Answer: If you are using 0.4.3 (which I assume) "default" security has been improved a bit.
This unfortunately means the rather insecure check_nrpe wont work.
When you install NSClient++ you have the option of selecting "insecure mode" which should work fine with the classic check_nrpe.
You can also tweak this "in post" using the nrpe command like so:
nscp nrpe install --insecure

If you want to use the "slightly more secure" modes offered by NSClient++ you need to install NSClient++ on the nagios server as well and use the NSClient++ version of check_nrpe which support modern SSL and certificate based authentication.
Comment: I saw this reference in the various forums. I will try it but it doesn't explain (to me) why there would be a difference between my three machines - all installed on the same day, from the same place, and using the same settings.
Comment: You can always copy the config from one node to the next, then it should be no change. Please also note that restart the service is required for changes to take effect.

nsclient - debugging connection issues


Expectation of the absolute value of the product of correlated jointly gaussians?

Question: I am reading the Performer paper https://arxiv.org/abs/2009.14794. To understand their ReLU kernel used to approximate softmax attention, I need to evaluate $\mathbb{E}[ReLU(x^T w) \cdot ReLU(y^T w)]$ where $w \sim \mathcal{N}(0, I)$. I was able to reduce the problem to the more general one of computing $\mathbb{E}[|X \cdot Y|]$ where $X,Y$ are correlated jointly Gaussians. However, now I am stuck. Is there an approach of computing this expression or bound it from above reasonably without numerical simulation? Cauchy-Schwarz seems to loose for the upper bound.
Comment: Because $\text{ReLU}(z) = 0$ if $z < 0$, then you could write (using the law of total expectation) $$\mathbb{E}[ReLU(x^T w) \cdot ReLU(y^T w)] = \Pr(x^Tw \geq 0, y^Tw \geq 0) \cdot E[x^Tw \cdot y^T w \mid x^Tw \geq 0, y^Tw \geq 0]$$ Would this be easier to evaluate? I think the answer may be yes, since $w$ consists of i.i.d Gaussians, and so $x^Tw$ and $y^T w$ are both Gaussian.
Comment: I did think about this approach as well, but the conditional expectation seems really hard to evaluate. In particular, you can simplify this to $Trace(y x^T\mathbb{E}[ww^T | x^T w \geq 0, y^T w \geq 0])$. Intuitively for the dimension of $w$ large enough the expectation should yield about the identity, but how to make this exact?
Answer: Probably not the best solution, but a direction that may be useful.
Suppose
\begin{align}
\begin{bmatrix}
X \\ Y
\end{bmatrix} \sim N_2\left(\begin{bmatrix} \mu_1 \\ \mu_2 \end{bmatrix},
\begin{bmatrix}
\sigma_1^2 & \rho\sigma_1\sigma_2 \\
\rho\sigma_1\sigma_2 & \sigma_2^2
\end{bmatrix}\right).
\end{align}
It is well known that the conditional distribution of $X$ given $Y = y$ is univariate normal:
\begin{align}
X | Y = y \sim N(\mu_1 + \rho\sigma_1\sigma_2^{-1}(y - \mu_2), (1 - \rho^2)\sigma_1^2). \tag{1}
\end{align}
This suggests that, to bound $E[|XY|] = E[E[|X||Y||Y]] = E[|Y|E[|X||Y]]$, we can evaluate $E[|X||Y]$ first.  In this answer (or use the property of folded normal distribution), it is shown that if $Z \sim N(\mu, \sigma^2)$, then
\begin{align}
E[|Z|] = \sigma\sqrt{\frac{2}{\pi}}e^{-\frac{\mu^2}{2\sigma^2}} + \mu(1 - 2\Phi(-\mu\sigma^{-1})), \tag{2}
\end{align}
where $\Phi$ is CDF of $N(0, 1)$.  $(1)$ and $(2)$ together then imply
\begin{align}
& E[|X||Y] = \sqrt{1 - \rho^2}\sigma_1\sqrt{\frac{2}{\pi}}e^{-\frac{[\mu_1 + \rho\sigma_1\sigma_2^{-1}(Y - \mu_2)]^2}{2(1 - \rho^2)\sigma_1^2}} \\
+& (\mu_1 + \rho\sigma_1\sigma_2^{-1}(Y - \mu_2))\left(1 - 2\Phi\left(-\frac{\mu_1 + \rho\sigma_1\sigma_2^{-1}(Y - \mu_2)}{\sqrt{1 - \rho^2}\sigma_1}\right)\right). \tag{3}
\end{align}
A trivial upper bound for $(3)$ is
\begin{align}
\sqrt{1 - \rho^2}\sigma_1\sqrt{\frac{2}{\pi}} + |\mu_1| + |\rho|\sigma_1\sigma_2^{-1}(|Y| + |\mu_2|),
\end{align}
which gives an upper bound for $E[|XY|]$ as
\begin{align}
 & CE[|Y|] + |\rho|\sigma_1\sigma_2^{-1}E[Y^2] \\
=& C\left[\sigma_2\sqrt{\frac{2}{\pi}}e^{-\frac{\mu_2^2}{2\sigma_2^2}} + \mu_2(1 - 2\Phi(-\mu_2\sigma_2^{-1}))\right] + |\rho|\sigma_1\sigma_2^{-1}(\sigma_2^2 + \mu_2^2), \tag{4}
\end{align}
where $C = \sqrt{1 - \rho^2}\sigma_1\sqrt{\frac{2}{\pi}} + |\mu_1| + |\rho|\sigma_1\sigma_2^{-1}|\mu_2|$.

Updates
Added R code of comparing bound $(4)$ and the Cauchy-Schwarz bound $\sqrt{(\sigma_1^2 + \mu_1^2)(\sigma_2^2 + \mu_2^2)}$. As expected, bound $(4)$ is sharper when $X$ and $Y$ are weakly correlated while Cauchy-Schwarz bound is sharper when $X$ and $Y$ are highly correlated.  Different setups of $\mu_i$ and $\sigma_i$ also result in different winners.  Those who are interested can play with it.
<code>bounds <- function(mu1, mu2, sigma1, sigma2, rho) {
  C1 <- sqrt(1 - rho^2) * sigma1 * sqrt(2/pi) + abs(mu1) + abs(rho * mu2) * sigma1/sigma2
  C2 <- sigma2 * sqrt(2/pi) * exp(-mu2^2/(2 * sigma2^2)) +
    mu2 * (1 - 2 * pnorm(-mu2/sigma2))
  C3 <- abs(rho) * sigma1 * (sigma2^2 + mu2^2)/sigma2
  UB1 <- C1 * C2 + C3
  UB2 <- sqrt((sigma1^2 + mu1^2) * (sigma2^2 + mu2^2))
  c(UB1, UB2)
}

para_mat <- cbind(rep(0, 10), rep(0, 10), rep(1, 10), rep(1, 10), seq(0.1, 0.9, len = 10))
colnames(para_mat) <- c("mu1", "mu2", "sigma1", "sigma2", "rho")

My_bound <- apply(para_mat, 1, function(t) bounds(t[1], t[2], t[3], t[4], t[5])[1])
CS_bound <- apply(para_mat, 1, function(t) bounds(t[1], t[2], t[3], t[4], t[5])[2])
cbind(para_mat, My_bound, CS_bound)

## Result:
        mu1 mu2 sigma1 sigma2       rho  My_bound CS_bound
   [1,]   0   0      1      1 0.1000000 0.7334287        1
   [2,]   0   0      1      1 0.1888889 0.8140485        1
   [3,]   0   0      1      1 0.2777778 0.8893436        1
   [4,]   0   0      1      1 0.3666667 0.9589474        1
   [5,]   0   0      1      1 0.4555556 1.0222792        1
   [6,]   0   0      1      1 0.5444444 1.0784391        1
   [7,]   0   0      1      1 0.6333333 1.1260001        1
   [8,]   0   0      1      1 0.7222222 1.1625473        1
   [9,]   0   0      1      1 0.8111111 1.1834650        1
  [10,]   0   0      1      1 0.9000000 1.1774961        1
</code>
Comment: @mhdadk  Added the updates.  Enjoy playing it :).
Comment: @N.Menet Surprisingly, for non-zero means ($\mu_1 \neq 0, \mu_2 \neq 0$) and heteroscedastic variances, C-S bound works better under many situations.
Comment: I did some numerical experiment, this upper bound is not uniformly tighter than the bound given by C-S inequality (i.e., for different $(\mu_1, \mu_2, \sigma_1, \sigma_2, \rho)$, it may or may not be sharper than C-S inequality).  So if you want to apply this upper bound, compare it with C-S bound first.
Comment: Nice idea. Could you include the code you used to run the numerical experiment?
Comment: Did a square in (1) get lost? Should the variance not be $(1-\rho^2) \sigma_1^2$? I guess for the centered jointly Gaussians $X = w^T x$ and $Y = w^T y$ of the original formulation one would thus get $E[|X \cdot Y |] \leq \sqrt{1-\rho^2} \sigma_1 \sigma_2 \frac{2}{\pi} + |\rho|\sigma_1\sigma_2$ compared to what Cauchy-Schwarz gives: $E[|X \cdot Y |] \leq \sigma_1 \sigma_2$ ? So for $|\rho|=1$ the two coincide and for $\rho=0$ an improvement of $\frac{2}{\pi} $ is observed?
Comment: Actually, if $\rho = 0$, i.e. $X,Y$ independent, then according to the expectation of centred folded distributions $\mathbb{E}[|X \cdot Y|] = \mathbb{E}[|X|] \cdot \mathbb{E}[|Y|] = \frac{2}{\pi} \sigma_1 \sigma_2$, meaning your formula is tight at both endpoints $\rho=0$ and $|\rho| = 1$. Neat!
Comment: @N.Menet Yes, it should be $1 - \rho^2$, I will fix it and check the numerical results again.
Comment: That is indeed interesting. Thank you for your answer, it helped a great deal. I never encountered folded normal distributions before.


How to remove the shadow of a button on Xamarin Forms

Question: is it possible?
I would like to remove the shadow of the buttons on Xamarin Forms.
Thanks
Comment: i guess you could just rework the template ...
Answer: For delete shadow on button Android you just need create a renderer in project Droid and set BackroundColor with transparent or other color.
For a project using PCL :
[assembly: ExportRenderer(typeof(Button),typeof(FlatButtonRenderer))]
namespace Project.Droid
    {
        public class FlatButtonRenderer : ButtonRenderer
        {
            protected override void OnDraw(Android.Graphics.Canvas canvas)
            {
                base.OnDraw(canvas);
            }
        }
    }

In XAML :
<Button BackgroundColor="Transparent" Text="ClickMe"/>

Comment: Incredible, i just created that class and the borders works and shadows was removed on android. Tks.
Comment: How to do this for shared project?
Answer: Explaining with more detail.
using Android.App;
using Android.Content.PM;
using Android.OS;
using Xamarin.Forms.Platform.Android;
using ProjectName.Droid;
using Xamarin.Forms;

[assembly: ExportRenderer(typeof(Xamarin.Forms.Button), typeof(FlatButtonRenderer))]
namespace ProjectName.Droid
{
    public class FlatButtonRenderer : ButtonRenderer
    {
        protected override void OnDraw(Android.Graphics.Canvas canvas)
        {
            base.OnDraw(canvas);
        }
    }
}

Comment: You can derive a new type of button. And only apply it to that button
Answer: @Tonatio in your renderer instead of using
[assembly: ExportRenderer(typeof(Xamarin.Forms.Button), typeof(FlatButtonRenderer))]

use this
[assembly: ExportRenderer(typeof(YourCustomButton), typeof(FlatButtonRenderer))]

you will have to make a CustomButton control that inherits from Xamarin.Forms.Button and then use that custom button in your xaml instead of regular button. that should do the thing
     //Add references to your custom control
        xmlns:controls="clr-namespace:YourNameSpace.Controls"
     //Use control
     <Grid>
           <controls:YourCustomButton x:Name="_customButton"/>
     </Grid>

Feel free to drop by if you need some more help.
Answer: You can now just set the Visual to Default instead of Material and that fixed it for me:
<Button
Visual="Default"
/>

Answer: There's a simple hack around this. Simply wrap the button in a Frame element, with HasShadow set to False
<Frame HasShadow="False" Padding="0" Margin="0">
    <Button Padding="15"
            Text="Log in"
            TextColor="Blue"
            FontSize="17" />
</Frame>

This will remove the button's shadow
Comment: This hack doesnt work.


Meaning of Average Compares in BST

Question: I am stuck with following question from the book 'Algorithms' 4th edition by Sedgewick and Wayne.
Add to BST a recursive method avgCompares() that computes the average number
of compares required by a random search hit in a given BST (the internal path
length of the tree divided by its size, plus one). Develop two implementations: a recursive
method (which takes linear time and space proportional to the height), and a
method like size() that adds a field to each node in the tree (and takes linear space and
constant time per query).
I am not clear on what the author mean by Average Compare in this question.
Note: I don't need assistance on coding part.
Comment: They want you to run Monte-Carlo simulation to compute average number of comparisons performed per search.
Answer: To get the average number of compares for a BST you must sum the number of comparisons to find every node given that the length of search for every node is equal to internal path to that node + 1. Finally to get the average value you must divide the sum by the total number of nodes. So it is just the average length of a node search.
Comment: Hi, can you please elaborate it with an example?
Comment: Let's say you have an unbalanced BST of 3 nodes in the form of a list. You need 1 comparison to find node 1, 2 for node 2 and 3 for node 3. So you get the total of 6 comparisons to find every node in the BST. Divided by the number of nodes (3) it gives 2 as the average number of compares.

Meaning of Average Compares in BST


The nth coordinate position along a path tracing the diagonals of an infinite matrix

Question: I am trying to find a formula or algorithm to calculate the nth pair of numbers in this infinite sequence, starting at 0. That is, for each number on the left, a method to calculate the corresponding pair of numbers on the right:
0: (0, 0)

1: (1, 0)
2: (0, 1)

3: (2, 0)
4: (1, 1)
5: (0, 2)

6: (3, 0)
7: (2, 1)
8: (1, 2)
9: (0, 3)

10: (4, 0)
11: (3, 1)
12: (2, 2)
13: (1, 3)
14: (0, 4)
...

Each pair of numbers represents a coordinate in an infinite 2 dimensional matrix. The ordering of the coordinates traces a path along each diagonal:
14
9 13
5 8 12
2 4 7 11
0 1 3 6 10

I have gotten as far as finding a Python function to generate a finite number of terms of the sequence:
def generate_seq(m):
  k = 0
  for i in range(m):
    for j in range(i):
      print(f'{k}: {(i - j - 1, j)}')
      k += 1

I also think that the last printed value of k can be calculated as k = (n * (n - 1) / 2) - 1.
Comment: Where is this problem from?
Comment: @Sal The automated generation of a font for an alphabet based on binary numbers. The nth letter in the alphabet will correspond to a grid of black and white pixels encoding the nth binary number. By iterating the zeros and ones along the diagonals, arbitrarily many additional letters can be added without changing any of the previous ones, except to pad them as needed with additional white space to keep their sizes the same.
Answer: I took the sequence of the first value in each pair
0 1 0 2 1 0 3 2 1 0 4 3 2 1 0 5 4 3 2 1 0 6 5 4 3 2 1 0
and entered it into the On-Line Encyclopedia of Integer Sequences. It identified the sequence as https://oeis.org/A025581. This led me to https://oeis.org/A073189/a073189.txt. From this I was able to define a Python function that appears to generate it:
import math

def binomial(n, k):
  return math.factorial(n) / (math.factorial(k) * math.factorial(n - k))

for n in range(0, 15):
  if n == 0:
    t1 = 0
    t2 = 0
  else:
    t1 = binomial(math.floor(3/2 + math.sqrt(2 + 2 * n)), 2) - (n + 1)
    t2 = n - binomial(math.floor(1/2 + math.sqrt(2 + 2 * n)), 2)

  print(f'{n}: {(t1, t2)}')


Can anyone modify this LINQ to SQL query so it only returns one instance of each row?

Question: var nodes = (from n in db.Nodes
                 join st in db.SessionTrackings on n.NodeID equals st.NodeID
                 where st.UserID == userid && st.GroupID == groupid
                 select n);

IDictionary<int, bool> trackingData = new Dictionary<int, bool>();

foreach (Node n in nodes)
{
    trackingData.Add(new KeyValuePair<int, bool>(n.ID, true));
}

I keep getting a 'that key was already added' because there could be many SessionTrackings per Node, however I just want to get back all the Nodes that have at least 1 SessionTracking in existence for the NodeID but I don't need to get the Nodes more than once. If there are 4000 SessionTrackings for a Node (say ID = 45) I still only one 1 instance of Node 45 in my IQueryable. How can I modify my query for this? Please don't worry about why I need it in a Dictionary that's just the way it is.
Comment: Is `st.NodeID` part of an association?  i.e. Does `st.Node` exist?
Comment: It's not clear how you get from `nodes` to `trackings`
Answer: You just need to tell the query engine that you only want distinct instances of your objects:
var nodes = (from n in db.Nodes
             join st in db.SessionTrackings on n.NodeID equals st.NodeID
             where st.UserID == userid && st.GroupID == groupid
             select n).Distinct();

IDictionary<int, bool> trackingData = nodes.ToDictionary(n => n.ID, n => true);

If you don't need the nodes query for anything else, you can combine the statements like this:
IDictionary<int, bool> trackingData =
            (from n in db.Nodes
             join st in db.SessionTrackings on n.NodeID equals st.NodeID
             where st.UserID == userid && st.GroupID == groupid
             select n.Id)
            .Distinct()
            .ToDictionary(i => i, i => true);

Comment: It looks like the OP actually wants a dictionary of tracking ids (`a.ID`) to bools.  Which means the OP should really just be using a HashSet(), passing your `trackings` result to the constructor.  (Though with a further select if the OP actually wants the ID instead of the object)
Comment: I agree that a dictionary mapping id -> true is a lot like a HashSet, but he probably needs to pass that dictionary to some other component he doesn't control (or sometimes needs to set the values to false).
Comment: to set the "values to false" in the HashSet analogy would simply mean the removal of the items from the HashSet.
Comment: Kirk: A HashSet gives you 2 states for any object: either in the set or not; the Dictionary gives you 3 states: either in the dictionary and true or false or not in the dictionary. It's not hard to imagine a situation where you need 3 states instead of 2.
Answer: This is how you can get the first session:
var nodes = (from n in db.Nodes
    join st in db.SessionTrackings on n.NodeID equals st.NodeID
    where st.UserID == userid && st.GroupID == groupid
    select n)
    .GroupBy(n => n.ID)
    .Select(g => g.First());

Answer: I think you would need to do something like
var nodeids = (from n in db.Nodes
join st in db.SessionTrackings on n.NodeID equals st.NodeId
where  st.UserId.equals(userid) && st.GroupID.equals(groupid)
select new {Id = n.Id})).distinct();

That should give you everything you need for the iteration, without repeats.


How to draw complex button with inset circle in xml?

Question: How to draw button like below image in xml? Basically, it has two different buttons. One is for I. another one is for Pick Up. Thanks.
Answer: Try this:
<RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:background="@drawable/bg_btn_coner"
            android:gravity="center"
            android:text="Pickup"
            android:textColor="@android:color/white"
            android:textSize="20sp" />

        <TextView
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:background="@drawable/bg_btn_coner"
            android:gravity="center"
            android:text="i"
            android:textColor="@android:color/white"
            android:textSize="20sp" />

    </RelativeLayout>

and bg_btn_coner.xml

<solid android:color="#737373" />

<stroke
    android:width="3dp"
    android:color="@android:color/white"></stroke>

<corners android:radius="50dp"></corners>

Result:
Answer: Try this. Example image is shown.
Note: you will have to fix the path to make the image perfect.

button_circle.xml
<?xml version="1.0" encoding="utf-8"?>

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <solid android:color="@android:color/darker_gray" />
</shape>

button_rectangle.xml
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="720dp"
    android:height="576dp"
    android:viewportWidth="720"
    android:viewportHeight="576">

    <path
        android:fillColor="@android:color/darker_gray"
        android:pathData="M700.461,426.359c0,51.164-7.764,92.641-17.336,92.641H76.369
c-9.575,0,17.191-101.692,17.191-152.855l-1.444-173.699c0-51.164-25.321-136.646-15.747-136.646h606.756
c9.572,0,17.336,41.476,17.336,92.64V426.359z" />
</vector>

You will have to fix the vector to make the shape perfect. but this a good example for u.
my_layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:layout_width="match_parent"
        android:layout_height="42dp"
        android:background="@drawable/button_rectangle"/>

    <Button
        android:layout_width="42dp"
        android:layout_height="42dp"
        android:background="@drawable/button_circle"/>
</RelativeLayout>

Hope this helps!


Does tilting the angle of the harmonica affect when overblowing?

Question: I just read a question about overblow on harmonica. One answer gave me the impression that the direction of the air stream should be directed at the bottom reed instead of the top reed. If that is the case, will adjusting the tilt of the harmonica aid in redirecting the air stream toward the bottom reed?
Answer: It might, but probably not.
I tried just now to hold an overblow while tilting the harmonica up and down; I got it from lying flat against my shin with my upper lip stretched over it (I felt like a tapir) to touching my nose (the latter an acrobatic feat which took me several minutes to nail). I used a Seydel Session Steal in A, and it worked for the hole 2 and hole 6 both.
What I meant (I suspect you are referring to my answer) isn't necessarily that the air needs to be actually redirected, but rather that imagining the air stream pointing downwards used to help me find the right mouth shape. It makes me raise the back of my tongue and general back area of my mouth, while lowering the front slightly. (I'll try to clarify the other answer too)
This said, I do understand the impulse to tilt the harp when doing difficult bends or overbends. I used to do it and I think I still do sometimes. The main effect of this, though, I think is to slightly change the length or volume of your mouth. With either side of your hand in contact with your face, pivoting around the point of contact, small precise movements are easier than it would be to simply move the harp in or out of your mouth. Thus you move one parameter away from the brain centre controlling your tongue, which is already overloaded trying to find the right shape. With practice, more of the things a beginner might do with her hands can be transferred to her mouth, but I see no drawback with keeping on using the hands for as long as one wishes.


Uncountable infinite family of uncountable subsets of an uncountable set

Question: Find an uncountable family of pairwise disjoint uncountable subsets, on an uncountable set B.
Comment: I found one. But I'm not going to give it to you.
Comment: Unfortunately, I have great difficulty even finding my own answers with the search tool.  I don't feel like complaining when others can't find the duplicate questions.
Comment: @Ross: I have fairly good luck finding my own answers if I can remember a couple of useful words from them, but I use Google to do it, searching on `keyword keyword brian site:math.stackexchange.com`.
Comment: (Also, please bother and search the site. Where your previous question is probably a duplicate, this one I'm pretty sure is a duplicate of an old question. Show some respect to the people who help you for *free* on the site.)
Comment: Are you allowed to choose the uncountable set $B$, or are you supposed to show that this can be done for **every** uncountable set $B$?
Comment: @Ross: Even if I'm wrong, and even if it wasn't asked before. I do expect that part of the process of asking a question is to try and figure out if the question was asked before. If the OP doesn't post any thought on the problem, and no thoughts about their effort to find out whether or not the problem was asked before, I will usually use my bad memory and decide whether or not this was asked or not. If the OP points out that they have searched the site, but didn't find; and they tried this or that, then that's a whole other thing.
Comment: @AsafKaragila I'm sorry if I offended you. I don't mean to disrespect at all. Please excuse me. I will try to search even better next time around. (Maybe its my way of typing when I search that gives me nothing.)
Comment: @Brian It was a bit confusing to me, but now when I think about it deeper, I think it is for any B we choose. Thanks for the hint too!
Comment: @Ross Thanks for the support. As I said, I don't mean to disrespect you amazing people who support us learners so well.
Comment: @user110842: You're welcome! If you're allowed to choose the $B$, you can simply ... oops! Never mind: Ross just posted the example that I was about to suggest.
Comment: No problem, and it's not a big deal. But before posting questions try and look around a little bit. See how good questions look like. Note that they all include your own efforts to solve the problem, and more than just the statement of the problem.
Comment: @Asaf I will do that from now on and include my own material too. Thanks for the hints!
Answer: HINT: If $A$ is any infinite set, then $|A\times A|=|A|$ (assuming the axiom of choice).
Answer: Hint:  If you get to choose $B$, a nice one is the infinite sequences of $0$'s and $1$'s.  If you think about alternate positions, you can find an explicit construction.
Answer: HINT: Since $A$ is uncountable $\aleph_1\leq|A|$. It suffices to show that you can split $\omega_1$ (or any set of size $\aleph_1$) into $\aleph_1$ parts. (This shows that the result in fact follows from a far weaker assumption than the axiom of choice.)


Can we manually identify feature distribution on Naive Bayes solutions?

Question: If we want to classify some samples based on some continuous features, we basically suppose that all features are from Gaussian distribution ( Gaussian naive Bayes in scikit-learn ). If we want to use Bayes rule, is that common to identify each feature's distribution manually and then use manual method of Bayes rule to identify the target? For example first feature maybe from Gaussian distribution, second feature will be from Gamma distribution and so.
Why I ask this, is that I mostly see that in Naive Bayes solutions, people ignore the distribution of features.
Answer: Naive Bayes does not make the assumption of normality. It makes the assumption that the features are independent. In the case of a normal distribution, there is actually no point in making the independence assumption, because you can directly estimate the covariance matrix and mean vector, even when the features are correlated. You can thus directly implement Bayes' decision rule without making the independence assumption. Mathematically, this is equivalent to a classification rule known as "quadratic discriminant analysis".
On the other hand, the naive Bayes classifier can be used without any distribution assumption, namely by using kernel density estimators. I do not know whether there already is a scikit implementation, but scikit includes a krenel density estimator sklearn.neighbors.KernelDensity, so you can build your own non-parametric naive Bayes classifiers with a few lines of code.
In R, you can use klaR::NaiveBayes with the option usekernel=TRUE.
Comment: The point of assumptions like normality or independence is to make the problem computationally simpler. Methods like neural nets,  random forests, kNN, or support vectore machines do not make either of these assumptions.
Comment: And just another question: are these kinds of assumptions important for other methods like deep learning or decision tree or random forest ? Or it just works for Bayes? Thanks


DataFrame groupBy when each group has a difference

Question: I'm attempting to groupby several columns in a DataFrame and only keep the rows where a specific column changed values.
Here is a sample of the dataset
Id  Type    Size    StoredAt
107  1       20    2019-08-01
107  1       20    2019-08-02
107  1       20    2019-07-31
107  1       20    2019-07-30
107  3       20    2019-07-29
108  1       20    2019-08-01
108  1       20    2019-08-02
108  3       20    2019-07-31

What I'm attempting to do is groupby so I only have two rows that shows when the type went from a 1 to a three. Here is what I want the DataFrame to look like.
Id  Type    Size    StoredAt
107  1       20    2019-08-01
107  3       20    2019-07-29
108  1       20    2019-08-01
108  3       20    2019-07-31

All I have so far
dataFrame.groupby(['Id', 'Type', 'Size'])['Id', 'Type', 'Size', 'StoredAt']

Which isn't returning what I'm expecting.
Comment: Are you trying to detect the point at which the change occurs (eg the 1 and 3 should be immediately next to each other? Or just the first example of a 1 or a 3 in that group?
Comment: The latter, I want the first time Type is a 1 and the last time Type is a 2
Answer: It looks like you're just keeping the first example of a 1 or a 3 within that group. In that case you can use the following to give your desired output:
df.groupby(['Id', 'Type']).first().reset_index()

This assumes that your dataframe is sorted on the "StoredAt" column. If it's not you will need to do a sort before hand.
An alternative would be to use drop_duplicates using only the subset of columns which should be unique combinations (Id and Type) in this case. This would be:
df.drop_duplicates(subset=['Id', 'Type'])

Answer: I think drop_duplicates work for you
df.drop_duplicates(['Id','Type'])
Out[256]:
    Id  Type  Size    StoredAt
0  107     1    20  2019-08-01
4  107     3    20  2019-07-29
5  108     1    20  2019-08-01
7  108     3    20  2019-07-31


SetEnvIf problem on htaccess

Question: I'm trying to get this running,
SetEnvIf Host ^dev\. HOST_DEVELOPMENT
SetEnvIf Host ^www\. HOST_PRODUCTION

<IfDefine HOST_DEVELOPMENT>

    # e.g. php_flag display_errors on

</IfDefine>

<IfDefine HOST_PRODUCTION>

    # e.g. php_flag display_errors off

</IfDefine>

but it doesn't work. any ideas?
Answer: <IfDefine> only runs when apache starts.  The HOST_* variables should be available in your PHP script, so you can check $_ENV['HOST_PRODUCTION'] and turn display_errors off at run time.

SetEnvIf problem on htaccess


Objeto para Array php

Question: Olá, estou com um problema, este código abaixo esta retornando um objeto de 'tipo', preciso que 'tipo' seja array.
while ($obj = $stmt->fetch(PDO::FETCH_ASSOC)) {
      $stmt2 = $db->query('SELECT * FROM wines a, uva b WHERE a.id_tipo = '.$obj['idtipo'].' AND a.id_uva = b.id GROUP BY a.id_uva');
       while ($obj2 = $stmt2->fetch(PDO::FETCH_ASSOC)) {
             $wines[$obj['tipo']][] = $obj2;
       }

}

Ele retorna assim
{"ESPUMANTES": [
    {
        "id": "5",
        "name": "MIOLO MILESSIME",
        "uva": "BRUT"
    },

],
"VINHOS BRANCOS": [
    {
        "id": "1",
        "name": "CASA VALDUGA LEOPOLDINA GRAN RESERVA",
        "uva": "CHARDONNAY"
    },

]}

preciso que "ESPUMANTES" e "VINHOS BRANCOS"  esteja dentro de um array.
{
[
   1: "ESPUMANTES" [
        {
            "id": "1",
            "name": "CASA VALDUGA LEOPOLDINA GRAN RESERVA",
            "uva": "CHARDONNAY"
        }
    ]
],
[
    2: "VINHOS BRANCOS" [
        {
            "id": "1",
            "name": "CASA VALDUGA LEOPOLDINA GRAN RESERVA",
            "uva": "CHARDONNAY"
        }
]

}
Comment: Se eu entendi direito. Você quer que fique assim: `array("ESPUMANTES", "VINHOS BRANCOS")`. É isso?
Comment: basicamente isso, mas dentro de cada um outro array com as informaçōes
Comment: Para cada vinho ele pode ter mais de uma categoria? É isso?
Comment: Exemplo... MIOLO MILESSIME pode ser "ESPUMANTES" e "VINHOS BRANCOS". É isso?
Comment: Você poderia mostrar o resultado final desejado?
Comment: algo parecido com isso, por que preciso iterar la no angular com ngFor os tipos de vinhos que são ESPUMANTES ou VINHOS BRANCOS, em uma lista que abre um modal com os vinhos em si.
Comment: Entendi. Vou postar uma resposta e você ve se dá certo.
Answer: Tente assim:
$x = 0;
while ($obj = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $stmt2 = $db->query('SELECT * FROM wines a, uva b WHERE a.id_tipo = '.$obj['idtipo'].' AND a.id_uva = b.id GROUP BY a.id_uva');
    while ($obj2 = $stmt2->fetch(PDO::FETCH_ASSOC)) {
        $wines[$x][$obj['tipo']] = $obj2;
    }
    $x++;
}

Comment: iiisssoo meu querido! hahaha, muito obrigado por me ajudar, e ajudar a comunidade que vai ter essa duvida no futuro, estou enrolado neste projeto a um tempo pois não sou bom com php valeu!! <3
Comment: XD tranquilo! As vezes é difícil entender o problema por isso demoramos um pouco. Mas é isso ai. Boa Sorte!
Answer: Aparenta ser um JSON estes dados
Tenta:
$array = json_decode($objeto, true);

http://php.net/manual/pt_BR/function.json-decode.php
Answer: Patrick, se você não ter a necessidade de ser dentro do PHP a transformação para array, pode fazer da seguinte forma.
Onde eu atribui o valor para x, seria no caso a response do teu servidor.
let x = {
"ESPUMANTES": [
    {
        "id": "5",
        "name": "MIOLO MILESSIME",
        "uva": "BRUT"
    }
],
"VINHOS BRANCOS": [
    {
        "id": "1",
        "name": "CASA VALDUGA LEOPOLDINA GRAN RESERVA",
        "uva": "CHARDONNAY"
    }
],
"VINHOS TINTOS": [
    {
        "id": "4",
        "name": "ERRAZURIZ 1870 RESERVA CARMENERE ",
        "uva": "CARMENERE"
    }
]
};

let z = Object.values(x);
z.forEach(res => { console.log(res) });

Objeto para Array php


How can I connect two routers to the same switch

Question: First of all, I'm not talking about those all-in-one routers that do wifi/switching/routing.  It drives me nuts when people call a Wifi box a "router".  Anway, I would like to do the following as shown in my diagram:
Is it possible to connect Router A and Router B to the same switch, while having Router B be connected to a different subnet?   Excuse my ignorance, but my motivation for setting it up this way is to make it so that when the computer labeled Computer on 184.108.40.206/24 tries to connect to a camera that is on a different subnet (10.5.1.0/24) traffic flows through the switch, then to Router B which routes the traffic to the appropriate subnet.  I want to bypass Router A because I want to reserve that router to only handle traffic associated with the 126.96.36.199/24 subnet & internet. I don't want it involved when going to the 10.5.1.0/24 subnet, hence the second router connected to the switch.
Specific questions I need clarification on:

First of all, is this even possible?
With this setup will I have to configure some sort of manual routing information on each device/computer so that it knows to go to Router B when wanting to go to that subnet?
I am unclear on what the "Default Gateway" setting on each machine would be, or if it matters at all.  Typically that would be set to Router A when only 1 router exists on the network. But what about when there are 2?.

EDIT: Notice the WAN port on Router B is empty, that's because I want to avoid putting any connected subnets behind a NAT.
Comment: I'm not aware if such routing behaviour exists. However, you can have DHCP send routing info to clients, assuming you use DHCP. For devices that don't, you would configure the route to 10.5.1 on each client that requires access to that network ... though [IRDP](https://en.wikipedia.org/wiki/ICMP_Router_Discovery_Protocol) seems to be a thing, but how supported it is I have no idea
Comment: This is definitely possible. But it requires to at least have some general clues about how IP networking works.
Comment: right @Massimo that's why i'm struggling a bit, it's good to know it is possible.  Perhaps I will give it a try and see where I end up.  Can you think of any Caveats I should look out for ?
Comment: if a computer on 126.96.36.199/24 needs to access 10.5.1.0/24 (without traversing through router A) then it needs a route entry for 10.5.1.0/24 pointing to the 220.127.116.11/24 IP of Router B ... by the way, 126.96.36.199/24 is not a "private" subnet, for instance, 126.96.36.199 is `172-5-1-1.lightspeed.oshkwi.sbcglobal.net`
Comment: @JaromandaX Sorry about the subnets, it's just for illustration purposes i couldn't quickly come up with proper private subnet
Comment: @JaromandaX It's OK if it uses Router "A" for the purpose of lookup... as long as the rest of the actual traffic flows only through the Switch, then Router "B"..  Is that the case? Or will traffic go to Router "A" and then back into the switch then into Router "B" because that would make me sad :(
Comment: not sure what you mean by "lookup".
Comment: @JaromandaX as in the computer wanting to connect to camera, goes to Router "A" and asks "Hey, whats the route to X"? (lookup) Then, thereafter computer goes directly to Router B via the answer it was given.  From then on, theoretically you turn off Router A and the computer could still reach the cameras on Router B?
Answer: For clarity, let's assign Router A's inside interface 18.104.22.168 and give Router B 18.104.22.168.
Assuming SWITCH is strictly a layer 2 device, computers on 126.96.36.199/24 should have a default gateway to 220.127.116.11 [Router A] and a static route to find 10.5.1.0/24 via 126.96.36.199 [Router B].
Windows computers, for example, would run a command like the following:
route add -p 10.5.1.0 MASK 255.255.255.0 184.108.40.206 METRIC 10

Default gateway is shorthand for "what do I do with any traffic that isn't local and hasn't been explicitly routed?" The answer is almost always, "send it towards the Internet."
Many switches are layer 3 aware.  The routing would be easier to manage there.  If SWITCH can do vlans, Router B may not be adding much value.
Comment: @7wp a trunk port allows for crossing vlans where an access port does not.  That's the only reason I can see for traffic hairpinning in the current 1 router solution.  The switch is preventing computer and camera from interacting directly, but the router keeps sending the traffic back to the switch.  Please try enabling trunking on the computer's switch port, then continuous ping the camera while you unplug and plug in the router.
Comment: Thanks I'm educated.  Just wanted to let you know that SWITCH does support v-lans it's set up that way now.  But traffic still wants to go to ROUTER A first.  For example if I reboot ROUTER A, I lose connection to the cameras on the subnet.  Hence why I'm trying to introduce another router.
Comment: Is the computer on a trunked port or an access port?
Comment: Sorry @maurkov I don't know what a trunked port is, so probably not.
Comment: Interesting @Maurkov I'll give it a shot.
Comment: FYI @Maurkov that trunking idea didn't work.  It just made my cameras inaccessible completely.