Why does a zoo object sometimes have dimensions and sometimes doesn't?

Question: I am trying to figure out why zoo objects sometimes have dimensions and sometimes they don't. Suppose I have:
x.dates <-c(as.Date('2018-01-01'), as.Date('2018-01-02'))
x <- rnorm(2)
y <- rnorm(2)
z1 <- zoo(x, x.dates)
z2 <- zoo(y, x.dates)

Why does the following return NULL:
dim(z1)
dim(z2)

but the following HAS Dimensions:
dim(merge(z1, z2))

How can I tune/tweak this to make both cases have dimensions? i.e. both cases to behave consistently.
Comment: `x` and `y` do *not* have dimensions so there is no reason to expect that `z1` and `z2`  have dimensions.  As @Rich Scriven points out `zoo(cbind(x), x.dates)` has dimensions.
Comment: @RichScriven I could use `merge.zoo` and that has the same effect as `merge` so I don't think the fact that merge is converting it to a `data.frame` has any bearing on the issue.
Comment: `merge` will use `merge.zoo` for `zoo` objects. See `methods(merge)`
Comment: why the negative votes?
Answer: Not really sure what you're asking for here, but you can run cbind on your individual zoo vectors, then they will have dimensions and remain as zoo classed objects.
cbind(z1)
#                     z1
# 2018-01-01  0.18104641
# 2018-01-02 -0.08397933

cbind(z2)
#                   z2
# 2018-01-01 1.6893870
# 2018-01-02 0.3941877

class(cbind(z1))
# [1] "zoo"
class(cbind(z2))
# [1] "zoo"

Comment: That's exactly what I was looking for!


Relacionamento único entre duas tabelas

Question: Então, estou com essas tabelas: users, chat_rooms and chat_room_allowed_users.
users
    id
    ...

chat_rooms
    id
    key
    user_host
    ...

chat_room_allowed_users
    id
    room_key
    user_allowed
    ...

O que estou tentando fazer, é retornar todos os chat_rooms relacionados com o Auth::user(), seja ele o host de um canal e/ou sendo algum participante de outro(s) canal(is).
Eu sei que dá para retornar esse resultado usando as queries do Eloquent, mas para deixar mais prático, estou tentando fazer isso com apenas um relacionamento.
Por agora, estou usando dois relacionamentos distintos (Auth::user()->chat_rooms_hosted e Auth::user()->chat_rooms_allowed) e dando um merge entre elas antes de passar para a view.
class User {
    ...

    public function chat_rooms_hosted(){
        return $this->hasMany(ChatRoom::class, 'user_host', 'id');
    }

    public function chat_rooms_allowed(){
        return $this->belongsTo(ChatRoomUserAllowed::class, 'id', 'user_allowed');
    }
}

É possível fazer esse relacionamento ou compensa usar a query do Eloquent mesmo?
Exemplo figurado:
class User {
    ...

    public function chat_rooms(){
        // A = $this->hasMany(ChatRoom::class, 'user_host', 'id');
        // B = $this->belongsTo(ChatRoomUserAllowed::class, 'id', 'user_allowed);
        // relacionamento = uniãoEntre(A e B);
        // return relacionamento;
    }

Comment: Isto responde à sua pergunta? [Como usar o relacionamento hasmany no laravel 5.2?](https://pt.stackoverflow.com/questions/173966/como-usar-o-relacionamento-hasmany-no-laravel-5-2)
Comment: Na real... não muito. Minha intenção é unir 2 relacionamentos (que já funcionam de forma independente) em um único e retornar esse relacionamento.
Comment: é a mesma ideia Samuel Vasconcellos
Comment: Acabei optando pelo appending values to JSON e funcionou, achei mais prático. Aliás, obrigado pela sugestão ;)
Answer: Você poderia adicionar um atributo customizado e inserir essa lógica dentro dele.
Appending values to JSON
Ou simplesmente criar um método dentro do seu model User:
public function chats ()
{
     // Aqui você coloca toda a lógica e retorna o valor
}

Então é só chamar o método Auth::user()->chats()
Comment: Sua resposta pode ser melhorada adicionando informações fundamentais. Basta [edit] para adicionar mais detalhes, como citações ou documentação para que outras pessoas possam confirmar que sua resposta está correta. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).
Comment: Beleza, vou testar aqui! Nunca usei o Appending values. Valeu Lucas!

Relacionamento único entre duas tabelas


Envio de anexo em email PHPMailer

Question: estou com um problema neste código, pois quando envio é feito o envio das informações recebo o retorno = 1, porem o anexo não é enviado alguém pode me ajudar?
ENVIO.PHP

    $arquivoreal = $_FILES['arquivo'];
    $Nome = $_POST['Nome'];
    $CPF = $_POST['CPF'];

    //Configurações do email, ajustar conforme necessidade
    //====================================================
    $email_destinatario ="email@example.com"; // pode ser qualquer email que receberá as mensagens
    $email_reply = "Supervisão";
    $email_assunto = "Curriculo"; // Este será o assunto da mensagem
    //====================================================

    //Monta o Corpo da Mensagem
    //====================================================
    $email_conteudo = "
Envio de Curriculo [SITE]

$Nome CPF: $CPF gostaria de fazer parte do nosso quadro de funcionarios, por isso enviou o curriculo pelo site

                        (Curriculo em anexo)
";
    //====================================================

    //Enviando o email
    //====================================================
        // EnviaEmailCorandini(assunto,msg corpo do email,email,Nome Destinatario,Arquivo em anexo);
    $retorno = EnviaEmailCorandini($email_assunto,$email_conteudo,$email_destinatario,$email_reply,$arquivoreal);

    if($retorno == 1){
        header("Location:index.php");
    }else{
            echo "Falha ao enviar o email";
    }
}
}

PHPMailer/index.php
 require 'PHPMailerAutoload.php';

 function EnviaEmail($assunto,$msg,$EmailDestino,$NomeDestino,$NomeArquivo){

    $mail = new PHPMailer();
    $mail->setLanguage('pt');

    $mail->isSMTP();
    $mail->Host         = $host;
    $mail->SMTPAuth     = true;
    $mail->Username     = $user;
    $mail->Password     = $password;
    $mail->Port         = $port;
    $mail->SMTPSecure   = $secure;

    $mail->From     = $from;
    $mail->FromName = $fromName;
    $mail->addReplyTo($from,$fromName);

    $mail->addAddress($EmailDestino,$NomeDestino);
    $mail->isHTML(true);
    $mail->CharSet      = 'utf-8';
    $mail->WordWrap     = 70;
    $mail->Subject      =  $assunto;
    $mail->Body         = $msg;
    $mail->AddAttachment($NomeArquivo);
    $send = $mail->Send();

    if($send)
        return 1;
    else
        return 0;
    }

Comment: Ele está retornando um porque de fato o e-mail foi enviado. De um echo nesse $nomeArquivo e tente acessar o arquivo pelo navegador. Lembre-se que para o phpmailer anexar é necessário o caminho absoluto do arquivo.
Comment: A questão é confusa, você usa a classe EnviaEmailCorandini mas colou o código da classe EnviaEmail. Ali você tem o último parâmetro $NomeArquivo mas está enviado um Array $arquivoreal = $_FILES['arquivo'], se quiser só o nome do arquivo seria $_FILES['arquivo']['tmp_name'], faltou pesquisar o manual: http://php.net/manual/pt_BR/features.file-upload.post-method.php
Answer: Pela descrição do código você precisa enviar o nome do arquivo, alterando a seguinte linha:
$arquivoreal = $_FILES['arquivo']['tmp_name'];

So que assim o anexo vai com o nome temporário.
Você pode corrigir de duas formas:

Mover o arquivo para algum local temporário com o nome correto:
$tmp_dir = $path_parts = pathinfo($_FILES['tmp_name']);
$arquivoreal = $tmp_dir['dirname'] . '/' . $_FILES['name'];
move_uploaded_file( $_FILES['tmp_name'], $arquivoreal);

Após o envio é necessário remover o arquivo:
$retorno = EnviaEmailCorandini(...);
unlink($arquivoreal);

