Programatically linking an image to content (Drupal 7)

Question: When I create a block through views I can easily link it to the content page by setting link image to in the field's settings.  But I also have some blocks that are created programmatically and I would like to similarly add links to these images.  How would I do this?
EDIT: Here is the code I use to create the block:
  $block = array();
  $rows = array();
  $format = 'l, F j, Y  - G:i';

  $header = array('Project Name', 'Screenshot' , 'Submitted');
  foreach ($results['node'] as $nid_array) {
    $row = $nid_array->nid;
    $node = node_load($row);
    $path = $node->field_icon_thumbnail['und'][0]['uri'];
      $variables = array(
    'path' =>  image_style_url('icon_thumbnail',$path),
    'alt' => 'Thumbnail',
    'title' => 'Thumbnail',
    'attributes' => array('class' => 'some-img', 'id' => 'my-img'),
    );
      $image = theme('image', $variables);

      $rows[] = array(
    l($node->title, "node/$node->nid"),
    $image,
    date($format, $node->changed)
      );
  }
  $rows = array_reverse($rows);
  $table = array('rows' => $rows, 'header' => $header, 'empty' => 'No terms found');
  $block['content'] = array(
  '#theme' => 'table',
  '#header' => $header,
  '#rows' => $rows,
  '#empty' => t('No terms found')
  );
  return $block;

Comment: I think you if you make it programmatically you should have nid that related to image so you can link image to node/nid
Comment: Hey Ahmed, I'm not quite sure what I would do with that html snipet.  I have added the code I use to create the block.  Do I need to create my block differently?
Answer: You can use the l() function to wrap the image in a link. As it's HTML you'll need to pass the html option to the function so that it isn't run through check_plain():
$image = theme('image', $variables);

$linked_image = l($image, "node/$node->nid", array('html' => TRUE));

$rows[] = array(
  l($node->title, "node/$node->nid"),
  $linked_image,
  date($format, $node->changed)
);

Comment: Missed that `html => TRUE`, thank you very much. That's what I looked for.


Pass HTML variable to separate javascript file

Question: I have a dictionary (sent from a python class) called "sentiments" in my html file. The following:
{% if sentiments %}

{{sentiments}}

{% else %}

none

{%endif%}

Prints:
('very positive', 34)
('positive', 64)
('neutral', 44)
('negative', 11)
('very negative', 27)

So I know that much is working fine. In a seperate javascript file, I have a morris bar chart with hard-coded values as follows:
Morris.Bar({
    element: 'bar-chart',
    data: [
        { x: 'V. Pos', y: 10},
        { x: 'Pos', y: 20},
        { x: 'Neutral', y: 30},
        { x: 'Neg', y: 20},
        { x: 'V.Neg', y: 10},
    ],

    xkey: 'x',
    ykeys: ['y'],
    labels: ['# Tweets'],
    barColors: function (row, series, type) {
        console.log("--> "+row.label, series, type);
        if(row.label == "V. Pos") return "#3300FF";
        else if(row.label == "Pos") return "#6600FF";
        else if(row.label == "Neutral") return "#9900FF";
        else if(row.label == "Neg") return "#FF3333";
        else return "#ff0000";
    }
});

I am calling this script as follows:

I would like to pass my dictionary "sentiment" to this script and use the values in it to populate the chart, rather than the hard-coded values I have now. Any help would be much appreciated. I am using Flask to connect my python and html.
Answer: You can transcribe the variable to JS by doing:

When rendering the page, make sure to pass in sentiments using json.dumps, like:
return render_template('page.html', sentiments_str=json.dumps(sentiments))

Comment: Thanks for the answer. I tried this and now this line:

    var sentiments_dict = {{ sentiments_str }}

Is giving me the error: "Expression statement is not an assignment or call"
Comment: I made some changes, try those.


What is wrong with my code? 5 + 5 will give me 55 instead of 10

Question: @IBAction func calcAns(sender: UIButton) {

   result = firstNumber.text + secondNumber.text
   outputLabel.text = "\(result)"

}

What is wrong with my code?  For example 5 + 5 will give me 55 instead of 10. Can someone please point out my mistake?
Comment: `5 + 5 = 10`, but  `"5" + "5" = "55"` .
Comment: your variable is treated as string instead of int, you need to convert it to int (or cast it)
Comment: Don't forget to upvote and/or accept answer(s) below, to expression appreciation for the help you have received. Thanks!
Answer: You are adding a string to another string:
firstNumber.text + secondNumber.text

If firstNumber.text was "Hello" and secondNumber.text was "World", the result would be "HelloWorld". As it is, you're concatenating "5" and "5" to get "55".
The solution would be to convert those strings into numeric values before adding them together.
Answer: You need to convert the string variable to int:
@IBAction func calcAns(sender: UIButton) {

   result = firstNumber.text.toInt() + secondNumber.text.toInt()
   outputLabel.text = "\(result)"

}

Answer: In Swift, + on strings is concatenation rather than addition.  The text property is a string rather than a number.
To convert it to a number, try:
if let first = firstNumber.text.toInt(),
       second = secondNumber.text.toInt() {

    outputLabel.text = toString(first + second)

}


How to create a new column takes the value from the sum of another column each row?

Question: Like taking the value from the first row 60, then add it to the new value from the next row and so on, like the example of the below table.
     field       A                             B
0      u       60.0                           60.0
1      v       78.0   >>     60.0  + 78.0  =  138.0
2      w       42.0   >>     138.0 + 42.0  =  180.0
3      x       61.0   >>     180.0 + 61.0  =  241.0
4      y       36.0   >>     241.0 + 36.0  =  277.0

Answer: Pandas has a built-in "cumulative sum"
import pandas as pd

df = pd.DataFrame(
    {
        "field": ["u", "v", "w", "x", "y"],
        "A": [60, 78, 42, 61, 36],
    }
)

df["B"] = df["A"].cumsum()

print(df)

Output:
  field   A    B
0     u  60   60
1     v  78  138
2     w  42  180
3     x  61  241
4     y  36  277

Answer: assuming that you are using a Pandas dataframe and it is named df you can do that operation in this way (without using builtin pandas .cumsum package):
columns_A = df["A"] #obtain the element of the columns A as a series
new_col= []
for i in range(len(columns_A)):
    if i <=0: # the first element tha can't be sum up
        new_col.append(a[i])
    else: # after the first element we start with cumulative sum
        new_col.append(new_col[i-1]+a[i]) #here with new_row[i-1] we obtain the previous element respect the
        #the current one and thanks to that we can obtain the cumulative sum
df["B"] = new_col #here we assign the name of the column and add the values to the dataframe


Drupal multi-site Aegir caching strategy

Question: We are migrating many sites from various content management systems onto a single Drupal/Aegir platform. We used to have a high density of sites on the same servers and Aegir definitely makes managing high density Drupal sites easier. Unfortunately having the same density of Drupal sites on scaled up hardware is leaving us with slower response times for the same amount of traffic. The platform/codebase is itself a bit of a beast, with some sites having 250+ modules enabled and response times stretching to 30+ seconds with Drupal caching disabled. The shared codebase acts as a sort of menu for business divisions to be able to choose features/themes from. With APC, Drupal cache and memcached running we still struggle on ocassion.
I think it makes sense to look at building up a caching layer in front of Apache-Drupal-Aegir before we start scaling the application layer horizontally. Aegir brings a big benefit to managing multiple sites and ending up with multiple Aegir instances takes away some of that benefit. In particular I like the idea of being able to cache some/all of the dynamic content for anonymous users in case the Aegir server is unavailable for any reason.
The options as I see it are:

Drupal boost module. Probably the easiest to setup but unfortunately does not appear to work with Aegir without some manual patching.
nginx as a reverse caching proxy. SSL support, easier to configure
Varnish as a reverse caching proxy. No SSL support, more difficult to configure
Ditch Apache and run Aegir on nginx/PHP-FPM. I prefer running Aegir on Apache at this stage as it will be easier for other engineers to troubleshoot.

We also have an HAProxy installation which load balances (actually failover/fault tolerance) for other applications, so we could always terminate the SSL at HAProxy and failover across multiple nginx or Varnish instances, with a single Drupal application server at the back. Though that means requests jumping through 3 layers to potentially hit the back-end, which doesn't sound too great.
Questions:

I'm tending to go for nginx as the reverse caching proxy because of simple configuration and management by other users and a single entry point for SSL management.
Is there any reason why I should choose Varnish instead?
Is nginx able to serve cached "dynamic" content to anonymous users in the eventuality of the back-end Drupal server being down?
Or is it purely restricted to static content such as images, JS, CSS etc?
What about having HAProxy on top of that, so we can failover between multiple nginx instances?
Or is it insane to have requests potentially going through 3 layers of proxy to reach the Apache/Drupal back-end?
Answer:
Use what your comfortable with for maintenance and configuration.
Probably, depending on config. (I don't use nginx)
Not crazy, it allows for a very quick switch time to another webserver.

I have varnish combined on my webservers with a separate apache reverseproxy doing ssl termination.
A little custom hook triggers a reverse proxy update on a Aegir migrate task.


Como se comunicar com webService SOAP

Question: Estou tentando comunicar com um WebService SOAP. Consegui realizar a comunicação utilizando o SOAPUI conforme imagem:

Estou desenvolvendo essa comunicação em c# da seguinte forma:
try
        {
            var service = new com.nexxera.flnws001qae.NexxeraWSv2ImplService();

            service.RequestSoapContext.Security.Tokens
                    .Add(new UsernameToken(Properties.Settings.Default.USUARIOWS, Properties.Settings.Default.SENHAWS, PasswordOption.SendPlainText));

            var FileName = System.IO.Path.GetFileName(currentFilePath);

            service.RequestSoapContext.Attachments.Add(new
                Microsoft.Web.Services2.Attachments.Attachment(FileName,
                    "application/octet-stream", currentFilePath));

            service.RequestSoapContext.Add("text/plain", new ContentType());

            var c = new StreamReader(currentFilePath).ReadToEnd();

            var fs = new com.nexxera.flnws001qae.fileWrapper
            {
                filename = currentFilePath.Split('\\').Last(),
                content = currentFilePath.Split('\\').Last()
            };
            var arqq = new com.nexxera.flnws001qae.uploadFilev2
            {
                destination = "LARIND.BANCOS",
                file = fs
            };

            var result = service.uploadFile(arqq);

        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message.ToString());
        }

Estou com o seguinte erro:
 {"Unsupported content type: application/dime"}

Não consigo setar a opção ContentType:
service.RequestSoapContext.ContentType = "text/plain";

Tentei utilizar o método passado pelo Carlos, chamada do método:
var envelope = new XmlDocument();
envelope.Load("C:\\Nexxera\\teste.xml");
GetResultservice(envelope, "http://flnws001qae.nexxera.com:80/nexxeraws/v2/SkylineWSv2");

conteudo do texte.xml:
<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:urn="urn:NexxeraWS">
<soapenv:Header/>
<soapenv:Body>
  <urn:uploadFile>

     <file>
        <filename>C:\Nexxera\log_0615.txt</filename>
        <content>C:\Nexxera\log_0614.txt</content>
     </file>

     <destination>LARIND.BANCOS</destination>
  </urn:uploadFile>

