Display a single view in different view format

Question: I want to display a view in both grid and list style, and allow the users to explicitly select the format in which they want to view (Like the picture below)
The JQuery which I used is
(function ($) {
    Drupal.behaviors.mytheme = {
  attach: function (context, settings) {
    $('#content').once('course-view', function() {

  if ($(".view").hasClass("course-view")) {
    $(".view").addClass("grid-view"); // Sets .grid-view as default class on the view

    $(".list").click(function() {
      if ($(".view").hasClass("grid-view")) {
        $(".view").addClass("list-view"); // adds .list-view to the view class
        $(".view").removeClass("grid-view"); // removes .grid-view from the view class
      }
    });

    $(".table").click(function() {
      if ($(".view").hasClass("list-view")) {
        $(".view").addClass("grid-view"); // adds .grid-view to the view class
        $(".view").removeClass("list-view"); // removes .list-view from the view class
      }
    });
  }
});
  }
    };
    })(jQuery);

Comment: May be adding two views can do this like /grid for grid view and /list for list view.
Comment: Try this https://www.drupal.org/project/views_modes.
Comment: In that case i have to create two different views, but i want this to happen only by using a single view.
Comment: Its a dev version, you can test it on local site.
Answer: I think Your Question resembles the video tutorial series in Code karate:
Multiple Views Series
Please Check It out... By adding and removing classes when clicking the grid and list icons using jQuery make this done..
Comment: I tried it but its not working, css classes are not being detected.
Comment: Can you please update your question with jquery you used. Try clearing cache
Answer: I didn't got your question ? According to the javascript you used the implementation will be achieved.
However the drupal way of doing this is to create another display of the view ( extend it from master ) and render both the views on the same page and write some JS which will hide the list view when grid button is clicked and hide grid view when list button is clicked.
One having display format- list having class list view and other having display format : grid having class grid.
$('.list').on('click',function() {
  $('.grid').removeClass('enabled');
  $(this).addClass('enabled');
  $('.grid-view').hide();
  $('.list-view').show();
});
$('.grid').on('click',function() {
  $('.list').removeClass('enabled');
  $(this).addClass('enabled');
  $('.grid-view').show();
  $('.list-view').hide();
});
$('.grid-view').hide(); //default settings
$('.list').addClass('enabled'); //default settings

Considering both options the first option with single view and pure js to handle it is correct way as in either case we need to change the class and generated HTML would be the same.
Moreover, If we have same view repeated twice then its useless to create one more view with the same Markup. As it will obstruct the performance and loading time of the page.
I can give you more detailed advice if you can become more descriptive.
Comment: This isn't working.
Comment: YOu need to have jQuery ver 1.7 as .on() is included in 1.7 ver
Comment: @Pujita: If you can be more descriptive . maybe I can help you out with js
Answer: Try this:
For this you need one instance of your view. No clone required.
Note: You need to set your view format to grid by default.
In view header, add Global custom text and add below HTML for toggle between grid and list.

View:Table  List

In template.php
function mytheme_preprocess_views_view(&$vars) {
  $view = &$vars['view'];
  // Make sure it's the correct view
  if ($view->name == 'participant_list') {

    // add needed javascript
    drupal_add_js(drupal_get_path('theme', 'mytheme') . '/script.js');

    // add needed stylesheet

  }
}

script.js (add in  the custom theme)
    (function ($) {
    Drupal.behaviors.mytheme = {
    attach: function (context, settings) {
       $(".list").click(function() {
         $( "div.view-participant-list" ).find("td").addClass("display_list" );
    });

        $(".grid").click(function() {
        $( "div.view-participant-list" ).find("td").removeClass( "display_list");
    });
  }
 };
})(jQuery);

.css
.display_list
{
    display:block;
}

Note: Here div.view-participant-list is selector in my case. You need to find your own.


How to calculate $P(A, B | C)$ from Bayesian Network?

Question: I have this bayesian network:
A -> B -> C I need to calculate $P(A, B|C)$. How can I do that?
I tried doing:
$P(A,B | C) = P(A|B,C)P(B|C)$
But I don't understand where to go from that considering I don't have any CPT that can help me in solving $P(A|B,C)$. I only have CPT's where $B$ is dependent on $A$ and $C$ is dependent on $B$.
Also, what should I read to be able to solve such weird flows' probabilities in the BN?
Comment: Try the definition of conditional probability, $P(X|Y) = \frac{P(X, Y)}{P(Y)}$
Comment: So long as you know the marginal probabilities $P(A)$ and $P(C)$ you can calculate it
Answer: In your network, the CPDs are P(A), P(B|A) and P(C|B). Also, C is independent of A given B.
$$
\begin{align}
P(AB|C)&=P(C|AB)P(AB)/P(C) \\
&=P(C|B)P(B|A)P(A)/(\sum_B P(C|B) \sum_A P(A)P(B|A))
\end{align}
$$
P(C) is calculated by summing out A and B from the joined distribution.
It's not a "weird" form, instead rather basic. You can read about conditional independence and information pass in the field of graphical models to learn more about it.
Answer: note1: you also have the probability table for $A$. You can think of it as the CPT for $P(A|\phi)$.
note2: at least when beginning with bayesian networks, I think it helps a lot to use the full notation $P(B=b|A=a)$, to understand what you're doing. Think of $A$ as a binary random variable that can take $a \in [0,1]$
If the network was only A->B, to derive $P(B=b|A=a)$, you would do:
$P(A=a, B=b) = P(A=a)P(B=b|A=a)$
$P(B=b) = \sum_{a\in A}P(A=a)P(B=b|A=a)$
so:
$P(A=a|B=b) = \frac{P(A=a,B=b)}{P(B=b)}$
for 3 variables, just apply these Bayesian equations more.


Which windows rights for powershell's Get-WmiObject on remote PC?

Question: When I run a simple powershell command on a remote PC such as
Get-WmiObject Win32_Process -computer Pc1
Some Pcs reply "Access denied", while other reply fine, but I can't get the difference.
Which rights are involved?
Answer: Have you looked at this ServerFault question Which permissions/rights does a user need to have WMI access on remote machines?
Answer: Disable windows firewall first, to see if it's that simple; if so, you can narrow it down to individual ports.
Comment: I'd be very surprised if this was a firewall issue.  The fact that some machines acquiesce, and others have the gaul to respond with a "Access denied" means the traffic is getting through to the target, and a response is getting back.
Comment: Reason I mentioned it is that I once inherited a network where half the users had the firewall enabled, the other half didn't.  I actually received access denied errors from the (WMI based) network monitoring software, which really wasn't what I expected, either.
Comment: Fair comment, I guess it pays it expect the unexpected!
Answer: You need to be a local admin on the target PC, and you need to be using those credentials.
Answer: Non admins should be able to run PowerShell WMI queries if the WMI Control permissions are adjusted to allow access.
My research found the following...
See KB 325353 and http://msdn.microsoft.com/en-us/library/aa393613(VS.85).aspx
On the target server:
Computer Management | WMI Control | Security Tab
Highlight Root\cimv2 node
Click Security button
For EVERYONE group, check Remote Enable box or add a group and grant Remote Enable and Enable Account.
I have not had a chance to test these settings yet.  Pls verify on NON-PRODUCTION server first.
Comment: It is interesting, but unfortunately does not solve the problem.


How do I hide a view's field based on role?

Question: In /admin/people, I want to hide the display name (i.e. the Display name must not appear in the user list), but only for a specific role.
In my .module file, I have tried following hooks:
<code>function hook_views_data_alter(array &$data) {
  kint($data['users']);die;
}

function hook_views_pre_render(\Drupal\views\ViewExecutable $view) {
  if($view->id() == 'myview'){
    print_r($view->result);die;
      // kint($value->_entity->get('title')->value);
  }
}

function hook_views_post_render(\Drupal\views\ViewExecutable $view) {
   if ($view->id() == 'viewid') {
    // Set the view title.
    $field_name = $view->getFields();
  }
}

function hook_field_views_data_views_data_alter(array &$data, \Drupal\field\FieldStorageConfigInterface $field) {
  $field_name = $field->getName();
  echo 'hjsjhwd';
  print_r($field_name);die;
  }
</code>
None of them helped me. I thought of getting fields of the view "user" and after that I will unset it for particular role. But in views listing, Name field is still appearing. How can I hide it for a particular role?
Is there any way to achieve this?
Comment: do you want to hide this field only in your view or you want it to be hide everywhere?
Comment: Only at /admin/people listing page. There comes a column of `display name ` at /admin/page, I want to hide that particular column actually. May be If I hide field, that column also gets hide for my particular role.
Answer: The most efficient way would be using hook_views_pre_view(), which allows you to alter a View at the very beginning of the process i.e. before any query is built/run and before any rendering takes place. You can remove the 'name' field handler from the View based on the desired logic.
<code>/**
 * Implements hook_views_pre_view().
 */