Ou classe EnviaMail, fazer uso do segundo parâmetro do método AddAttachment() como abaixo, mas para isso será necessário alterar a chamada a função:
// alterar a chamada
$retorno = EnviaEmailCorandini($email_assunto,$email_conteudo,$email_destinatario,$email_reply, $_FILES['arquivo']['tmp_name'], $_FILES['arquivo']['name']);
// alterar a definição da função
function EnviaEmail($assunto,$msg,$EmailDestino,$NomeDestino,$NomeArquivo, $NomeRealDoArquivo){
// alterar a inclusão do anexo
$mail->AddAttachment($NomeArquivo, $NomeRealDoArquivo);
Comment: Então, fiz desta forma e deu certo, porem vai como arquivo .tmp como eu poderia fazer para mandar o arquivo na mesma extensão e nome no qual foi "postado"
Comment: @MatheusSouza, editei a resposta para contemplar a mudança de nome do anexo.

Envio de anexo em email PHPMailer


How to build scoring model (scorecard) from logistic regression?

Question: I understand that you have to run the resulting regression line through the logistic function to get the predicted probability:
am.glm <- glm(am ~ hp + wt, data=mtcars, family=binomial)
newdata <- data.frame(hp=120, wt=2.8)
p1 <- predict(am.glm, newdata, type="response")
p2 <- 1/(1+exp(-(am.glm$coefficients[1] +
             am.glm$coefficients[2]*newdata[1,1] +
                 am.glm$coefficients[3]*newdata[1,2])))
p1 - p2
##            1
## 1.110223e-16

Now I want to build two scoring model with the aim in mind to be usable with a hand calculator only:

First model: I want to just take the two variables ($hp$, $wt$), multiply them by some factor and add them. The resulting number should be compared to a threshold number which then gives me the decision.
Second model: I want to have certain ranges of the two variables. Depending on the range the variable falls into I am given a number. At the end I simply add all numbers to arrive at my threshold number which again gives me the decision.

As an example from the area of credit scoring where these scorecards are used quite heavily (source: https://www.eflglobal.com/insights-sbbns-credit-risk-problem-loan-management-workshop/):

My question
How to go about and esp. how to transform the logistic regression coefficients to be able to build the two (or any of the two) models?
Perhaps you can even demonstrate the steps in R, making use of the above mtcars logistic regression.
Comment: (1) Express the threshold in log odds rather than probability. (2) You need to describe how that scorecard's arrived at. I suspect it's by fitting a different model to yours, in which the predictors are binned & coefficients estimated for each bin.
Comment: @Scortchi: Yeah, silly mistake, so it is $log(.5/(1-.5)) = log(1) = 0$
Comment: @Scortchi: So basically if one wants to have a probability of $.5$ the threshold is $exp(.5)/(1-exp(.5)) = -2.54$ ?
Comment: No - use the logit function, whose inverse is in your code above. The logit of 0.5 is 0.
Answer: The basic ideas are not that difficult:

First model: You just multiply the respective coefficients with the new data points and see whether the sum is bigger than the negative intercept (then am is 1)
Second model: You first bin the numerical variables into distinct intervals (with cut()) and then run the logistic regression again (dummy variables will be created automatically) . For new data points you check into which interval they would fall and add the resulting coefficients (if the interval is not present you assign 0). You again check whether the sum is bigger than the negative intercept (see first model above).

You can scale all the coefficients and the intercept by multiplying with a factor (e.g. it is quite popular to take 20/ln(2))
As an example consider the following case where we want to build a toy scoring model for predicting am from the mtcars dataset:
library(OneR) # for bin and eval_model function
mtcars_bin <- bin(mtcars)
m <- glm(am ~ hp + wt, data = mtcars_bin, family = binomial)
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
coefficients(m) #points for ranges
##   (Intercept)   hp(109,165]   hp(165,222]   hp(222,278]   hp(278,335]
##      21.30781      19.62427      19.91155      40.03050      62.28971
##  wt(2.3,3.08] wt(3.08,3.86] wt(3.86,4.64] wt(4.64,5.43]
##     -20.61467     -62.03146     -62.78544     -81.47841
prediction <- round(predict(m, type = 'response', mtcars_bin))
eval_model(prediction, mtcars_bin$am)
##
## Confusion matrix (absolute):
##           Actual
## Prediction  0  1 Sum
##        0   18  1  19
##        1    1 12  13
##        Sum 19 13  32
##
## Confusion matrix (relative):
##           Actual
## Prediction    0    1  Sum
##        0   0.56 0.03 0.59
##        1   0.03 0.38 0.41
##        Sum 0.59 0.41 1.00
##
## Accuracy:
## 0.9375 (30/32)
##
## Error rate:
## 0.0625 (2/32)
##
## Error rate reduction (vs. base rate):
## 0.8462 (p-value = 1.452e-05)
##
## different scaling
coefficients(m) * 20/log(2)
##   (Intercept)   hp(109,165]   hp(165,222]   hp(222,278]   hp(278,335]
##      614.8136      566.2367      574.5260     1155.0360     1797.3012
##  wt(2.3,3.08] wt(3.08,3.86] wt(3.86,4.64] wt(4.64,5.43]
##     -594.8136    -1789.8496    -1811.6048    -2350.9701

Obviously this model can be further improved by cutting the intervals differently, e.g. combining the ones which give comparable scores, rounding etc., but the general principle stays the same.


VSTS build error: non-whitespace before first tag

Question: VSTS Build definition is failing and I can't make heads or tails of this error...
C:\Windows\system32\chcp.com 65001
Active code page: 65001
Detected NuGet version 184.108.40.206 / 3.3.0
SYSTEMVSSCONNECTION exists true
Error: Non-whitespace before first tag.
Nuget Installer build step, Visual Studio Build build step
Are the build steps out of order? Am I not referencing the right file on the Nuget Installer step? The Nuget Installer calls for a nuget.config xml file but my .Net Core app houses its dependencies in a project.json file. Please let me know if I need to provide more information, or what's missing from the post that would make this easier to diagnose.
Answer: For .Net Core app, using dotnet-restore command to restore package. The dotnet restore command uses NuGet to restore dependencies as well as project-specific tools that are specified in the project.json file.
Add Command Line step to your build definition. (Tool: dotnet, Argument: restore, Working folder: [folder path, which contains the project.json file])

There is an article that can help you.
Comment: That's it! Thank you so much!
Comment: More fun. So that was a test project I created in order to play with build definitions. What tool do I need to use in order to build a dnx451 (or dnxcore50) app?
Comment: @SoloSheff For new question, it's better to create a new thread.


Getting Views Rows Data in Custom Module

Question: I dont know if im over thinking this but im not making much progress with my function. I am trying to get the values from views rows in my modules for example if I was to use $row->field_name inside of a view.tpl file then it would show the output of that row, except I am trying to do it in a module. Ultimately I am trying to render the image style of the 1st image that loads from the view. This is what I have so far.
function custom_module_views_pre_render(&$vars){
    if($vars->name == 'front_page'){
        $vars->result[0]->field_field_image[0]['rendered']['#image_style'] = 'front-page-scroll';
    }
}

Update 1: I've attached a image of what I am trying to do seeing how when I use preview(); execute(); or render(); it makes the function stop working, actually it makes the whole site stop working. If I cant get to the field view result count which counts the the number a current node is then I can say if($views->view_result_counter == 1) then render just that node. The function would look something like this.
function custom_module_views_pre_render(&$vars){
    $views = views_get_current_view('front_page', 'page');
    if($views->name == 'front_page'){
         if($views->views_result_counter == 1){
            $vars->result[0]->field_field_image[0]['rendered']['#image_style'] = 'front-page-scroll';
         }
    }
}

Here is a image of what I am trying to do, Now I currently have the 1st image rendering as I want it to but it keeps rendering the image of each page instead of it rendering one time only.

Now as for my view is there any reason why execute or render wouldnt work? this is what my view looks like.

any suggestions?
Comment: I see from your comment that you are using the [Infinite scroll](http://drupal.org/project/views_infinite_scroll) module, and from the image of your view, the [Masonry](http://drupal.org/project/masonry) module. Have you seen this [issue](http://drupal.org/node/1919110)? I am also having trouble understanding exactly what you are doing. In your image are you showing the start of the next page at the bottom? Is your module just changing the display of the first item in a page? Is each image a page? Are you trying to change the display of the first page? Could you expand your requirement?
Comment: I havent seen that post but I dont think it applies to this problem, basically what I am trying to do is render the very 1st image of the 1st page and no other images, right now when I do it, it renders the 1st image on every page instead of just the 1st one.
Answer: as this site is not about php programming I will not go very deep into this. but what you are probably looking for is http://api.drupal.org/api/views/views.module/function/views_get_view_result/7
to render the view use $view->render();
further reference: http://drupal.org/node/342132
Comment: Question about PHP are off topic, but answers with working code or roughed out code are always welcome and encouraged.
Comment: Thank you, Alhough it is php, I was looking more so for the right hook function to go about using.
Answer: You might be over thinking this. If you have working code, but the problem is that the code keeps on working, then the issue is to stop it from working again after it has done its job once.
The way to make a function aware if its previous iterations is to use a static variable. Try wrapping your working code with a static variable and test it like:
  // Only process one image.
  static $first_image_done = FALSE;
  if ( !$first_image_done ) {
    ...working code ...
    $first_image_done = TRUE;
  }

That way the function knows it has already processed the first image, and will skip the process on further iterations.
EDIT after time in chat:
The satic variable approach is not working because infinite scroll still works as a pager, and separate queries are being made for each page of output.
The current page position is controlled through the $pager (object) property of the $views object. The test for the first page can be accomplished as follows:
  $pager = $vars->pager;
  // Check for 'first page' condition
  if ( !isset($pager->current_page) || $pager->current_page == 0) {
     $vars->result[0]->field_field_image[0]['rendered']['#image_style'] = 'front-page-scroll';
  }

This should limit the image resizing to the first page of the view.
Comment: I wish i was over thinking it but this simply isnt the case, I tried using static to make the function only execute once and it executes every time a new page is loaded, this time I tried your version as well and it didn't work. Any other suggestions?
Comment: If the static variable is not working, then the program is being bootstrapped between pages. The view must still keep track of its pagination. Try placing `watchdog('custom module' '' . print_r($vars) . '')` within your code. Load two pages and look at your log to see how the view tracks its location. Then you know which property to test.
Comment: Thanks for replying, Ive actually tried this a few times and in the data its not printing out the views results that are being displayed on screen like the image field and the result counter, its prints out the data of the nodes and the settings of the views, but I cant specify which node to render if the latest node is always being changed. Any other suggestions?
Comment: If you check out the [API](http://api.drupal.org/api/views/views.api.php/function/hook_views_pre_render/7) your function would be better written as `function custom_module_views_pre_render(&$view)` and invoking **views_get_current_view** should not be unnecessary. I also assumed that the image you present above is what you are getting, perhaps mistakenly. I think we are still working at cross purpose. Perhaps we can move this to chat and try to drill down in the issue.
Comment: sure, i am in the drupal chat http://chat.stackexchange.com/rooms/327/drupal-answers
Answer: I think you are mixing the hook_views_pre_render with a themeing function.
In the hook, there is no $vars, you get access directly to the $view - the entire view, not only a row. So you will be able to do something along the lines of:
function YOURMOD_views_pre_render($view) {
  if ($view->name == 'YOURVIEW'
    && $view->current_display == 'YOUR_DISPLAY'
    && $view->query->pager->current_page == 0) {
    $row = $view->result[0];
    $row->field_YOUR_image[0]['rendered']['file']['#style_name'] = 'DIFFERENT_style';
  }
}

This way you just change the image style of the image and you can let drupal do the rest for you :).
Comment: Your function is pretty much the same as the one I currently have. It renders the 1st image of every page instead of just rendering the image on the 1st page which is what I am trying to achieve here.
Comment: sorry :) then you could check for `current_page` i guess (edited my answer above, not sure if its 1 or 0).  I just wanted to stress out you dont have to `views_get_current_view` - you have the view already :)
Comment: one more edit, this time it should really work :) use `$view->query->pager->current_page` instead.
Answer: I'm not exactly entirely following why you're working in your module.
Have you tried using 2 displays in your View? 1 regular display with a limit of 1 row, and an attachment display, displaying all results, but with an offset of 1, so that it skips the 1st row.
You can then change the Image preset on the regular View, but keep using thumbnail preset in the attachment View.
Or - I can't try it out right now - isn't there a counter somewhere in the $vars variable that contains what page you're on? If so, you can only intercept & change the row when you're on the 1st page
Comment: ive, tried those and your idea about the counter is a good idea however it wont work since the pagination is controlled by using infinite scroll views module


Circular statistics polar coordinates data in R