Me retorna erro:
O servidor remoto retornou um erro: (500) Erro Interno do Servidor.

Seguindo o exemplo do Carlos, implemente dessa forma:
 public string ProcessAttachment(string fileInput)
    {
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://flnws001qae.nexxera.com:80/nexxeraws/v2/SkylineWSv2");
        req.Method = "POST";
        req.ProtocolVersion = HttpVersion.Version11;
        req.Headers.Add("Accept-Encoding", "gzip,deflate");
        req.ContentType = "multipart/related; type=\"text/xml\"; start=\"teste\"; boundary=\"----=_Part_72_348989292.1565031692584\"";
        req.Headers.Add("SOAPAction", "\"\"");
        req.Headers.Add("MIME-Version", "1.0");
        //req.ContentLength = 1854;
        req.Host = "flnws001qae.nexxera.com:80";
        req.UserAgent = "Apache-HttpClient/4.1.1 (java 1.5)";
        req.KeepAlive = true;

        System.Net.ServicePointManager.Expect100Continue = false;
        Stream memStream = new System.IO.MemoryStream();
        FileStream fileStream = new FileStream(fileInput, FileMode.Open, FileAccess.Read);
        byte[] buffer = new byte[1024];
        int bytesRead = 0;
        while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
        {
            memStream.Write(buffer, 0, bytesRead);
        }
        fileStream.Close();
        Stream stm = req.GetRequestStream();
        memStream.Position = 0;
        byte[] tempBuffer = new byte[memStream.Length];
        memStream.Read(tempBuffer, 0, tempBuffer.Length);
        memStream.Close();
        stm.Write(tempBuffer, 0, tempBuffer.Length);
        stm.Close();
        HttpWebResponse resp = null;
        resp = (HttpWebResponse)req.GetResponse();
        stm = resp.GetResponseStream();
        StreamReader r = new StreamReader(stm);
        return r.ReadToEnd();
    }

Adicionei o arquivo arq.xml
            ------=_Part_72_348989292.1565031692584
            Content-Type: text/xml; charset=UTF-8
            Content-Transfer-Encoding: 8bit
            Content-ID: teste

            <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:urn="urn:NexxeraWS">
               <soapenv:Header>
                    <wsse:Security soapenv:mustUnderstand="1" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
                        <wsse:UsernameToken wsu:Id="UsernameToken-C3491A557C4FE15638156503169258275">
                            <wsse:Username>homologacao</wsse:Username>
                            <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">test</wsse:Password>
                            <wsse:Nonce EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary">vbCcpxa/p0Ceton7RevESw==</wsse:Nonce>
                            <wsu:Created>2019-08-05T19:01:32.582Z</wsu:Created>
                        </wsse:UsernameToken>
                    </wsse:Security>
                </soapenv:Header>
                <soapenv:Body>
                  <urn:uploadFile>

                     <file>
                        <filename>log_0805.txt</filename>
                        <content>log_0614.txt</content>
                     </file>

                     <destination>LARIND.BANCOS</destination>
                  </urn:uploadFile>
                </soapenv:Body>
            </soapenv:Envelope>
            ------=_Part_72_348989292.1565031692584
            Content-Type: text/plain; charset=us-ascii; name=log_0614.txt
            Content-Transfer-Encoding: 7bit
            Content-ID: <log_0614.txt>
            Content-Disposition: attachment; name="log_0614.txt"; filename="log_0614.txt"

            "LA09"; "33007110138"; "110273"; "S0007"; "785522"; "EFETUADA "; "CMPCTCRC"; "00"; "11/04/2019"; "13:06:50"; "       5155******33"; 89; 01; "5155";
            ------=_Part_72_348989292.1565031692583--

Qual seria a melhor de forma de atualizar esse arquivo.xml, pois para cada arquivo eu vou ter informações diferentes, como o nome, tamanho e diferente informações. Também tem o "----=Part" que deve mudar conforme as informações do meu log...txt.
Comment: acho que falta uma informação importante na sua pergunta ou ainda no título que é "usando anexo"
Answer: Faça desse jeito:
1º Crie uma estrutura com os dados do request, exemplo:
private StringContent MontarEnvelope()
{
    var envelope = $@"<soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:sfin=""urn:NexxeraWS"">
    <soapenv:Header/>
    <soapenv:Body>
        <sfin:empty/>
    </soapenv:Body>
    </soapenv:Envelope>";
    return new StringContent(envelope, Encoding.UTF8, "text/xml");
}

2º Crie seu metodo de chamada, exemplo:
static readonly HttpClient _httpClient = new HttpClient();

public async Task<string> Consultar()
{
    string url = "http://flnws001qae.nexxera.com:80/nexxeraws/v2/SkylineWSv2";
    var content = MontarEnvelope();
    using (var response = await _httpClient.PostAsync(url, content))
    {
        var soapResult = await response.Content.ReadAsStringAsync();
        return soapResult;
    }
}

3º
var resultado = await Consultar();

Esse é o caminho, o exemplo acima é assíncrono.
Answer: Bom dia. Segue exemplo:
public XmlDocument GetResultservice(XmlDocument envelope, string url)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                byte[] buffer2 = Encoding.ASCII.GetBytes(envelope.InnerXml);
                request.Timeout = 900;
                request.ContentType = "text/xml; charset=utf-8";
                request.Method = "POST";
                request.ContentLength = buffer2.Length;
                Stream PostData = request.GetRequestStream();
                PostData.Write(buffer2, 0, buffer2.Length);
                PostData.Close();
                WebResponse responsePost = (HttpWebResponse)request.GetResponse();
                Stream istreamPost = responsePost.GetResponseStream();
                XmlDocument res = new XmlDocument();
                using (StreamReader rd = new StreamReader(istreamPost, System.Text.Encoding.ASCII))
                {
                    res.LoadXml(rd.ReadToEnd().Replace("'", "''"));
                }
                istreamPost.Close();
                responsePost.Close();
                PostData.Close();
                request = null;
                return res;
            }catch(Exception e)
            {
                throw e;
            }
        }

Comment: Carlos Soares, não entendi seu código, onde e como deve utilizar esse código na minha aplicação?
Comment: Bom dia Tiago, tudo bem?
Essa é chamada soap sem adicionar uma referencia de serviço.
Comment: Tudo certo Carlos e com voce? Estou com dificuldades em utilizar o seu método, coloquei a tentativa de conexão no final da pergunta.
Comment: Tudo bem Tiago, você conseguiu  fazer está chamada numa ferramenta de teste, tipo postman?
Faça um teste, pode ser  erro na url ou no envelope.
Comment: Carlos implementei seu código. A principio funcionou, mas estou com outra dúvida, conforme perguntado na pergunta. Qual seria a melhor forma de atualizar esse arquivo?
Comment: Opa!
Esse arquivo é um retorno do webservice?

Como se comunicar com webService SOAP


Form Field Containers

Question: How do I get rid of the outer box around the location field for example. I don't like how the location title + background colours are repeated twice for additional fields.
I have this issue on every template, not just the one displayed so can answers please be generic so I can do it on every template.
Answer: Drupal uses renderable arrays, so there is probably something like this:
'location_outter' => array(
  '#type' => 'fieldset',
  '#title' => 'location',
  'location_inner' => array(
     '#type' => 'fieldset',
     '#title' => 'location',
     'city' => array(
        '#type' => 'textfield',
        '#title' => 'City',
     ),
   ),
);

So i think you can, if it is form, try use alter hook, for example yourmodule_user_form_alter and modify that renderable array.

Form Field Containers


Scheduling problem in chapter 3 of The Design of Approximation Algorithms by David P. Williamson and David B. Shmoys

Question: Suppose we have $m$ machines and $n$ jobs that can start immediately, and we want to distribute jobs to minimize the longest processing time among all machines. For any $\epsilon=1/k$ for some integer $k$, if we are sure all jobs have processing time more than $\epsilon T$ where $T$ is the upper bound for the optimal longest processing time and are able to find optimal solution with processing times of all jobs rounded down to integer multiples of $\epsilon^2T$, then we are able to say the job distribution we have solved is no more than $(1+\epsilon)T$. However, I am not sure if this holds when $1/\epsilon$ is not an integer. I don't know if it is covered somewhere in the textbook so I would appreciate a lot if anyone can point out the part where it is explained.
For the integer case, all jobs take time more than $\epsilon T$ which is an integer multiple of $\epsilon^2T$, so the rounded times are at least $\epsilon T$, and due to rounding, in our solution every machine takes less than $1/\epsilon$ jobs. The longest time in the rounded-down case is at most $T$, and without rounding it should be less than $$T+\frac{\epsilon^2T}{\epsilon}=T(1+\epsilon).$$ However in the non-integer case we cannot guarantee that the rounded time is still at least $\epsilon T$. The bound $L$ I can get is $$\frac{L}{\epsilon T}\epsilon^2T>L-T\Rightarrow L<\frac{T}{1-\epsilon}.$$ Is there a way to prove the bound $1+\epsilon$ or find a counter-example to this bound? Thanks for any contribution to this problem!
Answer: Suppose $1/\epsilon=a-b$ where $a=\lceil1/\epsilon\rceil$, and $b$ is small enough to make $\lfloor(a-b)^2\rfloor=a^2-1$, then $\lfloor T\rfloor=\epsilon^2T(a^2-1)$. If the jobs are $a+1$ jobs with time close to but less than $a\epsilon^2T$(which will be rounded down to $(a-1)\epsilon^2T$), one job with time $T$, and total number of machines $m=3$, then an optimal solution when job times are rounded down could be to assign all $a+1$ jobs with time around $a\epsilon^2T$ to a machine and the job with time $T$ to another. In this case the actual largest load is about $$a(a+1)\epsilon^2T>1/\epsilon(1/\epsilon+1)\epsilon^2T=(1+\epsilon)T,$$ thus proving the bound $1+\epsilon$ incorrect when $1/\epsilon$ is not an integer. The optimality of $T$ is guaranteed by making $a$ large. In this case an optimal solution could be to assign the job with time $T$ to a machine and split the rest almost equally between two machines, with one machine taking at most one more job than the other. In this case the optimal longest workload is $T$.


Node or Taxonomy reference field with "Add new item" on node creation page

Question: I would like to include an "Analyst" Reference field in a content type and allow users to create a new option without needing to leave the Add node page.  So it would be a drop-down with an "Add New Analyst" button.  So a pop-up or an iframe or something so the user doesn't have to leave the page to add a new option and then start over from scratch.
The "Analyst" could be a separate content type or even taxonomy term with multiple fields.
I would use Select (or other) module, but it doesn't support Node reference or taxonomy with multiple values.
Answer: For node reference fields, I use References Dialog to include a link for adding the referenced node. Looks like they are working on taxonomy references.


How to maximize regression coefficient instead of factor loadings in SEM?