function MY_MODULE_views_pre_view($view, $display_id, array &$args) {
  if ($view->id() !== 'user_admin_people') {
    return;
  }

  $user_roles = \Drupal::currentUser()->getRoles();
  if (!in_array('my-special-role', $user_roles)) {
    $view->removeHandler($display_id, 'field', 'name');
  }
}
</code>
This solution assumes that you are only interested to serve this very specific use case - remove the field only from this specific View. Users might still be able to see the Display Names of users in other areas of the website.
Comment: @NoSsweat If !== then return, therefore only execute the logic if ===
Comment: Good job, voted up
Comment: I think it should be `$views->id() ===` ?
Comment: I might be wrong, but should there be an 's' in `$views->id()`? Should it be `$view->id()`?
Comment: Also, if you want to see if the user has any of the roles, use `if (empty(array_intersect($userRoles, $userRolesAllowed)))`. More info on [`array_intersect`](http://www.php.net/array_intersect)
Comment: Custom code is no longer necessary as there's now a module for this.  See my answer for details.
Answer: You can hide fields using hook_entity_field_access, you can hide field based on user account (role is one of its properties), operation and entity which contain the field.
You also can use Field Permissions module to hide a field from certain roles.
Answer: When you need to delete the table header < td > and also rows < td > you can use template_preprocess_views_view_table
<code>/**
 * Implements template_preprocess_views_view_table().
 */
function TEMPLATE_preprocess_views_view_table(&$variables) {
  // @TODO: You should use $variables['view']->name and $variables['view']->current_display to apply this only one specific view.

  // Let's assume your field name is node status.
  // Remove header label.
  if (isset($variables['header']) && isset($variables['header']['status']) {
    unset($variables['header']['status']);
  }

  // Remove row columns.
  foreach($variables['rows'] as $key => $row) {
    if (isset($variables['rows']) && isset($variables['rows'][$key]) && isset($variables['rows'][$key]['status'])) {
      unset($variables['rows'][$key]['status']);
      unset($variables['result'][$key]->node_status);
    }
  }

  // You can always print_r($variables['rows']) to know what is exact field name that you need to delete.
  // print_r($variables['result']).
  // print_r($variables['header']).
}
</code>
Note: For any needs like this, try not to use more than two hooks to do your needs. Since Drupal always will do anything you want using one or two hooks no more.

Update: For Drupal 7 also using the same hook name on this URL template_preprocess_views_view_table
Answer: Use the Views Field Permissions module.  No custom code required!
Support for roles was added about a month ago.


Pinpoint & SNS Filters

Question: I have two way SMS setup with Pinpoint where the incoming SMS gets sent to an SNS Topic.  I'd like to re-use this SNS topic for other phone numbers that are using two way.  However, the subscribers to that topic will need to only see messages for the phone number that that particular subscriber is concerned with.
I know about subscription filter policies.  However, the incoming SMS doesn't have a "Message Attributes" key and I haven't seen a way I can promote the "to" phone number or "keyword" to the message attribute so I can filter on it.
Is there a way to parse the body of the message to create the filter for a subscription?
Answer: There are no properties of a two way message that are promoted to be filtered on.  I ended up sending the message to a lambda that promotes the properties I needed and re-published the message to another topic.  I then had subscription filters subscribed to that topic.

Pinpoint & SNS Filters


How to work in ANdroid Studio in a Group/Team?

Question: Some friends of mine and I are developing an App as a school project in Android Studio because the only language we currently speak is Java, and we don't know how to work as Team e.g. How do we share the code with all of us, or if we shall do it with GitHub how does that work too? We have little experience in these things and would appreciate it a lot if you could help me what we could do and what is the best way to proceed
Comment: You're headed in the right direction. Maybe this can help - https://youtube.com/watch?v=eulnSXkhE7I
Answer: You need a distributed version control system.
The most common version control system is git, but svn and mercurial also exist.
Then the version control system needs a centralized way to distribute the latest changes to everybody. The most common is Github; there is also Bitbucket and Gitlab.
Since you ask very general questions, I think the easier way would be using Github because it is the most common, and it integrates fairly easily with Android Studio. Even when solving differences between files (conflicts), Android Studio offers some handy dandy dialogs to ease the editions.


Escaping special characters in custom submit handler redirect URL?

Question: My submit handler contains a redirect to a URL formatted thus:
mysite.com/node/123/edit?step=step_2

and my problem is that it's appearing in the browser bar as:
mysite.com/node/123/edit%3Fstep%3Dstep=step_2

which messes up my redirect.
How do I escape the characters "=" and "?" for use in a URL for redirection from a custom submit handler?
Answer: If you use an array as the value for $form_state['redirect'], it will eventually be passed to url(). So you can use the same options as for that function to build up a structured query string:
$path = 'node/' . $nid . '/edit';
$query = array('step' => 'step_2');
$form_state['redirect'] = array($path, array('query' => $query));

There's more explanation in the documentation for the drupal_redirect_form() function.


Porque meu CONTROLLER não está pegando campos da VIEW?

Question: Estou fazendo um formulário na VIEW, porém os campos onde utilizo radio e select(option) não estão passando seus valores para o Controller. Se alguém souber porque.
Minha VIEW:
@model GerenciadorDeAtividades.Dominio.RecursoDominio

@{
    ViewBag.Title = "Cadastrar";
}

Cadastrar

        @using (Html.BeginForm())
        {
            @Html.AntiForgeryToken()
            @Html.ValidationSummary(true)

            <fieldset>
                <legend>Novo Recurso</legend>

                            @Html.LabelFor(model => model.Nome)
                            @Html.TextBoxFor(model => model.Nome, new { @class = "form-control", style = "width: 50%" })
                            @Html.ValidationMessageFor(model => model.Nome)

                            @Html.LabelFor(model => model.Categoria)
                            <select class="form-control" style = "width: 40%">
                                <option value="Gerente">Gerente</option>
                                <option value="Coordenador">Coordenador</option>
                                <option value="Desenvolvedor">Desenvolvedor</option>
                                <option value="Funcional">Funcional</option>
                            </select>

                            @Html.LabelFor(model => model.UsuarioSAP)
                            @Html.TextBoxFor(model => model.UsuarioSAP, new { @class = "form-control", style = "width: 40%"})
                            @Html.ValidationMessageFor(model => model.UsuarioSAP)

                            @Html.LabelFor(model => model.UsuarioAD)
                            @Html.TextBoxFor(model => model.UsuarioAD, new { @class = "form-control", style = "width: 40%" })
                            @Html.ValidationMessageFor(model => model.UsuarioAD)

                            @Html.LabelFor(model => model.Email)

                                &#64
                                @Html.TextBoxFor(model => model.Email, new { @class = "form-control", style = "width: 37%" })
                                @Html.ValidationMessageFor(model => model.Email)

                            @Html.LabelFor(model => model.Desenvolvedor) ?

                                    <input type="radio" name="radioDesenvolvedor" id="simD" value="True" checked>
                                    Sim

                                    <input type="radio" name="radioDesenvolvedor" id="naoD" value="False">
                                    Não

                            @Html.LabelFor(model => model.Externo) ?

                                    <input type="radio" name="radioExterno" id="simE" value="True" checked>
                                    Sim

                                    <input type="radio" name="radioExterno" id="naoE" value="False">
                                    Não

                    <button class="btn btn btn-primary" type="submit">Criar</button>
                    <button class="btn btn btn-primary" type="button" onclick="history.go(-1)">Cancelar</button>

            </fieldset>
        }

Meu Controller:
public ActionResult Cadastrar()
    {
        return View();
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Cadastrar(RecursoDominio recurso)
    {
        if (ModelState.IsValid)
        {
            appRecurso.Salvar(recurso);
            return RedirectToAction("Index");
        }
        return View(recurso);
    }

Answer: Quando você utilizar tags sem Html Helpers você deve colocar o nome da propriedade. no seu caso, você está apenas adicionando o ID. Assim, ao dar o submit, sua View não reconhece a propriedade, não levando assim o valor para o seu Controller.
Porém, como você está utilizando Helpers, continue assim.
Ficaria assim o seu código:
     @model GerenciadorDeAtividades.Dominio.RecursoDominio

@{
    ViewBag.Title = "Cadastrar";
}

Cadastrar

        @using (Html.BeginForm())
        {
            @Html.AntiForgeryToken()
            @Html.ValidationSummary(true)

            <fieldset>
                <legend>Novo Recurso</legend>

                            @Html.LabelFor(model => model.Nome)
                            @Html.TextBoxFor(model => model.Nome, new { @class = "form-control", style = "width: 50%" })
                            @Html.ValidationMessageFor(model => model.Nome)

                            @Html.LabelFor(model => model.Categoria)
                            @Html.DropDownListFor(model => model.Categoria, new List<SelectListItem>
                                    {
                                        new SelectListItem{Text = "Gerente", Value = "Gerente"},
                                        new SelectListItem{Text = "Coordenador", Value = "Coordenador"},
                                        new SelectListItem{Text = "Desenvolvedor", Value = "Desenvolvedor"},
                                        new SelectListItem{Text = "Funcional", Value = "Funcional"}
                                    }, new { @class = "form-control" })

                            @Html.LabelFor(model => model.UsuarioSAP)
                            @Html.TextBoxFor(model => model.UsuarioSAP, new { @class = "form-control", style = "width: 40%"})
                            @Html.ValidationMessageFor(model => model.UsuarioSAP)

                            @Html.LabelFor(model => model.UsuarioAD)
                            @Html.TextBoxFor(model => model.UsuarioAD, new { @class = "form-control", style = "width: 40%" })
                            @Html.ValidationMessageFor(model => model.UsuarioAD)

                            @Html.LabelFor(model => model.Email)

                                &#64
                                @Html.TextBoxFor(model => model.Email, new { @class = "form-control", style = "width: 37%" })
                                @Html.ValidationMessageFor(model => model.Email)

                            @Html.LabelFor(model => model.Desenvolvedor) ?
                             @Html.RadioButtonFor( model => model.Desenvolvedor, true, new { id = "simD",  class="radio" } )
                            Sim

                            @Html.RadioButtonFor( model => model.Desenvolvedor, false, new { id = "naoD",  class="radio" } )
                            Não

                    <button class="btn btn btn-primary" type="submit">Criar</button>
                    <button class="btn btn btn-primary" type="button" onclick="history.go(-1)">Cancelar</button>

            </fieldset>
        }

Como você não postou as entidades, cheque se a propriedade model => model.Categoria existe. E a mesma coisa para o RadioButtonFor(). Caso esteja com nomes diferentes, basta renomear para o correto.


redirecting depending on mysql field value

Question: I have 3 fields in mysql called colour1, colour2, colour3 with either a 'red' or 'blue' value. When attendance1 2 & 3 are submitted it saves in mysql then redirects to submitted1.html.
however if value for each field is 'no' I want it to redirect to submitted2.
Comment: You have the redirect, and you have the three values. Maybe I'm just having a bad night, but have you never heard of an if? (Also, while I'm at it, by the HTTP specification, Location is to be specified with a full URL, not a relative one. And, you should check if the indexes of the post array are set before accessing them.)
Answer: just add this above the last header
<code>if($_POST['attendance1'] == 'no' && $_POST['attendance2'] == 'no' && $_POST['attendance3'] == 'no'){
    header("Location: otherpage.html");
    exit();
}
</code>
Comment: please use the full url for the location header.
Comment: Please read: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html.  Absolute URI's are required, so yes it should be /otherpage.html.  To state that a full URL is required is entirely incorrect according to Header Field Definition Standards per W3.
Comment: wrong, you don't know what absolute means:  HTTP/1.1 requires an absolute URI as argument to » Location: ... http://nz.php.net/manual/en/function.header.php
Comment: @JamesL. Dagon is right. 1. What is an absolute URL? "The two forms [relative vs. absolute] are differentiated by the fact that absolute URIs always begin with a scheme name followed by a colon" [1](http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.2.2) 2. the Location is defined as `Location = "Location" ":" absoluteURI`, see your own link.


Como criar um robô utilizando requisições em Java?

Question: Eu tenho me interessado em fazer robôs para realizar pequenas tarefas repetitivas e chatas. Eu utilizo uma classe do Java chamada Robot. Entretanto, acho que a maneira que estou fazendo não é a mais adequada, pois é um robô bastante artesanal que trabalha com eventos do mouse e do teclado. Gostaria de desenvolver um baseado em requisições ao servidor (GET e POST por exemplo), mas não sei que classe ou quais recursos e técnicas utilizar.
Eis um código de exemplo dos "robôs artesanais":
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

public class Robo {

    public static void main(String[] args) throws AWTException, IOException,
            URISyntaxException {
        Robot robot = new Robot();

        int login[] = {
            KeyEvent.VK_L,
            KeyEvent.VK_O,
            KeyEvent.VK_G,
            KeyEvent.VK_I,
            KeyEvent.VK_N,
        };

        int senha[] = {
            KeyEvent.VK_1,
            KeyEvent.VK_2,
            KeyEvent.VK_3,
            KeyEvent.VK_4,
            KeyEvent.VK_5,
            KeyEvent.VK_6,
            KeyEvent.VK_7,
            KeyEvent.VK_8,
            KeyEvent.VK_9,
            KeyEvent.VK_0};

        java.awt.Desktop.getDesktop().browse(
                new URI("https://registro.br/cgi-bin/nicbr/login"));
        robot.delay(3000);

        //Login
        for (int i = 0; i < login.length; i++) {
            robot.keyPress(login[i]);
            robot.delay(100);
            robot.keyRelease(login[i]);
            robot.delay(300);
        }
        robot.delay(200);
        robot.keyPress(KeyEvent.VK_TAB);
        robot.delay(100);
        robot.keyRelease(KeyEvent.VK_TAB);
        robot.delay(1000);

        //Senha
        for (int j = 0; j < senha.length; j++) {
            robot.keyPress(senha[j]);
            robot.delay(100);
            robot.keyRelease(senha[j]);
            robot.delay(300);
        }
        robot.keyPress(KeyEvent.VK_ENTER);
        robot.delay(100);
        robot.keyRelease(KeyEvent.VK_ENTER);
        robot.delay(1000);

        try {
            for (int i = 0, j = 1000; i < 1000; i++, j--) {
                robot.mouseMove(i, j);
                robot.delay(5);
            }
            robot.delay(500);
            //robot.mousePress(InputEvent.BUTTON1_MASK);
            //robot.mouseRelease(InputEvent.BUTTON1_MASK);
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
        robot.delay(200);
    }
}

Answer: Para fazer requisições HTTP em Java, é necessário utilizar a classe de conexão HTTP providas pela jdk. Um exemplo é a HttpURLConnection. Ainda é possível utilizar alguns pacotes apache destinados para este fim.
Para finalizar, a sua pergunta está um pouco ampla, mas, dependendo do que você queira fazer, talvez java não seja a linguagem ideal para o tipo de tarefa que você quer fazer, talvez uma linguagem de script, como python, seja melhor para os seus fins, já que a sua intenção é criar scripts para realizar tarefas chatas.
Comment: Perfeito. Vou procurar estudar a HttpURLConnection. Era exatamente isto que queria.
Answer: Você pode automatizar tarefas dentro do computador utilizando algumas ferramentas.
Eu conheço estas duas ferramentas muito boas para automatizar tarefas, apesar de utilizarem linguagens próprias.

autohotkey
autoit ( recomendo )

Se você precisa de algo um pouco mais específico você pode utilizar a biblioteca Selenium
Se precisar um controle ainda mais especifico que trabalhe com requisições (GET,POST,PUT etc) e alguma interpretação do html melhor utilizar a biblioteca HttpCommons.


fmt.Printf("%f\n",x) rounds a Float64 to Float32, but fmt.Println(x) doesn't

Question: I was working on some tests with dictionaries, to do this I print out the Float64 values I want from a database in a format to copy and paste them into my test struct array, but when my tests failed I noticed that the values differ, but only by 0.0000000000002
Then, to check the value I wrote the following in a loop:
fmt.Printf("%f\n",value)
fmt.Println(value)

And I got the following values back:
702.200000
702.1999999999998
5683.090000
5683.089999999998
975.300000
975.3

I checked the docs and saw nothing that indicates that there's special notation for Float64 or that %f will replace Float64 for a Float32, however, I don't get the problem when I use %v or %g and the docs specify that they'll use %f when appropriate.
I don't get the problem when I specify a precision of 12 using %.12f either, but no default precision is specified in the docs.
Why does this happen?
EDIT: This is the same issue as the duplicate, but I believe Adrien's explanation about it is more detailed.
Comment: Possible duplicate of [Does converting a string to a float lose precision?](https://stackoverflow.com/questions/54169068/does-converting-a-string-to-a-float-lose-precision)
Answer: From the docs:

The default precision for %e, %f and %#g is 6; for %g it is the smallest number of digits necessary to identify the value uniquely.
Comment: The rest of the docs do, specifically that `%v` uses the "default format" which for "float32, complex64, etc" is `%g`, and that (regarding default precision) "for %g it is the smallest number of digits necessary to identify the value uniquely"
Comment: `fmt` has very thorough docs but they could definitely use a rewrite. It's full of internal references with no anchor links and details buried in the middle of a paragraph. It's unfortunate given how much use the package gets.
Comment: Ah, crud. I don't know why I didn't see that. I went through the docs to avoid exactly this. However, it doesn't explain why the precision changes when I use %v or %g, as stated in the question.
Comment: Thanks a lot Adrian! I don't know how I missed this, I'll blame the lack of morning coffee.


How to use spread props with Typescript using styled-components in React?

Question: So I am creating a UI component for my app to make styling consistent. That means, I need access to spread props for doing things like value, onChange etc.
This is what my TextInput component looks like:
import { DetailedHTMLProps, InputHTMLAttributes } from 'react';
import styled from 'styled-components';

const StyledInput = styled.input`
  display: block;
  width: 100%;
  margin-top: 0.5rem;
  padding: 0.5rem 1rem;
  border-radius: 0.25rem;
  border: 1px solid #e2e8f0;
  line-height: 1.5;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
`;

export const TextInput = ({
  ...rest
}: DetailedHTMLProps<
  InputHTMLAttributes<HTMLInputElement>,
  HTMLInputElement
>) => (
  <>


Not advisable to run ESX 4.0 host with 128Gb RAM - is there any truth to that?

Question: I was advise by my webhosting company providing managed colocation dedicated server service that adding 128Gb RAM to a Sunfire X2200M2 Server (Dual Quad Core 1.9Ghz) to run ESX 4.0 Host would not be advisable.
The Sunfire server support a maximum 128GB RAM, but they say its no point adding that much RAM as the Dual Quad Core CPU 1.9Ghz won't be able to cope with so much RAM in a virtualise environment and they recommend 24GB as the maximum. Anything higher, will experience performance degration. Does it make any sense to you?
The maximum supported RAM for ESX4.0 is 1TB as stated in the configuration maximum doc:
http://www.vmware.com/pdf/vsphere4/r40/vsp_40_config_max.pdf
The following shows that 128GB host has been deployed on HP hardware, so why not Sunfire??
http://www.eliaskhnaser.com/Article.aspx?blog=2&id=33
Any ESX guru out there like to share their thoughts? Thank you.
Answer: According to Sun's specs the max RAM it'll take is 64Gb. That said, there's no reason not to take ESXi or that server to its max ram. Unless your colo techs can come up with a very specific reasons. We're running ESXi servers quite happily with >100Gb of RAM on Dell and HP hardware, so unless there's some technical limit on that particular server model, I'd say you're good to go. The server is on VMWare's ESXi Hardware Compatibility List with a max RAM listing of 64Gb.
In my experience, with 2008 becoming more common as a VM Guest OS, you almost always run out of RAM on a virtual host before you run out of CPU. It depends on workload, of course, but VMs LOVE RAM, and this trend seems to be getting more and more pronounced.
I would warn that 8Gb RAM sticks are uneconomically expensive (3x or more the cost of 4Gb sticks). 4Gb sticks seem to be the sweet spot.
Another suggestion: If you're considering taking a single host to such a high level of RAM and this is your only ESXi host, you are putting a lot of eggs in 1 basket. A good option that gets you both scalability and resilience is to buy a second identical server and run them as a pair with less ram per server... Then if your one server falls over, you won't lose your environment.
EDIT: Just to illustrate the CPU-vs-memory usage in a production environment, here's a snippet from an email I sent out a few days ago, showing CPU and RAM utilization on virtual hosts at one of our datacenters. The servers in question are  HP DL360 G6 dual-quads with 70Gb RAM per host, running ~160 VMs across the 5. I'd love to see if others are seeing similar trends, or if this is just a characteristic of our workloads.
Comment: +1 very good answer =)
Comment: +1 nice answer. And I can confirm the CPU-vs-memory aspect. We have a somewhat older setup with 8 DL380 G5 with dual-quads and 16 GB RAM each, and we are starting to hit the limits running about 60 VMs.
Comment: +1 I want to also confirm cpu vs memory. We have three 32 GB servers where the memory usage is at 55-60% while the CPU is at 10-20%. Each server has eight 3.16 GHz CPU cores. We have 26 server VMs.
Comment: Thanks Chris for sharing your insights. And also pointing out that the server only supports max. 64GB. I had missed out on this detail, its worries me that they are using E.O.L model. But we are only leasing.

There is plan for another ESX Host with vCentre, adding as much RAM as possible is just to fulfill the web app requirement which needs as much RAM as possible for memcached servers and database server.

Great to know about the CPU vs RAM utilisation, thank you very much for sharing.

Cheers,
JK


Can somebody identify this distribution?

Question: I am searching for the name of the distribution associated with this density on $\mathbb{R}_+$:
$$p(r|\lambda) = \frac{2\lambda r\exp\left(\lambda\exp\left(-r^{2}\right)-r^{2}\right)}{\exp\left(\lambda\right)-1}.$$
It arises from the mixture distribution of
$$p(r|n)=2nr\cdot\exp\left(-nr^{2}\right)$$
($n\in \mathbb N_+$) with mixture weights from a "positive" Poisson distribution on $n>0$
$$p(n|\lambda)=\frac{\lambda^n \exp(-\lambda)}{n! (1-\exp(-\lambda))}$$
I first thought it looked like a Gumbel distribution, but I couldn't get it into the right shape.
Comment: There are plenty of ways this can be transformed into a "named" distribution.  *E.g.*, writing $r^2=-\log(\log(z))$ entails $1\lt z \lt e,$ $|dr|=dz/(z\log(z))$, and

$$2 r\exp\left(\lambda\exp\left(-r^{2}\right)-r^{2}\right)|dr|=z^{\lambda-1}\, \mathrm{d}z.$$

This exhibits the distribution as a transformation of a truncated power law.
Comment: The situation is not that trivial: the transformation to uniformity you refer to captures all the information about the distribution and typically is specific to that distribution. When you can find a *fixed, simple* transformation that--when applied to all distributions within a parameterized family--produces nice formulas, then you have accomplished something. That is why @Xi'an proposes a square and why I have pointed out the log-log transformation. These are perfectly analogous to the relationship between Normal and Lognormal distributions, for instance.
Comment: I completely agree. I was actually searching for the name of the distribution in that parametrization. Otherwise we could call all distributions uniform on $[0,1]$.
Comment: Hmm, I guess I misunderstood your previous point. But I see your last point.
Answer: I think it relates to a Gumbel distribution:
if I define $S=R^2$, when $R\sim p(r|\lambda)$, the density of $S$ is given by the Jacobian formula:
\begin{align*}
q(s|\lambda) &= p(\sqrt{s}|\lambda)\times \left|\frac{\text{d}r}{\text{d}s}\right|\\
&= p(\sqrt{s}|\lambda)\times \frac{1}{2\sqrt{s}}\\
&= \frac{2\lambda \sqrt{s}\exp\left(\lambda\exp\left(-s\right)-s\right)}{\exp\left(\lambda\right)-1}\,\frac{1}{2\sqrt{s}}\\
&= \frac{\lambda \exp\left(\lambda\exp\left(-s\right)-s\right)}{\exp\left(\lambda\right)-1}\\
&= \frac{\exp\left(\exp\left(\log\{\lambda\}-s\right)+\log\{\lambda\}-s\right)}{\exp\left(\lambda\right)-1}\\
&= \frac{\exp\left(\exp\left(-z\right)-z\right)}{\exp\left(\lambda\right)-1}\\
\end{align*}
where $z=s-\log\{\lambda\}$
So $S$ is almost distributed as a Gumbel distribution with parameter $(\log\{\lambda\},1)$ except that (a) its support is truncated to $(0,+\infty)$ and (b) there is a missing - in front of the exponential inside the exponential...
This means that $S-\log\{\lambda\}$ has a fixed distribution with the above density and cdf $F$. From this representation, there exists a transform $G^{-1}\circ F$ (with $G$ being the cdf of the Gumbel distribution) that turns $ S-\log\{\lambda\}$ into a standard Gumbel, but this is not very useful!
Note that, in the mixture representation, $S=R^2$ is then distributed as an Exponential $\mathcal{E}(n)$ variate.
Comment: I think Grumble distribution would be an awesome name. :)
Comment: Thanks for the answer Xi'an, but if it were a Gumbel distribution, shouldn't there be a "-" in front of the second exp, i.e. $\exp(-\exp(-x)-x)$.
Comment: Right! So this is an imaginary Gumble! (grumble, grumble)


How to customize the 'node content links' block?

Question: I'm using Organic Groups to make groups, and have made two content types to be added to the groups. I'm also using the OG extras module, so now I have the 'Node content links' block, where users may add content to the group. I want some of the users to see one of the links to create one content type, and the other users to see the other link to create the other content type.
How am I able to do this? Do I need to use organic group roles? If so, I'm unable to find out where I set this type of role for a member. I know where I can create them, but not assign them.
Answer: I was looking for this myself and come across this link:
http://makandracards.com/jan0sch/11463-drupal-organic-groups-extras-add-content-links
If you're using Drupal 7 and Organic Groups (2.x) you probably have the OG extras module enabled.
The documentation to enable the "create content" links for your organic group nodes is sparse. Therefore a short howto:

Enable all needed modules Enable the module entityreference
prepopulate!
Go to "Structure" -> "Content types" and select your
group content type, not your group type.
Click on "manage fields" and edit the field "og_group_ref".
Enable the checkbox labeled "Enable Entity reference prepopulate".
Enable the block named "Node content links".
Now you should be done. Steps 4-5 are needed for every group
content type in case you have multiple content types that can be
posted to groups.


SpringFramework and DBUnit integration test NoSuchBeanDefinitionException Java

Question: I am writing an integration test on a Spring controller. and i have this NoSuchBeanDefinitionException exception. I suppose that i do not have declared some bean in xml but i do not find any information.
ControllerTest
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, DirtiesContextTestExecutionListener.class,
        TransactionalTestExecutionListener.class, DbUnitTestExecutionListener.class })
@DatabaseSetup("login.xml")
public class LoginControllerTest2 {

    private static final String JDBC_DRIVER = "org.h2.Driver";
    private static final String JDBC_URL = "jdbc:h2:mem:login;DB_CLOSE_DELAY=-1";
    private static final String USER = "sa";
    private static final String PASS = "";
    private static final String SCHEMA_FILE = "h2.sql";
    private static final String DATASET = "login.xml";

    private MockMvc mockMvc;

    @Autowired
    private WebApplicationContext wac;

    @BeforeClass
    public static void createSchema() throws ClassNotFoundException {
        Class.forName(JDBC_DRIVER);
        try {
            Connection conn = dataSource().getConnection();
            InputStreamReader in = new InputStreamReader(LoginControllerTest2.class.getResourceAsStream(SCHEMA_FILE));
            RunScript.execute(conn, in);
        } catch (Exception e) {
            // TODO: handle exception
        }
    }

    @Before
    public void loadTestData() throws Exception {
        this.mockMvc = MockMvcBuilders.webApplicationContextSetup(this.wac).build();
        IDataSet ids = new FlatXmlDataSetBuilder().build(LoginControllerTest2.class.getResourceAsStream(DATASET));
        JdbcDatabaseTester databaseTester = new JdbcDatabaseTester(JDBC_DRIVER, JDBC_URL, USER, PASS);
        databaseTester.setSetUpOperation(org.dbunit.operation.DatabaseOperation.CLEAN_INSERT);
        databaseTester.setDataSet(ids);
        databaseTester.onSetup();
    }

    private static DataSource dataSource() {
        JdbcDataSource dataSource = new JdbcDataSource();
        dataSource.setURL(JDBC_URL);
        dataSource.setUser(USER);
        dataSource.setPassword(PASS);
        return dataSource;
    }

    @Test
    @ExpectedDatabase("login.xml")
    public void testShowForm() throws Exception {
        mockMvc.perform(get("/login")).andExpect(status().isOk()).andExpect(view().name("/login"))
                .andExpect(forwardedUrl("../../WebContent/j/login.jsp"))
                .andExpect(model().attribute("form", hasProperty("passportId", nullValue())))
                .andExpect(model().attribute("form", hasProperty("email", isEmptyOrNullString())))
                .andExpect(model().attribute("form", hasProperty("username", isEmptyOrNullString())))
                .andExpect(model().attribute("form", hasProperty("hostname", isEmptyOrNullString())))
                .andExpect(model().attribute("form", hasProperty("pass", isEmptyOrNullString())));
    }

}

Stack Trace
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'test.loginController.LoginControllerTest2': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.springframework.web.context.WebApplicationContext test.loginController.LoginControllerTest2.wac; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.web.context.WebApplicationContext] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1210)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:385)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:127)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:85)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:231)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:95)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.invokeTestMethod(SpringJUnit4ClassRunner.java:139)
    at org.junit.internal.runners.JUnit4ClassRunner.runMethods(JUnit4ClassRunner.java:51)
    at org.junit.internal.runners.JUnit4ClassRunner$1.run(JUnit4ClassRunner.java:44)
    at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:27)
    at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:37)
    at org.junit.internal.runners.JUnit4ClassRunner.run(JUnit4ClassRunner.java:42)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.springframework.web.context.WebApplicationContext test.loginController.LoginControllerTest2.wac; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.web.context.WebApplicationContext] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:561)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
    ... 18 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.web.context.WebApplicationContext] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1301)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1047)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:942)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:533)
    ... 20 more