Question: I am very much new to dealing with this type of data (polar coordinates!) and it would be great if someone could help me out.
My data come from an experiment in which I had 66 different pairs of bacterial strains of which I wanted to study the interactions. In order to study the effect of each strain on the other I compared the abundance of each strain when it was alone if compared to when it was paired with the other strain. So for example I calculated the effect of strain A on strain B and the effect of strain B on strain A. This gave me a point with the coordinates corresponding to the effect of A on B and B on A for each of my pairs. I converted these data into polar coordinates and I obtained this type of dataset:
treatment   radius  theta
1   5.346605488 -53.42975695
1   4.781032074 -48.89982034
1   3.408335845 -45.32998294
1   1.594707376 -30.28159102
1   4.995105439 -47.46835867
2   2.182870308 -69.97527886
2   1.376227293 -82.86544789
2   1.996722475 -81.86548945
2   4.087804099 -89.21073708
2   5.665053864 -71.35803445
3   7.655837189 -80.95798067
3   2.689244996 -69.29463991
3   3.286408329 -88.82404786
3   2.372054818 -77.3849227
3   2.401522618 -73.50042193
4   1.957466401 -86.72672854
4   1.094525546 -78.37493516
4   10.39191001 -79.39487844
4   2.81619011  -55.33935439
4   2.768492768 -83.27824524
5   2.960390522 -83.01541004
5   8.667030807 -85.17497452
5   3.171949653 -85.45600376
5   1.261198824 -52.24672527
6   4.339405038 -55.69025966
6   4.66365939  -59.88091407
6   3.030254841 -67.97377372
6   2.353734464 -61.28096828
6   1.046854294 -32.56853164
7   6.588535649 -85.19534077
7   4.198267055 -62.49718747
7   9.515127289 -82.14133253
7   1.261910096 -63.06872102
8   1.233816215 -47.98689163
8   0.855861695 -59.11215779
8   2.397212184 -80.04916414
8   5.404919495 -81.97150648
9   2.688518935 -61.30467223
9   3.966309178 -69.84947341
9   2.432244246 -68.81819762
9   3.43740085  -55.16458675
9   0.997997694 -71.83281473
10  1.683307917 -42.95687293
10  0.820014414 -80.66580717
10  1.290828883 -83.42955371
10  1.465916446 -79.83509581
10  2.302205529 -86.0459686
11  5.308080093 -73.1243189
11  1.520872026 -88.34749575
11  6.454746366 -76.58588688
11  4.78895044  -86.06747421
11  3.257530999 -70.74498431
12  2.900747649 -31.43851989
12  7.20087566  -74.40240034
12  3.506042507 -45.99152964
12  4.185267099 -50.23151617
12  7.050000726 -53.81709571
13  1.384155427 -58.09424224
13  5.053845739 -71.55457806
13  4.735068509 -84.72403735
13  2.680085474 -79.49351393
13  3.14974405  -74.8777932
14  2.948549954 -62.8023809
14  4.127180564 -80.86173441
14  3.262360907 -50.07616196
14  1.696876591 -22.29395164
14  2.729769567 -74.38232362
15  1.2955073   -81.4032846
15  3.527414889 -69.86791141
15  2.784319251 -52.20531863
15  2.612819797 -36.47272335
15  1.842054162 -66.66059134
16  1.840787298 -72.57479843
16  6.8643205   -73.09682469
16  2.654893118 -83.12032406
16  0.966705258 17.92145538
17  2.486480981 -72.75194085
17  1.743896498 -6.866658211
17  1.67501909  -74.00470613
17  0.257437514 9.570402798
18  0.713744723 -89.85444042
18  2.66346159  -69.89457024
18  0.643897066 -46.87018048
18  3.227695962 -82.37095963
18  0.927908178 -81.8102089
19  1.419620687 -27.19633419
19  1.235456006 -48.95104975
19  2.341406093 -59.51153717
19  1.707978572 -42.20335283
20  2.64762226  -62.26528889
20  3.999628573 -80.97346898
20  1.343423811 -50.26800644
21  0.550719617 -21.44166023
21  0.998411135 -53.46021735
21  4.645733848 -89.46562929
21  1.184768725 -25.64563336
22  1.236062405 -48.25907998
22  1.62781082  26.24924794
22  0.482285052 -49.13934417
22  2.456873132 -84.42483449
22  0.633405353 -34.76443981
23  2.501732027 -77.5145514
23  1.553947876 -47.03314351
23  1.904313581 -20.48864195
23  1.417719503 -18.97532658
23  3.359978244 -65.98810342
24  1.841779957 -57.82423336
24  1.944168995 -83.72435556
24  1.723335563 -86.43854809
24  2.245607465 -18.05044439
24  1.71018206  -84.01572549
25  3.160911024 -25.89542425
25  1.884353194 -88.84667861
25  1.657340195 -57.91688887
25  3.244710974 -30.41742685
25  3.047461157 -57.65594863
26  4.142434092 -79.10775556
26  4.70885302  -84.38144988
26  3.871701704 -77.37403595
26  1.815104811 -80.07878221
26  5.756489628 -87.15817329
27  1.760229703 -23.71849938
27  1.619479137 -89.41313301
27  0.949475302 -52.16437553
27  0.566431907 -2.634253126
27  1.67229617  -78.27332119
28  1.327650364 47.90821531
28  1.740336854 -44.01261513
28  1.321542483 -46.98765031
28  1.333688986 11.19965187
28  1.419719047 -69.08867896
29  0.648536009 -48.88086991
29  2.112819841 -84.22410986
29  1.088339926 -60.49238911
29  0.446947519 -1.971477582
29  0.726254374 17.38780438
30  0.610318812 12.73868599
30  1.011102767 -18.69664112
30  2.357970381 83.45729602
30  3.075981632 -86.54599794
30  4.399281053 -79.66361213
31  9.682561002 -73.23143687
31  6.486798742 -51.40872403
31  4.744326098 -57.84898633
31  10.94679131 -49.77486765
31  6.288273977 -53.54395613
32  2.422406181 -66.66946557
32  0.920208692 -50.71386553
32  2.318672106 -30.51639453
32  1.18158908  -65.28441973
33  0.770702488 -34.5071325
33  4.809790703 -87.88054507
33  1.243396123 -57.43726582
33  0.826032874 -63.68191021
33  2.379570873 -78.77666128
34  4.58813844  -57.16272711
34  3.240458513 -74.18252573
34  1.450322312 -46.82466405
34  5.097538168 -88.4063221
34  0.933642832 -20.56162779
35  6.494675784 -85.81998773
35  2.982113314 -83.96232252
35  3.209362461 -88.53565823
36  1.101045576 -63.44748768
36  2.18134314  -79.1625091
36  3.329661735 -88.18964925
36  2.110430927 -87.22933857
36  3.124463519 -81.17945818
37  2.256008327 -88.78732993
37  1.311453668 -74.55941719
37  3.458028215 -58.63737495
37  2.287683009 -63.59969694
37  3.089712989 -50.56807704
38  1.164101757 -84.99593698
38  1.227273765 -74.89875991
38  2.568166667 79.64657422
38  0.717633728 -19.13324987
38  0.466430262 -87.88375091
39  2.619934245 -57.70555911
39  4.505659844 -76.79125763
39  7.912571121 -48.30617156
39  3.936037923 -64.58813369
39  4.71978189  -42.52477656
40  6.26191457  -84.24228913
40  5.672705474 -89.53114846
40  1.791731701 -33.36207675
40  3.379644282 -69.43863361
40  1.563490233 -51.96221695
41  1.120633049 67.59124584
41  3.851234728 -54.95557743
41  3.992934669 -64.04201801
41  3.963263793 -83.83257337
41  6.285734806 -58.94235124
42  1.037265768 -56.39585703
42  0.702067455 -78.28956554
42  1.874208904 -73.25338047
42  2.683350538 -63.40789813
42  0.822052527 -76.00088947
43  2.071759974 -78.17313857
43  2.689560915 -88.73055479
43  0.703831415 -62.30962246
43  2.341558274 -83.86680849
43  1.595247369 -80.6598101
44  1.047233184 -84.42259527
44  2.543651769 -86.51355692
44  1.577552784 -73.91302464
44  1.689553615 -74.79168199
45  0.99484303  -80.19967507
45  1.044169017 -43.04384197
45  1.164074471 -49.08276664
45  0.689804286 -44.37561371
46  1.083862964 -64.15217472
46  2.626979422 -88.64235148
46  2.454247469 -47.05093786
46  2.77983216  -89.26329048
46  2.636957485 -81.03972204
47  0.413704382 -56.55826312
47  1.145326012 -84.64626702
47  2.038399115 -81.85662372
47  2.253731222 -86.41566587
47  1.3133469   64.52243412
48  3.403932556 -80.36071198
48  2.04929866  -70.47795907
48  2.274349863 -77.81310408
48  0.13593279  46.38254256
48  0.702184063 -3.612045051
49  0.906223302 -78.31476515
49  0.554538317 50.33543382
49  0.089680453 23.33095578
49  2.2831634   -67.13247686
49  1.627864676 -72.52132829
50  0.34672496  66.11871934
50  1.160451029 -66.89054777
50  1.760678964 -58.30762395
50  1.254324633 -41.19404821
50  1.730734607 -67.09376641
51  0.842785032 81.82395052
51  1.974954473 -80.682135
51  0.865344327 -47.07894474
51  0.909533784 -76.02511259
51  1.685635709 78.20115372
52  2.392503081 -79.74664961
52  1.946110615 -70.94946049
52  8.574258316 -42.65386143
52  2.538714806 -48.03630574
52  2.529050979 -29.92328407
53  2.866661501 -78.54261642
53  2.590927316 -75.08833379
53  5.90479778  -52.57345606
53  5.799716577 -48.23386105
53  2.07192245  -88.00474074
54  1.680713598 -73.63319735
54  2.557497408 -67.94294466
54  2.393764255 -56.19194117
54  6.026774503 -82.18275762
54  0.788317053 -30.6404756
55  1.859034516 -77.09826262
55  3.817813613 -69.26816285
55  3.42856831  -71.12750351
55  2.454971668 -61.22096633
55  1.618509495 -63.11739719
56  4.582911236 -31.04536129
56  3.997256178 -53.91325239
56  1.219757833 -77.19780486
56  7.377663053 -76.85745566
56  2.881431405 -68.73534505
57  2.004327103 -74.8284809
57  2.748344386 -71.30903296
57  2.460209206 -69.62695585
57  1.775560107 -80.3723268
57  2.645612131 -89.09829133
58  1.54991856  -62.44032153
58  6.534223736 -85.84648469
58  0.422375885 62.16515901
58  0.610233226 -27.29862046
58  3.393479727 -56.14377871
59  1.601596058 -64.70208698
59  1.319995497 -74.36073404
59  0.383925829 -45.27272566
59  0.770918761 -14.94572655
59  2.768653593 -88.55860395
60  3.100129667 -79.77906075
60  0.754369481 -56.41040781
60  1.063078742 -38.06663906
60  4.430727193 -35.69757344
60  1.151375695 -58.31667216
61  0.222873197 56.11287704
61  0.693297704 -10.64168064
61  4.895399027 -80.48905585
61  1.476161129 -79.09424876
61  2.362055223 -82.82717397
62  0.271796128 -77.99977538
62  2.712343601 -83.45960915
62  2.640394011 -79.62228636
62  2.044795801 -65.63167684
62  0.977870455 -79.87283982
63  2.093999943 -34.17579722
63  2.066850888 -58.30139095
63  1.919951867 -72.04915327
63  1.847203007 -53.3080848
63  2.523697396 -86.41516485
64  3.396946374 -76.88253208
64  1.502111371 -56.46177994
64  3.447925893 -83.55087526
64  1.436601103 -78.3262211
65  0.973834501 30.49055
65  1.047860828 22.48877392
65  1.493635682 -5.403700435
65  1.468349931 27.39802239
65  3.062567844 -37.09222845
66  1.172876541 83.48805632
66  1.35911911  -68.34950195
66  0.828509975 3.070100175
66  1.171217644 -37.19274186
66  1.914431983 -35.89376613

The idea is that the radius gives me a measure of the intensity of the interaction between the two strains while the angle (theta) gives me an idea of the type of the interaction ongoing between the two strains (depending on where the angle falls, corresponding to the cartesian plot quadrants, e.g. if it falls in the quadrant (-,-) it means that the interaction is mutual inhibition between the two strains).
I would like to do statistics to have a measure of the significance of the interactions between each strain. I thought I could determine if, for each treatment and across replicates, the distance from centre measure (radius) and the angle measure (theta) are significant (i.e. significantly different from 0). I am aware of the package "circular" but I am not sure of how to use it/which test could be useful for my case.
Any suggestion (also reading material!) would be very useful.
Comment: Maybe you need to explain a bit more the conversion and why you make it. It seems to be some sort of measure of the type of symbiose (mutualism: both positive, competition: both negative, or parasitism: one negative the other positive). I can see this as represented as circular coordinates. However, there seems to be ambiguity in the angle. I guess that you convert the Cartesian X,Y (the assymetric effects/influences of strain A and B on each other) into polar coordinates, but how do you determine which is X and which is Y? Do you have the same strain in the same role/axis each time?
Comment: You might also do the statistics in Cartesian coordinates, not? Why the conversion to polar coordinates?
Comment: You have both directions (A on B and B on A) in the plot, but which direction do you select for the x-axis and the y-axis?
Comment: I get the idea of the polar coordinates, that this is a way to express the interaction in terms of alternatives parameters, but what is the idea of the *"I would like to do statistics to have a measure of the significance of the interactions"* and why would you use these transformed coordinates for this (unspecified) significance test? It is unclear what sort of statistics you want to do.
Comment: Did you analyze 12 different strains which can form 66 pairs? I have the idea that in that case the 'a on b' and 'b on a' is being randomly mixed up. Depending on which strain is a or which strain is b you will get a different angle. (your data, with angle between -90 and +90 shows never a negative effect on the x-axis, why is that?)
Comment: @SextusEmpiricus Thanks for your comments. When I obtain and plot my cartesian (x,y) coordinates I have a symmetric plot in that I have both directions (A on B and B on A or B on A and A on B). There I select only one 'side' of symmetry and I continue by converting the data into polar coordinates (r, theta). I am interested into looking at polar coordinates in that (contrary to the cartesian) they give me two measures that I can directly link to the magnitude of the interaction (r) and the 'nature' of the interaction (theta).
Comment: The idea would be then to have a measure of the significance of the interactions using based on these two parameters (r and theta).
Comment: There is possibly an ambiguity here. Does interactions describe the outcome you are measuring or is it referring to interaction terms in a model?  Out of context "significance of interactions" usually refers to the second.
Answer: You may have many more data points, but scrutiny of a quick plot suggests