Question: I wonder if there is a method that allows finding factor loadings so that the factor would predict the distal outcome the best? The ordinary SEM model would estimate factor loadings and regression coefficients independently of each other, but I have a little interest in the factor itself, I am interested in this factor only in the relation to this external variable. I think it could be something like a target rotation method, where the target is the set of loadings that produce the factor that results in the largest regression coefficient.
To make it more clear I give an example. I have a factor representing cognitive abilities with 20 indicators, and the specific observed outcome variable - job performance. The ordinary SEM would try to fit factor model to a covariance of indicators, representing it best. Instead, I would like to see a factor that predicts job performance best and I don't really care about the quality of the factor model itself, except for it should reproduce in the other samples.
Comment: What purpose does the factor serve in your example? Why not just remove the factor and regress directly on the items?  Then create a factor using the predicted values from the regression.
Comment: I added a comment below. My real purpose isn't a prediction by itself, but finding the factor loadings that comply with an external validity criterion.
Answer: As Jeremy mentioned in the comments, if your goal is prediction, then there is no sense in creating an interpretable factor. You can use flexible regression or machine learning methods directly on the items. Adding a factor structure only limits the relationship between the items and the outcome by imposing independence constraints, which seem unnecessary to suit your goals. The goal of SEM is to test a constrained covariance structure among the the observed variables and estimate the parameters that minimize the difference between the constrained and observed covariance structures. If your goal is optimal prediction, none of that is relevant, and SEM is not the tool you should use.
Indeed, going down your road, you can construct a silly example that demonstrates the absurdity of using SEM to optimize prediction of an outcome. In your SEM, simply constrain the error variance of the outcome to be 0, the factor loadings to all be 0, and the mean and variance of the factor to be the mean and variance of your outcome. Your estimated coefficient will be 1, and the factor will have an R2 of 1.0, perfect prediction. Does this satisfy your desiderata? It's a factor whose relationship with the indicators is unimportant and it predicts the outcome extremely (i.e. perfectly) well. Clearly this is problematic.
The point is that with SEM, you can devise any constraints to satisfy your desires, but the goal of SEM is not to maximize prediction; rather, its very purpose is to reproduce the population covariance matrix of the observed variables with model constraints. It simply is not the tool for your job.
Comment: Thanks, you have clarified it a lot. My real purpose was to find a factor structure that satisfies the external validity criteria (not a prediction by itself). I think, your suggestion of constraining the residual of the outcome to zero is not a total absurd. I guess maybe instead of a constraint I can take a Bayesian perspective and substitute constraint with a small prior?


How do you search for substring in ansible group_names?

Question: For a group name hello, I use the following condition in ansible and it works fine:
when: "'hello' in group_names "

Is there a way to use a regular expression if I want to match for keywords hello in the following group_names:
hello
somewhere_hello
hello123

Answer: You can select and count items with filters:
when: group_names | select('search','hello') | list | count > 0

Answer: You can also use join and search:
when: group_names|join(" ")|search("hello")

Answer: As of 2.9 search is a test and not a filter:
group_names is search("hello")


Managing split tees in golf

Question: This week at golf's US Open, groups are teeing off the 1st and 9th holes. This is because the 9th tee is closer to the clubhouse than the 10th tee (i.e. logistics).
Split tees usually have groups tee off the 1st and 10th holes. However, wouldn't this kind of arrangement introduce more bottlenecks (assuming the same number of players tee off per group - eliminating the "uneven group" variable)? For example, one group gets held up. This holds the other groups back, eventually affecting groups who teed off the other hole to be affected.
How do golf organizers deal with split tee times and its risks, as it seems to introduce more unpredictable variables than traditional tee times?
Answer: For those who don't know, with the majors, and a lot of other golf tournaments on the PGA and European tours, the first-two rounds have groups of three players and the groups tee off at 11 minute intervals.  In the 3rd and 4th rounds players play in pairs and at 10 minute intervals.  This can change subject to weather conditions, reduced daylight times, etc.
Now, these tee-times are extremely tightly regimented. For example, at the British Open, Ivor Robson can penalise a player 2 strokes if they are 2 minutes late and disqualify them if they are 5 minutes late.  That's certainly an incentive to be on time.
I'm not exactly sure as to when 11 minutes was set as the de facto for tee-time intervals, but it is one that the golf associations deem the optimum time to get every player out on the course.
Also, with an average round of golf taking a little over 4 hours, the tee-times are arranged so that, once the last groups have started, the 1st tee starters and the 10th tee starters should be nicely "in sync" on the whole course.
However, to prevent bottlenecks the following is done:

Slow play is penalised with a stroke penalty.
In large fields, the round is split into two halves, with a morning group and an afternoon group.

Altogether, the 11 minute intervals, the size of the groups, the encouragement of quicker play and the splitting of the rounds, are what the associations believe to be the best way of preventing bottlenecks occurring.
That said, players do sometimes catch the group before them.  Only yesterday, on the first day of the 2012 US Open, Woods, Mickelson and Watson had to wait over 15 minutes for the 7th green to clear. (Live blog, 15:27).
In summary, the golf associations use their best judgement based on historical evidence whilst encouraging quick play.
Comment: Great answer! These are pro golfers so I don't expect much unprofessionalism taking place. As you said, players and golf associations prepare the best they can to prevent potential risks. Things still happen, but one can control only what s/he can control.
Comment: Waggle...waggle...(10 minutes later)...waggle. Just hit the ball!

Managing split tees in golf


Simplicity of rotational symmetry group of dodecahedron without proving it is $A_5$

Question: I am trying to prove that the rotational symmetry group $G$ of a regular dodecahedron is $A_5$.
I am trying to do this in an unusual way: I want to show that $G$ is simple. Since I can show $G$ is order 60 and can prove that any simple group of order 60 is $A_5$  I just need to argue it is simple.
I am aware of the standard proof that $G$ is $A_5$ by embedding cubes/ tetrahedrons: I want to prove that $G$ is simple without first showing it is $A_5$
Comment: Well, then pick the subgroups one by one and show they aren't normal.
Answer: Here is a combinatorial way, by simply counting elements and using the regularity of your dodecahedron. In the isometry group, you have

the identity element
$6\times 4=24$ elements of order $5$ (rotations with axe face-face),
$15\times 1=15$ elements of order $2$ (rotations with axe edge-edge),
$10\times 2=20$ elements of order $3$ (rotations with axe vertex-vertex).

Remark furthermore that by regularity of the dodecahedron, you act transitively on the set of axes face-face, on the set of axes edge-edge and the set of axes vertex-vertex. Since the rotations associated to each axe are of prime order, if a normal subgroup contain one rotation of given order, it contains all rotations of this order.
As a result we only have the following possibility (identity + some conjugacy classes) for the order of the normal subgroup:
$$1\text{, }16\text{, }21\text{, }25\text{, }36\text{, }40\text{, }45\text{, }60\text{.}$$
and using Lagrange's theorem the only possibility are $1$ and $60$.
Comment: @Patrick, my point is to **not** use Sylow theorem here. Let me expand a bit. Suppose I have a rotation $c$ of order $p$ in my normal subgroup  and $d$ a rotation with the same order $p$. Then, by transitivity of the action on the axes I get  that $c$ is conjugated to $d^k$ and since the order of $d$ is prime, $\langle d^k\rangle$ must contain $d$. Thus $d$ is contained in my normal subgroup as well.
Comment: Thank you, with the bit in bold I am able to convince myself that this is true through Sylow (for 3 and 5) and geometrical reasoning for 2. The way you phrased it made me suspect there is a general result about subgroups of prime order you are appealing to?


Significado de dois asteriscos na chamada de função

Question: Estou tentando entender um código sobre lista simplesmente encadeada. A função InserirInicio tem como paramêtro Nodo **inicio, float dado. Eu não consegui entender a utilização de dois asteriscos no parametro nessa função em expecifico, estaria  função solicitando um ponteiro de ponteiro?
Struct e função:
typedef struct nodo
{
    float dado;
    struct nodo *proximo;
} Nodo;

int InserirInicio(Nodo **inicio, float dado) {
    Nodo *nodo;
    if ((nodo = (Nodo *) malloc(sizeof(Nodo)))  == NULL)
      return 0;

    nodo->dado    = dado;
    nodo->proximo = NULL;

    if (*inicio != NULL)
        nodo->proximo = *inicio;

    *inicio = nodo;
    return 1;

}

Chamada da função:
int main()
{
    int i;

    Nodo *inicio = NULL;

    for(i = 0; i < 8; i++)
    {
        InserirInicio(&inicio, i * 15.0);
    }
return(0);
}

Comment: O siginificado de ** até entendo, minha duvida é porque ele foi usado nessa função em expecifico.
Comment: É uma lista encadeada ou alguma outra lista, certo? Quando você passa a referência de ponteiro para ponteiro, possivelmente irá trocar a posição desse ponteiro que está sendo apontado, mas manter seu conteúdo.  Faz um teste no papel simulando a interação desse código e você descobre rápido.
Answer:
O siginificado de ** até entendo, minha duvida é porque ele foi usado
  nessa função em expecifico