XML
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jdbc="http://www.springframework.org/schema/jdbc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
            http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd">

    <tx:annotation-driven transaction-manager="transactionManager" />
    <context:component-scan base-package="test.loginController" />

    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy">
        <constructor-arg>
            <bean class="org.springframework.jdbc.datasource.SimpleDriverDataSource">
                <property name="driverClass" value="org.h2.Driver" />
                <property name="url"
                    value="jdbc:h2:mem:login;DB_CLOSE_DELAY=-1;TRACE_LEVEL_SYSTEM_OUT=2;TRACE_LEVEL_FILE=4" />
                <property name="username" value="sa" />
                <property name="password" value="" />
            </bean>
        </constructor-arg>
    </bean>

    <jdbc:initialize-database data-source="dataSource">
        <jdbc:script location="/test/loginController/h2.sql" />
    </jdbc:initialize-database>

</beans>

Answer: Spring's @ContextConfiguration annotation without specifying any attributes. In this case the default GenericXmlContextLoader.
Try to add specific file xml something like configuration.xml:
   @ContextConfiguration("configuration.xml")
   @TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, DirtiesContextTestExecutionListener.class,  TransactionalTestExecutionListener.class, DbUnitTestExecutionListener.class })
   @DatabaseSetup("login.xml")
   public class LoginControllerTest2 {

You can use:
  @ContextConfiguration(classes = { Name_class.class })

Or:
  @ContextConfiguration(loader=AnnotationConfigContextLoader.class)

If you don't would to use @ContextConfiguration you can  use just @Configuration with xml file of configuration.
For more details got to link
Comment: the file in @ContextConfiguration can not be added that way.
Answer: I believe you need to add the @WebAppConfiguration annotation to your class, also, try specifying the XML location in the @ContextConfigurationannotation.
Comment: I can not specify the location of xml in @ContextConfiguration.
Comment: Can't you do it like this? `@ContextConfiguration(locations = { "classpath:/context-config.xml"})`, of course change the route to wherever your xml actually is. Also, did adding the @WebAppConfiguration annotation change anything?
Answer: I think this link demonstrates the best way to get application context anywhere, even in the non-bean class. I find it very useful. Hope its the same for you. The below is the abstract code of it .
Create a new class ApplicationContextProvider.java
    package com.myPackage.spring;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class ApplicationContextProvider implements ApplicationContextAware{

private static ApplicationContext context;

public static ApplicationContext getApplicationContext() {
    return context;
}

@Override
public void setApplicationContext(ApplicationContext ac)
        throws BeansException {
    context = ac;
   }
}

Add an entry in Applkication Context.xml or any other file in which you are autowiring Beans
<bean id="applicationContextProvder" class="com.myPackage.spring.ApplicationContextProvider"/>

Get the context like this
   @Autowired ApplicationContextProvider appContextProvider
     this.mockMvc = MockMvcBuilders.webApplicationContextSetup(appContextProvider.getApplicationContext()).build();

Hope This Helps !!!


Basic questions about Hyper-V

Question: I'm more xen & vmware experienced, that's why I do not have any deep knowledge of Hyper-V..
Please, help me with these questions:
I would like to have cluster made of 2 nodes (mostly Linux is virtualized).
1) What do you recommend, to have 2 Hyper-V servers and management consoles, or 2 Win2008 with Hyper-V ? What are the benefits of having win2008 with this feature?
2) How it is called that management console ? Could you please tell me the approximate pricing ?
3) Does the free edition of hyper-v server support some kind of high availability ? (one physical host goes down, and all running VMs are transfered on another host)
Thank you.
Answer:
Windows Hyper-V server is essentially just a Server Core installation (no GUI) with just the Hyper-V role. Server 2008 with Hyper-V is a a full version of Server 2008 with the Hyper-V role available. So if you want to use your Hyper-V host to do other things as well as host VM's (not really a good plan) then you will want the full version of Server 2008.
The management console is installed on a client machine, in the case of a server core installation, on a full instllation you could install it on the Hyper-V server its self, but I would reccomend having it on a client machine. There is no separate cost for the management console.
The free Hyper-V server does support host clustering and live migration, it does not support application fail over. See here for more information.
Comment: Good write-up. Two things: #2. He might be thinking of the [SCVMM](http://microsoft.com/scvmm) which is a much more advanced console for Hyper-V and ESX; it's not free, highly recommended for medium & large clusters. The normal Hyper-V & Clustering MMCs can accomplish most of the same though. #3. Hyper-V Server or Windows Server EE & DC support HA, Windows Server SE does not. Hyper-V Server is based on Windows Server Core EE with the other roles & licensing stripped out (plus a few other minor changes...).
Comment: @memjo as Chris mentioned, they Hyper-V console is a free MMC snap in that is available from a Windows client (when installed), this is free and will allow you to manage your VM's. If you want the more advanced control you get with SCVMM then you will need ot pay for this.
Comment: Thank you, but what is then XenCenter alternative in Hyper-V environment? I mean, I would welcome some GUI, where I am able to manage the VMs and cluster features, connect to VM console and so on. Is it System Center?
Answer: @Chris-S Thanks for the corrections!:

To support Microsoft Failover Clustering Services for Live Migration you need either free Hyper-V Server 2008 R2 or full Windows Server 2008 R2 Enterprise/Datacenter editions.
Maybe you mean SCVMM?  It's the optional add-on management system that does P2V, automated VM templates, etc. http://www.microsoft.com/systemcenter/en/us/virtual-machine-manager.aspx
You want to do live migration which requires you to setup Windows Clustering.  You must have iSCSI, shared SAS, or Fiber Channel SAN to store the VM's and I recommend minimum 4 NIC's in hosts.
Comment: 1. Windows Core can do HA; Windows Server SE can not, you need EE or DC. The free Hyper-V Server can also do HA. 3. You can also use a SAS SAN; MS recommends 4 NICs for network traffic and 2 more for SAN traffic; though I tend to agree with your 4 recommendation for smaller clusters.
Comment: @Chris-S, thank you for the corrections.  I learn something or re-learn something every day here :)

Basic questions about Hyper-V


How do I edit a Java-Desktop menu item?

Question: I need to edit a menu item for all users in the Launch menu of Java Desktop on a system running Solaris 10.  I need to set the launcher to a different executable.  I have followed the steps in the Java Desktop Administration Guide.  I can set the launcher to the correct file but cannot find an option to save the change.  Is there a way to do this from the command line?
Answer: Launch Menu/Applications, items are stored in /usr/share/applications in .desktop files.  One file per Launcher.  You can manually edit these files.  The launcher commands are in there near the bottom.
For Launchers outside of Applications, I'm actually trying to discover how those are controlled.  I need to remove a launcher under Launch Menu/Preferences