The observed range of angles is very limited, which often implies that you don't really need circular statistics. It is not even given that angle is the best way to record direction: sine or cosine may be closer to the underlying problem. Some kind of regression on angle or sine or cosine may suffice, with perhaps parameterisation so that $-90^\circ$ defines an intercept. (Perhaps you should just add $90^\circ$.)

There may well be hard limits in practice on what angles are possible or likely, and if so knowing them is very important to guide what makes scientific and statistical science.

The question of whether radius is significantly different from zero is hard to understand. First off, whatever is called a radius is usually a positive quantity, and if your definition implies otherwise, please explain. Second off, all reported values in the example are positive, so a significance test appears pointless for that reason. Perhaps you mean something more like "are radius and angle related?" to which the answer appears to be yes. Assuming that radius must be positive, analysis in terms of its logarithm seems indicated to me.

It makes quite a difference to analysis whether the angle is in some sense given and the radius is the outcome to be explained (which with problems like this is often true) -- or the opposite -- or neither.

Given the small subsamples I have not attempted an analysis in terms of treatments but the plot suggests that (e.g.) treatment 1 at least is quite distinctive.

Good statistical advice is very hard to give with no context whatsoever on what the numbers represent (other than something in polar coordinates).
EDIT Given more information and the full dataset, I can try a little more.
Disclaimer. I don't understand the science here and I don't even understand what kind of statistical problem this is. So why say more? I have some experience with circular data, which many statistical people don't have at all, so perhaps something a little helpful can be said.
The full dataset is 315 observations on 66 treatments, the latter represented by 5 observations in most instances, but only 3 or 4 in some (thus that's why not 330).
I can readily imagine that this represents a great deal of hard experimental work, but unfortunately from a statistical point of view 3, 4 or 5 observations is a very small sub-sample size for saying much reliably about individual treatments.
Circular plots may seem natural given the outcome space, but there can be a chicken and egg question that you have to look at several before you can think easily about any one (unless perhaps you already have some experience of thinking in and about that space, as is often true of compass direction).
That aside, I have found that linear plots can be very helpful too, which runs a little contrary to the advice in circular statistics texts and reviews.
A plot of the full data shows that they too seem limited, but now to half the circle. Is there any sense in which $90^\circ = -90^\circ$, because that would be an important detail? It affects what kind of test might make sense, but "typical" theta, however measured, is a long way from zero.
Another plot plots all of the data repeatedly, but a little arbitrarily picks out 4 treatments as extreme in either median or median absolute deviation on radius, theta or both. That's cherry-picking and nothing to do any formal testing.
As before, logarithmic scale for radius might help.
Comment: Thank you very much for your answer. I tried to edit the question providing more insights about my experimental design and where the data come from. Maybe the idea of testing for difference from 0 is not very good as you pointed out... I was trying to see if there was a way to test to distinguish between significant and non significant interactions!
Comment: Thanks for the further information, which unfortunately doesn't take me much further. Someone else may be able to help.
Comment: However, from one hint in your added details, it seems that the sample data are possibly misleading and the data can cover a much wider range and may fall into any quadrant. As your full data are not much larger, posting them all might help.
Comment: I added the entire table!
Answer: It is unclear what sort of statistical analysis you are doing, but you will most likely not need to bother yourself with circular statistics like circular distributions. This is because you are using an angle to express/illustrate the effects, but the angle is not an underlying mechanism in the distribution of the observations.

In the plot below you have the data in cartesian coordinates. The first six interactions are colored to give an impression of the variation within a single group.

You can see that the treatments have a large variation in magnitude but cluster around a particular angle. So indeed this conversion to angle is good and seems a simple way to categorize and quantify and compare the symbiosis.
Alternatively, you could assume a distribution of the error distribution of the points that has a correlation between the two axes, if the effect of 'a on b' is low/high, then this is also for the effect of 'b on a'. But this will mean that you have to deal with correlated errors. The conversion to polar coordinates seems to deal easily and naturally with this issue.

You do not need circular statistics.

The nature of the distribution of the angle is not such that the errors warp around. The variation in the angle for a specific treatment is only small.

The mechanism that determines the symbiosis is also not relating to the angle and something circular.
You have the different strains that have some coefficient of interaction/effect 'a on b' and 'b on a'. These two coefficients (let's call them $\beta_1$ and $\beta_2$) may vary somewhat (due to all kinds of measurement errors or variations in the experiment), and the magnitude of the overall interaction $\beta_m$ may vary (e.g. different times of incubation, treatment, temperature, or other factors that might influence the magnitude).
This gives you a simplistic model of the two effects $\beta_1 \cdot \beta_m$ and $\beta_2 \cdot \beta_m$. The errors/variations are not creating a circular effect. For random increases in the coefficients (which might add up), you do not get the aspect that you return to the same point.
Comparison: Something circular is an arrow pointing in some direction on a plane (imagine for instance the arrows/hands on a clock). If the arrow is randomly turned in some direction then multiple additions towards the same direction might bring the arrow/hand back to the original place. You do not have this behavior. If there are some effects in your experiment that cause fluctuations in the coefficients of the model $\beta_1$, $\beta_2$ then you do not get the effect that multiple additions in the same direction are gonna bring the angle of the effect back to the original position.
Comment: (+1) This is I guess much closer than mine to the OP's underlying problem. A comment and a question: I find my plot a bit clearer (surprise). Where does the colour coding come from?


Get a unique list (by key) from a list-in-list

Question: I have a list of requests. Each request has many approvers. I want to go through all the requests and their approvers and get a list of unique approvers and their requests.
Here are sample models:
var requestsToProcess = await GetBatchOfApprovedRequestsAsyn(); // new List<RequestModel>();

public class RequestModel
{
    public RequestModel()
    {
        ApproversList = new List<RequestApproverModel>();
    }

    public long   Id          { get; set; } // Key
    public string Brief       { get; set; }
    public string Description { get; set; }

    public List<RequestApproverModel> ApproversList { get; set; }
}

public class RequestApproverModel
{
    public string Email       { get; set; } // Key
    public string FullName    { get; set; }
}

I know how to get unique tuple from a list but don't understand if the target list is on an element of another list.
Comment: OP: I would suggest that you first flatten the structure (perhaps using `.SelectMany`) such that you have a Approver/Request combination object. Then you can group by the approver to get all requests by their approvers.
Comment: Does this answer your question? [Unique list of items using LINQ](https://stackoverflow.com/questions/3186818/unique-list-of-items-using-linq)
Comment: @Kraego Do you think it does?
Comment: @kraego, for a 0-level list, I already know how to extract my required tuple. But my target list is at depth level 2
Answer: Basically the premise, is flatten and project, then groupby, then optionally project again.
Given
var requests= new List<RequestModel>()
{
   new()
   {
      Id = 1,
      ApproversList = new List<RequestApproverModel>()
      {
         new(){Email = "bob"},
         new(){Email = "dole"}
      }
   },
   new()
   {
      Id = 2,
      ApproversList = new List<RequestApproverModel>()
      {
         new(){Email = "bob"},
         new(){Email = "blerg"}
      }
   }
};

Example
var results  =requests.SelectMany(request =>
      request.ApproversList,
      (request, approver) => new {request, approver})
   .GroupBy(x => x.approver.Email )
   .Select(x => new { Approver = x.Key, Requests = x.Select(y => y.request).ToList() });

foreach (var item in results)
{
   Console.WriteLine(item.Approver);
   foreach (var request in item.Requests)
      Console.WriteLine(" " + request.Id);
}

Output
bob
 1
 2
dole
 1
blerg
 2

Answer: The two complementary methods you need from LINQ are SelectMany, which unpacks a list-of-lists to a list, and GroupBy, which packs a list to a list-of-lists (you need to go from a-of-b to b-of-a)
var result = someRequestModels
  .SelectMany(rm => rm.ApproversList, (rm, ram) => new { RM = rm, RamEmail = ram.Email })
  .GroupBy(at => at.RamEmail, at => at.RM);

The SelectMany is like a nested pair of foreach
foreach(var rm in someRequestModels)
  foreach(var ram in rm.ApproversList)
    flatlist.Add(new { rm, ram});

This has turned the list of lists into a single list, repeating the RequestModel over and over per RequestApproverModel. You can then run a GroupBy of approver Email which takes every unique email in the flattened list and puts together a list of list of RequestModels. In non LINQ pseudocode it'd look something like:
foreach(var rmRamPair In flatlist)
  grouping[rmRamPair.Email].Add(rmRamPair.Rm);

This produces an IGrouping which is something like a list of lists, where each entry has a Key, a string of the approver's email and is an enumerable of all the requestmodels they have, so eg
foreach(var x in result){
  Console.WriteLine($"approver with email of {x.Key} has cases:";

  foreach(var rm in x)
    Console.WriteLine($"id is '{rm.Id}' and Brief is '{rm.Brief}'");

}

If it makes you more comfortable, you can call ToDictionary(x => x.Key, x => x.ToList()) on the result and you'll get a Dictionary<string, List<RequestModel>> out, the email being the key and and list of requestmodels being the value
If you want the whole RequestApproverModel, not just the email it might be a bit more tricky. It's easy if you've reused instances of RAM so if there is literally only one object in memory that is "email@example.com" and that object is present on a couple of different requests:
var ram = new RequestApproverModel{ Email = "email@example.com" };

var r1 = new RequestModel();
r1.ApproversList.Add(ram);

var r2 = new RequestModel();
r2.ApproversList.Add(ram);

Here the instance is the same one; you can just group by it instead of the email.
If you've ended up with objects that look the same but are at different memory addresses:
var r1 = new RequestModel();
r1.ApproversList.Add(new RequestApproverModel{ Email = "firstname.lastname@example.com" });

var r2 = new RequestModel();
r2.ApproversList.Add(new RequestApproverModel{ Email = "email@example.com" });

Then the standard implementation of Equals and GetHashcode(inherited from object) is useless because it's based on the memory stress where the instances live.
Your RequestModel class will instead need to implement Equals and GetHashcode that report equality based on Email, otherwise grouping by the whole RequestModel won't work out


Proving an infinite product formula

Question: I have found this formula and I am trying to prove it , but I have not any idea how to deal with it:
$$e^{ax}-e^{bx} = x(a-b)\exp\left[\frac{a+b}{2}x\right]\prod_{i=1}^{\infty}\left[1+\frac{(a-b)^2x^2}{2k^2\pi^{2}}\right] $$
It's too complicated for me, any suggestions ?
Answer: We have the following infinite product representation for $\sinh\,z$:
$$\frac{\sinh\,z}{z}=\prod_{k=1}^\infty\left(1+\frac{z^2}{k^2\pi^2}\right)$$
Comparing this with
$$e^{ax}-e^{bx} = x(a-b)\exp\left[\frac{a+b}{2}x\right]\prod_{i=1}^{\infty}\left[1+\frac{(a-b)^2x^2}{2k^2\pi^{2}}\right]$$
we find that
$$\prod_{i=1}^{\infty}\left[1+\frac{(a-b)^2x^2}{2k^2\pi^{2}}\right]=\frac{\sinh\frac{x(a-b)}{\sqrt 2}}{\frac{x(a-b)}{\sqrt 2}}$$
Use that $\sinh\,z=\frac{\exp\,z-\exp(-z)}{2}$ to prove/disprove your equation.
Comment: it's clear , thanks for your help .
Comment: Prigmin, there's a check mark next to Yuval's answer or mine that you can click if you're happy with any of them.
Comment: Yes,I've already do that . Thanks .
Answer: This is the famous sine product formula in disguise. See for example this writeup.
Comment: A good answer.  Unless, of course, the next step is the USE this formula to prove the sine product formula...

Proving an infinite product formula


Query for email address already existing

Question: I want to customise registration form action in my drupal8 site.I want to check email address is already existing.I have tried with different queries.But not worked.Can anyone to help me to solve this issue?
Comment: Can you post what you've done? Are you modifying the existing form, or trying to create a new registration form from scratch? As Alex mentioned, the default registration form already handles this for you.
Comment: @salu Let us know what you're trying and what you have done till now to achieve this.
Comment: I want to validate default registration form in drupal8.I added a custom ajax handler to validating the form.Because:
1) A user registering with already existing email id.
2)Then no validation message such as "This email id is already exsiting" will be shown to the user.And user can submit the form.
3)Then user will get an email like "Registration is unsuccesful because emai id is already existing".
What i did now is :
Answer: Use this code to check if there is a user with provided email.
<code>$account = user_load_by_mail($email);

if ($account) {
  // Do something.
  $form_state->setError(....
}
</code>
Besides, as I know in standard registration form there is already such validation.
Comment: Thanks for your reply.I have tried this in my custom module.But it is not working.
Comment: Yes..but i want to customise the things as well.When a user register with email id,whether email id exist or not,user will get the email regarding duplication of email id.
Answer: As pointed out in the comments the email uniqueness is already checked by default.
See core/modules/user/src/Entity/User.php
<code>$fields['mail'] = BaseFieldDefinition::create('email')
      ->setLabel(t('Email'))
      ->setDescription(t('The email of this user.'))
      ->setDefaultValue('')
      ->addConstraint('UserMailUnique')
      ->addConstraint('UserMailRequired')
      ->addConstraint('ProtectedUserField');
</code>
However, you should be able to create your own validation constraint.
First, implement hook_entity_bundle_field_info_alter()
<code>/**
 * Implements hook_entity_bundle_field_info_alter().
 */
function mymodule_entity_bundle_field_info_alter(&$fields, EntityTypeInterface $entity_type, $bundle) {

  if ($entity_type->id() === 'user') {
    $fields['email']->addConstraint('MyConstraint');
  }
}
</code>
Then your classes
<code><?php

namespace Drupal\mymodule\Plugin\Validation\Constraint;

use Symfony\Component\Validator\Constraint;

/**
 * My Constraint.
 *
 * @Constraint(
 *   id = "MyConstraint",
 *   label = @Translation("Check My Constraint"),
 * )
 */
class MyConstraint extends Constraint {

  public $message = 'My message @email';

}
</code>
And
<code>    <?php
namespace Drupal\mymodule\Plugin\Validation\Constraint;

    use Symfony\Component\Validator\Constraint;
    use Symfony\Component\Validator\ConstraintValidator;

    /**
     * MyConstraintsValidator class.
     */
    class MyConstraintsValidator extends ConstraintValidator {

      /**
       * Checks if the passed value is valid.
       */
      public function validate($value, Constraint $constraint) {

        $this->context->addViolation($constraint->message, ['@email' => 'foo']);
      }
    }
</code>
I have not tested the code above but should get you most of the way there.


understanding how imports work in solidity

Question: I am a beginner and trying to understand imports, especially in solidity. Say for example I import a contract from github to my smart contract and submit it to the blockchain, I am assuming that even if the github repository changes, the smart contract will stay as it was at the time of import and valid?
Secondly if I have a bunch of files in my local directory and import them into a main contract and then submit the main contract with the imports to the blockchain, will that smart contract work fine on the main net?
Apologies if this is a noob question lol, Thanks!
Answer: Basically, when you import a Github contract, it is the same as if you copy/paste that contract into a new file and simply import that file into your main contract. So when you deploy the smart contract think it as if the compiler mixed those contracts with the state they had at the moment of deployment, so any changes made to any of those contracts won't change the deployed code, as smart contracts are nearly immutable.
As regards the second question, it will work fine as long as all the logic is correct.


How do I get the List of Role and Number of users in them asp.net mvc

Question: Please how do I get the list of roles, along with the number of users having the role? something like this
I have tried this
var users = allusers.Where(x=>x.Roles.Select(role => role.Name).Contains("User")).count;
but this is just for one role. I need it for all the roles, and when a new role is added in the db, it should also add to the list.
Thanks
Comment: You need a `.GroupBy()` clause (on the `Name` field) and `.Sum()` the results of each group.
Answer: I know this question is over a year old, but here is an update in ASP Core 2.2.
This code runs on a PageModel, and things are getting simpler :)
<code>//Creation of class
public class RolesModel : PageModel
{
    private readonly UserManager<IdentityUser> _userManager;
    private readonly RoleManager<IdentityRole> _roleManager;
    private readonly ILogger<RolesModel> _logger;

    public RolesModel(
        UserManager<IdentityUser> userManager,
        RoleManager<IdentityRole> roleManager,
        ILogger<RolesModel> logger)
    {
        _userManager = userManager;
        _roleManager = roleManager;
        _logger = logger;
    }

//(...)
//Now check in some class

public async Task<IActionResult> OnGetAsync()
{
    var RolesList = _roleManager.Roles.OrderBy(x => x.Name).ToList();

    foreach (var role in RolesList)
    {
        var RolesUserlist = await _userManager.GetUsersInRoleAsync(role.Name);
        _logger.LogInformation($"Role {role.Name} has {RolesUserlist.Count} users");
    }
}
</code>
Cheers
Answer: Following code will be helpful to you.
<code>var  result = ( from r in userManager.UserRoles
                join u in userManager.Users on r.UserId equals u.Id
                group  new { r, u } by new { r.RoleId } into grp
                select new { name = grp.FirstOrDefault().r.Name, count=grp.Count()}).ToList();
</code>
Comment: Thanks @Abhilash, but I'm getting this error: The key selector type for the call to the 'GroupBy' method is not comparable in the underlying store provider. Thanks
Comment: In 'GroupBy' clause you have to give the correct field name for RoleName in your table. I just assumed it to be RoleName. You have to give your field name.
Comment: That is exactly what I did  var rolesUsers = userManager.Users.GroupBy(e => e.Roles)
               .Select(x => new UserRoleModel
               {
                   RoleName = x.Key,
                   NoOfUsers = x.Count()
               }).ToList();
Comment: So 'Roles' is the field in 'Users' table right. What is its datatype???
Comment: See the updated answer will be useful. Where 'Roles' should be the field in your user table.
Comment: My user table extends IdentityUser.
Comment: The code did not compile, when I did this:  var  result = ( from u in userManager.Users
                group  new { u } by new { u.Roles } into grp
                select new { name = grp.Key , count =grp.Count() }).ToList();, it threw the same exception error. Thanks so far.
Comment: What is the error. Not { u. Roles } change it to { u.Roles.Name }
Comment: ICollection does not contain a definition for Name and no extention method...sorry for late reply
Comment: What are the fields in your UserRole. What are the table actually you have .I don't understand.
Comment: It's the default fields that comes with asp.net identity UserRoles table (Just UserId and RoleId). Am assuming because it is the join table that's why.
Comment: please see the updated answer. I am not sure about field name. But this will works for you.
Comment: Wow!....Thanks Sooo Much. It finally works!...Thanks for your patience, I truly appreciate!. Have a nice day!.


ESP32 writing string to EEPROM

Question: I need to save some data to EEPROM because I want to retain that value even when the device is switched OFF.  When the device is powered again, I need to remember what was the last value.
I have no problems saving integer value to EEPROM as following:
void parse_item_inside(char* payload){

    cJSON* jsonObj = cJSON_Parse((char*)(payload));

  // Get pointer to specific field in JSON object

    cJSON* serial = cJSON_GetObjectItem(jsonObj, "Serial");

    cJSON* quantity = cJSON_GetObjectItem(jsonObj, "Quantity");

     //Get integer value - other fields allow access to strings, floats etc.

    strcpy(item_inside.serial,serial->valuestring);

    item_inside.quantity = quantity->valueint;

    EEPROM.put(2, item_inside.quantity);

    Serial.print("Checking serial before puting to eeprom=");

    Serial.println(item_inside.serial);

    EEPROM.put(4, item_inside.serial);

    //EEPROM.write(4,item_inside.serial);

    EEPROM.commit();

    Serial.print("ITEM_INSIDE_QUANTITY=");

    Serial.println(EEPROM.read(2));

    Serial.print("ITEM_INSIDE_SERIAL READ=");

    Serial.println(EEPROM.read(4));

    Serial.print("ITEM_INSIDE_SERIAL get=");

    Serial.println(EEPROM.get(4,local_serial));

    OLED_display(item_inside.quantity,number_to_pick);

// Delete JSON object (don't forget this)

  cJSON_Delete(jsonObj);

    }

However, when I try to put a string variable ( item_inside.serial)
EEPROM.put(4, item_inside.serial);

enter image description here
As you can see both functions, EEPROM.read and EEPROM.get did not work
Also, can someone help me understand when should I use EEPROM.write and EEPROM.put. Both of these seem to work fine for integer variable, However, EEPROM.write does not compile with string as it expects integer.
Also, is using EEPROM.read correct in this case , or should I use EEPROM.get function instead as I am not sure what are the differences
Answer: Juraj - you are right. i had some problems with addresses. I could not post the code properly in comment so il make a new answer.
item_inside serial is initialized as following:
char item_inside.serial[10];

    int address=0;
    EEPROM.writeByte(address,item_inside.quantity);
    address += sizeof(byte);

    EEPROM.writeString(address, item_inside.serial);
    address += 10;

    EEPROM.commit();

Now it properly writes to EEPROM
Answer: Use a structure to hold the data record:
struct SERIAL_DATA
{
    uint_8 numBytes;
    char   data[10];
};

#define BEGIN_OF_PAD 0

Save to EEPROM:
int addr = BEGIN_OF_PAD;
DATA_RECORD serialData;                            // Instanciate a record

serialData.numBytes = item_inside.quantity;        // Add field to record

String tmpStr = String(item_inside.serial);        // Could use strcpy() too.
                                                   // I prefer to use String in case I
                                                   // need to validate the data.
tmpStr.toCharArray(serialData.data, tmpStr.length()); // Add field to the record

EEPROM.put(addr, serialData);                      // Put record into EEPROM buffer
EEPROM.commit();                                   // Commit

addr += sizeof(serialData);                        // Advance address for next record

Retrieve from EEPROM:
#import <iostream>
using namespace std;

addr = BEGIN_OF_PAD;
DATA_RECORD retrievedData;                         // Instanciate a record

EEPROM.get(addr, retrievedData);                   // Retrieve a record from the EEPROM

cout<<"Data size: "<<retrievedData.numBytes<<endl; // Process the record as needed
cout<<"Data: "     <<retrievedData.data    <<endl;

addr += sizeof(serialData);                        // Advance address for next record

:::::::::::::::

ESP32 writing string to EEPROM


Why do we use sample mean in the total sum of squares (SST) calculation?

Question: I am trying to understand why the sample mean is used in the Total Sum of Squares or Total Deviation calculation.
In other words, what is so important or significant about the sample mean?
A lot of books and notes gloss over this information and it is frustrating me to no end.
Representation
Answer: Linear regression seeks to find the expected value (so the mean value) of $y$, given some specified features.
If we had no knowledge of the relationship between the features and $y$, a sensible guess is the overall mean of $y$.
The total sum of squares also winds up being related to the overall variance of $y$ when TSS is calculated this way, too.


Datatables only shows data after click on column length dropdown or typing on filter

Question: I am using jQuery DataTables and my data only shows when I click on the column length dropdown or when I type a text in filter input.
Javascript:
var oArtikliData = $.getJson('json.php?json=artikli');
oArtikliTable = $('#tbl_artikli').DataTable(
{
    "aaData": oArtikliData,
    "columnDefs":
    [
        {
            /* REDNI BROJ */
            "targets": 0,
            "data": "r_br"
        },
        {
            /* PROIZVOĐAČ */
            "targets": 1,
            "data": "proizvodjac"
        },
        {
            /* MODEL */
            "targets": 2,
            "data": "naziv"
        },
        {
            /* CIJENA BEZ PDV */
            "targets": 3,
            "data": "cijena_bezPDV"
        }
    ],
    "dom": 'R<"pdf_button"><"clear">lfrtip',
    "autoWidth": true,
    'iDisplayLength': 50,
    "lengthMenu": [[1,5,10, 25, 50], [1,5,10, 25, 50]]

    }
});

HTML:

                                    R.br.
                                    Proizvođač
                                    Model
                                    Cijena bez PDV-a

I am using the latest jQuery, I have tried in Chrome and Firefox, but the issue is still present.
Why does my data only appear under certain circumstances?
Answer:
SOLUTION

Your table is initialized before the data is retrieved from remote source, that is why no data shows initially. Also there is extra closing bracket } that should be removed.
Use the following code instead:
var oArtikliTable = $('#tbl_artikli').DataTable({
    "ajax": {
       "url": 'json.php?json=artikli',
       "dataSrc": ""
    },
    "columnDefs": [
        {
            /* REDNI BROJ */
            "targets": 0,
            "data": "r_br"
        },
        {
            /* PROIZVOĐAČ */
            "targets": 1,
            "data": "proizvodjac"
        },
        {
            /* MODEL */
            "targets": 2,
            "data": "naziv"
        },
        {
            /* CIJENA BEZ PDV */
            "targets": 3,
            "data": "cijena_bezPDV"
        }
    ],
    "dom": 'R<"pdf_button"><"clear">lfrtip',
    "autoWidth": true,
    'pageLength': 50,
    "lengthMenu": [[1,5,10, 25, 50], [1,5,10, 25, 50]]

});