A situação aqui é que a função InserirInicio tem que poder modificar o próprio Nodo que existe no main, este:
int main()
{
    int i;

    Nodo *inicio = NULL; //<--este

Que irá acontecer apenas quando este está a NULL, no entanto em C todos os parametros de funções são copias, logo se a função InserirInicio for desta forma:
int InserirInicio(Nodo *inicio, float dado) {
    ...
    inicio = nodo;

Está na verdade a alterar o parâmetro da função e não o ponteiro que existe no main.
Uma solução é em vez de passar o ponteiro, passar o local onde o ponteiro está na memoria, ou seja, um ponteiro para ponteiro, que é que vê no código. Assim pode alterar o original do main fazendo:
int InserirInicio(Nodo **inicio, float dado) {
    ...

    *inicio = nodo; //alterar o inicio que está no main

Na verdade nem é a unica solução. Também pode em vez de alterar diretamente o do main retornar o novo inicio, que seria assim:
int main() {
    ...

    for(i = 0; i < 8; i++)
    {
        inicio = InserirInicio(inicio, i * 15.0); //sem & e guardando em inicio
    }

E na função em vez de afetar, retornaria:
Node* InserirInicio(Nodo *inicio, float dado) {
    ...
    return nodo;
}

Repare que neste caso o parâmetro ficou apenas Nodo* mas o retorno passou também a ser do tipo Nodo*
Answer:
Eu não consegui entender a utilização de dois asteriscos no parametro nessa
  função em expecifico, estaria função solicitando um ponteiro de ponteiro?

É exatamente isso. Essa função InserirInicio exige em um de seus argumentos, um valor do tipo ponteiro de ponteiro Nodo (Nodo **).
Ela exige esse tipo de argumento para, por exemplo, ser capaz de alterar o valor de uma variável ponteiro Nodo (Nodo *) que foi declarada fora da própria função InserirInicio.
Nesses códigos que você passou, a variável inicio que foi declarada na função main (não confundir com a variável inicio que é parâmetro da função InserirInicio) é a variável que tem seu valor lido e depois alterado dentro da função InserirInicio, apesar de não ter sido declarada nessa função. Essa alteração de valor dentro de InserirInicio ocorre exatamente na linha *inicio = nodo;, e armazena um novo ponteiro na variável inicio que foi declarada em main.
E esse é o tipo de coisa que se consegue usando um ponteiro de ponteiro.


Cross product of 2 2D vectors

Question: Can anyone provide an example of a function that returns the cross product of TWO 2d vectors? I am trying to implement this algorithm.
C code would be great. Thanks.

EDIT: found another way todo it that works for 2D and is dead easy.
bool tri2d::inTriangle(vec2d pt) {
    float AB = (pt.y-p1.y)*(p2.x-p1.x) - (pt.x-p1.x)*(p2.y-p1.y);
    float CA = (pt.y-p3.y)*(p1.x-p3.x) - (pt.x-p3.x)*(p1.y-p3.y);
    float BC = (pt.y-p2.y)*(p3.x-p2.x) - (pt.x-p2.x)*(p3.y-p2.y);

    if (AB*BC>0.f && BC*CA>0.f)
        return true;
    return false;
}

Comment: How on earth can you ask for a function to calculate a cross-product, accept an answer that's incorrect, and then post a function that returns a boolean?  I'm voting this down and voting to close.
Comment: @tm1rbt -- Because SOers like to know when we are doing or helping with homework so that we can claim the credit transfers to our own academic transcripts.
Comment: Is this for work or home work?
Comment: This is for personal enjoyment. Why?
Comment: dup http://stackoverflow.com/questions/243945/calculating-a-2d-vectors-cross-product
Comment: don't be so rude and try reading it again "Given that the definition requires at least three dimensions, how does one calculate the cross product of two 2d vectors?"
Comment: @tm1rbrt: Just to know; because I know people who don't do either, elude their work and get it done thru' SO. Usually SO is for asking doubts; helping is something, but doing someone else's work is totally something else. Btw, don't use strong words like _moron_.
Comment: Agree with @duffymo. I think the topic creator wanted to calculate a cross product for his algorithm, but ended up using a different method that doesn't need vector algebra at all.
But I'm not voting this question down.
Answer: (Note: The cross-product of 2 vectors is only defined in 3D and 7D spaces.)
The code computes the z-component of 2 vectors lying on the xy-plane:
vec2D a, b;
...
double z = a.x * b.y - b.x * a.y;
return z;

Comment: @tm1rbrt: That `CrossProduct` should be a full 3D cross-product. You can always add back the two 0 components.
Comment: The 3-D cross product of two vectors in the x/y plane is always along the z axis, so there's no point in providing two additional numbers known to be zero.  Another way to look at it: the closest 2-D equivalent to a 3-D cross product is an operation (the one above) that returns a scalar.
Comment: The cross product of two vectors in 3D space is a 3D vector, yet your code only returns a double.  What good is one component?
Comment: Wow. Would like to give you an extra +1 for that link!
Comment: Also, I want to assure you that the above operation will in fact work correctly with the algorithm you link to.  If you work it out, the dot product of the resulting cross product vectors simplifies to a simple product of the resulting scalars.  Your updated version above could be considered a simplified (and nicely symmetric!) version of this:  by reducing the problem to comparing the signs of the resulting scalars, you can determine that the orientation of the original triangle is redundant.
Comment: @comingstorm - 2D doesn't necessarily mean in the xy-plane.  I understand vectors well enough to know what special case you're talking about, but there's nothing in the original question that spells out that restriction.  The updated answer that's provided is the correct, general answer.  In spite of the fact that your answer was accepted it's not correct for the general case.
Comment: Hey, first off, that's not *my* answer;  second, it is, in fact, correct.  The OQ was specifically about 2D vectors:  an answer phrased in terms of 3D vectors would be missing the point, and therefore incorrect.  Also, if you take a look at the link in the OQ, you will notice that his update, which you slagged for returning a boolean, is a (correct) implementation of his declared objective -- a point-in-triangle algorithm implemented for 2D vectors.
Answer: Mathworld Cross Product

Cross product of 2 2D vectors


User is notified when new content is created using Rules

Question: I created two groups in one group type.

Job Post
Business

Each group has its own content type(same label) and group permissions.
User Story:
"As a user(Job Post) I would like to be able to create a job. A job should contain a description and a job type - for example, plumbing."
As a plumber(Business) I would like to be notified every time a new job is posted that is for plumbing, but not for any other types of work."
How specifically can this be achieve using Rules as I'm a newbie on this module and still trying hard to make setup on this problem.
Comment: If you're new to the [Rules](https://www.drupal.org/project/rules) module, then you may not be aware of [this](http://meta.drupal.stackexchange.com/a/3616/39516) showstopper ... Apart from that, which module are you using, if any, for implementing those "groups"?
Comment: I'm using Group module. I have also Pathauto enabled.
Answer: It really depends on your setup. A simple way to achieve this would be to assign business users with a role let's say "Business". Once that's done you can create a trigger on creation of new node, set conditions based on your requirement e.g. user role = "Business" and category = "Plumber" and action to send out an email.
You might need additional modules if you're looking at sending out HTML emails.
Let me know if you need any help.
Thanks
Comment: Okey, thanks for your response. Yes, I have a role assigned to each. It is set in the group configuration by the Group module. Also, in my case I only want business to be notified in their page, not in email. Like if we can create a view that whenever a new job post was created for plumbing it will be added in the list view.
Comment: Yes you can do that by using some private messaging module like https://www.drupal.org/project/message_private or can create a new content type with user reference field attached to it. This user reference should point to the business where this message needs to be displayed. You can then create a view and list of all the nodes with user reference set to currently logged in business. You can also add a status field in content type to mark it as unread node and when a business views it, update it to read status.
Comment: Okey, sound like a solution to me. Will follow your instructions and update you. Thanks!


What is the name of this special class of Ordinary Differential Equations?

Question: Using a suitable substitution, transform the following equation into a first order Linear differential equation:
$y' = f_0(x) +f_1(x)*y + f_2(x) *y^2$  for $f_2(x)\not\equiv 0$
Attempt at a solution: I've found that if $y_1(x)$ is a solution, we can use $y(x) = y_1(x) + \frac{1}{u(x)}$ but I'm unfamiliar with proving stuff for this special class of ODEs. Please help.
Comment: These equations are known as [Riccati's equation](https://en.wikipedia.org/wiki/Riccati_equation).

Another helpful resource [here](http://www.sosmath.com/diffeq/first/riccati/riccati.html) that i'll leave for your perusal.
Answer: For
$$y' = f_0(x) +f_1(x)*y + f_2(x) *y^2 \hspace{5mm}  \text{for} \, f_2(x) \not\equiv 0$$
then, suppose $q_{0}(x)$ is a solution, let $y(x) = q_{0}(x) + p(x)$ to obtain
\begin{align}
q_{0}' + p' &= f_{0} + f_{1} q_{0} + f_{1} p + f_{2} (q_{0}^{2} + 2 q_{0} p + p^{2}) \\
p' &= f_{2} p^{2} + (f_{1} + 2 q_{0} f_{2}) p + (- q_{0}^{'} + f_{2} q_{0}^{2} + f_{1} q_{0} + f_{0}) \\
p' &= f_{2} p^{2} + Q_{0} p,
\end{align}
where $Q_{0} = f_{1} + 2 q_{0} f_{2}$.
Now
\begin{align}
\frac{p'}{p^{2}} - \frac{Q_{0}}{p} &= f_{2} \\
- \frac{d}{dx} \left(\frac{1}{p}\right) - Q_{0} \, \frac{1}{p} &= f_{2}
\end{align}
Let $v(x) = 1/p(x)$ to obtain, with use of integrating factor,
\begin{align}
v' + Q_{0} v &= - f_{2} \\
\frac{d}{dx} \left[ v \, e^{\int^{x} Q_{0} dt} \right] &= - f_{2} \, e^{ \int^{x} Q_{0} dt} \\
v &= e^{- \int^{x} Q_{0} dt} \, \left[c - \int^{x} f_{2}(u) \, e^{\int^{u} Q_{0} dt} \, du \right]
\end{align}
Placing everything together provides
$$y(x) = q_{0}(x) + e^{\int^{x} (f_{1}(t) + 2 q_{0}(t) f_{2}(t)) dt} \, \left(c + \int^{x}  f_{2}(u) \, e^{- \int^{u} (f_{1}(t) + 2 q_{0}(t) f_{2}(t)) dt} \, du \right)^{-1} $$


Is the trumpet's theoretical range unlimited?

Question: I'm more wondering about the upper register here, but I suppose this applies to pedal notes also. Is the trumpet's range theoretically unlimited? Is there anything (besides the player) that potentially could limit the range of the trumpet?
Comment: I'm guessing the physical size of the instrument will limit the minimum wavelength it can produce, and probably it would shatter or melt at a high enough frequency.  Except for the fact that you probably can't put enough energy into it for that via any normal means, you just wouldn't get a sound out of it.
Answer: As Matthew indicated in his comment, once the wavelength of the sound gets smaller than the diameter of the tubing, the trumpet will no longer behave like a column of air.  This means that, at these wavelengths, the trumpet will not support the resonance modes that make up its behaviour at normal frequencies.  I.e. not sound like a trumpet (to the extent that it sounds at all).
Comment: With a standard bore of .450", that is roughly 11.5 mm, and with sound speed of 340 m/s (is that the correct value to use here? Should it be affect by the air speed?), that limit is right below 30 kHz. The human ear is said to be able to hear frequencies up to 20 kHz.
Comment: Yes, that is pretty much the logic.


C++ boolalpha confusion

Question: Hi anyone can explain the following c++ code result?
input: true false 1
output: false, true, true,

#include <iostream>
using namespace std;
int main ()
{
    bool c1, c2, c3;
    cin >> c1 >> c2 >> c3;
    cout << boolalpha << c1 << ", " << c2 << ", " << c3 << ", " << endl;//LINE I
    return 0;
}

Comment: [cppreference.com](http://en.cppreference.com/w/cpp/io/manip/boolalpha)
Comment: Downvote for zero effort.
Answer: See here

Enables the boolalpha flag in the stream str as if by calling str.setf(std::ios_base::boolalpha

Always check the documentation first.
Answer: The istream object you operate on (cin here) expects either 0 or 1 for input to the bool, your input gave it true.  This causes the operation to fail, and the failbit to be set on the istream, since you don't check for input failing, the next two assignments to c2 and c3 does happen, and is instead skipped.  Thus, c1 is false, as the input operation failed.  c2 and c3 was not modified nor initialized, and thus could have any value.

C++ boolalpha confusion


In a musical note (A for an example) are all the other frequencies harmonic?

Question: In a musical note (A for an example) are all the other frequencies harmonic (integer multiples)? Is there any inharmonic frequencies in A?
Edit: A4 on the piano for example.
Im very grateful for all the answers I get. Thanks so much!
Comment: Which A? From what I've read, timpani A's have non-integer multiples of the loudest frequency in their overtone series. I've also read that the fundamental frequency of a timpani note is not the loudest.
Answer:
are there any inharmonic frequencies in A?

Simplistically speaking, 'A' tells us the fundamental pitch of the note (or at least it would if we knew which A - e.g. A4 is often, though not always, considered to be 440Hz).
However, whether or not there are any inharmonic frequencies completely depends on the timbre of the note. Looked at another way, it's (partly) the frequencies of the harmonics that define the timbre of the sound.
In a the sound of any 'real' instrument, there will almost certainly be frequencies that are not integer multiples of the fundamental. Some of these might be nearly integer multiples (for example, the 'stretched' partials you find on a string); some of them might not be close to integer multiples (for example, the partials in some bell sounds). There will also often be lots of energy in the sound that does not come from an identifiable partial of stable pitch, but is often described as noise. However, the boundary between noise and partials isn't really a clear one, as partials often have unstable frequencies and may be short-lived.
So, when we're talking about 'real' or acoustic instruments, we can almost certainly say NO, not all the other frequencies are harmonic. However, using a computer or synthesizer, it's possible to get close to a sound that has only integer harmonics.
Comment: in an acoustics class once the professor took a note (from a synth if i remember correctly) and slowly removed the harmonics. once certain number of harmonics were removed we could no longer tell what instrument was being played. even removing attack and changing decay didn't have as much effect on being able to identify the instrument.
Comment: "enharmonic" should be "inharmonic" (I don't have the rep to make trivial edits).
Comment: @b3ko yes, it's an interesting experiment - to do this kind of experiment yourself, a piece of software like [Spear](http://www.klingbeil.com/spear/) that deals in terms of partials can be useful.
Comment: I'm surprised removing the attack made so little difference.  Remember 'hybrid' synthesis - notably the Roland D50 - where a sampled attack was grafted onto a synthesised sustain and release?  It was remarkably effective.
Comment: Laurence Payne it was many years ago but if I remember correctly if he altered the attack we could still guess what instrument it was. Altering the harmonics made it next to impossible to tell what instrument it started as.
Answer: Depends what's playing it.  The harmonic series - the 2,3,4 etc. frequency ratios - are the overtones of a theoretical 'perfect' instrument.  That's a simple string, of negligible mass, vibrating as a whole, as two halves, as three thirds etc.
In real life, instruments are not perfect. They produce overtones that are displaced from those theoretical frequencies, and not of uniform strength. Sometimes, like the flute, they're pretty close.  Sometimes they are wildly displaced - the classic example is the church bell which can have a very strong overtone a major 7th above the fundamental.
Then there's the matter of the attack transient, the very beginning of each note when the bow bites into the string, the piano hammer strikes the string, the clapper hits the bell, a brass instrument note is 'tongued'...   That's generally completely inharmonic.  And it contains much of the characteristic of the note, the information as to WHAT instrument it is.
So yes, in most cases a note will contain plenty of 'imperfect' overtones.
Answer: If you select one (of the many) A, it is defined by one single frequency. One example might be the A having frequency 440Hz. If you dial in 440 Hz on a frequency generator, on setting sinus (it should be sine, see comments) wave, it will have only that frequency and sound an A.
But I guess, you are asking about A-s sound from other sources, say from instruments. There are a lot of different instruments which sound quite different. Some of these have mostly integer multiplier frequencys, ie 2x 3x 4x and so of the base frequency. In the example it would be 440Hz, 880Hz, and so on.
The actual relative strengths of these overtones in part define the sound of the instrument. A clarinet will sound different from a flute, partly because the volume of the different overtunes will differ. Here we are talking about the "overtones".
But it never is quite as easy. All instruments I have ever seen in addition creates various noises, one example is wind noise. This is not related to overtones.
Comment: Sinus waves get up my nose...
Comment: Tim: Sorry -- English not beeing my main language, can you decode the comment for me.
Comment: A sinus is a space in one's head, etc. The word you needed was **sine**. Just a joke...
Comment: Aah. Point taken on the Sinus vs Sine.
Answer: In addition to the other answers, two further reasons for non-integer multiples:

A piano often has 3 strings which are hit on each note. They may not be perfectly in tune with each other, in which case it cannot be the case that each of them vibrates at the same basic frequency.
The low notes of a piano in particular are built from coils of wire, which will provide a slightly imperfect vibration (i.e. even ignoring harmonics you may not see a sinusoidal vibration because the force on the string is not exactly proportionate to its displacement) - for instance the spring itself may vibrate with an additional transverse low frequency vibration changing the tension in the spring over time causing a slight change in pitch at e.g. 10Hz which would be heard as a small amount of vibrato. Inevitably that means you are not going to get a harmonics which are constantly at frequencies integer multiples of a theoretical base note.
Answer: Assuming you are asking about the mathematical relationship between pure sine wave tones corresponding to the fundamental frequency of notes on a piano, the relationship between the notes is close to but not exactly an integer multiple.
Starting with an A4 sine wave at 440 hz, we can get to A5 (880 hz) by doubling the frequency. We can get to A3 (220 hz) by cutting the frequency in half. Continuing to double the frequency goes to higher A's, and dividing the frequency goes to lower A's. This works for any note--doubling or halving the frequency takes you to the next octave of that note.
Going back to A4, if we multiply the frequency by 3, we get a note that sounds good when played in a chord with A4. If you tried to find it on a piano, you would get E6 (E5 is the first E above A4, E6 is the next one). Ignoring the extra octave for a moment, the interval between A and E is called a fifth, so multiplying frequencies by 3 is the origin of our concept of fifths.
Continuing, you could multiply THAT frequency by 3 to go from E6 to B7. Multiply by 3 again and you get a really high F#. Then a C#, G#, D#, ... This continues to cycle through the notes on the piano. (And remember that we can always divide by two to get lower octaves of the note, so I am ignoring the fact that we keep going to higher notes as we multiply.)
Now wait a minute. If we keep cycling through the notes on the piano, we are eventually going to get back to A. From the second paragraph above, every A is just 440 hz multiplied by some number of 2's, but somehow we cycled back to A by multiplying 440 hz by some number of 3's. How can 2*2*2*2... = 3*3*3*3...?
It doesn't. When you get back to A, you've multiplied the frequency by 3^12, which is 531441. This is pretty close to going up 19 octaves from the original note, which would mean multiplying the frequency by 2^19, which is 524288. The difference between these two tones is about 1.36%. Given that the frequency difference between half steps on a piano is about 5.95%, this is very badly out of tune.
If the fact that these frequencies are well outside the range of hearing bothers you, imagine instead that you start at a note and go down an octave. Then go up an octave-plus-a-fifth. Keep alternating. Whenever you get more than an octave above your original note, go down an extra octave. Keep doing this until you get back to the original note. You will have gone up an octave-plus-a-fifth 12 times, and down an octave 19 times. If you had actually been multiplying the frequency by 3 going up, you would now be at a frequency (531441 / 524288) times your original note's frequency.
Modern instruments for western music typically average out this error smoothly across the scale, which is called equal temperament. This results in a fifth that is (2.996614 / 2) times the original frequency rather than (3 / 2) times. Many different temperaments exist that balance getting a fifth that is closer to a multiple of 3 with having an awkward part of the scale that the music generally has to avoid.


Import Json data into node

Question: My goal is to import my own data set into Drupal 8 using Migrate modules (migrate_plus, migrate_tools).
In Drupal, I use Paragraph module, and here my trouble starts. I've build my own plugin to transform my own data into paragraph. The transformed data is good if i create a new node and attached to it into the transform() function but that's not what I want, it's only to say that my data may be correct (see comments below)
I do import with base field like text, tags or file, and with this, the node will be generated, but I can't figure out why 'return $paragraphs' won't anything.
PS : I un-install/install my module (and the conf migrate_plus generated) everytime I change my .yml file and cache rebuild.

Drupal (8.1.1)

migrate_plus (8.x-2.x-dev)
migrate_tools (8.x-2.0-beta1)
migrate_source_json (8.x-2.x-dev)
paragraphs (8.x-1.0-rc4)

Migration configuration for articles (config/install/migrate_plus.migration.article.yml)
id: article
label: Article
migration_group: Articles
migration_dependencies: {}

source:
  plugin: json_source
  path: http://www.example.com/dataset.json
  headers:
    Accept: 'application/json'
  identifier: id
  identifierDepth: 0
  fields:
    - id
    - title
    - paragraphs

destination:
  plugin: entity:node

process:
  type:
    plugin: default_value
    default_value: article

  title: title

  field_paragraphes:
      - source: paragraphs
        plugin: paragraphs_import

  uid:
    plugin: default_value
    default_value: 0

Dataset example:
[{
    "id": "1",
    "title": "article 1",
    "paragraphs": [{
        "id": "1",
        "title": "paragraph 1 article 1"
    }, {
        "id": "2",
        "title": "paragraph 2 article 1"
    }]
}, {
    "id": "2",
    "title": "article 2",
    "paragraphs": [{
        "id": "3",
        "title": "paragraph 1 article 2"
    }, {
        "id": "4",
        "title": "paragraph 2 article 2"
    }]
}]

Custom plugin used on 'field_paragraphes' (/src/Plugin/migrate/process/ParagraphsImport.php)
<?php

/**
 * @file
 * Contains \Drupal\my_module\Plugin\migrate\process\ParagraphsImport.
 */

namespace Drupal\my_module\Plugin\migrate\process;

use Drupal\migrate\MigrateExecutableInterface;
use Drupal\migrate\ProcessPluginBase;
use Drupal\migrate\Row;
use Drupal\node\Entity\Node;
use Drupal\paragraphs\Entity\Paragraph;

/**
 *
 * @MigrateProcessPlugin(
 *   id = "paragraphs_import"
 * )
 */
class ParagraphsImport extends ProcessPluginBase {
  /**
   * {@inheritdoc}
   */
  public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {
    // code only to add 1 paragraph to my node, to make thing easier to start

    // paragraph_txtimg = one paragraph type allowed into my paragraph field

    $paragraphs=array();
    $ppt_values = array(
      'id' => NULL,
      'type' => 'paragraph_txtimg',
    );
    $ppt_paragraph = Paragraph::create($ppt_values);
    $ppt_paragraph->save();

    // IF I uncomment this part, it will create a new node with a paragrah, this works
    // But this is not what I want to do, I want to return the paragraph to the node that will be created by migrate
    /*
      $node = Node::create(array(
        'type' => 'article',
        'title' => 'This is a new article with a fresh paragraph generated !',
        'field_paragraphes' => array(
          array(
            'target_id' => $ppt_paragraph->id(),
            'target_revision_id' => $ppt_paragraph->getRevisionId(),
          ),
        ),
      ));
      $node->save();
    */

    $target_id_dest = $ppt_paragraph->Id();
    $target_revision_id_dest = $ppt_paragraph->getRevisionId();
    $paragraphs[] = array('target_id' => $target_id_dest, 'target_revision_id' => $target_revision_id_dest);

    return $paragraphs;
  }

}

Answer: I finaly found the missing key :
transform() is called on EACH item of the source.
field_paragraphes:
 - source: paragraphs
   plugin: paragraphs_import # will be called for each value of source: paragraphs

And so, the return value should be the paragraph revision definition :
<?php

/**
 * @file
 * Contains \Drupal\my_module\Plugin\migrate\process\ParagraphsImport.
 */

namespace Drupal\my_module\Plugin\migrate\process;

use Drupal\migrate\MigrateExecutableInterface;
use Drupal\migrate\ProcessPluginBase;
use Drupal\migrate\Row;
use Drupal\node\Entity\Node;
use Drupal\paragraphs\Entity\Paragraph;

/**
 *
 * @MigrateProcessPlugin(
 *   id = "paragraphs_import"
 * )
 */
class ParagraphsImport extends ProcessPluginBase {
  /**
   * {@inheritdoc}
   */
  public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {
    // transform() is called on each source value

    $paragraph_options = array(
      'id' => NULL,
      'type' => 'paragraph_txtimg',
    );
    $paragraph = Paragraph::create($paragraph_options);
    $paragraph->save();

    return $paragraph;
  }

}

Comment: - What else if I wann a add nested paragraph?

Import Json data into node


Lista Com Array Gigantesco

Question: O software da como output uma lista com apenas um array gigante:
[array([0.000000e+00, 1.687500e-01, 5.062500e-01, ..., 3.616745e+03,
   3.617745e+03, 3.618245e+03])]

Meu objetivo era obter uma lista, com cada item desse array, separadamente. Para isso, eu tentei fazendo com o seguinte código:
lst = [item.tolist() for item in lst]

No entanto, meu resultado apenas tira o "array", pois a lista continua com apenas um item.
list = [[0, 0.16, 0.501...]]

meu objetivo era que list fosse:
list = [0, 0.16, 0.501...]

Answer: Se há apenas uma lista dentro de outra e você quer pegar a lista de dentro, você pode usar:
list = lst[0]

Lista Com Array Gigantesco


QML WebSocket error: Unsupported WebSocket scheme: http

Question: I created a simple chat application using QML's WebSockets component. It's just the client:
Window {
    id: root
    visible: true
    width: 1024
    height: 768

    property variant messages: []

    WebSocket {
        id: sock
        url: "http://localhost:3700"
        onTextMessageReceived: {
            var data = message;
            var messages = root.messages;
            if(data.message) {
                messages.push(data);
                var html = '';
                for(var i = 0; i < messages.length; i++) {
                    html += '' + (messages[i].username ? messages[i].username : 'Server') + ': ';
                    html += messages[i].message + '
';
                }
                messageBox.append(html);
            } else {
                messageBox.append("There is a problem:", data);
            }
        }
        onStatusChanged: {
            if (sock.status == WebSocket.Error) {
                messageBox.append("Error: " + sock.errorString);
            }
            else if (sock.status == WebSocket.Open) {
                messageBox.append("Socket open");
            }
            else if (sock.status == WebSocket.Closed) {
                messageBox.append("Socket closed");
            }
        }
        active: false
    }

The server is implemented on Node.js and Socket.io using this article.
The problem is, when I try to connect to the server the app throws this:
Error: Unsupported WebSocket scheme: http
If I change the protocol to ws, then the server closes the connection. What can I do?
The server code:
var express = require("express");
var app = express();
var port = 3700;

app.set('views', __dirname + '/tpl');
app.set('view engine', "jade");
app.engine('jade', require('jade').__express);
app.get("/", function(req, res){
    res.render("page");
});

app.use(express.static(__dirname + '/public'));

var io = require('socket.io').listen(app.listen(port));

io.sockets.on('connection', function (socket) {
    socket.emit('message', { message: 'welcome to the chat' });
    socket.on('send', function (data) {
        io.sockets.emit('message', data);
    });
});

console.log("Listening on port " + port);

Comment: Socket.io !== websockets. Socket.io first connects using xhr and then upgrades to websockets if they are supported.
Comment: Socket.io is on the server, there is no xhr there. Do you mean I need to create a server without Socket.io?
Comment: The initial connection to socket.io expects xhr... `Socket.IO never assumes that WebSocket will just work, because in practice there's a good chance that it won't. Instead, it establishes a connection with XHR or JSONP right away, and then attempts to upgrade the connection to WebSocket.`.
Answer: From Qt documentation:
The url must have one of 2 schemes: ws:// or wss://. When not supplied, then ws:// is used.
So you have to specify the url as
url: "ws://localhost:3700"

or wss:// if you use secured connection.
Also take into account that QML WebSocket supports only version 13 of the WebSocket protocol.
See RFC documentation for more info.
Answer: I found a much simplier solution for this problem.
It isn't as easy as setting url to "ws://localhost:3000" when using websockets with socket.io
You also have to set the transport-type when talking to socket.io, for example:
url: "ws://127.0.0.1:3000/socket.io/?EIO=3&transport=websocket"
This can be used with the QML WebSockets example provided by qt here
 http://doc.qt.io/qt-5/qtwebsockets-qmlwebsocketclient-qml-qmlwebsocketclient-main-qml.html


Power BI while loop

Question: I'm trying to do a while loop in Power BI M language. But all of the logic are all over my head!
How would you translate a very simple loop like this into M language?
while X == True:
    do abcdef
    if Y == True:
       end
Thanks very much!
Comment: Both M and DAX are more oriented towards working with columns rather than loops, so the best answer is dependent on what you're trying to do. Sometimes you do really need a loop, but much of the time there's a better way to achieve your goal within the language. What are you trying to do to a table that you want to use a loop for?
Comment: Thanks! I'm trying repeatedly make an API call and only stop when the server is ready. That's why I had to resort to using a loop.
Comment: Gotcha. That does sound like you probably do have to resort to a loop.
Answer: Loops in M are probably best handled with the List.Generate function.
This article does a pretty good job at explaining how it works:
https://potyarkin.ml/posts/2017/loops-in-power-query-m-language/
Using this function, let's look at a more specific implementation of a while loop, say to find Fibonacci numbers less than 1000.
a = 1
b = 1
while b < 1000
    b = a + b
    a = b - a

would translate to M something like this:
let
    data =
    List.Generate(
        () => [ a = 1, b = 1 ],
        each [b] < 1000,
        each [ b = [a] + [b], a = [b] ]
    ),
    output = Table.FromRecords(data)[a]
in output

I'm not sure the best way to handle your break condition Y. It might depend on the specific problem.

Power BI while loop


How can you compute sample size for a linear mixed model? G*Power only does repeated measures ANOVA

Question: I read everywhere that repeated measures ANOVA is inferior to mixed modelling (since it doesn't handle missing data as well and relies on sphericity assumption). G*Power doesn't tell you how to compute sample sizes for linear mixed models. Should I just do the calculation for RM-ANOVA and go with that number?
My study is: one group takes drug A, another drug B (blinded), surveys with a few continuous questions are given at 5 follow up appointments.
Answer: In general, because designs in which linear mixed models are to be used can be complex, it is better to work with a simulation-based approach rather than to rely on specific formulas. If you happen to work in R, you can have a look at the powerlmm package that facilitates this.
Comment: Wow thanks! Not sure why I couldn't find that on google before. Also I just realized I have your book next to me on my desk :)
Comment: I just realized there are a few parameters that it's very difficult (basically impossible) for me to make guesses for (variance of the random slopes, within subject variance) when running the simulation. What do people usually do in this situation? I'm thinking of telling them to choose a time point that they are most interested in and then doing a more simple calculation for a t.test of means or simple regression (response ~ baseline value + group). Or just trying to find some similar study.
Comment: Yes, it typically helps if you have some pilot data from which you can estimate all these parameters. If not, then either you can do as you suggested but then the sample size calculation is not for the longitudinal effect or you could present the results under different logical values for these parameters.


Drying my trumpet out after playing

Question: Whenever I practice on trumpet, after practicing there is a lot of water gathering inside the main tuning slide and thirs valve slide but also inside the valve caps so I have to unmount these valve caps and water comes out.
My question is if this is normal, and if I am doing right by doing all this everytime I practice, since I'm worried about my trumpet getting damaged in some way if I leave some of that water or moisture inside and I do not dry it out.
Will it dry out over time and, is emptying water inside slides enough? What do people (trumpeteers or brass players in general) do after playing the instrument for a while?
Comment: this is quite normal! I never cared for my instruments (except emptying the slides of course when bubbling! but now I have another euphonium I have to take care as the volves are locking  after a few days when not used  - if I don't dry them after playing. Anyway: It won't matter to take care to your instrument.
It
Answer: What is happening to your trumpet is completely normal. Your trumpet gets wet because, the warm air you is moist, and that moistness builds up into water. A wet trumpet isn't that harmful, its just that its harder to maintain each pitch. When my trumpet gets wet I use a very old cotton t-shirt to dry my trumpet, but you don't have to that; You can use other soft cloths to dry your trumpet. Here is more about wet and dry trumpets.

Drying my trumpet out after playing


Select dos últimos registros ordenados por 1 campo

Question: Tenho a seguinte estrutura de tabela

O objetivo é pegar os 3 últimos registros mais velhos (data mais antiga) ordenado pelo Nome. Hoje estou utilizando subselect:
Select * from
   (Select top 3 from TB
   order by Data desc) A
order by Nome

Tem algum outro jeito melhor de fazer isso?
Comment: Também poderia ser um self-join. Precisaria testar as duas opções para ver qual tem a melhor performance (estou sem SQL Server no momento). De qualquer maneira, parece uma boa solução.
Answer: Pode fazer assim também:
SELECT TOP 3 FROM TB ORDER BY Data DESC, Nome ASC

Comment: Isso só funciona se os 3 registros tiverem datas iguais.
Answer: Como o bfavaretto comentou vc já deve estar usando a melhor opção para seus requisitos.
Note você quer:

Os três últimos registros.
Apresenta-los ordenados pelo nome.

Para o primeiro requisito você deve usar o top 3 e uma ordenação pela data para retornar os registros que vc quer. Com os três registros em mãos você ordena-os só p/ questões visuais.
Usando um self join ou uma table variable pode fazer isso mas duvido que seja + eficiente (mas um acid test é necessário para ter certeza).
A resposta do Pedro Laini não cumpre o segundo requisito pq a ordenação por data vai ter precedência no resultado apresentado.
A resposta do Guilherme Torres não é reliable podendo falhar caso hajam "lacunas" entre os Ids (causados por deleção por exemplo). Além disso em sua questão não foi citada correlação entre a data e o Id.
A outra única opção razoável (dependendo do contexto) seria fazer a ordenação dos três registros retornados na UI ou no Service.
Answer: O ID é sequencial e a data crescente? Se for, daria para pegar o último id - 3.
Select * from TB where id >= (Select max(id) from TB) - 3  order by Nome

Comment: Falha se algum dos últimos registros for deletado por exemplo


OpenGL to eliminate tiles from the mesh as in the game candy crush?

Question: This code will generate a mesh.
It will switch the colors of the 2 adjacent tiles which are selected using mouse one after the another.
As a result, same color tiles may be present next to each other.
I want to eleminate such tiles out of the mesh
#include<stdlib.h>
#include<glut.h>
#include<stdio.h>
#define maxx 11
#define maxy 11
#define dx 50
#define dy 50

typedef struct cell
{
    GLfloat x0,y0,x1,y1;
    int color;
}cellt;

cellt board[20][20];
GLfloat color[3][3]={{0,0,1},{0,1,0},{1,0,0}};
GLfloat x0=0,y0=0;
GLint i,j,stroke=0,pastx,pasty,nextx,nexty,swapthetwo=0;

void init()
{
    int i=0,j=0;
    glClearColor(1.0,1.0,1.0,1.0);
    glColor3f(1.0,0.0,0.0);
    glPointSize(5.0);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluOrtho2D(0.0,499.0,0.0,499.0);
    glutPostRedisplay();
    for(i=0;i<maxx;i++)
        for(j=0;j<maxy;j++)
        {
            board[i][j].x0=x0+i*dx+1;
            board[i][j].x1=x0+(i+1)*dx-1;
            board[i][j].y0=y0+j*dy+1;
            board[i][j].y1=y0+(j+1)*dy-1;
            board[i][j].color=rand()%3;
        }
}

void display(void)
{
    glClear(GL_COLOR_BUFFER_BIT);
    for(i=0;i<maxx-1;i++)
    {
        for(j=0;j<maxy-1;j++)
        {
             glColor3fv(color[board[i][j].color]);
             glBegin(GL_POLYGON);
               glVertex2f(board[i][j].x0,board[i][j].y0);
               glVertex2f(board[i][j].x0,board[i][j].y1);
               glVertex2f(board[i][j].x1,board[i][j].y1);
               glVertex2f(board[i][j].x1,board[i][j].y0);
             glEnd();
             glColor3f(0.0,0.0,0.0);
             glBegin(GL_LINE_LOOP);
               glVertex2f(board[i][j].x0,board[i][j].y0);
               glVertex2f(board[i][j].x0,board[i][j].y1);
               glVertex2f(board[i][j].x1,board[i][j].y1);
               glVertex2f(board[i][j].x1,board[i][j].y0);
             glEnd();
        }
    }
    glFlush();
    glutSwapBuffers();
}

void mouse(int btn,int status,int x,int y) //mouse interfacing
{
    y=500-y;
    if((stroke == 0) && (btn == GLUT_LEFT_BUTTON) && (status == GLUT_DOWN))
    {
        stroke=1;
        pastx=x;
        pasty=y;
        printf("pastx=%d,%d\n",pastx/dx,pasty/dy);
    }
    if((stroke == 1) && (btn == GLUT_LEFT_BUTTON) && (status == GLUT_UP))
    {
        stroke=0;
        nextx=x;
        nexty=y;
        printf("nextx=%d,%d\n",nextx/dx,nexty/dy);
        if(abs(((pastx/dx)-(nextx/dx)) == 1) && ((pasty/dy) == (nexty/dy)))
            swapthetwo=1;
        if(abs(((pasty/dy)-(nexty/dy)) == 1) && ((pastx/dx) == (nextx/dx)))
            swapthetwo=1;
    }
}

void idle(void)
{
    int temp;
    if(swapthetwo)
    {
         swapthetwo=0;
         temp=board[pastx/dx][pasty/dy].color;
         board[pastx/dx][pasty/dy].color=board[nextx/dx][nexty/dy].color;
         board[nextx/dx][nexty/dy].color=temp;
         printf("swapped");
    }
    glutPostRedisplay();
}

int main(int argc,char **argv)
{
    glutInit(&argc,argv);
    glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGB);
    glutInitWindowSize(500,500);
    glutInitWindowPosition(0,0);
    glutCreateWindow("mesh");
    glutDisplayFunc(display);
    glutIdleFunc(idle);
    glutMouseFunc(mouse);
    init();
    glutMainLoop();
    return(0);
}

Comment: Yuo should post your code first and together well try to improve it.
Answer: I am posting another question(regarding the same project) here which is more relevant.
By fluke i saw my code in this question which you might have taken from my blog.
You may want to update your question after my answer. The question you are asking is about is in the following code:
if(abs(((pastx/dx)-(nextx/dx)) == 1) && ((pasty/dy) == (nexty/dy)))
            swapthetwo=1;
if(abs(((pasty/dy)-(nexty/dy)) == 1) && ((pastx/dx) == (nextx/dx)))
            swapthetwo=1;

Which is inside the mouse function. Before setting swapthetwo run a loop to check if that row or column are having same colored tiles. You should loop two tiles on all the four directions. If any color are same swap, vanish and move down. Otherwise flip back.
I have defined four functions to vanish the tiles like this:
void vanishup(int i,int j)
{
    board[i][j].color=4;
    board[i][j+1].color=4;
    board[i][j+2].color=4;

whitecount+=3;
}
void vanishleft(int i,int j)
{
    board[i][j].color=4;
    board[i-1][j].color=4;
    board[i-2][j].color=4;
    whitecount+=3;
}
void vanishdown(int i,int j)
{

    board[i][j].color=4;
    board[i][j-1].color=4;
    board[i][j-2].color=4;
    whitecount+=3;

}
void vanishright(int i,int j)
{

    board[i][j].color=4;
    board[i+1][j].color=4;
    board[i+2][j].color=4;
    whitecount+=3;
}

Then in the display function calling these vanish functions when the conditions are right:
//detecting three colors in a row
    if(!whitecount)
    {
        for(i=0;i<maxx-1;i++)
        {
            for(j=0;j<maxy-1;j++)
            {
                flag=0;
                col=10;
                for(k=0;k<3;k++)
                {
                    if(k==0)
                        if(((j+k)<maxy-1))
                            col=board[i][j+k].color;
                if(((j+k)<maxy-1))
                {   if(board[i][j+k].color!=col)
                    {flag=1;
                break;}
                }
                else flag=1;
                }
                if(!flag&&!vanishing)
                    vanishup(i,j);
                    //printf("vanish up\n");
                flag=0;
                col=10;
                for(k=0;k<3;k++)
                {
                    if(k==0)
                        if((j-k)>=0)
                        col=board[i][j-k].color;
                if(((j-k)>=0))
                {   if(board[i][j-k].color!=col)
                    {flag=1;
                break;}
                }
                else flag=1;
                }
                if(!flag&&!vanishing)
                    vanishdown(i,j);
                    //printf("vanish down\n");
                flag=0;
                col=10;
                for(k=0;k<3;k++)
                {
                    if(k==0)
                        if(((i+k)<maxx-1))
                            col=board[i+k][j].color;
                if(((i+k)<maxx-1))
                {   if(board[i+k][j].color!=col)
                    {flag=1;
                break;}
                }
                else flag=1;
                }
                if(!flag&&!vanishing)
                    vanishright(i,j);
                    //printf("vanish right\n");
                flag=0;
                col=10;
                for(k=0;k<3;k++)
                {
                    if(k==0)
                        if(((i-k)>=0)) col=board[i-k][j].color;
                if(((i-k)>=0))
                {   if(board[i-k][j].color!=col)
                    {flag=1;
                break;}
                } else flag=1;
                }
                if(!flag&&!vanishing)
                    vanishleft(i,j);
                    //printf("vanish left\n");

            }
        }
    }

Finally move all those blocks down which have a white block above them:
//move all blocks down if white spaces exist(some blocks vanished)

flag1=0;
    for(i=0;i<maxx-1;i++)
            {
                for(j=0;j<maxy-1;j++)
                {

                    if(board[i][j].color==4) //if any board color white
                    {
                    if((j+1)<(maxy-1))      // if any board position not above board
                    {   board[i][j].color=board[i][j+1].color;//move above color

                    board[i][j+1].color=4;                     // to below

                    }
                    else
                        {board[i][j].color=4;
                        whitecount--;
                        }
                    }
                    //else movecount--;

                }

            }
    if(flag1) movecount=0;
    cout<<movecount<<" "<<whitecount<<" ";

I must agree after taking all the pains still i am not satisfied as there are several bugs.
1) While the blocks are moving down if any three colours form a line even temporarily they vanish.
2) Another problem is two different coloured lines vanish at the same time.


Meu acesso está sendo negado ao executar o seguinte codigo

Question: private void GerarPDF(string pCaminhoArquivoPDF)
{
    Document doc = new Document();

    // Aqui acontece o erro
    PdfWriter.GetInstance(doc, new FileStream(pCaminhoArquivoPDF,FileMode.Create));

    try
    {
        Paragraph p = new Paragraph(textBox1.Text);
        doc.Open();
        doc.Add(p);
        doc.Close();

    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.StackTrace);
        //throw;
    }
}

private void OndeGerar(Object o,EventArgs e)
{
    GerarPDF( @"C:\Users\CAIO\Desktop\PDF's");
}

Comment: Tente executar o Visual Studio no modo administrador.
Comment: Normalmente erro de acesso negado pode ser que o caminho que você está tentando acessar nem exista. Já aconteceu isso comigo e fiquei pensando que poderia ser algo de acesso, mas no fim, era eu quem estava passando o caminho errado!
Comment: Pode esse apóstrofo aí, do `PDF's`?
Comment: @MarceloUchimura Pode sim "Arnaldo" :)
Answer: O problema poderá ter origem em dois pontos:

Permissões de escrita na pasta C:\Users\CAIO\Desktop\PDF's

Neste caso atribuir permissões de escrita ao utilizador

Falta de previlégios de escrita a partir do próprio Visual Studio (ou do IDE que está a utilizar para executar o código)

Neste caso executar o IDE em modo de Administrador

O facto da pasta "PDF's" ter uma plica ou apóstrofe também não ajuda muito, pode estar a provocar algum problema na criação do ficheiro. Pode até nem representar um problema, mas de qualquer forma deveria rever o nome.


Rounding unit vs Machine precision

Question: I'm not sure if this question should be asked here...
For a general floating point system defined using the tuple $(\beta, t, L, U)$, where $\beta$ is the base, $t$ is the number of bits in the mantissa, $L$ is the lower bound for the exponent and $U$ is similarly the upper bound for the exponent, the rounding unit is defined as $$r = \frac{1}{2}\beta^{1 - t}$$
If I try to calculate the rounding unit for a single precision IEEE floating-point number which has 24 bits (23 explicit and 1 implicit), I obtain:
$$r = \frac{1}{2}2^{1 - 24} = \frac{1}{2}2^{-23} = 2^{-24}$$
which happens to be (using Matlab)
$$5.960464477539062 * 10^{-8}$$
which seems to be half of
eps('single')

that is, the machine precision for single-precision floating-point numbers for Matlab. The machine precision should be the distance from one floating-point number to another, from my understanding.
If I do the same thing for double-precision, apparently the rounding unit happens to be half of the machine precision, which is the follows
eps = 2.220446049250313e-16

Why is that?
What's the relation between machine precision and rounding unit?
I think I understood what's the rounding unit: it basically should allow us, given a real number $x$, we know that $fl(x)$ (the floating point representation of $x$) is no more far away than this unit to the actual $x$, correct?
But then what's this machine precision or epsilon?
Edit
If you look at the table in this Wikipedia article, there are two columns with the name "machine epsilon", where the values of the entries of one column seem to be half (rounding unit) of the values of the respective entries in the other column (machine precision).

https://en.wikipedia.org/wiki/Machine_epsilon
Comment: At the outset you defined $t$ to be "number of bits in the mantissa".  Applying this to the single precision floating point computation you included the "implicit bit" in your count for $t$.  However it seems to me that should not have been counted, since the "implicit bit" is essentially the binary leading one to the left of the (normalized-by-exponent) radix point.
Comment: It makes sense to count the implicit bit in the bit precision.  The size of the rounding unit should shrink with greater precision and with more bits "in the mantissa".  But I suspect your formula treats the base $\beta$ mantissa size as places to the right of the radix point.  Perhaps you can give a citation for the definition if it differs from the Wikipedia article?  Also check the origins of the word "mantissa", *the part of a logarithm that follows the decimal point*.
Comment: Thanks.  Note that on page 19 they give the formula (for binary floating point) $\eta = \frac{1}{2} \times 2^{-t}$ which they say "has been called **rounding unit, machine precision, machine epsilon,** and more."  On the previous page $t$ is used to number the bits to the right of the (floating) radix point.  In both places they refer the Reader to Section 2.2 for "[f]urther details" and for $\eta$ to be "more generally defined".
Comment: Include "the implicit $1$" in what?  "Omit the $+1$" from what? The operational meaning of the formula they give for $\eta$ depends on how $t$ is defined, and I've pointed out that the numbering of bits by those authors at the beginning of the chapter counts only the $t$ bits to the *right* of the radix point.
Comment: Perhaps in the first line on page 22 the authors make the point that you are, that in the special case base $\beta = 2$ we can avoid explicitly storing the leading $1$ (on any nonzero floating point values).  Therefore the numbering of the "places of precision" $t$ for general base $\beta$ in Sec. 2.2 is "off by one" from how it was numbered in Sec. 2.1.
Answer: To illustrate what happens, I constructed a toy example with $\beta=2$ and $t=2$ and plotted the relative error (due to rounding)
$$
\frac{|fl(x)-x|}{x}=\frac{|2^e\times1.ab-x|}{x}
$$
where $e=\lfloor \log_2 x\rfloor$ and $1.ab$ is a binary number representing $x/2^e$ rounded off to two binary digits.
Here is the graph of $fl(x)$ along with the horizontal line $y=\tfrac12\times 2^{-2}=0.125$:

We can see that the relative rounding error is maximal just a little after $0.5,1$ and $2$. In fact the pattern repeats since each time the exponent $e$ is shifted by one, the number $x/2^e$ runs through the exact same values $[1,2)$ again.

The maximal relative error can be found exactly where $x=2^e\times (1+\tfrac12 \times 2^{-2})$ or simplified $x=2^e\times 1.125$. In base $2$ the number $1.125$ is $1.001_2$ and is being rounded up to $1.01_2=1.25$. Therefore
$$
\frac{|fl(1.125)-1.125|}{x}=\frac{|2^0\times1.25-1.125|}{1.125}=\frac{0.125}{1.125}
$$
which is just slightly less than $0.125$.

So why is this rounding unit (upper bound on the relative error) only half the size of the machine precision? Well, you can actually see it on the graph between $1$ and $2$: the distance between the valleys (zero error/full precision) is $2^{-2}=0.25$ which is rougly twice the height of the maximal error top.

Rounding unit vs Machine precision


Is this if condition equivalent to testing the existence of a variable?

Question: I'm digging around in some the system files on my Mac. In /etc/profile I've found the following excerpt:
 if [ "${BASH-no}" != "no" ]; then
        [ -r /etc/bashrc ] && . /etc/bashrc
 fi

I've tried echo "${x-no}" for various choices of x and it seems like it's printing the value of x whenever x exists (i.e. has been set), and no otherwise.
Which leads me to wonder: Is this condition simply testing whether the variable x has been set?
Further questions: What exactly does - do? Is there a better way to test whether a variable has been set?
Comment: See "Parameter Expansion" in `man bash`.
Answer:
Is this condition simply testing whether the variable x has been set?

Yes, though it gets confused in the unlikely event that BASH=no.

What exactly does - do?

Here's man bash:
[...] Omitting the colon results in a test only for a parameter that is  un‐set.

   ${parameter:-word}
         Use Default Values.  If parameter is unset or null (see above),
         the expansion of word is substituted. Otherwise, the
         value of parameter is substituted.

Is there a better way to test whether a variable has been set?

Yes: [ -v BASH ]. However, this is bash specific, so it defeats the purpose of checking if the current shell is bash before doing bash specific operations.
Answer: The meaning of ${BASH-no} is documented in §2.6.2, Parameter Expansion, of the Single Unix Specification:

${parameter:-[word]}
Use Default Values. If parameter is unset or null, the expansion of word (or an empty string if word is omitted) shall be substituted; otherwise, the value of parameter shall be substituted.

The meaning when the colon is omitted (as in your example) is described slightly later:

In the parameter expansions shown previously, use of the  in the format shall result in a test for a parameter that is unset or null; omission of the  shall result in a test for a parameter that is only unset.

Then there is a table, which may be easier to understand. Here are the relevant rows:

parameterSet and Not Null
parameterSet but Null
parameterUnset

${parameter:-word}
substitute parameter
substitute word
substitute word

${parameter-word}
substitute parameter
substitute null
substitute word

Here is a reliable, portable way to check whether a variable is not set at all. Note that I am using a + modifier instead of a - modifier in the parameter expansion:
if [ "${BASH+set}" = "" ]; then
    echo 'BASH not set at all'
else
    echo 'BASH is set, perhaps to the empty string'
fi

The expansion of "${BASH+set}" can only be "" if BASH is entirely unset. If BASH is set, even to the empty string, then "${BASH+set}" expands to "set" instead.


Randomized Block Design Models

Question: I have been asked to fit the following models in R:

The models are based on this data:

I know the mediums are the blocks and the units of the active ingredient are the treatments. I understand how to fit the first model and what it means. My questions then are

Can someone explain to me the meaning of the other models?
How would I fit, for example, model 2 in R?
Answer: Your models are not fully specified. $M_i$, the block effect, should that be treated as a fixed or random effect? Apart from that, model (1) treats the treatment as categorical (unordered) which does not seem reasonable to me. Model (2) and (3), which are equivalent and will lead to the same conclusions, treats the treatment as categorical but ordered (this polynomial parameterization is the default for ordered factors in R.) Model (4) and (5) treats the treatment as numerical, with quadratic/linear effects. Model (6) a null model without treatment effects.
One way to estimate model (2) in R is
<code>mod_2 <- lm(log(Kill) ~ as.factor(M) + poly(x, degree=3, simple=TRUE),
             data=your_data_frame)
</code>

Randomized Block Design Models


Shape of a concert harp

Question: Here is a typical concert harp:
Concert harp image at Wikipedia
The soundboard rises in a straight line from the lower notes to the higher ones. This makes sense as you would expect shorter strings for the higher notes.  However, the shape of the neck is more complex.  If length were the only factor determining the pitch (I know that it isn't) then the shape would be wrong.  The strings would need to decrease in length geometrically.  Is there a good physical reason for this shape or is it determined by tradition and aesthetics?
One feature that makes some sense is that the top few notes cease to get (much) shorter.  I guess that this is for the obvious reason that if they got too short then they could not be plucked.
Answer: See: https://www.theguardian.com/science/life-and-physics/2012/may/12/harp-physics
Quoting (emphasis mine):

If you want to have all your strings made of the same stuff (so they have similar tone) and at the same tension (so they take the same effort to pluck), you have to increase the length to get deeper notes. Unfortunately, you have to double the length every octave. This means an exponential growth in length, and would lead to an unfeasibly big harp.

Later:

The curve in the top of the frame ... is there to allow the lengths of the strings to grow exponentially as far as this is feasible. ... But if you extrapolate that curving shape as you go away from the harpist, you can see the harp would get too big before you got to the next octave. So the curvature in the frame changes, and the type of string has to change too, to keep the frequency dropping exponentially and so allow more octaves.

Also: https://math.stackexchange.com/questions/80789/why-isnt-a-harp-in-a-logarithmic-shape
Which has the accepted answer of (emphasis mine):

You would expect it to have an exponential shape. Which it does, more or less, until the bottom end of the scale − where practical considerations rule out 5-metre-tall harps.

And: https://scientificgems.wordpress.com/2017/04/26/mathematics-of-the-harp/ which has two striking images.
The first is what a harp would (sort of) look like if the lengths were purely exponential:

Followed by the shape if the tension and thickness are varied linearly to help shorten the length:

Going just from those two images, we still have the question of why a traditional harp (unlike the electric harp pictured in the last article) curves back towards the floor at the bass end, which is almost certainly to further limit the overall length of the harp. Even with the recurve, concert grand harps are very large instruments.
Comment: @ToddWilcox I am struggling to find a reference so this may be a myth,  Why do Yamaha make pianos and motorcycles: what's the connection? They made pianos first but a company wanting to make mopeds approached them to make the frames.  If you can make a piano frame then you should be able to make a moped frame.  After a while, Yamaha thought: why just make the moped frame, let's make the whole bike.  Well, 5m is still big for a motorcycle frame but a company making agricultural vehicles might have been able to assist.
Comment: @ToddWilcox I couldn't find much detail on the construction of the NZ piano, but there was a sentence on his website about bolting bits of metal together that made me think the frame might not be in one piece. Either way it's pretty impressive.
Comment: Thanks.  A 5m tall harp might look nice though.  Have you see the octobass?  Not quite 5m but it is very big.
Comment: @badjohn One problem with a 5 meter harp is plucking the strings at the right place to get the desired timbre across the whole string bed. Also, we would likely see a 5 meter piano before a 5 meter harp, since pianos aren't generally considered portable. The cost of manufacturing such an instrument (either harp or piano) would be considerable, and then you'd basically have to install it like an organ. Which might be cool for a piano, now that I think about it.
Comment: @ToddWilcox there's a [5m piano in New Zealand](https://www.worldpianonews.com/new-product/acoustic/worlds-largest-piano-2/) and a [6m piano in Poland](https://www.worldpianonews.com/new-product/acoustic/worlds-largest-piano-2/) if you can believe it!
Comment: @Bob Very interesting. The NZ piano seems to have a one-piece metal frame. I wonder how that was cast/forged/created, since that seems to be a major challenge and expense for larger pianos.
Comment: Another solution to the 5m harp is that the soundboard does not need to be straight; it could curve down.  It would mean that it would need to overhang the front of the stage (and maybe need a pit as well) or the player would have to sit on a ridiculously high stool.  Anything for the art.
Answer: I suspect there's at least some degree of tradition and aesthetics in the shape.
The note you get when plucking a string depends on a number of factors:

The length of the string.
The tension on the string.
The heaviness of the string (mass per unit length).

The heaviness in turn depends on:

The thickness of the string.
The density of the material used to make it.

As Todd Wilcox shows, just changing the length isn't practical.  There are also limits as to how much the tension can be changed.  If a string is too tight, it is difficult to play and will probably just snap.  If it's too loose, it bends too far and then makes a rather un-musical "boing" sound when released.
Most concert harps still use gut strings for the top few octaves.  These start out thin at the top end, and get fatter as the octaves go down.
At the point where the strings would get too fat, they are replaced with wire ones.  Wire has a higher density than gut, so the strings don't need to be so long.  In practice, wire strings are normally "wrapped", with a central wire, and another coiled tightly round it.  This increases the mass per unit length but not the stiffness when stretched.
Over the years, the harp makers will have worked out how to adjust the harp strings to get just the right playability and sound.

Shape of a concert harp