How do I edit a Java-Desktop menu item?


Running thin server as a init.d script on CentOS 6.3

Question: I followed the Slicehost tutorial here and was able to get thin installed in init.d to be able to start at boot.
I also created the required configuration file. When running thin from the command line logged in as root using the command below it works perfectly.

thin start -C /etc/thin/:config:.yml

However, when running thin using service thin start I get the following from the log files:
>> Writing PID to tmp/pids/thin.3000.pid
>> Changing process privilege to apache:apache
>> Using rack adapter
>> Exiting!
/var/www/sites/<path>/vendor/bundle/ruby/1.9.1/gems/guard-1.6.2/lib/guard.rb:23:in `expand_path': couldn't find HOME environment -- expanding `~' (ArgumentError)

I suspect there is some environment configuration setting missing but have no idea what to look for.
Has anyone been able to get this working or have any suggestions on what I can do to get this working?
Answer: Try adding a source of the profile directory to your init script near the top. Looks like the $HOME variable isn't defined.
. /etc/profile

Comment: Thank you for putting me on the right track. I made it simple and just added `export HOME=` into the script directly, since for some reason the  `. /etc/profile` didn't work. It's a quick hack for now but it is in a testing environment.


Separate JS and CSS list output of media class object for Django form in template

Question: I have simple question here. I know how to use django media in order to put js and css files which is specified in media class like this:
In forms.py for model
from django import forms

class CalendarWidget(forms.TextInput):
    class Media:
        css = {
            'all': ('pretty.css',)
        }
        js = ('animations.js', 'actions.js')

In template file
{{ form.media }}

However I want to put separately JS and CSS. It means I want to put CSS at head section and JS before body tag. So how I can achieve it using build in tags? Is it possible?
P.S. I cannot find out information from django documentation. (Perhaps, I look in wrong place). So give me a hint.
Answer: You can use {{form.media.css}} and {{form.media.js}} separately to put them at required places.
Reference docs subsets-of-assets.


Why for a multilinear form $w(X,Y,Z)$ it suffices to say that interchanging $X$ and $Y$ and $X$ and $Z$ changes the sign for $w$ to be alternating?

Question: Why for a multilinear form $w(X,Y,Z)$ it suffices to say that interchanging $X$ and $Y$ and/respectively $X$ and $Z$ changes the sign for $w$ to be alternating?
Answer: If you consider the case of a bilinear form, say $\omega$, note that if $\omega (x,y) = - \omega(y,x)$, then $\omega (x,x) = - \omega (x,x) \implies \omega (x,x) = 0$ so $\omega$ is alternating.
Formally a multilinear form is alternating if the symmetric group acts on the form by multiplying by the sign of the permutation. Note that $S_3$ is generated by a swapping of the first two elements, and a swapping of the first and last element. Specifying the action by the generators ends up specifying it for all 6 elements of $S_3$ and you can confirm it matches the definition of a multilinear form.
Answer: If you have a multilinear form $w$ with $n$-variables $(x_1,x_2\dots,x_n)$, you have to check that, for every $\sigma \in S_n$ ($S_n$ being the symmetric group) : $$w(x_{\sigma(1)},x_{\sigma(2)}\dots,x_{\sigma(n)}))=sign(\sigma)w(x_1,x_2\dots,x_n).$$
With $sign(\cdot)$ being the signature of the permutation.
If you found out that this is true for $\sigma_1,...\sigma_m$ such that $S_n=<\sigma_1,...\sigma_m>$, then it is true for every $\sigma$.
Indeed ; $$w((x_{\sigma_1 \circ \sigma_2 (1)},x_{\sigma_1 \circ \sigma_2 (2)}\dots,x_{\sigma_1 \circ \sigma_2 (n)}))=sign(\sigma_1)sign(\sigma_2)w(x_1,x_2\dots,x_n).$$
Since $(12)$ and $(13)$ generates $S_3$, then you only need to check for those two permutations if you have a trilinear form.


Crossfilter average group

Question: Im trying to calculate the average querytime by sum(querytimes) and then dividing them by a count.How can i get the count ?
var querytimeByMonthGroup = moveMonths.group().reduceSum(function (d) {
    return d.querytime;
});

var querytimeByMonthGroup = moveMonths.group().reduceSum(function (d) {
    return d.querytime / d.count; ???
});

Answer: I think a better (and the intended) way to do this is by defining your own reduce functions (add, remove, initial). You can then store your running sum, count etc. within the reduce functions and adjust them as appropriate when the filters add & remove data from the group.
An example of doing this with averages and with min & max are given in this similar question: Using Crossfilter, is it possible to track max/min when grouping?
Answer: I am not familiar with crossfilter, only just started playing with it. There may be a better way, but this provides a way to compute the count for the dimension(s) used for the grouping (I am not 100% clear that d.count refers to the count for the dimension used for the grouping, use another grouping if required).
Example derived from the code available at: https://github.com/square/crossfilter/wiki/API-Reference
var payments = crossfilter([
    {date: "2011-11-14T16:17:54Z", quantity: 2, total: 190, tip: 100, type: "tab"},
    {date: "2011-11-14T16:20:19Z", quantity: 2, total: 190, tip: 100, type: "tab"},
    {date: "2011-11-14T16:28:54Z", quantity: 1, total: 300, tip: 200, type: "visa"},
    {date: "2011-11-14T16:30:43Z", quantity: 2, total: 90, tip: 0, type: "tab"},
    {date: "2011-11-14T16:48:46Z", quantity: 2, total: 90, tip: 0, type: "tab"},
    {date: "2011-11-14T16:53:41Z", quantity: 2, total: 90, tip: 0, type: "tab"},
    {date: "2011-11-14T16:54:06Z", quantity: 1, total: 100, tip: 0, type: "cash"},
    {date: "2011-11-14T16:58:03Z", quantity: 2, total: 90, tip: 0, type: "tab"},
    {date: "2011-11-14T17:07:21Z", quantity: 2, total: 90, tip: 0, type: "tab"},
    {date: "2011-11-14T17:22:59Z", quantity: 2, total: 90, tip: 0, type: "tab"},
    {date: "2011-11-14T17:25:45Z", quantity: 2, total: 200, tip: 0, type: "cash"},
    {date: "2011-11-14T17:29:52Z", quantity: 1, total: 200, tip: 100, type: "visa"}
]);

var paymentsByType = payments.dimension(function(d) { return d.type; }),
        paymentVolumeByType = paymentsByType.group(),
        counts = paymentVolumeByType.reduceCount().all(),
        countByType = {};