DEMO

See this jsFiddle for code and demonstration.
Comment: Still not working. Im getting json data from my localhost, its small data. Im also getting this error Cannot use 'in' operator to search for 'length' in
Comment: @Hawkridge, can you please post a sample of your JSON data? Visit `json.php?json=artikli` and post your results.
Comment: @Hawkridge, added example to demonstrate that my solution works. Also there was extra `}` in your code that I missed.
Comment: I see that code works. Maybe is due to jQuery version because i getting error "Uncaught TypeError: Cannot use 'in' operator to search for 'length' in "
Comment: @Hawkridge, I outlined the reason why it happens in my answer. You need to let DataTables do the Ajax. Alternatively you need wait for response from remote source before initializing the table.
Comment: Yeah but i have same error when i enter manually data in html, without ajax.
Comment: I solved a problem. Problem was in old version of datatables. Thanx Gyrocode.com


How can I prove that, if $x,y,z>0$ and $xyz=1$, then $2(x^2+y^2+z^2)+9\geq 5(x+y+z)$

Question:
How can I prove that, if $x,y,z>0$ and $xyz=1$, then
$$2(x^2+y^2+z^2)+9\geq 5(x+y+z)$$

I used the famous inequality
$$x^2+y^2+z^2+3\geq 2(x+y+z)$$
I got $$2(x^2+y^2+z^2)+9\geq 4(x+y+z)+3\geq 5(x+y+z)$$
But, the last inequality gives $x+y+z\leq3$ which is not correct.
Answer: See the post by @arqady here: https://artofproblemsolving.com/community/c6h1293235p6852442
It's a pretty nice solution, so I'll copy it over here:
We prove the stronger inequality
$$xyz+2(x^2+y^2+z^2)+8\ge 5(x+y+z)$$
WLOG suppose $(x-1)(y-1)\ge 0\implies xy\ge x+y-1\implies xyz\ge xz+yz-z$.
Then we want to show that (by simply plugging in this inequality to the original one)
$$2z^2+(x+y-6)z+2x^2+2y^2-5x-5y+8\geq0$$
Let $x+y=2t$. Using the well-known and easy to prove inequality $2(x^2+y^2)\ge (x+y)^2$, it remains to show that
$$z^2+z(t-3)+2t^2-5t+4\ge 0$$
It suffices to show that
$$(t-3)^2\le 4(2t^2-5t+4)$$
Upon expansion and simplification, this is equivalent to $(t-1)^2\ge 0$, which is true.
Comment: @user376343, we re proving the general inequality where do not know is $xyz$ is equal to $1$ or not.
Comment: @ZFR right. I edit a new comment: In general, two or three of the numbers are smaller than 1, OR two or three are larger than 1. In the inequality, (the) two with equal position relatively to 1 are used.
Comment: @ZFR  There exists a pair $(a,b)$ from $x,y,z$ such that $(a-1)(b-1)\ge 0$ by the Pigeonhole Principle
Answer: pqr method:
Let $p = x + y + z,\, q = xy + yz + zx,\, r = xyz = 1$.
It suffices to prove that $2(p^2 - 2q) + 9 \ge 5p$ or
$$2p^2 - 4q + 9 - 5p \ge 0.$$
Using $p^3 - 4pq + 9r \ge 0$ (three degree Schur), we have
$$q \le \frac{p^3 + 9}{4p}.$$
It suffices to prove that
$$2p^2 - 4\cdot \frac{p^3 + 9}{4p} + 9 - 5p \ge 0$$
or
$$(p - 3)(p^2 - 2p + 3)/p \ge 0$$
which is true since $p\ge 3\sqrt[3]{r} = 3$ (AM-GM).
We are done.
Remark: Three degree Schur inequality is
$$a(a - b)(a - c) + b(b - c)(b - a) + c(c - a)(c - b) \ge 0.$$
In pqr language (or substitution), it is $p^3 - 4pq + 9r \ge 0$.


error while opening AVD manager

Question: I'm facing  common problems when running the codes to emulator . The console messages are
[2013-01-05 19:39:15 - Doodlz] Android Launch!
[2013-01-05 19:39:15 - Doodlz] adb is running normally.
[2013-01-05 19:39:15 - Doodlz] Performing com.deitel.doodlz.Doodlz activity launch
[2013-01-05 19:39:15 - Doodlz] Automatic Target Mode: launching new emulator with compatible AVD 'Nex'
[2013-01-05 19:39:15 - Doodlz] Launching a new emulator with Virtual Device 'Nex'

but the emulator was not launching at all even already waited for longer time.
After that, I tried starting the emulator from AVD manager, but the console messages told
[2013-01-05 19:39:25 - SDK Manager] Error parsing C:\Users\Dedy\.android\devices.xml, backing up to C:\Users\Dedy\.android\devices.xml.old
[2013-01-05 19:39:28 - SDK Manager] Error parsing C:\Users\Dedy\.android\devices.xml, backing up to C:\Users\Dedy\.android\devices.xml.old

I couldn't make out these problem. can someone tell me what should I do to troubleshoot these problems?
Thanks alot.
Comment: Have you tried to re-construct the AVD or to create a new latest AVD?
Comment: Yes, I did. but it still unsolved..
Comment: is your ADT is uptodate with your version sdk ?
Comment: yes, I use latest version of ADT..
Comment: have you tested that AVD is getting started manually ??
Answer: perform this steps :

Delete the old AVD and create new AVD. Might your AVD got corrupt.
if doesn't work Restart your eclipse and try again.
if doesn't work Go to  C:\Users\(username)\.android folder and deleted both the avd and cache folders. (it may not be necessary to remove both, I didn't check any further). This might help you !!
 go to this link and start emulator from command prompt. Check whether there is ADB connection between eclipse and emulator is started or stopped.
If none of them help re-install the sdk and eclipse.
Comment: I suggest, you should try this once and let us know.
Comment: thanks for your suggestion, I tried these steps, but problems still unsolved.
Comment: what problem your seeing now ?? have you restarted eclipse ?? clean up your code and restart again
Comment: Yes, same problems still occured. also when the emulator launched, no emulator in the list of devices in DDMS.. And when I checked from cmd "adb devices" , none list of devices attached
Comment: re-install everything..  no other options I think

error while opening AVD manager


Linux kernel upgrade broke named pipes

Question: We noticed a change with named pipes after a linux kernel upgrade. Using the scripts from http://www.linuxjournal.com/content/using-named-pipes-fifos-bash, we were able to replicate the issue. The scripts work on
Linux TEST05 3.13.0-55-generic #94-Ubuntu SMP Thu Jun 18 00:27:10 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux

but hang on
Linux TEST01 3.13.0-65-generic #106-Ubuntu SMP Fri Oct 2 22:08:27 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux

There seems to be a difference in how named pipes work. Is that intentional or not?
We captured the two scripts as pipe_reader.sh:
#!/bin/bash

pipe=/tmp/testpipe

trap "rm -f $pipe" EXIT

if [[ ! -p $pipe ]]; then
    mkfifo $pipe
fi

while true
do
    if read line <$pipe; then
        if [[ "$line" == 'quit' ]]; then
            break
        fi
        echo $line
    fi
done

echo "Reader exiting"

and pipe_writer.sh:
#!/bin/bash

pipe=/tmp/testpipe

if [[ ! -p $pipe ]]; then
    echo "Reader not running"
    exit 1
fi

if [[ "$1" ]]; then
    echo "$1" >$pipe
else
    echo "Hello from $$" >$pipe
fi