// what is returned by all is a pseudo-array. An object that behaves like an array.
// Trick to make it a proper array
Array.prototype.slice.call(counts).forEach(function(d) { countByType[d.key] = d.value; })
var paymentVolumeByType = paymentVolumeByType.reduceSum(function(d, i) {
    console.log(d.total, d.type, countByType[d.type])
    return d.total / countByType[d.type];
});
// accessing parentVolumeByType to cause the reduceSum function to be called
var topTypes = paymentVolumeByType.top(1);

Comment: The comment below is the intended way to achieve this.

Crossfilter average group


Quais as versões do SDK Android que, no mínimo, devo ter instaladas?

Question: Quando baixei o Android Studio e abri o SDK Manager ele mostra alguns pacotes para serem baixados e instalados. Vi que tem diversas versões de Android.
As minhas dúvidas são:

Quais deles são "extremamente" indispensáveis para que eu possa fazer build de App Android na minha máquina?
Por exemplo: Quero rodar na versão android 5.1.1. Preciso realmente baixar os mais de 10GB do pacote 5.1.1 inteiro?
Answer:
Quais deles são "extremamente" indispensáveis para que eu possa fazer build de App Android na minha máquina.

As versões que tem de ter na sua máquina são:

A versão mais recente. Deve compilar sempre a aplicação usando a versão mais recente da API. Assim poderá utilizar todos os recursos do SDK, incluindo os novos que não existem em versões anteriores.
Deve indicá-la no build.gradle em compileSdkVersion version.
As versões para as quais quiser criar emuladores. Se quiser testar a aplicação num emulador com Android 3, tem de fazer o download da API 11.

Quero rodar na versão android 5.1.1. Preciso realmente baixar os mais de 10GB do pacote 5.1.1 inteiro?

Não, desde que siga a regra de usar sempre a API mais recente para compilar a aplicação.
Sim, se quiser criar um emulador com Android 5.1.1 para testar a aplicação.

Onde a sua aplicação pode rodar, depende do que foi informado no build.gradle em defaultConfig(equivalente á tag <uses-sdk> no AndroidManifest.xml).
Ela tem três atributos:

android:minSdkVersion="integer"
android:targetSdkVersion="integer"
android:maxSdkVersion="integer"

Esses três atributos permitem à aplicação informar a sua compatibilidade com uma ou mais versões do Android.
O seu significado é o seguinte:

android:minSdkVersion="integer" - Indica o nível mínimo da API requerido para a aplicação correr. O Android não deixará que a aplicação seja instalada em dispositivos com um nível da API inferior ao valor indicado por este atributo.
android:targetSdkVersion="integer" - Indica o nível da API para o qual a aplicação foi feita.
Informa o sistema que a aplicação foi testada para correr nesse nível e o sistema não deverá disponibilizar qualquer tipo de "comportamento de compatibilidade" para a executar em dispositivos com nível de API igual.
android:maxSdkVersion="integer" - Indica o nível máximo da API em que a aplicação pode correr.
O Android não permitirá que a aplicação seja instalada em dispositivos com um nível da API superior ao valor indicado neste atributo.
Atenção: A declaração deste atributo não é recomendada, as novas versões da API são desenhadas para serem compativeis com as versões anteriores. Não há razão para intensionalmente bloquear a possibilidade da aplicação ser instalada em novas versões.
Comment: Não sei se entendi muito bem essa afirmação: **A versão mais recente. Deve compilar sempre a aplicação usando a versão mais recente da API. Deve indicá-la no build.gradle em compileSdkVersion version.** Existe alguma razão para isso? Ou melhor, se eu não utilizar a API mais recente não irá funcionar?
Comment: @Randrade Ao utilizar a versão mais recente irá poder utilizar todas os recursos dessa versão, recursos esses que poderão não existir em versões anteriores.
Comment: Entendi. É que ao ler aquela afirmação eu entendi outra coisa. Mas obrigado por esclarecer. :p
Answer: Também tive essa dúvida quando comecei a programar para Android.
Geralmente uso uma lista pequena de pacotes (o mínimo necessário) porque eu não dependo de emulador para testar o código, testo direto no Smartphone.
Lista mínima:
Tools:

Android SDK Tools
Android SDK Platform-tools
Android SDK Build-tools

Android N.N (API NN)

SDK Platform

Extras

Android Support Repository
Google Repository

Substitua NN pelo nível de API que é seu alvo android:targetSdkVersion (22 é para Android 5.1).
Caso você programe no Windows talvez vá precisar do Google USB Driver.
Se você precisa de um emulador, não precisa baixar todas imagens, baixe apenas as que tem Intel x86 Atom System image ou Intel x86 Atom_64 System image (se seu computador for de 10 anos pra cá). Obs.: é bom ter no mínimo uns 8 GB de RAM.
Um caso em que o pacote Android Support Repository é necessário é quando seu android:minSdkVersion difere do android:targetSdkVersion.


How to invoke method of QML object from C++

Question: I have following QML code:
Rectangle {
id: mainRect
...
    Rectangle{
    id: listRect
    ...
       ListModel {
          id: idModel
          ... some stuff added
       }
    }
}

And I want to clear idModel, using clear method of ListModel.
Stuff like this (inside QML) works perfectly:
 idModel.clear()

But I want to achieve same in C++.
Tried following:
  QQuickView view;
  view.setSource(QUrl("qrc:/main.qml"));
  QQuickItem* item = view.rootObject();
  QObject* model = item->findChild<QObject*>("mainRect")->findChild<QObject*>("listRect")->findChild<QObject*>("idModel");
  QMetaObject::invokeMethod(model,"clear");

also tried to search model as
 QObject* model = item->findChild<QObject*>("idModel");
 QObject* model = item->findChild<QObject*>("listRect")->findChild<QObject*>("idModel");

But this stuff above not working... I can't even understand - if nothing is found by findChild method in C++, or InvokeMethod is not working.
Could anyone explain this to me?
Using QT5.4 \ QtQuick 2.4
Answer: To use findChild() you should set objectName to your qml item.
Rectangle {
id: mainRect
...
    Rectangle{
    id: listRect
    ...
       ListModel {
          id: idModel
          objectName: "idModel"
          ... some stuff added
       }
    }
}

Then, you can get pointer to your ListModel
QObject* model = item->findChild<QObject*>("idModel");

To invoke method, you should use QMetaObject::invokeMethod()
QMetaObject::invokeMethod(model,"clear");


Tips on manually rebalancing data across a Parity Storage Space pool in Windows Server 2012 R2

Question: On my HP Microserver N54L which acts as file server, I have a parity storage spool consisting of the following:

4x 2TB WD Caviar Green
1x 3TB WD Caviar Green (Recently added)

The OS (Server 2012 R2) is run on an SSD.
The 2TB drives are all over 70% used, I added the 3TB drive recently because of low capacity warnings. What I didn't realise until finding out now is there is no data rebalancing system in 2012 R2, so the new drive I have added is not being used as I thought it would once introduced into the pool.

Furthermore I am now getting the prompt to add two additional drives to the pool, even though there is plenty of capacity since the upgrade, I'm assuming because all 4 of the 2TB drives are over 70% used, this warning is being generated.
Are there options available to manually rebalance the data across all the drives, reducing the usage on the 2TB drives, and sharing it across the new 3TB? Would Windows correct the issue overtime, simply by new data being introduced to the pool, its apparent there isn't any PowerShell commands available to do it, though apparently Microsoft have introduced this in Windows Server 2016, but this doesn't help my situation and its doubtful this feature would be added to 2012 R2.
I'm wondering if similar situations have happened to others and what the best action is to resolve it?
Answer: I know this an old thread. But maybe create a VHDX file in "disk manager" on the storage space. Then mount it move all your data into it.
Comment: I would of never of thought of that, that is a good idea!
Answer: 70% is simply the default warning.
A 3-column parity space requires free space on at least 3 drives in order that you can write data to it.
You are being asked to add 2 new disks because pretty soon only one disk will have free space, not the required 3.
You can manually rebalance by moving data off the parity space, and then moving it back on. When it gets written back to the parity space, it will do its best to distribute the chunks in a more balanced way taking into account the new 3TB drive. However due to the size mismatch you are always going to 'waste' some.
If you don't have somewhere to move the data to, you can likely achieve a limited rebalance by creating a simple (unprotected) storage space on the same storage pool. Move a couple of gigs of files there, then move it back to the parity space.
Naturally the files will be unprotected while on the simple space so only do this if you have a backup.
Comment: I found out that 70% was the default threshold you can adjust it via PowerShell `Set-StoragePool -FriendlyName "Friendly Pool Name" -ThinProvisioningAlertThresholds 85` as an example. I understand the add more drives warning better now, thanks. I guess I'll have to do some manual moving of data around to try and bring down the usage of the 2 TB drives and utilise more of the 3 TB. I don't have any more SATA ports free but I do have 3 USB 3.0 ports available which could come in to play. I'd probably keep one back for the Server Backup feature of Essentials, in case I wanted to rotate.
Comment: I guess another option besides manual rebalance would be to actually start replacing the 2 TB drives with bigger capacity, as an alternative. I could do this, due to the resiliency, removing one of drives would put the pool into a degraded state and then once the new drive is in, the repair operation would start moving data around and potentially do some balancing.


Exist a Drush command to update all the contents?

Question: We have a client who was adding content to a separated dev server, the dev server is whitelisted only and doesn't allow incoming/outgoing connections to a lot of services.
The client was adding videos with the video embed field module, which automatically generates a static file on our server.
The firewall config means that this error was produced
Warning: file_put_contents(temporary://fileTjnJTX): failed to open stream:      "DrupalTemporaryStreamWrapper::stream_open" call failed in      file_unmanaged_save_data() (line 1898 of /var/www/user/includes/file.inc).
The file could not be created.

When editing and saving the content drupal tries to regenerate the image if none is available Our sysadmin is working the firewall configuration to allow the connections, but we was wondering if there is any easy way/drush commands/mysql statment to update all content,
Comment: you got some advance?
Answer: You can take a look inside the module Drush Entity because in this module you have the command entity-update:
drush @drupal.d7 entity-update node 53 --fields=title

If you want to improve the command to work in all nodes you can read this post:
How to adapt the name of a custom Drush command?
EDIT:
If you want to learn about Drush alias (@drupal.d7) you can go to: Drush Aliases: What, Why and How
Comment: Didn't know Drush can do this, that's cool.
Comment: What does the @drupal.d7 refer to? And how can adapting the name of a cmd result in "work in all nodes"?
Comment: @Pierre.Vriens I don't know about the drupal.d7. I just copy the command from the module page, without drupal.d7 works fine. To work in all nodes just iterate trougth all the nodes ;-)
Comment: hm, that @drupal.d7 must be a [Drush Aliases](http://praxent.com/blog/drush-aliases-what-why-and-how) (feel free to enhance your answer with it if you want). Though I (still) wonder how such "iteration" should look ...
Comment: @Pierre.Vriens I will edit after. To iterate make a query to retrive all the nodes and then edit the title and save. Do you get the point?
Answer: Probably won't be a drush command for this but you can always create your own plugin for it since the actual code is fairly easy. Essentially what you want to do is to trigger 'node_save()' for all items matching your criteria which should trigger whatever follow-on actions, rules, etc. are associated with that content. The range of options listed in this question for bulk delete give you a number of code snippets to use but this is the one I would use (modified for your specific case:

Create a file with below code in root of drupal installation and
  execute the file.

<?php
  require_once './includes/bootstrap.inc';
  drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

  $aquery= db_query("SELECT nid FROM {node} AS n WHERE n.type = 'video'");
  while ($row = db_fetch_object($aquery)) {
    node_save($row->nid);
  }
?>

If you don't want to create php files, the Views Bulk Operations module offers a 'Node Save' action that can be just as simple.


Prove convergence from $|\sum_{k = 1}^n a_k |\leq \sqrt{n}$

Question: Given  $|\sum_{k = 1}^n a_k |\leq \sqrt{n}$, how to show that $\sum_{k = 1}^\infty a_k/k $ converges?.
I've not encountered a convergence problem where I don't know the convergence of $(a_n)$. So the usual test are out of option.
Comment: Use [Dirichlet's test](https://en.wikipedia.org/wiki/Dirichlet%27s_test)
Comment: @YadatiKiran, but $M$ is a constant the bound here is changing for each $n$
Answer: Let $\displaystyle s_n=\sum_{k=1}^{n} a_k$. $\:$ Then $\displaystyle\sum_{k=1}^{n} \dfrac {a_k} k = \sum_{k=1}^{n} \dfrac {s_k-s_{k-1}} k $ (with the convention $s_0=0$).  $\:$ This can be rewritten as $\displaystyle\sum_{k=1}^{n-1} s_k (\frac 1 k -\frac 1 {k+1})+\frac {s_n} n$. $\:$  It remains only to observe that $\displaystyle\sum_{k=1}^{\infty} \sqrt k (\frac 1 k -\frac 1 {k+1})=\sum_{k=1}^{\infty} \sqrt k \frac 1 {k(k+1)}$ is convergent by comparison with $\displaystyle\sum k^{-3/2}$.
Comment: @Hawk The fact that we are given  abound on the sums $s_k$ and not directly on the coefficients suggests that you should write $a_k=s_k-s_{k-1}$ and proceed as I have done. This technique is very powerful (especially in Fourier series).
Comment: Is there an instance when we know to invoke this telescoping $\sum_{k=1}^{n} \frac {a_k} k = \sum_{k=1}^{n} \frac {s_k-s_{k-1}} k$ technique?
Comment: Thank you for showing me this trick.


How to assess selected response distribution

Question: I am trying to predict the impact of readmission events (continuous) and type of readmission (medical, surgical, other) on total hospital costs. Because costs are skewed by nature, I am using a Gamma distribution with a log link function. Below is the model:
<code>PROC GENMOD data = abc;
  class type (ref='medical') gender (ref='F')/param=ref;
  model cost = event type age gender /dist=gamma link=log type3;
run;
</code>
Since the last time I posted this question, I did some more research on this topic and found:

Estimate alpha (shape) and beta (scale) parameters of the distribution and run goodness of fit test.
Check the deviance and chi-square value to assess model fit.

My question is: How would one validate whether the chosen distribution is indeed correct?
Comment: Welcome to the site.  Questions that are purely about programming/carrying out routine procedures in statistical packages are [off-topic](http://stats.stackexchange.com/help/on-topic) for this site and may be closed.  If you have an underlying statistical question, edit your post to emphasize it.  If your question is indeed about programming, try [Stack Overflow](http://stackoverflow.com/) or check out the list of [internet resources for statistical packages](http://meta.stats.stackexchange.com/questions/793/internet-support-for-statistics-software) that we maintain
Comment: The question now seems to be not about SAS, but about how to assess the proposed response distribution. I think this is suitably on topic now.
Answer: Maybe you could take a simpler approach.  Fit the cost data to a gamma distribution and then apply a goodness-of-fit test.  I you can't reject the gamma distribution then use it in the model.  Now find a transformation that makes the data approximately normal.  Then apply simple linear regression to the transformed data.  You would not need to use a generalized linear model.  In the generalized linear model, why did you choose the log function to be the link function?
Comment: Unlike OLS with a log-transformed dependent variable, the use of generalized linear model with log-link function preserves the standard interpretation of regression coefficients in terms of the effect of an independent variable on average costs. Using OLS with log-transformed dependent variable and back transforming introduces a bias, so I used gamma distribution with log link.
Comment: As suggested, I fit the cost data two ways and checked deviance (GOF test)  to determine which distribution fits best my data.                                               1) gamma with log link gives deviance 33.9002 and chi-square 0.223             2) gamma with identity link gives deviance 34.29 and chi-square 0.23. Although both the models are good, because deviance is less for gamma with log link, I believe that is a better pick. Any thoughts??
Comment: What matters is the conditional distribution of the response. This appears to suggest fitting the marginal distribution.


Alterando valor de um arraylist

Question: Estou com um problema no CASE 4 do meu código, quero alterar o preço do filme chamando o set, Porém ele não altera. Creio q seja problema de lógica, sou iniciante.
public static void main(String[] args) {
    Locale.setDefault(Locale.US);
    Scanner dados = new Scanner(System.in);

    List<Filme> filme = new ArrayList<>();
    Filme filmeC = new Filme();

    System.out.println("1 - Cadastrar filme \n2 - Excluir por ID \n3 - Checar filmes cadastrados");
    int numeroOpcoes = dados.nextInt();

    switch (numeroOpcoes) {
        case 1:
            for (int i = 0; i < 2; i++) {
                System.out.println("Digite ID");
                int id = dados.nextInt();

                System.out.println("Digite Nome");
                dados.nextLine();
                String nome = dados.nextLine();

                System.out.println("Genero");
                String genero = dados.nextLine();

                System.out.println("Quantidade");
                int quantidade = dados.nextInt();

                System.out.println("Preço");
                double preco = dados.nextDouble();

                filme.add(new Filme(id, nome, genero, quantidade, preco));
            }
        //break;
        case 2:
            System.out.println("entre com o ID para ser excluido");
            int idExcluir = dados.nextInt();
            Filme emp = filme.stream().filter(x -> x.getId() == idExcluir).findFirst().orElse(null);
            if (emp == null) {
                System.out.println("ID não existe");
            } else {
                filme.remove(emp);
                System.out.println("Removido com sucesso");
            }
        // break;
        case 3:
            for (Filme x : filme) {
                System.out.println(x);
            }
        // break;
        case 4:
            System.out.println("Digite o ID para modificar o preço");
            int idPreco = dados.nextInt();
            Filme valor = filme.stream().filter(x -> x.getId() == idPreco).findFirst().orElse(null);
            if (valor == null) {
                System.out.println("ID não existe");
            } else {
                System.out.println("Digite novo valor");
                double novoValor = dados.nextDouble(); // NÃO ENTENDO PQ NAO ALTERA AQUI
                filmeC.setPreco(novoValor);
                System.out.println("Valor alterado");
            }
            for (Filme x : filme) {
                System.out.println(x);
            }
            break;
    }

}

}

Comment: As primeiras três linhas do seu código acabaram não aparecendo na pergunta. Por favor, altere ela para que as linhas apareçam dentro da estrutura de código.
Comment: Pelo o que eu pude perceber, na hora de alterar o preço do filme você usou o objeto 'filmeC', mas o objeto que referencia o filme cujo ID é igual ao informado pelo usuário é a variável 'valor'.
Comment: Eu nao consigo acessar o set pelo filme. Ai criei o filmeC, porem ele nao altera a lista do filme.
Comment: Eu rodei o seu código aqui, e fiz essa alteração (substituí 'filmeC' por 'valor') e consegui alterar o valor do Filme. Tente fazer essa mudança para verificar se o código roda. Sugiro que naquela repetição que mostrar os filmes, ao invés de fazer apenas "System.out.println(x)", faça "System.out.println(x.getPreco())" (getter da variável preço) para verificar apenas os preços dos filmes cadastrados.
Answer: O seu erro acontece porque, na hora de realizar a alteração do preço, você está usando o objeto 'filmeC', enquanto que o objeto que referencia o objeto da classe filme cujo ID é igual ao informado pelo usuário é 'valor'. Para que o código funcione corretamente, substitua a linha
filmeC.setPreco(novoValor);

por
 valor.setPreco(novoValor);

Comment: Muito obrigado, resolveu meu problema.

Alterando valor de um arraylist


GEE results showing opposite of true marginal relationship with EXCH working correlation

Question: I am working on a modelling issue with two main effect variables: time period and Setting, related to an outcome, with all 3 being binary. My PI wants to test for moderating effects, so we have an interaction term included. There are repeated measures within individuals in the study. I have to code it in SAS but it is not my preferred language.
This is my SAS code:
<code>PROC GENMOD Data=lib.modeldata;
CLASS Study_ID Setting Period Outcome;
MODEL Outcome=period Setting period*setting / dist=binomial link=log;
repeated subject=Study_ID/type=EXCH;
RUN;
</code>
This is run over ~80000 obs, with about 14000 unique Study IDs.
When I run the model with this structure, it returns model parameters that have totally wild values out of line with the direction/magnitude of my contingency tables. When I run the same model with type=IND (i.e. assuming no clustering) the coefficient values are in line with the data and quite different.
Questions:

I thought misspecifying the correlation structure would not shift marginal estimates?
What could cause this? Is my model not converging?

I would really appreciate any answers or article links. I have done a good amount of reading and am unsure how this is even possible.
Answer: If the model is correctly specified, in the sense that
$$E[Y_{it}|\mathbf{X}_i]=\mathbf{X}_i\beta$$
then changing the working correlation structure does not affect the parameter being estimated.  This can go wrong for three related reasons.
The first reason is that the model could just be badly specified. You check this like you would in any regression model.
The second reason is that between-person and within-person associations are different. They are weighted differently by the exchangeable and independence working correlation structures.  To check this, define two variables $X_b$ that might be the baseline values of $X$ for each person and $X_w$ as the differences $X_{it}-X_{bi}$. Do these variables have similar coefficients? (reference)
The third reason is more complicated. The assumption, as I said, is
$$E[Y_{it}|\mathbf{X}_i]=\mathbf{X}_i\beta$$
not
$$E[Y_{it}|X_{it}]={X}_{it}\beta$$
That is, you need the past and future $X$s to be correctly modelled, not just the current $X$.  In particular, if $Y_{it}$ affects future $X$s, this will probably not be true. Here's the reference (and here's a rediscovery of it)
[note: 'assuming no clustering' is not really a good description of the independence working model, because it doesn't assume no clustering. It's a choice of weights, not an assumption]
Comment: Thank you, that is extremely helpful.
Comment: Thank you again, I did not fully understand the time-dependence assumptions of GEE and this was very educational. I now understand that GMM will likely be more appropriate for this dataset.
Comment: GMMs often have the same assumptions: the phrase "dynamic misspecification" is one example of the issues