Is there a fix?
EDIT:
We're running each script in its own terminal. They hang in the sense that the writer script never exists, and the reader script never shows the normal "Hello from..." output. We're executing them in an identical fashion under both kernel versions, so it's not an issue of running one script more than once, or any other procedural differences.
Comment: Unfortunately, we've downgraded the host where I could reproduce the problem. When I set up another box identically (using ansible scripts) the kernel version that didn't work now works fine. Perhaps we got a corrupt version of the kernel, not sure, but now I have no way to reproduce the problem. :(
Comment: I just tested on my machine with same kernel and the script works fine (well, I just echo'd manually but the named pipe functionality is fine). Since it's now working for you too, I guess it was just a glitch in the matrix. Or maybe /tmp was full or had bad permissions on your last machine.
Answer: I have not enough of reputation to write comment, so writing as an answer.
What do you mean by hang?  What happens than you execute pipe_reader.sh and pipe_writer.sh in other terminal?
Also, after executing both scripts, what does command:
ls -al /proc/$(pgrep pipe_reader.sh)/fd

show?
Maybe you have ran several .pipe_reader scripts, so only the first one receive the pipe_writer output? Make sure that
ps aux | grep pipe_reader | grep -v grep | wc -l

returns 1
Comment: Question updated.
Comment: please add output of `strace ./pipe_reader` and `strace ./pipe_writer.sh`
Answer: From what I understand 3.13.0-55 and 3.13.0-65 are both the same kernel (3.13) with some fixes/patches by the distribution provider. It is unlikely that the pipe functionality would be altered with this upgrade. I believe that breaking such functionality would be frowned upon by kernel developers.
There's something else going on.

Linux kernel upgrade broke named pipes


export to pdf with html decode

Question: I want to display one column (from a data source, using GridView) with html tags into a PDF .
I want the HTML to be decoded so that in the PDF, it won't print the literal html tags . here's my code:
In GridView_RowDataBound event:
for (int i = 0; i < GridView1.Rows.Count; i++)
    {
        if (GridView1.Rows[i].RowType == DataControlRowType.DataRow)
        {

            for (int j = 0; j < 6; j++)
            {
                decodeHTML = HttpUtility.HtmlDecode(GridView1.Rows[i].Cells[j].Text);
                GridView1.Rows[i].Cells[j].Text = decodeHTML;
            }
        }
    }

then added the HTML decoded gridview into PDF cell:
    Phrase cellText = new Phrase(GridView1.Rows[i].Cells[j].Text, baseFontNormal);

    iTextSharp.text.pdf.PdfPCell cell = new PdfPCell(cellText);
    if (j == 3) cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
    table.AddCell(cell);

Instead of displaying the data in a PDF format, it displays them in an HTML page (in browser). However, it will be displayed as PDF file ONLY if I remove the GridView_RowDataBound event, but then the data will print literal html tags, and I don't want this.
Comment: Hi @mkl, I think that the OP is making the wrong assumption about the `HtmlDecode` method.
Comment: *"Instead of displaying the data in a PDF format, it displays them in an HTML page (in browser)."* - if an html page is displayed instead of a pdf, you obviously return html and not pdf. So take a look at the code that writes to the response.
Comment: but when I remove (comment out) the code in the GridView_RowDataBound event, it exports as a PDF file as expected.
Comment: @mkl nope, that's not the case, Bruno Lowagie is correct
Comment: Yes, because "it displays them in an HTML page" was not an exact description, the page was a pdf page which merely showed some html source...
Answer: You are making the wrong assumption about the HtmlDecode method. You assume that this method can decode HTML, e.g.
This is italic and this is bold!
 into something like:

This is italic and this is bold!

But that is not the case. Take a look at the API documentation on MSDN:

Converts a string that has been HTML-encoded for HTTP transmission into a decoded string.

What does this mean?
It means that you can use HtmlDecode to convert a string like this:
<p>This is <i>italic</i> and this is <b>bold</b>!</p>

Into a string like this:

This is italic and this is bold!

The HtmlDecode method does not remove the tags. It makes sure that entities in the string (stuff like &) are converted to readable content. Hence it is normal that you see the tags in the PDF.
When you have HTML content, and you want to convert it to iText objects, you need an add-on to make that conversion. See Converting HTML to PDF using iText  to find out how to do this.
Comment: Thanks . That helps !

export to pdf with html decode


How to include seasonal effects into the system matrices of a state space model

Question: I am working on learning state space models and am leaning heavily on this very helpful documentation. However, I'm really confused about the best way to include both a seasonal effect and dynamic regressors into the model.
Let's further assuming that I want to use a simulation smoother to estimate the coefficients on the dynamic regressors.
My initial thought was to do something like the following (with the seasonal effect specified as dummy variables that sum to 1). That is to say, first regressing the dependent variable on the seasonal effect, then subtracting that effect and passing the remainder into the state space model.

y ~ normal(seasonal_effect, sigma)
y_prime = y - seasonal_effect
y_prime ~ state_space_model(...system matrices go here...)

The issue that I'm having with this specification is that:

It doesn't estimate any kind of seasonal effect even though my model clearly has one
It's estimating the dynamic linear model and the seasonal effect separately when they should seemingly be estimated together

From the available literature it seems that I should be able to code the seasonal effect directly into the system matrices, but I have no idea how.

If I put the seasonal dummies into the Z (or F, depending on the literature) design matrix, they are treated as a dynamic regressor, unless...
I restrict the state selection covariance matrix to only allow the non-seasonal dummies to evolve over time, but then the state estimates that I get from the seasonal dummies stay fixed at the values that I pass into the simulation smoother (as a1)

The libraries and models that I'm working with are very very clear once you have the system matrices specified, but I am lost on how to include seasonal effects into the system matrices of the dynamic linear model
Any help would be appreciated!
Answer: Here is an example from KFAS with two covariates and seasonal of length 12:
library(KFAS)
model_drivers <- SSModel(log(drivers) ~
        SSMseasonal(period = 12,  Q = 0) +
        log(PetrolPrice) + law, data = Seatbelts, H = NA)

First time point:
model_drivers$Z[,,1]
     (Intercept) log(PetrolPrice)              law       sea_dummy1       sea_dummy2       sea_dummy3       sea_dummy4       sea_dummy5       sea_dummy6       sea_dummy7       sea_dummy8       sea_dummy9      sea_dummy10      sea_dummy11
          1.0000          -2.2733           0.0000           1.0000           0.0000           0.0000           0.0000           0.0000           0.0000           0.0000           0.0000           0.0000           0.0000           0.0000

And matrix T:
model_drivers$T
, , 1

                 (Intercept) log(PetrolPrice) law sea_dummy1 sea_dummy2 sea_dummy3 sea_dummy4 sea_dummy5 sea_dummy6 sea_dummy7 sea_dummy8 sea_dummy9 sea_dummy10 sea_dummy11
(Intercept)                1                0   0          0          0          0          0          0          0          0          0          0           0           0
log(PetrolPrice)           0                1   0          0          0          0          0          0          0          0          0          0           0           0
law                        0                0   1          0          0          0          0          0          0          0          0          0           0           0
sea_dummy1                 0                0   0         -1         -1         -1         -1         -1         -1         -1         -1         -1          -1          -1
sea_dummy2                 0                0   0          1          0          0          0          0          0          0          0          0           0           0
sea_dummy3                 0                0   0          0          1          0          0          0          0          0          0          0           0           0
sea_dummy4                 0                0   0          0          0          1          0          0          0          0          0          0           0           0
sea_dummy5                 0                0   0          0          0          0          1          0          0          0          0          0           0           0
sea_dummy6                 0                0   0          0          0          0          0          1          0          0          0          0           0           0
sea_dummy7                 0                0   0          0          0          0          0          0          1          0          0          0           0           0
sea_dummy8                 0                0   0          0          0          0          0          0          0          1          0          0           0           0
sea_dummy9                 0                0   0          0          0          0          0          0          0          0          1          0           0           0
sea_dummy10                0                0   0          0          0          0          0          0          0          0          0          1           0           0
sea_dummy11                0                0   0          0          0          0          0          0          0          0          0          0           1           0

You can probably figure out the logic here, essentially the first row of seasonal part is full of values -1 and then there is values of 1 just below the diagonal of the seasonal part. And Z just contains one in the first entry and zeros on the rest.
Then you also have to remember to add some uncertainty for the seasonal states, i.e. prior state_1 ~ N(prior_mean, prior_variance).
With this model and wide priors for the variance parameter H, you should get the same results with KFAS as with some Bayesian solutions, so you can use KFAS to check the results even if you want to do fully Bayesian inference. And there is also an R package bssm which you can use for these kind of models directly for fully Bayesian inference (check functions bsm and run_mcmc).


Show nested circles on ggplot: polygons disappear when limited xy axis

Question: I am trying to show two nested circles in my ggplot object using ggforce::geom_circle that look like this:

It definitely works when I am plotting two circles:

but if I try to limit the x and y axis using scale_x or coord_cartesian either my polygons are weirdly cut, or not shown:

What can be the issue?
Here is a dummy example:
library(ggforce)

set.seed(4242)
dd <- data.frame(x = runif(20, min=0, max=2),
                 y = runif(20, min=0, max=2))

# There's presumably a way to do this within the above mutate function using case_when()
ggplot(dd) +

  geom_circle(aes(x0 = 0, y0 = 0, r = 2),
              inherit.aes = FALSE, fill = 'grey90',
              lty = 'dotted', color = 'grey70', alpha = 0.5) +
  geom_circle(aes(x0 = 0, y0 = 0, r = 0.5),
              inherit.aes = FALSE, fill = 'grey70',
              lty = 'dotted', color = 'grey50', alpha = 0.5) +
  geom_point(aes(x = x, y = y), size=1)+
  geom_abline(intercept = 0, slope=0.5, col='red') +
  geom_abline(intercept = 0, slope=1.8, col='blue') +
  #scale_x_continuous(expand = c(0, 0), limits = c(0, 2)) +
  #scale_y_continuous(expand = c(0, 0), limits = c(0, 2)) +
  coord_cartesian(xlim = c(0,2.5),   # try to limit the xy axis in two ways
                  ylim = c(0,2.5)) +
  theme_bw() +
  theme_update(legend.position = 'bottom') +
  theme_update(aspect.ratio=1)

Session info:
    R version 4.1.1 (2021-08-10)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 17763)

Matrix products: default

locale:
[1] LC_COLLATE=English_United States.1252
[2] LC_CTYPE=English_United States.1252
[3] LC_MONETARY=English_United States.1252
[4] LC_NUMERIC=C
[5] LC_TIME=English_United States.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] ggforce_0.4.1 ggplot2_3.3.6

loaded via a namespace (and not attached):
 [1] Rcpp_1.0.7       magrittr_2.0.2   MASS_7.3-54      tidyselect_1.1.2
 [5] munsell_0.5.0    colorspace_2.0-2 R6_2.5.1         rlang_1.0.2
 [9] fansi_1.0.2      dplyr_1.0.8      tools_4.1.1      grid_4.1.1
[13] gtable_0.3.0     utf8_1.2.2       cli_3.2.0        DBI_1.1.2
[17] withr_2.5.0      ellipsis_0.3.2   digest_0.6.28    assertthat_0.2.1
[21] tibble_3.1.6     lifecycle_1.0.1  crayon_1.5.0     farver_2.1.0
[25] tweenr_1.0.2     purrr_0.3.4      vctrs_0.3.8      glue_1.6.2
[29] labeling_0.4.2   polyclip_1.10-4  compiler_4.1.1   pillar_1.7.0
[33] generics_0.1.2   scales_1.1.1     pkgconfig_2.0.3

Comment: Sounds related to the following issue: https://github.com/tidyverse/ggplot2/issues/4498
Comment: Limiting the axis using scales would be expected to cause this problem, but I can't replicate your problem if I use the coord_cartesian method - it works just fine on my pc. Have you tried using different drawing devices - X11, ragg, png, pdf etc?
Comment: I am on windows. I have tried export it to `png` but was the same. I will try with `pdf` one. Thank you for suggestions @Allan Cameron!
Comment: @AllanCameron, indeed, the export to pdf works great, showing both circles! Weird. Thank youf or suggestion!
Answer: You could force the origin to 0 with expand and no limit in scale_*_continuous like this:
library(ggforce)
library(ggplot2)
set.seed(4242)
dd <- data.frame(x = runif(20, min=0, max=2),
                 y = runif(20, min=0, max=2))