Packet download speed drops for Ubuntu 20.04.05

Question: I have a virtual machine in VMware Workstation 16.2.3. running in Windows 10 Pro
I managed a few months ago to install Ubuntu 20.04.5.
The idea of creating this virtual machine is to be able to test different web applications, for that reason I have installed several versions of php and I have configured them to run as a virtual host; all this works correctly.
after a few months I decided to check for updates and the system tells me that there are 119 updates for the different packages... etc:
php 5.6.,php 7.2, php 7.4. y php 8.1.*
when executing the command:
<code>sudo apt update
sudo apt upgrade -y
</code>
only the first package in the list is downloaded successfully at a stable speed; from the second packet the speed drops rapidly to 99b speed; it doesn't even reach 1kb. 4 days ETA
I'm really baffled since canceling the download and repeating the upgrade command; it again downloads the previously queued package at a good speed but the second package is slowed down on download.
so on with all the packages; I've had to manually cancel and upgrade about 110 times. This exhausts me and I know that it is not correct.
The problem is that I don't know how to attack this problem; since in another virtual machine with the same VMWare setup running Ubuntu 22.04.1 I don't have this scenario... but I can't do all the tests in this version and I am forced to use the previous one 20.04...
my doubt; How can I or with what can I verify if my installation of this virtual machine is correct or if my virtual machine is correctly configured. The idea is to determine what is affecting the correct download of the packages.
Answer: This may sound a bit weird: Triple-Check your MTU. Especially the MTU of your internet gateway. Check if the right MTU is set there (verify with ping, for example) and do the same on the machine.
I have seen this on quite a few machines now and MTU was the one to blame.
Comment: how do you do that?
Comment: By sending packets (ICMP ping for example) until they get fragmented. Maybe this article helps: https://www.sonicwall.com/support/knowledge-base/how-can-i-determine-the-mtu-size-of-wan-interfaces-manually/170504812146650/
Comment: I'm not understanding anything... I'm using ubuntu 20.04... linux and in a virtual machine... what does that have to do with SonicOS (what you shared with me)
Comment: Did you read the article? It discusses "determine the MTU size of WAN interfaces" using windows and/or the linux command line. Which is exactly what you have asked for ("how do you do that"). Just ignore the last part, where it explains how to *set* it in SonicOS. You will have to *set* it on your own gateway (which vendro your question did no mention) just after you have *determined* it.


Is it safe to use synth and filter effect pedals without risk to guitar amp?

Question: The aim is to decide on a suitable signal path for my current pedals -- only two: Boss SY-1 Synth and Dr Scientist Dusk (low pass filter). Both pedals have other functions like loops but I don't intend to use that. My intended use case is:
SY-1

Get a glitchy-sounding tone

Dusk

Mainly  toggle low-pass filter with my expression pedal
Maybe tinker with tone if it adds anything interesting

I'm aware that placement of pedals can change the overall sound (like placing a Wah before / after volume pedal). However, as a fairly newcomer to equipment, I'm not sure what kind of category these pedals fall under.
Question
Is it safe for me to experiment with the placement these two in my signal path without risk to my amp (note: I don't have a compressor)? I don't mind experimenting for myself to get my desired tone, but it would be nice to hear from those with experience what kind of hypotheses I may want to be testing along the way.
Comment: Yes, guitar pedals can be placed in any order without changing the risk of damaging the amp. The main risks to amps come from physical damage and running them at maximum or high volume  for extended periods.
Comment: I edited the title to match the actual question better.
Answer: You can place pedals in any order, so no problems, just experiment. The other option on a lot of amps is to use the send and return ports, often on the back. You might even try one as you are doing, and the other in the send/return loop.
Comment: Agree. Guitar effect pedals, particularly the ones the OP has, are specifically made for crazy experimentation, so if there was any way to harm the amp, it would be a severe design error in the pedals.
Answer: A guitar amp not specifically intended for acoustic guitar will be pretty safe against abuse since it is built to get along overdriven as part of the sound.  Even if the overdrive in a solid-state amp tends to be an artificial emulation of an overdriven valve amp, it is rich in overtone content which is the most problematic for separate tweeters.  Guitar amps usually don't have separate tweeters.  Instead their speakers are supposed to deliver the whole frequency range which limits their accuracy both for lower and higher frequencies.
As a result, using a guitar amp for anything tends to be unproblematic for the amp but less than impressive for the listener.  With regard to actually using a guitar on non-guitar pedals, you might want to either put them in the "effect loop" or place them after a "buffer" pedal that will make the best of the high-impedance input from the guitar pickup.
Comment: Could you add details on 1. difference between solid state and valve guitar amps (the latter don't have tweeters either normally), 2. what exactly is supposed to be "less than impressive for the listener".


Resultados diferentes com a mesma instrução SQL

Question: Fala programadores(as), tranquilos?
Eu pesquisei bastante para não repetir perguntas aqui, mas realmente não entendo o motivo da instrução SQL funcionar no MySQL Workbench e na string SQL do Java/JDBC não.
Eu tenho duas tabelas jogo e categoria, e ao listar as categorias eu gostaria de informar a quantidade de jogos cadastrados na respectiva categoria, ex:
Categoria: Ação (3) jogos
Categoria: Corrida (1) jogos
Categoria: Luta (1) jogos
Um relacionamento onde uma categoria tem muitos jogos e cada jogo tem a sua categoria.
Bom, até aí tudo bem. O problema é que antes de inserir o SQL no método preparedStatement("SQL") no java eu faço um teste no MySQL Worckbench e o teste me retornou um resultado satisfatório:
SELECT c.id, c.categoria, COUNT(j.id_categoria) as qtd
FROM categoria c INNER JOIN jogo j ON c.id = j.id_categoria GROUP BY c.id;

Resultado no workbench
id   categoria   qtd
1      Ação      3
2     Corrida    1
3      Luta      1

Porém com o mesmo SQL no java o resultado é o sequinte:
id   categoria   qtd
1      Ação       1
1      Ação       1
1      Ação       1

Parte do método getAll() da classe CategoriaDAO.
PreparedStatement ps = conexao.preparedStatement("SQL_ACIMA");
ResultSet rs = ps.executeQuery();
List<Categoria> categorias = new ArrayList<>();
while(rs.next()) {
    categoria.setId(rs.getInt("c.id"));
    categoria.setCategoria(rs.getString("c.categoria"));
    categoria.setQtd(rs.getInt("qtd"));
    categorias.add(categoria);
}
return categorias;

No JSP:
<jsp:useBean id="categorias" class="br.com.jogos.CategoriaDAO"></jsp:useBean>
<c:forEach var="cat" items="${categorias.getAll()}">

        ${cat.getCategoria()}
        ${cat.getQtd()}

</c:forEach>

Se alguém tiver alguma ideia do motivo da mesma instrução SQL ter dois resultados distintos, eu já agradeço. Obrigado!
Answer: PreparedStatement ps = conexao.preparedStatement("SQL_ACIMA");
ResultSet rs = ps.executeQuery();
List<Categoria> categorias = new ArrayList<>();
while(rs.next()) {
    categoria.setId(rs.getInt("c.id"));
    categoria.setCategoria(rs.getString("c.categoria"));
    categoria.setQtd(rs.getInt("qtd"));
    categorias.add(categoria);
}
return categorias;

Observe que você está sempre usando a mesma instância de categoria e não instâncias diferentes! O que você queria era isso:
try (
    PreparedStatement ps = conexao.preparedStatement("SQL_ACIMA");
    ResultSet rs = ps.executeQuery();
) {
    List<Categoria> categorias = new ArrayList<>();
    while (rs.next()) {
        Categoria c = new Categoria();
        c.setId(rs.getInt("c.id"));
        c.setCategoria(rs.getString("c.categoria"));
        c.setQtd(rs.getInt("qtd"));
        categorias.add(c);
    }
    return categorias;
}

Ah, e lembre-se de usar o try-with-resources para gerenciar o PreparedStatement e o ResultSet adequadamente (e provavelmente o conexao também deveria).
Também sugiro utilizar objetos imutáveis com parâmetros passados no construtor. Se tivesse usado essa abordagem, o problema que você tem não teria acontecido. Tenho uma resposta sobre isso em uma outra pergunta.
Comment: Obrigado pelo seu tempo e sua resposta!
Comment: @IgorDias Se essa resposta resolveu o seu problema e não restou nenhuma dúvida, marque-a como correta/aceita ao clicar no "✅" que está ao lado dela, o que também marca a sua pergunta como resolvida. Se ainda te resta alguma dúvida ou gostaria de maiores esclarecimentos, fique a vontade para comentar.


How to return distinct domain names from email address values in MySQL?

Question: I have a MySQL table with values like:
+--------------+
| user_email   |
+--------------+
| email@example.com |
| email@example.com |
| email@example.com |
| email@example.com |
| firstname.lastname@example.com |
| firstname.lastname@example.com |
+--------------+

I need to return a list of unique domain names from this list of email address, such as:
gmail.com, yahoo.com, other.net
So far, I am using the following SQL statement to select this:
SELECT SUBSTRING_INDEX(user_email,'@',-1)

However, this only solves half of my problem - it is returning domain names. Using DISTINCT did not do the trick. What am I missing?
FYI: This is running on a LAMP stack. Thanks!
Comment: Have you seen
 ?
Maybe that helps.
Good luck!
Comment: It didn't really help, but thanks for the suggestion Fillipe.
Answer: Just use group by
SELECT SUBSTRING_INDEX(user_email,'@',-1) as domain_name FROM user_email group by domain_name

Comment: Ah, this led me to the solution. Thanks Hawili!
Comment: This is great, I added ", count(*)" to my query as I was looking for the top domains that I email
Answer: SELECT split_part (email,'@',2) as domain_name FROM pytest.emps group by domain_name;