ggplot(dd) +
  geom_circle(aes(x0 = 0, y0 = 0, r = 2),
              inherit.aes = FALSE, fill = 'grey90',
              lty = 'dotted', color = 'grey70', alpha = 0.5) +
  geom_circle(aes(x0 = 0, y0 = 0, r = 0.5),
              inherit.aes = FALSE, fill = 'grey70',
              lty = 'dotted', color = 'grey50', alpha = 0.5) +
  geom_point(aes(x = x, y = y), size=1)+
  geom_abline(intercept = 0, slope=0.5, col='red') +
  geom_abline(intercept = 0, slope=1.8, col='blue') +
  scale_x_continuous(expand = c(0, 0)) +
  scale_y_continuous(expand = c(0, 0)) +
  coord_cartesian(xlim = c(0,2.5),   # try to limit the xy axis in two ways
                  ylim = c(0,2.5)) +
  theme_bw() +
  theme_update(legend.position = 'bottom') +
  theme_update(aspect.ratio=1)

Created on 2022-10-28 with reprex v2.0.2
Comment: @maycca, The polygons are still missing when you run exactly my code? Could you please share your session info?
Comment: Thank your for your answer @Quinten! Still, when  run your code, my polygons are again missing, now both of them. Any other workaround?
Comment: no, they are still missing. I have added my session Info. Seems that I have a correct version of ggplot and R?
Answer: Aa @teuenbrand pointed out, this issues have been discussed here and was happening on later installations of R 4.1.0 oon Windows 10. These two options succesfully print the plot into pdf or png format, but still the plotting is not proper with R studio itself.
Workarounds:

printing the figure into pdf (not to png), suggested by @AllanCameron:
pdf("output.pdf")
 library(ggplot2)
 ggplot(data.frame(x = 1:10, ymin = 1:10, ymax = 10 + 1:10), aes(x)) +
   geom_ribbon(aes(ymin = ymin, ymax = ymax), alpha = 0.5) +
   coord_cartesian(c(1, 9))
 dev.off()

printing to png: recommened to use the ragg package, and print plot using agg_png command:
library(ragg)
agg_png("output2.png")

library(ggplot2)
ggplot(data.frame(x = 1:10, ymin = 1:10, ymax = 10 + 1:10), aes(x)) +
geom_ribbon(aes(ymin = ymin, ymax = ymax), alpha = 0.5) +
coord_cartesian(c(1, 9))

dev.off()

Plotting of two polygons while cropping the xy-plot limits:


Outlook JS Add-in - Pass data from taskpane to event

Question: I need help creating an outlook JS Add-in that can forward mails.
The idea
In a taskpane a list of mail addresses is shown that the user can click on.
At the click event the mail should be forwarded to the one the user clicked on.
Current state
The Add-in opens a reply window using Office.context.mailbox.item?.displayReplyAllFormAsync().
With the onNewMessageCompose event I want to change the recipient so that the user only has to click on "Send".
I try to find a work around so that I do not have to use the Graph API.
The issue
How can I pass e. g. the mail address from the taskpane JS code to the onNewMessageComposeHandler e. g. with a "global" storage both have access to?
I already tried using the local storage and the roaming settings. Both did not work.
Update: Thanks to the answer of "Outlook Add-ins Team - MSFT" I found the mistake:
When using the roaming storage and you set a value, you have to call saveAsync() afterwards.
According to the offical doc shared runtimes aren't supported:

An Outlook add-in that has the following features has as many as four runtimes. Shared runtimes aren't supported in Outlook.

A task pane
A function command
An event-based task [...]
A dialog [...]
Answer: You can use Roaming Settings to do this. The roaming setting can be set in your taskpane file and fetched in your LaunchEvent file. Refer this https://learn.microsoft.com/en-us/office/dev/add-ins/outlook/metadata-for-an-outlook-add-in#loading-roaming-settings
Browser session storage can also be used similarly https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage.
Comment: Thanks for the quick answer.
I did get it to work with the roaming settings.
My mistake was not to call the `saveAsync` function.


Proving that $a_m a_{m+1}$ is a part of a sequence

Question: Define the sequence $a_1, a_2, a_3, . . .$ by $a_1 = 4, a_2 = 7$ and for $n ≥ 2$,
$a_{n+1} = 2a_n − a_{n−1} + 2$.
Prove that, for every positive integer m, the number $a_m a_{m+1}$ is a term of the sequence.
I'm really struggling with question above. I have so far found that $a_n=n^2+3$ and have found that for $a_m a_{m+1}$,  $n=m^2+m+3$ and that $a_n$ is part of the sequence. For example, $a_1a_2=4 \times 7=28$, $n=1^2+1+3=5$ and if you check the sequence, the 5th term is 28 so 28 is part of the sequence. I have tried a proof by induction but this has not worked for me and I am a bit lost.
Comment: You seem done to me. What are you struggling with? EG Are you trying to prove that $a_n = n^2+3$, and have only "observed" the pattern so far?
Answer: You have almost solved it. Let me give a formal proofs.
\begin{align}
a_n - a_{n-1} &= a_{n-1} - a_{n-2} + 2\\
a_{n-1} - a_{n-2} &= a_{n-2} - a_{n-3} + 2\\
&\; \vdots\\
a_3 - a_2 &= a_2 - a_1 + 2
\end{align}
Adding all up, we get
\begin{align}
&a_{n} - a_2 = a_{n-1} - a_1 + 2(n-2)\\
\implies &a_n - a_{n-1} = 7 - 4 + 2(n-2) = 2n -1
\end{align}
Then again using addition, we will get
$$a_n - a_1 = 2(n+\cdots+2) -(n-1) = n(n+1) - 2-n+1 = (n+1)(n-1) = n^2 - 1$$
So, $a_n = n^2 + 3$.
Then, for next part
\begin{align}
a_m a_{m+1} &= (m^2 + 3) [(m+1)^2 + 3]\\
&=(m^2 + 3)(m^2 + 2m + 4)\\
&= m^4 + 2m^3 +7m^2+6m + 12\\
&= m^4 + m^2 + 9 + 2m^3 + 6m^2 + 6m + 3\\
&= (m^2 + m + 3)^2 + 3
\end{align}
Comment: Side note: To somewhat demystify the expansion at the end $$(m^2 + 3) [ (m+1)^2 + 3] = [(m + \sqrt{3}i) ( m - \sqrt{3}i) ] [ (m+1+\sqrt{3}i) ( m+1 - \sqrt{3} i )] =  [ (m+\sqrt{3} I )( m+1 - \sqrt{3} i ) ] [ ( m - \sqrt{3}i)(m+1+\sqrt{3}i) ] = [ m^2 + m + 3 + \sqrt{3} I ] [ m^2 + m + 3 - \sqrt{3} i ] = (m^2 + m + 3) ^2 + 3.$$ Admittedly this is much more complicated than the simple expansion, but provides the motivation for why $n = m^2 + m + 3$ would work. We can also make some generalizations from there.
Comment: Thank you so much!
Answer: Since you found $a_n=n^2+3$, I will start from here.
\begin{align*}
a_m a_{m+1} &= (m^2 + 3)\left[ (m+1)^2 + 3 \right]\\
&= [m(m+1)]^2 + 3[m^2+(m+1)^2] + 9 \\
&= (m^2 + m)^2 + 3(2m^2 + 2m + 1) + 9 \\
&= (m^2 + m + 3)^2 + 3
\end{align*}
Hence we showed $a_m a_{m+1}$ appeared at ($m^2 + m + 3$)th term of the sequence.


Print Vector of Class Objects

Question: I have three classes, a base class: Device, and two derived classes: SmartPhone, and Tablet.
Print is a virtual function that is redefined in the derived classes.
I would like to create an STL vector of devices (comprising of instances of smartphone and tablets), and then print names of the objects that are in the vector.
vector<unique_ptr<Device>> devices(3);
devices[0].reset(new SmartPhone(128, 8));
// memory size, screen size

for (int i = 0; i < 3; i++)
{
    devices[i].print();
}

I have an errors with my vector print implementation:

class "std::unique_ptr>" has no member "print"

How can I call the print function of each object in the vector?
Device Base Class:
virtual void print(); {}

SmartPhone Derived Class:
void print();

-
void SmartPhone::print()
{
    printName();
    cout << "Memory: " << getMemory() << " Screen Size: " << getScreenSize();
}

Comment: What's the declaration of `print`? Don't describe your code in prose, show a [mcve]
Comment: The problem is in your `print()` not your for loop. Also you probably wanted to define operator << () instead anyways.
Answer: You use a pointer, so you need to use pointer semantics:
devices[i]->print();

Operator -> for std::unique_ptr returns the object it manages (i.e. Device instance) and you can call methods on it.
Operator . tries to call method on std::unique_ptr object, and this class doesn't have any method called print.
Also notice that the declaration of your method makes it impossible to use together with std::cout. To make it work, your function would have to be changed to overload of operator << (see the reference for more info)
Answer: You need to call the print function on each element in the devices vector not on the vector itself.
devices[i].print()

Comment: This is an (almost) good answer, but OP changed the question after it was posted...

Print Vector of Class Objects


O que é o Lombok?

Question: O que é o Lombok e como eu poderia usá lo em uma classe java?
Quais as vantagens  e desvantagens de seu manuseio em uma aplicação java?
Answer: O Lombok é um Framework criado sob licença MIT, podendo ser usado livremente em qualquer projeto Java. Seu principal objetivo é diminuir a verbosidade das classes de mapeamento JPA, DTOs e Beans por exemplo.
Sua vantagem é evitar a repetição de código "clichê", como a criação de gets e sets para todos os atributos, métodos equals e hashCode, toString, Construtores entre outros. Dessa forma, o código fica mais limpo e claro.
Uma desvantagem que senti é a necessidade de instalação de Plugin no Intellij e Eclipse. Acredito que esses são as IDEs atualmente suportadas apenas.
Recomendo a utilização.
Fontes:

https://projectlombok.org
http://blog.caelum.com.br/java-menos-verboso-com-lombok/
Comment: Funciona normalmente no NetBeans também, inclusive **sem** a necessidade de instalar qualquer *plugin*.

O que é o Lombok?


Is there a vocal technique used here? If so, what is it called?

Question:

 (0:53)
I'm looking at this song "Just Hold Me" by Maria Mena which I found to be a very good song in terms of the vocals.
Though I'm curious, is there actually a specific vocal technique for this part of the chorus? It's ascending and I feel like there is a name for this.
Comment: Please add a description of the video and the technique so that your question will remain useful even if the video link goes dead.
Comment: One syllable ("Why") being sung over multiple notes is *melisma*, we have lots of questions on it. I can't transcribe the ascending notes that "Why" is set to right now, but I doubt there's a special name.
Comment: It sounds like there may be a register change between the lower and higher notes, which might be the technique of interest.
Answer: As one commenter said, a group of notes sung to one syllable of text is called a melisma, but one wouldn't consider that a "vocal technique". It's a composition choice followed by the singer. Further, she is singing more-or-less a melodic scale (up, then down-and-up), but again, one wouldn't consider that a vocal technique either. She is just singing the written score.
Vocal technique would include switching from full-voice to head-voice (which one could arguably say she did at the crescendo of the run). Or using vibrato (which she did for a split second at the crescendo). Or using special breathing techniques to handle long phrases (which she isn't for the single word). Otherwise, I'd say she's not using any distinguishable "vocal technique" during that run.